<commit_before>import requests, json
from slacker import Slacker

slack = Slacker('xoxp-3478131362-3477154371-3505081635-51a8a0')
username = 'upbot'
icon_emoji = 'mag'
commands = ['up', 'up help']
search = '!up reddit.com'

def post_message(text):
	slack.chat.post_message(text = text,
													username = username,
													icon_emoji = icon_emoji)

def need_help():
	post_message('I look up given address and tell you if it\'s up or naw.')

def respond():
	search = commands + text
	out = 'http://www.'+search
	conn = requests.get(out)
	status = conn.status_code

	if  status == 200:
		slack.chat.post_message(search + ' is up. It\'s just you.')
	else:
		slack.chat.post_message(search + 'is down. Check back later.')

def main():
	msguser = request.form.get("user_name", "").strip()
	if msguser == username or msguser.lower() == "slackbot":
		return

		text = request.form.get("text", "")
		match = re.findall(r"!(\S+)", text)

	if not match:
		return

		command = match[0]
   	#args = text.replace("!%s" % command, '')
   	#command = command.lower()

	if command not in commands:
		post_message('Not sure what "%s" is.' % command)
		return json.dumps({ })

	if command == 'up':
		respond()

	if command == 'up help':
		need_help()

	return json.dumps({ })
<commit_msg>no message<commit_after>import requests, json
from slacker import Slacker

slack = Slacker('xoxp-3478131362-3477154371-3505081635-51a8a0')
username = 'upbot'
icon_emoji = 'mag'
commands = ['up']

def post_message(text):
	slack.chat.post_message(text = text,
													username = username,
													icon_emoji = icon_emoji)

def need_help():
	post_message('I look up given address and tell you if it\'s up or naw.')

def respond():
	search = text - command
	out = 'http://www.'+search
	conn = requests.get(out)
	status = conn.status_code

	if  status == 200:
		slack.chat.post_message(search + ' is up. It\'s just you.')
	else:
		slack.chat.post_message(search + 'is down. Check back later.')

def main():
	text = request.form.get("text", "")
	match = re.findall(r"!(\S+)", text)

	if not match:
		return

		command = match[0]
   	args = text.replace("!%s" % command, '')
   	command = command.lower()

	if command not in commands:
		post_message('Not sure what "%s" is.' % command)
		return json.dumps({ })

	if command == 'up':
		respond()
	if command == 'up' and 'help':
		need_help()

	return json.dumps({ })
<|endoftext|>


<commit_before>import os

from whoosh.qparser import QueryParser
from whoosh.query import FuzzyTerm, And, Term

from whoosh import index
from whoosh.fields import Schema, ID, KEYWORD, TEXT

from whoosh.support.charset import accent_map
from whoosh.analysis import RegexTokenizer
from whoosh.analysis import CharsetFilter, LowercaseFilter, StopFilter

from lib.stopwords import stoplists

class IndexSchema():
    """
    Init schema and build a custom analyzer.

    All data to index will be put inside the
    """

    def __init__(self):

        chfilter = CharsetFilter(accent_map)
        stoplist = stoplists["en"].union(stoplists["fr"])
        analyzer = RegexTokenizer() | LowercaseFilter() | \
                   StopFilter(stoplist=stoplist) | chfilter

        self.schema = Schema(content=TEXT(analyzer=analyzer),
                             docType=TEXT,
                             docId=ID(stored=True),
                             tags=KEYWORD)

        if not os.path.exists("indexes"):
            os.mkdir("indexes")
            self.index = index.create_in("indexes", self.schema)
        else:
            self.index = index.open_dir("indexes")

    def clear_index(self):
        """
        Clear index: whoosh indexe create, create a new index in the directory
        even if an index exists.
        """

        if os.path.exists("indexes"):
            index.create_in("indexes", self.schema)

class Indexer():

    def index_doc(self, docType, doc, fields):
        """
        Add given doc to index, tag and given fields are stored.
        """

        indexSchema = IndexSchema()
        contents = []
        for field in fields:
            data = doc[field]
            if type(data) == "unicode":
                contents.append(data)
            elif data is not None:
                contents.append(data.encode("utf-8"))

        content = u" ".join(contents)
        writer = indexSchema.index.writer()
        writer.update_document(content=unicode(content),
                               docType=unicode(docType),
                               docId=unicode(doc["id"]),
                               tags=doc["tags"])
        writer.commit()

    def search_doc(self, word, docType):
        """
        Return a list of docs that contains given word and that matches
        given type.
        """

        indexSchema = IndexSchema()
        parser = QueryParser("content", schema=indexSchema.schema,
                termclass=FuzzyTerm)
        query = parser.parse(word)
        query = And([query, Term("docType", unicode(docType.lower()))])

        with indexSchema.index.searcher() as searcher:
            results = searcher.search(query)
            print [result["docId"] for result in results]
            return [result["docId"] for result in results]

    def remove_doc(self, id):
        """
        Remove given doc from index (doc of which docId is equal to id).
        """

        indexSchema = IndexSchema()

        writer = indexSchema.index.writer()
        writer.delete_by_term("docId", unicode(id))
        writer.commit()

    def remove_all(self):
        '''
        Remove all data from index.
        '''

        indexSchema = IndexSchema()
        indexSchema.clear_index()
<commit_msg>debug unicode<commit_after>import os

from whoosh.qparser import QueryParser
from whoosh.query import FuzzyTerm, And, Term

from whoosh import index
from whoosh.fields import Schema, ID, KEYWORD, TEXT

from whoosh.support.charset import accent_map
from whoosh.analysis import RegexTokenizer
from whoosh.analysis import CharsetFilter, LowercaseFilter, StopFilter

from lib.stopwords import stoplists

class IndexSchema():
    """
    Init schema and build a custom analyzer.

    All data to index will be put inside the
    """

    def __init__(self):

        chfilter = CharsetFilter(accent_map)
        stoplist = stoplists["en"].union(stoplists["fr"])
        analyzer = RegexTokenizer() | LowercaseFilter() | \
                   StopFilter(stoplist=stoplist) | chfilter

        self.schema = Schema(content=TEXT(analyzer=analyzer),
                             docType=TEXT,
                             docId=ID(stored=True),
                             tags=KEYWORD)

        if not os.path.exists("indexes"):
            os.mkdir("indexes")
            self.index = index.create_in("indexes", self.schema)
        else:
            self.index = index.open_dir("indexes")

    def clear_index(self):
        """
        Clear index: whoosh indexe create, create a new index in the directory
        even if an index exists.
        """

        if os.path.exists("indexes"):
            index.create_in("indexes", self.schema)

class Indexer():

    def index_doc(self, docType, doc, fields):
        """
        Add given doc to index, tag and given fields are stored.
        """

        indexSchema = IndexSchema()
        contents = []
        for field in fields:
            data = doc[field]
            if isinstance(data, unicode):
                contents.append(data)
            elif data is not None:
                contents.append(data.decode("utf-8"))

        content = u" ".join(contents)
        writer = indexSchema.index.writer()
        writer.update_document(content=content,
                               docType=unicode(docType),
                               docId=unicode(doc["id"]),
                               tags=doc["tags"])
        writer.commit()

    def search_doc(self, word, docType):
        """
        Return a list of docs that contains given word and that matches
        given type.
        """

        indexSchema = IndexSchema()
        parser = QueryParser("content", schema=indexSchema.schema,
                termclass=FuzzyTerm)
        query = parser.parse(word)
        query = And([query, Term("docType", unicode(docType.lower()))])

        with indexSchema.index.searcher() as searcher:
            results = searcher.search(query)
            print [result["docId"] for result in results]
            return [result["docId"] for result in results]

    def remove_doc(self, id):
        """
        Remove given doc from index (doc of which docId is equal to id).
        """

        indexSchema = IndexSchema()

        writer = indexSchema.index.writer()
        writer.delete_by_term("docId", unicode(id))
        writer.commit()

    def remove_all(self):
        '''
        Remove all data from index.
        '''

        indexSchema = IndexSchema()
        indexSchema.clear_index()
<|endoftext|>


<commit_before>#
# Jasy - Web Tooling Framework
# Copyright 2010-2012 Zynga Inc.
#

import logging, os

# Print out some info
import jasy
logging.info("Jasy %s" % jasy.__version__)
logging.debug("Jasy Path: %s" % os.path.dirname(os.path.abspath(jasy.__file__)))

def startSection(title):
    logging.info("")
    logging.info(">>> %s" % title.upper())
    logging.info("-------------------------------------------------------------------------------")

# Global permutation handling
__permutation = None

def getPermutation():
    global __permutation
    return __permutation

def setPermutation(use):
    global __permutation
    __permutation = use

# Global prefix handling
__prefix = None

def setPrefix(path):
    global __prefix

    if path is None:
        __prefix = None
        logging.info("Resetting dist folder")
    else:
        __prefix = os.path.normpath(os.path.abspath(os.path.expanduser(path)))
        logging.info("Setting prefix to: %s" % __prefix)

def getPrefix():
    global __prefix
    return __prefix

def prependPrefix(path):
    global __prefix

    if __prefix and not os.path.isabs(path):
        return os.path.join(__prefix, path)
    else:
        return path

# Global session object
from jasy.core.Session import Session
session = Session()

# Remote run support
__jasyCommand = None

def setJasyCommand(cmd):
    global __jasyCommand
    print("Setting jasy command to: %s" % cmd)
    __jasyCommand = cmd

def run(project, task, params=None):
    print("Running %s of project %s..." % (task, project))

    import subprocess
    from jasy.core.Project import getProjectByName

    # Pauses this session to allow sub process fully accessing the same projects
    session.pause()

    print("!!!PARAMS", params)

    # Change into sub folder and execute jasy task
    oldPath = os.getcwd()
    os.chdir(getProjectByName(project).getPath())
    subprocess.call([__jasyCommand, task])
    os.chdir(oldPath)

    # Resumes this session after sub process was finished
    session.resume()

# Task API for user scripts
from jasy.core.Task import *
from jasy.asset.Asset import *

# Resolving/Sorting classes
from jasy.js.Resolver import Resolver
from jasy.js.Sorter import Sorter

# API Writer
from jasy.js.api.Writer import ApiWriter

# Output options
from jasy.js.output.Optimization import Optimization
from jasy.js.output.Formatting import Formatting

formatting = Formatting()
optimization = Optimization("variables", "declarations", "blocks", "privates")

# Import file operation goodies
from jasy.util.File import *

# Import combiner script for merging/write js output
from jasy.js.output.Combiner import *

<commit_msg>Worked on remote jobs<commit_after>#
# Jasy - Web Tooling Framework
# Copyright 2010-2012 Zynga Inc.
#

import logging, os

# Print out some info
import jasy
logging.info("Jasy %s" % jasy.__version__)
logging.debug("Jasy Path: %s" % os.path.dirname(os.path.abspath(jasy.__file__)))

def startSection(title):
    logging.info("")
    logging.info(">>> %s" % title.upper())
    logging.info("-------------------------------------------------------------------------------")

# Global permutation handling
__permutation = None

def getPermutation():
    global __permutation
    return __permutation

def setPermutation(use):
    global __permutation
    __permutation = use

# Global prefix handling
__prefix = None

def setPrefix(path):
    global __prefix

    if path is None:
        __prefix = None
        logging.info("Resetting dist folder")
    else:
        __prefix = os.path.normpath(os.path.abspath(os.path.expanduser(path)))
        logging.info("Setting prefix to: %s" % __prefix)

def getPrefix():
    global __prefix
    return __prefix

def prependPrefix(path):
    global __prefix

    if __prefix and not os.path.isabs(path):
        return os.path.join(__prefix, path)
    else:
        return path

# Global session object
from jasy.core.Session import Session
session = Session()

# Remote run support
__jasyCommand = None

