<commit_before>"""
Mr. Box:
Practice box-sorting problem solution script in Python 3.5.2

The MIT License:
Copyright (c) 2017 Deives Collins
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

"""

import tkinter, math

class Box:
    """ Class for representing and manipulating box data """
    def __init__(self, dim1, dim2, dim3):
        self.l = dim1
        self.w = dim2
        self.h = dim3

        self.bases = [ (self.l,self.w),
                       (self.l,self.h),
                       (self.w,self.h) ]

    def __repr__(self):
        return '(L:'+str(self.l)+',W:'+str(self.w)+',H:'+str(self.h)+')'

    def __lt__(self,other):
        return self.l < other.l

    def __gt__(self,other):
        return self.l > other.l

    def __le__(self,other):
        return self.__lt__(other) or self.__eq__(other)

    def __ge__(self,other):
        return self.__gt__(other) or self.__eq__(other)

    def rotateToBase(self,base):
        """ Reorder the values of the box to reflect the dimensions of the box
            when rotated to the given valid base """
        dims = [self.l,self.w,self.h]
        for dim in base:
            if dim in dims:
                dims.remove(dim)
        self.h = dims[0]
        self.l,self.w = base[0],base[1]

class Tracker:
    """ Class for tracking progress of iteratated tasks """
    alignment = 40

    def __init__(self, total, text):
        self.count, self.percentage = 0, 0
        self.total, self.text = total, text
        self.progressBar()

    def incr(self):
        self.count += 1
        if int((self.count/self.total)*100) != self.percentage:
            self.percentage = int((self.count/self.total)*100)
            if self.percentage%5 == 0:
                self.progressBar()

    def progressBar(self):
        """ Display an updating progress bar reflecting the ratio current/total """
        steps = int(self.percentage/5)

        bar = '[' + '='*(steps) + '>' + ' '*(20-steps) + '] ' + '%02d'%self.percentage + '%'
        if self.count > 0:
            print('\b'*len(bar),end='',flush=True)
            if self.percentage == 100:
                print(' ',end='',flush=True)
        else:
            print(self.text,end=' ',flush=True)
            print(' '*(Tracker.alignment-(len(self.text)+1)),end='',flush=True)
        print(bar,end=(lambda x: '' if x < 100 else '\n')(self.percentage),flush=True)

def genBoxCombos(boxes):
    """ Generate all possible combinations of all possible lengths
        of the given set of boxes (independent of order) """
    def binaries(length, tracker):
        """ Generate binary sequence possibilities for given length """
        if length == 1:
            tracker.incr()
            return([0],[1])
        else:
            combos = []
            for combo in binaries(length-1, tracker):
                         # Recursive call
                for bit in ([0],[1]):
                    tracker.incr()
                    combos.append(bit+combo)
            return combos

    total = 1
    for x in range(len(boxes),1,-1):
        total += math.pow(2,x)
    tracker = Tracker(total, "Generating combination sequences:")
    bins = binaries(len(boxes),tracker)

    # Populate list of box combinations from binary sequences
    tracker = Tracker(len(bins),"Populating box combinations:")
    combos = []
    for sequence in bins:
        combo = [y for y in
                     map((lambda x: boxes[x[0]] if x[1] else None),
                         enumerate(sequence))
                 if y]
        combos.append(combo)
        tracker.incr()

    return combos

def genBaseHierarchy(boxes):
    """ Return:
            1. [ (l,w), (l,w), ... ]
               list of all bases (regardless of parent box) as tuples in
               descending order of area (l*w)
            2. { (l,w): { box:height } }
               dict, by base keys, of sub-dicts, by box keys, with heights
               corresponding to the vertical dimension of the given box
               with the given base """

    hierarchy = []
    for box in boxes:
        for base in box.bases:
            if not base in hierarchy:
                hierarchy.append(base)
    hierarchy.sort(key = lambda x: x[0]*x[1])

    baseDict = {}
    for base in hierarchy:
        heightDict = {}
        for box in boxes:
            if base in box.bases or (base[1],base[0]) in box.bases:
                box.rotateToBase(base)
                heightDict[box] = box.h
        baseDict[base] = heightDict

    return hierarchy, baseDict

def ruleCheck(baseCombo):
    """ Compare a list of base combinations for validity according to rule:
        length(baseA) > length(baseB) and width(baseA) > width(baseB);

        If the list does not satisfy the rule as given but does after
        horizontal rotation of one or more bases, the list is returned
        with these bases rotated """
    if len(baseCombo) <= 1:
        return True

    changed = False
    for index in range(len(baseCombo)-1):
        if not (baseCombo[index][0] > baseCombo[index+1][0] and
                baseCombo[index][1] > baseCombo[index+1][1]):

            # Try the base pair with the upper-most base rotated horizontally
            baseCombo[index+1] = (baseCombo[index+1][1],baseCombo[index+1][0])

            if (baseCombo[index][0] > baseCombo[index+1][0] and
                baseCombo[index][1] > baseCombo[index+1][1]):

                changed = True

            else:
                return False

    if changed:
        return baseCombo # Return corrected list
    else:
        return True

def stack(boxes):
    """ Determine the tallest stack of given boxes possible while satisfying
        ruleCheck() and output appropriately ordered and rotated boxes """
    boxCombos = genBoxCombos(boxes)
    hierarchy, baseDict = genBaseHierarchy(boxes)
    tracker = Tracker(len(boxCombos),"Evaluating stacks:")

    tallest, maxHeight = [],0
    for combo in boxCombos:
        stack = []
        for base in hierarchy:
            if len(combo) > 0:
                boxChoice, boxHeight = 0, 0
                for box in combo:
                    if box in baseDict[base]:
                        if baseDict[base][box] > boxHeight:
                            boxChoice, boxHeight = box, baseDict[base][box]
                if boxChoice:
                    combo.remove(boxChoice)
                    stack.append((boxChoice,base,boxHeight))

        stack.reverse()
        validate = ruleCheck([x[1] for x in stack])
        if validate:
            if type(validate) == list:
                # Update corrected values from ruleCheck()
                for index in range(len(validate)):
                    stack[index] = (stack[index][0],validate[index],stack[index][2])

            stackHeight = 0
            for boxInfo in stack:
                stackHeight += boxInfo[2]
            if stackHeight > maxHeight:
                tallest, maxHeight = stack, stackHeight

        tracker.incr()

    final = [x[0] for x in tallest]
    for index in range(len(final)):
        box = final[index]
        base = tallest[index][1]
        box.rotateToBase(base)

    return final

def display(boxes):
    """ Display the solution stack in a tkinter window """
    window = tkinter.Tk()
    window.title("Mr. Box Graphical Output")
    bgcol, linecol, textcol = "#000050", "#FFFFFF", "#00FF00"
    canvas = tkinter.Canvas(window, width=800, height=600,bg=bgcol)
    canvas.pack()

    bottomTransform = boxes[0].l*math.sin(0.4) + boxes[0].w*math.sin(0.4)
    height = bottomTransform
    for box in boxes:
        height += box.h
    scale = 500/height
    center, stackHeight = 799/2, 550-bottomTransform*scale

    for box in boxes:
        lenTransform = ( box.l*scale*math.cos(0.4),
                         box.l*scale*math.sin(0.4) )
        widTransform = ( box.w*scale*math.cos(0.4),
                         box.w*scale*math.sin(0.4) )
        hgtTransform = box.h*scale

        origin = (center,stackHeight)

        # Lower
        activePoint = (origin[0]+lenTransform[0],origin[1]+lenTransform[1])
        endPoint = (activePoint[0]-widTransform[0],activePoint[1]+widTransform[1])
        textPoint = (activePoint[0]-widTransform[0]/2,activePoint[1]+widTransform[1]/2)
        canvas.create_line(activePoint,endPoint,fill=linecol)
        canvas.create_text(textPoint,text='\n'+str(box.w),fill=textcol)

        activePoint = (origin[0]-widTransform[0],origin[1]+widTransform[1])
        endPoint = (activePoint[0]+lenTransform[0],activePoint[1]+lenTransform[1])
        textPoint = (activePoint[0]+lenTransform[0]/2,activePoint[1]+lenTransform[1]/2)
        canvas.create_line(activePoint,endPoint,fill=linecol)
        canvas.create_text(textPoint,text='\n'+str(box.l),fill=textcol)
        textPoint = (activePoint[0]-5,activePoint[1]-hgtTransform/2)
        canvas.create_text(textPoint,text='  '+str(box.h),fill=textcol,anchor='e')

        # Upper
        activePoint = (origin[0],origin[1]-hgtTransform)
        endPoint = (activePoint[0]+lenTransform[0],activePoint[1]+lenTransform[1])
        canvas.create_line(activePoint,endPoint,fill=linecol)

        stackHeight = activePoint[1]

        activePoint = endPoint
        endPoint = (activePoint[0]-widTransform[0],activePoint[1]+widTransform[1])
        canvas.create_line(activePoint,endPoint,fill=linecol)
        canvas.create_line(activePoint,activePoint[0],activePoint[1]+hgtTransform,
                           fill=linecol)

        activePoint = endPoint
        endPoint = (activePoint[0]-lenTransform[0],activePoint[1]-lenTransform[1])
        textPoint = (origin[0],activePoint[1]+hgtTransform/2)
        canvas.create_line(activePoint,endPoint,fill=linecol)
        canvas.create_line(activePoint,activePoint[0],activePoint[1]+hgtTransform,
                           fill=linecol)

        activePoint = endPoint
        endPoint = (origin[0],origin[1]-hgtTransform)
        canvas.create_line(activePoint,endPoint,fill=linecol)
        canvas.create_line(activePoint,activePoint[0],activePoint[1]+hgtTransform,
                           fill=linecol)

    height = height-bottomTransform
    if height % 1 == 0:
        height = int(height)
    canvas.create_text(center,585,text="Total Height: "+str(height),fill=textcol,font=("TkDefaultFont",16))

    window.mainloop()

