Programs & Examples On #Javadb

Java DB is Sun's supported distribution of the open source Apache Derby 100% Java technology database. It is fully transactional, secure, easy-to-use, standards-based SQL, JDBC API, and Java EE yet small, only 2.6 MB.

Create autoincrement key in Java DB using NetBeans IDE

Found a way of setting auto increment in netbeans 8.0.1 here on StackoOverflow Screenshot below:

see screenshot here

Using Mockito with multiple calls to the same method with the same arguments

Following can be used as a common method to return different arguments on different method calls. Only thing we need to do is we need to pass an array with order in which objects should be retrieved in each call.

@SafeVarargs
public static <Mock> Answer<Mock> getAnswerForSubsequentCalls(final Mock... mockArr) {
    return new Answer<Mock>() {
       private int count=0, size=mockArr.length;
       public Mock answer(InvocationOnMock invocation) throws throwable {
           Mock mock = null;
           for(; count<size && mock==null; count++){
                mock = mockArr[count];
           }

           return mock;    
       } 
    }
}

Ex. getAnswerForSubsequentCalls(mock1, mock3, mock2); will return mock1 object on first call, mock3 object on second call and mock2 object on third call. Should be used like when(something()).doAnswer(getAnswerForSubsequentCalls(mock1, mock3, mock2)); This is almost similar to when(something()).thenReturn(mock1, mock3, mock2);

Valid characters of a hostname?

If you're registering a domain and the termination (ex .com) it is not IDN, as Aaron Hathaway said: Hostnames are composed of series of labels concatenated with dots, as are all domain names. For example, en.wikipedia.org is a hostname. Each label must be between 1 and 63 characters long, and the entire hostname (including the delimiting dots but not a trailing dot) has a maximum of 253 ASCII characters.

The Internet standards (Requests for Comments) for protocols mandate that component hostname labels may contain only the ASCII letters a through z (in a case-insensitive manner), the digits 0 through 9, and the hyphen -. The original specification of hostnames in RFC 952, mandated that labels could not start with a digit or with a hyphen, and must not end with a hyphen. However, a subsequent specification (RFC 1123) permitted hostname labels to start with digits. No other symbols, punctuation characters, or white space are permitted.

Later, Spain with it's .es, .com.es, .org.es, .nom,es, .gob.es and .edu.es introduced IDN tlds, if your tld is one of .es or any other that supports it, any character can be used, but you can't combine alphabets like Latin, Greek or Cyril in one hostname, and that it respects the things that can't go at the start or at the end.

If you're using non-registered tlds, just for local networking, like with local DNS or with hosts files, you can treat them all as IDN.

Keep in mind some programs could not work well, especially old, outdated and unpopular ones.

How to resolve Error listenerStart when deploying web-app in Tomcat 5.5?

I encountered this error when the JDK that I compiled the app under was different from the tomcat JVM. I verified that the Tomcat manager was running jvm 1.6.0 but the app was compiled under java 1.7.0.

After upgrading Java and changing JAVA_HOME in our startup script (/etc/init.d/tomcat) the error went away.

Should I put #! (shebang) in Python scripts, and what form should it take?

If you have more than one version of Python and the script needs to run under a specific version, the she-bang can ensure the right one is used when the script is executed directly, for example:

#!/usr/bin/python2.7

Note the script could still be run via a complete Python command line, or via import, in which case the she-bang is ignored. But for scripts run directly, this is a decent reason to use the she-bang.

#!/usr/bin/env python is generally the better approach, but this helps with special cases.

Usually it would be better to establish a Python virtual environment, in which case the generic #!/usr/bin/env python would identify the correct instance of Python for the virtualenv.

Unicode character in PHP string

function unicode_to_textstring($str){

    $rawstr = pack('H*', $str);

    $newstr =  iconv('UTF-16BE', 'UTF-8', $rawstr);
    return $newstr;
}

$msg = '67714eac99c500200054006f006b0079006f002000530074006100740069006f006e003a0020';

echo unicode_to_textstring($str);

How to find all tables that have foreign keys that reference particular table.column and have values for those foreign keys?

Here you go:

USE information_schema;
SELECT *
FROM
  KEY_COLUMN_USAGE
WHERE
  REFERENCED_TABLE_NAME = 'X'
  AND REFERENCED_COLUMN_NAME = 'X_id';

If you have multiple databases with similar tables/column names you may also wish to limit your query to a particular database:

SELECT *
FROM
  KEY_COLUMN_USAGE
WHERE
  REFERENCED_TABLE_NAME = 'X'
  AND REFERENCED_COLUMN_NAME = 'X_id'
  AND TABLE_SCHEMA = 'your_database_name';

How to use refs in React with Typescript

I always do this, in that case to grab a ref

let input: HTMLInputElement = ReactDOM.findDOMNode<HTMLInputElement>(this.refs.input);

Fastest JSON reader/writer for C++

rapidjson is a C++ JSON parser/generator designed to be fast and small memory footprint.

There is a performance comparison with YAJL and JsonCPP.


Update:

I created an open source project Native JSON benchmark, which evaluates 29 (and increasing) C/C++ JSON libraries, in terms of conformance and performance. This should be an useful reference.

Copy file or directories recursively in Python

shutil.copy and shutil.copy2 are copying files.

shutil.copytree copies a folder with all the files and all subfolders. shutil.copytree is using shutil.copy2 to copy the files.

So the analog to cp -r you are saying is the shutil.copytree because cp -r targets and copies a folder and its files/subfolders like shutil.copytree. Without the -r cp copies files like shutil.copy and shutil.copy2 do.

PHP Remove elements from associative array

$key = array_search("Mark As Spam", $array);
unset($array[$key]);

For 2D arrays...

$remove = array("Mark As Spam", "Completed");
foreach($arrays as $array){
    foreach($array as $key => $value){
        if(in_array($value, $remove)) unset($array[$key]);
    }
}

What is the backslash character (\\)?

The \ on it's own is used to escape special characters, such as \n (new line), \t (tabulation), \" (quotes) when typing these specific values in a System.out.println() statement.

Thus, if you want to print a backslash, \, you can't have it on it's own since the compiler will be expecting a special character (such as the ones above). Thus, to print a backslash you need to escape it, since itself is also one of these special characters, thus, \\ yields \.

psql: could not connect to server: No such file or directory (Mac OS X)

None of the above worked for me. I had to reinstall Postgres the following way :

  • Uninstall postgresql with brew : brew uninstall postgresql
  • brew doctor (fix whatever is here)
  • brew cleanup
  • Remove all Postgres folders :

    • rm -r /usr/local/var/postgres
    • rm -r /Users/<username>/Library/Application\ Support/Postgres
  • Reinstall postgresql with brew : brew install postgresql

  • Start server : brew services start postgresql
  • You should now have to create your databases... (createdb)

'setInterval' vs 'setTimeout'

setInterval fires again and again in intervals, while setTimeout only fires once.

See reference at MDN.

How do I convert a dictionary to a JSON String in C#?

Sorry if the syntax is the tiniest bit off, but the code I'm getting this from was originally in VB :)

using System.Web.Script.Serialization;

...

Dictionary<int,List<int>> MyObj = new Dictionary<int,List<int>>();

//Populate it here...

string myJsonString = (new JavaScriptSerializer()).Serialize(MyObj);

Android ListView not refreshing after notifyDataSetChanged

An answer from AlexGo did the trick for me:

getActivity().runOnUiThread(new Runnable() {
        @Override
        public void run() {
         messages.add(m);
         adapter.notifyDataSetChanged();
         getListView().setSelection(messages.size()-1);
        }
});

List Update worked for me before when the update was triggered from a GUI event, thus being in the UI thread.

However, when I update the list from another event/thread - i.e. a call from outside the app, the update would not be in the UI thread and it ignored the call to getListView. Calling the update with runOnUiThread as above did the trick for me. Thanks!!

iOS Simulator to test website on Mac

If you are on Mac OS X just use Simulator. I don't know if it is available by default but it looks like it is a part of the Xcode suite.

Anyway it is free and really useful, it allows you to simulate many popular Apple devices:

enter image description here

Issue with adding common code as git submodule: "already exists in the index"

I'm afraid there's not enough information in your question to be certain about what's going on, since you haven't replied to my follow-up question, but this may be of help in any case.

That error means that projectfolder is already staged ("already exists in the index"). To find out what's going on here, try to list everything in the index under that folder with:

git ls-files --stage projectfolder

The first column of that output will tell you what type of object is in the index at projectfolder. (These look like Unix filemodes, but have special meanings in git.)

I suspect that you will see something like:

160000 d00cf29f23627fc54eb992dde6a79112677cd86c 0   projectfolder

(i.e. a line beginning with 160000), in which case the repository in projectfolder has already been added as a "gitlink". If it doesn't appear in the output of git submodule, and you want to re-add it as a submodule, you can do:

git rm --cached projectfolder

... to unstage it, and then:

git submodule add url_to_repo projectfolder

... to add the repository as a submodule.

However, it's also possible that you will see many blobs listed (with file modes 100644 and 100755), which would suggest to me that you didn't properly unstage the files in projectfolder before copying the new repository into place. If that's the case, you can do the following to unstage all of those files:

git rm -r --cached projectfolder

... and then add the submodule with:

git submodule add url_to_repo projectfolder

Detect page change on DataTable

Try using delegate instead of live as here:

$('#link-wrapper').delegate('a', 'click', function() {
  // do something ..
}

Elevating process privilege programmatically?

You can indicate the new process should be started with elevated permissions by setting the Verb property of your startInfo object to 'runas', as follows:

startInfo.Verb = "runas";

This will cause Windows to behave as if the process has been started from Explorer with the "Run as Administrator" menu command.

This does mean the UAC prompt will come up and will need to be acknowledged by the user: if this is undesirable (for example because it would happen in the middle of a lengthy process), you'll need to run your entire host process with elevated permissions by Create and Embed an Application Manifest (UAC) to require the 'highestAvailable' execution level: this will cause the UAC prompt to appear as soon as your app is started, and cause all child processes to run with elevated permissions without additional prompting.

Edit: I see you just edited your question to state that "runas" didn't work for you. That's really strange, as it should (and does for me in several production apps). Requiring the parent process to run with elevated rights by embedding the manifest should definitely work, though.

A select query selecting a select statement

I was over-complicating myself. After taking a long break and coming back, the desired output could be accomplished by this simple query:

SELECT Sandwiches.[Sandwich Type], Sandwich.Bread, Count(Sandwiches.[SandwichID]) AS [Total Sandwiches]
FROM Sandwiches
GROUP BY Sandwiches.[Sandwiches Type], Sandwiches.Bread;

Thanks for answering, it helped my train of thought.

Ignoring directories in Git repositories on Windows

I had similar issues. I work on a Windows tool chain with a shared repository with Linux guys, and they happily create files with the same (except for case) names in a given folder.

The effect is that I can clone the repository and immediately have dozens of 'modified' files that, if I checked in, would create havoc.

I have Windows set to case sensitive and Git to not ignore case, but it still fails (in the Win32 API calls apparently).

If I gitignore the files then I have to remember to not track the .gitignore file.

But I found a good answer here:

http://archive.robwilkerson.org/2010/03/02/git-tip-ignore-changes-to-tracked-files/index.html

How to check for valid email address?

I see a lot of complicated answers here. Some of them, fail to knowledge simple, true email address, or have false positives. Below, is the simplest way of testing that the string would be a valid email. It tests against 2 and 3 letter TLD's. Now that you technically can have larger ones, you may wish to increase the 3 to 4, 5 or even 10.

import re
def valid_email(email):
  return bool(re.search(r"^[\w\.\+\-]+\@[\w]+\.[a-z]{2,3}$", email))

How do I "shake" an Android device within the Android emulator to bring up the dev menu to debug my React Native app

It might be not direct solution, but I've created a lib that allows you to use 3 fingers touch instead of shake to open dev menu, when in development mode

https://github.com/pie6k/react-native-dev-menu-on-touch

You only have to wrap your app inside:

import DevMenuOnTouch from 'react-native-dev-menu-on-touch'; // or: import { DevMenuOnTouch } from 'react-native-dev-menu-on-touch'

class YourRootApp extends Component {
  render() {
    return (
      <DevMenuOnTouch>
        <YourApp />
      </DevMenuOnTouch>
    );
  }
}

It's really useful when you have to debug on real device and you have co-workers sitting next to you.

How to convert int to float in C?

integer division in C truncates the result so 50/100 will give you 0

If you want to get the desired result try this :

((float)number/total)*100

or

50.0/100

Why is the time complexity of both DFS and BFS O( V + E )

It's O(V+E) because each visit to v of V must visit each e of E where |e| <= V-1. Since there are V visits to v of V then that is O(V). Now you have to add V * |e| = E => O(E). So total time complexity is O(V + E).

How to get the indexpath.row when an element is activated?

Use an extension to UITableView to fetch the cell that contains any view:


@Paulw11's answer of setting up a custom cell type with a delegate property that sends messages to the table view is a good way to go, but it requires a certain amount of work to set up.

I think walking the table view cell's view hierarchy looking for the cell is a bad idea. It is fragile - if you later enclose your button in a view for layout purposes, that code is likely to break.

Using view tags is also fragile. You have to remember to set up the tags when you create the cell, and if you use that approach in a view controller that uses view tags for another purpose you can have duplicate tag numbers and your code can fail to work as expected.

I have created an extension to UITableView that lets you get the indexPath for any view that is contained in a table view cell. It returns an Optional that will be nil if the view passed in actually does not fall within a table view cell. Below is the extension source file in it's entirety. You can simply put this file in your project and then use the included indexPathForView(_:) method to find the indexPath that contains any view.

//
//  UITableView+indexPathForView.swift
//  TableViewExtension
//
//  Created by Duncan Champney on 12/23/16.
//  Copyright © 2016-2017 Duncan Champney.
//  May be used freely in for any purpose as long as this 
//  copyright notice is included.

import UIKit

public extension UITableView {
  
  /**
  This method returns the indexPath of the cell that contains the specified view
   
   - Parameter view: The view to find.
   
   - Returns: The indexPath of the cell containing the view, or nil if it can't be found
   
  */
  
    func indexPathForView(_ view: UIView) -> IndexPath? {
        let center = view.center
        let viewCenter = self.convert(center, from: view.superview)
        let indexPath = self.indexPathForRow(at: viewCenter)
        return indexPath
    }
}

To use it, you can simply call the method in the IBAction for a button that's contained in a cell:

func buttonTapped(_ button: UIButton) {
  if let indexPath = self.tableView.indexPathForView(button) {
    print("Button tapped at indexPath \(indexPath)")
  }
  else {
    print("Button indexPath not found")
  }
}

(Note that the indexPathForView(_:) function will only work if the view object it's passed is contained by a cell that's currently on-screen. That's reasonable, since a view that is not on-screen doesn't actually belong to a specific indexPath; it's likely to be assigned to a different indexPath when it's containing cell is recycled.)

EDIT:

You can download a working demo project that uses the above extension from Github: TableViewExtension.git

How to use Switch in SQL Server

Actually i am getting return value from a another sp into @temp and then it @temp =1 then i want to inc the count of @SelectoneCount by 1 and so on. Please let me know what is the correct syntax.

What's wrong with:

IF @Temp = 1 --Or @Temp = 2 also?
BEGIN
    SET @SelectoneCount = @SelectoneCount + 1
END

(Although this does reek of being procedural code - not usually the best way to use SQL)

How do I concatenate a boolean to a string in Python?

Using the so called f strings:

answer = True
myvar = f"the answer is {answer}"

Then if I do

print(myvar)

I will get:

the answer is True

I like f strings because one does not have to worry about the order in which the variables will appear in the printed text, which helps in case one has multiple variables to be printed as strings.

Remove border from buttons

For removing the default 'blue-border' from button on button focus:

In Html:

<button class="new-button">New Button...</button>

And in Css

button.new-button:focus {
    outline: none;
}

Hope it helps :)

