text:
/*
 * This file was originally distributed by Qualcomm Atheros, Inc.
 * under proprietary terms before Copyright ownership was assigned
 * to the Linux Foundation.
 */

#ifndef __WLAN_HDD_TRACE_H__
#define __WLAN_HDD_TRACE_H__

#include "macTrace.h"

#define NO_SESSION 0xFF

enum
{
    TRACE_CODE_HDD_OPEN_REQUEST,
    TRACE_CODE_HDD_STOP_REQUEST,
    TRACE_CODE_HDD_TX_TIMEOUT,
    TRACE_CODE_HDD_P2P_DEV_ADDR_IOCTL,
    TRACE_CODE_HDD_SETSUSPENDMODE_IOCTL,
    TRACE_CODE_HDD_SETROAMTRIGGER_IOCTL,
    TRACE_CODE_HDD_GETROAMTRIGGER_IOCTL,
    TRACE_CODE_HDD_SETROAMSCANPERIOD_IOCTL,
    TRACE_CODE_HDD_GETROAMSCANPERIOD_IOCTL,
    TRACE_CODE_HDD_SETROAMDELTA_IOCTL,
    TRACE_CODE_HDD_GETROAMDELTA_IOCTL,
    TRACE_CODE_HDD_GETBAND_IOCTL,
    TRACE_CODE_HDD_GETCOUNTRYREV_IOCTL,
    TRACE_CODE_HDD_SETROAMSCANCHANNELS_IOCTL,
    TRACE_CODE_HDD_GETROAMSCANCHANNELS_IOCTL,
    TRACE_CODE_HDD_HOSTAPD_OPEN_REQUEST,
    TRACE_CODE_HDD_HOSTAPD_STOP_REQUEST,
    TRACE_CODE_HDD_HOSTAPD_UNINIT_REQUEST,
    TRACE_CODE_HDD_SOFTAP_TX_TIMEOUT,
    TRACE_CODE_HDD_HOSTAPD_SET_MAC_ADDR,
    TRACE_CODE_HDD_HOSTAPD_P2P_SET_NOA_IOCTL,
    TRACE_CODE_HDD_HOSTAPD_P2P_SET_PS_IOCTL,
    TRACE_CODE_HDD_HOSTAPD_SET_SAP_CHANNEL_LIST_IOCTL,
    TRACE_CODE_HDD_ADD_VIRTUAL_INTF,
    TRACE_CODE_HDD_DEL_VIRTUAL_INTF,
    TRACE_CODE_HDD_CHANGE_VIRTUAL_INTF,
    TRACE_CODE_HDD_CFG80211_START_AP,
    TRACE_CODE_HDD_CFG80211_CHANGE_BEACON,
    TRACE_CODE_HDD_CFG80211_STOP_AP,
    TRACE_CODE_HDD_CFG80211_CHANGE_BSS,
    TRACE_CODE_HDD_CFG80211_ADD_KEY,
    TRACE_CODE_HDD_CFG80211_GET_KEY,
    TRACE_CODE_HDD_CFG80211_SET_DEFAULT_KEY,
    TRACE_CODE_HDD_CFG80211_CONNECT,
    TRACE_CODE_HDD_CFG80211_DISCONNECT,
    TRACE_CODE_HDD_CFG80211_JOIN_IBSS,
    TRACE_CODE_HDD_CFG80211_LEAVE_IBSS,
    TRACE_CODE_HDD_CFG80211_SET_WIPHY_PARAMS,
    TRACE_CODE_HDD_CFG80211_SET_TXPOWER,
    TRACE_CODE_HDD_CFG80211_GET_TXPOWER,
    TRACE_CODE_HDD_CFG80211_SET_CHANNEL,
    TRACE_CODE_HDD_CFG80211_ADD_BEACON,
    TRACE_CODE_HDD_CFG80211_SET_BEACON,
    TRACE_CODE_HDD_CFG80211_CHANGE_IFACE,
    TRACE_CODE_HDD_CHANGE_STATION,
    TRACE_CODE_HDD_CFG80211_UPDATE_BSS,
    TRACE_CODE_HDD_CFG80211_SCAN,
    TRACE_CODE_HDD_REMAIN_ON_CHANNEL,
    TRACE_CODE_HDD_REMAINCHANREADYHANDLER,
    TRACE_CODE_HDD_CFG80211_CANCEL_REMAIN_ON_CHANNEL,
    TRACE_CODE_HDD_ACTION,
    TRACE_CODE_HDD_MGMT_TX_CANCEL_WAIT,
    TRACE_CODE_HDD_CFG80211_GET_STA,
    TRACE_CODE_HDD_CFG80211_SET_POWER_MGMT,
    TRACE_CODE_HDD_CFG80211_DEL_STA,
    TRACE_CODE_HDD_CFG80211_ADD_STA,
    TRACE_CODE_HDD_CFG80211_SET_PMKSA,
    TRACE_CODE_HDD_CFG80211_UPDATE_FT_IES,
    TRACE_CODE_HDD_CFG80211_TDLS_MGMT,
    TRACE_CODE_HDD_CFG80211_TDLS_OPER,
    TRACE_CODE_HDD_CFG80211_SET_REKEY_DATA,
    TRACE_CODE_HDD_UNSUPPORTED_IOCTL,
    TRACE_CODE_HDD_SETROAMSCANCHANNELMINTIME_IOCTL,
    TRACE_CODE_HDD_GETROAMSCANCHANNELMINTIME_IOCTL,
    TRACE_CODE_HDD_STOP_NETDEV,
    TRACE_CODE_HDD_WAKE_NETDEV,
    TRACE_CODE_HDD_FLUSH_TX_QUEUES,
};

extern void hddTraceDump(void *pMac, tpvosTraceRecord pRecord, tANI_U16 recIndex);
extern void hddTraceInit(void);
#endif


text:
package com.deleidos.rtws.systemcfg.validation;

import javax.xml.bind.ValidationException;

public interface ComponentValidater {
	public void validate(Object bean, String version) throws ValidationException;
}

redpajama_set_name: RedPajamaGithub


