Пример #1
0
def getName(originalItem):
    '''
	Asks user to enter name of new lab, and check that the name is not already used

	Args:
		originalItem (pjlDB._LabItem) individual lab item generated by pjlDB

	Return: 
		labName (str) name of new lab
	'''
    labName = originalItem.name
    if originalItem.name == "":
        validName = False
        while not validName:
            labName = str(
                input(
                    color.yellow(
                        "Enter name of the new lab. Please use conventional titlecase (ie. This is a Title of a New Lab): "
                    )))
            if input(color.yellow(
                    "Is this name entered correctly? N/y: ")).lower() == "y":
                validName = True
            elif input(color.yellow(
                    "Would you like to try again? Y/n ")).lower() == "n":
                print("Exiting.")
                exit()
    return labName
Пример #2
0
def render_noose(count=0):
    noose = " "
    head = " "
    left_arm = " "
    torso = " "
    right_arm = " "
    left_leg = " "
    right_left = " "

    if count > 0:
        noose = "|"
    if count > 1:
        head = magenta("0")
    if count > 2:
        left_arm = yellow("/")
    if count > 3:
        torso = yellow("|")
    if count > 4:
        right_arm = yellow("\\")
    if count > 5:
        left_leg = cyan("/")
    if count > 6:
        right_left = cyan("\\")
        head = magenta("X")

    top_row = "   +---+"
    noose_row = str.format("\n   %s   |" % noose)
    head_row = str.format("\n   %s   |" % head)
    torso_row = str.format("\n  %s%s%s  |" % (left_arm, torso, right_arm))
    leg_row = str.format("\n  %s %s  |" % (left_leg, right_left))
    bottom_row = "\n       |\n==========\n"

    print(top_row + noose_row + head_row + torso_row + leg_row + bottom_row)
Пример #3
0
def getNewTopic(topicSource, masterList):
    '''
	Get list of topics from user and check if they are valid

	Args: 
		topicSource (string) path to file containing list of disciplines
		masterList (list) complete pool of valid topics

	Return:
		topics (str) single valid topic
	'''
    valid = False
    while not valid:
        item = input(color.yellow("Enter new topic: "))
        for i in masterList:
            if i.replace("'", "").lower() == item.replace("'", "").lower():
                valid = True
                item = i
                print(item)
                print("Adding " + i + " to topics")
                print("")
        if not valid:
            print(color.cyan(item + " is an invalid topic."))
            if not input(color.yellow(
                    "Would you like to try again? Y/n ")).lower() == "n":
                continue
            else:
                break
    return item
Пример #4
0
def confirmEntry(new_version):
    '''
	print out what information entered by usee, and asks for confirmation

	Args:
		new_version (dict) dictionary containing all data in for that pjlDB can enter into database

	Return:
		(bool) True if information has been confirmed by user
	'''
    print("")

    print(
        color.yellow("Please confirm that the information entered is correct"))
    print("lab id: " + new_version["idnum"])
    print("name: " + new_version["name"])
    print("type: " + new_version["type"])
    print("original Directory: " + new_version["originalDir"])
    print("course: " + new_version["course"])
    print("semester: " + new_version["semester"])
    print("year: " + new_version["year"])
    print("directory: " + new_version["directory"])
    print("path: " + new_version["path"])
    print("equipment: ")
    printList(new_version["equipment"])
    print("disciplines: ")
    printList(new_version["disciplines"])
    print("topics: ")
    printList(new_version["topics"])
    if not input(
            color.yellow("Is this information correct? N/y: ")).lower() == "y":
        print("exiting...")
        exit()
Пример #5
0
def getNewSoftware(masterList):
    '''
	Get list of software from user and check if they are valid

	Args: 
		masterList (list) complete pool of valid topics

	Return:
		software (str) single valid software for new lab
	'''
    valid = False
    while not valid:
        item = input(color.yellow("Enter new software: "))
        for i in masterList:
            if i.lower() == item.lower():
                valid = True
                item = i
                print("Adding " + i + " to software")
                print("")
        if not valid:
            print(color.cyan(item + " is invalid software."))
            if not input(color.yellow(
                    "Would you like to try again? Y/n ")).lower() == "n":
                continue
            else:
                break
    return item
Пример #6
0
def displayLabItem(lab):
    print("")
    print(
        color.yellow(
            "Please confirm that the information entered is correct."))
    print("-------------------------------------------------------")
    print("lab id: " + lab.id_num)
    print("")
    print("name: " + lab.name)
    print("")
    print("type: " + lab.lab_type)
    print("")
    print("equipment: ")
    print("----------")
    printEquipList(lab.equipment)
    print("")
    print("disciplines: ")
    printList(lab.disciplines)
    print("topics: ")
    printList(lab.topics)
    if input(
            color.yellow("Is this information correct? N/y: ")).lower() == "y":
        return True
    else:
        print("exiting...")
        return
        exit()
