Programs & Examples On #Trust

Trust is a measure of how much an entity relies on other entities for its security.

Could not establish trust relationship for SSL/TLS secure channel -- SOAP

Try this:

System.Net.ServicePointManager.SecurityProtocol = System.Net.SecurityProtocolType.Tls12;

Notice that you have to work at least with 4.5 .NET framework

How can I install a CPAN module into a local directory?

local::lib will help you. It will convince "make install" (and "Build install") to install to a directory you can write to, and it will tell perl how to get at those modules.

In general, if you want to use a module that is in a blib/ directory, you want to say perl -Mblib ... where ... is how you would normally invoke your script.

How to view the roles and permissions granted to any database user in Azure SQL server instance?

Building on @tmullaney 's answer, you can also left join in the sys.objects view to get insight when explicit permissions have been granted on objects. Make sure to use the LEFT join:

SELECT DISTINCT pr.principal_id, pr.name AS [UserName], pr.type_desc AS [User_or_Role], pr.authentication_type_desc AS [Auth_Type], pe.state_desc,
    pe.permission_name, pe.class_desc, o.[name] AS 'Object' 
    FROM sys.database_principals AS pr 
    JOIN sys.database_permissions AS pe ON pe.grantee_principal_id = pr.principal_id
    LEFT JOIN sys.objects AS o on (o.object_id = pe.major_id)

mkdir's "-p" option

-p|--parent will be used if you are trying to create a directory with top-down approach. That will create the parent directory then child and so on iff none exists.

-p, --parents no error if existing, make parent directories as needed

About rlidwka it means giving full or administrative access. Found it here https://itservices.stanford.edu/service/afs/intro/permissions/unix.

RuntimeError: module compiled against API version a but this version of numpy is 9

Check the path

import numpy
print numpy.__path__

For me this was /System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/numpy So I moved it to a temporary place

sudo mv /System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/numpy \
/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/numpy_old

and then the next time I imported numpy the path was /Library/Python/2.7/site-packages/numpy/init.pyc and all was well.

How can I remove the top and right axis in matplotlib?

If you need to remove it from all your plots, you can remove spines in style settings (style sheet or rcParams). E.g:

import matplotlib as mpl

mpl.rcParams['axes.spines.right'] = False
mpl.rcParams['axes.spines.top'] = False

If you want to remove all spines:

mpl.rcParams['axes.spines.left'] = False
mpl.rcParams['axes.spines.right'] = False
mpl.rcParams['axes.spines.top'] = False
mpl.rcParams['axes.spines.bottom'] = False

Getting list of parameter names inside python function

locals() returns a dictionary with local names:

def func(a,b,c):
    print(locals().keys())

prints the list of parameters. If you use other local variables those will be included in this list. But you could make a copy at the beginning of your function.

How can I create a self-signed cert for localhost?

Since this question is tagged with IIS and I can't find a good answer on how to get a trusted certificate I will give my 2 cents about it:

First use the command from @AuriRahimzadeh in PowerShell as administrator:

New-SelfSignedCertificate -DnsName "localhost" -CertStoreLocation "cert:\LocalMachine\My"

This is good but the certificate is not trusted and will result in the following error. It is because it is not installed in Trusted Root Certification Authorities.

enter image description here

Solve this by starting mmc.exe.

Then go to:

File -> Add or Remove Snap-ins -> Certificates -> Add -> Computer account -> Local computer. Click Finish.

Expand the Personal folder and you will see your localhost certificate:

enter image description here

Copy the certificate into Trusted Root Certification Authorities - Certificates folder.

The final step is to open Internet Information Services (IIS) Manager or simply inetmgr.exe. From there go to your site, select Bindings... and Add... or Edit.... Set https and select your certificate from the drop down.

enter image description here

Your certificate is now trusted:

enter image description here

What is the difference between Scrum and Agile Development?

At an outset what I can say is - Agile is an evolutionary methodology from Unified Process which focuses on Iterative & Incremental Development (IID). IID emphasizes iterative development more on construction phases (actual coding) and incremental deliveries. It wouldn't emphasize more on Requirements Analysis (Inception) and Design (Elaboration) being handled in the iterations itself. So, Iteration here is not a "mini project by itself".

In Agile, we take this IDD a bit further, adding more realities like Team Collaboration, Evolutionary Requirements and Design etc. And SCRUM is the tool to enable it by considering the human factors and building around 'Wisdom of the Group' principle. So, Sprint here is a "mini project by itself" bettering a pure IID model.

So, iterations implemented in Agile way are, yes, theoretically Sprints (highlighting the size of the iterations being small and deliveries being quick). I don't really differentiate between Agile and SCRUM and I see that SCRUM is a natural way of putting the Agile principles into use.

The imported project "C:\Microsoft.CSharp.targets" was not found

In my case, I opened my .csproj file in notepad and removed the following three lines. Worked like a charm:

<Import Project="..\packages\Microsoft.CodeDom.Providers.DotNetCompilerPlatform.1.0.0\build\Microsoft.CodeDom.Providers.DotNetCompilerPlatform.props" Condition="Exists('..\packages\Microsoft.CodeDom.Providers.DotNetCompilerPlatform.1.0.0\build\Microsoft.CodeDom.Providers.DotNetCompilerPlatform.props')" />
<Import Project="..\packages\Microsoft.Net.Compilers.1.0.0\build\Microsoft.Net.Compilers.props" Condition="Exists('..\packages\Microsoft.Net.Compilers.1.0.0\build\Microsoft.Net.Compilers.props')" />
<Import Project="..\packages\Microsoft.Net.Compilers.1.3.2\build\Microsoft.Net.Compilers.props" Condition="Exists('..\packages\Microsoft.Net.Compilers.1.3.2\build\Microsoft.Net.Compilers.props')" />

Center Plot title in ggplot2

As stated in the answer by Henrik, titles are left-aligned by default starting with ggplot 2.2.0. Titles can be centered by adding this to the plot:

theme(plot.title = element_text(hjust = 0.5))

However, if you create many plots, it may be tedious to add this line everywhere. One could then also change the default behaviour of ggplot with

theme_update(plot.title = element_text(hjust = 0.5))

Once you have run this line, all plots created afterwards will use the theme setting plot.title = element_text(hjust = 0.5) as their default:

theme_update(plot.title = element_text(hjust = 0.5))
ggplot() + ggtitle("Default is now set to centered")

enter image description here

To get back to the original ggplot2 default settings you can either restart the R session or choose the default theme with

theme_set(theme_gray())

How to check if curl is enabled or disabled

Hope this helps.

<?php
    function _iscurl() {
        return function_exists('curl_version');
    }
?>

Change the Bootstrap Modal effect

If you take a look at the bootstraps fade class used with the modal window you will find, that all it does, is to set the opacity value to 0 and adds a transition for the opacity rule.

Whenever you launch a modal the in class is added and will change the opacity to a value of 1.

Knowing that you can easily build your own fade-scale class.

Here is an example.

_x000D_
_x000D_
@import url("https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css");_x000D_
_x000D_
.fade-scale {_x000D_
  transform: scale(0);_x000D_
  opacity: 0;_x000D_
  -webkit-transition: all .25s linear;_x000D_
  -o-transition: all .25s linear;_x000D_
  transition: all .25s linear;_x000D_
}_x000D_
_x000D_
.fade-scale.in {_x000D_
  opacity: 1;_x000D_
  transform: scale(1);_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>_x000D_
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>_x000D_
_x000D_
<!-- Button trigger modal -->_x000D_
<button type="button" class="btn btn-primary btn-lg" data-toggle="modal" data-target="#myModal">_x000D_
  Launch demo modal_x000D_
</button>_x000D_
_x000D_
<!-- Modal -->_x000D_
<div class="modal fade-scale" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">_x000D_
  <div class="modal-dialog" role="document">_x000D_
    <div class="modal-content">_x000D_
      <div class="modal-header">_x000D_
        <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>_x000D_
        <h4 class="modal-title" id="myModalLabel">Modal title</h4>_x000D_
      </div>_x000D_
      <div class="modal-body">_x000D_
        ..._x000D_
      </div>_x000D_
      <div class="modal-footer">_x000D_
        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>_x000D_
        <button type="button" class="btn btn-primary">Save changes</button>_x000D_
      </div>_x000D_
    </div>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

-- UPDATE --

This answer is getting more up votes lately so i figured i add an update to show how easy it is to customize the BS modal in and out animations with the help of the great Animate.css library by
Daniel Eden.

All that needs to be done is to include the stylesheet to your <head></head> section. Now you simply need to add the animated class, plus one of the entrance classes of the library to the modal element.

<div class="modal animated fadeIn" id="myModal" tabindex="-1" role="dialog" ...>
  ...
</div>

But there is also a way to add an out animation to the modal window and since the library has a bunch of cool animations that will make an element disappear, why not use them. :)

To use them you will need to toggle the classes on the modal element, so it is actually better to call the modal window via JavaScript, which is described here.

You will also need to listen for some of the modal events to know when it's time to add or remove the classes from the modal element. The events being fired are described here.

To trigger a custom out animation you can't use the data-dismiss="modal" attribute on a button inside the modal window that's suppose to close the modal. You can simply add your own attribute like data-custom-dismiss="modal" and use that to call the $('selector').modal.('hide') method on it.

Here is an example that shows all the different possibilities.