text:
/*
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package io.prestosql.tests.product.launcher.env;

import com.google.common.collect.Ordering;

import javax.inject.Inject;

import java.util.List;
import java.util.Map;

import static com.google.common.base.Preconditions.checkArgument;
import static java.util.Objects.requireNonNull;

public final class EnvironmentFactory
{
    private final Map<String, EnvironmentProvider> environmentProviders;

    @Inject
    public EnvironmentFactory(Map<String, EnvironmentProvider> environmentProviders)
    {
        this.environmentProviders = requireNonNull(environmentProviders, "environmentProviders is null");
    }

    public Environment.Builder get(String environmentName)
    {
        checkArgument(environmentProviders.containsKey(environmentName), "No environment with name '%s'. Those do exist, however: %s", environmentName, list());
        return environmentProviders.get(environmentName)
                .createEnvironment(environmentName);
    }

    public List<String> list()
    {
        return Ordering.natural().sortedCopy(environmentProviders.keySet());
    }
}


text:
Sound::Sound () {
   // Create new sound source
   alGenSources (1, &(this->source));
   alSourcei (this->source, AL_BUFFER, 0);

   this->loaded = false;
}

Sound::Sound (const SoundBuffer &buffer) {
   this->loaded = false;
   this->loadFromBuffer (buffer);
}

Sound::~Sound () {
   // Delete the sound source

   alSourcei (this->source, AL_BUFFER, 0);
   alDeleteSources (1, &(this->source));
}

void Sound::loadFromBuffer (const SoundBuffer &buffer) {
   // Set source settings
   alSourcef (this->source, AL_PITCH, 1.0f);
   alSourcef (this->source, AL_GAIN, 1.0f);
   alSource3f (this->source, AL_VELOCITY, 0.0f, 0.0f, 0.0f);
   alSource3f (this->source, AL_POSITION, 0.0f, 0.0f, 0.0f);
   alSourcei (this->source, AL_LOOPING, AL_FALSE);

   // Attach buffer
   alSourcei (this->source, AL_BUFFER, buffer.getALBuffer());

   this->loaded = true;
}

void Sound::play () {
   if (this->loaded) {
      alSourcePlay (this->source);
   }
}

void Sound::pause () {
   if (this->isPlaying()) {
      alSourcePause (this->source);
   }
}

void Sound::stop () {
   if (this->isPlaying()) {
      alSourceStop (this->source);
   }
}

bool Sound::isPlaying () {
   bool playing = false;

   if (this->loaded) {
      ALint state;
      alGetSourcei (this->source, AL_SOURCE_STATE, &state);

      if (state == AL_PLAYING) {
         playing = true;
      }
   }

   return playing;
}


text:
typedef struct tcp_client tcp_client;

struct tcp_client {
    int fd;
    uint32_t host;
    uint16_t port;
};

void tcp_client_init(tcp_client* client);

int tcp_client_connect(tcp_client* client, const char* host, uint16_t port);

long tcp_client_send(tcp_client* client, const void* buf, size_t len);

long tcp_client_recv(tcp_client* client, void* buf, size_t len);

int tcp_client_close(tcp_client* client);

#endif // LWHTTP_TCP_CLIENT_H


text:
.DynarchCalendar, .DynarchCalendar-focused {
  background-color: #d4d0c8;
}

.DynarchCalendar-topBar,
.DynarchCalendar-bottomBar,
.DynarchCalendar-focused .DynarchCalendar-topBar,
.DynarchCalendar-focused .DynarchCalendar-bottomBar {
  background-color: #848078;
  color: #fff;
}

.DynarchCalendar-title div { color: #fff; }

.DynarchCalendar-dayNames { background-color: #f4f0e8; }

.DynarchCalendar-hover-navBtn div,
.DynarchCalendar-hover-title div,
.DynarchCalendar-hover-bottomBar-today {
  border-color: #f4f0e8 #444038 #444038 #f4f0e8;
  background-color: #d4d0c8;
  color: #000;
}
.DynarchCalendar-menu table td div.DynarchCalendar-hover-navBtn {
  border-color: #f4f0e8 #444038 #444038 #f4f0e8;
  background-color: #e4e0d8;
  color: #000;
}

.DynarchCalendar-pressed-navBtn div,
.DynarchCalendar-pressed-title div,
.DynarchCalendar-pressed-bottomBar-today,
.DynarchCalendar-menu table td div.DynarchCalendar-pressed-navBtn {
  border-color: #444038 #f4f0e8 #f4f0e8 #444038;
  background-color: #646058;
  color: #fff;
}

.DynarchCalendar-hover-date {
  border-color: #f4f0e8 #444038 #444038 #f4f0e8;
  background-color: #e4e0d8;
}
.DynarchCalendar-day {
  -moz-border-radius: 0;
  -webkit-border-radius: 0;
  border-radius: 0;
}

.DynarchCalendar-day-disabled {
  background: #c4c0b8;
}

.DynarchCalendar-hover-week { background-color: #e4e0d8 !important; }

.DynarchCalendar-day-selected {
  background-color: #e4e0d8;
  border: 1px solid;
  border-color: #444038 #f4f0e8 #f4f0e8 #444038;
  margin: 0;
}

.DynarchCalendar-day-today.DynarchCalendar-day-selected { background-color: #e4e0d8; }

.DynarchCalendar-menu {
  background-color: #d4d0c8;
}


text:
package heafirst.designpatterns.strategy.duck;

import heafirst.designpatterns.strategy.duck.behavior.FlyRocketPowered;

public class MiniDuckSimulator {
    public static void main(String[] args) {
        Duck mallard = new MallardDuck();
        mallard.performFly();
        mallard.performQuack();

        Duck model = new ModelDuck();
        model.performFly();
        model.setFlyBehavior(new FlyRocketPowered());
        model.performFly();
    }
}


text:
package com.streamsets.datacollector.event.json;

public class StageInfoJson {

  private String stageName;
  private int stageVersion;
  private String libraryName;

  public String getStageName() {
    return stageName;
  }

  public void setStageName(String stageName) {
    this.stageName = stageName;
  }

  public int getStageVersion() {
    return stageVersion;
  }

  public void setStageVersion(int stageVersion) {
    this.stageVersion = stageVersion;
  }

  public String getLibraryName() {
    return libraryName;
  }

  public void setLibraryName(String libraryName) {
    this.libraryName = libraryName;
  }

}


text:
<?php

namespace App\Http\Controllers;

use Illuminate\Routing\Controller as BaseController;

class CategoriesController extends BaseController
{
    public function index()
    {
    	$categories = \App\Category::filter()->load(\App\Category::$relationships);

    	return response()->json($categories);
    }
}


text:
/**********************************************************\
|                                                          |
|                          hprose                          |
|                                                          |
| Official WebSite: http://www.hprose.com/                 |
|                   http://www.hprose.org/                 |
|                                                          |
\**********************************************************/
/**********************************************************\
 *                                                        *
 * DateSerializer.java                                    *
 *                                                        *
 * Date serializer class for Java.                        *
 *                                                        *
 * LastModified: Aug 6, 2016                              *
 * Author: Ma Bingyao <andot@hprose.com>                  *
 *                                                        *
\**********************************************************/

package hprose.io.serialize;

import static hprose.io.HproseTags.TagSemicolon;
import hprose.util.DateTime;
import java.io.IOException;
import java.io.OutputStream;
import java.sql.Date;
import java.util.Calendar;

public final class DateSerializer extends ReferenceSerializer<Date> {

    public final static DateSerializer instance = new DateSerializer();

    @Override
    public final void serialize(Writer writer, Date date) throws IOException {
        super.serialize(writer, date);
        OutputStream stream = writer.stream;
        Calendar calendar = DateTime.toCalendar(date);
        ValueWriter.writeDateOfCalendar(stream, calendar);
        stream.write(TagSemicolon);
    }
}


text:
'use strict';

describe('Controller: ResetCtrl', function () {

  // load the controller's module
  beforeEach(module('dashboardApp'));

  var ResetCtrl, scope;

  // Initialize the controller and a mock scope
  beforeEach(inject(function ($controller, $rootScope) {
    scope = $rootScope.$new();
    ResetCtrl = $controller('ResetCtrl', {
      $scope: scope
    });
  }));

  it('should ...', function () {
    expect(1).toEqual(1);
  });
});


text:
package com.dslplatform.plugin;

import org.eclipse.jface.resource.ImageDescriptor;
import org.eclipse.ui.plugin.AbstractUIPlugin;
import org.osgi.framework.BundleContext;

/**
 * The activator class controls the plug-in life cycle
 */
public class Activator extends AbstractUIPlugin {

	// The plug-in ID
	public static final String PLUGIN_ID = "DSL_Editor_No5"; //$NON-NLS-1$

	// The shared instance
	private static Activator plugin;

	/**
	 * The constructor
	 */
	public Activator() {
	}

	/*
	 * (non-Javadoc)
	 * @see org.eclipse.ui.plugin.AbstractUIPlugin#start(org.osgi.framework.BundleContext)
	 */
	public void start(BundleContext context) throws Exception {
		super.start(context);
		plugin = this;
	}

	/*
	 * (non-Javadoc)
	 * @see org.eclipse.ui.plugin.AbstractUIPlugin#stop(org.osgi.framework.BundleContext)
	 */
	public void stop(BundleContext context) throws Exception {
		plugin = null;
		super.stop(context);
	}

	/**
	 * Returns the shared instance
	 *
	 * @return the shared instance
	 */
	public static Activator getDefault() {
		return plugin;
	}

	/**
	 * Returns an image descriptor for the image file at the given
	 * plug-in relative path
	 *
	 * @param path the path
	 * @return the image descriptor
	 */
	public static ImageDescriptor getImageDescriptor(String path) {

		return imageDescriptorFromPlugin(PLUGIN_ID, path);
	}
}


text:
NS_ASSUME_NONNULL_BEGIN
@class MDTextField;
@interface MDSuggestPopupView
    : UIButton <UITableViewDataSource, UITableViewDelegate>

@property(nullable, nonatomic) NSArray <NSString*>*suggestionsDictionary;

- (instancetype)initWithTextField:(MDTextField *)textField;
- (void)textView:(MDTextField *)textField didChangeText:(NSString *)text;

@end
NS_ASSUME_NONNULL_END


text:
using System.Runtime.Serialization;

namespace DvachBrowser4.Core.Models.Posting
{
    /// <summary>
    /// Поле комментария.
    /// </summary>
    [DataContract(Namespace = CoreConstants.DvachBrowserNamespace)]
    public class PostingCommentCapability : PostingCapability
    {
        /// <summary>
        /// Тип разметки.
        /// </summary>
        [DataMember]
        public PostingMarkupType MarkupType { get; set; }

        /// <summary>
        /// Максимальный размер (null - неизвестно).
        /// </summary>
        [DataMember]
        public int? MaxLength { get; set; }
    }
}


text:
namespace lua {

void moduleRetain();
void moduleRelease();

//------ Reflector Component ------//

class Exception_Reflector : public co::ReflectorBase
{
public:
	Exception_Reflector()
	{
		moduleRetain();
	}

	virtual ~Exception_Reflector()
	{
		moduleRelease();
	}

	co::IType* getType()
	{
		return co::typeOf<lua::Exception>::get();
	}

	co::uint32 getSize()
	{
		return sizeof(lua::Exception);
	}

	void raise( const std::string& message )
	{
		throw lua::Exception( message );
	}
};

//------ Reflector Creation Function ------//

co::IReflector* __createExceptionReflector()
{
    return new Exception_Reflector;
}

} // namespace lua


text:
class Camera
{
public:
    Camera();

    void moveCamera(const QVector3D &_direction);

    void setScreenSize(const int &_width, const int &_height);
    void setRayOrigin(QVector3D &_origin);
    void setRayDirection(const int &_row, const int &_col, QVector3D &_direction);

    QVector3D& getEye();
    QVector3D& getAt();
    QVector3D& getUp();

    int getScreenHeight();
    int getScreenWidth();

private:
    QVector3D  m_Eye;
    QVector3D  m_At;
    QVector3D  m_Up;
    QMatrix4x4 m_CameraToWorld;