Пример #7
0
 def print_context(self):
     #pykd.dbgCommand('.cls')
     self.context.update_regs()
     pykd.dprintln(color.yellow("[------ Register --------------------------------------------------------------------------------------------]"), dml=True)
     self.print_regs()
     pykd.dprintln(color.yellow("[------ Code ------------------------------------------------------------------------------------------------]"), dml=True)
     self.print_code()
     pykd.dprintln(color.yellow("[------ Stack -----------------------------------------------------------------------------------------------]"), dml=True)
     self.print_stack()
     pykd.dprintln(color.yellow("[------------------------------------------------------------------------------------------------------------]"), dml=True)
Пример #8
0
def equipNameOptions(item):
    '''
	Sometimes a piece of a equipment is a piece of the kit. In these cases it can be useful for the name
	in the equipment list to appear as the part, but keep the equipment id number of the kit. This function
	allows the user to choose a name from the list of components in a kit.

	Args:
		item (pjlDB.EquipDB) entire equipment inventory database object generated by pjlDB

	Return:
		name (str) Name of equipment item
	'''
    if debug: print(color.green("[Debug - equipNameOptions]  entering"))
    print()
    print(
        color.yellow(
            "What name you would like displayed for this item? Pick a number [default = 0]."
        ))
    print()
    #	print("[0] " + item.name)

    kitItems = item.kit.split(",")
    kitItems[:0] = [item.name]
    for i in range(0, len(kitItems)):
        index = str(i)
        print("[" + index + "] " + kitItems[i].strip())
    validName = False
    while not validName:
        #selection = int(input(color.yellow("Please Choose a Name for This Item? [0] ")))
        selection = input(
            color.yellow("Please Choose a Name for This Item? [0] "))
        if selection == "":
            selection = 0
        elif selection.isdigit():
            selection = int(selection)
        #else
        #print(selection)

        if debug:
            print(
                color.green("[Debug - equipNameOptions] selection " +
                            str(selection)))
        #if 1 <= selection <= len(kitItems) + 1:
        if 0 <= selection <= len(kitItems):
            name = kitItems[selection].strip()
            validName = True
        elif selection == 0:
            name = item.name
            validName = True
        else:
            print(selection + " is not a option.")
            if input(color.yellow(
                    "Do you wish to try again? Y/n: ")).lower() == "n":
                exit()
    return name
Пример #9
0
def cmpTwoLogDir(logPath1,logPath2,dataCardNames):
    if not(os.path.isdir(logPath1)):
        print color.red('Log directory ' + logPath1 + ' does not exist - EXIT!')
        sys.exit(1)
    if not(os.path.isdir(logPath2)):
        print color.red('Log directory ' + logPath2 + ' does not exist - EXIT!')
        sys.exit(1)
    logFiles = []
    for card in dataCardNames:
        logFiles.append(card+'.log')
    cmps = filecmp.cmpfiles(logPath1,logPath2,logFiles)
    print color.green('=====================================================')
    print color.green('Files which are the same:')
    for file in cmps[0]:
        print color.green(file)
    print color.green('=====================================================')
    print
    print color.red('=====================================================')
    print color.red('Files which are NOT the same:')
    for file in cmps[1]:
        print color.red(file)
    print color.red('=====================================================')
    print
    print color.yellow('=====================================================')
    print color.yellow('Files which script was not able to compare:')
    for file in cmps[2]:
        print color.yellow(file)
    print color.yellow('=====================================================')
    print
Пример #10
0
def getLabObject(labdb):
    '''
	Used to generate a pjl lab object from the labDB.xml database

	Args:
		labdb (pjlDB.labDB) entire lab database object generated by pjlDB

	Return:
		lab (pjlDB._LabItem) individual lab item generated by pjlDB
	'''
    if debug: print(color.green("[Debug - getLabObject] entering"))
    validID = False
    while not validID:
        idnum = input(color.yellow("Enter lab ID number: "))
        if len(idnum) == 4 and idnum.isdigit() == True:
            try:
                lab = labdb.getLab(idnum)
                validID = True
            except pjlDB.IDDoesNotExist:  ### not working properly
                print("Message")
        else:
            print(
                color.red("[ERROR] ") +
                "ID formate in not valid. Valid IDs are of the form ####. Please try again"
            )
            validID = False
    if debug: print(color.green("[Debug - getLabObject] leaving"))
    return lab
