'개인공부'에 해당되는 글 5건

  1. 2016.03.12 Consensus Algorism
  2. 2016.01.26 Python Introduction
  3. 2016.01.14 JavaScript 이용하여 Map 쓰기 And Ajax 전송
  4. 2016.01.12 Tomcat 주소 변경
  5. 2015.08.05 햄릿 증후군??

개인적으로 Raft 알고리즘에 대해 알아볼 일이 생겼다

Raft알고리즘은 Paxos 알고리즘의 기존의 잘못된 점을 고쳐 발전시킨 알고리즘이라고 한다. 그렇다면 과연 Paxos Raft 알고리즘이 속해 있는 합의 알고리즘이 무엇인지 알아보겠다.

합의 알고리즘은 분산 시스템의 결함 허용 방식의 하나이다.
이는 결함이 있는 분산 시스템이 합의된 하나의 제안을 공유할 있도록 설계되어 있다.

 

분산 컴퓨팅 시스템과 다수 Agent 시스템의 기본적인 문제점은 잘못된 프로세스가 존재하에 시스템의 안정성을 달성하는 것이다. 이것은 자주 프로세스들을 몇몇 데이터(컴퓨터 계산중 필요한) 수락하기 위해 필요하다.

예를 들어 합의 어플리케이션은 데이터베이스에 트랜잭션 커밋 여부, 인증된 리더(State machine replication Atomic broadcasts) 수락하기 위해 포함한다..


현실에서 어플리케이션들은 include clock synchronization, PageRank, opinion formation, power smart grids, state estimation, control of UAVs, load balancing등이 포함되어진다.

 

 

합의 문제는 다수의 프로세스를 하나의 데이터 값으로 묶는 약속이 필요하다.

몇몇 프로세스들은 실패 또는 믿을수 없는 다른 방향으로 수도 있고 그래서 합의 프로토콜들은 반드시 fault tolerant or resilient(탄력적이어야하고, 실패 결함이 있어야 한다).

프로세스들은 반드시 어디가에서 4개의 그들의 후보값을 넣고 다른 하나와 의사소통하고 하나의 합의 값으로 수락한다.

합의 문제는 멀티 클러스터 시스템을 제어하기위한 기본적인 문제이다. 

어쨌든 하나 또는 다수 실패 프로세스들은 만약 합의가 도달하지 못하거나 잘못 도달하도록  비뚤어지게 한다.

 

약속들은 합의문제를 해결이 되도록 그려진다. 제한된 숫자의 Faulty 프로세스들과 거래하도록 디자인 되어진다.

이러한 약속들은 반드시 개의 요구사항이 만족 되어야 한다.

예를 들어 하찮은 프로토콜은 모든 프로세스의 출력 바이너리 값을 가지게 될것이다.

1.    이것은 유용하지 않고 요구사항이 출력은 이와 같이 수정되어지면 어떠한 입력과도 반드시 의존하게된다.

이것은 출력값의 합의 프로토콜은 반드시 몇몇 프로세스의 입력값이다. 다른 요구사항은 프로세스는 결정 할지도 모른다.

 오류  발생하지 않는 경우 올바른 프로세스실행 불린다. 실패를 중단합의 프로토콜  내성  다음과 같은 속성을 만족해야한다
종료
모든 올바른 프로세스가 어떤 값을 결정한다.
효력
모든 프로세스가동일한  v  제안 하는 경우 , 모든 과정은 정확한 V  결정한다.
청렴
모든 올바른 과정은 대부분 하나의 값으로 결정 하고, 어떤  v  결정하면 , 다음에 v 일부 프로세스에 의해 제안 되어 있어야합니다.
협정
모든 정확한 프로세스  동일한 값에 동의해야한다 .
 

이러한 프로세스의 동의하는 과정을 합의라 한다.

Posted by MIDDLE
,

https://www.youtube.com/watch?v=tKTZoB2Vjuk


Google Python Class Day 1 Part 1 동영상 강의


파이썬 이란

Python Introduction

Prelude

Welcome to Google's Python online tutorial. It is based on the introductory Python course offered internally. Originally created during the Python 2.4 days, we've tried to keep the content universal and exercises relevant, even for newer releases. As mentioned on the setup page, this material covers Python 2. While we recommend "avoiding" Python 3 for now, recognize that it is the future, as all new features are only going there. The good news is that developers learning either version can pick up the other without too much difficulty. If you want to know more about choosing Python 2 vs. 3, check out this post.