_x000D_
_x000D_
/* -------------------------------------------------------_x000D_
| This first part can be ignored, it is just getting_x000D_
| all the different entrance and exit classes of the_x000D_
| animate-config.json file from the github repo._x000D_
--------------------------------------------------------- */_x000D_
_x000D_
var animCssConfURL = 'https://api.github.com/repos/daneden/animate.css/contents/animate-config.json';_x000D_
var selectIn = $('#animation-in-types');_x000D_
var selectOut = $('#animation-out-types');_x000D_
var getAnimCSSConfig = function ( url ) { return $.ajax( { url: url, type: 'get', dataType: 'json' } ) };_x000D_
var decode = function ( data ) {_x000D_
  var bin = Uint8Array.from( atob( data['content'] ), function( char ) { return char.charCodeAt( 0 ) } );_x000D_
  var bin2Str = String.fromCharCode.apply( null, bin );_x000D_
  return JSON.parse( bin2Str )_x000D_
}_x000D_
var buildSelect = function ( which, name, animGrp ) {_x000D_
  var grp = $('<optgroup></optgroup>');_x000D_
  grp.attr('label', name);_x000D_
  $.each(animGrp, function ( idx, animType ) {_x000D_
    var opt = $('<option></option>')_x000D_
    opt.attr('value', idx)_x000D_
    opt.text(idx)_x000D_
    grp.append(opt);_x000D_
  })_x000D_
  which.append(grp) _x000D_
}_x000D_
getAnimCSSConfig( animCssConfURL )_x000D_
  .done (function ( data ) {_x000D_
  var animCssConf = decode ( data );_x000D_
  $.each(animCssConf, function(name, animGrp) {_x000D_
    if ( /_entrances/.test(name) ) {_x000D_
      buildSelect(selectIn, name, animGrp);_x000D_
    }_x000D_
    if ( /_exits/.test(name) ) {_x000D_
      buildSelect(selectOut, name, animGrp);_x000D_
    }_x000D_
  })_x000D_
})_x000D_
_x000D_
_x000D_
/* -------------------------------------------------------_x000D_
| Here is were the fun begins._x000D_
--------------------------------------------------------- */_x000D_
_x000D_
var modalBtn = $('button');_x000D_
var modal = $('#myModal');_x000D_
var animInClass = "";_x000D_
var animOutClass = "";_x000D_
_x000D_
modalBtn.on('click', function() {_x000D_
  animInClass = selectIn.find('option:selected').val();_x000D_
  animOutClass = selectOut.find('option:selected').val();_x000D_
  if ( animInClass == '' || animOutClass == '' ) {_x000D_
    alert("Please select an in and out animation type.");_x000D_
  } else {_x000D_
    modal.addClass(animInClass);_x000D_
    modal.modal({backdrop: false});_x000D_
  }_x000D_
})_x000D_
_x000D_
modal.on('show.bs.modal', function () {_x000D_
  var closeModalBtns = modal.find('button[data-custom-dismiss="modal"]');_x000D_
  closeModalBtns.one('click', function() {_x000D_
    modal.on('webkitAnimationEnd oanimationend msAnimationEnd animationend', function( evt ) {_x000D_
      modal.modal('hide')_x000D_
    });_x000D_
    modal.removeClass(animInClass).addClass(animOutClass);_x000D_
  })_x000D_
})_x000D_
_x000D_
modal.on('hidden.bs.modal', function ( evt ) {_x000D_
  var closeModalBtns = modal.find('button[data-custom-dismiss="modal"]');_x000D_
  modal.removeClass(animOutClass)_x000D_
  modal.off('webkitAnimationEnd oanimationend msAnimationEnd animationend')_x000D_
  closeModalBtns.off('click')_x000D_
})
_x000D_
@import url('https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css');_x000D_
@import url('https://cdnjs.cloudflare.com/ajax/libs/animate.css/3.5.2/animate.css');_x000D_
_x000D_
select, button:not([data-custom-dismiss="modal"]) {_x000D_
  margin: 10px 0;_x000D_
  width: 220px;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>_x000D_
_x000D_
<div class="container">_x000D_
  <div class="row">_x000D_
    <div class="col-xs-4 col-xs-offset-4 col-sm-4 col-sm-offset-4">_x000D_
      <select id="animation-in-types">_x000D_
        <option value="" selected>Choose animation-in type</option>_x000D_
      </select>_x000D_
    </div>_x000D_
  </div>_x000D_
  <div class="row">_x000D_
    <div class="col-xs-4 col-xs-offset-4 col-sm-4 col-sm-offset-4">_x000D_
      <select id="animation-out-types">_x000D_
        <option value="" selected>Choose animation-out type</option>_x000D_
      </select>_x000D_
    </div>_x000D_
  </div>_x000D_
  <div class="row">_x000D_
    <div class="col-xs-4 col-xs-offset-4 col-sm-4 col-sm-offset-4">_x000D_
      <button class="btn btn-default">Open Modal</button>_x000D_
    </div>_x000D_
  </div>_x000D_
</div>_x000D_
_x000D_
<!-- Modal -->_x000D_
<div class="modal animated" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">_x000D_
  <div class="modal-dialog" role="document">_x000D_
    <div class="modal-content">_x000D_
      <div class="modal-header">_x000D_
        <button type="button" class="close" data-custom-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>_x000D_
        <h4 class="modal-title" id="myModalLabel">Modal title</h4>_x000D_
      </div>_x000D_
      <div class="modal-body">_x000D_
        ..._x000D_
      </div>_x000D_
      <div class="modal-footer">_x000D_
        <button type="button" class="btn btn-default" data-custom-dismiss="modal">Close</button>_x000D_
      </div>_x000D_
    </div>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Cannot open new Jupyter Notebook [Permission Denied]

You don't have to install or uninstall anything. if you are using python 2 use pip to install and upgrade. But if you want to use python3 then follow the steps below:

sudo apt-get install python3-pip python3-dev

then in terminal use this

pip3 install -U jupyter

final step is to launch jupyter notebook so,in terminal just type

jupyter notebook

all the issues or problems of premissions etc will be resolved.

Force overwrite of local file with what's in origin repo?

Simplest version, assuming you're working on the same branch that the file you want is on:

git checkout path/to/file.

I do this so often that I've got an alias set to gc='git checkout'.

How do I fix a Git detached head?

Realizing I had a detached head without knowing how I managed to get it (like three commits away), I also found out that trying to merge, rebase or cherry-pick triggered hundreds of merge-conflicts, so I took a different approach:

  1. (Assuming everything is committed (working tree is "clean"))

  2. Save my commit messages: git log > /tmp/log

  3. Save my working tree: mkdir /tmp/backup && cp -a all_my files_and_directories /tmp/backup

  4. Revert to master: git checkout master

  5. Remove all the working files and directories: rm ...

  6. Use the backup: cp -a /tmp/backup/. .

  7. git add and git commit using messages from saved /tmp/log, maybe repeating it with different sub-sets of files...

The disadvantage is that you loose your commit history if one file was changed multiple times since master, but in the end I had a clean master.

How can I account for period (AM/PM) using strftime?

The Python time.strftime docs say:

When used with the strptime() function, the %p directive only affects the output hour field if the %I directive is used to parse the hour.

Sure enough, changing your %H to %I makes it work.

Difference between Pragma and Cache-Control headers?

There is no difference, except that Pragma is only defined as applicable to the requests by the client, whereas Cache-Control may be used by both the requests of the clients and the replies of the servers.

So, as far as standards go, they can only be compared from the perspective of the client making a requests and the server receiving a request from the client. The http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.32 defines the scenario as follows:

HTTP/1.1 caches SHOULD treat "Pragma: no-cache" as if the client had sent "Cache-Control: no-cache". No new Pragma directives will be defined in HTTP.

  Note: because the meaning of "Pragma: no-cache as a response
  header field is not actually specified, it does not provide a
  reliable replacement for "Cache-Control: no-cache" in a response

The way I would read the above:

  • if you're writing a client and need no-cache:

    • just use Pragma: no-cache in your requests, since you may not know if Cache-Control is supported by the server;
    • but in replies, to decide on whether to cache, check for Cache-Control
  • if you're writing a server:

    • in parsing requests from the clients, check for Cache-Control; if not found, check for Pragma: no-cache, and execute the Cache-Control: no-cache logic;
    • in replies, provide Cache-Control.

Of course, reality might be different from what's written or implied in the RFC!

How do you display a Toast from a background thread on Android?

Sometimes, you have to send message from another Thread to UI thread. This type of scenario occurs when you can't execute Network/IO operations on UI thread.

Below example handles that scenario.

  1. You have UI Thread
  2. You have to start IO operation and hence you can't run Runnable on UI thread. So post your Runnable to handler on HandlerThread
  3. Get the result from Runnable and send it back to UI thread and show a Toast message.

Solution:

  1. Create a HandlerThread and start it
  2. Create a Handler with Looper from HandlerThread:requestHandler
  3. Create a Handler with Looper from Main Thread: responseHandler and override handleMessage method
  4. post a Runnable task on requestHandler
  5. Inside Runnable task, call sendMessage on responseHandler
  6. This sendMessage result invocation of handleMessage in responseHandler.
  7. Get attributes from the Message and process it, update UI

Sample code:

    /* Handler thread */

    HandlerThread handlerThread = new HandlerThread("HandlerThread");
    handlerThread.start();
    Handler requestHandler = new Handler(handlerThread.getLooper());

    final Handler responseHandler = new Handler(Looper.getMainLooper()) {
        @Override
        public void handleMessage(Message msg) {
            //txtView.setText((String) msg.obj);
            Toast.makeText(MainActivity.this,
                    "Runnable on HandlerThread is completed and got result:"+(String)msg.obj,
                    Toast.LENGTH_LONG)
                    .show();
        }
    };

    for ( int i=0; i<5; i++) {
        Runnable myRunnable = new Runnable() {
            @Override
            public void run() {
                try {

                    /* Add your business logic here and construct the 
                       Messgae which should be handled in UI thread. For 
                       example sake, just sending a simple Text here*/

                    String text = "" + (++rId);
                    Message msg = new Message();

                    msg.obj = text.toString();
                    responseHandler.sendMessage(msg);
                    System.out.println(text.toString());

                } catch (Exception err) {
                    err.printStackTrace();
                }
            }
        };
        requestHandler.post(myRunnable);
    }

Useful articles:

handlerthreads-and-why-you-should-be-using-them-in-your-android-apps

android-looper-handler-handlerthread-i

How do I initialize a TypeScript Object with a JSON-Object?

you can use Object.assign I don't know when this was added, I'm currently using Typescript 2.0.2, and this appears to be an ES6 feature.

client.fetch( '' ).then( response => {
        return response.json();
    } ).then( json => {
        let hal : HalJson = Object.assign( new HalJson(), json );
        log.debug( "json", hal );

here's HalJson

export class HalJson {
    _links: HalLinks;
}

export class HalLinks implements Links {
}

export interface Links {
    readonly [text: string]: Link;
}

export interface Link {
    readonly href: URL;
}

here's what chrome says it is

HalJson {_links: Object}
_links
:
Object
public
:
Object
href
:
"http://localhost:9000/v0/public

so you can see it doesn't do the assign recursively

How to set the margin or padding as percentage of height of parent container?

An answer to a slightly different question: You can use vh units to pad elements to the center of the viewport:

.centerme {
    margin-top: 50vh;
    background: red;
}

<div class="centerme">middle</div>

What is the use of the JavaScript 'bind' method?

The bind() method creates a new function instance whose this value is bound to the value that was passed into bind(). For example:

   window.color = "red"; 
   var o = { color: "blue" }; 
   function sayColor(){ 
       alert(this.color); 
   } 
   var objectSayColor = sayColor.bind(o); 
   objectSayColor(); //blue 

Here, a new function called objectSayColor() is created from sayColor() by calling bind() and passing in the object o. The objectSayColor() function has a this value equivalent to o, so calling the function, even as a global call, results in the string “blue” being displayed.

Reference : Nicholas C. Zakas - PROFESSIONAL JAVASCRIPT® FOR WEB DEVELOPERS

Correct path for img on React.js

A friend showed me how to do this as follows:

"./" works when the file requesting the image (e.g., "example.js") is on the same level within the folder tree structure as the folder "images".

How to check if a specific key is present in a hash or not?

It is very late but preferably symbols should be used as key:

my_hash = {}
my_hash[:my_key] = 'value'

my_hash.has_key?("my_key")
 => false 
my_hash.has_key?("my_key".to_sym)
 => true 

my_hash2 = {}
my_hash2['my_key'] = 'value'

my_hash2.has_key?("my_key")
 => true 
my_hash2.has_key?("my_key".to_sym)
 => false 

But when creating hash if you pass string as key then it will search for the string in keys.

But when creating hash you pass symbol as key then has_key? will search the keys by using symbol.


If you are using Rails, you can use Hash#with_indifferent_access to avoid this; both hash[:my_key] and hash["my_key"] will point to the same record

How to scale an Image in ImageView to keep the aspect ratio

I use this:

<ImageView
android:id="@+id/logo"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_centerInParent="true"
android:scaleType="centerInside"
android:src="@drawable/logo" />

Check if a key exists inside a json object

I change your if statement slightly and works (also for inherited obj - look on snippet)

if(!("merchant_id" in thisSession)) alert("yeah");

_x000D_
_x000D_
var sessionA = {_x000D_
  amt: "10.00",_x000D_
  email: "[email protected]",_x000D_
  merchant_id: "sam",_x000D_
  mobileNo: "9874563210",_x000D_
  orderID: "123456",_x000D_
  passkey: "1234",_x000D_
}_x000D_
_x000D_
var sessionB = {_x000D_
  amt: "10.00",_x000D_
  email: "[email protected]",_x000D_
  mobileNo: "9874563210",_x000D_
  orderID: "123456",_x000D_
  passkey: "1234",_x000D_
}_x000D_
_x000D_
_x000D_
var sessionCfromA = Object.create(sessionA); // inheritance_x000D_
sessionCfromA.name = 'john';_x000D_
_x000D_
_x000D_
if (!("merchant_id" in sessionA)) alert("merchant_id not in sessionA");_x000D_
if (!("merchant_id" in sessionB)) alert("merchant_id not in sessionB");_x000D_
if (!("merchant_id" in sessionCfromA)) alert("merchant_id not in sessionCfromA");_x000D_
_x000D_
if ("merchant_id" in sessionA) alert("merchant_id in sessionA");_x000D_
if ("merchant_id" in sessionB) alert("merchant_id in sessionB");_x000D_
if ("merchant_id" in sessionCfromA) alert("merchant_id in sessionCfromA");
_x000D_
_x000D_
_x000D_

Create table with jQuery - append

Here is what you can do: http://jsfiddle.net/n7cyE/4/

$('#here_table').append('<table></table>');
var table = $('#here_table').children();
 for(i=0;i<3;i++){
    table.append( '<tr><td>' + 'result' +  i + '</td></tr>' );
}

Best regards!

How to use delimiter for csv in python

CSV Files with Custom Delimiters

By default, a comma is used as a delimiter in a CSV file. However, some CSV files can use delimiters other than a comma. Few popular ones are | and \t.

import csv
data_list = [["SN", "Name", "Contribution"],
             [1, "Linus Torvalds", "Linux Kernel"],
             [2, "Tim Berners-Lee", "World Wide Web"],
             [3, "Guido van Rossum", "Python Programming"]]
with open('innovators.csv', 'w', newline='') as file:
    writer = csv.writer(file, delimiter='|')
    writer.writerows(data_list)

output:

SN|Name|Contribution
1|Linus Torvalds|Linux Kernel
2|Tim Berners-Lee|World Wide Web
3|Guido van Rossum|Python Programming

Write CSV files with quotes

import csv

row_list = [["SN", "Name", "Contribution"],
             [1, "Linus Torvalds", "Linux Kernel"],
             [2, "Tim Berners-Lee", "World Wide Web"],
             [3, "Guido van Rossum", "Python Programming"]]
with open('innovators.csv', 'w', newline='') as file:
    writer = csv.writer(file, quoting=csv.QUOTE_NONNUMERIC, delimiter=';')
    writer.writerows(row_list) 

output:

"SN";"Name";"Contribution"
1;"Linus Torvalds";"Linux Kernel"
2;"Tim Berners-Lee";"World Wide Web"
3;"Guido van Rossum";"Python Programming"

As you can see, we have passed csv.QUOTE_NONNUMERIC to the quoting parameter. It is a constant defined by the csv module.

csv.QUOTE_NONNUMERIC specifies the writer object that quotes should be added around the non-numeric entries.

There are 3 other predefined constants you can pass to the quoting parameter:

  • csv.QUOTE_ALL - Specifies the writer object to write CSV file with quotes around all the entries.
  • csv.QUOTE_MINIMAL - Specifies the writer object to only quote those fields which contain special characters (delimiter, quotechar or any characters in lineterminator)
  • csv.QUOTE_NONE - Specifies the writer object that none of the entries should be quoted. It is the default value.
import csv

row_list = [["SN", "Name", "Contribution"],
             [1, "Linus Torvalds", "Linux Kernel"],
             [2, "Tim Berners-Lee", "World Wide Web"],
             [3, "Guido van Rossum", "Python Programming"]]
with open('innovators.csv', 'w', newline='') as file:
    writer = csv.writer(file, quoting=csv.QUOTE_NONNUMERIC,
                        delimiter=';', quotechar='*')
    writer.writerows(row_list)

output:

*SN*;*Name*;*Contribution*
1;*Linus Torvalds*;*Linux Kernel*
2;*Tim Berners-Lee*;*World Wide Web*
3;*Guido van Rossum*;*Python Programming*

Here, we can see that quotechar='*' parameter instructs the writer object to use * as quote for all non-numeric values.

How to generate .angular-cli.json file in Angular Cli?

I found similar error it was located to C:\Users\sony\AppData\Roaming\npm\node_modules\@angular\cli\node_modules\@schematics\angular\workspace\files

it is installed in windows try to search in c drive angular.json you will view the file

rsync: how can I configure it to create target directory on server?

This answer uses bits of other answers, but hopefully it'll be a bit clearer as to the circumstances. You never specified what you were rsyncing - a single directory entry or multiple files.

So let's assume you are moving a source directory entry across, and not just moving the files contained in it.

Let's say you have a directory locally called data/myappdata/ and you have a load of subdirectories underneath this. You have data/ on your target machine but no data/myappdata/ - this is easy enough:

rsync -rvv /path/to/data/myappdata/ user@host:/remote/path/to/data/myappdata

You can even use a different name for the remote directory:

rsync -rvv --recursive /path/to/data/myappdata user@host:/remote/path/to/data/newdirname

If you're just moving some files and not moving the directory entry that contains them then you would do:

rsync -rvv /path/to/data/myappdata/*.txt user@host:/remote/path/to/data/myappdata/

and it will create the myappdata directory for you on the remote machine to place your files in. Again, the data/ directory must exist on the remote machine.

Incidentally, my use of -rvv flag is to get doubly verbose output so it is clear about what it does, as well as the necessary recursive behaviour.

Just to show you what I get when using rsync (3.0.9 on Ubuntu 12.04)

$ rsync -rvv *.txt [email protected]:/tmp/newdir/
opening connection using: ssh -l user remote.machine rsync --server -vvre.iLsf . /tmp/newdir/
[email protected]'s password:
sending incremental file list
created directory /tmp/newdir
delta-transmission enabled
bar.txt
foo.txt
total: matches=0  hash_hits=0  false_alarms=0 data=0

Hope this clears this up a little bit.

How do you handle multiple submit buttons in ASP.NET MVC Framework?

You can check the name in the action as has been mentioned, but you might consider whether or not this is good design. It is a good idea to consider the responsibility of the action and not couple this design too much to UI aspects like button names. So consider using 2 forms and 2 actions:

<% Html.BeginForm("Send", "MyController", FormMethod.Post); %>
<input type="submit" name="button" value="Send" />
<% Html.EndForm(); %>

<% Html.BeginForm("Cancel", "MyController", FormMethod.Post); %>
<input type="submit" name="button" value="Cancel" />
<% Html.EndForm(); %>

Also, in the case of "Cancel", you are usually just not processing the form and are going to a new URL. In this case you do not need to submit the form at all and just need a link:

<%=Html.ActionLink("Cancel", "List", "MyController") %>

Firebase: how to generate a unique numeric ID for key?

As explained above, you can use the Firebase default push id.

If you want something numeric you can do something based on the timestamp to avoid collisions

f.e. something based on date,hour,second,ms, and some random int at the end

01612061353136799031

Which translates to:

016-12-06 13:53:13:679 9031

It all depends on the precision you need (social security numbers do the same with some random characters at the end of the date). Like how many transactions will be expected during the day, hour or second. You may want to lower precision to favor ease of typing.

You can also do a transaction that increments the number id, and on success you will have a unique consecutive number for that user. These can be done on the client or server side.

(https://firebase.google.com/docs/database/android/read-and-write)

Restricting input to textbox: allowing only numbers and decimal point

A small correction to @rebisco's brilliant answer to validate the decimal perfectly.

function isNumberKey(evt) {
    debugger;
    var charCode = (evt.which) ? evt.which : event.keyCode;
    if (charCode == 46 && evt.srcElement.value.split('.').length>1) {
        return false;
    }
    if (charCode != 46 && charCode > 31 && (charCode < 48 || charCode > 57))
        return false;
    return true;
}

What is the most useful script you've written for everyday life?

Mass file renaming via drag&drop.

Ages ago I've made a small VBScript that accepts a RegEx and replaces file names accordingly. You would simply drop a bunch of files or folders on it. I found that to be very useful throughout the years.

gist.github.com/15824 (Beware, the comments are in German)

Removing whitespace from strings in Java

You should use

s.replaceAll("\\s+", "");

instead of:

s.replaceAll("\\s", "");

This way, it will work with more than one spaces between each string. The + sign in the above regex means "one or more \s"

--\s = Anything that is a space character (including space, tab characters etc). Why do we need s+ here?

Pandas rename column by position?

You can do this:

df.rename(columns={ df.columns[1]: "whatever" })

When to use React "componentDidUpdate" method?

This lifecycle method is invoked as soon as the updating happens. The most common use case for the componentDidUpdate() method is updating the DOM in response to prop or state changes.

You can call setState() in this lifecycle, but keep in mind that you will need to wrap it in a condition to check for state or prop changes from previous state. Incorrect usage of setState() can lead to an infinite loop. Take a look at the example below that shows a typical usage example of this lifecycle method.

componentDidUpdate(prevProps) {
 //Typical usage, don't forget to compare the props
 if (this.props.userName !== prevProps.userName) {
   this.fetchData(this.props.userName);
 }
}

Notice in the above example that we are comparing the current props to the previous props. This is to check if there has been a change in props from what it currently is. In this case, there won’t be a need to make the API call if the props did not change.

For more info, refer to the official docs:

How to use MD5 in javascript to transmit a password

If someone is sniffing your plain-text HTTP traffic (or cache/cookies) for passwords just turning the password into a hash won't help - The hash password can be "replayed" just as well as plain-text. The client would need to hash the password with something somewhat random (like the date and time) See the section on "AUTH CRAM-MD5" here: http://www.fehcom.de/qmail/smtpauth.html

How to show the "Are you sure you want to navigate away from this page?" when changes committed?

here is my html

<!DOCTYPE HMTL>
<meta charset="UTF-8">
<html>
<head>
<title>Home</title>
<script type="text/javascript" src="script.js"></script>
</head>

 <body onload="myFunction()">
    <h1 id="belong">
        Welcome To My Home
    </h1>
    <p>
        <a id="replaceME" onclick="myFunction2(event)" href="https://www.ccis.edu">I am a student at Columbia College of Missouri.</a>
    </p>
</body>

And so this is how I did something similar in javaScript

var myGlobalNameHolder ="";

function myFunction(){
var myString = prompt("Enter a name", "Name Goes Here");
    myGlobalNameHolder = myString;
    if (myString != null) {
        document.getElementById("replaceME").innerHTML =
        "Hello " + myString + ". Welcome to my site";

        document.getElementById("belong").innerHTML =
        "A place you belong";
    }   
}

// create a function to pass our event too
function myFunction2(event) {   
// variable to make our event short and sweet
var x=window.onbeforeunload;
// logic to make the confirm and alert boxes
if (confirm("Are you sure you want to leave my page?") == true) {
    x = alert("Thank you " + myGlobalNameHolder + " for visiting!");
}
}

How to disable SSL certificate checking with Spring RestTemplate?

Here's a solution where security checking is disabled (for example, conversing with the localhost) Also, some of the solutions I've seen now contain deprecated methods and such.

/**
 * @param configFilePath
 * @param ipAddress
 * @param userId
 * @param password
 * @throws MalformedURLException
 */
public Upgrade(String aConfigFilePath, String ipAddress, String userId, String password) {
    configFilePath = aConfigFilePath;
    baseUri = "https://" + ipAddress + ":" + PORT + "/";

    restTemplate = new RestTemplate(createSecureTransport(userId, password, ipAddress, PORT));
    restTemplate.getMessageConverters().add(new MappingJacksonHttpMessageConverter());
    restTemplate.getMessageConverters().add(new StringHttpMessageConverter());
 }

ClientHttpRequestFactory createSecureTransport(String username,
        String password, String host, int port) {
    HostnameVerifier nullHostnameVerifier = new HostnameVerifier() {
        public boolean verify(String hostname, SSLSession session) {
            return true;
        }
    };
    UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(username, password);
    CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
    credentialsProvider.setCredentials(
            new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT, AuthScope.ANY_REALM), credentials);

    HttpClient client = HttpClientBuilder.create()
            .setSSLHostnameVerifier(nullHostnameVerifier)
            .setSSLContext(createContext())
            .setDefaultCredentialsProvider(credentialsProvider).build();

    HttpComponentsClientHttpRequestFactory requestFactory = 
            new HttpComponentsClientHttpRequestFactory(client);

    return requestFactory;
}

private SSLContext createContext() {
    TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
        public java.security.cert.X509Certificate[] getAcceptedIssuers() {
            return null;
        }

        public void checkClientTrusted(
                java.security.cert.X509Certificate[] certs, String authType) {
        }

        public void checkServerTrusted(
                java.security.cert.X509Certificate[] certs, String authType) {
        }
    } };

    try {
        SSLContext sc = SSLContext.getInstance("SSL");
        sc.init(null, trustAllCerts, null);
        SSLContext.setDefault(sc);
        HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
        HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() {
            public boolean verify(String hostname, SSLSession session) {
                    return true;
                }
            });
        return sc;

    } catch (Exception e) {
    }
    return null;
}

How can I create a copy of an Oracle table without copying the data?

Just use a where clause that won't select any rows:

create table xyz_new as select * from xyz where 1=0;

Limitations

The following things will not be copied to the new table:

  • sequences
  • triggers
  • indexes
  • some constraints may not be copied
  • materialized view logs

This also does not handle partitions


Writing Python lists to columns in csv

If you are happy to use a 3rd party library, you can do this with Pandas. The benefits include seamless access to specialized methods and row / column labeling:

import pandas as pd

list1 = [1, 2, 3]
list2 = [4, 5, 6]
list3 = [7, 8, 9]

df = pd.DataFrame(list(zip(*[list1, list2, list3]))).add_prefix('Col')

df.to_csv('file.csv', index=False)

print(df)

   Col0  Col1  Col2
0     1     4     7
1     2     5     8
2     3     6     9

Getting current device language in iOS?

For Swift 3.0 below code can be used to answer your question:

 let language = Bundle.main.preferredLocalizations.first! as NSString

Making custom right-click context menus for my web-app

I know this question is very old, but just came up with the same problem and solved it myself, so I'm answering in case anyone finds this through google as I did. I based my solution on @Andrew's one, but basically modified everything afterwards.

EDIT: seeing how popular this has been lately, I decided to update also the styles to make it look more like 2014 and less like windows 95. I fixed the bugs @Quantico and @Trengot spotted so now it's a more solid answer.

EDIT 2: I set it up with StackSnippets as they're a really cool new feature. I leave the good jsfiddle here for reference thought (click on the 4th panel to see them work).

New Stack Snippet:

_x000D_
_x000D_
// JAVASCRIPT (jQuery)_x000D_
_x000D_
// Trigger action when the contexmenu is about to be shown_x000D_
$(document).bind("contextmenu", function (event) {_x000D_
    _x000D_
    // Avoid the real one_x000D_
    event.preventDefault();_x000D_
    _x000D_
    // Show contextmenu_x000D_
    $(".custom-menu").finish().toggle(100)._x000D_
    _x000D_
    // In the right position (the mouse)_x000D_
    css({_x000D_
        top: event.pageY + "px",_x000D_
        left: event.pageX + "px"_x000D_
    });_x000D_
});_x000D_
_x000D_
_x000D_
// If the document is clicked somewhere_x000D_
$(document).bind("mousedown", function (e) {_x000D_
    _x000D_
    // If the clicked element is not the menu_x000D_
    if (!$(e.target).parents(".custom-menu").length > 0) {_x000D_
        _x000D_
        // Hide it_x000D_
        $(".custom-menu").hide(100);_x000D_
    }_x000D_
});_x000D_
_x000D_
_x000D_
// If the menu element is clicked_x000D_
$(".custom-menu li").click(function(){_x000D_
    _x000D_
    // This is the triggered action name_x000D_
    switch($(this).attr("data-action")) {_x000D_
        _x000D_
        // A case for each action. Your actions here_x000D_
        case "first": alert("first"); break;_x000D_
        case "second": alert("second"); break;_x000D_
        case "third": alert("third"); break;_x000D_
    }_x000D_
  _x000D_
    // Hide it AFTER the action was triggered_x000D_
    $(".custom-menu").hide(100);_x000D_
  });
_x000D_
/* CSS3 */_x000D_
_x000D_
/* The whole thing */_x000D_
.custom-menu {_x000D_
    display: none;_x000D_
    z-index: 1000;_x000D_
    position: absolute;_x000D_
    overflow: hidden;_x000D_
    border: 1px solid #CCC;_x000D_
    white-space: nowrap;_x000D_
    font-family: sans-serif;_x000D_
    background: #FFF;_x000D_
    color: #333;_x000D_
    border-radius: 5px;_x000D_
    padding: 0;_x000D_
}_x000D_
_x000D_
/* Each of the items in the list */_x000D_
.custom-menu li {_x000D_
    padding: 8px 12px;_x000D_
    cursor: pointer;_x000D_
    list-style-type: none;_x000D_
    transition: all .3s ease;_x000D_
    user-select: none;_x000D_
}_x000D_
_x000D_
.custom-menu li:hover {_x000D_
    background-color: #DEF;_x000D_
}
_x000D_
<!-- HTML -->_x000D_
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.js"></script>_x000D_
_x000D_
<ul class='custom-menu'>_x000D_
  <li data-action="first">First thing</li>_x000D_
  <li data-action="second">Second thing</li>_x000D_
  <li data-action="third">Third thing</li>_x000D_