    int   m_ScreenWidth;
    int   m_ScreenHeight;
    float m_FOV;
    float m_AspectRatio;
};

#endif // CAMERA_H


text:
from requests.packages.urllib3.exceptions import InsecureRequestWarning
from django.shortcuts import render
from ..models import Station
from ..models import ApiKey
import requests
import json
import datetime
from datetime import timedelta
from ..utils.lgUtils import *
from django.http import JsonResponse, HttpResponse
from collections import defaultdict
from simplejson.scanner import JSONDecodeError
from django.core.urlresolvers import resolve
from django.views.decorators.csrf import csrf_exempt

import logging
logger = logging.getLogger("django")

requests.packages.urllib3.disable_warnings(InsecureRequestWarning)

def getConcreteValues(request):
    logger.info("Getting Concrete Weather values")
    date = request.POST['date']
    station_id = request.POST.get('station', 0)
    allStations = request.POST.get('allStations', 0)

    sparkIp = getSparkIp()
    ip = getDjangoIp()

    getAllStations = allStations == str(1)

    stations = Station.objects.all()

    try:
        response = requests.get(
            'http://' + sparkIp + ':5000/getMeasurement?date=' + date + '&station_id=' + station_id +
            '&allStations=' + str(getAllStations), stream=True)
    except requests.exceptions.ConnectionError:
        return render(request, '500.html')

    try:
        jsonData = json.loads(response.json())

        stationsWeather = {}
        if len(jsonData) == 0:
            return render(request, 'floybd/weather/weatherConcreteView.html',
                          {'noData': True, 'date': date})

        for row in jsonData:
            concreteStation = Station.objects.get(station_id=row.get("station_id"))
            stationData = {}

            timestamp = row.get("measure_date")
            measureDate = datetime.datetime.utcfromtimestamp(float(timestamp) / 1000).strftime('%d-%m-%Y')
            contentString = '
' + \
                            '
' + \
                            '
' + \
                            '
' + concreteStation.name + '
' + \
                            '
' + measureDate + '
' + \
                            '
' + \
                            '
' + \
                            '
Max Temp: ' + str(row.get("max_temp")) + \
                            '
Med Temp: ' + str(row.get("med_temp")) + \
                            '
Min Temp: ' + str(row.get("min_temp")) + \
                            '
Max Pressure: ' + str(row.get("max_pressure")) + \
                            '
Min Pressure: ' + str(row.get("min_pressure")) + \
                            '
Precip: ' + str(row.get("precip")) + \
                            '
Insolation: ' + str(row.get("insolation")) + \
                            '
' + \
                            '
' + \
                            '
'
            stationData["timestamp"] = timestamp
            stationData["measureDate"] = measureDate
            stationData["contentString"] = contentString
            stationData["latitude"] = concreteStation.latitude
            stationData["longitude"] = concreteStation.longitude
            stationData["name"] = concreteStation.name
            stationsWeather[row.get("station_id")] = stationData

        if getAllStations:
            kml = simplekml.Kml()
            for key, value in stationsWeather.items():
                kml.newpoint(name=value["name"], description=value["contentString"],
                             coords=[(value["longitude"], value["latitude"])])

            fileName = "measurement_" + str(date) + ".kml"
            currentDir = os.getcwd()
            dir1 = os.path.join(currentDir, "static/kmls")
            dirPath2 = os.path.join(dir1, fileName)

            kml.save(dirPath2)
            return render(request, 'floybd/weather/weatherConcreteView.html',
                          {'kml': 'http://' + ip + ':'+getDjangoPort(request)+'/static/kmls/' + fileName, 'date': date})
        else:
            concreteStation = Station.objects.get(station_id=station_id)
            contentString = stationsWeather[station_id]["contentString"]
            return render(request, 'floybd/weather/weatherConcreteView.html',
                          {'stations': stations, 'concreteStation': concreteStation,
                           'weatherData': contentString, 'date': date})
    except JSONDecodeError:
        return render(request, '500.html')

def sendConcreteValuesToLG(request):
    date = request.POST['date']

    allStations = request.POST.get('allStations', 0)

    sparkIp = getSparkIp()

    if str(allStations) == str(1):
        fileurl = request.POST['fileUrl']
        fileName = "measurement_" + str(date) + ".kmz"
        currentDir = os.getcwd()
        dir1 = os.path.join(currentDir, "static/kmls")
        dirPath2 = os.path.join(dir1, fileName)

        try:
            response = requests.get(
                'http://' + sparkIp + ':5000/getAllStationsMeasurementsKML?date=' + date,
                stream=True)
        except requests.exceptions.ConnectionError:
            return render(request, '500.html')

        with open(dirPath2, 'wb') as f:
            logger.info("Downloading Cylinders KMZ from Flask...")
            for chunk in response.iter_content(chunk_size=1024):
                print('.', end='')
                if chunk:  # filter out keep-alive new chunks
                    f.write(chunk)
            f.close()

        sendKmlToLG(fileName, request)

        sendFlyToToLG("40.416775", "-3.703790", 25000, 0, 69, 130000, 2)

        playTour("Tour And Rotation")

        return render(request, 'floybd/weather/weatherConcreteView.html',
                      {'kml': fileurl, 'date': date})

    else:
        station_id = request.POST['station']
        weatherData = request.POST['weatherData']

    fileName = "measurement_" + str(date) + ".kml"
    currentDir = os.getcwd()
    dir1 = os.path.join(currentDir, "static/kmls")
    dirPath2 = os.path.join(dir1, fileName)

    response = requests.get('http://' + sparkIp + ':5000/getMeasurementKml?date='
                            + date + '&station_id=' + station_id, stream=True)
    with open(dirPath2, 'wb') as f:
        logger.info("Downloading Cylinders KMZ from Flask...")
        for chunk in response.iter_content(chunk_size=1024):
            print('.', end='')
            if chunk:  # filter out keep-alive new chunks
                f.write(chunk)

    stations = Station.objects.all()
    concreteStation = Station.objects.get(station_id=station_id)

    sendKmlToLG(fileName, request)
    if concreteStation is not None:
        sendFlyToToLG(concreteStation.latitude, concreteStation.longitude, 25000, 0, 69, 130000, 2)

    playTour("Tour And Rotation")

    return render(request, 'floybd/weather/weatherConcreteView.html',
                  {'stations': stations, 'concreteStation': concreteStation,
                   'weatherData': weatherData, 'date': date})

def weatherConcreteIndex(request):
    stations = Station.objects.all()
    return render(request, 'floybd/weather/weatherConcrete.html', {'stations': stations})

def weatherPredictions(request):
    stations = Station.objects.all()
    columnsList = ["max_temp", "med_temp", "min_temp", "max_pressure", "min_pressure",
                   "precip", "insolation"]
    return render(request, 'floybd/weather/weatherPrediction.html',
                  {'stations': stations, 'columnsList': columnsList})

def getPrediction(request):
    station_id = request.POST['station']
    columnsToPredict = request.POST.getlist('columnToPredict')

    sparkIp = getSparkIp()
    ip = getDjangoIp()

    jsonData = {"station_id": station_id, "columnsToPredict": columnsToPredict}
    payload = json.dumps(jsonData)

    try:
        response = requests.post('http://' + sparkIp + ':5000/getPrediction',
                                 headers={'Accept': 'application/json', 'Content-Type': 'application/json'},
                                 data=payload)
    except requests.exceptions.ConnectionError:
        return render(request, '500.html')

    if response.json():
        try:
            result = json.loads(response.json())
        except JSONDecodeError:
            return render(request, '500.html')
        concreteStation = Station.objects.get(station_id=station_id)

        kml = simplekml.Kml()
        tour = kml.newgxtour(name="Show Balloon")
        playlist = tour.newgxplaylist()

        contentString = '<link rel = "stylesheet" href = "https://code.getmdl.io/1.3.0/' \
                        'material.blue_grey-red.min.css" / > ' + \
                        '<link rel="stylesheet" href="https://fonts.googleapis.com/css?' \
                        'family=Roboto:regular,bold,italic,thin,light,bolditalic,black,medium&lang=en"/>' + \
                        '

' + \
                        '
' + '
' + '
' + \
                        '
' + \
                        concreteStation.name + '
' + \
                        '
' + \
                        '
'

        for row in result:
            jsonRow = json.loads(row)

            for column in columnsToPredict:
                if jsonRow.get("prediction_" + column) is not None:
                    contentString += '
' \
                                    '
' \
                                     '' + column + ''\
                                     ':

' \
                                     '
' + \
                                     str("%.2f" % round(jsonRow.get("prediction_" + column), 2)) + '

'
        contentString += '

