1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
# Your task is to make sure that this mapper code does not fail on corrupt data lines,
# but instead just ignores them and continues working
import sys

def mapper():
    # read standard input line by line
    for line in sys.stdin:
        # strip off extra whitespace, split on tab and put the data in an array
        data = line.strip().split("\t")

        # This is the place you need to do some defensive programming
        # what if there are not exactly 6 fields in that line?
        # YOUR CODE HERE
        if len(data)==6 :
       
            # this next line is called 'multiple assignment' in Python
            # this is not really necessary, we could access the data
            # with data[2] and data[5], but we do this for conveniency
            # and to make the code easier to read
            date, time, store, item, cost, payment = data
       
            # Now print out the data that will be passed to the reducer
            print "{0}\t{1}".format(store, cost)
       
       
test_text = """2013-10-09\t13:22\tMiami\tBoots\t99.95\tVisa
2013-10-09\t13:22\tNew York\tDVD\t9.50\tMasterCard
2013-10-09 13:22:59 I/O Error
^d8x28orz28zoijzu1z1zp1OHH3du3ixwcz114<f
1\t2\t3"""


# This function allows you to test the mapper with the provided test string
def main():
    import StringIO
    sys.stdin = StringIO.StringIO(test_text)
    mapper()
    sys.stdin = sys.__stdin__

Java String Anagrams

Problem
Two strings and are called anagrams if they consist same characters, but may be in different orders. So the list of anagrams of is .

Given two strings, print Anagrams if they are anagrams, print Not Anagrams if they are not. The strings may consist at most English characters; the comparison should NOT be case sensitive.

This exercise will verify that you can sort the characters of a string, or compare frequencies of characters.

Sample Input 0

anagram
margana

Sample Output 0

Anagrams

Sample Input 1

anagramm
marganaa
Sample Output 1:

Not Anagrams

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
    /**
     * Two strings and are called anagrams if they consist same characters, but may be in different orders. So
     * the list of anagrams of is .
     *
     * Given two strings, print Anagrams if they are anagrams, print Not Anagrams if they are not. The strings
     * may consist at most English characters; the comparison should NOT be case sensitive.
     *
     * This exercise will verify that you can sort the characters of a string, or compare frequencies of
     * characters.
     *
     * @param a
     * @param b
     *
     * @return
     */

    static boolean isAnagram( String a, String b ) {

        Collection<String> s1 = new ArrayList<>();

        for (int i = 0; i < a.length(); i++) {
            s1.add( String.valueOf( a.charAt( i ) ).toUpperCase() );
        }

        boolean result = true;
        for (int i = 0; i < b.length(); i++) {
            String charAt = String.valueOf( b.charAt( i ) ).toUpperCase();
            if ( !s1.contains( charAt ) ) {
                result = false;
            } else {
                s1.remove( charAt );
                //System.out.print( charAt + " : " );
                //System.out.println( s1 );
            }
        }

        return s1.size() > 0 ? false : result;
    }

Java String Compare

Problem
Given a string, find out the lexicographically smallest and largest substring of length .

[Note: Lexicographic order is also known as alphabetic order dictionary order. So “ball” is smaller than “cat”, “dog” is smaller than “dorm”. Capital letter always comes before smaller letter, so “Happy” is smaller than “happy” and “Zoo” is smaller than “ball”.]

Input Format

First line will consist a string containing english alphabets which has at most characters. 2nd line will consist an integer .

Output Format

In the first line print the lexicographically minimum substring. In the second line print the lexicographically maximum substring.

Sample Input

1
2
welcometojava
3

Sample Output

1
2
ava
wel

Explanation

Here is the list of all substrings of length :

1
2
3
4
5
6
7
8
9
10
11
wel
elc
lco
com
ome
met
eto
toj
oja
jav
ava

Among them ava is the smallest and wel is the largest.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
/**
 * Copyright 2016. ABN Software. All Rights reserved.<br>
 * <br>
 * Created ..... 3 окт. 2016 г.<br>
 * <br>
 */

package info.abnsoft.java.HackerRank.sep2016;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Scanner;

/**
 * @author annik
 *
 */

public class SolutionStringLexi {