def main():
    print("""
####
#  #
######    MR. BOX:
#    #
########      The friendly box-stacking proof-of-concept script
#      #         2017 Deives Collins
######## \n""")

    print("Mr. Box is a practice program designed to solve the following problem:\n")

    print("Objective:  Find the tallest possible stack given a set of boxes\n")

    print("Constraint: Box A can only be stacked on top of Box B if both")
    print("            the length and width of Box B are larger than the")
    print("            length and width of Box A\n")

    print("Mr. Box will now request information about the set of boxes you wish")
    print("to use for the problem.\n")

    count = ''
    while not count.isnumeric():
        print("How many boxes will be in the set?")
        print("# of boxes:",end=' ')
        count = input()
        print("")
        if not count.isnumeric():
            print("Error:")
            print("# of boxes must be entered in numeric characters (1,2,3, ...) only\n")
    count = int(count)

    boxes = []
    for index in range(0,count):
        dims = ['','','']
        while not ( (type(dims[0]) == int or type(dims[0]) == float) and
                    (type(dims[1]) == int or type(dims[1]) == float) and
                    (type(dims[2]) == int or type(dims[2]) == float) ):
            print("For box "+str(index+1)+" of "+str(count)+":\n")
            print("Enter the length:",end=' ')
            dims[0] = input()
            print("           width:",end=' ')
            dims[1] = input()
            print("          height:",end=' ')
            dims[2] = input()
            print("")

            for idx in range(3):
                if dims[idx].isnumeric():
                    dims[idx] = int(dims[idx])
                elif '.' in dims[idx]:
                    fl = dims[idx]
                    if fl[:fl.index('.')].isnumeric() and \
                       fl[fl.index('.')+1:].isnumeric():
                        dims[idx] = float(fl)
                else:
                    print("Error:")
                    print("Dimensions must be entered in numeric characters (1,2,3, ...)")
                    print("and (optionally) a maximum of 1 decimal point\n")

        boxes.append(Box(dims[0],dims[1],dims[2]))

    print("Mr. Box will now irreversibly change your life.\n")

    boxes = stack(boxes)
    display(boxes)

if __name__ == "__main__":
    main()
<commit_msg>Update mrbox.py<commit_after>"""
Mr. Box:
Practice box-sorting problem solution script in Python 3.5.2

The MIT License:
Copyright (c) 2017 Deives Collins
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

"""

import tkinter, math

class Box:
    """ Class for representing and manipulating box data """
    def __init__(self, dim1, dim2, dim3):
        self.l = dim1
        self.w = dim2
        self.h = dim3

        self.bases = [ (self.l,self.w),
                       (self.l,self.h),
                       (self.w,self.h) ]

    def __repr__(self):
        return '(L:'+str(self.l)+',W:'+str(self.w)+',H:'+str(self.h)+')'

    def __lt__(self,other):
        return self.l < other.l

    def __gt__(self,other):
        return self.l > other.l

    def __le__(self,other):
        return self.__lt__(other) or self.__eq__(other)

    def __ge__(self,other):
        return self.__gt__(other) or self.__eq__(other)

    def rotateToBase(self,base):
        """ Reorder the values of the box to reflect the dimensions of the box
            when rotated to the given valid base """
        dims = [self.l,self.w,self.h]
        for dim in base:
            if dim in dims:
                dims.remove(dim)
        self.h = dims[0]
        self.l,self.w = base[0],base[1]

class Tracker:
    """ Class for tracking progress of iteratated tasks """
    alignment = 40

    def __init__(self, total, text):
        self.count, self.percentage = 0, 0
        self.total, self.text = total, text
        self.progressBar()

    def incr(self):
        self.count += 1
        if int((self.count/self.total)*100) != self.percentage:
            self.percentage = int((self.count/self.total)*100)
            if self.percentage%5 == 0:
                self.progressBar()

    def progressBar(self):
        """ Display an updating progress bar reflecting the ratio current/total """
        steps = int(self.percentage/5)

        bar = '[' + '='*(steps) + '>' + ' '*(20-steps) + '] ' + '%02d'%self.percentage + '%'
        if self.count > 0:
            print('\b'*len(bar),end='',flush=True)
            if self.percentage == 100:
                print(' ',end='',flush=True)
        else:
            print(self.text,end=' ',flush=True)
            print(' '*(Tracker.alignment-(len(self.text)+1)),end='',flush=True)
        print(bar,end=(lambda x: '' if x < 100 else '\n')(self.percentage),flush=True)

def genBoxCombos(boxes):
    """ Generate all possible combinations of all possible lengths
        of the given set of boxes (independent of order) """
    def binaries(length, tracker):
        """ Generate binary sequence possibilities for given length """
        if length == 1:
            tracker.incr()
            return([0],[1])
        else:
            combos = []
            for combo in binaries(length-1, tracker):
                         # Recursive call
                for bit in ([0],[1]):
                    tracker.incr()
                    combos.append(bit+combo)
            return combos

    total = 1
    for x in range(len(boxes),1,-1):
        total += math.pow(2,x)
    tracker = Tracker(total, "Generating combination sequences:")
    bins = binaries(len(boxes),tracker)

    # Populate list of box combinations from binary sequences
    tracker = Tracker(len(bins),"Populating box combinations:")
    combos = []
    for sequence in bins:
        combo = [y for y in
                     map((lambda x: boxes[x[0]] if x[1] else None),
                         enumerate(sequence))
                 if y]
        combos.append(combo)
        tracker.incr()

    return combos

def genBaseHierarchy(boxes):
    """ Return:
            1. [ (l,w), (l,w), ... ]
               list of all bases (regardless of parent box) as tuples in
               descending order of area (l*w)
            2. { (l,w): { box:height } }
               dict, by base keys, of sub-dicts, by box keys, with heights
               corresponding to the vertical dimension of the given box
               with the given base """

    hierarchy = []
    for box in boxes:
        for base in box.bases:
            if not base in hierarchy:
                hierarchy.append(base)
    hierarchy.sort(key = lambda x: x[0]*x[1])

    baseDict = {}
    for base in hierarchy:
        heightDict = {}
        for box in boxes:
            if base in box.bases or (base[1],base[0]) in box.bases:
                box.rotateToBase(base)
                heightDict[box] = box.h
        baseDict[base] = heightDict

    return hierarchy, baseDict

def ruleCheck(baseCombo):
    """ Compare a list of base combinations for validity according to rule:
        length(baseA) > length(baseB) and width(baseA) > width(baseB);

        If the list does not satisfy the rule as given but does after
        horizontal rotation of one or more bases, the list is returned
        with these bases rotated """
    if len(baseCombo) <= 1:
        return True

    changed = False
    for index in range(len(baseCombo)-1):
        if not (baseCombo[index][0] > baseCombo[index+1][0] and
                baseCombo[index][1] > baseCombo[index+1][1]):

            # Try the base pair with the upper-most base rotated horizontally
            baseCombo[index+1] = (baseCombo[index+1][1],baseCombo[index+1][0])

            if (baseCombo[index][0] > baseCombo[index+1][0] and
                baseCombo[index][1] > baseCombo[index+1][1]):

                changed = True

            else:
                return False

    if changed:
        return baseCombo # Return corrected list
    else:
        return True

def stack(boxes):
    """ Determine the tallest stack of given boxes possible while satisfying
        ruleCheck() and output appropriately ordered and rotated boxes """
    boxCombos = genBoxCombos(boxes)
    hierarchy, baseDict = genBaseHierarchy(boxes)
    tracker = Tracker(len(boxCombos),"Evaluating stacks:")

    tallest, maxHeight = [],0
    for combo in boxCombos:
        stack = []
        for base in hierarchy:
            if len(combo) > 0:
                boxChoice, boxHeight = 0, 0
                for box in combo:
                    if box in baseDict[base]:
                        if baseDict[base][box] > boxHeight:
                            boxChoice, boxHeight = box, baseDict[base][box]
                if boxChoice:
                    combo.remove(boxChoice)
                    stack.append((boxChoice,base,boxHeight))

        stack.reverse()
        validate = ruleCheck([x[1] for x in stack])
        if validate:
            if type(validate) == list:
                # Update corrected values from ruleCheck()
                for index in range(len(validate)):
                    stack[index] = (stack[index][0],validate[index],stack[index][2])

            stackHeight = 0
            for boxInfo in stack:
                stackHeight += boxInfo[2]
            if stackHeight > maxHeight:
                tallest, maxHeight = stack, stackHeight

        tracker.incr()

    final = [x[0] for x in tallest]
    for index in range(len(final)):
        box = final[index]
        base = tallest[index][1]
        box.rotateToBase(base)

    return final

