Beispiel #1
0
 def finalize(self):
     Place.finalize(self)
     
     self._owner = None
     self._turn_list = []
     self._game.finalize()
     self._game = None
Beispiel #2
0
def plate(size, chaise):
    for i in range(size):
        if i % 2 == 0:
            c = Place(randrange(5000, 50000, 500))
        else:
            c = Place(randrange(-100000, -5000, 5000))
        chaise.plateau.append(c)
Beispiel #3
0
def test_lamp() :
    tz = tzlocal.get_localzone()
    place = Place(nkpCoord())
    place.findSunTimes()

    scheme = murklanScheme(place)
    lamp = Lamp(1)

    lamp.update(datetime.time(12, 10, 5, 0, tz), scheme[1])
    test_wait("Lamp expected to be OFF. Press enter to continue.")
    
    lamp.update(datetime.time(5, 50, 5, 0, tz), scheme[1])
    test_wait("Lamp expected to be OFF. Press enter to continue.")
    
    lamp.update(datetime.time(6, 30, 5, 0, tz), scheme[1])
    test_wait("Lamp expected to be ON. Press enter to continue.")
    
    lamp.update(datetime.time(8, 30, 5, 0, tz), scheme[1])
    test_wait("Lamp expected to be ON. Press enter to continue.")
    
    lamp.update(datetime.time(9, 10, 5, 0, tz), scheme[1])
    test_wait("Lamp expected to be OFF. Press enter to continue.")
    
    lamp.update(datetime.time(18, 40, 5, 0, tz), scheme[1])         # after sunset but within offset
    test_wait("Lamp expected to be OFF. Press enter to continue.")
    
    lamp.update(datetime.time(18, 59, 5, 0, tz), scheme[1])
    test_wait("Lamp expected to be ON. Press enter to continue.")
    
    lamp.update(datetime.time(22, 29, 5, 0, tz), scheme[1])
    test_wait("Lamp expected to be ON. Press enter to continue.")
    
    lamp.update(datetime.time(22, 30, 5, 0, tz), scheme[1])
    test_wait("Lamp expected to be OFF. Press enter to continue.")
Beispiel #4
0
    def press_add(self, name, country, priority):
        """
        Handler for pressing the add button
        :return: None
        """
        if (not name) or (not country) or (not priority):
            self.status_text = "All fields must be completed"
        else:

            try:
                priority = int(priority)
                if priority < 1:
                    self.status_text = "Priority must be > 0"
                else:
                    # Adding widget
                    p = Place(name=name,
                              country=country,
                              priority=priority,
                              visited_status=False)
                    temp_str = p.__str__(
                    ) + " (visited)" if p.visited_status else p.__str__()
                    temp_button = Button(text=temp_str)
                    temp_button.bind(on_release=self.press_entry)
                    temp_button.place = p
                    temp_button.state = "down" if p.visited_status else "normal"
                    # add the button to the "entries_box" using add_widget()
                    self.root.ids.entries_box.add_widget(temp_button)
                    self.clear_fields()
                    # Adding to place collection
                    self.pc.add_place(p)
            except:
                self.status_text = "Please enter a valid number"
Beispiel #5
0
 def process_message(self, player, text):
     if text and text.startswith('/'):
         reply = self._game.process_message(player, text[1:])
         if reply == None:
             Place.process_message(self, player, text)
         elif reply:
             self.send(player, reply)
Beispiel #6
0
def outputFile(intervieweeName):
    global places, placeDict, newPlaceDict

    newFileName = 'newCSVs/' + intervieweeName + '_placeName.csv'
    outFile = open(newFileName, "w")

    outFile.write("name,address,city,latitude,longitude,source\n")

    for place in places:
        if placeDict.has_key(place):
            placeToAdd = placeDict[place]
        else:
            print(
                "This place -> " + place +
                " isn't in our current system. Fill in some new information.")
            # Add resiliancy tests and error catches
            address = raw_input("Enter address: ")
            city = raw_input("Enter city, state: ")
            latitude = raw_input("Enter latitude: ")
            longitude = raw_input("Enter longitude: ")
            source = raw_input("Enter source: ")

            placeToAdd = Place(place, address, city, latitude, longitude,
                               source)
            newPlaceDict[place] = placeToAdd
            placeDict[place] = placeToAdd

        outFile.write(placeToAdd.toString())
def run_tests() :
    """Test Place class."""

    # Test empty place (defaults)
    print ("Test empty place:")
    default_place = Place ( )
    print (default_place)
    assert default_place.name == ""
    assert default_place.country == ""
    assert default_place.priority == 0
    assert not default_place.is_visited

    # Test initial-value place
    print ("Test initial-value place:")
    new_place = Place ("Malagar", "Spain", 1, False)
    # TODO: Write tests to show this initialisation works
    print ("Test aleranate method for marking visited places")
    """This is the visited value that has changed from boolean to str; oupost should still be the same"""
    new_places = place ("Malagar", "spain", 1, "n")
    print (new_places)

    # TODO: Add more tests, as appropriate, for each method
    print (new_places)
    """String is representation of place"""
    print (new_places.check_visited ( ))
    """Check if place has been visited or not"""
    print (new_places.is_important ( ))
    """Important that place is added to the list"""