We strongly recommend you follow along with the companion videos throughout the course, starting with the first one. If you're seeking a companion MOOC course, try the ones from Udacity and Coursera (intro to programming [beginners] or intro to Python), and if you're looking for a companion book to your learning, regardless of your Python skill level, check out these reading lists. Finally, if you're seeking self-paced online learning without watching videos, try the ones listed towards the end of this post — each feature learning content as well as a Python interactive interpreter you can practice with. What's this "interpreter" we mention? You'll find out in the next section!

Language Introduction

Python is a dynamic, interpreted (bytecode-compiled) language. There are no type declarations of variables, parameters, functions, or methods in source code. This makes the code short and flexible, and you lose the compile-time type checking of the source code. Python tracks the types of all values at runtime and flags code that does not make sense as it runs.

An excellent way to see how Python code works is to run the Python interpreter and type code right into it. If you ever have a question like, "What happens if I add an int to a list?" Just typing it into the Python interpreter is a fast and likely the best way to see what happens. (See below to see what really happens!)

$ python        ## Run the Python interpreter
Python 2.7.9 (default, Dec 30 2014, 03:41:42)
[GCC 4.1.2 20080704 (Red Hat 4.1.2-55)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> a = 6       ## set a variable in this interpreter session
>>> a           ## entering an expression prints its value
6
>>> a + 2
8
>>> a = 'hi'    ## 'a' can hold a string just as well
>>> a
'hi'
>>> len(a)      ## call the len() function on a string
2
>>> a + len(a)  ## try something that doesn't work
Traceback (most recent call last):
 
File "", line 1, in
TypeError: cannot concatenate 'str' and 'int' objects
>>> a + str(len(a))  ## probably what you really wanted
'hi2'
>>> foo         ## try something else that doesn't work
Traceback (most recent call last):
 
File "", line 1, in
NameError: name 'foo' is not defined
>>> ^D          ## type CTRL-d to exit (CTRL-z in Windows/DOS terminal)

As you can see above, it's easy to experiment with variables and operators. Also, the interpreter throws, or "raises" in Python parlance, a runtime error if the code tries to read a variable that has not been assigned a value. Like C++ and Java, Python is case sensitive so "a" and "A" are different variables. The end of a line marks the end of a statement, so unlike C++ and Java, Python does not require a semicolon at the end of each statement. Comments begin with a '#' and extend to the end of the line.

Python source code

Python source files use the ".py" extension and are called "modules." With a Python modulehello.py, the easiest way to run it is with the shell command "python hello.py Alice" which calls the Python interpreter to execute the code in hello.py, passing it the command line argument "Alice". See the official docs page on all the different options you have when running Python from the command-line.

Here's a very simple hello.py program (notice that blocks of code are delimited strictly using indentation rather than curly braces — more on this later!):

#!/usr/bin/env python

# import modules used here -- sys is a very standard one
import sys

# Gather our code in a main() function
def main():
   
print 'Hello there', sys.argv[1]
   
# Command line args are in sys.argv[1], sys.argv[2] ...
   
# sys.argv[0] is the script name itself and can be ignored

# Standard boilerplate to call the main() function to begin
# the program.
if __name__ == '__main__':
    main
()

Running this program from the command line looks like:

$ python hello.py Guido
Hello there Guido
$ ./hello.py Alice  ## without needing 'python' first (Unix)
Hello there Alice

Imports, Command-line arguments, and len()

The outermost statements in a Python file, or "module", do its one-time setup — those statements run from top to bottom the first time the module is imported somewhere, setting up its variables and functions. A Python module can be run directly — as above "python hello.py Bob" — or it can be imported and used by some other module. When a Python file is run directly, the special variable "__name__" is set to "__main__". Therefore, it's common to have the boilerplate if __name__ ==... shown above to call a main() function when the module is run directly, but not when the module is imported by some other module.

In a standard Python program, the list sys.argv contains the command-line arguments in the standard way with sys.argv[0] being the program itself, sys.argv[1] the first argument, and so on. If you know about argc, or the number of arguments, you can simply request this value from Python with len(sys.argv), just like we did in the interactive interpreter code above when requesting the length of a string. In general, len() can tell you how long a string is, the number of elements in lists and tuples (another array-like data structure), and the number of key-value pairs in a dictionary.

User-defined Functions

Functions in Python are defined like this:

# Defines a "repeat" function that takes 2 arguments.
def repeat(s, exclaim):
   
"""
    Returns the string 's' repeated 3 times.
    If exclaim is true, add exclamation marks.
    """


    result
= s + s + s # can also use "s * 3" which is faster (Why?)
   
if exclaim:
        result
= result + '!!!'
   
return result

Notice also how the lines that make up the function or if-statement are grouped by all having the same level of indentation. We also presented 2 different ways to repeat strings, using the + operator which is more user-friendly, but * also works because it's Python's "repeat" operator, meaning that '-' * 10 gives '----------', a neat way to create an onscreen "line." In the code comment, we hinted that * works faster than +, the reason being that * calculates the size of the resulting object once whereas with +, that calculation is made each time + is called. Both + and * are called "overloaded" operators because they mean different things for numbers vs. for strings (and other data types).

The def keyword defines the function with its parameters within parentheses and its code indented. The first line of a function can be a documentation string ("docstring") that describes what the function does. The docstring can be a single line, or a multi-line description as in the example above. (Yes, those are "triple quotes," a feature unique to Python!) Variables defined in the function are local to that function, so the "result" in the above function is separate from a "result" variable in another function. The return statement can take an argument, in which case that is the value returned to the caller.

Here is code that calls the above repeat() function, printing what it returns:

def main():
   
print repeat('Yay', False)      ## YayYayYay
   
print repeat('Woo Hoo', True)   ## Woo HooWoo HooWoo Hoo!!!

At run time, functions must be defined by the execution of a "def" before they are called. It's typical to def a main() function towards the bottom of the file with the functions it calls above it.

Indentation

One unusual Python feature is that the whitespace indentation of a piece of code affects its meaning. A logical block of statements such as the ones that make up a function should all have the same indentation, set in from the indentation of their parent function or "if" or whatever. If one of the lines in a group has a different indentation, it is flagged as a syntax error.

Python's use of whitespace feels a little strange at first, but it's logical and I found I got used to it very quickly. Avoid using TABs as they greatly complicate the indentation scheme (not to mention TABs may mean different things on different platforms). Set your editor to insert spaces instead of TABs for Python code.

A common question beginners ask is, "How many spaces should I indent?" According to the official Python style guide (PEP 8), you should indent with 4 spaces. (Fun fact: Google's internal style guideline dictates indenting by 2 spaces!)

Code Checked at Runtime

Python does very little checking at compile time, deferring almost all type, name, etc. checks on each line until that line runs. Suppose the above main() calls repeat() like this:

def main():
   
if name == 'Guido':
       
print repeeeet(name) + '!!!'
   
else:
       
print repeat(name)

The if-statement contains an obvious error, where the repeat() function is accidentally typed in as repeeeet(). The funny thing in Python ... this code compiles and runs fine so long as the name at runtime is not 'Guido'. Only when a run actually tries to execute the repeeeet() will it notice that there is no such function and raise an error. This just means that when you first run a Python program, some of the first errors you see will be simple typos like this. This is one area where languages with a more verbose type system, like Java, have an advantage ... they can catch such errors at compile time (but of course you have to maintain all that type information ... it's a tradeoff).

Variable Names

Since Python variables don't have any type spelled out in the source code, it's extra helpful to give meaningful names to your variables to remind yourself of what's going on. So use "name" if it's a single name, and "names" if it's a list of names, and "tuples" if it's a list of tuples. Many basic Python errors result from forgetting what type of value is in each variable, so use your variable names (all you have really) to help keep things straight.

As far as actual naming goes, some languages prefer underscored_parts for variable names made up of "more than one word," but other languages prefer camelCasing. In general, Python prefers the underscore method but guides developers to defer to camelCasing if integrating into existing Python code that already uses that style. Readability counts. Read more in the section on naming conventions in PEP 8.

As you can guess, keywords like 'print' and 'while' cannot be used as variable names — you'll get a syntax error if you do. However, be careful not to use built-ins as variable names. For example, while 'str' and 'list' may seem like good names, you'd be overriding those system variables. Built-ins are not keywords and thus, are susceptible to inadvertent use by new Python developers.

More on Modules and their Namespaces

Suppose you've got a module "binky.py" which contains a "def foo()". The fully qualified name of that foo function is "binky.foo". In this way, various Python modules can name their functions and variables whatever they want, and the variable names won't conflict — module1.foo is different from module2.foo. In the Python vocabulary, we'd say that binky, module1, and module2 each have their own "namespaces," which as you can guess are variable name-to-object bindings.

For example, we have the standard "sys" module that contains some standard system facilities, like the argv list, and exit() function. With the statement "import sys" you can can then access the definitions in the sys module and makes them available by their fully-qualified name, e.g. sys.exit(). (Yes, 'sys' has a namespace too!)

  import sys

 
# Now can refer to sys.xxx facilities
  sys
.exit(0)

There is another import form that looks like this: "from sys import argv, exit". That makes argv and exit() available by their short names; however, we recommend the original form with the fully-qualified names because it's a lot easier to determine where a function or attribute came from.

There are many modules and packages which are bundled with a standard installation of the Python interpreter, so you don't have do anything extra to use them. These are collectively known as the "Python Standard Library." Commonly used modules/packages include:

  • sys — access to exit(), argv, stdin, stdout, ...
  • re — regular expressions
  • os — operating system interface, file system

You can find the documentation of all the Standard Library modules and packages athttp://docs.python.org/library.

Online help, help(), and dir()

There are a variety ways to get help for Python.

  • Do a Google search, starting with the word "python", like "python list" or "python string lowercase". The first hit is often the answer. This technique seems to work better for Python than it does for other languages for some reason.
  • The official Python docs site — docs.python.org — has high quality docs. Nonetheless, I often find a Google search of a couple words to be quicker.
  • There is also an official Tutor mailing list specifically designed for those who are new to Python and/or programming!
  • Many questions (and answers) can be found on StackOverflow and Quora.
  • Use the help() and dir() functions (see below).

Inside the Python interpreter, the help() function pulls up documentation strings for various modules, functions, and methods. These doc strings are similar to Java's javadoc. The dir() function tells you what the attributes of an object are. Below are some ways to call help() and dir() from the interpreter:

  • help(len) — help string for the built-in len() function; note that it's "len" not "len()", which is a call to the function, which we don't want
  • help(sys) — help string for the sys module (must do an import sys first)
  • dir(sys) — dir() is like help() but just gives a quick list of its defined symbols, or "attributes"
  • help(sys.exit) — help string for the exit() function in the sys module
  • help('xyz'.split) — help string for the split() method for string objects. You can callhelp() with that object itself or an example of that object, plus its attribute. For example, calling help('xyz'.split) is the same as calling help(str.split).
  • help(list) — help string for list objects
  • dir(list) — displays list object attributes, including its methods
  • help(list.append) — help string for the append() method for list objects


Posted by MIDDLE
,

/**


 * 예제 :

 *   var data = new Map();

 *   data.put("key1", "value1");

 *   data.put("key2", "value2");

 *   data.get("key1");

 *   data.size();

 *   

 */

  

Map = function(){

this.map = new Object();

};

Map.prototype = {   

put : function(key, value){   

/*if ( value.constructor == Array ){

for ( var i =0 ; i < value.size(); i++ ) {

 this.map[key] = value[i];

 alert(i + key + " : " + value[i]);

}

alert('This is an array!' + value.legnth);

}else{*/

this.map[key] = value;

/*}*/

},   

get : function(key){   

return this.map[key];

},

containsKey : function(key){    

return key in this.map;

},

containsValue : function(value){    

for(var prop in this.map){

if(this.map[prop] == value) return true;

}

return false;

},

isEmpty : function(key){    

return (this.size() == 0);

},

clear : function(){   

for(var prop in this.map){

delete this.map[prop];

}

},

remove : function(key){    

delete this.map[key];

},

keys : function(){   

/*var keys = new Array();   

for(var prop in this.map){   

keys.push(prop);

}   

return keys;*/

var keys = new Array();

var resVal = "";

var count = 0;

for(var prop in this.map){   

keys.push(prop);

if(count > 0){

resVal += "_";

}

resVal += prop;

count++;

}   

return resVal;

},

values : function(){   

/*var values = new Array();   

for(var prop in this.map){   

values.push(this.map[prop]);

}   

return values;*/

var values = new Array();

var resVal = "";

var count = 0;

for(var prop in this.map){   

values.push(prop);

if(count > 0){

resVal += "_";

}

resVal += this.map[prop];

count++;

}   

return resVal;

},

size : function(){

var count = 0;

for (var prop in this.map) {

count++;

}

return count;

}

};

 

 


Key와 Values는 _ 를 이용하여 구분자를 사용하였다. JavaScript Taraditional을 사용하게 될경우 배열의 형태가 깨질 우려가 있기 때문에 배열의 구분자는 사용하지 않아야 한다.

  



Ajax 보내는 부분에서 data 불러오기

function _fnCallJson(reqURL, data, async, callback) {

// 처리시는 동기화

$.ajaxSetup({

async : false

});

var args = "";

// callback 함수가 null일시에 값만 return 해준다.

var _response;

var defaultAsync = false;

var resDataType = "json";

if (data != null && data.size() > 0) {

var keys = data.keys().toString().split('_');

var values = data.values().toString().split('_');

alert("_fnCallJson Key :  " + data.keys().toString() + " val :  "+  data.values().toString());

for (var i = 0; i < keys.length; i++) {

if (i > 0)

args += "&";

if (keys[i].length > 0)

args += keys[i] + "=" + values[i];

}

}

if (callback != null ){

}

//else{

// resDataType = "html";

//}

var resAsync = "";

if (async != null && async.length > 0) {

resAsync = async;

} else {

resAsync = defaultAsync;

}

$.ajax({

type : "POST",

url : reqURL,

data : args,

async : resAsync,

traditional : true,

contentType : "application/x-www-form-urlencoded; charset=utf-8",

dataType : resDataType, // xml, html, json, jsonp, script, text

success : function(data) {

if (callback != null ) {

callback(data);

}else{

//_response = $.parseJSON(data);

_response = data;

}

}

});

return _response;

// 처리시는 동기화

$.ajaxSetup({

async : false

});

}

Posted by MIDDLE
,
  • Tomcat 서버를 sh shutdown.sh 명령어를 통해 Shutdown 한 후 webapps 폴더 내부에서 모든 파일을 삭제를 한다. 올리고자하는 WAR파일명을 ROOT.war로 변경한뒤 폴더에 업로드 후 bin 폴더의 sh startup.sh 명령어로 실행한다.

  • Leave your war file in $CATALINA_BASE/webapps under its original name. Turn off autoDeployand deployOnStartup in your Host element in the server.xml file. Explicitly define all application Contexts in server.xml, specifying both the path and docBase attributes. You must do this because you have disabled all the Tomcat auto-deploy mechanisms, and Tomcat will not deploy your applications anymore unless it finds their Context in the server.xml.

    second method: in order to make any change to any application, you will have to stop and restart Tomcat.

  • $CATALINA_BASE/webapps 에 고유 이름이 있다면 Ex) webapps/project. shutdown 완료 이후 conf 폴더 내부의 server.xml 파일을 확인 이후 docBase를 추가한다.
    docBase추가 방법은

    <Host name="localhost"  appBase="webapps"

                unpackWARs="true" autoDeploy="true">


            <!-- SingleSignOn valve, share authentication between web applications

                 Documentation at: /docs/config/valve.html -->

            <!--

            <Valve className="org.apache.catalina.authenticator.SingleSignOn" />

            -->


            <!-- Access log processes all example.

                 Documentation at: /docs/config/valve.html

                 Note: The pattern used is equivalent to using pattern="common" -->

          <Valve className="org.apache.catalina.valves.AccessLogValve" directory="logs"

                   prefix="localhost_access_log." suffix=".txt"

                   pattern="%h %l %u %t &quot;%r&quot; %s %b" />

            <Context docBase="project" path="" reloadable="true" />

    </Host>

아래의 한줄을 Server.xml 에 추가를 하면 해결된다.

Posted by MIDDLE
,

햄릿 증후군??

개인공부 2015. 8. 5. 09:05

메이비 세대가 함의 하는것은 결정을 잘 내리지 못하는 현상이 개인의 나쁜 습관에만 기인 하는 것이 아니라, 기회 과잉의 바다에 빠뜨리고 수많은 선택을 강요하는 사회배경에도 일부 책임을 묻는다는 사실이다. 이제 햄릿 증후군은 세대론의 범주가 됐다. 결정에 어려움을 느끼는 소비자들은 그선택을 스스로 내리기보다 누군가의 도움을 얻어서라도 정답에 가까운 선택을 하려고한다.


이러한 문제를 해결하기 위해 다양한 앱과 사이트들에서는 전문가를 고용하여 사용자들을 손쉽게 고를수있도록 리스트업을 한다던지 하여서 사용자를 유도하는 방식을 사용한다.


이러한 사용자들을 끌어들이기 위해서는 전문가나 최적화에 대한 방법만이 전부일까? 한번 생각해보자.

Posted by MIDDLE
,