Materialized Views

REFRESH FAST Categories

There are three ways to categorize a materialized view’s ability to be fast refreshed.

  1. It can never be fast refreshed.
  2. It can always be fast refreshed.
  3. It can be fast refreshed after certain kinds of changes to the base table but not others.

For the first case Oracle will raise an error if you try to create such a materialized view with its refresh method defaulted to REFRESH FAST. In the example below table T does not have a materialized view log on it. Materialized views based on T cannot therefore be fast refreshed. If we attempt to create such a materialized view we get an error.

create materialized view MV REFRESH FAST as select * from t2 ; as select * from t2 * ERROR at line 3: ORA-23413: table "SCOTT"."T2" does not have a materialized view log

Source: Materialized Views: REFRESH FAST Categories

Hits: 42

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

Top 5 DevSecOps Tools To Use In 2018

DevSecOps involves creating a ‘Security as Code’ culture with ongoing, flexible collaboration between release engineers and security teams with the aim of bridging traditional gaps between IT and security while ensuring fast, safe delivery of code. In this era where online presence is paramount and a source that makes trading convenient and easy where personal data can be controlled on internet platforms, it is important to be security conscious. With the pros of online services, there are also the cons and this include cyber threats which explores business vulnerability to breach data and security therefore causing possible harm. With that said, it is important to make everyone in the software development life cycle responsible for security to prevent possible threats in the company.

DevSecOps is more about changing IT culture and people’s mindsets when it comes to security measured online and there are various tools to support the development, in this article we will discuss only the top 5 tools to use in 2018.

1. Data management

This is an important tool for everyone who needs security, it helps you to manage the data you share and enables you search, improve and create useful information for data which can be generated. It may not be able to store all your data but it is a vital tool that can help you backup your operation.

2. Threat detection and response

This tool helps you correlate threat indications from firewalls or host sensors then respond to them immediately by resolving the issue with a cleanup as well as update your drive. In the process, it can scan your device to identify possible threats and check the performance and speed.

3. Lifecycle management

In large firms, top management make decisions and share it with other staffs in the enterprise for everyone to be aligned with the strategy and in the process of sharing data, public or private information’s can be distributed which can be confidential. To avoid the risk of getting those information’s to the wrong party the company needs to use an enterprise lifecycle management tool that can provide visibility, backlogs and an insight into the integration server to guarantee an end-to-end compliance with security, privacy and other regulatory requirements.

4. Security unit testing

Security Unit Testing tools help you scan for application security flaws in real time while developers help your business achieve its goals. As much as you can use a tool, you also need a developer to help you test early and development lifecycle to integrate into the existing development toolchain for your e-commerce web design. You also need a Magento support if you are not a developer, to help you with your service, performance update and the maintenance of your ecommerce business.

5. ThreatModeler

This tool automatically analyzes any information a user provides to check for any potential threat based on accurate threat intelligence. This tool also provides the mitigating security requirements and test cases to ensure security implementation.

Hits: 107

No New New: Raw Pointers Removed from C++

Two weeks ago, the ISO C++ standard meeting took place in Jacksonville. Today I want to make a short detour and write about the revolutionary decision that was made in the Jacksonville meeting. Additionally, I refer to the Will no Longer Have Pointers by Fluent C++. The standard committee decided that pointers will be deprecated in C++20 and will with very high probability removed in C++23.

To be honest, what seems like a revolution is only the last step in a long evolution. First, let me explain the big picture.

 The evolution of pointers in C++

Pointers are part of C++ since the first beginning. We got them from C. From the first beginning there was always the tendency in C++ to make the handling with pointers more type-safe without paying the extra cost.

With C++98 we got std::auto_ptr to express exclusive ownership. But std::auto_ptr had a big issue. When you copy an std::auto_ptr the resource will be moved. What looks like a copy operation was actually a move operation. The graphic shows the surprising behaviour of an std::auto_ptr.

This was extremely bad and the reason for a lot of serious bugs; therefore, we got std::unique_ptr with C++11 and std::auto_ptr was deprecated in C++11 and finally removed in C++17. Additionally, we got std::shared_ptr and std::weak_ptr in C++11 for handling shared ownership. You can not copy but move an std::unique_ptr and if you copy or assign an std::shared_ptr, the internal reference counter will be increased. Have a look here:

Since C++11 C++ has a multithreading library. This makes the handling with std::shared_ptr quite challenging because an std::shared_ptr is per definition shared but not thread-safe. Only the control-block is thread-safe but not the access to its resource. That means, modifying the reference counter is an atomic operation and you have the guarantee that the resource will be deleted exactly once. This is the reason we will get with C++20 atomic smart pointers: std::atomic_shared_ptr and std::atmic_weak_ptr. Read the details in the proposal: Atomic Smart Pointers.

Hits: 91

“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

Code Like a Pythonista: Idiomatic Python

Dictionary and Iterators

Dictionaries implement a sq_contains slot that implements the same test as the has_key() method. This means that we can write

if k in dict: ...
which is equivalent to
if dict.has_key(k): ...

Dictionaries implement a tp_iter slot that returns an efficient iterator that iterates over the keys of the dictionary. During such an iteration, the dictionary should not be modified, except that setting the value for an existing key is allowed (deletions or additions are not, nor is the update() method). This means that we can write

    for k in dict: ...

which is equivalent to, but much faster than

for k in dict.keys(): ...

as long as the restriction on modifications to the dictionary (either by the loop or by another thread) are not violated.

Add methods to dictionaries that return different kinds of iterators explicitly:

for key in dict.iterkeys(): ...
for value in dict.itervalues(): ...
for key, value in dict.iteritems(): ...

This means that for x in dict is shorthand for for x in dict.iterkeys().

Other mappings, if they support iterators at all, should also iterate over the keys. However, this should not be taken as an absolute rule; specific applications may have different requirements.

Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren’t special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.

navs = {} for (portfolio, equity, position) in data: navs.setdefault(portfolio, 0) navs[portfolio] += position * prices[equity]

Source: http://www.omahapython.org/IdiomaticPython.html

Hits: 42

The best code editors for WordPress developers

Hello! Since you are reading this article, it means that you are a WordPress developer, just like me, and strive to make your work with WordPress as productive as possible.

What do we have to do when creating sites on WordPress? We do not just edit PHP files. We should be a programmer and WEB-designer, have the skills to work with HTML, CSS and JavaScript, as it is necessary for a successful WEB-programming.

And a modern IDE or text editor that wants to win the favor of users should provide support for all the necessary languages and technologies.

As a rule, to manage several projects you need a full PHP development environment, such as PhpStorm or CodeLobster. But I also use text editors too, for example if I need to quickly correct a template or modify the code of my function.

Creators of code editors are constantly working on adding new and expanding existing capabilities of their products to support CMS WordPress. Because the community of programmers understand the importance of implementing WordPress support in their software.