def display(boxes):
    """ Display the solution stack in a tkinter window """
    window = tkinter.Tk()
    window.title("Mr. Box Graphical Output")
    bgcol, linecol, textcol = "#000050", "#FFFFFF", "#00FF00"
    canvas = tkinter.Canvas(window, width=800, height=600,bg=bgcol)
    canvas.pack()

    bottomTransform = boxes[0].l*math.sin(0.4) + boxes[0].w*math.sin(0.4)
    height = bottomTransform
    for box in boxes:
        height += box.h
    scale = 500/height
    center, stackHeight = 799/2, 550-bottomTransform*scale

    for box in boxes:
        lenTransform = ( box.l*scale*math.cos(0.4),
                         box.l*scale*math.sin(0.4) )
        widTransform = ( box.w*scale*math.cos(0.4),
                         box.w*scale*math.sin(0.4) )
        hgtTransform = box.h*scale

        origin = (center,stackHeight)

        # Lower
        activePoint = (origin[0]+lenTransform[0],origin[1]+lenTransform[1])
        endPoint = (activePoint[0]-widTransform[0],activePoint[1]+widTransform[1])
        textPoint = (activePoint[0]-widTransform[0]/2,activePoint[1]+widTransform[1]/2)
        canvas.create_line(activePoint,endPoint,fill=linecol)
        canvas.create_text(textPoint,text='\n'+str(box.w),fill=textcol)

        activePoint = (origin[0]-widTransform[0],origin[1]+widTransform[1])
        endPoint = (activePoint[0]+lenTransform[0],activePoint[1]+lenTransform[1])
        textPoint = (activePoint[0]+lenTransform[0]/2,activePoint[1]+lenTransform[1]/2)
        canvas.create_line(activePoint,endPoint,fill=linecol)
        canvas.create_text(textPoint,text='\n'+str(box.l),fill=textcol)
        textPoint = (activePoint[0]-5,activePoint[1]-hgtTransform/2)
        canvas.create_text(textPoint,text='  '+str(box.h),fill=textcol,anchor='e')

        # Upper
        activePoint = (origin[0],origin[1]-hgtTransform)
        endPoint = (activePoint[0]+lenTransform[0],activePoint[1]+lenTransform[1])
        canvas.create_line(activePoint,endPoint,fill=linecol)

        stackHeight = activePoint[1]

        activePoint = endPoint
        endPoint = (activePoint[0]-widTransform[0],activePoint[1]+widTransform[1])
        canvas.create_line(activePoint,endPoint,fill=linecol)
        canvas.create_line(activePoint,activePoint[0],activePoint[1]+hgtTransform,
                           fill=linecol)

        activePoint = endPoint
        endPoint = (activePoint[0]-lenTransform[0],activePoint[1]-lenTransform[1])
        textPoint = (origin[0],activePoint[1]+hgtTransform/2)
        canvas.create_line(activePoint,endPoint,fill=linecol)
        canvas.create_line(activePoint,activePoint[0],activePoint[1]+hgtTransform,
                           fill=linecol)

        activePoint = endPoint
        endPoint = (origin[0],origin[1]-hgtTransform)
        canvas.create_line(activePoint,endPoint,fill=linecol)
        canvas.create_line(activePoint,activePoint[0],activePoint[1]+hgtTransform,
                           fill=linecol)

    height = height-bottomTransform
    if height % 1 == 0:
        height = int(height)
    canvas.create_text(center,585,text="Total Height: "+str(height),fill=textcol,font=("TkDefaultFont",16))

    window.mainloop()

def main():
    print("""
####
#  #
######    MR. BOX:
#    #
########      The friendly box-stacking proof-of-concept script
#      #         (c) 2017 Deives Collins | MIT License
######## \n""")

    print("Mr. Box is a practice program designed to solve the following problem:\n")

    print("Objective:  Find the tallest possible stack given a set of boxes\n")

    print("Constraint: Box A can only be stacked on top of Box B if both")
    print("            the length and width of Box B are larger than the")
    print("            length and width of Box A\n")

    print("Mr. Box will now request information about the set of boxes you wish")
    print("to use for the problem.\n")

    count = ''
    while not count.isnumeric():
        print("How many boxes will be in the set?")
        print("# of boxes:",end=' ')
        count = input()
        print("")
        if not count.isnumeric():
            print("Error:")
            print("# of boxes must be entered in numeric characters (1,2,3, ...) only\n")
    count = int(count)

    boxes = []
    for index in range(0,count):
        dims = ['','','']
        while not ( (type(dims[0]) == int or type(dims[0]) == float) and
                    (type(dims[1]) == int or type(dims[1]) == float) and
                    (type(dims[2]) == int or type(dims[2]) == float) ):
            print("For box "+str(index+1)+" of "+str(count)+":\n")
            print("Enter the length:",end=' ')
            dims[0] = input()
            print("           width:",end=' ')
            dims[1] = input()
            print("          height:",end=' ')
            dims[2] = input()
            print("")

            for idx in range(3):
                if dims[idx].isnumeric():
                    dims[idx] = int(dims[idx])
                elif '.' in dims[idx]:
                    fl = dims[idx]
                    if fl[:fl.index('.')].isnumeric() and \
                       fl[fl.index('.')+1:].isnumeric():
                        dims[idx] = float(fl)
                else:
                    print("Error:")
                    print("Dimensions must be entered in numeric characters (1,2,3, ...)")
                    print("and (optionally) a maximum of 1 decimal point\n")

        boxes.append(Box(dims[0],dims[1],dims[2]))

    print("Mr. Box will now irreversibly change your life.\n")

    boxes = stack(boxes)
    display(boxes)

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


<commit_before>"""Abstracted file parsing functions
"""

from re import match
from os import walk, path

def sub_directories(parent_dir):
    root, dirs, files = next(walk(parent_dir))
    return [path.join(root, sd) for sd in dirs]

def get_files(directory, filterfn=lambda x: True):
    """Get all the files that are direct children to the given directory and
    match the given filter function

    :param directory: the directory whose immediate children are to be returned
    :param filterfn: the function with which to filter files
    :return: a list of all of the file paths of the files that are direct
    children to the given directory and match the filter function
    """
    root, dirs, files = next(walk(directory))
    filepaths_list = [path.join(root, f) for f in files]
    return list(filter(filterfn, filepaths_list))

def get_files_r(directory, filterfn=lambda x: True):
    """Recursively get all of the files that children (direct or indirect) to
    the given directory and match the given filter function

    :param directory: the directory whose children are to be returned
    :param filterfn: the filter function with which to filter the children
    :return: a list of all of the file paths of the files that are children
    to the given directory and match the filter function
    """
    w = walk(directory)
    filepaths_list = list()
    for root, dirs, files in w:
        filepaths_list.extend([path.join(root, f) for f in files])
    return list(filter(filterfn, filepaths_list))

def has_extension(fname, ext):
    return ext == _get_extension(fname)

def _get_extension(fname):
    return fname[fname.rfind('.'):]

def filename_elts_list(filename, split_char):
    """Get a list of the elements in the filename where name elements are
    separated by split_char
    :param split_char:
    :param filename:
    """
    ext_index = filename.rfind('.')
    dir_index = filename.rfind('/')
    if dir_index != -1:
        filename_woext = filename[dir_index:ext_index]
    else:
        filename_woext = filename[:ext_index]
    return filename_woext.split(split_char)

def elt_from_felts(felts, elt_regex):
    for elt in felts:
        if matches_completely(regex=elt_regex, string=elt):
            return elt
    else:
        return None

def _get_lines(filename):
    """Returns all of the lines read from the given file in a list (with
    line separators and blank lines removed
    """
    with open(filename) as f:
        lines = f.readlines()
    # Remove line separators
    lines = map(lambda x: x.strip(), lines)
    # Remove blank lines
    lines = filter(lambda x: len(x) > 0, lines)
    return list(lines)

def content_lines(filename, comment_char):
    """Returns a list of all of the lines that are not comments
    :param comment_char:
    :param filename:
    """
    lines = _get_lines(filename)
    return list(filter(lambda x: x[0] is not comment_char, lines))

def comment_lines(filename, comment_char):
    """Returns all of the lines read from the given filename that are
    descriptive comments
    :param comment_char:
    :param filename:
    """
    lines = _get_lines(filename)
    lines = filter(lambda x: x[0] is comment_char, lines)
    lines = map(lambda x: x.strip(comment_char).strip(), lines)
    lines = filter(lambda x: x is not '', lines)
    return list(lines)

def index_of_line(lines, line_regex):
    for line, index in zip(lines, range(len(lines))):
        if matches_completely(regex=line_regex, string=line):
            return index, line
    else:
        return None

def matches_completely(regex, string):
    """Returns true if the regex matches the string completely,
    false otherwise
    :param regex: Regular expression pattern to match
    :param string: String to test
    """
    m = match(pattern=regex, string=string)
    if m is not None and m.group(0) == string:
        return True
    else:
        return False

def half_int_str_to_float(string):
    if '/' in string:
        return reduce(lambda a, b: int(a)/int(b), string.split('/'))
    else:
        return int(string)

def half_int_float_to_str(f):
    if int(f) - f == 0:
        return str(int(f))
    else:
        return str(int(2 * f)) + '/2'
<commit_msg>Changed filename_elts_list function so that it can be used with directory names as well.<commit_after>"""Abstracted file parsing functions
"""

from re import match
from os import walk, path

def sub_directories(parent_dir):
    root, dirs, files = next(walk(parent_dir))
    return [path.join(root, sd) for sd in dirs]

def get_files(directory, filterfn=lambda x: True):
    """Get all the files that are direct children to the given directory and
    match the given filter function

    :param directory: the directory whose immediate children are to be returned
    :param filterfn: the function with which to filter files
    :return: a list of all of the file paths of the files that are direct
    children to the given directory and match the filter function
    """
    root, dirs, files = next(walk(directory))
    filepaths_list = [path.join(root, f) for f in files]
    return list(filter(filterfn, filepaths_list))

def get_files_r(directory, filterfn=lambda x: True):
    """Recursively get all of the files that children (direct or indirect) to
    the given directory and match the given filter function

    :param directory: the directory whose children are to be returned
    :param filterfn: the filter function with which to filter the children
    :return: a list of all of the file paths of the files that are children
    to the given directory and match the filter function
    """
    w = walk(directory)
    filepaths_list = list()
    for root, dirs, files in w:
        filepaths_list.extend([path.join(root, f) for f in files])
    return list(filter(filterfn, filepaths_list))

def has_extension(fname, ext):
    return ext == _get_extension(fname)

def _get_extension(fname):
    return fname[fname.rfind('.'):]

def filename_elts_list(filename, split_char):
    """Get a list of the elements in the filename where name elements are
    separated by split_char
    :param filename: Name of the file or directory to split
    :param split_char: Character by which to split the string
    """
    ext_index = filename.rfind('.')
    dir_index = filename.rfind('/')
    if dir_index != -1 and ext_index != -1:
        filename_woext = filename[dir_index:ext_index]
    elif ext_index != -1:
        filename_woext = filename[:ext_index]
    elif dir_index != -1:
        filename_woext = filename[dir_index:]
    else:
        filename_woext = filename
    return filename_woext.split(split_char)

