<commit_before># -*- coding: utf-8 -
#
# Copyright (c) 2008 (c) Benoit Chesneau <benoitc@e-engura.com>
#
# 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 BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer
import cgi
import os
import socket
import threading
import unittest
import urlparse

from restclient.http import CurlHTTPClient, HTTPLib2HTTPClient
from restclient.rest import Resource, RestClient, RequestFailed, \
ResourceNotFound, Unauthorized
from _server_test import HOST, PORT

class HTTPClientTestCase(unittest.TestCase):
    httpclient = HTTPLib2HTTPClient()

    def setUp(self):
        self.url = 'http://%s:%s' % (HOST, PORT)
        self.res = Resource(self.url, self.httpclient)

    def tearDown(self):
        self.res = None

    def testGet(self):
        result = self.res.get()
        self.assert_(result == "welcome")

    def testGetWithContentType(self):
        result = self.res.get('/json', headers={'Content-Type': 'application/json'})
        self.assert_(result.http_code == 200)
        def bad_get():
            result = self.res.get('/json', headers={'Content-Type': 'text/plain'})
        self.assertRaises(RequestFailed, bad_get)

    def testNotFound(self):
        def bad_get():
            result = self.res.get("/unknown")

        self.assertRaises(ResourceNotFound, bad_get)

    def testGetWithQuery(self):
        result = self.res.get('/query', test="testing")
        self.assert_(result.http_code == 200)

    def testSimplePost(self):
        result = self.res.post(payload="test")
        self.assert_(result=="test")

    def testPostWithContentType(self):
        result = self.res.post('/json', payload="test",
                headers={'Content-Type': 'application/json'})
        self.assert_(result.http_code == 200 )
        def bad_post():
            result = self.res.post('/json', payload="test",
                    headers={'Content-Type': 'text/plain'})
        self.assertRaises(RequestFailed, bad_post)

    def testEmptyPost(self):
        result = self.res.post('/empty', payload="",
                headers={'Content-Type': 'application/json'})
        self.assert_(result.http_code == 200 )
        result = self.res.post('/empty',headers={'Content-Type': 'application/json'})
        self.assert_(result.http_code == 200 )

    def testPostWithQuery(self):
        result = self.res.post('/query', test="testing")
        self.assert_(result.http_code == 200)

    def testSimplePut(self):
        result = self.res.put(payload="test")
        self.assert_(result=="test")

    def testPutWithContentType(self):
        result = self.res.put('/json', payload="test",
                headers={'Content-Type': 'application/json'})
        self.assert_(result.http_code == 200 )
        def bad_put():
            result = self.res.put('/json', payload="test",
                    headers={'Content-Type': 'text/plain'})
        self.assertRaises(RequestFailed, bad_put)

    def testEmptyPut(self):
        result = self.res.put('/empty', payload="",
                headers={'Content-Type': 'application/json'})
        self.assert_(result.http_code == 200 )
        result = self.res.put('/empty',headers={'Content-Type': 'application/json'})
        self.assert_(result.http_code == 200 )

    def testPuWithQuery(self):
        result = self.res.put('/query', test="testing")
        self.assert_(result.http_code == 200)

    def testHead(self):
        result = self.res.head('/ok')
        self.assert_(result.http_code == 200)

    def testDelete(self):
        result = self.res.delete('/delete')
        self.assert_(result.http_code == 200)

class CurlHTTPClientTestCase(HTTPClientTestCase):
    httpclient = CurlHTTPClient()

    def testAuth(self):
        httpclient = self.httpclient
        httpclient.add_credentials("test", "test")

        res = Resource(self.url, httpclient)
        result = res.get('/auth')
        self.assert_(result.http_code == 200)

        httpclient.add_credentials("test", "test2")

        def niettest():
            res = Resource(self.url, httpclient)
            result = res.get('/auth')
        self.assertRaises(Unauthorized, niettest)

if __name__ == '__main__':
    from _server_test import run_server_test
    run_server_test()
    unittest.main()
<commit_msg>no need to retest httplib2 based client<commit_after># -*- coding: utf-8 -
#
# Copyright (c) 2008 (c) Benoit Chesneau <benoitc@e-engura.com>
#
# 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 BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer
import cgi
import os
import socket
import threading
import unittest
import urlparse

from restclient.http import CurlHTTPClient
from restclient.rest import Resource, RestClient, RequestFailed, \
ResourceNotFound, Unauthorized
from _server_test import HOST, PORT

class HTTPClientTestCase(unittest.TestCase):
    httpclient = CurlHTTPClient()

    def setUp(self):
        self.url = 'http://%s:%s' % (HOST, PORT)
        self.res = Resource(self.url, self.httpclient)

    def tearDown(self):
        self.res = None

    def testGet(self):
        result = self.res.get()
        self.assert_(result == "welcome")

    def testGetWithContentType(self):
        result = self.res.get('/json', headers={'Content-Type': 'application/json'})
        self.assert_(result.http_code == 200)
        def bad_get():
            result = self.res.get('/json', headers={'Content-Type': 'text/plain'})
        self.assertRaises(RequestFailed, bad_get)

    def testNotFound(self):
        def bad_get():
            result = self.res.get("/unknown")

        self.assertRaises(ResourceNotFound, bad_get)

    def testGetWithQuery(self):
        result = self.res.get('/query', test="testing")
        self.assert_(result.http_code == 200)

    def testSimplePost(self):
        result = self.res.post(payload="test")
        self.assert_(result=="test")

    def testPostWithContentType(self):
        result = self.res.post('/json', payload="test",
                headers={'Content-Type': 'application/json'})
        self.assert_(result.http_code == 200 )
        def bad_post():
            result = self.res.post('/json', payload="test",
                    headers={'Content-Type': 'text/plain'})
        self.assertRaises(RequestFailed, bad_post)

    def testEmptyPost(self):
        result = self.res.post('/empty', payload="",
                headers={'Content-Type': 'application/json'})
        self.assert_(result.http_code == 200 )
        result = self.res.post('/empty',headers={'Content-Type': 'application/json'})
        self.assert_(result.http_code == 200 )

    def testPostWithQuery(self):
        result = self.res.post('/query', test="testing")
        self.assert_(result.http_code == 200)

    def testSimplePut(self):
        result = self.res.put(payload="test")
        self.assert_(result=="test")

    def testPutWithContentType(self):
        result = self.res.put('/json', payload="test",
                headers={'Content-Type': 'application/json'})
        self.assert_(result.http_code == 200 )
        def bad_put():
            result = self.res.put('/json', payload="test",
                    headers={'Content-Type': 'text/plain'})
        self.assertRaises(RequestFailed, bad_put)

    def testEmptyPut(self):
        result = self.res.put('/empty', payload="",
                headers={'Content-Type': 'application/json'})
        self.assert_(result.http_code == 200 )
        result = self.res.put('/empty',headers={'Content-Type': 'application/json'})
        self.assert_(result.http_code == 200 )

    def testPuWithQuery(self):
        result = self.res.put('/query', test="testing")
        self.assert_(result.http_code == 200)

    def testHead(self):
        result = self.res.head('/ok')
        self.assert_(result.http_code == 200)

    def testDelete(self):
        result = self.res.delete('/delete')
        self.assert_(result.http_code == 200)

    def testAuth(self):
        httpclient = self.httpclient
        httpclient.add_credentials("test", "test")

        res = Resource(self.url, httpclient)
        result = res.get('/auth')
        self.assert_(result.http_code == 200)

        httpclient.add_credentials("test", "test2")

        def niettest():
            res = Resource(self.url, httpclient)
            result = res.get('/auth')
        self.assertRaises(Unauthorized, niettest)

if __name__ == '__main__':
    from _server_test import run_server_test
    run_server_test()
    unittest.main()
<|endoftext|>


<commit_before>#!/usr/bin/env python
# coding=utf-8

"""
This sample script was written on behalf of Graham and an enquiry he
had for a years worth of output data for Hydro & Biogas stations.

As usual REGO output will be used a proxy for output.

The library appears unable to cope with setting the technology field
directly and so we restrict the options setting to the year, month and
scheme and then simply filter the returned data.
"""

import argparse
import sys
import csv
from datetime import date

from pywind.ofgem import *