    public static void main( String[] args ) {

        /*
         * Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named
         * Solution.
         */

        Scanner sc = new Scanner( System.in );
        String str = sc.nextLine();
        int count = sc.nextInt();
        sc.close();
//        System.out.println(str);
//        System.out.println(count);
        // splitted words :
        List<String> splitted = new ArrayList<String>();
        // sorted words
        List<String> result = new LinkedList<String>();
        if ( str.length() <= count ) {
            result.add( str );
        } else {
            for (int i = 0; i <= str.length() - count; i++) {
                //            System.out.println(str.substring(i,i+count));
                splitted.add( str.substring( i, i + count ) );
            }
            String cur = splitted.get( 0 );
            result.add( cur ); // add 1st element

            System.out.println( splitted );

            // TODO : if size==0 ?
            for (int i = 1; i < splitted.size(); i++) {
                boolean notFoundMin = true;
                for (int j = 0; j < result.size(); j++) {
                    cur = result.get( j );
                    if ( isLexicSmaller( splitted.get( i ), cur ) ) {
                        // when arr[i] is smaller insert at first
                        result.add( j, splitted.get( i ) );
                        notFoundMin = false;
//                        cur = splitted.get( i );
                        break;
                    }
                }
                if ( notFoundMin ) {
                    result.add( splitted.get( i ) ); // add at the end of list
//                    cur = splitted.get( i );
                }
            }
        }
        System.out.println( result );
        System.out.println( ( (LinkedList<String>) result ).getFirst() );
        System.out.println( ( (LinkedList<String>) result ).getLast() );
    }

    /*
     * When a < b returns true, else FALSE.
     */

    private static boolean isLexicSmaller( String a, String b ) {

        boolean result = false;
        int i = -1;
        do {
            i++;
            if ( a.charAt( i ) != b.charAt( i ) ) {
                if ( a.charAt( i ) < b.charAt( i ) ) {
                    result = true;
                }
            }
        } while (a.charAt( i ) == b.charAt( i ) && i < ( a.length() - 1 ));
        return result;
    }

}

SAMPLE : Java String.matches()

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
/**
 * Copyright 2013. ABN Software. All Rights reserved.<br>
 * <br>
 * Homepage .... http://www.ABNsoft.info<br>
 * <br>
 * Project ..... ABNTest<br>
 * Package ..... ABNTest<br>
 * File name ... StringMatch.java<br>
 * <br>
 * Author ...... Andre<br>
 * Created ..... 18.04.2013<br>
 * <br>
 */

package info.abnsoft.java.trying;

import java.util.regex.Pattern;

/**
 * @author annik
 *
 */

public class StringMatch
{
    public static void main(final String[] args) {
        //
        final StringBuffer sb = new StringBuffer( "<response>\n"+
"    <category>client</category>\n"+
"    <action>Login</action>\n"+
"    <code>1000</code>\n"+
"    <msg>Command completed successfully</msg>\n"+
"    <value>L115:no value</value>\n"+
"    <resData>\n"+
"    </resData>\n"+
"    <cltrid>RM.2013.04.18.1366294770248</cltrid>\n"+
"    <svtrid>RM.2013.04.18.1366294770248-API-SRV</svtrid>\n"+
"    <chksum>8fc683ce8d7772f91ac28224fa3e6cc0</chksum>\n"+
"</response>\n" );
       
        System.out.println(sb.toString());
       
        System.out.println("\n\n======================");
        final String pattern0 = "(?s).*" + "</response>" + ".*";
        System.out.println(pattern0);
       
        if (sb.toString().toLowerCase().matches(pattern0)) {
            System.out.println("MATCH");
        }else {
            System.out.println(" ! FAILED");
        }
       
        System.out.println("\n\n======================");
        final String pattern1 = "(?m)(?s)" + "</response>" + "";
        System.out.println(pattern1);
       
        if (sb.toString().toLowerCase().matches(pattern1)) {
            System.out.println("MATCH");
        }else {
            System.out.println(" ! FAILED");
        }
       
        System.out.println("\n\n======================");
        final String pattern2 = "" + "</response>" + "";
        final Pattern p = Pattern.compile(pattern2, Pattern.MULTILINE+Pattern.DOTALL);
        System.out.println(p.matcher(sb.toString().toLowerCase()).find());  //true


    }
}

that code above will print follow :

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
<response>
    <category>client</category>
    <action>Login</action>
    <code>1000</code>
    <msg>Command completed successfully</msg>
    <value>L115:no value</value>
    <resData>
    </resData>
    <cltrid>RM.2013.04.18.1366294770248</cltrid>
    <svtrid>RM.2013.04.18.1366294770248-API-SRV</svtrid>
    <chksum>8fc683ce8d7772f91ac28224fa3e6cc0</chksum>
</response>



======================
(?s).*</response>.*
MATCH


======================
(?m)(?s)</response>
 ! FAILED


======================
true

Error with MySQL DATETIME ‘0000-00-00 00:00:00’ can not be represented as java.sql.Timestamp

When I started work with MySQL from Hibernate I got exceptions with approximate content :
… ‘0000-00-00 00:00:00’ …. can not be represented as java.sql.Timestamp