def elt_from_felts(felts, elt_regex):
    for elt in felts:
        if matches_completely(regex=elt_regex, string=elt):
            return elt
    else:
        return None

def _get_lines(filename):
    """Returns all of the lines read from the given file in a list (with
    line separators and blank lines removed
    """
    with open(filename) as f:
        lines = f.readlines()
    # Remove line separators
    lines = map(lambda x: x.strip(), lines)
    # Remove blank lines
    lines = filter(lambda x: len(x) > 0, lines)
    return list(lines)

def content_lines(filename, comment_char):
    """Returns a list of all of the lines that are not comments
    :param comment_char:
    :param filename:
    """
    lines = _get_lines(filename)
    return list(filter(lambda x: x[0] is not comment_char, lines))

def comment_lines(filename, comment_char):
    """Returns all of the lines read from the given filename that are
    descriptive comments
    :param comment_char:
    :param filename:
    """
    lines = _get_lines(filename)
    lines = filter(lambda x: x[0] is comment_char, lines)
    lines = map(lambda x: x.strip(comment_char).strip(), lines)
    lines = filter(lambda x: x is not '', lines)
    return list(lines)

def index_of_line(lines, line_regex):
    for line, index in zip(lines, range(len(lines))):
        if matches_completely(regex=line_regex, string=line):
            return index, line
    else:
        return None

def matches_completely(regex, string):
    """Returns true if the regex matches the string completely,
    false otherwise
    :param regex: Regular expression pattern to match
    :param string: String to test
    """
    m = match(pattern=regex, string=string)
    if m is not None and m.group(0) == string:
        return True
    else:
        return False

def half_int_str_to_float(string):
    if '/' in string:
        return reduce(lambda a, b: int(a)/int(b), string.split('/'))
    else:
        return int(string)

def half_int_float_to_str(f):
    if int(f) - f == 0:
        return str(int(f))
    else:
        return str(int(2 * f)) + '/2'
<|endoftext|>


<commit_before>#! /usr/bin/python3
import os
import re
import argparse

def main():
    argparser = argparse.ArgumentParser("py2by", description="Bython is a python preprosessor that translates braces into indentation", formatter_class=argparse.RawTextHelpFormatter)

if __name__ == '__main__':
	main()<commit_msg>py2by: parsing of input arguments done, most of the framework in place<commit_after>#! /usr/bin/python3
import os
import re
import argparse
import sys

def parse_indent_style_input(indentinput):
    if indentinput == "1s":
        return " "

    elif indentinput == "2s":
        return "  "

    elif indentinput == "4s":
        return "    "

    elif indentinput == "8s":
        return "        "

    elif indentinput == "t":
        return "\t"

    else:
        return None

def ends_in_py(word):
    return word[-3:] == ".py"

def change_file_name(name):
    if ends_in_py(name):
        return name[:-3] + ".by"

    else:
        return name + ".by"

def reverse_parse(filename, indent_style):
    indent_symbol = parse_indent_style_input(indent_style)

    if not indent_symbol:
        print("Input error: %s is not a valid indentation style!" % (indent_style))
        sys.exit(1)

    infile = open(filename, "r")
    outfile = open(change_file_name(filename), "w")

    previous_line = ""
    indentation_level = 0

    for line in infile:
        pass

    infile.close()
    outfile.close()

def main():
    argparser = argparse.ArgumentParser("py2by", description="py2by translates python to bython", formatter_class=argparse.RawTextHelpFormatter)
    argparser.add_argument("input", type=str, help="python file to translate", nargs=1)
    argparser.add_argument("-i", "--indent_style", type=str, help="style of indentation to look for: 1s, 2s, 4s, 8s or t (default: 4s)", nargs=1)

    cmd_args = argparser.parse_args()

    reverse_parse(cmd_args.input, cmd_args.indent_style[0])

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


<commit_before>#!/usr/bin/python2

import pyglet
from pyglet.window import key
from time import time, strftime, localtime

running = False
begin, now, total = 0, 0, 0
size = (320, 240)
format = "%.2f"

window = pyglet.window.Window(size[0], size[1], caption="Stopwatch", \
                              visible=False)
label = pyglet.text.Label('0.00', font_size=36,
                          x=window.width/2, y=window.height/2,
                          anchor_x='center', anchor_y='center')
window.set_visible()

@window.event
def on_key_release(symbol, modifiers):
    global now, begin, running, total
    if symbol == key.SPACE:
        if not running:
            running = True
            begin = time()
        else:
            running = False
            now = time()
            total += now - begin
    if symbol == key.BACKSPACE:
        total = 0
        begin = time()
        running = False

@window.event
def on_draw():
    window.clear()
    label.draw()

def update_time(dt):
    global now, begin, total
    if running:
        now = time()
        label.text = format % (now - begin + total)
    else:
        label.text = format % (total)

pyglet.clock.schedule_interval(update_time, 0.01)
pyglet.app.run()
<commit_msg>Added time formatting.<commit_after>#!/usr/bin/python2

import pyglet
from pyglet.window import key
import time

running = False
begin, now, total = 0, 0, 0
size = (320, 240)

window = pyglet.window.Window(size[0], size[1], caption="Stopwatch",
                              visible=False)
label = pyglet.text.Label('00:00:00:00', font_size=36,
                          x=window.width/2, y=window.height/2,
                          anchor_x='center', anchor_y='center')
window.set_visible()

@window.event
def on_key_release(symbol, modifiers):
    global now, begin, running, total
    if symbol == key.SPACE:
        if not running:
            running = True
            begin = time.time()
        else:
            running = False
            now = time.time()
            total += now - begin
    if symbol == key.BACKSPACE:
        total = 0
        begin = time.time()
        running = False

@window.event
def on_draw():
    window.clear()
    label.draw()

def get_millis(timestamp):
    millis = str(timestamp - int(timestamp))[2:4]
    if millis == "":
        return "00"
    else:
        return millis

def update_time(dt):
    global now, begin, total
    if running:
        now = time.time()
        label.text = time.strftime("%H:%M:%S:", time.gmtime(now - begin + total)) + get_millis(now - begin + total)
    else:
        label.text = time.strftime("%H:%M:%S:", time.gmtime(total)) + get_millis(total)

pyglet.clock.schedule_interval(update_time, 0.01)
pyglet.app.run()
<|endoftext|>


<commit_before>"""Implement the Queue module."""
from dll import DLL

class Queue(object):
    """Define the Queue class.

    It is important to note that the "tail" of our queue is actually the front of the Queue.

    __init__(): initializes the Queue class as a composite of the DLL class.
    enqueue(): uses the push method from DLL to add nodes to the end of the Queue.
    dequeue(): removes a node from the front of the dequeue
    peek(): Looks at the front value of the Queue without removing it or advancing the view beyond it.
    size(): returns the size of the Queue.
    """

    def __init__(self, iterable=None):
        """Initiate the Queue as an instance of DLL."""
        self._container = DLL(iterable)

    def enqueue(self, val):
        """Add value to the Queue at the end."""
        self._container.push(val)

    def dequeue(self):
        """Remove the first value of the queue."""
        try:
            return self._container.shift()
        except AttributeError:
            raise AttributeError("Cannot dequeue from an empty Queue.")

    def peek(self):
        """Look at next value in the Queue without removing."""
        try:
            return self._container.tail.val
        except AttributeError:
            raise AttributeError("Queue is empty.")

    def size(self):
        """How big the Queue is."""
        return self._container.size_of_list
<commit_msg>updating<commit_after>"""Implement the Queue module."""
from dll import DLL

class Queue(object):
    """Define the Queue class.

    It is important to note that the "tail" of our queue is actually the front of the Queue.

    __init__(): initializes the Queue class as a composite of the DLL class.
    enqueue(): uses the push method from DLL to add nodes to the end of the Queue.
    dequeue(): removes a node from the front of the dequeue
    peek(): Looks at the front value of the Queue without removing it or advancing the view beyond it.
    size(): returns the size of the Queue.
    """

    def __init__(self, iterable=None):
        """Initiate the Queue as an instance of DLL."""
        self._container = DLL(iterable)

    def enqueue(self, val):
        """Add value to the Queue at the end."""
        self._container.push(val)

    def dequeue(self):
        """Remove the first value of the queue."""
        try:
            return self._container.shift()
        except AttributeError:
            raise AttributeError("Cannot dequeue from an empty Queue.")

    def peek(self):
        """Look at next value in the Queue without removing."""
        try:
            return self._container.tail.val
        except AttributeError:
            return "Queue is empty."

    def size(self):
        """How big the Queue is."""
        return self._container.size_of_list
<|endoftext|>


<commit_before>#
# __COPYRIGHT__
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY
# KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

__revision__ = "__FILE__ __REVISION__ __DATE__ __DEVELOPER__"

import os
import stat
import sys

Version = "__VERSION__"

man_pages = [
    'scons.1',
    'sconsign.1',
    'scons-time.1',
]

# change to setup.py directory if it was executed from other dir
(head, tail) = os.path.split(sys.argv[0])
if head:
    os.chdir(head)
    sys.argv[0] = tail

is_win32 = 0
if not sys.platform == 'win32':
    try:
        if sys.argv[1] == 'bdist_wininst':
            is_win32 = 1
    except IndexError:
        pass
else:
    is_win32 = 1

import distutils
import distutils.core
import distutils.command.install
import distutils.command.install_data
import distutils.command.install_lib
import distutils.command.install_scripts
import distutils.command.build_scripts

_install = distutils.command.install.install
_install_data = distutils.command.install_data.install_data
_install_lib = distutils.command.install_lib.install_lib
_install_scripts = distutils.command.install_scripts.install_scripts
_build_scripts = distutils.command.build_scripts.build_scripts