</ul>_x000D_
_x000D_
<!-- Not needed, only for making it clickable on StackOverflow -->_x000D_
Right click me
_x000D_
_x000D_
_x000D_

Note: you might see some small bugs (dropdown far from the cursor, etc), please make sure that it works in the jsfiddle, as that's more similar to your webpage than StackSnippets might be.

How to convert a byte array to its numeric value (Java)?

If this is an 8-bytes numeric value, you can try:

BigInteger n = new BigInteger(byteArray);

If this is an UTF-8 character buffer, then you can try:

BigInteger n = new BigInteger(new String(byteArray, "UTF-8"));

Why am I getting "(304) Not Modified" error on some links when using HttpWebRequest?

It is not an issue it is because of caching...

To overcome this add a timestamp to your endpoint call, e.g. axios.get('/api/products').

After timestamp it should be axios.get(/api/products?${Date.now()}.

It will resolve your 304 status code.

Is it possible to iterate through JSONArray?

You can use the opt(int) method and use a classical for loop.

notifyDataSetChanged example

I recently wrote on this topic, though this post it old, I thought it will be helpful to someone who wants to know how to implement BaseAdapter.notifyDataSetChanged() step by step and in a correct way.

Please follow How to correctly implement BaseAdapter.notifyDataSetChanged() in Android or the newer blog BaseAdapter.notifyDataSetChanged().

How to find column names for all tables in all databases in SQL Server

I used:

EXEC sp_MSforeachdb 'Use ? Select * From INFORMATION_SCHEMA.COLUMNS '

It seems to work for what I needed.

How do I check if a directory exists? "is_dir", "file_exists" or both?

$save_folder = "some/path/" . date('dmy');

if (!file_exists($save_folder)) {
   mkdir($save_folder, 0777);
}

Scraping: SSL: CERTIFICATE_VERIFY_FAILED error for http://en.wikipedia.org

to use unverified ssl you can add this to your code:

import ssl
ssl._create_default_https_context = ssl._create_unverified_context

Can a table have two foreign keys?

create table Table1
(
  id varchar(2),
  name varchar(2),
  PRIMARY KEY (id)
)


Create table Table1_Addr
(
  addid varchar(2),
  Address varchar(2),
  PRIMARY KEY (addid)
)

Create table Table1_sal
(
  salid varchar(2),`enter code here`
  addid varchar(2),
  id varchar(2),
  PRIMARY KEY (salid),
  index(addid),
  index(id),
  FOREIGN KEY (addid) REFERENCES Table1_Addr(addid),
  FOREIGN KEY (id) REFERENCES Table1(id)
)

Efficient way to add spaces between characters in a string

s = "BINGO"
print(" ".join(s))

Should do it.

Can you create nested WITH clauses for Common Table Expressions?

With does not work embedded, but it does work consecutive

;WITH A AS(
...
),
B AS(
...
)
SELECT *
FROM A
UNION ALL
SELECT *
FROM B

EDIT Fixed the syntax...

Also, have a look at the following example

SQLFiddle DEMO

How to extract duration time from ffmpeg output?

If you want to retrieve the length (and possibly all other metadata) from your media file with ffmpeg by using a python script you could try this:

import subprocess
import json

input_file  = "< path to your input file here >"

metadata = subprocess.check_output(f"ffprobe -i {input_file} -v quiet -print_format json -show_format -hide_banner".split(" "))

metadata = json.loads(metadata)
print(f"Length of file is: {float(metadata['format']['duration'])}")
print(metadata)

Output:

Length of file is: 7579.977143

{
  "streams": [
    {
      "index": 0,
      "codec_name": "mp3",
      "codec_long_name": "MP3 (MPEG audio layer 3)",
      "codec_type": "audio",
      "codec_time_base": "1/44100",
      "codec_tag_string": "[0][0][0][0]",
      "codec_tag": "0x0000",
      "sample_fmt": "fltp",
      "sample_rate": "44100",
      "channels": 2,
      "channel_layout": "stereo",
      "bits_per_sample": 0,
      "r_frame_rate": "0/0",
      "avg_frame_rate": "0/0",
      "time_base": "1/14112000",
      "start_pts": 353600,
      "start_time": "0.025057",
      "duration_ts": 106968637440,
      "duration": "7579.977143",
      "bit_rate": "320000",
      ...
      ...

MongoDB - admin user not authorized

I followed these steps on Centos 7 for MongoDB 4.2. (Remote user)

Update mongod.conf file

vi /etc/mongod.conf
   net:
     port: 27017
     bindIp: 0.0.0.0 
   security:
     authorization: enabled

Start MongoDB service demon

systemctl start mongod

Open MongoDB shell

mongo

Execute this command on the shell

use admin
db.createUser(
  {
    user: 'admin',
    pwd: 'YouPassforUser',
    roles: [ { role: 'root', db: 'admin' } ]
  }
);

Remote root user has been created. Now you can test this database connection by using any MongoDB GUI tool from your dev machine. Like Robo 3T

Color theme for VS Code integrated terminal

You can actually modify your user settings and edit each colour individually by adding the following to the user settings.

  1. Open user settings (ctrl + ,)
  2. Search for workbench and select Edit in settings.json under Color Customizations
"workbench.colorCustomizations" : {
    "terminal.foreground" : "#00FD61",
    "terminal.background" : "#383737"
}

For more on what colors you can edit you can find out here.

Spring 3.0: Unable to locate Spring NamespaceHandler for XML schema namespace

I ran into a similar error, but refering to Spring Webflow in a newly created Roo project. The solution for me turned out to be (Project) / right-click / Maven / Enable Maven Dependencies (followed by some restarts and republishes to Tomcat).

It appeared that STS or m2Eclipse was failing to push all the spring webflow jars into the web app lib directory. I'm not sure why. But enabling maven dependency handling and then rebuilding seemed to fix the problem; the webflow jars finally get published and thus it can find the schema namespace references.

I investigated this by exploring the tomcat directory that the web app was published to, clicking into WEB-INF/lib/ while it was running and noticing that it was missing webflow jar files.

How do I create a view controller file after creating a new view controller?

To add new ViewController once you have have an existing ViewController, follow below step:

  1. Click on background of Main.storyboard.

  2. Search and select ViewController from object library at the utility window.

  3. Drag and drop it in background to create a new ViewController.

sort json object in javascript

Here is a simple snippet that sorts a javascript representation of a Json.

function isObject(v) {
    return '[object Object]' === Object.prototype.toString.call(v);
};

JSON.sort = function(o) {
if (Array.isArray(o)) {
        return o.sort().map(JSON.sort);
    } else if (isObject(o)) {
        return Object
            .keys(o)
        .sort()
            .reduce(function(a, k) {
                a[k] = JSON.sort(o[k]);

                return a;
            }, {});
    }

    return o;
}

It can be used as follows:

JSON.sort({
    c: {
        c3: null,
        c1: undefined,
        c2: [3, 2, 1, 0],
    },
    a: 0,
    b: 'Fun'
});

That will output:

{
  a: 0,
  b: 'Fun',
  c: {
    c2: [3, 2, 1, 0],
    c3: null
  }
}

Running Command Line in Java

Have you tried the exec command within the Runtime class?

Runtime.getRuntime().exec("java -jar map.jar time.rel test.txt debug")

Runtime - Java Documentation

How to customize Bootstrap 3 tab color

_x000D_
_x000D_
.panel.with-nav-tabs .panel-heading {_x000D_
  padding: 5px 5px 0 5px;_x000D_
}_x000D_
_x000D_
.panel.with-nav-tabs .nav-tabs {_x000D_
  border-bottom: none;_x000D_
}_x000D_
_x000D_
.panel.with-nav-tabs .nav-justified {_x000D_
  margin-bottom: -1px;_x000D_
}_x000D_
_x000D_
_x000D_
/********************************************************************/_x000D_
_x000D_
_x000D_
/*** PANEL DEFAULT ***/_x000D_
_x000D_
.with-nav-tabs.panel-default .nav-tabs>li>a,_x000D_
.with-nav-tabs.panel-default .nav-tabs>li>a:hover,_x000D_
.with-nav-tabs.panel-default .nav-tabs>li>a:focus {_x000D_
  color: #777;_x000D_
}_x000D_
_x000D_
.with-nav-tabs.panel-default .nav-tabs>.open>a,_x000D_
.with-nav-tabs.panel-default .nav-tabs>.open>a:hover,_x000D_
.with-nav-tabs.panel-default .nav-tabs>.open>a:focus,_x000D_
.with-nav-tabs.panel-default .nav-tabs>li>a:hover,_x000D_
.with-nav-tabs.panel-default .nav-tabs>li>a:focus {_x000D_
  color: #777;_x000D_
  background-color: #ddd;_x000D_
  border-color: transparent;_x000D_
}_x000D_
_x000D_
.with-nav-tabs.panel-default .nav-tabs>li.active>a,_x000D_
.with-nav-tabs.panel-default .nav-tabs>li.active>a:hover,_x000D_
.with-nav-tabs.panel-default .nav-tabs>li.active>a:focus {_x000D_
  color: #555;_x000D_
  background-color: #fff;_x000D_
  border-color: #ddd;_x000D_
  border-bottom-color: transparent;_x000D_
}_x000D_
_x000D_
.with-nav-tabs.panel-default .nav-tabs>li.dropdown .dropdown-menu {_x000D_
  background-color: #f5f5f5;_x000D_
  border-color: #ddd;_x000D_
}_x000D_
_x000D_
.with-nav-tabs.panel-default .nav-tabs>li.dropdown .dropdown-menu>li>a {_x000D_
  color: #777;_x000D_
}_x000D_
_x000D_
.with-nav-tabs.panel-default .nav-tabs>li.dropdown .dropdown-menu>li>a:hover,_x000D_
.with-nav-tabs.panel-default .nav-tabs>li.dropdown .dropdown-menu>li>a:focus {_x000D_
  background-color: #ddd;_x000D_
}_x000D_
_x000D_
.with-nav-tabs.panel-default .nav-tabs>li.dropdown .dropdown-menu>.active>a,_x000D_
.with-nav-tabs.panel-default .nav-tabs>li.dropdown .dropdown-menu>.active>a:hover,_x000D_
.with-nav-tabs.panel-default .nav-tabs>li.dropdown .dropdown-menu>.active>a:focus {_x000D_
  color: #fff;_x000D_
  background-color: #555;_x000D_
}_x000D_
_x000D_
_x000D_
/********************************************************************/_x000D_
_x000D_
_x000D_
/*** PANEL PRIMARY ***/_x000D_
_x000D_
.with-nav-tabs.panel-primary .nav-tabs>li>a,_x000D_
.with-nav-tabs.panel-primary .nav-tabs>li>a:hover,_x000D_
.with-nav-tabs.panel-primary .nav-tabs>li>a:focus {_x000D_
  color: #fff;_x000D_
}_x000D_
_x000D_
.with-nav-tabs.panel-primary .nav-tabs>.open>a,_x000D_
.with-nav-tabs.panel-primary .nav-tabs>.open>a:hover,_x000D_
.with-nav-tabs.panel-primary .nav-tabs>.open>a:focus,_x000D_
.with-nav-tabs.panel-primary .nav-tabs>li>a:hover,_x000D_
.with-nav-tabs.panel-primary .nav-tabs>li>a:focus {_x000D_
  color: #fff;_x000D_
  background-color: #3071a9;_x000D_
  border-color: transparent;_x000D_
}_x000D_
_x000D_
.with-nav-tabs.panel-primary .nav-tabs>li.active>a,_x000D_
.with-nav-tabs.panel-primary .nav-tabs>li.active>a:hover,_x000D_
.with-nav-tabs.panel-primary .nav-tabs>li.active>a:focus {_x000D_
  color: #428bca;_x000D_
  background-color: #fff;_x000D_
  border-color: #428bca;_x000D_
  border-bottom-color: transparent;_x000D_
}_x000D_
_x000D_
.with-nav-tabs.panel-primary .nav-tabs>li.dropdown .dropdown-menu {_x000D_
  background-color: #428bca;_x000D_
  border-color: #3071a9;_x000D_
}_x000D_
_x000D_
.with-nav-tabs.panel-primary .nav-tabs>li.dropdown .dropdown-menu>li>a {_x000D_
  color: #fff;_x000D_
}_x000D_
_x000D_
.with-nav-tabs.panel-primary .nav-tabs>li.dropdown .dropdown-menu>li>a:hover,_x000D_
.with-nav-tabs.panel-primary .nav-tabs>li.dropdown .dropdown-menu>li>a:focus {_x000D_
  background-color: #3071a9;_x000D_
}_x000D_
_x000D_
.with-nav-tabs.panel-primary .nav-tabs>li.dropdown .dropdown-menu>.active>a,_x000D_
.with-nav-tabs.panel-primary .nav-tabs>li.dropdown .dropdown-menu>.active>a:hover,_x000D_
.with-nav-tabs.panel-primary .nav-tabs>li.dropdown .dropdown-menu>.active>a:focus {_x000D_
  background-color: #4a9fe9;_x000D_
}_x000D_
_x000D_
_x000D_
/********************************************************************/_x000D_
_x000D_
_x000D_
/*** PANEL SUCCESS ***/_x000D_
_x000D_
.with-nav-tabs.panel-success .nav-tabs>li>a,_x000D_
.with-nav-tabs.panel-success .nav-tabs>li>a:hover,_x000D_
.with-nav-tabs.panel-success .nav-tabs>li>a:focus {_x000D_
  color: #3c763d;_x000D_
}_x000D_
_x000D_
.with-nav-tabs.panel-success .nav-tabs>.open>a,_x000D_
.with-nav-tabs.panel-success .nav-tabs>.open>a:hover,_x000D_
.with-nav-tabs.panel-success .nav-tabs>.open>a:focus,_x000D_
.with-nav-tabs.panel-success .nav-tabs>li>a:hover,_x000D_
.with-nav-tabs.panel-success .nav-tabs>li>a:focus {_x000D_
  color: #3c763d;_x000D_
  background-color: #d6e9c6;_x000D_
  border-color: transparent;_x000D_
}_x000D_
_x000D_
.with-nav-tabs.panel-success .nav-tabs>li.active>a,_x000D_
.with-nav-tabs.panel-success .nav-tabs>li.active>a:hover,_x000D_
.with-nav-tabs.panel-success .nav-tabs>li.active>a:focus {_x000D_
  color: #3c763d;_x000D_
  background-color: #fff;_x000D_
  border-color: #d6e9c6;_x000D_
  border-bottom-color: transparent;_x000D_
}_x000D_
_x000D_
.with-nav-tabs.panel-success .nav-tabs>li.dropdown .dropdown-menu {_x000D_
  background-color: #dff0d8;_x000D_
  border-color: #d6e9c6;_x000D_
}_x000D_
_x000D_
.with-nav-tabs.panel-success .nav-tabs>li.dropdown .dropdown-menu>li>a {_x000D_
  color: #3c763d;_x000D_
}_x000D_
_x000D_
.with-nav-tabs.panel-success .nav-tabs>li.dropdown .dropdown-menu>li>a:hover,_x000D_
.with-nav-tabs.panel-success .nav-tabs>li.dropdown .dropdown-menu>li>a:focus {_x000D_
  background-color: #d6e9c6;_x000D_
}_x000D_
_x000D_
.with-nav-tabs.panel-success .nav-tabs>li.dropdown .dropdown-menu>.active>a,_x000D_
.with-nav-tabs.panel-success .nav-tabs>li.dropdown .dropdown-menu>.active>a:hover,_x000D_
.with-nav-tabs.panel-success .nav-tabs>li.dropdown .dropdown-menu>.active>a:focus {_x000D_
  color: #fff;_x000D_
  background-color: #3c763d;_x000D_
}_x000D_
_x000D_
_x000D_
/********************************************************************/_x000D_
_x000D_
_x000D_
/*** PANEL INFO ***/_x000D_
_x000D_
.with-nav-tabs.panel-info .nav-tabs>li>a,_x000D_
.with-nav-tabs.panel-info .nav-tabs>li>a:hover,_x000D_
.with-nav-tabs.panel-info .nav-tabs>li>a:focus {_x000D_
  color: #31708f;_x000D_
}_x000D_
_x000D_
.with-nav-tabs.panel-info .nav-tabs>.open>a,_x000D_
.with-nav-tabs.panel-info .nav-tabs>.open>a:hover,_x000D_
.with-nav-tabs.panel-info .nav-tabs>.open>a:focus,_x000D_
.with-nav-tabs.panel-info .nav-tabs>li>a:hover,_x000D_
.with-nav-tabs.panel-info .nav-tabs>li>a:focus {_x000D_
  color: #31708f;_x000D_
  background-color: #bce8f1;_x000D_
  border-color: transparent;_x000D_
}_x000D_
_x000D_
.with-nav-tabs.panel-info .nav-tabs>li.active>a,_x000D_
.with-nav-tabs.panel-info .nav-tabs>li.active>a:hover,_x000D_
.with-nav-tabs.panel-info .nav-tabs>li.active>a:focus {_x000D_
  color: #31708f;_x000D_
  background-color: #fff;_x000D_
  border-color: #bce8f1;_x000D_
  border-bottom-color: transparent;_x000D_
}_x000D_
_x000D_
.with-nav-tabs.panel-info .nav-tabs>li.dropdown .dropdown-menu {_x000D_
  background-color: #d9edf7;_x000D_
  border-color: #bce8f1;_x000D_
}_x000D_
_x000D_
.with-nav-tabs.panel-info .nav-tabs>li.dropdown .dropdown-menu>li>a {_x000D_
  color: #31708f;_x000D_
}_x000D_
_x000D_
.with-nav-tabs.panel-info .nav-tabs>li.dropdown .dropdown-menu>li>a:hover,_x000D_
.with-nav-tabs.panel-info .nav-tabs>li.dropdown .dropdown-menu>li>a:focus {_x000D_
  background-color: #bce8f1;_x000D_
}_x000D_
_x000D_
.with-nav-tabs.panel-info .nav-tabs>li.dropdown .dropdown-menu>.active>a,_x000D_
.with-nav-tabs.panel-info .nav-tabs>li.dropdown .dropdown-menu>.active>a:hover,_x000D_
.with-nav-tabs.panel-info .nav-tabs>li.dropdown .dropdown-menu>.active>a:focus {_x000D_
  color: #fff;_x000D_
  background-color: #31708f;_x000D_
}_x000D_
_x000D_
_x000D_
/********************************************************************/_x000D_
_x000D_
_x000D_
/*** PANEL WARNING ***/_x000D_
_x000D_
.with-nav-tabs.panel-warning .nav-tabs>li>a,_x000D_
.with-nav-tabs.panel-warning .nav-tabs>li>a:hover,_x000D_
.with-nav-tabs.panel-warning .nav-tabs>li>a:focus {_x000D_
  color: #8a6d3b;_x000D_
}_x000D_
_x000D_
.with-nav-tabs.panel-warning .nav-tabs>.open>a,_x000D_
.with-nav-tabs.panel-warning .nav-tabs>.open>a:hover,_x000D_
.with-nav-tabs.panel-warning .nav-tabs>.open>a:focus,_x000D_
.with-nav-tabs.panel-warning .nav-tabs>li>a:hover,_x000D_
.with-nav-tabs.panel-warning .nav-tabs>li>a:focus {_x000D_
  color: #8a6d3b;_x000D_
  background-color: #faebcc;_x000D_
  border-color: transparent;_x000D_
}_x000D_
_x000D_
.with-nav-tabs.panel-warning .nav-tabs>li.active>a,_x000D_
.with-nav-tabs.panel-warning .nav-tabs>li.active>a:hover,_x000D_
.with-nav-tabs.panel-warning .nav-tabs>li.active>a:focus {_x000D_
  color: #8a6d3b;_x000D_
  background-color: #fff;_x000D_
  border-color: #faebcc;_x000D_
  border-bottom-color: transparent;_x000D_
}_x000D_
_x000D_
.with-nav-tabs.panel-warning .nav-tabs>li.dropdown .dropdown-menu {_x000D_
  background-color: #fcf8e3;_x000D_
  border-color: #faebcc;_x000D_
}_x000D_
_x000D_
.with-nav-tabs.panel-warning .nav-tabs>li.dropdown .dropdown-menu>li>a {_x000D_
  color: #8a6d3b;_x000D_
}_x000D_
_x000D_
.with-nav-tabs.panel-warning .nav-tabs>li.dropdown .dropdown-menu>li>a:hover,_x000D_
.with-nav-tabs.panel-warning .nav-tabs>li.dropdown .dropdown-menu>li>a:focus {_x000D_
  background-color: #faebcc;_x000D_
}_x000D_
_x000D_
.with-nav-tabs.panel-warning .nav-tabs>li.dropdown .dropdown-menu>.active>a,_x000D_
.with-nav-tabs.panel-warning .nav-tabs>li.dropdown .dropdown-menu>.active>a:hover,_x000D_
.with-nav-tabs.panel-warning .nav-tabs>li.dropdown .dropdown-menu>.active>a:focus {_x000D_
  color: #fff;_x000D_
  background-color: #8a6d3b;_x000D_
}_x000D_
_x000D_
_x000D_
/********************************************************************/_x000D_
_x000D_
_x000D_
/*** PANEL DANGER ***/_x000D_
_x000D_
.with-nav-tabs.panel-danger .nav-tabs>li>a,_x000D_
.with-nav-tabs.panel-danger .nav-tabs>li>a:hover,_x000D_
.with-nav-tabs.panel-danger .nav-tabs>li>a:focus {_x000D_
  color: #a94442;_x000D_
}_x000D_
_x000D_
.with-nav-tabs.panel-danger .nav-tabs>.open>a,_x000D_
.with-nav-tabs.panel-danger .nav-tabs>.open>a:hover,_x000D_
.with-nav-tabs.panel-danger .nav-tabs>.open>a:focus,_x000D_
.with-nav-tabs.panel-danger .nav-tabs>li>a:hover,_x000D_
.with-nav-tabs.panel-danger .nav-tabs>li>a:focus {_x000D_
  color: #a94442;_x000D_
  background-color: #ebccd1;_x000D_
  border-color: transparent;_x000D_
}_x000D_
_x000D_
.with-nav-tabs.panel-danger .nav-tabs>li.active>a,_x000D_
.with-nav-tabs.panel-danger .nav-tabs>li.active>a:hover,_x000D_
.with-nav-tabs.panel-danger .nav-tabs>li.active>a:focus {_x000D_
  color: #a94442;_x000D_
  background-color: #fff;_x000D_
  border-color: #ebccd1;_x000D_
  border-bottom-color: transparent;_x000D_
}_x000D_
_x000D_
.with-nav-tabs.panel-danger .nav-tabs>li.dropdown .dropdown-menu {_x000D_
  background-color: #f2dede;_x000D_
  /* bg color */_x000D_
  border-color: #ebccd1;_x000D_
  /* border color */_x000D_
}_x000D_
_x000D_
.with-nav-tabs.panel-danger .nav-tabs>li.dropdown .dropdown-menu>li>a {_x000D_
  color: #a94442;_x000D_
  /* normal text color */_x000D_
}_x000D_
_x000D_
.with-nav-tabs.panel-danger .nav-tabs>li.dropdown .dropdown-menu>li>a:hover,_x000D_
.with-nav-tabs.panel-danger .nav-tabs>li.dropdown .dropdown-menu>li>a:focus {_x000D_
  background-color: #ebccd1;_x000D_
  /* hover bg color */_x000D_
}_x000D_
_x000D_
.with-nav-tabs.panel-danger .nav-tabs>li.dropdown .dropdown-menu>.active>a,_x000D_
.with-nav-tabs.panel-danger .nav-tabs>li.dropdown .dropdown-menu>.active>a:hover,_x000D_
.with-nav-tabs.panel-danger .nav-tabs>li.dropdown .dropdown-menu>.active>a:focus {_x000D_
  color: #fff;_x000D_
  /* active text color */_x000D_
  background-color: #a94442;_x000D_
  /* active bg color */_x000D_
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<link href="//netdna.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css" rel="stylesheet" id="bootstrap-css">_x000D_
<script src="//netdna.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.min.js"></script>_x000D_
<!------ Include the above in your HEAD tag ---------->_x000D_
_x000D_
<div class="container">_x000D_
  <div class="page-header">_x000D_
    <h1>Panels with nav tabs.<span class="pull-right label label-default">:)</span></h1>_x000D_
  </div>_x000D_
  <div class="row">_x000D_
    <div class="col-md-6">_x000D_
      <div class="panel with-nav-tabs panel-default">_x000D_
        <div class="panel-heading">_x000D_
          <ul class="nav nav-tabs">_x000D_
            <li class="active"><a href="#tab1default" data-toggle="tab">Default 1</a></li>_x000D_
            <li><a href="#tab2default" data-toggle="tab">Default 2</a></li>_x000D_
            <li><a href="#tab3default" data-toggle="tab">Default 3</a></li>_x000D_
            <li class="dropdown">_x000D_
              <a href="#" data-toggle="dropdown">Dropdown <span class="caret"></span></a>_x000D_
              <ul class="dropdown-menu" role="menu">_x000D_
                <li><a href="#tab4default" data-toggle="tab">Default 4</a></li>_x000D_
                <li><a href="#tab5default" data-toggle="tab">Default 5</a></li>_x000D_
              </ul>_x000D_
            </li>_x000D_
          </ul>_x000D_
        </div>_x000D_
        <div class="panel-body">_x000D_
          <div class="tab-content">_x000D_
            <div class="tab-pane fade in active" id="tab1default">Default 1</div>_x000D_
            <div class="tab-pane fade" id="tab2default">Default 2</div>_x000D_
            <div class="tab-pane fade" id="tab3default">Default 3</div>_x000D_
            <div class="tab-pane fade" id="tab4default">Default 4</div>_x000D_
            <div class="tab-pane fade" id="tab5default">Default 5</div>_x000D_
          </div>_x000D_
        </div>_x000D_
      </div>_x000D_
    </div>_x000D_
    <div class="col-md-6">_x000D_
      <div class="panel with-nav-tabs panel-primary">_x000D_
        <div class="panel-heading">_x000D_
          <ul class="nav nav-tabs">_x000D_
            <li class="active"><a href="#tab1primary" data-toggle="tab">Primary 1</a></li>_x000D_
            <li><a href="#tab2primary" data-toggle="tab">Primary 2</a></li>_x000D_
            <li><a href="#tab3primary" data-toggle="tab">Primary 3</a></li>_x000D_
            <li class="dropdown">_x000D_
              <a href="#" data-toggle="dropdown">Dropdown <span class="caret"></span></a>_x000D_
              <ul class="dropdown-menu" role="menu">_x000D_
                <li><a href="#tab4primary" data-toggle="tab">Primary 4</a></li>_x000D_
                <li><a href="#tab5primary" data-toggle="tab">Primary 5</a></li>_x000D_
              </ul>_x000D_
            </li>_x000D_
          </ul>_x000D_
        </div>_x000D_
        <div class="panel-body">_x000D_
          <div class="tab-content">_x000D_
            <div class="tab-pane fade in active" id="tab1primary">Primary 1</div>_x000D_
            <div class="tab-pane fade" id="tab2primary">Primary 2</div>_x000D_
            <div class="tab-pane fade" id="tab3primary">Primary 3</div>_x000D_
            <div class="tab-pane fade" id="tab4primary">Primary 4</div>_x000D_
            <div class="tab-pane fade" id="tab5primary">Primary 5</div>_x000D_
          </div>_x000D_
        </div>_x000D_
      </div>_x000D_
    </div>_x000D_
  </div>_x000D_
</div>_x000D_
<div class="container">_x000D_
  <div class="row">_x000D_
    <div class="col-md-6">_x000D_
      <div class="panel with-nav-tabs panel-success">_x000D_
        <div class="panel-heading">_x000D_
          <ul class="nav nav-tabs">_x000D_
            <li class="active"><a href="#tab1success" data-toggle="tab">Success 1</a></li>_x000D_
            <li><a href="#tab2success" data-toggle="tab">Success 2</a></li>_x000D_
            <li><a href="#tab3success" data-toggle="tab">Success 3</a></li>_x000D_
            <li class="dropdown">_x000D_
              <a href="#" data-toggle="dropdown">Dropdown <span class="caret"></span></a>_x000D_
              <ul class="dropdown-menu" role="menu">_x000D_
                <li><a href="#tab4success" data-toggle="tab">Success 4</a></li>_x000D_
                <li><a href="#tab5success" data-toggle="tab">Success 5</a></li>_x000D_
              </ul>_x000D_
            </li>_x000D_
          </ul>_x000D_
        </div>_x000D_
        <div class="panel-body">_x000D_
          <div class="tab-content">_x000D_
            <div class="tab-pane fade in active" id="tab1success">Success 1</div>_x000D_
            <div class="tab-pane fade" id="tab2success">Success 2</div>_x000D_
            <div class="tab-pane fade" id="tab3success">Success 3</div>_x000D_
            <div class="tab-pane fade" id="tab4success">Success 4</div>_x000D_
            <div class="tab-pane fade" id="tab5success">Success 5</div>_x000D_
          </div>_x000D_
        </div>_x000D_
      </div>_x000D_
    </div>_x000D_
    <div class="col-md-6">_x000D_
      <div class="panel with-nav-tabs panel-info">_x000D_
        <div class="panel-heading">_x000D_
          <ul class="nav nav-tabs">_x000D_
            <li class="active"><a href="#tab1info" data-toggle="tab">Info 1</a></li>_x000D_
            <li><a href="#tab2info" data-toggle="tab">Info 2</a></li>_x000D_
            <li><a href="#tab3info" data-toggle="tab">Info 3</a></li>_x000D_
            <li class="dropdown">_x000D_
              <a href="#" data-toggle="dropdown">Dropdown <span class="caret"></span></a>_x000D_
              <ul class="dropdown-menu" role="menu">_x000D_
                <li><a href="#tab4info" data-toggle="tab">Info 4</a></li>_x000D_
                <li><a href="#tab5info" data-toggle="tab">Info 5</a></li>_x000D_
              </ul>_x000D_
            </li>_x000D_
          </ul>_x000D_
        </div>_x000D_
        <div class="panel-body">_x000D_
          <div class="tab-content">_x000D_
            <div class="tab-pane fade in active" id="tab1info">Info 1</div>_x000D_
            <div class="tab-pane fade" id="tab2info">Info 2</div>_x000D_
            <div class="tab-pane fade" id="tab3info">Info 3</div>_x000D_
            <div class="tab-pane fade" id="tab4info">Info 4</div>_x000D_
            <div class="tab-pane fade" id="tab5info">Info 5</div>_x000D_
          </div>_x000D_
        </div>_x000D_
      </div>_x000D_
    </div>_x000D_
  </div>_x000D_
</div>_x000D_
<div class="container">_x000D_
  <div class="row">_x000D_
    <div class="col-md-6">_x000D_
      <div class="panel with-nav-tabs panel-warning">_x000D_
        <div class="panel-heading">_x000D_
          <ul class="nav nav-tabs">_x000D_
            <li class="active"><a href="#tab1warning" data-toggle="tab">Warning 1</a></li>_x000D_
            <li><a href="#tab2warning" data-toggle="tab">Warning 2</a></li>_x000D_
            <li><a href="#tab3warning" data-toggle="tab">Warning 3</a></li>_x000D_
            <li class="dropdown">_x000D_
              <a href="#" data-toggle="dropdown">Dropdown <span class="caret"></span></a>_x000D_
              <ul class="dropdown-menu" role="menu">_x000D_
                <li><a href="#tab4warning" data-toggle="tab">Warning 4</a></li>_x000D_
                <li><a href="#tab5warning" data-toggle="tab">Warning 5</a></li>_x000D_
              </ul>_x000D_
            </li>_x000D_
          </ul>_x000D_
        </div>_x000D_
        <div class="panel-body">_x000D_
          <div class="tab-content">_x000D_
            <div class="tab-pane fade in active" id="tab1warning">Warning 1</div>_x000D_
            <div class="tab-pane fade" id="tab2warning">Warning 2</div>_x000D_
            <div class="tab-pane fade" id="tab3warning">Warning 3</div>_x000D_
            <div class="tab-pane fade" id="tab4warning">Warning 4</div>_x000D_
            <div class="tab-pane fade" id="tab5warning">Warning 5</div>_x000D_
          </div>_x000D_
        </div>_x000D_
      </div>_x000D_
    </div>_x000D_
    <div class="col-md-6">_x000D_
      <div class="panel with-nav-tabs panel-danger">_x000D_
        <div class="panel-heading">_x000D_
          <ul class="nav nav-tabs">_x000D_
            <li class="active"><a href="#tab1danger" data-toggle="tab">Danger 1</a></li>_x000D_
            <li><a href="#tab2danger" data-toggle="tab">Danger 2</a></li>_x000D_
            <li><a href="#tab3danger" data-toggle="tab">Danger 3</a></li>_x000D_
            <li class="dropdown">_x000D_
              <a href="#" data-toggle="dropdown">Dropdown <span class="caret"></span></a>_x000D_
              <ul class="dropdown-menu" role="menu">_x000D_
                <li><a href="#tab4danger" data-toggle="tab">Danger 4</a></li>_x000D_
                <li><a href="#tab5danger" data-toggle="tab">Danger 5</a></li>_x000D_
              </ul>_x000D_
            </li>_x000D_
          </ul>_x000D_
        </div>_x000D_
        <div class="panel-body">_x000D_
          <div class="tab-content">_x000D_
            <div class="tab-pane fade in active" id="tab1danger">Danger 1</div>_x000D_
            <div class="tab-pane fade" id="tab2danger">Danger 2</div>_x000D_
            <div class="tab-pane fade" id="tab3danger">Danger 3</div>_x000D_
            <div class="tab-pane fade" id="tab4danger">Danger 4</div>_x000D_
            <div class="tab-pane fade" id="tab5danger">Danger 5</div>_x000D_
          </div>_x000D_
        </div>_x000D_
      </div>_x000D_
    </div>_x000D_
  </div>_x000D_
</div>_x000D_
<br/>
_x000D_
_x000D_
_x000D_

Parse error: syntax error, unexpected T_ECHO in

Missing ; after var_dump($row)

ROW_NUMBER() in MySQL

Also a bit late but today I had the same need so I did search on Google and finally a simple general approach found here in Pinal Dave's article http://blog.sqlauthority.com/2014/03/09/mysql-reset-row-number-for-each-group-partition-by-row-number/

I wanted to focus on Paul's original question (that was my problem as well) so I summarize my solution as a working example.

Beacuse we want to partition over two column I would create a SET variable during the iteration to identify if a new group was started.

SELECT col1, col2, col3 FROM (
  SELECT col1, col2, col3,
         @n := CASE WHEN @v = MAKE_SET(3, col1, col2)
                    THEN @n + 1 -- if we are in the same group
                    ELSE 1 -- next group starts so we reset the counter
                END AS row_number,
         @v := MAKE_SET(3, col1, col2) -- we store the current value for next iteration
    FROM Table1, (SELECT @n := 0, @v := NULL) r -- helper table for iteration with startup values
   ORDER BY col1, col2, col3 DESC -- because we want the row with maximum value
) x WHERE row_number = 1 -- and here we select exactly the wanted row from each group

The 3 means at the first parameter of MAKE_SET that I want both value in the SET (3=1|2). Of course if we do not have two or more columns constructing the groups we can eliminate the MAKE_SET operation. The construction is exactly the same. This is working for me as required. Many thanks to Pinal Dave for his clear demonstration.

Android Studio Gradle Already disposed Module

I figured out this problem by:

  1. ./gradlew clean
  2. Restart Android Studio

How to use JavaScript variables in jQuery selectors?

var x = $(this).attr("name");
$("#" + x).hide();

Using number as "index" (JSON)

JSON regulates key type to be string. The purpose is to support the dot notation to access the members of the object.

For example, person = {"height":170, "weight":60, "age":32}. You can access members by person.height, person.weight, etc. If JSON supports value keys, then it would look like person.0, person.1, person.2.

How can I change the default Mysql connection timeout when connecting through python?

I know this is an old question but just for the record this can also be done by passing appropriate connection options as arguments to the _mysql.connect call. For example,

con = _mysql.connect(host='localhost', user='dell-pc', passwd='', db='test',
          connect_timeout=1000)

Notice the use of keyword parameters (host, passwd, etc.). They improve the readability of your code.

For detail about different arguments that you can pass to _mysql.connect, see MySQLdb API documentation

An example of how to use getopts in bash

The example packaged with getopt (my distro put it in /usr/share/getopt/getopt-parse.bash) looks like it covers all of your cases:

#!/bin/bash

# A small example program for using the new getopt(1) program.
# This program will only work with bash(1)
# An similar program using the tcsh(1) script language can be found
# as parse.tcsh

# Example input and output (from the bash prompt):
# ./parse.bash -a par1 'another arg' --c-long 'wow!*\?' -cmore -b " very long "
# Option a
# Option c, no argument
# Option c, argument `more'
# Option b, argument ` very long '
# Remaining arguments:
# --> `par1'
# --> `another arg'
# --> `wow!*\?'

# Note that we use `"$@"' to let each command-line parameter expand to a 
# separate word. The quotes around `$@' are essential!
# We need TEMP as the `eval set --' would nuke the return value of getopt.
TEMP=`getopt -o ab:c:: --long a-long,b-long:,c-long:: \
     -n 'example.bash' -- "$@"`

if [ $? != 0 ] ; then echo "Terminating..." >&2 ; exit 1 ; fi

# Note the quotes around `$TEMP': they are essential!
eval set -- "$TEMP"

while true ; do
    case "$1" in
        -a|--a-long) echo "Option a" ; shift ;;
        -b|--b-long) echo "Option b, argument \`$2'" ; shift 2 ;;
        -c|--c-long) 
            # c has an optional argument. As we are in quoted mode,
            # an empty parameter will be generated if its optional
            # argument is not found.
            case "$2" in
                "") echo "Option c, no argument"; shift 2 ;;
                *)  echo "Option c, argument \`$2'" ; shift 2 ;;
            esac ;;
        --) shift ; break ;;
        *) echo "Internal error!" ; exit 1 ;;
    esac
