def addStation(data): try: stationType_id = int(data["stationType"]) serialNum = data["serialNum"] latitude = float(data["latitude"]) longitude = float(data["longitude"]) frequency = data["frequency"] token = data["token"] # se recupera el tipo de estacion stationType = StationType.objects.get(id=stationType_id) automatic = stationType.automatic # se crea una estacion station = Station() station.serialNum = serialNum station.location = Point(longitude, latitude) station.active = True station.stationType = stationType # si la estacion es automatica # se agregan la frecuencia # y el token if (automatic == True): if (frequency == "" or token == ""): return "Error: faltan argumentos" frequency = float(frequency) if (frequency <= 0): return "Error: frecuencia debe ser mayor que cero" station.frequency = frequency station.token = token station.save() except Exception as e: return "Error " + str(e) return None
def submitstation(request): if request.method == 'POST': form = StationForm(request.POST) if form.is_valid(): cd = form.cleaned_data mystation = Station(lat = cd['latitude'], lon = cd['longitude'], why = cd['why'], comment = cd['comment'], creator = request.user, like = 0, dontlike= 0, dontcare = 0, nbsupports = 0, activated = 'A') mystation.save() mystations=Station.objects.all()[0:1] return HttpResponseRedirect('/stations?id={0}'.format(mystations[0].id)) else: form = StationForm() return render_to_response('submitstation.html', {'current_menu':'station', 'me': request.user.username, 'form': form}, context_instance=RequestContext(request))
def delete_Stationt(id): try: station = Station.query.get(id) Station.delete(station) except BaseException: abort(404) return jsonify({'Deleted Astronaut': id, 'success': True})
def _build_line_data(self, station_df): ''' Constructs all stations on the line ''' stations = station_df['station_name'].unique() station_data = station_df[station_df['station_name'] == stations[0]] line = [ Station(station_data['station_id'].unique()[0], stations[0], self.color) ] prev_station = line[0] for station in stations[1:]: station_data = station_df[station_df['station_name'] == station] new_station = Station( station_data['station_id'].unique()[0], station, self.color, prev_station, ) prev_station.dir_b = new_station prev_station = new_station line.append(new_station) return line
def _build_line_data(self, station_df): """Constructs all stations on the line""" stations = station_df["station_name"].unique() print('stations:', stations) station_data = station_df[station_df["station_name"] == stations[0]] line = [ Station(station_data["station_id"].unique()[0], stations[0], self.color) ] prev_station = line[0] for station in stations[1:]: station_data = station_df[station_df["station_name"] == station] new_station = Station( station_data["station_id"].unique()[0], station, self.color, prev_station, ) prev_station.dir_b = new_station prev_station = new_station line.append(new_station) #print('line:', type(line), len(line), line) #for item in line: # print(item) return line
def _build_line_data(self, station_df): """Constructs all stations on the line""" stations = station_df["station_name"].unique() logger.info(f"\nunique statns: {stations}") station_data = station_df[station_df["station_name"] == stations[0]] # logger.info(f"{station_data}") line = [ Station(station_data["station_id"].unique()[0], stations[0], self.color) ] prev_station = line[0] for station in stations[1:]: station_data = station_df[station_df["station_name"] == station] new_station = Station( station_data["station_id"].unique()[0], station, self.color, prev_station, ) prev_station.dir_b = new_station prev_station = new_station line.append(new_station) return line
def _build_line_data(self, station_df): """Constructs all stations on the line""" logging.debug("line - _build_line_data") stations = station_df["station_name"].unique() station_data = station_df[station_df["station_name"] == stations[0]] line = [ Station(station_data["station_id"].unique()[0], stations[0], self.color) ] prev_station = line[0] for station in stations[1:]: station_data = station_df[station_df["station_name"] == station] new_station = Station( station_data["station_id"].unique()[0], station, self.color, prev_station, ) prev_station.dir_b = new_station prev_station = new_station logging.info(f"new_station: {new_station}") line.append(new_station) return line
def add_Station(): try: data = json.loads(request.data) print(data) station = Station(CrewCapacity=data['crewcapacity'], FuelCapacity=data['fuelcapacity']) Station.insert(station) except BaseException: abort(403) return paginate_Station()
def post(self, request): response_data = { 'retCode': error_constants.ERR_STATUS_SUCCESS[0], 'retMsg': error_constants.ERR_STATUS_SUCCESS[1] } try: station_id = int(request.POST.get('stationId')) name = request.POST.get('name') location = request.POST.get('location') channel = request.POST.get('channel', '') call_sign = request.POST.get('callSign', '') remark_1 = request.POST.get('remark1', '') remark_2 = request.POST.get('remark2', '') remark_3 = request.POST.get('remark3', '') except Exception as ex: print 'function name: ', __name__ print Exception, ":", ex return generate_error_response( error_constants.ERR_INVALID_PARAMETER, status.HTTP_400_BAD_REQUEST) cur_station = Station.objects.get(id=station_id) district_id = cur_station.district_id section_id = cur_station.section_id new_station = Station(name=name, location=location, channel=channel, remark1=remark_1, call_sign=call_sign, remark2=remark_2, remark3=remark_3, district_id=district_id) try: with transaction.atomic(): new_station.save() except Exception as ex: print 'function name: ', __name__ print Exception, ":", ex return generate_error_response( error_constants.ERR_SAVE_INFO_FAIL, status.HTTP_500_INTERNAL_SERVER_ERROR) chief = cur_station.chief.all() trans = cur_station.exec_chief_trans.all() for item in chief: new_station.chief.add(item) for item in trans: new_station.exec_chief_trans.add(item) # 路的段/岗数量更新 if section_id: road_id = Section.objects.get(id=section_id).road_id if road_id: cur_guard_road = guard_road.objects.filter(uid=road_id + increment) cur_guard_road.update(sectionnum=F('stationnum') + 1) return Response(response_data, status.HTTP_200_OK)
def handle_result(self, tree): stations = [] ns = "http://www.etis.fskab.se/v1.0/ETISws" for station in tree.find('.//{%s}NearestStopAreas' % ns): s = Station() s.name = station.find('.//{%s}Name' % ns).text s.key = station.find('.//{%s}Id' % ns).text X = int(station.find('.//{%s}X' % ns).text) Y = int(station.find('.//{%s}Y' % ns).text) (s.lat, s.lon) = util.RT90_to_WGS84(X, Y) stations.append(s) return [model_to_dict(s) for s in stations]
def create_neo_db(): # Create temporary station and vehicle tmp_station = Station(short='STATI', name='Station', latitude=10.0, longitude=10.0).save() tmp_vehicle = Vehicle(code='100').save() spatial_query = "CALL spatial.addPointLayer('spati')" neo_db.cypher_query(query=spatial_query) tmp_station.delete() tmp_vehicle.delete()
def populate_by_qs(s, output=stdout): encoded_s = s.encode('utf-8') output.write('QUERYING FOR %s\n' % encoded_s) body = send_req('querystation.asp', {'inpPointFr': encoded_s}) tree = ElementTree() tree.parse(StringIO(body)) root = tree.getroot() points = root.getiterator(NS + 'Point') for point in points: station = Station() station.identifier = int(point.find(NS + 'Id').text) try: station = Station.objects.get(identifier=station.identifier) except Station.DoesNotExist: station.name = point.find(NS + 'Name').text station.x = int(point.find(NS + 'X').text) station.y = int(point.find(NS + 'Y').text) station.save() output.write(' STORED %s\n' % station.name.encode('utf-8')) except Station.MultipleObjectsReturned: output.write(' ERROR %d, %s\n' % (station.identifier, station.name.encode('utf-8'))) else: # output.write(' IGNORE %s\n' % (station.name.encode('utf-8'))) pass
def iepginput(d): a_title = Title(name=d['program-title']) b_waves = Waves(name=d['station']) c_station = Station(name=d['station-name']) d_comments = Comments(name=d['comment']) op = timeset(d, start) ed = timeset(d, end) sg1 = d['genre-1'] * 16 + d['subgenre-1'] if d['genre-2'] == 0: x = Program(title=a_title, program_id=d['program-id'], waves=b_waves, station=c_station, start=op, end=ed, gen_1=d['genre-1'], sgn_1=sg1, comments=d_comments) x.save else: sg2 = d['genre-2'] * 16 + d['subgenre-2'] x = Program(title=a_title, program_id=d['program-id'], waves=b_waves, station=c_station, start=op, end=ed, gen_1=d['genre-1'], sgn_1=sg1, gen_2=d['genre-2'], sgn_2=sg2, comments=d_comments) x.save
def process_data(data): # first decouple binary data barr = bytearray(data) proto = UnicornProto.from_buffer(barr) print proto.device for field in proto._fields_: print field[0], getattr(proto, field[0]) #get device station, _ = Station.get_or_create(device_id=proto.device, ) # store parsed data into DB measured = Measurement.create( station=station, timestamp=proto.timestamp, temperature=proto.temperature, humidity=proto.humidity, pressure=proto.pressure, CO2=proto.CO2, light=proto.light, snow=proto.snow_intensity, rain=proto.rain_intensity, battery=proto.battery, ) return measured
def get_closest_stations(self, request, **kwargs): self.method_check(request, allowed=['get']) self.throttle_check(request) lat = float(request.GET['lat']) long = float(request.GET['long']) city_code = request.GET.get('city', None) num_stations = int(request.GET.get('num', 1)) city = None if city_code: city = City.available.get(code=city_code) stations = Station.closest_stations(lat, long, city, num_stations) objects = [] for (distance, station) in stations: bundle = self.build_bundle(obj=station, request=request) bundle = self.full_dehydrate(bundle) objects.append({ 'distance': distance, 'station': bundle }) object_list = { 'objects': objects, } self.log_throttled_access(request) return self.create_response(request, object_list)
def get_closest_stations(self, request, **kwargs): self.method_check(request, allowed=['get']) self.throttle_check(request) lat = float(request.GET['lat']) long = float(request.GET['long']) city_code = request.GET.get('city', None) num_stations = int(request.GET.get('num', 1)) city = None if city_code: city = City.available.get(code=city_code) stations = Station.closest_stations(lat, long, city, num_stations) objects = [] for (distance, station) in stations: bundle = self.build_bundle(obj=station, request=request) bundle = self.full_dehydrate(bundle) objects.append({'distance': distance, 'station': bundle}) object_list = { 'objects': objects, } self.log_throttled_access(request) return self.create_response(request, object_list)
def get_stations_for_journey_time_update(self) -> Iterable[Station]: docs: Iterable[DocumentSnapshot] = self._destinations\ .order_by('journey_times_updated')\ .limit(1)\ .get() return map(lambda doc: Station.from_dict(doc.to_dict()), docs)
def _handle_station(self, value): """Adds the station to this Line's data model""" if value["line"] != self.color: return self.stations[value["station_id"]] = Station.from_message(value) logger.info('handled station %s, added into %s line' % (value["station_id"], self.color))
def _handle_station(self, value): ''' Adds the station to this Line's data model ''' if value['line'] != self.color: return self.stations[value['station_id']] = Station.from_message(value)
def _handle_station(self, value): """Adds the station to this Line's data model""" station_id = value["station_id"] if value["line"] == self.color: station = Station.from_message(value) self.stations[station_id] = station logger.debug("[%s line] added station %d: %s", value["line"], station_id, station.station_name)
def get_stations_for_journey_costs_update(self) -> Iterable[Station]: this_year = date.today().year docs: Iterable[DocumentSnapshot] = self._destinations\ .where('journey_costs_updated', '<', datetime(this_year, 1, 1))\ .order_by('journey_costs_updated')\ .limit(1).get() return map(lambda doc: Station.from_dict(doc.to_dict()), docs)
def on_get(self, req, resp, name=None): try: if not name: result = list(Station.select().dicts()) else: result = model_to_dict(Station.get(name=name)) except Exception as ex: self.logger.error(ex) print ex description = ('Aliens have attacked our base! We will ' 'be back as soon as we fight them off. ' 'We appreciate your patience.') raise falcon.HTTPServiceUnavailable('Service Outage', description, 30) resp.context['result'] = result resp.status = falcon.HTTP_200
def station(): station = Station(request.form['name'], request.form['lat'], request.form['lng']) db.session.add(station) db.session.commit() return jsonify(Station.query.get(station.id).json())
def get(self): station_name = self.request.get("station") genre = self.request.get("genre") station = Station.get(station_name) self.response.headers[b"Content-Type"] = b"application/json; charset=utf-8" data = json.dumps(station.to_dict(genre), ensure_ascii=False) self.response.write(data)
def pack_station_for_list_views(wban, months): station = Station.get(Station.WBAN == wban) station_data = {'wban': station.WBAN} station_data['name'] = station.attributes.get('Name', 'n/a') station_data['state'] = station.attributes.get('State', 'n/a') station_data['station_data'] = months return station_data
def _handle_station(self, value): """Adds the station to this Line's data model""" line = value.get("line") self.stationsCount += 1 print(f"STATIONS:{self.stationsCount}") if value["line"] != self.color: self.noStations += 1 print(f"NO STATIONS:{self.noStations}") return self.stations[value["station_id"]] = Station.from_message(value)
def get_station_states(): qs = Station.select(Station.attributes['State'].alias('state')).where(Station.attributes['State'] != 'None')\ .order_by(Station.attributes['State']).distinct() choices = [ ('none', 'Please select'), ] for station in qs: choices.append((station.state, station.state)) return choices
def _build_line_data(self, station_df): stations = station_df["station_name"].unique() station_data = station_df[station_df["station_name"] == stations[0]] line = [ Station(station_data["station_id"].unique()[0], stations[0], self.color) ] prev_station = line[0] for station in stations[1:]: station_data = station_df[station_df["station_name"] == station] new_station = Station( station_data["station_id"].unique()[0], station, self.color, prev_station, ) prev_station.dir_b = new_station prev_station = new_station line.append(new_station) return line
def get(self, state): weather = get_previous_selections() stations = [] queryset = Station.select().where(Station.attributes['State'] == state) for station in queryset: if station.attributes.get('Name'): stations.append({ "code": station.WBAN, "name": station.attributes['Name'] }) return jsonify(select_option=weather['station'], stations=stations)
def _handle_station(self, value): """Adds the station to this Line's data model""" logger.info( f"In Line({self.color}), creating station:{json.dumps(value, indent=2)}" ) if (value["line"] != self.color): logger.warning( f"Oops...station msg to wrong line. color: {self.color}") return self.stations[value["station_id"]] = Station.from_message(value)
def sample_data(): station = Station(id=3, name='lelkek', lat=32.551, lng=64.112, is_outside=False) bike = Bike(id=4, can_be_rented=False, can_be_returned=False, version=2, marke_id=23, marke_name="Kekrad", is_pedelec=False) location = TemporalLocation(time_from=datetime.now(), time_to=datetime.now()) location.bike = bike location.station = station return station, bike, location
def post(self): import urllib data = urllib.unquote(self.request.body) data = json.loads(data) stations = data["stations"] stores = data["stores"] stores_by_station = {} for k, v in groupby(stores, lambda x: x["station_id"]): stores_by_station[k] = list(v) for station in stations: s = Station(id=station["id"], name=station["name"], lat=station["lat"], lng=station["lng"]) s.put() for store in stores: s = Store(station_id=store["station_id"], name=store["name"], genre=store["genre"], lat=store["lat"], lng=store["lng"]) s.put() self.response.headers[b"Content-Type"] = b"application/json; charset=utf-8" self.response.write(json.dumps({"status": "success"}, ensure_ascii=False))
def load_stops(): session = Session() stops = parse_stops() stations = [] for stop in stops: if stop['parent'] == '': stations.append( Station(stop['sid'], stop['name'], stop['lat'], stop['lng'])) session.add_all(stations) session.commit()
def _build_line_data(self, station_df) -> List[Station]: """Constructs all stations on the line""" stations: List[str]=station_df["station_name"].unique() station_data=station_df[station_df["station_name"] == stations[0]] line: List[Station]=[ Station(station_data["station_id"].unique()[0], stations[0], self.color) ] prev_station=line[0] for station in stations[1:]: station_data=station_df[station_df["station_name"] == station] new_station=Station( station_data["station_id"].unique()[0], station, self.color, prev_station, ) prev_station.dir_b=new_station prev_station=new_station line.append(new_station) return line
def _build_line_data(self, station_df): """Constructs all stations on the line""" stations = station_df["station_name"].unique() station_data = station_df[station_df["station_name"] == stations[0]] line = [ Station(station_data["station_id"].unique()[0], stations[0], self.color) ] prev_station = line[0] for station in stations[1:]: station_data = station_df[station_df["station_name"] == station] new_station = Station( station_data["station_id"].unique()[0], station, self.color, prev_station, ) prev_station.dir_b = new_station prev_station = new_station line.append(str(new_station).encode('utf8')) return line
def create_station(session, service_provider_id, name="TestStation", no_commit=False): station = Station(-1, name) station.service_provider_id = service_provider_id station.short_name = name[:8] station.medium_name = name[:16] station.long_name = name[:64] station.short_description = name[:128] station.radioepgpi_enabled = True session.add(station) if not no_commit: session.commit() time.sleep(config.SPI_GENERATION_INTERVAL * 3) return station
def stations(): response.content_type = 'application/json' #mc_key = md5("stations") #stations = MC.get(mc_key) stations = Station.objects() return json.dumps([s.to_dict() for s in stations],indent=4)
def range_hourly(station_id, year_start, year_end, month_start, month_end, day_start, local_tz_name): """ Calls Environment Canada endpoint and parses the returned XML into StationData objects. Keyword arguments: station_id -- Integer corresponding to an Environment Canada station ID (ie. location of weather reading). year_start -- Integer indicating the year of the first weather history request. year_end -- Integer indicating the year of the last weather history request (inclusive). In combination with month_start and month_end, all weather history between start and end times will be requested. month_start -- Integer indicating the month of the first weather history request. month_end -- Integer indicating the month of the last weather history request (inclusive). In combination with year_start and year_end, all weather history between start and end times will be requested. day_start -- Integer indicating the starting day of the forecast, though multiple days of forecasted data will be returned. local_tz_name -- String representation of local timezone name (eg. 'America/Toronto'). Return: Two two-item vector [station, observations] where station is a model.Station object and observations is a list of hourly model.Observation objects. """ # Instantiate objects that are returned by this method station = None observations = list() y = year_start m = month_start d = day_start req_date = datetime(y, m, d) end_date = datetime(year_end, month_end, day_start) while req_date <= end_date: xml_response = fetch_content(station_id=station_id, year_num=y, month_num=m, day_num_start=d, timeframe=1, frmt='xml') xml_string = xml_response.read().decode('utf-8') weather_root = ElementTree.fromstring(xml_string) # Only populate Station once if station == None: station = Station() station.station_id = station_id station.local_tz_str = local_tz_name station_local_tz = pytz.timezone(local_tz_name) epoch = datetime.utcfromtimestamp(0) offset_delta = station_local_tz.utcoffset(epoch) station_std_tz = timezone(offset_delta) for si_elmnt in weather_root.iter('stationinformation'): name_txt = si_elmnt.find('name').text if name_txt and name_txt != ' ': station.name = name_txt province_txt = si_elmnt.find('province').text if province_txt and province_txt != ' ': station.province = province_txt latitude_txt = si_elmnt.find('latitude').text if latitude_txt and latitude_txt != ' ': station.latitude = float(latitude_txt) longitude_txt = si_elmnt.find('longitude').text if longitude_txt and longitude_txt != ' ': station.longitude = float(longitude_txt) elevation_txt = si_elmnt.find('elevation').text if elevation_txt and elevation_txt != ' ': station.elevation = float(elevation_txt) climate_id_txt = si_elmnt.find('climate_identifier').text if climate_id_txt and climate_id_txt != ' ': station.climate_identifier = int(climate_id_txt) # Iterate stationdata XML elements and append Observations to list for sd_elmnt in weather_root.iter('stationdata'): observation = Observation() # Get portions of date_time for observation year_txt = sd_elmnt.attrib['year'] month_txt = sd_elmnt.attrib['month'] day_txt = sd_elmnt.attrib['day'] hour_txt = sd_elmnt.attrib['hour'] minute_txt = sd_elmnt.attrib['minute'] if year_txt and month_txt and day_txt and hour_txt and minute_txt: observation.obs_datetime_std = datetime(year=int(year_txt), month=int(month_txt), day=int(day_txt), hour=int(hour_txt), minute=int(minute_txt), second=0, microsecond=0, tzinfo=station_std_tz) observation.obs_datetime_dst = observation.obs_datetime_std.astimezone(station_local_tz) if 'quality' in sd_elmnt.attrib: quality_txt = sd_elmnt.attrib['quality'] else: quality_txt = None if quality_txt and quality_txt != ' ': observation.obs_quality = quality_txt # Set StationData fields based on child elements' values observation.station_id = station_id temp_txt = sd_elmnt.find('temp').text if temp_txt and temp_txt != ' ': observation.temp_c = float(temp_txt) dptemp_txt = sd_elmnt.find('dptemp').text if dptemp_txt and dptemp_txt != ' ': observation.dewpoint_temp_c = float(dptemp_txt) relhum_txt = sd_elmnt.find('relhum').text if relhum_txt and relhum_txt != ' ': observation.rel_humidity_pct = int(relhum_txt) winddir_txt = sd_elmnt.find('winddir').text if winddir_txt and winddir_txt != ' ': observation.wind_dir_deg = int(winddir_txt) * 10 windspd_txt = sd_elmnt.find('windspd').text if windspd_txt and windspd_txt != ' ': observation.wind_speed_kph = int(windspd_txt) visibility_txt = sd_elmnt.find('visibility').text if visibility_txt and visibility_txt != ' ': observation.visibility_km = float(visibility_txt) stnpress_txt = sd_elmnt.find('stnpress').text if stnpress_txt and stnpress_txt != ' ': observation.station_pressure_kpa = float(stnpress_txt) humidex_txt = sd_elmnt.find('humidex').text if humidex_txt and humidex_txt != ' ': observation.humidex = float(humidex_txt) windchill_txt = sd_elmnt.find('windchill').text if windchill_txt and windchill_txt != ' ': observation.wind_chill = int(windchill_txt) observation.weather_desc = sd_elmnt.find('weather').text # Add StationData element to list observations.append(observation) # Increment year and month to populate date range if m < 12: m += 1 else: y += 1 m = 1 req_date = datetime(y, m, d) # Return XML elements parsed into a list of StationData objects return [station, observations]