I had to spend a lot of time to pick up several IDEs and text editors with advanced features and convenient functionality for WordPress developers.

I suggest you to discover these wonderful programs.

SublimeText

Sublime Text is a fast text editor with a fashionable user interface. It perfectly supports HTML, CSS and JavaScript syntax without additional plug-ins.

To expand the functionality and add tools for WordPress developers, you need to install special packages.

Run the program and go to the main menu “Tools” -> “Install Package Control …”. Package Control is a package that allows you to manage other plug-ins.

After that, you can download, install and remove plug-ins. To start the Package Control, go to the main menu “Preferences” -> “Package Control”.

In order for the program to load the list of available modules, it is necessary to select from the list or enter from the keyboard the command “Install Package”.

Let’s enter “WordPress” in the search bar to filter out the plug-ins specific to this CMS.

From the list, you can immediately select the first “WordPress” package and install it by double-clicking it. This package adds a set of snippets and the ability to auto-complete the functions of WordPress.

Sublime Text

The next plugin we select from the list is called “Search WordPress Codex”. Using it, you can search the official WordPress online help directly from the editor.

For example, right-click on the function and select “WordPress Codex” -> “Search Selection” from the context menu to view online help on it.

Sublime Text

Also there are several popular extensions that you should pay attention to, for example:

  • WordPress snippets – provides a collection of snippets for WordPress programmers.
  • WordPress New Project Config – helps you to create and configure a new project for WordPress CMS.
  • Genesis – facilitates the work of the creators of themes for WordPress, which use the child themes of Genesis.

Atom

Atom is another text editor with a lot of advanced functions and beautiful design. It positions itself as an IDE and successfully competes with other similar programs, such as Sublim Text and Rapid PHP.

Atom is based on themes and packages, so it has a wide range of functions and is flexibly configured. It has its own package manager, which we will use to install WordPress support.

Launch Atom and go to the main menu “File” -> “Settings”. In the opened settings tab, click on “Install”.

Now, to find new packages, enter the keyword “wordpress” in the search field and press “Enter”. You can also click on the “Packages” button.

In the list that appears, let’s choose one of the popular packages, for example – Autocomplete WordPress Hooks. This extension will help the developer by providing the completion of WordPress Actions and Filters.

Find this package in the list and click the “Install” button. After a minute we will see that the package is installed.

Now check the functionality of the just added module. Start type the name of the function and press Ctrl + Space.

Atom Now check the functionality of the just added module. Start type the name of the function and press Ctrl + Space.
Atom

After that, we can also use the hints on the parameters of the function.

Atom

The algorithm for working with other packages is the same. Just read the description, and if the functionality is suitable, install it.

For example, you can install the following add-ons:

  • WordPress API – this add-on greatly speeds up the development process, offering useful WordPress snippets.
  • WordPress Dictionary for Atom – adds snippets for all WordPress functions, including Actions and Filters.

Rapid PHP

Rapid PHP is also a good editor with support of PHP, HTML, CSS and JavaScript. It successfully combines the functionality of the real IDE with high speed.

It is not resource-demanding, has a built-in PHP debugger, supports HTML5, CSS3 and several frameworks, including WordPress.

For higher performance, ability to work with frameworks is disabled by default. To enable WordPress support, go to the main menu “Options” -> “Frameworks”.

In the list that appears, you can select one or more libraries that you want to work with. In this case, choose WordPress and click “OK”.

In the next step, let’s create the project, for that we go to the main menu and select “Project” -> “New Project”.

Now enter the project name and path to the project files. In this example, specify the folder with WordPress installed.

When the project is created, you can view its contents in the right pane of the program using the file browser.

Rapid PHP provides the programmer with ability to use the autocompletion feature when pressing the Ctrl + Space keys.

Rapid PHP
Rapid PHP

You can also trigger an instant prompt on WordPress functions by pressing Shift + Ctrl + Space.

Rapid PHP
Rapid PHP

If in the process of work you need to use the online help for any PHP function, just place the cursor on its name and press the F1 key. The page with online help will be displayed in the browser installed on the system.

CodeLobster

CodeLobster is a functional IDE that provides a complete set of tools for the web developer.

It has an editor of PHP, HTML, CSS and JavaScript with suggestions and autocompletion.

CodeLobster allows you to work with databases directly from the IDE, edit PHP files on the local computer and on a remote server using FTP.

Among other things, you can use PHP debugger, contextual and dynamic help.

There is a convenient function of installing WordPress directly from the program. In addition to that the CMS is installed and configured instantly, much faster than via the WEB-interface.

For example, to create a project, go to the main menu “Project” -> “Create Project …”.

Then in the dialog box, you can specify the type of the project, which will be created using the framework or one of the popular CMS.

Select “Create Empty WordPress Site”, enter the name and specify the location of the directory for installation. Then the New WordPress Site Wizard will run.

It will take only a few steps to configure the connection to the database and at the last step specify the parameters of our blog.

After clicking the “Finish” button, the fresh WordPress distribution will be installed and a new project will be created, you can immediately start working.

If we move the mouse pointer to any function name, we get information about it in a tooltip.

CodeLobster

For full information about this function from the official WordPress documentation, it is enough to select it and press the F1 key.

To use autocompletion, just start typing the name of the function and press Ctrl + Space.

CodeLobster

CodeLobster includes the WordPress plugin in its professional version. That allows the developer to quickly start working with this CMS, since no additional installation is required.

PhpStorm

PhpStorm is a PHP IDE with many convenient features for the web developer. This programming environment is built on the IntelliJ IDEA platform and inherited all the capabilities of the parent platform.

For WordPress programmers, the distribution of the IDE comes with a special plug-in for integration with WordPress.

To start working, you need to register WordPress in the program. Start PhpStorm and go to the main menu “File” -> “Settings …”.

In the settings we will find the section “Languages & Frameworks” and select the “PHP” item. Then in the “Include Path” tab we press the plus button and specify the path to the installed CMS.

The directory with the installation will be indexed, this will allow us to use the WordPress source code when navigating through functions and showing dynamic help.

In addition, you can set the WordPress coding style, which for sure has already became familiar to WordPress developers.

In the program settings window, go to “Editor” -> “Code Style” -> “PHP”. Click on the link “Set from …” and select “Predefined Style” -> “WordPress” from the drop-down list.

Click “OK” to save the settings.

Now consider the process of creation of a new project. In the main menu, select “File” -> “New Project …”.

In the opened dialog, go to the “WordPress Plugin” section and specify the directory for the project and the second one – there the WordPress is installed.

Choose the location of the project in the folder with WordPress. Then click “Create” – so we create a project based on the existing source files.

You should wait a few seconds while PhpStorm scans the files. After that the project is opened and we can continue to study the functions of the program.

To use auto-completion, start entering the name of the function and press Ctrl + Space.

PhpStorm

It is enough just to set the cursor to the function name and press Ctrl + Q to get dynamic help on this function.