def main():
    parser = argparse.ArgumentParser(description='Extract monthly data for supplied year for Hydro or Biogas stations.')
    parser.add_argument('--year',
                        action='store',
                        type=int,
                        default=date.today().year - 1,
                        help='Year to extract data for')
    parser.add_argument('--technology', nargs='*')

    args = parser.parse_args()

    if args.technology is None:
        print "You must specify at least one technology group"
        sys.exit(0)
    print "  Searching year ", args.year, "\n"
    tids = []
    fn = "_".join(args.technology) + "_%d.csv" % args.year
    print fn
    for t in args.technology:
        for poss in CertificateSearch.TECHNOLOGY_LIST:
            if t.lower() in poss.lower():
                tids.append(CertificateSearch.TECHNOLOGY_LIST[poss])
                print "  Filter will match technology ", poss

    cs = CertificateSearch()
    cs.set_start_year(args.year)
    cs.set_finish_year(args.year)
    cs.set_start_month(1)
    cs.set_finish_month(12)
    cs['scheme'] = 1

    print "\n\nSearching for certificates..."
    cs.get_data()
    print "\n Complete.\n\nTotal of %d records to be filtered" % len(cs)
    added = 0

    with open(fn, 'wb') as csvfile:
        spamwriter = csv.writer(csvfile, delimiter=',',
                                quotechar='"', quoting=csv.QUOTE_MINIMAL)
        spamwriter.writerow([x.capitalize() for x in cs.certificates[0].FIELDS])
        for c in cs.certificates:
            for t in args.technology:
                if t.lower() in c['technology'].lower():
                    spamwriter.writerow(c.as_list())
                    added += 1
    print "Filtering complete. %d records saved as %s" % (added, fn)

if __name__ == '__main__':
    main()
<commit_msg>Update annual_output.py<commit_after>#!/usr/bin/env python
# coding=utf-8

"""
This sample script was written on behalf of Graham and an enquiry he
had for a years worth of output data for Hydro & Biogas stations.

As usual REGO output will be used a proxy for output.

The library appears unable to cope with setting the technology field
directly and so we restrict the options setting to the year, month and
scheme and then simply filter the returned data.
"""

import argparse
import sys
import csv
from datetime import date

from pywind.ofgem import *

def main():
    parser = argparse.ArgumentParser(description='Extract monthly data for supplied year for Hydro or Biogas stations.')
    parser.add_argument('--year',
                        action='store',
                        type=int,
                        default=date.today().year - 1,
                        help='Year to extract data for')
    parser.add_argument('--technology', nargs='*')

    args = parser.parse_args()

    if args.technology is None:
        print ("You must specify at least one technology group")
        sys.exit(0)
    print ("  Searching year ", args.year, "\n")
    tids = []
    fn = "_".join(args.technology) + "_%d.csv" % args.year
    print (fn)
    for t in args.technology:
        for poss in CertificateSearch.TECHNOLOGY_LIST:
            if t.lower() in poss.lower():
                tids.append(CertificateSearch.TECHNOLOGY_LIST[poss])
                print ("  Filter will match technology ", poss)

    cs = CertificateSearch()
    cs.set_start_year(args.year)
    cs.set_finish_year(args.year)
    cs.set_start_month(1)
    cs.set_finish_month(12)
    cs['scheme'] = 1

    print ("\n\nSearching for certificates...")
    cs.get_data()
    print ("\n Complete.\n\nTotal of %d records to be filtered" % len(cs))
    added = 0

    with open(fn, 'wb') as csvfile:
        spamwriter = csv.writer(csvfile, delimiter=',',
                                quotechar='"', quoting=csv.QUOTE_MINIMAL)
        spamwriter.writerow([x.capitalize() for x in cs.certificates[0].FIELDS])
        for c in cs.certificates:
            for t in args.technology:
                if t.lower() in c['technology'].lower():
                    spamwriter.writerow(c.as_list())
                    added += 1
    print ("Filtering complete. %d records saved as %s" % (added, fn))

if __name__ == '__main__':
    main()
<|endoftext|>


<commit_before>"""An XBlock providing thumbs-up/thumbs-down voting."""

from xblock.core import XBlock, XBlockAside
from xblock.fields import Scope, Integer, Boolean
from xblock.fragment import Fragment
import pkg_resources

import logging
log = logging.getLogger(__name__)

class ThumbsBlockBase(object):
    """
    An XBlock with thumbs-up/thumbs-down voting.

    Vote totals are stored for all students to see.  Each student is recorded
    as has-voted or not.

    This demonstrates multiple data scopes and ajax handlers.

    """
    upvotes = Integer(help="Number of up votes", default=0, scope=Scope.user_state_summary)
    downvotes = Integer(help="Number of down votes", default=0, scope=Scope.user_state_summary)
    voted = Boolean(help="Has this student voted?", default=False, scope=Scope.user_state)

    def student_view(self, context=None):  # pylint: disable=W0613
        """
        Create a fragment used to display the XBlock to a student.
        `context` is a dictionary used to configure the display (unused)

        Returns a `Fragment` object specifying the HTML, CSS, and JavaScript
        to display.
        """

        # Load the HTML fragment from within the package and fill in the template
        html_str = pkg_resources.resource_string(__name__, "static/html/thumbs.html")
        frag = Fragment(unicode(html_str).format(self=self))

        # Load the CSS and JavaScript fragments from within the package
        css_str = pkg_resources.resource_string(__name__, "static/css/thumbs.css")
        frag.add_css(unicode(css_str))

        js_str = pkg_resources.resource_string(__name__,
                                               "static/js/src/thumbs.js")
        frag.add_javascript(unicode(js_str))

        frag.initialize_js('ThumbsBlock')
        return frag

    problem_view = student_view

    @XBlock.json_handler
    def vote(self, data, suffix=''):  # pylint: disable=unused-argument
        """
        Update the vote count in response to a user action.
        """
        # Here is where we would prevent a student from voting twice, but then
        # we couldn't click more than once in the demo!
        #
        #     if self.voted:
        #         log.error("cheater!")
        #         return

        if data['voteType'] not in ('up', 'down'):
            log.error('error!')
            return

        if data['voteType'] == 'up':
            self.upvotes += 1
        else:
            self.downvotes += 1

        self.voted = True

        return {'up': self.upvotes, 'down': self.downvotes}

    @staticmethod
    def workbench_scenarios():
        """A canned scenario for display in the workbench."""
        return [
            ("three thumbs at once",
             """\
                <vertical_demo>
                    <thumbs/>
                    <thumbs/>
                    <thumbs/>
                </vertical_demo>
             """)
        ]

class ThumbsBlock(ThumbsBlockBase, XBlock):
    """
    An XBlock with thumbs-up/thumbs-down voting.

    Vote totals are stored for all students to see.  Each student is recorded
    as has-voted or not.

    This demonstrates multiple data scopes and ajax handlers.
    """
    pass

class ThumbsAside(ThumbsBlockBase, XBlockAside):
    """
    An XBlockAside with thumbs-up/thumbs-down voting.

    Vote totals are stored for all students to see.  Each student is recorded
    as has-voted or not.

    This demonstrates multiple data scopes and ajax handlers.
    """

    @XBlockAside.aside_for('student_view')
    def student_view_aside(self, block, context=None): #pylint: disable=unused-argument
        """
        Allow the thumbs up/down-voting to work as an Aside as well as an XBlock.
        """
        fragment = self.student_view(context)
        fragment.initialize_js('ThumbsAside')
        return fragment
<commit_msg>Fix PEP8: inline comment<commit_after>"""An XBlock providing thumbs-up/thumbs-down voting."""

from xblock.core import XBlock, XBlockAside
from xblock.fields import Scope, Integer, Boolean
from xblock.fragment import Fragment
import pkg_resources

import logging
log = logging.getLogger(__name__)