Пример #11
0
def moveVersionDir(info, root):
    '''
	adds source file to lab repository.
		Makes new directory
		rsyncs files except for contents of Support_Docs folder

	Args:
		info (dict) information about new lab object
		root (str) root path of lab repository

	Return:
		none
	'''
    versionDir = root + info["directory"]
    if not os.path.isdir(versionDir):
        os.system("mkdir " + versionDir)
        #os.system("echo rsync -avz --exclude Support_Docs " + info["originalDir"] + " " + versionDir)
        os.system("sudo rsync -avz --exclude Support_Docs " +
                  info["originalDir"] + " " + versionDir)
    else:
        print("")
        print(color.cyan("Lab folder " + versionDir + " Already Exists."))
        print("")
        if input(
                color.yellow("Do you want to update the folder contents? N/y: "
                             )).lower() == "y":
            print("")
            os.system("rsync -avz --exclude Support_Docs " +
                      info["originalDir"] + " " + versionDir)
        else:
            print("Exiting...")
            exit()
Пример #12
0
 def _format_review(self):
     if not self.reviews['reviews']:
         return ''
     review = self.reviews['reviews'][self._current_review]
     return '%s\n User: %s\n Rating: %s\n Review: %s\n' % (
         color.green('Review'), color.cyan(review['user']['name']),
         color.yellow('*' * review['rating']), review['excerpt'])
def test_combination():
    print
    tpl = color.green('the quick {} jump over the {} dog')
    f = tpl.format(
        color.yellow('brown fox'),
        color.red_bg('lazy'),
    )
    print repr(f)
    print f

    tpl = color.green_bg('the quick {} jump over the {} dog')
    f = tpl.format(
        color.yellow('brown fox'),
        color.red_bg('lazy'),
    )
    print repr(f)
    print f
Пример #14
0
def TWindbg(args):
    """TWindbg: List all the command in TWindbg """
    if len(args) != 0:
        raise CmdExecError("Invalid argument number")
    banner = color.yellow("TWindbg: PEDA-like debugger UI for WinDbg\n")
    banner += color.gray("For latest update, check the project page: ")
    banner += color.white("https://github.com/bruce30262/TWindbg\n")
    banner += color.orange("Use \"[cmd] help\" for further command usage\n")
    pykd.dprintln(banner, dml=True)
    print_all_usage()
Пример #15
0
def getTopicList(originalItem, topicSource):
    '''
	generates a list of topics

	Args:
		originalItem (pjlDB._LabItem) individual lab item generated by pjlDB
		topicSource (string) path to file containing list of topics

	Return:
		topicItems (list) valid topics
	'''
    topicItems = []
    if input(
            color.yellow(
                "Would you like to edit the topics list for this lab? y/N ")
    ).lower() == "y":
        print("")
        print("Current Topics")
        print("-------------------")
        for i in originalItem.topics:
            print(i)
        print("")
        topicItems = []
        topicItems = topicRemove(originalItem)
        print("")
        allItems = False
        while not allItems:
            if input(
                    color.yellow(
                        "Would you like to add a new topic for this lab? y/N ")
            ).lower() == "y":
                print("")
                masterList = getValidList(topicSource)
                print("")
                print("Valid Topics")
                printList(masterList)
                topicItems.append(getNewTopic(topicSource, masterList))
            else:
                allItems = True
        topicItems = list(set(topicItems))
    else:
        topicItems = originalItem.topics
    return topicItems
Пример #16
0
def diff(n1, n2):
    if n2 is None:
        return color.cyan(' %9f') % n1

    if n1 > n2:
        return color.blue('+%9f') % (n1)
    elif n1 < n2:
        return color.red('-%9f') % (n1)
    else:
        return color.yellow(' %9f') % n1
Пример #17
0
	def _format_review(self):
		if not self.reviews['reviews']:
			return ''
		review = self.reviews['reviews'][self._current_review]
		return '%s\n User: %s\n Rating: %s\n Review: %s\n' % (
			color.green('Review'),
			color.cyan(review['user']['name']),
			color.yellow('*' * review['rating']),
			review['excerpt']
		)