PhpStorm

IDE also supports WordPress Actions and Filters. When you press Ctrl + Space, you can quickly get a dynamic hint about the existing parameters.

This review can be completed for now. As you can see, all of the programs in this article have their advantages.

Which one to choose? A simple and lightweight text editor, such as Rapid PHP, or a complex IDE, such as PhpStorm?

I chose CodeLobster, that combines the speed of work, functionality and ease of setting up WordPress projects. I’m happy to add it to my set of web development tools.

It’s very interesting to know what your favorite editor is? Do you create sites on WordPress, or use another CMS? I suggest sharing your experience with other readers. I really look forward to your comments.

 

Hits: 30

Python rename special characters in filename

Problem

When upload files to One Drive i have problem with files contain special characters. Below you found Python script witch remove any special characters form filenames. Change

lv_path = "D:\\Netbeans Projects"

and enjoy!

Solution

rename spec characters (Python 3+, W7)
#!/usr/bin/env python
#
# wychwytywanie i zmiana nazwy plików
#
import os
import string
import re
import sys

delchars = ''.join(c for c in map(chr, range(256)) if not c.isalnum())

# paths = (os.path.join(root, filename)
#          for root, _, filenames in os.walk('.')
#          for filename in filenames)

# print(paths)
lv_path = "D:\\Netbeans Projects"

paths = (os.path.join(root, filename)
         for root, _, filenames in os.walk(lv_path)
         for filename in filenames)

print ("Search at " + lv_path)

for path in paths:
    newname = path.replace('#', '')
    newname = newname.replace('%', '')
    newname = newname.replace('*', '')
    newname = newname.replace('<', '')
    newname = newname.replace('>', '')
    newname = newname.replace('*', '')
    newname = newname.replace('?', '')
    newname = newname.replace('$', '')
    #newname = newname.replace('!', '')
    #newname = path.replace('\'', '-')
    newname = newname.replace('"', '')
    newname = newname.replace('\'', '')
    newname = path.replace('Å', 'ś')
    newname = path.replace('Å', 'ń')
    #newname = path.translate(str.maketrans("","",delchars))

    #re.sub('[^\w\-_\. ]', '_', newname)

    if newname != path:
        # print(path)
        print(os.path.dirname(path.encode('utf8').decode(sys.stdout.encoding)) + "\t" + os.path.basename(path.encode('utf8').decode(sys.stdout.encoding)) +
              "\t\t\t -> " + os.path.basename(newname.encode('utf8').decode(sys.stdout.encoding)))
        os.rename(path, newname)

Source(s)

Hits: 1095

How to make webservices Java, Tomcat, Metro and Eclipse

Abstract

It is about impelemtation webserwices on Tomcat in Java (Metro, Ant)

Creating the Service Provider Environment

Prerequisites

These series of articles require the following software to be installed on your system:

  1. JDK,
  2. Apache Ant 1.6.5 or later, Apache Ant is a Java library and command-line tool whose mission is to drive processes described in build files as targets and extension points dependent upon each other. The main known usage of Ant is the build of Java applications. Ant supplies a number of built-in tasks allowing to compile, assemble, test and run Java applications. Ant can also be used effectively to build non Java applications, for instance C or C++ applications. More generally, Ant can be used to pilot any type of process which can be described in terms of targets and tasks… for example deploy webserwices…
    1. http://ant.apache.org/manual/index.html
    2. http://ant.apache.org/bindownload.cgi
  3. web container: either Glassfish v3.x or Apache Tomcat 7.0+
    1. http://localhost:8080 – console
  1. programming webserwices engine
    1. Metro Standalone Budle 2.x (in case of using Apache Tomcat as a web container)
      1. https://metro.java.net/2.3.1/ Metro
      2. https://metro.java.net/getting-started/building-a-simple-metro-application.html
    2. http://trickyinfo.blogspot.com/2012/08/web-services-development-using-eclipse.html – other way to build webserwices in Eclipse
    3. http://www.eclipse.org/webtools/community/education/web/t320/Implementing_a_Simple_Web_Service.pdf
    4. http://www.ibm.com/developerworks/webservices/tutorials/ws-eclipse-javase1/ws-eclipse-javase1.html
    5. https://www.eclipse.org/webtools/ws/ – Eclipse WS tool
      1. Eclipse Web Services Explorer tool http://www.eclipse.org/webtools/initial-contribution/IBM/evalGuides/WebServicesToolsEval.html
    6. https://netbeans.org/kb/docs/websvc/jax-ws.html

How to prepare webserwis from WSDL

http://www.eclipse.org/webtools/community/education/web/t320/Generating_a_client_from_WSDL.pdf

Set Tomcat

Assuming Java (JDK + JRE) is installed in your system, do the following steps:

  1. Install Tomcat7
  2. Copy ‘tools.jar’ from ‘C:\Program Files (x86)\Java\jdk1.6.0_27\lib’ and paste it under ‘C:\Program Files (x86)\Apache Software Foundation\Tomcat 7.0\lib’.
  3. Setup paths in your Environment Variables as shown below:

C:>echo %path%

C:\Program Files (x86)\Java\jdk1.6.0_27\bin;%CATALINA_HOME%\bin;

C:>echo %classpath%

C:\Program Files (x86)\Java\jdk1.6.0_27\lib\tools.jar;
C:\Program Files (x86)\Apache Software Foundation\Tomcat 7.0\lib\servlet-api.jar;

C:>echo %CATALINA_HOME%

C:\Program Files (x86)\Apache Software Foundation\Tomcat 7.0;

C:>echo %JAVA_HOME%

C:\Program Files (x86)\Java\jdk1.6.0_27;

Now you can test whether Tomcat is setup correctly, by typing the following commands in your command prompt:

C:/>javap javax.servlet.ServletException
C:/>javap javax.servlet.http.HttpServletRequest

It should show a bunch of classes

Now start Tomcat service by double clicking on ‘Tomcat7.exe‘ under ‘C:\Program Files (x86)\Apache Software Foundation\Tomcat 7.0\bin’.

Errors

INFO: The APR based Apache Tomcat Native library which allows optimal performance in production environments was not found on the java.library.path:

60down voteaccepted

It means exactly what it says: “The APR based Apache Tomcat Native library which allows optimal performance in production environments was not found on the java.library.path”

The library referred to is bundled into an OS specific dll (tcnative-1.dll) loaded via JNI. It allows tomcat to use OS functionalities not provided in the Java Runtime (such as sendfile, epoll, OpenSSL, system status, etc.). Tomcat will run just fine without it, but for some use cases, it will be faster with the native libraries.

If you really want it, download the tcnative-1.dll (or libtcnative.so for Linux) and put it in the bin folder, and add a system property to the launch configuration of the tomcat server in eclipse.

 -Djava.library.path=c:\dev\tomcat\bin

Set Metro

