def get_duration(): """duration grab input""" while True: duration = input('please input the duration ' 'of the task in minutes: ') # tests input against regex pattern if pattern test durpattern = re.compile("(\d+)") durmatch = durpattern.fullmatch(duration) # if pattern fails test if not durmatch: print('this is not an appropriate format') # if pattern passes loop breaks and values stored else: utility = Utility() duration = utility.str2time(duration) clear() return duration
def RetiredUtility(a, c, NextUtilityFun, UtilityParams, transfer, params): beta = params["beta"] r = params["r"] a_prime = a * (1 + r) - c + transfer next_utility = NextUtilityFun(a_prime) total_utility = Utility( c) + beta * next_utility # need more arguments for Utility function return total_utility
def LastWorkingPeriodUtility(a, c, NextUtilityFun, UtilityParams, transfer, params): beta = UtilityParams["beta"] b = params["b"] r = params["r"] a_prime = a * (1 + r) + transfer - c total_utility = Utility(c, 0, UtilityParams) + b + beta * NextUtilityFun(a_prime) return total_utility
def analyzeVisualize(sentiment): with open('pickled/pipeline_holdout.pickle', 'rb') as pipeline_holdout: pipeline = pickle.load(pipeline_holdout) with open('pickled/metrics_cm_holdout.pickle', 'rb') as metrics_cm: clf_cm = pickle.load(metrics_cm) with open('pickled/metrics_cr_holdout.pickle', 'rb') as metrics_cr: clf_cr = pickle.load(metrics_cr) with open('pickled/metrics_dataframe.pickle', 'rb') as df: metrics_df = pickle.load(df) with open('pickled/metrics_dataframe_kfold.pickle', 'rb') as df: metrics_df_kfold = pickle.load(df) clf_svc = pipeline[2] clf_names = sentiment.clf_names labels = ['negative', 'positive'] visualizer = DataVisualizer() for cm, cr, name in zip(clf_cm, clf_cr, clf_names): visualizer.plotConfusionMatrix(cm, labels, name) visualizer.plotClassificationReport(cr, labels, name) metrics_df.rename(columns = {"Accuracy": "value_Accuracy", "Precision": "value_Precision", "Recall": "value_Recall", "F1-score": "value_F1-score", "ROC AUC": "value_ROC AUC"}, inplace = True) metrics_df['id'] = metrics_df.index metrics_df_long = pd.wide_to_long(metrics_df, stubnames = 'value', i = 'id', j = 'id_m', sep = '_', suffix = '\w') metrics_df_long['Metrics'] = metrics_df_long.index.get_level_values('id_m') visualizer.plotClassifierPerformanceComparison(metrics_df_long, clf_names, 'Holdout') metrics_df_kfold.rename(columns = {"Accuracy": "value_Accuracy", "Precision": "value_Precision", "Recall": "value_Recall", "F1-score": "value_F1-score", "ROC AUC": "value_ROC AUC"}, inplace = True) metrics_df_kfold['id'] = metrics_df_kfold.index metrics_df_kfold_long = pd.wide_to_long(metrics_df_kfold, stubnames = 'value', i = 'id', j = 'id_m', sep = '_', suffix = '\w') metrics_df_kfold_long['Metrics'] = metrics_df_kfold_long.index.get_level_values('id_m') visualizer.plotClassifierPerformanceComparison(metrics_df_kfold_long, clf_names, 'K-Fold') util = Utility() data = util.classifiersVsFeatures() colors = ['blue', 'yellow', 'red', 'green'] visualizer.plotClassifiersVsFeatures(data, clf_names, colors) top_features = util.showTopFeatures(clf_svc, n = 30) print('The 30 most informative features for both positive and negative coefficients:\n') print(top_features)
def get_date(): while True: date = input('please input a date for' 'the entry in the format yyyy/mm/dd:') # tests input against regex pattern if pattern pails test pattern = re.compile("(\d{4}\/\d{2}\/\d{2})") match = pattern.fullmatch(date) # if not a match error i if not match: print('this is not an appropriate format') # if match a Utility object is instantiated # date variable passed to Utility.date2string which tests # string to see if its a valid date # and while loop is broken else: utility = Utility() date = utility.str2date(date) clear() return date
def checkUrlParameters(inputCurrency, outputCurrency, amount): """Checks if the URL parameters are valid and returns currency three letter code representation and a float amount value""" Utility.checkArguments(inputCurrency, amount) inputCurrency = Currencies.getCurrencyCode(inputCurrency) if None not in outputCurrency: outputCurrency = [Currencies.getCurrencyCode(outputCurrency[0])] if None in outputCurrency: outputCurrency = copy.copy(Currencies.listOfCurrencies) outputCurrency.remove(inputCurrency) amount = abs(float(amount)) return { 'input_currency': inputCurrency, 'output_currency': outputCurrency, 'amount': amount }
def main(): try: args = CmdParser.parseArguments() inputCurrency = Currencies.getCurrencyCode(args['input']) outputCurrency = args['output'] amount = args['amount'] conversion = CurrencyConverter.getConversion(inputCurrency, outputCurrency, amount) printResults = JsonCreator.finalOutput(inputCurrency, conversion, amount) print(printResults) except InvalidArgumentError as invArgErr: Utility.errorStatement(invArgErr.message) except RequestError as reqErr: sys.stderr.write(reqErr.message) sys.exit()
def GET(self, *vpath, **params): self.paramMap = {} for k,v in params.items(): self.paramMap[k] = v ridesList = [] cherrypy.response.headers["Content-Type"] = "application/json" if vpath: if (vpath[0] == "near"): if not (self._validate_param("lat") and self._validate_param("lon")): cherrypy.response.status = 400 return json.dumps({"Error":True,"Message":PMIP.REQUEST_PARAM_MISSING}) if (self.paramMap.has_key("limit")): rideDocs = self._find_near(self.paramMap["lat"], self.paramMap["lon"], self.paramMap["limit"]) else: rideDocs = self._find_near(self.paramMap["lat"], self.paramMap["lon"]) elif(vpath[0] == "within"): if not (self._validate_param("lat") and self._validate_param("lon") and self._validate_param("radius")): cherrypy.response.status = 400 return json.dumps({"Error":True,"Message":PMIP.REQUEST_PARAM_MISSING}) if (self.paramMap.has_key("limit")): rideDocs = self._find_within_circle(self.paramMap["lat"], self.paramMap["lon"], self.paramMap["radius"], self.paramMap["limit"]) else: rideDocs = self._find_within_circle(self.paramMap["lat"], self.paramMap["lon"], self.paramMap["radius"]) elif(vpath[0] == "tags"): if not (self._validate_param("tag")): cherrypy.response.status = 400 return json.dumps({"Error":True,"Message":PMIP.REQUEST_PARAM_MISSING}) else: rideDocs = self._find_with_tags(self.paramMap["tag"]) # elif(vpath[0] == "route"): # if not (self._validate_param("from") and self._validate_param("to") and self._validate_param("from")): # cherrypy.response.status = 400 # return json.dumps({"Error":True,"Message":PMIP.REQUEST_PARAM_MISSING}) # else: # rideDocs = self._find_for_route(self.paramMap["from"],self.paramMap["to"]) else: cherrypy.response.status = 400 return json.dumps({"Error":True,"Message":PMIP.INVALID_URI}) for rideDoc in rideDocs : result = Utility.getRide(rideDoc) ridesList.append(result) return json.dumps(ridesList);
# written for openrobotics.ca from __future__ import print_function from __future__ import unicode_literals import sys from os import path sys.path.append(path.dirname(__file__) + 'lib/') #for generic functionality sys.path.append(path.dirname(__file__) + 'modules/') #specific to various hardware import random import struct from utilities import Utility from serial_manager import SerialManager utils = Utility() manager = SerialManager() print('\nSelect a port to connect to or a menu option below') manager.list_ports() from threads import AutoTimer, EventWrapper from data_structures import v2_drivetrain as v2dt from data_structures import mini_arm as marm marm.status = ord('k') v2dt.speed1 = 1 v2dt.speed2 = 255 v2dt.status = ord('k')
def parseArguments() -> dict: """Parses the command line arguments""" conversionAmount = -1 inputCurrency = None outputCurrencies = [None] if len(sys.argv) == 1: print(Utility.help()) sys.exit() try: optlist, args = getopt.getopt( sys.argv[1:], 'h', ['amount=', 'input_currency=', 'output_currency=', 'help']) except getopt.GetoptError: raise InvalidArgumentError( "Oops, it looks like you entered an invalid option.") if not len(args) == 0: raise InvalidArgumentError( "Oops, it looks like you entered an invalid option.") for option, argument in optlist: if option in ('-h', '--help'): print(Utility.help()) sys.exit() elif option in '--amount': if conversionAmount is not -1: raise InvalidArgumentError( "Please select only one amount, output or input currency." ) conversionAmount = argument elif option in '--input_currency': if inputCurrency is not None: raise InvalidArgumentError( "Please select only one amount, output or input currency." ) inputCurrency = argument elif option in '--output_currency': if not None in outputCurrencies: raise InvalidArgumentError( "Please select only one amount, output or input currency." ) outputCurrencies = [argument] Utility.checkArguments(inputCurrency, conversionAmount) inputCurrency = Currencies.getCurrencyCode(inputCurrency) conversionAmount = abs(float(conversionAmount)) if None not in outputCurrencies: outputCurrencies = [ Currencies.getCurrencyCode(outputCurrencies[0]) ] else: outputCurrencies = copy.copy(Currencies.listOfCurrencies) outputCurrencies.remove(inputCurrency) return { 'amount': conversionAmount, 'input': inputCurrency, 'output': outputCurrencies }
def checkIfFileExists(baseCurrency): """Checks if a cache file for a given base already exists""" cacheFile = Utility.createFileName(baseCurrency) return os.path.isfile(cacheFile)
def loadCachedResponse(baseCurrency): """Returns the content of a cache file""" cacheFile = Utility.createFileName(baseCurrency) with open(cacheFile, 'rb') as file: return pickle.load(file)
def updateCache(baseCurrency, apiResponse): """Updates cache file""" cacheFile = Utility.createFileName(baseCurrency) apiResponse['date'] = Utility.currentDate() with open(cacheFile, "wb") as file: pickle.dump(apiResponse, file, pickle.HIGHEST_PROTOCOL)
from __future__ import unicode_literals import sys from os import path sys.path.append(path.dirname(__file__) + 'lib/') #for generic functionality sys.path.append(path.dirname(__file__) + 'modules/') #specific to various hardware from threading import Thread from time import clock from time import sleep from utilities import Utility from serial_manager import SerialManager from pololu_controller import PololuController from Servo import * from data_structures import mini_arm as marm utils = Utility() alive = True def quit(): global alive alive = False manager1 = SerialManager() print('Ports available') manager1.list_ports() print('Select Dynamixel port') user_input = utils.getch() if manager1.open_port(user_input, 115200): serv2 = Robotis_Servo(manager1,2)
def reverseString(): data = request.get_json() return jsonify(message=Utility.getReverseString(data.get("message")), rand=Utility.getRandomNumber())
from telegram import ReplyKeyboardMarkup, ReplyKeyboardRemove, ParseMode, ChatAction, MessageEntity, Bot from telegram import InlineKeyboardButton, InlineKeyboardMarkup from telegram.ext import Updater, CommandHandler, ConversationHandler, MessageHandler, Filters, PicklePersistence, PrefixHandler, CallbackQueryHandler import re, os, requests, sys, time, json from datetime import datetime from utilities import Utility from Dealer_Interaction.src import utils from Dealer_Interaction.src import dealer_persistence persistence_filename = "bot_persistence" Utility_Obj = Utility() Utils_Obj = utils.Utils() Dealer_Persistence_Obj = dealer_persistence.Dealer_Persistence() BOT_TOKEN = "" # t.me/ColligoBot BOT_DEV_TOKEN = "1140474924:AAEEt2LD6Hg0TRXZDZU7HoHullUtEqNQAPc" # t.me/Colligo_Development_Bot BOT_TOKEN = BOT_DEV_TOKEN # Development mode Bot_Obj = Bot(BOT_TOKEN) #---------[Some Strings]--------- bot_replies = { "main_message": "*Utilizza la tastiera sottostante*", "category_message": "Seleziona a quale categoria appartiene il tuo negozio.(Max 3)\n*[Premere il pulsante Fine per terminare la selezione]*",
def user_search(self): """ user_search gathers and stores user input related to search entries handles user data gathering and storage for search by date, duration regex pattern and exact match. once data is gathered and stored a WorkLog object is instantiated and the data passed to the relevant search method of worklog object """ while True: # prompt choose search method search_option = input('please choose a search option: ') # if user provides a invalid response to prompt if search_option not in ('a', 'b', 'c', 'd', 'e'): print('this is not an available option') # if response valid loop will break else: break # if date prompt for date get input if search_option == 'a': clear() # begin loop for entry search by date data collection while True: date = input('please input a date to search ' 'in the format yyyy/mm/dd: ') # tests input against regex pattern pattern = re.compile("(\d{4}\/\d{2}\/\d{2})") match = pattern.fullmatch(date) # if pattern fails test # messsage will prompt until correct format recieved if not match: print('this is not an appropriate format') continue # if usre input valid elif match: # Utility object instantiated utility = Utility() # string -> datetime object str2date = utility.str2date(date) # Worklog object instantiated search = Inspector() # call to WorkLog.search_by_date mentod # method handles search logic/ display of relevant entry try: clear() "\n" print('here are the matching entries: \n') search_results = search.search_by_date(str2date) app() except ValueError: print('It looks like there is no matching results') app() # if duration prompt for duration get input elif search_option == 'b': # begin loop for entry search by duration data collection while True: duration = input('please input the duration of the task ' 'that you want to search: ') # tests input against regex pattern durpattern = re.compile("(\d+)") durmatch = durpattern.fullmatch(duration) # if pattern fails test # messsage will prompt until correct format recieved if not durmatch: print('this is not an appropriate format') continue # if user input valid elif durmatch: # Utility object instantiated utility = Utility() # string -> timedelta str2time = utility.str2time(duration) # Worklog object instantiated search = Inspector() # call to WorkLog.search_by_duration # method handles search logic/ display of relevant entry try: clear() "\n" print('here are the matching entries: \n') search_results = search.search_by_duration(str2time) app() except ValueError: print('It looks like there is no matching results') app() # if string prompt for string get input elif search_option == 'c': while True: string = input('please type string and we' 'will search against it: ') # Worklog object instantiated search = Inspector() # call to WorkLog.search_by_duration # method handles search logic/ display of relevant entry try: clear() "\n" print('here are the matching entries: ') search_results = search.search_by_string(string) # if now matching entries app() except ValueError: print('It looks like there is no matching results') app() elif search_option == 'd': while True: string = input('please type employee name to search for: ') # Worklog object instantiated search = Inspector() # call to WorkLog.search_by_duration # method handles search logic/ display of relevant entry try: clear() "\n" print('here are the matching entries: \n') search_results = search.search_by_employee(string) app() except ValueError: print('It looks like there is no matching results') app() elif search_option == 'e': clear() app()
# written for openrobotics.ca import sys from os import path sys.path.append(path.dirname(__file__) + 'lib/') #for generic functionality sys.path.append(path.dirname(__file__) + 'modules/') #specific to various hardware from threading import Thread from time import clock from time import sleep from utilities import Utility from serial_manager import SerialManager from pololu_controller import PololuController from Servo import * from data_structures import mini_arm as marm utils = Utility() alive = True def quit(): global alive alive = False manager1 = SerialManager() print 'Ports available' manager1.list_ports() print 'Select Dynamixel port' user_input = utils.getch() if manager1.open_port(user_input, 57600): serv_2 = Robotis_Servo(manager1, 1)