Пример #18
0
def equipInfoReview(eqdb, originalItem):
    '''
	Controls the review and editing of equipment list. Asks user to input id numbers and 
	quantity of equipment needed for the new lab. User also can input an alternate/secondary 
	equipment item for each primary item
	
	Input id numbers are check for correctness

	Args:
		eqdb (pjlDB.EquipDB) entire equipment inventory database object generated by pjlDB
		originalItem (pjlDB._LabItem) individual lab item generated by pjlDB
	
	Return:
		equipItems (list of dictionaries)
	'''
    if debug: print(color.green("[Debug - equipInfoReview]  entering"))
    equipItems = []
    if originalItem.equipment:
        for i in originalItem.equipment:
            print("ID Number [" + i['id'] + "]: Name [" + i['name'] +
                  "]: Alternate Name: [" + i['alt-name'] + "]: Amount [" +
                  i['amount'] + "]")
            if input(color.yellow("Would you like to edit this entry? y/N: ")
                     ).lower() == "y":
                equipID = input("Enter new id number [" + i['id'] +
                                "], enter 'delete' to remove this item ")
                if equipID == "":
                    equipID = i['id']
                if equipID == "delete":
                    print("deleting " + i['id'] + " " + i['name'])
                else:
                    if debug:
                        print(
                            color.green(
                                "[Debug - equipInfoReview] editing equipment item???"
                            ))
                    item = addEquipItem(eqdb, equipID)
                    if not item == "":
                        if debug:
                            print(
                                color.green(
                                    "[Debug - equipInfoReview]  adding edited entry???"
                                ))
                        equipItems.append(item)
                    else:
                        equipItems.append(i)
                # if not equipID == "delete":
                # 	item = addEquipItem(eqdb,equipID)
                # 	print("enter editing code here")
                # else:
                # 	print("deleting " + i['id'] + " " + i['name'])
            else:
                equipItems.append(i)
    if debug: print(color.green("[Debug - equipInfoReview]  leaving"))
    return equipItems
Пример #19
0
def getDisciplineList(originalItem, disciplineSource):
    '''
	generates a list of disciplines

	Args:
		originalItem (pjlDB._LabItem) individual lab item generated by pjlDB
		disciplineSource (string) path to file containing list of disciplines

	Return:
		disciplineItems (list) valid disciplines
	'''
    disciplineItems = []
    if input(
            color.yellow(
                "Would you like to edit the disciplines list for this lab? y/N "
            )).lower() == "y":
        print("")
        print("Current Disciplines")
        print("-------------------")
        for i in originalItem.disciplines:
            print(i)
        print("")
        disciplineItems = []
        disciplineItems = disciplineRemove(originalItem)
        allItems = False
        while not allItems:
            if input(
                    color.yellow(
                        "Would you like to add a new discipline for this lab? y/N "
                    )).lower() == "y":
                print("")
                masterList = getValidList(disciplineSource)
                print("")
                print("Valid Disciplines")
                printList(masterList)
                disciplineItems.append(getNewDisciplines(masterList))
            else:
                allItems = True
        disciplineItems = list(set(disciplineItems))
    else:
        disciplineItems = originalItem.disciplines
    return disciplineItems
Пример #20
0
def getSoftwareList(originalItem, softwareSource):
    '''
	generates a list of software

	Args:
		originalItem (pjlDB._LabItem) individual lab item generated by pjlDB
		softwareSource (string) path to file containing list of available software

	Return:
		softwareItems (list) valid software
	'''
    softwareItems = []
    if input(
            color.yellow(
                "Would you like to edit the software list for this lab? y/N ")
    ).lower() == "y":
        print("")
        print("Current Software")
        print("-------------------")
        for i in originalItem.software:
            print(i)
        print("")
        softwareItems = []
        softwareItems = softwareRemove(originalItem)
        allItems = False
        while not allItems:
            if input(
                    color.yellow(
                        "Would you like to add a new software for this lab? y/N "
                    )).lower() == "y":
                print("")
                masterList = getValidList(softwareSource)
                print("")
                print("Valid Software")
                printList(masterList)
                softwareItems.append(getNewSoftware(masterList))
            else:
                allItems = True
        softwareItems = list(set(softwareItems))
    else:
        softwareItems = originalItem.software
    return softwareItems
Пример #21
0
def getEquipList(eqdb, originalItem):
    '''
	generates a list of equipment

	Args:
		eqdb (pjlDB.EquipDB) entire equipment inventory database object generated by pjlDB
		originalItem (pjlDB._LabItem) individual lab item generated by pjlDB

	Return:
		equipItems (list of dictionaries)
	'''
    if debug: print(color.green("[Debug - getEquipList]  entering"))
    print("")
    if input(
            color.yellow(
                "Would you like to edit the equipment list for this lab? y/N ")
    ).lower() == "y":
        print("")
        print("Current Equipment List")
        print("-------------------")
        for i in originalItem.equipment:
            # i['alt-name'] = "TEST NAME"
            # i['alt-id'] = "0000"
            print(i['id'] + " " + i['name'] + " [" + i['alt-id'] + " " +
                  i['alt-name'] + "] " + " (" + i['amount'] + ")")
        equipItems = []
        equipItems = equipInfoReview(eqdb, originalItem)
        allItems = False
        while not allItems:
            print("")
            if input(
                    color.yellow(
                        "Would you like to add a new piece of equipment for this lab? y/N "
                    )).lower() == "y":
                itemId = input(color.yellow("Enter the equipment id number: "))
                equipItems.append(addEquipItem(eqdb, itemId))
            else:
                allItems = True
    else:
        equipItems = originalItem.equipment
    if debug: print(color.green("[Debug - getEquipList]  leaving"))
    return equipItems