Again, the top-level directory of the Tomcat installation is passed as an argument to the ant command. To shutdown Tomcat, change directories, invoke ant, and restart Tomcat by executing these commands:

catalina.sh stop
ant -Dtomcat.home=<TOMCAT_INSTALL_DIR> -f <METRO_INSTALL_DIR>/metro-on-tomcat.xml install
catalina.sh start

Other Tutorials

  • http://www.ibm.com/developerworks/learn/web/index.html
  • http://stackoverflow.com/questions/14579661/how-to-set-catalina-home-variable-in-windows-7#17044342

Hits: 0

Java wariacje z ciągiem Fibonacciego

Zadanie

Utwórz rekurencyjna metode obliczajaca ciag Fibonacciego, zdefiniowany dla elementu fibonacci(n) jako sume fibonacci(n-1) + fibonacci(n-2) przy załozeniu, ze fibonacci(1) i fibonacci(2) maja odpowiednio wartosci 1 i 2.

Ciąg Fibonaciego

In mathematics, the Fibonacci numbers are the numbers in the following integer sequence, called the Fibonacci sequence, and characterized by the fact that every number after the first two is the sum of the two preceding ones:[1][2]

1 , 1 , 2 , 3 , 5 , 8 , 13 , 21 , 34 , 55 , 89 , 144 , …

Often, especially in modern usage, the sequence is extended by one more initial term:

0 , 1 , 1 , 2 , 3 , 5 , 8 , 13 , 21 , 34 , 55 , 89 , 144 , …[3]

The Fibonacci spiral: an approximation of the golden spiral created by drawing circular arcs connecting the opposite corners of squares in the Fibonacci tiling;[4] this one uses squares of sizes 1, 1, 2, 3, 5, 8, 13, 21, and 34.

By definition, the first two numbers in the Fibonacci sequence are either 1 and 1, or 0 and 1, depending on the chosen starting point of the sequence, and each subsequent number is the sum of the previous two.

In mathematical terms, the sequence Fn of Fibonacci numbers is defined by the recurrence relation

{\displaystyle F_{n}=F_{n-1}+F_{n-2},}

with seed values[1][2]

  {\displaystyle F_{1}=1,\;F_{2}=1}

or[5]

{\displaystyle F_{0}=0,\;F_{1}=1.}

The Fibonacci sequence is named after Italian mathematician Leonardo of Pisa, known as Fibonacci. His 1202 book Liber Abaci introduced the sequence to Western European mathematics,[6] although the sequence had been described earlier as Virahanka numbers in Indian mathematics.[7][8][9] The sequence described in Liber Abaci began with F1 = 1.

Fibonacci numbers are closely related to Lucas numbers  L_{n} in that they form a complementary pair of Lucas sequencesU_{n}(1,-1)=F_{n} and V_{n}(1,-1)=L_{n}. They are intimately connected with the golden ratio; for example, the closest rational approximations to the ratio are 2/1, 3/2, 5/3, 8/5, … .

Fibonacci numbers appear unexpectedly often in mathematics, so much so that there is an entire journal dedicated to their study, the Fibonacci Quarterly. Applications of Fibonacci numbers include computer algorithms such as the Fibonacci search technique and the Fibonacci heap data structure, and graphs called Fibonacci cubes used for interconnecting parallel and distributed systems. They also appear in biological settings,[10] such as branching in trees, phyllotaxis (the arrangement of leaves on a stem), the fruit sprouts of a pineapple,[11] the flowering of an artichoke, an uncurling fern and the arrangement of a pine cone‘s bracts.[12]

— Source: https://en.wikipedia.org/wiki/Fibonacci_number

Closed form

\(x_{n}=\frac{(1+5^{1/2})^{n} -(1-5^{1/2})^n}{\sqrt{5}2^n}\)

https://math.stackexchange.com/questions/1145342/find-a-formula-for-the-nth-fibonacci-number?newreg=1b687d38e42346fa97a2fdfe3a94c389

Java program and others interesting links

Sources from Bitbucket

bitbucket-icon

 

 

/*
 * Example program to find fibonacci numbers
 */
package Fibonacci;

import static java.lang.Math.sqrt;
import java.util.Scanner;

/**
 *
 * @author KPreiskorn
 */
public class Fibonacci {

  /**
   * @param args the command line arguments
   */
  @SuppressWarnings("resource")
  public static void main(String args[]) {

    // input to print Fibonacci series upto how many numbers
    log("Enter number n Fibonacci to print: ");
    int number = new Scanner(System.in).nextInt();

    log("\nUsing Method-1: Using Recursion. Provided Number: " + number);
    // printing Fibonacci series upto number
    for (int i = 1; i <= number; i++) {
      System.out.printf("%3d %6d\n", i, fibonacciRecusion(i));
    }

    log("\nMethod-2: Fibonacci number at location " + number + " is ==> " + (fibonacciLoop(number) + ""));

    System.out.printf("\nMethod #3 (fibonacciClosedForm): Fibonacci number at location %d is %.0f\n\n", number, fibonacciClosedForm(number));

  }

  // Method-1: Java program for Fibonacci number using recursion.
  public static int fibonacciRecusion(int number) {
    if (number == 1 || number == 2) {
      return 1;
    }

    return fibonacciRecusion(number - 1) + fibonacciRecusion(number - 2); // tail recursion
  }

  // Method-2: Java program for Fibonacci number using Loop.
  public static int fibonacciLoop(int number) {
    if (number == 1 || number == 2) {
      return 1;
    }
    int fibo1 = 1, fibo2 = 1, fibonacci = 1;
    for (int i = 3; i <= number; i++) {
      fibonacci = fibo1 + fibo2; // Fibonacci number is sum of previous two Fibonacci number
      fibo1 = fibo2;
      fibo2 = fibonacci;

    }
    return fibonacci; // Fibonacci number
  }

  // metod 3: Closed-form expression
  public static double fibonacciClosedForm(int n) {
    double q = (1 + sqrt(5)) / 2;

    return Math.floor(Math.pow(q, n) / sqrt(5) + 1 / 2); // Fibonacci number
  }

  private static void log(String number) {
    System.out.println(number);

  }

}

Hits: 201

What are the best programming fonts?

The choice the font in Firefox or Sulbimetext it is always hard decision….

As much as choice of a font is subjective there are important criteria to consider when choosing a programming font. The characters should be clear, easy to read, in cases of clashing ones such as 1, l, i or O, o, 0 easily distinguishable, differences between different kinds of brackets, quotes and parentheses should be clear, punctuation should be emphasized and they shouldn’t break up words or sentences due to uneven character widths. There are two ways fonts are drawn – as bitmaps or as vectors. Vector fonts allow more efficient scaling, but for screens with resolution below 720p it might be worth considering bitmap fonts as they are generally more legible at smaller sizes on low-resolution screens.

Source: What are the best programming fonts? – Slant

Hits: 12