Beispiel #8
0
    def __init__(self, filename, places):

        root = FromXmlFile(filename)

        walker = root.createTreeWalker(root.documentElement,
                                      NodeFilter.SHOW_ELEMENT, None, 0)

        while 1:
            nodeName = walker.currentNode.nodeName
            attribs = walker.currentNode.attributes

            if nodeName == 'game':
                self.startingPlace = attribs['startingPlace'].value
                self.serverHost = attribs['serverHost'].value
                self.serverPort = attribs['serverPort'].value
                
            elif nodeName == 'place':
                placeName = attribs['name'].value
                desc = attribs['description'].value
                currentPlace = Place(placeName, desc)
                places[placeName] = currentPlace

            elif nodeName == 'object':
                currentPlace.addObject(attribs['name'].value)

            elif nodeName == 'connection':
                currentPlace.addConnection(attribs['place'].value)

            next = walker.nextNode()
            
            if next is None: break
Beispiel #9
0
 def show_place(self):
     #This method is used for displaying the place from the data list
     id_count = 0  #this variable is used for defining each button ids
     for a in self.sorted_data:  #looop for make sure all the data list is read that the data already sorted.
         id_count = id_count + 1  #the variable will be add each loop for giving each place different ids
         if a[3] == "n":  #conditions to check if its unvisited or visited to give different color
             entries_box = Button(
                 id=str(id_count),  #defining the place button id
                 text="{0} in {1}, priority {2}".format(
                     a[0], a[1],
                     a[2]),  #set the data name button for the place name
                 background_color=
                 UNVISITED_COLOR,  #give background color red on the unvsiited place
                 on_press=lambda x: Place.mark_place(self, x.id)
             )  #give the button action when its press it will be marked and passed the data based on their own ids
             self.root.ids.entries_box.add_widget(
                 entries_box
             )  #add widget button in entries box from the button setting in entries box
         else:  #conditions to check if its unvisited or visited to give different color
             entries_box = Button(
                 id=str(id_count),  #defining the place button id
                 text="{0} in {1}, priority {2} (visited)".format(
                     a[0], a[1],
                     a[2]),  #set the data name button for the place name
                 background_color=
                 VISITED_COLOR,  #give background color red on the unvsiited place
                 on_press=lambda x: Place.mark_place(self, x.id)
             )  #give the button action when its press it will be marked and passed the data based on their own ids
             self.root.ids.entries_box.add_widget(
                 entries_box
             )  #add widget button in entries box from the button setting in entries box
Beispiel #10
0
def run_tests():
    """Test Place class."""

    # Test empty place (defaults)
    print("Test empty place:")
    default_place = Place()
    print(default_place)
    assert default_place.name == ""
    assert default_place.country == ""
    assert default_place.priority == 0
    assert default_place.is_visited

    # Test initial-value place
    print("Test initial-value place:")
    new_place = Place("Malagar", "Spain", 1, False)
    print(new_place)
    assert new_place.name == "Malagar"
    assert new_place.country == "Spain"
    assert new_place.priority == 1
    assert not default_place.is_visited is False

    print("Test for making places visited")
    visited_test_place = Place("Townsville", "Australia", 9, False)
    assert visited_test_place.is_visited is False
    print(visited_test_place)
Beispiel #11
0
 def sorted(self, sort_choice):
     """sorting based on users choice"""
     self.root.ids.entries_box.clear_widgets()
     Place.sort(self, OPTIONS[sort_choice])
     self.show_place()
     self.root.ids.visit.text = "Place to visist: " + str(
         Place.visit_place(self))
Beispiel #12
0
    def __init__(self):
        pygame.init()
        config.screen = pygame.display.set_mode(
            (config.screen_width, config.screen_height))
        config.screen.fill(colors.white)
        new_snake = Snake()
        config.snakes += [new_snake]
        place = Place()

        config.process = True

        while config.process:
            for i in pygame.event.get():
                if i.type == pygame.QUIT:  #ыыыыыыыыыыыыы
                    exit()
            pressed = pygame.mouse.get_pressed()
            if pressed[0]:
                speeding = 2
            else:
                speeding = 1
            for s in config.snakes:
                s.move(speeding)
            while config.food_energy + config.snake_energy < config.max_energy:  # Ну или сколько там
                new_food = Food()
                config.all_food += [new_food]
            config.screen.fill(colors.black)
            for f in config.all_food:
                f.draw(new_snake.coords)
            for s in config.snakes:
                s.draw()
            place.draw(new_snake.coords)
            pygame.display.update()
            pygame.time.delay(40)
Beispiel #13
0
class Times:
    def __init__(self, cinemaID, kinoID):
        self.time = []
        for db in DB().select(
                "Time", "*",
                "cinema_id=" + str(cinemaID) + " AND kino_id=" + str(kinoID)):
            arr = {}
            arr["id"] = db[0]
            arr['time'] = db[3]
            arr['price'] = db[4]
            self.time.append(arr)
        self.chosenID = None

    def getTimes(self):
        return self.time

    def setChosenTime(self, id):
        self.chosenID = id
        self.place = Place(self.chosenID)

    def getPlace(self):
        return self.place.getPlaces()

    def setChosenPlaces(self, place):
        self.place.setChosenPlaces(place)
Beispiel #14
0
def make_places():
    places = []
    for i in range(69):
        places.append(Place(i))
    areas = []
    for i in range(5):
        areas.append(Place(i))
    return places, areas