done
echo "Remaining arguments:"
for arg do echo '--> '"\`$arg'" ; done

Eclipse plugin for generating a class diagram

Try eUML2. its a single click generator no need to drag n drop.

Array Length in Java

`

int array[]=new int[3]; array.length;

so here we have created an array with a memory space of 3... this is how it looks actually

0th 1st 2nd ...........> Index 2 4 5 ...........> Number

So as u see the size of this array is 3 but the index of array is only up to 2 since any array starts with 0th index.

second statement' output shall be 3 since the length of the array is 3... Please don't get confused between the index value and the length of the array....

cheers!

Error when checking Java version: could not find java.dll

Reinstall JDK and set system variable JAVA_HOME on your JDK. (e.g. C:\tools\jdk7)
And add JAVA_HOME variable to your PATH system variable

Type in command line

echo %JAVA_HOME%

and

java -version

To verify whether your installation was done successfully.


This problem generally occurs in Windows when your "Java Runtime Environment" registry entry is missing or mismatched with the installed JDK. The mismatch can be due to multiple JDKs.

Steps to resolve:

  1. Open the Run window:

    Press windows+R

  2. Open registry window:

    Type regedit and enter.

  3. Go to: \HKEY_LOCAL_MACHINE\SOFTWARE\JavaSoft\

  4. If Java Runtime Environment is not present inside JavaSoft, then create a new Key and give the name Java Runtime Environment.

  5. For Java Runtime Environment create "CurrentVersion" String Key and give appropriate version as value:

JRE regedit entry

  1. Create a new subkey of 1.8.

  2. For 1.8 create a String Key with name JavaHome with the value of JRE home:

    JRE regedit entry 2

Ref: https://mybindirectory.blogspot.com/2019/05/error-could-not-find-javadll.html

Using sed and grep/egrep to search and replace

try something using a for loop

 for i in `egrep -lR "YOURSEARCH" .` ; do echo  $i; sed 's/f/k/' <$i >/tmp/`basename $i`; mv /tmp/`basename $i` $i; done

not pretty, but should do.

How to get element by classname or id

@tasseKATT's Answer is great, but if you don't want to make a directive, why not use $document?

.controller('ExampleController', ['$scope', '$document', function($scope, $document) {
  var dumb = function (id) {
  var queryResult = $document[0].getElementById(id)
  var wrappedID = angular.element(queryResult);
  return wrappedID;
};

PLUNKR

node.js: read a text file into an array. (Each line an item in the array.)

i just want to add @finbarr great answer, a little fix in the asynchronous example:

Asynchronous:

var fs = require('fs');
fs.readFile('file.txt', function(err, data) {
    if(err) throw err;
    var array = data.toString().split("\n");
    for(i in array) {
        console.log(array[i]);
    }
    done();
});

@MadPhysicist, done() is what releases the async. call.

Simple excel find and replace for formulas

You can also click on the Formulas tab in Excel and select Show Formulas, then use the regular "Find" and "Replace" function. This should not affect the rest of your formula.

Html.RenderPartial() syntax with Razor

Html.RenderPartial() is a void method - you can check whether a method is a void method by placing your mouse over the call to RenderPartial in your code and you will see the text (extension) void HtmlHelper.RenderPartial...

Void methods require a semicolon at the end of the calling code.

In the Webforms view engine you would have encased your Html.RenderPartial() call within the bee stings <% %>

like so

<% Html.RenderPartial("Path/to/my/partial/view"); %>

when you are using the Razor view engine the equivalent is

@{Html.RenderPartial("Path/to/my/partial/view");}

Iterating through all the cells in Excel VBA or VSTO 2005

For a VB or C# app, one way to do this is by using Office Interop. This depends on which version of Excel you're working with.

For Excel 2003, this MSDN article is a good place to start. Understanding the Excel Object Model from a Visual Studio 2005 Developer's Perspective

You'll basically need to do the following:

  • Start the Excel application.
  • Open the Excel workbook.
  • Retrieve the worksheet from the workbook by name or index.
  • Iterate through all the Cells in the worksheet which were retrieved as a range.
  • Sample (untested) code excerpt below for the last step.

    Excel.Range allCellsRng;
    string lowerRightCell = "IV65536";
    allCellsRng = ws.get_Range("A1", lowerRightCell).Cells;
    foreach (Range cell in allCellsRng)
    {
        if (null == cell.Value2 || isBlank(cell.Value2))
        {
          // Do something.
        }
        else if (isText(cell.Value2))
        {
          // Do something.
        }
        else if (isNumeric(cell.Value2))
        {
          // Do something.
        }
    }

For Excel 2007, try this MSDN reference.

Export database schema into SQL file

You can generate scripts to a file via SQL Server Management Studio, here are the steps:

  1. Right click the database you want to generate scripts for (not the table) and select tasks - generate scripts
  2. Next, select the requested table/tables, views, stored procedures, etc (from select specific database objects)
  3. Click advanced - select the types of data to script
  4. Click Next and finish

MSDN Generate Scripts

When generating the scripts, there is an area that will allow you to script, constraints, keys, etc. From SQL Server 2008 R2 there is an Advanced Option under scripting:

enter image description here

Could not open input file: artisan

After struggling with this issue, I found out that you need to find where artisan resides by running sudo find / -name artisan, and from there run the command php artisan ....

Converting HTML to Excel?

We copy/paste html pages from our ERP to Excel using "paste special.. as html/unicode" and it works quite well with tables.

Appending a vector to a vector

a.insert(a.end(), b.begin(), b.end());

or

a.insert(std::end(a), std::begin(b), std::end(b));

The second variant is a more generically applicable solution, as b could also be an array. However, it requires C++11. If you want to work with user-defined types, use ADL:

using std::begin, std::end;
a.insert(end(a), begin(b), end(b));

How to reset (clear) form through JavaScript?

form.reset() is a DOM element method (not one on the jQuery object), so you need:

$("#client.frm")[0].reset();
//faster version:
$("#client")[0].reset();

Or without jQuery:

document.getElementById("client").reset();

How do you execute SQL from within a bash script?

I've used the jdbcsql project on Sourceforge.

On *nix systems, this will create a csv stream of results to standard out:

java -Djava.security.egd=file///dev/urandom -jar jdbcsql.jar -d oracledb_SID -h $host -p 1521 -U some_username -m oracle -P "$PW" -f excel -s "," "$1"

Note that adding the -Djava.security.egd=file///dev/urandom increases performance greatly

Windows commands are similar: see http://jdbcsql.sourceforge.net/

Xcode: Could not locate device support files

  1. Download & mount http://adcdownload.apple.com/Developer_Tools/Xcode_7.3.1/Xcode_7.3.1.dmg I was first wandered if it could be mounted directly through hdiutil attach and looks like it could but not for everyone's accounts.

  2. Open to see its content and copy Contents/Developer/Platforms/iPhoneOS.platform/DeviceSupport/7.1 to same path into Xcode application directory.

  3. Restart Xcode

Turn off axes in subplots

import matplotlib.pyplot as plt

fig, ax = plt.subplots(2, 2)


To turn off axes for all subplots, do either:

[axi.set_axis_off() for axi in ax.ravel()]

or

map(lambda axi: axi.set_axis_off(), ax.ravel())

What's the difference between window.location= and window.location.replace()?

window.location adds an item to your history in that you can (or should be able to) click "Back" and go back to the current page.

window.location.replace replaces the current history item so you can't go back to it.

See window.location:

assign(url): Load the document at the provided URL.

replace(url):Replace the current document with the one at the provided URL. The difference from the assign() method is that after using replace() the current page will not be saved in session history, meaning the user won't be able to use the Back button to navigate to it.

Oh and generally speaking:

window.location.href = url;

is favoured over:

window.location = url;

Remove plot axis values

Change the axis_colour to match the background and if you are modifying the background dynamically you will need to update the axis_colour simultaneously. * The shared picture shows the graph/plot example using mock data ()

### Main Plotting Function ###
plotXY <- function(time, value){

    ### Plot Style Settings ###

    ### default bg is white, set it the same as the axis-colour 
    background <- "white"

    ### default col.axis is black, set it the same as the background to match
    axis_colour <- "white"

    plot_title <- "Graph it!"
    xlabel <- "Time"
    ylabel <- "Value"
    label_colour <- "black"
    label_scale <- 2
    axis_scale <- 2
    symbol_scale <- 2
    title_scale <- 2
    subtitle_scale <- 2
    # point style 16 is a black dot
    point <- 16 
    # p - points, l - line, b - both
    plot_type <- "b"

    plot(time, value, main=plot_title, cex=symbol_scale, cex.lab=label_scale, cex.axis=axis_scale, cex.main=title_scale, cex.sub=subtitle_scale, xlab=xlabel, ylab=ylabel, col.lab=label_colour, col.axis=axis_colour, bg=background, pch=point, type=plot_type)
}

plotXY(time, value)

enter image description here

Export to CSV using MVC, C# and jQuery

In addition to Biff MaGriff's answer. To export the file using JQuery, redirect the user to a new page.

$('#btn_export').click(function () {
    window.location.href = 'NewsLetter/Export';
});

Current user in Magento?

Found under "app/code/core/Mage/Page/Block/Html/Header.php":

public function getWelcome()
{
    if (empty($this->_data['welcome'])) {
        if (Mage::app()->isInstalled() && Mage::getSingleton('customer/session')->isLoggedIn()) {
            $this->_data['welcome'] = $this->__('Welcome, %s!', Mage::getSingleton('customer/session')->getCustomer()->getName());
        } else {
            $this->_data['welcome'] = Mage::getStoreConfig('design/header/welcome');
        }
    }

    return $this->_data['welcome'];
}

So it looks like Mage::getSingleton('customer/session')->getCustomer() will get your current logged in customer ;)

To get the currently logged in admin:

Mage::getSingleton('admin/session')->getUser();

Get the first element of an array

Some arrays don't work with functions like list, reset or current. Maybe they're "faux" arrays - partially implementing ArrayIterator, for example.

If you want to pull the first value regardless of the array, you can short-circuit an iterator:

foreach($array_with_unknown_keys as $value) break;

Your value will then be available in $value and the loop will break after the first iteration. This is more efficient than copying a potentially large array to a function like array_unshift(array_values($arr)).

You can grab the key this way too:

foreach($array_with_unknown_keys as $key=>$value) break;

If you're calling this from a function, simply return early:

function grab_first($arr) {
    foreach($arr as $value) return $value;
}

Python pandas: fill a dataframe row by row

This is a simpler version

import pandas as pd
df = pd.DataFrame(columns=('col1', 'col2', 'col3'))
for i in range(5):
   df.loc[i] = ['<some value for first>','<some value for second>','<some value for third>']`