class _options(object):
    pass

Options = _options()

Installed = []

def set_explicitly(name, args):
    """
    Return if the installation directory was set explicitly by the
    user on the command line.  This is complicated by the fact that
    "install --install-lib=/foo" gets turned into "install_lib
    --install-dir=/foo" internally.
    """
    if args[0] == "install_" + name:
        s = "--install-dir="
    else:
        # The command is something else (usually "install")
        s = "--install-%s=" % name
    set = 0
    length = len(s)
    for a in args[1:]:
        if a[:length] == s:
            set = 1
            break
    return set

class install(_install):
    user_options = _install.user_options + [
                    ('no-scons-script', None,
                     "don't install 'scons', only install 'scons-%s'" % Version),
                    ('no-version-script', None,
                     "don't install 'scons-%s', only install 'scons'" % Version),
                    ('install-bat', None,
                     "install 'scons.bat' script"),
                    ('no-install-bat', None,
                     "do not install 'scons.bat' script"),
                    ('install-man', None,
                     "install SCons man pages"),
                    ('no-install-man', None,
                     "do not install SCons man pages"),
                    ('standard-lib', None,
                     "install SCons library in standard Python location"),
                    ('standalone-lib', None,
                     "install SCons library in separate standalone directory"),
                    ('version-lib', None,
                     "install SCons library in version-numbered directory"),
                   ]
    boolean_options = _install.boolean_options + [
                       'no-scons-script',
                       'no-version-script',
                       'install-bat',
                       'no-install-bat',
                       'install-man',
                       'no-install-man',
                       'standard-lib',
                       'standalone-lib',
                       'version-lib'
                      ]

    if hasattr(os, 'link'):
        user_options.append(
                    ('hardlink-scons', None,
                     "hard link 'scons' to the version-numbered script, don't make a separate 'scons' copy"),
                     )
        boolean_options.append('hardlink-script')

    if hasattr(os, 'symlink'):
        user_options.append(
                    ('symlink-scons', None,
                     "make 'scons' a symbolic link to the version-numbered script, don't make a separate 'scons' copy"),
                     )
        boolean_options.append('symlink-script')

    def initialize_options(self):
        _install.initialize_options(self)
        self.no_scons_script = 0
        self.no_version_script = 0
        self.install_bat = 0
        self.no_install_bat = not is_win32
        self.install_man = 0
        self.no_install_man = is_win32
        self.standard_lib = 0
        self.standalone_lib = 0
        self.version_lib = 0
        self.hardlink_scons = 0
        self.symlink_scons = 0
        # Don't warn about having to put the library directory in the
        # search path.
        self.warn_dir = 0

    def finalize_options(self):
        _install.finalize_options(self)
        if self.install_bat:
            Options.install_bat = 1
        else:
            Options.install_bat = not self.no_install_bat
        if self.install_man:
            Options.install_man = 1
        else:
            Options.install_man = not self.no_install_man
        Options.standard_lib = self.standard_lib
        Options.standalone_lib = self.standalone_lib
        Options.version_lib = self.version_lib
        Options.install_scons_script = not self.no_scons_script
        Options.install_version_script = not self.no_version_script
        Options.hardlink_scons = self.hardlink_scons
        Options.symlink_scons = self.symlink_scons

def get_scons_prefix(libdir, is_win32):
    """
    Return the right prefix for SCons library installation.  Find
    this by starting with the library installation directory
    (.../site-packages, most likely) and crawling back up until we reach
    a directory name beginning with "python" (or "Python").
    """
    drive, head = os.path.splitdrive(libdir)
    while head:
        if head == os.sep:
            break
        head, tail = os.path.split(head)
        if tail.lower()[:6] == "python":
            # Found the Python library directory...
            if is_win32:
                # ...on Win32 systems, "scons" goes in the directory:
                #    C:\PythonXX => C:\PythonXX\scons
                return os.path.join(drive + head, tail)
            else:
                # ...on other systems, "scons" goes above the directory:
                #    /usr/lib/pythonX.X => /usr/lib/scons
                return os.path.join(drive + head)
    return libdir

def force_to_usr_local(self):
    """
    A hack to decide if we need to "force" the installation directories
    to be under /usr/local.  This is because Mac Os X Tiger and
    Leopard, by default, put the libraries and scripts in their own
    directories under /Library or /System/Library.
    """
    return (sys.platform[:6] == 'darwin' and
            (self.install_dir[:9] == '/Library/' or
             self.install_dir[:16] == '/System/Library/'))

class install_lib(_install_lib):
    def finalize_options(self):
        _install_lib.finalize_options(self)
        if force_to_usr_local(self):
            self.install_dir = '/usr/local/lib'
        args = self.distribution.script_args
        if not set_explicitly("lib", args):
            # They didn't explicitly specify the installation
            # directory for libraries...
            is_win32 = sys.platform == "win32" or args[0] == 'bdist_wininst'
            prefix = get_scons_prefix(self.install_dir, is_win32)
            if Options.standalone_lib:
                # ...but they asked for a standalone directory.
                self.install_dir = os.path.join(prefix, "scons")
            elif Options.version_lib or not Options.standard_lib:
                # ...they asked for a version-specific directory,
                # or they get it by default.
                self.install_dir = os.path.join(prefix, "scons-%s" % Version)

        msg = "Installed SCons library modules into %s" % self.install_dir
        Installed.append(msg)

class install_scripts(_install_scripts):
    def finalize_options(self):
        _install_scripts.finalize_options(self)
        if force_to_usr_local(self):
            self.install_dir = '/usr/local/bin'
        self.build_dir = os.path.join('build', 'scripts')
        msg = "Installed SCons scripts into %s" % self.install_dir
        Installed.append(msg)

    def do_nothing(self, *args, **kw):
        pass

    def hardlink_scons(self, src, dst, ver):
        try: os.unlink(dst)
        except OSError: pass
        os.link(ver, dst)

    def symlink_scons(self, src, dst, ver):
        try: os.unlink(dst)
        except OSError: pass
        os.symlink(os.path.split(ver)[1], dst)

    def copy_scons(self, src, dst, *args):
        try: os.unlink(dst)
        except OSError: pass
        self.copy_file(src, dst)
        self.outfiles.append(dst)

    def report(self, msg, args):
        # Wrapper around self.announce, used by older distutils versions.
        self.announce(msg % args)

    def run(self):
        # This "skip_build/build_scripts" block is cut-and-paste from
        # distutils.
        if not self.skip_build:
            self.run_command('build_scripts')

        # Custom SCons installation stuff.
        if Options.hardlink_scons:
            create_basename_script = self.hardlink_scons
        elif Options.symlink_scons:
            create_basename_script = self.symlink_scons
        elif Options.install_scons_script:
            create_basename_script = self.copy_scons
        else:
            create_basename_script = self.do_nothing

        if Options.install_version_script:
            create_version_script = self.copy_scons
        else:
            create_version_script = self.do_nothing

        inputs = self.get_inputs()
        bat_scripts = [x for x in inputs if x[-4:] == '.bat']
        non_bat_scripts = [x for x in inputs if x[-4:] != '.bat']

        self.outfiles = []
        self.mkpath(self.install_dir)

        for src in non_bat_scripts:
            base = os.path.basename(src)
            scons = os.path.join(self.install_dir, base)
            scons_ver = scons + '-' + Version
            create_version_script(src, scons_ver)
            create_basename_script(src, scons, scons_ver)

        if Options.install_bat:
            if is_win32:
                bat_install_dir = get_scons_prefix(self.install_dir, is_win32)
            else:
                bat_install_dir = self.install_dir
            for src in bat_scripts:
                scons_bat = os.path.join(bat_install_dir, 'scons.bat')
                scons_version_bat = os.path.join(bat_install_dir,
                                                 'scons-' + Version + '.bat')
                self.copy_scons(src, scons_bat)
                self.copy_scons(src, scons_version_bat)

        # This section is cut-and-paste from distutils, modulo being
        # able
        if os.name == 'posix':
            try: report = distutils.log.info
            except AttributeError: report = self.report
            # Set the executable bits (owner, group, and world) on
            # all the scripts we just installed.
            for file in self.get_outputs():
                if self.dry_run:
                    report("changing mode of %s", file)
                else:
                    mode = ((os.stat(file)[stat.ST_MODE]) | 0555) & 07777
                    report("changing mode of %s", file)
                    os.chmod(file, mode)

class build_scripts(_build_scripts):
    def finalize_options(self):
        _build_scripts.finalize_options(self)
        self.build_dir = os.path.join('build', 'scripts')

class install_data(_install_data):
    def initialize_options(self):
        _install_data.initialize_options(self)
    def finalize_options(self):
        _install_data.finalize_options(self)
        if force_to_usr_local(self):
            self.install_dir = '/usr/local'
        if Options.install_man:
            if is_win32:
                dir = 'Doc'
            else:
                dir = os.path.join('man', 'man1')
            self.data_files = [(dir, man_pages)]
            man_dir = os.path.join(self.install_dir, dir)
            msg = "Installed SCons man pages into %s" % man_dir
            Installed.append(msg)
        else:
            self.data_files = []

description = "Open Source next-generation build tool."

long_description = """Open Source next-generation build tool.
Improved, cross-platform substitute for the classic Make
utility.  In short, SCons is an easier, more reliable
and faster way to build software."""

scripts = [
    'script/scons',
    'script/sconsign',
    'script/scons-time',

    # We include scons.bat in the list of scripts, even on UNIX systems,
    # because we provide an option to allow it be installed explicitly,
    # for example if you're installing from UNIX on a share that's
    # accessible to Windows and you want the scons.bat.
    'script/scons.bat',
]