ImportError: No Module Named bs4 (BeautifulSoup)

Addendum to the original query: modules.py

help('modules')

$python modules.py

It lists that module bs4 already been installed.

_codecs_kr          blinker             json                six
_codecs_tw          brotli              kaitaistruct        smtpd
_collections        bs4                 keyword             smtplib
_collections_abc    builtins            ldap3               sndhdr
_compat_pickle      bz2                 lib2to3             socket

Proper solution is:

pip install --upgrade bs4

Should solve the problem.

Not only that, it will show same error for other modules as well. So you got to issue the pip command same way as above for those errored module(s).

Importing lodash into angular2 + typescript application

I successfully imported lodash in my project with the following commands:

npm install lodash --save
typings install lodash --save

Then i imported it in the following way:

import * as _ from 'lodash';

and in systemjs.config.js i defined this:

map: { 'lodash' : 'node_modules/lodash/lodash.js' }

How to convert a string to lower or upper case in Ruby

Ruby has a few methods for changing the case of strings. To convert to lowercase, use downcase:

"hello James!".downcase    #=> "hello james!"

Similarly, upcase capitalizes every letter and capitalize capitalizes the first letter of the string but lowercases the rest:

"hello James!".upcase      #=> "HELLO JAMES!"
"hello James!".capitalize  #=> "Hello james!"
"hello James!".titleize    #=> "Hello James!"

If you want to modify a string in place, you can add an exclamation point to any of those methods:

string = "hello James!"
string.downcase!
string   #=> "hello james!"

Refer to the documentation for String for more information.

Error:Execution failed for task ':app:compileDebugKotlin'. > Compilation error. See log for more details

I Had the same problem and finally reached to the solution.

add "--stacktrace --debug" to your command-line options(File -> Settings -> Compiler) then run it. This will show the problem(unwanted code) in your code.

Extract first and last row of a dataframe in pandas

Here is the same style as in large datasets:

x = df[:5]
y = pd.DataFrame([['...']*df.shape[1]], columns=df.columns, index=['...'])
z = df[-5:]
frame = [x, y, z]
result = pd.concat(frame)

print(result)

Output:

                     date  temp
0     1981-01-01 00:00:00  20.7
1     1981-01-02 00:00:00  17.9
2     1981-01-03 00:00:00  18.8
3     1981-01-04 00:00:00  14.6
4     1981-01-05 00:00:00  15.8
...                   ...   ...
3645  1990-12-27 00:00:00    14
3646  1990-12-28 00:00:00  13.6
3647  1990-12-29 00:00:00  13.5
3648  1990-12-30 00:00:00  15.7
3649  1990-12-31 00:00:00    13

Javascript wait() function

Javascript isn't threaded, so a "wait" would freeze the entire page (and probably cause the browser to stop running the script entirely).

To specifically address your problem, you should remove the brackets after donothing in your setTimeout call, and make waitsecs a number not a string:

console.log('before');
setTimeout(donothing,500); // run donothing after 0.5 seconds
console.log('after');

But that won't stop execution; "after" will be logged before your function runs.

To wait properly, you can use anonymous functions:

console.log('before');
setTimeout(function(){
    console.log('after');
},500);

All your variables will still be there in the "after" section. You shouldn't chain these - if you find yourself needing to, you need to look at how you're structuring the program. Also you may want to use setInterval / clearInterval if it needs to loop.

Calculate RSA key fingerprint

$ ssh-add -l 

will also work on Mac OS X v10.8 (Mountain Lion) - v10.10 (Yosemite).

It also supports the option -E to specify the fingerprint format so in case MD5 is needed (it's often used, e.g. by GitHub), just add -E md5 to the command.

What is the use of BindingResult interface in spring MVC?

Well its a sequential process. The Request first treat by FrontController and then moves towards our own customize controller with @Controller annotation.

but our controller method is binding bean using modelattribute and we are also performing few validations on bean values.

so instead of moving the request to our controller class, FrontController moves it towards one interceptor which creates the temp object of our bean and the validate the values. if validation successful then bind the temp obj values with our actual bean which is stored in @ModelAttribute otherwise if validation fails it does not bind and moves the resp towards error page or wherever u want.

enter image description here

How to make an input type=button act like a hyperlink and redirect using a get request?

There are several different ways to do that -- first, simply put it inside a form that points to where you want it to go:

<form action="/my/link/location" method="get">
    <input type="submit" value="Go to my link location" 
         name="Submit" id="frm1_submit" />
</form>

This has the advantage of working even without javascript turned on.

Second, use a stand-alone button with javascript:

<input type="submit" value="Go to my link location" 
    onclick="window.location='/my/link/location';" />       

This however, will fail in browsers without JavaScript (Note: this is really bad practice -- you should be using event handlers, not inline code like this -- this is just the simplest way of illustrating the kind of thing I'm talking about.)

The third option is to style an actual link like a button:

<style type="text/css">
.my_content_container a {
    border-bottom: 1px solid #777777;
    border-left: 1px solid #000000;
    border-right: 1px solid #333333;
    border-top: 1px solid #000000;
    color: #000000;
    display: block;
    height: 2.5em;
    padding: 0 1em;
    width: 5em;       
    text-decoration: none;       
}
// :hover and :active styles left as an exercise for the reader.
</style>

<div class="my_content_container">
    <a href="/my/link/location/">Go to my link location</a>
</div>

This has the advantage of working everywhere and meaning what you most likely want it to mean.

How to do jquery code AFTER page loading?

Use load instead of ready:

$(document).load(function () {
 // code here
});

Update You need to use .on() since jQuery 1.8. (http://api.jquery.com/on/)

$(window).on('load', function() {
 // code here
});

From this answer:

According to http://blog.jquery.com/2016/06/09/jquery-3-0-final-released/:

Removed deprecated event aliases

.load, .unload, and .error, deprecated since jQuery 1.8, are no more. Use .on() to register listeners.

https://github.com/jquery/jquery/issues/2286

PHP foreach loop through multidimensional array

If you mean the first and last entry of the array when talking about a.first and a.last, it goes like this:

foreach ($arr_nav as $inner_array) {
    echo reset($inner_array); //apple, orange, pear
    echo end($inner_array); //My Apple, View All Oranges, A Pear
}

arrays in PHP have an internal pointer which you can manipulate with reset, next, end. Retrieving keys/values works with key and current, but using each might be better in many cases..

Retrieving the text of the selected <option> in <select> element

Under HTML5 you are be able to do this:

document.getElementById('test').selectedOptions[0].text

MDN's documentation at https://developer.mozilla.org/en-US/docs/Web/API/HTMLSelectElement/selectedOptions indicates full cross-browser support (as of at least December 2017), including Chrome, Firefox, Edge and mobile browsers, but excluding Internet Explorer.

"relocation R_X86_64_32S against " linking Error

I also had similar problems when trying to link static compiled fontconfig and expat into a linux shared object:

/opt/rh/devtoolset-7/root/usr/libexec/gcc/x86_64-redhat-linux/7/ld: /3rdparty/fontconfig/lib/linux-x86_64/libfontconfig.a(fccfg.o): relocation R_X86_64_32 against `.rodata.str1.1' can not be used when making a shared object; recompile with -fPIC
/opt/rh/devtoolset-7/root/usr/libexec/gcc/x86_64-redhat-linux/7/ld: /3rdparty/expat/lib/linux-x86_64/libexpat.a(xmlparse.o): relocation R_X86_64_PC32 against symbol `stderr@@GLIBC_2.2.5' can not be used when making a shared object; recompile with -fPIC
[...]

This contrary to the fact that I was already passing -fPIC flags though CFLAGS variable, and other compilers/linkers variants (clang/lld) were perfectly working with the same build configuration. It ended up that these dependencies control position-independent code settings through despicable autoconf scripts and need --with-pic switch during build configuration on linux gcc/ld combination, and its lack probably overrides same the setting in CFLAGS. Pass the switch to configure script and the dependencies will be correctly compiled with -fPIC.

How do I run a program from command prompt as a different user and as an admin

Runas doesn't magically run commands as an administrator, it runs them as whatever account you provide credentials for. If it's not an administrator account, runas doesn't care.

Generate random integers between 0 and 9

Best way is to use import Random function

import random
print(random.sample(range(10), 10))

or without any library import:

n={} 
for i in range(10):
    n[i]=i

for p in range(10):
    print(n.popitem()[1])

here the popitems removes and returns an arbitrary value from the dictionary n.

How to detect scroll direction

You can use this simple plugin to add scrollUp and scrollDown to your jQuery

https://github.com/phpust/JQueryScrollDetector

var lastScrollTop = 0;
var action = "stopped";
var timeout = 100;
// Scroll end detector:
$.fn.scrollEnd = function(callback, timeout) {    
      $(this).scroll(function(){
        // get current scroll top 
        var st = $(this).scrollTop();
        var $this = $(this);
        // fix for page loads
        if (lastScrollTop !=0 )
        {
            // if it's scroll up
            if (st < lastScrollTop){
                action = "scrollUp";
            } 
            // else if it's scroll down
            else if (st > lastScrollTop){
                action = "scrollDown";
            }
        }
        // set the current scroll as last scroll top
        lastScrollTop = st;
        // check if scrollTimeout is set then clear it
        if ($this.data('scrollTimeout')) {
          clearTimeout($this.data('scrollTimeout'));
        }
        // wait until timeout done to overwrite scrolls output
        $this.data('scrollTimeout', setTimeout(callback,timeout));
    });
};

$(window).scrollEnd(function(){
    if(action!="stopped"){
        //call the event listener attached to obj.
        $(document).trigger(action); 
    }
}, timeout);

How do I create a MongoDB dump of my database?

If your database in the local system. Then you type the below command. for Linux terminal

mongodump -h SERVER_NAME:PORT -d DATABASE_NAME

If database user and password are there then you below code.

mongodump -h SERVER_NAME:PORT -d DATABASE_NAME -u DATABASE_USER -p PASSWORD

This worked very well in my Linux terminal.

Android emulator: could not get wglGetExtensionsStringARB error

I ran into this issue running Android Studio 1.4. In the Android Virtual Device (AVD) Manager, I had checked the 'Use Host GPU' box, thinking this would give me some sort of boost in the emulator's speed.
Android Studio will let you choose a device that's configured that way, and it will show you the command it used to start the virtual device: Android Studio 'Run' window output

but for some reason, it doesn't warn you that the program crashed, and it doesn't show you the stderr message that you would see had you run it from the command line yourself: Output as run on the command line

When I ran it from Android Studio, I didn't see the dialog box in the screenshot above, though it shows up just fine when you run the command from the command line, so I just sat there patiently for a few minutes while nothing happened.
As pointed out elsewhere, the drivers needed for the Use Host GPU option are not yet available. Reading through that post, it appears that this setting can be used with some Intel CPUs but not the ARM chip I chose (see CPU/ABI setting below).

My solution was to just uncheck the "Use Host GPU" box which is near the bottom of the window opened through the 'edit' option after choosing the virtual device in the Android Virtual Devices tab in the AVD Manager. You can get to the AVD manager directly in Windows at
%ANDROID_HOME%\AVD Manager.exe
where in my Windows 8 install, %ANDROID_HOME% resolved to
c:\users\myusername\AppData\Local\Android\Sdk

I don't have it running on Linux at the moment, but I'd assume it's in a similar path there, i.e.:
${ANDROID_HOME}/

After unchecking the 'Use Host GPU' box, I opted to check the 'Snapshot' box next to it (as I understand, that stores a copy of the already-built vm so it doesn't need to get rebuilt every time, which should save some startup time for future instances). Here are the full settings I used:
Edit Android Virtual Device (AVD) window screenshot

Can the Twitter Bootstrap Carousel plugin fade in and out on slide transition

Yes. Bootstrap uses CSS transitions so it can be done easily without any Javascript. Just use CSS3. Please take a look at

carousel.carousel-fade

in the CSS of the following examples:

DNS problem, nslookup works, ping doesn't

I think this behavior can be turned off, but Window's online help wasn't extremely clear:

If you disable NetBIOS over TCP/IP, you cannot use broadcast-based NetBIOS name resolution to resolve computer names to IP addresses for computers on the same network segment. If your computers are on the same network segment, and NetBIOS over TCP/IP is disabled, you must install a DNS server and either have the computers register with DNS (or manually configure DNS records) or configure entries in the local Hosts file for each computer.

In Windows XP, there is a checkbox:

Advanced TCP/IP Settings

[ ] Enable LMHOSTS lookup

There is also a book that covers this at length, "Networking Personal Computers with TCP/IP: Building TCP/IP Networks (old O'Reilly book)". Unfortunately, I cannot look it up because I disposed of my copy a while ago.

VS Code - Search for text in all files in a directory

A simple answer is to click the magnifying glass on the left side bar

What is difference between monolithic and micro kernel?

Monolithic kernel

All the parts of a kernel like the Scheduler, File System, Memory Management, Networking Stacks, Device Drivers, etc., are maintained in one unit within the kernel in Monolithic Kernel

Advantages

•Faster processing

Disadvantages

•Crash Insecure •Porting Inflexibility •Kernel Size explosion

Examples •MS-DOS, Unix, Linux

Micro kernel

Only the very important parts like IPC(Inter process Communication), basic scheduler, basic memory handling, basic I/O primitives etc., are put into the kernel. Communication happen via message passing. Others are maintained as server processes in User Space

Advantages

•Crash Resistant, Portable, Smaller Size

Disadvantages

•Slower Processing due to additional Message Passing

Examples •Windows NT

Query to display all tablespaces in a database and datafiles

SELECT a.file_name,
       substr(A.tablespace_name,1,14) tablespace_name,
       trunc(decode(A.autoextensible,'YES',A.MAXSIZE-A.bytes+b.free,'NO',b.free)/1024/1024) free_mb,
       trunc(a.bytes/1024/1024) allocated_mb,
       trunc(A.MAXSIZE/1024/1024) capacity,
       a.autoextensible ae
FROM (
     SELECT file_id, file_name,
            tablespace_name,
            autoextensible,
            bytes,
            decode(autoextensible,'YES',maxbytes,bytes) maxsize
     FROM   dba_data_files
     GROUP BY file_id, file_name,
              tablespace_name,
              autoextensible,
              bytes,
              decode(autoextensible,'YES',maxbytes,bytes)
     ) a,
     (SELECT file_id,
             tablespace_name,
             sum(bytes) free
      FROM   dba_free_space
      GROUP BY file_id,
               tablespace_name
      ) b
WHERE a.file_id=b.file_id(+)
AND A.tablespace_name=b.tablespace_name(+)
ORDER BY A.tablespace_name ASC; 

Encrypt Password in Configuration Files?

A simple way of doing this is to use Password Based Encryption in Java. This allows you to encrypt and decrypt a text by using a password.

This basically means initializing a javax.crypto.Cipher with algorithm "AES/CBC/PKCS5Padding" and getting a key from javax.crypto.SecretKeyFactory with the "PBKDF2WithHmacSHA512" algorithm.

Here is a code example (updated to replace the less secure MD5-based variant):

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.AlgorithmParameters;
import java.security.GeneralSecurityException;
import java.security.NoSuchAlgorithmException;
import java.security.spec.InvalidKeySpecException;
import java.util.Base64;
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.PBEKeySpec;
import javax.crypto.spec.SecretKeySpec;

public class ProtectedConfigFile {

    public static void main(String[] args) throws Exception {
        String password = System.getProperty("password");
        if (password == null) {
            throw new IllegalArgumentException("Run with -Dpassword=<password>");
        }

        // The salt (probably) can be stored along with the encrypted data
        byte[] salt = new String("12345678").getBytes();

        // Decreasing this speeds down startup time and can be useful during testing, but it also makes it easier for brute force attackers
        int iterationCount = 40000;
        // Other values give me java.security.InvalidKeyException: Illegal key size or default parameters
        int keyLength = 128;
        SecretKeySpec key = createSecretKey(password.toCharArray(),
                salt, iterationCount, keyLength);

        String originalPassword = "secret";
        System.out.println("Original password: " + originalPassword);
        String encryptedPassword = encrypt(originalPassword, key);
        System.out.println("Encrypted password: " + encryptedPassword);
        String decryptedPassword = decrypt(encryptedPassword, key);
        System.out.println("Decrypted password: " + decryptedPassword);
    }

    private static SecretKeySpec createSecretKey(char[] password, byte[] salt, int iterationCount, int keyLength) throws NoSuchAlgorithmException, InvalidKeySpecException {
        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA512");
        PBEKeySpec keySpec = new PBEKeySpec(password, salt, iterationCount, keyLength);
        SecretKey keyTmp = keyFactory.generateSecret(keySpec);
        return new SecretKeySpec(keyTmp.getEncoded(), "AES");
    }

    private static String encrypt(String property, SecretKeySpec key) throws GeneralSecurityException, UnsupportedEncodingException {
        Cipher pbeCipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        pbeCipher.init(Cipher.ENCRYPT_MODE, key);
        AlgorithmParameters parameters = pbeCipher.getParameters();
        IvParameterSpec ivParameterSpec = parameters.getParameterSpec(IvParameterSpec.class);
        byte[] cryptoText = pbeCipher.doFinal(property.getBytes("UTF-8"));
        byte[] iv = ivParameterSpec.getIV();
        return base64Encode(iv) + ":" + base64Encode(cryptoText);
    }

    private static String base64Encode(byte[] bytes) {
        return Base64.getEncoder().encodeToString(bytes);
    }

    private static String decrypt(String string, SecretKeySpec key) throws GeneralSecurityException, IOException {
        String iv = string.split(":")[0];
        String property = string.split(":")[1];
        Cipher pbeCipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        pbeCipher.init(Cipher.DECRYPT_MODE, key, new IvParameterSpec(base64Decode(iv)));
        return new String(pbeCipher.doFinal(base64Decode(property)), "UTF-8");
    }

    private static byte[] base64Decode(String property) throws IOException {
        return Base64.getDecoder().decode(property);
    }
}

One problem remains: Where should you store the password that you use to encrypt the passwords? You can store it in the source file and obfuscate it, but it's not too hard to find it again. Alternatively, you can give it as a system property when you start the Java process (-DpropertyProtectionPassword=...).

The same issue remains if you use the KeyStore, which also is protected by a password. Basically, you will need to have one master password somewhere, and it's pretty hard to protect.

Remote branch is not showing up in "git branch -r"

Update your remote if you still haven't done so:

$ git remote update
$ git branch -r

How to keep :active css style after click a button

CSS

:active denotes the interaction state (so for a button will be applied during press), :focus may be a better choice here. However, the styling will be lost once another element gains focus.

The final potential alternative using CSS would be to use :target, assuming the items being clicked are setting routes (e.g. anchors) within the page- however this can be interrupted if you are using routing (e.g. Angular), however this doesnt seem the case here.

_x000D_
_x000D_
.active:active {_x000D_
  color: red;_x000D_
}_x000D_
.focus:focus {_x000D_
  color: red;_x000D_
}_x000D_
:target {_x000D_
  color: red;_x000D_
}
_x000D_
<button class='active'>Active</button>_x000D_
<button class='focus'>Focus</button>_x000D_
<a href='#target1' id='target1' class='target'>Target 1</a>_x000D_
<a href='#target2' id='target2' class='target'>Target 2</a>_x000D_
<a href='#target3' id='target3' class='target'>Target 3</a>
_x000D_
_x000D_
_x000D_

Javascript / jQuery

As such, there is no way in CSS to absolutely toggle a styled state- if none of the above work for you, you will either need to combine with a change in your HTML (e.g. based on a checkbox) or programatically apply/remove a class using e.g. jQuery

_x000D_
_x000D_
$('button').on('click', function(){_x000D_
    $('button').removeClass('selected');_x000D_
    $(this).addClass('selected');_x000D_
});
_x000D_
button.selected{_x000D_
  color:red;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
_x000D_
<button>Item</button><button>Item</button><button>Item</button>_x000D_
  
_x000D_
_x000D_
_x000D_

android : Error converting byte to dex

In case it helps someone, in my case I was using a custom package in release mode instead of in debug mode.

I just changed the package from "release" to "debug" and it worked.

Pass path with spaces as parameter to bat file

Use "%~1". %~1 alone removes surrounding quotes. However since you can't know whether the input parameter %1 has quotes or not, you should ensure by "%~1" that they are added for sure. This is especially helpful when concatenating variables, e.g. convert.exe "%~1.input" "%~1.output"

How to calculate the sum of all columns of a 2D numpy array (efficiently)

Other alternatives for summing the columns are

numpy.einsum('ij->j', a)

and

numpy.dot(a.T, numpy.ones(a.shape[0]))

If the number of rows and columns is in the same order of magnitude, all of the possibilities are roughly equally fast:

enter image description here

If there are only a few columns, however, both the einsum and the dot solution significantly outperform numpy's sum (note the log-scale):

enter image description here


Code to reproduce the plots:

import numpy
import perfplot


def numpy_sum(a):
    return numpy.sum(a, axis=1)


def einsum(a):
    return numpy.einsum('ij->i', a)


def dot_ones(a):
    return numpy.dot(a, numpy.ones(a.shape[1]))


perfplot.save(
    "out1.png",
    # setup=lambda n: numpy.random.rand(n, n),
    setup=lambda n: numpy.random.rand(n, 3),
    n_range=[2**k for k in range(15)],
    kernels=[numpy_sum, einsum, dot_ones],
    logx=True,
    logy=True,
    xlabel='len(a)',
    )

LINQ to SQL - How to select specific columns and return strongly typed list

The issue was in fact that one of the properties was a relation to another table. I changed my LINQ query so that it could get the same data from a different method without needing to load the entire table.

Thank you all for your help!

How to add a set path only for that batch file executing?

Just like any other environment variable, with SET:

SET PATH=%PATH%;c:\whatever\else

If you want to have a little safety check built in first, check to see if the new path exists first:

IF EXIST c:\whatever\else SET PATH=%PATH%;c:\whatever\else

If you want that to be local to that batch file, use setlocal:

setlocal
set PATH=...
set OTHERTHING=...

@REM Rest of your script

Read the docs carefully for setlocal/endlocal , and have a look at the other references on that site - Functions is pretty interesting too and the syntax is tricky.

The Syntax page should get you started with the basics.

CRON job to run on the last day of the month

The last day of month can be 28-31 depending on what month it is (Feb, March etc). However in either of these cases, the next day is always 1st of next month. So we can use that to make sure we run some job always on the last day of a month using the code below:

0 8 28-31 * * [ "$(date +%d -d tomorrow)" = "01" ] && /your/script.sh

Rebasing remote branches in Git

It comes down to whether the feature is used by one person or if others are working off of it.

You can force the push after the rebase if it's just you:

git push origin feature -f

However, if others are working on it, you should merge and not rebase off of master.

git merge master
git push origin feature

This will ensure that you have a common history with the people you are collaborating with.

On a different level, you should not be doing back-merges. What you are doing is polluting your feature branch's history with other commits that don't belong to the feature, making subsequent work with that branch more difficult - rebasing or not.

This is my article on the subject called branch per feature.

Hope this helps.

Resizing image in Java

Simple way in Java

public void resize(String inputImagePath,
            String outputImagePath, int scaledWidth, int scaledHeight)
            throws IOException {
        // reads input image
        File inputFile = new File(inputImagePath);
        BufferedImage inputImage = ImageIO.read(inputFile);
 
        // creates output image
        BufferedImage outputImage = new BufferedImage(scaledWidth,
                scaledHeight, inputImage.getType());
 
        // scales the input image to the output image
        Graphics2D g2d = outputImage.createGraphics();
        g2d.drawImage(inputImage, 0, 0, scaledWidth, scaledHeight, null);
        g2d.dispose();
 
        // extracts extension of output file
        String formatName = outputImagePath.substring(outputImagePath
                .lastIndexOf(".") + 1);
 
        // writes to output file
        ImageIO.write(outputImage, formatName, new File(outputImagePath));
    }

Place a button right aligned

Another possibility is to use an absolute positioning oriented to the right. You can do it this way:

style="position: absolute; right: 0;"

npm start error with create-react-app

Author of Create React App checking in.

You absolutely should not be installing react-scripts globally.
You also don't need ./node_modules/react-scripts/bin/ in package.json as this answer implies.

If you see this:

npm ERR! [email protected] start: `react-scripts start`
npm ERR! spawn ENOENT

It just means something went wrong when dependencies were installed the first time.

I suggest doing these three steps:

  1. npm install -g npm@latest to update npm because it is sometimes buggy.
  2. rm -rf node_modules to remove the existing modules.
  3. npm install to re-install the project dependencies.

This should fix the problem.
If it doesn't, please file an issue with a link to your project and versions of Node and npm.

How to add two edit text fields in an alert dialog

Check this code in alert box have edit textview when click OK it displays on screen using toast.

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    final AlertDialog.Builder alert = new AlertDialog.Builder(this);
    final EditText input = new EditText(this);
    alert.setView(input);
    alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int whichButton) {
            String value = input.getText().toString().trim();
            Toast.makeText(getApplicationContext(), value, 
                Toast.LENGTH_SHORT).show();
        }
    });

    alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int whichButton) {
            dialog.cancel();
        }
    });
    alert.show();               
}

