Programs & Examples On #Casyncsocket

Artificially create a connection timeout error

The technique I use frequently to simulate a random connection timeout is to use ssh local port forwarding.

ssh -L 12345:realserver.com:80 localhost

This will forward traffic on localhost:12345 to realserver.com:80 You can loop this around in your own local machine as well, if you want:

ssh -L 12345:localhost:8080 localhost

So you can point your application at your localhost and custom port, and the traffic will get routed to the target host:port. Then you can exit out of this shell (you may also need to ctrl+c the shell after you exit) and it will kill the forwarding which causes your app to see a connection loss.

Java Mouse Event Right Click

To avoid any ambiguity, use the utilities methods from SwingUtilities :

SwingUtilities.isLeftMouseButton(MouseEvent anEvent) SwingUtilities.isRightMouseButton(MouseEvent anEvent) SwingUtilities.isMiddleMouseButton(MouseEvent anEvent)

How to pip install a package with min and max version range?

An elegant method would be to use the ~= compatible release operator according to PEP 440. In your case this would amount to:

package~=0.5.0

As an example, if the following versions exist, it would choose 0.5.9:

  • 0.5.0
  • 0.5.9
  • 0.6.0

For clarification, each pair is equivalent:

~= 0.5.0
>= 0.5.0, == 0.5.*

~= 0.5
>= 0.5, == 0.*

Sort a Map<Key, Value> by values

Using Guava library:

public static <K,V extends Comparable<V>>SortedMap<K,V> sortByValue(Map<K,V> original){
    var comparator = Ordering.natural()
            .reverse() // highest first
            .nullsLast()
            .onResultOf(Functions.forMap(original, null))
            .compound(Ordering.usingToString());
    return ImmutableSortedMap.copyOf(original, comparator);
}

How do I tell Maven to use the latest version of a dependency?

If you want Maven should use the latest version of a dependency, then you can use Versions Maven Plugin and how to use this plugin, Tim has already given a good answer, follow his answer.

But as a developer, I will not recommend this type of practices. WHY?

answer to why is already given by Pascal Thivent in the comment of the question

I really don't recommend this practice (nor using version ranges) for the sake of build reproducibility. A build that starts to suddenly fail for an unknown reason is way more annoying than updating manually a version number.

I will recommend this type of practice:

<properties>
    <spring.version>3.1.2.RELEASE</spring.version>
</properties>

<dependencies>

    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-core</artifactId>
        <version>${spring.version}</version>
    </dependency>

    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-context</artifactId>
        <version>${spring.version}</version>
    </dependency>

</dependencies>

it is easy to maintain and easy to debug. You can update your POM in no time.

How to get the number of columns in a matrix?

When want to get row size with size() function, below code can be used:

size(A,1)

Another usage for it:

[height, width] = size(A)

So, you can get 2 dimension of your matrix.

List comprehension with if statement

If you use sufficiently big list not in b clause will do a linear search for each of the item in a. Why not use set? Set takes iterable as parameter to create a new set object.

>>> a = ["a", "b", "c", "d", "e"]
>>> b = ["c", "d", "f", "g"]
>>> set(a).intersection(set(b))
{'c', 'd'}

Error in contrasts when defining a linear model in R

The answers by the other authors have already addressed the problem of factors with only one level or NAs.

Today, I stumbled upon the same error when using the rstatix::anova_test() function but my factors were okay (more than one level, no NAs, no character vectors, ...). Instead, I could fix the error by dropping all variables in the dataframe that are not included in the model. I don't know what's the reason for this behavior but just knowing about this might also be helpful when encountering this error.

Python circular importing?

If you run into this issue in a fairly complex app it can be cumbersome to refactor all your imports. PyCharm offers a quickfix for this that will automatically change all usage of the imported symbols as well.

enter image description here

Convert stdClass object to array in PHP

For one-dimensional arrays:

$array = (array)$class; 

For multi-dimensional array:

function stdToArray($obj){
  $reaged = (array)$obj;
  foreach($reaged as $key => &$field){
    if(is_object($field))$field = stdToArray($field);
  }
  return $reaged;
}

How do you return the column names of a table?

Not sure if there is an easier way in 2008 version.

USE [Database Name]
SELECT COLUMN_NAME,* 
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = 'YourTableName' AND TABLE_SCHEMA='YourSchemaName'

How to pass an ArrayList to a varargs method parameter?

A shorter version of the accepted answer using Guava:

.getMap(Iterables.toArray(locations, WorldLocation.class));

can be shortened further by statically importing toArray:

import static com.google.common.collect.toArray;
// ...

    .getMap(toArray(locations, WorldLocation.class));

How to show another window from mainwindow in QT

  1. Implement a slot in your QMainWindow where you will open your new Window,
  2. Place a widget on your QMainWindow,
  3. Connect a signal from this widget to a slot from the QMainWindow (for example: if the widget is a QPushButton connect the signal click() to the QMainWindow custom slot you have created).

Code example:

MainWindow.h

// ...
include "newwindow.h"
// ...
public slots:
   void openNewWindow();
// ...
private:
   NewWindow *mMyNewWindow;
// ...
}

MainWindow.cpp

// ...
   MainWindow::MainWindow()
   {
      // ...
      connect(mMyButton, SIGNAL(click()), this, SLOT(openNewWindow()));
      // ...
   }
// ...
void MainWindow::openNewWindow()
{
   mMyNewWindow = new NewWindow(); // Be sure to destroy your window somewhere
   mMyNewWindow->show();
   // ...
}

This is an example on how display a custom new window. There are a lot of ways to do this.

Getting permission denied (public key) on gitlab

There seem to be differences between the two ways to access a git repository i.e. using either SSH or HTTPS. For me, I encountered the error because I was trying to push my local repository using SSH.

The problem can simply be solved by clicking the clone button on the landing page of your project and the copying the HTTPS link and replacing it to the SSH link appearing with the format "git@gitlab...".

Return Max Value of range that is determined by an Index & Match lookup

You don't need an index match formula. You can use this array formula. You have to press CTL + SHIFT + ENTER after you enter the formula.

=MAX(IF((A1:A6=A10)*(B1:B6=B10),C1:F6))

SNAPSHOT

enter image description here

jQuery - Detect value change on hidden input field

You can simply use the below function, You can also change the type element.

 $("input[type=hidden]").bind("change", function() {
       alert($(this).val()); 
 });

Changes in value to hidden elements don't automatically fire the .change() event. So, wherever it is that you're setting that value, you also have to tell jQuery to trigger it.

HTML

 <div id="message"></div>
<input type="hidden" id="testChange" value="0"  />    

JAVASCRIPT

var $message = $('#message');
var $testChange = $('#testChange');
var i = 1;

function updateChange() {
    $message.html($message.html() + '<p>Changed to ' + $testChange.val() + '</p>');
}

$testChange.on('change', updateChange);

setInterval(function() {
    $testChange.val(++i).trigger('change');; 
    console.log("value changed" +$testChange.val());
}, 3000);

updateChange();

should work as expected.

http://jsfiddle.net/7CM6k/3/

Move all files except one

For bash, sth answer is correct. Here is the zsh (my shell of choice) syntax:

mv ~/Linux/Old/^Tux.png ~/Linux/New/

Requires EXTENDED_GLOB shell option to be set.

Why does Git treat this text file as a binary file?

I have had same problem. I found the thread when I search solution on google, still I don't find any clue. But I think I found the reason after studying, the below example will explain clearly my clue.

    echo "new text" > new.txt
    git add new.txt
    git commit -m "dummy"

for now, the file new.txt is considered as a text file.

    echo -e "newer text\000" > new.txt
    git diff

you will get this result

diff --git a/new.txt b/new.txt
index fa49b07..410428c 100644
Binary files a/new.txt and b/new.txt differ

and try this

git diff -a

you will get below

    diff --git a/new.txt b/new.txt
    index fa49b07..9664e3f 100644
    --- a/new.txt
    +++ b/new.txt
    @@ -1 +1 @@
    -new file
    +newer text^@

Convert NSDate to NSString

Hope to add more value by providing the normal formatter including the year, month and day with the time. You can use this formatter for more than just a year

[dateFormat setDateFormat: @"yyyy-MM-dd HH:mm:ss zzz"]; 

Twitter Bootstrap modal: How to remove Slide down effect

The modals used by the bootstrap use CSS3 to supply the effects and they can be removed by eliminating the appropriate classes from modals container div:

<div class="modal hide fade in" id="myModal">
   ....
</div>

As you can see this modal has a class of .fade, meaning it is set to fade in and.in, meaning it will slide in. So just remove the class related to the effect you wish to remove, which in your case is just the .in class.

Edit: Just ran some tests and it appears that that is not the case, the .in class is added by javascript, though you can modify he slideDown behavior with css like so:

.modal.fade {
    -webkit-transition: none;
    -moz-transition: none;
    -ms-transition: none;
    -o-transition: none;
    transition: none;
}

Demo

Difference between filter and filter_by in SQLAlchemy

We actually had these merged together originally, i.e. there was a "filter"-like method that accepted *args and **kwargs, where you could pass a SQL expression or keyword arguments (or both). I actually find that a lot more convenient, but people were always confused by it, since they're usually still getting over the difference between column == expression and keyword = expression. So we split them up.

Please explain about insertable=false and updatable=false in reference to the JPA @Column annotation

I would like to add to the answers of BalusC and Pascal Thivent another common use of insertable=false, updatable=false:

Consider a column that is not an id but some kind of sequence number. The responsibility for calculating the sequence number may not necessarily belong to the application.

For example, sequence number starts with 1000 and should increment by one for each new entity. This is easily done, and very appropriately so, in the database, and in such cases these configurations makes sense.

jQuery dialog popup

You can use the following script. It worked for me

The modal itself consists of a main modal container, a header, a body, and a footer. The footer contains the actions, which in this case is the OK button, the header holds the title and the close button, and the body contains the modal content.

 $(function () {
        modalPosition();
        $(window).resize(function () {
            modalPosition();
        });
        $('.openModal').click(function (e) {
            $('.modal, .modal-backdrop').fadeIn('fast');
            e.preventDefault();
        });
        $('.close-modal').click(function (e) {
            $('.modal, .modal-backdrop').fadeOut('fast');
        });
    });
    function modalPosition() {
        var width = $('.modal').width();
        var pageWidth = $(window).width();
        var x = (pageWidth / 2) - (width / 2);
        $('.modal').css({ left: x + "px" });
    }

Refer:- Modal popup using jquery in asp.net

What is the difference between bottom-up and top-down?

Following is the DP based solution for Edit Distance problem which is top down. I hope it will also help in understanding the world of Dynamic Programming:

public int minDistance(String word1, String word2) {//Standard dynamic programming puzzle.
         int m = word2.length();
            int n = word1.length();


     if(m == 0) // Cannot miss the corner cases !
                return n;
        if(n == 0)
            return m;
        int[][] DP = new int[n + 1][m + 1];

        for(int j =1 ; j <= m; j++) {
            DP[0][j] = j;
        }
        for(int i =1 ; i <= n; i++) {
            DP[i][0] = i;
        }

        for(int i =1 ; i <= n; i++) {
            for(int j =1 ; j <= m; j++) {
                if(word1.charAt(i - 1) == word2.charAt(j - 1))
                    DP[i][j] = DP[i-1][j-1];
                else
                DP[i][j] = Math.min(Math.min(DP[i-1][j], DP[i][j-1]), DP[i-1][j-1]) + 1; // Main idea is this.
            }
        }

        return DP[n][m];
}

You can think of its recursive implementation at your home. It's quite good and challenging if you haven't solved something like this before.

Catching FULL exception message

You can add:

-ErrorVariable errvar

And then look in $errvar.

How can I kill all sessions connecting to my oracle database?

Before killing sessions, if possible do

ALTER SYSTEM ENABLE RESTRICTED SESSION;

to stop new sessions from connecting.

How to extract elements from a list using indices in Python?

Try

numbers = range(10, 16)
indices = (1, 1, 2, 1, 5)

result = [numbers[i] for i in indices]

changing the owner of folder in linux

Use chown to change ownership and chmod to change rights.

use the -R option to apply the rights for all files inside of a directory too.

Note that both these commands just work for directories too. The -R option makes them also change the permissions for all files and directories inside of the directory.

For example

sudo chown -R username:group directory

will change ownership (both user and group) of all files and directories inside of directory and directory itself.

sudo chown username:group directory

will only change the permission of the folder directory but will leave the files and folders inside the directory alone.

you need to use sudo to change the ownership from root to yourself.

Edit:

Note that if you use chown user: file (Note the left-out group), it will use the default group for that user.

Also You can change the group ownership of a file or directory with the command:

chgrp group_name file/directory_name

You must be a member of the group to which you are changing ownership to.

You can find group of file as follows

# ls -l file
-rw-r--r-- 1 root family 0 2012-05-22 20:03 file

# chown sujit:friends file

User 500 is just a normal user. Typically user 500 was the first user on the system, recent changes (to /etc/login.defs) has altered the minimum user id to 1000 in many distributions, so typically 1000 is now the first (non root) user.

What you may be seeing is a system which has been upgraded from the old state to the new state and still has some processes knocking about on uid 500. You can likely change it by first checking if your distro should indeed now use 1000, and if so alter the login.defs file yourself, the renumber the user account in /etc/passwd and chown/chgrp all their files, usually in /home/, then reboot.

But in answer to your question, no, you should not really be worried about this in all likelihood. It'll be showing as "500" instead of a username because o user in /etc/passwd has a uid set of 500, that's all.

Also you can show your current numbers using id i'm willing to bet it comes back as 1000 for you.

INSERT INTO from two different server database

You cannot directly copy a table into a destination server database from a different database if source db is not in your linked servers. But one way is possible that, generate scripts (schema with data) of the desired table into one table temporarily in the source server DB, then execute the script in the destination server DB to create a table with your data. Finally use INSERT INTO [DESTINATION_TABLE] select * from [TEMPORARY_SOURCE_TABLE]. After getting the data into your destination table drop the temporary one.

I found this solution when I faced the same situation. Hope this helps you too.

Which is fastest? SELECT SQL_CALC_FOUND_ROWS FROM `table`, or SELECT COUNT(*)

According to the following article: https://www.percona.com/blog/2007/08/28/to-sql_calc_found_rows-or-not-to-sql_calc_found_rows/

If you have an INDEX on your where clause (if id is indexed in your case), then it is better not to use SQL_CALC_FOUND_ROWS and use 2 queries instead, but if you don't have an index on what you put in your where clause (id in your case) then using SQL_CALC_FOUND_ROWS is more efficient.

Colspan all columns