def setJasyCommand(cmd):
    global __jasyCommand
    print("Setting jasy command to: %s" % cmd)
    __jasyCommand = cmd

def run(project, task, **kwargs):
    print("Running %s of project %s..." % (task, project))

    import subprocess
    from jasy.core.Project import getProjectByName

    # Pauses this session to allow sub process fully accessing the same projects
    session.pause()

    # Build parameter list from optional arguments
    params = ["--%s=%s" % (key, kwargs[key]) for key in kwargs]
    if not "prefix" in kwargs:
        params.append("--prefix=%s" % __prefix)

    args = [__jasyCommand, task] + params
    print("ARGS: ", args)

    # Change into sub folder and execute jasy task
    oldPath = os.getcwd()
    os.chdir(getProjectByName(project).getPath())
    subprocess.call(args)
    os.chdir(oldPath)

    # Resumes this session after sub process was finished
    session.resume()

# Task API for user scripts
from jasy.core.Task import *
from jasy.asset.Asset import *

# Resolving/Sorting classes
from jasy.js.Resolver import Resolver
from jasy.js.Sorter import Sorter

# API Writer
from jasy.js.api.Writer import ApiWriter

# Output options
from jasy.js.output.Optimization import Optimization
from jasy.js.output.Formatting import Formatting

formatting = Formatting()
optimization = Optimization("variables", "declarations", "blocks", "privates")

# Import file operation goodies
from jasy.util.File import *

# Import combiner script for merging/write js output
from jasy.js.output.Combiner import *

<|endoftext|>


<commit_before>#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# ======================================================================
#
# hc.py
# ------
# Simple, pure Python model of the HC stream cipher with
# support for 128 and 256 bit keys.
#
# Note: Currently the model is only implementing HC-256.
#
#
# Author: Joachim Strömbergson
# Copyright (c) 2017, Assured AB
# 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.
#
# 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.
#
# ======================================================================

# ------------------------------------------------------------------
# Python module imports.
# ------------------------------------------------------------------
import sys

# -------------------------------------------------------------------
# HC
# The HC stream cipher class.
# ------------------------------------------------------------------
class HC():
    def __init__(self, verbose=False):
        # Constants
        self.MAX_W32 = 0xffffffff
        self.HC256_TSIZE = 1024
        self.HC128_TSIZE = 512
        self.DUMP_W_ELEMENTS = 64
        self.DUMP_PQ_ELEMENTS = 64

        # Allocate the internal state variables.
        self.verbose = verbose
        self.W = [0] * 2560
        self.P = [0] * 1024
        self.Q = [0] * 1024
        self.i = 0

    # Initialize the internal state given the key and iv.
    def init(self, key, iv):
        for i in range(8):
            self.W[i] = key[i]
            self.W[(i + 8)] = iv[i]

        for i in range(16, 2560):
            self.W[i] = (self.f2(self.W[(i - 2)]) + self.W[(i - 7)] +
                         self.f1(self.W[(i - 15)]) + self.W[(i - 16)] + i) & self.MAX_W32

        if self.verbose:
            self.dump_w()

        for i in range(1024):
            self.P[i] = self.W[(i + 512)]
            self.Q[i] = self.W[(i + 1536)]

        if self.verbose:
            print("P and Q before 4096 internal updates.")
            self.dump_pq()

        for i in range(4096):
            self.next()

        if self.verbose:
            print("P and Q after 4096 internal updates.")
            self.dump_pq()

    # Update internal state and return the next word.
    def next(self):
        j = self.i % 1024
        if (self.i % 2048) < 1024:
            if self.verbose:
                print("i = %04d, i3 = %04d, i10 = %04d, i1023 = %04d" %
                          (j, self.subm(j, 3), self.subm(j, 10), self.subm(j, 1023)))

                print("x[i] = 0x%08x, x[i3] = 0x%08x, x[i10] = 0x%08x, x[i1023] = 0x%08x" %
                          (self.P[j], self.P[self.subm(j, 3)],
                           self.P[self.subm(j, 10)], self.P[self.subm(j, 1023)]))

            self.P[j] = (self.P[j] + self.P[self.subm(j, 10)] +
                         self.g1(self.P[self.subm(j, 3)],
                         self.P[self.subm(j, 1023)])) & self.MAX_W32

            if self.verbose:
                print("New x[i] = 0x%08x" % self.P[j])

            s = self.h1(self.P[self.subm(j, 12)]) ^ self.P[j]

        else:
            self.Q[j] = (self.Q[j] + self.Q[self.subm(j, 10)] +
                         self.g2(self.Q[self.subm(j, 3)],
                         self.Q[self.subm(j, 1023)])) & self.MAX_W32
            s = self.h2(self.Q[self.subm(j, 12)]) ^ self.Q[j]

        self.i += 1
        return s

    # Internal HC functions.
    def f1(self, x):
        return self.rotr(x, 7) ^ self.rotr(x, 18) ^ self.shr(x, 3)

    def f2(self, x):
        return self.rotr(x, 17) ^ self.rotr(x, 19) ^ self.shr(x, 10)

    def g1(self, x, y):
        result = (self.rotr(x, 10) ^ self.rotr(x, 23) +
                  self.Q[((x ^ y) % 1024)]) & self.MAX_W32
        if self.verbose:
            print("In g1. x = 0x%08x, y = 0x%08x, res = 0x%08x" % (x, y, result))
        return result

    def g2(self, x, y):
        result = (self.rotr(x, 10) ^ self.rotr(x, 23) +
                  self.P[((x ^ y) % 1024)]) & self.MAX_W32
        if self.verbose:
            print("In g2. x = 0x%08x, y = 0x%08x, res = 0x%08x" % (x, y, result))
        return result

    def h1(self, x):
        (x0, x1, x2, x3) = self.w2b(x)
        return (self.Q[x0] + self.Q[(x1 + 256)] +
                self.Q[(x2 + 512)] + self.Q[(x3 + 768)]) & self.MAX_W32

    def h2(self, x):
        (x0, x1, x2, x3) = self.w2b(x)
        return (self.P[x0] + self.P[(x1 + 256)] +
                self.P[(x2 + 512)] + self.P[(x3 + 768)]) & self.MAX_W32

    # Helper functions needed to implement the HC functions.
    def rotr(self, w, b):
        return ((w >> b) | (w << (32 - b))) & self.MAX_W32

    def shr(self, w, b):
        return (w >> b)

    def w2b(self, x):
        x0 = x >> 24
        x1 = x >> 16 & 0xff
        x2 = x >> 8 & 0xff
        x3 = x & 0xff
        return (x0, x1, x2, x3)

    def subm(self, x, y):
        return (x - y) % 1024

    def dump_w(self):
        print("State of the W array:")
        for i in range(0, self.DUMP_W_ELEMENTS, 4):
            print("W[%04d..%04d]: 0x%08x 0x%08x 0x%08x 0x%08x" %
                      (i, i+3, self.W[i], self.W[i+1], self.W[i+2], self.W[i+3]))
        print("")

    def dump_pq(self):
        print("State of the P array:")
        for i in range(0, self.DUMP_PQ_ELEMENTS, 4):
            print("P[%04d..%04d]: 0x%08x 0x%08x 0x%08x 0x%08x" %
                      (i, i+3, self.P[i], self.P[i+1], self.P[i+2], self.P[i+3]))
        print("")
        print("State of the Q array:")
        for i in range(0, self.DUMP_PQ_ELEMENTS, 4):
            print("Q[%04d..%04d]: 0x%08x 0x%08x 0x%08x 0x%08x" %
                      (i, i+3, self.Q[i], self.Q[i+1], self.Q[i+2], self.Q[i+3]))
        print("")

# ------------------------------------------------------------------
# test_rotr()
# Test the hc help function rotr()
# ------------------------------------------------------------------
def test_rotr():
    my_hc = HC()
    print("Testing rotr help function.")
    for i in range(33):
        print("rotr %02d steps: 0x%08x" % (i, my_hc.rotr(0x00000001, i)))
    print("")

# ------------------------------------------------------------------
# test_hc()
# Test the HC implementation with 128 and 256 bit keys.
# ------------------------------------------------------------------
def test_hc():
    my_key = [0] * 8
    my_iv = [0] * 8

    my_hc = HC(verbose=True)
    my_hc.init(my_key, my_iv)

    for i in range(16):
        print("keystream %02d = 0x%08x" % (i, my_hc.next()))

# ------------------------------------------------------------------
# main()
# If executed tests the ChaCha class using known test vectors.
# ------------------------------------------------------------------
def main():
    print("Testing the HC stream cipher model")
    print("==================================")
    print

#    test_rotr()
    test_hc()

# ------------------------------------------------------------------
# __name__
# Python thingy which allows the file to be run standalone as
# well as parsed from within a Python interpreter.
# ------------------------------------------------------------------
if __name__ == "__main__":
    # Run the main function.
    sys.exit(main())

# ======================================================================
# EOF hc.py
# ======================================================================
<commit_msg>Splitting the g1 function into subparts that can be analyzed.<commit_after>#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# ======================================================================
#
# hc.py
# ------
# Simple, pure Python model of the HC stream cipher with
# support for 128 and 256 bit keys.
#
# Note: Currently the model is only implementing HC-256.
#
#
# Author: Joachim Strömbergson
# Copyright (c) 2017, Assured AB
# 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.
#
# 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.
#
# ======================================================================

# ------------------------------------------------------------------
# Python module imports.
# ------------------------------------------------------------------
import sys