arguments = {
    'name'             : "scons",
    'version'          : Version,
    'description'      : description,
    'long_description' : long_description,
    'author'           : 'Steven Knight',
    'author_email'     : 'knight@baldmt.com',
    'url'              : "http://www.scons.org/",
    'packages'         : ["SCons",
                          "SCons.compat",
                          "SCons.Node",
                          "SCons.Options",
                          "SCons.Platform",
                          "SCons.Scanner",
                          "SCons.Script",
                          "SCons.Tool",
                          "SCons.Tool.MSCommon",
                          "SCons.Tool.packaging",
                          "SCons.Variables",
                         ],
    'package_dir'      : {'' : 'engine'},
    'data_files'       : [('man/man1', man_pages)],
    'scripts'          : scripts,
    'cmdclass'         : {'install'         : install,
                          'install_lib'     : install_lib,
                          'install_data'    : install_data,
                          'install_scripts' : install_scripts,
                          'build_scripts'   : build_scripts}
}

distutils.core.setup(**arguments)

if Installed:
    print '\n'.join(Installed)

# Local Variables:
# tab-width:4
# indent-tabs-mode:nil
# End:
# vim: set expandtab tabstop=4 shiftwidth=4:
<commit_msg>add NOTE about the way Python installed and why it is not importable, please review<commit_after>#
# __COPYRIGHT__
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY
# KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

"""
NOTE: Installed SCons is not importable like usual Python packages and
      is executed explicitly with command line scripts. Historically
      this was made to allow multiple SCons versions to coexist within
      single Python installation, explicit invokation was necessary to
      avoid confusion over which version of SCons is active.

      By default SCons is installed into versioned directory, e.g.
      site-packages/scons-2.1.0.alpha.20101125 and much of the stuff
      below is dedicated to make it happen on various platforms.
"""

__revision__ = "__FILE__ __REVISION__ __DATE__ __DEVELOPER__"

import os
import stat
import sys

Version = "__VERSION__"

man_pages = [
    'scons.1',
    'sconsign.1',
    'scons-time.1',
]

# change to setup.py directory if it was executed from other dir
(head, tail) = os.path.split(sys.argv[0])
if head:
    os.chdir(head)
    sys.argv[0] = tail

is_win32 = 0
if not sys.platform == 'win32':
    try:
        if sys.argv[1] == 'bdist_wininst':
            is_win32 = 1
    except IndexError:
        pass
else:
    is_win32 = 1

import distutils
import distutils.core
import distutils.command.install
import distutils.command.install_data
import distutils.command.install_lib
import distutils.command.install_scripts
import distutils.command.build_scripts

_install = distutils.command.install.install
_install_data = distutils.command.install_data.install_data
_install_lib = distutils.command.install_lib.install_lib
_install_scripts = distutils.command.install_scripts.install_scripts
_build_scripts = distutils.command.build_scripts.build_scripts

class _options(object):
    pass

Options = _options()

Installed = []

def set_explicitly(name, args):
    """
    Return if the installation directory was set explicitly by the
    user on the command line.  This is complicated by the fact that
    "install --install-lib=/foo" gets turned into "install_lib
    --install-dir=/foo" internally.
    """
    if args[0] == "install_" + name:
        s = "--install-dir="
    else:
        # The command is something else (usually "install")
        s = "--install-%s=" % name
    set = 0
    length = len(s)
    for a in args[1:]:
        if a[:length] == s:
            set = 1
            break
    return set

class install(_install):
    user_options = _install.user_options + [
                    ('no-scons-script', None,
                     "don't install 'scons', only install 'scons-%s'" % Version),
                    ('no-version-script', None,
                     "don't install 'scons-%s', only install 'scons'" % Version),
                    ('install-bat', None,
                     "install 'scons.bat' script"),
                    ('no-install-bat', None,
                     "do not install 'scons.bat' script"),
                    ('install-man', None,
                     "install SCons man pages"),
                    ('no-install-man', None,
                     "do not install SCons man pages"),
                    ('standard-lib', None,
                     "install SCons library in standard Python location"),
                    ('standalone-lib', None,
                     "install SCons library in separate standalone directory"),
                    ('version-lib', None,
                     "install SCons library in version-numbered directory"),
                   ]
    boolean_options = _install.boolean_options + [
                       'no-scons-script',
                       'no-version-script',
                       'install-bat',
                       'no-install-bat',
                       'install-man',
                       'no-install-man',
                       'standard-lib',
                       'standalone-lib',
                       'version-lib'
                      ]

    if hasattr(os, 'link'):
        user_options.append(
                    ('hardlink-scons', None,
                     "hard link 'scons' to the version-numbered script, don't make a separate 'scons' copy"),
                     )
        boolean_options.append('hardlink-script')

    if hasattr(os, 'symlink'):
        user_options.append(
                    ('symlink-scons', None,
                     "make 'scons' a symbolic link to the version-numbered script, don't make a separate 'scons' copy"),
                     )
        boolean_options.append('symlink-script')

    def initialize_options(self):
        _install.initialize_options(self)
        self.no_scons_script = 0
        self.no_version_script = 0
        self.install_bat = 0
        self.no_install_bat = not is_win32
        self.install_man = 0
        self.no_install_man = is_win32
        self.standard_lib = 0
        self.standalone_lib = 0
        self.version_lib = 0
        self.hardlink_scons = 0
        self.symlink_scons = 0
        # Don't warn about having to put the library directory in the
        # search path.
        self.warn_dir = 0

    def finalize_options(self):
        _install.finalize_options(self)
        if self.install_bat:
            Options.install_bat = 1
        else:
            Options.install_bat = not self.no_install_bat
        if self.install_man:
            Options.install_man = 1
        else:
            Options.install_man = not self.no_install_man
        Options.standard_lib = self.standard_lib
        Options.standalone_lib = self.standalone_lib
        Options.version_lib = self.version_lib
        Options.install_scons_script = not self.no_scons_script
        Options.install_version_script = not self.no_version_script
        Options.hardlink_scons = self.hardlink_scons
        Options.symlink_scons = self.symlink_scons

def get_scons_prefix(libdir, is_win32):
    """
    Return the right prefix for SCons library installation.  Find
    this by starting with the library installation directory
    (.../site-packages, most likely) and crawling back up until we reach
    a directory name beginning with "python" (or "Python").
    """
    drive, head = os.path.splitdrive(libdir)
    while head:
        if head == os.sep:
            break
        head, tail = os.path.split(head)
        if tail.lower()[:6] == "python":
            # Found the Python library directory...
            if is_win32:
                # ...on Win32 systems, "scons" goes in the directory:
                #    C:\PythonXX => C:\PythonXX\scons
                return os.path.join(drive + head, tail)
            else:
                # ...on other systems, "scons" goes above the directory:
                #    /usr/lib/pythonX.X => /usr/lib/scons
                return os.path.join(drive + head)
    return libdir

def force_to_usr_local(self):
    """
    A hack to decide if we need to "force" the installation directories
    to be under /usr/local.  This is because Mac Os X Tiger and
    Leopard, by default, put the libraries and scripts in their own
    directories under /Library or /System/Library.
    """
    return (sys.platform[:6] == 'darwin' and
            (self.install_dir[:9] == '/Library/' or
             self.install_dir[:16] == '/System/Library/'))

class install_lib(_install_lib):
    def finalize_options(self):
        _install_lib.finalize_options(self)
        if force_to_usr_local(self):
            self.install_dir = '/usr/local/lib'
        args = self.distribution.script_args
        if not set_explicitly("lib", args):
            # They didn't explicitly specify the installation
            # directory for libraries...
            is_win32 = sys.platform == "win32" or args[0] == 'bdist_wininst'
            prefix = get_scons_prefix(self.install_dir, is_win32)
            if Options.standalone_lib:
                # ...but they asked for a standalone directory.
                self.install_dir = os.path.join(prefix, "scons")
            elif Options.version_lib or not Options.standard_lib:
                # ...they asked for a version-specific directory,
                # or they get it by default.
                self.install_dir = os.path.join(prefix, "scons-%s" % Version)

        msg = "Installed SCons library modules into %s" % self.install_dir
        Installed.append(msg)

class install_scripts(_install_scripts):
    def finalize_options(self):
        _install_scripts.finalize_options(self)
        if force_to_usr_local(self):
            self.install_dir = '/usr/local/bin'
        self.build_dir = os.path.join('build', 'scripts')
        msg = "Installed SCons scripts into %s" % self.install_dir
        Installed.append(msg)

    def do_nothing(self, *args, **kw):
        pass

    def hardlink_scons(self, src, dst, ver):
        try: os.unlink(dst)
        except OSError: pass
        os.link(ver, dst)

    def symlink_scons(self, src, dst, ver):
        try: os.unlink(dst)
        except OSError: pass
        os.symlink(os.path.split(ver)[1], dst)

    def copy_scons(self, src, dst, *args):
        try: os.unlink(dst)
        except OSError: pass
        self.copy_file(src, dst)
        self.outfiles.append(dst)

    def report(self, msg, args):
        # Wrapper around self.announce, used by older distutils versions.
        self.announce(msg % args)

    def run(self):
        # This "skip_build/build_scripts" block is cut-and-paste from
        # distutils.
        if not self.skip_build:
            self.run_command('build_scripts')

        # Custom SCons installation stuff.
        if Options.hardlink_scons:
            create_basename_script = self.hardlink_scons
        elif Options.symlink_scons:
            create_basename_script = self.symlink_scons
        elif Options.install_scons_script:
            create_basename_script = self.copy_scons
        else:
            create_basename_script = self.do_nothing

        if Options.install_version_script:
            create_version_script = self.copy_scons
        else:
            create_version_script = self.do_nothing

        inputs = self.get_inputs()
        bat_scripts = [x for x in inputs if x[-4:] == '.bat']
        non_bat_scripts = [x for x in inputs if x[-4:] != '.bat']

        self.outfiles = []
        self.mkpath(self.install_dir)

        for src in non_bat_scripts:
            base = os.path.basename(src)
            scons = os.path.join(self.install_dir, base)
            scons_ver = scons + '-' + Version
            create_version_script(src, scons_ver)
            create_basename_script(src, scons, scons_ver)

        if Options.install_bat:
            if is_win32:
                bat_install_dir = get_scons_prefix(self.install_dir, is_win32)
            else:
                bat_install_dir = self.install_dir
            for src in bat_scripts:
                scons_bat = os.path.join(bat_install_dir, 'scons.bat')
                scons_version_bat = os.path.join(bat_install_dir,
                                                 'scons-' + Version + '.bat')
                self.copy_scons(src, scons_bat)
                self.copy_scons(src, scons_version_bat)

        # This section is cut-and-paste from distutils, modulo being
        # able
        if os.name == 'posix':
            try: report = distutils.log.info
            except AttributeError: report = self.report
            # Set the executable bits (owner, group, and world) on
            # all the scripts we just installed.
            for file in self.get_outputs():
                if self.dry_run:
                    report("changing mode of %s", file)
                else:
                    mode = ((os.stat(file)[stat.ST_MODE]) | 0555) & 07777
                    report("changing mode of %s", file)
                    os.chmod(file, mode)