class ThumbsBlockBase(object):
    """
    An XBlock with thumbs-up/thumbs-down voting.

    Vote totals are stored for all students to see.  Each student is recorded
    as has-voted or not.

    This demonstrates multiple data scopes and ajax handlers.

    """
    upvotes = Integer(help="Number of up votes", default=0, scope=Scope.user_state_summary)
    downvotes = Integer(help="Number of down votes", default=0, scope=Scope.user_state_summary)
    voted = Boolean(help="Has this student voted?", default=False, scope=Scope.user_state)

    def student_view(self, context=None):  # pylint: disable=W0613
        """
        Create a fragment used to display the XBlock to a student.
        `context` is a dictionary used to configure the display (unused)

        Returns a `Fragment` object specifying the HTML, CSS, and JavaScript
        to display.
        """

        # Load the HTML fragment from within the package and fill in the template
        html_str = pkg_resources.resource_string(__name__, "static/html/thumbs.html")
        frag = Fragment(unicode(html_str).format(self=self))

        # Load the CSS and JavaScript fragments from within the package
        css_str = pkg_resources.resource_string(__name__, "static/css/thumbs.css")
        frag.add_css(unicode(css_str))

        js_str = pkg_resources.resource_string(__name__,
                                               "static/js/src/thumbs.js")
        frag.add_javascript(unicode(js_str))

        frag.initialize_js('ThumbsBlock')
        return frag

    problem_view = student_view

    @XBlock.json_handler
    def vote(self, data, suffix=''):  # pylint: disable=unused-argument
        """
        Update the vote count in response to a user action.
        """
        # Here is where we would prevent a student from voting twice, but then
        # we couldn't click more than once in the demo!
        #
        #     if self.voted:
        #         log.error("cheater!")
        #         return

        if data['voteType'] not in ('up', 'down'):
            log.error('error!')
            return

        if data['voteType'] == 'up':
            self.upvotes += 1
        else:
            self.downvotes += 1

        self.voted = True

        return {'up': self.upvotes, 'down': self.downvotes}

    @staticmethod
    def workbench_scenarios():
        """A canned scenario for display in the workbench."""
        return [
            ("three thumbs at once",
             """\
                <vertical_demo>
                    <thumbs/>
                    <thumbs/>
                    <thumbs/>
                </vertical_demo>
             """)
        ]

class ThumbsBlock(ThumbsBlockBase, XBlock):
    """
    An XBlock with thumbs-up/thumbs-down voting.

    Vote totals are stored for all students to see.  Each student is recorded
    as has-voted or not.

    This demonstrates multiple data scopes and ajax handlers.
    """
    pass

class ThumbsAside(ThumbsBlockBase, XBlockAside):
    """
    An XBlockAside with thumbs-up/thumbs-down voting.

    Vote totals are stored for all students to see.  Each student is recorded
    as has-voted or not.

    This demonstrates multiple data scopes and ajax handlers.
    """

    @XBlockAside.aside_for('student_view')
    def student_view_aside(self, block, context=None):  # pylint: disable=unused-argument
        """
        Allow the thumbs up/down-voting to work as an Aside as well as an XBlock.
        """
        fragment = self.student_view(context)
        fragment.initialize_js('ThumbsAside')
        return fragment
<|endoftext|>


<commit_before># -*- coding: utf-8 -*-
##############################################################################
#
#    Saas Manager
#    Copyright (C) 2013 Sistemas ADHOC
#    No email
#
#    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 <http://www.gnu.org/licenses/>.
#
##############################################################################

{   'active': False,
    'author': u'Sistemas ADHOC',
    'category': u'base.module_category_knowledge_management',
    'demo_xml': [
      ],
    'depends': [u'law_tracking',],
    'description': """
Law Tracking custom translations
================================
* Traduccion de mail de invitacion a portal (no funciona porque en la version saas el envio de email desde portal no se esta traduciendo)
""",
    'init_xml': [],
    'installable': True,
    'license': 'AGPL-3',
    'name': u'Law Tracking Custom Translations',
    'test': [],
    'update_xml': [
    ],
    'init_xml': [

    ],
    'version': u'1.1',
    'css': [
        'static/src/css/note.css',
        ],
    'application': True,
    'website': 'www.sistemasadhoc.com.ar'}

# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
<commit_msg>FIX dependencies on custom trnaslations<commit_after># -*- coding: utf-8 -*-
##############################################################################
#
#    Saas Manager
#    Copyright (C) 2013 Sistemas ADHOC
#    No email
#
#    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 <http://www.gnu.org/licenses/>.
#
##############################################################################

{   'active': False,
    'author': u'Sistemas ADHOC',
    'category': u'base.module_category_knowledge_management',
    'demo_xml': [
      ],
    'depends': [u'law_tracking','web_kanban'],
    'description': """
Law Tracking custom translations
================================
* Traduccion de mail de invitacion a portal (no funciona porque en la version saas el envio de email desde portal no se esta traduciendo)
""",
    'init_xml': [],
    'installable': True,
    'license': 'AGPL-3',
    'name': u'Law Tracking Custom Translations',
    'test': [],
    'update_xml': [
    ],
    'init_xml': [

    ],
    'version': u'1.1',
    'css': [
        'static/src/css/note.css',
        ],
    'application': True,
    'website': 'www.sistemasadhoc.com.ar'}

# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
<|endoftext|>


<commit_before>__author__ = 'Per'

# decrypts a (binary/Ascii) number with XOR-operator and given cypher

plaintext = "001100"  # STRING!!!     will become input later
plainKey = "0110"
decryptedText = ""

def checkIfOnly_1_used(key, plaintext):  # checks if text and key is in binary code (made of only 1's and 0's)

    textNumbersAreCorrect = None  # if text is binary => true, else => false
    keyNumbersAreCorrect = None  # if key is binary => true, else => false
    allNumbersAreCorrect = None

    for char in key:   # checks on Key

        if (char == "0") or (char == "1"):
            keyNumbersAreCorrect = True
        else:
            keyNumbersAreCorrect = False
            break

    for char in plaintext:  # checks on Text

        if (char == "0") or (char == "1"):
            textNumbersAreCorrect = True
        else:
            textNumbersAreCorrect = False

    if (keyNumbersAreCorrect == True) & (textNumbersAreCorrect == True):  # add's both checks to 1

        allNumbersAreCorrect = True
    else:
        allNumbersAreCorrect = False

    return allNumbersAreCorrect

def matchKeyLengthToPlaintextLenght(key, plaintext):

    matchedKey = key  # for case if length of key and text is the same

    if len(plaintext) > len(key):   # if key is to short

        lengthDiff = len(plaintext) - len(key)  # the length difference between key and plaintext
        matchedKeyAsList = []

        for letter in key:  # makes key a list

            matchedKeyAsList.append(letter)

        matchedKeyAsList.append(matchedKeyAsList[0])  # and add's it's first letter to the end

        if lengthDiff > 1:   # if more than one letter needs to be added to the key

            for i in range (1, lengthDiff):  # it is appended to the end of the list

                matchedKeyAsList.append(matchedKeyAsList[i])

        matchedKey = "".join(matchedKeyAsList)   # joins key list back to String

    elif len(plaintext) < len(key):   # if key is to long

        lengthDiff = len(key) - len(plaintext)  # difference between key and text
        matchedKeyAsList = []

        for letter in key:  # makes key a list

            matchedKeyAsList.append(letter)

        for i in range (0, lengthDiff):  # and removes as many items from 0 to length diff, so length of text and key is equal
            matchedKeyAsList.pop(i)

        matchedKey = "".join(matchedKeyAsList)  # joins key list back to String

    return matchedKey

bool_numbersAreCorrect = checkIfOnly_1_used(plainKey, plaintext)

print(bool_numbersAreCorrect)

matchedKey = matchKeyLengthToPlaintextLenght(plainKey, plaintext)

print(matchedKey)

<commit_msg>improved readability<commit_after>__author__ = 'Per'

# decrypts a (binary/Ascii) number with XOR-operator and given cypher

plaintext = "001100"  # STRING!!!     will become input later
plainKey = "0110"
decryptedText = ""

def checkIfOnly_1_used(key, plaintext):  # checks if text and key is in binary code (made of only 1's and 0's)

    textNumbersAreCorrect = None  # if text is binary => true, else => false
    keyNumbersAreCorrect = None  # if key is binary => true, else => false
    allNumbersAreCorrect = None

    for char in key:   # checks on Key

        if (char == "0") or (char == "1"):
            keyNumbersAreCorrect = True
        else:
            keyNumbersAreCorrect = False
            break

    for char in plaintext:  # checks on Text

        if (char == "0") or (char == "1"):
            textNumbersAreCorrect = True
        else:
            textNumbersAreCorrect = False

    if (keyNumbersAreCorrect == True) & (textNumbersAreCorrect == True):  # add's both checks to 1

        allNumbersAreCorrect = True
    else:
        allNumbersAreCorrect = False

    return allNumbersAreCorrect