# -------------------------------------------------------------------
# HC
# The HC stream cipher class.
# ------------------------------------------------------------------
class HC():
    def __init__(self, verbose=False):
        # Constants
        self.MAX_W32 = 0xffffffff
        self.HC256_TSIZE = 1024
        self.HC128_TSIZE = 512
        self.DUMP_W_ELEMENTS = 64
        self.DUMP_PQ_ELEMENTS = 64

        # Allocate the internal state variables.
        self.verbose = verbose
        self.W = [0] * 2560
        self.P = [0] * 1024
        self.Q = [0] * 1024
        self.i = 0

    # Initialize the internal state given the key and iv.
    def init(self, key, iv):
        for i in range(8):
            self.W[i] = key[i]
            self.W[(i + 8)] = iv[i]

        for i in range(16, 2560):
            self.W[i] = (self.f2(self.W[(i - 2)]) + self.W[(i - 7)] +
                         self.f1(self.W[(i - 15)]) + self.W[(i - 16)] + i) & self.MAX_W32

        if self.verbose:
            self.dump_w()

        for i in range(1024):
            self.P[i] = self.W[(i + 512)]
            self.Q[i] = self.W[(i + 1536)]

        if self.verbose:
            print("P and Q before 4096 internal updates.")
            self.dump_pq()

        for i in range(4096):
            self.next()

        if self.verbose:
            print("P and Q after 4096 internal updates.")
            self.dump_pq()

    # Update internal state and return the next word.
    def next(self):
        j = self.i % 1024
        if (self.i % 2048) < 1024:
            if self.verbose:
                print("i = %04d, i3 = %04d, i10 = %04d, i1023 = %04d" %
                          (j, self.subm(j, 3), self.subm(j, 10), self.subm(j, 1023)))

                print("x[i] = 0x%08x, x[i3] = 0x%08x, x[i10] = 0x%08x, x[i1023] = 0x%08x" %
                          (self.P[j], self.P[self.subm(j, 3)],
                           self.P[self.subm(j, 10)], self.P[self.subm(j, 1023)]))

            self.P[j] = (self.P[j] + self.P[self.subm(j, 10)] +
                         self.g1(self.P[self.subm(j, 3)],
                         self.P[self.subm(j, 1023)])) & self.MAX_W32

            if self.verbose:
                print("New x[i] = 0x%08x" % self.P[j])
                print("")

            s = self.h1(self.P[self.subm(j, 12)]) ^ self.P[j]

        else:
            self.Q[j] = (self.Q[j] + self.Q[self.subm(j, 10)] +
                         self.g2(self.Q[self.subm(j, 3)],
                         self.Q[self.subm(j, 1023)])) & self.MAX_W32
            s = self.h2(self.Q[self.subm(j, 12)]) ^ self.Q[j]

        self.i += 1
        return s

    # Internal HC functions.
    def f1(self, x):
        return self.rotr(x, 7) ^ self.rotr(x, 18) ^ self.shr(x, 3)

    def f2(self, x):
        return self.rotr(x, 17) ^ self.rotr(x, 19) ^ self.shr(x, 10)

    def g1(self, x, y):
        qval = self.Q[((x ^ y) % 1024)]
        rot10 = self.rotr(x, 10)
        rot23 = self.rotr(x, 23)
        result = ((rot10 ^ rot23) + qval) & self.MAX_W32
        if self.verbose:
            print("In g1. x = 0x%08x, y = 0x%08x, res = 0x%08x" % (x, y, result))
        return result

    def g2(self, x, y):
        result = (self.rotr(x, 10) ^ self.rotr(x, 23) +
                  self.P[((x ^ y) % 1024)]) & self.MAX_W32
        if self.verbose:
            print("In g2. x = 0x%08x, y = 0x%08x, res = 0x%08x" % (x, y, result))
        return result

    def h1(self, x):
        (x0, x1, x2, x3) = self.w2b(x)
        return (self.Q[x0] + self.Q[(x1 + 256)] +
                self.Q[(x2 + 512)] + self.Q[(x3 + 768)]) & self.MAX_W32

    def h2(self, x):
        (x0, x1, x2, x3) = self.w2b(x)
        return (self.P[x0] + self.P[(x1 + 256)] +
                self.P[(x2 + 512)] + self.P[(x3 + 768)]) & self.MAX_W32

    # Helper functions needed to implement the HC functions.
    def rotr(self, w, b):
        return ((w >> b) | (w << (32 - b))) & self.MAX_W32

    def shr(self, w, b):
        return (w >> b)

    def w2b(self, x):
        x0 = x >> 24
        x1 = x >> 16 & 0xff
        x2 = x >> 8 & 0xff
        x3 = x & 0xff
        return (x0, x1, x2, x3)

    def subm(self, x, y):
        return (x - y) % 1024

    def dump_w(self):
        print("State of the W array:")
        for i in range(0, self.DUMP_W_ELEMENTS, 4):
            print("W[%04d..%04d]: 0x%08x 0x%08x 0x%08x 0x%08x" %
                      (i, i+3, self.W[i], self.W[i+1], self.W[i+2], self.W[i+3]))
        print("")

    def dump_pq(self):
        print("State of the P array:")
        for i in range(0, self.DUMP_PQ_ELEMENTS, 4):
            print("P[%04d..%04d]: 0x%08x 0x%08x 0x%08x 0x%08x" %
                      (i, i+3, self.P[i], self.P[i+1], self.P[i+2], self.P[i+3]))
        print("")
        print("State of the Q array:")
        for i in range(0, self.DUMP_PQ_ELEMENTS, 4):
            print("Q[%04d..%04d]: 0x%08x 0x%08x 0x%08x 0x%08x" %
                      (i, i+3, self.Q[i], self.Q[i+1], self.Q[i+2], self.Q[i+3]))
        print("")

# ------------------------------------------------------------------
# test_rotr()
# Test the hc help function rotr()
# ------------------------------------------------------------------
def test_rotr():
    my_hc = HC()
    print("Testing rotr help function.")
    for i in range(33):
        print("rotr %02d steps: 0x%08x" % (i, my_hc.rotr(0x00000001, i)))
    print("")

# ------------------------------------------------------------------
# test_hc()
# Test the HC implementation with 128 and 256 bit keys.
# ------------------------------------------------------------------
def test_hc():
    my_key = [0] * 8
    my_iv = [0] * 8

    my_hc = HC(verbose=True)
    my_hc.init(my_key, my_iv)

    for i in range(16):
        print("keystream %02d = 0x%08x" % (i, my_hc.next()))

# ------------------------------------------------------------------
# main()
# If executed tests the ChaCha class using known test vectors.
# ------------------------------------------------------------------
def main():
    print("Testing the HC stream cipher model")
    print("==================================")
    print

#    test_rotr()
    test_hc()

# ------------------------------------------------------------------
# __name__
# Python thingy which allows the file to be run standalone as
# well as parsed from within a Python interpreter.
# ------------------------------------------------------------------
if __name__ == "__main__":
    # Run the main function.
    sys.exit(main())

# ======================================================================
# EOF hc.py
# ======================================================================
<|endoftext|>


<commit_before># -*- coding: utf-8 -*-

import phuzzy as ph
from phuzzy.mpl import mix_mpl
import matplotlib.pyplot as plt
import numpy as np
# import matplotlib.mlab as mlab
import matplotlib.colors
from matplotlib.patches import Polygon
from matplotlib.collections import PatchCollection

def f(x1, x2):
    return (x1-1)**2+(x2+.4)**2 + .1

xs = np.linspace(-1, 2, 100)
ys = np.linspace(-1, 1, 100)

Xs, Ys = np.meshgrid(xs, ys)

Zs = f(Xs, Ys)

Hf = 200.  # mm
Bf = 300.  # mm
fig, axs = plt.subplots(2,2, dpi=90, facecolor='w', edgecolor='k', figsize=(Bf / 25.4, Hf / 25.4))

axl = axs[0,0]
axr = axs[0,1]
axc = axs[1,1]
axz = axs[1,0]
axl.set_title("z.l")
axr.set_title("z.r")
for ax in [axl, axr, axc]:
    ax.set_xlabel("x")
    ax.set_ylabel("y")

cmap = "autumn"

csc = axc.contourf(Xs, Ys, Zs, alpha=.2, cmap=cmap)
csc2 = axc.contour(Xs, Ys, Zs, color="k", cmap=cmap)
axc.clabel(csc2, fontsize=9, inline=1, alpha=1)

norm= matplotlib.colors.Normalize(vmin=csc.vmin, vmax=csc.vmax)
sm = plt.cm.ScalarMappable(norm=norm, cmap =csc.cmap)
sm.set_array([])
cbar = fig.colorbar(sm, ticks=csc.levels)
cbar.set_label("z")
x = ph.Trapezoid(alpha0=[-1,2], alpha1=[-.5, .5])
y = ph.TruncNorm(alpha0=[-1,0.5])

z = f(x,y)
z.name = "z"
print(z.df)

for i, zi in z.df.iterrows():
    xi = x.df.loc[i]
    yi = y.df.loc[i]
    axl.plot([xi.l, xi.r, xi.r, xi.l, xi.l],
            [yi.l, yi.l, yi.r, yi.r, yi.l],
             c=sm.to_rgba(zi.l))

    axr.plot([xi.l, xi.r, xi.r, xi.l, xi.l],
            [yi.l, yi.l, yi.r, yi.r, yi.l],
             c=sm.to_rgba(zi.r))

    polygon = Polygon(np.vstack([[xi.l, xi.r, xi.r, xi.l, xi.l],
                           [yi.l, yi.l, yi.r, yi.r, yi.l]]).T)
    pl = PatchCollection([polygon], alpha=.1, color=sm.to_rgba(zi.l))
    axl.add_collection(pl)

    pl = PatchCollection([polygon], alpha=.1, color=sm.to_rgba(zi.r))
    axr.add_collection(pl)

# cs = axl.contourf(Xs, Ys, Zs, alpha=.2, cmap="hot")
cs2 = axl.contour(Xs, Ys, Zs, cmap=cmap)
# cs2k = axl.contour(Xs, Ys, Zs, colors="k")
axl.clabel(cs2, fontsize=9, inline=1, alpha=1)

# csr = axr.contourf(Xs, Ys, Zs, alpha=.2, cmap="hot")
csr2 = axr.contour(Xs, Ys, Zs, color="k", cmap=cmap)
axr.clabel(csr2, fontsize=9, inline=1, alpha=1)

axl.scatter([1], [-.4])
axr.scatter([1], [-.4])
axc.scatter([1], [-.4])

mix_mpl(z)
z.plot(ax= axz, show=False)
axz.set_title(z)
axc.set_title("f(x,y)")
fig.tight_layout()
plt.show()
<commit_msg>add min_2d example<commit_after># -*- coding: utf-8 -*-

import phuzzy as ph
from phuzzy.mpl import mix_mpl
import matplotlib.pyplot as plt
import numpy as np
# import matplotlib.mlab as mlab
import matplotlib.colors
from matplotlib.patches import Polygon
from matplotlib.collections import PatchCollection

def f(x1, x2):
    return (x1-1)**2+(x2+.4)**2 + .1

xs = np.linspace(-1, 2, 100)
ys = np.linspace(-1, 1, 100)

Xs, Ys = np.meshgrid(xs, ys)

Zs = f(Xs, Ys)

Hf = 200.  # mm
Bf = 300.  # mm
fig, axs = plt.subplots(2,2, dpi=90, facecolor='w', edgecolor='k', figsize=(Bf / 25.4, Hf / 25.4))

axl = axs[0,0]
axr = axs[0,1]
axc = axs[1,1]
axz = axs[1,0]
axl.set_title("z.l")
axr.set_title("z.r")
for ax in [axl, axr, axc]:
    ax.set_xlabel("x")
    ax.set_ylabel("y")

cmap = "autumn"

csc = axc.contourf(Xs, Ys, Zs, alpha=1, cmap=cmap)
csc2 = axc.contour(Xs, Ys, Zs, colors="k")
axc.clabel(csc2, fontsize=9, inline=1, alpha=1)

norm= matplotlib.colors.Normalize(vmin=csc.vmin, vmax=csc.vmax)
sm = plt.cm.ScalarMappable(norm=norm, cmap =csc.cmap)
sm.set_array([])
cbar = fig.colorbar(sm, ticks=csc.levels)
cbar.set_label("z")
x = ph.Trapezoid(alpha0=[-1,2], alpha1=[-.5, .5])
y = ph.TruncNorm(alpha0=[-1,0.5])

z = f(x,y)
z.name = "z"
print(z.df)

# left
# cs = axl.contourf(Xs, Ys, Zs, alpha=.2, cmap="hot")
norml = matplotlib.colors.Normalize(vmin=z.df.l.min(), vmax=z.df.l.max())
sml = plt.cm.ScalarMappable(norm=norml, cmap=cmap)
sml.set_array([])
csl2 = axl.contour(Xs, Ys, Zs, colors="k")
# cs2k = axl.contour(Xs, Ys, Zs, colors="k")
axl.clabel(csl2, fontsize=9, inline=1, alpha=1)
cbarl = fig.colorbar(sml, ticks=[z.df.l.min(), z.df.l.max()], ax=axl)
cbarl.set_label("z.l")

# right
# cs = axr.contourf(Xs, Ys, Zs, alpha=.2, cmap="hot")
normr = matplotlib.colors.Normalize(vmin=z.df.r.min(), vmax=z.df.r.max())
smr = plt.cm.ScalarMappable(norm=normr, cmap=cmap)
smr.set_array([])
csr2 = axr.contour(Xs, Ys, Zs, colors="k")
# cs2k = axl.contour(Xs, Ys, Zs, colors="k")
axr.clabel(csr2, fontsize=9, inline=1, alpha=1)
cbarr = fig.colorbar(smr, ticks=[z.df.r.min(), z.df.r.max()], ax=axr)
cbarr.set_label("z.r")