My solution for this bug was following :
As I used bean datasource :

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
<beans
   xmlns="http://www.springframework.org/schema/beans"
   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">

 
<bean
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
    <property name="location">
        <!-- <value>/WEB-INF/database/database.properties</value> -->
        <value>/META-INF/spring/database/database.properties</value>
    </property>
</bean>
 
<bean id="dataSource"
        class="org.springframework.jdbc.datasource.DriverManagerDataSource">
    <property name="driverClassName" value="${jdbc.driverClassName}" />
    <property name="url" value="${jdbc.url}?zeroDateTimeBehavior=convertToNull" />
    <property name="username" value="${jdbc.username}" />
    <property name="password" value="${jdbc.password}" />
</bean>
 
</beans>

I added into property URL :

Because I added also in bean id=”sessionFactory” such property :

1
2
3
4
5
6
7
        <property name="hibernateProperties">
            <props>
.....
                <!--  -->
                <prop key="hibernate.connection.zeroDateTimeBehavior">convertToNull</prop>
            </props>
        </property>

that does not help to resolve exception.

MySQL enum in HIBERNATE

How to provide corresponding hibernate Entity and MySQL ENUM type ?

1
enum('Active','Pending','Cancelled','Suspend')

With ANNOTATION :

1
2
@Column(name="status", columnDefinition="enum('Active','Pending','Cancelled','Suspend')")
public String status;

With XML config :

1
2
3
4
5
<property
   name="status"
   column="STATUS"
   type="string"
   not-null="true" />

MAVEN Error assembling WAR : webxml attribute is required (or pre-existing WEB-INF/web.xml if executing in update mode) -> [Help 1]

I try to assemble war using maven and I get :

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
[INFO] ------------------------------------------------------------------------
[INFO] BUILD FAILURE
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 13.761s
[INFO] Finished at: Tue Apr 09 02:46:52 GST 2013
[INFO] Final Memory: 6M/18M
[INFO] ------------------------------------------------------------------------
[ERROR] Failed to execute goal org.apache.maven.plugins:maven-war-plugin:2.1.1:war (default-war) on project RegMaster: Error assembling WAR: webxml attribute is required (or pre-existing WEB-INF/web.xml if executing in update mode) -> [Help 1]
org.apache.maven.lifecycle.LifecycleExecutionException: Failed to execute goal org.apache.maven.plugins:maven-war-plugin:2.1.1:war (default-war) on project RegMaster: Error assembling WAR: webxml attribute is required (or pre-existing WEB-INF/web.xml if executing in update mode)
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:217)
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:153)
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:145)
    at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject(LifecycleModuleBuilder.java:84)
    at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject(LifecycleModuleBuilder.java:59)
    at org.apache.maven.lifecycle.internal.LifecycleStarter.singleThreadedBuild(LifecycleStarter.java:183)
    at org.apache.maven.lifecycle.internal.LifecycleStarter.execute(LifecycleStarter.java:161)
    at org.apache.maven.DefaultMaven.doExecute(DefaultMaven.java:320)
    at org.apache.maven.DefaultMaven.execute(DefaultMaven.java:156)
    at org.apache.maven.cli.MavenCli.execute(MavenCli.java:537)
    at org.apache.maven.cli.MavenCli.doMain(MavenCli.java:196)
    at org.apache.maven.cli.MavenCli.main(MavenCli.java:141)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:601)
    at org.codehaus.plexus.classworlds.launcher.Launcher.launchEnhanced(Launcher.java:290)
    at org.codehaus.plexus.classworlds.launcher.Launcher.launch(Launcher.java:230)
    at org.codehaus.plexus.classworlds.launcher.Launcher.mainWithExitCode(Launcher.java:409)
    at org.codehaus.plexus.classworlds.launcher.Launcher.main(Launcher.java:352)
Caused by: org.apache.maven.plugin.MojoExecutionException: Error assembling WAR: webxml attribute is required (or pre-existing WEB-INF/web.xml if executing in update mode)
    at org.apache.maven.plugin.war.WarMojo.execute(WarMojo.java:175)
    at org.apache.maven.plugin.DefaultBuildPluginManager.executeMojo(DefaultBuildPluginManager.java:101)
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:209)
    ... 19 more