def matchKeyLengthToPlaintextLenght(key, plaintext):

    matchedKey = key  # for case if length of key and text is the same

    if len(plaintext) > len(key):   # if key is to short

        lengthDiff = len(plaintext) - len(key)  # the length difference between key and plaintext
        matchedKeyAsList = []

        for letter in key:  # makes key a list

            matchedKeyAsList.append(letter)

        matchedKeyAsList.append(matchedKeyAsList[0])  # and add's it's first letter to the end

        if lengthDiff > 1:   # if more than one letter needs to be added to the key

            for i in range (1, lengthDiff):  # it is appended to the end of the list

                matchedKeyAsList.append(matchedKeyAsList[i])

        matchedKey = "".join(matchedKeyAsList)   # joins key list back to String

    elif len(plaintext) < len(key):   # if key is to long

        lengthDiff = len(key) - len(plaintext)  # difference between key and text
        matchedKeyAsList = []

        for letter in key:  # makes key a list

            matchedKeyAsList.append(letter)

        for i in range (0, lengthDiff):  # and removes as many items from 0 to length diff, so length of text and key is equal
            matchedKeyAsList.pop(i)

        matchedKey = "".join(matchedKeyAsList)  # joins key list back to String

    return matchedKey

bool_numbersAreCorrect = checkIfOnly_1_used(plainKey, plaintext)

print(bool_numbersAreCorrect)

matchedKey = matchKeyLengthToPlaintextLenght(plainKey, plaintext)

print(matchedKey)

<|endoftext|>


<commit_before>import os, pickle, re, sys
from common.safeprint import safeprint
from multiprocessing import Lock

bountyList = []
bountyLock = Lock()

class Bounty:
  ip = ""
  btc = ""
  reward = 0
  data = []

  def __init__(self, ipAddress, btcAddress, rewardAmount, dataList=[]):
    self.ip = ipAddress
    self.btc = btcAddress
    self.reward = rewardAmount
    self.data = dataList

  def isValid(self):
    try:
      safeprint("Testing IP address")
      #is IP valid
      b = int(self.ip.split(":")[1]) in range(1024,49152)
      b = int(self.ip.split(":")[0].split(".")[0]) in range(0,256) and b
      b = int(self.ip.split(":")[0].split(".")[1]) in range(0,256) and b
      b = int(self.ip.split(":")[0].split(".")[2]) in range(0,256) and b
      b = int(self.ip.split(":")[0].split(".")[3]) in range(0,256) and b
      if not b:
        return False
      #ping IP
      #is Bitcoin address valid
      safeprint("Testing Bitcoin address")
      address = str(self.btc)
      #The following is a soft check
      #A deeper check will need to be done in order to assure this is correct
      if not re.match(re.compile("^[a-zA-Z1-9]{27,35}$"),address):
        return False
      #is reward valid
      safeprint("Testing reward")
      b = int(self.reward)
      return (b >= 0)
    except:
      return False

  def isPayable(self):
    #check if address has enough
    return False

def verify(string):
  test = pickle.loads(string)
  try:
    safeprint("Testing IP address")
    #is IP valid
    b = int(test.ip.split(":")[1]) in range(1024,49152)
    b = int(test.ip.split(":")[0].split(".")[0]) in range(0,256) and b
    b = int(test.ip.split(":")[0].split(".")[1]) in range(0,256) and b
    b = int(test.ip.split(":")[0].split(".")[2]) in range(0,256) and b
    b = int(test.ip.split(":")[0].split(".")[3]) in range(0,256) and b
    if not b:
      return False
    #ping IP
    #is Bitcoin address valid
    safeprint("Testing Bitcoin address")
    address = str(test.btc)
    #The following is a soft check
    #A deeper check will need to be done in order to assure this is correct
    if not re.match(re.compile("^[a-zA-Z1-9]{27,35}$"),address):
      return False
    #is reward valid
    safeprint("Testing reward")
    b = int(test.reward)
    return (b >= 0)
  except:
    return False

def saveToFile():
  if os.path.exists("bounties.pickle"):
    pickle.dump(boutyList,"bounties.pickle")
    return True
  return False

def loadFromFile():
  if os.path.exists("settings.conf"):
    bountyList = pickle.load("bounties.pickle")
    return True
  return False

def loadBounties():
  loadFromFile()
  if len(bountyList) is 0:
    requestBounties()
  return len(bountyList) is not 0

def requestBounties(peerList):
  for peer in peerList:
    bountyList.extend(requestBounty(peer))

def requestBounty(peer):
  safeprint("currently unsupported")

def sendBounty(peer):
  safeprint("currently unsupported")
  if len(bountyList) is 0:
    loadBounties()
  #send bounties
  dumpBounties()

def addBounty(bounty):
  a = False
  if type(bounty) == type("aaa") and sys.version_info[0] >= 3:
    safeprint("Fed as string, encoding utf-8")
    bounty = bounty.encode('utf-8')
  elif sys.version_info[0] < 3:
    safeprint("External verify")
    a = verify(bounty)
  if type(bounty) == type("a".encode('utf-8')):
    safeprint("External verify")
    a = verify(bounty)
    bounty = pickle.loads(bounty)
  else:
    c = pickle.dumps(bounty,1)
    if type(c) == type("aaa") and sys.version_info[0] >= 3:
      safeprint("Fed as string, encoding utf-8")
      c = c.encode('utf-8')
    safeprint("External verify")
    a = verify(c)
  safeprint("Internal verify")
  b = bounty.isValid()
  if a and b:
    with bountyLock:
      bountyList.append(bounty)
  return (a and b)

def getBounty(charity, factor):
  for bounty in bountyList:
    if best is None:
      best = bounty
    elif best.rewardAmount < bounty.rewardAmount and bounty.isValid() and (isPayable(factor) or charity):
      best = bounty
  return best
<commit_msg>Hopefully fix addBounty()<commit_after>import os, pickle, re, sys
from common.safeprint import safeprint
from multiprocessing import Lock

bountyList = []
bountyLock = Lock()

class Bounty:
  ip = ""
  btc = ""
  reward = 0
  data = []

  def __init__(self, ipAddress, btcAddress, rewardAmount, dataList=[]):
    self.ip = ipAddress
    self.btc = btcAddress
    self.reward = rewardAmount
    self.data = dataList

  def isValid(self):
    try:
      safeprint("Testing IP address")
      #is IP valid
      b = int(self.ip.split(":")[1]) in range(1024,49152)
      b = int(self.ip.split(":")[0].split(".")[0]) in range(0,256) and b
      b = int(self.ip.split(":")[0].split(".")[1]) in range(0,256) and b
      b = int(self.ip.split(":")[0].split(".")[2]) in range(0,256) and b
      b = int(self.ip.split(":")[0].split(".")[3]) in range(0,256) and b
      if not b:
        return False
      #ping IP
      #is Bitcoin address valid
      safeprint("Testing Bitcoin address")
      address = str(self.btc)
      #The following is a soft check
      #A deeper check will need to be done in order to assure this is correct
      if not re.match(re.compile("^[a-zA-Z1-9]{27,35}$"),address):
        return False
      #is reward valid
      safeprint("Testing reward")
      b = int(self.reward)
      return (b >= 0)
    except:
      return False

  def isPayable(self):
    #check if address has enough
    return False

def verify(string):
  test = pickle.loads(string)
  try:
    safeprint("Testing IP address")
    #is IP valid
    b = int(test.ip.split(":")[1]) in range(1024,49152)
    b = int(test.ip.split(":")[0].split(".")[0]) in range(0,256) and b
    b = int(test.ip.split(":")[0].split(".")[1]) in range(0,256) and b
    b = int(test.ip.split(":")[0].split(".")[2]) in range(0,256) and b
    b = int(test.ip.split(":")[0].split(".")[3]) in range(0,256) and b
    if not b:
      return False
    #ping IP
    #is Bitcoin address valid
    safeprint("Testing Bitcoin address")
    address = str(test.btc)
    #The following is a soft check
    #A deeper check will need to be done in order to assure this is correct
    if not re.match(re.compile("^[a-zA-Z1-9]{27,35}$"),address):
      return False
    #is reward valid
    safeprint("Testing reward")
    b = int(test.reward)
    return (b >= 0)
  except:
    return False

def saveToFile():
  if os.path.exists("bounties.pickle"):
    pickle.dump(boutyList,"bounties.pickle")
    return True
  return False

def loadFromFile():
  if os.path.exists("settings.conf"):
    bountyList = pickle.load("bounties.pickle")
    return True
  return False

def loadBounties():
  loadFromFile()
  if len(bountyList) is 0:
    requestBounties()
  return len(bountyList) is not 0

def requestBounties(peerList):
  for peer in peerList:
    bountyList.extend(requestBounty(peer))