for i, zi in z.df.iterrows():
    xi = x.df.loc[i]
    yi = y.df.loc[i]
    polygon = Polygon(np.vstack([[xi.l, xi.r, xi.r, xi.l, xi.l],
                           [yi.l, yi.l, yi.r, yi.r, yi.l]]).T)

    pl = PatchCollection([polygon], alpha=1, color=sml.to_rgba(zi.l))
    axl.add_collection(pl)
    pr = PatchCollection([polygon], alpha=1, color=sm.to_rgba(zi.r))
    axr.add_collection(pr)

    axl.plot([xi.l, xi.r, xi.r, xi.l, xi.l],
            [yi.l, yi.l, yi.r, yi.r, yi.l],
             c="k", alpha=.5, lw=.5, dashes=[2,2])

    axr.plot([xi.l, xi.r, xi.r, xi.l, xi.l],
            [yi.l, yi.l, yi.r, yi.r, yi.l],
             c="k", alpha=.5, lw=.5, dashes=[2,2])

# # csr = axr.contourf(Xs, Ys, Zs, alpha=.2, cmap="hot")
# csr2 = axr.contour(Xs, Ys, Zs, color="k", cmap=cmap)
# axr.clabel(csr2, fontsize=9, inline=1, alpha=1)

axl.scatter([1], [-.4])
axr.scatter([1], [-.4])
axc.scatter([1], [-.4])

mix_mpl(z)
z.plot(ax= axz, show=False)
axz.set_title(z)
axc.set_title("f(x,y)")
fig.tight_layout()
plt.show()
<|endoftext|>


<commit_before><commit_msg>	modified:   cluster_read.py<commit_after><|endoftext|>


<commit_before>#===============================================================================
# Copyright (c) 2015, Max Zwiessele
# 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 GPy.plotting.abstract_plotting_library 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.
#===============================================================================

#===============================================================================
# Make sure that the necessary files and functions are
# defined in the plotting library:
class AbstractPlottingLibrary(object):
    def __init__(self):
        """
        Set the defaults dictionary in the _defaults variable:

        E.g. for matplotlib we define a file defaults.py and
            set the dictionary of it here:

                from . import defaults
                _defaults = defaults.__dict__
        """
        self._defaults = {}
        self.__defaults = None

    @property
    def defaults(self):
        #===============================================================================
        if self.__defaults is None:
            from collections import defaultdict
            class defaultdict(defaultdict):
                def __getattr__(self, *args, **kwargs):
                    return defaultdict.__getitem__(self, *args, **kwargs)
            self.__defaults = defaultdict(dict, self._defaults)
        return self.__defaults
        #===============================================================================

    def figure(self, nrows, ncols, **kwargs):
        """
        Get a new figure with nrows and ncolumns subplots.
        Does not initialize the canvases yet.
        """
        raise NotImplementedError("Implement all plot functions in AbstractPlottingLibrary in order to use your own plotting library")

    def new_canvas(self, figure=None, col=1, row=1, projection='2d', xlabel=None, ylabel=None, zlabel=None, title=None, xlim=None, ylim=None, zlim=None, **kwargs):
        """
        Return a canvas, kwargupdate for your plotting library.

        if figure is not None, create a canvas in the figure
        at subplot position (col, row).

        This method does two things, it creates an empty canvas
        and updates the kwargs (deletes the unnecessary kwargs)
        for further usage in normal plotting.

        the kwargs are plotting library specific kwargs!

        :param {'2d'|'3d'} projection: The projection to use.

        E.g. in matplotlib this means it deletes references to ax, as
        plotting is done on the axis itself and is not a kwarg.

        :param xlabel: the label to put on the xaxis
        :param ylabel: the label to put on the yaxis
        :param zlabel: the label to put on the zaxis (if plotting in 3d)
        :param title: the title of the plot
        :param legend: if True, plot a legend, if int make legend rows in the legend
        :param (float, float) xlim: the limits for the xaxis
        :param (float, float) ylim: the limits for the yaxis
        :param (float, float) zlim: the limits for the zaxis (if plotting in 3d)
        """
        raise NotImplementedError("Implement all plot functions in AbstractPlottingLibrary in order to use your own plotting library")

    def add_to_canvas(self, canvas, plots, legend=True, title=None, **kwargs):
        """
        Add plots is a dictionary with the plots as the
        items or a list of plots as items to canvas.

        The kwargs are plotting library specific kwargs!

        E.g. in matplotlib this does not have to do anything to add stuff, but
        we set the legend and title.

        !This function returns the updated canvas!

        :param title: the title of the plot
        :param legend: whether to plot a legend or not
        """
        raise NotImplementedError("Implement all plot functions in AbstractPlottingLibrary in order to use your own plotting library")

    def show_canvas(self, canvas, **kwargs):
        """
        Draw/Plot the canvas given.
        """
        raise NotImplementedError

    def plot(self, cavas, X, Y, Z=None, color=None, label=None, **kwargs):
        """
        Make a line plot from for Y on X (Y = f(X)) on the canvas.
        If Z is not None, plot in 3d!

        the kwargs are plotting library specific kwargs!
        """
        raise NotImplementedError("Implement all plot functions in AbstractPlottingLibrary in order to use your own plotting library")

    def plot_axis_lines(self, ax, X, color=None, label=None, **kwargs):
        """
        Plot lines at the bottom (lower boundary of yaxis) of the axis at input location X.

        If X is two dimensional, plot in 3d and connect the axis lines to the bottom of the Z axis.

        the kwargs are plotting library specific kwargs!
        """
        raise NotImplementedError("Implement all plot functions in AbstractPlottingLibrary in order to use your own plotting library")

    def surface(self, canvas, X, Y, Z, color=None, label=None, **kwargs):
        """
        Plot a surface for 3d plotting for the inputs (X, Y, Z).

        the kwargs are plotting library specific kwargs!
        """
        raise NotImplementedError("Implement all plot functions in AbstractPlottingLibrary in order to use your own plotting library")

    def scatter(self, canvas, X, Y, Z=None, color=None, vmin=None, vmax=None, label=None, **kwargs):
        """
        Make a scatter plot between X and Y on the canvas given.

        the kwargs are plotting library specific kwargs!

        :param canvas: the plotting librarys specific canvas to plot on.
        :param array-like X: the inputs to plot.
        :param array-like Y: the outputs to plot.
        :param array-like Z: the Z level to plot (if plotting 3d).
        :param array-like c: the colorlevel for each point.
        :param float vmin: minimum colorscale
        :param float vmax: maximum colorscale
        :param kwargs: the specific kwargs for your plotting library
        """
        raise NotImplementedError("Implement all plot functions in AbstractPlottingLibrary in order to use your own plotting library")

    def barplot(self, canvas, x, height, width=0.8, bottom=0, color=None, label=None, **kwargs):
        """
        Plot vertical bar plot centered at x with height
        and width of bars. The y level is at bottom.

        the kwargs are plotting library specific kwargs!

        :param array-like x: the center points of the bars
        :param array-like height: the height of the bars
        :param array-like width: the width of the bars
        :param array-like bottom: the start y level of the bars
        :param kwargs: kwargs for the specific library you are using.
        """
        raise NotImplementedError("Implement all plot functions in AbstractPlottingLibrary in order to use your own plotting library")

    def xerrorbar(self, canvas, X, Y, error, color=None, label=None, **kwargs):
        """
        Make an errorbar along the xaxis for points at (X,Y) on the canvas.
        if error is two dimensional, the lower error is error[:,0] and
        the upper error is error[:,1]

        the kwargs are plotting library specific kwargs!
        """
        raise NotImplementedError("Implement all plot functions in AbstractPlottingLibrary in order to use your own plotting library")

    def yerrorbar(self, canvas, X, Y, error, color=None, label=None, **kwargs):
        """
        Make errorbars along the yaxis on the canvas given.
        if error is two dimensional, the lower error is error[0, :] and
        the upper error is error[1, :]

        the kwargs are plotting library specific kwargs!
        """
        raise NotImplementedError("Implement all plot functions in AbstractPlottingLibrary in order to use your own plotting library")

    def imshow(self, canvas, X, extent=None, label=None, vmin=None, vmax=None, **kwargs):
        """
        Show the image stored in X on the canvas.

        The origin of the image show is (0,0), such that X[0,0] gets plotted at [0,0] of the image!

        the kwargs are plotting library specific kwargs!
        """
        raise NotImplementedError("Implement all plot functions in AbstractPlottingLibrary in order to use your own plotting library")

    def imshow_interact(self, canvas, plot_function, extent=None, label=None, vmin=None, vmax=None, **kwargs):
        """
        This function is optional!

        Create an imshow controller to stream
        the image returned by the plot_function. There is an imshow controller written for
        mmatplotlib, which updates the imshow on changes in axis.

        The origin of the image show is (0,0), such that X[0,0] gets plotted at [0,0] of the image!

        the kwargs are plotting library specific kwargs!
        """
        raise NotImplementedError("Implement all plot functions in AbstractPlottingLibrary in order to use your own plotting library")

    def annotation_heatmap(self, canvas, X, annotation, extent, label=None, **kwargs):
        """
        Plot an annotation heatmap. That is like an imshow, but
        put the text of the annotation inside the cells of the heatmap (centered).

        :param canvas: the canvas to plot on
        :param array-like annotation: the annotation labels for the heatmap
        :param [horizontal_min,horizontal_max,vertical_min,vertical_max] extent: the extent of where to place the heatmap
        :param str label: the label for the heatmap
        :return: a list of both the heatmap and annotation plots [heatmap, annotation], or the interactive update object (alone)
        """
        raise NotImplementedError("Implement all plot functions in AbstractPlottingLibrary in order to use your own plotting library")

    def annotation_heatmap_interact(self, canvas, plot_function, extent, label=None, resolution=15, **kwargs):
        """
        if plot_function is not None, return an interactive updated
        heatmap, which updates on axis events, so that one can zoom in
        and out and the heatmap gets updated. See the matplotlib implementation
        in matplot_dep.controllers.

        the plot_function returns a pair (X, annotation) to plot, when called with
        a new input X (which would be the grid, which is visible on the plot
        right now)

        :param canvas: the canvas to plot on
        :param array-like annotation: the annotation labels for the heatmap
        :param [horizontal_min,horizontal_max,vertical_min,vertical_max] extent: the extent of where to place the heatmap
        :param str label: the label for the heatmap
        :return: a list of both the heatmap and annotation plots [heatmap, annotation], or the interactive update object (alone)
        :param plot_function: the function, which generates new data for given input locations X
        :param int resolution: the resolution of the interactive plot redraw - this is only needed when giving a plot_function
        """
        raise NotImplementedError("Implement all plot functions in AbstractPlottingLibrary in order to use your own plotting library")

    def contour(self, canvas, X, Y, C, Z=None, color=None, label=None, **kwargs):
        """
        Make a contour plot at (X, Y) with heights/colors stored in C on the canvas.

        if Z is not None: make 3d contour plot at (X, Y, Z) with heights/colors stored in C on the canvas.

        the kwargs are plotting library specific kwargs!
        """
        raise NotImplementedError("Implement all plot functions in AbstractPlottingLibrary in order to use your own plotting library")

    def fill_between(self, canvas, X, lower, upper, color=None, label=None, **kwargs):
        """
        Fill along the xaxis between lower and upper.

        the kwargs are plotting library specific kwargs!
        """
        raise NotImplementedError("Implement all plot functions in AbstractPlottingLibrary in order to use your own plotting library")

    def fill_gradient(self, canvas, X, percentiles, color=None, label=None, **kwargs):
        """
        Plot a gradient (in alpha values) for the given percentiles.

        the kwargs are plotting library specific kwargs!
        """
        print("fill_gradient not implemented in this backend.")
<commit_msg>[plotting] small edit<commit_after>#===============================================================================
# Copyright (c) 2015, Max Zwiessele
# 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 GPy.plotting.abstract_plotting_library 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.
#===============================================================================