Caused by: org.codehaus.plexus.archiver.ArchiverException: webxml attribute is required (or pre-existing WEB-INF/web.xml if executing in update mode)
    at org.codehaus.plexus.archiver.war.WarArchiver.initZipOutputStream(WarArchiver.java:149)
    at org.codehaus.plexus.archiver.zip.AbstractZipArchiver.createArchiveMain(AbstractZipArchiver.java:346)
    at org.codehaus.plexus.archiver.zip.AbstractZipArchiver.execute(AbstractZipArchiver.java:250)
    at org.codehaus.plexus.archiver.AbstractArchiver.createArchive(AbstractArchiver.java:871)
    at org.apache.maven.archiver.MavenArchiver.createArchive(MavenArchiver.java:543)
    at org.apache.maven.plugin.war.WarMojo.performPackaging(WarMojo.java:225)
    at org.apache.maven.plugin.war.WarMojo.execute(WarMojo.java:159)
    ... 21 more
[ERROR]
[ERROR]
[ERROR] For more information about the errors and possible solutions, please read the following articles:
[ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/MojoExecutionException

solution is :

1
2
3
4
5
6
7
<plugin>            
  <groupId>org.apache.maven.plugins</groupId>
  <artifactId>maven-war-plugin</artifactId>
  <configuration>
    <webXml>src\main\webapp\WEB-INF\web.xml</webXml>        
  </configuration>
</plugin

How to add DATABASE access in Dynamic Web Project ?

We will get such structure :

Add DATABSE in Dynamic Web Projet

Add DATABSE in Dynamic Web Projet

1. Create in your WEB_ROOT these folders: WEB-INF/database
2. Create file “datapase.properties” :

1
2
3
4
5
jdbc.driverClassName=org.postgresql.Driver
jdbc.url=jdbc\:postgresql\://109.197.1.1\:5433/yourDB
jdbc.username=yourLogin
jdbc.password=yourPWD
jdbc.showSql=true

3. Create DataSource.xml file – it contains bean “dataSource” and gets value from “datapase.properties” file :

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
<beans
   xmlns="http://www.springframework.org/schema/beans"
   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">

 
<bean
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
    <property name="location">
        <value>/WEB-INF/database/database.properties</value>
    </property>
</bean>
 
<bean id="dataSource"
        class="org.springframework.jdbc.datasource.DriverManagerDataSource">
    <property name="driverClassName" value="${jdbc.driverClassName}" />
    <property name="url" value="${jdbc.url}" />
    <property name="username" value="${jdbc.username}" />
    <property name="password" value="${jdbc.password}" />
</bean>
 
</beans>

4. Create Hibernate.xml file – it cares about Spring Transactions, Hibernate Session Factory :

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
<?xml version="1.0" encoding="UTF-8"?>
<beans
   xmlns="http://www.springframework.org/schema/beans"
   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xmlns:context="http://www.springframework.org/schema/context"
   xmlns:tx="http://www.springframework.org/schema/tx"
   xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
       http://www.springframework.org/schema/context
       http://www.springframework.org/schema/context/spring-context-3.0.xsd
       http://www.springframework.org/schema/tx
       http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
       ">


    <!-- Hibernate transaction manager -->
    <tx:annotation-driven transaction-manager="transactionManager" />
    <bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
        <property name="sessionFactory" ref="sessionFactory" />
    </bean>

    <!-- Hibernate session factory -->
    <bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">

        <property name="dataSource">
            <ref bean="dataSource" />
        </property>

        <property name="hibernateProperties">
            <props>
                <prop key="hibernate.dialect">org.hibernate.dialect.PostgreSQLDialect</prop>
                <prop key="hibernate.show_sql">true</prop>
                <!-- +1 -->
                <prop key="hibernate.format_sql">true</prop>
                <prop key="hibernate.hbm2ddl.auto">create</prop>
                <!-- Enable Hibernate's automatic session context management
                   Spring manages the transaction, and it doesn't need of that the session is holding in a
                   hibernate thread.
               <prop key="hibernate.current_session_context_class">thread</prop>
               -->
                <prop key="hibernate.current_session_context_class">org.springframework.orm.hibernate3.SpringSessionContext</prop>

            </props>
        </property>

        <property name="packagesToScan" value="ru.tomatch.admin.model" />

        <property name="configurationClass">
            <value>org.hibernate.cfg.AnnotationConfiguration</value>
        </property>

        <property name="exposeTransactionAwareSessionFactory">
            <value>false</value>
        </property>


    </bean>
</beans>

5. And last file applicationContext.xml :

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
<beans
   xmlns="http://www.springframework.org/schema/beans"
   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xmlns:context="http://www.springframework.org/schema/context"
   xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
       http://www.springframework.org/schema/context
       http://www.springframework.org/schema/context/spring-context-3.0.xsd">

   
    <!-- Database Configuration -->
    <import resource="./database/DataSource.xml"/>
    <import resource="./database/Hibernate.xml"/>
 
    <!-- Auto scan the components -->
    <context:component-scan base-package="some.your.package1" />    
    <context:component-scan base-package="some.your.package2" />    

</beans>