Beispiel #15
0
def add_place(places):
    """Add new place to places list"""
    name, country, priority = get_valid_input()
    new_place = Place(name, country, priority, False)
    # if statement so print statement doesn't return 'None' if new place isn't important
    if new_place.is_important():
        print(new_place.is_important())
    places.append(new_place)
Beispiel #16
0
 def quit(self, player):
     Place.quit(self, player)
         
     self._game.game_over(True)
     
     self._turn_list.remove(player)
     if self._owner == player and self._turn_list:
         self._owner = self._turn_list[0]
Beispiel #17
0
 def set_en_passant(self, src, tgt):
     piece = self[src]
     src_x, src_y = src.coords
     tgt_x, tgt_y = tgt.coords
     if piece.id == 'p' and abs(tgt_y - src_y) == 2:
         for addx, addy in ((1, 0), (-1, 0)): #TODO refactor
             plc = Place((tgt_x + addx, tgt_y + addy))
             if self.inside_at(plc) and str(self[plc]) == f'{self.enemy}p':
                 self[plc].can_en_passant = (plc, Place((src_x, (tgt_y + src_y) // 2)), tgt) #GOTO; ATTACK
 def __init__(self, name, description):
     """
     Initialize UniquePlace object.
     
     @param name:           The name of the UniquePlace.
     @param description:    A description of the UniquePlace.
     """
     #Call parent class init function
     Place.__init__(self, name, description)
Beispiel #19
0
def run_tests():
    """Test PlaceCollection class."""

    # Test empty PlaceCollection (defaults)
    print("Test empty PlaceCollection:")
    place_collection = PlaceCollection()
    print(place_collection)
    assert not place_collection.places  # an empty list is considered False

    # Test get_unvisited method
    print("Test get_unvisited method:")
    p = PlaceCollection()
    place1 = Place("Sydney", "Australia", 3, True)
    place2 = Place("New York", "USA", 4, False)
    place3 = Place("Tokyo", "Japan", 1, True)
    p.add_place(place1)
    p.add_place(place2)
    p.add_place(place3)
    print(p)
    print("{} total unvisited places".format(p.get_unvisited()))

    # Test loading places
    print("Test loading places:")
    place_collection.load_places('places.csv')
    print(place_collection)
    assert place_collection.places  # assuming CSV file is non-empty, non-empty list is considered True

    # Test adding a new Place with values
    # print("Test adding new place:")
    # place_collection.add_place(Place("Smithfield", "Australia", 5, False))
    # print(place_collection)

    # Test sorting places
    print("Test sorting - priority:")
    place_collection.sort_places("priority")
    print(place_collection)

    # Test sorting places
    print("Test sorting - name:")
    place_collection.sort_places("name")
    print(place_collection)

    # Test sorting places
    print("Test sorting - country:")
    place_collection.sort_places("country")
    print(place_collection)

    # Test sorting places
    print("Test sorting - visited:")
    place_collection.sort_places("is_visited")
    print(place_collection)

    # Test saving places (check CSV file manually to see results)
    print("Test saving")
    place_collection.save_places('places.csv')
    assert place_collection.places
 def __init__(self, name, description, greetings):
     """
     Initialize UniquePlace object.
     
     @param name:            The name of the UniquePlace.
     @param description:     A description of the UniquePlace.
     @param greetings:       The greetings the user gets as he enters.
     """
     #Call parent class init function
     Place.__init__(self, name, description, greetings)
Beispiel #21
0
def test_interval() :
    tz = tzlocal.get_localzone()
    place = Place(nkpCoord())
    place.findSunTimes()
    interval = TimeInterval(SunriseTimepoint(datetime.timedelta(hours = 1), place),
                            AbsoluteTimepoint(datetime.time(13, 10, 5, 0, tz)))
    print str(interval.within(datetime.time(12, 10, 5, 0, tz))) + ' expected true.'
    print str(interval.within(datetime.time(13, 10, 6, 0, tz))) + ' expected false.'
    print str(interval.within(datetime.time(5, 10, 5, 0, tz))) + ' expected false.'
    print str(interval.within(datetime.time(8, 10, 5, 0, tz))) + ' expected true.'
Beispiel #22
0
 def sorted(self, sort_choice) :
     """This method is used for sorting based on users choice"""
     self.root.ids.entries_box.clear_widgets ( )
     """To make sure the same button is created the widget will be cleared"""
     Place.sort (self, OPTIONS [ sort_choice ])
     """It will call Place method for sorting based on the choice in the dictionary"""
     self.show_place ( )
     """This method is used for showing the place based on the data in button widget form after its being cleared"""
     self.root.ids.visit.text = "Place to visist: " + str (Place.visit_place (self))
     """After it will be sorted it will show the place needed to visit"""
def run_tests():
    """Test Place class."""

    # Test empty place (defaults)
    print("Test empty place:")
    default_place = Place()
    print(default_place)
    # assert default_place.name == ""
    # assert default_place.country == ""
    # assert default_place.priority == 0
    # assert not default_place.is_visited

    # Test initial-value place
    print("Test initial-value place:")
    new_place = Place("Malagar", "Spain", 1, False)

    # TODO: Write tests to show this initialisation works

    print(new_place)
    # TODO: Add more tests, as appropriate, for each method
    # test mark_visited
    new_place.mark_visited()
    print(new_place)

    # test mark_unvisited
    new_place.mark_unvisited()
    print(new_place)

    # test isimportant place
    new_place.isimportant()
Beispiel #24
0
 def __init__(self, stare_ref, player, name, passwd, hall_ref):
     Place.__init__(self, stare_ref)
     
     self._owner = player
     self._name = name
     self._passwd = passwd
     self._hall_ref = hall_ref
     self._player_list[player._account] = player
     self._turn_list = [player]
     player._loc_ref = weakref.ref(self)
     self._game = Game(weakref.ref(self))
Beispiel #25
0
def getPlace(placeId):
    url = placeAPIBase + "placeid=" + placeId + key_text

    response = requests.get(url)

    placeJson = response.json()
    placeInfo = Place(placeJson["result"]["url"], placeJson["result"]["id"],
                      placeJson["result"]["name"], "TEST")
    placeInfo.toString()

    return placeInfo
Beispiel #26
0
    def nextHand(self, board, previousMove, isBlack):
        if isBlack:
            if not board.canBlackPlace:
                return Place(-1, -1)
        else:
            if not board.canWhitePlace:
                return Place(-1, -1)

        if self.is_random:
            return self.randomNextHand(board, isBlack)

        return self.simpleBdSearchNextHand(board, previousMove, isBlack)
Beispiel #27
0
 def load_places(self, file_name):
     """Load place information from csv to list, return a place list"""
     file = open(file_name, "r")
     content = file.readlines()  # read the whole file
     for i in content:
         place = i.strip('\n').split(',')
         if place[3] == 'v':
             new_place = Place(place[0], place[1], place[2], True)
             self.places.append(new_place)
         elif place[3] == 'n':
             new_place = Place(place[0], place[1], place[2], False)
             self.places.append(new_place)
     file.close()
Beispiel #28
0
    def __init__(self, name, description, greetings, buildings = None):
        """
        Initializes the city.

        @param name:           The name of the city.
        @param description:    A description of the city.
        @param greetings:      The greetings the user gets as he enters the 
                               city.
        @param buildings:      A list of the buildings in the city.
        """
        #Call parent's init method
        Place.__init__(self, name, description, greetings)
        
        self._buildings = buildings
Beispiel #29
0
    def press_entry(self, button):  #Function that displays the 2nd message
        buttonID = button.id  #Determine the id on the widget buttons
        selectedPlace = Place()
        for place in self.place_list.places:
            #Loop the Place within the Place list

            if buttonID == place.name:
                selectedPlace = place
                break

        message = ""
        #Mark the Place visited/unvisited
        if selectedPlace.is_visited == 'v':
            selectedPlace.mark_unvisited()
            if selectedPlace.is_important():
                message = "You need to visited {}.Get going!".format(
                    selectedPlace.name)
            else:
                message = "You need to visited {}.".format(selectedPlace.name)
        else:
            selectedPlace.mark_visited()
            if selectedPlace.is_important():
                message = "You visited {}.Great travelling!".format(
                    selectedPlace.name)
            else:
                message = "You visited {}.".format(selectedPlace.name)
        self.root.ids.entriesBox.clear_widgets()  #Apply to Kivy GUI
        self.create_widgets()
        self.message2 = message
def add_place(place_lists):
    """Add user input of place to list"""
    name = check_input_text("Name: ")  # assign variable to called function
    country = check_input_text(
        "country: ")  # assign variable to called function
    priority = check_priority_format()  # assign variable to called function

    # store user input as new list first and mark the place as unvisited
    save_data = Place(name, country, str(priority), False)
    save_data.get_visited_unvisited()

    # add stored list into place_lists
    place_lists.append(save_data)
    print('{} by {} ({}) added to place list'.format(name, country, priority))
Beispiel #31
0
def run_tests():
    """Test Place class."""

    # Test empty place (defaults)
    print("Test empty place:")
    default_place = Place()
    print(default_place)
    assert default_place.name == ""
    assert default_place.country == ""
    assert default_place.priority == 0
    assert not default_place.is_visited

    # Test initial-value place
    print("Test initial-value place:")
    new_place = Place("Malagar", "Spain", 1, False)
    # TODO: Write tests to show this initialisation works
    assert new_place.name == "Malagar"
    assert new_place.country == "Spain"
    assert new_place.priority == 1
    assert not new_place.is_visited

    # TODO: Add more tests, as appropriate, for each method
    print("Test place mark visited")
    new_place.visited()
    assert new_place.is_visited
    print("Test place mark unvisited")
    new_place.unvisited()
    assert not new_place.is_visited
    print("Test place is important")
    assert new_place.is_important()
Beispiel #32
0
def run_tests():
    """Test Place class."""

    # Test empty place (defaults)
    print("Test empty place:")
    default_place = Place()
    print(default_place)
    assert default_place.name == ""
    assert default_place.country == ""
    assert default_place.priority == 0
    assert not default_place.is_visited

    # Test initial-value place
    print("Test initial-value place:")
    new_place = Place("Malagar", "Spain", 1, False)
Beispiel #33
0
def price():
    price = Price(request.form.get("price"), request.form.get("Currency"))
    incity = Place(request.form.get("incity")).name
    outcity = Place(request.form.get("outcity")).name
    date = "{}/{}/{}".format(request.form.get("day"),
                             request.form.get("month"),
                             request.form.get("year"))
    ids = cities_ids(incity, outcity, "files\\ids.txt")
    #coefficient = price.currency_coefficient("USD")
    coefficient = 0.037216
    while True:
        try:
            search_id = get_search_id(ids[0], ids[1], date=date)
            break
        except:
            pass
    while True:
        try:

            get_tickets_json("files\\initial_tickets.json", search_id)
            dct = tickets_info(inpath="files\\initial_tickets.json",
                               search_id=search_id,
                               outpath="files\\final_tickets.json")
            break
        except:
            pass
    info = []
    place_in = Place(incity)
    place_out = Place(outcity)
    place_in.get_coordinates()
    place_out.get_coordinates()
    get_map([place_in, place_out],
            "templates\\map.html",
            location=list(place_out.coordinates))
    for num in dct.values():
        info.append([
            "Departure time: {}".format(num["departureTime"]),
            "Arrival time: {}".format(num["ar_time"]),
            "Number of stops: {}".format(num["stops"]),
            "Company: {}".format(num["companyName"]), "Price: {}".format(
                str(round(num["price"] / coefficient,
                          2))), "Transport: {}".format(num["mode"]),
            "Departure station: {}".format(num["stations_dep"][0]["name"]),
            "Arrival station: {}".format(num["stattions_ar"][0]["name"]),
            num["url"]
        ])
    new_price = price.price * coefficient
    return render_template("price.html", new_price=new_price, info=info)
Beispiel #34
0
    def startElement(self, namespaceURI, localName, name, attrs):
        """Called on every start element of XML file.

        On elements from xapi creates Place object and set attributes.
        On elements from nominatim sets display_name(address) and if place
        is valid, add it to the Places.
        """
        # Node from xapi - create Place
        if name == "node":
            self._place = Place(str(attrs.value("id")))
            self._place.set_lat(str(attrs.value("lat")))
            self._place.set_lon(str(attrs.value("lon")))
        # Tag from xapi - assign name and type
        elif name == "tag":
            if attrs.value("k") == "name":
                self._place.set_name(unicode(attrs.value("v"), "utf-8"))
            elif attrs.value("k") == "amenity":
                if str(attrs.value("v")) in self._valid_types:
                    self._place.set_amenity(str(attrs.value("v")))
            elif attrs.value("k") == "website":
                self._place.set_website(unicode(attrs.value("v"), "utf-8"))
            elif attrs.value("k") == "cuisine":
                self._place.set_cuisine(unicode(attrs.value("v"), "utf-8"))
            elif attrs.value("k") == "opening_hours":
                self._place.set_opening_hours(unicode(attrs.value("v"),
                "utf-8"))
        # Place from nominatim - set display_name
        elif name == "reversegeocode":
            self._reverse_geo = True
            self._querystring = attrs.value("querystring")
        elif name == "result":
            if self._reverse_geo:
                self._osm_id = str(attrs.value("osm_id"))
        self._current_text = ""
        return True
Beispiel #35
0
    def __initialization(self, data):
        if data is None:
            raise Exception("Data is invalid")

        self.firstname = data.get('firstname', None)
        self.lastname = data.get(u'lastname', None)
        self.birthdate = data.get('birthdate', None)
        birthplace = data.get('birthplace', None)
        if birthplace is not None:
            self.birthplace = Place(birthplace)

        employers = data.get('work_experience', [])
        if isinstance(employers, list):
            for employer in employers:
                self.work_experience.append(
                    Employer(employer)
                )

        degrees = data.get('education', [])
        if isinstance(degrees, list):
            for degree in degrees:
                self.education.append(Degree(degree))

        contacts = data.get('contacts', [])
        if isinstance(contacts, list):
            for contact in contacts:
                self.contacts.append(Contact.get_instance(contact))
Beispiel #36
0
 def load_places(self):
     open_file = open("places.csv", "r")
     for place in open_file.readlines():
         file = place.split(",")
         self.places_list.append(
             [Place(file[0], file[1], int(file[2]), file[3].strip())])
     open_file.close()
Beispiel #37
0
 def __setitem__(self, key, value):
     if type(key) is Place:
         self.board_list[key.idx] = value
     elif type(key) is tuple:
         self.board_list[Place(key).idx] = value
     else:
         self.board_list[key] = value
def run_tests():
    """Test PlaceCollection class."""

    # Test empty PlaceCollection (defaults)
    print("Test empty PlaceCollection:")
    place_collection = PlaceCollection()
    print(place_collection)
    assert not place_collection.places  # an empty list is considered False

    # Test loading places
    print("Test loading places:")
    place_collection.load_places('places.csv')
    print(place_collection)
    assert place_collection.places  # assuming CSV file is non-empty, non-empty list is considered True

    # Test adding a new Place with values
    print("Test adding new place:")
    place_collection.add_place(Place("Smithfield", "Australia", 5, False))
    print(place_collection)

    # Test sorting places
    print("Test sorting - priority:")
    place_collection.sort("priority")
    print(place_collection)

    print("Test sorting - name:")
    place_collection.sort("name")
    print(place_collection)
Beispiel #39
0
 def __getitem__(self, query):
     if type(query) is Place:
         return self.board_list[query.idx]
     elif type(query) is tuple:
         return self.board_list[Place(query).idx]
     elif type(query) in (int, slice):
         return self.board_list[query]
Beispiel #40
0
def result_to_plcae_obj(cityid, cityname, jobname, result):
    business_status = None
    if 'business_status' in result:
        business_status = result['business_status']
    formatted_address = None
    if 'formatted_address' in result:
        formatted_address = result['formatted_address']
    name = None
    if 'name' in result:
        name = result['name']
    opening_hours = None
    if 'opening_hours' in result:
        opening_hours = result['opening_hours']
    plus_code = None
    if 'plus_code' in result:
        plus_code = result['plus_code']
    rating = None
    if 'rating' in result:
        rating = result['rating']
    types = None
    if 'types' in result:
        types = result['types']
    user_ratings_total = None
    if 'user_ratings_total' in result:
        user_ratings_total = result['user_ratings_total']
    p = Place(cityid, cityname, jobname, business_status, formatted_address,
              name, opening_hours, plus_code, rating, types,
              user_ratings_total)
    return p
Beispiel #41
0
    def add_new_place(self):
        """
        adds new place to the place collection
        """
        # Get the text from the text inputs
        new_place = self.root.ids.new_place.text
        new_country = self.root.ids.new_country.text
        new_priority = self.root.ids.new_priority.text

        if new_place == BLANK_STRING or new_country == BLANK_STRING or new_priority == BLANK_STRING:
            self.update_program_status_bar("All fields must be completed")
        else:
            try:
                new_priority = int(new_priority)
                if new_priority < 0:
                    self.update_program_status_bar(
                        "Please enter a number >= 0")
                    self.update_program_status_bar(
                        "Please enter a number <= 0")
                else:
                    self.root.ids.new_place.text = BLANK_STRING
                    self.root.ids.new_country.text = BLANK_STRING
                    self.root.ids.new_priority.text = BLANK_STRING
                    self.place_collections.add_place(
                        Place(new_place, new_country, new_priority))
                    self.sort_places(self.root.ids.select_day.text)
                    self.update_program_status_bar(
                        "{} {} from {} Added".format(new_place, new_country,
                                                     new_priority))
            except ValueError:
                self.update_program_status_bar("Please enter a valid number")
            except TypeError:
                self.update_program_status_bar("Please enter a valid number")
Beispiel #42
0
def run_tests():
    """Test PlaceCollection class."""
    """Test empty PlaceCollection (defaults)"""
    print("Test empty PlaceCollection:")
    place_collection = PlaceCollection()
    print(place_collection)
    assert not place_collection.list_data  # an empty list is considered False
    """Test loading places"""
    print("Test loading places:")
    place_collection.read_places('places.csv')
    print(place_collection)
    assert place_collection.list_data  # assuming CSV file is non-empty, non-empty list is considered True
    """Test adding a new Place with values"""
    print("Test adding new place:")
    place_collection.add_place(Place("Smithfield", "Australia", 5, False))
    print(place_collection)
    """Test sorting - name:"""
    print("Test sorting - name:")
    place_collection.s_places("name")
    print(place_collection)
    """Test sorting - country:"""
    print("Test sorting - country:")
    place_collection.s_places("country")
    print(place_collection)
    """Test sorting places - priority"""
    print("Test sorting - priority:")
    place_collection.s_places("priority")
    print(place_collection)
    """Test sorting places - visited_status"""
    print("Test sorting - visited:")
    place_collection.s_places("visited")
    print(place_collection)
    """Test listing places"""
    print("Test listing:")
    place_collection.list_all_places()
Beispiel #43
0
def get_nearby_result(query, lat, lon, result_types):
	location_str = str(lat) + "," + str(lon)
	query_result = google_places.nearby_search(
		location=location_str, keyword=query,
		radius=20000, types=result_types)

	places = []
	length = min(query_result.places, 2)

	for g_place in query_result.places[:length]:
		place = Place(g_place.geo_location, g_place.name, g_place.place_id)
		g_place.get_details()
		place.set_detail(g_place.website)
		for photo in g_place.photos:
			photo.get(maxheight=500, maxwidth=500)
			place.add_image(photo.url)
		places.append(place)
	return places
Beispiel #44
0
class Person(object):
    """
    Person model
    """
    education = []
    work_experience = []
    firstname = ""
    lastname = ""
    birthdate = ""
    birthplace = ""
    contacts = []

    def __init__(self, data):
        self.__initialization(data)

    def __initialization(self, data):
        if data is None:
            raise Exception("Data is invalid")

        self.firstname = data.get('firstname', None)
        self.lastname = data.get(u'lastname', None)
        self.birthdate = data.get('birthdate', None)
        birthplace = data.get('birthplace', None)
        if birthplace is not None:
            self.birthplace = Place(birthplace)

        employers = data.get('work_experience', [])
        if isinstance(employers, list):
            for employer in employers:
                self.work_experience.append(
                    Employer(employer)
                )

        degrees = data.get('education', [])
        if isinstance(degrees, list):
            for degree in degrees:
                self.education.append(Degree(degree))

        contacts = data.get('contacts', [])
        if isinstance(contacts, list):
            for contact in contacts:
                self.contacts.append(Contact.get_instance(contact))

    def to_json(self):
        return {
            "firstname": self.firstname,
            "lastname": self.lastname,
            "birth":{
                "date": self.birthdate,
                "place": self.birthplace.to_json()
            },
            'education': [degree.to_json() for degree in self.education],
            'work_experience': [employer.to_json() for employer in self.work_experience],
            'contacts': [contact.to_json() for contact in self.contacts]
        }
 def to_dict(self):
     ''' Returns a hash of a booking in the database '''
     data = {}
     place = Place.get(Place.id == self.place)
     user = User.get(User.id == self.user)
     data['place_id'] = place.id
     data['user_id'] = user.id
     data['is_validated'] = self.is_validated
     data['date_start'] = self.date_start.strftime("%Y/%m/%d %H:%M:%S")
     data['number_nights'] = self.number_nights
     return super(PlaceBook, self).to_dict(self, data)
Beispiel #46
0
	def to_dict(self):
		place = Place.get(Place.id == self.place)
		user = User.get(User.id == self.user)
		data =  {	'id': self.id,
					'created_at': self.created_at.strftime('%Y/%m/%d %H:%M:%S'),
					'updated_at': self.updated_at.strftime('%Y/%m/%d %H:%M:%S'),
					'place_id': place.id,
					'user_id': user.id,
					'is_validated': self.is_validated,
					'date_start': self.date_start,
					'number_nights': self.number_nights	}

		return data
    def __init__(self, data):
        self.name = data.get('name', None)
        self.title = data.get('title', None)
        self.sector = data.get('sector', None)
        self.from_date = data.get('from_date', None)
        self.to_date = data.get('to_date', None)
        self.summary = data.get('summary', None)
        keywords = data.get('keywords', [])
        if not isinstance(keywords, list):
            keywords = []
        self.keywords = keywords

        place = data.get('place', None)
        if place is not None:
            self.place = Place(place)
class Employer(object):
    """
    Employer model that represents a real work experience
    """
    from_date = ""
    to_date = ""
    place = None
    summary = "",
    name = ""
    title = ""
    sector = "",
    keywords = []

    def __init__(self, data):
        self.name = data.get('name', None)
        self.title = data.get('title', None)
        self.sector = data.get('sector', None)
        self.from_date = data.get('from_date', None)
        self.to_date = data.get('to_date', None)
        self.summary = data.get('summary', None)
        keywords = data.get('keywords', [])
        if not isinstance(keywords, list):
            keywords = []
        self.keywords = keywords

        place = data.get('place', None)
        if place is not None:
            self.place = Place(place)

    def to_json(self):
        return {
            'name': self.name,
            'title': self.title,
            'sector': self.sector,
            'from_date': self.from_date,
            'to_date': self.to_date,
            'summary': self.summary,
            'keywords': self.keywords,
            'place': self.place.to_json() if not self.place is None else None
        }
Beispiel #49
0
def new_place_json(request):
    ''' Takes a GeoJSON string as POST data and saves it as a new place
         saves and returns back geojson for the place
    '''
        
    if not request.method == 'POST':
        return render_to_json_response({'error': 'Method Not Allowed'}, status=405)
        
    geojson = json.loads(request.body)
    if geojson.has_key("comment"):
        comment = geojson.pop("comment")
    else:
        comment = ''
    json_obj = geojson.pop("properties")
    json_obj['geometry'] = geojson['geometry']
    json_obj['centroid'] = []
    if geojson["geometry"]:
        centroid = GEOSGeometry(json.dumps(json_obj['geometry'])).centroid
        json_obj['centroid'] = list(centroid.coords)      
        
    p = Place(json_obj)
    
    import random, hashlib
    p.id = hashlib.md5(p.name + str(random.random())).hexdigest()[:16]        
    p.relationships = []

    if settings.GAZETTEER["url"]:
        uri = settings.GAZETTEER["url"] + "/gazetteer/feature/"+ p.id
    else:
        uri = "http://gazetteer.in/feature/"+p.id
    p.uris.append(uri)
    
    user_id = request.user.id
    username = request.user.username
    
    metadata = {
        'user': username,
        'user_id': user_id,
        'comment': comment
    }
    
    p.save(metadata=metadata)
    new_place = p.copy() #returns a copy of the newly saved place
    return render_to_json_response(new_place.to_geojson())
Beispiel #50
0
    def build(cls, data, start, end, center=None):
        
        log.info("Loading OpenPaths data...")

        if center is not None:
            points = [Point(i, float(d['lon']), float(d['lat']), d['t']) for i, d in enumerate(data) if d['t'] >= start and d['t'] <= end and science.geo_distance((float(d['lon']), float(d['lat'])), center) <= RADIUS]            
        else:
            points = [Point(i, float(d['lon']), float(d['lat']), d['t']) for i, d in enumerate(data) if d['t'] >= start and d['t'] <= end]                        
        points.sort(key=lambda p: p.t)                

        log.info("Generating graph...")
        start_clock = time.clock()  


        paths = Path.find_paths(points)
        places = Place.find_places(paths, CLUSTER_RADIUS)  
        cities = City.find_cities(places, CITY_RADIUS)
        almanac = Almanac(points, paths, places, cities)

        # almanac.label()        

        print("(%ss)" % (time.clock() - start_clock))

        return almanac
Beispiel #51
0
class OSMHandler(QXmlDefaultHandler):

    """Class processing XML data from OSM service and holding places.

    Class is procesing data from xapi.openstreetmap.org and from
    nominatim.openstreetmap.org.
    """

    def __init__(self, types, location, parent=None):
        """Initialize Places.

        @param types: list of allowed types of places
        @type types: list
        @param location: location from main aplication, needed for fall back
        @type location: Location
        @param parent: parent object
        @type parent: OSM
        """
        QXmlDefaultHandler.__init__(self)
        self._location = location
        self._parent = parent
        self._place = ""
        self._places = Places()
        self._valid_types = types
        self._error_str = ""
        self._reverse_geo = False
        self._current_text = ""
        self._querystring = ""
        self._osm_id = 0

    def startElement(self, namespaceURI, localName, name, attrs):
        """Called on every start element of XML file.

        On elements from xapi creates Place object and set attributes.
        On elements from nominatim sets display_name(address) and if place
        is valid, add it to the Places.
        """
        # Node from xapi - create Place
        if name == "node":
            self._place = Place(str(attrs.value("id")))
            self._place.set_lat(str(attrs.value("lat")))
            self._place.set_lon(str(attrs.value("lon")))
        # Tag from xapi - assign name and type
        elif name == "tag":
            if attrs.value("k") == "name":
                self._place.set_name(unicode(attrs.value("v"), "utf-8"))
            elif attrs.value("k") == "amenity":
                if str(attrs.value("v")) in self._valid_types:
                    self._place.set_amenity(str(attrs.value("v")))
            elif attrs.value("k") == "website":
                self._place.set_website(unicode(attrs.value("v"), "utf-8"))
            elif attrs.value("k") == "cuisine":
                self._place.set_cuisine(unicode(attrs.value("v"), "utf-8"))
            elif attrs.value("k") == "opening_hours":
                self._place.set_opening_hours(unicode(attrs.value("v"),
                "utf-8"))
        # Place from nominatim - set display_name
        elif name == "reversegeocode":
            self._reverse_geo = True
            self._querystring = attrs.value("querystring")
        elif name == "result":
            if self._reverse_geo:
                self._osm_id = str(attrs.value("osm_id"))
        self._current_text = ""
        return True

    def endElement(self, namespaceURI, localName, name):
        """Called on every end element of XML file."""
        # When we are at the end of node from xapi add place to places.
        if name == "node" and self._place.is_valid():
            self._places.add(self._place)
        # End of data from nominatim
        elif name == "result":
            if self._reverse_geo:
                self._places.set_display_name(self._osm_id, self._current_text)
                # Send places to dataengine
                self._parent.send_place(self._osm_id)
        elif name == "reversegeocode":
            self._reverse_geo = False
            self._osm_id = 0
        elif name == "error":
            if self._reverse_geo:
                self._error_str = self._current_text
                return False
        return True

    def characters(self, string):
        """Remember XML values."""
        self._current_text += unicode(string, "utf-8")
        return True

    def fatalError(self, exception):
        """Called in case of error.

        If nominatim can't find the id, try fall back mode.
        """
        if self._error_str == "OSM ID Not Found":
            try:
                (rest, osm_id) = str(self._querystring).rsplit("=", 1)
                self._places.set_display_name(osm_id, "%s, %s, %s" % \
                (self._places.search(osm_id).get_name(),
                self._location.getCity(), self._location.getCountry()), True)
                self._parent.send_place(osm_id)
            except Exception:
                pass
            return True
        raise Exception(self._error_str)

    def errorString(self):
        """Returns error string.

        @return: error string
        @rtype:str
        """
        return self._error_str

    def get_places(self):
        """Returns places.

        @return: places
        @rtype: Places
        """
        return self._places

    def clear_places(self):
        """Resets places."""
        self._places = Places()
Beispiel #52
0
 def __init__(self, stare_ref):
     Place.__init__(self, stare_ref)
     
     self._room_list = {}
Beispiel #53
0
    motifs[motif_id] = "\n".join(motif)
    return motifs


def join_meme(meme_motifs, motif_ids):
    '''
    meme_motifs[motif_id]=""
    motif_ids=[]
    '''
    return "\n".join([meme_motifs['header']] +
                 [meme_motifs[str(motif_id)] for motif_id in motif_ids])


if __name__ == '__main__':
    p = PlantCARE('plantcare.db')
    pl = Place('place.db')
    meme_slv = shelve.open("meme_motifs.slv")
    # meme_zslv = zshelve.open("meme_motifs.zslv")
    meme_motifs = jaspar2meme(
        '/home/gahoo/Project/jaspar/all_data/FlatFileDir/')
    # meme_motifs = split_meme(meme_motifs)
    #meme_slv['jaspar'] = split_meme(meme_motifs)
    meme_slv.update(split_meme(meme_motifs))
    # meme_zslv['jaspar'] = split_meme(meme_motifs)
    # print join_meme(meme_motifs, meme_motifs.keys()[5:9])
    meme_motifs = iupac2meme(p.getMotifSeq())
    # meme_motifs = split_meme(meme_motifs)
    #print join_meme(meme_motifs, meme_motifs.keys())
    #meme_slv['plantcare'] = split_meme(meme_motifs)
    meme_slv.update(split_meme(meme_motifs))
    # meme_zslv['plantcare'] = split_meme(meme_motifs)