Beispiel #1
0
 def test_post_error(self):
     api_handler = ApiHandler()
     newData = {"userId": 500,
                "title": "Security Interview Post",
                "body": "This is an insertion test with a known API"}
     result = api_handler.post("post", newData)
     self.assertTupleEqual(result, ("Error", "Not Found"))
Beispiel #2
0
 def test_post(self):
     api_handler = ApiHandler()
     newData = {"userId": 500,
                "title": "Security Interview Post",
                "body": "This is an insertion test with a known API"}
     result = api_handler.post("posts", newData)
     self.assertTupleEqual(result, (101, 201, "Express"))
 def update(self, city):
     apiHandler = ApiHandler(city)
     apiHandler.request_daily()
     print(city)
     self.labeltemp.text = f'{str(round(apiHandler.temp - 273))} C{degree_sign}'
     self.labeltemp_min.text = f'Min: {str(round(apiHandler.tempMin - 273))} C{degree_sign}'
     self.labeltemp_max.text = f'Max: {str(round(apiHandler.tempMax - 273))} C{degree_sign}'
     self.labelcityName.text = city
Beispiel #4
0
    def solve(self, startStation, endStation):
        startCoordinates = ApiHandler.getCoordinates(startStation)
        endCoordinates = ApiHandler.getCoordinates(endStation)

        startMetro = self._getNearestStation(
            (startCoordinates["lat"], startCoordinates["lng"]), "METRO",
            self.preProcesser.graphMaker.stops)
        endMetro = self._getNearestStation(
            (endCoordinates["lat"], endCoordinates["lng"]), "METRO",
            self.preProcesser.graphMaker.stops)
        startTime = datetime.datetime.now()
        startTime = str(startTime)[-15:-7]

        # print(startMetro, endMetro)

        timeRoute = self.graphAlgorithms.djsktra(
            self.nameToIndex[startMetro["name"]],
            self.nameToIndex[endMetro["name"]], self.g, "time", "cost",
            self.indexToName, startTime)
        costRoute = self.graphAlgorithms.djsktra(
            self.nameToIndex[startMetro["name"]],
            self.nameToIndex[endMetro["name"]], self.g, "cost", "time",
            self.indexToName, startTime)
        comfortRoute = ApiHandler.uberGoPrice(startCoordinates["lat"],
                                              startCoordinates["lng"],
                                              endCoordinates["lat"],
                                              endCoordinates["lng"],
                                              startStation, endStation)

        toReturn = {
            "timeRoute": timeRoute,
            "costRoute": costRoute,
            "comfort": comfortRoute
        }

        print timeRoute
        print '\n'
        print costRoute
        print '\n'
        print comfortRoute

        return toReturn
        # startIndex = self.preProcesser.graphMaker.nameToIndex[startMetro["name"]]
        # endIndex = self.preProcesser.graphMaker.nameToIndex[endMetro["name"]]
        # uberGo = ApiHandler.uberGoPrice(startCoordinates["lat"], startCoordinates["lng"], endCoordinates["lat"], endCoordinates["lng"])


# main = Main()
# main.solve("IIT delhi", "IIIT delhi, okhla")

# To-do
# Get the metro api for getting cost between two stations and add them to graphs.
# Get the uber api for getting cost between two locations - best comfort zone.
# Traverse over all coordinates to get the nearest metro station or bus stop.
# Run djisktra on the graph made by the bus and metro tickets people have.
# Includes: by cost, by comfort, by time, by mixtures of these, least number of changes, metro line changing should also be included.
Beispiel #5
0
class MessageProcessingService(object):
    def __init__(self, requestServer):
        self._api = ApiHandler()
        self._hostUrl = requestServer.ServerLocal if debuggingOnPC else requestServer.ServerExternal
        self._lightsPath = requestServer.ConfirmLights
        self._antiforgeryTokenPath = requestServer.AntiforgeryToken

    def format_url(self, host, path):
        return '{0}/{1}'.format(host, path)

    def process_message(self, message):
        try:

            messageParts = message.decode().split(',')
            miLightSwitcher = MiLightSwitcher()
            if miLightSwitcher.has_message_prefix(messageParts):
                LOGGER.info('Processing MiLight switch command')

                lightGroup = messageParts[1].strip()
                command = messageParts[2].strip()
                value = int(messageParts[3].strip()
                            ) if len(messageParts) >= 4 else None

                miLightSwitcher.switch_lights(lightGroup, command, value)

            else:
                LOGGER.info('Processing Energenie switch command')

                lightState = int(messageParts[0].strip())
                lightIdsStr = messageParts[1].strip().split(' ')
                # if no light ids provided means all lights should be switched to lightState
                # mapping to list since otherwise would be lazily evaluated and would cause mayhem!
                lightIds = list(map(
                    int, lightIdsStr)) if lightIdsStr != [''] else None

                lightSwitcher = EnergenieLightSwitcher()
                lightSwitcher.switch_lights(lightState, lightIds)

                # update state on homeHud website
                # TODO: Move this somewhere
                lightsState = []
                for piLight in lightSwitcher.LIGHTS:
                    light = Light(piLight.Id, piLight.State)
                    lightsState.append(light)

                self._api.postJsonWithAntiforgery(
                    url=self.format_url(self._hostUrl, self._lightsPath),
                    antiforgeryPath=self.format_url(
                        self._hostUrl, self._antiforgeryTokenPath),
                    data=lightsState,
                    params=None)

        except ValueError:
            LOGGER.error('Parsing message {0} failed'.format(message))