Пример #22
0
def update(conf, args):
  '''Apply updates from the upstream repository.'''

  print('Checking for updates...')

  # fetch changes from the canonical repo
  git.fetch(constants.GIT_REMOTE, no_tags=True, quiet=True)

  # get a list of the commit messages for the incoming changes
  updates = git('--no-pager', 'log', '..FETCH_HEAD', oneline=True)
  updates = [tuple(m.split(None, 1)) for m in updates.splitlines()]

  # print out a list of the incoming updates
  if len(updates) > 0:
    print('Available updates:')

    max_updates = 10
    for commit, msg in updates[:max_updates]:
      print(color.yellow('*'), msg)

    # print a special message if too many updates are available
    if len(updates) > max_updates:
      print('...and', color.green(len(updates) - max_updates), 'more!')
      print('Run `git log ..FETCH_HEAD` to see the full list')

    # bail if we have uncommitted changes (git exits non-0 in this case)
    if git.diff(exit_code=True, quiet=True, _ok_code=(0, 1)).exit_code != 0:
      raise ValueError('The repository has uncommitted changes. Handle them, '
        'then try updating again.')

    print('Applying the update...')

    # stash _all_ changes to the repo
    git.stash(include_untracked=True, all=True, quiet=True)

    # squash all the fetched commits together and merge them into master
    git.merge('@{u}', squash=True, quiet=True)

    # add a nice update commit that includes the latest upstream commit hash
    commit_message = 'Update dotparty to %s' % updates[0][0]
    git.commit(m=commit_message, quiet=True)

    # TODO: if squash merge failed, roll back to the pre-update state and
    # complain with instructions for the user to do their own update.

    # un-stash all our old changes
    git.stash('pop', quiet=True)

    # push our changes back up to the remote
    git.push(quiet=True)

    print('Update successful!')
  else:
    print('Already up-to-date!')
Пример #23
0
def getType():
    '''
	asks user what type of experiment this is. There are only two options lab or labatorial

	Args:
		none

	Return (str) type experiment. lab or labatorial
	'''
    validType = False
    while not validType:
        labType = input(
            color.yellow("Is this a lab or a labatorial? ")).lower()
        if labType == "lab" or labType == "labatorial":
            validType = True
        else:
            if input(color.yellow(
                    "Would you like to try again? Y/n: ")).lower() == "n":
                exit()
    return labType.capitalize()
Пример #24
0
def cvsCO(projectName,tagName='',dirName=''):
    #TODO check is there is CVSROOT variable - if no, ask user
    #do cvs check out
    print color.yellow('Checking project from cvs ...')
    command = 'cvs co '
    if(dirName != ''):
        command = command + '-d ' + dirName
    if(tagName != ''):
        command = command + ' -r ' + tagName + ' ' + projectName
    else:
        command = command + ' ' + projectName
    if(debug):
        print color.blue('Command is: ')
        print color.blue(command)
    timeStart = time.time()    
    os.system(command)
    timeEnd = time.time()
    print color.yellow('Check out finished, elapsed time [s]: ' + str(timeEnd - timeStart))
                
    #check if check out was OK - look if the directory is created
    print color.yellow('Now checking consistency...')
    if(dirName != ''):
        coDir = dirName
    else:
        coDir = projectName
    if not(os.path.exists(coDir)):
        print color.red('Directiry ' + coDir + ' does not exist - EXIT!')
        sys.exit(1)
    else:
        print color.green('Check out OK')
        print
        return coDir