#===============================================================================
# Make sure that the necessary files and functions are
# defined in the plotting library:
class AbstractPlottingLibrary(object):
    def __init__(self):
        """
        Set the defaults dictionary in the _defaults variable:

        E.g. for matplotlib we define a file defaults.py and
            set the dictionary of it here:

                from . import defaults
                _defaults = defaults.__dict__
        """
        self._defaults = {}
        self.__defaults = None

    @property
    def defaults(self):
        #===============================================================================
        if self.__defaults is None:
            from collections import defaultdict
            class defaultdict(defaultdict):
                def __getattr__(self, *args, **kwargs):
                    return defaultdict.__getitem__(self, *args, **kwargs)
            self.__defaults = defaultdict(dict, self._defaults)
        return self.__defaults
        #===============================================================================

    def figure(self, nrows, ncols, **kwargs):
        """
        Get a new figure with nrows and ncolumns subplots.
        Does not initialize the canvases yet.

        There is individual kwargs for the individual plotting libraries to use.
        """
        raise NotImplementedError("Implement all plot functions in AbstractPlottingLibrary in order to use your own plotting library")

    def new_canvas(self, figure=None, col=1, row=1, projection='2d', xlabel=None, ylabel=None, zlabel=None, title=None, xlim=None, ylim=None, zlim=None, **kwargs):
        """
        Return a canvas, kwargupdate for your plotting library.

        if figure is not None, create a canvas in the figure
        at subplot position (col, row).

        This method does two things, it creates an empty canvas
        and updates the kwargs (deletes the unnecessary kwargs)
        for further usage in normal plotting.

        the kwargs are plotting library specific kwargs!

        :param {'2d'|'3d'} projection: The projection to use.

        E.g. in matplotlib this means it deletes references to ax, as
        plotting is done on the axis itself and is not a kwarg.

        :param xlabel: the label to put on the xaxis
        :param ylabel: the label to put on the yaxis
        :param zlabel: the label to put on the zaxis (if plotting in 3d)
        :param title: the title of the plot
        :param legend: if True, plot a legend, if int make legend rows in the legend
        :param (float, float) xlim: the limits for the xaxis
        :param (float, float) ylim: the limits for the yaxis
        :param (float, float) zlim: the limits for the zaxis (if plotting in 3d)
        """
        raise NotImplementedError("Implement all plot functions in AbstractPlottingLibrary in order to use your own plotting library")

    def add_to_canvas(self, canvas, plots, legend=True, title=None, **kwargs):
        """
        Add plots is a dictionary with the plots as the
        items or a list of plots as items to canvas.

        The kwargs are plotting library specific kwargs!

        E.g. in matplotlib this does not have to do anything to add stuff, but
        we set the legend and title.

        !This function returns the updated canvas!

        :param title: the title of the plot
        :param legend: whether to plot a legend or not
        """
        raise NotImplementedError("Implement all plot functions in AbstractPlottingLibrary in order to use your own plotting library")

    def show_canvas(self, canvas, **kwargs):
        """
        Draw/Plot the canvas given.
        """
        raise NotImplementedError

    def plot(self, cavas, X, Y, Z=None, color=None, label=None, **kwargs):
        """
        Make a line plot from for Y on X (Y = f(X)) on the canvas.
        If Z is not None, plot in 3d!

        the kwargs are plotting library specific kwargs!
        """
        raise NotImplementedError("Implement all plot functions in AbstractPlottingLibrary in order to use your own plotting library")

    def plot_axis_lines(self, ax, X, color=None, label=None, **kwargs):
        """
        Plot lines at the bottom (lower boundary of yaxis) of the axis at input location X.

        If X is two dimensional, plot in 3d and connect the axis lines to the bottom of the Z axis.

        the kwargs are plotting library specific kwargs!
        """
        raise NotImplementedError("Implement all plot functions in AbstractPlottingLibrary in order to use your own plotting library")

    def surface(self, canvas, X, Y, Z, color=None, label=None, **kwargs):
        """
        Plot a surface for 3d plotting for the inputs (X, Y, Z).

        the kwargs are plotting library specific kwargs!
        """
        raise NotImplementedError("Implement all plot functions in AbstractPlottingLibrary in order to use your own plotting library")

    def scatter(self, canvas, X, Y, Z=None, color=None, vmin=None, vmax=None, label=None, **kwargs):
        """
        Make a scatter plot between X and Y on the canvas given.

        the kwargs are plotting library specific kwargs!

        :param canvas: the plotting librarys specific canvas to plot on.
        :param array-like X: the inputs to plot.
        :param array-like Y: the outputs to plot.
        :param array-like Z: the Z level to plot (if plotting 3d).
        :param array-like c: the colorlevel for each point.
        :param float vmin: minimum colorscale
        :param float vmax: maximum colorscale
        :param kwargs: the specific kwargs for your plotting library
        """
        raise NotImplementedError("Implement all plot functions in AbstractPlottingLibrary in order to use your own plotting library")

    def barplot(self, canvas, x, height, width=0.8, bottom=0, color=None, label=None, **kwargs):
        """
        Plot vertical bar plot centered at x with height
        and width of bars. The y level is at bottom.

        the kwargs are plotting library specific kwargs!

        :param array-like x: the center points of the bars
        :param array-like height: the height of the bars
        :param array-like width: the width of the bars
        :param array-like bottom: the start y level of the bars
        :param kwargs: kwargs for the specific library you are using.
        """
        raise NotImplementedError("Implement all plot functions in AbstractPlottingLibrary in order to use your own plotting library")

    def xerrorbar(self, canvas, X, Y, error, color=None, label=None, **kwargs):
        """
        Make an errorbar along the xaxis for points at (X,Y) on the canvas.
        if error is two dimensional, the lower error is error[:,0] and
        the upper error is error[:,1]

        the kwargs are plotting library specific kwargs!
        """
        raise NotImplementedError("Implement all plot functions in AbstractPlottingLibrary in order to use your own plotting library")

    def yerrorbar(self, canvas, X, Y, error, color=None, label=None, **kwargs):
        """
        Make errorbars along the yaxis on the canvas given.
        if error is two dimensional, the lower error is error[0, :] and
        the upper error is error[1, :]

        the kwargs are plotting library specific kwargs!
        """
        raise NotImplementedError("Implement all plot functions in AbstractPlottingLibrary in order to use your own plotting library")

    def imshow(self, canvas, X, extent=None, label=None, vmin=None, vmax=None, **kwargs):
        """
        Show the image stored in X on the canvas.

        The origin of the image show is (0,0), such that X[0,0] gets plotted at [0,0] of the image!

        the kwargs are plotting library specific kwargs!
        """
        raise NotImplementedError("Implement all plot functions in AbstractPlottingLibrary in order to use your own plotting library")

    def imshow_interact(self, canvas, plot_function, extent=None, label=None, vmin=None, vmax=None, **kwargs):
        """
        This function is optional!

        Create an imshow controller to stream
        the image returned by the plot_function. There is an imshow controller written for
        mmatplotlib, which updates the imshow on changes in axis.

        The origin of the image show is (0,0), such that X[0,0] gets plotted at [0,0] of the image!

        the kwargs are plotting library specific kwargs!
        """
        raise NotImplementedError("Implement all plot functions in AbstractPlottingLibrary in order to use your own plotting library")

    def annotation_heatmap(self, canvas, X, annotation, extent, label=None, **kwargs):
        """
        Plot an annotation heatmap. That is like an imshow, but
        put the text of the annotation inside the cells of the heatmap (centered).

        :param canvas: the canvas to plot on
        :param array-like annotation: the annotation labels for the heatmap
        :param [horizontal_min,horizontal_max,vertical_min,vertical_max] extent: the extent of where to place the heatmap
        :param str label: the label for the heatmap
        :return: a list of both the heatmap and annotation plots [heatmap, annotation], or the interactive update object (alone)
        """
        raise NotImplementedError("Implement all plot functions in AbstractPlottingLibrary in order to use your own plotting library")

    def annotation_heatmap_interact(self, canvas, plot_function, extent, label=None, resolution=15, **kwargs):
        """
        if plot_function is not None, return an interactive updated
        heatmap, which updates on axis events, so that one can zoom in
        and out and the heatmap gets updated. See the matplotlib implementation
        in matplot_dep.controllers.

        the plot_function returns a pair (X, annotation) to plot, when called with
        a new input X (which would be the grid, which is visible on the plot
        right now)

        :param canvas: the canvas to plot on
        :param array-like annotation: the annotation labels for the heatmap
        :param [horizontal_min,horizontal_max,vertical_min,vertical_max] extent: the extent of where to place the heatmap
        :param str label: the label for the heatmap
        :return: a list of both the heatmap and annotation plots [heatmap, annotation], or the interactive update object (alone)
        :param plot_function: the function, which generates new data for given input locations X
        :param int resolution: the resolution of the interactive plot redraw - this is only needed when giving a plot_function
        """
        raise NotImplementedError("Implement all plot functions in AbstractPlottingLibrary in order to use your own plotting library")

    def contour(self, canvas, X, Y, C, Z=None, color=None, label=None, **kwargs):
        """
        Make a contour plot at (X, Y) with heights/colors stored in C on the canvas.

        if Z is not None: make 3d contour plot at (X, Y, Z) with heights/colors stored in C on the canvas.

        the kwargs are plotting library specific kwargs!
        """
        raise NotImplementedError("Implement all plot functions in AbstractPlottingLibrary in order to use your own plotting library")

    def fill_between(self, canvas, X, lower, upper, color=None, label=None, **kwargs):
        """
        Fill along the xaxis between lower and upper.

        the kwargs are plotting library specific kwargs!
        """
        raise NotImplementedError("Implement all plot functions in AbstractPlottingLibrary in order to use your own plotting library")

    def fill_gradient(self, canvas, X, percentiles, color=None, label=None, **kwargs):
        """
        Plot a gradient (in alpha values) for the given percentiles.

        the kwargs are plotting library specific kwargs!
        """
        print("fill_gradient not implemented in this backend.")
<|endoftext|>


<commit_before>from Config import *

# Not sure what this number does, but we need some threshold that we'd like to
# avoid crossing.
setOption("BadnessThreshold", 42)

# Ignore documentation issues.
addFilter('no-manual-page-for-binary')
addFilter('no-documentation')

# Ignore spelling errors unilt there's a support for custom dictionaries.
# TODO: add such support.
addFilter('spelling-error')

# Ignore unversioned bundled provides.
addFilter('unversioned-explicit-provides bundled\([a-z\-]+\)')

# Don't care about groups.
addFilter('non-standard-group')

# Ignore all lint warnings in submodules:
addFilter('third_party/submodules/')
# Ignore all lint warnings in symlinks from submodules.
addFilter('SPECS/cmake.spec')
addFilter('SPECS/gdb.spec')
addFilter('SPECS/gperftools.spec')
addFilter('libev-devel.x86_64')
addFilter('SPECS/libcomps.spec')
addFilter('nginx\.(spec|x86_64|src)')
addFilter('SPECS/perl.spec')
addFilter('perl.src')
addFilter('perl-common-sense.x86_64')
addFilter('perl-Compress-Raw-Bzip2.x86_64')
addFilter('perl-Data-OptList.src')
addFilter('perl-Data-Section.src')
addFilter('perl-GD.x86_64')
addFilter('perl-HTML-Parser.x86_64')
addFilter('perl-libintl\.(x86_64|src|spec)')
addFilter('perl-Mojolicious.src')
addFilter('perl-Params-Util.x86_64')
addFilter('perl-Pod-Coverage.spec')
addFilter('perl-Software-License\.(src|spec)')
addFilter('perl-Sub-Exporter\.(src|spec)')
addFilter('perl-Sub-Install.src')
addFilter('perl-Pod-Coverage.src')
addFilter('perl-libintl\.(x86_64|src)')
addFilter('perl-Test-Pod\.(src|spec)')
addFilter('perl-TermReadKey\.(x86_64|src)')
addFilter('perl-Test-Pod\.(src|spec)')
addFilter('perl-Text-Template.noarch')
addFilter('python(2|3)?-acme\.(src|noarch)')
addFilter('pyOpenSSL-doc.noarch')
addFilter('python-pyrfc3339.src')
addFilter('SPECS/puppet.spec')
addFilter('SPECS/python-iniparse.spec')
addFilter('python-pyrfc3339.src')
addFilter('SPECS/os-prober.spec')
addFilter('SPECS/puppet.spec')
addFilter('yum\.(spec|src)')