SQL corner: 7 kind of SQL Joins. Including : INNER JOIN, LEFT JOIN, RIGHT JOIN, FULL JOIN

Infographic of the 7 kind of SQL Joins. Including : INNER JOIN, LEFT JOIN, RIGHT JOIN, FULL JOIN, with or without the intersect. Very useful for web developer. Source : http://sql.sh #SQL #JOIN

7-sql-join

Source: Pinterest http://sql.sh/2401-sql-join-infographie

Other sources about JOIN

Hits: 109

Java – Suma kolejnych liczb całkowitych od 5 do 1000

Zadanie 1. Suma kolejnych liczb całkowitych od 5 do 1000

Sumowanie – operacja dodawania ciągu liczb, której wynikiem jest suma. Jeśli liczby są dodawane kolejno od lewej do prawej to pośrednie wyniki nazywa się sumami częściowymi lub cząstkowymi. Sumowane liczby (zwane składnikami) mogą być całkowite, rzeczywiste lub zespolone. Oprócz liczb sumowaniu mogą podlegać również inne wielkości: wektory, macierze, wielomiany, lub ogólnie, elementy grupy addytywnej (a nawet monoid). Dla ciągów o skończonej liczbie takich elementów sumowanie zawsze zwraca dobrze określoną sumę.

Sumowanie ciągów nieskończonych nie zawsze jest możliwe, a kiedy wartość nieskończonego sumowania może być podana, to obejmuje ona więcej niż tylko zwykłą operację dodawania, mianowicie pojęcie granicy. Sumowanie nieskończonych ciągów tworzy konstrukcję zwaną szeregiem. Innym pojęciem obejmującym granice skończonych sum jest całka. Pojęcie sumowania nabiera szczególnego znaczenia w powiązaniu z ekstrapolacją w kontekście szeregów rozbieżnych.

Sumowanie ciągu [1, 2, 4, 2] to wyrażenie, którego wartością jest suma wszystkich elementów ciągu. W podanym przykładzie to 1 + 2 + 4 + 2 = 9. Ponieważ dodawanie jest łączne, wynik nie zależy od kolejności wykonywanych działań, na przykład (1 + 2) + (4 + 2) lub 1 + ((2 + 4) + 2) daje w wyniku 9, stąd zazwyczaj pomijane są nawiasy w przypadku wielokrotnego dodawania. Dodawanie jest ponadto przemienne, więc permutacja wyrazów skończonego ciągu również nie zmienia jego sumy (w przypadku ciągów nieskończonych ta właściwość nie zawsze jest prawdziwa; zobacz twierdzenie Riemanna o szeregach warunkowo zbieżnych i kryteria zbieżności szeregów).

Nie ma specjalnego wyróżnionego zapisu sumowania jawnie podanych ciągów gdyż odpowiadające mu wyrażenie wielokrotnego dodawania jest w tym przypadku wystarczające. Drobne trudności pojawiają się gdy ciąg jest jednoelementowy: sumowanie ciągu jednoelementowego nie zawiera znaku dodawania (jest więc nieodróżnialne od wyniku) a sumowanie ciągu pustego nie da się nawet zapisać (lecz można podać w jego sumę „0”). Jednak gdy wyrazy ciągu układają się w jakiś wzór to użyteczny a nawet niezbędny staje się operator sumowania. Na przykład jeśli rozpatrywać sumowanie liczb całkowitych od 1 do 100 można wykorzystać wielokropek w wyrażeniu dodawania aby oznaczyć brakujące wyrazy: 1 + 2 + 3 + … + 99 + 100. W tym przykładzie wzór jest łatwy do odgadnięcia, lecz dla bardziej skomplikowanych przypadków konieczne jest bardziej precyzyjne określanie kolejnych wyrazów, które można osiągnąć dzięki operatorowi „Σ”. Korzystając z tego operatora ten sam przykład można zapisać jako:

  \sum _{{i=1}}^{{100}}i

Wartością tego sumowania jest 5050. Można ją znaleźć bez wykonywania 99 dodawań, ponieważ można wykazać (metodą indukcji matematycznej), że

  \sum _{{i=1}}^{n}i={\frac {n(n+1)}2}

dla wszystkich liczb naturalnych n.

— źródło Wiki https://pl.wikipedia.org/wiki/Sumowanie

Zadanie 2. Utwórz tablice 5-cio elementową i wygeneruj do niej losowe wartości z przedziału <-10, 10>

Zadanie 3. Oblicza ile jest dodatnich elementów w tablicy myIntArray.

np. odpowiedź programu: W tablicy myIntArray[5] jest/są  3 dodatnie elementy

Source from Bitbucket https://bitbucket.org/karol-preiskorn/java-examples/overview

Zapis wyników do pliku

Dodanie logowania log4j (w przygotowaniu)

uses log4j in code
static Logger logger = LoggerFactory.getLogger("SumN");	  

logger.info("start");

  1. https://alvinalexander.com/blog/post/java/sample-how-format-log4j-logging-logfile-output
  2. https://alvinalexander.com/blog/post/java/how-print-exception-stack-trace-using-log4j-commons
  3. https://logging.apache.org/log4j/1.2/manual.html

Suma kwadratów n pierwszych liczb naturalnych (w przygotowaniu)

\(1^{2}+2^{2}+3^{2}+4^{2}+\dots+n^{2}=\sum_{k=1}^{n}k^{2}=\frac{n(n+1)(2n+1)}{6}=s_{2}\)

https://pl.wikisource.org/wiki/Sumy

Hits: 628

SublimeText 3 tips and customization

I think that is one of best text editor for Linux and W$. Bellow I add some tips and usefully configuration.

Regexp conversion to Wiki links

Conversion to Wiki links add [ before and ] after text.

Find what: (http.{2,})
Relpace to: [\1]

Polish letters in Sublimetext 3

Polskie znaki diakrytyczne w Sublime Text 3 – dodanie wpisów do Key Bindings – User (na platformie Windows jest to plik Default (Windows).sublime-keymap):

[
{"keys": ["control+alt+a"], "command": "insert", "args": {"characters": "ą"}},
{"keys": ["control+alt+c"], "command": "insert", "args": {"characters": "ć"}},
{"keys": ["control+alt+e"], "command": "insert", "args": {"characters": "ę"}},
{"keys": ["control+alt+l"], "command": "insert", "args": {"characters": "ł"}},
{"keys": ["control+alt+n"], "command": "insert", "args": {"characters": "ń"}},
{"keys": ["control+alt+o"], "command": "insert", "args": {"characters": "ó"}},
{"keys": ["control+alt+s"], "command": "insert", "args": {"characters": "ś"}},
{"keys": ["control+alt+x"], "command": "insert", "args": {"characters": "ź"}},
{"keys": ["control+alt+z"], "command": "insert", "args": {"characters": "ż"}},
{"keys": ["shift+control+alt+a"], "command": "insert", "args": {"characters": "Ą"}},
{"keys": ["shift+control+alt+c"], "command": "insert", "args": {"characters": "Ć"}},
{"keys": ["shift+control+alt+e"], "command": "insert", "args": {"characters": "Ę"}},
{"keys": ["shift+control+alt+l"], "command": "insert", "args": {"characters": "Ł"}},
{"keys": ["shift+control+alt+n"], "command": "insert", "args": {"characters": "Ń"}},
{"keys": ["shift+control+alt+o"], "command": "insert", "args": {"characters": "Ó"}},
{"keys": ["shift+control+alt+s"], "command": "insert", "args": {"characters": "Ś"}},
{"keys": ["shift+control+alt+x"], "command": "insert", "args": {"characters": "Ź"}},
{"keys": ["shift+control+alt+z"], "command": "insert", "args": {"characters": "Ż"}}
]