Пример #25
0
def build(binary,projectDir=''):
    if(binary == ''):
        print color.red('Build: Name of not specified  - EXIT!')
        sys.exit(1)
    command = 'make'
    origPath = os.path.abspath('./')
    if(projectDir != ''):
        if(os.path.exists(projectDir)):
            os.chdir(projectDir)
        else:
            print color.red('Directiry ' + projectDir + ' does not exist - EXIT!')
            sys.exit(1)
    if not (os.path.exists('Makefile')):
        print color.red('Makefile ' + os.path.abspath('./') + '/Makefile does not exist - EXIT!')
        sys.exit(1)
    print color.yellow('Build start ...')
    if(debug):
        print color.blue('Directory is ')
        print color.blue(os.path.abspath('./'))
    timeStart = time.time()
    os.system(command)
    timeEnd = time.time()
    print color.yellow('Build finished, elapsed time [s]: ' + str(timeEnd - timeStart))
    os.chdir(origPath)

    #check if check out was OK - look if the directory is created
    print color.yellow('Now checking consistency...')
    if not(os.path.exists(projectDir+'/'+binary)):
        print color.red('File ' + os.path.abspath(projectDir) + '/' + binary + ' does not exist - EXIT!')
        sys.exit(1)
    else:
        print color.green('Build OK')
        print
        return os.path.abspath(projectDir) + '/' + binary
Пример #26
0
def main():
    parser = argparse.ArgumentParser(
        description='Scan n images to png and make a gif with them.')
    parser.add_argument('n',
                        type=int,
                        help='number of elements in the sequence')
    parser.add_argument('name', help='name of the sequence')
    parser.add_argument('--width',
                        '-W',
                        type=int,
                        default=DEFAULT_WIDTH,
                        help='width of the scanning area (in mm)')
    parser.add_argument('--height',
                        '-H',
                        type=int,
                        default=DEFAULT_HEIGHT,
                        help='height of the scanning area (in mm)')
    parser.add_argument('--delay',
                        '-d',
                        type=int,
                        default=DEFAULT_DELAY,
                        help='delay between images (in ms)')
    parser.add_argument('--resolution',
                        '-r',
                        type=int,
                        default=DEFAULT_RESOLUTION,
                        help='scanning resolution (in dpi)')
    parser.add_argument('--rotate',
                        '-R',
                        type=int,
                        default=DEFAULT_ROTATION,
                        help='rotate (in degrees)')
    args = vars(parser.parse_args())

    # Make PNG from scan
    png_list = []
    for i in range(args['n']):
        fi_name = '{}-{}.png'.format(args["name"], i)
        png_list.append(fi_name)
        with open(fi_name, 'wb') as fi:
            subprocess.call(scan_cmd.format(**args), shell=True, stdout=fi)
        print(yellow(fi_name))

    # Make GIF from PNG
    inp = ' '.join(png_list)
    out = '{}.gif'.format(args["name"])
    subprocess.call(gif_cmd.format(**args, input_files=inp, output_file=out),
                    shell=True)
    print(magenta(out))
Пример #27
0
def validYear():
    '''
	Asks user to enter the year the lab was used in, and checks that it is a valid year

	Args:
		none

	Return:
		year (str) valid 4 digit year
	'''
    validYear = False
    while not validYear:
        year = input(color.yellow("Enter year: "))
        if len(year) == 4 and year.isdigit() == True:
            validYear = True
        else:
            print("Year is invalid.")
    return year
Пример #28
0
def topicRemove(originalItem):
    '''
	Removes unwanted topics 

	Args:
		originalItem (pjlDB._LabItem) individual lab item generated by pjlDB
	
	Return:
		topicItems (list) wanted topics
	'''
    topicItems = []
    if originalItem.topics:
        for i in originalItem.topics:
            if not input(
                    color.yellow("Would you like to remove \"" + i +
                                 "\" as a topic? If so enter 'delete': ")
            ).lower() == "delete":
                topicItems.append(i)
    return topicItems
Пример #29
0
def disciplineRemove(originalItem):
    '''
	Removes unwanted disciplines 

	Args:
		originalItem (pjlDB._LabItem) individual lab item generated by pjlDB
	
	Return:
		disciplineItems (list) wanted disciplines
	'''
    disciplineItems = []
    if originalItem.disciplines:
        for i in originalItem.disciplines:
            if not input(
                    color.yellow("Would you like to remove \"" + i +
                                 "\" as a discipline? If so enter 'delete': ")
            ).lower() == "delete":
                disciplineItems.append(i)
    return disciplineItems