# Python is mostly third-party and has lots of warnings.
# TODO: clean those up.
addFilter('SPECS/python.spec')
addFilter('SPECS/python3.spec')
addFilter('third_party/subtrees/python/python.spec')
addFilter('third_party/subtrees/python3/python3.spec')
addFilter('python-debuginfo.x86_64')
addFilter('python-libs.x86_64')
addFilter('python-devel.x86_64')
addFilter('python-macros.noarch')
addFilter('python.x86_64')
addFilter('python3.src:[0-9]+: W: hardcoded-library-path')

# RPM is special, let's ignore warnings from it.
addFilter('SPECS/rpm.spec')
addFilter('third_party/subtrees/rpm/rpm.spec')

# DNF have a lot of weird stuff:
addFilter('dnf.spec.*libdir-macro-in-noarch-package')

# VIM: allow mixed space/tab usage in specific line.
addFilter('vim.spec:218: W: mixed-use-of-spaces-and-tabs')
# Ignore unversioned provide /bin/vi, versioning it triggers another lint
# warning.
addFilter('vim.spec:[0-9]+: W: unversioned-explicit-provides /bin/vi')

## Perl
# Perl packages are weird and often don't have -devel part.
addFilter('perl-Tk.x86_64: W: devel-file-in-non-devel-package')
# Some of them also depend on perl-devel
addFilter('perl-ExtUtils-Miniperl.noarch: W: devel-dependency')
# Perl-Tk has weird deps
addFilter('perl-Tk.spec:63: W: comparison-operator-in-deptoken')

## Let's encrypt:
# Allow pems in test files.
addFilter('python2-letsencrypt.noarch: W: pem-certificate /usr/lib/python2.7/site-packages/letsencrypt/tests/testdata/.*')
# Allow some nonstandard permissions
addFilter('letsencrypt.noarch: W: non-standard-dir-perm /var/log/letsencrypt 0')
addFilter('letsencrypt.noarch: W: non-standard-dir-perm /var/lib/letsencrypt 0')
addFilter('letsencrypt.noarch: W: non-standard-dir-perm /etc/letsencrypt 0')
# TODO: fix following
addFilter('letsencrypt.noarch: W: log-files-without-logrotate')

## Libcomps
# URL broken :(
addFilter('libcomps.spec: W: invalid-url Source0: https://github.com/midnightercz/libcomps/libcomps-0.1.7.tar.gz')

## GDB
# Following should be ok for debugger.
addFilter('gdb.spec:[0-9]+: W: unversioned-explicit-obsoletes devtoolset')
addFilter('gdb.x86_64: W: unstripped-binary-or-object /usr/bin/gdb')
addFilter('gdb-gdbserver.x86_64: W: unstripped-binary-or-object /usr/lib64/libinproctrace.so')
addFilter('gdb-gdbserver.x86_64: W: unstripped-binary-or-object /usr/bin/gdbserver')
addFilter('gdb-gdbserver.x86_64: W: shared-lib-calls-exit /usr/lib64/libinproctrace.so exit@GLIBC_2.2.5')
addFilter('gdb.x86_64: W: only-non-binary-in-usr-lib')
addFilter('gdb-gdbserver.x86_64: W: no-soname /usr/lib64/libinproctrace.so')
addFilter('gdb.spec:[0-9]+: W: hardcoded-library-path')
addFilter('gdb.x86_64: W: dangerous-command-in-%pre mv')
addFilter('gdb.x86_64: W: devel-file-in-non-devel-package /usr/include/gdb/jit-reader.h')
addFilter('gdb.src:[0-9]+: W: hardcoded-library-path')
# Snapshots dissapear quickly
addFilter('gdb.src: W: invalid-url Source0: ftp://sourceware.org/pub/gdb/snapshots/current/.*')

## Python-pip
addFilter('python(3|2)?-pip.noarch: W: non-executable-script /usr/lib/python.\../site-packages/pip/_vendor/requests/packages/chardet/chardetect.py')
<commit_msg>perl: Ignore ifarch-applied-patch lint warning for Patch3.<commit_after>from Config import *

# Not sure what this number does, but we need some threshold that we'd like to
# avoid crossing.
setOption("BadnessThreshold", 42)

# Ignore documentation issues.
addFilter('no-manual-page-for-binary')
addFilter('no-documentation')

# Ignore spelling errors unilt there's a support for custom dictionaries.
# TODO: add such support.
addFilter('spelling-error')

# Ignore unversioned bundled provides.
addFilter('unversioned-explicit-provides bundled\([a-z\-]+\)')

# Don't care about groups.
addFilter('non-standard-group')

# Ignore all lint warnings in submodules:
addFilter('third_party/submodules/')
# Ignore all lint warnings in symlinks from submodules.
addFilter('SPECS/cmake.spec')
addFilter('SPECS/gdb.spec')
addFilter('SPECS/gperftools.spec')
addFilter('libev-devel.x86_64')
addFilter('SPECS/libcomps.spec')
addFilter('nginx\.(spec|x86_64|src)')
addFilter('perl-common-sense.x86_64')
addFilter('perl-Compress-Raw-Bzip2.x86_64')
addFilter('perl-Data-OptList.src')
addFilter('perl-Data-Section.src')
addFilter('perl-GD.x86_64')
addFilter('perl-HTML-Parser.x86_64')
addFilter('perl-libintl\.(x86_64|src|spec)')
addFilter('perl-Mojolicious.src')
addFilter('perl-Params-Util.x86_64')
addFilter('perl-Pod-Coverage.spec')
addFilter('perl-Software-License\.(src|spec)')
addFilter('perl-Sub-Exporter\.(src|spec)')
addFilter('perl-Sub-Install.src')
addFilter('perl-Pod-Coverage.src')
addFilter('perl-libintl\.(x86_64|src)')
addFilter('perl-Test-Pod\.(src|spec)')
addFilter('perl-TermReadKey\.(x86_64|src)')
addFilter('perl-Test-Pod\.(src|spec)')
addFilter('perl-Text-Template.noarch')
addFilter('python(2|3)?-acme\.(src|noarch)')
addFilter('pyOpenSSL-doc.noarch')
addFilter('python-pyrfc3339.src')
addFilter('SPECS/puppet.spec')
addFilter('SPECS/python-iniparse.spec')
addFilter('python-pyrfc3339.src')
addFilter('SPECS/os-prober.spec')
addFilter('SPECS/puppet.spec')
addFilter('yum\.(spec|src)')

# Python is mostly third-party and has lots of warnings.
# TODO: clean those up.
addFilter('SPECS/python.spec')
addFilter('SPECS/python3.spec')
addFilter('third_party/subtrees/python/python.spec')
addFilter('third_party/subtrees/python3/python3.spec')
addFilter('python-debuginfo.x86_64')
addFilter('python-libs.x86_64')
addFilter('python-devel.x86_64')
addFilter('python-macros.noarch')
addFilter('python.x86_64')
addFilter('python3.src:[0-9]+: W: hardcoded-library-path')

# RPM is special, let's ignore warnings from it.
addFilter('SPECS/rpm.spec')
addFilter('third_party/subtrees/rpm/rpm.spec')

# DNF have a lot of weird stuff:
addFilter('dnf.spec.*libdir-macro-in-noarch-package')

# VIM: allow mixed space/tab usage in specific line.
addFilter('vim.spec:218: W: mixed-use-of-spaces-and-tabs')
# Ignore unversioned provide /bin/vi, versioning it triggers another lint
# warning.
addFilter('vim.spec:[0-9]+: W: unversioned-explicit-provides /bin/vi')

## Perl
# Perl packages are weird and often don't have -devel part.
addFilter('perl-Tk.x86_64: W: devel-file-in-non-devel-package')
# Some of them also depend on perl-devel
addFilter('perl-ExtUtils-Miniperl.noarch: W: devel-dependency')
# Perl-Tk has weird deps
addFilter('perl-Tk.spec:63: W: comparison-operator-in-deptoken')

## Let's encrypt:
# Allow pems in test files.
addFilter('python2-letsencrypt.noarch: W: pem-certificate /usr/lib/python2.7/site-packages/letsencrypt/tests/testdata/.*')
# Allow some nonstandard permissions
addFilter('letsencrypt.noarch: W: non-standard-dir-perm /var/log/letsencrypt 0')
addFilter('letsencrypt.noarch: W: non-standard-dir-perm /var/lib/letsencrypt 0')
addFilter('letsencrypt.noarch: W: non-standard-dir-perm /etc/letsencrypt 0')
# TODO: fix following
addFilter('letsencrypt.noarch: W: log-files-without-logrotate')

## Libcomps
# URL broken :(
addFilter('libcomps.spec: W: invalid-url Source0: https://github.com/midnightercz/libcomps/libcomps-0.1.7.tar.gz')

## GDB
# Following should be ok for debugger.
addFilter('gdb.spec:[0-9]+: W: unversioned-explicit-obsoletes devtoolset')
addFilter('gdb.x86_64: W: unstripped-binary-or-object /usr/bin/gdb')
addFilter('gdb-gdbserver.x86_64: W: unstripped-binary-or-object /usr/lib64/libinproctrace.so')
addFilter('gdb-gdbserver.x86_64: W: unstripped-binary-or-object /usr/bin/gdbserver')
addFilter('gdb-gdbserver.x86_64: W: shared-lib-calls-exit /usr/lib64/libinproctrace.so exit@GLIBC_2.2.5')
addFilter('gdb.x86_64: W: only-non-binary-in-usr-lib')
addFilter('gdb-gdbserver.x86_64: W: no-soname /usr/lib64/libinproctrace.so')
addFilter('gdb.spec:[0-9]+: W: hardcoded-library-path')
addFilter('gdb.x86_64: W: dangerous-command-in-%pre mv')
addFilter('gdb.x86_64: W: devel-file-in-non-devel-package /usr/include/gdb/jit-reader.h')
addFilter('gdb.src:[0-9]+: W: hardcoded-library-path')
# Snapshots dissapear quickly
addFilter('gdb.src: W: invalid-url Source0: ftp://sourceware.org/pub/gdb/snapshots/current/.*')

## Python-pip
addFilter('python(3|2)?-pip.noarch: W: non-executable-script /usr/lib/python.\../site-packages/pip/_vendor/requests/packages/chardet/chardetect.py')

## Perl
addFilter('perl.spec: W: %ifarch-applied-patch Patch3: perl-5.8.0-libdir64.patch')
<|endoftext|>


<commit_before>from Config import *

# Not sure what this number does, but we need some threshold that we'd like to
# avoid crossing.
setOption("BadnessThreshold", 42)

# Ignore documentation issues.
addFilter('no-manual-page-for-binary')
addFilter('no-documentation')

# Ignore spelling errors unilt there's a support for custom dictionaries.
# TODO: add such support.
addFilter('spelling-error')

# Ignore unversioned bundled provides.
addFilter('unversioned-explicit-provides bundled\([a-z\-]+\)')

# Don't care about groups.
addFilter('non-standard-group')