def requestBounty(peer):
  safeprint("currently unsupported")

def sendBounty(peer):
  safeprint("currently unsupported")
  if len(bountyList) is 0:
    loadBounties()
  #send bounties
  dumpBounties()

def addBounty(bounty):
  a = False
  if type(bounty) == type("aaa") and sys.version_info[0] >= 3:
    bounty = bounty.encode('utf-8')
  safeprint("External verify")
  a = verify(bounty)
  b = pickle.loads(bounty)
  safeprint("Internal verify")
  b = bounty.isValid()
  if a and b:
    with bountyLock:
      bountyList.append(bounty)
  return (a and b)

def getBounty(charity, factor):
  for bounty in bountyList:
    if best is None:
      best = bounty
    elif best.rewardAmount < bounty.rewardAmount and bounty.isValid() and (isPayable(factor) or charity):
      best = bounty
  return best
<|endoftext|>


<commit_before>
"""
.. module:: operators.python_pipeline_operator

    :synopsis: A PythonOperator that moves XCOM data used by the pipeline

.. moduleauthor:: Ludovic Claude <ludovic.claude@chuv.ch>
"""

from airflow.operators.python_operator import PythonOperator
from airflow.utils import apply_defaults
from airflow_pipeline.pipelines import TransferPipelineXComs

import logging

class PythonPipelineOperator(PythonOperator, TransferPipelineXComs):

    """
    A PythonOperator that moves XCOM data used by the pipeline.

    :param python_callable: A reference to an object that is callable
    :type python_callable: python callable
    :param op_kwargs: a dictionary of keyword arguments that will get unpacked
        in your function
    :type op_kwargs: dict
    :param op_args: a list of positional arguments that will get unpacked when
        calling your callable
    :type op_args: list
    :param provide_context: if set to true, Airflow will pass a set of
        keyword arguments that can be used in your function. This set of
        kwargs correspond exactly to what you can use in your jinja
        templates. For this to work, you need to define `**kwargs` in your
        function header.
    :type provide_context: bool
    :param templates_dict: a dictionary where the values are templates that
        will get templated by the Airflow engine sometime between
        ``__init__`` and ``execute`` takes place and are made available
        in your callable's context after the template has been applied
    :type templates_dict: dict of str
    :param templates_exts: a list of file extensions to resolve while
        processing templated fields, for examples ``['.sql', '.hql']``
    :param parent_task: name of the parent task to use to locate XCom parameters
    :type parent_task: str
    """

    template_fields = ('templates_dict', 'incoming_parameters', )
    template_ext = tuple()
    ui_color = '#94A147'

    @apply_defaults
    def __init__(
            self,
            python_callable,
            op_args=None,
            op_kwargs=None,
            provide_context=True,
            templates_dict=None,
            templates_exts=None,
            parent_task=None,
            *args, **kwargs):

        PythonOperator.__init__(self,
                                python_callable=python_callable,
                                op_args=op_args,
                                op_kwargs=op_kwargs,
                                provide_context=provide_context,
                                templates_dict=templates_dict,
                                templates_exts=templates_exts,
                                *args, **kwargs)
        TransferPipelineXComs.__init__(self, parent_task, None)

    def pre_execute(self, context):
        self.read_pipeline_xcoms(context, expected=['dataset'])

    def execute(self, context):
        self.op_kwargs = self.op_kwargs or {}
        self.pipeline_xcoms = self.pipeline_xcoms or {}
        if self.provide_context:
            context.update(self.op_kwargs)
            context.update(self.pipeline_xcoms)
            self.op_kwargs = context

        return_value = self.python_callable(*self.op_args, **self.op_kwargs)
        logging.info("Done. Returned value was: " + str(return_value))

        if isinstance(return_value, dict):
            self.pipeline_xcoms.update(return_value)

        self.write_pipeline_xcoms(context)

        return return_value
<commit_msg>Add provenance tracking to Python pipeline operator<commit_after>
"""
.. module:: operators.python_pipeline_operator

    :synopsis: A PythonOperator that moves XCOM data used by the pipeline

.. moduleauthor:: Ludovic Claude <ludovic.claude@chuv.ch>
"""

from airflow.operators.python_operator import PythonOperator
from airflow.utils import apply_defaults
from airflow_pipeline.pipelines import TransferPipelineXComs

import logging
import json

class PythonPipelineOperator(PythonOperator, TransferPipelineXComs):

    """
    A PythonOperator that moves XCOM data used by the pipeline.

    :param python_callable: A reference to an object that is callable.
        If the call returns a Python dictionary with the key 'folder', the
        value of that key will be used to build provenance and scan the output folder for files.
    :type python_callable: python callable
    :param op_kwargs: a dictionary of keyword arguments that will get unpacked
        in your function
    :type op_kwargs: dict
    :param op_args: a list of positional arguments that will get unpacked when
        calling your callable
    :type op_args: list
    :param provide_context: if set to true, Airflow will pass a set of
        keyword arguments that can be used in your function. This set of
        kwargs correspond exactly to what you can use in your jinja
        templates. For this to work, you need to define `**kwargs` in your
        function header.
    :type provide_context: bool
    :param templates_dict: a dictionary where the values are templates that
        will get templated by the Airflow engine sometime between
        ``__init__`` and ``execute`` takes place and are made available
        in your callable's context after the template has been applied
    :type templates_dict: dict of str
    :param templates_exts: a list of file extensions to resolve while
        processing templated fields, for examples ``['.sql', '.hql']``
    :param parent_task: name of the parent task to use to locate XCom parameters
    :type parent_task: str
    :param on_failure_trigger_dag_id: The dag_id to trigger if this stage of the pipeline has failed,
        i.e. when validate_result_callable raises AirflowSkipException.
    :type on_failure_trigger_dag_id: str
    :param software_versions: List of software and their versions used to build provenance information.
    :type software_versions: dictionary
    """

    template_fields = ('templates_dict', 'incoming_parameters', )
    template_ext = tuple()
    ui_color = '#94A147'

    @apply_defaults
    def __init__(
            self,
            python_callable,
            op_args=None,
            op_kwargs=None,
            provide_context=True,
            templates_dict=None,
            templates_exts=None,
            parent_task=None,
            on_failure_trigger_dag_id=None,
            software_versions=None,
            *args, **kwargs):

        PythonOperator.__init__(self,
                                python_callable=python_callable,
                                op_args=op_args,
                                op_kwargs=op_kwargs,
                                provide_context=provide_context,
                                templates_dict=templates_dict,
                                templates_exts=templates_exts,
                                *args, **kwargs)
        TransferPipelineXComs.__init__(self, parent_task, None)
        self.on_failure_trigger_dag_id = on_failure_trigger_dag_id
        self.software_versions = software_versions

    def pre_execute(self, context):
        self.read_pipeline_xcoms(context, expected=['dataset'])

    def execute(self, context):
        self.op_kwargs = self.op_kwargs or {}
        self.pipeline_xcoms = self.pipeline_xcoms or {}
        if self.provide_context:
            context.update(self.op_kwargs)
            context.update(self.pipeline_xcoms)
            self.op_kwargs = context

        try:
            return_value = self.python_callable(*self.op_args, **self.op_kwargs)
        except Exception as e:
            self.trigger_dag(context, self.on_failure_trigger_dag_id, str(e))
            raise
        logging.info("Done. Returned value was: " + str(return_value))

        if isinstance(return_value, dict):
            self.pipeline_xcoms.update(return_value)
            if 'folder' in return_value:
                self.track_provenance(return_value['folder'], json.dumps(
                    self.software_versions) if self.software_versions else '{}')

        self.write_pipeline_xcoms(context)

        return return_value
<|endoftext|>


<commit_before><commit_msg>Implement jobs endpoints<commit_after>from src.endpoints.base import Base

class Jobs(Base):
	endpoint = '/jobs'

	def get_status_of_job(self, job_id):
		return self.client.get(
			self.endpoint + '/' + job_id + '/status'
		)

	def get_status_of_jobs(self, type, params=None):
		return self.client.get(
			self.endpoint + '/type/' + type + '/statuses',
			params=params
		)
<|endoftext|>


<commit_before>import os, pickle, re, sys
from common.safeprint import safeprint
from multiprocessing import Lock
from hashlib import sha256

global bountyList
global bountyLock
global bountyPath
global keyList
bountyList = []
bountyLock = Lock()
bounty_path = "data" + os.sep + "bounties.pickle"
keyList = []

