Categories
discuss

ECMAScript 6 features available in Node.js 0.12

A new stable release of Node.js (0.12) has landed recently with an upgraded Google’s v8 JavaScript engine, v3.28.73.

What ECMAScript 6 features are currently present in Node.js, without using the --harmony flag?

I have checked several sites claiming to list the ES 6 features but all of them seem out of date – most prominently, this table (Update: now updated with current Node.js status as of 0.12), because several of the features are listed as requiring the --harmony flag while I found some of them being enabled by default (Maps, Sets, Symbols, to name a few). Update: Node specific tables have since been made available

Also, trying to google this information purely for the v8 engine gives too up-to-date information – current v8 release is 4.2.*, which is quite ahead of what Node.js uses.

My hopes are that this question (and its answers) will become a comprehensive summary on what ES 6 features are now available to Node.js developers.

ES 6 features enabled in Node.js 0.12 I currently know of:

  • Maps, Sets / WeakMaps, WeakSets
  • Symbols
  • Object.observe
  • Promises
  • Number
    • .isInteger
    • .isSafeInteger
    • .isNaN
    • .EPSILON
    • .MIN_SAFE_INTEGER
    • .MAX_SAFE_INTEGER
  • Math
    • .clz32
    • .imul
    • .sign
    • .log10
    • .log2
    • .log1p
    • .expm1
    • .cosh
    • .sinh
    • .tanh
    • .acosh
    • .asinh
    • .atanh
    • .trunc
    • .fround
    • .cbrt
    • .hypot

Answer

Features without --harmony flag:

I thinks that’s all that we have without --harmony flag.

Features with --harmony flag:

I think that’s all. Maybe if I forgot something – I’ll add it later to the list.

Categories
discuss

How to test DAO methods using Mockito?

I’ve started to discovered Mockito library and there is a question for which I didn’t find the proper answer.

If I have for example such method in my UserDAO class that saves user in database:

public class UserDAO{
...
 public void create(User user) {
        Connection connection = null;
        PreparedStatement pstmt = null;
        ResultSet generatedKeys = null;
        try {

            connection = getConnection();
            pstmt = connection.prepareStatement(INSERT_USER,
                    PreparedStatement.RETURN_GENERATED_KEYS);
            int counter = 1;
            pstmt.setString(counter++, user.getFirstName());
            pstmt.setString(counter++, user.getLastName());
            pstmt.setString(counter++, user.getEmail());
            pstmt.setString(counter++, user.getPassword());
            pstmt.setString(counter++, user.getRole());
            pstmt.setString(counter, user.getLang());

            pstmt.execute();
            connection.commit();
            generatedKeys = pstmt.getGeneratedKeys();

            if (generatedKeys.next()) {
                user.setId(generatedKeys.getInt(Fields.GENERATED_KEY));
            }
        } catch (SQLException e) {
            rollback(connection);
            LOG.error("Can not create a user", e);
        } finally {
            close(connection);
            close(pstmt);
            close(generatedKeys);
        }
    }
  ....
}

How should I test it ?

If I want to test for example a DAO class then I need to create a DataSource mock, Connection mock, ResultSet mock etc ? And so not to test the database itself ?

But what if I want to also test the behavior of dao and database ?

Would you please produce some code samples, links that could be helpful and show best approaches of doing it ?

Answer

Here is a good start using Mockito to test your UserDAO. This code uses a good amount of the Mockito features, so you can see how to use them. Let me know if you have questions.

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.sql.DataSource;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import static org.junit.Assert.*;
import org.junit.runner.RunWith;
import static org.mockito.Matchers.anyInt;
import static org.mockito.Matchers.anyString;
import org.mockito.Mock;
import static org.mockito.Mockito.doNothing;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import org.mockito.runners.MockitoJUnitRunner;

@RunWith(MockitoJUnitRunner.class)
public class TestUserDAO {

    @Mock
    DataSource mockDataSource;
    @Mock
    Connection mockConn;
    @Mock
    PreparedStatement mockPreparedStmnt;
    @Mock
    ResultSet mockResultSet;
    int userId = 100;

    public TestUserDAO() {
    }

    @BeforeClass
    public static void setUpClass() throws Exception {
    }

    @AfterClass
    public static void tearDownClass() {
    }

    @Before
    public void setUp() throws SQLException {
        when(mockDataSource.getConnection()).thenReturn(mockConn);
        when(mockDataSource.getConnection(anyString(), anyString())).thenReturn(mockConn);
        doNothing().when(mockConn).commit();
        when(mockConn.prepareStatement(anyString(), anyInt())).thenReturn(mockPreparedStmnt);
        doNothing().when(mockPreparedStmnt).setString(anyInt(), anyString());
        when(mockPreparedStmnt.execute()).thenReturn(Boolean.TRUE);
        when(mockPreparedStmnt.getGeneratedKeys()).thenReturn(mockResultSet);
        when(mockResultSet.next()).thenReturn(Boolean.TRUE, Boolean.FALSE);
        when(mockResultSet.getInt(Fields.GENERATED_KEYS)).thenReturn(userId);
    }

    @After
    public void tearDown() {
    }