# Ignore all lint warnings in submodules:
addFilter('third_party/submodules/')
# Ignore all lint warnings in symlinks from submodules.
addFilter('SPECS/cmake.spec')
addFilter('SPECS/gdb.spec')
addFilter('SPECS/gperftools.spec')
addFilter('libev-devel.x86_64')
addFilter('SPECS/libcomps.spec')
addFilter('nginx\.(spec|x86_64|src)')
addFilter('SPECS/perl.spec')
addFilter('perl.src')
addFilter('perl-Compress-Raw-Bzip2.x86_64')
addFilter('perl-Data-OptList.src')
addFilter('perl-Data-Section.src')
addFilter('perl-GD.x86_64')
addFilter('perl-HTML-Parser.x86_64')
addFilter('perl-libintl\.(x86_64|src|spec)')
addFilter('perl-Mojolicious.src')
addFilter('perl-Params-Util.x86_64')
addFilter('perl-Pod-Coverage.spec')
addFilter('perl-Software-License\.(src|spec)')
addFilter('perl-Sub-Exporter\.(src|spec)')
addFilter('perl-Sub-Install.src')
addFilter('perl-Pod-Coverage.src')
addFilter('perl-libintl\.(x86_64|src)')
addFilter('perl-Test-Pod\.(src|spec)')
addFilter('perl-TermReadKey\.(x86_64|src)')
addFilter('perl-Test-Pod\.(src|spec)')
addFilter('perl-Text-Template.noarch')
addFilter('python(2|3)?-acme\.(src|noarch)')
addFilter('pyOpenSSL-doc.noarch')
addFilter('python-pyrfc3339.src')
addFilter('SPECS/puppet.spec')
addFilter('SPECS/python-iniparse.spec')
addFilter('python-pyrfc3339.src')
addFilter('SPECS/os-prober.spec')
addFilter('SPECS/puppet.spec')
addFilter('yum\.(spec|src)')

# Python is mostly third-party and has lots of warnings.
# TODO: clean those up.
addFilter('SPECS/python.spec')
addFilter('SPECS/python3.spec')
addFilter('third_party/subtrees/python/python.spec')
addFilter('third_party/subtrees/python3/python3.spec')
addFilter('python-debuginfo.x86_64')
addFilter('python-libs.x86_64')
addFilter('python-devel.x86_64')
addFilter('python-macros.noarch')
addFilter('python.x86_64')
addFilter('python3.src:[0-9]+: W: hardcoded-library-path')

# RPM is special, let's ignore warnings from it.
addFilter('SPECS/rpm.spec')
addFilter('third_party/subtrees/rpm/rpm.spec')

# DNF have a lot of weird stuff:
addFilter('dnf.spec.*libdir-macro-in-noarch-package')

# VIM: allow mixed space/tab usage in specific line.
addFilter('vim.spec:218: W: mixed-use-of-spaces-and-tabs')
# Ignore unversioned provide /bin/vi, versioning it triggers another lint
# warning.
addFilter('vim.spec:[0-9]+: W: unversioned-explicit-provides /bin/vi')

## Perl
# Perl packages are weird and often don't have -devel part.
addFilter('perl-Tk.x86_64: W: devel-file-in-non-devel-package')
# Some of them also depend on perl-devel
addFilter('perl-ExtUtils-Miniperl.noarch: W: devel-dependency')
# Perl-Tk has weird deps
addFilter('perl-Tk.spec:63: W: comparison-operator-in-deptoken')

## Let's encrypt:
# Allow pems in test files.
addFilter('python2-letsencrypt.noarch: W: pem-certificate /usr/lib/python2.7/site-packages/letsencrypt/tests/testdata/.*')
# Allow some nonstandard permissions
addFilter('letsencrypt.noarch: W: non-standard-dir-perm /var/log/letsencrypt 0')
addFilter('letsencrypt.noarch: W: non-standard-dir-perm /var/lib/letsencrypt 0')
addFilter('letsencrypt.noarch: W: non-standard-dir-perm /etc/letsencrypt 0')
# TODO: fix following
addFilter('letsencrypt.noarch: W: log-files-without-logrotate')

## Libcomps
# URL broken :(
addFilter('libcomps.spec: W: invalid-url Source0: https://github.com/midnightercz/libcomps/libcomps-0.1.7.tar.gz')

## GDB
# Following should be ok for debugger.
addFilter('gdb.spec:[0-9]+: W: unversioned-explicit-obsoletes devtoolset')
addFilter('gdb.x86_64: W: unstripped-binary-or-object /usr/bin/gdb')
addFilter('gdb-gdbserver.x86_64: W: unstripped-binary-or-object /usr/lib64/libinproctrace.so')
addFilter('gdb-gdbserver.x86_64: W: unstripped-binary-or-object /usr/bin/gdbserver')
addFilter('gdb-gdbserver.x86_64: W: shared-lib-calls-exit /usr/lib64/libinproctrace.so exit@GLIBC_2.2.5')
addFilter('gdb.x86_64: W: only-non-binary-in-usr-lib')
addFilter('gdb-gdbserver.x86_64: W: no-soname /usr/lib64/libinproctrace.so')
addFilter('gdb.spec:[0-9]+: W: hardcoded-library-path')
addFilter('gdb.x86_64: W: dangerous-command-in-%pre mv')
addFilter('gdb.x86_64: W: devel-file-in-non-devel-package /usr/include/gdb/jit-reader.h')
addFilter('gdb.src:[0-9]+: W: hardcoded-library-path')
# Snapshots dissapear quickly
addFilter('gdb.src: W: invalid-url Source0: ftp://sourceware.org/pub/gdb/snapshots/current/.*')

## Python-pip
addFilter('python(3|2)?-pip.noarch: W: non-executable-script /usr/lib/python.\../site-packages/pip/_vendor/requests/packages/chardet/chardetect.py')
<commit_msg>perl-common-sense: Ignore lint errors in the rpm file.<commit_after>from Config import *

# Not sure what this number does, but we need some threshold that we'd like to
# avoid crossing.
setOption("BadnessThreshold", 42)

# Ignore documentation issues.
addFilter('no-manual-page-for-binary')
addFilter('no-documentation')

# Ignore spelling errors unilt there's a support for custom dictionaries.
# TODO: add such support.
addFilter('spelling-error')

# Ignore unversioned bundled provides.
addFilter('unversioned-explicit-provides bundled\([a-z\-]+\)')

# Don't care about groups.
addFilter('non-standard-group')

# Ignore all lint warnings in submodules:
addFilter('third_party/submodules/')
# Ignore all lint warnings in symlinks from submodules.
addFilter('SPECS/cmake.spec')
addFilter('SPECS/gdb.spec')
addFilter('SPECS/gperftools.spec')
addFilter('libev-devel.x86_64')
addFilter('SPECS/libcomps.spec')
addFilter('nginx\.(spec|x86_64|src)')
addFilter('SPECS/perl.spec')
addFilter('perl.src')
addFilter('perl-common-sense.x86_64')
addFilter('perl-Compress-Raw-Bzip2.x86_64')
addFilter('perl-Data-OptList.src')
addFilter('perl-Data-Section.src')
addFilter('perl-GD.x86_64')
addFilter('perl-HTML-Parser.x86_64')
addFilter('perl-libintl\.(x86_64|src|spec)')
addFilter('perl-Mojolicious.src')
addFilter('perl-Params-Util.x86_64')
addFilter('perl-Pod-Coverage.spec')
addFilter('perl-Software-License\.(src|spec)')
addFilter('perl-Sub-Exporter\.(src|spec)')
addFilter('perl-Sub-Install.src')
addFilter('perl-Pod-Coverage.src')
addFilter('perl-libintl\.(x86_64|src)')
addFilter('perl-Test-Pod\.(src|spec)')
addFilter('perl-TermReadKey\.(x86_64|src)')
addFilter('perl-Test-Pod\.(src|spec)')
addFilter('perl-Text-Template.noarch')
addFilter('python(2|3)?-acme\.(src|noarch)')
addFilter('pyOpenSSL-doc.noarch')
addFilter('python-pyrfc3339.src')
addFilter('SPECS/puppet.spec')
addFilter('SPECS/python-iniparse.spec')
addFilter('python-pyrfc3339.src')
addFilter('SPECS/os-prober.spec')
addFilter('SPECS/puppet.spec')
addFilter('yum\.(spec|src)')

# Python is mostly third-party and has lots of warnings.
# TODO: clean those up.
addFilter('SPECS/python.spec')
addFilter('SPECS/python3.spec')
addFilter('third_party/subtrees/python/python.spec')
addFilter('third_party/subtrees/python3/python3.spec')
addFilter('python-debuginfo.x86_64')
addFilter('python-libs.x86_64')
addFilter('python-devel.x86_64')
addFilter('python-macros.noarch')
addFilter('python.x86_64')
addFilter('python3.src:[0-9]+: W: hardcoded-library-path')

# RPM is special, let's ignore warnings from it.
addFilter('SPECS/rpm.spec')
addFilter('third_party/subtrees/rpm/rpm.spec')

# DNF have a lot of weird stuff:
addFilter('dnf.spec.*libdir-macro-in-noarch-package')

# VIM: allow mixed space/tab usage in specific line.
addFilter('vim.spec:218: W: mixed-use-of-spaces-and-tabs')
# Ignore unversioned provide /bin/vi, versioning it triggers another lint
# warning.
addFilter('vim.spec:[0-9]+: W: unversioned-explicit-provides /bin/vi')

## Perl
# Perl packages are weird and often don't have -devel part.
addFilter('perl-Tk.x86_64: W: devel-file-in-non-devel-package')
# Some of them also depend on perl-devel
addFilter('perl-ExtUtils-Miniperl.noarch: W: devel-dependency')
# Perl-Tk has weird deps
addFilter('perl-Tk.spec:63: W: comparison-operator-in-deptoken')

## Let's encrypt:
# Allow pems in test files.
addFilter('python2-letsencrypt.noarch: W: pem-certificate /usr/lib/python2.7/site-packages/letsencrypt/tests/testdata/.*')
# Allow some nonstandard permissions
addFilter('letsencrypt.noarch: W: non-standard-dir-perm /var/log/letsencrypt 0')
addFilter('letsencrypt.noarch: W: non-standard-dir-perm /var/lib/letsencrypt 0')
addFilter('letsencrypt.noarch: W: non-standard-dir-perm /etc/letsencrypt 0')
# TODO: fix following
addFilter('letsencrypt.noarch: W: log-files-without-logrotate')

## Libcomps
# URL broken :(
addFilter('libcomps.spec: W: invalid-url Source0: https://github.com/midnightercz/libcomps/libcomps-0.1.7.tar.gz')

## GDB
# Following should be ok for debugger.
addFilter('gdb.spec:[0-9]+: W: unversioned-explicit-obsoletes devtoolset')
addFilter('gdb.x86_64: W: unstripped-binary-or-object /usr/bin/gdb')
addFilter('gdb-gdbserver.x86_64: W: unstripped-binary-or-object /usr/lib64/libinproctrace.so')
addFilter('gdb-gdbserver.x86_64: W: unstripped-binary-or-object /usr/bin/gdbserver')
addFilter('gdb-gdbserver.x86_64: W: shared-lib-calls-exit /usr/lib64/libinproctrace.so exit@GLIBC_2.2.5')
addFilter('gdb.x86_64: W: only-non-binary-in-usr-lib')
addFilter('gdb-gdbserver.x86_64: W: no-soname /usr/lib64/libinproctrace.so')
addFilter('gdb.spec:[0-9]+: W: hardcoded-library-path')
addFilter('gdb.x86_64: W: dangerous-command-in-%pre mv')
addFilter('gdb.x86_64: W: devel-file-in-non-devel-package /usr/include/gdb/jit-reader.h')
addFilter('gdb.src:[0-9]+: W: hardcoded-library-path')
# Snapshots dissapear quickly
addFilter('gdb.src: W: invalid-url Source0: ftp://sourceware.org/pub/gdb/snapshots/current/.*')