class build_scripts(_build_scripts):
    def finalize_options(self):
        _build_scripts.finalize_options(self)
        self.build_dir = os.path.join('build', 'scripts')

class install_data(_install_data):
    def initialize_options(self):
        _install_data.initialize_options(self)
    def finalize_options(self):
        _install_data.finalize_options(self)
        if force_to_usr_local(self):
            self.install_dir = '/usr/local'
        if Options.install_man:
            if is_win32:
                dir = 'Doc'
            else:
                dir = os.path.join('man', 'man1')
            self.data_files = [(dir, man_pages)]
            man_dir = os.path.join(self.install_dir, dir)
            msg = "Installed SCons man pages into %s" % man_dir
            Installed.append(msg)
        else:
            self.data_files = []

description = "Open Source next-generation build tool."

long_description = """Open Source next-generation build tool.
Improved, cross-platform substitute for the classic Make
utility.  In short, SCons is an easier, more reliable
and faster way to build software."""

scripts = [
    'script/scons',
    'script/sconsign',
    'script/scons-time',

    # We include scons.bat in the list of scripts, even on UNIX systems,
    # because we provide an option to allow it be installed explicitly,
    # for example if you're installing from UNIX on a share that's
    # accessible to Windows and you want the scons.bat.
    'script/scons.bat',
]

arguments = {
    'name'             : "scons",
    'version'          : Version,
    'description'      : description,
    'long_description' : long_description,
    'author'           : 'Steven Knight',
    'author_email'     : 'knight@baldmt.com',
    'url'              : "http://www.scons.org/",
    'packages'         : ["SCons",
                          "SCons.compat",
                          "SCons.Node",
                          "SCons.Options",
                          "SCons.Platform",
                          "SCons.Scanner",
                          "SCons.Script",
                          "SCons.Tool",
                          "SCons.Tool.MSCommon",
                          "SCons.Tool.packaging",
                          "SCons.Variables",
                         ],
    'package_dir'      : {'' : 'engine'},
    'data_files'       : [('man/man1', man_pages)],
    'scripts'          : scripts,
    'cmdclass'         : {'install'         : install,
                          'install_lib'     : install_lib,
                          'install_data'    : install_data,
                          'install_scripts' : install_scripts,
                          'build_scripts'   : build_scripts}
}

distutils.core.setup(**arguments)

if Installed:
    print '\n'.join(Installed)

# Local Variables:
# tab-width:4
# indent-tabs-mode:nil
# End:
# vim: set expandtab tabstop=4 shiftwidth=4:
<|endoftext|>


<commit_before>import setuptools

setuptools.setup(
    name="nycdb",
    version="0.1.20",
    url="https://github.com/aepyornis/nyc-db",

    author="ziggy",
    author_email="nycdb@riseup.net",

    license='AGPL-3.0-or-later',

    description="database of nyc housing data",
    long_description=open('README.md').read(),

    entry_points={
        'console_scripts': [
            'nycdb=nycdb.cli:main'
        ],
    },

    packages=['nycdb'],

    package_data={
        'nycdb': [
            'datasets/*.yml',
            'sql/*.sql',
            'sql/**/*.sql'
        ]
    },

    include_package_data=True,

    python_requires='>=3',

    install_requires=[
        'PyYAML>=5.1',
        'requests>=2.18',
        'xlrd>=1.1.0',
        'pyproj>=2.1.3',
        'psycopg2>=2.7',
        'tqdm>=4.28.1'
    ],

    classifiers=[
        'Development Status :: 3 - Alpha',
        'License :: OSI Approved :: GNU Affero General Public License v3 or later (AGPLv3+)',
        'Programming Language :: Python :: 3 :: Only',
        'Programming Language :: Python :: 3.6',
        'Programming Language :: Python :: 3.7',
    ]
)
<commit_msg>0.1.21<commit_after>import setuptools

setuptools.setup(
    name="nycdb",
    version="0.1.21",
    url="https://github.com/aepyornis/nyc-db",

    author="ziggy",
    author_email="nycdb@riseup.net",

    license='AGPL-3.0-or-later',

    description="database of nyc housing data",
    long_description=open('README.md').read(),

    entry_points={
        'console_scripts': [
            'nycdb=nycdb.cli:main'
        ],
    },

    packages=['nycdb'],

    package_data={
        'nycdb': [
            'datasets/*.yml',
            'sql/*.sql',
            'sql/**/*.sql'
        ]
    },

    include_package_data=True,

    python_requires='>=3',

    install_requires=[
        'PyYAML>=5.1',
        'requests>=2.18',
        'xlrd>=1.1.0',
        'pyproj>=2.1.3',
        'psycopg2>=2.7',
        'tqdm>=4.28.1'
    ],

    classifiers=[
        'Development Status :: 3 - Alpha',
        'License :: OSI Approved :: GNU Affero General Public License v3 or later (AGPLv3+)',
        'Programming Language :: Python :: 3 :: Only',
        'Programming Language :: Python :: 3.6',
        'Programming Language :: Python :: 3.7',
    ]
)
<|endoftext|>


<commit_before>from distutils.core import setup

setup(
    name='UberCarrot',
    version='0.1a1',
    packages=['caspartalk'],
    package_dir={'caspartalk': 'caspartalk'},
    url='',
    license='',
    author='Callum McLean',
    author_email='calmcl1@aol.com',
    description=''
)
<commit_msg>That's not how setup.py works<commit_after>from distutils.core import setup

setup(
    name='UberCarrot',
    version='0.1a1',
    packages=['caspartalk'],
    package_dir={'', 'src'},
    url='',
    license='',
    author='Callum McLean',
    author_email='calmcl1@aol.com',
    description=''
)
<|endoftext|>


<commit_before># Copyright 2015 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS-IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

"""Python Cloud Debugger build and packaging script."""

import ConfigParser
from glob import glob
import os
import re
from distutils import sysconfig
from setuptools import Extension
from setuptools import setup

def RemovePrefixes(optlist, bad_prefixes):
  for bad_prefix in bad_prefixes:
    for i, flag in enumerate(optlist):
      if flag.startswith(bad_prefix):
        optlist.pop(i)
        break
  return optlist

def ReadConfig(section, value, default):
  try:
    config = ConfigParser.ConfigParser()
    config.read('setup.cfg')
    return config.get(section, value)
  except:  # pylint: disable=bare-except
    return default

LONG_DESCRIPTION = (
    'The Cloud Debugger lets you inspect the state of an application at any\n'
    'code location without stopping or slowing it down. The debugger makes it\n'
    'easier to view the application state without adding logging statements.\n'
    '\n'
    'For more details please see '
    'https://github.com/GoogleCloudPlatform/cloud-debug-python\n')

lib_dirs = ReadConfig('build_ext',
                      'library_dirs',
                      sysconfig.get_config_var('LIBDIR')).split(':')
extra_compile_args = ReadConfig('cc_options', 'extra_compile_args', '').split()
extra_link_args = ReadConfig('cc_options', 'extra_link_args', '').split()

static_libs = []
deps = ['libgflags.a', 'libglog.a']
for dep in deps:
  for lib_dir in lib_dirs:
    path = os.path.join(lib_dir, dep)
    if os.path.isfile(path):
      static_libs.append(path)
assert len(static_libs) == len(deps), (static_libs, deps, lib_dirs)

cvars = sysconfig.get_config_vars()
cvars['OPT'] = str.join(' ', RemovePrefixes(
    cvars.get('OPT').split(),
    ['-g', '-O', '-Wstrict-prototypes']))

# Determine the current version of the package. The easiest way would be to
# import "googleclouddebugger" and read its __version__ attribute.
# Unfortunately we can't do that because "googleclouddebugger" depends on
# "cdbg_native" that hasn't been built yet.
version = None
with open('googleclouddebugger/__init__.py', 'r') as init_file:
  version_pattern = re.compile(r"^\s*__version__\s*=\s*'([0-9.]*)'")
  for line in init_file:
    match = version_pattern.match(line)
    if match:
      version = match.groups()[0]
print 'clouddebugger module version is {0}'.format(version)
assert version

cdbg_native_module = Extension(
    'googleclouddebugger.cdbg_native',
    sources=glob('googleclouddebugger/*.cc'),
    extra_compile_args=[
        '-std=c++0x',
        '-Werror',
        '-g0',
        '-O3',
    ] + extra_compile_args,
    extra_link_args=static_libs + extra_link_args,
    libraries=['rt'])

setup(
    name='google-python-cloud-debugger',
    description='Python Cloud Debugger',
    long_description=LONG_DESCRIPTION,
    url='https://github.com/GoogleCloudPlatform/cloud-debug-python',
    author='Google Inc.',
    version=version,
    install_requires=['google-api-python-client'],
    packages=['googleclouddebugger'],
    ext_modules=[cdbg_native_module],
    license='Apache License, Version 2.0',
    keywords='google cloud debugger',
    classifiers=[
        'Programming Language :: Python :: 2.7',
        'Development Status :: 3 - Alpha',
        'Intended Audience :: Developers'
    ])