Beispiel #6
0
 def test_get(self):
     api_handler = ApiHandler()
     result = api_handler.get("posts", 99)
     self.assertDictEqual(
         result, {"title": "temporibus sit alias " +
                  "delectus eligendi possimus magni",
                  "userId": 10, "id": 99,
                  "body": "quo deleniti praesentium " +
                  "dicta non quod\n" +
                  "aut est molestias\n" +
                  "molestias et officia quis nihil\nitaque dolorem quia"})
class MessageProcessingService(object):

    def __init__(self, requestServer):
        self._api = ApiHandler()
        self._hostUrl = requestServer.ServerLocal if debuggingOnPC else requestServer.ServerExternal
        self._lightsPath = requestServer.ConfirmLights
        self._antiforgeryTokenPath = requestServer.AntiforgeryToken

    def format_url(self, host, path):
        return '{0}/{1}'.format(host, path)

    def process_message(self, message):
        lightSwitcher = EnergenieLightSwitcher()

        try:

            messageParts = message.decode().split(',')
            lightState = int(messageParts[0].strip())
            lightIdsStr = messageParts[1].strip().split(' ')
            # if no light ids provided means all lights should be switched to lightState
            # mapping to list since otherwise would be lazily evaluated and would cause mayhem!
            lightIds = list(map(int, lightIdsStr)) if lightIdsStr != [''] else None

        except ValueError:
            LOGGER.error('Parsing message {0} failed'.format(message))

        lightSwitcher.switch_lights(lightState, lightIds)

        lightsState = []
        for piLight in lightSwitcher.PiLights:
            light = Light(piLight.Id, piLight.State)
            lightsState.append(light)

        self._api.postJsonWithAntiforgery(
            url=self.format_url(self._hostUrl, self._lightsPath),
            antiforgeryPath=self.format_url(self._hostUrl, self._antiforgeryTokenPath),
            data=lightsState,
            params=None)
    def update(self, city):
        apiHandler = ApiHandler(city)
        apiHandler.request_5days()
        print(city)
        self.label1day.text = f'{str(round(apiHandler.temp1day - 273))} C{degree_sign}'
        self.label1day_data = apiHandler.temp1day_data
        self.label1day_weather = apiHandler.temp1day_weather

        self.label2day.text = f'{str(round(apiHandler.temp2day - 273))} C{degree_sign}'
        self.label2day_data = apiHandler.temp2day_data
        self.label2day_weather = apiHandler.temp2day_weather

        self.label3day.text = f'{str(round(apiHandler.temp3day - 273))} C{degree_sign}'
        self.label3day_data = apiHandler.temp3day_data
        self.label3day_weather = apiHandler.temp3day_weather

        self.label4day.text = f'{str(round(apiHandler.temp4day - 273))} C{degree_sign}'
        self.label4day_data = apiHandler.temp4day_data
        self.label4day_weather = apiHandler.temp4day_weather

        self.label5day.text = f'{str(round(apiHandler.temp5day - 273))} C{degree_sign}'
        self.label5day_data = apiHandler.temp5day_data
        self.label5day_weather = apiHandler.temp5day_weather