Пример #30
0
def getEditInfo(originalItem, eqdb, disciplineSource, topicSource,
                softwareSource, testMode):
    '''
	Main function that collects information for new version of lab entry

	Args:
		originalItem (pjlDB._LabItem) individual lab item generated by pjlDB
		eqdb (pjlDB.EquipDB) entire equipment inventory database object generated by pjlDB
		disiplineSource (str) path of file that contains all valid disciplines
		topicSource (str) path of file that contains all valid topics
		testMode (bool) allows script to be run in testing mode. No output written.
	
	Return:
		originalItem (pjlDB._LabItem) updated individual lab item
		updatedVersion (dict) new information related to an updated version
	'''
    if debug: print(color.green("[Debug - getEditInfo]  entering"))
    print("Editing info for \"" + originalItem.name + "\".")
    originalItem.equipment = getEquipList(eqdb, originalItem)
    print("")
    originalItem.software = getSoftwareList(originalItem, softwareSource)
    print("")
    originalItem.disciplines = getDisciplineList(originalItem,
                                                 disciplineSource)
    print("")
    originalItem.topics = getTopicList(originalItem, topicSource)
    print("")
    updatedVersion = {}
    if input(color.yellow("Would you like to updated a version of  lab? y/N ")
             ).lower() == "y":
        #		if not testMode:
        updatedVersion = updateVersionInfo(originalItem)
        originalItem.versions = updateVersion(originalItem, updatedVersion)


#		else:
#			updatedVersion = {'course': 'PHYS 227', 'semester': 'Fall', 'year': '2019', 'originalDir': '/home/pgimby/labs/under-construction/227FA2019/0023/', 'pdf': 'Lab-01-IntroToComputationalModelling.pdf', 'directory': '/data/repository/0023-Introduction-to-3D-Computational-Modelling/0023-PHYS227FA2019', 'labFolder': '/data/repository/0023-Introduction-to-3D-Computational-Modelling/', 'path': '/data/repository/0023-Introduction-to-3D-Computational-Modelling/0023-PHYS227FA2019/Lab-01-IntroToComputationalModelling.pdf'}
#			tmp = updateVersion(originalItem,updatedVersion)
#			print("")
#moveVersionDir(updatedVersion,root)
#tmp2 = validDB(updatedVersion,originalItem,labdb)
#print(tmp2)
    return originalItem, updatedVersion
Пример #31
0
def getOriginalPdf(dir):
    '''
	Asks user for name of lab pdf file, and check that it exists

	Args:
		dir (str) pathname of the folder that the pdf should be in

	Return:
		pdfName (str) location of pdf file for new lab
	'''
    validPath = False
    while not validPath:
        pdfName = input(
            color.yellow("Enter the name of the student version pdf: "))
        if os.path.isfile(dir + pdfName):
            validPath = True
        else:
            print("PDF does not exist. Please try again.")
    return pdfName
Пример #32
0
def softwareRemove(originalItem):
    '''
	Removes unwanted software

	Args:
		originalItem (pjlDB._LabItem) individual lab item generated by pjlDB
	
	Return:
		softwareItems (list) wanted software
	'''
    softwareItems = []
    if originalItem.software:
        for i in originalItem.software:
            if not input(
                    color.yellow(
                        "Would you like to remove \"" + i +
                        "\" as needed software? If so enter 'delete': ")
            ).lower() == "delete":
                softwareItems.append(i)
    return softwareItems
Пример #33
0
    def __randompick(self):
        '''
        returns one arbitrary entry from the current list of files

        >>> x = FileSelector()
        >>> x.__randompick()
        '''
        log.info("*** choosing randomly from %d files (%d played = %4.1f%%)",
                 len(self.files), len(self.recentlist),
                 100. * len(self.recentlist) / len(self.files))
        tries = 0
        maxtries = 10
        notplayed = [x for x in self.files if not x in self.recentlist]
        if len(notplayed) == 0:
            log.info(
                color.yellow(
                    "played all %d items in list. clearing recentlist to start over again."
                ), len(self.files))
            self.recentlist.clear()
            notplayed = self.files
        return random.choice(notplayed)  # choose one
Пример #34
0
def validSemester(validSemesters):
    '''
	Asks user to enter the semester the lab was used in, and checks it against a list of valid semesters

	Args:
		validSemesters (list) list of valid courses

	Return:
		semesterName (str) valid semester name
	'''
    validSemester = False
    while not validSemester:
        semesterName = str(input(
            color.yellow("Enter semester: "))).capitalize()
        for i in validSemesters:
            if semesterName == i:
                validSemester = True
        if not validSemester:
            print("Invalid semester")
            print("Valid semesters are...")
            for i in validSemesters:
                print(i)
    return semesterName
Пример #35
0
def validCourse(validCourses):
    '''
	Asks user to enter the course the lab was used in, and checks it against a list of valid courses

	Args:
		validCourses (list) list of valid courses

	Return:
		course (str) valid course number
	'''
    validCourse = False
    while not validCourse:
        courseNum = str(input(color.yellow("Enter course number: ")))
        for i in validCourses:
            if courseNum == i:
                course = "PHYS " + courseNum
                validCourse = True
        if not validCourse:
            print("Invalid Course number")
            print("Valid courses are...")
            for i in validCourses:
                print(i)
    return course