Get a DataTable Columns DataType

What you want to use is this property:

dt.Columns[0].DataType

The DataType property will set to one of the following:

Boolean
Byte
Char
DateTime
Decimal
Double
Int16
Int32
Int64
SByte
Single
String
TimeSpan
UInt16
UInt32
UInt64

DataColumn.DataType Property MSDN Reference

How to check the extension of a filename in a bash script?

You could also do:

   if [ "${FILE##*.}" = "txt" ]; then
       # operation for txt files here
   fi

Open link in new tab or window

You should add the target="_blank" and rel="noopener noreferrer" in the anchor tag.

For example:

<a target="_blank" rel="noopener noreferrer" href="http://your_url_here.html">Link</a>

Adding rel="noopener noreferrer" is not mandatory, but it's a recommended security measure. More information can be found in the links below.

Source:

Detect network connection type on Android

Currently, only MOBILE and WIFI is supported. Take a look and human readable type function.

In bash, how to store a return value in a variable?

Something like this could be used, and still maintaining meanings of return (to return control signals) and echo (to return information) and logging statements (to print debug/info messages).

v_verbose=1
v_verbose_f=""         # verbose file name
FLAG_BGPID=""

e_verbose() {
        if [[ $v_verbose -ge 0 ]]; then
                v_verbose_f=$(tempfile)
                tail -f $v_verbose_f &
                FLAG_BGPID="$!"
        fi
}

d_verbose() {
        if [[ x"$FLAG_BGPID" != "x" ]]; then
                kill $FLAG_BGPID > /dev/null
                FLAG_BGPID=""
                rm -f $v_verbose_f > /dev/null
        fi
}

init() {
        e_verbose

        trap cleanup SIGINT SIGQUIT SIGKILL SIGSTOP SIGTERM SIGHUP SIGTSTP
}

cleanup() {
        d_verbose
}

init

fun1() {
    echo "got $1" >> $v_verbose_f
    echo "got $2" >> $v_verbose_f
    echo "$(( $1 + $2 ))"
    return 0
}

a=$(fun1 10 20)
if [[ $? -eq 0 ]]; then
    echo ">>sum: $a"
else
    echo "error: $?"
fi
cleanup

In here, I'm redirecting debug messages to separate file, that is watched by tail, and if there is any changes then printing the change, trap is used to make sure that background process always ends.

This behavior can also be achieved using redirection to /dev/stderr, But difference can be seen at the time of piping output of one command to input of other command.

Center align "span" text inside a div

If you know the width of the span you could just stuff in a left margin.

Try this:

.center { text-align: center}
div.center span { display: table; }

Add the "center: class to your .

If you want some spans centered, but not others, replace the "div.center span" in your style sheet to a class (e.g "center-span") and add that class to the span.

Get top first record from duplicate records having no unique identity

The answer depends on specifically what you mean by the "top 1000 distinct" records.

If you mean that you want to return at most 1000 distinct records, regardless of how many duplicates are in the table, then write this:

SELECT DISTINCT TOP 1000 id, uname, tel
FROM Users
ORDER BY <sort_columns>

If you only want to search the first 1000 rows in the table, and potentially return much fewer than 1000 distinct rows, then you would write it with a subquery or CTE, like this:

SELECT DISTINCT *
FROM
(
    SELECT TOP 1000 id, uname, tel
    FROM Users
    ORDER BY <sort_columns>
) u

The ORDER BY is of course optional if you don't care about which records you return.

Open images? Python

if location == a2:
    img = Image.open("picture.jpg")
    Img.show

Make sure the name of the image is in parantheses this should work

What is the proper way to format a multi-line dict in Python?

I use #3. Same for long lists, tuples, etc. It doesn't require adding any extra spaces beyond the indentations. As always, be consistent.

mydict = {
    "key1": 1,
    "key2": 2,
    "key3": 3,
}

mylist = [
    (1, 'hello'),
    (2, 'world'),
]

nested = {
    a: [
        (1, 'a'),
        (2, 'b'),
    ],
    b: [
        (3, 'c'),
        (4, 'd'),
    ],
}

Similarly, here's my preferred way of including large strings without introducing any whitespace (like you'd get if you used triple-quoted multi-line strings):

data = (
    "iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAABG"
    "l0RVh0U29mdHdhcmUAQWRvYmUgSW1hZ2VSZWFkeXHJZTwAAAEN"
    "xBRpFYmctaKCfwrBSCrRLuL3iEW6+EEUG8XvIVjYWNgJdhFjIX"
    "rz6pKtPB5e5rmq7tmxk+hqO34e1or0yXTGrj9sXGs1Ib73efh1"
    "AAAABJRU5ErkJggg=="
)

Ignore <br> with CSS?

You can use span elements instead of the br if you want the white space method to work, as it depends on pseudo-elements which are "not defined" for replaced elements.

HTML

<p>
   To break lines<span class="line-break">in a paragraph,</span><span>don't use</span><span>the 'br' element.</span>
</p>

CSS

span {white-space: pre;}

span:after {content: ' ';}

span.line-break {display: block;}

span.line-break:after {content: none;}

DEMO

The line break is simply achieved by setting the appropriate span element to display:block.

By using IDs and/ or Classes in your HTML markup you can easily target every single or combination of span elements by CSS or use CSS selectors like nth-child().

So you can e.g. define different break points by using media queries for a responsive layout.