How to refresh Android listview?

For me after changing information in sql database nothing could refresh list view( to be specific expandable list view) so if notifyDataSetChanged() doesn't help, you can try to clear your list first and add it again after that call notifyDataSetChanged(). For example

private List<List<SomeNewArray>> arrayList;
List<SomeNewArray> array1= getArrayList(...);
List<SomeNewArray> array2= getArrayList(...);
arrayList.clear();
arrayList.add(array1);
arrayList.add(array2);
notifyDataSetChanged();

Hope it makes sense for you.

How to iterate through two lists in parallel?

You can bundle the nth elements into a tuple or list using comprehension, then pass them out with a generator function.

def iterate_multi(*lists):
    for i in range(min(map(len,lists))):
        yield tuple(l[i] for l in lists)

for l1, l2, l3 in iterate_multi([1,2,3],[4,5,6],[7,8,9]):
    print(str(l1)+","+str(l2)+","+str(l3))

How do I get the size of a java.sql.ResultSet?

I got an exception when using rs.last()

if(rs.last()){
    rowCount = rs.getRow(); 
    rs.beforeFirst();
}

:

java.sql.SQLException: Invalid operation for forward only resultset

it's due to by default it is ResultSet.TYPE_FORWARD_ONLY, which means you can only use rs.next()

the solution is:

stmt=conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
    ResultSet.CONCUR_READ_ONLY); 

LDAP server which is my base dn

The base dn is dc=example,dc=com.

I don't know about openca, but I will try this answer since you got very little traffic so far.

A base dn is the point from where a server will search for users. So I would try to simply use admin as a login name.

If openca behaves like most ldap aware applications, this is what is going to happen :

  1. An ldap search for the user admin will be done by the server starting at the base dn (dc=example,dc=com).
  2. When the user is found, the full dn (cn=admin,dc=example,dc=com) will be used to bind with the supplied password.
  3. The ldap server will hash the password and compare with the stored hash value. If it matches, you're in.

Getting step 1 right is the hardest part, but mostly because we don't get to do it often. Things you have to look out for in your configuraiton file are :

  • The dn your application will use to bind to the ldap server. This happens at application startup, before any user comes to authenticate. You will have to supply a full dn, maybe something like cn=admin,dc=example,dc=com.
  • The authentication method. It is usually a "simple bind".
  • The user search filter. Look at the attribute named objectClass for your admin user. It will be either inetOrgPerson or user. There will be others like top, you can ignore them. In your openca configuration, there should be a string like (objectClass=inetOrgPerson). Whatever it is, make sure it matches your admin user's object Class. You can specify two object class with this search filter (|(objectClass=inetOrgPerson)(objectClass=user)).

Download an LDAP Browser, such as Apache's Directory Studio. Connect using your application's credentials, so you will see what your application sees.

How to stop and restart memcached server?

if linux

if install by apt-get

service memcached stop
service memcached restart

if install by source code

Usage: /etc/init.d/memcached {start|stop|restart|force-reload|status}

can also simply kill $pid to stop

How can I control the speed that bootstrap carousel slides in items?

One thing I noticed is that Bootstrap 3 is adding the styles with both a .6s and 0.6s. So you may need to explicitly define your transition duration like this (CSS)

    .carousel-inner>.item {
    -webkit-transition: 0.9s ease-in-out left;
    transition: 0.9s ease-in-out left;
    -webkit-transition: 0.9s, ease-in-out, left;
    -moz-transition: .9s, ease-in-out, left;
    -o-transition: .9s, ease-in-out, left;
    transition: .9s, ease-in-out, left;
    }

How to Disable GUI Button in Java

import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Dimension;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.BoxLayout;
import javax.swing.JSeparator;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;


public class IPGUI extends JFrame implements ActionListener 
{
    private static JPanel contentPane;

    private JButton btnConvertDocuments;
    private JButton btnExtractImages;
    private JButton btnParseRIDValues;
    private JButton btnParseImageInfo;

    //Create the frame
    public IPGUI() 
    {
        //Sets frame properties
        setTitle("IP Extractor");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setBounds(100, 100, 250, 300);
        contentPane = new JPanel();
        contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
        contentPane.setLayout(new BorderLayout(0, 0));
        setContentPane(contentPane);

        //Creates new JPanel with boxlayout
        JPanel panel = new JPanel();
        contentPane.add(panel, BorderLayout.CENTER);
        panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));

        //////////////////New Button//////////////////

        JButton btnConvertDocuments = new JButton("1. Convert Documents");
        btnConvertDocuments.setAlignmentX(Component.CENTER_ALIGNMENT);
        btnConvertDocuments.setMaximumSize(new Dimension(160, 0));
        btnConvertDocuments.setPreferredSize(new Dimension(0, 50));

        panel.add(btnConvertDocuments);

        btnConvertDocuments.setActionCommand("w");
        btnConvertDocuments.addActionListener((ActionListener) this);

        JSeparator separator_3 = new JSeparator();
        panel.add(separator_3);

        //////////////////New Button//////////////////

        btnExtractImages = new JButton("2. Extract Images");
        btnExtractImages.setAlignmentX(Component.CENTER_ALIGNMENT);
        btnExtractImages.setMaximumSize(new Dimension(160, 0));
        btnExtractImages.setPreferredSize(new Dimension(0, 50));

        panel.add(btnExtractImages);

        btnExtractImages.setActionCommand("x");
        btnExtractImages.addActionListener((ActionListener) this);

        JSeparator separator_2 = new JSeparator();
        panel.add(separator_2);

        //////////////////New Button//////////////////

        JButton btnParseRIDValues = new JButton("3. Parse rId Values");
        btnParseRIDValues.setAlignmentX(Component.CENTER_ALIGNMENT);
        btnParseRIDValues.setMaximumSize(new Dimension(160, 0));
        btnParseRIDValues.setPreferredSize(new Dimension(0, 50));

        panel.add(btnParseRIDValues);

        btnParseRIDValues.setActionCommand("y");
        btnParseRIDValues.addActionListener((ActionListener) this);

        JSeparator separator_1 = new JSeparator();
        panel.add(separator_1);

        //////////////////New Button//////////////////

        JButton btnParseImageInfo = new JButton("4. Parse Image Info.");
        btnParseImageInfo.setAlignmentX(Component.CENTER_ALIGNMENT);
        btnParseImageInfo.setMaximumSize(new Dimension(160, 0));
        btnParseImageInfo.setPreferredSize(new Dimension(0, 50));

        panel.add(btnParseImageInfo);

        btnParseImageInfo.setActionCommand("z");
        btnParseImageInfo.addActionListener((ActionListener) this);
    }

    public void actionPerformed(ActionEvent event) 
    {
        String command = event.getActionCommand();

        if (command.equals("w"))
        {
            FileConverter fc = new FileConverter();
            btnConvertDocuments.setEnabled(false);
        }
        else if (command.equals("x"))
        {
            ImageExtractor ie = new ImageExtractor();
            btnExtractImages.setEnabled(false);
        }
        else if (command.equals("y")) 
        {
            XMLIDParser xip = new XMLIDParser();
            btnParseRIDValues.setEnabled(false);
        }
        else if (command.equals("z")) 
        {
            XMLTagParser xtp = new XMLTagParser();
            btnParseImageInfo.setEnabled(false);        
        }
    }


}

Here is the solution I came up with thanks to everyone's help. Thank you again everyone for your input, really appreciate it!

Should I use px or rem value units in my CSS?

This article describes pretty well the pros and cons of px, em, and rem.

The author finally concludes that the best method is probably to use both px and rem, declaring px first for older browsers and redeclaring rem for newer browsers:

html { font-size: 62.5%; } 
body { font-size: 14px; font-size: 1.4rem; } /* =14px */
h1   { font-size: 24px; font-size: 2.4rem; } /* =24px */

Unzip All Files In A Directory

aunpack -e *.zip, with atool installed. Has the advantage that it deals intelligently with errors, and always unpacks into subdirectories unless the zip contains only one file . Thus, there is no danger of polluting the current directory with masses of files, as there is with unzip on a zip with no directory structure.

System.Data.SqlClient.SqlException: Login failed for user

I had similar experience and it took me time to solve the problem. Though, my own case was ASP.Net MVC Core and Core framework. Setting Trusted_Connection=False; solved my problem.

Inside appsettings.json file

"ConnectionStrings": {
    "DefaultConnection": "Server=servername; Database=databasename; User Id=userid; Password=password; Trusted_Connection=False; MultipleActiveResultSets=true",
  },

Creating an Instance of a Class with a variable in Python

Given your edit i assume you have the class name as a string and want to instantiate the class? Just use a dictionary as a dispatcher.

class Foo(object):
    pass

class Bar(object):
    pass

dispatch_dict = {"Foo": Foo, "Bar": Bar}
dispatch_dict["Foo"]() # returns an instance of Foo

The transaction manager has disabled its support for remote/network transactions

I had the same error message. For me changing pooling=False to ;pooling=true;Max Pool Size=200 in the connection string fixed the problem.

Assign an initial value to radio button as checked

I've put this answer on a similar question that was marked as a duplicate of this question. The answer has helped a decent amount of people so I thought I'd add it here too in just in case.