'

        point = kml.newpoint(name="", description=contentString,
                             coords=[(concreteStation.longitude, concreteStation.latitude)])
        point.style.iconstyle.icon.href = 'https://png.icons8.com/thermometer-automation/ultraviolet/80'
        point.style.balloonstyle.bgcolor = simplekml.Color.lightblue
        point.style.balloonstyle.text = "$[description]"
        point.gxballoonvisibility = 0

        doFlyToSmooth(playlist, concreteStation.latitude, concreteStation.longitude, 0, 4855570, 3.0, 0)
        playlist.newgxwait(gxduration=3.0)
        doFlyToSmooth(playlist, concreteStation.latitude, concreteStation.longitude, 1000, 5000, 5.0, 0)
        playlist.newgxwait(gxduration=5.0)
        doFlyToSmooth(playlist, concreteStation.latitude, concreteStation.longitude, 1000, 5000, 1)
        playlist.newgxwait(gxduration=1)

        animatedupdateshow = playlist.newgxanimatedupdate(gxduration=5.0)
        animatedupdateshow.update.change = '<Placemark targetId="{0}"><visibility>1</visibility>' \
                                           '<gx:balloonVisibility>1</gx:balloonVisibility></Placemark>' \
            .format(point.placemark.id)

        doRotation(playlist, float(concreteStation.latitude), float(concreteStation.longitude), 1000, 5000)

        playlist.newgxwait(gxduration=5.0)

        animatedupdateshow = playlist.newgxanimatedupdate(gxduration=0.1)
        animatedupdateshow.update.change = '<Placemark targetId="{0}"><visibility>0</visibility>' \
                                           '<gx:balloonVisibility>0</gx:balloonVisibility></Placemark>' \
            .format(point.placemark.id)

        fileName = "prediction.kml"
        currentDir = os.getcwd()
        dir1 = os.path.join(currentDir, "static/kmls")
        dirPath2 = os.path.join(dir1, fileName)

        kml.save(dirPath2)

        kmlpath = "http://" + ip + ":"+getDjangoPort(request)+"/static/kmls/" + fileName

        return render(request, 'floybd/weather/weatherPredictionView.html',
                      {'fileName': fileName, 'kml': kmlpath, 'backUrl': resolve("/predictWeather").url_name,
                       'concreteStation': concreteStation})
    else:
        return render(request, 'floybd/weather/weatherPredictionView.html')

def sendPredictionsToLG(request):
    fileName = request.POST.get("fileName")
    backUrl = request.POST.get("backUrl")
    ip = getDjangoIp()
    kmlpath = "http://" + ip + ":"+getDjangoPort(request)+"/static/kmls/" + fileName
    station_id = request.POST.get("station_id")
    stats = request.POST.get("stats", 0)

    concreteStation = Station.objects.get(station_id=station_id)

    sendKmlToLG(fileName, request)
    playTour("Show Balloon")

    return render(request, 'floybd/weather/weatherPredictionView.html',
                  {'fileName': fileName, 'kml': kmlpath, 'backUrl': backUrl,
                   'concreteStation': concreteStation, 'stats': stats == str("1")})

def weatherStats(request):
    stations = Station.objects.all()
    return render(request, 'floybd/weather/weatherStats.html', {'stations': stations})

def getStats(request):
    stations = Station.objects.all()

    ip = getDjangoIp()

    allStations = request.POST.get('allStations', 0)
    allStationsBool = allStations == str(1)
    allTime = request.POST.get('allTime', 0)
    dateFrom = request.POST.get('dateFrom', 0)
    dateTo = request.POST.get('dateTo', 0)
    station_id = request.POST.get('station', 0)
    addGraphs = request.POST.get('addGraphs', 0)

    addGraphs = (addGraphs == str("1"))

    logger.debug("AllStations:", allStations)
    logger.debug("allTime:", allTime)
    logger.debug("dateFrom:", dateFrom)
    logger.debug("dateTo:", dateTo)
    logger.debug("station_id:", station_id)
    logger.debug("addGraphs:", addGraphs)

    jsonData = {"station_id": station_id, "dateTo": dateTo, "dateFrom": dateFrom, "allTime": allTime,
                "allStations": allStations}

    payload = json.dumps(jsonData)

    try:
        response = requests.post('http://130.206.117.178:5000/getStats',
                                 headers={'Accept': 'application/json', 'Content-Type': 'application/json'},
                                 data=payload)
    except requests.exceptions.ConnectionError:
        return render(request, '500.html')

    try:
        result = json.loads(response.json())
    except JSONDecodeError:
        return render(request, '500.html')
    intervalData = False
    oneStation = (allStations != str("1"))
    if allTime != str(1) and allStations != str(1):
        intervalData = True

    stationsWeather = {}
    kml = simplekml.Kml()

    if allStationsBool:
        tourAllStations = kml.newgxtour(name="Tour All Stations")
        playlistAllStations = tourAllStations.newgxplaylist()

    for row in result:
        concreteStation = Station.objects.get(station_id=row.get("station_id"))
        stationData = {}

        if allTime == str(1):
            if addGraphs:
                contentString = getContentStringWithGraphs(row)
            else:
                contentString = '<link rel = "stylesheet" href = "https://code.getmdl.io/1.3.0/' \
                                'material.blue_grey-red.min.css" / > ' + \
                                '<link rel="stylesheet" href="https://fonts.googleapis.com/css?' \
                                'family=Roboto:regular,bold,italic,thin,light,bolditalic,black,medium&lang=en"/>' + \
                                '

' + \
                                '
' + '
' + '
' + \
                                '
' +\
                                concreteStation.name + '
' + \
                                '
' + \
                                '
' + \
                                '
' + \
                                '
Average Max Temp:
' + \
                                '
' + \
                                '
' + \
                                '
' +\
                                str("%.2f" % round(row.get("avgMaxTemp"), 2)) + ' ºC
' + \
                                '
' + \
                                '
' + \
                                '
Average Med Temp:
' + \
                                '
' + \
                                '
' + \
                                '
' +\
                                str("%.2f" % round(row.get("avgMedTemp"), 2)) + ' ºC
' + \
                                '
' + \
                                '
' + \
                                '
Average Min Temp:
' + \
                                '
' + \
                                '
' + \
                                '
' + \
                                str("%.2f" % round(row.get("avgMinTemp"), 2))+' ºC
' + \
                                '
' + \
                                '
' + \
                                '
Average Max Pressure :
' + \
                                '
' + \
                                '
' + \
                                '
' + str(row.get("avgMaxPressure")) +\
                                ' hPa
' + \
                                '
' + \
                                '
' + \
                                '
Average Min Pressure:
' + \
                                '
' + \
                                '
' + \
                                '
' +\
                                str(row.get("avgMinPressure")) + ' hPa
' + \
                                '
' + \
                                '
' + \
                                '
Average Precipitation:
' + \
                                '
' + \
                                '
' + \
                                '
' + \
                                str("%.2f" % round(row.get("avgPrecip"), 2)) + ' mm
' + \
                                '
' + \
                                '
' + \
                                '
Max Maximum Temperature:
' + \
                                '
' + \
                                '
' + \
                                '
' +\
                                str(row.get("maxMaxTemp")) + ' ºC
' + \
                                '
' + \
                                '
' + \
                                '
Min Maximum Temperature:
' + \
                                '
' + \
                                '
' + \
                                '
' +\
                                str(row.get("minMaxTemp")) + ' ºC
' + \
                                '
' + \
                                '
' + \
                                '
Max Medium Temperature:
' + \
                                '
' + \
                                '
' + \
                                '
' +\
                                str(row.get("maxMedTemp")) + ' ºC
' + \
                                '
' + \
                                '
' + \
                                '
Min Medium Temperature:
' + \
                                '
' + \
                                '
' + \
                                '
' +\
                                str(row.get("minMedTemp")) + ' ºC
' + \
                                '
' + \
                                '
' + \
                                '
Max Minimum Temperature:
' + \
                                '
' + \
                                '
' + \
                                '
' +\
                                str(row.get("maxMinTemp")) + ' ºC
' + \
                                '
' + \
                                '
' + \
                                '
Min Minimum Temperature:
' + \
                                '
' + \
                                '
' + \
                                '
' +\
                                str(row.get("minMaxTemp")) + ' ºC
' + \
                                '
' + \
                                '
' + \
                                '
Max Precipitation:
' + \
                                '
' + \
                                '
' + \
                                '
' +\
                                str(row.get("maxPrecip")) + ' mm
' + \
                                '
' + \
                                '
' + \
                                '

' + \
                                '

'

        else:
            contentString = '<link rel = "stylesheet" href =' \
                            ' "https://code.getmdl.io/1.3.0/material.blue_grey-red.min.css" / > ' + \
                            '<link rel="stylesheet" href="https://fonts.googleapis.com/css?' \
                            'family=Roboto:regular,bold,italic,thin,light,bolditalic,black,medium&lang=en"/>' + \
                            '

' + \
                            '
' + '
' + '
' + \
                            '
' +\
                            concreteStation.name + '
' + \
                            '
' + \
                            '
' + \
                            '
' + \
                            '
Average Max Temp:
' + \
                            '
' + \
                            '
' + \
                            '
' +\
                            str("%.2f" % round(row.get("avg(max_temp)"), 2)) + ' ºC
' + \
                            '
' + \
                            '
' + \
                            '
Average Med Temp:
' + \
                            '
' + \
                            '
' + \
                            '
' + \
                            str("%.2f" % round(row.get("avg(med_temp)"), 2)) + ' ºC
' + \
                            '
' + \
                            '
' + \
                            '
Average Min Temp:
' + \
                            '
' + \
                            '
' + \
                            '