## Python-pip
addFilter('python(3|2)?-pip.noarch: W: non-executable-script /usr/lib/python.\../site-packages/pip/_vendor/requests/packages/chardet/chardetect.py')
<|endoftext|>


<commit_before>import shell
from gitFunctions import Commiter
import shouter

class ImportHandler:
    dateFormat = "yyyy-MM-dd HH:mm:ss"
    informationSeparator = "@@"

    def __init__(self, config):
        self.config = config
        self.git = Commiter()

    def initialize(self):
        config = self.config
        repo = config.repo
        shell.execute("lscm login -r %s -u %s -P %s" % (repo, config.user, config.password))
        shell.execute("lscm create workspace -r %s -s %s %s" % (repo, config.earlieststreamname, config.workspace))
        # implement logic here for replacing components by oldest baseline - scm set components
        config.collectstreamuuids()
        shouter.shout("Starting initial load of workspace")
        shell.execute("lscm load -r %s %s" % (repo, config.workspace))
        shouter.shout("Initial load of workspace finished")

    def acceptchangesfromstreams(self):
        streamuuids = self.config.streamuuids
        for streamuuid in streamuuids:
            streamname = self.config.streamnames[streamuuids.index(streamuuid)]
            self.git.branch(streamname)
            for componentBaseLineEntry in self.getbaselinesfromstream(streamuuid):
                if Commiter.commitcounter % 100 is 0:
                    self.git.pushbranch(streamname)
                self.acceptchangesfrombaseline(componentBaseLineEntry)
            self.git.pushbranch(streamname)

    def getbaselinesfromstream(self, stream):
        filename = self.config.getlogpath("StreamComponents_" + stream + ".txt")
        shell.execute("lscm --show-alias n --show-uuid y list components -v -r " + self.config.repo + " " + stream,
                      filename)
        componentbaselinesentries = []
        skippedfirstrow = False
        islinewithcomponent = 2
        component = None
        baseline = None
        with open(filename, 'r') as file:
            for line in file:
                cleanedline = line.strip()
                if cleanedline:
                    if not skippedfirstrow:
                        skippedfirstrow = True
                        continue
                    splittedlines = line.split("\"")[0].split(" ")
                    if islinewithcomponent % 2 is 0:
                        component = splittedlines[3].strip()[1:-1]
                    else:
                        baseline = splittedlines[5].strip()[1:-1]

                    if baseline is not None and component is not None:
                        componentbaselinesentries.append(self.createcomponentbaselineentry(component, baseline))
                        baseline = None
                        component = None
                    islinewithcomponent += 1
        return componentbaselinesentries

    def acceptchangesfrombaseline(self, componentbaselineentry):
        startcomponentmigrationmessage = "Start accepting changes in component '%s' from baseline '%s'" % \
                                         (componentbaselineentry.componentname, componentbaselineentry.baselinename)
        shouter.shoutwithdate(startcomponentmigrationmessage)

        self.acceptchangesintoworkspace(componentbaselineentry.baseline)

        componentmigratedmessage = "All changes in component '%s' from baseline '%s' are accepted" % \
                                   (componentbaselineentry.componentname, componentbaselineentry.baselinename)
        shouter.shout(componentmigratedmessage)

    def acceptchangesintoworkspace(self, baselinetocompare):
        changeentries = self.getchangeentries(baselinetocompare)
        for changeEntry in changeentries:
            revision = changeEntry.revision
            acceptingmsg = "Accepting: " + changeEntry.comment + " (Date: " + changeEntry.date + " Author: " \
                           + changeEntry.author + " Revision: " + revision + ")"
            shouter.shout(
                acceptingmsg)

            acceptcommand = "lscm accept --changes " + revision
            shell.execute(acceptcommand, self.config.getlogpath("accept.txt"), "a")
            self.git.addandcommit(changeEntry)

            shouter.shout("Revision '" + revision + "' accepted")

    def getchangeentries(self, baselinetocompare):
        outputfilename = self.config.getlogpath("Compare_" + baselinetocompare + ".txt")
        shell.execute(
            "lscm --show-alias n --show-uuid y compare ws " + self.config.workspace + " baseline " + baselinetocompare + " -r " + self.config.repo + " -I sw -C @@{name}@@ --flow-directions i -D @@\"" + self.dateFormat + "\"@@",
            outputfilename)
        changeentries = []
        with open(outputfilename, 'r') as file:
            for line in file:
                cleanedline = line.strip()
                if cleanedline:
                    splittedlines = cleanedline.split(self.informationSeparator)
                    revisionwithbrackets = splittedlines[0].strip()
                    revision = revisionwithbrackets[1:-1]
                    author = splittedlines[1].strip()
                    comment = splittedlines[2].strip()
                    date = splittedlines[3].strip()
                    changeentry = ChangeEntry(revision, author, date, comment)
                    changeentries.append(changeentry)
        return changeentries

    def createcomponentbaselineentry(self, component, baseline):
        componentname = self.getcomponentname(component)
        baselinename = self.getbaselinename(baseline)
        return ComponentBaseLineEntry(component, baseline, componentname, baselinename)

    def getcomponentname(self, componentuuid):
        componentname = ""
        lines = shell.getoutput("lscm --show-alias n show attributes -C %s -r %s" % (componentuuid, self.config.repo))
        if lines:
            componentname = lines[0].strip()
        return componentname

    def getbaselinename(self, baselineuuid):
        baselinename = ""
        lines = shell.getoutput("lscm --show-alias n show attributes -b %s -r %s" % (baselineuuid, self.config.repo))
        for line in lines:
            line = line.strip()
            if line:
                splittedlines = line.split("\"")
                baselinename = splittedlines[1].strip()
        return baselinename

class ChangeEntry:
    def __init__(self, revision, author, date, comment):
        self.revision = revision
        self.author = author
        self.date = date
        self.comment = comment

class ComponentBaseLineEntry:
    def __init__(self, component, baseline, componentname, baselinename):
        self.component = component
        self.baseline = baseline
        self.componentname = componentname
        self.baselinename = baselinename
<commit_msg>natural names without ""<commit_after>import shell
from gitFunctions import Commiter
import shouter

class ImportHandler:
    dateFormat = "yyyy-MM-dd HH:mm:ss"
    informationSeparator = "@@"

    def __init__(self, config):
        self.config = config
        self.git = Commiter()

    def initialize(self):
        config = self.config
        repo = config.repo
        shell.execute("lscm login -r %s -u %s -P %s" % (repo, config.user, config.password))
        shell.execute("lscm create workspace -r %s -s %s %s" % (repo, config.earlieststreamname, config.workspace))
        # implement logic here for replacing components by oldest baseline - scm set components
        config.collectstreamuuids()
        shouter.shout("Starting initial load of workspace")
        shell.execute("lscm load -r %s %s" % (repo, config.workspace))
        shouter.shout("Initial load of workspace finished")

    def acceptchangesfromstreams(self):
        streamuuids = self.config.streamuuids
        for streamuuid in streamuuids:
            streamname = self.config.streamnames[streamuuids.index(streamuuid)]
            self.git.branch(streamname)
            for componentBaseLineEntry in self.getbaselinesfromstream(streamuuid):
                if Commiter.commitcounter % 100 is 0:
                    self.git.pushbranch(streamname)
                self.acceptchangesfrombaseline(componentBaseLineEntry)
            self.git.pushbranch(streamname)

    def getbaselinesfromstream(self, stream):
        filename = self.config.getlogpath("StreamComponents_" + stream + ".txt")
        shell.execute("lscm --show-alias n --show-uuid y list components -v -r " + self.config.repo + " " + stream,
                      filename)
        componentbaselinesentries = []
        skippedfirstrow = False
        islinewithcomponent = 2
        component = None
        baseline = None
        with open(filename, 'r') as file:
            for line in file:
                cleanedline = line.strip()
                if cleanedline:
                    if not skippedfirstrow:
                        skippedfirstrow = True
                        continue
                    splittedlines = line.split("\"")[0].split(" ")
                    if islinewithcomponent % 2 is 0:
                        component = splittedlines[3].strip()[1:-1]
                    else:
                        baseline = splittedlines[5].strip()[1:-1]

                    if baseline is not None and component is not None:
                        componentbaselinesentries.append(self.createcomponentbaselineentry(component, baseline))
                        baseline = None
                        component = None
                    islinewithcomponent += 1
        return componentbaselinesentries

    def acceptchangesfrombaseline(self, componentbaselineentry):
        startcomponentmigrationmessage = "Start accepting changes in component '%s' from baseline '%s'" % \
                                         (componentbaselineentry.componentname, componentbaselineentry.baselinename)
        shouter.shoutwithdate(startcomponentmigrationmessage)

        self.acceptchangesintoworkspace(componentbaselineentry.baseline)

        componentmigratedmessage = "All changes in component '%s' from baseline '%s' are accepted" % \
                                   (componentbaselineentry.componentname, componentbaselineentry.baselinename)
        shouter.shout(componentmigratedmessage)

    def acceptchangesintoworkspace(self, baselinetocompare):
        changeentries = self.getchangeentries(baselinetocompare)
        for changeEntry in changeentries:
            revision = changeEntry.revision
            acceptingmsg = "Accepting: " + changeEntry.comment + " (Date: " + changeEntry.date + " Author: " \
                           + changeEntry.author + " Revision: " + revision + ")"
            shouter.shout(
                acceptingmsg)

            acceptcommand = "lscm accept --changes " + revision
            shell.execute(acceptcommand, self.config.getlogpath("accept.txt"), "a")
            self.git.addandcommit(changeEntry)

            shouter.shout("Revision '" + revision + "' accepted")

    def getchangeentries(self, baselinetocompare):
        outputfilename = self.config.getlogpath("Compare_" + baselinetocompare + ".txt")
        shell.execute(
            "lscm --show-alias n --show-uuid y compare ws " + self.config.workspace + " baseline " + baselinetocompare + " -r " + self.config.repo + " -I sw -C @@{name}@@ --flow-directions i -D @@\"" + self.dateFormat + "\"@@",
            outputfilename)
        changeentries = []
        with open(outputfilename, 'r') as file:
            for line in file:
                cleanedline = line.strip()
                if cleanedline:
                    splittedlines = cleanedline.split(self.informationSeparator)
                    revisionwithbrackets = splittedlines[0].strip()
                    revision = revisionwithbrackets[1:-1]
                    author = splittedlines[1].strip()
                    comment = splittedlines[2].strip()
                    date = splittedlines[3].strip()
                    changeentry = ChangeEntry(revision, author, date, comment)
                    changeentries.append(changeentry)
        return changeentries

    def createcomponentbaselineentry(self, component, baseline):
        componentname = self.getcomponentname(component)
        baselinename = self.getbaselinename(baseline)
        return ComponentBaseLineEntry(component, baseline, componentname, baselinename)

    def getcomponentname(self, componentuuid):
        componentname = ""
        lines = shell.getoutput("lscm --show-alias n show attributes -C %s -r %s" % (componentuuid, self.config.repo))
        if lines:
            componentname = lines[0].strip()[1:-1]
        return componentname

    def getbaselinename(self, baselineuuid):
        baselinename = ""
        lines = shell.getoutput("lscm --show-alias n show attributes -b %s -r %s" % (baselineuuid, self.config.repo))
        if lines:
            splittedlines = lines[0].strip().split("\"")
            baselinename = splittedlines[1].strip()
        return baselinename

class ChangeEntry:
    def __init__(self, revision, author, date, comment):
        self.revision = revision
        self.author = author
        self.date = date
        self.comment = comment

class ComponentBaseLineEntry:
    def __init__(self, component, baseline, componentname, baselinename):
        self.component = component
        self.baseline = baseline
        self.componentname = componentname
        self.baselinename = baselinename
<|endoftext|>