def getUTC():
    from calendar import timegm
    from time import gmtime
    return timegm(gmtime())

class Bounty(object):
    """An object representation of a Bounty
    Parts:
    ip         -- The ip address of the requesting node
    btc        -- The Bitcoin address of the requesting party
    reward     -- The reward amount in satoshis to be given over 24 hours
                   (x | x == 0 or 1440 <= x <= 100000000) (1440 is 1 satoshi/minute)
    ident      -- A value set by the issuer to determine which problem/test to send
    timeout    -- Unix time at which the bounty expires (defaults to 24 hours)
    data       -- A dictionary containing optional, additional information
        author -- String which represents the group providing the Bounty
        reqs   -- Dict containing requirements keyed by the related python calls
                   ("sys.platform":"win32")
        perms  -- Dict containing the minimum required security policies
                   (if empty, most restrictive assumed)
        key    -- A tuple which contains the RSA n and e values for this Bounty
                   (required only when reward is 0)
        sig    -- A Bytes object of the Bounty's print output signed by the above key
                   (required only when reward is 0)
        TDL    -- More to be defined in later versions
    """

    def __repr__(self):
        """Gives a string representation of the bounty"""
        output = "<Bounty: ip=" + str(self.ip) + ", btc=" + str(self.btc) + ", reward=" + str(self.reward)
        if self.ident != None:
            output = output + ", id=" + str(self.ident)
        if self.timeout != None:
            output = output + ", timeout=" + str(self.timeout)
        if self.data and self.data != {'author':'','reqs':{},'perms':{}}:
            if self.data.get('author') and self.data.get('author') != '':
                output = output + ", author=" + str(self.data.get('author'))
            if self.data.get('reqs') and self.data.get('reqs') != {} and type(self.data.get('reqs')) == type({}):
                output = output + ", reqs=" + str(sorted(self.data.get('reqs').items(), key=lambda x: x[0]))
            if self.data.get('perms') and self.data.get('perms') != {} and type(self.data.get('perms')) == type({}):
                output = output + ", perms=" + str(sorted(self.data.get('perms').items(), key=lambda x: x[0]))
        return output + ">"

    def __eq__(self, other):
        """Determines whether the bounties are equal"""
        return (self.reward == other.reward) and (self.ident == other.ident) and (self.data == other.data)

    def __ne__(self, other):
        """Determines whether the bounties are unequal"""
        return not self.__eq__(other)

    def __lt__(self, other):
        """Determines whether this bounty has a lower priority"""
        if self.reward < other.reward:
            return True
        elif self.timeout < other.timeout:
            return True
        else:
            return False

    def __gt__(self, other):
        """Determines whether this bounty has a higher priority"""
        if self.reward > other.reward:
            return True
        elif self.timeout > other.timeout:
            return True
        else:
            return False

    def __le__(self, other):
        """Determines whether this bounty has a lower priority or is equal"""
        boolean = self.__lt__(other)
        if boolean:
            return boolean
        else:
            return self.__eq__(other)

    def __ge__(self, other):
        """Determines whether this bounty has a higher or is equal"""
        boolean = self.__gt__(other)
        if boolean:
            return boolean
        else:
            return self.__eq__(other)

    def __hash__(self):
        h = [self.__repr__()]
        if self.data.get('key') is not None:
            h.append(str(self.data.get('key')))
        if self.data.get('sig') is not None:
            h.append(str(self.data.get('sig')))
        return hash(tuple(h))

    def __init__(self, ipAddress, btcAddress, rewardAmount, timeout=None, ident=None, dataDict={}, keypair=None):
        """Initialize a Bounty; constructor"""
        self.ip = ipAddress
        self.btc = btcAddress
        self.reward = rewardAmount
        self.ident = None
        if timeout is not None:
            self.timeout = timeout
        else:
            self.timeout = getUTC() + 86400
        self.data = {'author':'',
                     'reqs':{},
                     'perms':{}}
        if ident is not None:
            self.ident = ident
        if dataDict is not None:
            self.data.update(dataDict)
        if keypair is not None:
            self.sign(keypair)

    def isValid(self):
        """Internal method which checks the Bounty as valid under the most minimal version

        ip      -- Must be in valid range
        btc     -- Must be in valid namespace
        reward  -- Must be in valid range
        timeout -- Must be greater than the current time
        """
        try:
            safeprint("Testing IP address",verbosity=1)
            boolean = int(self.ip.split(":")[1]) in range(1024,49152)
            if len(self.ip.split(":")[0].split(".")) != 4:
                return False
            for sect in self.ip.split(":")[0].split("."):
                boolean = int(sect) in range(0,256) and boolean
            if not boolean:
                return False
            safeprint("Testing Bitcoin address",verbosity=1)
            address = str(self.btc)
            #The following is a soft check
            #A deeper check will need to be done in order to assure this is correct
            if not checkAddressValid(address):
                return False
            safeprint("Testing reward",verbosity=1)
            reward = int(self.reward)
            boolean = reward >= 1440 and reward <= 100000000
            if reward == 0 or reward is None:
                safeprint("Testing signature validity",verbosity=1)
                boolean = self.checkSign()
            if boolean is False:
                return False
            safeprint("Testing timeout",verbosity=1)
            if self.timeout < getUTC(): #check against current UTC
                return False
            from common.call import parse
            safeprint("Testing bounty requirements",verbosity=1)
            if parse(self.data.get('reqs')):
                return 1
            else:
                return -1
        except:
            return False

    def isPayable(self, factor):
        """check if address has enough"""
        return True #later make this a wrapper for pywallet.balance()

    def checkSign(self):
        """check if the signature attatched to the Bounty is valid"""
        try:
            from rsa import verify, PublicKey
            safeprint(keyList)
            if self.data.get('key') in keyList:    #where key is (PublicKey.n, PublicKey.e)
                expected = str(self).encode('utf-8')
                n = self.data.get('key')[0]
                e = self.data.get('key')[1]
                return verify(expected,self.data.get('sig'),PublicKey(n,e))
            return False
        except:
            return False

    def sign(self,privateKey):    #where privateKey is a private key generated by rsa.PrivateKey()
        """Signa bounty and attach the key value"""
        try:
            from rsa import sign
            expected = str(self).encode('utf-8')
            self.data.update({'key' : (privateKey.n, privateKey.e),
                              'sig' : sign(expected, privateKey, 'SHA-256')})
        except:
            return False

def addKey(key):
    global keyList
    keyList.append(key)

def checkAddressValid(address):
    """Check to see if a Bitcoin address is within the valid namespace. Will potentially give false positives based on leading 1s"""
    if not re.match(re.compile("^[a-km-zA-HJ-Z1-9]{26,35}$"),address):
        return False
    decimal = 0
    for char in address:
        decimal = decimal * 58 + '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'.index(char)
    if sys.version_info[0] < 3:
        """long does not have a to_bytes() in versions less than 3. This is an equivalent function"""
        bcbytes = (('%%0%dx' % (25 << 1) % decimal).decode('hex')[-25:])
        return bcbytes[-4:] == sha256(sha256(bcbytes[:-4]).digest()).digest()[:4]
    else:
        bcbytes = decimal.to_bytes(25, 'big')
        return bcbytes[-4:] == sha256(sha256(bcbytes[:-4]).digest()).digest()[:4]

def verify(string):
    """External method which checks the Bounty as valid under implementation-specific requirements. This can be defined per user.

    ip      -- Must be in valid range
    btc     -- Must be in valid namespace
    reward  -- Must be in valid range
    timeout -- Must be greater than the current time
    """
    test = None
    if type(string) == type(Bounty(None,None,None)):
        test = string
    else:
        try:
            test = pickle.loads(string)
        except:
            return False
    try:
        safeprint("Testing IP address",verbosity=1)
        boolean = int(test.ip.split(":")[1]) in range(1024,49152)
        if len(test.ip.split(":")[0].split(".")) != 4:
            return False
        for sect in test.ip.split(":")[0].split("."):
            boolean = int(sect) in range(0,256) and boolean
        if not boolean:
            return False
        safeprint("Testing Bitcoin address",verbosity=1)
        address = str(test.btc)
        #The following is a soft check
        #A deeper check will need to be done in order to assure this is correct
        if not checkAddressValid(address):
            return False
        safeprint("Testing reward",verbosity=1)
        reward = int(test.reward)
        boolean = reward >= 1440 and reward <= 100000000
        if reward == 0 or reward is None:
            safeprint("Testing signature validity",verbosity=1)
            boolean = test.checkSign()
        if boolean is False:
            return False
        safeprint("Testing timeout",verbosity=1)
        if test.timeout < getUTC(): #check against current UTC
            return False
        from common.call import parse
        safeprint("Testing bounty requirements",verbosity=1)
        if parse(test.data.get('reqs')):
            return 1
        else:
            return -1
    except:
        return False