' + \
                            str("%.2f" % round(row.get("avg(min_temp)"), 2)) + ' ºC
' + \
                            '
' + \
                            '
' + \
                            '
Average Max Pressure :
' + \
                            '
' + \
                            '
' + \
                            '
' +\
                            str(row.get("avg(max_pressure)")) + ' hPa
' + \
                            '
' + \
                            '
' + \
                            '
Average Min Pressure:
' + \
                            '
' + \
                            '
' + \
                            '
' +\
                            str(row.get("avg(min_pressure)")) + ' hPa
' + \
                            '
' + \
                            '
' + \
                            '
Average Precipitation:
' + \
                            '
' + \
                            '
' + \
                            '
' + \
                            str("%.2f" % round(row.get("avg(precip)"), 2)) + ' mm
' + \
                            '
' + \
                            '
' + \
                            '
Insolation:
' + \
                            '
' + \
                            '
' + \
                            '
' +\
                            str(row.get("avg(insolation)")) + '
' + \
                            '
' + \
                            '
' + \
                            '

' + \
                            '

'

        stationData["contentString"] = contentString
        stationData["latitude"] = concreteStation.latitude
        stationData["longitude"] = concreteStation.longitude
        stationData["name"] = concreteStation.name
        stationsWeather[row.get("station_id")] = stationData

        point = kml.newpoint(name=stationData["name"], description=stationData["contentString"],
                             coords=[(stationData["longitude"], stationData["latitude"])])
        point.style.iconstyle.icon.href = 'https://png.icons8.com/thermometer-automation/ultraviolet/80'
        point.style.balloonstyle.bgcolor = simplekml.Color.lightblue
        point.style.balloonstyle.text = "$[description]"
        # point.gxballoonvisibility = 0

        if allStationsBool:
            doFlyToSmooth(playlistAllStations,  float(stationData["latitude"]), float(stationData["longitude"]),
                          0, 4855570, 3.0, 0)
            playlistAllStations.newgxwait(gxduration=3.0)
            doFlyToSmooth(playlistAllStations,  float(stationData["latitude"]), float(stationData["longitude"]),
                          1000, 5000, 5.0, 0)
            playlistAllStations.newgxwait(gxduration=5.0)
            doFlyToSmooth(playlistAllStations,  float(stationData["latitude"]), float(stationData["longitude"]),
                          1000, 5000, 1)
            playlistAllStations.newgxwait(gxduration=1)

            animatedupdateshow = playlistAllStations.newgxanimatedupdate(gxduration=5.0)
            animatedupdateshow.update.change = '<Placemark targetId="{0}"><visibility>1</visibility>' \
                                               '<gx:balloonVisibility>1</gx:balloonVisibility></Placemark>' \
                .format(point.placemark.id)

            doRotation(playlistAllStations, float(stationData["latitude"]), float(stationData["longitude"]), 1000, 5000)

            playlistAllStations.newgxwait(gxduration=5.0)

            animatedupdateshow = playlistAllStations.newgxanimatedupdate(gxduration=0.1)
            animatedupdateshow.update.change = '<Placemark targetId="{0}"><visibility>0</visibility>' \
                                               '<gx:balloonVisibility>0</gx:balloonVisibility></Placemark>' \
                .format(point.placemark.id)

        else:
            point.gxballoonvisibility = 0
            tour = kml.newgxtour(name="Show Balloon")
            playlist = tour.newgxplaylist()

            doFlyToSmooth(playlist, float(stationData["latitude"]), float(stationData["longitude"]), 0, 4855570, 3.0, 0)
            playlist.newgxwait(gxduration=3.0)
            doFlyToSmooth(playlist, float(stationData["latitude"]), float(stationData["longitude"]), 1000, 5000, 5.0, 0)
            playlist.newgxwait(gxduration=5.0)
            doFlyToSmooth(playlist, float(stationData["latitude"]), float(stationData["longitude"]), 1000, 5000, 1)
            playlist.newgxwait(gxduration=1)

            animatedupdateshow = playlist.newgxanimatedupdate(gxduration=0.1)
            animatedupdateshow.update.change = '<Placemark targetId="{0}"><visibility>1</visibility>' \
                                               '<gx:balloonVisibility>1</gx:balloonVisibility></Placemark>' \
                .format(point.placemark.id)

            doRotation(playlist, float(stationData["latitude"]), float(stationData["longitude"]), 1000, 5000)

            animatedupdateshow = playlist.newgxanimatedupdate(gxduration=0.1)
            animatedupdateshow.update.change = '<Placemark targetId="{0}"><visibility>0</visibility>' \
                                               '<gx:balloonVisibility>0</gx:balloonVisibility></Placemark>' \
                .format(point.placemark.id)

    fileName = "stats.kml"
    currentDir = os.getcwd()
    dir1 = os.path.join(currentDir, "static/kmls")
    dirPath2 = os.path.join(dir1, fileName)
    concreteStation = Station.objects.get(station_id=station_id)

    kml.save(dirPath2)

    return render(request, 'floybd/weather/weatherStats.html', {'kml': 'http://' + ip + ':'+getDjangoPort(request) +
                                                                       '/static/kmls/' + fileName,
                                                                'stations': stations, 'fileName': fileName,
                                                                'intervalData': intervalData, "dateTo": dateTo,
                                                                "dateFrom": dateFrom, "station": station_id,
                                                                'concreteStation': concreteStation,
                                                                'oneStation': oneStation,
                                                                'allStations': allStations,
                                                                'allTime': allTime == str("1")})

def getContentStringWithGraphs(rowData):
    logger.info("Getting Graphs...")
    contentString = '

' + \
                    '
Max Temp
' + \
                    '
Avg Max Temp: ' + str("{0:.2f}".format(rowData.get("avgMaxTemp"))) + \
                    '
Max Max Temp: ' + str("{0:.2f}".format(rowData.get("maxMaxTemp"))) + \
                    '
Min Max Temp: ' + str("{0:.2f}".format(rowData.get("minMaxTemp"))) + \
                    '
 ' + \
                    '	' + \
                    '
Med Temp
' + \
                    '
Avg Med Temp: ' + str("{0:.2f}".format(rowData.get("avgMedTemp"))) + \
                    '
Max Med Temp: ' + str("{0:.2f}".format(rowData.get("maxMedTemp"))) + \
                    '
Min Med Temp: ' + str("{0:.2f}".format(rowData.get("minMedTemp"))) + \
                    '
 ' + \
                    '	' + \
                    '
Min Temp
' + \
                    '
Avg Min Temp: ' + str("{0:.2f}".format(rowData.get("avgMinTemp"))) + \
                    '
Max Min Temp: ' + str("{0:.2f}".format(rowData.get("maxMinTemp"))) + \
                    '
Min Min Temp: ' + str("{0:.2f}".format(rowData.get("minMinTemp"))) + \
                    '
' + \
                    '

' + \
                    '
Max Pressure
' + \
                    '
Avg Max Pressure: ' + str("{0:.2f}".format(rowData.get("avgMaxPressure"))) + \
                    '

' + \
                    '	' + \
                    '
Min Pressure
' + \
                    '
Avg Min Pressure: ' + str("{0:.2f}".format(rowData.get("avgMinPressure"))) + \
                    '

 ' + \
                    '	' + \
                    '
Precipitation
' + \
                    '
Avg Precip: ' + str("{0:.2f}".format(rowData.get("avgPrecip"))) + \
                    '
Max Precip: ' + str("{0:.2f}".format(rowData.get("maxPrecip"))) + \
                    '
' + \
                    '

'

    return contentString

def getGraphDataForStats(request):
    station_id = request.GET.get("station")
    dateFrom = request.GET.get("dateFrom")
    dateTo = request.GET.get("dateTo")
    allTime = request.GET.get('allTime', 0)

    logger.debug("Station: ", station_id)
    logger.debug("Date From: ", dateFrom)
    logger.debug("Date To: ", dateTo)
    logger.debug("allTime: ", allTime)

    jsonData = {"station_id": station_id, "dateTo": dateTo, "dateFrom": dateFrom}
    payload = json.dumps(jsonData)

    try:
        response = requests.post('http://' + getSparkIp() + ':5000/getWeatherDataInterval',
                                 headers={'Accept': 'application/json', 'Content-Type': 'application/json'},
                                 data=payload)
        result = json.loads(response.json())
    except requests.exceptions.ConnectionError:
        return render(request, '500.html')
    except JSONDecodeError:
        return render(request, '500.html')

    if result:
        data = {
            'stationData': result
        }
    else:
        data = {}

    return JsonResponse(data)