And you can also simply add/ remove/ toggle classes by Javascript (jQuery).

The "advantage" of this method is its robustness - works in every browser that supports pseudo-elements (see: Can I use - CSS Generated content).

As an alternative it is also possible to add a line break via pseudo-elements:

span.break:before {  
    content: "\A";
    white-space: pre;
}

DEMO

try/catch with InputMismatchException creates infinite loop

As the bError = false statement is never reached in the try block, and the statement is struck to the input taken, it keeps printing the error in infinite loop.

Try using it this way by using hasNextInt()

catch (Exception e) {
            System.out.println("Error!");
           input.hasNextInt();         
        }

Or try using nextLine() coupled with Integer.parseInt() for taking input....

Scanner scan = new Scanner(System.in);

int num1 = Integer.parseInt(scan.nextLine());
int num2 = Integer.parseInt(scan.nextLine());

Simple DateTime sql query

Open up the Access File you are trying to export SQL data to. Delete any Queries that are there. Everytime you run SQL Server Import wizard, even if it fails, it creates a Query in the Access DB that has to be deleted before you can run the SQL export Wizard again.

Change size of axes title and labels in ggplot2

I think a better way to do this is to change the base_size argument. It will increase the text sizes consistently.

g + theme_grey(base_size = 22)

As seen here.

Creating a new column based on if-elif-else condition

To formalize some of the approaches laid out above:

Create a function that operates on the rows of your dataframe like so:

def f(row):
    if row['A'] == row['B']:
        val = 0
    elif row['A'] > row['B']:
        val = 1
    else:
        val = -1
    return val

Then apply it to your dataframe passing in the axis=1 option:

In [1]: df['C'] = df.apply(f, axis=1)

In [2]: df
Out[2]:
   A  B  C
a  2  2  0
b  3  1  1
c  1  3 -1

Of course, this is not vectorized so performance may not be as good when scaled to a large number of records. Still, I think it is much more readable. Especially coming from a SAS background.

Edit

Here is the vectorized version

df['C'] = np.where(
    df['A'] == df['B'], 0, np.where(
    df['A'] >  df['B'], 1, -1)) 

How can I remove the decimal part from JavaScript number?

With ES2015, Math.trunc() is available.

Math.trunc(2.3)                       // 2
Math.trunc(-2.3)                      // -2
Math.trunc(22222222222222222222222.3) // 2.2222222222222223e+22
Math.trunc("2.3")                     // 2
Math.trunc("two")                     // NaN
Math.trunc(NaN)                       // NaN

It's not supported in IE11 or below, but does work in Edge and every other modern browser.

Merge / convert multiple PDF files into one PDF

pdfunite is fine to merge entire PDFs. If you want, for example, pages 2-7 from file1.pdf and pages 1,3,4 from file2.pdf, you have to use pdfseparate to split the files into separate PDFs for each page to give to pdfunite.

At that point you probably want a program with more options. qpdf is the best utility I've found for manipulating PDFs. pdftk is bigger and slower and Red Hat/Fedora don't package it because of its dependency on gcj. Other PDF utilities have Mono or Python dependencies. I found qpdf produced a much smaller output file than using pdfseparate and pdfunite to assemble pages into a 30-page output PDF, 970kB vs. 1,6450 kB. Because it offers many more options, qpdf's command line is not as simple; the original request to merge file1 and file2 can be performed with

qpdf --empty --pages file1.pdf file2.pdf -- merged.pdf

Append String in Swift

let string2 = " there"
var instruction = "look over"

choice 1 :

 instruction += string2;

  println(instruction)

choice 2:

 var Str = instruction + string2;

 println(Str)

ref this

How to return more than one value from a function in Python?

Here is also the code to handle the result:

def foo (a):
    x=a
    y=a*2
    return (x,y)

(x,y) = foo(50)

Create 3D array using Python

If you insist on everything initializing as empty, you need an extra set of brackets on the inside ([[]] instead of [], since this is "a list containing 1 empty list to be duplicated" as opposed to "a list containing nothing to duplicate"):

distance=[[[[]]*n]*n]*n

Do I really need to encode '&' as '&amp;'?

Update (March 2020): The W3C validator no longer complains about escaping URLs.

I was checking why Image URL's need escaping, hence tried it in https://validator.w3.org. The explanation is pretty nice. It highlights that even URL's need to be escaped. [PS:I guess it will unescaped when its consumed since URL's need &. Can anyone clarify?]

<img alt="" src="foo?bar=qut&qux=fop" />

An entity reference was found in the document, but there is no reference by that name defined. Often this is caused by misspelling the reference name, unencoded ampersands, or by leaving off the trailing semicolon (;). The most common cause of this error is unencoded ampersands in URLs as described by the WDG in "Ampersands in URLs". Entity references start with an ampersand (&) and end with a semicolon (;). If you want to use a literal ampersand in your document you must encode it as "&" (even inside URLs!). Be careful to end entity references with a semicolon or your entity reference may get interpreted in connection with the following text. Also keep in mind that named entity references are case-sensitive; &Aelig; and æ are different characters. If this error appears in some markup generated by PHP's session handling code, this article has explanations and solutions to your problem.

Check if datetime instance falls in between other two datetime objects

Do simple compare > and <.

if (dateA>dateB && dateA<dateC)
    //do something

If you care only on time:

if (dateA.TimeOfDay>dateB.TimeOfDay && dateA.TimeOfDay<dateC.TimeOfDay)
    //do something

Is there a good reason I see VARCHAR(255) used so often (as opposed to another length)?

When you say 2^8 you get 256, but the numbers in computers terms begins from the number 0. So, then you got the 255, you can probe it in a internet mask for the IP or in the IP itself.

255 is the maximum value of a 8 bit integer : 11111111 = 255

Does that help?

Hot to get all form elements values using jQuery?

jQuery has very helpful function called serialize.

Demo: http://jsfiddle.net/55xnJ/2/

//Just type:
$("#preview_form").serialize();

//to get result:
single=Single&multiple=Multiple&multiple=Multiple3&check=check2&radio=radio1

Tools for creating Class Diagrams

I always use Gliffy works perfectly and does lots of things including class diagrams.

Authorize a non-admin developer in Xcode / Mac OS

Answer suggested by @Stacy Simpson:

We are struggling with the issue described in these threads and none of the resolutions seem to work:

As I'm new to SO, I cannot post in either thread. (The first one is actually closed and I disagree with the localization reasoning...)

Anyway, we created a work-around using AppleScript that folks may be interested in. The script below should be executed asynchronously prior to launching your automated test:

osascript <script name> <password> &

Here is the script:

on run argv
    # Delay for 10 seconds as this script runs asynchronously to the automation process and is kicked off first.
    delay 10

    # Inspect all running processes
    tell application "System Events"
        set ProcessList to name of every process
        # Determine if authentication is being requested
        if "SecurityAgent" is in ProcessList then
            # Bring this dialogue to the front
            tell application "SecurityAgent" to activate
            # Enter provided password
            keystroke item 1 of argv
            keystroke return
        end if
    end tell
end run

Probably not very secure, but it's the best work-around we've come up with to allow tests to run without requiring user intervention.

Hopefully, I can get enough points to post the answer; or, someone can unprotect this question. Regards.

I need to round a float to two decimal places in Java

You can make use of DecimalFormat to give you the style you wish.

DecimalFormat df = new DecimalFormat("0.00E0");
double number = 1.2975118E7;
System.out.println(df.format(number));  // prints 1.30E7

Since it's in scientific notation, you won't be able to get the number any smaller than 107 without losing that many orders of magnitude of accuracy.

How to position absolute inside a div?

The problem is described (among other) in this article.

#box is relatively positioned, which makes it part of the "flow" of the page. Your other divs are absolutely positioned, so they are removed from the page's "flow".

Page flow means that the positioning of an element effects other elements in the flow.

In other words, as #box now sees the dom, .a and .b are no longer "inside" #box.

To fix this, you would want to make everything relative, or everything absolute.

One way would be:

.a {
   position:relative;
   margin-top:10px;
   margin-left:10px;
   background-color:red;
   width:210px;
   padding: 5px;
}

Capture Image from Camera and Display in Activity

In Activity:

@Override
    protected void onCreate(Bundle savedInstanceState) {
                 image = (ImageView) findViewById(R.id.imageButton);
        image.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                try {
                SimpleDateFormat sdfPic = new SimpleDateFormat(DATE_FORMAT);
                currentDateandTime = sdfPic.format(new Date()).replace(" ", "");
                File imagesFolder = new File(IMAGE_PATH, currentDateandTime);
                imagesFolder.mkdirs();
                Random generator = new Random();
                int n = 10000;
                n = generator.nextInt(n);
                String fname = IMAGE_NAME + n + IMAGE_FORMAT;
                File file = new File(imagesFolder, fname);
                outputFileUri = Uri.fromFile(file);
                cameraIntent= new Intent(
                        android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
                cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);
                                startActivityForResult(cameraIntent, CAMERA_DATA);
                }catch(Exception e) {
                    e.printStackTrace();
                }

            }
        });
           @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch(requestCode) {
        case CAMERA_DATA :
                final int IMAGE_MAX_SIZE = 300;
                try {
                    // Bitmap bitmap;
                    File file = null;
                    FileInputStream fis;
                    BitmapFactory.Options opts;
                    int resizeScale;
                    Bitmap bmp;
                    file = new File(outputFileUri.getPath());
                    // This bit determines only the width/height of the
                    // bitmap
                    // without loading the contents
                    opts = new BitmapFactory.Options();
                    opts.inJustDecodeBounds = true;
                    fis = new FileInputStream(file);
                    BitmapFactory.decodeStream(fis, null, opts);
                    fis.close();

                    // Find the correct scale value. It should be a power of
                    // 2
                    resizeScale = 1;

                    if (opts.outHeight > IMAGE_MAX_SIZE
                            || opts.outWidth > IMAGE_MAX_SIZE) {
                        resizeScale = (int) Math.pow(2, (int) Math.round(Math.log(IMAGE_MAX_SIZE/ (double) Math.max(opts.outHeight, opts.outWidth)) / Math.log(0.5)));
                    }

                    // Load pre-scaled bitmap
                    opts = new BitmapFactory.Options();
                    opts.inSampleSize = resizeScale;
                    fis = new FileInputStream(file);
                    bmp = BitmapFactory.decodeStream(fis, null, opts);
                    Bitmap getBitmapSize = BitmapFactory.decodeResource(
                            getResources(), R.drawable.male);
                    image.setLayoutParams(new RelativeLayout.LayoutParams(
                            200,200));//(width,height);
                    image.setImageBitmap(bmp);
                    image.setRotation(90);
                    fis.close();

                    ByteArrayOutputStream baos = new ByteArrayOutputStream();
                    bmp.compress(Bitmap.CompressFormat.JPEG, 70, baos);
                    imageByte = baos.toByteArray();
                    break;
                } catch (FileNotFoundException e) {

                    e.printStackTrace();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }

in layout.xml:

enter code here
<RelativeLayout
        android:id="@+id/relativeLayout2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content">


        <ImageView
            android:id="@+id/imageButton"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"

                            android:src="@drawable/XXXXXXX"
            android:textAppearance="?android:attr/textAppearanceSmall" />

in manifest.xml:

    <uses-permission android:name="android.permission.CAMERA" />   <uses-feature android:name="android.hardware.camera" />

Which is the best Linux C/C++ debugger (or front-end to gdb) to help teaching programming?

Qt Creator, apart from other goodies, also has a good debugger integration, for CDB, GDB and the Symnbian debugger, on all supported platforms. You don't need to use Qt to use the Qt Creator IDE, nor do you need to use QMake - it also has CMake integration, although QMake is very easy to use.

You may want to use Qt Creator as the IDE to teach programming with, consider it has some good features:

  • Very smart and advanced C++ editor
  • Project and build management tools
  • QMake and CMake integration
  • Integrated, context-sensitive help system
  • Excellent visual debugger (CDB, GDB and Symbian)
  • Supports GCC and VC++
  • Rapid code navigation tools
  • Supports Windows, Linux and Mac OS X

How to get the query string by javascript?

You can easily build a dictionary style collection...

function getQueryStrings() { 
  var assoc  = {};
  var decode = function (s) { return decodeURIComponent(s.replace(/\+/g, " ")); };
  var queryString = location.search.substring(1); 
  var keyValues = queryString.split('&'); 

  for(var i in keyValues) { 
    var key = keyValues[i].split('=');
    if (key.length > 1) {
      assoc[decode(key[0])] = decode(key[1]);
    }
  } 

  return assoc; 
} 

And use it like this...

var qs = getQueryStrings();
var myParam = qs["myParam"]; 

Avoiding NullPointerException in Java

You can couple your Class with Unit Testing using a framework like JUnit. This way your code will be clean (no useless checkings) and you will be sure your instances wont be null.

This is one good reason (of many) to use Unit Testing.

Creating a PDF from a RDLC Report in the Background

You don't need to have a reportViewer control anywhere - you can create the LocalReport on the fly:

var lr = new LocalReport
{
    ReportPath = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location) ?? @"C:\", "Reports", "PathOfMyReport.rdlc"),
    EnableExternalImages = true
};

lr.DataSources.Add(new ReportDataSource("NameOfMyDataSet", model));

string mimeType, encoding, extension;

Warning[] warnings;
string[] streams;
var renderedBytes = lr.Render
    (
        "PDF",
        @"<DeviceInfo><OutputFormat>PDF</OutputFormat><HumanReadablePDF>False</HumanReadablePDF></DeviceInfo>",
        out mimeType,
        out encoding,
        out extension,
        out streams,
        out warnings
    );

var saveAs = string.Format("{0}.pdf", Path.Combine(tempPath, "myfilename"));

var idx = 0;
while (File.Exists(saveAs))
{
    idx++;
    saveAs = string.Format("{0}.{1}.pdf", Path.Combine(tempPath, "myfilename"), idx);
}

using (var stream = new FileStream(saveAs, FileMode.Create, FileAccess.Write))
{
    stream.Write(renderedBytes, 0, renderedBytes.Length);
    stream.Close();
}

lr.Dispose();

You can also add parameters: (lr.SetParameter()), handle subreports: (lr.SubreportProcessing+=YourHandler), or pretty much anything you can think of.

HTML/Javascript change div content

Assuming you're not using jQuery or some other library that makes this sort of thing easier for you, you can just use the element's innerHTML property.

document.getElementById("content").innerHTML = "whatever";

How to import a csv file into MySQL workbench?

At the moment it is not possible to import a CSV (using MySQL Workbench) in all platforms, nor is advised if said file does not reside in the same host as the MySQL server host.

However, you can use mysqlimport.

Example:

mysqlimport --local --compress --user=username --password --host=hostname \
--fields-terminated-by=',' Acme sales.part_*

In this example mysqlimport is instructed to load all of the files named "sales" with an extension starting with "part_". This is a convenient way to load all of the files created in the "split" example. Use the --compress option to minimize network traffic. The --fields-terminated-by=',' option is used for CSV files and the --local option specifies that the incoming data is located on the client. Without the --local option, MySQL will look for the data on the database host, so always specify the --local option.

There is useful information on the subject in AWS RDS documentation.

how to use getSharedPreferences in android

If someone used this:

val sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context)

PreferenceManager is now depricated, refactor to this:

val sharedPreferences = context.getSharedPreferences(context.packageName + "_preferences", Context.MODE_PRIVATE)

How to lock specific cells but allow filtering and sorting

