Programs & Examples On #Reverting

PHP7 : install ext-dom issue

First of all, read the warning! It says do not run composer as root! Secondly, you're probably using Xammp on your local which has the required php libraries as default.

But in your server you're missing ext-dom. php-xml has all the related packages you need. So, you can simply install it by running:

sudo apt-get update
sudo apt install php-xml

Most likely you are missing mbstring too. If you get the error, install this package as well with:

sudo apt-get install php-mbstring

Then run:

composer update
composer require cviebrock/eloquent-sluggable

How to unapply a migration in ASP.NET Core with EF Core

More details and solutions here:

I don't understand why we are confusing things up here. So I'll write down a clear explanation, and what you have to notice.

All the commands will be written using dotnet.

This solution is provided for .net Core 3.1, but should be compatible with all other generations as well

Removing migrations:

  • Removing a migration deletes the file from your project (which should be clear for everyone)
  • Removing a migration can only be done, if the migration is not applied to the database yet
  • To remove last created migration: cd to_your_project then dotnet ef migrations remove

Note: Removing a migration works only, if you didn't execute yet dotnet ef database update or called in your c# code Database.Migrate(), in other words, only if the migration is not applied to your database yet.

Unapplying migrations (revert migrations):

  • Removes unwanted changes from the database
  • Does not delete the migration file from your project, but allows you to remove it after unapplying
  • To revert a migration, you can either:
    • Create a new migration dotnet ef migrations add <your_changes> and apply it, which is recommended by microsoft.
    • Or, update your database to a specified migration (which is basically unapplying or reverting the non chosen migrations) with dotnet ef database update <your_migration_name_to_jump_back_to>

Note: if the migration you want to unapply, does not contain a specific column or table, which are already in your database applied and being used, the column or table will be dropped, and your data will be lost.

After reverting the migration, you can remove your unwanted migration

Hopefully this helps someone!

npm install error - unable to get local issuer certificate

There is an issue discussed here which talks about using ca files, but it's a bit beyond my understanding and I'm unsure what to do about it.

This isn't too difficult once you know how! For Windows:

Using Chrome go to the root URL NPM is complaining about (so in your case). Open up dev tools and go to Security-> View Certificate. Check Certification path and make sure your at the top level certificate, if not open that one. Now go to "Details" and export the cert with "Copy to File...".

You need to convert this from DER to PEM. There are several ways to do this, but the easiest way I found was an online tool which should be easy to find with relevant keywords.

Now if you open the key with your favorite text editor you should see




This is the format you need. You can do this for as many keys as you need, and combine them all into one file. I had to do github and the npm registry keys in my case.

Now just edit your .npmrc to point to the file containing your keys like so


I have personally found this to perform significantly better behind our corporate proxy as opposed to the strict-ssl option. YMMV.

API Gateway CORS: no 'Access-Control-Allow-Origin' header

If anyone else is running into this still - I was able to track down the root cause in my application.

If you are running API-Gateway with custom Authorizers - API-Gateway will send a 401 or 403 back before it actually hits your server. By default - API-Gateway is NOT configured for CORS when returning 4xx from a custom authorizer.

Also - if you happen to be getting a status code of 0 or 1 from a request running through API Gateway, this is probably your issue.

To fix - in the API Gateway configuration - go to "Gateway Responses", expand "Default 4XX" and add a CORS configuration header there. i.e.

Access-Control-Allow-Origin: '*'

Make sure to re-deploy your gateway - and voila!

Cannot checkout, file is unmerged

If you want to discard modifications you made to the file, you can do:

git reset first_Name.txt
git checkout first_Name.txt

OwinStartup not firing

I messed around with a lot of the suggestions on this post.

I had the following but still could not land on a break point. Throwing an exception proved the code was being entered.

  <add key="owin:AutomaticAppStartup" value="true" />
  <add key="owin:appStartup" value="SSOResource.Startup, SSOResource" />

Finally out of desperation I looked at project->properties, and then under the WEB section I also checked the NATIVE CODE checkbox (ASP.NET should be already checked).

That finally fixed it for me.

Note : I am using Visual Studio 2017 Professional.

Git, How to reset origin/master to a commit?

Since I had a similar situation, I thought I'd share my situation and how these answers helped me (thanks everyone).

So I decided to work locally by amending my last commit every time I wanted to save my progress on the main branch (I know, I should've branched out, committed on that, kept pushing and later merge back to master).

One late night, in paranoid fear of loosing my progress to hardware failure or something out of the ether, I decided to push master to origin. Later I kept amending my local master branch and when I decided it's time to push again, I was faced with different master branches and found out I can't amend origin/upstream (duh!) like I can local development branches.

So I didn't checkout master locally because I already was after a commit. Master was unchanged. I didn't even need to reset --hard, my current commit was OK.

I just forced push to origin, without even specifying what commit I wanted to force on master since in this case it's whatever HEAD is at. Checked git diff master..origin/master so there weren't any differences and that's it. All fixed. Thanks! (I know, I'm a git newbie, please forgive!).

So if you're already OK with your master branch locally, just:

git push --force origin master
git diff master..origin/master

How to install a specific version of Node on Ubuntu?

Try this way. This worked me.

  1. wget file)

  2. Go to the directory where the Node.js binary was downloaded to, and then run command i.e, sudo tar -C /usr/local --strip-components 1 -xzf node-v0.10.36-linux-x64.tar.gz to install the Node.js binary package in “/usr/local/”.

  3. You can check:-

    $ node -v
    $ npm -v

Should I check in folder "node_modules" to Git when creating a Node.js app on Heroku?

My biggest concern with not checking folder node_modules into Git is that 10 years down the road, when your production application is still in use, npm may not be around. Or npm might become corrupted; or the maintainers might decide to remove the library that you rely on from their repository; or the version you use might be trimmed out.

This can be mitigated with repository managers like Maven, because you can always use your own local Nexus (Sonatype) or Artifactory to maintain a mirror with the packages that you use. As far as I understand, such a system doesn't exist for npm. The same goes for client-side library managers like Bower and Jam.js.

If you've committed the files to your own Git repository, then you can update them when you like, and you have the comfort of repeatable builds and the knowledge that your application won't break because of some third-party action.

Continuous CSS rotation animation on hover, animated back to 0deg on hover out

The solution is to set the default value in your .elem. But this annimation work fine with -moz but not yet implement in -webkit

Look at the fiddle I updated from yours :

It works fine with Firefox but not with Chrome

    position: absolute;_x000D_
    top: 40px;_x000D_
    left: 40px;_x000D_
    width: 0; _x000D_
    height: 0;_x000D_
    border-style: solid;_x000D_
    border-width: 75px;_x000D_
    border-color: red blue green orange;_x000D_
    transition-property: transform;_x000D_
    transition-duration: 1s;_x000D_