def sendStatsToLG(request):
    fileName = request.POST.get("fileName")
    sendKmlToLG(fileName, request)
    # sendKmlToLG1(fileName, request)
    stations = Station.objects.all()

    allStations = request.POST.get('allStations', 0)
    allTime = request.POST.get('allTime', 0)
    dateFrom = request.POST.get('dateFrom', 0)
    dateTo = request.POST.get('dateTo', 0)
    station_id = request.POST.get('station', 0)
    station = request.POST.get('station', 0)
    concreteStation = Station.objects.get(station_id=station)

    oneStation = (allStations != str("1"))
    intervalData = False
    if not allTime and not allStations:
        intervalData = True

    if oneStation:
        playTour("Show Balloon")

    else:
        sendFlyToToLG(40.4378693, -3.8199627, 1000, 0, 77, 5000, 2)
        time.sleep(2)
        playTour("Tour All Stations")

    ip = getDjangoIp()

    return render(request, 'floybd/weather/weatherStats.html', {'kml': 'http://' + ip + ':'+getDjangoPort(request) +
                                                                       '/static/kmls/' + fileName,
                                                                'stations': stations, 'fileName': fileName,
                                                                'intervalData': intervalData, "dateTo": dateTo,
                                                                "dateFrom": dateFrom, "station": station_id,
                                                                'concreteStation': concreteStation,
                                                                'oneStation': oneStation,
                                                                'allTime': allTime,
                                                                'allStations': allStations})

def citydashboard(request):
    stations = Station.objects.all()
    return render(request, 'floybd/weather/indexDashboard.html', {'stations': stations})

def viewDashboard(request):
    station = request.GET.get('station', None)
    daysBefore = request.GET.get('daysBefore', None)

    sparkIp = getSparkIp()

    today = time.strftime("%Y-%m-%d")
    previousDate = datetime.datetime.today() - timedelta(days=int(daysBefore))
    jsonData = {"station_id": station, "dateTo": today, "dateFrom": previousDate.strftime("%Y-%m-%d")}

    logger.debug("From: " + previousDate.strftime("%Y-%m-%d"))
    logger.debug("Today: " + today)

    payload = json.dumps(jsonData)

    try:
        response = requests.post('http://' + sparkIp + ':5000/getWeatherDataInterval',
                                 headers={'Accept': 'application/json', 'Content-Type': 'application/json'},
                                 data=payload)
        result = json.loads(response.json())
    except JSONDecodeError:
        return render(request, '500.html')
    except requests.exceptions.ConnectionError:
        return render(request, '500.html')
    if result:
        data = {
            'stationData': result
        }
    else:
        data = {}
    return JsonResponse(data)

def weatherPredictionsStats(request):
    stations = Station.objects.all()

    return render(request, 'floybd/weather/weatherPredictionStats.html',
                  {'stations': stations})

def getPredictionStats(request):
    today = time.strftime("%Y-%m-%d")
    station_id = request.POST['station']
    sparkIp = getSparkIp()
    ip = getDjangoIp()

    jsonData = {"station_id": station_id, "fecha": today}
    payload = json.dumps(jsonData)

    try:
        response = requests.post('http://' + sparkIp + ':5000/getPredictionStats',
                                 headers={'Accept': 'application/json', 'Content-Type': 'application/json'},
                                 data=payload)
    except requests.exceptions.ConnectionError:
        return render(request, '500.html')

    if response.json():
        try:
            result = json.loads(response.json())
        except JSONDecodeError:
            return render(request, '500.html')
        concreteStation = Station.objects.get(station_id=station_id)
        kml = simplekml.Kml()
        tour = kml.newgxtour(name="Show Balloon")
        playlist = tour.newgxplaylist()
        if len(result) > 0:

            contentString = '<link rel = "stylesheet" href =' \
                            ' "https://code.getmdl.io/1.3.0/material.blue_grey-red.min.css" / > ' + \
                            '<link rel="stylesheet" href="https://fonts.googleapis.com/css?' \
                            'family=Roboto:regular,bold,italic,thin,light,bolditalic,black,medium&lang=en"/>' + \
                            '

' + \
                            '
' + '
' + '
' + \
                            '
' +\
                            concreteStation.name + '
' + \
                            '
' + \
                            '
' + \
                            '
' + \
                            '
Max Temp:
' + \
                            '
' + \
                            '
' + \
                            '
' +\
                            str("%.2f" % round(result[0].get("max_temp"), 2)) + ' ºC
' + \
                            '
' + \
                            '
' + \
                            '
Med Temp:
' + \
                            '
' + \
                            '
' + \
                            '
' + \
                            str("%.2f" % round(result[0].get("med_temp"), 2)) + ' ºC
' + \
                            '
' + \
                            '
' + \
                            '
Min Temp:
' + \
                            '
' + \
                            '
' + \
                            '
' + \
                            str("%.2f" % round(result[0].get("min_temp"), 2)) + ' ºC
' + \
                            '
' + \
                            '
' + \
                            '
Avg Precip:
' + \
                            '
' + \
                            '
' + \
                            '
' + \
                            str("%.2f" % round(result[0].get("precip"), 2)) + ' mm
' + \
                            '
' + \
                            '
' + \
                            '
Max Press:
' + \
                            '
' + \
                            '
' + \
                            '
' +\
                            str("%.2f" % round(result[0].get("max_pressure"), 2)) + ' hPa
' + \
                            '
' + \
                            '
' + \
                            '
Min Press:
' + \
                            '
' + \
                            '
' + \
                            '
' +\
                            str("%.2f" % round(result[0].get("min_pressure"), 2)) + ' hPa
' + \
                            '
' + \
                            '
' + \
                            '
Insolation:
' + \
                            '
' + \
                            '
' + \
                            '
' +\
                            str(result[0].get("insolation")) + '
' + \
                            '
' + \
                            '
' + \
                            '

' + \
                            '

'

            point = kml.newpoint(name="", description=contentString, coords=[(concreteStation.longitude,
                                                                             concreteStation.latitude)])

            point.style.balloonstyle.bgcolor = simplekml.Color.lightblue
            point.style.balloonstyle.text = "$[description]"
            point.gxballoonvisibility = 0
            point.style.iconstyle.icon.href = 'https://png.icons8.com/thermometer-automation/ultraviolet/80'

            doFlyToSmooth(playlist, concreteStation.latitude, concreteStation.longitude, 0, 4855570, 3.0, 0)
            playlist.newgxwait(gxduration=3.0)
            doFlyToSmooth(playlist, concreteStation.latitude, concreteStation.longitude, 1000, 5000, 5.0, 0)
            playlist.newgxwait(gxduration=5.0)
            doFlyToSmooth(playlist, concreteStation.latitude, concreteStation.longitude, 1000, 5000, 1)
            playlist.newgxwait(gxduration=1)

            animatedupdateshow = playlist.newgxanimatedupdate(gxduration=5.0)
            animatedupdateshow.update.change = '<Placemark targetId="{0}"><visibility>1</visibility>' \
                                               '<gx:balloonVisibility>1</gx:balloonVisibility></Placemark>' \
                .format(point.placemark.id)

            doRotation(playlist, float(concreteStation.latitude), float(concreteStation.longitude), 1000, 5000)

            playlist.newgxwait(gxduration=5.0)

            animatedupdateshow = playlist.newgxanimatedupdate(gxduration=0.1)
            animatedupdateshow.update.change = '<Placemark targetId="{0}"><visibility>0</visibility>' \
                                               '<gx:balloonVisibility>0</gx:balloonVisibility></Placemark>' \
                .format(point.placemark.id)

        fileName = "prediction.kml"
        currentDir = os.getcwd()
        dir1 = os.path.join(currentDir, "static/kmls")
        dirPath2 = os.path.join(dir1, fileName)

        kml.save(dirPath2)

        kmlpath = "http://" + ip + ":"+getDjangoPort(request)+"/static/kmls/" + fileName

        return render(request, 'floybd/weather/weatherPredictionView.html',
                      {'fileName': fileName, 'kml': kmlpath, 'backUrl': resolve("/predictWeatherStats").url_name,
                       'concreteStation': concreteStation, 'stats': True})
    else:
        return render(request, 'floybd/weather/weatherPredictionView.html')

@csrf_exempt
def currentWeather(request):
    logger.info("Getting current weather... ")
    try:
        response = requests.get('http://' + getSparkIp() + ':5000/getKey',
                                headers={'Accept': 'application/json', 'Content-Type': 'application/json'})

        api_key_resp = response.json()
        api_key = api_key_resp[0]['api_key']
    except requests.exceptions.ConnectionError:
        logger.error("Server not available. Getting local apiKey")
        apiKeyObject = ApiKey.objects.all()[0]
        api_key = apiKeyObject.key
        logger.info("Local ApiKey: ", api_key)

    querystring = {"api_key": api_key}
    headers = {'cache-control': "no-cache"}
    base_url = "https://opendata.aemet.es/opendata"

    currentWeatherData = getData(base_url + "/api/observacion/convencional/todas", headers, querystring)

    stationsDict = defaultdict(list)
    logger.info("Parsing current weather... ")
    kml = simplekml.Kml()
    tourCurrentWeather = kml.newgxtour(name="Tour Current Weather")
    playlistCurrentWeather = tourCurrentWeather.newgxplaylist()

    for row in currentWeatherData:
        jsonData = json.loads(json.dumps(row))
        stationId = jsonData.get("idema")
        stationsDict[stationId].append(jsonData)

    totalStations = len(stationsDict.items())
    stationNumber = 1

    logger.info("Generating current weather kml... ")
    for key, value in stationsDict.items():
        actualPercentage = (stationNumber/totalStations)*100
        printpercentage(actualPercentage)

        try:
            jsonData = json.loads(json.dumps(value[-1]))
        except JSONDecodeError:
            return render(request, '500.html')

        latitude = float(jsonData.get("lat"))
        longitude = float(jsonData.get("lon"))
        datetimeStr = datetime.datetime.strptime(jsonData.get("fint"), "%Y-%m-%dT%H:%M:%S").strftime(
            '%H:%M:%S %Y-%m-%d')

        contentString = '<link rel = "stylesheet" href = "' \
                        'https://code.getmdl.io/1.3.0/material.blue_grey-red.min.css" / > ' + \
                        '<link rel="stylesheet" href="https://fonts.googleapis.com/css?' \
                        'family=Roboto:regular,bold,italic,thin,light,bolditalic,black,medium&lang=en"/>' + \
                        '