class FutureWeather(FloatLayout, MDAdaptiveWidget):
    apiHandler = ApiHandler(maincity)
    apiHandler.request_5days()

    temp1day = f'{str(round(apiHandler.temp1day - 273))} C{degree_sign}'
    temp1day_data = apiHandler.temp1day_data
    temp1day_weather = apiHandler.temp1day_weather

    temp2day = f'{str(round(apiHandler.temp2day - 273))} C{degree_sign}'
    temp2day_data = apiHandler.temp2day_data
    temp2day_weather = apiHandler.temp2day_weather

    temp3day = f'{str(round(apiHandler.temp3day - 273))} C{degree_sign}'
    temp3day_data = apiHandler.temp3day_data
    temp3day_weather = apiHandler.temp3day_weather

    temp4day = f'{str(round(apiHandler.temp4day - 273))} C{degree_sign}'
    temp4day_data = apiHandler.temp4day_data
    temp4day_weather = apiHandler.temp4day_weather

    temp5day = f'{str(round(apiHandler.temp5day - 273))} C{degree_sign}'
    temp5day_data = apiHandler.temp5day_data
    temp5day_weather = apiHandler.temp5day_weather

    def update(self, city):
        apiHandler = ApiHandler(city)
        apiHandler.request_5days()
        print(city)
        self.label1day.text = f'{str(round(apiHandler.temp1day - 273))} C{degree_sign}'
        self.label1day_data = apiHandler.temp1day_data
        self.label1day_weather = apiHandler.temp1day_weather

        self.label2day.text = f'{str(round(apiHandler.temp2day - 273))} C{degree_sign}'
        self.label2day_data = apiHandler.temp2day_data
        self.label2day_weather = apiHandler.temp2day_weather

        self.label3day.text = f'{str(round(apiHandler.temp3day - 273))} C{degree_sign}'
        self.label3day_data = apiHandler.temp3day_data
        self.label3day_weather = apiHandler.temp3day_weather

        self.label4day.text = f'{str(round(apiHandler.temp4day - 273))} C{degree_sign}'
        self.label4day_data = apiHandler.temp4day_data
        self.label4day_weather = apiHandler.temp4day_weather

        self.label5day.text = f'{str(round(apiHandler.temp5day - 273))} C{degree_sign}'
        self.label5day_data = apiHandler.temp5day_data
        self.label5day_weather = apiHandler.temp5day_weather
class DailyWeather(FloatLayout, MDAdaptiveWidget):
    apiHandler = ApiHandler(maincity)
    apiHandler.request_daily()

    temp = f'{str(round(apiHandler.temp - 273))} C{degree_sign}'
    temp_min = f'Min: {str(round(apiHandler.tempMin - 273))} C{degree_sign}'
    temp_max = f'Max: {str(round(apiHandler.tempMax - 273))} C{degree_sign}'
    cityName = maincity
    today = str(date.today())
    weather_description = apiHandler.weatherDescription

    def update(self, city):
        apiHandler = ApiHandler(city)
        apiHandler.request_daily()
        print(city)
        self.labeltemp.text = f'{str(round(apiHandler.temp - 273))} C{degree_sign}'
        self.labeltemp_min.text = f'Min: {str(round(apiHandler.tempMin - 273))} C{degree_sign}'
        self.labeltemp_max.text = f'Max: {str(round(apiHandler.tempMax - 273))} C{degree_sign}'
        self.labelcityName.text = city
Beispiel #11
0
from ApiHandler import ApiHandler
import datetime

api_handler = ApiHandler()
newPost = {
    "title": "Security Interview Post",
    "userId": 500,
    "body": "This is an insertion test with a known API"
}

print("\nGoal 1. Print the value of the title for post number 99")
data = api_handler.get("posts", 99)
print("Title:", data["title"], "\n")

print("Goal 2. Inject a field called time into the results")
data = api_handler.get("posts", 100)
print("Retrieved data:")
print(data, "\n")
data["time"] = datetime.datetime.now().strftime("%m/%d/%Y, %H:%M:%S")
print("Modified data:")
print(data, "\n")

print("Goal 3. Create a new /posts entry")
data = api_handler.post("posts", newPost)
print("A new /posts entry has been created\n")
print("Goal 4. Determine if your post was successful")
print("Yes, the post was successful")
print(newPost, "\n")

print("Goal 5. Print the tuple from #4")
print(data, "\n")
 def __init__(self, requestServer):
     self._api = ApiHandler()
     self._hostUrl = requestServer.ServerLocal if debuggingOnPC else requestServer.ServerExternal
     self._lightsPath = requestServer.ConfirmLights
     self._antiforgeryTokenPath = requestServer.AntiforgeryToken
Beispiel #13
0
 def test_delete_error(self):
     api_handler = ApiHandler()
     result = api_handler.delete("post", 101)
     self.assertTupleEqual(result, ("Error", "Not Found"))
Beispiel #14
0
 def test_delete(self):
     api_handler = ApiHandler()
     result = api_handler.delete("posts", 101)
     self.assertTupleEqual(result, (200, "nosniff"))
Beispiel #15
0
 def test_get_error(self):
     api_handler = ApiHandler()
     result = api_handler.get("post", 99)
     self.assertDictEqual(result, {"title": "N/A"})