I know this is super old, but comes up whenever I google this issue. You can unprotect the range as given in the above cells and then add data validation to the unprotected cells to reference something outrageous like "423fdgfdsg3254fer" and then if users try to edit any those cells, they will be unable to, but you're sorting and filtering will now work.

Is it possible for UIStackView to scroll?

Just add this to viewdidload:

let insets = UIEdgeInsetsMake(20.0, 0.0, 0.0, 0.0)
scrollVIew.contentInset = insets
scrollVIew.scrollIndicatorInsets = insets

source: https://developer.apple.com/library/ios/documentation/UserExperience/Conceptual/AutolayoutPG/LayoutUsingStackViews.html

Does Spring @Transactional attribute work on a private method?

Yes, it is possible to use @Transactional on private methods, but as others have mentioned this won't work out of the box. You need to use AspectJ. It took me some time to figure out how to get it working. I will share my results.

I chose to use compile-time weaving instead of load-time weaving because I think it's an overall better option. Also, I'm using Java 8 so you may need to adjust some parameters.

First, add the dependency for aspectjrt.

<dependency>
    <groupId>org.aspectj</groupId>
    <artifactId>aspectjrt</artifactId>
    <version>1.8.8</version>
</dependency>

Then add the AspectJ plugin to do the actual bytecode weaving in Maven (this may not be a minimal example).

<plugin>
    <groupId>org.codehaus.mojo</groupId>
    <artifactId>aspectj-maven-plugin</artifactId>
    <version>1.8</version>
    <configuration>
        <complianceLevel>1.8</complianceLevel>
        <source>1.8</source>
        <target>1.8</target>
        <aspectLibraries>
            <aspectLibrary>
                <groupId>org.springframework</groupId>
                <artifactId>spring-aspects</artifactId>
            </aspectLibrary>
        </aspectLibraries>
    </configuration>
    <executions>
        <execution>
            <goals>
                <goal>compile</goal>
            </goals>
        </execution>
    </executions>
</plugin>

Finally add this to your config class

@EnableTransactionManagement(mode = AdviceMode.ASPECTJ)

Now you should be able to use @Transactional on private methods.

One caveat to this approach: You will need to configure your IDE to be aware of AspectJ otherwise if you run the app via Eclipse for example it may not work. Make sure you test against a direct Maven build as a sanity check.

how to redirect to home page

maybe

var re = /^https?:\/\/[^/]+/i;
window.location.href = re.exec(window.location.href)[0];

is what you're looking for?

Find the files that have been changed in last 24 hours

You can do that with

find . -mtime 0

From man find:

[The] time since each file was last modified is divided by 24 hours and any remainder is discarded. That means that to match -mtime 0, a file will have to have a modification in the past which is less than 24 hours ago.

range() for floats

There will be of course some rounding errors, so this is not perfect, but this is what I use generally for applications, which don't require high precision. If you wanted to make this more accurate, you could add an extra argument to specify how to handle rounding errors. Perhaps passing a rounding function might make this extensible and allow the programmer to specify how to handle rounding errors.

arange = lambda start, stop, step: [i + step * i for i in range(int((stop - start) / step))]

If I write:

arange(0, 1, 0.1)

It will output:

[0.0, 0.1, 0.2, 0.30000000000000004, 0.4, 0.5, 0.6000000000000001, 0.7000000000000001, 0.8, 0.9]

Handling key-press events (F1-F12) using JavaScript and jQuery, cross-browser

Try this solution if works.

window.onkeypress = function(e) {
    if ((e.which || e.keyCode) == 116) {
        alert("fresh");
    }
}

How to parse the Manifest.mbdb file in an iOS 4.0 iTunes Backup

Thank you, user374559 and reneD -- that code and description is very helpful.

My stab at some Python to parse and print out the information in a Unix ls-l like format:

#!/usr/bin/env python
import sys

def getint(data, offset, intsize):
    """Retrieve an integer (big-endian) and new offset from the current offset"""
    value = 0
    while intsize > 0:
        value = (value<<8) + ord(data[offset])
        offset = offset + 1
        intsize = intsize - 1
    return value, offset

def getstring(data, offset):
    """Retrieve a string and new offset from the current offset into the data"""
    if data[offset] == chr(0xFF) and data[offset+1] == chr(0xFF):
        return '', offset+2 # Blank string
    length, offset = getint(data, offset, 2) # 2-byte length
    value = data[offset:offset+length]
    return value, (offset + length)

def process_mbdb_file(filename):
    mbdb = {} # Map offset of info in this file => file info
    data = open(filename).read()
    if data[0:4] != "mbdb": raise Exception("This does not look like an MBDB file")
    offset = 4
    offset = offset + 2 # value x05 x00, not sure what this is
    while offset < len(data):
        fileinfo = {}
        fileinfo['start_offset'] = offset
        fileinfo['domain'], offset = getstring(data, offset)
        fileinfo['filename'], offset = getstring(data, offset)
        fileinfo['linktarget'], offset = getstring(data, offset)
        fileinfo['datahash'], offset = getstring(data, offset)
        fileinfo['unknown1'], offset = getstring(data, offset)
        fileinfo['mode'], offset = getint(data, offset, 2)
        fileinfo['unknown2'], offset = getint(data, offset, 4)
        fileinfo['unknown3'], offset = getint(data, offset, 4)
        fileinfo['userid'], offset = getint(data, offset, 4)
        fileinfo['groupid'], offset = getint(data, offset, 4)
        fileinfo['mtime'], offset = getint(data, offset, 4)
        fileinfo['atime'], offset = getint(data, offset, 4)
        fileinfo['ctime'], offset = getint(data, offset, 4)
        fileinfo['filelen'], offset = getint(data, offset, 8)
        fileinfo['flag'], offset = getint(data, offset, 1)
        fileinfo['numprops'], offset = getint(data, offset, 1)
        fileinfo['properties'] = {}
        for ii in range(fileinfo['numprops']):
            propname, offset = getstring(data, offset)
            propval, offset = getstring(data, offset)
            fileinfo['properties'][propname] = propval
        mbdb[fileinfo['start_offset']] = fileinfo
    return mbdb

def process_mbdx_file(filename):
    mbdx = {} # Map offset of info in the MBDB file => fileID string
    data = open(filename).read()
    if data[0:4] != "mbdx": raise Exception("This does not look like an MBDX file")
    offset = 4
    offset = offset + 2 # value 0x02 0x00, not sure what this is
    filecount, offset = getint(data, offset, 4) # 4-byte count of records 
    while offset < len(data):
        # 26 byte record, made up of ...
        fileID = data[offset:offset+20] # 20 bytes of fileID
        fileID_string = ''.join(['%02x' % ord(b) for b in fileID])
        offset = offset + 20
        mbdb_offset, offset = getint(data, offset, 4) # 4-byte offset field
        mbdb_offset = mbdb_offset + 6 # Add 6 to get past prolog
        mode, offset = getint(data, offset, 2) # 2-byte mode field
        mbdx[mbdb_offset] = fileID_string
    return mbdx

def modestr(val):
    def mode(val):
        if (val & 0x4): r = 'r'
        else: r = '-'
        if (val & 0x2): w = 'w'
        else: w = '-'
        if (val & 0x1): x = 'x'
        else: x = '-'
        return r+w+x
    return mode(val>>6) + mode((val>>3)) + mode(val)

def fileinfo_str(f, verbose=False):
    if not verbose: return "(%s)%s::%s" % (f['fileID'], f['domain'], f['filename'])
    if (f['mode'] & 0xE000) == 0xA000: type = 'l' # symlink
    elif (f['mode'] & 0xE000) == 0x8000: type = '-' # file
    elif (f['mode'] & 0xE000) == 0x4000: type = 'd' # dir
    else: 
        print >> sys.stderr, "Unknown file type %04x for %s" % (f['mode'], fileinfo_str(f, False))
        type = '?' # unknown
    info = ("%s%s %08x %08x %7d %10d %10d %10d (%s)%s::%s" % 
            (type, modestr(f['mode']&0x0FFF) , f['userid'], f['groupid'], f['filelen'], 
             f['mtime'], f['atime'], f['ctime'], f['fileID'], f['domain'], f['filename']))
    if type == 'l': info = info + ' -> ' + f['linktarget'] # symlink destination
    for name, value in f['properties'].items(): # extra properties
        info = info + ' ' + name + '=' + repr(value)
    return info

verbose = True
if __name__ == '__main__':
    mbdb = process_mbdb_file("Manifest.mbdb")
    mbdx = process_mbdx_file("Manifest.mbdx")
    for offset, fileinfo in mbdb.items():
        if offset in mbdx:
            fileinfo['fileID'] = mbdx[offset]
        else:
            fileinfo['fileID'] = "<nofileID>"
            print >> sys.stderr, "No fileID found for %s" % fileinfo_str(fileinfo)
        print fileinfo_str(fileinfo, verbose)

How can I make a Python script standalone executable to run without ANY dependency?

py2exe will make the EXE file you want, but you need to have the same version of MSVCR90.dll on the machine you're going to use your new EXE file.

See Tutorial for more information.

How to call Android contacts list?

I do it this way for Android 2.2 Froyo release: basically use eclipse to create a class like: public class SomePickContactName extends Activity

then insert this code. Remember to add the private class variables and CONSTANTS referenced in my version of the code:

protected void onCreate(Bundle savedInstanceState) 
{
  super.onCreate(savedInstanceState);       
  Intent intentContact = new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI); 
  startActivityForResult(intentContact, PICK_CONTACT);
}//onCreate

public void onActivityResult(int requestCode, int resultCode, Intent intent) 
{

  if (requestCode == PICK_CONTACT)
  {         
    getContactInfo(intent);         
    // Your class variables now have the data, so do something with it. 
  }
}//onActivityResult

protected void getContactInfo(Intent intent)
{

   Cursor cursor =  managedQuery(intent.getData(), null, null, null, null);      
   while (cursor.moveToNext()) 
   {           
       String contactId = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
       name = cursor.getString(cursor.getColumnIndexOrThrow(ContactsContract.Contacts.DISPLAY_NAME)); 

       String hasPhone = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER));

       if ( hasPhone.equalsIgnoreCase("1"))
           hasPhone = "true";
       else
           hasPhone = "false" ;

       if (Boolean.parseBoolean(hasPhone)) 
       {
        Cursor phones = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,ContactsContract.CommonDataKinds.Phone.CONTACT_ID +" = "+ contactId,null, null);
        while (phones.moveToNext()) 
        {
          phoneNumber = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
        }
        phones.close();
       }

       // Find Email Addresses
       Cursor emails = getContentResolver().query(ContactsContract.CommonDataKinds.Email.CONTENT_URI,null,ContactsContract.CommonDataKinds.Email.CONTACT_ID + " = " + contactId,null, null);
       while (emails.moveToNext()) 
       {
        emailAddress = emails.getString(emails.getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA));
       }
       emails.close();

    Cursor address = getContentResolver().query(
                ContactsContract.CommonDataKinds.StructuredPostal.CONTENT_URI,
                null,
                ContactsContract.CommonDataKinds.StructuredPostal.CONTACT_ID + " = " + contactId,
                null, null);
    while (address.moveToNext()) 
    { 
      // These are all private class variables, don't forget to create them.
      poBox      = address.getString(address.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.POBOX));
      street     = address.getString(address.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.STREET));
      city       = address.getString(address.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.CITY));
      state      = address.getString(address.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.REGION));
      postalCode = address.getString(address.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.POSTCODE));
      country    = address.getString(address.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.COUNTRY));
      type       = address.getString(address.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.TYPE));
    }  //address.moveToNext()   
  }  //while (cursor.moveToNext())        
   cursor.close();
}//getContactInfo

java: use StringBuilder to insert at the beginning

I had a similar requirement when I stumbled on this post. I wanted a fast way to build a String that can grow from both sides ie. add new letters on the front as well as back arbitrarily. I know this is an old post, but it inspired me to try out a few ways to create strings and I thought I'd share my findings. I am also using some Java 8 constructs in this, which could have optimised the speed in cases 4 and 5.

https://gist.github.com/SidWagz/e41e836dec65ff24f78afdf8669e6420

The Gist above has the detailed code that anyone can run. I took few ways of growing strings in this; 1) Append to StringBuilder, 2) Insert to front of StringBuilder as as shown by @Mehrdad, 3) Partially insert from front as well as end of the StringBuilder, 4) Using a list to append from end, 5) Using a Deque to append from the front.

// Case 2    
StringBuilder build3 = new StringBuilder();
IntStream.range(0, MAX_STR)
                    .sequential()
                    .forEach(i -> {
                        if (i%2 == 0) build3.append(Integer.toString(i)); else build3.insert(0, Integer.toString(i));
                    });
String build3Out = build3.toString();


//Case 5
Deque<String> deque = new ArrayDeque<>();
IntStream.range(0, MAX_STR)
                .sequential()
                .forEach(i -> {
                    if (i%2 == 0) deque.addLast(Integer.toString(i)); else deque.addFirst(Integer.toString(i));
                });

String dequeOut = deque.stream().collect(Collectors.joining(""));

I'll focus on the front append only cases ie. case 2 and case 5. The implementation of StringBuilder internally decides how the internal buffer grows, which apart from moving all buffer left to right in case of front appending limits the speed. While time taken when inserting directly to the front of the StringBuilder grows to really high values, as shown by @Mehrdad, if the need is to only have strings of length less than 90k characters (which is still a lot), the front insert will build a String in the same time as it would take to build a String of the same length by appending at the end. What I am saying is that time time penalty indeed kicks and is huge, but only when you have to build really huge strings. One could use a deque and join the strings at the end as shown in my example. But StringBuilder is a bit more intuitive to read and code, and the penalty would not matter for smaller strings.

Actually the performance for case 2 is much faster than case 1, which I don't seem to understand. I assume the growth for the internal buffer in StringBuilder would be the same in case of front append and back append. I even set the minimum heap to a very large amount to avoid delay in heap growth, if that would have played a role. Maybe someone who has a better understanding can comment below.

Capitalize the first letter of string in AngularJs

If you are after performance, try to avoid using AngularJS filters as they are applied twice per each expression to check for their stability.

A better way would be to use CSS ::first-letter pseudo-element with text-transform: uppercase;. That can't be used on inline elements such as span, though, so the next best thing would be to use text-transform: capitalize; on the whole block, which capitalizes every word.

Example:

_x000D_
_x000D_
var app = angular.module('app', []);_x000D_
_x000D_
app.controller('Ctrl', function ($scope) {_x000D_
   $scope.msg = 'hello, world.';_x000D_
});
_x000D_
.capitalize {_x000D_
  display: inline-block;  _x000D_
}_x000D_
_x000D_
.capitalize::first-letter {_x000D_
  text-transform: uppercase;_x000D_
}_x000D_
_x000D_
.capitalize2 {_x000D_
  text-transform: capitalize;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>_x000D_
<div ng-app="app">_x000D_
    <div ng-controller="Ctrl">_x000D_
        <b>My text:</b> <div class="capitalize">{{msg}}</div>_x000D_
        <p><b>My text:</b> <span class="capitalize2">{{msg}}</span></p>_x000D_
    </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Django 1.7 throws django.core.exceptions.AppRegistryNotReady: Models aren't loaded yet

Just encountered the same issue. The problem is because of django-registration incompatible with django 1.7 user model.

A simple fix is to change these lines of code, at your installed django-registration module::

try:
    from django.contrib.auth import get_user_model
    User = get_user_model()
except ImportError:
    from django.contrib.auth.models import User  

to::

from django.conf import settings
try:
    from django.contrib.auth import get_user_model
    User = settings.AUTH_USER_MODEL
except ImportError:
    from django.contrib.auth.models import User 

Mine is at .venv/local/lib/python2.7/site-packages/registration/models.py (virtualenv)

Git merge two local branches

For merging first branch to second one:

on first branch: git merge secondBranch

on second branch: Move to first branch-> git checkout firstBranch-> git merge secondBranch

C# Listbox Item Double Click Event

It depends whether you ListBox object of the System.Windows.Forms.ListBox class, which does have the ListBox.IndexFromPoint() method. But if the ListBox object is from the System.Windows.Control.Listbox class, the answer from @dark-knight (marked as correct answer) does not work.

Im running Win 10 (1903) and current versions of the .NET framework (4.8). This issue should not be version dependant though, only whether your Application is using WPF or Windows Form for the UI. See also: WPF vs Windows Form

Disable button in angular with two conditions?

Declare a variable in component.ts and initialize it to some value

 buttonDisabled: boolean;

  ngOnInit() {
    this.buttonDisabled = false;
  }

Now in .html or in the template, you can put following code:

<button disabled="{{buttonDisabled}}"> Click Me </button>

Now you can enable/disable button by changing value of buttonDisabled variable.

Can we execute a java program without a main() method?

Now - no


Prior to Java 7:

Yes, sequence is as follows:

  • jvm loads class
  • executes static blocks
  • looks for main method and invokes it

So, if there's code in a static block, it will be executed. But there's no point in doing that.

How to test that:

public final class Test {
    static {
        System.out.println("FOO");
    }
}

Then if you try to run the class (either form command line with java Test or with an IDE), the result is:

FOO
java.lang.NoSuchMethodError: main

How to check if a number is a power of 2

return ((x != 0) && !(x & (x - 1)));

If x is a power of two, its lone 1 bit is in position n. This means x – 1 has a 0 in position n. To see why, recall how a binary subtraction works. When subtracting 1 from x, the borrow propagates all the way to position n; bit n becomes 0 and all lower bits become 1. Now, since x has no 1 bits in common with x – 1, x & (x – 1) is 0, and !(x & (x – 1)) is true.

How to call a method after a delay in Android

everybody seems to forget to clean the Handler before posting a new runnable or message on it. Otherway they could potentially accumulate and cause bad behaviour.

handler.removeMessages(int what);
// Remove any pending posts of messages with code 'what' that are in the message queue.

handler.removeCallbacks(Runnable r)
// Remove any pending posts of Runnable r that are in the message queue.

Google server putty connect 'Disconnected: No supported authentication methods available (server sent: publickey)

Apparently running sudo chmod -R a+rw on your home folder causes this to happen as well.

How can I get the line number which threw exception?

Simple way, use the Exception.ToString() function, it will return the line after the exception description.

You can also check the program debug database as it contains debug info/logs about the whole application.

Splitting String with delimiter

How are you calling split? It works like this:

def values = '1182-2'.split('-')
assert values[0] == '1182'
assert values[1] == '2'

How do I change UIView Size?

Here you go. this should work.

questionFrame.frame = CGRectMake(0 , 0, self.view.frame.width, self.view.frame.height * 0.7) 

answerFrame.frame =  CGRectMake(0 , self.view.frame.height * 0.7, self.view.frame.width, self.view.frame.height * 0.3)

How do you check if a certain index exists in a table?

If the hidden purpose of your question is to DROP the index before making INSERT to a large table, then this is useful one-liner:

DROP INDEX IF EXISTS [IndexName] ON [dbo].[TableName]

This syntax is available since SQL Server 2016. Documentation for IF EXISTS:

https://blogs.msdn.microsoft.com/sqlserverstorageengine/2015/11/03/drop-if-exists-new-thing-in-sql-server-2016/

In case you deal with a primery key instead, then use this:

ALTER TABLE [TableName] DROP CONSTRAINT IF EXISTS [PK_name] 

What does print(... sep='', '\t' ) mean?

The sep='\t' can be use in many forms, for example if you want to read tab separated value: Example: I have a dataset tsv = tab separated value NOT comma separated value df = pd.read_csv('gapminder.tsv'). when you try to read this, it will give you an error because you have tab separated value not csv. so you need to give read csv a different parameter called sep='\t'.

Now you can read: df = pd.read_csv('gapminder.tsv, sep='\t'), with this you can read the it.

How to globally replace a forward slash in a JavaScript string?

This is Christopher Lincolns idea but with correct code:

function replace(str,find,replace){
    if (find != ""){
        str = str.toString();
        var aStr = str.split(find);
        for(var i = 0; i < aStr.length; i++) {
            if (i > 0){
                str = str + replace + aStr[i];
            }else{
                str = aStr[i];
            }
        }
    }
    return str;
}

Example Usage:

var somevariable = replace('//\\\/\/sdfas/\/\/\\\////','\/sdf','replacethis\');

Javascript global string replacement is unecessarily complicated. This function solves that problem. There is probably a small performance impact, but I'm sure its negligable.

Heres an alternative function, looks much cleaner, but is on average about 25 to 20 percent slower than the above function:

function replace(str,find,replace){
    if (find !== ""){
        str = str.toString().split(find).join(replace);
    }
    return str;
}

413 Request Entity Too Large - File Upload Issue

First edit the Nginx configuration file (nginx.conf)

Location: sudo nano /etc/nginx/nginx.conf

Add following codes:

http {
        client_max_body_size 100M;
}

Then Add the following lines in PHP configuration file(php.ini)

Location: sudo gedit /etc/php5/fpm/php.ini

Add following codes:

memory_limit = 128M 
post_max_size = 20M  
upload_max_filesize = 10M

How to make a redirection on page load in JSF 1.x

you should use action instead of actionListener:

<h:commandLink id="close" action="#{bean.close}" value="Close" immediate="true" 
                                   />

and in close method you right something like:

public String close() {
   return "index?faces-redirect=true";
}

where index is one of your pages(index.xhtml)

Of course, all this staff should be written in our original page, not in the intermediate. And inside the close() method you can use the parameters to dynamically choose where to redirect.

Gaussian fit for Python

sigma = sum(y*(x - mean)**2)

should be

sigma = np.sqrt(sum(y*(x - mean)**2))

Trigger css hover with JS

I don't think what your asking is possible.

See: Hover Item with JQuery

Basically, adding a class is the only way to accomplish this that I am aware of.

What is the right way to debug in iPython notebook?

Use ipdb

Install it via

pip install ipdb

Usage:

In[1]: def fun1(a):
   def fun2(a):
       import ipdb; ipdb.set_trace() # debugging starts here
       return do_some_thing_about(b)
   return fun2(a)
In[2]: fun1(1)

For executing line by line use n and for step into a function use s and to exit from debugging prompt use c.

For complete list of available commands: https://appletree.or.kr/quick_reference_cards/Python/Python%20Debugger%20Cheatsheet.pdf

Delete files in subfolder using batch script

I had to complete the same task and I used a "for" loop and a "del" command as follows:

@ECHO OFF

set dir=%cd%

FOR /d /r %dir% %%x in (archive\) do (
    if exist "%%x" del %%x\*.txt /f /q
)

You can set the dir variable with any start directory you want or used the current directory (%cd%) variable.

These are the options for "for" command:

  • /d For directories
  • /r For recursive

These are the options for "del" command:

  • /f Force deletes read-only files
  • /q Quiet mode; suppresses prompts for delete confirmations.

.NET Events - What are object sender & EventArgs e?

The sender is the control that the action is for (say OnClick, it's the button).

The EventArgs are arguments that the implementor of this event may find useful. With OnClick it contains nothing good, but in some events, like say in a GridView 'SelectedIndexChanged', it will contain the new index, or some other useful data.

What Chris is saying is you can do this:

protected void someButton_Click (object sender, EventArgs ea)
{
    Button someButton = sender as Button;
    if(someButton != null)
    {
        someButton.Text = "I was clicked!";
    }
}

How to draw polygons on an HTML5 canvas?

from http://www.scienceprimer.com/drawing-regular-polygons-javascript-canvas:

The following code will draw a hexagon. Change the number of sides to create different regular polygons.

_x000D_
_x000D_
var ctx = document.getElementById('hexagon').getContext('2d');_x000D_
_x000D_
// hexagon_x000D_
var numberOfSides = 6,_x000D_
    size = 20,_x000D_
    Xcenter = 25,_x000D_
    Ycenter = 25;_x000D_
_x000D_
ctx.beginPath();_x000D_
ctx.moveTo (Xcenter +  size * Math.cos(0), Ycenter +  size *  Math.sin(0));          _x000D_
_x000D_
for (var i = 1; i <= numberOfSides;i += 1) {_x000D_
  ctx.lineTo (Xcenter + size * Math.cos(i * 2 * Math.PI / numberOfSides), Ycenter + size * Math.sin(i * 2 * Math.PI / numberOfSides));_x000D_
}_x000D_
_x000D_
ctx.strokeStyle = "#000000";_x000D_
ctx.lineWidth = 1;_x000D_
ctx.stroke();
_x000D_
#hexagon { border: thin dashed red; }
_x000D_
<canvas id="hexagon"></canvas>
_x000D_
_x000D_
_x000D_

Can CSS detect the number of children an element has?

No. Well, not really. There are a couple of selectors that can get you somewhat close, but probably won't work in your example and don't have the best browser compatibility.

:only-child

The :only-child is one of the few true counting selectors in the sense that it's only applied when there is one child of the element's parent. Using your idealized example, it acts like children(1) probably would.

:nth-child

The :nth-child selector might actually get you where you want to go depending on what you're really looking to do. If you want to style all elements if there are 8 children, you're out of luck. If, however, you want to apply styles to the 8th and later elements, try this:

p:nth-child( n + 8 ){
    /* add styles to make it pretty */
}

Unfortunately, these probably aren't the solutions you're looking for. In the end, you'll probably need to use some Javascript wizardry to apply the styles based on the count - even if you were to use one of these, you'd need to have a hard look at browser compatibility before going with a pure CSS solution.

W3 CSS3 Spec on pseudo-classes

EDIT I read your question a little differently - there are a couple other ways to style the parent, not the children. Let me throw a few other selectors your way:

:empty and :not

This styles elements that have no children. Not that useful on its own, but when paired with the :not selector, you can style only the elements that have children:

div:not(:empty) {
    /* We know it has stuff in it! */
}

You can't count how many children are available with pure CSS here, but it is another interesting selector that lets you do cool things.

Changing SqlConnection timeout

Old post but as it comes up for what I was searching for I thought I'd add some information to this topic. I was going to add a comment but I don't have enough rep.

As others have said:

connection.ConnectionTimeout is used for the initial connection

command.CommandTimeout is used for individual searches, updates, etc.

But:

connection.ConnectionTimeout is also used for committing and rolling back transactions.

Yes, this is an absolutely insane design decision.

So, if you are running into a timeout on commit or rollback you'll need to increase this value through the connection string.

How can getContentResolver() be called in Android?

A solution would be to get the ContentResolver from the context

ContentResolver contentResolver = getContext().getContentResolver();

Link to the documentation : ContentResolver

Using Ansible set_fact to create a dictionary from register results

I think I got there in the end.

The task is like this:

- name: Populate genders
  set_fact:
    genders: "{{ genders|default({}) | combine( {item.item.name: item.stdout} ) }}"
  with_items: "{{ people.results }}"

It loops through each of the dicts (item) in the people.results array, each time creating a new dict like {Bob: "male"}, and combine()s that new dict in the genders array, which ends up like:

{
    "Bob": "male",
    "Thelma": "female"
}

It assumes the keys (the name in this case) will be unique.


I then realised I actually wanted a list of dictionaries, as it seems much easier to loop through using with_items:

- name: Populate genders
  set_fact:
    genders: "{{ genders|default([]) + [ {'name': item.item.name, 'gender': item.stdout} ] }}"
  with_items: "{{ people.results }}"

This keeps combining the existing list with a list containing a single dict. We end up with a genders array like this:

[
    {'name': 'Bob', 'gender': 'male'},
    {'name': 'Thelma', 'gender': 'female'}
]

How to initialize array to 0 in C?

If you'd like to initialize the array to values other than 0, with gcc you can do:

int array[1024] = { [ 0 ... 1023 ] = -1 };

This is a GNU extension of C99 Designated Initializers. In older GCC, you may need to use -std=gnu99 to compile your code.

How can I remove or replace SVG content?

Setting the id attribute when appending the svg element can also let d3 select so remove() later on this element by id :

var svg = d3.select("theParentElement").append("svg")
.attr("id","the_SVG_ID")
.attr("width",...

...

d3.select("#the_SVG_ID").remove();

Android button font size

<resource>
<style name="button">
<item name="android:textSize">15dp</item>
</style>
<resource>

How correctly produce JSON by RESTful web service?

@POST
@Path ("Employee")
@Consumes("application/json")
@Produces("application/json")
public JSONObject postEmployee(JSONObject jsonObject)throws Exception{
    return jsonObject;
}       

Find a string within a cell using VBA

you never change the value of rng so it always points to the initial cell

copy the Set rng = rng.Offset(1, 0) to a new line before loop

also, your InStr test will always fail
True is -1, but the return from InStr will be greater than 0 when the string is found. change the test to remove = True

new code:

Sub IfTest()
 'This should split the information in a table up into cells
 Dim Splitter() As String
 Dim LenValue As Integer     'Gives the number of characters in date string
 Dim LeftValue As Integer    'One less than the LenValue to drop the ")"
 Dim rng As Range, cell As Range
 Set rng = ActiveCell

Do While ActiveCell.Value <> Empty
    If InStr(rng, "%") Then
        ActiveCell.Offset(0, 0).Select
        Splitter = Split(ActiveCell.Value, "% Change")
        ActiveCell.Offset(0, 10).Select
        ActiveCell.Value = Splitter(1)
        ActiveCell.Offset(0, -1).Select
        ActiveCell.Value = "% Change"
        ActiveCell.Offset(1, -9).Select
    Else
        ActiveCell.Offset(0, 0).Select
        Splitter = Split(ActiveCell.Value, "(")
        ActiveCell.Offset(0, 9).Select
        ActiveCell.Value = Splitter(0)
        ActiveCell.Offset(0, 1).Select
        LenValue = Len(Splitter(1))
        LeftValue = LenValue - 1
        ActiveCell.Value = Left(Splitter(1), LeftValue)
        ActiveCell.Offset(1, -10).Select
    End If
Set rng = rng.Offset(1, 0)
Loop

End Sub

Visual Studio 2015 installer hangs during install?

This solution is a safe mix of killing the sub tasks answer and the waiting answer:

  • when the installer gets stuck, simply launch the task manager and kill the process
  • if you attempt to run the app again, it will say that the app installation is not complete
  • run the installer again, and click on repair
  • installs fine

Java - get the current class name?

I'm assuming this is happening for an anonymous class. When you create an anonymous class you actually create a class that extends the class whose name you got.

The "cleaner" way to get the name you want is:

If your class is an anonymous inner class, getSuperClass() should give you the class that it was created from. If you created it from an interface than you're sort of SOL because the best you can do is getInterfaces() which might give you more than one interface.

The "hacky" way is to just get the name with getClassName() and use a regex to drop the $1.

jquery datatables hide column

Hide columns dynamically

The previous answers are using legacy DataTables syntax. In v 1.10+, you can use column().visible():

var dt = $('#example').DataTable();
//hide the first column
dt.column(0).visible(false);

To hide multiple columns, columns().visible() can be used:

var dt = $('#example').DataTable();
//hide the second and third columns
dt.columns([1,2]).visible(false);

Here is a Fiddle Demo.

Hide columns when the table is initialized

To hide columns when the table is initialized, you can use the columns option:

$('#example').DataTable( {
    'columns' : [
        null,
        //hide the second column
        {'visible' : false },
        null,
        //hide the fourth column
        {'visible' : false }
    ]
});

For the above method, you need to specify null for columns that should remain visible and have no other column options specified. Or, you can use columnDefs to target a specific column:

$('#example').DataTable( {
    'columnDefs' : [
        //hide the second & fourth column
        { 'visible': false, 'targets': [1,3] }
    ]
});

Going through a text file line by line in C

Say you're dealing with some other delimiter, such as a \t tab, instead of a \n newline.

A more general approach to delimiters is the use of getc(), which grabs one character at a time.

Note that getc() returns an int, so that we can test for equality with EOF.

Secondly, we define an array line[BUFFER_MAX_LENGTH] of type char, in order to store up to BUFFER_MAX_LENGTH-1 characters on the stack (we have to save that last character for a \0 terminator character).

Use of an array avoids the need to use malloc and free to create a character pointer of the right length on the heap.

#define BUFFER_MAX_LENGTH 1024

int main(int argc, char* argv[])
{
    FILE *file = NULL;
    char line[BUFFER_MAX_LENGTH];
    int tempChar;
    unsigned int tempCharIdx = 0U;

    if (argc == 2)
         file = fopen(argv[1], "r");
    else {
         fprintf(stderr, "error: wrong number of arguments\n"
                         "usage: %s textfile\n", argv[0]);
         return EXIT_FAILURE;
    }

    if (!file) {
         fprintf(stderr, "error: could not open textfile: %s\n", argv[1]);
         return EXIT_FAILURE;
    }

    /* get a character from the file pointer */
    while(tempChar = fgetc(file))
    {
        /* avoid buffer overflow error */
        if (tempCharIdx == BUFFER_MAX_LENGTH) {
            fprintf(stderr, "error: line is too long. increase BUFFER_MAX_LENGTH.\n");
            return EXIT_FAILURE;
        }

        /* test character value */
        if (tempChar == EOF) {
            line[tempCharIdx] = '\0';
            fprintf(stdout, "%s\n", line);
            break;
        }
        else if (tempChar == '\n') {
            line[tempCharIdx] = '\0';
            tempCharIdx = 0U;
            fprintf(stdout, "%s\n", line);
            continue;
        }
        else
            line[tempCharIdx++] = (char)tempChar;
    }

    return EXIT_SUCCESS;
}

If you must use a char *, then you can still use this code, but you strdup() the line[] array, once it is filled up with a line's worth of input. You must free this duplicated string once you're done with it, or you'll get a memory leak:

#define BUFFER_MAX_LENGTH 1024

int main(int argc, char* argv[])
{
    FILE *file = NULL;
    char line[BUFFER_MAX_LENGTH];
    int tempChar;
    unsigned int tempCharIdx = 0U;
    char *dynamicLine = NULL;

    if (argc == 2)
         file = fopen(argv[1], "r");
    else {
         fprintf(stderr, "error: wrong number of arguments\n"
                         "usage: %s textfile\n", argv[0]);
         return EXIT_FAILURE;
    }

    if (!file) {
         fprintf(stderr, "error: could not open textfile: %s\n", argv[1]);
         return EXIT_FAILURE;
    }

    while(tempChar = fgetc(file))
    {
        /* avoid buffer overflow error */
        if (tempCharIdx == BUFFER_MAX_LENGTH) {
            fprintf(stderr, "error: line is too long. increase BUFFER_MAX_LENGTH.\n");
            return EXIT_FAILURE;
        }

        /* test character value */
        if (tempChar == EOF) {
            line[tempCharIdx] = '\0';
            dynamicLine = strdup(line);
            fprintf(stdout, "%s\n", dynamicLine);
            free(dynamicLine);
            dynamicLine = NULL;
            break;
        }
        else if (tempChar == '\n') {
            line[tempCharIdx] = '\0';
            tempCharIdx = 0U;
            dynamicLine = strdup(line);
            fprintf(stdout, "%s\n", dynamicLine);
            free(dynamicLine);
            dynamicLine = NULL;
            continue;
        }
        else
            line[tempCharIdx++] = (char)tempChar;
    }

    return EXIT_SUCCESS;
}

Create PDF with Java

Another alternative would be JasperReports: JasperReports Library. It uses iText itself and is more than a PDF library you asked for, but if it fits your needs I'd go for it.

Simply put, it allows you to design reports that can be filled during runtime. If you use a custom datasource, you might be able to integrate JasperReports easily into the existing system. It would save you the whole layouting troubles, e.g. when invoices span over more sites where each side should have a footer and so on.

Android Studio: /dev/kvm device permission denied

In order to make a virtual device in Linux - I have to follow this three command and it helps me to avoid trouble for building avd devices - the process are -

sudo apt install qemu-kvm
sudo adduser $USER kvm
sudo chown $USER /dev/kvm 

so, now you are good to go, restart android studio and start building application with emulator.

CSS Margin: 0 is not setting to 0

After reading this and troubleshooting the same issues, I agree that it is related to headings (h1 for sure, havent played with any others), also browser styles adding margins and paddings with clever rules that are hard to find and over-ride.

I have adapted a technique used to apply the box-sizing property properly to margins and paddings. the original article for box-sizing is located at CSS-Tricks :

html {
margin: 0;
padding: 0;
}
*, *:before, *:after {
margin: inherit;
padding: inherit;
}

So far it is exactly the trick for not using complex resets and makes applying a design much easier for myself anyways. Hope it helps.

Conversion of System.Array to List

You can just give it try to your code:

Array ints = Array.CreateInstance(typeof(int), 5);
ints.SetValue(10, 0);

ints.SetValue(20, 1);
ints.SetValue(10, 2);
ints.SetValue(34, 3);
ints.SetValue(113, 4);

int[] anyVariable=(int[])ints;

Then you can just use the anyVariable as your code.

How to add new item to hash

Create hash as:

h = Hash.new
=> {}

Now insert into hash as:

h = Hash["one" => 1]

Why is HttpClient BaseAddress not working?

It turns out that, out of the four possible permutations of including or excluding trailing or leading forward slashes on the BaseAddress and the relative URI passed to the GetAsync method -- or whichever other method of HttpClient -- only one permutation works. You must place a slash at the end of the BaseAddress, and you must not place a slash at the beginning of your relative URI, as in the following example.

using (var handler = new HttpClientHandler())
using (var client = new HttpClient(handler))
{
    client.BaseAddress = new Uri("http://something.com/api/");
    var response = await client.GetAsync("resource/7");
}

Even though I answered my own question, I figured I'd contribute the solution here since, again, this unfriendly behavior is undocumented. My colleague and I spent most of the day trying to fix a problem that was ultimately caused by this oddity of HttpClient.

How can I create a dropdown menu from a List in Tkinter?

To create a "drop down menu" you can use OptionMenu in tkinter

Example of a basic OptionMenu:

from Tkinter import *

master = Tk()

variable = StringVar(master)
variable.set("one") # default value

w = OptionMenu(master, variable, "one", "two", "three")
w.pack()

mainloop()

More information (including the script above) can be found here.


Creating an OptionMenu of the months from a list would be as simple as:

from tkinter import *

OPTIONS = [
"Jan",
"Feb",
"Mar"
] #etc

master = Tk()

variable = StringVar(master)
variable.set(OPTIONS[0]) # default value

w = OptionMenu(master, variable, *OPTIONS)
w.pack()

mainloop()

In order to retrieve the value the user has selected you can simply use a .get() on the variable that we assigned to the widget, in the below case this is variable:

from tkinter import *

OPTIONS = [
"Jan",
"Feb",
"Mar"
] #etc

master = Tk()

variable = StringVar(master)
variable.set(OPTIONS[0]) # default value

w = OptionMenu(master, variable, *OPTIONS)
w.pack()

def ok():
    print ("value is:" + variable.get())

button = Button(master, text="OK", command=ok)
button.pack()

mainloop()

I would highly recommend reading through this site for further basic tkinter information as the above examples are modified from that site.

Calculating difference between two timestamps in Oracle in milliseconds

Better to use procedure like that:

CREATE OR REPLACE FUNCTION timestamp_diff
(
start_time_in TIMESTAMP
, end_time_in TIMESTAMP
)
RETURN NUMBER
AS
l_days NUMBER;
l_hours NUMBER;
l_minutes NUMBER;
l_seconds NUMBER;
l_milliseconds NUMBER;
BEGIN
SELECT extract(DAY FROM end_time_in-start_time_in)
, extract(HOUR FROM end_time_in-start_time_in)
, extract(MINUTE FROM end_time_in-start_time_in)
, extract(SECOND FROM end_time_in-start_time_in)
INTO l_days, l_hours, l_minutes, l_seconds
FROM dual;

l_milliseconds := l_seconds*1000 + l_minutes*60*1000 + l_hours*60*60*1000 + l_days*24*60*60*1000;
RETURN l_milliseconds;

END;

You can check it by calling:

SELECT timestamp_diff (TO_TIMESTAMP('12.04.2017 12:00:00.00', 'DD.MM.YYYY HH24:MI:SS.FF'), 
                      TO_TIMESTAMP('12.04.2017 12:00:01.111', 'DD.MM.YYYY HH24:MI:SS.FF')) 
            as milliseconds
    FROM DUAL;

How can I get all a form's values that would be submitted without submitting

You can use this simple loop to get all the element names and their values.

var params = '';
for( var i=0; i<document.FormName.elements.length; i++ )
{
   var fieldName = document.FormName.elements[i].name;
   var fieldValue = document.FormName.elements[i].value;

   // use the fields, put them in a array, etc.

   // or, add them to a key-value pair strings, 
   // as in regular POST

   params += fieldName + '=' + fieldValue + '&';
}

// send the 'params' variable to web service, GET request, ...

JavaScript Chart.js - Custom data formatting to display on tooltip

You want to specify a custom tooltip template in your chart options, like this :

 // String - Template string for single tooltips
 tooltipTemplate: "<%if (label){%><%=label %>: <%}%><%= value + ' %' %>",
 // String - Template string for multiple tooltips
 multiTooltipTemplate: "<%= value + ' %' %>",

This way you can add a '%' sign after your values if that's what you want.

Here's a jsfiddle to illustrate this.

Note that tooltipTemplate applies if you only have one dataset, multiTooltipTemplate applies if you have several datasets.

This options are mentioned in the global chart configuration section of the documentation. Do have a look, it's worth checking for all the other options that can be customized in there.

Note that Your datasets should only contain numeric values. (No % signs or other stuff there).

Animate a custom Dialog

I have created the Fade in and Fade Out animation for Dialogbox using ChrisJD code.

  1. Inside res/style.xml

    <style name="AppTheme" parent="android:Theme.Light" />
    <style name="PauseDialog" parent="@android:style/Theme.Dialog">
        <item name="android:windowAnimationStyle">@style/PauseDialogAnimation</item>
    </style>
    
    <style name="PauseDialogAnimation">
        <item name="android:windowEnterAnimation">@anim/fadein</item>
        <item name="android:windowExitAnimation">@anim/fadeout</item>
    </style>
    

  2. Inside anim/fadein.xml

    <alpha xmlns:android="http://schemas.android.com/apk/res/android"
        android:interpolator="@android:anim/accelerate_interpolator"
        android:fromAlpha="0.0" android:toAlpha="1.0" android:duration="500" />
    
  3. Inside anim/fadeout.xml

    <alpha xmlns:android="http://schemas.android.com/apk/res/android"
        android:interpolator="@android:anim/anticipate_interpolator"
        android:fromAlpha="1.0" android:toAlpha="0.0" android:duration="500" />
    
  4. MainActivity

    Dialog imageDiaglog= new Dialog(MainActivity.this,R.style.PauseDialog);
    

DisplayName attribute from Resources?

How about writing a custom attribute:

public class LocalizedDisplayNameAttribute: DisplayNameAttribute
{
    public LocalizedDisplayNameAttribute(string resourceId) 
        : base(GetMessageFromResource(resourceId))
    { }

    private static string GetMessageFromResource(string resourceId)
    {
        // TODO: Return the string from the resource file
    }
}

which could be used like this:

public class MyModel 
{
    [Required]
    [LocalizedDisplayName("labelForName")]
    public string Name { get; set; }
}

How to get URI from an asset File?

Worked for me Try this code

   uri = Uri.fromFile(new File("//assets/testdemo.txt"));
   String testfilepath = uri.getPath();
    File f = new File(testfilepath);
    if (f.exists() == true) {
    Toast.makeText(getApplicationContext(),"valid :" + testfilepath, 2000).show();
    } else {
   Toast.makeText(getApplicationContext(),"invalid :" + testfilepath, 2000).show();
 }

curl POST format for CURLOPT_POSTFIELDS

for nested arrays you can use:

$data = [
  'name[0]' = 'value 1',
  'name[1]' = 'value 2',
  'name[2]' = 'value 3',
  'id' = 'value 4',
  ....
];

Rails 4: how to use $(document).ready() with turbo-links

I just learned of another option for solving this problem. If you load the jquery-turbolinks gem it will bind the Rails Turbolinks events to the document.ready events so you can write your jQuery in the usual way. You just add jquery.turbolinks right after jquery in the js manifest file (by default: application.js).

Jetty: HTTP ERROR: 503/ Service Unavailable

Remove/Delete the project from workspace. and Reimport the project to the workspace. This method worked for me.

How to search JSON tree with jQuery

You can search on a json object array using $.grep() like this:

var persons = {
    "person": [
        {
            "name": "Peter",
            "age": 43,
            "sex": "male"
        }, {
            "name": "Zara",
            "age": 65,
            "sex": "female"
        }
      ]
   }
};
var result = $.grep(persons.person, function(element, index) {
   return (element.name === 'Peter');
});
alert(result[0].age);

CSS: How to remove pseudo elements (after, before,...)?

This depends on what's actually being added by the pseudoselectors. In your situation, setting content to "" will get rid of it, but if you're setting borders or backgrounds or whatever, you need to zero those out specifically. As far as I know, there's no one cure-all for removing everything about a before/after element regardless of what it is.

Is this how you define a function in jQuery?

That is how you define an anonymous function that gets called when the document is ready.

Python: instance has no attribute

Your class doesn't have a __init__(), so by the time it's instantiated, the attribute atoms is not present. You'd have to do C.setdata('something') so C.atoms becomes available.

>>> C = Residues()
>>> C.atoms.append('thing')

Traceback (most recent call last):
  File "<pyshell#84>", line 1, in <module>
    B.atoms.append('thing')
AttributeError: Residues instance has no attribute 'atoms'

>>> C.setdata('something')
>>> C.atoms.append('thing')   # now it works
>>> 

Unlike in languages like Java, where you know at compile time what attributes/member variables an object will have, in Python you can dynamically add attributes at runtime. This also implies instances of the same class can have different attributes.

To ensure you'll always have (unless you mess with it down the line, then it's your own fault) an atoms list you could add a constructor:

def __init__(self):
    self.atoms = []

How do you embed binary data in XML?

Try Base64 encoding/decoding your binary data. Also look into CDATA sections

Animate scroll to ID on page load

You are only scrolling the height of your element. offset() returns the coordinates of an element relative to the document, and top param will give you the element's distance in pixels along the y-axis:

$("html, body").animate({ scrollTop: $('#title1').offset().top }, 1000);

And you can also add a delay to it:

$("html, body").delay(2000).animate({scrollTop: $('#title1').offset().top }, 2000);

What is the best IDE to develop Android apps in?

You can also develop rich UI filled Android applications using Adobe AIR. If you plan to go that route then Flex Builder Burrito is the best IDE. Take a look at this post as to how easy it is to build an AIR4Android app http://blog.air4android.com/?p=13

Fluid or fixed grid system, in responsive design, based on Twitter Bootstrap

Source - http://coding.smashingmagazine.com/2009/06/02/fixed-vs-fluid-vs-elastic-layout-whats-the-right-one-for-you/

Pros

  • Fixed-width layouts are much easier to use and easier to customize in terms of design.
  • Widths are the same for every browser, so there is less hassle with images, forms, video and other content that are fixed-width.
  • There is no need for min-width or max-width, which isn’t supported by every browser anyway.
  • Even if a website is designed to be compatible with the smallest screen resolution, 800×600, the content will still be wide enough at a larger resolution to be easily legible.

Cons

  • A fixed-width layout may create excessive white space for users with larger screen resolutions, thus upsetting “divine proportion,” the “Rule of Thirds,” overall balance and other design principles.
  • Smaller screen resolutions may require a horizontal scroll bar, depending the fixed layout’s width.
  • Seamless textures, patterns and image continuation are needed to accommodate those with larger resolutions.
  • Fixed-width layouts generally have a lower overall score when it comes to usability.

SQL Format as of Round off removing decimals

check the round function and how does the length argument works. It controls the behaviour of the precision of the result

Powershell Invoke-WebRequest Fails with SSL/TLS Secure Channel

If, like me, none of the above quite works, it might be worth also specifically trying a lower TLS version alone. I had tried both of the following, but didn't seem to solve my problem:

[Net.ServicePointManager]::SecurityProtocol = "tls12, tls11, tls"
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12 -bor [Net.SecurityProtocolType]::Tls11 -bor [Net.SecurityProtocolType]::Tls

In the end, it was only when I targetted TLS 1.0 (specifically remove 1.1 and 1.2 in the code) that it worked:

[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls

The local server (that this was being attempted on) is fine with TLS 1.2, although the remote server (which was previously "confirmed" as fine for TLS 1.2 by a 3rd party) seems not to be.

Hope this helps someone.

How can I repeat a character in Bash?

Python is ubiquitous and works the same everywhere.

python -c "import sys; print('*' * int(sys.argv[1]))" "=" 100

Character and count are passed as separate parameters.

How to use BufferedReader in Java

As far as i understand fr is the object of your FileReadExample class. So it is obvious it will not have any method like fr.readLine() if you dont create one yourself.

secondly, i think a correct constructor of the BufferedReader class will help you do your task.

String str;
BufferedReader buffread = new BufferedReader(new FileReader(new File("file.dat")));
str = buffread.readLine();
.
.
buffread.close();

this should help you.

c++ array assignment of multiple values

const static int newvals[] = {34,2,4,5,6};

std::copy(newvals, newvals+sizeof(newvals)/sizeof(newvals[0]), array);

Datatable select with multiple conditions

    protected void FindCsv()
    {
        string strToFind = "2";

        importFolder = @"C:\Documents and Settings\gmendez\Desktop\";

        fileName = "CSVFile.csv";

        connectionString= @"Driver={Microsoft Text Driver (*.txt; *.csv)};Dbq="+importFolder+";Extended Properties=Text;HDR=No;FMT=Delimited";
        conn = new OdbcConnection(connectionString);

        System.Data.Odbc.OdbcDataAdapter  da = new OdbcDataAdapter("select * from [" + fileName + "]", conn);
        DataTable dt = new DataTable();
        da.Fill(dt);

        dt.Columns[0].ColumnName = "id";

        DataRow[] dr = dt.Select("id=" + strToFind);

        Response.Write(dr[0][0].ToString() + dr[0][1].ToString() + dr[0][2].ToString() + dr[0][3].ToString() + dr[0][4].ToString() + dr[0][5].ToString());
    }

How to serialize/deserialize to `Dictionary<int, string>` from custom XML not using XElement?

With the help of a temporary item class

public class item
{
    [XmlAttribute]
    public int id;
    [XmlAttribute]
    public string value;
}

Sample Dictionary:

Dictionary<int, string> dict = new Dictionary<int, string>()
{
    {1,"one"}, {2,"two"}
};

.

XmlSerializer serializer = new XmlSerializer(typeof(item[]), 
                                 new XmlRootAttribute() { ElementName = "items" });

Serialization

serializer.Serialize(stream, 
              dict.Select(kv=>new item(){id = kv.Key,value=kv.Value}).ToArray() );

Deserialization

var orgDict = ((item[])serializer.Deserialize(stream))
               .ToDictionary(i => i.id, i => i.value);

------------------------------------------------------------------------------

Here is how it can be done using XElement, if you change your mind.

Serialization

XElement xElem = new XElement(
                    "items",
                    dict.Select(x => new XElement("item",new XAttribute("id", x.Key),new XAttribute("value", x.Value)))
                 );
var xml = xElem.ToString(); //xElem.Save(...);

Deserialization

XElement xElem2 = XElement.Parse(xml); //XElement.Load(...)
var newDict = xElem2.Descendants("item")
                    .ToDictionary(x => (int)x.Attribute("id"), x => (string)x.Attribute("value"));

Error LNK2019 unresolved external symbol _main referenced in function "int __cdecl invoke_main(void)" (?invoke_main@@YAHXZ)

I had same Problem when i was trying to create executable from program that having no main() method. When i included sample main() method like this

int main(){
  return 0;
}

It solved

What are the most useful Intellij IDEA keyboard shortcuts?

Yes, Ctrl + Shift + A is the most useful one. It's a meta shortcut

How can I reuse a navigation bar on multiple pages?

This is what helped me. My navigation bar is in the body tag. Entire code for navigation bar is in nav.html file (without any html or body tag, only the code for navigation bar). In the target page, this goes in the head tag:

<script src="https://code.jquery.com/jquery-1.10.2.js"></script>

Then in the body tag, a container is made with an unique id and a javascript block to load the nav.html into the container, as follows:

<!--Navigation bar-->
<div id="nav-placeholder">

</div>

<script>
$(function(){
  $("#nav-placeholder").load("nav.html");
});
</script>
<!--end of Navigation bar-->

Module AppRegistry is not registered callable module (calling runApplication)

Ok guys, here we are my solution for this issue:

  • npm install native-base@latest -g

  • npm install react-native@latest -g

  • change package.json for these dependencies

  • delete node_modules and npm install

  • Open it Xcode and Build/Run from scratch

I hope it helped

Oracle Not Equals Operator

The difference is :

"If you use !=, it returns sub-second. If you use <>, it takes 7 seconds to return. Both return the right answer."

Oracle not equals (!=) SQL operator

Regards

"A connection attempt failed because the connected party did not properly respond after a period of time" using WebClient

I know it's an old post but I came across the exact same issue and I managed to use this by turning off MALWAREBYTES program which was causing the issue.

How can I add 1 day to current date?

In my humble opinion the best way is to just add a full day in milliseconds, depending on how you factor your code it can mess up if your on the last day of the month.

for example Feb 28 or march 31.

Here is an example of how i would do it:

var current = new Date(); //'Mar 11 2015' current.getTime() = 1426060964567
var followingDay = new Date(current.getTime() + 86400000); // + 1 day in ms
followingDay.toLocaleDateString();

imo this insures accuracy

here is another example i Do not like that can work for you but not as clean that dose the above

var today = new Date('12/31/2015');
var tomorrow = new Date(today);
tomorrow.setDate(today.getDate()+1);
tomorrow.toLocaleDateString();

imho this === 'POOP'

So some of you have had gripes about my millisecond approach because of day light savings time. So Im going to bash this out. First, Some countries and states do not have Day light savings time. Second Adding exactly 24 hours is a full day. If the date number dose not change once a year but then gets fixed 6 months later i don't see a problem there. But for the purpose of being definite and having to deal with allot the evil Date() i have thought this through and now thoroughly hate Date. So this is my new Approach

var dd = new Date(); // or any date and time you care about 
var dateArray =  dd.toISOString().split('T')[0].split('-').concat( dd.toISOString().split('T')[1].split(':') );
// ["2016", "07", "04", "00", "17", "58.849Z"] at Z 

Now for the fun part!

var date = { 
    day: dateArray[2],
    month: dateArray[1],
    year: dateArray[0],
    hour: dateArray[3],
    minutes: dateArray[4],
    seconds:dateArray[5].split('.')[0],
    milliseconds: dateArray[5].split('.')[1].replace('Z','')
}

now we have our Official Valid international Date Object clearly written out at Zulu meridian. Now to change the date

  dd.setDate(dd.getDate()+1); // this gives you one full calendar date forward
  tomorrow.setDate(dd.getTime() + 86400000);// this gives your 24 hours into the future. do what you want with it.

SEVERE: ContainerBase.addChild: start:org.apache.catalina.LifecycleException: Failed to start error

This issue arises because of different reasons. It might encountered if you are using Spring boot built war file. As Spring boot web and rest starter projects jars do have embedded Tomcat in it, hence fails with "SEVERE: ContainerBase.addChild: start: org.apache.catalina.LifecycleException".

You can fix this by exclusion of the embedded tomcat at the time of packaging by using exclusions in case of maven.

Maven dependency of "spring-boot-starter-web" will look like

   <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
        <exclusions>
            <exclusion>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-tomcat</artifactId>
            </exclusion>
        </exclusions>
    </dependency>

What operator is <> in VBA

This is an Inequality operator.

Also,this might be helpful for future: Operators listed by Functionality

Can I check if Bootstrap Modal Shown / Hidden?

With Bootstrap 4:

if ($('#myModal').hasClass('show')) {
    alert("Modal is visible")
}

How to properly stop the Thread in Java?

I didn't get the interrupt to work in Android, so I used this method, works perfectly:

boolean shouldCheckUpdates = true;

private void startupCheckForUpdatesEveryFewSeconds() {
    threadCheckChat = new Thread(new CheckUpdates());
    threadCheckChat.start();
}

private class CheckUpdates implements Runnable{
    public void run() {
        while (shouldCheckUpdates){
            System.out.println("Do your thing here");
        }
    }
}

 public void stop(){
        shouldCheckUpdates = false;
 }

How can I subset rows in a data frame in R based on a vector of values?

Really human comprehensible example (as this is the first time I am using %in%), how to compare two data frames and keep only rows containing the equal values in specific column:

# Set seed for reproducibility.
set.seed(1)

# Create two sample data frames.
data_A <- data.frame(id=c(1,2,3), value=c(1,2,3))
data_B <- data.frame(id=c(1,2,3,4), value=c(5,6,7,8))

# compare data frames by specific columns and keep only 
# the rows with equal values 
data_A[data_A$id %in% data_B$id,]   # will keep data in data_A
data_B[data_B$id %in% data_A$id,]   # will keep data in data_b

Results:

> data_A[data_A$id %in% data_B$id,]
  id value
1  1     1
2  2     2
3  3     3

> data_B[data_B$id %in% data_A$id,]
  id value
1  1     5
2  2     6
3  3     7

What is the proper use of an EventEmitter?

There is no: nono and no: yesyes. The truth is in the middle And no reasons to be scared because of the next version of Angular.

From a logical point of view, if You have a Component and You want to inform other components that something happens, an event should be fired and this can be done in whatever way You (developer) think it should be done. I don't see the reason why to not use it and i don't see the reason why to use it at all costs. Also the EventEmitter name suggests to me an event happening. I usually use it for important events happening in the Component. I create the Service but create the Service file inside the Component Folder. So my Service file becomes a sort of Event Manager or an Event Interface, so I can figure out at glance to which event I can subscribe on the current component.

I know..Maybe I'm a bit an old fashioned developer. But this is not a part of Event Driven development pattern, this is part of the software architecture decisions of Your particular project.

Some other guys may think that use Observables directly is cool. In that case go ahead with Observables directly. You're not a serial killer doing this. Unless you're a psychopath developer, So far the Program works, do it.

Converting an object to a string

maybe you are looking for

JSON.stringify(JSON.stringify(obj))


"{\"id\":30}"

Assigning variables with dynamic names in Java

You don't. The closest thing you can do is working with Maps to simulate it, or defining your own Objects to deal with.

Convert python long/int to fixed size byte array

One-liner:

bytearray.fromhex('{:0192x}'.format(big_int))

The 192 is 768 / 4, because OP wanted 768-bit numbers and there are 4 bits in a hex digit. If you need a bigger bytearray use a format string with a higher number. Example:

>>> big_int = 911085911092802609795174074963333909087482261102921406113936886764014693975052768158290106460018649707059449553895568111944093294751504971131180816868149233377773327312327573120920667381269572962606994373889233844814776702037586419
>>> bytearray.fromhex('{:0192x}'.format(big_int))
bytearray(b'\x96;h^\xdbJ\x8f3obL\x9c\xc2\xb0-\x9e\xa4Sj-\xf6i\xc1\x9e\x97\x94\x85M\x1d\x93\x10\\\x81\xc2\x89\xcd\xe0a\xc0D\x81v\xdf\xed\xa9\xc1\x83p\xdbU\xf1\xd0\xfeR)\xce\x07\xdepM\x88\xcc\x7fv\\\x1c\x8di\x87N\x00\x8d\xa8\xbd[<\xdf\xaf\x13z:H\xed\xc2)\xa4\x1e\x0f\xa7\x92\xa7\xc6\x16\x86\xf1\xf3')
>>> lepi_int = 0x963b685edb4a8f336f624c9cc2b02d9ea4536a2df669c19e9794854d1d93105c81c289cde061c0448176dfeda9c18370db55f1d0fe5229ce07de704d88cc7f765c1c8d69874e008da8bd5b3cdfaf137a3a48edc229a41e0fa792a7c61686f1f
>>> bytearray.fromhex('{:0192x}'.format(lepi_int))
bytearray(b'\tc\xb6\x85\xed\xb4\xa8\xf36\xf6$\xc9\xcc+\x02\xd9\xeaE6\xa2\xdff\x9c\x19\xe9yHT\xd1\xd91\x05\xc8\x1c(\x9c\xde\x06\x1c\x04H\x17m\xfe\xda\x9c\x187\r\xb5_\x1d\x0f\xe5"\x9c\xe0}\xe7\x04\xd8\x8c\xc7\xf7e\xc1\xc8\xd6\x98t\xe0\x08\xda\x8b\xd5\xb3\xcd\xfa\xf17\xa3\xa4\x8e\xdc"\x9aA\xe0\xfay*|aho\x1f')

[My answer had used hex() before. I corrected it with format() in order to handle ints with odd-sized byte expressions. This fixes previous complaints about ValueError.]

Sending JWT token in the headers with Postman

enter image description here

Everything else ie. Params, Authorization, Body, Pre-request Script, Tests is empty, just open the Headers tab and add as shown in image. Its the same for GET request as well.

How do I get the Session Object in Spring?

If all that you need is details of User, for Spring Version 4.x you can use @AuthenticationPrincipal and @EnableWebSecurity tag provided by Spring as shown below.

Security Configuration Class:

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
   ...
}

Controller method:

@RequestMapping("/messages/inbox")
public ModelAndView findMessagesForUser(@AuthenticationPrincipal User user) {
    ...
}