This doesn't exactly answer the question but for anyone using AngularJS trying to achieve this, the answer is slightly different. And actually the normal answer won't work (at least it didn't for me).

Your html will look pretty similar to the normal radio button:

<input type='radio' name='group' ng-model='mValue' value='first' />First
<input type='radio' name='group' ng-model='mValue' value='second' /> Second

In your controller you'll have declared the mValue that is associated with the radio buttons. To have one of these radio buttons preselected, assign the $scope variable associated with the group to the desired input's value:

$scope.mValue="second"

This makes the "second" radio button selected on loading the page.

Can't create handler inside thread which has not called Looper.prepare()

Try this

    Handler mHandler = new Handler(Looper.getMainLooper());
                        mHandler.post(new Runnable() {
                            @Override
                            public void run() {
 //your code here that talks with the UI level widgets/ try to access the UI 
//elements from this block because this piece of snippet will run in the UI/MainThread.                                     
                            }
                        });

How to vertically center a "div" element for all browsers using CSS?

Not answering for browser compatibility but to also mention the new Grid and the not so new Flexbox feature.

Grid

From: Mozilla - Grid Documentation - Align Div Vertically

Browser Support: Grid Browser Support

CSS:

.wrapper {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  grid-gap: 10px;
  grid-auto-rows: 200px;
  grid-template-areas: 
    ". a a ."
    ". a a .";
}
.item1 {
  grid-area: a;
  align-self: center;
  justify-self: center;
}

HTML:

<div class="wrapper">
 <div class="item1">Item 1</div>
</div>

Flexbox

Browser Support: Flexbox Browser Support

CSS:

display: -webkit-box;
display: -moz-box;
display: -ms-flexbox;
display: -webkit-flex;
display: flex;
align-items: center;
justify-content: center;

Mapping list in Yaml to list of objects in Spring Boot

I had much issues with this one too. I finally found out what's the final deal.

Referring to @Gokhan Oner answer, once you've got your Service class and the POJO representing your object, your YAML config file nice and lean, if you use the annotation @ConfigurationProperties, you have to explicitly get the object for being able to use it. Like :

@ConfigurationProperties(prefix = "available-payment-channels-list")
//@Configuration  <-  you don't specificly need this, instead you're doing something else
public class AvailableChannelsConfiguration {

    private String xyz;
    //initialize arraylist
    private List<ChannelConfiguration> channelConfigurations = new ArrayList<>();

    public AvailableChannelsConfiguration() {
        for(ChannelConfiguration current : this.getChannelConfigurations()) {
            System.out.println(current.getName()); //TADAAA
        }
    }

    public List<ChannelConfiguration> getChannelConfigurations() {
        return this.channelConfigurations;
    }

    public static class ChannelConfiguration {
        private String name;
        private String companyBankAccount;
    }

}

And then here you go. It's simple as hell, but we have to know that we must call the object getter. I was waiting at initialization, wishing the object was being built with the value but no. Hope it helps :)

How to run TestNG from command line

If none of the above answers work, you can run the test in IDE, get the class path and use it in your command. Ex: If you are using Intellij IDEA, you can find it at the top of the console(screenshot below). Intellij Console

Clicking on the highlighted part expands and displays the complete class path.

you need to remove the references to jars inside the folder: JetBrains\IntelliJ IDEA Community Edition 2019.1.3

java -cp "path_copied" org.testng.TestNG testng.xml

Git: How do I list only local branches?

git show-ref --heads

The answer by @gertvdijk is the most concise and elegant, but I wanted to leave this here because it helped me grasp the idea that refs/heads/* are equivalent to local branches.

Most of the time the refs/heads/master ref is a file at .git/refs/heads/master that contains a git commit hash that points to the git object that represents the current state of your local master branch, so each file under .git/refs/heads/* represents a local branch.

SOAP vs REST (differences)

Addition for:

++ A mistake that’s often made when approaching REST is to think of it as “web services with URLs”—to think of REST as another remote procedure call (RPC) mechanism, like SOAP, but invoked through plain HTTP URLs and without SOAP’s hefty XML namespaces.

++ On the contrary, REST has little to do with RPC. Whereas RPC is service oriented and focused on actions and verbs, REST is resource oriented, emphasizing the things and nouns that comprise an application.

UndefinedMetricWarning: F-score is ill-defined and being set to 0.0 in labels with no predicted samples

According to @Shovalt's answer, but in short:

Alternatively you could use the following lines of code

    from sklearn.metrics import f1_score
    metrics.f1_score(y_test, y_pred, labels=np.unique(y_pred))

This should remove your warning and give you the result you wanted, because it no longer considers the difference between the sets, by using the unique mode.

Auto Scale TextView Text to Fit within Bounds

I just created the following method (based on the ideas of Chase) which might help you if you want to draw text to any canvas:

private static void drawText(Canvas canvas, int xStart, int yStart,
        int xWidth, int yHeigth, String textToDisplay,
        TextPaint paintToUse, float startTextSizeInPixels,
        float stepSizeForTextSizeSteps) {

    // Text view line spacing multiplier
    float mSpacingMult = 1.0f;
    // Text view additional line spacing
    float mSpacingAdd = 0.0f;
    StaticLayout l = null;
    do {
        paintToUse.setTextSize(startTextSizeInPixels);
        startTextSizeInPixels -= stepSizeForTextSizeSteps;
        l = new StaticLayout(textToDisplay, paintToUse, xWidth,
                Alignment.ALIGN_NORMAL, mSpacingMult, mSpacingAdd, true);
    } while (l.getHeight() > yHeigth);

    int textCenterX = xStart + (xWidth / 2);
    int textCenterY = (yHeigth - l.getHeight()) / 2;

    canvas.save();
    canvas.translate(textCenterX, textCenterY);
    l.draw(canvas);
    canvas.restore();
}

This could be used e.g. in any onDraw() method of any custom view.

ActiveX component can't create object

It turns out to get this application working under VBScript, I had to do two things.

  1. Run RegAsm.exe to register the DLLs.
  2. Run the C:\Windows\SysWOW64\cscript.exe to run my VBScript.

If these don't work, check out the other answer here about enabling 32-bit applications in IIS.

Detect click outside React component

To extend on the accepted answer made by Ben Bud, if you are using styled-components, passing refs that way will give you an error such as "this.wrapperRef.contains is not a function".

The suggested fix, in the comments, to wrap the styled component with a div and pass the ref there, works. Having said that, in their docs they already explain the reason for this and the proper use of refs within styled-components:

Passing a ref prop to a styled component will give you an instance of the StyledComponent wrapper, but not to the underlying DOM node. This is due to how refs work. It's not possible to call DOM methods, like focus, on our wrappers directly. To get a ref to the actual, wrapped DOM node, pass the callback to the innerRef prop instead.

Like so:

<StyledDiv innerRef={el => { this.el = el }} />

Then you can access it directly within the "handleClickOutside" function:

handleClickOutside = e => {
    if (this.el && !this.el.contains(e.target)) {
        console.log('clicked outside')
    }
}

This also applies for the "onBlur" approach:

componentDidMount(){
    this.el.focus()
}
blurHandler = () => {
    console.log('clicked outside')
}
render(){
    return(
        <StyledDiv
            onBlur={this.blurHandler}
            tabIndex="0"
            innerRef={el => { this.el = el }}
        />
    )
}

Eclipse - no Java (JRE) / (JDK) ... no virtual machine

I have windows 7 64-bit, and I had this same problem with eclipse. To get it to work, I had to use internet explorer (64-bit version) to download java. This was the only way to get java to install a 64-bit version. When I used firefox to install java, it automatically installed a 32-bit version (so idiotic!). And The Eclipse 64-bit version wouldn't detect the java 32-bit version.

Importing images from a directory (Python) to list or dictionary

from PIL import Image
import os, os.path

imgs = []
path = "/home/tony/pictures"
valid_images = [".jpg",".gif",".png",".tga"]
for f in os.listdir(path):
    ext = os.path.splitext(f)[1]
    if ext.lower() not in valid_images:
        continue
    imgs.append(Image.open(os.path.join(path,f)))
   

How do I set a Windows scheduled task to run in the background?

Assuming the application you are attempting to run in the background is CLI based, you can try calling the scheduled jobs using Hidden Start

Also see: http://www.howtogeek.com/howto/windows/hide-flashing-command-line-and-batch-file-windows-on-startup/

How to run a cron job inside a docker container?

When running on some trimmed down images that restrict root access, I had to add my user to the sudoers and run as sudo cron

_x000D_
_x000D_
FROM node:8.6.0_x000D_
RUN apt-get update && apt-get install -y cron sudo_x000D_
_x000D_
COPY crontab /etc/cron.d/my-cron_x000D_
RUN chmod 0644 /etc/cron.d/my-cron_x000D_
RUN touch /var/log/cron.log_x000D_
_x000D_
# Allow node user to start cron daemon with sudo_x000D_
RUN echo 'node ALL=NOPASSWD: /usr/sbin/cron' >>/etc/sudoers_x000D_
_x000D_
ENTRYPOINT sudo cron && tail -f /var/log/cron.log
_x000D_
_x000D_
_x000D_

Maybe that helps someone

Scanner only reads first word instead of line

input.next() takes in the first whitsepace-delimited word of the input string. So by design it does what you've described. Try input.nextLine().

Trying to SSH into an Amazon Ec2 instance - permission error

You can find the answer from the ASW guide. 400 protects it by making it read only and only for the owner.

chmod 400 mykey.pem

How can I export the schema of a database in PostgreSQL?

set up a new postgresql server and replace its data folder with the files from your external disk.

You will then be able to start that postgresql server up and retrieve the data using pg_dump (pg_dump -s for the schema-only as mentioned)

failed to find target with hash string android-23

In Android Studio File -> Invalidate Caches/Restart solved the issue for me.

MVC Razor view nested foreach's model

Another much simpler possibility is that one of your property names is wrong (probably one you just changed in the class). This is what it was for me in RazorPages .NET Core 3.

Python str vs unicode types

When you define a as unicode, the chars a and á are equal. Otherwise á counts as two chars. Try len(a) and len(au). In addition to that, you may need to have the encoding when you work with other environments. For example if you use md5, you get different values for a and ua

Can an Android App connect directly to an online mysql database

Yes definitely you can connect to the MySql online database for that you need to create a web service. This web service will provide you access to the MySql database. Then you can easily pull and push data to MySql Database. PHP will be a good option for creating web service its simple to implement. Good luck...

Shell script not running, command not found

I'm new to shell scripting too, but I had this same issue. Make sure at the end of your script you have a blank line. Otherwise it won't work.

How to change the href for a hyperlink using jQuery

href in an attribute, so you can change it using pure JavaScript, but if you already have jQuery injected in your page, don't worry, I will show it both ways:

Imagine you have this href below:

<a id="ali" alt="Ali" href="http://dezfoolian.com.au">Alireza Dezfoolian</a>

And you like to change it the link...

Using pure JavaScript without any library you can do:

document.getElementById("ali").setAttribute("href", "https://stackoverflow.com");

But also in jQuery you can do:

$("#ali").attr("href", "https://stackoverflow.com");

or

$("#ali").prop("href", "https://stackoverflow.com");

In this case, if you already have jQuery injected, probably jQuery one look shorter and more cross-browser...but other than that I go with the JS one...

How can I hash a password in Java?

You can actually use a facility built in to the Java runtime to do this. The SunJCE in Java 6 supports PBKDF2, which is a good algorithm to use for password hashing.

byte[] salt = new byte[16];
random.nextBytes(salt);
KeySpec spec = new PBEKeySpec("password".toCharArray(), salt, 65536, 128);
SecretKeyFactory f = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
byte[] hash = f.generateSecret(spec).getEncoded();
Base64.Encoder enc = Base64.getEncoder();
System.out.printf("salt: %s%n", enc.encodeToString(salt));
System.out.printf("hash: %s%n", enc.encodeToString(hash));

Here's a utility class that you can use for PBKDF2 password authentication:

import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.KeySpec;
import java.util.Arrays;
import java.util.Base64;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.PBEKeySpec;

/**
 * Hash passwords for storage, and test passwords against password tokens.
 * 
 * Instances of this class can be used concurrently by multiple threads.
 *  
 * @author erickson
 * @see <a href="http://stackoverflow.com/a/2861125/3474">StackOverflow</a>
 */
public final class PasswordAuthentication
{

  /**
   * Each token produced by this class uses this identifier as a prefix.
   */
  public static final String ID = "$31$";

  /**
   * The minimum recommended cost, used by default
   */
  public static final int DEFAULT_COST = 16;

  private static final String ALGORITHM = "PBKDF2WithHmacSHA1";

  private static final int SIZE = 128;

  private static final Pattern layout = Pattern.compile("\\$31\\$(\\d\\d?)\\$(.{43})");

  private final SecureRandom random;

  private final int cost;

  public PasswordAuthentication()
  {
    this(DEFAULT_COST);
  }

  /**
   * Create a password manager with a specified cost
   * 
   * @param cost the exponential computational cost of hashing a password, 0 to 30
   */
  public PasswordAuthentication(int cost)
  {
    iterations(cost); /* Validate cost */
    this.cost = cost;
    this.random = new SecureRandom();
  }

  private static int iterations(int cost)
  {
    if ((cost < 0) || (cost > 30))
      throw new IllegalArgumentException("cost: " + cost);
    return 1 << cost;
  }

  /**
   * Hash a password for storage.
   * 
   * @return a secure authentication token to be stored for later authentication 
   */
  public String hash(char[] password)
  {
    byte[] salt = new byte[SIZE / 8];
    random.nextBytes(salt);
    byte[] dk = pbkdf2(password, salt, 1 << cost);
    byte[] hash = new byte[salt.length + dk.length];
    System.arraycopy(salt, 0, hash, 0, salt.length);
    System.arraycopy(dk, 0, hash, salt.length, dk.length);
    Base64.Encoder enc = Base64.getUrlEncoder().withoutPadding();
    return ID + cost + '$' + enc.encodeToString(hash);
  }

  /**
   * Authenticate with a password and a stored password token.
   * 
   * @return true if the password and token match
   */
  public boolean authenticate(char[] password, String token)
  {
    Matcher m = layout.matcher(token);
    if (!m.matches())
      throw new IllegalArgumentException("Invalid token format");
    int iterations = iterations(Integer.parseInt(m.group(1)));
    byte[] hash = Base64.getUrlDecoder().decode(m.group(2));
    byte[] salt = Arrays.copyOfRange(hash, 0, SIZE / 8);
    byte[] check = pbkdf2(password, salt, iterations);
    int zero = 0;
    for (int idx = 0; idx < check.length; ++idx)
      zero |= hash[salt.length + idx] ^ check[idx];
    return zero == 0;
  }

  private static byte[] pbkdf2(char[] password, byte[] salt, int iterations)
  {
    KeySpec spec = new PBEKeySpec(password, salt, iterations, SIZE);
    try {
      SecretKeyFactory f = SecretKeyFactory.getInstance(ALGORITHM);
      return f.generateSecret(spec).getEncoded();
    }
    catch (NoSuchAlgorithmException ex) {
      throw new IllegalStateException("Missing algorithm: " + ALGORITHM, ex);
    }
    catch (InvalidKeySpecException ex) {
      throw new IllegalStateException("Invalid SecretKeyFactory", ex);
    }
  }

  /**
   * Hash a password in an immutable {@code String}. 
   * 
   * <p>Passwords should be stored in a {@code char[]} so that it can be filled 
   * with zeros after use instead of lingering on the heap and elsewhere.
   * 
   * @deprecated Use {@link #hash(char[])} instead
   */
  @Deprecated
  public String hash(String password)
  {
    return hash(password.toCharArray());
  }

  /**
   * Authenticate with a password in an immutable {@code String} and a stored 
   * password token. 
   * 
   * @deprecated Use {@link #authenticate(char[],String)} instead.
   * @see #hash(String)
   */
  @Deprecated
  public boolean authenticate(String password, String token)
  {
    return authenticate(password.toCharArray(), token);
  }

}

What exactly is the difference between Web API and REST API in MVC?

ASP.NET Web API is a framework that makes it easy to build HTTP services that reach a broad range of clients, including browsers and mobile devices. ASP.NET Web API is an ideal platform for building RESTful applications on the .NET Framework.

REST

RESTs sweet spot is when you are exposing a public API over the internet to handle CRUD operations on data. REST is focused on accessing named resources through a single consistent interface.

SOAP

SOAP brings it’s own protocol and focuses on exposing pieces of application logic (not data) as services. SOAP exposes operations. SOAP is focused on accessing named operations, each implement some business logic through different interfaces.

Though SOAP is commonly referred to as “web services” this is a misnomer. SOAP has very little if anything to do with the Web. REST provides true “Web services” based on URIs and HTTP.

Reference: http://spf13.com/post/soap-vs-rest

And finally: What they could be referring to is REST vs. RPC See this: http://encosia.com/rest-vs-rpc-in-asp-net-web-api-who-cares-it-does-both/

Display PNG image as response to jQuery AJAX request

Method 1

You should not make an ajax call, just put the src of the img element as the url of the image.

This would be useful if you use GET instead of POST

<script type="text/javascript" > 

  $(document).ready( function() { 
      $('.div_imagetranscrits').html('<img src="get_image_probes_via_ajax.pl?id_project=xxx" />')
  } );

</script>

Method 2

If you want to POST to that image and do it the way you do (trying to parse the contents of the image on the client side, you could try something like this: http://en.wikipedia.org/wiki/Data_URI_scheme

You'll need to encode the data to base64, then you could put data:[<MIME-type>][;charset=<encoding>][;base64],<data> into the img src

as example:

<img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg==" alt="Red dot img" />

To encode to base64:

make sounds (beep) with c++

std::cout << '\7';

How to compare two List<String> to each other?

You could also use Except(produces the set difference of two sequences) to check whether there's a difference or not:

IEnumerable<string> inFirstOnly = a1.Except(a2);
IEnumerable<string> inSecondOnly = a2.Except(a1);
bool allInBoth = !inFirstOnly.Any() && !inSecondOnly.Any();

So this is an efficient way if the order and if the number of duplicates does not matter(as opposed to the accepted answer's SequenceEqual). Demo: Ideone

If you want to compare in a case insentive way, just add StringComparer.OrdinalIgnoreCase:

a1.Except(a2, StringComparer.OrdinalIgnoreCase)

Dealing with float precision in Javascript

Check out this link.. It helped me a lot.

http://www.w3schools.com/jsref/jsref_toprecision.asp

The toPrecision(no_of_digits_required) function returns a string so don't forget to use the parseFloat() function to convert to decimal point of required precision.

Add marker to Google Map on Click

In 2017, the solution is:

map.addListener('click', function(e) {
    placeMarker(e.latLng, map);
});

function placeMarker(position, map) {
    var marker = new google.maps.Marker({
        position: position,
        map: map
    });
    map.panTo(position);
}

Making a mocked method return an argument that was passed to it

With Java 8 it is possible to create a one-line answer even with older version of Mockito:

when(myMock.myFunction(anyString()).then(i -> i.getArgumentAt(0, String.class));

Of course this is not as useful as using AdditionalAnswers suggested by David Wallace, but might be useful if you want to transform argument "on the fly".

How to recover corrupted Eclipse workspace?

This thread may be a bit older, but since this still is a problem nowadays, I thought I’d propose a new solution for backing up Eclipse.

  • At http://profiles.yatta.de you can download the Yatta Eclipse Launcher. You can use it to save your Eclipse and workspace setup.

  • After installation, the Launcher will discover your existing Eclipse installations and workspaces.

  • Click the Upload & Share button (the blue one) on the right of the entry you want to back up.

(You won’t actually “share” your Eclipse or workspace with anyone. You’ll just upload a setup file with your metadata that only you have access to yourself . You could share this later, but you can also just use it as a backup).

If you do that, you’ll be able to re-setup your IDE really fast if you ever have a fragged workspace or Eclipse installation.

How do I get the time of day in javascript/Node.js?

You should checkout the Date object.

In particular, you can look at the getHours() method for the Date object.

getHours() return the time from 0 - 23, so make sure to deal with it accordingly. I think 0-23 is a bit more intuitive since military time runs from 0 - 23, but it's up to you.

With that in mind, the code would be something along the lines of:

var date = new Date();
var current_hour = date.getHours();

PHP - Redirect and send data via POST

Alternatively, setting a session variable before the redirect and test it in the destination url, can solve this problem for me.

MySQL - Get row number on select

Take a look at this.

Change your query to:

SET @rank=0;
SELECT @rank:=@rank+1 AS rank, itemID, COUNT(*) as ordercount
  FROM orders
  GROUP BY itemID
  ORDER BY ordercount DESC;
SELECT @rank;

The last select is your count.

What possibilities can cause "Service Unavailable 503" error?

Primarily what that means is that there are too many concurrent requests and further that they exceed the default 1000 queued requests. That is there are 1000 or more queued requests to your website.

This could happen (assuming there are no faults in your app) if there are long running tasks and as a result the Request queue is backed up.

Depending on how the application pool has been set up you may see this kind of thing. Typically, the app pool's Process Model has an item called Maximum Worker Processes. By default this is 1. If you set it to more than 1 (typically up to a max of the number of cores on the hardware) you may not see this happen.

Just to note that unless the site is extremely busy you should not see this. If you do, it's really pointing to long running tasks

How to draw a filled triangle in android canvas?

You probably need to do something like :

Paint red = new Paint();

red.setColor(android.graphics.Color.RED);
red.setStyle(Paint.Style.FILL);

And use this color for your path, instead of your ARGB. Make sure the last point of your path ends on the first one, it makes sense also.

Tell me if it works please !

Convert a numpy.ndarray to string(or bytes) and convert it back to numpy.ndarray

This is a fast way to encode the array, the array shape and the array dtype:

def numpy_to_bytes(arr: np.array) -> str:
    arr_dtype = bytearray(str(arr.dtype), 'utf-8')
    arr_shape = bytearray(','.join([str(a) for a in arr.shape]), 'utf-8')
    sep = bytearray('|', 'utf-8')
    arr_bytes = arr.ravel().tobytes()
    to_return = arr_dtype + sep + arr_shape + sep + arr_bytes
    return to_return

def bytes_to_numpy(serialized_arr: str) -> np.array:
    sep = '|'.encode('utf-8')
    i_0 = serialized_arr.find(sep)
    i_1 = serialized_arr.find(sep, i_0 + 1)
    arr_dtype = serialized_arr[:i_0].decode('utf-8')
    arr_shape = tuple([int(a) for a in serialized_arr[i_0 + 1:i_1].decode('utf-8').split(',')])
    arr_str = serialized_arr[i_1 + 1:]
    arr = np.frombuffer(arr_str, dtype = arr_dtype).reshape(arr_shape)
    return arr

To use the functions:

a = np.ones((23, 23), dtype = 'int')
a_b = numpy_to_bytes(a)
a1 = bytes_to_numpy(a_b)
np.array_equal(a, a1) and a.shape == a1.shape and a.dtype == a1.dtype

How to call a PHP function on the click of a button

Button clicks are client side whereas PHP is executed server side, but you can achieve this by using Ajax:

$('.button').click(function() {
  $.ajax({
    type: "POST",
    url: "some.php",
    data: { name: "John" }
  }).done(function( msg ) {
    alert( "Data Saved: " + msg );
  });
});

In your PHP file:

<?php
    function abc($name){
        // Your code here
    }
?>

Add number of days to a date

Use this addDate() function to add or subtract days, month or years (you will need the auxiliar function reformatDate() as well)

/**
 * $date self explanatory
 * $diff the difference to add or subtract: e.g. '2 days' or '-1 month'
 * $format the format for $date
 **/
    function addDate($date = '', $diff = '', $format = "d/m/Y") {
        if (empty($date) || empty($diff))
            return false;
        $formatedDate = reformatDate($date, $format, $to_format = 'Y-m-d H:i:s');
        $newdate = strtotime($diff, strtotime($formatedDate));
        return date($format, $newdate);
    }
    //Aux function
    function reformatDate($date, $from_format = 'd/m/Y', $to_format = 'Y-m-d') {
        $date_aux = date_create_from_format($from_format, $date);
        return date_format($date_aux,$to_format);
    }

Note: only for php >=5.3

Alternative to the HTML Bold tag

Its in CSS you have to set font-weight: bold; as style

How to run a command as a specific user in an init script?

Instead of sudo, try

su - username command

In my experience, sudo is not always available on RHEL systems, but su is, because su is part of the coreutils package whereas sudo is in the sudo package.

Unfortunately Launcher3 has stopped working error in android studio?

I didn't found any particular answer to this question but i deleted the emulator and create a new one and increase the Ram size of the new emulator.Then the emulator works fine.

How do I get the Date & Time (VBS)

Show time in form 24 hours

Right("0" & hour(now),2) & ":" & Right("0" & minute(now),2)   = 01:35
Right("0" & hour(now),2)                                      = 01
Right("0" & minute(now),2)                                    = 35

How to provide shadow to Button

you can use this great library https://github.com/BluRe-CN/ComplexView and it is really easy to use

How to Handle Button Click Events in jQuery?

$('#btnSubmit').click(function(event){
    alert("Button Clicked");
});

or as you are using submit button so you can write your code in form's validate event like

$('#myForm').validate(function(){
    alert("Hello World!!");
});

How do I get the value of a registry key and ONLY the value using powershell

Following code will enumerate all values for a certain Registry key, will sort them and will return value name : value pairs separated by colon (:):

$path = 'HKLM:\SOFTWARE\Wow6432Node\Microsoft\.NETFramework';

Get-Item -Path $path | Select-Object -ExpandProperty Property | Sort | % {
    $command = [String]::Format('(Get-ItemProperty -Path "{0}" -Name "{1}")."{1}"', $path, $_);
    $value = Invoke-Expression -Command $command;
    $_ + ' : ' + $value; };

Like this:

DbgJITDebugLaunchSetting : 16

DbgManagedDebugger : "C:\Windows\system32\vsjitdebugger.exe" PID %d APPDOM %d EXTEXT "%s" EVTHDL %d

InstallRoot : C:\Windows\Microsoft.NET\Framework\

How to load a tsv file into a Pandas DataFrame?

As of 17.0 from_csv is discouraged.

Use pd.read_csv(fpath, sep='\t') or pd.read_table(fpath).

Vim: How to insert in visual block mode?

You might also have a use case where you want to delete a block of text and replace it .

Like this

Hello World
Hello World

You can visual block select before "W" and hit Shift+i - Type "Cool" - Hit ESC and then delete "World" by visual block selection .

Alternatively, the cooler way to do it is to just visual block select "World" in both lines. Type c for change. Now you are in the insert mode. Insert the stuff you want and hit ESC. Both gets reflected with lesser keystrokes.

Hello Cool 
Hello Cool

How to convert array values to lowercase in PHP?

Just for completeness: you may also use array_walk:

array_walk($yourArray, function(&$value)
{
  $value = strtolower($value);
});

From PHP docs:

If callback needs to be working with the actual values of the array, specify the first parameter of callback as a reference. Then, any changes made to those elements will be made in the original array itself.

Or directly via foreach loop using references:

foreach($yourArray as &$value)
  $value = strtolower($value);

Note that these two methods change the array "in place", whereas array_map creates and returns a copy of the array, which may not be desirable in case of very large arrays.

How to install node.js as windows service?

From this blog

Next up, I wanted to host node as a service, just like IIS. This way it’d start up with my machine, run in the background, restart automatically if it crashes and so forth.

This is where nssm, the non-sucking service manager, enters the picture. This tool lets you host a normal .exe as a Windows service.

Here are the commands I used to setup an instance of the your node application as a service, open your cmd like administrator and type following commands:

nssm.exe install service_name c:\your_nodejs_directory\node.exe c:\your_application_directory\server.js
net start service_name

Removing an item from a select box

window.onload = function ()
{   
    var select = document.getElementById('selectBox');
    var delButton = document.getElementById('delete');

    function remove()
    {
        value = select.selectedIndex;
        select.removeChild(select[value]);
    }

    delButton.onclick = remove;    
}

To add the item I would create second select box and:

var select2 = document.getElementById('selectBox2');
var addSelect = document.getElementById('addSelect');

function add()
{
    value1 = select2.selectedIndex;
    select.appendChild(select2[value1]);    
}

addSelect.onclick = add;

Not jQuery though.

How to merge lists into a list of tuples?

The output which you showed in problem statement is not the tuple but list

list_c = [(1,5), (2,6), (3,7), (4,8)]

check for

type(list_c)

considering you want the result as tuple out of list_a and list_b, do

tuple(zip(list_a,list_b)) 

String to decimal conversion: dot separation instead of comma

You are viewing your decimal or double values in Visual Studio. That doesn't respect the culture settings you have on your code.

Change the Region and Language settings on your Control Panel if you want to see decimal and double values having the comma as the decimal separator.

Maintain aspect ratio of div but fill screen width and height in CSS?

My original question for this was how to both have an element of a fixed aspect, but to fit that within a specified container exactly, which makes it a little fiddly. If you simply want an individual element to maintain its aspect ratio it is a lot easier.

The best method I've come across is by giving an element zero height and then using percentage padding-bottom to give it height. Percentage padding is always proportional to the width of an element, and not its height, even if its top or bottom padding.

W3C Padding Properties

So utilising that you can give an element a percentage width to sit within a container, and then padding to specify the aspect ratio, or in other terms, the relationship between its width and height.

.object {
    width: 80%; /* whatever width here, can be fixed no of pixels etc. */
    height: 0px;
    padding-bottom: 56.25%;
}
.object .content {
    position: absolute;
    top: 0px;
    left: 0px;
    height: 100%;
    width: 100%;
    box-sizing: border-box;
    -moz-box-sizing: border-box;
    padding: 40px;
}

So in the above example the object takes 80% of the container width, and then its height is 56.25% of that value. If it's width was 160px then the bottom padding, and thus the height would be 90px - a 16:9 aspect.

The slight problem here, which may not be an issue for you, is that there is no natural space inside your new object. If you need to put some text in for example and that text needs to take it's own padding values you need to add a container inside and specify the properties in there.

Also vw and vh units aren't supported on some older browsers, so the accepted answer to my question might not be possible for you and you might have to use something more lo-fi.

How to retrieve the current value of an oracle sequence without increment it?

I also tried to use CURRVAL, in my case to find out if some process inserted new rows to some table with that sequence as Primary Key. My assumption was that CURRVAL would be the fastest method. But a) CurrVal does not work, it will just get the old value because you are in another Oracle session, until you do a NEXTVAL in your own session. And b) a select max(PK) from TheTable is also very fast, probably because a PK is always indexed. Or select count(*) from TheTable. I am still experimenting, but both SELECTs seem fast.

I don't mind a gap in a sequence, but in my case I was thinking of polling a lot, and I would hate the idea of very large gaps. Especially if a simple SELECT would be just as fast.

Conclusion:

  • CURRVAL is pretty useless, as it does not detect NEXTVAL from another session, it only returns what you already knew from your previous NEXTVAL
  • SELECT MAX(...) FROM ... is a good solution, simple and fast, assuming your sequence is linked to that table

Javascript geocoding from address to latitude and longitude numbers not working

The script tag to the api has changed recently. Use something like this to query the Geocoding API and get the JSON object back

<script type="text/javascript" src="https://maps.googleapis.com/maps/api/geocode/json?address=THE_ADDRESS_YOU_WANT_TO_GEOCODE&key=YOUR_API_KEY"></script>

The address could be something like

1600+Amphitheatre+Parkway,+Mountain+View,+CA (URI Encoded; you should Google it. Very useful)

or simply

1600 Amphitheatre Parkway, Mountain View, CA

By entering this address https://maps.googleapis.com/maps/api/geocode/json?address=1600+Amphitheatre+Parkway,+Mountain+View,+CA&key=YOUR_API_KEY inside the browser, along with my API Key, I get back a JSON object which contains the Latitude & Longitude for the city of Moutain view, CA.

{"results" : [
  {
     "address_components" : [
        {
           "long_name" : "1600",
           "short_name" : "1600",
           "types" : [ "street_number" ]
        },
        {
           "long_name" : "Amphitheatre Parkway",
           "short_name" : "Amphitheatre Pkwy",
           "types" : [ "route" ]
        },
        {
           "long_name" : "Mountain View",
           "short_name" : "Mountain View",
           "types" : [ "locality", "political" ]
        },
        {
           "long_name" : "Santa Clara County",
           "short_name" : "Santa Clara County",
           "types" : [ "administrative_area_level_2", "political" ]
        },
        {
           "long_name" : "California",
           "short_name" : "CA",
           "types" : [ "administrative_area_level_1", "political" ]
        },
        {
           "long_name" : "United States",
           "short_name" : "US",
           "types" : [ "country", "political" ]
        },
        {
           "long_name" : "94043",
           "short_name" : "94043",
           "types" : [ "postal_code" ]
        }
     ],
     "formatted_address" : "1600 Amphitheatre Pkwy, Mountain View, CA 94043, USA",
     "geometry" : {
        "location" : {
           "lat" : 37.4222556,
           "lng" : -122.0838589
        },
        "location_type" : "ROOFTOP",
        "viewport" : {
           "northeast" : {
              "lat" : 37.4236045802915,
              "lng" : -122.0825099197085
           },
           "southwest" : {
              "lat" : 37.4209066197085,
              "lng" : -122.0852078802915
           }
        }
     },
     "place_id" : "ChIJ2eUgeAK6j4ARbn5u_wAGqWA",
     "types" : [ "street_address" ]
  }],"status" : "OK"}

Web Frameworks such like AngularJS allow us to perform these queries with ease.

Unzipping files in Python

import zipfile
with zipfile.ZipFile(path_to_zip_file, 'r') as zip_ref:
    zip_ref.extractall(directory_to_extract_to)

That's pretty much it!

How do I use floating-point division in bash?

Improving a little the answer of marvin:

RESULT=$(awk "BEGIN {printf \"%.2f\",${IMG_WIDTH}/${IMG2_WIDTH}}")

bc doesn't come always as installed package.

Secure FTP using Windows batch script

    ftps -a -z -e:on -pfxfile:"S-PID.p12" -pfxpwfile:"S-PID.p12.pwd" -user:<S-PID number> -s:script <RemoteServerName> 2121

S-PID.p12 => certificate file name ;
S-PID.p12.pwd => certificate password file name ; 
RemoteServerName =>  abcd123 ; 
2121 => port number ; 
ftps => command is part of ftps client software ; 

How can I create Min stl priority_queue?

You can do it in multiple ways:
1. Using greater as comparison function :

 #include <bits/stdc++.h>

using namespace std;

int main()
{
    priority_queue<int,vector<int>,greater<int> >pq;
    pq.push(1);
    pq.push(2);
    pq.push(3);

    while(!pq.empty())
    {
        int r = pq.top();
        pq.pop();
        cout<<r<< " ";
    }
    return 0;
}

2. Inserting values by changing their sign (using minus (-) for positive number and using plus (+) for negative number :

int main()
{
    priority_queue<int>pq2;
    pq2.push(-1); //for +1
    pq2.push(-2); //for +2
    pq2.push(-3); //for +3
    pq2.push(4);  //for -4

    while(!pq2.empty())
    {
        int r = pq2.top();
        pq2.pop();
        cout<<-r<<" ";
    }

    return 0;
}

3. Using custom structure or class :

struct compare
{
    bool operator()(const int & a, const int & b)
    {
        return a>b;
    }
};

int main()
{

    priority_queue<int,vector<int>,compare> pq;
    pq.push(1);
    pq.push(2);
    pq.push(3);

    while(!pq.empty())
    {
        int r = pq.top();
        pq.pop();
        cout<<r<<" ";
    }

    return 0;
}

4. Using custom structure or class you can use priority_queue in any order. Suppose, we want to sort people in descending order according to their salary and if tie then according to their age.

    struct people
    {
        int age,salary;

    };
    struct compare{
    bool operator()(const people & a, const people & b)
        {
            if(a.salary==b.salary)
            {
                return a.age>b.age;
            }
            else
            {
                return a.salary>b.salary;
            }

    }
    };
    int main()
    {

        priority_queue<people,vector<people>,compare> pq;
        people person1,person2,person3;
        person1.salary=100;
        person1.age = 50;
        person2.salary=80;
        person2.age = 40;
        person3.salary = 100;
        person3.age=40;


        pq.push(person1);
        pq.push(person2);
        pq.push(person3);

        while(!pq.empty())
        {
            people r = pq.top();
            pq.pop();
            cout<<r.salary<<" "<<r.age<<endl;
    }
  1. Same result can be obtained by operator overloading :

    struct people
    {
    int age,salary;
    
    bool operator< (const people & p)const
    {
        if(salary==p.salary)
        {
            return age>p.age;
        }
        else
        {
            return salary>p.salary;
        }
    }};
    

    In main function :

    priority_queue<people> pq;
    people person1,person2,person3;
    person1.salary=100;
    person1.age = 50;
    person2.salary=80;
    person2.age = 40;
    person3.salary = 100;
    person3.age=40;
    
    
    pq.push(person1);
    pq.push(person2);
    pq.push(person3);
    
    while(!pq.empty())
    {
        people r = pq.top();
        pq.pop();
        cout<<r.salary<<" "<<r.age<<endl;
    }
    

Javascript Array Alert

If you want to see the array as an array, you can say

alert(JSON.stringify(aCustomers));

instead of all those document.writes.

http://jsfiddle.net/5b2eb/

However, if you want to display them cleanly, one per line, in your popup, do this:

alert(aCustomers.join("\n"));

http://jsfiddle.net/5b2eb/1/

Version vs build in Xcode

Another way is to set the version number in appDelegate didFinishLaunchingWithOptions:

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
     NSString * ver = [self myVersion];
     NSLog(@"version: %@",ver);

     NSUserDefaults* userDefaults = [NSUserDefaults standardUserDefaults];
     [userDefaults setObject:ver forKey:@"version"];
     return YES;
}

- (NSString *) myVersion {
    NSString *version = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"];
    NSString *build = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleVersion"];
    return [NSString stringWithFormat:@"%@ build %@", version, build];
}

Why is "throws Exception" necessary when calling a function?

If you propagate the exception by declaring the throws directive in the signature of the current method, then somewhere up the line or call stack a try/catch construct must be used to handle the exception.

What is the difference between user and kernel modes in operating systems?

These are two different modes in which your computer can operate. Prior to this, when computers were like a big room, if something crashes – it halts the whole computer. So computer architects decide to change it. Modern microprocessors implement in hardware at least 2 different states.

User mode:

  • mode where all user programs execute. It does not have access to RAM and hardware. The reason for this is because if all programs ran in kernel mode, they would be able to overwrite each other’s memory. If it needs to access any of these features – it makes a call to the underlying API. Each process started by windows except of system process runs in user mode.

Kernel mode:

  • mode where all kernel programs execute (different drivers). It has access to every resource and underlying hardware. Any CPU instruction can be executed and every memory address can be accessed. This mode is reserved for drivers which operate on the lowest level

How the switch occurs.

The switch from user mode to kernel mode is not done automatically by CPU. CPU is interrupted by interrupts (timers, keyboard, I/O). When interrupt occurs, CPU stops executing the current running program, switch to kernel mode, executes interrupt handler. This handler saves the state of CPU, performs its operations, restore the state and returns to user mode.

http://en.wikibooks.org/wiki/Windows_Programming/User_Mode_vs_Kernel_Mode

http://tldp.org/HOWTO/KernelAnalysis-HOWTO-3.html

http://en.wikipedia.org/wiki/Direct_memory_access

http://en.wikipedia.org/wiki/Interrupt_request

CFLAGS, CCFLAGS, CXXFLAGS - what exactly do these variables control?

As you noticed, these are Makefile {macros or variables}, not compiler options. They implement a set of conventions. (Macros is an old name for them, still used by some. GNU make doc calls them variables.)

The only reason that the names matter is the default make rules, visible via make -p, which use some of them.

If you write all your own rules, you get to pick all your own macro names.

In a vanilla gnu make, there's no such thing as CCFLAGS. There are CFLAGS, CPPFLAGS, and CXXFLAGS. CFLAGS for the C compiler, CXXFLAGS for C++, and CPPFLAGS for both.

Why is CPPFLAGS in both? Conventionally, it's the home of preprocessor flags (-D, -U) and both c and c++ use them. Now, the assumption that everyone wants the same define environment for c and c++ is perhaps questionable, but traditional.


P.S. As noted by James Moore, some projects use CPPFLAGS for flags to the C++ compiler, not flags to the C preprocessor. The Android NDK, for one huge example.

Calling Python in Java?

It depends on what do you mean by python functions? if they were written in cpython you can not directly call them you will have to use JNI, but if they were written in Jython you can easily call them from java, as jython ultimately generates java byte code.

Now when I say written in cpython or jython it doesn't make much sense because python is python and most code will run on both implementations unless you are using specific libraries which relies on cpython or java.

see here how to use Python interpreter in Java.

Spacing between elements

If you want vertical spacing between elements, use a margin.

Don't add extra elements if you don't need to.

Git commit with no commit message

Git requires a commit to have a comment, otherwise it wont accept the commit.

You can configure a default template with git as your default commit message or can look up the --allow-empty-message flag in git. I think (not 100% sure) you can reconfigure git to accept empty commit messages (which isn´t such a good idea). Normally each commit should be a bit of work which is described by your message.

Get OS-level system information

Add OSHI dependency via maven:

<dependency>
    <groupId>com.github.dblock</groupId>
    <artifactId>oshi-core</artifactId>
    <version>2.2</version>
</dependency>

Get a battery capacity left in percentage:

SystemInfo si = new SystemInfo();
HardwareAbstractionLayer hal = si.getHardware();
for (PowerSource pSource : hal.getPowerSources()) {
    System.out.println(String.format("%n %s @ %.1f%%", pSource.getName(), pSource.getRemainingCapacity() * 100d));
}

How is Java platform-independent when it needs a JVM to run?

Java is not platform independent in that it runs on the JVM. Having said that, you gain platform independence via programming against a single abstract machine that has concrete realizations on most common OS platforms (and some embedded appliances).

A related idea is the hardware abstraction layer present in many operating systems that allows the same OS to run on disparate hardware.

In you original question, Turbo C is analagous to the javac program, and the JVM is the OS/HAL.

TypeLoadException says 'no implementation', but it is implemented

This simply means that the implementation project is out of date in my cases. The DLL containing the interface was rebuilt but the implementation dll was stale.

What's the best way to break from nested loops in JavaScript?

Already mentioned previously by swilliams, but with an example below (Javascript):

// Function wrapping inner for loop
function CriteriaMatch(record, criteria) {
  for (var k in criteria) {
    if (!(k in record))
      return false;

    if (record[k] != criteria[k])
      return false;
  }

  return true;
}

// Outer for loop implementing continue if inner for loop returns false
var result = [];

for (var i = 0; i < _table.length; i++) {
  var r = _table[i];

  if (!CriteriaMatch(r[i], criteria))
    continue;

  result.add(r);
}

When does socket.recv(recv_size) return?

Yes, your conclusion is correct. socket.recv is a blocking call.

socket.recv(1024) will read at most 1024 bytes, blocking if no data is waiting to be read. If you don't read all data, an other call to socket.recv won't block.

socket.recv will also end with an empty string if the connection is closed or there is an error.

If you want a non-blocking socket, you can use the select module (a bit more complicated than just using sockets) or you can use socket.setblocking.

I had issues with socket.setblocking in the past, but feel free to try it if you want.

Use HTML5 to resize an image before upload

Here is what I ended up doing and it worked great.

First I moved the file input outside of the form so that it is not submitted:

<input name="imagefile[]" type="file" id="takePictureField" accept="image/*" onchange="uploadPhotos(\'#{imageUploadUrl}\')" />
<form id="uploadImageForm" enctype="multipart/form-data">
    <input id="name" value="#{name}" />
    ... a few more inputs ... 
</form>

Then I changed the uploadPhotos function to handle only the resizing:

window.uploadPhotos = function(url){
    // Read in file
    var file = event.target.files[0];

    // Ensure it's an image
    if(file.type.match(/image.*/)) {
        console.log('An image has been loaded');

        // Load the image
        var reader = new FileReader();
        reader.onload = function (readerEvent) {
            var image = new Image();
            image.onload = function (imageEvent) {

                // Resize the image
                var canvas = document.createElement('canvas'),
                    max_size = 544,// TODO : pull max size from a site config
                    width = image.width,
                    height = image.height;
                if (width > height) {
                    if (width > max_size) {
                        height *= max_size / width;
                        width = max_size;
                    }
                } else {
                    if (height > max_size) {
                        width *= max_size / height;
                        height = max_size;
                    }
                }
                canvas.width = width;
                canvas.height = height;
                canvas.getContext('2d').drawImage(image, 0, 0, width, height);
                var dataUrl = canvas.toDataURL('image/jpeg');
                var resizedImage = dataURLToBlob(dataUrl);
                $.event.trigger({
                    type: "imageResized",
                    blob: resizedImage,
                    url: dataUrl
                });
            }
            image.src = readerEvent.target.result;
        }
        reader.readAsDataURL(file);
    }
};

As you can see I'm using canvas.toDataURL('image/jpeg'); to change the resized image into a dataUrl adn then I call the function dataURLToBlob(dataUrl); to turn the dataUrl into a blob that I can then append to the form. When the blob is created, I trigger a custom event. Here is the function to create the blob:

/* Utility function to convert a canvas to a BLOB */
var dataURLToBlob = function(dataURL) {
    var BASE64_MARKER = ';base64,';
    if (dataURL.indexOf(BASE64_MARKER) == -1) {
        var parts = dataURL.split(',');
        var contentType = parts[0].split(':')[1];
        var raw = parts[1];

        return new Blob([raw], {type: contentType});
    }

    var parts = dataURL.split(BASE64_MARKER);
    var contentType = parts[0].split(':')[1];
    var raw = window.atob(parts[1]);
    var rawLength = raw.length;

    var uInt8Array = new Uint8Array(rawLength);

    for (var i = 0; i < rawLength; ++i) {
        uInt8Array[i] = raw.charCodeAt(i);
    }

    return new Blob([uInt8Array], {type: contentType});
}
/* End Utility function to convert a canvas to a BLOB      */

Finally, here is my event handler that takes the blob from the custom event, appends the form and then submits it.

/* Handle image resized events */
$(document).on("imageResized", function (event) {
    var data = new FormData($("form[id*='uploadImageForm']")[0]);
    if (event.blob && event.url) {
        data.append('image_data', event.blob);

        $.ajax({
            url: event.url,
            data: data,
            cache: false,
            contentType: false,
            processData: false,
            type: 'POST',
            success: function(data){
               //handle errors...
            }
        });
    }
});

jQuery changing style of HTML element

you could also specify multiple style values like this

$('#navigation ul li').css({'display': 'inline-block','background-color': '#ff0000', 'color': '#ffffff'});

What is Linux’s native GUI API?

In Linux the graphical user interface is not a part of the operating system. The graphical user interface found on most Linux desktops is provided by software called the X Window System, which defines a device independent way of dealing with screens, keyboards and pointer devices.

X Window defines a network protocol for communication, and any program that knows how to "speak" this protocol can use it. There is a C library called Xlib that makes it easier to use this protocol, so Xlib is kind of the native GUI API. Xlib is not the only way to access an X Window server; there is also XCB.

Toolkit libraries such as GTK+ (used by GNOME) and Qt (used by KDE), built on top of Xlib, are used because they are easier to program with. For example they give you a consistent look and feel across applications, make it easier to use drag-and-drop, provide components standard to a modern desktop environment, and so on.

How X draws on the screen internally depends on the implementation. X.org has a device independent part and a device dependent part. The former manages screen resources such as windows, while the latter communicates with the graphics card driver, usually a kernel module. The communication may happen over direct memory access or through system calls to the kernel. The driver translates the commands into a form that the hardware on the card understands.

As of 2013, a new window system called Wayland is starting to become usable, and many distributions have said they will at some point migrate to it, though there is still no clear schedule. This system is based on OpenGL/ES API, which means that in the future OpenGL will be the "native GUI API" in Linux. Work is being done to port GTK+ and QT to Wayland, so that current popular applications and desktop systems would need minimal changes. The applications that cannot be ported will be supported through an X11 server, much like OS X supports X11 apps through Xquartz. The GTK+ port is expected to be finished within a year, while Qt 5 already has complete Wayland support.

To further complicate matters, Ubuntu has announced they are developing a new system called Mir because of problems they perceive with Wayland. This window system is also based on the OpenGL/ES API.

Where can I get a list of Countries, States and Cities?

geonames.org has an api and a data dump of worldwide geographical places.

How to serve an image using nodejs

Let me just add to the answers above, that optimizing images, and serving responsive images helps page loading times dramatically since >90% of web traffic are images. You might want to pre-process images using JS / Node modules such as imagemin and related plug-ins, ideally during the build process with Grunt or Gulp.

Optimizing images means processing finding an ideal image type, and selecting optimal compression to achieve a balance between image quality and file size.

Serving responsive images translates into creating several sizes and formats of each image automatically and using srcset in your HTML allows you to serve optimal image set (that is, the ideal format and dimensions, thus optimal file size) for every single browser).

Image processing automation during the build process means incorporating it up once, and presenting optimized images further on, requiring minimum extra time.

Some great read on responsive images, minification in general, imagemin node module and using srcset.

Java generics: multiple generic parameters?

You can declare multiple type variables on a type or method. For example, using type parameters on the method:

<P, Q> int f(Set<P>, Set<Q>) {
  return 0;
}

Angular routerLink does not navigate to the corresponding component

For anyone having this error after spliting modules check your routes, the following happened to me:

public-routing.module.ts:

const routes: Routes = [
    { path: '', component: HomeComponent },
    { path: '**', redirectTo: 'home' } // ? This was my mistake
    { path: 'home', component: HomeComponent },
    { path: 'privacy-policy', component: PrivacyPolicyComponent },
    { path: 'credits', component: CreditsComponent },
    { path: 'contact', component: ContactComponent },
    { path: 'news', component: NewsComponent },
    { path: 'presentation', component: PresentationComponent }
]

@NgModule({
    imports: [RouterModule.forRoot(routes)],
    exports: [RouterModule]
})
export class PublicRoutingModule { }

app-routing.module.ts:

const routes: Routes = [
];

@NgModule({
    imports: [RouterModule.forRoot(routes)],
    exports: [RouterModule]
})
export class AppRoutingModule { }

Move { path: '**', redirectTo: 'home' } to your AppRoutingModule:

public-routing.module.ts:

const routes: Routes = [
    { path: '', component: HomeComponent },
    { path: 'home', component: HomeComponent },
    { path: 'privacy-policy', component: PrivacyPolicyComponent },
    { path: 'credits', component: CreditsComponent },
    { path: 'contact', component: ContactComponent },
    { path: 'news', component: NewsComponent },
    { path: 'presentation', component: PresentationComponent }
]

@NgModule({
    imports: [RouterModule.forRoot(routes)],
    exports: [RouterModule]
})
export class PublicRoutingModule { }

app-routing.module.ts:

const routes: Routes = [
    { path: '**', redirectTo: 'home' }
];

@NgModule({
    imports: [RouterModule.forRoot(routes)],
    exports: [RouterModule]
})
export class AppRoutingModule { }

Merge unequal dataframes and replace missing rows with 0

Take a look at the help page for merge. The all parameter lets you specify different types of merges. Here we want to set all = TRUE. This will make merge return NA for the values that don't match, which we can update to 0 with is.na():

zz <- merge(df1, df2, all = TRUE)
zz[is.na(zz)] <- 0

> zz
  x y
1 a 0
2 b 1
3 c 0
4 d 0
5 e 0

Updated many years later to address follow up question

You need to identify the variable names in the second data table that you aren't merging on - I use setdiff() for this. Check out the following:

df1 = data.frame(x=c('a', 'b', 'c', 'd', 'e', NA))
df2 = data.frame(x=c('a', 'b', 'c'),y1 = c(0,1,0), y2 = c(0,1,0))

#merge as before
df3 <- merge(df1, df2, all = TRUE)
#columns in df2 not in df1
unique_df2_names <- setdiff(names(df2), names(df1))
df3[unique_df2_names][is.na(df3[, unique_df2_names])] <- 0 

Created on 2019-01-03 by the reprex package (v0.2.1)

Is there a git-merge --dry-run option?

I know this is theoretically off-topic, but practically very on-topic for people landing here from a Google search.

When in doubt, you can always use the Github interface to create a pull-request and check if it indicates a clean merge is possible.

How to ignore user's time zone and force Date() use specific time zone

Presuming you get the timestamp in Helsinki time, I would create a date object set to midnight January 1 1970 UTC (for disregarding the local timezone settings of the browser). Then just add the needed number of milliseconds to it.

_x000D_
_x000D_
var _date = new Date( Date.UTC(1970, 0, 1, 0, 0, 0, 0) );_x000D_
_date.setUTCMilliseconds(1270544790922);_x000D_
_x000D_
alert(_date); //date shown shifted corresponding to local time settings_x000D_
alert(_date.getUTCFullYear());    //the UTC year value_x000D_
alert(_date.getUTCMonth());       //the UTC month value_x000D_
alert(_date.getUTCDate());        //the UTC day of month value_x000D_
alert(_date.getUTCHours());       //the UTC hour value_x000D_
alert(_date.getUTCMinutes());     //the UTC minutes value
_x000D_
_x000D_
_x000D_

Watch out later, to always ask UTC values from the date object. This way users will see the same date values regardless of local settings. Otherwise date values will be shifted corresponding to local time settings.

jQuery check/uncheck radio button onclick

-- EDIT --

It sure looks like your code is forcing a radio input to behave like a checkbox input. You might think about just using a checkbox input without the need for jQuery. However, if you want to force, like @manji said, you need to store the value outside the click handler and then set it on each click to the opposite of what it is at that time. @manji's answer is correct, I would just add that you should cache jQuery objects instead of re-querying the DOM:

var $radio = $("#radioinstant"),
    isChecked = $radio.attr("checked");

$radio.click(function() {

    isChecked = !isChecked;
    $(this).attr("checked", isChecked);

});

Close application and launch home screen on Android

Run the second activity using start activity for result:

Intent intent = new Intent(FirstActivity.this, SecondActivity.class);

//This line is important
intent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);

startActivityForResult(intent, REQUEST_CODE);

Add this function to the first Activity:

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if(rquestCode == REQUEST_CODE)
        if(resultCode == RESULT_CANCELED)
            finish();
}