def getBountyList():
    """Retrieves the bounty list. Temporary method"""
    temp = []
    with bountyLock:
        temp = bountyList
    return temp

def saveToFile(bountyList):
    """Save the current bounty list to a file"""
    if not os.path.exists(bounty_path.split(os.sep)[0]):
        os.mkdir(bounty_path.split(os.sep)[0])
    pickle.dump(bountyList,open(bounty_path, "wb"),0)
    return True

def loadFromFile():
    """Load a previous bounty list from a file"""
    if os.path.exists(bounty_path):
        with bountyLock:
            try:
                bountyList = pickle.load(open(bounty_path,"rb"))
            except:
                return False
        return True
    return False

def addBounty(bounty):
    """Verify a bounty, and add it to the list if it is valid"""
    first = False
    safeprint([sys.version_info[0],sys.version_info[1],sys.version_info[2]])
    if sys.version_info[0] == 2 and sys.version_info[1] == 6 and (type(bounty) == type("aaa") or type(bounty) == type(unicode("aaa"))):
        safeprint("Fed as string in 2.6; encoding ascii and ignoring errors")
        try:
            bounty = bounty.encode('ascii','ignore')
        except:
            bounty = str(bounty)
    elif type(bounty) == type("aaa") and sys.version_info[0] >= 3:
        safeprint("Fed as string; encoding utf-8")
        bounty = bounty.encode('utf-8')
    safeprint(pickle.loads(bounty))
    safeprint("External verify",verbosity=1)
    try:
        bounty = pickle.loads(bounty)
    except:
        return False
    first = verify(bounty)
    safeprint("Internal verify")
    second = bounty.isValid()
    safeprint(second)
    if not second:
        rval = -3
    elif not first:
        rval = -2
    elif bounty in getBountyList():
        rval = -1
    elif second == -1:
        rval = 0
    else:
        rval = 1
    if rval == 1:
        addValidBounty(bounty)
    return rval

def addValidBounty(bounty):
    """This adds a bounty to the list under the assumption that it's already been validated. Must be of type common.bounty.Bounty"""
    with bountyLock:
        global bountyList
        bountyList.append(bounty)
        bountyList = list(set(bountyList))  #trim it in the simplest way possible. Doesn't protect against malleability

def internalVerify(bounty): #pragma: no cover
    """Proxy for the Bounty.isValid() method, for use with multiprocessing.Pool"""
    return bounty.isValid()

def addBounties(bounties):
    """Add a list of bounties in parallel using multiprocessing.Pool for verification"""
    from multiprocessing.pool import ThreadPool
    pool = ThreadPool()
    async = pool.map_async(verify,bounties)  #defer this for possible efficiency boost
    internal = pool.map(internalVerify,bounties)
    external = async.get()
    rvals = []
    for i in range(len(bounties)):
        if not internal[i]:
            rvals.append(-3)
        elif not external[i]:
            rvals.append(-2)
        elif bounties[i] in getBountyList():
            rvals.append(-1)
        elif internal[i] == -1:
            rvals.append(0)
        else:
            rvals.append(1)
        if rvals[i] == 1:
            addValidBounty(bounties[i])
    return rvals

def getBounty(charity, factor):
    """Retrieve the next best bounty from the list"""
    temp = getBountyList()
    safeprint("bountyList = " + str(temp),verbosity=3)
    if temp == []:
        return None
    elif charity:
        for bounty in temp:
            if bounty.isValid():
                index = temp.index(bounty)
                return temp.pop(index)
    else:
        best = None
        for bounty in temp:
            if best is None:
                best = bounty
            elif best < bounty and bounty.isValid() and bounty.isPayable(factor):
                best = bounty
        return best
<commit_msg>Remove debug print<commit_after>import os, pickle, re, sys
from common.safeprint import safeprint
from multiprocessing import Lock
from hashlib import sha256

global bountyList
global bountyLock
global bountyPath
global keyList
bountyList = []
bountyLock = Lock()
bounty_path = "data" + os.sep + "bounties.pickle"
keyList = []

def getUTC():
    from calendar import timegm
    from time import gmtime
    return timegm(gmtime())

class Bounty(object):
    """An object representation of a Bounty
    Parts:
    ip         -- The ip address of the requesting node
    btc        -- The Bitcoin address of the requesting party
    reward     -- The reward amount in satoshis to be given over 24 hours
                   (x | x == 0 or 1440 <= x <= 100000000) (1440 is 1 satoshi/minute)
    ident      -- A value set by the issuer to determine which problem/test to send
    timeout    -- Unix time at which the bounty expires (defaults to 24 hours)
    data       -- A dictionary containing optional, additional information
        author -- String which represents the group providing the Bounty
        reqs   -- Dict containing requirements keyed by the related python calls
                   ("sys.platform":"win32")
        perms  -- Dict containing the minimum required security policies
                   (if empty, most restrictive assumed)
        key    -- A tuple which contains the RSA n and e values for this Bounty
                   (required only when reward is 0)
        sig    -- A Bytes object of the Bounty's print output signed by the above key
                   (required only when reward is 0)
        TDL    -- More to be defined in later versions
    """

    def __repr__(self):
        """Gives a string representation of the bounty"""
        output = "<Bounty: ip=" + str(self.ip) + ", btc=" + str(self.btc) + ", reward=" + str(self.reward)
        if self.ident != None:
            output = output + ", id=" + str(self.ident)
        if self.timeout != None:
            output = output + ", timeout=" + str(self.timeout)
        if self.data and self.data != {'author':'','reqs':{},'perms':{}}:
            if self.data.get('author') and self.data.get('author') != '':
                output = output + ", author=" + str(self.data.get('author'))
            if self.data.get('reqs') and self.data.get('reqs') != {} and type(self.data.get('reqs')) == type({}):
                output = output + ", reqs=" + str(sorted(self.data.get('reqs').items(), key=lambda x: x[0]))
            if self.data.get('perms') and self.data.get('perms') != {} and type(self.data.get('perms')) == type({}):
                output = output + ", perms=" + str(sorted(self.data.get('perms').items(), key=lambda x: x[0]))
        return output + ">"

    def __eq__(self, other):
        """Determines whether the bounties are equal"""
        return (self.reward == other.reward) and (self.ident == other.ident) and (self.data == other.data)

    def __ne__(self, other):
        """Determines whether the bounties are unequal"""
        return not self.__eq__(other)

    def __lt__(self, other):
        """Determines whether this bounty has a lower priority"""
        if self.reward < other.reward:
            return True
        elif self.timeout < other.timeout:
            return True
        else:
            return False

    def __gt__(self, other):
        """Determines whether this bounty has a higher priority"""
        if self.reward > other.reward:
            return True
        elif self.timeout > other.timeout:
            return True
        else:
            return False

    def __le__(self, other):
        """Determines whether this bounty has a lower priority or is equal"""
        boolean = self.__lt__(other)
        if boolean:
            return boolean
        else:
            return self.__eq__(other)

    def __ge__(self, other):
        """Determines whether this bounty has a higher or is equal"""
        boolean = self.__gt__(other)
        if boolean:
            return boolean
        else:
            return self.__eq__(other)

    def __hash__(self):
        h = [self.__repr__()]
        if self.data.get('key') is not None:
            h.append(str(self.data.get('key')))
        if self.data.get('sig') is not None:
            h.append(str(self.data.get('sig')))
        return hash(tuple(h))

    def __init__(self, ipAddress, btcAddress, rewardAmount, timeout=None, ident=None, dataDict={}, keypair=None):
        """Initialize a Bounty; constructor"""
        self.ip = ipAddress
        self.btc = btcAddress
        self.reward = rewardAmount
        self.ident = None
        if timeout is not None:
            self.timeout = timeout
        else:
            self.timeout = getUTC() + 86400
        self.data = {'author':'',
                     'reqs':{},
                     'perms':{}}
        if ident is not None:
            self.ident = ident
        if dataDict is not None:
            self.data.update(dataDict)
        if keypair is not None:
            self.sign(keypair)

    def isValid(self):
        """Internal method which checks the Bounty as valid under the most minimal version

        ip      -- Must be in valid range
        btc     -- Must be in valid namespace
        reward  -- Must be in valid range
        timeout -- Must be greater than the current time
        """
        try:
            safeprint("Testing IP address",verbosity=1)
            boolean = int(self.ip.split(":")[1]) in range(1024,49152)
            if len(self.ip.split(":")[0].split(".")) != 4:
                return False
            for sect in self.ip.split(":")[0].split("."):
                boolean = int(sect) in range(0,256) and boolean
            if not boolean:
                return False
            safeprint("Testing Bitcoin address",verbosity=1)
            address = str(self.btc)
            #The following is a soft check
            #A deeper check will need to be done in order to assure this is correct
            if not checkAddressValid(address):
                return False
            safeprint("Testing reward",verbosity=1)
            reward = int(self.reward)
            boolean = reward >= 1440 and reward <= 100000000
            if reward == 0 or reward is None:
                safeprint("Testing signature validity",verbosity=1)
                boolean = self.checkSign()
            if boolean is False:
                return False
            safeprint("Testing timeout",verbosity=1)
            if self.timeout < getUTC(): #check against current UTC
                return False
            from common.call import parse
            safeprint("Testing bounty requirements",verbosity=1)
            if parse(self.data.get('reqs')):
                return 1
            else:
                return -1
        except:
            return False

    def isPayable(self, factor):
        """check if address has enough"""
        return True #later make this a wrapper for pywallet.balance()

    def checkSign(self):
        """check if the signature attatched to the Bounty is valid"""
        try:
            from rsa import verify, PublicKey
            safeprint(keyList)
            if self.data.get('key') in keyList:    #where key is (PublicKey.n, PublicKey.e)
                expected = str(self).encode('utf-8')
                n = self.data.get('key')[0]
                e = self.data.get('key')[1]
                return verify(expected,self.data.get('sig'),PublicKey(n,e))
            return False
        except:
            return False

    def sign(self,privateKey):    #where privateKey is a private key generated by rsa.PrivateKey()
        """Signa bounty and attach the key value"""
        try:
            from rsa import sign
            expected = str(self).encode('utf-8')
            self.data.update({'key' : (privateKey.n, privateKey.e),
                              'sig' : sign(expected, privateKey, 'SHA-256')})
        except:
            return False