Below is a concise es6 solution (similar to Rainbabba's answer but without the jQuery).

_x000D_
_x000D_
Array.from(document.querySelectorAll('[data-colspan-max]')).forEach(td => {_x000D_
    let table = td;_x000D_
    while (table && table.nodeName !== 'TABLE') table = table.parentNode;_x000D_
    td.colSpan = Array.from(table.querySelector('tr').children).reduce((acc, child) => acc + child.colSpan, 0);_x000D_
});
_x000D_
html {_x000D_
  font-family: Verdana;_x000D_
}_x000D_
tr > * {_x000D_
  padding: 1rem;_x000D_
  box-shadow: 0 0 8px gray inset;_x000D_
}
_x000D_
<table>_x000D_
<thead>_x000D_
  <tr>_x000D_
    <th>Header 1</th>_x000D_
    <th>Header 2</th>_x000D_
    <th>Header 3</th>_x000D_
    <th>Header 4</th>_x000D_
    <th>Header 5</th>_x000D_
    <th>Header 6</th>_x000D_
  </tr>_x000D_
</thead>_x000D_
<tbod><tr>_x000D_
  <td data-colspan-max>td will be set to full width</td>_x000D_
</tr></tbod>_x000D_
</table>
_x000D_
_x000D_
_x000D_

Mockito : doAnswer Vs thenReturn

doAnswer and thenReturn do the same thing if:

  1. You are using Mock, not Spy
  2. The method you're stubbing is returning a value, not a void method.

Let's mock this BookService

public interface BookService {
    String getAuthor();
    void queryBookTitle(BookServiceCallback callback);
}

You can stub getAuthor() using doAnswer and thenReturn.

BookService service = mock(BookService.class);
when(service.getAuthor()).thenReturn("Joshua");
// or..
doAnswer(new Answer() {
    @Override
    public Object answer(InvocationOnMock invocation) throws Throwable {
        return "Joshua";
    }
}).when(service).getAuthor();

Note that when using doAnswer, you can't pass a method on when.

// Will throw UnfinishedStubbingException
doAnswer(invocation -> "Joshua").when(service.getAuthor());

So, when would you use doAnswer instead of thenReturn? I can think of two use cases:

  1. When you want to "stub" void method.

Using doAnswer you can do some additionals actions upon method invocation. For example, trigger a callback on queryBookTitle.

BookServiceCallback callback = new BookServiceCallback() {
    @Override
    public void onSuccess(String bookTitle) {
        assertEquals("Effective Java", bookTitle);
    }
};
doAnswer(new Answer() {
    @Override
    public Object answer(InvocationOnMock invocation) throws Throwable {
        BookServiceCallback callback = (BookServiceCallback) invocation.getArguments()[0];
        callback.onSuccess("Effective Java");
        // return null because queryBookTitle is void
        return null;
    }
}).when(service).queryBookTitle(callback);
service.queryBookTitle(callback);
  1. When you are using Spy instead of Mock

When using when-thenReturn on Spy Mockito will call real method and then stub your answer. This can cause a problem if you don't want to call real method, like in this sample:

List list = new LinkedList();
List spy = spy(list);
// Will throw java.lang.IndexOutOfBoundsException: Index: 0, Size: 0
when(spy.get(0)).thenReturn("java");
assertEquals("java", spy.get(0));

Using doAnswer we can stub it safely.

List list = new LinkedList();
List spy = spy(list);
doAnswer(invocation -> "java").when(spy).get(0);
assertEquals("java", spy.get(0));

Actually, if you don't want to do additional actions upon method invocation, you can just use doReturn.

List list = new LinkedList();
List spy = spy(list);
doReturn("java").when(spy).get(0);
assertEquals("java", spy.get(0));

Why are the Level.FINE logging messages not showing?

WHY

As mentioned by @Sheepy, the reason why it doesn't work is that java.util.logging.Logger has a root logger that defaults to Level.INFO, and the ConsoleHandler attached to that root logger also defaults to Level.INFO. Therefore, in order to see the FINE (, FINER or FINEST) output, you need to set the default value of the root logger and its ConsoleHandler to Level.FINE as follows:

Logger.getLogger("").setLevel(Level.FINE);
Logger.getLogger("").getHandlers()[0].setLevel(Level.FINE);


The problem of your Update (solution)

As mentioned by @mins, you will have the messages printed twice on the console for INFO and above: first by the anonymous logger, then by its parent, the root logger which also has a ConsoleHandler set to INFO by default. To disable the root logger, you need to add this line of code: logger.setUseParentHandlers(false);

There are other ways to prevent logs from being processed by default Console handler of the root logger mentioned by @Sheepy, e.g.:

Logger.getLogger("").getHandlers()[0].setLevel( Level.OFF );

But Logger.getLogger("").setLevel( Level.OFF ); won't work because it only blocks the message passed directly to the root logger, not the message comes from a child logger. To illustrate how the Logger Hierarchy works, I draw the following diagram:

enter image description here

public void setLevel(Level newLevel) set the log level specifying which message levels will be logged by this logger. Message levels lower than this value will be discarded. The level value Level.OFF can be used to turn off logging. If the new level is null, it means that this node should inherit its level from its nearest ancestor with a specific (non-null) level value.

How to replace special characters in a string?

You can use basic regular expressions on strings to find all special characters or use pattern and matcher classes to search/modify/delete user defined strings. This link has some simple and easy to understand examples for regular expressions: http://www.vogella.de/articles/JavaRegularExpressions/article.html

Scale an equation to fit exact page width

I just had the situation that I wanted this only for lines exceeding \linewidth, that is: Squeezing long lines slightly. Since it took me hours to figure this out, I would like to add it here.

I want to emphasize that scaling fonts in LaTeX is a deadly sin! In nearly every situation, there is a better way (e.g. multline of the mathtools package). So use it conscious.

In this particular case, I had no influence on the code base apart the preamble and some lines slightly overshooting the page border when I compiled it as an eBook-scaled pdf.

\usepackage{environ}         % provides \BODY
\usepackage{etoolbox}        % provides \ifdimcomp
\usepackage{graphicx}        % provides \resizebox

\newlength{\myl}
\let\origequation=\equation
\let\origendequation=\endequation

\RenewEnviron{equation}{
  \settowidth{\myl}{$\BODY$}                       % calculate width and save as \myl
  \origequation
  \ifdimcomp{\the\linewidth}{>}{\the\myl}
  {\ensuremath{\BODY}}                             % True
  {\resizebox{\linewidth}{!}{\ensuremath{\BODY}}}  % False
  \origendequation
}

Before before After after

How to get image height and width using java?

You could use the Toolkit, no need for ImageIO

Image image = Toolkit.getDefaultToolkit().getImage(file.getAbsolutePath());
int width = image.getWidth(null);
int height = image.getHeight(null);

If you don't want to handle the loading of the image do

ImageIcon imageIcon = new ImageIcon(file.getAbsolutePath());
int height = imageIcon.getIconHeight();
int width = imageIcon.getIconWidth();

Getting "net::ERR_BLOCKED_BY_CLIENT" error on some AJAX calls

Opera Blocker and others check all files/urls in Network. Then compares to the list. It is EasyPrivacy and EasyList. If your file/url in this, your will be ban. Good luck.

So... I find FilterLists for all addBlockers!

Gradient borders

Gradient Borders from Css-Tricks: http://css-tricks.com/examples/GradientBorder/

.multbg-top-to-bottom {
  border-top: 3px solid black;
  background-image: -webkit-gradient(linear, 0 0, 0 100%, from(#000), to(transparent));
  background-image: -webkit-linear-gradient(#000, transparent);
  background-image:
      -moz-linear-gradient(#000, transparent),
      -moz-linear-gradient(#000, transparent);
  background-image:
      -o-linear-gradient(#000, transparent),
      -o-linear-gradient(#000, transparent);
  background-image: 
      linear-gradient(#000, transparent),
      linear-gradient(#000, transparent);
  -moz-background-size: 3px 100%;
  background-size: 3px 100%;
  background-position: 0 0, 100% 0;
  background-repeat: no-repeat; 
}

How to Load RSA Private Key From File

You need to convert your private key to PKCS8 format using following command:

openssl pkcs8 -topk8 -inform PEM -outform DER -in private_key_file  -nocrypt > pkcs8_key

After this your java program can read it.

Python 3 - ValueError: not enough values to unpack (expected 3, got 2)

You probably want to assign the lastname you are reading out here

lastname = sheet.cell(row=r, column=3).value

to something; currently the program just forgets it

you could do that two lines after, like so

unpaidMembers[name] = lastname, email

your program will still crash at the same place, because .items() still won't give you 3-tuples but rather something that has this structure: (name, (lastname, email))

good news is, python can handle this

for name, (lastname, email) in unpaidMembers.items():

etc.

What does /p mean in set /p?

For future reference, you can get help for any command by using the /? switch, which should explain what switches do what.

According to the set /? screen, the format for set /p is SET /P variable=[promptString] which would indicate that the p in /p is "prompt." It just prints in your example because <nul passes in a nul character which immediately ends the prompt so it just acts like it's printing. It's still technically prompting for input, it's just immediately receiving it.

/L in for /L generates a List of numbers.

From ping /?:

Usage: ping [-t] [-a] [-n count] [-l size] [-f] [-i TTL] [-v TOS]
            [-r count] [-s count] [[-j host-list] | [-k host-list]]
            [-w timeout] [-R] [-S srcaddr] [-4] [-6] target_name

Options:
    -t             Ping the specified host until stopped.
                   To see statistics and continue - type Control-Break;
                   To stop - type Control-C.
    -a             Resolve addresses to hostnames.
    -n count       Number of echo requests to send.
    -l size        Send buffer size.
    -f             Set Don't Fragment flag in packet (IPv4-only).
    -i TTL         Time To Live.
    -v TOS         Type Of Service (IPv4-only. This setting has been deprecated
                   and has no effect on the type of service field in the IP Header).
    -r count       Record route for count hops (IPv4-only).
    -s count       Timestamp for count hops (IPv4-only).
    -j host-list   Loose source route along host-list (IPv4-only).
    -k host-list   Strict source route along host-list (IPv4-only).
    -w timeout     Timeout in milliseconds to wait for each reply.
    -R             Use routing header to test reverse route also (IPv6-only).
    -S srcaddr     Source address to use.
    -4             Force using IPv4.
    -6             Force using IPv6.

Is mongodb running?

On Ubuntu (doc)

sudo systemctl status mongod

If running

? mongod.service - MongoDB Database Server
     Loaded: loaded (/lib/systemd/system/mongod.service; disabled; vendor preset: enabled)
     Active: active (running) since Wed 2020-10-14 14:13:40 UTC; 3s ago
       Docs: https://docs.mongodb.org/manual
   Main PID: 1604 (mongod)
     Memory: 210.8M
     CGroup: /system.slice/mongod.service
             +-1604 /usr/bin/mongod --config /etc/mongod.conf

If not running

? mongod.service - MongoDB Database Server
     Loaded: loaded (/lib/systemd/system/mongod.service; disabled; vendor preset: enabled)
     Active: inactive (dead)
       Docs: https://docs.mongodb.org/manual

To start mongodb

sudo systemctl start mongod

Splitting applicationContext to multiple files

I find the following setup the easiest.

Use the default config file loading mechanism of DispatcherServlet:

The framework will, on initialization of a DispatcherServlet, look for a file named [servlet-name]-servlet.xml in the WEB-INF directory of your web application and create the beans defined there (overriding the definitions of any beans defined with the same name in the global scope).

In your case, simply create a file intrafest-servlet.xml in the WEB-INF dir and don't need to specify anything specific information in web.xml.

In intrafest-servlet.xml file you can use import to compose your XML configuration.

<beans>
  <bean id="bean1" class="..."/>
  <bean id="bean2" class="..."/>

  <import resource="foo-services.xml"/>
  <import resource="foo-persistence.xml"/>
</beans>

Note that the Spring team actually prefers to load multiple config files when creating the (Web)ApplicationContext. If you still want to do it this way, I think you don't need to specify both context parameters (context-param) and servlet initialization parameters (init-param). One of the two will do. You can also use commas to specify multiple config locations.

How to unpack and pack pkg file?

In addition to what @abarnert said, I today had to find out that the default cpio utility on Mountain Lion uses a different archive format per default (not sure which), even with the man page stating it would use the old cpio/odc format. So, if anyone stumbles upon the cpio read error: bad file format message while trying to install his/her manipulated packages, be sure to include the format in the re-pack step:

find ./Foo.app | cpio -o --format odc | gzip -c > Payload

Tomcat is not running even though JAVA_HOME path is correct

I had Win 8 x86 installed. My Path variable had entry C:\Program Files\Java\jdk1.6.0_31\bin and I also had following variables:

  • JAVA_HOME : C:\Program Files\Java\jdk1.6.0_31;
  • JRE_HOME : C:\Program Files\Java\jre6;

My tomcat is installed at C:\Program Files\Apache Software Foundation\apache-tomcat-7.0.41

And still it did not worked for me.

I tried by replacing Program Files in those paths with Progra~1. I also tried by moving JAVA to another folder so that full path to it does not contain any spaces. But nothing worked.

Finally environment variables that worked for me are:

  • Kept path variable as is with full Program Files i.e. C:\Program Files\Java\jdk1.6.0_31\bin
  • JAVA_HOME : C:\Program Files\Java\jdk1.6.0_31
  • Deleted JRE_HOME

So what I did is removed JRE_HOME and removed semicolon at the end of JAVA_HOME. I think semicolon should not be an issue, though I removed it. I am giving these settings, since after a lot of googling nothing worked for me and suddenly these seem to work. You can replicate and see if it works for you.

This also worked for Win 7 x64, where

  • Path variable contained C:\Program Files (x86)\Java\jdk1.7.0_17\bin
  • JAVA_HOME is set to C:\Program Files (x86)\Java\jdk1.7.0_17 (without semicoln)

Please tell me why this worked, I know removing JRE_HOME was weird solution, but any guesses what difference it makes?

Installing PHP Zip Extension

Simply use sudo yum install php-zip

Count the cells with same color in google spreadsheet

The previous functions didn't work for me, so I've made another function that use the same logic of one of the answers above: parse the formula in the cell to find the referenced range of cells to examine and than look for the coloured cells. You can find a detailed description here: Google Script count coloured with reference, but the code is below:

function countColoured(reference) {
  var sheet = SpreadsheetApp.getActiveSheet();
  var formula = SpreadsheetApp.getActiveRange().getFormula();
  var args = formula.match(/=\w+\((.*)\)/i)[1].split('!');
  try {
    if (args.length == 1) {
      var range = sheet.getRange(args[0]);
    }
    else {
      sheet = ss.getSheetByName(args[0].replace(/'/g, ''));
      range = sheet.getRange(args[1]);
    }
  }
  catch(e) {
    throw new Error(args.join('!') + ' is not a valid range');
  }
  var c = 0;
  var numRows = range.getNumRows();
  var numCols = range.getNumColumns();
  for (var i = 1; i <= numRows; i++) {
    for (var j = 1; j <= numCols; j++) {
      c = c + ( range.getCell(i,j).getBackground() == "#ffffff" ? 0 : 1 );
    }
  }
  return c > 0 ? c : "" ;
}

jQuery: get the file name selected from <input type="file" />

<input onchange="readURL(this);"  type="file" name="userfile" />
<img src="" id="blah"/>
<script>
 function readURL(input) {
    if (input.files && input.files[0]) {
        var reader = new FileReader();

        reader.onload = function (e) {
            $('#blah')
                    .attr('src', e.target.result)
                    .width(150).height(200);
        };

        reader.readAsDataURL(input.files[0]);
        //console.log(reader);
        //alert(reader.readAsDataURL(input.files[0]));
    }
}
</script>

How to disassemble a binary executable in Linux to get the assembly code?

An interesting alternative to objdump is gdb. You don't have to run the binary or have debuginfo.

$ gdb -q ./a.out 
Reading symbols from ./a.out...(no debugging symbols found)...done.
(gdb) info functions 
All defined functions:

Non-debugging symbols:
0x00000000004003a8  _init
0x00000000004003e0  __libc_start_main@plt
0x00000000004003f0  __gmon_start__@plt
0x0000000000400400  _start
0x0000000000400430  deregister_tm_clones
0x0000000000400460  register_tm_clones
0x00000000004004a0  __do_global_dtors_aux
0x00000000004004c0  frame_dummy
0x00000000004004f0  fce
0x00000000004004fb  main
0x0000000000400510  __libc_csu_init
0x0000000000400580  __libc_csu_fini
0x0000000000400584  _fini
(gdb) disassemble main
Dump of assembler code for function main:
   0x00000000004004fb <+0>:     push   %rbp
   0x00000000004004fc <+1>:     mov    %rsp,%rbp
   0x00000000004004ff <+4>:     sub    $0x10,%rsp
   0x0000000000400503 <+8>:     callq  0x4004f0 <fce>
   0x0000000000400508 <+13>:    mov    %eax,-0x4(%rbp)
   0x000000000040050b <+16>:    mov    -0x4(%rbp),%eax
   0x000000000040050e <+19>:    leaveq 
   0x000000000040050f <+20>:    retq   
End of assembler dump.
(gdb) disassemble fce
Dump of assembler code for function fce:
   0x00000000004004f0 <+0>:     push   %rbp
   0x00000000004004f1 <+1>:     mov    %rsp,%rbp
   0x00000000004004f4 <+4>:     mov    $0x2a,%eax
   0x00000000004004f9 <+9>:     pop    %rbp
   0x00000000004004fa <+10>:    retq   
End of assembler dump.
(gdb)

With full debugging info it's even better.

(gdb) disassemble /m main
Dump of assembler code for function main:
9       {
   0x00000000004004fb <+0>:     push   %rbp
   0x00000000004004fc <+1>:     mov    %rsp,%rbp
   0x00000000004004ff <+4>:     sub    $0x10,%rsp

10        int x = fce ();
   0x0000000000400503 <+8>:     callq  0x4004f0 <fce>
   0x0000000000400508 <+13>:    mov    %eax,-0x4(%rbp)

11        return x;
   0x000000000040050b <+16>:    mov    -0x4(%rbp),%eax

12      }
   0x000000000040050e <+19>:    leaveq 
   0x000000000040050f <+20>:    retq   

End of assembler dump.
(gdb)

objdump has a similar option (-S)

Disable Laravel's Eloquent timestamps

Add this line into your model:

Overwrite existing variable $timestamps true to false

/**
 * Indicates if the model should be timestamped.
 *
 * @var bool
 */

public $timestamps = false;

Generate random numbers uniformly over an entire range

If you are able to, use Boost. I have had good luck with their random library.

uniform_int should do what you want.

Random word generator- Python

There are a number of dictionary files available online - if you're on linux, a lot of (all?) distros come with an /etc/dictionaries-common/words file, which you can easily parse (words = open('/etc/dictionaries-common/words').readlines(), eg) for use.

tsql returning a table from a function or store procedure

Use this as a template

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:      <Author,,Name>
-- Create date: <Create Date,,>
-- Description: <Description,,>
-- =============================================
CREATE FUNCTION <Table_Function_Name, sysname, FunctionName> 
(
    -- Add the parameters for the function here
    <@param1, sysname, @p1> <data_type_for_param1, , int>, 
    <@param2, sysname, @p2> <data_type_for_param2, , char>
)
RETURNS 
<@Table_Variable_Name, sysname, @Table_Var> TABLE 
(
    -- Add the column definitions for the TABLE variable here
    <Column_1, sysname, c1> <Data_Type_For_Column1, , int>, 
    <Column_2, sysname, c2> <Data_Type_For_Column2, , int>
)
AS
BEGIN
    -- Fill the table variable with the rows for your result set

    RETURN 
END
GO

That will define your function. Then you would just use it as any other table:

Select * from MyFunction(Param1, Param2, etc.)

phpmyadmin logs out after 1440 secs

If you have phpmyadmin configuration storage setup, the settings will be pulled out of your phpmyadmin.pma__userconfig table, and will override anything you have in config.inc.php. In this table, each MYSQL user can be assigned a different set of phpmyadmin settings.

How to compile a static library in Linux?

See Creating a shared and static library with the gnu compiler [gcc]

gcc -c -o out.o out.c

-c means to create an intermediary object file, rather than an executable.

ar rcs libout.a out.o

This creates the static library. r means to insert with replacement, c means to create a new archive, and s means to write an index. As always, see the man page for more info.

MVC Return Partial View as JSON

Instead of RenderViewToString I prefer a approach like

return Json(new { Url = Url.Action("Evil", model) });

then you can catch the result in your javascript and do something like

success: function(data) {
    $.post(data.Url, function(partial) { 
        $('#IdOfDivToUpdate').html(partial);
    });
}

Reset the database (purge all), then seed a database

I use rake db:reset which drops and then recreates the database and includes your seeds.rb file. http://guides.rubyonrails.org/migrations.html#resetting-the-database

Fragment onResume() & onPause() is not called on backstack

Although with different code, I experienced the same problem as the OP, because I originally used

fm.beginTransaction()
            .add(R.id.fragment_container_main, fragment)
            .addToBackStack(null)
            .commit();

instead of

fm.beginTransaction()
                .replace(R.id.fragment_container_main, fragment)
                .addToBackStack(null)
                .commit();

With "replace" the first fragment gets recreated when you return from the second fragment and therefore onResume() is also called.

Jackson - How to process (deserialize) nested JSON?

Here is a rough but more declarative solution. I haven't been able to get it down to a single annotation, but this seems to work well. Also not sure about performance on large data sets.

Given this JSON:

{
    "list": [
        {
            "wrapper": {
                "name": "Jack"
            }
        },
        {
            "wrapper": {
                "name": "Jane"
            }
        }
    ]
}

And these model objects:

public class RootObject {
    @JsonProperty("list")
    @JsonDeserialize(contentUsing = SkipWrapperObjectDeserializer.class)
    @SkipWrapperObject("wrapper")
    public InnerObject[] innerObjects;
}

and

public class InnerObject {
    @JsonProperty("name")
    public String name;
}

Where the Jackson voodoo is implemented like:

@Retention(RetentionPolicy.RUNTIME)
@JacksonAnnotation
public @interface SkipWrapperObject {
    String value();
}

and

public class SkipWrapperObjectDeserializer extends JsonDeserializer<Object> implements
        ContextualDeserializer {
    private Class<?> wrappedType;
    private String wrapperKey;

    public JsonDeserializer<?> createContextual(DeserializationContext ctxt,
            BeanProperty property) throws JsonMappingException {
        SkipWrapperObject skipWrapperObject = property
                .getAnnotation(SkipWrapperObject.class);
        wrapperKey = skipWrapperObject.value();
        JavaType collectionType = property.getType();
        JavaType collectedType = collectionType.containedType(0);
        wrappedType = collectedType.getRawClass();
        return this;
    }

    @Override
    public Object deserialize(JsonParser parser, DeserializationContext ctxt)
            throws IOException, JsonProcessingException {
        ObjectMapper mapper = new ObjectMapper();
        ObjectNode objectNode = mapper.readTree(parser);
        JsonNode wrapped = objectNode.get(wrapperKey);
        Object mapped = mapIntoObject(wrapped);
        return mapped;
    }

    private Object mapIntoObject(JsonNode node) throws IOException,
            JsonProcessingException {
        JsonParser parser = node.traverse();
        ObjectMapper mapper = new ObjectMapper();
        return mapper.readValue(parser, wrappedType);
    }
}

Hope this is useful to someone!

How to call a function after a div is ready?

inside your <div></div> element you can call the $(document).ready(function(){}); execute a command, something like

<div id="div1">
    <script>
        $(document).ready(function(){
         //do something
        });
    </script>
</div>

and you can do the same to other divs that you have. this was suitable if you loading your div via partial view

Limiting the number of characters in a JTextField

private void jTextField1KeyPressed(java.awt.event.KeyEvent evt)
{
    if(jTextField1.getText().length()>=5)
    {
        jTextField1.setText(jTextField1.getText().substring(0, 4));
    }
}

I have taken a jtextfield whose name is jTextField1, the code is in its key pressed event. I Have tested it and it works. And I am using the NetBeans IDE.

Identifying country by IP address

It's not that easy. IP adresses are not assigned to countries as such, but to companies and organizations.

But maybe this can help you out: http://www.maxmind.com/app/geolitecountry

Using os.walk() to recursively traverse directories in Python

Try this:

import os
root_name = next(os.walk("."))[0]
dir_names = next(os.walk("."))[1]
file_names = next(os.walk("."))[2]

Here I'm assuming your path as "." in which the root_file and other directories are there. So, Basically we are just iterating throughout the tree by using next() call, as our os.walk is only generative function. By doing this we can save all the Directory and file names in dir_names and file_names respectively.

Generate HTML table from 2D JavaScript array

Pure functional table without new lines (Just for fun)

const pureFunctionalTable = data => 
    [document.createElement('table')].filter(table => !table.appendChild(
        data.reduce((tbody, row) =>
            !tbody.appendChild(row.reduce((tr, cell) =>
                !tr.appendChild(document.createElement('td'))
                   .appendChild(document.createTextNode(cell)) || tr
                , document.createElement('tr'))
            ) || tbody, document.createElement('tbody'))) || table)[0];


Usage

document.body.appendChild(pureFunctionalTable([
    ['row 1, cell 1', 'row 1, cell 2'],
    ['row 2, cell 1', 'row 2, cell 2']
]));

Android:java.lang.OutOfMemoryError: Failed to allocate a 23970828 byte allocation with 2097152 free bytes and 2MB until OOM

For me, the problem was that my .png file was being de-compressed to be a really huge bitmap in memory, because the image had very large dimensions (even though the file size was tiny).

So the fix was to simply resize the image :)

How to grep (search) committed code in the Git history

If you want to browse code changes (see what actually has been changed with the given word in the whole history) go for patch mode - I found a very useful combination of doing:

git log -p
# Hit '/' for search mode.
# Type in the word you are searching.
# If the first search is not relevant, hit 'n' for next (like in Vim ;) )

Typescript es6 import module "File is not a module error"

Extended - to provide more details based on some comments

The error

Error TS2306: File 'test.ts' is not a module.

Comes from the fact described here http://exploringjs.com/es6/ch_modules.html

17. Modules

This chapter explains how the built-in modules work in ECMAScript 6.

17.1 Overview

In ECMAScript 6, modules are stored in files. There is exactly one module per file and one file per module. You have two ways of exporting things from a module. These two ways can be mixed, but it is usually better to use them separately.

17.1.1 Multiple named exports

There can be multiple named exports:

//------ lib.js ------
export const sqrt = Math.sqrt;
export function square(x) {
    return x * x;
}
export function diag(x, y) {
    return sqrt(square(x) + square(y));
}
...

17.1.2 Single default export

There can be a single default export. For example, a function:

//------ myFunc.js ------
export default function () { ··· } // no semicolon!

Based on the above we need the export, as a part of the test.js file. Let's adjust the content of it like this:

// test.js - exporting es6
export module App {
  export class SomeClass {
    getName(): string {
      return 'name';
    }
  }
  export class OtherClass {
    getName(): string {
      return 'name';
    }
  }
}

And now we can import it with these thre ways:

import * as app1 from "./test";
import app2 = require("./test");
import {App} from "./test";

And we can consume imported stuff like this:

var a1: app1.App.SomeClass  = new app1.App.SomeClass();
var a2: app1.App.OtherClass = new app1.App.OtherClass();

var b1: app2.App.SomeClass  = new app2.App.SomeClass();
var b2: app2.App.OtherClass = new app2.App.OtherClass();

var c1: App.SomeClass  = new App.SomeClass();
var c2: App.OtherClass = new App.OtherClass();

and call the method to see it in action:

console.log(a1.getName())
console.log(a2.getName())
console.log(b1.getName())
console.log(b2.getName())
console.log(c1.getName())
console.log(c2.getName())

Original part is trying to help to reduce the amount of complexity in usage of the namespace

Original part:

I would really strongly suggest to check this Q & A:

How do I use namespaces with TypeScript external modules?

Let me cite the first sentence:

Do not use "namespaces" in external modules.

Don't do this.

Seriously. Stop.

...

In this case, we just do not need module inside of test.ts. This could be the content of it adjusted test.ts:

export class SomeClass
{
    getName(): string
    {
        return 'name';
    }
}

Read more here

Export =

In the previous example, when we consumed each validator, each module only exported one value. In cases like this, it's cumbersome to work with these symbols through their qualified name when a single identifier would do just as well.

The export = syntax specifies a single object that is exported from the module. This can be a class, interface, module, function, or enum. When imported, the exported symbol is consumed directly and is not qualified by any name.

we can later consume it like this:

import App = require('./test');

var sc: App.SomeClass = new App.SomeClass();

sc.getName();

Read more here:

Optional Module Loading and Other Advanced Loading Scenarios

In some cases, you may want to only load a module under some conditions. In TypeScript, we can use the pattern shown below to implement this and other advanced loading scenarios to directly invoke the module loaders without losing type safety.

The compiler detects whether each module is used in the emitted JavaScript. For modules that are only used as part of the type system, no require calls are emitted. This culling of unused references is a good performance optimization, and also allows for optional loading of those modules.

The core idea of the pattern is that the import id = require('...') statement gives us access to the types exposed by the external module. The module loader is invoked (through require) dynamically, as shown in the if blocks below. This leverages the reference-culling optimization so that the module is only loaded when needed. For this pattern to work, it's important that the symbol defined via import is only used in type positions (i.e. never in a position that would be emitted into the JavaScript).

Phone number formatting an EditText in Android

You need to create a class:

public class PhoneTextFormatter implements TextWatcher {

    private final String TAG = this.getClass().getSimpleName();

    private EditText mEditText;

    private String mPattern;

    public PhoneTextFormatter(EditText editText, String pattern) {
        mEditText = editText;
        mPattern = pattern;
        //set max length of string
        int maxLength = pattern.length();
        mEditText.setFilters(new InputFilter[]{new InputFilter.LengthFilter(maxLength)});
    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {
        StringBuilder phone = new StringBuilder(s);

        Log.d(TAG, "join");

        if (count > 0 && !isValid(phone.toString())) {
            for (int i = 0; i < phone.length(); i++) {
                Log.d(TAG, String.format("%s", phone));
                char c = mPattern.charAt(i);

                if ((c != '#') && (c != phone.charAt(i))) {
                    phone.insert(i, c);
                }
            }

            mEditText.setText(phone);
            mEditText.setSelection(mEditText.getText().length());
        }
    }

    @Override
    public void afterTextChanged(Editable s) {

    }

    private boolean isValid(String phone)
    {
        for (int i = 0; i < phone.length(); i++) {
            char c = mPattern.charAt(i);

            if (c == '#') continue;

            if (c != phone.charAt(i)) {
                return false;
            }
        }

        return true;
    }
}

Use this as follows:

phone = view.findViewById(R.id.phone);
phone.addTextChangedListener(new PhoneTextFormatter(phone, "+7 (###) ###-####"));

How to preview git-pull without doing fetch?

You can fetch from a remote repo, see the differences and then pull or merge.

This is an example for a remote repo called origin and a branch called master tracking the remote branch origin/master:

git checkout master                                                  
git fetch                                        
git diff origin/master
git pull --rebase origin master

How to make CSS width to fill parent?

EDIT:

Those three different elements all have different rendering rules.

So for:

table#bar you need to set the width to 100% otherwise it will be only be as wide as it determines it needs to be. However, if the table rows total width is greater than the width of bar it will expand to its needed width. IF i recall you can counteract this by setting display: block !important; though its been awhile since ive had to fix that. (im sure someone will correct me if im wrong).

textarea#bar i beleive is a block level element so it will follow the rules the same as the div. The only caveat here is that textarea take an attributes of cols and rows which are measured in character columns. If this is specified on the element it will override the width specified by the css.

input#bar is an inline element, so by default you cant assign it width. However the similar to textarea's cols attribute, it has a size attribute on the element that can determine width. That said, you can always specifiy a width by using display: block; in your css for it. Then it will follow the same rendering rules as the div.

td#foo will be rendered as a table-cell which has some craziness to it. Bottom line here is that for your purposes its going to act just like div#foo as far as restricting the width of its contents. The only issue here is going to be potential unwrappable text in the column somewhere which would make it ignore your width setting. Also all cells in the column are going to get the width of the widest cell.


Thats the default behavior of block level element - ie. if width is auto (the default) then it will be 100% of the inner width of the containing element. so in essence:

#foo {width: 800px;}
#bar {padding-left: 2px; padding-right: 2px; margin-left: 2px; margin-right: 2px;}

will give you exactly what you want.

How to change an input button image using CSS?

Perhaps you could just import a .js file as well and have the image replacement there, in JavaScript.

How to configure "Shorten command line" method for whole project in IntelliJ

If you use JDK version from 9+, you should select

Run > Edit Configurations... > Select JUnit template.

Then, select @argfile (Java 9+) as in the image below. Please try it. Good luck friends.

enter image description here

How to write LaTeX in IPython Notebook?

I developed prettyPy, which offers a nice way to print equation. Unfortunately, it's not performant and needs testing.

Example:

enter image description here

Granted, sympy is a great alternative and although prettyPy doesn't allow for evaluating expressions, variable initialization is not required.

How to kill a while loop with a keystroke?

There is always sys.exit().

The system library in Python's core library has an exit function which is super handy when prototyping. The code would be along the lines of:

import sys

while True:
    selection = raw_input("U: Create User\nQ: Quit")
    if selection is "Q" or selection is "q":
        print("Quitting")
        sys.exit()
    if selection is "U" or selection is "u":
        print("User")
        #do_something()

jQuery Datepicker close datepicker after selected date

There is another code that's works for me (jQuery).

_x000D_
_x000D_
$(".datepicker").datepicker({_x000D_
    format: "dd/mm/yyyy",_x000D_
    autoHide: true_x000D_
    })
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/datepicker/0.6.5/datepicker.js"></script>_x000D_
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/datepicker/0.6.5/datepicker.css" />_x000D_
Date: <input type="text" readonly="true" class="datepicker">
_x000D_
_x000D_
_x000D_

Merge Two Lists in R

In general one could,

merge_list <- function(...) by(v<-unlist(c(...)),names(v),base::c)

Note that the by() solution returns an attributed list, so it will print differently, but will still be a list. But you can get rid of the attributes with attr(x,"_attribute.name_")<-NULL. You can probably also use aggregate().

Disable Copy or Paste action for text box?

Best way to do this is to add a data attribute to the field (textbox) where you want to avoid the cut,copy and paste.

Just create a method for the same which is as follows :-

function ignorePaste() {

$("[data-ignorepaste]").bind("cut copy paste", function (e) {
            e.preventDefault(); //prevent the default behaviour 
        });

};

Then once when you add the above code simply add the data attribute to the field where you want to ignore cut copy paste. in our case your add a data attribute to confirm email text box as below :-

Confirm Email: <input type="textbox" id= "confirmEmail" data-ignorepaste=""/>

Call the method ignorePaste()

So in this way you will be able to use this throughout the application, all you need to do is just add the data attribute where you want to ignore cut copy paste

https://jsfiddle.net/0ac6pkbf/21/

Getting Exception(org.apache.poi.openxml4j.exception - no content type [M1.13]) when reading xlsx file using Apache POI?

Try saving the file as Excel Workbook ONLY. NOT any other format. It worked for me. I was getting the same error.

How to repeat a char using printf?

There is no such thing. You'll have to either write a loop using printf or puts, or write a function that copies the string count times into a new string.

How do I clear this setInterval inside a function?

Simplest way I could think of: add a class.

Simply add a class (on any element) and check inside the interval if it's there. This is more reliable, customisable and cross-language than any other way, I believe.

_x000D_
_x000D_
var i = 0;_x000D_
this.setInterval(function() {_x000D_
  if(!$('#counter').hasClass('pauseInterval')) { //only run if it hasn't got this class 'pauseInterval'_x000D_
    console.log('Counting...');_x000D_
    $('#counter').html(i++); //just for explaining and showing_x000D_
  } else {_x000D_
    console.log('Stopped counting');_x000D_
  }_x000D_
}, 500);_x000D_
_x000D_
/* In this example, I'm adding a class on mouseover and remove it again on mouseleave. You can of course do pretty much whatever you like */_x000D_
$('#counter').hover(function() { //mouse enter_x000D_
    $(this).addClass('pauseInterval');_x000D_
  },function() { //mouse leave_x000D_
    $(this).removeClass('pauseInterval');_x000D_
  }_x000D_
);_x000D_
_x000D_
/* Other example */_x000D_
$('#pauseInterval').click(function() {_x000D_
  $('#counter').toggleClass('pauseInterval');_x000D_
});
_x000D_
body {_x000D_
  background-color: #eee;_x000D_
  font-family: Calibri, Arial, sans-serif;_x000D_
}_x000D_
#counter {_x000D_
  width: 50%;_x000D_
  background: #ddd;_x000D_
  border: 2px solid #009afd;_x000D_
  border-radius: 5px;_x000D_
  padding: 5px;_x000D_
  text-align: center;_x000D_
  transition: .3s;_x000D_
  margin: 0 auto;_x000D_
}_x000D_
#counter.pauseInterval {_x000D_
  border-color: red;  _x000D_
}
_x000D_
<!-- you'll need jQuery for this. If you really want a vanilla version, ask -->_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
_x000D_
_x000D_
<p id="counter">&nbsp;</p>_x000D_
<button id="pauseInterval">Pause/unpause</button></p>
_x000D_
_x000D_
_x000D_

use of entityManager.createNativeQuery(query,foo.class)

Here is a DB2 Stored Procidure that receive a parameter

SQL

CREATE PROCEDURE getStateByName (IN StateName VARCHAR(128))
DYNAMIC RESULT SETS 1
P1: BEGIN
    -- Declare cursor
    DECLARE State_Cursor CURSOR WITH RETURN for
    -- #######################################################################
    -- # Replace the SQL statement with your statement.
    -- # Note: Be sure to end statements with the terminator character (usually ';')
    -- #
    -- # The example SQL statement SELECT NAME FROM SYSIBM.SYSTABLES
    -- # returns all names from SYSIBM.SYSTABLES.
    -- ######################################################################
    SELECT * FROM COUNTRY.STATE
    WHERE PROVINCE_NAME LIKE UPPER(stateName);
    -- Cursor left open for client application
    OPEN Province_Cursor;
END P1

Java

//Country is a db2 scheme

//Now here is a java Entity bean Method

public List<Province> getStateByName(String stateName) throws Exception {

    EntityManager em = this.em;
    List<State> states= null;
    try {
        Query query = em.createNativeQuery("call NGB.getStateByName(?1)", Province.class);
        query.setParameter(1, provinceName);
        states= (List<Province>) query.getResultList();
    } catch (Exception ex) {
        throw ex;
    }

    return states;
}

How can I get the max (or min) value in a vector?

If you want to use the function std::max_element(), the way you have to do it is:

double max = *max_element(vector.begin(), vector.end());
cout<<"Max value: "<<max<<endl;

I hope this can help.

Storing image in database directly or as base64 data?

I recommend looking at modern databases like NoSQL and also I agree with user1252434's post. For instance I am storing a few < 500kb PNGs as base64 on my Mongo db with binary set to true with no performance hit at all. Mongo can be used to store large files like 10MB videos and that can offer huge time saving advantages in metadata searches for those videos, see storing large objects and files in mongodb.

Why do I need to override the equals and hashCode methods in Java?

To help you check for duplicate Objects, we need a custom equals and hashCode.

Since hashcode always returns a number its always fast to retrieve an object using a number rather than an alphabetic key. How will it do? Assume we created a new object by passing some value which is already available in some other object. Now the new object will return the same hash value as of another object because the value passed is same. Once the same hash value is returned, JVM will go to the same memory address every time and if in case there are more than one objects present for the same hash value it will use equals() method to identify the correct object.

How do you access the value of an SQL count () query in a Java program

It's similar to above but you can try like

public Integer count(String tableName) throws CrateException {
        String query = String.format("Select count(*) as size from %s", tableName);
        try (Statement s = connection.createStatement()) {
            try (ResultSet resultSet = queryExecutor.executeQuery(s, query)) {
                Preconditions.checkArgument(resultSet.next(), "Result set is empty");
                return resultSet.getInt("size");
            }
        } catch (SQLException e) {
            throw new CrateException(e);
        }
    }
}

Remove commas from the string using JavaScript

This is the simplest way to do it.

let total = parseInt(('100,000.00'.replace(',',''))) + parseInt(('500,000.00'.replace(',','')))

Prevent onmouseout when hovering child element of the parent absolute div WITHOUT jQuery

There are a simple way to make it work. The element and all childs you set a same class name, then:

element.onmouseover = function(event){
 if (event.target.className == "name"){
 /*code*/
 }
}

Double decimal formatting in Java

new DecimalFormat("#0.00").format(4.0d);

How to change Git log date formats

Be aware of the "date=iso" format: it isn't exactly ISO 8601.
See commit "466fb67" from Beat Bolli (bbolli), for Git 2.2.0 (November 2014)

pretty: provide a strict ISO 8601 date format

Git's "ISO" date format does not really conform to the ISO 8601 standard due to small differences, and it cannot be parsed by ISO 8601-only parsers, e.g. those of XML toolchains.

The output from "--date=iso" deviates from ISO 8601 in these ways:

  • a space instead of the T date/time delimiter
  • a space between time and time zone
  • no colon between hours and minutes of the time zone

Add a strict ISO 8601 date format for displaying committer and author dates.
Use the '%aI' and '%cI' format specifiers and add '--date=iso-strict' or '--date=iso8601-strict' date format names.

See this thread for discussion.

Finding sum of elements in Swift array

Keep it simple...

var array = [1, 2, 3, 4, 5, 6, 7, 9, 0]
var n = 0
for i in array {
    n += i
}
print("My sum of elements is: \(n)")

Output:

My sum of elements is: 37

Heroku: How to push different local Git branches to Heroku/master

Also note that if your using the git flow system and your feature branch might be called

feature/mobile_additions

and with a git remote called stagingtwo, then the command to push to heroku would be

git push stagingtwo feature/mobile_additions:master

Undefined Symbols for architecture x86_64: Compiling problems

There's no mystery here, the linker is telling you that you haven't defined the missing symbols, and you haven't.

Similarity::Similarity() or Similarity::~Similarity() are just missing and you have defined the others incorrectly,

void Similarity::readData(Scanner& inStream){
}

not

void readData(Scanner& inStream){
}

etc. etc.

The second one is a function called readData, only the first is the readData method of the Similarity class.

To be clear about this, in Similarity.h

void readData(Scanner& inStream);

but in Similarity.cpp

void Similarity::readData(Scanner& inStream){
}

How do you get the width and height of a multi-dimensional array?

// Two-dimensional GetLength example.
int[,] two = new int[5, 10];
Console.WriteLine(two.GetLength(0)); // Writes 5
Console.WriteLine(two.GetLength(1)); // Writes 10

What difference between the DATE, TIME, DATETIME, and TIMESTAMP Types

DATE: It is used for values with a date part but no time part. MySQL retrieves and displays DATE values in YYYY-MM-DD format. The supported range is 1000-01-01 to 9999-12-31.

DATETIME: It is used for values that contain both date and time parts. MySQL retrieves and displays DATETIME values in YYYY-MM-DD HH:MM:SS format. The supported range is 1000-01-01 00:00:00 to 9999-12-31 23:59:59.

TIMESTAMP: It is also used for values that contain both date and time parts, and includes the time zone. TIMESTAMP has a range of 1970-01-01 00:00:01 UTC to 2038-01-19 03:14:07 UTC.

TIME: Its values are in HH:MM:SS format (or HHH:MM:SS format for large hours values). TIME values may range from -838:59:59 to 838:59:59. The hours part may be so large because the TIME type can be used not only to represent a time of day (which must be less than 24 hours), but also elapsed time or a time interval between two events (which may be much greater than 24 hours, or even negative).

How to convert Rows to Columns in Oracle?

You can do it with a pivot query, like this:

select * from (
   select LOAN_NUMBER, DOCUMENT_TYPE, DOCUMENT_ID
   from my_table t
)
pivot 
(
   MIN(DOCUMENT_ID)
   for DOCUMENT_TYPE in ('Voters ID','Pan card','Drivers licence')
)

Here is a demo on sqlfiddle.com.

How can I copy data from one column to another in the same table?

This will update all the rows in that columns if safe mode is not enabled.

UPDATE table SET columnB = columnA;

If safe mode is enabled then you will need to use a where clause. I use primary key as greater than 0 basically all will be updated

UPDATE table SET columnB = columnA where table.column>0;

List of enum values in java

An enum is just another class in Java, it should be possible.

More accurately, an enum is an instance of Object: http://docs.oracle.com/javase/6/docs/api/java/lang/Enum.html

So yes, it should work.

Android: Storing username and password?

You can also look at the SampleSyncAdapter sample from the SDK. It may help you.

How to find if an array contains a string

Using the code from my answer to a very similar question:

Sub DoSomething()
Dim Mainfram(4) As String
Dim cell As Excel.Range

Mainfram(0) = "apple"
Mainfram(1) = "pear"
Mainfram(2) = "orange"
Mainfram(3) = "fruit"

For Each cell In Selection
  If IsInArray(cell.Value, MainFram) Then
    Row(cell.Row).Style = "Accent1"
  End If
Next cell

End Sub

Function IsInArray(stringToBeFound As String, arr As Variant) As Boolean
  IsInArray = (UBound(Filter(arr, stringToBeFound)) > -1)
End Function

How can I set the form action through JavaScript?

Do as Rabbott says, or if you refuse jQuery:

<script type="text/javascript">
function get_action() { // inside script tags
  return form_action;
}
</script>

<form action="" onsubmit="this.action=get_action();">
...
</form>

How to remove a field completely from a MongoDB document?

db.example.updateMany({},{"$unset":{"tags.words":1}})

We can also use this to update multiple documents.

Print PHP Call Stack

Use debug_backtrace to get a backtrace of what functions and methods had been called and what files had been included that led to the point where debug_backtrace has been called.

It says that TypeError: document.getElementById(...) is null

It means that element with id passed to getElementById() does not exist.

Loop through Map in Groovy?

Quite simple with a closure:

def map = [
           'iPhone':'iWebOS',
           'Android':'2.3.3',
           'Nokia':'Symbian',
           'Windows':'WM8'
           ]

map.each{ k, v -> println "${k}:${v}" }

How to cast Object to its actual type?

Cast it to its real type if you now the type for example it is oriented from class named abc. You can call your function in this way :

(abc)(obj)).MyFunction();

if you don't know the function it can be done in a different way. Not easy always. But you can find it in some way by it's signature. If this is your case, you should let us know.

Run command on the Ansible host

ansible your_server_name -i custom_inventory_file_name -m -a "uptime"

The default module is command module, hence command keyword is not required.

If you need to issue any command with elevated privileges use -b at the end of the same command.

ansible your_server_name -i custom_inventory_file_name -m -a "uptime" -b

How to auto-size an iFrame?

In IE 5.5+, you can use the contentWindow property:

iframe.height = iframe.contentWindow.document.scrollHeight;

In Netscape 6 (assuming firefox as well), contentDocument property:

iframe.height = iframe.contentDocument.scrollHeight

adding classpath in linux

For linux users, and to sum up and add to what others have said here, you should know the following:

  1. Global variables are not evil. $CLASSPATH is specifically what Java uses to look through multiple directories to find all the different classes it needs for your script (unless you explicitly tell it otherwise with the -cp override).

  2. The colon (":") character separates the different directories. There is only one $CLASSPATH and it has all the directories in it. So, when you run "export CLASSPATH=...." you want to include the current value "$CLASSPATH" in order to append to it. For example:

    export CLASSPATH=.
    export CLASSPATH=$CLASSPATH:/usr/share/java/mysql-connector-java-5.1.12.jar
    

    In the first line above, you start CLASSPATH out with just a simple 'dot' which is the path to your current working directory. With that, whenever you run java it will look in the current working directory (the one you're in) for classes. In the second line above, $CLASSPATH grabs the value that you previously entered (.) and appends the path to a mysql dirver. Now, java will look for the driver AND for your classes.

  3. echo $CLASSPATH
    

    is super handy, and what it returns should read like a colon-separated list of all the directories you want java looking in for what it needs to run your script.

  4. Tomcat does not use CLASSPATH. Read what to do about that here: https://tomcat.apache.org/tomcat-8.0-doc/class-loader-howto.html

Specify the from user when sending email using the mail command

Here's a solution.

The second easiest solution after -r (which is to specify a From: header and separate it from the body by a newline like this

 $mail -s "Subject" [email protected]
 From: Joel <[email protected]>

 Hi!
 .

works in only a few mail versions, don't know what version redhat carries).

PS: Most versions of mail suck!

Cannot connect to MySQL 4.1+ using old authentication

If you do not have Administrator access to the MySQL Server configuration (i.e. you are using a hosting service), then there are 2 options to get this to work:

1) Request that the old_passwords option be set to false on the MySQL server

2) Downgrade PHP to 5.2.2 until option 1 occurs.

From what I've been able to find, the issue seems to be with how the MySQL account passwords are stored and if the 'old_passwords' setting is set to true. This causes a compatibility issue between MySQL and newer versions of PHP (5.3+) where PHP attempts to connect using a 41-character hash but the MySQL server is still storing account passwords using a 16-character hash.

This incompatibility was brought about by the changing of the hashing method used in MySQL 4.1 which allows for both short and long hash lengths (Scenario 2 on this page from the MySQL site: http://dev.mysql.com/doc/refman/5.5/en/password-hashing.html) and the inclusion of the MySQL Native Driver in PHP 5.3 (backwards compatibility issue documented on bullet 7 of this page from the PHP documentation: http://www.php.net/manual/en/migration53.incompatible.php).

Kotlin: How to get and set a text to TextView in Android using Kotlin?

Yes its late - but may help someone on reference

xml with EditText, Button and TextView

onClick on Button will update the value from EditText to TextView

        <EditText
            android:id="@+id/et_id"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"/>

        <Button
            android:id="@+id/btn_submit_id"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"/>

        <TextView
            android:id="@+id/txt_id"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"/>

Look at the code do the action in your class

Don't need to initialize the id's of components like in Java. You can do it by their xml Id's

override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_sample)

        btn_submit_id.setOnClickListener {
            txt_id.setText(et_id.text);
        }
    }

also you can set value in TextView like,

textview.text = "your value"

jQuery: How can I create a simple overlay?

An overlay is, simply put, a div that stays fixed on the screen (no matter if you scroll) and has some sort of opacity.

This will be your CSS for cross browser opacity of 0.5:

#overlay {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background-color: #000;
    filter:alpha(opacity=50);
    -moz-opacity:0.5;
    -khtml-opacity: 0.5;
    opacity: 0.5;
    z-index: 10000;
}

This will be your jQuery code (no UI needed). You're just going to create a new element with the ID #overlay. Creating and destroying the DIV should be all you need.

var overlay = jQuery('<div id="overlay"> </div>');
overlay.appendTo(document.body)

For performance reasons you might wanna have the DIV hidden and setting the display to block and none as you need it or not.

Hope it helps!

Edit: As @Vitaly so well put it, be sure to check your DocType. Read more on the comments on his findings..

Win32Exception (0x80004005): The wait operation timed out

In our case we were able to narrow the cause down to a number of views which had WITH SCHEMABINDING on them. Although this is supposed to improve performance it was resulting in an awful query plan (doing a single record update on a table which was being referenced by these views was taking nearly 2 seconds of elapsed time). Removing WITH SCHEMABINDING has meant all is running smoothly again and the "wait operation timed out" errors have gone.

Adding sheets to end of workbook in Excel (normal method not working?)

Try this

mainWB.Sheets.Add(After:=mainWB.Sheets(mainWB.Sheets.Count)).Name = new_sheet_name

javax.faces.application.ViewExpiredException: View could not be restored

When our page is idle for x amount of time the view will expire and throw javax.faces.application.ViewExpiredException to prevent this from happening one solution is to create CustomViewHandler that extends ViewHandler and override restoreView method all the other methods are being delegated to the Parent

import java.io.IOException;
import javax.faces.FacesException;
import javax.faces.application.ViewHandler;
import javax.faces.component.UIViewRoot;
import javax.faces.context.FacesContext;
import javax.servlet.http.HttpServletRequest;

public class CustomViewHandler extends ViewHandler {
    private ViewHandler parent;

    public CustomViewHandler(ViewHandler parent) {
        //System.out.println("CustomViewHandler.CustomViewHandler():Parent View Handler:"+parent.getClass());
        this.parent = parent;
    }

    @Override 
    public UIViewRoot restoreView(FacesContext facesContext, String viewId) {
    /**
     * {@link javax.faces.application.ViewExpiredException}. This happens only  when we try to logout from timed out pages.
     */
        UIViewRoot root = null;
        root = parent.restoreView(facesContext, viewId);
        if(root == null) {
            root = createView(facesContext, viewId);
        }
        return root;
    }

    @Override
    public Locale calculateLocale(FacesContext facesContext) {
        return parent.calculateLocale(facesContext);
    }

    @Override
    public String calculateRenderKitId(FacesContext facesContext) {
        String renderKitId = parent.calculateRenderKitId(facesContext);
        //System.out.println("CustomViewHandler.calculateRenderKitId():RenderKitId: "+renderKitId);
        return renderKitId;
    }

    @Override
    public UIViewRoot createView(FacesContext facesContext, String viewId) {
        return parent.createView(facesContext, viewId);
    }

    @Override
    public String getActionURL(FacesContext facesContext, String actionId) {
        return parent.getActionURL(facesContext, actionId);
    }

    @Override
    public String getResourceURL(FacesContext facesContext, String resId) {
        return parent.getResourceURL(facesContext, resId);
    }

    @Override
    public void renderView(FacesContext facesContext, UIViewRoot viewId) throws IOException, FacesException {
        parent.renderView(facesContext, viewId);
    }

    @Override
    public void writeState(FacesContext facesContext) throws IOException {
        parent.writeState(facesContext);
    }

    public ViewHandler getParent() {
        return parent;
    }

}   

Then you need to add it to your faces-config.xml

<application>
    <view-handler>com.demo.CustomViewHandler</view-handler>
</application>

Thanks for the original answer on the below link: http://www.gregbugaj.com/?p=164

Hide Spinner in Input Number - Firefox 29

Faced the same issue post Firefox update to 29.0.1, this is also listed out here https://bugzilla.mozilla.org/show_bug.cgi?id=947728

Solutions: They(Mozilla guys) have fixed this by introducing support for "-moz-appearance" for <input type="number">. You just need to have a style associated with your input field with "-moz-appearance:textfield;".

I prefer the CSS way E.g.:-

.input-mini{
-moz-appearance:textfield;}

Or

You can do it inline as well:

<input type="number" style="-moz-appearance: textfield">

How can you create multiple cursors in Visual Studio Code

Alt + Click works in OSX. Code Version 1.14.2

How to get row index number in R?

Perhaps this complementary example of "match" would be helpful.

Having two datasets:

first_dataset <- data.frame(name = c("John", "Luke", "Simon", "Gregory", "Mary"),
                            role = c("Audit", "HR", "Accountant", "Mechanic", "Engineer"))

second_dataset <- data.frame(name = c("Mary", "Gregory", "Luke", "Simon"))

If the name column contains only unique across collection values (across whole collection) then you can access row in other dataset by value of index returned by match

name_mapping <- match(second_dataset$name, first_dataset$name)

match returns proper row indexes of names in first_dataset from given names from second: 5 4 2 1 example here - accesing roles from first dataset by row index (by given name value)

for(i in 1:length(name_mapping)) {
    role <- as.character(first_dataset$role[name_mapping[i]])   
    second_dataset$role[i] = role
}

===

second dataset with new column:
     name       role
1    Mary   Engineer
2 Gregory   Mechanic
3    Luke Supervisor
4   Simon Accountant

How do I create a round cornered UILabel on the iPhone?

Swift 3

If you want rounded label with background color, in addition to most of the other answers, you need to set layer's background color as well. It does not work when setting view background color.

label.layer.cornerRadius = 8
label.layer.masksToBounds = true
label.layer.backgroundColor = UIColor.lightGray.cgColor

If you are using auto layout, want some padding around the label and do not want to set the size of the label manually, you can create UILabel subclass and override intrinsincContentSize property:

class LabelWithPadding: UILabel {
    override var intrinsicContentSize: CGSize {
        let defaultSize = super.intrinsicContentSize
        return CGSize(width: defaultSize.width + 12, height: defaultSize.height + 8)
    }
}

To combine the two you will also need to set label.textAlignment = center, otherwise the text would be left aligned.

How to vertically align <li> elements in <ul>?

I had the same problem. Try this.

<nav>
    <ul>
        <li><a href="#">AnaSayfa</a></li>
        <li><a href="#">Hakkimizda</a></li>
        <li><a href="#">Iletisim</a></li>
    </ul>
</nav>
@charset "utf-8";

nav {
    background-color: #9900CC;
    height: 80px;
    width: 400px;
}

ul {
    list-style: none;
    float: right;
    margin: 0;
}

li {
    float: left;
    width: 100px;
    line-height: 80px;
    vertical-align: middle;
    text-align: center;
    margin: 0;
}

nav li a {
    width: 100px;
    text-decoration: none;
    color: #FFFFFF;
}

Get selected text from a drop-down list (select box) using jQuery

This code worked for me.

$("#yourdropdownid").children("option").filter(":selected").text();

How do I edit $PATH (.bash_profile) on OSX?

Determine which shell you're using by typing echo $SHELL in Terminal.

Then open/create correct rc file. For Bash it's $HOME/.bash_profile or $HOME/.bashrc. For Z shell it's $HOME/.zshrc.

Add this line to the file end:

export PATH="$PATH:/your/new/path"

To verify, refresh variables by restarting Terminal or typing source $HOME/.<rc file> and then do echo $PATH

Entry point for Java applications: main(), init(), or run()?

as a beginner, i import acm packages, and in this package, run() starts executing of a thread, init() initialize the Java Applet.

Facebook Javascript SDK Problem: "FB is not defined"

Use a setTimeout, because sometimes the FB.init takes some time to get declared

function testAPI() {
     console.log('Welcome!  Fetching your information.... ');
     FB.api('/me', function(response) {
         console.log('Good to see you, ' + response.name + '.');
     });
}
function login() {
    FB.login(function(response) {
        if (response.authResponse) {
            testAPI();
        } else {
            // cancelled
        }
    });
}
setTimeout(function() {
    login();
},2000);

Passing null arguments to C# methods

From C# 2.0:

private void Example(int? arg1, int? arg2)
{
    if(arg1 == null)
    {
        //do something
    }
    if(arg2 == null)
    {
        //do something else
    }
}

How to create a temporary directory/folder in Java?

I got the same problem so this is just another answer for those who are interested, and it's similar to one of the above:

public static final String tempDir = System.getProperty("java.io.tmpdir")+"tmp"+System.nanoTime();
static {
    File f = new File(tempDir);
    if(!f.exists())
        f.mkdir();
}

And for my application, I decided that to add in a option to clear the temp on exit so I added in a shut-down hook:

Runtime.getRuntime().addShutdownHook(new Thread() {
        @Override
        public void run() {
            //stackless deletion
            String root = MainWindow.tempDir;
            Stack<String> dirStack = new Stack<String>();
            dirStack.push(root);
            while(!dirStack.empty()) {
                String dir = dirStack.pop();
                File f = new File(dir);
                if(f.listFiles().length==0)
                    f.delete();
                else {
                    dirStack.push(dir);
                    for(File ff: f.listFiles()) {
                        if(ff.isFile())
                            ff.delete();
                        else if(ff.isDirectory())
                            dirStack.push(ff.getPath());
                    }
                }
            }
        }
    });

The method delete all subdirs and files before deleting the temp, without using the callstack (which is totally optional and you could do it with recursion at this point), but I want to be on the safe side.

How can I multiply all items in a list together with Python?

This is my code:

def product_list(list_of_numbers):
    xxx = 1
    for x in list_of_numbers:
        xxx = xxx*x
    return xxx

print(product_list([1,2,3,4]))

result : ('1*1*2*3*4', 24)

Using 'starts with' selector on individual class names

While the top answer here is a workaround for the asker's particular case, if you're looking for a solution to actually using 'starts with' on individual class names:

You can use this custom jQuery selector, which I call :acp() for "A Class Prefix." Code is at the bottom of this post.

var test = $('div:acp("starting_text")');

This will select any and all <div> elements that have at least one class name beginning with the given string ("starting_text" in this example), regardless of whether that class is at the beginning or elsewhere in the class attribute strings.

<div id="1" class="apple orange lemon" />
<div id="2" class="orange applelemon banana" />
<div id="3" class="orange lemon apple" />
<div id="4" class="lemon orangeapple" />
<div id="5" class="lemon orange" />

var startsWithapp = $('div:acp("app")');

This will return elements 1, 2, and 3, but not 4 or 5.

Here's the declaration for the :acp custom selector, which you can put anywhere:

$(function(){
    $.expr[":"].acp = function(elem, index, m){
          var regString = '\\b' + m[3];
          var reg = new RegExp(regString, "g");
          return elem.className.match(reg);
    }
});

I made this because I do a lot of GreaseMonkey hacking of websites on which I have no backend control, so I often need to find elements with class names that have dynamic suffixes. It's been very useful.

How can I find the latitude and longitude from address?

public void goToLocationFromAddress(String strAddress) {
    //Create coder with Activity context - this
    Geocoder coder = new Geocoder(this);
    List<Address> address;

    try {
        //Get latLng from String
        address = coder.getFromLocationName(strAddress, 5);

        //check for null
        if (address != null) {

            //Lets take first possibility from the all possibilities.
            try {
                Address location = address.get(0);
                LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());

                //Animate and Zoon on that map location
                mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
                mMap.animateCamera(CameraUpdateFactory.zoomTo(15));
            } catch (IndexOutOfBoundsException er) {
                Toast.makeText(this, "Location isn't available", Toast.LENGTH_SHORT).show();
            }

        }


    } catch (IOException e) {
        e.printStackTrace();
    }
}

Chart.js v2 - hiding grid lines

OK, nevermind.. I found the trick:

    scales: {
      yAxes: [
        {
          gridLines: {
                lineWidth: 0
            }
        }
      ]
    }

How-to turn off all SSL checks for postman for a specific site

This is not the exact answer to this question, but those who are not able to find setting popup. Their is two ways to open setting pop up.

  1. Way 1

  2. Way 2

Removing all line breaks and adding them after certain text

You can also go to Notepad++ and do the following steps:

Edit->LineOperations-> Remove Empty Lines or Remove Empty Lines(Containing blank characters)

What does "use strict" do in JavaScript, and what is the reasoning behind it?

When adding "use strict";, the following cases will throw a SyntaxError before the script is executing:

  • Paving the way for future ECMAScript versions, using one of the newly reserved keywords (in prevision for ECMAScript 6): implements, interface, let, package, private, protected, public, static, and yield.

  • Declaring function in blocks

    if(a<b){ function f(){} }
    
  • Octal syntax

    var n = 023;
    
  • this point to the global object.

     function f() {
          "use strict";
          this.a = 1;
     };
     f(); 
    
  • Declaring twice the same name for a property name in an object literal

     {a: 1, b: 3, a: 7} 
    

    This is no longer the case in ECMAScript 6 (bug 1041128).

  • Declaring two function arguments with the same name function

    f(a, b, b){}
    
  • Setting a value to an undeclared variable

    function f(x){
       "use strict";
       var a = 12;
       b = a + x*35; // error!
    }
    f();
    
  • Using delete on a variable name delete myVariable;

  • Using eval or arguments as variable or function argument name

    "use strict";
    arguments++;
    var obj = { set p(arguments) { } };
    try { } catch (arguments) { }
    function arguments() { } 
    

Sources:

How do you set a JavaScript onclick event to a class with css

Here is my solution through CSS, It does not use any JavaScript at all

HTML:

<a href="#openModal">Open Modal</a>

<div id="openModal" class="modalDialog">
        <div>   <a href="#close" title="Close" class="close">X</a>

                <h2>Modal Box</h2>

            <p>This is a sample modal box that can be created using the powers of CSS3.</p>
            <p>You could do a lot of things here like have a pop-up ad that shows when your website loads, or create a login/register form for users.</p>
        </div>
    </div>

CSS:

.modalDialog {
    position: fixed;
    font-family: Arial, Helvetica, sans-serif;
    top: 0;
    right: 0;
    bottom: 0;
    left: 0;
    background: rgba(0, 0, 0, 0.8);
    z-index: 99999;
    opacity:0;
    -webkit-transition: opacity 400ms ease-in;
    -moz-transition: opacity 400ms ease-in;
    transition: opacity 400ms ease-in;
    pointer-events: none;
}
.modalDialog:target {
    opacity:1;
    pointer-events: auto;
}
.modalDialog > div {
    width: 400px;
    position: relative;
    margin: 10% auto;
    padding: 5px 20px 13px 20px;
    border-radius: 10px;
    background: #fff;
    background: -moz-linear-gradient(#fff, #999);
    background: -webkit-linear-gradient(#fff, #999);
    background: -o-linear-gradient(#fff, #999);
}
.close {
    background: #606061;
    color: #FFFFFF;
    line-height: 25px;
    position: absolute;
    right: -12px;
    text-align: center;
    top: -10px;
    width: 24px;
    text-decoration: none;
    font-weight: bold;
    -webkit-border-radius: 12px;
    -moz-border-radius: 12px;
    border-radius: 12px;
    -moz-box-shadow: 1px 1px 3px #000;
    -webkit-box-shadow: 1px 1px 3px #000;
    box-shadow: 1px 1px 3px #000;
}
.close:hover {
    background: #00d9ff;
}

CSS alert No JavaScript Just pure HTML and CSS

I believe that it will do the trick for you as it has for me

How to add to the end of lines containing a pattern with sed or awk?

This works for me

sed '/^all:/ s/$/ anotherthing/' file

The first part is a pattern to find and the second part is an ordinary sed's substitution using $ for the end of a line.

If you want to change the file during the process, use -i option

sed -i '/^all:/ s/$/ anotherthing/' file

Or you can redirect it to another file

sed '/^all:/ s/$/ anotherthing/' file > output

How to set a header in an HTTP response?

Header fields are not copied to subsequent requests. You should use either cookie for this (addCookie method) or store "REMOTE_USER" in session (which you can obtain with getSession method).

How to iterate through property names of Javascript object?

In JavaScript 1.8.5, Object.getOwnPropertyNames returns an array of all properties found directly upon a given object.

Object.getOwnPropertyNames ( obj )

and another method Object.keys, which returns an array containing the names of all of the given object's own enumerable properties.

Object.keys( obj )

I used forEach to list values and keys in obj, same as for (var key in obj) ..

Object.keys(obj).forEach(function (key) {
      console.log( key , obj[key] );
});

This all are new features in ECMAScript , the mothods getOwnPropertyNames, keys won't supports old browser's.

Java count occurrence of each item in an array

It can be done in a very simple way using collections please find the code below

String[] array = {"name1","name1","name2","name2", "name2"};
List<String> sampleList=(List<String>) Arrays.asList(array);
for(String inpt:array){
int frequency=Collections.frequency(sampleList,inpt);
System.out.println(inpt+" "+frequency);
}

Here the output will be like name1 2 name1 2 name2 3 name2 3 name2 3

To avoid printing redundant keys use HashMap and get your desired output

Disable button in WPF?

In MVVM (wich makes a lot of things a lot easier - you should try it) you would have two properties in your ViewModel Text that is bound to your TextBox and you would have an ICommand property Apply (or similar) that is bound to the button:

<Button Command="Apply">Apply</Button>

The ICommand interface has a Method CanExecute that is where you return true if (!string.IsNullOrWhiteSpace(this.Text). The rest is done by WPF for you (enabling/disabling, executing the actual command on click).

The linked article explains it in detail.

How to use onClick event on react Link component?

You are passing hello() as a string, also hello() means execute hello immediately.

try

onClick={hello}

A cron job for rails: best practices?

That is interesting no one mentioned the Sidetiq. It is nice addition if you already using Sidekiq.

Sidetiq provides a simple API for defining recurring workers for Sidekiq.

Job will look like this:

class MyWorker
  include Sidekiq::Worker
  include Sidetiq::Schedulable

  recurrence { hourly.minute_of_hour(15, 45) }

  def perform
    # do stuff ...
  end
end

Fixed page header overlaps in-page anchors

A minimally intrusive approach using jQuery:

Link:

<a href="#my-anchor-1" class="anchor-link">Go To Anchor 1</a>

Content:

<h3 id="my-anchor-1">Here is Anchor 1</a>

Script:

$(".anchor-link").click(function() {
    var headerHeight = 120;
    $('html, body').stop(true, true).animate({
        scrollTop: $(this.hash).offset().top - headerHeight
    }, 750);
    return false;
});

By assigning the anchor-link class to the links, the behaviour of other links (like accordion or tab controls) are not affected.

The question doesn't want javascript but the other more popular question is closed because of this one and I couldn't answer there.

How do I split a string, breaking at a particular character?

With JavaScript’s String.prototype.split function:

var input = 'john smith~123 Street~Apt 4~New York~NY~12345';

var fields = input.split('~');

var name = fields[0];
var street = fields[1];
// etc.

Is there a Mutex in Java?

Any object in Java can be used as a lock using a synchronized block. This will also automatically take care of releasing the lock when an exception occurs.

Object someObject = ...;

synchronized (someObject) {
  ...
}

You can read more about this here: Intrinsic Locks and Synchronization

HTML button onclick event

This example will help you:

<form>
    <input type="button" value="Open Window" onclick="window.open('http://www.google.com')">
</form>

You can open next page on same page by:

<input type="button" value="Open Window" onclick="window.open('http://www.google.com','_self')">

IsNothing versus Is Nothing

I agree with "Is Nothing". As stated above, it's easy to negate with "IsNot Nothing".

I find this easier to read...

If printDialog IsNot Nothing Then
    'blah
End If

than this...

If Not obj Is Nothing Then
    'blah
End If

vue.js 'document.getElementById' shorthand

you can find your answer in the combination of these two pages in the API:

ref is used to register a reference to an element or a child component. The reference will be registered under the parent component’s $refs object. If used on a plain DOM element, the reference will be that element

An object that holds child components that have ref registered.

Create an enum with string values

export enum PaymentType {
                Cash = 1,
                Credit = 2
            }
var paymentType = PaymentType[PaymentType.Cash];

How do I use shell variables in an awk script?

I had to insert date at the beginning of the lines of a log file and it's done like below:

DATE=$(date +"%Y-%m-%d")
awk '{ print "'"$DATE"'", $0; }' /path_to_log_file/log_file.log

It can be redirect to another file to save

Are parameters in strings.xml possible?

If you need to format your strings using String.format(String, Object...), then you can do so by putting your format arguments in the string resource. For example, with the following resource:

<string name="welcome_messages">Hello, %1$s! You have %2$d new messages.</string>

In this example, the format string has two arguments: %1$s is a string and %2$d is a decimal number. You can format the string with arguments from your application like this:

Resources res = getResources();
String text = String.format(res.getString(R.string.welcome_messages), username, mailCount);

If you wish more look at: http://developer.android.com/intl/pt-br/guide/topics/resources/string-resource.html#FormattingAndStyling

How do I fix a compilation error for unhandled exception on call to Thread.sleep()?

You can get rid of the first line. You don't need import java.lang.*;

Just change your 5th line to:

public static void main(String [] args) throws Exception

How do I fix the indentation of an entire file in Vi?

For complex C++ files vim does not always get the formatting right when using vim's = filter command. So for a such situations it is better to use an external C++ formatter like astyle (or uncrustify) e.g.:

:%!astyle

Vim's '=' function uses its internal formatter by default (which doesn't always gets things right) but one can also set it use an external formatter, like astyle, by setting it up appropriately as discussed in this question.

Hard reset of a single file

You can use the following command:

git checkout HEAD -- my-file.txt

... which will update both the working copy of my-file.txt and its state in the index with that from HEAD.

-- basically means: treat every argument after this point as a file name. More details in this answer. Thanks to VonC for pointing this out.

How to Add Incremental Numbers to a New Column Using Pandas

import numpy as np

df['New_ID']=np.arange(880,880+len(df.Fruit))
df=df.reindex(columns=['New_ID','ID','Fruit'])

Indent List in HTML and CSS

Normally, all lists are being displayed vertically anyways. So do you want to display it horizontally?

Anyways, you asked to override the main css file and set some css locally. You cannot do it inside <ul> with style="", that it would apply on the children (<li>).

Closest thing to locally manipulating your list would be:

<style>
    li {display: inline-block;}
</style>
<ul>
  <li>Coffee</li>
  <li>Tea
    <ul>
        <li>Black tea</li>
        <li>Green tea</li>
    </ul>
  </li>
  <li>Milk</li>
</ul>

Use YAML with variables

This is how I was able to configure yaml files to refer to variable.

I have values.yaml where we have root level fields which are used as template variables inside values.yaml

values.yaml

.....  
databaseUserPropName: spring.datasource.username  
databaseUserName: sa  
.....  
secrets:
    type: Opaque  
    name: dbservice-secrets  
    data:  
      - name: "{{ .Values.databaseUserPropName }}"  
        value: "{{ .Values.databaseUserName }}"  
.....

When referencing these values in secret.yaml, we would use tpl function using syntax {{ tpl TEMPLATE_STRING VALUES }}

secret.yaml

when using inside range i:e iteration

  {{ range .Values.deployments.secrets.data }}
    {{ tpl .name $ }}: "{{ tpl .value $ }}"
  {{ end }}

when directly referring as variable

  {{ tpl .Values.deployments.secrets.data.name . }}
  {{ tpl .Values.deployments.secrets.data.value . }}

$ - this is global variable and will always point to the root context . - this variable will point to the root context based on where it used.

Using the last-child selector

As an alternative to using a class you could use a detailed list, setting the child dt elements to have one style and the child dd elements to have another. Your example would become:

#refundReasonMenu #nav li:dd
{
  border-bottom: 1px solid #b5b5b5;
}

html:

<div id="refundReasonMenu">
  <dl id="nav">
        <dt><a id="abc" href="#">abcde</a></dt>
        <dd><a id="def" href="#">xyz</a></dd>
  </dl>
</div>

Neither method is better than the other and it is just down to personal preference.

Redraw datatables after using ajax to refresh the table content?

check fnAddData: https://legacy.datatables.net/ref

$(document).ready(function () {
  var table = $('#example').dataTable();
  var url = '/RESTApplicationTest/webresources/entity.person';
  $.get(url, function (data) {
    for (var i = 0; i < data.length; i++) {
      table.fnAddData([data[i].idPerson, data[i].firstname, data[i].lastname, data[i].email, data[i].phone])
    }
  });
});

System.Runtime.InteropServices.COMException (0x800A03EC)

Some googling reveals that potentially you've got a corrupt file:

http://bitterolives.blogspot.com/2009/03/excel-interop-comexception-hresult.html

and that you can tell excel to open it anyway with the CorruptLoad parameter, with something like...

Workbook workbook = excelApplicationObject.Workbooks.Open(path, CorruptLoad: true);

How to disable input conditionally in vue.js

Bear in mind that ES6 Sets/Maps don't appear to be reactive as far as i can tell, at time of writing.

Specify sudo password for Ansible

Probably the best way to do this - assuming that you can't use the NOPASSWD solution provided by scottod is to use Mircea Vutcovici's solution in combination with Ansible vault.

For example, you might have a playbook something like this:

- hosts: all

  vars_files:
    - secret

  tasks:
    - name: Do something as sudo
      service: name=nginx state=restarted
      sudo: yes

Here we are including a file called secret which will contain our sudo password.

We will use ansible-vault to create an encrypted version of this file:

ansible-vault create secret

This will ask you for a password, then open your default editor to edit the file. You can put your ansible_sudo_pass in here.

e.g.: secret:

ansible_sudo_pass: mysudopassword

Save and exit, now you have an encrypted secret file which Ansible is able to decrypt when you run your playbook. Note: you can edit the file with ansible-vault edit secret (and enter the password that you used when creating the file)

The final piece of the puzzle is to provide Ansible with a --vault-password-file which it will use to decrypt your secret file.

Create a file called vault.txt and in that put the password that you used when creating your secret file. The password should be a string stored as a single line in the file.

From the Ansible Docs:

.. ensure permissions on the file are such that no one else can access your key and do not add your key to source control

Finally: you can now run your playbook with something like

ansible-playbook playbook.yml -u someuser -i hosts --sudo --vault-password-file=vault.txt 

The above is assuming the following directory layout:

.
|_ playbook.yml
|_ secret
|_ hosts
|_ vault.txt

You can read more about Ansible Vault here: https://docs.ansible.com/playbooks_vault.html

Close virtual keyboard on button press

mMyTextView.setOnEditorActionListener(new TextView.OnEditorActionListener() {
    public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
        if (actionId == EditorInfo.IME_ACTION_SEARCH) {
            // hide virtual keyboard
            InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
            imm.hideSoftInputFromWindow(m_txtSearchText.getWindowToken(), 
                                      InputMethodManager.RESULT_UNCHANGED_SHOWN);
            return true;
        }
        return false;
    }
});

Free tool to Create/Edit PNG Images?

ImageMagick and GD can handle PNGs too; heck, you could even do stuff with nothing but gdk-pixbuf. Are you looking for a graphical editor, or scriptable/embeddable libraries?

How to register ASP.NET 2.0 to web server(IIS7)?

I got it resolved by doing Repir on .NET framework Extended, in Add/Remove program ;

Using win2008R2, .NET framework 4.0

Difference between single and double quotes in Bash

Single quotes won't interpolate anything, but double quotes will. For example: variables, backticks, certain \ escapes, etc.

Example:

$ echo "$(echo "upg")"
upg
$ echo '$(echo "upg")'
$(echo "upg")

The Bash manual has this to say:

3.1.2.2 Single Quotes

Enclosing characters in single quotes (') preserves the literal value of each character within the quotes. A single quote may not occur between single quotes, even when preceded by a backslash.

3.1.2.3 Double Quotes

Enclosing characters in double quotes (") preserves the literal value of all characters within the quotes, with the exception of $, `, \, and, when history expansion is enabled, !. The characters $ and ` retain their special meaning within double quotes (see Shell Expansions). The backslash retains its special meaning only when followed by one of the following characters: $, `, ", \, or newline. Within double quotes, backslashes that are followed by one of these characters are removed. Backslashes preceding characters without a special meaning are left unmodified. A double quote may be quoted within double quotes by preceding it with a backslash. If enabled, history expansion will be performed unless an ! appearing in double quotes is escaped using a backslash. The backslash preceding the ! is not removed.

The special parameters * and @ have special meaning when in double quotes (see Shell Parameter Expansion).

Gaussian fit for Python

Explanation

You need good starting values such that the curve_fit function converges at "good" values. I can not really say why your fit did not converge (even though the definition of your mean is strange - check below) but I will give you a strategy that works for non-normalized Gaussian-functions like your one.

Example

The estimated parameters should be close to the final values (use the weighted arithmetic mean - divide by the sum of all values):

import matplotlib.pyplot as plt
from scipy.optimize import curve_fit
import numpy as np

x = np.arange(10)
y = np.array([0, 1, 2, 3, 4, 5, 4, 3, 2, 1])

# weighted arithmetic mean (corrected - check the section below)
mean = sum(x * y) / sum(y)
sigma = np.sqrt(sum(y * (x - mean)**2) / sum(y))

def Gauss(x, a, x0, sigma):
    return a * np.exp(-(x - x0)**2 / (2 * sigma**2))

popt,pcov = curve_fit(Gauss, x, y, p0=[max(y), mean, sigma])

plt.plot(x, y, 'b+:', label='data')
plt.plot(x, Gauss(x, *popt), 'r-', label='fit')
plt.legend()
plt.title('Fig. 3 - Fit for Time Constant')
plt.xlabel('Time (s)')
plt.ylabel('Voltage (V)')
plt.show()

I personally prefer using numpy.

Comment on the definition of the mean (including Developer's answer)

Since the reviewers did not like my edit on #Developer's code, I will explain for what case I would suggest an improved code. The mean of developer does not correspond to one of the normal definitions of the mean.

Your definition returns:

>>> sum(x * y)
125

Developer's definition returns:

>>> sum(x * y) / len(x)
12.5 #for Python 3.x

The weighted arithmetic mean:

>>> sum(x * y) / sum(y)
5.0

Similarly you can compare the definitions of standard deviation (sigma). Compare with the figure of the resulting fit:

Resulting fit

Comment for Python 2.x users

In Python 2.x you should additionally use the new division to not run into weird results or convert the the numbers before the division explicitly:

from __future__ import division

or e.g.

sum(x * y) * 1. / sum(y)

How do I check if an HTML element is empty using jQuery?

if ($('#element').is(':empty')){
  //do something
}

for more info see http://api.jquery.com/is/ and http://api.jquery.com/empty-selector/

EDIT:

As some have pointed, the browser interpretation of an empty element can vary. If you would like to ignore invisible elements such as spaces and line breaks and make the implementation more consistent you can create a function (or just use the code inside of it).

  function isEmpty( el ){
      return !$.trim(el.html())
  }
  if (isEmpty($('#element'))) {
      // do something
  }

You can also make it into a jQuery plugin, but you get the idea.

"Not allowed to load local resource: file:///C:....jpg" Java EE Tomcat

Many browsers have changed their security policies to no longer allow reading data directly from file shares or even local resources. You need to either place the files somewhere that your tomcat instance can serve them up and put a "regular" http url in the html you generate. This can be accomplished by either providing a servlet which reads and provides the file putting the file into a directory where tomcat will serve it up as "static" content.

What's the difference between ClusterIP, NodePort and LoadBalancer service types in Kubernetes?

Lets assume you created a Ubuntu VM on your local machine. It's IP address is 192.168.1.104.

You login into VM, and installed Kubernetes. Then you created a pod where nginx image running on it.

1- If you want to access this nginx pod inside your VM, you will create a ClusterIP bound to that pod for example:

$ kubectl expose deployment nginxapp --name=nginxclusterip --port=80 --target-port=8080

Then on your browser you can type ip address of nginxclusterip with port 80, like:

http://10.152.183.2:80

2- If you want to access this nginx pod from your host machine, you will need to expose your deployment with NodePort. For example:

$ kubectl expose deployment nginxapp --name=nginxnodeport --port=80 --target-port=8080 --type=NodePort

Now from your host machine you can access to nginx like:

http://192.168.1.104:31865/

In my dashboard they appear as:

enter image description here

Below is a diagram shows basic relationship.

enter image description here

How to check if C string is empty

First replace the scanf() with fgets() ...

do {
    if (!fgets(url, sizeof url, stdin)) /* error */;
    /* ... */
} while (*url != '\n');

Are (non-void) self-closing tags valid in HTML5?

Self-closing tags are valid in HTML5, but not required.

<br> and <br /> are both fine.

Why does JPA have a @Transient annotation?

Purpose is different:

The transient keyword and @Transient annotation have two different purposes: one deals with serialization and one deals with persistence. As programmers, we often marry these two concepts into one, but this is not accurate in general. Persistence refers to the characteristic of state that outlives the process that created it. Serialization in Java refers to the process of encoding/decoding an object's state as a byte stream.

The transient keyword is a stronger condition than @Transient:

If a field uses the transient keyword, that field will not be serialized when the object is converted to a byte stream. Furthermore, since JPA treats fields marked with the transient keyword as having the @Transient annotation, the field will not be persisted by JPA either.

On the other hand, fields annotated @Transient alone will be converted to a byte stream when the object is serialized, but it will not be persisted by JPA. Therefore, the transient keyword is a stronger condition than the @Transient annotation.

Example

This begs the question: Why would anyone want to serialize a field that is not persisted to the application's database? The reality is that serialization is used for more than just persistence. In an Enterprise Java application there needs to be a mechanism to exchange objects between distributed components; serialization provides a common communication protocol to handle this. Thus, a field may hold critical information for the purpose of inter-component communication; but that same field may have no value from a persistence perspective.

For example, suppose an optimization algorithm is run on a server, and suppose this algorithm takes several hours to complete. To a client, having the most up-to-date set of solutions is important. So, a client can subscribe to the server and receive periodic updates during the algorithm's execution phase. These updates are provided using the ProgressReport object:

@Entity
public class ProgressReport implements Serializable{

    private static final long serialVersionUID = 1L;

    @Transient
    long estimatedMinutesRemaining;
    String statusMessage;
    Solution currentBestSolution;

}

The Solution class might look like this:

@Entity
public class Solution implements Serializable{

    private static final long serialVersionUID = 1L;

    double[][] dataArray;
    Properties properties;
}

The server persists each ProgressReport to its database. The server does not care to persist estimatedMinutesRemaining, but the client certainly cares about this information. Therefore, the estimatedMinutesRemaining is annotated using @Transient. When the final Solution is located by the algorithm, it is persisted by JPA directly without using a ProgressReport.

How to create UILabel programmatically using Swift?

Another code swift3

let myLabel = UILabel()
    myLabel.frame = CGRect(x: 0, y: 0, width: 100, height: 100)
    myLabel.center = CGPoint(x: 0, y: 0)
    myLabel.textAlignment = .center
    myLabel.text = "myLabel!!!!!"
    self.view.addSubview(myLabel)

J2ME/Android/BlackBerry - driving directions, route between two locations

J2ME Map Route Provider

maps.google.com has a navigation service which can provide you route information in KML format.

To get kml file we need to form url with start and destination locations:

public static String getUrl(double fromLat, double fromLon,
                            double toLat, double toLon) {// connect to map web service
    StringBuffer urlString = new StringBuffer();
    urlString.append("http://maps.google.com/maps?f=d&hl=en");
    urlString.append("&saddr=");// from
    urlString.append(Double.toString(fromLat));
    urlString.append(",");
    urlString.append(Double.toString(fromLon));
    urlString.append("&daddr=");// to
    urlString.append(Double.toString(toLat));
    urlString.append(",");
    urlString.append(Double.toString(toLon));
    urlString.append("&ie=UTF8&0&om=0&output=kml");
    return urlString.toString();
}

Next you will need to parse xml (implemented with SAXParser) and fill data structures:

public class Point {
    String mName;
    String mDescription;
    String mIconUrl;
    double mLatitude;
    double mLongitude;
}

public class Road {
    public String mName;
    public String mDescription;
    public int mColor;
    public int mWidth;
    public double[][] mRoute = new double[][] {};
    public Point[] mPoints = new Point[] {};
}

Network connection is implemented in different ways on Android and Blackberry, so you will have to first form url:

 public static String getUrl(double fromLat, double fromLon,
     double toLat, double toLon)

then create connection with this url and get InputStream.
Then pass this InputStream and get parsed data structure:

 public static Road getRoute(InputStream is) 

Full source code RoadProvider.java

BlackBerry

class MapPathScreen extends MainScreen {
    MapControl map;
    Road mRoad = new Road();
    public MapPathScreen() {
        double fromLat = 49.85, fromLon = 24.016667;
        double toLat = 50.45, toLon = 30.523333;
        String url = RoadProvider.getUrl(fromLat, fromLon, toLat, toLon);
        InputStream is = getConnection(url);
        mRoad = RoadProvider.getRoute(is);
        map = new MapControl();
        add(new LabelField(mRoad.mName));
        add(new LabelField(mRoad.mDescription));
        add(map);
    }
    protected void onUiEngineAttached(boolean attached) {
        super.onUiEngineAttached(attached);
        if (attached) {
            map.drawPath(mRoad);
        }
    }
    private InputStream getConnection(String url) {
        HttpConnection urlConnection = null;
        InputStream is = null;
        try {
            urlConnection = (HttpConnection) Connector.open(url);
            urlConnection.setRequestMethod("GET");
            is = urlConnection.openInputStream();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return is;
    }
}

See full code on J2MEMapRouteBlackBerryEx on Google Code

Android

Android G1 screenshot

public class MapRouteActivity extends MapActivity {
    LinearLayout linearLayout;
    MapView mapView;
    private Road mRoad;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        mapView = (MapView) findViewById(R.id.mapview);
        mapView.setBuiltInZoomControls(true);
        new Thread() {
            @Override
            public void run() {
                double fromLat = 49.85, fromLon = 24.016667;
                double toLat = 50.45, toLon = 30.523333;
                String url = RoadProvider
                        .getUrl(fromLat, fromLon, toLat, toLon);
                InputStream is = getConnection(url);
                mRoad = RoadProvider.getRoute(is);
                mHandler.sendEmptyMessage(0);
            }
        }.start();
    }

    Handler mHandler = new Handler() {
        public void handleMessage(android.os.Message msg) {
            TextView textView = (TextView) findViewById(R.id.description);
            textView.setText(mRoad.mName + " " + mRoad.mDescription);
            MapOverlay mapOverlay = new MapOverlay(mRoad, mapView);
            List<Overlay> listOfOverlays = mapView.getOverlays();
            listOfOverlays.clear();
            listOfOverlays.add(mapOverlay);
            mapView.invalidate();
        };
    };

    private InputStream getConnection(String url) {
        InputStream is = null;
        try {
            URLConnection conn = new URL(url).openConnection();
            is = conn.getInputStream();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return is;
    }
    @Override
    protected boolean isRouteDisplayed() {
        return false;
    }
}

See full code on J2MEMapRouteAndroidEx on Google Code

how to force maven to update local repo

If you are installing into local repository, there is no special index/cache update needed.

Make sure that:

  1. You have installed the first artifact in your local repository properly. Simply copying the file to .m2 may not work as expected. Make sure you install it by mvn install

  2. The dependency in 2nd project is setup correctly. Check on any typo in groupId/artifactId/version, or unmatched artifact type/classifier.

How do I find the maximum of 2 numbers?

Use the builtin function max.

Example: max(2, 4) returns 4.

Just for giggles, there's a min as well...should you need it. :P

How to upgrade Git on Windows to the latest version?

First, check your git version by using this command

git version

Then follow the case according to your git version

Three cases:

  1. If your git version is 2.14.1 or earlier:

    Uninstall the git, download the latest git, and install it again.

  2. And versions between 2.14.2 and 2.16.1:

    Use command git update

  3. If the version is equal to or greater than Git 2.16.1(2):

    Use command git update-git-for-windows

How to concatenate characters in java?

Do you want to make a string out of them?

String s = new StringBuilder().append(char1).append(char2).append(char3).toString();

Note that

String b = "b";
String s = "a" + b + "c";

Actually compiles to

String s = new StringBuilder("a").append(b).append("c").toString();

Edit: as litb pointed out, you can also do this:

"" + char1 + char2 + char3;

That compiles to the following:

new StringBuilder().append("").append(c).append(c1).append(c2).toString();

Edit (2): Corrected string append comparison since, as cletus points out, a series of strings is handled by the compiler.

The purpose of the above is to illustrate what the compiler does, not to tell you what you should do.

How can I post an array of string to ASP.NET MVC Controller without a form?

Thanks everyone for the answers. Another quick solution will be to use jQuery.param method with traditional parameter set to true to convert JSON object to string:

$.post("/your/url", $.param(yourJsonObject,true));

Is there any JSON Web Token (JWT) example in C#?

It would be better to use standard and famous libraries instead of writing the code from scratch.

  1. JWT for encoding and decoding JWT tokens
  2. Bouncy Castle supports encryption and decryption, especially RS256 get it here

Using these libraries you can generate a JWT token and sign it using RS256 as below.

    public string GenerateJWTToken(string rsaPrivateKey)
    {
        var rsaParams = GetRsaParameters(rsaPrivateKey);
        var encoder = GetRS256JWTEncoder(rsaParams);

        // create the payload according to the Google's doc
        var payload = new Dictionary<string, object>
        {
            { "iss", ""},
            { "sub", "" },
            // and other key-values according to the doc
        };

        // add headers. 'alg' and 'typ' key-values are added automatically.
        var header = new Dictionary<string, object>
        {
            { "kid", "{your_private_key_id}" },
        };

        var token = encoder.Encode(header,payload, new byte[0]);

        return token;
    }

    private static IJwtEncoder GetRS256JWTEncoder(RSAParameters rsaParams)
    {
        var csp = new RSACryptoServiceProvider();
        csp.ImportParameters(rsaParams);

        var algorithm = new RS256Algorithm(csp, csp);
        var serializer = new JsonNetSerializer();
        var urlEncoder = new JwtBase64UrlEncoder();
        var encoder = new JwtEncoder(algorithm, serializer, urlEncoder);

        return encoder;
    }

    private static RSAParameters GetRsaParameters(string rsaPrivateKey)
    {
        var byteArray = Encoding.ASCII.GetBytes(rsaPrivateKey);
        using (var ms = new MemoryStream(byteArray))
        {
            using (var sr = new StreamReader(ms))
            {
                // use Bouncy Castle to convert the private key to RSA parameters
                var pemReader = new PemReader(sr);
                var keyPair = pemReader.ReadObject() as AsymmetricCipherKeyPair;
                return DotNetUtilities.ToRSAParameters(keyPair.Private as RsaPrivateCrtKeyParameters);
            }
        }
    }

ps: the RSA private key should have the following format:

-----BEGIN RSA PRIVATE KEY----- {base64 formatted value} -----END RSA PRIVATE KEY-----

Is it possible to make Font Awesome icons larger than 'fa-5x'?

Alternatively you can edit the source and create your own incrementations

FontAwesome 5

https://github.com/FortAwesome/Font-Awesome/blob/master/web-fonts-with-css/less/_larger.less

// Icon Sizes
// -------------------------

.larger(@factor) when (@factor > 0) {
  .larger((@factor - 1));

  .@{fa-css-prefix}-@{factor}x {
    font-size: (@factor * 1em);
  }
}

/* makes the font 33% larger relative to the icon container */
.@{fa-css-prefix}-lg {
  font-size: (4em / 3);
  line-height: (3em / 4);
  vertical-align: -.0667em;
}

.@{fa-css-prefix}-xs {
  font-size: .75em;
}

.@{fa-css-prefix}-sm {
  font-size: .875em;
}

// Change the number below to create your own incrementations
// This currently creates classes .fa-1x - .fa-10x
.larger(10);

FontAwesome 4

https://github.com/FortAwesome/Font-Awesome/blob/v4.7.0/less/larger.less

// Icon Sizes
// -------------------------

/* makes the font 33% larger relative to the icon container */
.@{fa-css-prefix}-lg {
    font-size: (4em / 3);
    line-height: (3em / 4);
    vertical-align: -15%;
}

.@{fa-css-prefix}-2x { font-size: 2em; }
.@{fa-css-prefix}-3x { font-size: 3em; }
.@{fa-css-prefix}-4x { font-size: 4em; }
.@{fa-css-prefix}-5x { font-size: 5em; }

// Your custom sizes
.@{fa-css-prefix}-6x { font-size: 6em; }
.@{fa-css-prefix}-7x { font-size: 7em; }
.@{fa-css-prefix}-8x { font-size: 8em; }

How to get evaluated attributes inside a custom directive

The other answers here are very much correct, and valuable. But sometimes you just want simple: to get a plain old parsed value at directive instantiation, without needing updates, and without messing with isolate scope. For instance, it can be handy to provide a declarative payload into your directive as an array or hash-object in the form:

my-directive-name="['string1', 'string2']"

In that case, you can cut to the chase and just use a nice basic angular.$eval(attr.attrName).

element.val("value = "+angular.$eval(attr.value));

Working Fiddle.

How to control border height?

not bad .. but try this one ... (should works for all but ist just -webkit included)

<br>
<input type="text" style="
  background: transparent;
border-bottom: 1px solid #B5D5FF;
border-left: 1px solid;
border-right: 1px solid;
border-left-color: #B5D5FF;
border-image: -webkit-linear-gradient(top, #fff 50%, #B5D5FF 0%) 1 repeat;
">

//Feel free to edit and add all other browser..

PHPMailer AddAddress()

All answers are great. Here is an example use case for multiple add address: The ability to add as many email you want on demand with a web form:

See it in action with jsfiddle here (except the php processor)

### Send unlimited email with a web form
# Form for continuously adding e-mails:
<button type="button" onclick="emailNext();">Click to Add Another Email.</button>
<div id="addEmail"></div>
<button type="submit">Send All Emails</button>
# Script function:
<script>
function emailNext() {
    var nextEmail, inside_where;
    nextEmail = document.createElement('input');
    nextEmail.type = 'text';
    nextEmail.name = 'emails[]';
    nextEmail.className = 'class_for_styling';
    nextEmail.style.display = 'block';
    nextEmail.placeholder  = 'Enter E-mail Here';
    inside_where = document.getElementById('addEmail');
    inside_where.appendChild(nextEmail);
    return false;
}
</script>
# PHP Data Processor:
<?php
// ...
// Add the rest of your $mailer here...
if ($_POST[emails]){
    foreach ($_POST[emails] AS $postEmail){
        if ($postEmail){$mailer->AddAddress($postEmail);}
    }
} 
?>

So what it does basically is to generate a new input text box on every click with the name "emails[]".

The [] added at the end makes it an array when posted.

Then we go through each element of the array with "foreach" on PHP side adding the:

    $mailer->AddAddress($postEmail);

node.js string.replace doesn't work?

If you just want to clobber all of the instances of a substring out of a string without using regex you can using:

    var replacestring = "A B B C D"
    const oldstring = "B";
    const newstring = "E";
    while (replacestring.indexOf(oldstring) > -1) {
        replacestring = replacestring.replace(oldstring, newstring);
    }        
    //result: "A E E C D"

How to parse JSON in Scala using standard Scala classes?

I tried a few things, favouring pattern matching as a way of avoiding casting but ran into trouble with type erasure on the collection types.

The main problem seems to be that the complete type of the parse result mirrors the structure of the JSON data and is either cumbersome or impossible to fully state. I guess that is why Any is used to truncate the type definitions. Using Any leads to the need for casting.

I've hacked something below which is concise but is extremely specific to the JSON data implied by the code in the question. Something more general would be more satisfactory but I'm not sure if it would be very elegant.

implicit def any2string(a: Any)  = a.toString
implicit def any2boolean(a: Any) = a.asInstanceOf[Boolean]
implicit def any2double(a: Any)  = a.asInstanceOf[Double]

case class Language(name: String, isActive: Boolean, completeness: Double)

val languages = JSON.parseFull(jstr) match {
  case Some(x) => {
    val m = x.asInstanceOf[Map[String, List[Map[String, Any]]]]

    m("languages") map {l => Language(l("name"), l("isActive"), l("completeness"))}
  }
  case None => Nil
}

languages foreach {println}

excel - if cell is not blank, then do IF statement

Your formula is wrong. You probably meant something like:

=IF(AND(NOT(ISBLANK(Q2));NOT(ISBLANK(R2)));IF(Q2<=R2;"1";"0");"")

Another equivalent:

=IF(NOT(OR(ISBLANK(Q2);ISBLANK(R2)));IF(Q2<=R2;"1";"0");"")

Or even shorter:

=IF(OR(ISBLANK(Q2);ISBLANK(R2));"";IF(Q2<=R2;"1";"0"))

OR EVEN SHORTER:

=IF(OR(ISBLANK(Q2);ISBLANK(R2));"";--(Q2<=R2))

How do I convert this list of dictionaries to a csv file?

import csv
toCSV = [{'name':'bob','age':25,'weight':200},
         {'name':'jim','age':31,'weight':180}]
keys = toCSV[0].keys()
with open('people.csv', 'w', newline='')  as output_file:
    dict_writer = csv.DictWriter(output_file, keys)
    dict_writer.writeheader()
    dict_writer.writerows(toCSV)

EDIT: My prior solution doesn't handle the order. As noted by Wilduck, DictWriter is more appropriate here.

When should I use curly braces for ES6 import?

Usually when you export a function you need to use the {}.

If you have

export const x

you use

import {x} from ''

If you use

export default const x

you need to use

import x from ''

Here you can change X to whatever variable you want.

Build project into a JAR automatically in Eclipse

Regarding to Peter's answer and Micheal's addition to it you may find How Do I Automatically Generate A .jar File In An Eclipse Java Project useful. Because even you have "*.jardesc" file on your project you have to run it manually. It may cools down your "eclipse click hassle" a bit.

ITextSharp HTML to PDF?

It has ability to convert HTML file in to pdf.

Required namespace for conversions are:

using iTextSharp.text;
using iTextSharp.text.pdf;

and for conversion and download file :

// Create a byte array that will eventually hold our final PDF
Byte[] bytes;

// Boilerplate iTextSharp setup here

// Create a stream that we can write to, in this case a MemoryStream
using (var ms = new MemoryStream())
{
    // Create an iTextSharp Document which is an abstraction of a PDF but **NOT** a PDF
    using (var doc = new Document())
    {
        // Create a writer that's bound to our PDF abstraction and our stream
        using (var writer = PdfWriter.GetInstance(doc, ms))
        {
            // Open the document for writing
            doc.Open();

            string finalHtml = string.Empty;

            // Read your html by database or file here and store it into finalHtml e.g. a string
            // XMLWorker also reads from a TextReader and not directly from a string
            using (var srHtml = new StringReader(finalHtml))
            {
                // Parse the HTML
                iTextSharp.tool.xml.XMLWorkerHelper.GetInstance().ParseXHtml(writer, doc, srHtml);
            }

            doc.Close();
        }
    }

    // After all of the PDF "stuff" above is done and closed but **before** we
    // close the MemoryStream, grab all of the active bytes from the stream
    bytes = ms.ToArray();
}

// Clear the response
Response.Clear();
MemoryStream mstream = new MemoryStream(bytes);

// Define response content type
Response.ContentType = "application/pdf";

// Give the name of file of pdf and add in to header
Response.AddHeader("content-disposition", "attachment;filename=invoice.pdf");
Response.Buffer = true;
mstream.WriteTo(Response.OutputStream);
Response.End();

Do not want scientific notation on plot axis

Use options(scipen=5) or some other high enough number. The scipen option determines how likely R is to switch to scientific notation, the higher the value the less likely it is to switch. Set the option before making your plot, if it still has scientific notation, set it to a higher number.

How to use border with Bootstrap

While it's probably not the correct way to do it, something that I've found to be a simple workaround is to simply use a box-shadow rather than a border... This doesn't break the grid system. For example, in your case:

HTML

<div class="container">
    <div class="row" >
        <div class="span12">
            <div class="row">
                <div class="span4">
                    1
                </div>
                <div class="span4">
                    2
                </div>
                <div class="span4">
                    3
                </div>
            </div>
        </div>
    </div>
</div>

CSS

.span12{
    -moz-box-shadow: 0 0 2px black;
    -webkit-box-shadow: 0 0 2px black;
    box-shadow: 0 0 2px black;
}

Fiddle

Executing "SELECT ... WHERE ... IN ..." using MySQLdb

Very simple:

Just use the below formation###

rules_id = ["9","10"]

sql2 = "SELECT * FROM attendance_rules_staff WHERE id in"+str(tuple(rules_id))

note the str(tuple(rules_id)).

Remove folder and its contents from git/GitHub's history

If you are here to copy-paste code:

This is an example which removes node_modules from history

git filter-branch --tree-filter "rm -rf node_modules" --prune-empty HEAD
git for-each-ref --format="%(refname)" refs/original/ | xargs -n 1 git update-ref -d
echo node_modules/ >> .gitignore
git add .gitignore
git commit -m 'Removing node_modules from git history'
git gc
git push origin master --force

What git actually does:

The first line iterates through all references on the same tree (--tree-filter) as HEAD (your current branch), running the command rm -rf node_modules. This command deletes the node_modules folder (-r, without -r, rm won't delete folders), with no prompt given to the user (-f). The added --prune-empty deletes useless (not changing anything) commits recursively.

The second line deletes the reference to that old branch.

The rest of the commands are relatively straightforward.

How to subtract hours from a date in Oracle so it affects the day also

Others have commented on the (incorrect) use of 2/11 to specify the desired interval.

I personally however prefer writing things like that using ANSI interval literals which makes reading the query much easier:

sysdate - interval '2' hour

It also has the advantage of being portable, many DBMS support this. Plus I don't have to fire up a calculator to find out how many hours the expression means - I'm pretty bad with mental arithmetics ;)

Basic HTTP and Bearer Token Authentication

With nginx you can send both tokens like this (even though it's against the standard):

Authorization: Basic basic-token,Bearer bearer-token

This works as long as the basic token is first - nginx successfully forwards it to the application server.

And then you need to make sure your application can properly extract the Bearer from the above string.

Laravel blank white screen

Strange for me, but in my case I had to clear the laravel's cache to solve the issue.