And add this to the second Activity:

@Override
public boolean onKeyDown(int keyCode, KeyEvent event)  {
    if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {

        Log.i(TAG, "Back key pressed");
        setResult(RESULT_CANCELED);
        finish();
        return true;
    }
    return super.onKeyDown(keyCode, event);
}

Programmatic equivalent of default(Type)

If you're using .NET 4.0 or above and you want a programmatic version that isn't a codification of rules defined outside of code, you can create an Expression, compile and run it on-the-fly.

The following extension method will take a Type and get the value returned from default(T) through the Default method on the Expression class:

public static T GetDefaultValue<T>()
{
    // We want an Func<T> which returns the default.
    // Create that expression here.
    Expression<Func<T>> e = Expression.Lambda<Func<T>>(
        // The default value, always get what the *code* tells us.
        Expression.Default(typeof(T))
    );

    // Compile and return the value.
    return e.Compile()();
}

public static object GetDefaultValue(this Type type)
{
    // Validate parameters.
    if (type == null) throw new ArgumentNullException("type");

    // We want an Func<object> which returns the default.
    // Create that expression here.
    Expression<Func<object>> e = Expression.Lambda<Func<object>>(
        // Have to convert to object.
        Expression.Convert(
            // The default value, always get what the *code* tells us.
            Expression.Default(type), typeof(object)
        )
    );