Adding comma to each line using sublime text

To add comma to any line

  1. Select the lines you want to modify
  2. CTRL + SHIFT + L
  3. RIGHT_ARROW
  4. COMMA

Using ctrl + shift + L is how you can modify all selected lines. Very handy 🙂 Make batch edits with Multiple Selections.

Column Selection can be used to select a rectangular area of a file. Column selection doesn’t operate via a separate mode, instead it makes use of multiple selections.

You can use additive selections to select multiple blocks of text, or subtractive selections to remove a block.

‘Find What’: $ // matching all ends of your lines
‘Replace With’: , // replaces all line ends with a coma

MXU20623GAD
MXU20899GAA
MXU20975GAA
MXU24246GAD
MXU29901GAA
MXU30079GAA
MXU30090GAA
MXU34015GAA
Sublimetext array

Solve this problem

Source: Best of Sublime Text 3: Features, Plugins, and Settings | Scotch

Emmet is usefull

Emmet is an absolute time saver. You can build HTML on the fly easily and quickly.

To Use: ctrl + alt + enter and start typing your Emmet styled HTML

  • ctrl + d: Select the current word and the next same word
  • ctrl + click: Every place you click will create a cursor to edit
  • ctrl + shift + f AND alt + enter: Find a word in your files and then select them all
Emmet in sublimetext

Check out our Emmet Interactive Guide to learn more and try out Emmet for yourself.

DocBlockr