' + \
                        '
' + '
' + '
' + \
                        '
' +\
                        jsonData.get("ubi") + '
' + \
                        '
Station ID: ' +\
                        jsonData.get("idema") + '
' + \
                        '
Date: ' +\
                        datetimeStr + '
' + \
                        '
' + \
                        '
' + \
                        '
' + \
                        '
Max Temp:
' + \
                        '
' + \
                        '
' + \
                        '
' +\
                        str(jsonData.get("tamax")) + ' ºC
' + \
                        '
' + \
                        '
' + \
                        '
Actual Temp:
' + \
                        '
' + \
                        '
' + \
                        '
' +\
                        str(jsonData.get("ta")) + ' ºC
' + \
                        '
' + \
                        '
' + \
                        '
Min Temp:
' + \
                        '
' + \
                        '
' + \
                        '
' +\
                        str(jsonData.get("tamin")) + ' ºC
' + \
                        '
' + \
                        '
' + \
                        '
Relative Humidity :
' + \
                        '
' + \
                        '
' + \
                        '
' +\
                        str(jsonData.get("hr")) + ' %
' + \
                        '
' + \
                        '
' + \
                        '
Precipitation:
' + \
                        '
' + \
                        '
' + \
                        '
' +\
                        str(jsonData.get("precip")).replace("None", "0") + ' mm
' + \
                        '
' + \
                        '
' + \
                        '

' + \
                        '

'

        point = kml.newpoint(name=jsonData.get("ubi"), description=contentString,
                             coords=[(longitude, latitude)])

        point.style.balloonstyle.bgcolor = simplekml.Color.lightblue
        point.style.balloonstyle.text = contentString
        point.style.iconstyle.icon.href = 'https://png.icons8.com/thermometer-automation/ultraviolet/80'
        point.gxballoonvisibility = 0

        doFlyTo(playlistCurrentWeather, latitude, longitude, 1000, 5000, 3.0)
        playlistCurrentWeather.newgxwait(gxduration=3.0)

        animatedupdateshow = playlistCurrentWeather.newgxanimatedupdate(gxduration=5.0)
        animatedupdateshow.update.change = '<Placemark targetId="{0}"><visibility>1</visibility>' \
                                           '<gx:balloonVisibility>1</gx:balloonVisibility></Placemark>' \
            .format(point.placemark.id)

        doRotation(playlistCurrentWeather, latitude, longitude, 1000, 5000)

        animatedupdateshow = playlistCurrentWeather.newgxanimatedupdate(gxduration=0.1)
        animatedupdateshow.update.change = '<Placemark targetId="{0}"><visibility>0</visibility>' \
                                           '<gx:balloonVisibility>0</gx:balloonVisibility></Placemark>' \
            .format(point.placemark.id)

        stationNumber += 1

    fileName = "currentWeather.kmz"
    currentDir = os.getcwd()
    dir1 = os.path.join(currentDir, "static/kmls")
    dirPath2 = os.path.join(dir1, fileName)

    kml.savekmz(dirPath2, format=False)
    command = "echo '' | sshpass -p lqgalaxy ssh lg@" + getLGIp() + \
              " 'cat - > /var/www/html/kmls.txt'"
    os.system(command)

    sendKmlToLG(fileName, request)
    time.sleep(5)
    playTour("Tour Current Weather")

    return HttpResponse(status=204)

def getData(url, headers, querystring):
    """	Make the request to the api	"""
    try:
        response = requests.request("GET", url, headers=headers, params=querystring, verify=False)

        if response:
            jsonResponse = response.json()
            if jsonResponse.get('estado') == 200:
                link = jsonResponse.get('datos')
                data = requests.request("GET", link, verify=False)
                if data.status_code == 200:
                    return data.json()
                else:
                    return 0
            elif jsonResponse.get('estado') == 429:
                # Sleep until next minute
                logger.debug("####Sleeping")
                time.sleep(60)
                logger.debug("####Waked up!!")
                return getData(url)
    except requests.exceptions.ConnectionError:
        logger.error("####ERROR!! => Sleeping")
        time.sleep(120)
        logger.debug("####Waked up!!")
        return getData(url)

@csrf_exempt
def dummyWeather(request):

    sendDemoKmlToLG("dummyWeather.kmz", request)
    time.sleep(3)
    playTour("Tour Current Weather")

    return HttpResponse(status=204)


text:
module.exports.InvalidOptionFieldError = function InvalidOptionFieldError(message) {
  Error.call(this);
  this.message = message;
};


text:
class Tabs < Component
end


text:
#include "DataSet.h"
using namespace Statistics;

void DataSet::GetObservations(std::vector<Vector>& output)
{
  output.resize(0);
  output.resize(data.m);
  for(int i=0;i<data.m;i++)
    data.getRowRef(i,output[i]);
}

void DataSet::SetObservations(const std::vector<Vector>& input)
{
  if(input.empty()) {
    data.clear();
    return;
  }
  data.resize(input.size(),input[0].n);
  for(int i=0;i<data.m;i++) {
    assert(input[i].n == input[0].n);
    data.copyRow(i,input[i]);
  }
}

/*
void DataSet::SetObservation(int i,std::vector<Real>& in);
void DataSet::SetObservation(int i,Vector& in);

void DataSet::GetObservation(int i,std::vector<Real>& out);
void DataSet::GetObservation(int i,Vector& out);

void DataSet::SetElement(int j,std::vector<Real>& in);
void DataSet::SetElement(int j,Vector& in);
*/

void DataSet::GetElement(int j,std::vector<Real>& out)
{
  out.resize(data.m);
  for(int i=0;i<data.m;i++)
    out[i] = data(i,j);
}

void DataSet::GetElement(int j,Vector& out)
{
  data.getColCopy(j,out);
}


text:
<?php
require("DatabaseConnection.php");
function createHomePageCustomizationArea()
{
	try
{
    $c=DatabaseConnection::getConnection();
    $rs=$c->query("select * from tbl_homedata");
    echo '<form  action="" method="GET"  >';
    foreach($rs as $row)
    {
        echo "".$row["propertyLabel"]."";
echo '<input type="text" class="form-control"  name="'.$row["propertyName"].'" value="'.$row["propertyValue"].'" required >';
    echo "
";
    }
    echo '<button type="submit" class="btn btn-success btn-lg myButton pull-right">Save</button>';
    echo "
";
    echo "</form>";
    $rs=null;
    $c=null;
}
catch(Exception $exception)
{
    echo $exception->getMessage();
}
}

?>


text:
var deepCustomizer = function(includeVertices) {
	return function(val, id, obj) {
		var clone = {};
		if (val === null) {
			return null;
		} else if (_.isElement(val)) {
			// when deepcloning, drop DOM nodes
			return null;
		// if val is a pattern object
		} else if (_.isElement(val.this) && val.this.classList.contains("pattern")) {
			// drop DOM node, copy everything over (shallow clone)
			// except for start and end: decircularize by collapsing reference into an index
			for (var prop in val) {
				if (prop === "end" || prop === "start") {
					clone[prop] = {};
					for (var prop1 in val[prop]) {
						if (prop1 === "edge") {
							clone[prop][prop1] = val[prop][prop1].index;
						} else {
							clone[prop][prop1] = val[prop][prop1];
						}
					}
				} else if (_.isElement(val[prop])) {
					clone[prop] = null;
				} else {
					clone[prop] = val[prop];
				}
			}
			return clone;
		// if val is an edge object
		} else if (_.isElement(val.this) && val.this.classList.contains("edge")) {
			for (var prop in val) {
			// drop DOM node, copy everything over (shallow clone)
			// except for patterns: decircularize by collapsing reference into an index
				if (prop === "patterns") {
					clone[prop] = _.map(val[prop], function(p) {
						return _.cloneDeep(p, function(val, id, obj) {
							if (id === "pattern") {
								return val.index;
							}
						});
					});
				} else if (_.isElement(val[prop])) {
					clone[prop] = null;
				} else {
					clone[prop] = val[prop];
				}
			}
			return clone;
		// if val is a vertex object
		} else if (_.isElement(val.this) && val.this.classList.contains("vertex")) {
			if (includeVertices) {
				// drop DOM node, copy everything over (shallow clone)
				for (var prop in val) {
					if (_.isElement(val[prop])) {
						clone[prop] = null;
					} else {
						clone[prop] = val[prop];
					}
				}
				return clone;
			} else {
				return null;
			}
		}
	};
};