    @Test
    public void testCreateWithNoExceptions() throws SQLException {

        UserDAO instance = new UserDAO(mockDataSource);
        instance.create(new User());

        //verify and assert
        verify(mockConn, times(1)).prepareStatement(anyString(), anyInt());
        verify(mockPreparedStmnt, times(6)).setString(anyInt(), anyString());
        verify(mockPreparedStmnt, times(1)).execute();
        verify(mockConn, times(1)).commit();
        verify(mockResultSet, times(2)).next();
        verify(mockResultSet, times(1)).getInt(Fields.GENERATED_KEYS);
    }

    @Test(expected = SQLException.class)
    public void testCreateWithPreparedStmntException() throws SQLException {

         //mock
         when(mockConn.prepareStatement(anyString(), anyInt())).thenThrow(new SQLException());


        try {
            UserDAO instance = new UserDAO(mockDataSource);
            instance.create(new User());
        } catch (SQLException se) {
            //verify and assert
            verify(mockConn, times(1)).prepareStatement(anyString(), anyInt());
            verify(mockPreparedStmnt, times(0)).setString(anyInt(), anyString());
            verify(mockPreparedStmnt, times(0)).execute();
            verify(mockConn, times(0)).commit();
            verify(mockResultSet, times(0)).next();
            verify(mockResultSet, times(0)).getInt(Fields.GENERATED_KEYS);
            throw se;
        }

    }
}
Categories
discuss

Notification bar icon turns white in Android 5 Lollipop

I have an app showing custom notifications. The problem is that when running in Android 5 the small icon in the Notification bar is shown in white. How can I fix this?

Answer

The accepted answer is not (entirely) correct. Sure, it makes notification icons show in color, but does so with a BIG drawback – by setting the target SDK to lower than Android Lollipop!

If you solve your white icon problem by setting your target SDK to 20, as suggested, your app will not target Android Lollipop, which means that you cannot use Lollipop-specific features.

Have a look at http://developer.android.com/design/style/iconography.html, and you’ll see that the white style is how notifications are meant to be displayed in Android Lollipop.

In Lollipop, Google also suggest that you use a color that will be displayed behind the (white) notification icon – https://developer.android.com/about/versions/android-5.0-changes.html

So, I think that a better solution is to add a silhouette icon to the app and use it if the device is running Android Lollipop.

For instance:

Notification notification = new Notification.Builder(context)
            .setAutoCancel(true)
            .setContentTitle("My notification")
            .setContentText("Look, white in Lollipop, else color!")
            .setSmallIcon(getNotificationIcon())
            .build();

    return notification;

And, in the getNotificationIcon method:

private int getNotificationIcon() {
    boolean useWhiteIcon = (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP);
    return useWhiteIcon ? R.drawable.icon_silhouette : R.drawable.ic_launcher;
}
Categories
discuss

How can I control how Android TTS plays audio

I have a class that uses the Android TTS API to transcribe text to audio. I can control the pitch and speed; but I noticed the engine requires a text string and also a hash object. I noticed some words are pronounced too quickly to be easily recognized, and inflection seems too unnatural. Is there a way I can control these two things; possibly through the HashMap? The following is how I’m using the engine:

    mTts = new TextToSpeech(Globals.context, this); // context, listener
}

@Override
public void onInit(int status) {
    HashMap<String, String> myHashRender = new HashMap();
    myHashRender.put(TextToSpeech.Engine.KEY_PARAM_UTTERANCE_ID, speech);
    mTts.setPitch(0.8f);
    mTts.setSpeechRate(0.6f);
    mTts.synthesizeToFile(speech, myHashRender, fileOutPath);
    while (mTts.isSpeaking()) try {
        Thread.sleep(100);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
    mTts.stop();
    mTts.shutdown();

Answer

Google TTS does not currently support that, but here is what you can do: During parsing of your text, you can change parts of it to get the intonation and inflection you want.

For example, if you encounter the word ‘Hey’ you rewrite it on the fly to ‘Heeeey’ before you send it to the TTS engine to get a different pronounciation.

It is not pretty but it is a workaround.

Categories
discuss

Java – sort only subsection of array

I have an array of characters

String a = "badabcde";
char[] chArr = a.toCharArray(); // 'b','a','d','a','b','c','d','e'

What’s the easiest way to sort only a section of the array, given a start and end index?

// 'b','a','d','a','b','c','d','e'
subSort(array, startIndex, endIndex);

Ex: 
subSort(chArr, 2, 5);
// 'b','a','a','b','c','d','d','e' // sorts indices 2 to 5 

Answer

I think public static void sort(char[] a, int fromIndex, int toIndex) answers your question.

String a = "badabcde";
char[] chArr = a.toCharArray(); // 'b','a','d','a','b','c','d','e'

// fromIndex - the index of the first element (inclusive) to be sorted
// toIndex - the index of the last element (exclusive) to be sorted
Arrays.sort(chArr,2,6);
Source: stackoverflow
Text is available under the Creative Commons Attribution-ShareAlike License; additional terms may apply. By using this site, you agree to the Privacy Policy, and Copyright Policy. Content is available under CC BY-SA 3.0 unless otherwise noted. The answers/resolutions are collected from stackoverflow, are licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0 © No Copyrights, All Questions are retrived from public domain..