A really great way to easily create doc blocks for many languages including JavaScript, PHP, and CoffeeScript. Just type in /** above your function and press tab. Watch the magic as DocBlockr takes the function name and variables and creates your doc block.

sublime-docblockr-example-start
sublime-docblockr-example-finish

BracketHighlighter

This plugin provides bracket highlighting for all sorts of brackets.

brackethighlighter

Sublime Text 3 is an amazing piece of software. To start, it is a clean, functional, and fast code editor. Not only does it have incredible built in features (multi-edit and vim mode), but it has support for plugins, snippets, and many other things.

Source: Best of Sublime Text 3: Features, Plugins, and Settings | Scotch

Reference links

Hits: 72

Unique session ID

The UNIQUE_SESSION_ID function returns a character string unique to the session among all sessions currently connected to the database. The return string can be up to 24 bytes in length. Multiple calls to the function from the same session will always return the same string. The program header follows:

FUNCTION DBMS_SESSION.UNIQUE_SESSION_ID
RETURN VARCHAR2;

Notes

UNIQUE_SESSION_ID is functionally identical to the DBMS_PIPE.UNIQUE_SESSION_NAME function; however, their return values are not identical. Be very careful not to write code that assumes that these two functions are equivalent.

The UNIQUE_SESSION_ID function does not raise any exceptions.

Example

To display the value of the unique id for the current session, specify the following:

DECLARE
   my_unique_id   VARCHAR2(30);
BEGIN
   my_unique_id := DBMS_SESSION.UNIQUE_SESSION_ID;
   DBMS_OUTPUT.PUT_LINE('UNIQUE ID: '||my_unique_id);
END;

An example of output from executing the preceding PL/SQL block follows:

UNIQUE ID: F000E4020000

— Source https://www.toadworld.com/platforms/oracle/w/wiki/3246.dbms-session-unique-session-id

When you have problem receive information about session in Oracle PLSQL database for example purposes journalling. Look bellow on SQLs witch rewrite two or more rows:

SELECT *
FROM v$session s
WHERE username IS NOT NULL 
AND s.AUDSID = SYS_CONTEXT ('userenv', 'sessionid')
ORDER BY username, osuser;

You need add two condition to receive one row.

WHERE username IS NOT NULL 
AND s.AUDSID = SYS_CONTEXT ('userenv', 'sessionid') 
AND S.SID = SYS_CONTEXT ('userenv', 'sid')

Final query return unique session row:

SELECT *
FROM v$session s
WHERE username IS NOT NULL AND s.AUDSID = SYS_CONTEXT ('userenv', 'sessionid') AND S.SID = SYS_CONTEXT ('userenv', 'sid')
ORDER BY username, osuser;

Hits: 106

5 Best Eclipse Plugins: #1 (Eclox with Doxygen, Graphviz and Mscgen) | MCU on Eclipse

5 Best Eclipse Plugins: #1 (Eclox with Doxygen, Graphviz and Mscgen)Posted on June 25, 2012 by Erich Styger 24 VotesThe #1 award in my list goes to Eclox+Doxygen+Graphviz+Mscgen. Yes, it is a single Eclipse plugin (Eclox) for Doxygen, and with two other powerful tools. It solves a typical engineering problem: “How to document my project? And how to keep it up-to-date?”. Like many other engineers, I do not like to write documentation. Because it is painful. I want to write code and program. Writing documentation for it should be fun too. And it should solve the problem that the documentation does not match what has been implemented. I’m a big fan of the ‘single source’ concept: information has to be in a single place, and not copied and distributed among different places. And here my #1 helps me doing this.In a traditional way the following flow is used: Create a design, specify and document the API Implement the software Write the user documentation Ship it Maintain and ship and again, and again, and

Source: 5 Best Eclipse Plugins: #1 (Eclox with Doxygen, Graphviz and Mscgen) | MCU on Eclipse

Usefully for write and maintenance plugin for Eclipse…

  1. Doxygen: http://www.stack.nl/~dimitri/doxygen/ or www.doxygen.org
  2. Graphviz: http://www.graphviz.org
  3. Mscgen: http://www.mcternan.me.uk/mscgen/

after this article i use all of them.

Hits: 70

Arrays of Pointers

9.4 Arrays of Pointers

As seen in the last example, sorting an array of strings requires swapping the strings which can require copying a lot of data. For efficiency, it is better to avoid actual swapping of data whenever a data item is large, such as a string or an entire data base record. In addition, arrays may be needed in more than one order; for example, we may need an exam scores array sorted by Id number and by weighted scores; or, we may need strings in both an unsorted form and a sorted form.
In either of these cases, we must either keep two copies of the data, each sorted differently, or find a more efficient way to store the data structure. The solution is to use pointers to elements of the array and swap pointers. Consider some examples:

int data1, data2, *ptr1, *ptr2, *save;
data1 = 100; 
data2 = 200; 
ptr1 = *data1; 
ptr2 = *data2;

We could swap the values of the data and store the swapped values in data1 and data2 or we could simply swap the values of the pointers:

save = ptr1;
ptr1 = ptr2;
ptr2 = save;

We have not changed the values in

data1

and data2 but ptr1 now accesses data2 and ptr2 access data1. We have swapped the pointer values so they point to objects in a different order. We can apply the same idea to strings:

char name1[] = "John";
char name2[] = "Dave";
char *p1, *p2, *save;
p1 = name1; 
p2 = name2;

Pointers p1 and p2 point to strings name1 and name2. We can now swap the pointer values so p1 and p2 point to name2 and name1, respectively.

In general, an array of pointers can be used to point to an array of data items with each element of the pointer array pointing to an element of the data array. Data items can be accessed either directly in the data array, or indirectly by dereferencing the elements of the pointer array. The advantage of a pointer array is that the pointers can be reordered in any manner without moving the data items. For example, the pointer array can be reordered so that the successive elements of the pointer array point to data items in sorted order without moving the data items. Reordering pointers is relatively fast compared to reordering large data items such as data records or strings. This approach saves a lot of time, with the additional advantage that the data items remain available in the original order. Let us see how we might implement such a scheme.

STRPTRS: Given an array of strings, use pointers to order the strings in sorted form, leaving the array unchanged.

We will use an array of character pointers to point to the strings declared as follows:

char * nameptr[MAX];

The array, nameptr[], is an array of size MAX, and each element of the array is a character pointer. It is then possible to assign character pointer values to the elements of the array; for example:

nameptr[i] = "John Smith";

The string "John Smith" is placed somewhere in memory by the compiler and the pointer to the string constant is then assigned to nameptr[i]. It is also possible to assign the value of any string pointer to nameptr[i]; for example, if s is a string, then it is possible to assign the pointer value s to nameptr[i]:

nameptr[i] = s;

In particular, we can read strings into a two dimensional array, names[][], and assign each string pointer, names[i] to the element of the pointer array, nameptr[]:

for (i = 0; i < MAX && gets(names[i]); i++)
          nameptr[i] = names[i];

The strings can then be accessed either by names[i] or by nameptr[i] as seen in Figure 9.4. We can then reorder the pointers in nameptr[] so that they successively point to the strings in sorted order as seen in Figure 9.4. We can then print the strings in the original order by accessing them through names[i]and print the strings in sorted order by accessing them through nameptr[i]. Here is the algorithm

/**
 * Zadania
 * -------
 * z1: Napisz program, który pokazuje, które atrybuty procesu macierzystego są dziedziczone przez proces potomny  uruchomiony za pomocą funkcji fork(), które zaś otrzymują nową wartość.
 * z2: Napisz program, który pokazuje, które atrybuty procesu są zachowane przez proces po wykonaniu funkcji exec().
 * z3: Napisz program, który wyświetla identyfikator procesu (PID) i nazwę związanego z nim polecenia dla wszystkich procesów uruchomionych przez użytkownika podanego w wierszu wywołania programu. Wskazówka: informacje te można uzyskać przeglądając katalog /proc z plików (interesują nas katalogi, których właścicielem jest dany  użytkownik) i pliki /proc/PID/status
 *
 * Każdy proces charakteryzuje się pewnymi atrybutami. Należą do nich:
 * Identyfikator procesu PID
 * Identyfikator procesu macierzystego PPID
 * Rzeczywisty identyfikator właściciela procesu
 * Rzeczywisty identyfikator grupy procesu
 * Efektywny identyfikator właściciela procesu
 * Efektywny identyfikator grupy procesu
 * Katalog bieżący i katalog główny
 * Maska tworzenia pliku
 * Identyfikator sesji
 * Terminal sterujący
 * Deskryptory otwartych plików
 * Ustalenia dotyczące obsługi sygnałów
 * Ustawienia zmiennych środowiskowych
 * Ograniczenia zasobów
 *
 *
 * Potomek dziedziczy z procesu potomnego wiele własności:
 rzeczywisty identyfikator użytkownika, rzeczywisty identyfikator grupy, obowiązujący identyfikator użytkownika, obowiązujący identyfikator grupy,
 identyfikatory dodatkowych grup,
 identyfikator sesji,
 terminal sterujący,
 sygnalizator ustanowienia identyfikatora użytkownika oraz sygnalizator ustanowienia identyfikatora grupy,
 deskryptory otwartych plików (są kopiowane)
 bieżący katalog roboczy,
 katalog główny,
 maskę tworzenia plików,
 maskę sygnałów oraz dyspozycje obsługi sygnałów,
 sygnalizator zamykania przy wywołaniu funkcji exec (close-on-exec) dla wszystkich otwartych deskryptorów plików,
 środowisko,
 przyłączone segmenty pamięci wspólnej,
 ograniczenia zasobów systemowych.
 Są jednak pewne różnice między procesem macierzystym a potomnym:
 wartość powrotu z funkcji fork,
 różne identyfikatory procesów,
 inne identyfikatory procesów macierzystych - w procesie potomnym jest to identyfikator procesu macierzystego; w procesie macierzystym identyfikator procesu macierzystego nie zmienia się,
 w procesie potomnym wartości tms_utime, tms_cutime i tms_ustime są równe 0,
 potomek nie dziedziczy rygli plików, ustalonych w procesie macierzystym,
 w procesie potomnym są zerowane wszystkie zaległe alarmy,
 w procesie potomnym jest zerowany zbiór zaległych sygnałów.
 */

#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 

extern char** environ;
char *prt_parent;

int glob = 1;           // zewnętrzna zmienna

/* Prints the environment, one environment variable to a line, of the process given by PID. */
char *print_process_environment(pid_t pid) {
    int fd;
    char filename[24];
    char environment[8192];
    size_t length;
    char* next_var;
    /* Generate the name of the environ file for the process. */
    snprintf(filename, sizeof(filename), "/proc/%d/environ", (int) pid);
    /* Read the contents of the file. */
    fd = open(filename, O_RDONLY);
    length = sizeof(environ);
    printf("Size of environ: %d\n", length);
    close(fd);
    /* read does not NUL-terminate the buffer, so do it here. */
    environment[length] = '\0';
    /* Loop over variables. Variables are separated by NULs. */
    next_var = environment;
    while (next_var < environment + length) { /* Print the variable. Each is NUL-terminated, so just treat it like an ordinary string. */ printf(">> %s\n", next_var);
        /* Advance to the next variable. Since each variable is
         NUL-terminated, strlen counts the length of the next variable,
         not the entire variable list. */
        next_var += strlen(next_var) + 1;
    }
    return (environment);
}