Пример #36
0
def runDataCards(binaryPath,dataCardPath,logPath):
    '''binaryPath - absolut path to executelbe file
       dataCardPath - absolut path to datacards directory
       logPath - absolut path to log directory'''
    if not(os.path.isfile(binaryPath)):
        print color.red('Binary file ' + binaryPath + ' does not exist - EXIT!')
        sys.exit(1)
    if not(os.path.isdir(dataCardPath)):
        print color.red('Data card file ' + dataCardPath + ' does not exist - EXIT!')
        sys.exit(1)
    if not(os.path.isdir(logPath)):
        print color.red('Log directory ' + logPath + ' does not exist - EXIT!')
        sys.exit(1)
    binaryDir = (binaryPath.rsplit('/',1))[0]
    if not(os.path.isdir(binaryDir)):
        print color.red('Directory with binary file does not exist - probably not used absoluth path to executeble file - EXIT!')
        sys.exit(1)
    dataCards = os.listdir(dataCardPath)
    origDir = os.path.abspath('./')
    os.chdir(binaryDir)
    for dataCard in dataCards:
        cardFile = dataCardPath+'/'+dataCard
        logFile = logPath+'/'+dataCard+'.log'
        if(os.path.isfile(cardFile)):
            print color.yellow('Now running ' + dataCard)
            command = binaryPath + ' < ' + cardFile + ' > ' + logFile
            if(debug):
                print color.blue('Command is:')
                print color.blue(command)
            timeStart = time.time()
            os.system(command)
            timeEnd = time.time()
            print color.yellow('Test ' + dataCard + ' finisehd, elapsed time [s]: ' + str(timeEnd - timeStart))
            if(os.path.isfile(logFile)):
                print color.green('Log file ' + logFile  + ' created')
            else:
                print color.red('WARNING: log file ' + logFile + ' was not created - something goes wrong!!!' )
        else:
            print color.yellow(dataCard + ' not a file, skipping...')
    os.chdir(origDir)
Пример #37
0
  new_records.append({
      'digest': "".join(digest.split()),
      'digestType': digest_type,
      'algorithm': algorithm,
      'keyTag': keytag,
      'maxSigLife': str(3600*24*90), # FIXME(tansell): Defaulting to 90 days...
      })

to_add = []
for dsrecord in sorted(current_records):
  dsid = dsrecord['keyTag']+" "+str(dsrecord['algorithm'])
  if dsrecord in new_records:
    print color.green("Current %s" % dsid)
  else:
    print color.red("Removing %s" % dsid)
    req = DeleteRequest(
        url="https://www.gkg.net/ws/domain/%s/ds/%s" % (domain, dsrecord['digest']),
        )
    print urllib2.urlopen(req).read()

for dsrecord in sorted(new_records):
  if dsrecord in current_records:
    continue

  dsid = dsrecord['keyTag']+" "+str(dsrecord['algorithm'])
  print color.yellow("Adding %s" % dsid)
  url = "https://www.gkg.net/ws/domain/%s/ds" % domain
  r = urllib2.urlopen(url, data=simplejson.dumps(dsrecord))
  print r.read()
Пример #38
0
def warnmsg (text):
    print (yellow( "[warning] %s" % (text) ) )
Пример #39
0
  for line in g.stdout.xreadlines():
    print "   ", line.strip()
  assert g.wait() == 0

  for publisher in publish_to:
    check_prog = "%s/check_%s.py" % (root, publisher)
    if not os.path.exists(check_prog):
      check_prog = "%s/check_root.py" % (root,)
    update_prog = "%s/update_%s.py" % (root, publisher)
    assert os.path.exists(update_prog), update_prog

    print " Checking", publisher
    c = subprocess.Popen("python -u %s %s" % (check_prog, domain), shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, bufsize=1)
    for line in c.stdout.xreadlines():
      print "   ", line.strip()
    retcode = c.wait()
    if retcode != 0:
      print color.yellow("   Need to update!")
      u = subprocess.Popen("python -u %s %s" % (update_prog, domain), shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, bufsize=1)
      for line in u.stdout.xreadlines():
        print "   ", line.strip()
      retcode = u.wait()
      if retcode != 0:
        print color.red("   Update failed!")
      else:
        print color.green("   Update successful!")
    else:
      print color.green("   Everything up to date!")

  os.chdir(curdir)