    // Compile and return the value.
    return e.Compile()();
}

You should also cache the above value based on the Type, but be aware if you're calling this for a large number of Type instances, and don't use it constantly, the memory consumed by the cache might outweigh the benefits.

How to stretch in width a WPF user control to its window?

What container are you adding the UserControl to? Generally when you add controls to a Grid, they will stretch to fill the available space (unless their row/column is constrained to a certain width).

How to convert a plain object into an ES6 Map?

The answer by Nils describes how to convert objects to maps, which I found very useful. However, the OP was also wondering where this information is in the MDN docs. While it may not have been there when the question was originally asked, it is now on the MDN page for Object.entries() under the heading Converting an Object to a Map which states:

Converting an Object to a Map

The new Map() constructor accepts an iterable of entries. With Object.entries, you can easily convert from Object to Map:

const obj = { foo: 'bar', baz: 42 }; 
const map = new Map(Object.entries(obj));
console.log(map); // Map { foo: "bar", baz: 42 }

Difference between two dates in years, months, days in JavaScript

I do it this way. Precise? Maybe or maybe not. Try it

<html>
  <head>
    <title> Age Calculator</title>
  </head>

  <input type="date" id="startDate" value="2000-01-01">
  <input type="date" id="endDate"  value="2020-01-01">
  <button onclick="getAge(new Date(document.getElementById('startDate').value), new Date(document.getElementById('endDate').value))">Check Age</button>
  <script>
    function getAge (startDate, endDate) {
      var diff = endDate-startDate
      var age = new Date(new Date("0000-01-01").getTime()+diff)
      var years = age.getFullYear()
      var months = age.getMonth()
      var days = age.getDate()
      console.log(years,"years",months,"months",days-1,"days")
      return (years+"years "+ months+ "months"+ days,"days")
    }
  </script>
</html>

Working with huge files in VIM

I had the same problem, but it was a 300GB mysql dump and I wanted to get rid of the DROP and change CREATE TABLE to CREATE TABLE IF NOT EXISTS so didn't want to run two invocations of sed. I wrote this quick Ruby script to dupe the file with those changes:

#!/usr/bin/env ruby

matchers={
    %q/^CREATE TABLE `foo`/ => %q/CREATE TABLE IF NOT EXISTS `foo`/,
    %q/^DROP TABLE IF EXISTS `foo`;.*$/ => "-- DROP TABLE IF EXISTS `foo`;"
}

matchers.each_pair { |m,r|
    STDERR.puts "%s: %s" % [ m, r ]
}

STDIN.each { |line|
    #STDERR.puts "line=#{line}"
    line.chomp!
    unless matchers.length == 0
        matchers.each_pair { |m,r|
            re=/#{m}/
            next if line[re].nil?
            line.sub!(re,r)
            STDERR.puts "Matched: #{m} -> #{r}"
            matchers.delete(m)
            break
        }
    end
    puts line
}

Invoked like

./mreplace.rb < foo.sql > foo_two.sql

Why maven? What are the benefits?

Maven is one of the tools where you need to actually decide up front that you like it and want to use it, since you will spend quite some time learning it, and having made said decision once and for all will allow you to skip all kinds of doubt while learning (because you like it and want to use it)!

The strong conventions help in many places - like Hudson that can do wonders with Maven projects - but it may be hard to see initially.

edit: As of 2016 Maven is the only Java build tool where all three major IDEs can use the sources out of the box. In other words, using maven makes your build IDE-agnostic. This allows for e.g. using Netbeans profiling even if you normally work In eclipse

Dump Mongo Collection into JSON format

From the Mongo documentation:

The mongoexport utility takes a collection and exports to either JSON or CSV. You can specify a filter for the query, or a list of fields to output

Read more here: http://www.mongodb.org/display/DOCS/mongoexport

IntelliJ and Tomcat.. Howto..?

NOTE: Community Edition doesn't support JEE.

First, you will need to install a local Tomcat server. It sounds like you may have already done this.

Next, on the toolbar at the top of IntelliJ, click the down arrow just to the left of the Run and Debug icons. There will be an option to Edit Configurations. In the resulting popup, click the Add icon, then click Tomcat and Local.

From that dialog, you will need to click the Configure... button next to Application Server to tell IntelliJ where Tomcat is installed.

How to read from stdin line by line in Node

You can use the readline module to read from stdin line by line:

var readline = require('readline');
var rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout,
  terminal: false
});

rl.on('line', function(line){
    console.log(line);
})