int main(int argc, char **argv) {
    int var = 100;              // zmienna automatyczna na stows
    char **env = environ;       // środowisko parent
    // zapamiętanie environ w tablicy

    printf("PROGRAM Z1\n\n");
    printf("Zmienne srodowiskowe parent: ----------------------------\n");
    while (*env) {
        printf("%s\n", *env++);
    }

    printf("---------------------------------------------------------\n");
    
    for (int i = 0; *env != NULL && gets(env[i]); i++)
              nameptr[i] = env[i];
    
    pid_t pid = fork();

    if (pid == 0) {
        // child process
        glob++;
        var++;
        printf("child process: pid %d, ppid %d, getuid %d, geteuid %d, getgid %d, glob = %d, var = %d\n", getpid(), getppid(), getuid(), geteuid(), getgid(),
                glob, var);

        /**
         * wy swietlenie zmiennych środowiskowych różnych od parent
         */
        printf("Zmienne srodowiskowe child różne od parent:\n");
        char environment_1[8192];
        char * prt_env = &environment_1;
        prt_env = print_process_environment(pid);
        char **env_child = environ;
        printf("Size of *char: %d\n", sizeof(environ));

        while (*env_child) {
            printf("compare - %s %d\n", *env_child, strcmp(*env_child++, *env++));
            //printf("%s -----\n", *env2++);
            //if (strcmp(*env2, ++*env) == 0) {
            //
            //} else {
            //printf("%s jest takie samo\n", *env2);
            //}
            //*env_child++;
            //*env++;
        }
        printf("-------------------- x --------------------\n");

    } else if (pid > 0) {
        // parent process
        printf("parent process: pid %d, ppid %d, getuid %d, geteuid %d, getgid %d, glob = %d, var = %d\n", getpid(), getppid(), getuid(), geteuid(), getgid(),
                glob, var);
    } else {
        // fork failed
        printf("fork() failed!\n");
        return (1);
    }

    printf("-- end of program pid %d\n", getpid());

    return (0);
}

Hits: 0

Programowanie współbieżne C na Linux – przykłady

Przykładowe zadania z programowania współbieżnego na systemie Linux

  1. Napisz program, który pokazuje, które atrybuty procesu macierzystego są dziedziczone przez proces potomny uruchomiony za pomocą funkcji fork(), które zaś otrzymują nową wartość.
  2. Napisz program, który pokazuje, które atrybuty procesu są zachowane przez proces po wykonaniu funkcji exec().
  3. Napisz program, który wyświetla identyfikator procesu (PID) i nazwę związanego z nim polecenia dla wszystkich procesów uruchomionych przez użytkownika podanego w wierszu wywołania programu.
/**
 * Uzupełnij program shell z o „ręczną” obsługę potoków.
 * ----------------------------------------------------
 * Napisz program, który zbiera komunikaty od wielu programów i wyświetla je na ekranie. Do komunikacji użyj potoku nazwanego.
 *
 * Wskazówka: Utwórz program rdfifo, którego zadaniem jest utworzenie kolejki FIFO i czytanie z niej danych.
 * Utwórz program wrfifo, który otwiera kolejkę FIFO tylko do zapisu i wpisuje do niej dane (np. swoj pid i czas).
 *
 * Q: W jaki sposób przekażesz wspólną nazwę kolejki FIFO do tych programów?
 * A: przez zmienną statyczą
 *
 * Q: W jaki sposób zapewnić działanie programu zbierającego komunikaty również wtedy, kiedy nie ma programu piszącego do łącza?
 * A: przez proces pętli nieskończonej ze sleep
 *
 * Q: Jak zapewnić to, że komunikaty pochodzące od różnych programów wyświetlane są w całości, tzn. nie są rozdzielane  komunikatami od innych programów?
 * A: flush? (do sprawdzenia).
 *
 */

Wskazówka: informacje te można uzyskać przeglądając katalog /proc z plików (interesują nas katalogi, których właścicielem jest dany użytkownik) i pliki /proc/PID/status

Sources

C programing tutorial

 

Example solution 1 (draft)


Zrzut z działania

Example solution 2 (draft)

Using fork() in C/C++ – a minimum working example

In a C or C++ program, fork() can be used to create a new process, known as a child process. This child is initially a copy of the the parent, but can be used to run a different branch of the program or even execute a completely different program. After forking, child and parent processes run in parallel. Any variables local to the parent process will have been copied for the child process, so updating a variable in one process will not affect the other.

Consider the following example program:

This program declares a counter variable, set to zero, before fork()ing. After the fork call, we have two processes running in parallel, both incrementing their own version of counter. Each process will run to completion and exit. Because the processes run in parallel, we have no way of knowing which will finish first. Running this program will print something similar to what is shown below, though results may vary from one run to the next.

--beginning of program
parent process: counter=1
parent process: counter=2
parent process: counter=3
child process: counter=1
parent process: counter=4
child process: counter=2
parent process: counter=5
child process: counter=3
--end of program--
child process: counter=4
child process: counter=5
--end of program--

Hits: 118

Narzędzia to projektowania baz danych

GNU-GPL

Multiple versions/licenses (each has a “free” and a “not-free” version)

  • DBVisualizer
  • Toad http://www.toadsoft.com/

Not-free

  • Microsoft Visio – (If you already have it, it does work quite well)
  • DataStudio – 30 day trial http://www.aquafold.com
  • DBWrench – 30 day trial http://www.dbwrench.com/

ER diagram tool

  • http://druid.sf.net/
  • http://schemaspy.sourceforge.net/
  • http://uml.sourceforge.net/index.php

Hits: 11

Automat komórkowy w C | Cellular automaton (CA) in C

Cellular automata and Moore neighborhood

Cellular automaton (CA) is by definition a periodic grid of cells, where in each cell sits a finite automaton, and a set of (identical) rules for every such automaton describing to which state it switches on a next moment of discrete time ti+1, depending of its own state and states of all its neighbors on a current moment of time ti. For now, we will be interested in 2d, rectangular CA, and a neighborhood which includes 8 neighbors of the cell. This is what is called the Moore neighborhood, because it was invented by Edward Moore.

Rules Brain

http://zvold.blogspot.com/2010/01/conways-life-and-brians-brain-cellular.html

  • Each cell has three possible states: passive, active, and semi-active.
  • If a cell is active, it goes to semi-active state on the next step
  • If a cell is semi-active, it becomes passive on the next step
  • If a cell is passive, it becomes active if and only if it has exactly 2 active neighbors

Materials

Source

/**
* Brian's Brain
*
* Rules:
* -------
* Each cell has three possible states: passive, active, and semi-active.
* If a cell is active, it goes to semi-active state on the next step
* If a cell is semi-active, it becomes passive on the next step
* If a cell is passive, it becomes active if and only if it has exactly 2 active neighbors
*
**/
#include 
#include 

#include 
#include 

 

Hits: 34

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

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

Up ↑