working on it ...

Filters

Explore InChannel Snippets

Sort by

Found 500 snippets

    public by tomsim modified Sunday at 5:41:50 PM  16  0  3  0

    Simple RPC call

    Simple function to call RPC (only 1k uncompressed). Use this instead of JQuery. Alternatively, use zepto.min.js from zeptojs.com if you have 26K to spare.
    /* 
    Addapted from Paolo Manna git pmanna/mongoose_os_playground browser_rpc_service.js
    */
    
    var platform = '';
    var host = '';
    
    var defCallBack = function(response) {
      if ((response) && (response.error)) {
    	  alert(response.message);
      }
    };
    
    // Common call to RPC services on the board
    function callRPCService(cmd, params, callback) {
      if (!callback) {
    	  callback = defCallBack;
      }
      var xhttp = new XMLHttpRequest();
      
      xhttp.onreadystatechange = function() {
        if (this.readyState == 4 && this.status == 200) {
          callback(this.response);
        }
      };
      
      xhttp.open('POST', 'rpc/' + cmd + '?' + new Date().getTime(), true);
      xhttp.responseType = 'json';
      xhttp.send(JSON.stringify(params));
    }
    
    // Discover which platform we're using, to enable/disable features
    function startup() {
      callRPCService('Config.Get',{}, function(response) {
        if (response) {
          platform = response.device.id;
          console.log('Platform is: ' + platform);
    
          var mac_id = (response.device.id.split("_"))[1];
    
          host = mac_id + '.local';
          document.getElementById("hostname").innerHTML = host;
        }
      });
    }
    
    // Reboots the microcontroller
    function rebootDevice() {
      callRPCService('Sys.Reboot',{delay_ms:500});
    }
    
    						

    public by tomsim modified Sunday at 5:39:39 PM  11  0  2  0

    Using simple RPC service

    Use simple rpc script to call RPC service on small IOT devices
    <html>
    <head>
    	<script src="simple_rpc_service.js"></script>
    </head>
    <body onLoad='startup();'>
    <h4 id="hostname"> </h4>
    <p>Hello, see <a target="_blank" href="/rpc/Config.Get">rpc</a>
    <br><a target="_blank" href="/rpc/clearAll">clear strip</a>
    
    <p><table>
      <tr><td>Pin</td> <td><input type="number" id="GPIO.pin" value='2'/></td></tr>
      <tr><td>Red</td><td><input type="range" id="rval" name="rval" min="0" max="255" value='0' onchange="setPixel()"/></td></tr>
      <tr><td>Green</td><td><input type="range" id="gval" name="gval" min="0" max="255" value='0' onchange="setPixel()"/></td></tr>
      <tr><td>Blue</td><td><input type="range" id="bval" name="bval" min="0" max="255" value='0' onchange="setPixel()"/></td></tr>
    </table>
    <p><button href="#" id="setPixel" onclick="setPixel()">Set Pixel</button>
    <button href="#" id="clearAll" onclick="callRPCService('clearAll')">Clear All Pixel</button>
    <p><button href="#" id="setPixel" onclick="rebootDevice()">Reboot</button>
    
    <script>
    
      var log = function(msg) {
        console.log(msg);
      };
      log('Starting ...');
      function setPixel() {
        log("setPixel...");
      	var pin = parseInt(document.getElementById("GPIO.pin").value);
      	var rv = parseInt(document.getElementById("rval").value);
      	var gv = parseInt(document.getElementById("gval").value);
      	var bv = parseInt(document.getElementById("bval").value);
    	callRPCService('setPixel',{px:pin, r:rv, g:gv, b:bv});
      };
    </script>
    
    </body>
    </html>
    

    public by tomsim modified Sunday at 4:55:46 PM  11  0  3  0

    ESP8266 wifi web server setup

    Lambda style Wifi web server with DHT22 data upload to ThingSpeak
    /* DHTServer - ESP8266 Webserver with a DHT sensor as an input
    
       Based on ESP8266Webserver, DHTexample, and BlinkWithoutDelay (thank you)
    
       Version 1.0  5/3/2014  Version 1.0 Mike Barela for Adafruit Industries
    */
    #include <ESP8266WiFi.h>
    #include <WiFiClient.h>
    #include <ESP8266WebServer.h>
    #include <DHT.h>
    #include <TimeLib.h>
    #include "ThingSpeak.h"
    
    #define DHTTYPE DHT22
    
    const int DHTPIN = D4;
    
    const char* ssid     = "mySSID";
    const char* password = "myPassword";
    
    ESP8266WebServer server(80);
    
    /*============ ThingSpeak setup ==================*/
    // Note:  Each channel has its own number and write API key
    // API key is what get used - wrong channel number doesn't matter
    
    // Temperature Humidity Channel
    static unsigned long myChannelNumber = 123456;
    static const char 	*myWriteAPIKey = "AB1CDEF6HIJKLMNO";
    static WiFiClient  client;
    
    /*============ End ThingSpeak setup ==============*/
    
    
    // Initialize DHT sensor 
    // NOTE: For working with a faster than ATmega328p 16 MHz Arduino chip, like an ESP8266,
    // you need to increase the threshold for cycle counts considered a 1 or 0.
    // You can do this by passing a 3rd parameter for this threshold.  It's a bit
    // of fiddling to find the right value, but in general the faster the CPU the
    // higher the value.  The default for a 16mhz AVR is a value of 6.  For an
    // Arduino Due that runs at 84mhz a value of 30 works.
    // This is for the ESP8266 processor on ESP-01 
    DHT dht(DHTPIN, DHTTYPE, 11); // 11 works fine for ESP8266
     
    float lastHumdty, lastTempF;  // Values read from sensor
    static int nextSampleMinute = 15;
    static int minuteSampleInterval = 15;
    
    // Generally, you should use "unsigned long" for variables that hold time
    unsigned long previousMillis = 0;        // will store last temp was read
    const long interval = 2000;              // interval at which to read sensor
    
    void getTemperature() {
      // Wait at least 2 seconds seconds between measurements.
      // if the difference between the current time and last time you read
      // the sensor is bigger than the interval you set, read the sensor
      // Works better than delay for things happening elsewhere also
      unsigned long currentMillis = millis();
     
      if(currentMillis - previousMillis >= interval) {
        // save the last time you read the sensor 
        previousMillis = currentMillis;   
    
        // Reading temperature for humidity takes about 250 milliseconds!
        // Sensor readings may also be up to 2 seconds 'old' (it's a very slow sensor)
        lastHumdty = dht.readHumidity();          // Read humidity (percent)
        lastTempF = dht.readTemperature(true);     // Read temperature as Fahrenheit
        // Check if any reads failed and exit early (to try again).
        if (isnan(lastHumdty) || isnan(lastTempF)) {
          Serial.println("Failed to read from DHT sensor!");
          return;
        }
      }
    }
    
    static int uploadData(void)
    {
    	ThingSpeak.setField( 1, lastTempF);
    	ThingSpeak.setField( 2, lastHumdty);
    	int rc = ThingSpeak.writeFields(myChannelNumber, myWriteAPIKey);
    //	Serial.println(String("Post rc=")+rc);
    	return rc;
    }
    
     
    const String HTML_TYPE = "text/html";
    
    void handle_null() {
        Serial.println("Handle null");
    	server.send(200,HTML_TYPE,"");
    	delay(100);
    }
    void handleRoot()
    {
    	String wstr = 
    	"<p>Hello from the weather esp8266, read from /temp or /humidity"
    	"<br>set <a href=/set?minuteSampleInterval=5>5 minute</a> sample interval"
    	", <a href=/set?nextSampleMinute=15>sample at 15 </a> minute"
    	"<br>Take <a href=/sample>sample Data</a> and upload to ThingSpeak"
    	"<br><a href=/temp>Get Temperature</a>"
    	"<br><a href=/humidity>Get Humidity</a>";
    	wstr += "<br>Last temperature: " + String(lastTempF)+"F";
    	wstr += " humidity: " + String(lastHumdty)+"%";
    	wstr += "<br>Current minute: " + String(minute(now()));
    	wstr += " next sample time: " + String(nextSampleMinute)+" min.";
    	wstr += " sample interval: " + String(minuteSampleInterval)+" min.";
    	server.send(200,HTML_TYPE, wstr);
    	delay(100);
    }
    void doSample()
    {
    	Serial.println("DoSample");
    	getTemperature();
    	int rc = uploadData();
    	String wstr = "<p>Take sample data:  ";
    	wstr += "<br>Temperature " + String(lastTempF);
    	wstr += "<br>Humidity " + String(lastHumdty);
    	wstr += "<br>Upload thingspeak rc=" + String(rc);
    	server.send(200,HTML_TYPE, wstr);
    }
     
    // Web Server Service Definition structure
    // =======================================
    typedef struct s_WebServiceDef
    {
    	const char *urlName;
    	void (*doit)(void);
    } WebServiceDef;
    
    /* =======================================================================
    	Define web service definition here
    	Each entry has a URL name and a lambda function to service the request
       =======================================================================
    */
    static WebServiceDef wsd[] = {
    	{ "/", handleRoot },
    	{ "/favicon", handle_null },
    	{ "/temp",			// url name
    		[] ()				// lambda function
    		{
    			getTemperature();       // read sensor
    			String wstr="Temperature: "+String((int)lastTempF)+" F";
    			server.send(200, "text/plain", wstr);   // send to someones browser when asked
    		}
    	},
    	{ "/humidity", []()
    		{ 
    			getTemperature();
    			String wstr="Humidity: "+String((int)lastHumdty)+"%";
    			server.send(200, "text/plain", wstr);
    		}
    	},
    	{ "/sample", doSample },
    	{ "/set", []()
    		{
    			String n = String("minuteSampleInterval");
    			if (server.hasArg(n))
    			{
    				int v = server.arg(n).toInt();
    				if (v)
    					minuteSampleInterval = v;
    			}
    			n = String("nextSampleMinute");
    			if (server.hasArg(n))
    			{
    				int v = server.arg(n).toInt();
    				if (v)
    					nextSampleMinute = v;
    			}
    			server.send(200, "text/plain", "ok");
    		}
    	},
     	{0,0}
    };
    
    static void setupServerHandler(void)
    {
    	for (int i; wsd[i].urlName; i++)
    	{
    		server.on( wsd[i].urlName, wsd[i].doit);
    	}
    	server.onNotFound(handleRoot);
    }
    
    static int nextAlarmMin(int sampleInterval)
    {
    	int nextMin = minute(now());
    	nextMin = ((nextMin + sampleInterval) % 60);	// alarm every 5 min
    	return nextMin;
    }
    
    
    
    void setup(void)
    {
    	// You can open the Arduino IDE Serial Monitor window to see what the code is doing
    	Serial.begin(115200);  // Serial connection from ESP-01 via 3.3v console cable
    	dht.begin();           // initialize temperature sensor
    
    	// Connect to WiFi network
    	WiFi.begin(ssid, password);
    	Serial.print("\n\r \n\rWorking to connect");
    
    	// Wait for connection
    	while (WiFi.status() != WL_CONNECTED) {
    	delay(500);
    	Serial.print(".");
    	}
    	Serial.println("");
    	Serial.println("DHT Weather Reading Server");
    	Serial.print("Connected to ");
    	Serial.println(ssid);
    	Serial.print("IP address: ");
    	Serial.println(WiFi.localIP());
    
    	ThingSpeak.begin(client);
    
    	setupServerHandler();
    
    	server.begin();
    	Serial.println("HTTP server started");
    }
     
    void loop(void)
    {
    	int currentMinute = minute(now());
    
    	if (currentMinute == nextSampleMinute)
    	{
    		// trigger sample at set interval
    		Serial.println("Regular sample");
    		getTemperature();
    		int rc = uploadData();
    		Serial.println("rc=" + String(rc));
    
    		nextSampleMinute = nextAlarmMin(minuteSampleInterval);
    		delay(1000);
    	}
    
    	server.handleClient();
    } 
    
    

    public by azazqadir modified Thursday at 10:25:40 AM  69  0  3  0

    Adding Captcha in CodeIgniter

    Source: https://www.cloudways.com/blog/captcha-in-codeigniter/
    <?php
    
    defined('BASEPATH') OR exit('your exit message');
    
    class Captcha extends CI_Controller
    
    {
    
       function __construct()
    
       {
    
           parent::__construct();
    
           $this->load->helper('captcha');
    
       }
    
       public function index()
    
       {
    
           if ($this->input->post('submit')) {
    
               $captcha_insert = $this->input->post('captcha');
    
               $contain_sess_captcha = $this->session->userdata('valuecaptchaCode');
    
               if ($captcha_insert === $contain_sess_captcha) {
    
                   echo 'Success';
    
               } else {
    
                   echo 'Failure';
    
               }
    
           }
    
           $config = array(
    
               'img_url' => base_url() . 'image_for_captcha/',
    
               'img_path' => 'image_for_captcha/',
    
               'img_height' => 45,
    
               'word_length' => 5,
    
               'img_width' => '45',
    
               'font_size' => 10
    
           );
    
           $captcha = create_captcha($config);
    
           $this->session->unset_userdata('valuecaptchaCode');
    
           $this->session->set_userdata('valuecaptchaCode', $captcha['word']);
    
           $data['captchaImg'] = $captcha['image'];
    
           $this->load->view('captcha/index', $data);
    
       }
    
       public function refresh()
    
       {
    
           $config = array(
    
               'img_url' => base_url() . 'image_for_captcha/',
    
               'img_path' => 'image_for_captcha/',
    
               'img_height' => 45,
    
               'word_length' => 5,
    
               'img_width' => '45',
    
               'font_size' => 10
    
           );
    
           $captcha = create_captcha($config);
    
           $this->session->unset_userdata('valuecaptchaCode');
    
           $this->session->set_userdata('valuecaptchaCode', $captcha['word']);
    
           echo $captcha['image'];
    
       }
    
    }

    public by Hlinh modified Thursday at 2:47:29 AM  28  0  3  0

    Lookbook For Magento 2

    Lookbook for Magento 2 is a magical tool which allows you to create multiple image collections for your products basing on the images you upload. What makes this extension so special and unique is that it offers a Pinning option for every image, i.e you can pin different images for products/ items onto the main image, which ultimately envisages a c
    The Lookbook is a magical tool which allows you to create multiple image collections for your products basing on the images you upload.						

    public by klopez0017 modified Jan 11, 2018  33  0  2  0

    Lua Header

    Lua Function Header
    LUA
    -- *******************************************
    -- * 
    -- *******************************************

    public by sjschmalfeld modified Jan 4, 2018  234  0  4  0

    SQL Duplicates

    WITH cte AS
    (SELECT *, ROW_NUMBER() OVER (PARTITION BY col1, col2, col3, col4 ORDER BY (SELECT 0)) AS DuplicateRowNumber
        FROM table
    )
    SELECT FROM cte WHERE DuplicateRowNumber > 1
    
    
    or----
    
    WITH cte as
    (SELECT PEOPLE.*, Loan.LoanID, ROW_NUMBER() OVER (PARTITION BY SocialSecurityNo ORDER BY SocialSecurityNo) AS DuplicateRowNumber
    FROM people INNER JOIN LOAN ON FK_PeopleID=PeopleID WHERE ISNULL(SocialSecurityNo,'') <> '' AND SocialSecurityNo <> '--' AND SocialSecurityNo <> '000-00-0000' AND loan.Status='active' )
    
    SELECT * INTO #TEMP99 FROM CTE WHERE cte.DuplicateRowNumber > 1
    
    SELECT *,b.SocialSecurityNo FROM dbo.Loan 
    	INNER JOIN (SELECT PeopleID,SocialSecurityNo FROM PEOPLE WHERE SocialSecurityNo	 
    							IN (SELECT SocialSecurityNo FROM #temp99)) b 
    	ON B.PeopleID=LOAN.FK_PeopleID
    	WHERE LOAN.Status='ACTIVE'
    
    DROP TABLE #TEMP99  
    
    
    -- Another way
    	--GET RID OF #NewAddressCandidates ADDESSES ALEADY IN THE ADDRESS TABLE
    	DELETE FROM #NewAddressCandidates WHERE EXISTS (
    	SELECT t.[Address1] 
    				,t.Address2
    				,t.City
    				,t.[State]
    				,SUBSTRING(t.Zip,1,5) AS ZIP, 
    				SUBSTRING(t.Zip,7,4) AS ZIP4 
    		FROM #NewAddressCandidates T 
    			INTERSECT  
    		SELECT [Address1] ,[Address2],[City],[State],[Zip],ZIP4 FROM dbo.[Address])				
    		
    		
    -- Another way
    	WITH NODUP AS 
    		(SELECT  A.ADDRESS1,A.ADDRESS2,A.CITY,A.STATE,A.ZIP,A.ZIP4
    			  , row_number() OVER ( PARTITION BY  A.ADDRESS1,A.ADDRESS2,A.CITY,A.STATE,A.ZIP,A.ZIP4 ORDER BY  A.ADDRESS1,A.ADDRESS2,A.CITY,A.STATE,A.ZIP,A.ZIP4 ) AS nr
    		FROM    #NewAddressCandidates A)
    	DELETE FROM NODUP WHERE NR > 1;	
    	
    	SELECT * INTO  #UniqueNewAddresses  FROM #NewAddressCandidates WHERE EXISTS (
    	SELECT t.[Address1] 
    				,t.Address2
    				,t.City
    				,t.[State]
    				,SUBSTRING(t.Zip,1,5) AS ZIP, 
    				SUBSTRING(t.Zip,7,4) AS ZIP4 			
    		FROM #NewAddressCandidates T 
    			EXCEPT 
    		SELECT [Address1] ,[Address2],[City],[State],[Zip],ZIP4 FROM dbo.[Address])
    		
    		
    		
    		

    public by michaelbukachi modified Jan 4, 2018  54  0  3  0

    Javafx confirmation dialog

    Utility method to show a confirmation dialog using javafx
    private boolean showConfirmationDialog(String message) {
    		Alert alert = new Alert(AlertType.CONFIRMATION);
    		alert.setTitle("Confirm Action");
    		alert.setHeaderText(null);
    		alert.setContentText(message);
    		Optional<ButtonType> result = alert.showAndWait();
    		
    		return result.get() == ButtonType.OK;
    	}

    public by michaelbukachi modified Jan 4, 2018  52  0  3  0

    JavaFx message dialog

    A utility method to show a message dialog using java fx
    private void showMessageDialog(String message) {
        	Alert alert = new Alert(AlertType.INFORMATION);
    		alert.setTitle("Confirm Action");
    		alert.setHeaderText(null);
    		alert.setContentText(message);
    		alert.show();
    	}

    public by mikealdin modified Jan 3, 2018  96  1  1  0

    getting error code10:2:12:3:1 Amazon Alexa - Wi-Fi Troubleshooting

    getting error code10:2:12:3:1 Amazon Alexa - Wi-Fi Troubleshooting: Alexa-app-Wi-Fi-troubleshooting
    Amazon Alexa is most famous voice enable app that is compatible with all Amazon echo devices and also with some third party devices.
    When you will get this error code message(10:2:12:3:1) on Alexa App what will you do? 
    Try to follow these steps:
    ...In the Alexa app, go to the left navigation panel and select Settings.
    ...Select your Echo device and Update Wi-Fi easily. If you're adding a new device to your account, select Set up a new device then
    ...On your Amazon Echo device, press & hold the Action button until the light ring changes to orange. 
    ...Your mobile device will then connect to your Amaozn Echo device. A list of available Wi-Fi networks appear in the Alexa app.
    
    Tips: Connect your Echo device through Wi-Fi setting manually.
    
    Select your Wi-Fi network and enter the password. If you don't see your Wi-Fi/network, scroll down and 
    select Add a Network or Rescan.
    
    Reboot your device again and will be sure not see this error again.
    
    
    • Public Snippets
    • Channels Snippets