def addKey(key):
    global keyList
    keyList.append(key)

def checkAddressValid(address):
    """Check to see if a Bitcoin address is within the valid namespace. Will potentially give false positives based on leading 1s"""
    if not re.match(re.compile("^[a-km-zA-HJ-Z1-9]{26,35}$"),address):
        return False
    decimal = 0
    for char in address:
        decimal = decimal * 58 + '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'.index(char)
    if sys.version_info[0] < 3:
        """long does not have a to_bytes() in versions less than 3. This is an equivalent function"""
        bcbytes = (('%%0%dx' % (25 << 1) % decimal).decode('hex')[-25:])
        return bcbytes[-4:] == sha256(sha256(bcbytes[:-4]).digest()).digest()[:4]
    else:
        bcbytes = decimal.to_bytes(25, 'big')
        return bcbytes[-4:] == sha256(sha256(bcbytes[:-4]).digest()).digest()[:4]

def verify(string):
    """External method which checks the Bounty as valid under implementation-specific requirements. This can be defined per user.

    ip      -- Must be in valid range
    btc     -- Must be in valid namespace
    reward  -- Must be in valid range
    timeout -- Must be greater than the current time
    """
    test = None
    if type(string) == type(Bounty(None,None,None)):
        test = string
    else:
        try:
            test = pickle.loads(string)
        except:
            return False
    try:
        safeprint("Testing IP address",verbosity=1)
        boolean = int(test.ip.split(":")[1]) in range(1024,49152)
        if len(test.ip.split(":")[0].split(".")) != 4:
            return False
        for sect in test.ip.split(":")[0].split("."):
            boolean = int(sect) in range(0,256) and boolean
        if not boolean:
            return False
        safeprint("Testing Bitcoin address",verbosity=1)
        address = str(test.btc)
        #The following is a soft check
        #A deeper check will need to be done in order to assure this is correct
        if not checkAddressValid(address):
            return False
        safeprint("Testing reward",verbosity=1)
        reward = int(test.reward)
        boolean = reward >= 1440 and reward <= 100000000
        if reward == 0 or reward is None:
            safeprint("Testing signature validity",verbosity=1)
            boolean = test.checkSign()
        if boolean is False:
            return False
        safeprint("Testing timeout",verbosity=1)
        if test.timeout < getUTC(): #check against current UTC
            return False
        from common.call import parse
        safeprint("Testing bounty requirements",verbosity=1)
        if parse(test.data.get('reqs')):
            return 1
        else:
            return -1
    except:
        return False

def getBountyList():
    """Retrieves the bounty list. Temporary method"""
    temp = []
    with bountyLock:
        temp = bountyList
    return temp

def saveToFile(bountyList):
    """Save the current bounty list to a file"""
    if not os.path.exists(bounty_path.split(os.sep)[0]):
        os.mkdir(bounty_path.split(os.sep)[0])
    pickle.dump(bountyList,open(bounty_path, "wb"),0)
    return True

def loadFromFile():
    """Load a previous bounty list from a file"""
    if os.path.exists(bounty_path):
        with bountyLock:
            try:
                bountyList = pickle.load(open(bounty_path,"rb"))
            except:
                return False
        return True
    return False

def addBounty(bounty):
    """Verify a bounty, and add it to the list if it is valid"""
    first = False
    safeprint([sys.version_info[0],sys.version_info[1],sys.version_info[2]])
    if sys.version_info[0] == 2 and sys.version_info[1] == 6 and (type(bounty) == type("aaa") or type(bounty) == type(unicode("aaa"))):
        safeprint("Fed as string in 2.6; encoding ascii and ignoring errors")
        try:
            bounty = bounty.encode('ascii','ignore')
        except:
            bounty = str(bounty)
    elif type(bounty) == type("aaa") and sys.version_info[0] >= 3:
        safeprint("Fed as string; encoding utf-8")
        bounty = bounty.encode('utf-8')
    safeprint(pickle.loads(bounty))
    safeprint("External verify",verbosity=1)
    try:
        bounty = pickle.loads(bounty)
    except:
        return False
    first = verify(bounty)
    safeprint("Internal verify")
    second = bounty.isValid()
    if not second:
        rval = -3
    elif not first:
        rval = -2
    elif bounty in getBountyList():
        rval = -1
    elif second == -1:
        rval = 0
    else:
        rval = 1
    if rval == 1:
        addValidBounty(bounty)
    return rval

def addValidBounty(bounty):
    """This adds a bounty to the list under the assumption that it's already been validated. Must be of type common.bounty.Bounty"""
    with bountyLock:
        global bountyList
        bountyList.append(bounty)
        bountyList = list(set(bountyList))  #trim it in the simplest way possible. Doesn't protect against malleability

def internalVerify(bounty): #pragma: no cover
    """Proxy for the Bounty.isValid() method, for use with multiprocessing.Pool"""
    return bounty.isValid()

def addBounties(bounties):
    """Add a list of bounties in parallel using multiprocessing.Pool for verification"""
    from multiprocessing.pool import ThreadPool
    pool = ThreadPool()
    async = pool.map_async(verify,bounties)  #defer this for possible efficiency boost
    internal = pool.map(internalVerify,bounties)
    external = async.get()
    rvals = []
    for i in range(len(bounties)):
        if not internal[i]:
            rvals.append(-3)
        elif not external[i]:
            rvals.append(-2)
        elif bounties[i] in getBountyList():
            rvals.append(-1)
        elif internal[i] == -1:
            rvals.append(0)
        else:
            rvals.append(1)
        if rvals[i] == 1:
            addValidBounty(bounties[i])
    return rvals

def getBounty(charity, factor):
    """Retrieve the next best bounty from the list"""
    temp = getBountyList()
    safeprint("bountyList = " + str(temp),verbosity=3)
    if temp == []:
        return None
    elif charity:
        for bounty in temp:
            if bounty.isValid():
                index = temp.index(bounty)
                return temp.pop(index)
    else:
        best = None
        for bounty in temp:
            if best is None:
                best = bounty
            elif best < bounty and bounty.isValid() and bounty.isPayable(factor):
                best = bounty
        return best
<|endoftext|>