<commit_msg>Remove unnecessary print statement ------------- Created by MOE: https://github.com/google/moe MOE_MIGRATED_REVID=114444841<commit_after># Copyright 2015 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS-IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

"""Python Cloud Debugger build and packaging script."""

import ConfigParser
from glob import glob
import os
import re
from distutils import sysconfig
from setuptools import Extension
from setuptools import setup

def RemovePrefixes(optlist, bad_prefixes):
  for bad_prefix in bad_prefixes:
    for i, flag in enumerate(optlist):
      if flag.startswith(bad_prefix):
        optlist.pop(i)
        break
  return optlist

def ReadConfig(section, value, default):
  try:
    config = ConfigParser.ConfigParser()
    config.read('setup.cfg')
    return config.get(section, value)
  except:  # pylint: disable=bare-except
    return default

LONG_DESCRIPTION = (
    'The Cloud Debugger lets you inspect the state of an application at any\n'
    'code location without stopping or slowing it down. The debugger makes it\n'
    'easier to view the application state without adding logging statements.\n'
    '\n'
    'For more details please see '
    'https://github.com/GoogleCloudPlatform/cloud-debug-python\n')

lib_dirs = ReadConfig('build_ext',
                      'library_dirs',
                      sysconfig.get_config_var('LIBDIR')).split(':')
extra_compile_args = ReadConfig('cc_options', 'extra_compile_args', '').split()
extra_link_args = ReadConfig('cc_options', 'extra_link_args', '').split()

static_libs = []
deps = ['libgflags.a', 'libglog.a']
for dep in deps:
  for lib_dir in lib_dirs:
    path = os.path.join(lib_dir, dep)
    if os.path.isfile(path):
      static_libs.append(path)
assert len(static_libs) == len(deps), (static_libs, deps, lib_dirs)

cvars = sysconfig.get_config_vars()
cvars['OPT'] = str.join(' ', RemovePrefixes(
    cvars.get('OPT').split(),
    ['-g', '-O', '-Wstrict-prototypes']))

# Determine the current version of the package. The easiest way would be to
# import "googleclouddebugger" and read its __version__ attribute.
# Unfortunately we can't do that because "googleclouddebugger" depends on
# "cdbg_native" that hasn't been built yet.
version = None
with open('googleclouddebugger/__init__.py', 'r') as init_file:
  version_pattern = re.compile(r"^\s*__version__\s*=\s*'([0-9.]*)'")
  for line in init_file:
    match = version_pattern.match(line)
    if match:
      version = match.groups()[0]
assert version

cdbg_native_module = Extension(
    'googleclouddebugger.cdbg_native',
    sources=glob('googleclouddebugger/*.cc'),
    extra_compile_args=[
        '-std=c++0x',
        '-Werror',
        '-g0',
        '-O3',
    ] + extra_compile_args,
    extra_link_args=static_libs + extra_link_args,
    libraries=['rt'])

setup(
    name='google-python-cloud-debugger',
    description='Python Cloud Debugger',
    long_description=LONG_DESCRIPTION,
    url='https://github.com/GoogleCloudPlatform/cloud-debug-python',
    author='Google Inc.',
    version=version,
    install_requires=['google-api-python-client'],
    packages=['googleclouddebugger'],
    ext_modules=[cdbg_native_module],
    license='Apache License, Version 2.0',
    keywords='google cloud debugger',
    classifiers=[
        'Programming Language :: Python :: 2.7',
        'Development Status :: 3 - Alpha',
        'Intended Audience :: Developers'
    ])
<|endoftext|>


<commit_before>from bisect import bisect as bis

def shift(a, beg, end):
    p = end
    while p > beg:
        a[p] = a[p - 1]
        p -= 1

n = int(input())
arr = list(map(int, input().split()))
for i in range(1, n):
    el = arr[i]
    ins = bis(arr[:i], el)
    shift(arr, ins, i)
    arr[ins] = el
print(*arr
<commit_msg>Task B corrected.<commit_after>from bisect import bisect as bis

def shift(a, beg, end):
    p = end
    while p > beg:
        a[p] = a[p - 1]
        p -= 1

n = int(input())
arr = list(map(int, input().split()))
for i in range(1, n):
    el = arr[i]
    ins = bis(arr[:i], el)
    shift(arr, ins, i)
    arr[ins] = el
print(*arr)
<|endoftext|>


<commit_before>"""Implementations of the possible states for a robot."""

import time

from matrix import matrix

class BaseState(object):

	def __init__(self, robot):
		self.robot = robot
		self.is_oriented = False  # wut?  states aren't oriented.  robots are.

	def run(self, *args, **kwargs):
		raise NotImplementedError()

class CorridorState(BaseState):
	"""Actions for proceeding down a corridor.

	This algorithm uses proportional-differential control to follow the
	reference trajectory (centerline of the corridor).
	"""

	MOVE_DURATION = 1  # seconds of movement before the next sensor measurement
	SENSOR_ANGLES = {
		'L': 300,  # default angle for sensing to the left
		'R': 60    # default angle for sensing to the right
	}
	TAU_P = 0.2
	TAU_D = 1.0

	def _sense_initial_position(self):
		"""Learn about this corridor and our place in it.

		Returns a tuple (x, y), where:
			x is the total width of the corridor in cm.
			y is the displacement from the corridor center in cm.  Positive
				displacement indicates a position left of center.
		"""

		right_dist = self.robot.sense(x=90)
		left_dist = self.robot.sense(x=270)
		width = right_dist + left_dist

		return (width / 2.0 - left_dist, width)

	def run(self, *args, **kwargs):
		print 'Running CorridorState'

		# Ensure the robot is stopped
		self.robot.stop()

		# TODO: orient the robot, if is_oriented is False.
		# Until then, assume the robot is centered and aligned on the corridor.
		self.is_oriented = True

		# Sense the cross-track error and width of the corridor:
		last_cte, width = self._sense_initial_position()
		print 'Corridor width: {0}'.format(width)
		if last_cte > 0:
			sensor_side = 'L'
		else:
			sensor_side = 'R'

		# Start the robot
		self.robot.fwd()

		# True when a new (non-corridor) state is detected
		new_state = False

		while not new_state:

			# Sense new cte
			angle = self.SENSOR_ANGLES[sensor_side]
			dist = self.robot.sense(x=angle)
			if sensor_side == 'R':
				new_cte = dist - width / 2.0
			else:
				new_cte = width / 2.0 - dist

			# Check for new state
			# TODO: sense logic for state change detection

			# Adjust steering
			steering_factor = -self.TAU_P * new_cte - self.TAU_D * (new_cte - last_cte)
			self.robot.steer(steering_factor)
			last_cte = new_cte

			# Set sensor side to the wall that the robot is steering toward
			if steering_factor > 0:
				pass #sensor_side = 'L'
			else:
				pass #sensor_side = 'R'

			# Pause for delay period:
			time.sleep(self.MOVE_DURATION)

			# Print debug data
			print sensor_side, dist, last_cte, steering_factor
<commit_msg>Detect emerging from the corridor (naive).<commit_after>"""Implementations of the possible states for a robot."""

import time

from matrix import matrix

class BaseState(object):

	def __init__(self, robot):
		self.robot = robot
		self.is_oriented = False  # wut?  states aren't oriented.  robots are.

	def run(self, *args, **kwargs):
		raise NotImplementedError()

class CorridorState(BaseState):
	"""Actions for proceeding down a corridor.

	This algorithm uses proportional-differential control to follow the
	reference trajectory (centerline of the corridor).
	"""

	MOVE_DURATION = 1  # seconds of movement before the next sensor measurement
	SENSOR_ANGLES = {
		'L': 300,  # default angle for sensing to the left
		'R': 60    # default angle for sensing to the right
	}
	TAU_P = 0.2
	TAU_D = 1.0

	def _sense_initial_position(self):
		"""Learn about this corridor and our place in it.

		Returns a tuple (x, y), where:
			x is the total width of the corridor in cm.
			y is the displacement from the corridor center in cm.  Positive
				displacement indicates a position left of center.
		"""

		right_dist = self.robot.sense(x=90)
		left_dist = self.robot.sense(x=270)
		width = right_dist + left_dist

		return (width / 2.0 - left_dist, width)

	def run(self, *args, **kwargs):
		print 'Running CorridorState'

		# Ensure the robot is stopped
		self.robot.stop()

		# TODO: orient the robot, if is_oriented is False.
		# Until then, assume the robot is centered and aligned on the corridor.
		self.is_oriented = True

		# Sense the cross-track error and width of the corridor:
		last_cte, width = self._sense_initial_position()
		print 'Corridor width: {0}'.format(width)
		if last_cte > 0:
			sensor_side = 'L'
		else:
			sensor_side = 'R'

		# Start the robot
		self.robot.fwd()

		while True:

			# Sense new cte
			angle = self.SENSOR_ANGLES[sensor_side]
			dist = self.robot.sense(x=angle)
			if sensor_side == 'R':
				new_cte = dist - width / 2.0
			else:
				new_cte = width / 2.0 - dist

			# Check for new state
			# TODO: expand this to check straight ahead and opposite side
			if new_cte > width:
				break

			# Adjust steering
			steering_factor = -self.TAU_P * new_cte - self.TAU_D * (new_cte - last_cte)
			self.robot.steer(steering_factor)
			last_cte = new_cte

			# Set sensor side to the wall that the robot is steering toward
			if steering_factor > 0:
				pass #sensor_side = 'L'
			else:
				pass #sensor_side = 'R'

			# Pause for delay period:
			time.sleep(self.MOVE_DURATION)

			# Print debug data
			print sensor_side, dist, last_cte, steering_factor
<|endoftext|>