.elem:hover {_x000D_
    animation-name: rotate; _x000D_
    animation-duration: 2s; _x000D_
    animation-iteration-count: infinite;_x000D_
    animation-timing-function: linear;_x000D_
@keyframes rotate {_x000D_
    from {transform: rotate(0deg);}_x000D_
    to {transform: rotate(360deg);}_x000D_
<div class="elem"></div>

moving changed files to another branch for check-in

Sadly this happens to me quite regularly as well and I use git stash if I realized my mistake before git commit and use git cherry-pick otherwise, both commands are explained pretty well in other answers

I want to add a clarification for git checkout targetBranch: this command will only preserve your working directory and staged snapshot if targetBranch has the same history as your current branch

If you haven't already committed your changes, just use git checkout to move to the new branch and then commit them normally

@Amber's statement is not false, when you move to a newBranch,git checkout -b newBranch, a new pointer is created and it is pointing to the exact same commit as your current branch.
In fact, if you happened to have an another branch that shares history with your current branch (both point at the same commit) you can "move your changes" by git checkout targetBranch

However, usually different branches means different history, and Git will not allow you to switch between these branches with a dirty working directory or staging area. in which case you can either do git checkout -f targetBranch (clean and throwaway changes) or git stage + git checkout targetBranch (clean and save changes), simply running git checkout targetBranch will give an error:

error: Your local changes to the following files would be overwritten by checkout: ... Please commit your changes or stash them before you switch branches. Aborting

jQuery attr() change img src

You remove the original image here:

newImg.animate(css, SPEED, function() {
    (callback || function() {})();

And all that's left behind is newImg. Then you reset link references the image using #rocket:

$("#rocket").attr('src', ...

But your newImg doesn't have an id attribute let alone an id of rocket.

To fix this, you need to remove img and then set the id attribute of newImg to rocket:

newImg.animate(css, SPEED, function() {
    var old_id = img.attr('id');
    newImg.attr('id', old_id);
    (callback || function() {})();

And then you'll get the shiny black rocket back again:

UPDATE: A better approach (as noted by mellamokb) would be to hide the original image and then show it again when you hit the reset button. First, change the reset action to something like this:

    $("#wrapper").css('top', '250px');
    $('.throbber, .morpher').remove(); // Clear out the new stuff.
    $("#rocket").show();               // Bring the original back.

And in the newImg.load function, grab the images original size:

var orig = {
    width: img.width(),
    height: img.height()

And finally, the callback for finishing the morphing animation becomes this:

newImg.animate(css, SPEED, function() {
    (callback || function() {})();

New and improved:

The leaking of $('.throbber, .morpher') outside the plugin isn't the best thing ever but it isn't a big deal as long as it is documented.

Reset par to the default values at startup

Every time a new device is opened par() will reset, so another option is simply do and continue.

Revert a jQuery draggable object back to its original container on out event of droppable

I'm not sure if this will work for your actual use, but it works in your test case - updated at .

I just made it so that the built-in revert is only used if the item has not been dropped before. If it has been dropped, the revert is done manually. You could adjust this to animate to some calculated offset by checking the actual CSS properties, but I'll let you play with that because a lot of it depends on the CSS of the draggable and it's surrounding DOM structure.

$(function() {
        revert:  function(dropped) {
             var $draggable = $(this),
                 hasBeenDroppedBefore = $'hasBeenDropped'),
                 wasJustDropped = dropped && dropped[0].id == "droppable";
             if(wasJustDropped) {
                 // don't revert, it's in the droppable
                 return false;
             } else {
                 if (hasBeenDroppedBefore) {
                     // don't rely on the built in revert, do it yourself
                     $draggable.animate({ top: 0, left: 0 }, 'slow');
                     return false;
                 } else {
                     // just let the built in revert work, although really, you could animate to 0,0 here as well
                     return true;

        activeClass: 'ui-state-hover',
        hoverClass: 'ui-state-active',
        drop: function(event, ui) {
            $(ui.draggable).data('hasBeenDropped', true);

Reverting to a previous revision using TortoiseSVN

I have used the same instructions Stefan used, taken from Tortoise website.

But it's important to click COMMIT right after. I was getting crazy until I realized that.

If you need to make an older revision your head revision do the following:

  1. Select the file or folder in which you need to revert the changes. If you want to revert all changes, this should be the top level folder.

  2. Select TortoiseSVN ? Show Log to display a list of revisions. You may need to use Show All or Next 100 to show the revision(s) you are interested in.

  3. Right click on the selected revision, then select Context Menu ? Revert to this revision. This will discard all changes after the selected revision.

  4. Make a commit.

How to uninstall Python 2.7 on a Mac OS X 10.6.4?

If you're thinking about manually removing Apple's default Python 2.7, I'd suggest you hang-fire and do-noting: Looks like Apple will very shortly do it for you:

Python 2.7 Deprecated in OSX 10.15 Catalina

Python 2.7- as well as Ruby & Perl- are deprecated in Catalina: (skip to section "Scripting Language Runtimes" > "Deprecations")

Apple To Remove Python 2.7 in OSX 10.16

Indeed, if you do nothing at all, according to The Mac Observer, by OSX version 10.16, Python 2.7 will disappear from your system:

Given this revelation, I'd suggest the best course of action is do nothing and wait for Apple to wipe it for you. As Apple is imminently about to remove it for you, doesn't seem worth the risk of tinkering with your Python environment.

NOTE: I see the question relates specifically to OSX v 10.6.4, but it appears this question has become a pivot-point for all OSX folks interested in removing Python 2.7 from their systems, whatever version they're running.

Reverting to a specific commit based on commit id with Git?

Do you want to roll back your repo to that state, or you just want your local repo to look like that?

If you reset --hard, it will make your local code and local history be just like it was at that commit. But if you wanted to push this to someone else who has the new history, it would fail:

git reset --hard c14809fa

And if you reset --soft, it will move your HEAD to where they were , but leave your local files etc. the same:

git reset --soft c14809fa

So what exactly do you want to do with this reset?

Edit -

You can add "tags" to your repo.. and then go back to a tag. But a tag is really just a shortcut to the sha1.

You can tag this as TAG1.. then a git reset --soft c14809fa, git reset --soft TAG1, or git reset --soft c14809fafb08b9e96ff2879999ba8c807d10fb07 would all do the same thing.

Reverting single file in SVN to a particular revision

The best way is to:

svn merge -c -RevisionToUndo ^/trunk

This will undo all files of the revision than simply revert those file you don't like to undo. Don't forget the dash (-) as prefix for the revision.

svn revert File1 File2

Now commit the changes back.

Handling file renames in git

Step1: rename the file from oldfile to newfile

git mv #oldfile #newfile

Step2: git commit and add comments

git commit -m "rename oldfile to newfile"

Step3: push this change to remote sever

git push origin #localbranch:#remotebranch

Revert to a commit by a SHA hash in Git?

Should be as simple as:

git reset --hard 56e05f

That'll get you back to that specific point in time.

Update Item to Revision vs Revert to Revision

@BaltoStar update to revision syntax:

svn update -r30

Where 30 is revision number. Hope this help!

Given a class, see if instance has method (Ruby)

I don't know why everyone is suggesting you should be using instance_methods and include? when method_defined? does the job.

class Test
  def hello; end

Test.method_defined? :hello #=> true


In case you are coming to Ruby from another OO language OR you think that method_defined means ONLY methods that you defined explicitly with:

def my_method

then read this:

In Ruby, a property (attribute) on your model is basically a method also. So method_defined? will also return true for properties, not just methods.

For example:

Given an instance of a class that has a String attribute first_name:

<instance>.first_name.class #=> String

<instance>.class.method_defined?(:first_name) #=> true

since first_name is both an attribute and a method (and a string of type String).

How do I correct this Illegal String Offset?

if ($inputs['type'] == 'attach') {

The code is valid, but it expects the function parameter $inputs to be an array. The "Illegal string offset" warning when using $inputs['type'] means that the function is being passed a string instead of an array. (And then since a string offset is a number, 'type' is not suitable.)

So in theory the problem lies elsewhere, with the caller of the code not providing a correct parameter.

However, this warning message is new to PHP 5.4. Old versions didn't warn if this happened. They would silently convert 'type' to 0, then try to get character 0 (the first character) of the string. So if this code was supposed to work, that's because abusing a string like this didn't cause any complaints on PHP 5.3 and below. (A lot of old PHP code has experienced this problem after upgrading.)

You might want to debug why the function is being given a string by examining the calling code, and find out what value it has by doing a var_dump($inputs); in the function. But if you just want to shut the warning up to make it behave like PHP 5.3, change the line to:

if (is_array($inputs) && $inputs['type'] == 'attach') {

storing user input in array

You have at least these 3 issues:

  1. you are not getting the element's value properly
  2. The div that you are trying to use to display whether the values have been saved or not has id display yet in your javascript you attempt to get element myDiv which is not even defined in your markup.
  3. Never name variables with reserved keywords in javascript. using "string" as a variable name is NOT a good thing to do on most of the languages I can think of. I renamed your string variable to "content" instead. See below.

You can save all three values at once by doing:

var title=new Array();
var names=new Array();//renamed to names -added an S- 
                      //to avoid conflicts with the input named "name"
var tickets=new Array();

function insert(){
    var titleValue = document.getElementById('title').value;
    var actorValue = document.getElementById('name').value;
    var ticketsValue = document.getElementById('tickets').value;

And then change the show function to:

function show() {
  var content="<b>All Elements of the Arrays :</b><br>";
  for(var i = 0; i < title.length; i++) {
     content +=title[i]+"<br>";
  for(var i = 0; i < names.length; i++) {
     content +=names[i]+"<br>";
  for(var i = 0; i < tickets.length; i++) {
     content +=tickets[i]+"<br>";
  document.getElementById('display').innerHTML = content; //note that I changed 
                                                    //to 'display' because that's
                                              //what you have in your markup

Here's a jsfiddle for you to play around.

How to use JavaScript to change div backgroundColor

To do this without jQuery or any other library, you'll need to attach onMouseOver and onMouseOut events to each div and change the style in the event handlers.

For example:

var category = document.getElementById("catestory");
for (var child = category.firstChild; child != null; child = child.nextSibling) {
    if (child.nodeType == 1 && child.className == "content") {
        child.onmouseover = function() {
   = "#FF0000";

        child.onmouseout = function() {
            // Set to transparent to let the original background show through.
   = "transparent"; 

If your h2 has not set its own background, the div background will show through and color it too.

Adding and reading from a Config file

  1. Add an Application Configuration File item to your project (Right -Click Project > Add item). This will create a file called app.config in your project.

  2. Edit the file by adding entries like <add key="keyname" value="someValue" /> within the <appSettings> tag.

  3. Add a reference to the System.Configuration dll, and reference the items in the config using code like ConfigurationManager.AppSettings["keyname"].

How to master AngularJS?

Try out these videos They are awesome to get started

setting JAVA_HOME & CLASSPATH in CentOS 6


  1. Click on the Terminal icon in the desktop panel to open a terminal window and access the command prompt.
  2. Type the command which java to find the path to the Java executable file.
  3. Type the command su - to become the root user.
  4. Type the command vi /root/.bash_profile to open the system bash_profile file in the Vi text editor. You can replace vi with your preferred text editor.
  5. Type export JAVA_HOME=/usr/local/java/ at the bottom of the file. Replace /usr/local/java with the location found in step two.
  6. Save and close the bash_profile file.
  7. Type the command exit to close the root session.
  8. Log out of the system and log back in.
  9. Type the command echo $JAVA_HOME to ensure that the path was set correctly.

set java_home in centos

Cross Domain Form POSTing

The same origin policy is applicable only for browser side programming languages. So if you try to post to a different server than the origin server using JavaScript, then the same origin policy comes into play but if you post directly from the form i.e. the action points to a different server like:

<form action="">

and there is no javascript involved in posting the form, then the same origin policy is not applicable.

See wikipedia for more information

How to iterate through table in Lua?

For those wondering why ipairs doesn't print all the values of the table all the time, here's why (I would comment this, but I don't have enough good boy points).

The function ipairs only works on tables which have an element with the key 1. If there is an element with the key 1, ipairs will try to go as far as it can in a sequential order, 1 -> 2 -> 3 -> 4 etc until it cant find an element with a key that is the next in the sequence. The order of the elements does not matter.

Tables that do not meet those requirements will not work with ipairs, use pairs instead.


ipairsCompatable = {"AAA", "BBB", "CCC"}
ipairsCompatable2 = {[1] = "DDD", [2] = "EEE", [3] = "FFF"}
ipairsCompatable3 = {[3] = "work", [2] = "does", [1] = "this"}

notIpairsCompatable = {[2] = "this", [3] = "does", [4] = "not"}
notIpairsCompatable2 = {[2] = "this", [5] = "doesn't", [24] = "either"}

ipairs will go as far as it can with it's iterations but won't iterate over any other element in the table.

kindofIpairsCompatable = {[2] = 2, ["cool"] = "bro", [1] = 1, [3] = 3, [5] = 5 }

When printing these tables, these are the outputs. I've also included pairs outputs for comparison.

ipairs + ipairsCompatable
1       AAA
2       BBB
3       CCC

ipairs + ipairsCompatable2
1       DDD
2       EEE
3       FFF

ipairs + ipairsCompatable3
1       this
2       does
3       work

ipairs + notIpairsCompatable

pairs + notIpairsCompatable
2       this
3       does
4       not

ipairs + notIpairsCompatable2

pairs + notIpairsCompatable2
2       this
5       doesnt
24      either

ipairs + kindofIpairsCompatable
1       1
2       2
3       3

pairs + kindofIpairsCompatable
1       1
2       2
3       3
5       5
cool    bro

Setting default value for TypeScript object passed as argument

Typescript supports default parameters now:

Also, adding a default value allows you to omit the type declaration, because it can be inferred from the default value:

function sayName(firstName: string, lastName = "Smith") {
  const name = firstName + ' ' + lastName;


What is the difference between Dim, Global, Public, and Private as Modular Field Access Modifiers?

Dim and Private work the same, though the common convention is to use Private at the module level, and Dim at the Sub/Function level. Public and Global are nearly identical in their function, however Global can only be used in standard modules, whereas Public can be used in all contexts (modules, classes, controls, forms etc.) Global comes from older versions of VB and was likely kept for backwards compatibility, but has been wholly superseded by Public.

Trim last character from a string

In .NET 5 / C# 8:

You can write the code marked as the answer as:

public static class StringExtensions
    public static string TrimLastCharacters(this string str) => string.IsNullOrEmpty(str) ? str : str.TrimEnd(str[^1]);

However, as mentioned in the answer, this removes all occurrences of that last character. If you only want to remove the last character you should instead do:

    public static string RemoveLastCharacter(this string str) => string.IsNullOrEmpty(str) ? str : str[..^1];

A quick explanation for the new stuff in C# 8:

The ^ is called the "index from end operator". The .. is called the "range operator". ^1 is a shortcut for arr.length - 1. You can get all items after the first character of an array with arr[1..] or all items before the last with arr[..^1]. These are just a few quick examples. For more information, see, "Indices and ranges" section.

dropzone.js - how to do something after ALL files are uploaded

I up-voted you as your method is simple. I did make only a couple of slight amends as sometimes the event fires even though there are no bytes to send - On my machine it did it when I clicked the remove button on a file.

myDropzone.on("totaluploadprogress", function(totalPercentage, totalBytesToBeSent, totalBytesSent ){
            if(totalPercentage >= 100 && totalBytesSent) {
                // All done! Call func here

org.apache.jasper.JasperException: Unable to compile class for JSP:

This line of yours:

<%@ page import="pageNumber.*, java.util.*,*" %>

Requires an @ symbol before % like this:

<%@ page import="pageNumber.*, java.util.*,*" @%>

Including another class in SCSS

Another option could be using an Attribute Selector:

  //your style here

Whereas every class starting with "your-class-name" uses this style.

So in your case, you could do it like so:

  display: inline-block;
  //some other properties
   color: darken(#FFFFFF, 10%);

  //specifically for class b
  width: 100px;
     color: darken(#FFFFFF, 20%);

More about Attribute Selectors on w3Schools

Random float number generation

If you are using C++ and not C, then remember that in technical report 1 (TR1) and in the C++0x draft they have added facilities for a random number generator in the header file, I believe it is identical to the Boost.Random library and definitely more flexible and "modern" than the C library function, rand.

This syntax offers the ability to choose a generator (like the mersenne twister mt19937) and then choose a distribution (normal, bernoulli, binomial etc.).

Syntax is as follows (shameless borrowed from this site):

  #include <iostream>
  #include <random>


  std::tr1::mt19937 eng;  // a core engine class 
  std::tr1::normal_distribution<float> dist;     

  for (int i = 0; i < 10; ++i)        
      std::cout << dist(eng) << std::endl;

Counting the number of option tags in a select tag in jQuery

Another approach that can be useful.


Delete topic in Kafka

Adding to above answers one has to delete the meta data associated with that topic in zookeeper consumer offset path.

bin/ zookeeperhost:port

rmr /consumers/<sample-consumer-1>/offsets/<deleted-topic>

Otherwise the lag will be negative in kafka-monitoring tools based on zookeeper.

How do I test a single file using Jest?

You could use the file name with npm test --:

npm test -- fileName.jsx 

Batch file: Find if substring is in string (not in a file)

To find a text in the Var, Example:

var_text="demo string test"
Echo.%var_text% | findstr /C:"test">nul && (
    echo "found test" 
    ) || Echo.%var_text% | findstr /C:"String">nul && (
             echo "found String with S uppercase letter" 
    ) || (
             echo "Not Found " 


  1. & Execute_that AND execute_this
  2. || Ex: Execute_that IF_FAIL execute this
  3. && Ex: Execute_that IF_SUCCESSFUL execute this
  4. >nul no echo result of command
  5. findstr
  6. /C: Use string as a literal search string

Best way to convert text files between character sets?

Try iconv Bash function

I've put this into .bashrc:

    iconv -f ISO-8859-1 -t UTF-8 $1 > $1.tmp
    rm $1
    mv $1.tmp $1
} be able to convert files like so:


How to duplicate a whole line in Vim?

Do this:

First, yy to copy the current line, and then p to paste.

Truncate string in Laravel blade templates

Laravel 6 Update:

$value = 'Artificial Intelligence';
$var = Str::limit($value, $limit = 15, $end = '');

<p class="card-text">{{ Illuminate\Support\Str::limit($value, 7) }}</p>
<h2 class="main-head">{!! Str::limit($value, 5) !!}</h2>

How does a hash table work?

A hash table totally works on the fact that practical computation follows random access machine model i.e. value at any address in memory can be accessed in O(1) time or constant time.

So, if I have a universe of keys (set of all possible keys that I can use in a application, e.g. roll no. for student, if it's 4 digit then this universe is a set of numbers from 1 to 9999), and a way to map them to a finite set of numbers of size I can allocate memory in my system, theoretically my hash table is ready.

Generally, in applications the size of universe of keys is very large than number of elements I want to add to the hash table(I don't wanna waste a 1 GB memory to hash ,say, 10000 or 100000 integer values because they are 32 bit long in binary reprsentaion). So, we use this hashing. It's sort of a mixing kind of "mathematical" operation, which maps my large universe to a small set of values that I can accomodate in memory. In practical cases, often space of a hash table is of the same "order"(big-O) as the (number of elements *size of each element), So, we don't waste much memory.

Now, a large set mapped to a small set, mapping must be many-to-one. So, different keys will be alloted the same space(?? not fair). There are a few ways to handle this, I just know the popular two of them:

  • Use the space that was to be allocated to the value as a reference to a linked list. This linked list will store one or more values, that come to reside in same slot in many to one mapping. The linked list also contains keys to help someone who comes searching. It's like many people in same apartment, when a delivery-man comes, he goes to the room and asks specifically for the guy.
  • Use a double hash function in an array which gives the same sequence of values every time rather than a single value. When I go to store a value, I see whether the required memory location is free or occupied. If it's free, I can store my value there, if it's occupied I take next value from the sequence and so on until I find a free location and I store my value there. When searching or retreiving the value, I go back on same path as given by the sequence and at each location ask for the vaue if it's there until I find it or search all possible locations in the array.

Introduction to Algorithms by CLRS provides a very good insight on the topic.

What's the "average" requests per second for a production web application?

You can search "slashdot effect analysis" for graphs of what you would see if some aspect of the site suddenly became popular in the news, e.g. this graph on wiki.

Web-applications that survive tend to be the ones which can generate static pages instead of putting every request through a processing language.

There was an excellent video (I think it might have been on I think it might have been by flickr web team? Does someone know the link?) with ideas on how to scale websites beyond the single server, e.g. how to allocate connections amongst the mix of read-only and read-write servers to get best effect for various types of users.

Need to get current timestamp in Java

The fact that SimpleDateFormat is not thread-safe does not mean you cannot use it. What that only means is that you must not use a single (potentially, but not necessarily static) instance that gets accessed from several threads at once.

Instead, just make sure you create a fresh SimpleDateFormat for each thread. Instances created as local variables inside a method are safe by definition, because they cannot be reached from any concurrent threads.

You might want to take a look at the ThreadLocal class, although I would recommend to just create a new instance wherever you need one. You can, of course, have the format definition defined as a static final String DATE_FORMAT_PATTERN = "..."; somewhere and use that for each new instance.

How to make --no-ri --no-rdoc the default for gem install?

Note that --no-ri and --no-rdoc have been deprecated according to the new guides. The recommended way is to use --no-document in ~/.gemrc or /etc/gemrc.

install: --no-document
update: --no-document


gem: --no-document

JQuery - Set Attribute value

Some things before the actual code..

the hash (#) you use as the selector is for IDs and not for names of elements. also the disabled attribute is not a true false scenario .. if it has disabled attribute it means that it is true .. you need to remove the attribute and not set it to false. Also there are the form selectors that identify specific types of items in a form ..

so the code would be


Bringing the answer up-to-date

You should use the .prop() method (added since v1.6)

$("input:checkbox[name='chk0']").prop('disabled', false); // to enable the checkbox


$("input:checkbox[name='chk0']").prop('disabled', true); // to disable the checkbox

Using reflection in Java to create a new instance with the reference variable type set to the new instance class name?

You want to be able to pass in a Class and get a type-safe instance of that class? Try the following:

public static void main(String [] args) throws Exception {
    String s = instanceOf(String.class);

public static <T> T instanceOf (Class<T> clazz) throws Exception {
    return clazz.newInstance();

Cannot read property 'addEventListener' of null

I've a collection of quotes along with names. I'm using update button to update the last quote associated with a specific name but on clicking update button it's not updating. I'm including code below for server.js file and external js file (main.js).

main.js (external js)

var update = document.getElementById('update');
if (update){
update.addEventListener('click', function () {

  fetch('quotes', {
  method: 'put',
  headers: {'Content-Type': 'application/json'},
  body: JSON.stringify({
    'name': 'Muskan',
    'quote': 'I find your lack of faith disturbing.'
})var update = document.getElementById('update');
if (update){
update.addEventListener('click', function () {

  fetch('quotes', {
  method: 'put',
  headers: {'Content-Type': 'application/json'},
  body: JSON.stringify({
    'name': 'Muskan',
    'quote': 'I find your lack of faith disturbing.'
.then(res =>{
    if(res.ok) return res.json()
.then(data =>{

server.js file

app.put('/quotes', (req, res) => {
  db.collection('quotations').findOneAndUpdate({name: 'Vikas'},{
        quote: req.body.quote
    sort: {_id: -1},
    upsert: true
  },(err, result) =>{
    if (err) return res.send(err);


Where can I get Google developer key

You should be able to generate a Youtube API key there.

The recommended way to authorize your API call is to use OAuth 2.0 (without API key), as pointed by the documentation an API key is only necessary when using OAuth 1.0 credentials.

The API key for your application can be found in the Google APIs Console in API Access > Simple API.

Changing the image source using jQuery

Hope this can work

<img id="dummyimage" src="" alt="" />
<button id="changeSize">Change Size</button>
$(document).ready(function() {
    var flag = 0;
    $("button#changeSize").click(function() {
        if (flag == 0) {
            $("#dummyimage").attr("src", "");
            flag = 1;
        } else if (flag == 1) {
            $("#dummyimage").attr("src", "");
            flag = 0;

Is it possible to modify a string of char in C?

It seems like your question has been answered but now you might wonder why char *a = "String" is stored in read-only memory. Well, it is actually left undefined by the c99 standard but most compilers choose to it this way for instances like:

printf("Hello, World\n");

c99 standard(pdf) [page 130, section 6.7.8]:

The declaration:

char s[] = "abc", t[3] = "abc";

defines "plain" char array objects s and t whose elements are initialized with character string literals. This declaration is identical to char

s[] = { 'a', 'b', 'c', '\0' }, t[] = { 'a', 'b', 'c' };

The contents of the arrays are modifiable. On the other hand, the declaration

char *p = "abc";

defines p with type "pointer to char" and initializes it to point to an object with type "array of char" with length 4 whose elements are initialized with a character string literal. If an attempt is made to use p to modify the contents of the array, the behavior is undefined.

How can I make a "color map" plot in matlab?

I also suggest using contourf(Z). For my problem, I wanted to visualize a 3D histogram in 2D, but the contours were too smooth to represent a top view of histogram bars.

So in my case, I prefer to use jucestain's answer. The default shading faceted of pcolor() is more suitable. However, pcolor() does not use the last row and column of the plotted matrix. For this, I used the padarray() function:

pcolor(padarray(Z,[1 1],0,'post'))

Sorry if that is not really related to the original post

'ssh-keygen' is not recognized as an internal or external command

I just had this issue and thought I'd share what I thought was an easier way around this.

Open git-bash and run the same command with the addition of -C since you're commenting in your email address: ssh-keygen -t rsa -C "[email protected]" command. That's it.

git-bash should have been installed when you installed git. If you can't find it you can check C:\Program Files\Git\Git Bash

The first time I did this it failed to create the .ssh folder for me so I had to open a standard Command Prompt and mkdir C:\Users\yourusername\.ssh

How do I convert a float to an int in Objective C?

what's wrong with:

int myInt = myFloat;

bear in mind this'll use the default rounding rule, which is towards zero (i.e. -3.9f becomes -3)

Are there any log file about Windows Services Status?

The most likely place to find this sort of information is in the event viewer (under Administrative tools in XP or run eventvwr) This is where most services log warnings errors etc.

How do I find the authoritative name-server for a domain name?

You can use the whois service. On a UNIX like operating system you would execute the following command. Alternatively you can do it on the web at


You would get the following response.

...text removed here...

Domain servers in listed order: NS51.DOMAINCONTROL.COM NS52.DOMAINCONTROL.COM

You can use nslookup or dig to find out more information about records for a given domain. This might help you resolve the conflicts you have described.

Is it possible to have SSL certificate for IP address, not domain name?

The answer is yes. In short, it is a subject alternative name (SAN) certificate that contains IPs where you would typically see DNS entries. The certificate type is not limited to Public IPs - that restriction is only imposed by a signing authority rather than the technology. I just wanted to clarify that point. I suspect you really just want to get rid of that pesky insecure prompt on your internal websites and devices without the cost and hassle of giving them DNS names then paying for a CA to issue a cert every year or two. You should NOT be trying to convince the world that your IP address is a reputable website and folks should feel comfortable providing their payment information. Now that we have established why no reputable organization wants to issue this type of certificate, lets just do it ourselves with a self signed SAN certificate. Internally I have a trusted certificate that is deployed to all of our hosts, then I sign this type of certificate with it and all devices become trusted. Doing that here is beyond the scope of the question but I think it relevant to the discussion as the question and solution go hand in hand. To be concise, here is how to generate an individual self signed SAN certificate with IP addresses. Expand the IP list to include your entire subnet and use one cert for everything.

#using: OpenSSL 1.1.1c FIPS  28 May 2019 / CentOS Linux release 8.2.2004

C=US ; ST=Confusion ; L=Anywhere ; O=Private\ Subnet ; [email protected]

openssl genrsa -out ip.key $BITS


cp /etc/pki/tls/openssl.cnf /tmp/openssl.cnf
echo -e "$SAN" >> /tmp/openssl.cnf

openssl req -subj "$SUBJ" -new -x509 -days 10950 \
    -key ip.key -out ip.crt -batch \
    -set_serial 168933982 \
    -config /tmp/openssl.cnf \
    -extensions SAN

openssl x509 -in ip.crt -noout -text

System.Threading.Timer in C# it seems to be not working. It runs very fast every 3 second

Is using System.Threading.Timer mandatory?

If not, System.Timers.Timer has handy Start() and Stop() methods (and an AutoReset property you can set to false, so that the Stop() is not needed and you simply call Start() after executing).

If file exists then delete the file

IF both POS_History_bim_data_*.zip and POS_History_bim_data_*.zip.trg exists in  Y:\ExternalData\RSIDest\ Folder then Delete File Y:\ExternalData\RSIDest\Target_slpos_unzip_done.dat

Full width layout with twitter bootstrap

Because the accepted answer isn't on the same planet as BS3, I'll share what I'm using to achieve nearly full-width capabilities.

First off, this is cheating. It's not really fluid width - but it appears to be - depending on the size of the screen viewing the site.

The problem with BS3 and fluid width sites is that they have taken this "mobile first" approach, which requires that they define every freaking screen width up to what they consider to be desktop (1200px) I'm working on a laptop with a 1900px wide screen - so I end up with 350px on either side of the content at what BS3 thinks is a desktop sized width.

They have defined 10 screen widths (really only 5, but anyway). I don't really feel comfortable changing those, because they are common widths. So, I chose to define some extra widths for BS to choose from when deciding the width of the container class.

The way I use BS is to take all of the Bootstrap provided LESS files, omit the variables.less file to provide my own, and add one of my own to the end to override the things I want to change. Within my less file, I add the following to achieve 2 common screen width settings:

@media screen and (min-width: 1600px) {
    .container {
        max-width: (1600px - @grid-gutter-width);
@media screen and (min-width: 1900px) {
    .container {
        max-width: (1900px - @grid-gutter-width);

These two settings set the example for what you need to do to achieve different screen widths. Here, you get full width at 1600px, and 1900px. Any less than 1600 - BS falls back to the 1200px width, then to 768px and so forth - down to phone size.

If you have larger to support, just create more @media screen statements like these. If you're building the CSS instead, you'll want to determine what gutter width was used and subtract it from your target screen width.


Bootstrap 3.0.1 and up (so far) - it's as easy as setting @container-large-desktop to 100%

How can I roll back my last delete command in MySQL?

Rollback normally won't work on these delete functions and surely a backup only can save you.

If there is no backup then there is no way to restore it as delete queries ran on PuTTY,Derby using .sql files are auto committed once you fire the delete query.

Initializing select with AngularJS and ng-repeat

For the select tag, angular provides the ng-options directive. It gives you the specific framework to set up options and set a default. Here is the updated fiddle using ng-options that works as expected:

Updated HTML (code stays the same)

<body ng-app ng-controller="AppCtrl">
<div>Operator is: {{filterCondition.operator}}</div>
<select ng-model="filterCondition.operator" ng-options="operator.value as operator.displayName for operator in operators">

<ng-container> vs <template>

In my case it acts like a <div> or <span> however even <span> messes up with my AngularFlex styling but ng-container doesn't.

Firebase FCM force onTokenRefresh() to be called

The onTokenRefresh() method is going to be called whenever a new token is generated. Upon app install, it will be generated immediately (as you have found to be the case). It will also be called when the token has changed.

According to the FirebaseCloudMessaging guide:

You can target notifications to a single, specific device. On initial startup of your app, the FCM SDK generates a registration token for the client app instance.


Source Link:

This means that the token registration is per app. It sounds like you would like to utilize the token after a user is logged in. What I would suggest is that you save the token in the onTokenRefresh() method to internal storage or shared preferences. Then, retrieve the token from storage after a user logs in and register the token with your server as needed.

If you would like to manually force the onTokenRefresh(), you can create an IntentService and delete the token instance. Then, when you call getToken, the onTokenRefresh() method will be called again.

Example Code:

public class DeleteTokenService extends IntentService
    public static final String TAG = DeleteTokenService.class.getSimpleName();

    public DeleteTokenService()

    protected void onHandleIntent(Intent intent)
            // Check for current token
            String originalToken = getTokenFromPrefs();
            Log.d(TAG, "Token before deletion: " + originalToken);

            // Resets Instance ID and revokes all tokens.

            // Clear current saved token

            // Check for success of empty token
            String tokenCheck = getTokenFromPrefs();
            Log.d(TAG, "Token deleted. Proof: " + tokenCheck);

            // Now manually call onTokenRefresh()
            Log.d(TAG, "Getting new token");
        catch (IOException e)

    private void saveTokenToPrefs(String _token)
        // Access Shared Preferences
        SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
        SharedPreferences.Editor editor = preferences.edit();

        // Save to SharedPreferences
        editor.putString("registration_id", _token);

    private String getTokenFromPrefs()
        SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
        return preferences.getString("registration_id", null);



public class FirebaseInstanceIdService extends Service

This class is deprecated. In favour of overriding onNewToken in FirebaseMessagingService. Once that has been implemented, this service can be safely removed.

onTokenRefresh() is deprecated. Use onNewToken() in MyFirebaseMessagingService

public class MyFirebaseMessagingService extends FirebaseMessagingService {

public void onNewToken(String s) {

public void onMessageReceived(RemoteMessage remoteMessage) {

SCRIPT7002: XMLHttpRequest: Network Error 0x2ef3, Could not complete the operation due to error 00002ef3


I only observed this error today, for me the Error code was different though.

SCRIPT7002: XMLHttpRequest: Network Error 0x2efd, Could not complete the operation due to error 00002efd.

It was occurring randomly and not all the time. but what it noticed is, if it comes for subsequent ajax calls. so i put some delay of 5 seconds between the ajax calls and it resolved.

Difference between _self, _top, and _parent in the anchor tag target attribute


Opens a new window and show the related data.


Opens the window in the same frame, it means existing window itself.


Opens the linked document in the full body of the window.


Opens data in the size of parent window.

How can I remove a specific item from an array?

Remove by Index

A function that returns a copy of array without the element at index:

* removeByIndex
* @param {Array} array
* @param {Number} index
function removeByIndex(array, index){
      return array.filter(function(elem, _index){
          return index != _index;
l = [1,3,4,5,6,7];
console.log(removeByIndex(l, 1));

$> [ 1, 4, 5, 6, 7 ]

Remove by Value

Function that return a copy of array without the Value.

* removeByValue
* @param {Array} array
* @param {Number} value
function removeByValue(array, value){
      return array.filter(function(elem, _index){
          return value != elem;
l = [1,3,4,5,6,7];
console.log(removeByValue(l, 5));

$> [ 1, 3, 4, 6, 7]

How to set min-font-size in CSS

.class {
    font-size: clamp(minimum-size, prefered-size, maximum-size)

using this you could set it up so prefered and max values are 5vw but the minimum is 15px or something so it won't go over 5vw but if 5vw < 15px it will stick to 15px

AppFabric installation failed because installer MSI returned with error code : 1603

So, I was having the same issue. The main reason I am installing Appfabric is to create a SharePoint 2013 development server.
What did not work:

  • Updating the Environmental Variable PSModulePath - did not work. Still recieved the 1603 error after running the setup agian.
  • tried to find the registry entries. Could not find them.

What worked for me to get Appfrabic installed was installing from the setup file via powershell. Woo hoo! It worked for me! This is the link I retrieved the commands from: Installing AppFabric 1.1 with PowerShell DSC results in modal dialog error

        Start-Process -FilePath 'c:\temp\SharePoint\pre\appfabric\setup.exe' -ArgumentList '/i cacheclient","cachingService","CacheAdmin /gac /l c:\temp\appfabric.log' -Wait | Write-verbose
        Start-Process -FilePath 'c:\temp\SharePoint\pre\AppFabric1.1-RTM-KB2671763-x64-ENU.exe' -ArgumentList '/quiet' -Wait | Write-verbose

I hope this helps others with the same issue.

Verifying that a string contains only letters in C#

I think is a good case to use Regular Expressions:

public bool IsAlpha(string input)
    return Regex.IsMatch(input, "^[a-zA-Z]+$");

public bool IsAlphaNumeric(string input)
    return Regex.IsMatch(input, "^[a-zA-Z0-9]+$");

public bool IsAlphaNumericWithUnderscore(string input)
    return Regex.IsMatch(input, "^[a-zA-Z0-9_]+$");

Adding div element to body or document in JavaScript

The most underrated method is insertAdjacentElement. You can literally add your HTML using one single line.

document.body.insertAdjacentElement('beforeend', html)

Read about it here -

How to split a string with angularJS

You could try this:

$scope.testdata = [{ 'name': 'name,id' }, {'name':'someName,someId'}]
$scope.array= [];
angular.forEach($scope.testdata, function (value, key) {
    $scope.array.push({ 'name':',')[0], 'id':',')[1] });

This way you can save the data for later use and acces it by using an ng-repeat like this:

<div ng-repeat="item in array">{{}}{{}}</div>

I hope this helped someone,
Plunker link: here
All credits go to @jwpfox and @Mohideen ibn Mohammed from the answer above.

How to delete empty folders using windows command prompt?

You don't need usebackq:

FOR /F delims^= %%A IN ('DIR/AD/B/S^|SORT/R') DO RD "%%A"

How to convert list data into json in java

You can use the following method which uses Jackson library

public static <T> List<T> convertToList(String jsonString, Class<T> target) {
    if(StringUtils.isEmpty(jsonString)) return List.of();

        return new ObjectMapper().readValue(jsonString, new ObjectMapper().getTypeFactory().
                constructCollectionType(List.class, target));
    } catch ( JsonProcessingException | JSONException e) {
        return List.of();

while installing vc_redist.x64.exe, getting error "Failed to configure per-machine MSU package."

The OS failed to install the required update Windows8.1-KB2999226-x64.msu. However I tried to find the particular update from -

C:\ProgramData\Package Cache\469A82B09E217DDCF849181A586DF1C97C0C5C85\packages\Patch\amd64\Windows8.1-KB2999226-x64.msu.

I couldn't find it there so I installed the kb2999226 update from here (Windows 10 Universal C runtime)

Then I installed the update according to my OS and after that It was working fine.

Listing available com ports with Python

Basically mentioned this in pyserial documentation

ports =

for port, desc, hwid in sorted(ports):
        print("{}: {} [{}]".format(port, desc, hwid))

Result :

COM1: Communications Port (COM1) [ACPI\PNP0501\1]

COM7: MediaTek USB Port (COM7) [USB VID:PID=0E8D:0003 SER=6 LOCATION=1-2.1]

How to achieve function overloading in C?

Here is the clearest and most concise example I've found demonstrating function overloading in C:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int addi(int a, int b) {
    return a + b;

char *adds(char *a, char *b) {
    char *res = malloc(strlen(a) + strlen(b) + 1);
    strcpy(res, a);
    strcat(res, b);
    return res;

#define add(a, b) _Generic(a, int: addi, char*: adds)(a, b)

int main(void) {
    int a = 1, b = 2;
    printf("%d\n", add(a, b)); // 3

    char *c = "hello ", *d = "world";
    printf("%s\n", add(c, d)); // hello world

    return 0;

How to get random value out of an array?

One line: $ran[rand(0, count($ran) - 1)]

Using NSLog for debugging

type : BOOL DATA (YES/NO) OR(1/0)

BOOL dtBool = 0; 


BOOL dtBool = NO;
NSLog(dtBool ? @"Yes" : @"No");


type : Long

long aLong = 2015;
NSLog(@"Display Long: %ld”, aLong);

OUTPUT : Display Long: 2015

long long veryLong = 20152015;
NSLog(@"Display very Long: %lld", veryLong);

OUTPUT : Display very Long: 20152015

type : String

NSString *aString = @"A string";
NSLog(@"Display string: %@", aString);

OUTPUT : Display String: a String

type : Float

float aFloat = 5.34245;
NSLog(@"Display Float: %F", aFloat);

OUTPUT : isplay Float: 5.342450

type : Integer

int aInteger = 3;    
NSLog(@"Display Integer: %i", aInteger);

OUTPUT : Display Integer: 3

NSLog(@"\nDisplay String: %@ \n\n Display Float: %f \n\n Display Integer: %i", aString, aFloat, aInteger);

OUTPUT : String: a String

Display Float: 5.342450

Display Integer: 3

capture div into image using html2canvas didn't work for me... just a blank page rendered... but I was able to make the png appear on the page by replacing the src attribute of a pre-existing img element created as the target.

     element_to_png("container", "testhtmltocanvasimg");_x000D_
function element_to_png(srcElementID, targetIMGid){_x000D_
    console.log("element_to_png called for element id " + srcElementID);_x000D_
    html2canvas($("#"+srcElementID)[0]).then( function (canvas) {_x000D_
        var myImage = canvas.toDataURL("image/png");_x000D_
        $("#"+targetIMGid).attr("src", myImage);_x000D_
  console.log("html2canvas completed.  png rendered to " + targetIMGid);_x000D_
<div id="testhtmltocanvasdiv" class="mt-3">_x000D_
   <img src="" id="testhtmltocanvasimg">_x000D_

I can then right-click on the rendered png and "save as". May be just as easy to use the "snipping tool" to capture the element, but html2canvas is an certainly an interesting bit of code!

How to specify the actual x axis values to plot as x axis ticks in R

Hope this coding will helps you :)

plot(x,y,xaxt = 'n')


How to switch a user per task or set of tasks?

In Ansible 2.x, you can use the block for group of tasks:

- block:
    - name: checkout repo
        version: master
        dest: "{{ dst }}"
    - name: change perms
      dest: "{{ dst }}"
      state: directory
      mode: 0755
      owner: some_user
  become: yes
  become_user: some user

Spring JSON request getting 406 (not Acceptable)

I had same issue, with Latest Spring 4.1.1 onwards you need to add following jars to pom.xml.


also make sure you have following jar:



406 Spring MVC Json, not acceptable according to the request "accept" headers

What is an 'undeclared identifier' error and how do I fix it?

Every undeclared variable in c error comes because the compiler is not able to find it in the project. One can include the external (header) file of the library in which the variable is defined. Hence in your question, you require <stdio.h>, that is a standard input output file, which describes printf(), functionality.

According to the documentation, the declaration of fprintf() is in i.e. you have to include it, before using the function.

Difference between chr(13) and chr(10)

Chr(10) is the Line Feed character and Chr(13) is the Carriage Return character.

You probably won't notice a difference if you use only one or the other, but you might find yourself in a situation where the output doesn't show properly with only one or the other. So it's safer to include both.

Historically, Line Feed would move down a line but not return to column 1:


Similarly Carriage Return would return to column 1 but not move down a line:


Paste this into a text editor and then choose to "show all characters", and you'll see both characters present at the end of each line. Better safe than sorry.

Rmi connection refused with localhost

it seems that you should set your command as an String[],for example:

String[] command = new String[]{"rmiregistry","2020"};

it just like the style of main(String[] args).

C++ int float casting

he does an integer divide, which means 3 / 4 = 0. cast one of the brackets to float

 (float)(a.y - b.y) / (a.x - b.x);

Run-time error '1004' - Method 'Range' of object'_Global' failed

When you reference Range like that it's called an unqualified reference because you don't specifically say which sheet the range is on. Unqualified references are handled by the "_Global" object that determines which object you're referring to and that depends on where your code is.

If you're in a standard module, unqualified Range will refer to Activesheet. If you're in a sheet's class module, unqualified Range will refer to that sheet.

inputTemplateContent is a variable that contains a reference to a range, probably a named range. If you look at the RefersTo property of that named range, it likely points to a sheet other than the Activesheet at the time the code executes.

The best way to fix this is to avoid unqualified Range references by specifying the sheet. Like

With ThisWorkbook.Worksheets("Template")
    .Range(inputTemplateHeader).Value = NO_ENTRY
    .Range(inputTemplateContent).Value = NO_ENTRY
End With

Adjust the workbook and worksheet references to fit your particular situation.

Eclipse "Server Locations" section disabled and need to change to use Tomcat installation

Ok, sorry for my previous answer, I had never seen that Overview screen before.

Here is how I did it:

  1. Right click on my tomcat server in "Servers" view, select "Properties…"
  2. In the "General" panel, click on the "Switch Location" button
  3. The "Location: [workspace metadata]" bit should have been replaced by something else.
  4. Open (or close and reopen) the Overview screen for the server.

How is length implemented in Java Arrays?

It is a public final field for the array type. You can refer to the document below:

Django, creating a custom 500/404 error page

In Django 3.x, the accepted answer won't work because render_to_response has been removed completely as well as some more changes have been made since the version the accepted answer worked for.

Some other answers are also there but I'm presenting a little cleaner answer:

In your main file:

handler404 = 'yourapp.views.handler404'
handler500 = 'yourapp.views.handler500'

In yourapp/ file:

def handler404(request, exception):
    context = {}
    response = render(request, "pages/errors/404.html", context=context)
    response.status_code = 404
    return response

def handler500(request):
    context = {}
    response = render(request, "pages/errors/500.html", context=context)
    response.status_code = 500
    return response

Ensure that you have imported render() in yourapp/ file:

from django.shortcuts import render

Side note: render_to_response() was deprecated in Django 2.x and it has been completely removed in verision 3.x.

Eclipse error "ADB server didn't ACK, failed to start daemon"

I had the same problem. But there was no process of adb on my laptop. I just log out and log in to my account, and it's resolved...

ADB could start from CMD windows after that.

How do you print in Sublime Text 2

  1. Install the Package Control first and restart your editor. See: How to install plugins to Sublime Text 2 editor?
  2. Install Highlight plugin.
    1. Open the pallete, press ctrl+shift+p (Win, Linux) or cmd+shift+p (OS X).
    2. Type and confirm: Install Package
    3. Type and confirm: Highlight or Print

Also see related printing forum topic: Printing from sublime

Saving Excel workbook to constant path with filename from two fields

Ok, at that time got it done with the help of a friend and the code looks like this.

Sub Saving()

Dim part1 As String

Dim part2 As String

part1 = Range("C5").Value

part2 = Range("C8").Value

ActiveWorkbook.SaveAs Filename:= _

"C:\-docs\cmat\Desktop\pieteikumi\" & part1 & " " & part2 & ".xlsm", FileFormat:= _
xlOpenXMLWorkbookMacroEnabled, CreateBackup:=False

End Sub

How do I edit this part (FileFormat:= _ xlOpenXMLWorkbookMacroEnabled) for it to save as Excel 97-2013 Workbook, have tried several variations with no success. Thankyou

Seems, that I found the solution, but my idea is flawed. By doing this FileFormat:= _ xlOpenXMLWorkbook, it drops out a popup saying, the you cannot save this workbook as a file without Macro enabled. So, is this impossible?

iterate through a map in javascript

The callback to $.each() is passed the property name and the value, in that order. You're therefore trying to iterate over the property names in the inner call to $.each(). I think you want:

$.each(myMap, function (i, val) {
  $.each(val, function(innerKey, innerValue) {
    // ...

In the inner loop, given an object like your map, the values are arrays. That's OK, but note that the "innerKey" values will all be numbers.

edit — Now once that's straightened out, here's the next problem:

    setTimeout(function () {

      // ...

    }, i * 6000);

The first time through that loop, "i" will be the string "partnr1". Thus, that multiplication attempt will result in a NaN. You can keep an external counter to keep track of the property count of the outer map:

var pcount = 1;
$.each(myMap, function(i, val) {
  $.each(val, function(innerKey, innerValue) {
    setTimeout(function() {
      // ...
    }, pcount++ * 6000);

Preprocessing in scikit learn - single sample - Depreciation warning

I faced the same issue and got the same deprecation warning. I was using a numpy array of [23, 276] when I got the message. I tried reshaping it as per the warning and end up in nowhere. Then I select each row from the numpy array (as I was iterating over it anyway) and assigned it to a list variable. It worked then without any warning.

array = []

Then you can use the python list object (here 'array') as an input to sk-learn functions. Not the most efficient solution, but worked for me.

Deleting all pending tasks in celery / rabbitmq

From the docs:

$ celery -A proj purge


from proj.celery import app

(EDIT: Updated with current method.)

Non-Static method cannot be referenced from a static context with methods and variables

Merely for the purposes of making your program work, take the contents of your main() method and put them in a constructor:

public BookStoreApp2()
   // Put contents of main method here

Then, in your main() method. Do this:

public void main( String[] args )
  new BookStoreApp2();

What is JavaScript garbage collection?

"In computer science, garbage collection (GC) is a form of automatic memory management. The garbage collector, or just collector, attempts to reclaim garbage, or memory used by objects that will never be accessed or mutated again by the application."

All JavaScript engines have their own garbage collectors, and they may differ. Most time you do not have to deal with them because they just do what they supposed to do.

Writing better code mostly depends of how good do you know programming principles, language and particular implementation.

How can I enable the Windows Server Task Scheduler History recording?

This may help others where there is no option to Enable/Disable the history anywhere in Task Scheduler.

Open Event Viewer (either in Computer Management or Admin Tools > Event Viewer).

In Event Viewer make sure the Preview Pane is showing (View > Preview Pane should be ticked)

In the left hand pane expand Application and Service Logs then Microsoft, Windows, TaskScheduler and then select Operational.

You should have Actions showing in the preview pane with two sections - Operational and below that Event nnn, TaskScheduler. One of the items listed in the Operational section should be Properties. Click this item and the Enable Logging option is on the General tab.

My problem was that the maximum log size had been reached and even though the overwrite old events option was selected it wasn't logging new events. I suspect that might have been a permissions issue but I changed it to Archive when full and all is now working again.

Hope this helps someone else out there. If you don't have the options I've mentioned above I'm sorry, but I don't know where you should look.

Matrix Transpose in Python

Python 2:

>>> theArray = [['a','b','c'],['d','e','f'],['g','h','i']]
>>> zip(*theArray)
[('a', 'd', 'g'), ('b', 'e', 'h'), ('c', 'f', 'i')]

Python 3:

>>> [*zip(*theArray)]
[('a', 'd', 'g'), ('b', 'e', 'h'), ('c', 'f', 'i')]

How do I escape a single quote ( ' ) in JavaScript?

    document.getElementById("something").innerHTML = "<img src=\"something\" onmouseover=\"change('ex1')\" />";


    document.getElementById("something").innerHTML = '<img src="something" onmouseover="change(\'ex1\')" />';

It should be working...

Passing multiple values for same variable in stored procedure

You will need to do a couple of things to get this going, since your parameter is getting multiple values you need to create a Table Type and make your store procedure accept a parameter of that type.

Split Function Works Great when you are getting One String containing multiple values but when you are passing Multiple values you need to do something like this....


CREATE TYPE dbo.TYPENAME AS TABLE   (     arg int    )  GO 

Stored Procedure to Accept That Type Param

 CREATE PROCEDURE mainValues   @TableParam TYPENAME READONLY  AS     BEGIN     SET NOCOUNT ON;   --Temp table to store split values   declare @tmp_values table (   value nvarchar(255) not null);        --function splitting values     INSERT INTO @tmp_values (value)    SELECT arg FROM @TableParam      SELECT * FROM @tmp_values  --<-- For testing purpose END 


Declare a variable of that type and populate it with your values.

 DECLARE @Table TYPENAME     --<-- Variable of this TYPE   INSERT INTO @Table                --<-- Populating the variable   VALUES (331),(222),(876),(932)  EXECUTE mainValues @Table   --<-- Stored Procedure Executed  


╔═══════╗ ║ value ║ ╠═══════╣ ║   331 ║ ║   222 ║ ║   876 ║ ║   932 ║ ╚═══════╝ 

Unix command to check the filesize

You can use:ls -lh, then you will get a list of file information

$apply already in progress error

If scope must be applied in some cases, then you can set a timeout so that the $apply is deferred until the next tick

setTimeout(function(){ scope.$apply(); });

or wrap your code in a $timeout(function(){ .. }); because it will automatically $apply the scope at the end of execution. If you need your function to behave synchronously, I'd do the first.

How to convert BigDecimal to Double in Java?

Use doubleValue method present in BigDecimal class :

double doubleValue()

Converts this BigDecimal to a double.

Get all table names of a particular database by SQL query?



How to render an array of objects in React?

You can pass any JavaScript expression as children, by enclosing it within {}. For example, these expressions are equivalent:



This is often useful for rendering a list of JSX expressions of arbitrary length. For example, this renders an HTML list:

function Item(props) {
  return <li>{props.message}</li>;

function TodoList() {
  const todos = ['finish doc', 'submit pr', 'nag dan to review'];
  return (
      { => <Item key={message} message={message} />)}

class First extends React.Component {_x000D_
  constructor(props) {_x000D_
    this.state = {_x000D_
      data: [{name: 'bob'}, {name: 'chris'}],_x000D_
  render() {_x000D_
    return (_x000D_
        { => <li key={}>{}</li>)}_x000D_
  <First />,_x000D_
<script src=""></script>_x000D_
<script src=""></script>_x000D_
<div id="root"></div>

Oracle: SQL query that returns rows with only numeric values

If the only characters to consider are letters then you can do:

select X from myTable where upper(X) = lower(X)

But of course that won't filter out other characters, just letters.

Check if element found in array c++

In C++ you would use std::find, and check if the resultant pointer points to the end of the range, like this:

Foo array[10];
... // Init the array here
Foo *foo = std::find(std::begin(array), std::end(array), someObject);
// When the element is not found, std::find returns the end of the range
if (foo != std::end(array)) {
    cerr << "Found at position " << std::distance(array, foo) << endl;
} else {
    cerr << "Not found" << endl;

How to get the class of the clicked element?


Convert from MySQL datetime to another format with PHP

To correctly format a DateTime object in PHP for storing in MySQL use the standardised format that MySQL uses, which is ISO 8601.

PHP has had this format stored as a constant since version 5.1.1, and I highly recommend using it rather than manually typing the string each time.

$dtNow = new DateTime();
$mysqlDateTime = $dtNow->format(DateTime::ISO8601);

This, and a list of other PHP DateTime constants are available at

Debug assertion failed. C++ vector subscript out of range

this type of error usually occur when you try to access data through the index in which data data has not been assign. for example

//assign of data in to array
for(int i=0; i<10; i++){
//accessing of data through array index
for(int i=10; i>=0; i--){
cout << arr[i];

the code will give error (vector subscript out of range) because you are accessing the arr[10] which has not been assign yet.

Python Script Uploading files via FTP

Try this:

#!/usr/bin/env python

import os
import paramiko 
ssh = paramiko.SSHClient()
ssh.connect('hostname', username="username", password="password")
sftp = ssh.open_sftp()
localpath = '/home/e100075/python/ss.txt'
remotepath = '/home/developers/screenshots/ss.txt'
sftp.put(localpath, remotepath)

How can I create a copy of an object in Python?

To get a fully independent copy of an object you can use the copy.deepcopy() function.

For more details about shallow and deep copying please refer to the other answers to this question and the nice explanation in this answer to a related question.

Error: "The sandbox is not in sync with the Podfile.lock..." after installing RestKit with cocoapods

Check in your project that Pods are maybe not being pushed to Git. So it's obvious that compile will break since it cannot find the Pods directory

 diff "${PODS_ROOT}/../../Podfile.lock" "${PODS_ROOT}/Manifest.lock" > /dev/null

I solved this by issuing pod install in the Terminal after navigating to my project's directory.

Indeed, I had an error cannot find pod command which meant that cocoapods were not installed. This is fixed via gem install cocoapods. If you get any dependency error, just install each command that is reported missing. In my case I had to update Ruby and after that cocoapods were installed properly and I was able to use the command pod install.

PS. If you have Pods directory, try pod update. Maybe your library needs updating.

Insertion sort vs Bubble Sort Algorithms

Though both the sorts are O(N^2).The hidden constants are much smaller in Insertion sort.Hidden constants refer to the actual number of primitive operations carried out.

When insertion sort has better running time?

  1. Array is nearly sorted-notice that insertion sort does fewer operations in this case, than bubble sort.
  2. Array is of relatively small size: insertion sort you move elements around, to put the current element.This is only better than bubble sort if the number of elements is few.

Notice that insertion sort is not always better than bubble sort.To get the best of both worlds, you can use insertion sort if array is of small size, and probably merge sort(or quicksort) for larger arrays.

Run a Command Prompt command from Desktop Shortcut

Using the Drag and Drop method

  1. From the windows search bar type in cmd to pull up the windows bar operation.
  2. When the command line option is shown, right click it and select Open File Location.
  3. The file explorer opens and the shortcut link is highlighted in the folder. If it is not highlighted, then select it.
  4. Hold down the Control key and using the mouse drag the shortcut to the desktop. If you don't see Copy to Desktop while dragging and before dropping, then push down and hold the Control key until you see the message.
  5. Drop the link on the desktop.
  6. Change properties as needed.

Selecting only first-level elements in jquery


 $("ul.rootlist > target-element")
2   $("ul.rootlist").find(target-element).eq(0) (only one instance)
3   $("ul.rootlist").children(target-element)

there are probably many other ways

Mysql service is missing

I came across the same problem. I properly installed the MYSQL Workbench 6.x, but faced the connection as below:

enter image description here

I did a bit R&D on this and found that MySQL service in service.msc is not present. To achieve this I created a new connection in MySQL Workbench then manually configured the MySQL Database Server in "System Profile" (see the below picture).

You also need to install MySQL Database Server and set a configuration file path for my.ini. Now at last test the connection (make sure MySQL service is running in services.msc).

enter image description here

Write a file in external storage in Android

To write into external storage in Lollipop+ devices we need:

  1. Add the following permission into Manifest:

           <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
  2. Request an approval from the user:

           public static final int REQUEST_WRITE_STORAGE = 112; 
           private requestPermission(Activity context) {
               boolean hasPermission = (ContextCompat.checkSelfPermission(context, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED);
               if (!hasPermission) {
                     new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
               } else {
                 // You are allowed to write external storage:
                 String path = Environment.getExternalStorageDirectory().getAbsolutePath() + "/new_folder";
                 File storageDir = new File(path);
                 if (!storageDir.exists() && !storageDir.mkdirs()) {
                   // This should never happen - log handled exception!
  3. Handle the user response inside Activity:

    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
         super.onRequestPermissionsResult(requestCode, permissions, grantResults);
         switch (requestCode)
          case Preferences.REQUEST_WRITE_STORAGE: {
             if (grantResults.length > 0 && grantResults[0] ==  PackageManager.PERMISSION_GRANTED) {
               Toast.makeText(this, "The app was allowed to write to your storage!", Toast.LENGTH_LONG).show();
               // Reload the activity with permission granted or use the features what required the permission
             } else {
               Toast.makeText(this, "The app was not allowed to write to your storage. Hence, it cannot function properly. Please consider granting it this permission", Toast.LENGTH_LONG).show();

UILabel - Wordwrap text

If you set numberOfLines to 0 (and the label to word wrap), the label will automatically wrap and use as many of lines as needed.

If you're editing a UILabel in IB, you can enter multiple lines of text by pressing option+return to get a line break - return alone will finish editing.

Python 3 Building an array of bytes

what about simply constructing your frame from a standard list ?

frame = bytes([0xA2,0x01,0x02,0x03,0x04])

the bytes() constructor can build a byte frame from an iterable containing int values. an iterable is anything which implements the iterator protocol: an list, an iterator, an iterable object like what is returned by range()...

Java Try and Catch IOException Problem

The reason you are getting the the IOException is because you are not catching the IOException of your countLines method. You'll want to do something like this:

public static void main(String[] args) {
  int lines = 0;  

  // TODO - Need to get the filename to populate sFileName.  Could
  // come from the command line arguments.

   try {
       lines = LineCounter.countLines(sFileName);
    catch(IOException ex){
        System.out.println (ex.toString());
        System.out.println("Could not find file " + sFileName);

   if(lines > 0) {
     // Do rest of program.

Using PowerShell credentials without being prompted for a password

I saw one example that uses Import/Export-CLIXML.

These are my favorite commands for the issue you're trying to resolve. And the simplest way to use them is.

$passwordPath = './password.txt'
if (-not (test-path $passwordPath)) {
    $cred = Get-Credential -Username domain\username -message 'Please login.'
    Export-CliXML -InputObject $cred -Path $passwordPath
$cred = Import-CliXML -path $passwordPath

So if the file doesn't locally exist it will prompt for the credentials and store them. This will take a [pscredential] object without issue and will hide the credentials as a secure string.

Finally just use the credential like you normally do.

Restart-Computer -ComputerName ... -Credentail $cred

Note on Securty:

Securely store credentials on disk

When reading the Solution, you might at first be wary of storing a password on disk. While it is natural (and prudent) to be cautious of littering your hard drive with sensitive information, the Export-CliXml cmdlet encrypts credential objects using the Windows standard Data Protection API. This ensures that only your user account can properly decrypt its contents. Similarly, the ConvertFrom-SecureString cmdlet also encrypts the password you provide.

Edit: Just reread the original question. The above will work so long as you've initialized the [pscredential] to the hard disk. That is if you drop that in your script and run the script once it will create that file and then running the script unattended will be simple.

How long do browsers cache HTTP 301s?

In the absense of cache control directives that specify otherwise, a 301 redirect defaults to being cached without any expiry date.

That is, it will remain cached for as long as the browser's cache can accommodate it. It will be removed from the cache if you manually clear the cache, or if the cache entries are purged to make room for new ones.

You can verify this at least in Firefox by going to about:cache and finding it under disk cache. It works this way in other browsers including Chrome and the Chromium based Edge, though they don't have an about:cache for inspecting the cache.

In all browsers it is still possible to override this default behavior using caching directives, as described below:

If you don't want the redirect to be cached

This indefinite caching is only the default caching by these browsers in the absence of headers that specify otherwise. The logic is that you are specifying a "permanent" redirect and not giving them any other caching instructions, so they'll treat it as if you wanted it indefinitely cached.

The browsers still honor the Cache-Control and Expires headers like with any other response, if they are specified.

You can add headers such as Cache-Control: max-age=3600 or Expires: Thu, 01 Dec 2014 16:00:00 GMT to your 301 redirects. You could even add Cache-Control: no-cache so it won't be cached permanently by the browser or Cache-Control: no-store so it can't even be stored in temporary storage by the browser.

Though, if you don't want your redirect to be permanent, it may be a better option to use a 302 or 307 redirect. Issuing a 301 redirect but marking it as non-cacheable is going against the spirit of what a 301 redirect is for, even though it is technically valid. YMMV, and you may find edge cases where it makes sense for a "permanent" redirect to have a time limit. Note that 302 and 307 redirects aren't cached by default by browsers.

If you previously issued a 301 redirect but want to un-do that

If people still have the cached 301 redirect in their browser they will continue to be taken to the target page regardless of whether the source page still has the redirect in place. Your options for fixing this include:

  • A simple solution is to issue another redirect back again.

    If the browser is directed back to a same URL a second time during a redirect, it should fetch it from the origin again instead of redirecting again from cache, in an attempt to avoid a redirect loop. Comments on this answer indicate this now works in all major browsers - but there may be some minor browsers where it doesn't.

  • If you don't have control over the site where the previous redirect target went to, then you are out of luck. Try and beg the site owner to redirect back to you.

Prevention is better than cure - avoid a 301 redirect if you are not sure you want to permanently de-commission the old URL.

How to format a duration in java? (e.g format H:MM:SS)

in scala, no library needed:

def prettyDuration(str:List[String],seconds:Long):List[String]={
  seconds match {
    case t if t < 60 => str:::List(s"${t} seconds")
    case t if (t >= 60 && t< 3600 ) => List(s"${t / 60} minutes"):::prettyDuration(str, t%60)
    case t if (t >= 3600 && t< 3600*24 ) => List(s"${t / 3600} hours"):::prettyDuration(str, t%3600)
    case t if (t>= 3600*24 ) => List(s"${t / (3600*24)} days"):::prettyDuration(str, t%(3600*24))
val dur = prettyDuration(List.empty[String], 12345).mkString("")

Changing password with Oracle SQL Developer

The built-in reset password option may not work for user. In this case the password can be reset using following SQL statement:

ALTER user "user" identified by "NewPassword" replace "OldPassword";

Setting table column width

<table style="width: 100%">_x000D_
       <col span="1" style="width: 15%;">_x000D_
       <col span="1" style="width: 70%;">_x000D_
       <col span="1" style="width: 15%;">_x000D_
    <!-- Put <thead>, <tbody>, and <tr>'s here! -->_x000D_
            <td style="background-color: #777">15%</td>_x000D_
            <td style="background-color: #aaa">70%</td>_x000D_
            <td style="background-color: #777">15%</td>_x000D_

Webfont Smoothing and Antialiasing in Firefox and Opera

Case: Light text with jaggy web font on dark background Firefox (v35)/Windows
Example: Google Web Font Ruda

Surprising solution -
adding following property to the applied selectors:

selector {
    text-shadow: 0 0 0;

Actually, result is the same just with text-shadow: 0 0;, but I like to explicitly set blur-radius.

It's not an universal solution, but might help in some cases. Moreover I haven't experienced (also not thoroughly tested) negative performance impacts of this solution so far.

Convert NaN to 0 in javascript

Methods that use isNaN do not work if you're trying to use parseInt, for example:

parseInt("abc"); // NaN
parseInt(""); // NaN
parseInt("14px"); // 14

But in the second case isNaN produces false (i.e. the null string is a number)

n="abc"; isNaN(n) ? 0 : parseInt(n); // 0
n=""; isNaN(n) ? 0: parseInt(n); // NaN
n="14px"; isNaN(n) ? 0 : parseInt(n); // 14

In summary, the null string is considered a valid number by isNaN but not by parseInt. Verified with Safari, Firefox and Chrome on OSX Mojave.

Fastest way to iterate over all the chars in a String

This is just micro-optimisation that you shouldn't worry about.

char[] chars = str.toCharArray();

returns you a copy of str character arrays (in JDK, it returns a copy of characters by calling System.arrayCopy).

Other than that, str.charAt() only checks if the index is indeed in bounds and returns a character within the array index.

The first one doesn't create additional memory in JVM.

httpd-xampp.conf: How to allow access to an external IP besides localhost?

<LocationMatch "^/(?i:(?:xampp|licenses|phpmyadmin|webalizer|server-status|server-info))">
Order deny,allow
Deny from all
Allow from all
Allow from ::1 
ErrorDocument 403 /error/HTTP_XAMPP_FORBIDDEN.html.var

add to txt file > httpd-xampp.conf

C++ inheritance - inaccessible base?

By default, inheritance is private. You have to explicitly use public:

class Bar : public Foo

Linq to Entities - SQL "IN" clause

Real example:

var trackList = Model.TrackingHistory.GroupBy(x => x.ShipmentStatusId).Select(x => x.Last()).Reverse();
List<int> done_step1 = new List<int>() {2,3,4,5,6,7,8,9,10,11,14,18,21,22,23,24,25,26 };
bool isExists = trackList.Where(x => done_step1.Contains(x.ShipmentStatusId.Value)).FirstOrDefault() != null;

How can I get the line number which threw exception?

Working for me:

var st = new StackTrace(e, true);

// Get the bottom stack frame
var frame = st.GetFrame(st.FrameCount - 1);
// Get the line number from the stack frame
var line = frame.GetFileLineNumber();
var method = frame.GetMethod().ReflectedType.FullName;
var path = frame.GetFileName();

Unresponsive KeyListener for JFrame

You must add your keyListener to every component that you need. Only the component with the focus will send these events. For instance, if you have only one TextBox in your JFrame, that TextBox has the focus. So you must add a KeyListener to this component as well.

The process is the same:

myComponent.addKeyListener(new KeyListener ...);

Note: Some components aren't focusable like JLabel.

For setting them to focusable you need to:


Merging two arrays in .NET

In C# 3.0 you can use LINQ's Concat method to accomplish this easily:

int[] front = { 1, 2, 3, 4 };
int[] back = { 5, 6, 7, 8 };
int[] combined = front.Concat(back).ToArray();

In C# 2.0 you don't have such a direct way, but Array.Copy is probably the best solution:

int[] front = { 1, 2, 3, 4 };
int[] back = { 5, 6, 7, 8 };

int[] combined = new int[front.Length + back.Length];
Array.Copy(front, combined, front.Length);
Array.Copy(back, 0, combined, front.Length, back.Length);

This could easily be used to implement your own version of Concat.

Git Bash: Could not open a connection to your authentication agent

above solution doesn't work for me for unknown reason. below is my workaround which was worked successfully.

1) DO NOT generate a new ssh key by using command ssh-keygen -t rsa -C"[email protected]", you can delete existing SSH keys.

2) but use Git GUI, -> "Help" -> "Show ssh key" -> "Generate key", the key will saved to ssh automatically and no need to use ssh-add anymore.

Regex pattern for numeric values


I'd just use "[0-9]+" to represent positive whole numbers.

Angular checkbox and ng-click

The order of execution of ng-click and ng-model is ambiguous since they do not define clear priorities. Instead you should use ng-change or a $watch on the $scope to ensure that you obtain the correct values of the model variable.

In your case, this should work:

<input type="checkbox" ng-model="vm.myChkModel" ng-change="vm.myClick(vm.myChkModel)">

Format Instant to String


This saves you from having to convert to UTC. However, some other language's time frameworks may not support the milliseconds so you should do


How do I remove all null and empty string values from an object?

You're deleting sjonObj.key, literally. You need to use array access notation:

delete sjonObj[key];

However, that will also delete where value is equal to 0, since you're not using strict comparison. Use === instead:

$.each(sjonObj, function(key, value){
    if (value === "" || value === null){
        delete sjonObj[key];

However, this will only walk the object shallowly. To do it deeply, you can use recursion:

(function filter(obj) {
    $.each(obj, function(key, value){
        if (value === "" || value === null){
            delete obj[key];
        } else if ( === '[object Object]') {
        } else if ($.isArray(value)) {
            $.each(value, function (k,v) { filter(v); });

var sjonObj = {_x000D_
  "executionMode": "SEQUENTIAL",_x000D_
  "coreTEEVersion": "",_x000D_
  "testSuiteId": "yyy",_x000D_
  "testSuiteFormatVersion": "",_x000D_
  "testStatus": "IDLE",_x000D_
  "reportPath": "",_x000D_
  "startTime": 0,_x000D_
  "durationBetweenTestCases": 20,_x000D_
  "endTime": 0,_x000D_
  "lastExecutedTestCaseId": 0,_x000D_
  "repeatCount": 0,_x000D_
  "retryCount": 0,_x000D_
  "fixedTimeSyncSupported": false,_x000D_
  "totalRepeatCount": 0,_x000D_
  "totalRetryCount": 0,_x000D_
  "summaryReportRequired": "true",_x000D_
  "postConditionExecution": "ON_SUCCESS",_x000D_
  "testCaseList": [_x000D_
      "executionMode": "SEQUENTIAL",_x000D_
      "commandList": [_x000D_
      "testCaseList": [_x000D_
      "testStatus": "IDLE",_x000D_
      "boundTimeDurationForExecution": 0,_x000D_
      "startTime": 0,_x000D_
      "endTime": 0,_x000D_
      "label": null,_x000D_
      "repeatCount": 0,_x000D_
      "retryCount": 0,_x000D_
      "totalRepeatCount": 0,_x000D_
      "totalRetryCount": 0,_x000D_
      "testCaseId": "a",_x000D_
      "summaryReportRequired": "false",_x000D_
      "postConditionExecution": "ON_SUCCESS"_x000D_
      "executionMode": "SEQUENTIAL",_x000D_
      "commandList": [_x000D_
      "testCaseList": [_x000D_
          "executionMode": "SEQUENTIAL",_x000D_
          "commandList": [_x000D_
              "commandParameters": {_x000D_
                "serverAddress": "",_x000D_
                "echoRequestCount": "",_x000D_
                "sendPacketSize": "",_x000D_
                "interval": "",_x000D_
                "ttl": "",_x000D_
                "addFullDataInReport": "True",_x000D_
                "maxRTT": "",_x000D_
                "failOnTargetHostUnreachable": "True",_x000D_
                "failOnTargetHostUnreachableCount": "",_x000D_
                "initialDelay": "",_x000D_
                "commandTimeout": "",_x000D_
                "testDuration": ""_x000D_
              "commandName": "Ping",_x000D_
              "testStatus": "IDLE",_x000D_
              "label": "",_x000D_
              "reportFileName": "tc_2-tc_1-cmd_1_Ping",_x000D_
              "endTime": 0,_x000D_
              "startTime": 0,_x000D_
              "repeatCount": 0,_x000D_
              "retryCount": 0,_x000D_
              "totalRepeatCount": 0,_x000D_
              "totalRetryCount": 0,_x000D_
              "postConditionExecution": "ON_SUCCESS",_x000D_
              "detailReportRequired": "true",_x000D_
              "summaryReportRequired": "true"_x000D_
          "testCaseList": [_x000D_
          "testStatus": "IDLE",_x000D_
          "boundTimeDurationForExecution": 0,_x000D_
          "startTime": 0,_x000D_
          "endTime": 0,_x000D_
          "label": null,_x000D_
          "repeatCount": 0,_x000D_
          "retryCount": 0,_x000D_
          "totalRepeatCount": 0,_x000D_
          "totalRetryCount": 0,_x000D_
          "testCaseId": "dd",_x000D_
          "summaryReportRequired": "false",_x000D_
          "postConditionExecution": "ON_SUCCESS"_x000D_
      "testStatus": "IDLE",_x000D_
      "boundTimeDurationForExecution": 0,_x000D_
      "startTime": 0,_x000D_
      "endTime": 0,_x000D_
      "label": null,_x000D_
      "repeatCount": 0,_x000D_
      "retryCount": 0,_x000D_
      "totalRepeatCount": 0,_x000D_
      "totalRetryCount": 0,_x000D_
      "testCaseId": "b",_x000D_
      "summaryReportRequired": "false",_x000D_
      "postConditionExecution": "ON_SUCCESS"_x000D_
(function filter(obj) {_x000D_
    $.each(obj, function(key, value){_x000D_
        if (value === "" || value === null){_x000D_
            delete obj[key];_x000D_
        } else if ( === '[object Object]') {_x000D_
        } else if (Array.isArray(value)) {_x000D_
            value.forEach(function (el) { filter(el); });_x000D_
<script src=""></script>

Note that if you're willing to use a library like lodash/underscore.js, you can use _.pick instead. However, you will still need to use recursion to filter deeply, since neither library provides a deep filter function.

sjonObj = (function filter(obj) {
    var filtered = _.pick(obj, function (v) { return v !== '' && v !== null; });
    return _.cloneDeep(filtered, function (v) { return v !== filtered && _.isPlainObject(v) ? filter(v) : undefined; });

This variant has the added advantage of leaving the original object unmodified, but it does create an entirely new copy, which would be less efficient if you don't need the original object.

var sjonObj = {_x000D_
  "executionMode": "SEQUENTIAL",_x000D_
  "coreTEEVersion": "",_x000D_
  "testSuiteId": "yyy",_x000D_
  "testSuiteFormatVersion": "",_x000D_
  "testStatus": "IDLE",_x000D_
  "reportPath": "",_x000D_
  "startTime": 0,_x000D_
  "durationBetweenTestCases": 20,_x000D_
  "endTime": 0,_x000D_
  "lastExecutedTestCaseId": 0,_x000D_
  "repeatCount": 0,_x000D_
  "retryCount": 0,_x000D_
  "fixedTimeSyncSupported": false,_x000D_
  "totalRepeatCount": 0,_x000D_
  "totalRetryCount": 0,_x000D_
  "summaryReportRequired": "true",_x000D_
  "postConditionExecution": "ON_SUCCESS",_x000D_
  "testCaseList": [_x000D_
      "executionMode": "SEQUENTIAL",_x000D_
      "commandList": [_x000D_
      "testCaseList": [_x000D_
      "testStatus": "IDLE",_x000D_
      "boundTimeDurationForExecution": 0,_x000D_
      "startTime": 0,_x000D_
      "endTime": 0,_x000D_
      "label": null,_x000D_
      "repeatCount": 0,_x000D_
      "retryCount": 0,_x000D_
      "totalRepeatCount": 0,_x000D_
      "totalRetryCount": 0,_x000D_
      "testCaseId": "a",_x000D_
      "summaryReportRequired": "false",_x000D_
      "postConditionExecution": "ON_SUCCESS"_x000D_
      "executionMode": "SEQUENTIAL",_x000D_
      "commandList": [_x000D_
      "testCaseList": [_x000D_
          "executionMode": "SEQUENTIAL",_x000D_
          "commandList": [_x000D_
              "commandParameters": {_x000D_
                "serverAddress": "",_x000D_
                "echoRequestCount": "",_x000D_
                "sendPacketSize": "",_x000D_
                "interval": "",_x000D_
                "ttl": "",_x000D_
                "addFullDataInReport": "True",_x000D_
                "maxRTT": "",_x000D_
                "failOnTargetHostUnreachable": "True",_x000D_
                "failOnTargetHostUnreachableCount": "",_x000D_
                "initialDelay": "",_x000D_
                "commandTimeout": "",_x000D_
                "testDuration": ""_x000D_
              "commandName": "Ping",_x000D_
              "testStatus": "IDLE",_x000D_
              "label": "",_x000D_
              "reportFileName": "tc_2-tc_1-cmd_1_Ping",_x000D_
              "endTime": 0,_x000D_
              "startTime": 0,_x000D_
              "repeatCount": 0,_x000D_
              "retryCount": 0,_x000D_
              "totalRepeatCount": 0,_x000D_
              "totalRetryCount": 0,_x000D_
              "postConditionExecution": "ON_SUCCESS",_x000D_
              "detailReportRequired": "true",_x000D_
              "summaryReportRequired": "true"_x000D_
          "testCaseList": [_x000D_
          "testStatus": "IDLE",_x000D_
          "boundTimeDurationForExecution": 0,_x000D_
          "startTime": 0,_x000D_
          "endTime": 0,_x000D_
          "label": null,_x000D_
          "repeatCount": 0,_x000D_
          "retryCount": 0,_x000D_
          "totalRepeatCount": 0,_x000D_
          "totalRetryCount": 0,_x000D_
          "testCaseId": "dd",_x000D_
          "summaryReportRequired": "false",_x000D_
          "postConditionExecution": "ON_SUCCESS"_x000D_
      "testStatus": "IDLE",_x000D_
      "boundTimeDurationForExecution": 0,_x000D_
      "startTime": 0,_x000D_
      "endTime": 0,_x000D_
      "label": null,_x000D_
      "repeatCount": 0,_x000D_
      "retryCount": 0,_x000D_
      "totalRepeatCount": 0,_x000D_
      "totalRetryCount": 0,_x000D_
      "testCaseId": "b",_x000D_
      "summaryReportRequired": "false",_x000D_
      "postConditionExecution": "ON_SUCCESS"_x000D_
sjonObj = (function filter(obj) {_x000D_
    var filtered = _.pick(obj, function (v) { return v !== '' && v !== null; });_x000D_
    return _.cloneDeep(filtered, function (v) { return v !== filtered && _.isPlainObject(v) ? filter(v) : undefined; });_x000D_
<script src="//"></script>

PHP errors NOT being displayed in the browser [Ubuntu 10.10]

  1. First you need to find the path to the php.ini file
  2. You will find the file in the specified path /etc/php/7.0/apache2/. If you are changing the values in the CLI folder or the CGI folder it will not work.
  3. Make the following changes

display_errors = On

  1. Restart you apache server

/etc/init.d/apache2 restart

Android findViewById() in Custom View

public View getView(int position, View convertView, ViewGroup parent) {
    View row = convertView;
    ImageHolder holder = null;
    if (row == null) {
        LayoutInflater inflater = ((Activity) context).getLayoutInflater();
        row = inflater.inflate(layoutResourceId, parent, false);
        holder = new ImageHolder();
        editText = (EditText) row.findViewById(;
        loadButton = (ImageButton) row.findViewById(;
    } else {
        holder = (ImageHolder) row.getTag();

    holder.editText.setText("Your Value");
    holder.loadButton.setImageBitmap("Your Bitmap Value");
    return row;

How to create a notification with NotificationCompat.Builder?

The NotificationCompat.Builder is the most easy way to create Notifications on all Android versions. You can even use features that are available with Android 4.1. If your app runs on devices with Android >=4.1 the new features will be used, if run on Android <4.1 the notification will be an simple old notification.

To create a simple Notification just do (see Android API Guide on Notifications):

NotificationCompat.Builder mBuilder =
    new NotificationCompat.Builder(this)
    .setContentTitle("My notification")
    .setContentText("Hello World!")
    .setContentIntent(pendingIntent); //Required on Gingerbread and below

You have to set at least smallIcon, contentTitle and contentText. If you miss one the Notification will not show.

Beware: On Gingerbread and below you have to set the content intent, otherwise a IllegalArgumentException will be thrown.

To create an intent that does nothing, use:

final Intent emptyIntent = new Intent();
PendingIntent pendingIntent = PendingIntent.getActivity(ctx, NOT_USED, emptyIntent, PendingIntent.FLAG_UPDATE_CURRENT);

You can add sound through the builder, i.e. a sound from the RingtoneManager:


The Notification is added to the bar through the NotificationManager:

NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

Word wrapping in phpstorm

You may also want to consider the Wrap to Column plugin, which implements the equivalent to Alt-q in Emacs and gq in vim. This may be preferable to having very long lines that are wrapped by the editor.

This plugin can be installed from any IDEA-based IDE by searching for Wrap to Column.

It has the additional benefit that you can choose to wrap only sections of text that you want :-)

Python timedelta in years

If you're trying to check if someone is 18 years of age, using timedelta will not work correctly on some edge cases because of leap years. For example, someone born on January 1, 2000, will turn 18 exactly 6575 days later on January 1, 2018 (5 leap years included), but someone born on January 1, 2001, will turn 18 exactly 6574 days later on January 1, 2019 (4 leap years included). Thus, you if someone is exactly 6574 days old, you can't determine if they are 17 or 18 without knowing a little more information about their birthdate.

The correct way to do this is to calculate the age directly from the dates, by subtracting the two years, and then subtracting one if the current month/day precedes the birth month/day.

Append an empty row in dataframe using pandas

You can add a new series, and name it at the same time. The name will be the index of the new row, and all the values will automatically be NaN.


How to Lock the data in a cell in excel using vba

You can also do it on the worksheet level captured in the worksheet's change event. If that suites your needs better. Allows for dynamic locking based on values, criteria, ect...

Private Sub Worksheet_Change(ByVal Target As Range)

    'set your criteria here
    If Target.Column = 1 Then

        'must disable events if you change the sheet as it will
        'continually trigger the change event
        Application.EnableEvents = False
        Application.EnableEvents = True

        MsgBox "You cannot do that!"
    End If
End Sub

jQuery: how to find first visible input/select/textarea excluding buttons?

This is an improvement over @Mottie's answer because as of jQuery 1.5.2 :text selects input elements that have no specified type attribute (in which case type="text" is implied):


Peak-finding algorithm for Python/SciPy

First things first, the definition of "peak" is vague if without further specifications. For example, for the following series, would you call 5-4-5 one peak or two?


In this case, you'll need at least two thresholds: 1) a high threshold only above which can an extreme value register as a peak; and 2) a low threshold so that extreme values separated by small values below it will become two peaks.

Peak detection is a well-studied topic in Extreme Value Theory literature, also known as "declustering of extreme values". Its typical applications include identifying hazard events based on continuous readings of environmental variables e.g. analysing wind speed to detect storm events.

C++ Fatal Error LNK1120: 1 unresolved externals

From msdn

When you created the project, you made the wrong choice of application type. When asked whether your project was a console application or a windows application or a DLL or a static library, you made the wrong chose windows application (wrong choice).

Go back, start over again, go to File -> New -> Project -> Win32 Console Application -> name your app -> click next -> click application settings.

For the application type, make sure Console Application is selected (this step is the vital step).

The main for a windows application is called WinMain, for a DLL is called DllMain, for a .NET application is called Main(cli::array ^), and a static library doesn't have a main. Only in a console app is main called main

How do I convert a Swift Array to a String?

Nowadays, in iOS 13+ and macOS 10.15+, we might use ListFormatter:

let formatter = ListFormatter()

let names = ["Moe", "Larry", "Curly"]
if let string = formatter.string(from: names) {

That will produce a nice, natural language string representation of the list. A US user will see:

Moe, Larry, and Curly

It will support any languages for which (a) your app has been localized; and (b) the user’s device is configured. For example, a German user with an app supporting German localization, would see:

Moe, Larry und Curly

How to make CSS3 rounded corners hide overflow in Chrome/Opera

opacity: 0.99; on wrapper solve webkit bug

How can I stop float left?

A standard approach is to add a clearing div between the two floating block level elements:

<div style="clear:both;"></div>

What is a None value?

The book you refer to is clearly trying to greatly simplify the meaning of None. Python variables don't have an initial, empty state – Python variables are bound (only) when they're defined. You can't create a Python variable without giving it a value.

>>> print(x)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'x' is not defined
>>> def test(x):
...   print(x)
>>> test()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: test() takes exactly 1 argument (0 given)
>>> def test():
...   print(x)
>>> test()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 2, in test
NameError: global name 'x' is not defined

but sometimes you want to make a function mean different things depending on whether a variable is defined or not. You can create an argument with a default value of None:

>>> def test(x=None):
...   if x is None:
...     print('no x here')
...   else:
...     print(x)
>>> test()
no x here
>>> test('x!')

The fact that this value is the special None value is not terribly important in this case. I could've used any default value:

>>> def test(x=-1):
...   if x == -1:
...     print('no x here')
...   else:
...     print(x)
>>> test()
no x here
>>> test('x!')

…but having None around gives us two benefits:

  1. We don't have to pick a special value like -1 whose meaning is unclear, and
  2. Our function may actually need to handle -1 as a normal input.
>>> test(-1)
no x here


So the book is a little misleading mostly in its use of the word reset – assigning None to a name is a signal to a programmer that that value isn't being used or that the function should behave in some default way, but to reset a value to its original, undefined state you must use the del keyword:

>>> x = 3
>>> x
>>> del x
>>> x
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'x' is not defined

What is the difference between __str__ and __repr__?

One aspect that is missing in other answers. It's true that in general the pattern is:

  • Goal of __str__: human-readable
  • Goal of __repr__: unambiguous, possibly machine-readable via eval

Unfortunately, this differentiation is flawed, because the Python REPL and also IPython use __repr__ for printing objects in a REPL console (see related questions for Python and IPython). Thus, projects which are targeted for interactive console work (e.g., Numpy or Pandas) have started to ignore above rules and provide a human-readable __repr__ implementation instead.

Align text to the bottom of a div

Flex Solution

It is perfectly fine if you want to go with the display: table-cell solution. But instead of hacking it out, we have a better way to accomplish the same using display: flex;. flex is something which has a decent support.

.wrap {_x000D_
  height: 200px;_x000D_
  width: 200px;_x000D_
  border: 1px solid #aaa;_x000D_
  margin: 10px;_x000D_
  display: flex;_x000D_
.wrap span {_x000D_
  align-self: flex-end;_x000D_
<div class="wrap">_x000D_
  <span>Align me to the bottom</span>_x000D_

In the above example, we first set the parent element to display: flex; and later, we use align-self to flex-end. This helps you push the item to the end of the flex parent.

Old Solution (Valid if you are not willing to use flex)

If you want to align the text to the bottom, you don't have to write so many properties for that, using display: table-cell; with vertical-align: bottom; is enough

div {_x000D_
  display: table-cell;_x000D_
  vertical-align: bottom;_x000D_
  border: 1px solid #f00;_x000D_
  height: 100px;_x000D_
  width: 100px;_x000D_

(Or JSFiddle)

Mockito: List Matchers with generics

Before Java 8 (versions 7 or 6) I use the new method ArgumentMatchers.anyList:

import static org.mockito.Mockito.*;
import org.mockito.ArgumentMatchers;

verify(mock, atLeastOnce()).process(ArgumentMatchers.<Bar>anyList());

Spark difference between reduceByKey vs groupByKey vs aggregateByKey vs combineByKey



                    .flatMap(line => line.split(" ") )
                    .map(word => (word,1))
                    .map((x,y) => (x,sum(y)))

groupByKey can cause out of disk problems as data is sent over the network and collected on the reduce workers.



                    .flatMap(line => line.split(" "))
                    .map(word => (word,1))
                    .reduceByKey((x,y)=> (x+y))

Data are combined at each partition, only one output for one key at each partition to send over the network. reduceByKey required combining all your values into another value with the exact same type.


same as reduceByKey, which takes an initial value.

3 parameters as input i. initial value ii. Combiner logic iii. sequence op logic


val keysWithValuesList = Array("foo=A", "foo=A", "foo=A", "foo=A", "foo=B", "bar=C", "bar=D", "bar=D")
    val data = sc.parallelize(keysWithValuesList)
    //Create key value pairs
    val kv ="=")).map(v => (v(0), v(1))).cache()
    val initialCount = 0;
    val addToCounts = (n: Int, v: String) => n + 1
    val sumPartitionCounts = (p1: Int, p2: Int) => p1 + p2
    val countByKey = kv.aggregateByKey(initialCount)(addToCounts, sumPartitionCounts)

ouput: Aggregate By Key sum Results bar -> 3 foo -> 5


3 parameters as input

  1. Initial value: unlike aggregateByKey, need not pass constant always, we can pass a function that will return a new value.
  2. merging function
  3. combine function


val result = rdd.combineByKey(
                        (v) => (v,1),
                        ( (acc:(Int,Int),v) => acc._1 +v , acc._2 +1 ) ,
                        ( acc1:(Int,Int),acc2:(Int,Int) => (acc1._1+acc2._1) , (acc1._2+acc2._2)) 
                        ).map( { case (k,v) => (k,v._1/v._2.toDouble) })

reduceByKey,aggregateByKey,combineByKey preferred over groupByKey

Reference: Avoid groupByKey

BigDecimal setScale and round

One important point that is alluded to but not directly addressed is the difference between "precision" and "scale" and how they are used in the two statements. "precision" is the total number of significant digits in a number. "scale" is the number of digits to the right of the decimal point.

The MathContext constructor only accepts precision and RoundingMode as arguments, and therefore scale is never specified in the first statement.

setScale() obviously accepts scale as an argument, as well as RoundingMode, however precision is never specified in the second statement.

If you move the decimal point one place to the right, the difference will become clear:

// 1.
new BigDecimal("35.3456").round(new MathContext(4, RoundingMode.HALF_UP));
//result = 35.35
// 2.
new BigDecimal("35.3456").setScale(4, RoundingMode.HALF_UP);
// result = 35.3456

Check if table exists

I don't actually find any of the presented solutions here to be fully complete so I'll add my own. Nothing new here. You can stitch this together from the other presented solutions plus various comments.

There are at least two things you'll have to make sure:

  1. Make sure you pass the table name to the getTables() method, rather than passing a null value. In the first case you let the database server filter the result for you, in the second you request a list of all tables from the server and then filter the list locally. The former is much faster if you are only searching for a single table.

  2. Make sure to check the table name from the resultset with an equals match. The reason is that the getTables() does pattern matching on the query for the table and the _ character is a wildcard in SQL. Suppose you are checking for the existence of a table named EMPLOYEE_SALARY. You'll then get a match on EMPLOYEESSALARY too which is not what you want.

Ohh, and do remember to close those resultsets. Since Java 7 you would want to use a try-with-resources statement for that.

Here's a complete solution:

public static boolean tableExist(Connection conn, String tableName) throws SQLException {
    boolean tExists = false;
    try (ResultSet rs = conn.getMetaData().getTables(null, null, tableName, null)) {
        while ( { 
            String tName = rs.getString("TABLE_NAME");
            if (tName != null && tName.equals(tableName)) {
                tExists = true;
    return tExists;

You may want to consider what you pass as the types parameter (4th parameter) on your getTables() call. Normally I would just leave at null because you don't want to restrict yourself. A VIEW is as good as a TABLE, right? These days many databases allow you to update through a VIEW so restricting yourself to only TABLE type is in most cases not the way to go. YMMV.

How do I force Internet Explorer to render in Standards Mode and NOT in Quirks?

  1. Using html5 doctype at the beginning of the page.

    <!DOCTYPE html>

  2. Force IE to use the latest render mode

    <meta http-equiv="X-UA-Compatible" content="IE=edge">

  3. If your target browser is ie8, then check your compatible settings in IE8

I blog this in details

SSH library for Java

Take a look at the very recently released SSHD, which is based on the Apache MINA project.

Missing Authentication Token while accessing API Gateway?

I've lost some time for a silly reason:

When you create a stage, the link displayed does not contain the resource part of the URL:



The /get-list was missing

And of course, you need to check that the method configuration looks like this:

enter image description here

batch file to check 64bit or 32bit OS

set "_os=64"
if "%PROCESSOR_ARCHITECTURE%"=="x86" (if not defined PROCESSOR_ARCHITEW6432 set "_os=32")

Based on:


Automatically open default email client and pre-populate content

Try this: It will open the default mail directly.

<a href="mailto:[email protected]"><img src="ICON2.png"></a>

How do I list all the files in a directory and subdirectories in reverse chronological order?

Try this one:

find . -type f -printf "%T@ %p\n" | sort -nr | cut -d\  -f2-

Integer expression expected error in shell script

If you are just comparing numbers, I think there's no need to change syntax, just correct those lines, lines 6 and 9 brackets.

Line 6 before: if [ "$age" -le "7"] -o [ "$age" -ge " 65" ]

After: if [ "$age" -le "7" -o "$age" -ge "65" ]

Line 9 before: elif [ "$age" -gt "7"] -a [ "$age" -lt "65"]

After: elif [ "$age" -gt "7" -a "$age" -lt "65" ]

warning: implicit declaration of function

The right way is to declare function prototype in header.



#ifndef MAIN_H
#define MAIN_H

int some_main(const char *name);



#include "main.h"

int main()
    some_main("Hello, World\n");

int some_main(const char *name)
    printf("%s", name);

Alternative with one file (main.c)

static int some_main(const char *name);

int some_main(const char *name)
    // do something

Using setDate in PreparedStatement

The docs explicitly says that java.sql.Date will throw:

  • IllegalArgumentException - if the date given is not in the JDBC date escape format (yyyy-[m]m-[d]d)

Also you shouldn't need to convert a date to a String then to a, this seems superfluous (and bug-prone!). Instead you could:

java.sql.Date sqlDate := new java.sql.Date(now.getTime());
prs.setDate(2, sqlDate);
prs.setDate(3, sqlDate);

How to use a dot "." to access members of dictionary?

I like the Munch and it gives lot of handy options on top of dot access.

import munch

temp_1 = {'person': { 'fname': 'senthil', 'lname': 'ramalingam'}}

dict_munch = munch.munchify(temp_1)


Tomcat base URL redirection

Name your webapp WAR “ROOT.war” or containing folder “ROOT”

What does --net=host option in Docker command really do?

After the docker installation you have 3 networks by default:

docker network ls
NETWORK ID          NAME                DRIVER              SCOPE
f3be8b1ef7ce        bridge              bridge              local
fbff927877c1        host                host                local
023bb5940080        none                null                local

I'm trying to keep this simple. So if you start a container by default it will be created inside the bridge (docker0) network.

$ docker run -d jenkins
1498e581cdba        jenkins             "/bin/tini -- /usr..."   3 minutes ago       Up 3 minutes        8080/tcp, 50000/tcp   friendly_bell

In the dockerfile of jenkins the ports 8080 and 50000 are exposed. Those ports are opened for the container on its bridge network. So everything inside that bridge network can access the container on port 8080 and 50000. Everything in the bridge network is in the private range of "Subnet": "", If you want to access them from the outside you have to map the ports with -p 8080:8080. This will map the port of your container to the port of your real server (the host network). So accessing your server on 8080 will route to your bridgenetwork on port 8080.

Now you also have your host network. Which does not containerize the containers networking. So if you start a container in the host network it will look like this (it's the first one):

CONTAINER ID        IMAGE               COMMAND                  CREATED             STATUS              PORTS                 NAMES
1efd834949b2        jenkins             "/bin/tini -- /usr..."   6 minutes ago       Up 6 minutes                              eloquent_panini
1498e581cdba        jenkins             "/bin/tini -- /usr..."   10 minutes ago      Up 10 minutes       8080/tcp, 50000/tcp   friendly_bell

The difference is with the ports. Your container is now inside your host network. So if you open port 8080 on your host you will acces the container immediately.

$ sudo iptables -I INPUT 5 -p tcp -m tcp --dport 8080 -j ACCEPT

I've opened port 8080 in my firewall and when I'm now accesing my server on port 8080 I'm accessing my jenkins. I think this blog is also useful to understand it better.

Jquery href click - how can I fire up an event?

You are binding the click event to anchors with an href attribute with value sign_new.

Either bind anchors with class sign_new or bind anchors with href value #sign_up. I would prefer the former.

How to refresh an access form

"Requery" is indeed what you what you want to run, but you could do that in Form A's "On Got Focus" event. If you have code in your Form_Load, perhaps you can move it to Form_Got_Focus.

Formatting PowerShell Get-Date inside string

Instead of using string interpolation you could simply format the DateTime using the ToString("u") method and concatenate that with the rest of the string:

$startTime = Get-Date
Write-Host "The script was started " + $startTime.ToString("u") 

SQL Developer is returning only the date, not the time. How do I fix this?

Can you try this?

Go to Tools> Preferences > Database > NLS and set the Date Format as MM/DD/YYYY HH24:MI:SS

Spark DataFrame TimestampType - how to get Year, Month, Day values from field?

Actually, we really do not need to import any python library. We can separate the year, month, date using simple SQL. See the below example,

|       _c0|

I have a date column in my data frame which contains the date, month and year and assume I want to extract only the year from the column.

sqlDF = spark.sql("SELECT EXTRACT(year from `_c0`) FROM res ")

Here I'm creating a temporary view and store the year values using this single line and the output will be,

|year(CAST(_c0 AS DATE))|
|                   1872|
|                   1873|
|                   1874|
|                   1875|
|                   1876|
|                   1876|
|                   1877|
|                   1877|
|                   1878|
|                   1878|
|                   1879|
|                   1879|
|                   1879|

Best way to detect when a user leaves a web page?

In the case you need to do some asynchronous code (like sending a message to the server that the user is not focused on your page right now), the event beforeunload will not give time to the async code to run. In the case of async I found that the visibilitychange and mouseleave events are the best options. These events fire when the user change tab, or hiding the browser, or taking the courser out of the window scope.

document.addEventListener('mouseleave', e=>{_x000D_
     //do some async code_x000D_
document.addEventListener('visibilitychange', e=>{_x000D_
     if (document.visibilityState === 'visible') {_x000D_
   //report that user is in focus_x000D_
    } else {_x000D_
     //report that user is out of focus_x000D_
    }  _x000D_

Can pandas automatically recognize dates?

You could use pandas.to_datetime() as recommended in the documentation for pandas.read_csv():

If a column or index contains an unparseable date, the entire column or index will be returned unaltered as an object data type. For non-standard datetime parsing, use pd.to_datetime after pd.read_csv.


>>> D = {'date': '2013-6-4'}
>>> df = pd.DataFrame(D, index=[0])
>>> df
0  2013-6-4
>>> df.dtypes
date    object
dtype: object
>>> df['date'] = pd.to_datetime(, format='%Y-%m-%d')
>>> df
0 2013-06-04
>>> df.dtypes
date    datetime64[ns]
dtype: object

Searching if value exists in a list of objects using Linq

Another possibility

if (list.Count(customer => customer.Firstname == "John") > 0) {

How to install a specific version of Node on Ubuntu?

FYI, according to this page in the wiki of the nodejs github repo, Chris Lea's PPA (mentioned in several other answers) has been superseded by the NodeSource distributions as the main way of installing nodejs from source in Ubuntu:

curl -sL | sudo bash -
sudo apt-get install -y nodejs

This is supported for the three latest (at the time of writing this) LTS versions of Ubuntu: 10.04 (lucid), 12.04 LTS (precise) and 14.04 (trusty).

I'm not sure this will help in installing an old version of nodejs, but I'm putting this here in case it helps others who needed to install a specific (newer) version of nodejs that isn't included in their distro's repositories.

How to set value in @Html.TextBoxFor in Razor syntax?

This works for me, in MVC5:

@Html.TextBoxFor(m => m.Name, new { @class = "form-control", id = "theID" , @Value="test" })

Comparing the contents of two files in Sublime Text

View - Layout and View - Groups will do in latest Sublime 3


Shift+Alt+2 --> creates 2 columns

Ctrl+2 --> move selected file to column 2

This is for side by side comparison. For actual diff, there is the diff function other already mentioned. Unfortunately, I can't find a way to make columns scroll at the same time, which would be a nice feature.

How to set up ES cluster?

It is usually handled automatically.

If autodiscovery doesn't work. Edit the elastic search config file, by enabling unicast discovery

Node 1: mycluster "node1"
    node.master: true true false [""]

Node 2: mycluster "node2"
    node.master: false true false [""]

and so on for node 3,4,5. Make node 1 master, and the rest only as data nodes.

Edit: Please note that by ES rule, if you have N nodes, then by convention, N/2+1 nodes should be masters for fail-over mechanisms They may or may not be data nodes, though.

Also, in case auto-discovery doesn't work, most probable reason is because the network doesn't allow it (and therefore disabled). If too many auto-discovery pings take place across multiple servers, the resources to manage those pings will prevent other services from running correctly.

For ex, think of a 10,000 node cluster and all 10,000 nodes doing the auto-pings.

The performance impact of using instanceof in Java

instanceof is probably going to be more costly than a simple equals in most real world implementations (that is, the ones where instanceof is really needed, and you can't just solve it by overriding a common method, like every beginner textbook as well as Demian above suggest).

Why is that? Because what is probably going to happen is that you have several interfaces, that provide some functionality (let's say, interfaces x, y and z), and some objects to manipulate that may (or not) implement one of those interfaces... but not directly. Say, for instance, I have:

w extends x

A implements w

B extends A

C extends B, implements y

D extends C, implements z

Suppose I am processing an instance of D, the object d. Computing (d instanceof x) requires to take d.getClass(), loop through the interfaces it implements to know whether one is == to x, and if not do so again recursively for all of their ancestors... In our case, if you do a breadth first exploration of that tree, yields at least 8 comparisons, supposing y and z don't extend anything...

The complexity of a real-world derivation tree is likely to be higher. In some cases, the JIT can optimize most of it away, if it is able to resolve in advance d as being, in all possible cases, an instance of something that extends x. Realistically, however, you are going to go through that tree traversal most of the time.

If that becomes an issue, I would suggest using a handler map instead, linking the concrete class of the object to a closure that does the handling. It removes the tree traversal phase in favor of a direct mapping. However, beware that if you have set a handler for C.class, my object d above will not be recognized.

here are my 2 cents, I hope they help...

Load Image from javascript

just click on image and will change:

 <img src="" id="imgLoad">_x000D_
<script type='text/javascript'>_x000D_
 var img = document.getElementById('imgLoad'); _x000D_
 img.onclick = function() { img.src = ""; }_x000D_

How to "EXPIRE" the "HSET" child key in redis?

You can. Here is an example.

redis> hset key f1 1
(integer) 1
redis> hset key f2 2
(integer) 1
redis> hvals key
1) "1"
2) "1"
3) "2"
redis> expire key 10
(integer) 1
redis> hvals key
1) "1"
2) "1"
3) "2"
redis> hvals key
1) "1"
2) "1"
3) "2"
redis> hvals key

Use EXPIRE or EXPIREAT command.

If you want to expire specific keys in the hash older then 1 month. This is not possible. Redis expire command is for all keys in the hash. If you set daily hash key, you can set a keys time to live.

hset key-20140325 f1 1
expire key-20140325 100
hset key-20140325 f1 2

Setting the correct encoding when piping stdout in Python

An arguable sanitized version of Craig McQueen's answer.

import sys, codecs
class EncodedOut:
    def __init__(self, enc):
        self.enc = enc
        self.stdout = sys.stdout
    def __enter__(self):
        if sys.stdout.encoding is None:
            w = codecs.getwriter(self.enc)
            sys.stdout = w(sys.stdout)
    def __exit__(self, exc_ty, exc_val, tb):
        sys.stdout = self.stdout


with EncodedOut('utf-8'):
    print u'ÅÄÖåäö'

Why should I use IHttpActionResult instead of HttpResponseMessage?

I'd rather implement TaskExecuteAsync interface function for IHttpActionResult. Something like:

    public Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken)
        var response = _request.CreateResponse(HttpStatusCode.InternalServerError, _respContent);

        switch ((Int32)_respContent.Code)
            case 1:
            case 6:
            case 7:
                response = _request.CreateResponse(HttpStatusCode.InternalServerError, _respContent);
            case 2:
            case 3:
            case 4:
                response = _request.CreateResponse(HttpStatusCode.BadRequest, _respContent);

        return Task.FromResult(response);

, where _request is the HttpRequest and _respContent is the payload.

I just discovered why all ASP.Net websites are slow, and I am trying to work out what to do about it

Unless your application has specially needs, I think you have 2 approaches:

  1. Do not use session at all
  2. Use session as is and perform fine tuning as joel mentioned.

Session is not only thread-safe but also state-safe, in a way that you know that until the current request is completed, every session variable wont change from another active request. In order for this to happen you must ensure that session WILL BE LOCKED until the current request have completed.

You can create a session like behavior by many ways, but if it does not lock the current session, it wont be 'session'.

For the specific problems you mentioned I think you should check HttpContext.Current.Response.IsClientConnected. This can be useful to to prevent unnecessary executions and waits on the client, although it cannot solve this problem entirely, as this can be used only by a pooling way and not async.

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

Add a hidden reset button :

<input id="Reset1" type="reset" value="reset" class="hidden" />

Click the reset button to clear the input.


How to decompile an APK or DEX file on Android platform?

An APK is just in zip format. You can unzip it like any other .zip file.

You can decompile .dex files using the dexdump tool, which is provided in the Android SDK.

See for more dex info.

How to generate a random string of 20 characters

public String randomString(String chars, int length) {
  Random rand = new Random();
  StringBuilder buf = new StringBuilder();
  for (int i=0; i<length; i++) {
  return buf.toString();

Using Jquery Datatable with AngularJs

Take a look at this: AngularJS+JQuery(datatable)

FULL code:

JQuery Datatables's Documentation:

var dialogApp = angular.module('tableExample', []);

    dialogApp.directive('myTable', function() {
        return function(scope, element, attrs) {

            // apply DataTable options, use defaults if none specified by user
            var options = {};
            if (attrs.myTable.length > 0) {
                options = scope.$eval(attrs.myTable);
            } else {
                options = {
                    "bStateSave": true,
                    "iCookieDuration": 2419200, /* 1 month */
                    "bJQueryUI": true,
                    "bPaginate": false,
                    "bLengthChange": false,
                    "bFilter": false,
                    "bInfo": false,
                    "bDestroy": true

            // Tell the dataTables plugin what columns to use
            // We can either derive them from the dom, or use setup from the controller           
            var explicitColumns = [];
            element.find('th').each(function(index, elem) {
            if (explicitColumns.length > 0) {
                options["aoColumns"] = explicitColumns;
            } else if (attrs.aoColumns) {
                options["aoColumns"] = scope.$eval(attrs.aoColumns);

            // aoColumnDefs is dataTables way of providing fine control over column config
            if (attrs.aoColumnDefs) {
                options["aoColumnDefs"] = scope.$eval(attrs.aoColumnDefs);

            if (attrs.fnRowCallback) {
                options["fnRowCallback"] = scope.$eval(attrs.fnRowCallback);

            // apply the plugin
            var dataTable = element.dataTable(options);

            // watch for any changes to our data, rebuild the DataTable
            scope.$watch(attrs.aaData, function(value) {
                var val = value || null;
                if (val) {

function Ctrl($scope) {

    $scope.message = '';            

        $scope.myCallback = function(nRow, aData, iDisplayIndex, iDisplayIndexFull) {            
            $('td:eq(2)', nRow).bind('click', function() {
                $scope.$apply(function() {
            return nRow;

        $scope.someClickHandler = function(info) {
            $scope.message = 'clicked: '+ info.price;

        $scope.columnDefs = [ 
            { "mDataProp": "category", "aTargets":[0]},
            { "mDataProp": "name", "aTargets":[1] },
            { "mDataProp": "price", "aTargets":[2] }

        $scope.overrideOptions = {
            "bStateSave": true,
            "iCookieDuration": 2419200, /* 1 month */
            "bJQueryUI": true,
            "bPaginate": true,
            "bLengthChange": false,
            "bFilter": true,
            "bInfo": true,
            "bDestroy": true

        $scope.sampleProductCategories = [

                "name": "1948 Porsche 356-A Roadster",
                "price": 53.9,
                  "category": "Classic Cars",
                "name": "1948 Porsche Type 356 Roadster",
                "price": 62.16,
            "category": "Classic Cars",
                "name": "1949 Jaguar XK 120",
                "price": 47.25,
            "category": "Classic Cars",
                "name": "1936 Harley Davidson El Knucklehead",
                "price": 24.23,
            "category": "Motorcycles",
                "name": "1957 Vespa GS150",
                "price": 32.95,
            "category": "Motorcycles",
                "name": "1960 BSA Gold Star DBD34",
                "price": 37.32,
            "category": "Motorcycles",
                "name": "1900s Vintage Bi-Plane",
                "price": 34.25,
            "category": "Planes",
                "name": "1900s Vintage Tri-Plane",
                "price": 36.23,
            "category": "Planes",
                "name": "1928 British Royal Navy Airplane",
                "price": 66.74,
            "category": "Planes",
                "name": "1980s Black Hawk Helicopter",
                "price": 77.27,
            "category": "Planes",
                "name": "ATA: B757-300",
                "price": 59.33,
            "category": "Planes",



Incrementing a date in JavaScript

The easiest way is to convert to milliseconds and add 1000*60*60*24 milliseconds e.g.:

var tomorrow = new Date(today.getTime()+1000*60*60*24);

How do I remove the title bar from my app?

Try changing styles to NoActionBar if that doesn't works add this code to your main activity

 protected void onCreate(Bundle savedInstanceState) {
        ActionBar actionBar = getSupportActionBar();


org.apache.catalina.LifecycleException: Failed to start component [StandardServer[8005]]A child container failed during start

One of the problems that can cause this is when you forget to put the / character in the WebServlet annotation @WebServlet("/example") @WebServlet("example") I hope it works, it worked for me.

Fastest way of finding differences between two files in unix?

You could also try to include md5-hash-sums or similar do determine whether there are any differences at all. Then, only compare files which have different hashes...

Bootstrap: Position of dropdown menu relative to navbar item

If you want to display the menu up, just add the class "dropup"
and remove the class "dropdown" if exists from the same div.

<div class="btn-group dropup">

enter image description here

Java check if boolean is null

boolean can only be true or false because it's a primitive datatype (+ a boolean variables default value is false). You can use the class Boolean instead if you want to use null values. Boolean is a reference type, that's the reason you can assign null to a Boolean "variable". Example:

Boolean testvar = null;
if (testvar == null) { ...}

Check if a given key already exists in a dictionary and increment it

Agreed with cgoldberg. How I do it is:

    dict[key] += 1
except KeyError:
    dict[key] = 1

So either do it as above, or use a default dict as others have suggested. Don't use if statements. That's not Pythonic.

Convert pyQt UI to python

I've ran into the same problem recently. After finding the correct path to the pyuic4 file using the file finder I've ran:

C:\Users\ricckli.qgis2\python\plugins\qgis2leaf>C:\OSGeo4W64\bin\pyuic4 -o ui_q ui_qgis2leaf.ui

As you can see my ui file was placed in this folder...

QT Creator was installed separately and the pyuic4 file was placed there with the OSGEO4W installer

Installing tkinter on ubuntu 14.04

Try writing the following in the terminal:

sudo apt-get install python-tk

Don't forget to actually import Tkinter module at the beginning of your program:

import Tkinter

About "*.d.ts" in TypeScript

The "d.ts" file is used to provide typescript type information about an API that's written in JavaScript. The idea is that you're using something like jQuery or underscore, an existing javascript library. You want to consume those from your typescript code.

Rather than rewriting jquery or underscore or whatever in typescript, you can instead write the d.ts file, which contains only the type annotations. Then from your typescript code you get the typescript benefits of static type checking while still using a pure JS library.

port forwarding in windows

nginx is useful for forwarding HTTP on many platforms including Windows. It's easy to setup and extend with more advanced configuration. A basic configuration could look something like this:

events {}

http {
     server {


        location / {

Convert String to Double - VB

VB.NET Sample Code

Dim A as String = "5.3"
Dim B as Double

B = CDbl(Val(A)) '// Val do hard work

'// Get output 
MsgBox (B) '// Output is 5,3 Without Val result is 53.0

Word wrap for a label in Windows Forms

The quick answer: switch off AutoSize.

The big problem here is that the label will not change its height automatically (only width). To get this right you will need to subclass the label and include vertical resize logic.

Basically what you need to do in OnPaint is:

  1. Measure the height of the text (Graphics.MeasureString).
  2. If the label height is not equal to the height of the text set the height and return.
  3. Draw the text.

You will also need to set the ResizeRedraw style flag in the constructor.

C# Threading - How to start and stop a thread

This is how I do it...

public class ThreadA {
    public ThreadA(object[] args) {
    public void Run() {
        while (true) {
            Thread.sleep(1000); // wait 1 second for something to happen.
            if(conditionToExitReceived) // what im waiting for...
        //perform cleanup if there is any...

Then to run this in its own thread... ( I do it this way because I also want to send args to the thread)

private void FireThread(){
    Thread thread = new Thread(new ThreadStart(this.startThread));
private void (startThread){
    new ThreadA(args).Run();

The thread is created by calling "FireThread()"

The newly created thread will run until its condition to stop is met, then it dies...

You can signal the "main" with delegates, to tell it when the thread has died.. so you can then start the second one...

Best to read through : This MSDN Article

Call an activity method from a fragment

((your_activity) getActivity).method_name()

Where your_activity is the name of your activity and method_name() is the name of the method you want to call.

System.BadImageFormatException An attempt was made to load a program with an incorrect format

It's possibly a 32 - 64 bits mismatch.

If you're running on a 64-bit OS, the Assembly RevitAPI may be compiled as 32-bit and your process as 64-bit or "Any CPU".

Or, the RevitAPI is compiled as 64-bit and your process is compiled as 32-bit or "Any CPU" and running on a 32-bit OS.

Shell Script Syntax Error: Unexpected End of File

in my case the issue was in the EOL Conversion. (End Of Line).

i created the file on windows and only after i converted the EOL from windows(CR LF) to unix(LF), everything went well.

I did the conversion with Notepad++ very easily from: Edit -> EOL Conversion -> Unix(LF)

Using comma as list separator with AngularJS


angular.module('App.filters', [])
    .filter('joinBy', function () {
        return function (input,delimiter) {
            return (input || []).join(delimiter || ',');

And in template:

{{ itemsArray | joinBy:',' }}

Show or hide element in React

with the newest version react 0.11 you can also just return null to have no content rendered.

Rendering to null