var isNode = function(o){
  return (
    typeof Node === "object" ? o instanceof Node :
    o && typeof o === "object" && typeof o.nodeType === "number" && typeof o.nodeName==="string"
  );
};

var reduceCircularity = function(tile) {

	var tileCopy = _.cloneDeep(tile);
	_.each(tileCopy.patterns, function(p, index) {
		p.end.edge = p.end.edge.index; // replace reference with id
		p.start.edge = p.start.edge.index;
		p.index = index;
		_.each(p.intersectedVertices, function(iv) {
			delete iv.p;
		});
	});

	_.each(tileCopy.edges, function(e) {
		_.each(e.patterns, function(p) {
			p.pattern = p.pattern.index;
		});
	});

	return tileCopy;
};

var circularize = function(tile) {

	_.each(tile.patterns, function(p, index) {
		p.end.edge = tile.edges[p.end.edge]; // dereference index
		p.start.edge = tile.edges[p.start.edge];
	});

	_.each(tile.edges, function(e) {
		_.each(e.patterns, function(p) {
			p.pattern = tile.patterns[p.pattern];
		});
	});

	return tile;
};

// used for circularizing tiles on the canvas, which have been flattened
// via deepCopy
var canvasCircularize = function(tile) {

	_.each(tile.patterns, function(p, index) {
		p.end.edge = tile.edges[p.end.edge.index]; // dereference index
		p.start.edge = tile.edges[p.start.edge.index];
	});

	_.each(tile.edges, function(e) {
		_.each(e.patterns, function(p) {
			p.pattern = tile.patterns[p.pattern.index];
		});
	});

	return tile;
};

var loadFromJson = function(loaded, callback) {
	if (loaded.version >= minSupportedVersion) {
		d3.select(".loading-overlay").classed("in", true);

		var canvasTransform = loaded.canvasTransform;

		assembleCanvas.each(function(d) {
			d.transform = canvasTransform;
		})
		.attr("transform", num.getTransform);
		commonZoomHandler.scale(num.getScale(canvasTransform));
		commonZoomHandler.translate(num.getTranslation(canvasTransform));

		var palette = loaded.palette;
		_.each(palette, circularize);
		polygonID = _.max(_.pluck(palette, "polygonID")) + 1;

		if (loaded.version === 0.2) {
			polylist = loaded.polylist;
			_.each(polylist, function(group) {
				_.each(group.tiles, circularize);
			});
		} else {
			polylist = _.map(loaded.polylist, function(group) {
				group.tiles = _.map(group.tiles, function(tile, tileIndex) {
					var tileTemplate = _.find(palette, function(t) {
						return t.polygonID === tile.polygonID;
					});
					var tileTemplateCopy = _.clone(tileTemplate);
					tileTemplateCopy.edges = _.map(tileTemplate.edges, function(edge, edgeIndex) {
						var edgeCopy = _.clone(edge);
						edgeCopy.id = [tileIndex, edgeIndex];
						return edgeCopy;
					});
					tileTemplateCopy.patterns = _.map(tileTemplate.patterns, _.clone);
					tileTemplateCopy.transform = tile.transform;
					return tileTemplateCopy;
				});
				return group;
			});
		}

		resetAndDraw(assembleCanvas, polylist, assembleCanvasOptions);
		assembleSVGDrawer.set(palette);
		assembleSVGDrawer.draw();

		if (loaded.colorMap) {
			colorMap = loaded.colorMap;
			_.each(colorMap, function(c) {
				_.each(c.strips, function(s) {
					s.patternList = _.omit(_.map(s.patternList, function(p) {
						if (p) {
							return {assembleCounterpart: polylist[p[0]].tiles[p[1]].patterns[p[2]]};
						}
						return null;
					}), function(p) { return p === null; });
				});
			});
		}

		if (loaded.stripViewParams) {
			var p = loaded.stripViewParams;

			if (p.thickness) { thicknessSlider.setValue(p.thickness); }
			if (p.extension) { extensionSlider.setValue(p.extension); }
			if (p.stripHeight) { stripHeight.setValue(p.stripHeight); }
			if (p.widthFactor) { widthFactor.setValue(p.widthFactor); }
			if (p.interSpacing) { interSpacing.setValue(p.interSpacing); }
			if (p.printHeight) { printHeight.setValue(p.printHeight); }
			if (p.printWidth) { printWidth.setValue(p.printWidth); }
			if (typeof p.outline !== "undefined") {
				$("#outlineToggle").bootstrapSwitch('state', p.outline);
			}
		}

		updateInferButton();

		if (loaded.cropData) {
			setupCropOverlay();
			$("#cropMode").bootstrapSwitch('state', loaded.cropData.cropMode);

			cropData.vertices = _.map(d3.selectAll(".crop-vertex").filter(function(d) {
				return d.correspondsTo && _.any(loaded.cropData.vertices, function(v) {
					return v.x === d.x && v.y === d.y;
				});
			})[0], function(d) {
				return d.__data__;
			});
			recomputeHull();

			teardownCropOverlay();

			if (cropData.hullEdges.length > 2 && $("#cropMode").bootstrapSwitch("state") &&
				!$("#patternCroppingSwitch").bootstrapSwitch("state")) {
				$("#patternCroppingSwitch").bootstrapSwitch("state", true);
			}
		}

		var nonPlanarEdgeJoinsExist = false;
		d3.selectAll(".edge.joined").each(function(d) {
			nonPlanarEdgeJoinsExist = nonPlanarEdgeJoinsExist || !d.joinedTo.isPlanar;
		});
		if (nonPlanarEdgeJoinsExist && !$("#nonPlanarSwitch").bootstrapSwitch("state")) {
			$("#nonPlanarSwitch").bootstrapSwitch("state", true);
		}

		d3.select(".loading-overlay").classed("in", false);
		invalidateStripCache();

		if (callback) {
			callback();
		}

	} else {
		if (typeof loaded.version === "undefined") {
			loaded.version = "?";
		}
		d3.select(".loading-overlay").classed("in", false);
		throw {
			message: "File was from Sliceform Studio v" + loaded.version +
				" but only >=v" + minSupportedVersion + " is supported."
		};
	}
};

var generateAbridgedColorMap = function() {
	_.each(polylist, function(gp, gpIdx) {
		_.each(gp.tiles, function(tile, tileIdx) {
			_.each(tile.patterns, function(pattern, patternIdx) {
				pattern.uniqId = [gpIdx, tileIdx, patternIdx];
			});
		});
	});

	var colorMapCopy = _.map(colorMap, function(c) {
		return {
			color: c.color,
			strips: _.map(c.strips, function(s) {
			return {patternList: _.map(s.patternList, function(p) {
				return p.assembleCounterpart.uniqId;})};
			})
		};
	});

	_.each(polylist, function(gp, gpIdx) {
		_.each(gp.tiles, function(tile, tileIdx) {
			_.each(tile.patterns, function(pattern, patternIdx) {
				delete pattern.uniqId;
			});
		});
	});

	return colorMapCopy;
};

var saveToFileWithTitle = function(title) {

	var reducedPolylist = _.map(polylist, function(gp) {
		var gpClone = _.clone(gp);
		gpClone.tiles = _.map(gp.tiles, function(tile) {
			return {
				polygonID: tile.polygonID,
				transform: tile.transform
			};
		});
		return gpClone;
	});

	var nonCircularPalette = _.map(assembleSVGDrawer.get(), function(tile) {
		return reduceCircularity(tile);
	});

	var abridgedColorMap = generateAbridgedColorMap();

	var cropVertices = _.map(cropData.vertices, function(v) { return _.pick(v, _.isNumber); });

	var saveFile = {
		polylist: reducedPolylist,
		palette: nonCircularPalette,
		cropData: {
			vertices: cropVertices,
			cropMode: $("#cropMode").bootstrapSwitch("state")
		},
		colorMap: abridgedColorMap,
		canvasTransform: assembleCanvas.node().__data__.transform,
		version: wallpaperVersion,
		stripViewParams: {
			thickness: thicknessSlider.getValue(),
			extension: extensionSlider.getValue(),
			outline: $("#outlineToggle").bootstrapSwitch("state"),
			stripHeight: stripHeight.getValue(),
			widthFactor: widthFactor.getValue(),
			interSpacing: interSpacing.getValue(),
			printHeight: printHeight.getValue(),
			printWidth: printWidth.getValue()
		}
	};

	var saveFileText = JSON.stringify(saveFile, function(k,v) {
		return (isNode(v)) ? "tag" : v;
	});

	var bb = new Blob([saveFileText], {type: "application/json"});
	var pom = d3.select("#downloadLink").node();
	pom.download = title;
	pom.href = window.URL.createObjectURL(bb);
	pom.dataset.downloadurl = ["application/json", pom.download, pom.href].join(':');
	pom.click();
};

var getUrlVars = function() {
    var vars = [], hash;
    var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split(/[&#]/);
    for(var i = 0; i < hashes.length; i++)
    {
        hash = hashes[i].split('=');
        vars.push(hash[0]);
        vars[hash[0]] = hash[1];
    }
    return vars;
};


text:
table-normalizer-js
===================