Programs & Examples On #Dynamic dispatch

In computer science, dynamic dispatch is the process of selecting which implementation of a polymorphic operation (method or function) to call at runtime.

How does the "this" keyword work?

Since this thread has bumped up, I have compiled few points for readers new to this topic.

How is the value of this determined?

We use this similar to the way we use pronouns in natural languages like English: “John is running fast because he is trying to catch the train.” Instead we could have written “… John is trying to catch the train”.

var person = {    
    firstName: "Penelope",
    lastName: "Barrymore",
    fullName: function () {

    // We use "this" just as in the sentence above:
       console.log(this.firstName + " " + this.lastName);

    // We could have also written:
       console.log(person.firstName + " " + person.lastName);
    }
}

this is not assigned a value until an object invokes the function where it is defined. In the global scope, all global variables and functions are defined on the window object. Therefore, this in a global function refers to (and has the value of) the global window object.

When use strict, this in global and in anonymous functions that are not bound to any object holds a value of undefined.

The this keyword is most misunderstood when: 1) we borrow a method that uses this, 2) we assign a method that uses this to a variable, 3) a function that uses this is passed as a callback function, and 4) this is used inside a closure — an inner function. (2)

table

What holds the future

Defined in ECMA Script 6, arrow-functions adopt the this binding from the enclosing (function or global) scope.

function foo() {
     // return an arrow function
     return (a) => {
     // `this` here is lexically inherited from `foo()`
     console.log(this.a);
  };
}
var obj1 = { a: 2 };
var obj2 = { a: 3 };

var bar = foo.call(obj1);
bar.call( obj2 ); // 2, not 3!

While arrow-functions provide an alternative to using bind(), it’s important to note that they essentially are disabling the traditional this mechanism in favor of more widely understood lexical scoping. (1)


References:

  1. this & Object Prototypes, by Kyle Simpson. © 2014 Getify Solutions.
  2. javascriptissexy.com - http://goo.gl/pvl0GX
  3. Angus Croll - http://goo.gl/Z2RacU

How to find event listeners on a DOM node when debugging or from the JavaScript code?

It depends on how the events are attached. For illustration presume we have the following click handler:

var handler = function() { alert('clicked!') };

We're going to attach it to our element using different methods, some which allow inspection and some that don't.

Method A) single event handler

element.onclick = handler;
// inspect
console.log(element.onclick); // "function() { alert('clicked!') }"

Method B) multiple event handlers

if(element.addEventListener) { // DOM standard
    element.addEventListener('click', handler, false)
} else if(element.attachEvent) { // IE
    element.attachEvent('onclick', handler)
}
// cannot inspect element to find handlers

Method C): jQuery

$(element).click(handler);
  • 1.3.x

     // inspect
     var clickEvents = $(element).data("events").click;
     jQuery.each(clickEvents, function(key, value) {
         console.log(value) // "function() { alert('clicked!') }"
     })
    
  • 1.4.x (stores the handler inside an object)

     // inspect
     var clickEvents = $(element).data("events").click;
     jQuery.each(clickEvents, function(key, handlerObj) {
         console.log(handlerObj.handler) // "function() { alert('clicked!') }"
         // also available: handlerObj.type, handlerObj.namespace
     })
    
  • 1.7+ (very nice)

    Made using knowledge from this comment.

     events = $._data(this, 'events');
     for (type in events) {
       events[type].forEach(function (event) {
         console.log(event['handler']);
       });
     }
    

(See jQuery.fn.data and jQuery.data)

Method D): Prototype (messy)

$(element).observe('click', handler);
  • 1.5.x

     // inspect
     Event.observers.each(function(item) {
         if(item[0] == element) {
             console.log(item[2]) // "function() { alert('clicked!') }"
         }
     })
    
  • 1.6 to 1.6.0.3, inclusive (got very difficult here)

     // inspect. "_eventId" is for < 1.6.0.3 while 
     // "_prototypeEventID" was introduced in 1.6.0.3
     var clickEvents = Event.cache[element._eventId || (element._prototypeEventID || [])[0]].click;
     clickEvents.each(function(wrapper){
         console.log(wrapper.handler) // "function() { alert('clicked!') }"
     })
    
  • 1.6.1 (little better)

     // inspect
     var clickEvents = element.getStorage().get('prototype_event_registry').get('click');
     clickEvents.each(function(wrapper){
         console.log(wrapper.handler) // "function() { alert('clicked!') }"
     })
    

When clicking the resulting output in the console (which shows the text of the function), the console will navigate directly to the line of the function's declaration in the relevant JS file.

How can I close a login form and show the main form without my application closing?

Evan the post is too old i like to give you a trick to do this if you wants to show splash/login screen and when the progress bar of splash screen get certain value/or successful login happen and closed the splash/login then re show the main form, frm-main will be the startup form not frm-spalash

in frm-main

public partial class frmMain : Form
{
    public frmMain()
    { 
        frmSplash frm = new frmSplash();
        frm.Show(); // new splash screen will shows
        this.Opacity=0; // will hide your main form
        InitializeComponent();
    }
 }

in the frm-Splash

private void timer1_Tick(object sender, EventArgs e)
{
 int cnt = progressBar1.Value;

    switch (cnt)
    {
        case 0:
                //Do sum stuff
            break;
        case 100:

            this.Close(); //close the frm-splash
            frmMain.ActiveForm.Opacity = 100; // show the frm-main

            break;
    }

    progressBar1.Value = progressBar1.Value+1;
}

if you use it for login form

private void btlogin_Click(object sender, EventArgs e)
{
 bool login = false;

    //try your login here 
    //connect your database or whatever
    //and then when it success update login variable as true

        if(login == true){

            this.Close(); //close the frm-login
            frmMain.ActiveForm.Opacity = 100; // show the frm-main

        }else{
              //inform user about failed login
        }
}

note that i use a timer and a progress bar to manipulate the actions you don't need those two it just for sake of complete answer only, hope this helps

Access mysql remote database from command line

Try this command mysql -uuser -hhostname -PPORT -ppassword.

I faced a similar situation and later when mysql port for host was entered with the command, it was solved.

How can I return the difference between two lists?

I was looking for a different problem and came across this, so I will add my solution to a related problem: comparing two Maps.

    // make a copy of the data
    Map<String,String> a = new HashMap<String,String>(actual);
    Map<String,String> e = new HashMap<String,String>(expected);
    // check *every* expected value
    for(Map.Entry<String, String> val : e.entrySet()){
        // check for presence
        if(!a.containsKey(val.getKey())){
            System.out.println(String.format("Did not find expected value: %s", val.getKey()));
        }
        // check for equality
        else{
            if(0 != a.get(val.getKey()).compareTo(val.getValue())){
                System.out.println(String.format("Value does not match expected: %s", val.getValue()));
            }
            // we have found the item, so remove it 
            // from future consideration. While it 
            // doesn't affect Java Maps, other types of sets
            // may contain duplicates, this will flag those
            // duplicates. 
            a.remove(val.getKey());
        }
    }
    // check to see that we did not receive extra values
    for(Map.Entry<String,String> val : a.entrySet()){
        System.out.println(String.format("Found unexpected value: %s", val.getKey()));
    }

It works on the same principle as the other solutions but also compares not only that values are present, but that they contain the same value. Mostly I've used this in accounting software when comparing data from two sources (Employee and Manager entered values match; Customer and Corporate transactions match; ... etc)

updating table rows in postgres using subquery

If there are no performance gains using a join, then I prefer Common Table Expressions (CTEs) for readability:

WITH subquery AS (
    SELECT address_id, customer, address, partn
    FROM  /* big hairy SQL */ ...
)
UPDATE dummy
SET customer = subquery.customer,
    address  = subquery.address,
    partn    = subquery.partn
FROM subquery
WHERE dummy.address_id = subquery.address_id;

IMHO a bit more modern.

How to get child element by class name?

In my opinion, each time you can, you should use Array and its methods. They are much, much faster then looping over the whole DOM / wrapper, or pushing stuff into empty array. Majority of solutions presented here you can call Naive as described here (great article btw):

https://medium.com/@chuckdries/traversing-the-dom-with-filter-map-and-arrow-functions-1417d326d2bc

My solution: (live preview on Codepen: https://codepen.io/Nikolaus91/pen/wEGEYe)

const wrapper = document.getElementById('test') // take a wrapper by ID -> fastest
const itemsArray = Array.from(wrapper.children) // make Array from his children

const pickOne = itemsArray.map(item => { // loop over his children using .map() --> see MDN for more
   if(item.classList.contains('four')) // we place a test where we determine our choice
     item.classList.add('the-chosen-one') // your code here
})

Android Drawing Separator/Divider Line in Layout?

To complete Camille Sévigny answer you can additionally define your own line shape for example to custom the line color.

Define an xml shape in drawable directory. line_horizontal.xml:

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto" android:shape="line">
    <stroke android:width="2dp" android:color="@android:color/holo_blue_dark" />
    <size android:width="5dp" />
</shape>

Use this line in your layout with the wished attributes:

    <ImageView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:paddingBottom="2dp"
        android:paddingLeft="5dp"
        android:paddingRight="5dp"
        android:paddingTop="2dp"
        android:src="@drawable/line_horizontal" />

React.createElement: type is invalid -- expected a string

For future googlers:

My solution to this problem was to upgrade react and react-dom to their latest versions on NPM. Apparently I was importing a Component that was using the new fragment syntax and it was broken in my older version of React.

What is the simplest method of inter-process communication between 2 C# processes?

Anonymous pipes.

Use Asynchronous operations with BeginRead/BeginWrite and AsyncCallback.

Changing :hover to touch/click for mobile devices

A CSS only solution for those who are having trouble with mobile touchscreen button styling.

This will fix your hover-stick / active button problems.

_x000D_
_x000D_
body, html {
  width: 600px;
}
p {
  font-size: 20px;
}

button {
  border: none;
  width: 200px;
  height: 60px;
  border-radius: 30px;
  background: #00aeff;
  font-size: 20px;
}

button:active {
  background: black;
  color: white;
}

.delayed {
  transition: all 0.2s;
  transition-delay: 300ms;
}

.delayed:active {
  transition: none;
}
_x000D_
<h1>Sticky styles for better touch screen buttons!</h1>

<button>Normal button</button>

<button class="delayed"><a href="https://www.google.com"/>Delayed style</a></button>

<p>The CSS :active psuedo style is displayed between the time when a user touches down (when finger contacts screen) on a element to the time when the touch up (when finger leaves the screen) occures.   With a typical touch-screen tap interaction, the time of which the :active psuedo style is displayed can be very small resulting in the :active state not showing or being missed by the user entirely.  This can cause issues with users not undertanding if their button presses have actually reigstered or not.</p>

<p>Having the the :active styling stick around for a few hundred more milliseconds after touch up would would improve user understanding when they have interacted with a button.</p>
_x000D_
_x000D_
_x000D_

C dynamically growing array

There are a couple of options I can think of.

  1. Linked List. You can use a linked list to make a dynamically growing array like thing. But you won't be able to do array[100] without having to walk through 1-99 first. And it might not be that handy for you to use either.
  2. Large array. Simply create an array with more than enough space for everything
  3. Resizing array. Recreate the array once you know the size and/or create a new array every time you run out of space with some margin and copy all the data to the new array.
  4. Linked List Array combination. Simply use an array with a fixed size and once you run out of space, create a new array and link to that (it would be wise to keep track of the array and the link to the next array in a struct).

It is hard to say what option would be best in your situation. Simply creating a large array is ofcourse one of the easiest solutions and shouldn't give you much problems unless it's really large.

Printing the value of a variable in SQL Developer

DECLARE

  CTABLE USER_OBJECTS.OBJECT_NAME%TYPE;
  CCOLUMN ALL_TAB_COLS.COLUMN_NAME%TYPE;
  V_ALL_COLS VARCHAR2(5000);

  CURSOR CURSOR_TABLE
    IS
    SELECT OBJECT_NAME 
    FROM USER_OBJECTS 
    WHERE OBJECT_TYPE='TABLE'
    AND OBJECT_NAME LIKE 'STG%';

  CURSOR CURSOR_COLUMNS (V_TABLE_NAME IN VARCHAR2)
    IS
    SELECT COLUMN_NAME
    FROM ALL_TAB_COLS
    WHERE TABLE_NAME = V_TABLE_NAME;

BEGIN

  OPEN CURSOR_TABLE;
  LOOP
    FETCH CURSOR_TABLE INTO CTABLE;

    OPEN CURSOR_COLUMNS (CTABLE);
    V_ALL_COLS := NULL;
    LOOP

      FETCH CURSOR_COLUMNS INTO CCOLUMN;
      V_ALL_COLS := V_ALL_COLS || CCOLUMN;
      IF CURSOR_COLUMNS%FOUND THEN
        V_ALL_COLS := V_ALL_COLS || ', ';
      ELSE
        EXIT;
      END IF;
    END LOOP;
   close CURSOR_COLUMNS ;
    DBMS_OUTPUT.PUT_LINE(V_ALL_COLS);
    EXIT WHEN CURSOR_TABLE%NOTFOUND;
  END LOOP;`enter code here`
  CLOSE CURSOR_TABLE;

END;

I have added Close of second cursor. It working and getting output as well...

Linker Error C++ "undefined reference "

Your error shows you are not compiling file with the definition of the insert function. Update your command to include the file which contains the definition of that function and it should work.

How do I view the Explain Plan in Oracle Sql developer?

EXPLAIN PLAN FOR

In SQL Developer, you don't have to use EXPLAIN PLAN FOR statement. Press F10 or click the Explain Plan icon.

enter image description here

It will be then displayed in the Explain Plan window.

If you are using SQL*Plus then use DBMS_XPLAN.

For example,

SQL> EXPLAIN PLAN FOR
  2  SELECT * FROM DUAL;

Explained.

SQL> SELECT * FROM TABLE(DBMS_XPLAN.DISPLAY);

PLAN_TABLE_OUTPUT
--------------------------------------------------------------------------
Plan hash value: 272002086

--------------------------------------------------------------------------
| Id  | Operation         | Name | Rows  | Bytes | Cost (%CPU)| Time     |
--------------------------------------------------------------------------
|   0 | SELECT STATEMENT  |      |     1 |     2 |     2   (0)| 00:00:01 |
|   1 |  TABLE ACCESS FULL| DUAL |     1 |     2 |     2   (0)| 00:00:01 |
--------------------------------------------------------------------------

8 rows selected.

SQL>

See How to create and display Explain Plan

How to add some non-standard font to a website?

Typeface.js JavaScript Way:

With typeface.js you can embed custom fonts in your web pages so you don't have to render text to images

Instead of creating images or using flash just to show your site's graphic text in the font you want, you can use typeface.js and write in plain HTML and CSS, just as if your visitors had the font installed locally.

http://typeface.neocracy.org/

How to find rows in one table that have no corresponding row in another table

For my small dataset, Oracle gives almost all of these queries the exact same plan that uses the primary key indexes without touching the table. The exception is the MINUS version which manages to do fewer consistent gets despite the higher plan cost.

--Create Sample Data.
d r o p table tableA;
d r o p table tableB;

create table tableA as (
   select rownum-1 ID, chr(rownum-1+70) bb, chr(rownum-1+100) cc 
      from dual connect by rownum<=4
);

create table tableB as (
   select rownum ID, chr(rownum+70) data1, chr(rownum+100) cc from dual
   UNION ALL
   select rownum+2 ID, chr(rownum+70) data1, chr(rownum+100) cc 
      from dual connect by rownum<=3
);

a l t e r table tableA Add Primary Key (ID);
a l t e r table tableB Add Primary Key (ID);

--View Tables.
select * from tableA;
select * from tableB;

--Find all rows in tableA that don't have a corresponding row in tableB.

--Method 1.
SELECT id FROM tableA WHERE id NOT IN (SELECT id FROM tableB) ORDER BY id DESC;

--Method 2.
SELECT tableA.id FROM tableA LEFT JOIN tableB ON (tableA.id = tableB.id)
WHERE tableB.id IS NULL ORDER BY tableA.id DESC;

--Method 3.
SELECT id FROM tableA a WHERE NOT EXISTS (SELECT 1 FROM tableB b WHERE b.id = a.id) 
   ORDER BY id DESC;

--Method 4.
SELECT id FROM tableA
MINUS
SELECT id FROM tableB ORDER BY id DESC;

Set new id with jQuery

Use .val() not attr('value').

How to restore/reset npm configuration to default values?

To reset user defaults

Run this in the command line (or git bash on windows):

echo "" > $(npm config get userconfig)
npm config edit

To reset global defaults

echo "" > $(npm config get globalconfig)
npm config --global edit

If you need sudo then run this instead:

sudo sh -c 'echo "" > $(npm config get globalconfig)'

LaTeX: Prevent line break in a span of text

Also, if you have two subsequent words in regular text and you want to avoid a line break between them, you can use the ~ character.

For example:

As we can see in Fig.~\ref{BlaBla}, there is nothing interesting to see. A~better place..

This can ensure that you don't have a line starting with a figure number (without the Fig. part) or with an uppercase A.

In WPF, what are the differences between the x:Name and Name attributes?

When you declare a Button element in XAML you are referring to a class defined in windows run time called Button.

Button has many attribute such as background, text, margin, ..... and an attribute called Name.

Now when you declare a Button in XAML is like creating an anonymous object that happened to have an attribute called Name.

In general you can not refer to an anonymous object, but in WPF framework XAML processor enables you to refer to that object by whatever value you have given to Name attribute.

So far so good.

Another way to create an object is create a named object instead of anonymous object. In this case XAML namespace has an attribute for an object called Name (and since it is in XAML name space thus have X:) that you may set so you can identify your object and refer to it.

Conclusion:

Name is an attribute of a specific object, but X:Name is one attribute of that object (there is a class that defines a general object).

Should MySQL have its timezone set to UTC?

How about making your app agnostic of the server's timezone?

Owing to any of these possible scenarios:

  • You might not have control over the web/database server's timezone settings
  • You might mess up and set the settings incorrectly
  • There are so many settings as described in the other answers, and so many things to keep track of, that you might miss something
  • An update on the server, or a software reset, or another admin, might unknowing reset the servers' timezone to the default - thus breaking your application

All of the above scenarios give rise to breaking of your application's time calculations. Thus it appears that the better approach is to make your application work independent of the server's timezone.

The idea is simply to always create dates in UTC before storing them into the database, and always re-create them from the stored values in UTC as well. This way, the time calculations won't ever be incorrect, because they're always in UTC. This can be achieved by explicity stating the DateTimeZone parameter when creating a PHP DateTime object.

On the other hand, the client side functionality can be configured to convert all dates/times received from the server to the client's timezone. Libraries like moment.js make this super easy to do.

For example, when storing a date in the database, instead of using the NOW() function of MySQL, create the timestamp string in UTC as follows:

// Storing dates
$date = new DateTime('now', new DateTimeZone('UTC'));
$sql = 'insert into table_name (date_column) values ("' . $date . '")';

// Retreiving dates
$sql = 'select date_column from table_name where condition';
$dateInUTC = new DateTime($date_string_from_db, new DateTimeZone('UTC'));

You can set the default timezone in PHP for all dates created, thus eliminating the need to initialize the DateTimeZone class every time you want to create a date.

What is Android keystore file, and what is it used for?

You can find more information about the signing process on the official Android documentation here : http://developer.android.com/guide/publishing/app-signing.html

Yes, you can sign several applications with the same keystore. But you must remember one important thing : if you publish an app on the Play Store, you have to sign it with a non debug certificate. And if one day you want to publish an update for this app, the keystore used to sign the apk must be the same. Otherwise, you will not be able to post your update.

How to avoid reverse engineering of an APK file?

First rule of app security: Any machine to which an attacker gains unrestricted physical or electronic access now belongs to your attacker, regardless of where it actually is or what you paid for it.

Second rule of app security: Any software that leaves the physical boundaries inside which an attacker cannot penetrate now belongs to your attacker, regardless of how much time you spent coding it.

Third rule: Any information that leaves those same physical boundaries that an attacker cannot penetrate now belongs to your attacker, no matter how valuable it is to you.

The foundations of information technology security are based on these three fundamental principles; the only truly secure computer is the one locked in a safe, inside a Farraday cage, inside a steel cage. There are computers that spend most of their service lives in just this state; once a year (or less), they generate the private keys for trusted root certification authorities (in front of a host of witnesses with cameras recording every inch of the room in which they are located).

Now, most computers are not used under these types of environments; they're physically out in the open, connected to the Internet over a wireless radio channel. In short, they're vulnerable, as is their software. They are therefore not to be trusted. There are certain things that computers and their software must know or do in order to be useful, but care must be taken to ensure that they can never know or do enough to cause damage (at least not permanent damage outside the bounds of that single machine).

You already knew all this; that's why you're trying to protect the code of your application. But, therein lies the first problem; obfuscation tools can make the code a mess for a human to try to dig through, but the program still has to run; that means the actual logic flow of the app and the data it uses are unaffected by obfuscation. Given a little tenacity, an attacker can simply un-obfuscate the code, and that's not even necessary in certain cases where what he's looking at can't be anything else but what he's looking for.

Instead, you should be trying to ensure that an attacker cannot do anything with your code, no matter how easy it is for him to obtain a clear copy of it. That means, no hard-coded secrets, because those secrets aren't secret as soon as the code leaves the building in which you developed it.

These key-values you have hard-coded should be removed from the application's source code entirely. Instead, they should be in one of three places; volatile memory on the device, which is harder (but still not impossible) for an attacker to obtain an offline copy of; permanently on the server cluster, to which you control access with an iron fist; or in a second data store unrelated to your device or servers, such as a physical card or in your user's memories (meaning it will eventually be in volatile memory, but it doesn't have to be for long).

Consider the following scheme. The user enters their credentials for the app from memory into the device. You must, unfortunately, trust that the user's device is not already compromised by a keylogger or Trojan; the best you can do in this regard is to implement multi-factor security, by remembering hard-to-fake identifying information about the devices the user has used (MAC/IP, IMEI, etc), and providing at least one additional channel by which a login attempt on an unfamiliar device can be verified.

The credentials, once entered, are obfuscated by the client software (using a secure hash), and the plain-text credentials discarded; they have served their purpose. The obfuscated credentials are sent over a secure channel to the certificate-authenticated server, which hashes them again to produce the data used to verify the validity of the login. This way, the client never knows what is actually compared to the database value, the app server never knows the plaintext credentials behind what it receives for validation, the data server never knows how the data it stores for validation is produced, and a man in the middle sees only gibberish even if the secure channel were compromised.

Once verified, the server transmits back a token over the channel. The token is only useful within the secure session, is composed of either random noise or an encrypted (and thus verifiable) copy of the session identifiers, and the client application must send this token on the same channel to the server as part of any request to do something. The client application will do this many times, because it can't do anything involving money, sensitive data, or anything else that could be damaging by itself; it must instead ask the server to do this task. The client application will never write any sensitive information to persistent memory on the device itself, at least not in plain text; the client can ask the server over the secure channel for a symmetric key to encrypt any local data, which the server will remember; in a later session the client can ask the server for the same key to decrypt the data for use in volatile memory. That data won't be the only copy, either; anything the client stores should also be transmitted in some form to the server.

Obviously, this makes your application heavily dependent on Internet access; the client device cannot perform any of its basic functions without proper connection to and authentication by the server. No different than Facebook, really.

Now, the computer that the attacker wants is your server, because it and not the client app/device is the thing that can make him money or cause other people pain for his enjoyment. That's OK; you get much more bang for your buck spending money and effort to secure the server than in trying to secure all the clients. The server can be behind all kinds of firewalls and other electronic security, and additionally can be physically secured behind steel, concrete, keycard/pin access, and 24-hour video surveillance. Your attacker would need to be very sophisticated indeed to gain any kind of access to the server directly, and you would (should) know about it immediately.

The best an attacker can do is steal a user's phone and credentials and log in to the server with the limited rights of the client. Should this happen, just like losing a credit card, the legitimate user should be instructed to call an 800 number (preferably easy to remember, and not on the back of a card they'd carry in their purse, wallet or briefcase which could be stolen alongside the mobile device) from any phone they can access that connects them directly to your customer service. They state their phone was stolen, provide some basic unique identifier, and the account is locked, any transactions the attacker may have been able to process are rolled back, and the attacker is back to square one.

Space between border and content? / Border distance from content?

Add padding. Padding the element will increase the space between its content and its border. However, note that a box-shadow will begin outside the border, not the content, meaning you can't put space between the shadow and the box. Alternatively you could use :before or :after pseudo selectors on the element to create a slightly bigger box that you place the shadow on, like so: http://jsbin.com/aqemew/edit#source

How can I detect browser type using jQuery?

You can use this code to find correct browser and you can make changes for any target browser.....

_x000D_
_x000D_
function myFunction() { _x000D_
        if((navigator.userAgent.indexOf("Opera") || navigator.userAgent.indexOf('OPR')) != -1 ){_x000D_
            alert('Opera');_x000D_
        }_x000D_
        else if(navigator.userAgent.indexOf("Chrome") != -1 ){_x000D_
            alert('Chrome');_x000D_
        }_x000D_
        else if(navigator.userAgent.indexOf("Safari") != -1){_x000D_
            alert('Safari');_x000D_
        }_x000D_
        else if(navigator.userAgent.indexOf("Firefox") != -1 ){_x000D_
             alert('Firefox');_x000D_
        }_x000D_
        else if((navigator.userAgent.indexOf("MSIE") != -1 ) || (!!document.documentMode == true )){_x000D_
          alert('IE'); _x000D_
        }  _x000D_
        else{_x000D_
           alert('unknown');_x000D_
        }_x000D_
    }
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
<head>_x000D_
 <title>Browser detector</title>_x000D_
_x000D_
</head>_x000D_
<body onload="myFunction()">_x000D_
// your code here _x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

SQL statement to get column type

Using SQL Server:

SELECT DATA_TYPE 
FROM INFORMATION_SCHEMA.COLUMNS
WHERE 
     TABLE_NAME = 'yourTableName' AND 
     COLUMN_NAME = 'yourColumnName'

How to implement class constants?

For me none of earlier answer works. I did need to convert my static class to enum. Like this:

export enum MyConstants {
  MyFirstConstant = 'MyFirstConstant',
  MySecondConstant = 'MySecondConstant'
}

Then in my component I add new property as suggested in other answers

export class MyComponent {
public MY_CONTANTS = MyConstans;
constructor() { }
}

Then in my component's template I use it this way

<div [myDirective]="MY_CONTANTS.MyFirstConstant"> </div>

EDIT: Sorry. My problem was different than OP's. I still leave this here if someelse have same problem than I.

Drop a temporary table if it exists

Check for the existence by retrieving its object_id:

if object_id('tempdb..##clients_keyword') is not null
    drop table ##clients_keyword

Executing <script> injected by innerHTML after AJAX call

Here is the script that will evaluates all script tags in the text.

function evalJSFromHtml(html) {
  var newElement = document.createElement('div');
  newElement.innerHTML = html;

  var scripts = newElement.getElementsByTagName("script");
  for (var i = 0; i < scripts.length; ++i) {
    var script = scripts[i];
    eval(script.innerHTML);
  }
}

Just call this function after you receive your HTML from server. Be warned: using eval can be dangerous.

Demo: http://plnkr.co/edit/LA7OPkRfAtgOhwcAnLrl?p=preview

how to do file upload using jquery serialization

$(document).on('click', '#submitBtn', function(e){
e.preventDefault();
e.stopImmediatePropagation();
var form = $("#myForm").closest("form");
var formData = new FormData(form[0]);
$.ajax({
    type: "POST",
    data: formData,
    dataType: "json",
    url: form.attr('action'),
    processData: false,
    contentType: false,
    success: function(data) {
         alert('Sucess! Form data posted with file type of input also!');
    }
)};});

By making use of new FormData() and setting processData: false, contentType:false in ajax call submission of form with file input worked for me

Using above code I am able to submit form data with file field also through Ajax

applying css to specific li class

The CSS you have applies color #c1c1c1 to all <a> elements.

And it also applies color #c1c1c1 to the first <li> element.

Perhaps the code you posted is missing something because I don't see any other colors being defined.

What is the best way to get the minimum or maximum value from an Array of numbers?

You have to loop through the array, no other way to check all elements. Just one correction for the code - if all elements are negative, maxValue will be 0 at the end. You should initialize it with the minimum possible value for integer.
And if you are going to search the array many times it's a good idea to sort it first, than searching is faster (binary search) and minimum and maximum elements are just the first and the last.

get launchable activity name of package from adb

I didn't find it listed so updating the list.

You need to have the apk installed and running in front on your phone for this solution:

Windows CMD line:

adb shell dumpsys window windows | findstr <any unique string from your pkg Name>

Linux Terminal:

adb shell dumpsys window windows | grep -i <any unique string from your Pkg Name>

OUTPUT for Calculator package would be:

Window #7 Window{39ced4b1 u0 com.android.calculator2/com.android.calculator2.Calculator}:

    mOwnerUid=10036 mShowToOwnerOnly=true package=com.android.calculator2 appop=NONE

    mToken=AppWindowToken{29a4bed4 token=Token{2f850b1a ActivityRecord{eefe5c5 u0 com.android.calculator2/.Calculator t322}}}

    mRootToken=AppWindowToken{29a4bed4 token=Token{2f850b1a ActivityRecord{eefe5c5 u0 com.android.calculator2/.Calculator t322}}}

    mAppToken=AppWindowToken{29a4bed4 token=Token{2f850b1a ActivityRecord{eefe5c5 u0 com.android.calculator2/.Calculator t322}}}

    WindowStateAnimator{3e160d22 com.android.calculator2/com.android.calculator2.Calculator}:

      mSurface=Surface(name=com.android.calculator2/com.android.calculator2.Calculator)

  mCurrentFocus=Window{39ced4b1 u0 com.android.calculator2/com.android.calculator2.Calculator}

  mFocusedApp=AppWindowToken{29a4bed4 token=Token{2f850b1a ActivityRecord{eefe5c5 u0 com.android.calculator2/.Calculator t322}}}

Main part is, First Line:

Window #7 Window{39ced4b1 u0 com.android.calculator2/com.android.calculator2.Calculator}:

First part of the output is package name:

com.android.calculator2

Second Part of output (which is after /) can be two things, in our case its:

com.android.calculator2.Calculator

  1. <PKg name>.<activity name> = <com.android.calculator2>.<Calculator>

    so .Calculator is our activity

  2. If second part is entirely different from Package name and doesn't seem to contain pkg name which was before / in out output, then entire second part can be used as main activity.

Can't start Tomcat as Windows Service

  1. Check the apache tomcat catalina log: ../logs/catalina.log
  2. If in the log you find the "port was used" exception, then Check windows used ports and processes with following command: Run cmd netstat -ao it will list all listening ports and corresponding process Id, you can find the port which was used by Tomcat from the configuration file: ../conf/server.xml

    <Connector port="8080" protocol="HTTP/1.1"
           connectionTimeout="20000"
           redirectPort="8443" />
    

and kill the process which use the tomcat port

HTML: Image won't display?

I confess to not having read the whole thread. However when I faced a similar issue I found that checking carefully the case of the file name and correcting that in the HTML reference fixed a similar issue. So local preview on Windows worked but when I published to my server (hosted Linux) I had to make sure "mugshot.jpg" was changed to "mugshot.JPG". Part of the problem is the defaults in Windows hiding full file names behind file type indications.

How do I find out my python path using python?

import subprocess
python_path = subprocess.check_output("which python", shell=True).strip()
python_path = python_path.decode('utf-8')

Loading scripts after page load?

http://jsfiddle.net/c725wcn9/2/embedded

You will need to inspect the DOM to check this works. Jquery is needed.

$(document).ready(function(){
   var el = document.createElement('script');
   el.type = 'application/ld+json';
   el.text = JSON.stringify({ "@context": "http://schema.org",  "@type": "Recipe", "name": "My recipe name" });

   document.querySelector('head').appendChild(el);
});

How do you build a Singleton in Dart?

I use this simple pattern on dart and previously on Swift. I like that it's terse and only one way of using it.

class Singleton {
  static Singleton shared = Singleton._init();
  Singleton._init() {
    // init work here
  }

  void doSomething() {
  }
}

Singleton.shared.doSomething();

How do I implement a progress bar in C#?

The idea behind reporting progress with the background worker is through sending a 'percent completed' event. You are yourself responsible for determining somehow 'how much' work has been completed. Unfortunately this is often the most difficult part.

In your case, the bulk of the work is database-related. There is to my knowledge no way to get progress information from the DB directly. What you can try to do however, is split up the work dynamically. E.g., if you need to read a lot of data, a naive way to implement this could be.

  • Determine how many rows are to be retrieved (SELECT COUNT(*) FROM ...)
  • Divide the actual reading in smaller chunks, reporting progress every time one chunk is completed:

    for (int i = 0; i < count; i++)
    {
        bgWorker.ReportProgress((100 * i) / count);
        // ... (read data for step i)
    }
    

How to add pandas data to an existing csv file?

You can append to a csv by opening the file in append mode:

with open('my_csv.csv', 'a') as f:
    df.to_csv(f, header=False)

If this was your csv, foo.csv:

,A,B,C
0,1,2,3
1,4,5,6

If you read that and then append, for example, df + 6:

In [1]: df = pd.read_csv('foo.csv', index_col=0)

In [2]: df
Out[2]:
   A  B  C
0  1  2  3
1  4  5  6

In [3]: df + 6
Out[3]:
    A   B   C
0   7   8   9
1  10  11  12

In [4]: with open('foo.csv', 'a') as f:
             (df + 6).to_csv(f, header=False)

foo.csv becomes:

,A,B,C
0,1,2,3
1,4,5,6
0,7,8,9
1,10,11,12

How to unpack an .asar file?

From the asar documentation

(the use of npx here is to avoid to install the asar tool globally with npm install -g asar)

Extract the whole archive:

npx asar extract app.asar destfolder 

Extract a particular file:

npx asar extract-file app.asar main.js

Find elements inside forms and iframe using Java and Selenium WebDriver

On Selenium >= 3.41 (C#) the rigth syntax is:

webDriver = webDriver.SwitchTo().Frame(webDriver.FindElement(By.Name("icontent")));

Get the time difference between two datetimes

If we want only hh:mm:ss, we can use a function like that:

//param: duration in milliseconds
MillisecondsToTime: function(duration) {
    var seconds = parseInt((duration/1000)%60)
        , minutes = parseInt((duration/(1000*60))%60)
        , hours = parseInt((duration/(1000*60*60))%24)
        , days  = parseInt(duration/(1000*60*60*24));

    var hoursDays = parseInt(days*24);
    hours += hoursDays;
    hours = (hours < 10) ? "0" + hours : hours;
    minutes = (minutes < 10) ? "0" + minutes : minutes;
    seconds = (seconds < 10) ? "0" + seconds : seconds;
    return hours + ":" + minutes + ":" + seconds;
}

Extract a page from a pdf as a jpeg

GhostScript performs much faster than Poppler for a Linux based system.

Following is the code for pdf to image conversion.

def get_image_page(pdf_file, out_file, page_num):
    page = str(page_num + 1)
    command = ["gs", "-q", "-dNOPAUSE", "-dBATCH", "-sDEVICE=png16m", "-r" + str(RESOLUTION), "-dPDFFitPage",
               "-sOutputFile=" + out_file, "-dFirstPage=" + page, "-dLastPage=" + page,
               pdf_file]
    f_null = open(os.devnull, 'w')
    subprocess.call(command, stdout=f_null, stderr=subprocess.STDOUT)

GhostScript can be installed on macOS using brew install ghostscript

Installation information for other platforms can be found here. If it is not already installed on your system.

JavaScript or jQuery browser back button click detector

Found this to work well cross browser and mobile back_button_override.js .

(Added a timer for safari 5.0)

// managage back button click (and backspace)
var count = 0; // needed for safari
window.onload = function () { 
    if (typeof history.pushState === "function") { 
        history.pushState("back", null, null);          
        window.onpopstate = function () { 
            history.pushState('back', null, null);              
            if(count == 1){window.location = 'your url';}
         }; 
     }
 }  
setTimeout(function(){count = 1;},200);

JUnit Testing private variables?

I can't tell if you've found some special case code which requires you to test against private fields. But in my experience you never have to test something private - always public. Maybe you could give an example of some code where you need to test private?

SQL - select distinct only on one column

A very typical approach to this type of problem is to use row_number():

select t.*
from (select t.*,
             row_number() over (partition by number order by id) as seqnum
      from t
     ) t
where seqnum = 1;

This is more generalizable than using a comparison to the minimum id. For instance, you can get a random row by using order by newid(). You can select 2 rows by using where seqnum <= 2.

SQL state [99999]; error code [17004]; Invalid column type: 1111 With Spring SimpleJdbcCall

I have a function which returns a CLOB and I was seeing the above error when I'd forgotten to declare the return value as an output parameter. Initially I had:

protected SimpleJdbcCall buildJdbcCall(JdbcTemplate jdbcTemplate)
{
    SimpleJdbcCall call = new SimpleJdbcCall(jdbcTemplate)
        .withSchemaName(schema)
        .withCatalogName(catalog)
        .withFunctionName(functionName)
        .withReturnValue()          
        .declareParameters(buildSqlParameters());

    return call;
}

public SqlParameter[] buildSqlParameters() {
    return new SqlParameter[]{
        new SqlParameter("p_names", Types.VARCHAR),
        new SqlParameter("p_format", Types.VARCHAR),
        new SqlParameter("p_units", Types.VARCHAR),
        new SqlParameter("p_datums", Types.VARCHAR),
        new SqlParameter("p_start", Types.VARCHAR),
        new SqlParameter("p_end", Types.VARCHAR),
        new SqlParameter("p_timezone", Types.VARCHAR),
        new SqlParameter("p_office_id", Types.VARCHAR),
        };
}

The buildSqlParameters method should have included the SqlOutParameter:

public SqlParameter[] buildSqlParameters() {
    return new SqlParameter[]{
        new SqlParameter("p_names", Types.VARCHAR),
        new SqlParameter("p_format", Types.VARCHAR),
        new SqlParameter("p_units", Types.VARCHAR),
        new SqlParameter("p_datums", Types.VARCHAR),
        new SqlParameter("p_start", Types.VARCHAR),
        new SqlParameter("p_end", Types.VARCHAR),
        new SqlParameter("p_timezone", Types.VARCHAR),
        new SqlParameter("p_office_id", Types.VARCHAR),
        new SqlOutParameter("l_clob", Types.CLOB)  // <-- This was missing!
    }; 
}

How to JUnit test that two List<E> contain the same elements in the same order?

I prefer using Hamcrest because it gives much better output in case of a failure

Assert.assertThat(listUnderTest, 
       IsIterableContainingInOrder.contains(expectedList.toArray()));

Instead of reporting

expected true, got false

it will report

expected List containing "1, 2, 3, ..." got list containing "4, 6, 2, ..."

IsIterableContainingInOrder.contain

Hamcrest

According to the Javadoc:

Creates a matcher for Iterables that matches when a single pass over the examined Iterable yields a series of items, each logically equal to the corresponding item in the specified items. For a positive match, the examined iterable must be of the same length as the number of specified items

So the listUnderTest must have the same number of elements and each element must match the expected values in order.

git push says "everything up-to-date" even though I have local changes

Maybe you're pushing a new local branch?

A new local branch must be pushed explicitly:

git push origin your-new-branch-name

Just one of those things about git... You clone a repo, make a branch, commit some changes, push... "Everything is up to date". I understand why it happens, but this workflow is extremely unfriendly to newcomers.

Numpy - add row to array

You can also do this:

newrow = [1,2,3]
A = numpy.concatenate((A,newrow))

What is the difference between $routeProvider and $stateProvider?

Angular's own ng-Router takes URLs into consideration while routing, UI-Router takes states in addition to URLs.

States are bound to named, nested and parallel views, allowing you to powerfully manage your application's interface.

While in ng-router, you have to be very careful about URLs when providing links via <a href=""> tag, in UI-Router you have to only keep state in mind. You provide links like <a ui-sref="">. Note that even if you use <a href=""> in UI-Router, just like you would do in ng-router, it will still work.

So, even if you decide to change your URL some day, your state will remain same and you need to change URL only at .config.

While ngRouter can be used to make simple apps, UI-Router makes development much easier for complex apps. Here its wiki.

Most efficient way to create a zero filled JavaScript array?

I have nothing against:

Array.apply(null, Array(5)).map(Number.prototype.valueOf,0);
new Array(5+1).join('0').split('').map(parseFloat);

suggested by Zertosh, but in a new ES6 array extensions allow you to do this natively with fill method. Now IE edge, Chrome and FF supports it, but check the compatibility table

new Array(3).fill(0) will give you [0, 0, 0]. You can fill the array with any value like new Array(5).fill('abc') (even objects and other arrays).

On top of that you can modify previous arrays with fill:

arr = [1, 2, 3, 4, 5, 6]
arr.fill(9, 3, 5)  # what to fill, start, end

which gives you: [1, 2, 3, 9, 9, 6]

php, mysql - Too many connections to database error

This can happen due to too many connection same time or many chat at same time. Also it can happen due too many session.

The best way to sort out this issue is restart MySQL.

service mysqld restart

or

service mysql restart

or

 /etc/init.d/mysqld restart

How to plot two histograms together in R?

Here is an even simpler solution using base graphics and alpha-blending (which does not work on all graphics devices):

set.seed(42)
p1 <- hist(rnorm(500,4))                     # centered at 4
p2 <- hist(rnorm(500,6))                     # centered at 6
plot( p1, col=rgb(0,0,1,1/4), xlim=c(0,10))  # first histogram
plot( p2, col=rgb(1,0,0,1/4), xlim=c(0,10), add=T)  # second

The key is that the colours are semi-transparent.

Edit, more than two years later: As this just got an upvote, I figure I may as well add a visual of what the code produces as alpha-blending is so darn useful:

enter image description here

How to get request URI without context path?

getPathInfo() sometimes return null. In documentation HttpServletRequest

This method returns null if there was no extra path information.

I need get path to file without context path in Filter and getPathInfo() return me null. So I use another method: httpRequest.getServletPath()

public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException
{
    HttpServletRequest httpRequest = (HttpServletRequest) request;
    HttpServletResponse httpResponse = (HttpServletResponse) response;

    String newPath = parsePathToFile(httpRequest.getServletPath());
    ...

}

How to run a cron job inside a docker container?

Another route you can take is Ofelia, which is a highly configurable task runner image that allows 4 modes of execution.

job-exec: this job is executed inside of a running container.
job-run: runs a command inside of a new container, using a specific image.
job-local: runs the command inside of the host running ofelia.
job-service-run: runs the command inside a new "run-once" service, for running inside a swarm

The advantage here is that somebody else has done all the heavy lifting for you. Super convenient and easy.

It also has a spiffy official mascot.

enter image description here

Get values from an object in JavaScript

I am sorry that your concluding question is not that clear but you are wrong from the very first line. The variable data is an Object not an Array

To access the attributes of an object is pretty easy:

alert(data.second);

But, if this does not completely answer your question, please clarify it and post back.

Thanks !

How to catch all exceptions in c# using try and catch?

Both approaches will catch all exceptions. There is no significant difference between your two code examples except that the first will generate a compiler warning because ex is declared but not used.

But note that some exceptions are special and will be rethrown automatically.

ThreadAbortException is a special exception that can be caught, but it will automatically be raised again at the end of the catch block.

http://msdn.microsoft.com/en-us/library/system.threading.threadabortexception.aspx


As mentioned in the comments, it is usually a very bad idea to catch and ignore all exceptions. Usually you want to do one of the following instead:

  • Catch and ignore a specific exception that you know is not fatal.

    catch (SomeSpecificException)
    {
        // Ignore this exception.
    }
    
  • Catch and log all exceptions.

    catch (Exception e)
    {
        // Something unexpected went wrong.
        Log(e);
        // Maybe it is also necessary to terminate / restart the application.
    }
    
  • Catch all exceptions, do some cleanup, then rethrow the exception.

    catch
    {
        SomeCleanUp();
        throw;
    }
    

Note that in the last case the exception is rethrown using throw; and not throw ex;.

Connection refused on docker container

If you are using Docker toolkit on window 10 home you will need to access the webpage through docker-machine ip command. It is generally 192.168.99.100:

It is assumed that you are running with publish command like below.

docker run -it -p 8080:8080 demo

With Window 10 pro version you can access with localhost or corresponding loopback 127.0.0.1:8080 etc (Tomcat or whatever you wish). This is because you don't have a virtual box there and docker is running directly on Window Hyper V and loopback is directly accessible.

Verify the hosts file in window for any digression. It should have 127.0.0.1 mapped to localhost

Remove Unnamed columns in pandas dataframe

df = df.loc[:, ~df.columns.str.contains('^Unnamed')]

In [162]: df
Out[162]:
   colA  ColB  colC  colD  colE  colF  colG
0    44    45    26    26    40    26    46
1    47    16    38    47    48    22    37
2    19    28    36    18    40    18    46
3    50    14    12    33    12    44    23
4    39    47    16    42    33    48    38

if the first column in the CSV file has index values, then you can do this instead:

df = pd.read_csv('data.csv', index_col=0)

In Excel, sum all values in one column in each row where another column is a specific value

You could do this using SUMIF. This allows you to SUM a value in a cell IF a value in another cell meets the specified criteria. Here's an example:

 -   A         B
 1   100       YES
 2   100       YES
 3   100       NO

Using the formula: =SUMIF(B1:B3, "YES", A1:A3), you will get the result of 200.

Here's a screenshot of a working example I just did in Excel:

Excel SUMIF Example

Reason: no suitable image found

In my case ,the keychain is showing the certificate as untrusted ,to solve this problem I have set the trust options of certificate as "Always trust". Setting the certificate to "Always trust" was the main cause of the crash. I was not able to install the application into device. Solved this by setting trust option to "System defaults" instead of "Always trust" .It worked for me.

Mosaic Grid gallery with dynamic sized images

I suggest Freewall. It is a cross-browser and responsive jQuery plugin to help you create many types of grid layouts: flexible layouts, images layouts, nested grid layouts, metro style layouts, pinterest like layouts ... with nice CSS3 animation effects and call back events. Freewall is all-in-one solution for creating dynamic grid layouts for desktop, mobile, and tablet.

Home page and document: also found here.

How to find good looking font color if background color is known?

Similar to @Aaron Digulla's suggestion except that I would suggest a graphics design tool, select the base color, in your case the background color, then adjust the Hue, Saturation and Value. Using this you can create color swatches very easily. Paint.Net is free and I use it all the time for this and also the pay-for-tools will also do this.

How to display UTF-8 characters in phpMyAdmin?

Its realy simple to add multilanguage in myphpadmin if you got garbdata showing in myphpadmin, just go to myphpadmin click your database go to operations tab in operation tab page see collation section set it to utf8_general_ci, after that all your garbdata will show correctly. a simple and easy trick

LD_LIBRARY_PATH vs LIBRARY_PATH

Since I link with gcc why ld is being called, as the error message suggests?

gcc calls ld internally when it is in linking mode.

Overriding a JavaScript function while referencing the original

You could do something like this:

var a = (function() {
    var original_a = a;

    if (condition) {
        return function() {
            new_code();
            original_a();
        }
    } else {
        return function() {
            original_a();
            other_new_code();
        }
    }
})();

Declaring original_a inside an anonymous function keeps it from cluttering the global namespace, but it's available in the inner functions.

Like Nerdmaster mentioned in the comments, be sure to include the () at the end. You want to call the outer function and store the result (one of the two inner functions) in a, not store the outer function itself in a.

How to install Android SDK on Ubuntu?

To install it on a Debian based system simply do

# Install latest JDK
sudo apt install default-jdk

# install unzip if not installed yet
sudo apt install unzip

# get latest sdk tools - link will change. go to https://developer.android.com/studio/#downloads to get the latest one
cd ~
wget https://dl.google.com/android/repository/sdk-tools-linux-4333796.zip

# unpack archive
unzip sdk-tools-linux-4333796.zip

rm sdk-tools-linux-4333796.zip

mkdir android-sdk
mv tools android-sdk/tools

Then add the Android SDK to your PATH, open ~/.bashrc in editor and add the following lines into the file

# Export the Android SDK path 
export ANDROID_HOME=$HOME/android-sdk
export PATH=$PATH:$ANDROID_HOME/tools/bin
export PATH=$PATH:$ANDROID_HOME/platform-tools

# Fixes sdkmanager error with java versions higher than java 8
export JAVA_OPTS='-XX:+IgnoreUnrecognizedVMOptions --add-modules java.se.ee'

Run

source ~/.bashrc

Show all available sdk packages

sdkmanager --list

Identify latest android platform (here it's 28) and run

sdkmanager "platform-tools" "platforms;android-28"

Now you have adb, fastboot and the latest sdk tools installed

How to check for null/empty/whitespace values with a single test?

While checking null or Empty value for a column, I noticed that there are some support concerns in various Databases.

Every Database doesn't support TRIM method.

Below is the matrix just to understand the supported methods by different databases.

The TRIM function in SQL is used to remove specified prefix or suffix from a string. The most common pattern being removed is white spaces. This function is called differently in different databases:

  • MySQL: TRIM(), RTRIM(), LTRIM()
  • Oracle: RTRIM(), LTRIM()
  • SQL Server: TRIM(), RTRIM(), LTRIM()

How to Check Empty/Null/Whitespace :-

Below are two different ways according to different Databases-

The syntax for these trim functions are:

  1. Use of Trim to check-

    SELECT FirstName FROM UserDetails WHERE TRIM(LastName) IS NULL

  2. Use of LTRIM & RTRIM to check-

    SELECT FirstName FROM UserDetails WHERE LTRIM(RTRIM(LastName)) IS NULL

Above both ways provide same result just use based on your DataBase support. It Just returns the FirstName from UserDetails table if it has an empty LastName

Hoping this will help others too :)

Kubernetes pod gets recreated when deleted

If you have a job that continues running, you need to search the job and delete it:

kubectl get job --all-namespaces | grep <name>

and

kubectl delete job <job-name>

Host 'xxx.xx.xxx.xxx' is not allowed to connect to this MySQL server

Just perform the following steps:

1a) Connect to mysql (via localhost)

mysql -uroot -p

1b) If the mysql server is running in Kubernetes (K8s) and being accessed via a NodePort

kubectl exec -it [pod-name] -- /bin/bash
mysql -uroot -p
  1. Create user

    CREATE USER 'user'@'%' IDENTIFIED BY 'password';

  2. Grant permissions

    GRANT ALL PRIVILEGES ON *.* TO 'user'@'%' WITH GRANT OPTION;

  3. Flush privileges

    FLUSH PRIVILEGES;

Error: vector does not name a type

Also you can add #include<vector> in the header. When two of the above solutions don't work.

Insert and set value with max()+1 problems

Correct, you can not modify and select from the same table in the same query. You would have to perform the above in two separate queries.

The best way is to use a transaction but if your not using innodb tables then next best is locking the tables and then performing your queries. So:

Lock tables customers write;

$max = SELECT MAX( customer_id ) FROM customers;

Grab the max id and then perform the insert

INSERT INTO customers( customer_id, firstname, surname )
VALUES ($max+1 , 'jim', 'sock')

unlock tables;

Check if Cell value exists in Column, and then get the value of the NEXT Cell

After t.thielemans' answer, I worked that just

=VLOOKUP(A1, B:C, 2, FALSE) 

works fine and does what I wanted, except that it returns #N/A for non-matches; so it is suitable for the case where it is known that the value definitely exists in the look-up column.

Edit (based on t.thielemans' comment):

To avoid #N/A for non-matches, do:

=IFERROR(VLOOKUP(A1, B:C, 2, FALSE), "No Match")

New og:image size for Facebook share?

UPDATE: The image size Must be larger than (600 x 315px)

The image size can be any size because Faceboook re-size the image width & height.

The default height is 208px & width is 398px for a post permalink:

www.facebook.com/{username}/posts/{post_id}

But for a timeline view:

www.facebook.com/{username}

width is 377px & height is 197px

I hope this will help you!

Enabling/installing GD extension? --without-gd

if you are on a Debian based server (such as Ubuntu) you can run the following command:

apt-get install php-gd

Then once it is complete run:

/etc/init.d/apache2 restart

This will restart your server and enable GD in PHP.

If you are on another type of system you will need to use something else (like yum install) or compile directly into PHP.

Best practice: PHP Magic Methods __set and __get

I am now returning to setters and getters but I am also putting the getters and setters in the magic methos __get and __set. This way I have a default behavior when I do this

$class->var;

This will just call the getter I have set in the __get. Normally I will just use the getter directly but there are still some instances where this is just simpler.

How to set margin of ImageView using code, not xml

If you want to change imageview margin but leave all other margins intact.

  1. Get MarginLayoutParameters of your image view in this case: myImageView

     MarginLayoutParams marginParams = (MarginLayoutParams) myImageView.getLayoutParams();
    
  2. Now just change the margin you want to change but leave the others as they are:

     marginParams.setMargins(marginParams.leftMargin, 
                             marginParams.topMargin, 
                             150, //notice only changing right margin
                             marginParams.bottomMargin); 
    

ORA-00060: deadlock detected while waiting for resource

I was testing a function that had multiple UPDATE statements within IF-ELSE blocks.

I was testing all possible paths, so I reset the tables to their previous values with 'manual' UPDATE statements each time before running the function again.

I noticed that the issue would happen just after those UPDATE statements;

I added a COMMIT; after the UPDATE statement I used to reset the tables and that solved the problem.

So, caution, the problem was not the function itself...

Get Client Machine Name in PHP

Not in PHP.
phpinfo(32) contains everything PHP able to know about particular client, and there is no [windows] computer name

Twitter Bootstrap and ASP.NET GridView

There are 2 steps to resolve this:

  1. Add UseAccessibleHeader="true" to Gridview tag:

    <asp:GridView ID="MyGridView" runat="server" UseAccessibleHeader="true">
    
  2. Add the following Code to the PreRender event:


Protected Sub MyGridView_PreRender(sender As Object, e As EventArgs) Handles MyGridView.PreRender
    Try
        MyGridView.HeaderRow.TableSection = TableRowSection.TableHeader
    Catch ex As Exception
    End Try
End Sub

Note setting Header Row in DataBound() works only when the object is databound, any other postback that doesn't databind the gridview will result in the gridview header row style reverting to a standard row again. PreRender works everytime, just make sure you have an error catch for when the gridview is empty.

No server in windows>preferences

Follow the below steps:

1.Goto Help -> Install new Software
2.Give address http://download.eclipse.org/releases/oxygen and name as your choice.
3.Search for Java EE and choose 1.Eclipse Java EE Developer Tools 
4.Search for JST and choose 2.JST Server Adapters 3.JST Server Adapters 
5.Click next and accept the license agreement.

Find the server option in the window-->preferences and add server as you need

How to vertically align into the center of the content of a div with defined width/height?

I would say to add a paragraph with a period in it and style it like so:

<p class="center">.</p>

<style>
.center {font-size: 0px; margin-bottom: anyPercentage%;}
</style>

You may need to toy around with the percentages to get it right

How to export query result to csv in Oracle SQL Developer?

FYI to anyone who runs into problems, there is a bug in CSV timestamp export that I just spent a few hours working around. Some fields I needed to export were of type timestamp. It appears the CSV export option even in the current version (3.0.04 as of this posting) fails to put the grouping symbols around timestamps. Very frustrating since spaces in the timestamps broke my import. The best workaround I found was to write my query with a TO_CHAR() on all my timestamps, which yields the correct output, albeit with a little more work. I hope this saves someone some time or gets Oracle on the ball with their next release.

How to darken a background using CSS?

Setting background-blend-mode to darken would be the most direct and shortest way to achieve the purpose however you must set a background-color first for the blend mode to work.
This is also the best way if you need to manipulate the values in javascript later on.

background: rgba(0, 0, 0, .65) url('http://fc02.deviantart.net/fs71/i/2011/274/6/f/ocean__sky__stars__and_you_by_muddymelly-d4bg1ub.png');
background-blend-mode: darken;

Can I use for background-blend

Finding partial text in range, return an index

You can use "wildcards" with MATCH so assuming "ASDFGHJK" in H1 as per Peter's reply you can use this regular formula

=INDEX(G:G,MATCH("*"&H1&"*",G:G,0)+3)

MATCH can only reference a single column or row so if you want to search 6 columns you either have to set up a formula with 6 MATCH functions or change to another approach - try this "array formula", assuming search data in A2:G100

=INDIRECT("R"&REPLACE(TEXT(MIN(IF(ISNUMBER(SEARCH(H1,A2:G100)),(ROW(A2:G100)+3)*1000+COLUMN(A2:G100))),"000000"),4,0,"C"),FALSE)

confirmed with Ctrl-Shift-Enter

How to get multiple selected values from select box in JSP?

Since I don't find a simple answer just adding more this will be JSP page. save this content to a jsp file once you run you can see the values of the selected displayed.

Update: save the file as test.jsp and run it on any web/app server

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
<%@ page import="java.lang.*" %>
<%@ page import="java.io.*" %>
<% String[] a = request.getParameterValues("multiple");
if(a!=null)
{
for(int i=0;i<a.length;i++){
//out.println(Integer.parseInt(a[i])); //If integer
out.println(a[i]);
}}
%>
<html>
<body>
<form action="test.jsp" method="get">
<select name="multiple" multiple="multiple"><option value="1">1</option><option value="2">2</option><option value="3">3</option></select>
<input type="submit">
</form>
</body>
</html>

Declare Variable for a Query String

DECLARE @theDate DATETIME
SET @theDate = '2010-01-01'

Then change your query to use this logic:

AND 
(
    tblWO.OrderDate > DATEADD(MILLISECOND, -1, @theDate) 
    AND tblWO.OrderDate < DATEADD(DAY, 1, @theDate)
)

load iframe in bootstrap modal

I came across this implementation in Codepen. I hope you find it helpful.

this.on('hidden.bs.modal', function(){
      $(this).find('iframe').html("").attr("src", "");
    });

Is there a 'box-shadow-color' property?

A quick and copy/paste you can use for Chrome and Firefox would be: (change the stuff after the # to change the color)

-moz-border-radius: 10px;
-webkit-border-radius: 10px;
-khtml-border-radius: 10px;
-border-radius: 10px;
-moz-box-shadow: 0 0 15px 5px #666;
-webkit-box-shadow: 0 0 15px 05px #666;

Matt Roberts' answer is correct for webkit browsers (safari, chrome, etc), but I thought someone out there might want a quick answer rather than be told to learn to program to make some shadows.

Create array of regex matches

In Java 9, you can now use Matcher#results() to get a Stream<MatchResult> which you can use to get a list/array of matches.

import java.util.regex.Pattern;
import java.util.regex.MatchResult;
String[] matches = Pattern.compile("your regex here")
                          .matcher("string to search from here")
                          .results()
                          .map(MatchResult::group)
                          .toArray(String[]::new);
                    // or .collect(Collectors.toList())

How to post SOAP Request from PHP

In my experience, it's not quite that simple. The built-in PHP SOAP client didn't work with the .NET-based SOAP server we had to use. It complained about an invalid schema definition. Even though .NET client worked with that server just fine. By the way, let me claim that SOAP interoperability is a myth.

The next step was NuSOAP. This worked for quite a while. By the way, for God's sake, don't forget to cache WSDL! But even with WSDL cached users complained the damn thing is slow.

Then, we decided to go bare HTTP, assembling the requests and reading the responses with SimpleXMLElemnt, like this:

$request_info = array();

$full_response = @http_post_data(
    'http://example.com/OTA_WS.asmx',
    $REQUEST_BODY,
    array(
        'headers' => array(
            'Content-Type' => 'text/xml; charset=UTF-8',
            'SOAPAction'   => 'HotelAvail',
        ),
        'timeout' => 60,

    ),
    $request_info
);

$response_xml = new SimpleXMLElement(strstr($full_response, '<?xml'));

foreach ($response_xml->xpath('//@HotelName') as $HotelName) {
    echo strval($HotelName) . "\n";
}

Note that in PHP 5.2 you'll need pecl_http, as far as (surprise-surpise!) there's no HTTP client built in.

Going to bare HTTP gained us over 30% in SOAP request times. And from then on we redirect all the performance complains to the server guys.

In the end, I'd recommend this latter approach, and not because of the performance. I think that, in general, in a dynamic language like PHP there's no benefit from all that WSDL/type-control. You don't need a fancy library to read and write XML, with all that stubs generation and dynamic proxies. Your language is already dynamic, and SimpleXMLElement works just fine, and is so easy to use. Also, you'll have less code, which is always good.

Differences between utf8 and latin1

UTF-8 is prepared for world domination, Latin1 isn't.

If you're trying to store non-Latin characters like Chinese, Japanese, Hebrew, Russian, etc using Latin1 encoding, then they will end up as mojibake. You may find the introductory text of this article useful (and even more if you know a bit Java).

Note that full 4-byte UTF-8 support was only introduced in MySQL 5.5. Before that version, it only goes up to 3 bytes per character, not 4 bytes per character. So, it supported only the BMP plane and not e.g. the Emoji plane. If you want full 4-byte UTF-8 support, upgrade MySQL to at least 5.5 or go for another RDBMS like PostgreSQL. In MySQL 5.5+ it's called utf8mb4.

Property 'catch' does not exist on type 'Observable<any>'

Warning: This solution is deprecated since Angular 5.5, please refer to Trent's answer below

=====================

Yes, you need to import the operator:

import 'rxjs/add/operator/catch';

Or import Observable this way:

import {Observable} from 'rxjs/Rx';

But in this case, you import all operators.

See this question for more details:

Padding characters in printf

Bash + seq to allow parameter expansion

Similar to @Dennis Williamson answer, but if seq is available, the length of the pad string need not be hardcoded. The following code allows for passing a variable to the script as a positional parameter:

COLUMNS="${COLUMNS:=80}"
padlength="${1:-$COLUMNS}"
pad=$(printf '\x2D%.0s' $(seq "$padlength") )

string2='bbbbbbb'
for string1 in a aa aaaa aaaaaaaa
do
     printf '%s' "$string1"
     printf '%*.*s' 0 $(("$padlength" - "${#string1}" - "${#string2}" )) "$pad"
     printf '%s\n' "$string2"
     string2=${string2:1}
done

The ASCII code "2D" is used instead of the character "-" to avoid the shell interpreting it as a command flag. Another option is "3D" to use "=".

In absence of any padlength passed as an argument, the code above defaults to the 80 character standard terminal width.

To take advantage of the the bash shell variable COLUMNS (i.e., the width of the current terminal), the environment variable would need to be available to the script. One way is to source all the environment variables by executing the script preceded by . ("dot" command), like this:

. /path/to/script

or (better) explicitly pass the COLUMNS variable when executing, like this:

/path/to/script $COLUMNS

How do I change the color of radio buttons?

I builded another fork of @klewis' code sample to demonstrate some playing with pure css and gradients by using :before/:after pseudo elements and a hidden radio input button.

enter image description here

HTML:

sample radio buttons:
<div style="background:lightgrey;">
    <span class="radio-item">
        <input type="radio" id="ritema" name="ritem" class="true" value="ropt1" checked="checked">
        <label for="ritema">True</label>
    </span>

    <span class="radio-item">
        <input type="radio" id="ritemb" name="ritem" class="false" value="ropt2">
        <label for="ritemb">False</label>
    </span>
</div>

:

CSS:

.radio-item input[type='radio'] {
    visibility: hidden;
    width: 20px;
    height: 20px;
    margin: 0 5px 0 5px;
    padding: 0;
}
    .radio-item input[type=radio]:before {
        position: relative;
        margin: 4px -25px -4px 0;
        display: inline-block;
        visibility: visible;
        width: 20px;
        height: 20px;
        border-radius: 10px;
        border: 2px inset rgba(150,150,150,0.75);
        background: radial-gradient(ellipse at top left, rgb(255,255,255) 0%, rgb(250,250,250) 5%, rgb(230,230,230) 95%, rgb(225,225,225) 100%);
        content: "";
    }
        .radio-item input[type=radio]:checked:after {
            position: relative;
            top: 0;
            left: 9px;
            display: inline-block;
            visibility: visible;
            border-radius: 6px;
            width: 12px;
            height: 12px;
            background: radial-gradient(ellipse at top left, rgb(245,255,200) 0%, rgb(225,250,100) 5%, rgb(75,175,0) 95%, rgb(25,100,0) 100%);
            content: "";
        }
            .radio-item input[type=radio].true:checked:after {
                background: radial-gradient(ellipse at top left, rgb(245,255,200) 0%, rgb(225,250,100) 5%, rgb(75,175,0) 95%, rgb(25,100,0) 100%);
            }
            .radio-item input[type=radio].false:checked:after {
                background: radial-gradient(ellipse at top left, rgb(255,225,200) 0%, rgb(250,200,150) 5%, rgb(200,25,0) 95%, rgb(100,25,0) 100%);
            }
.radio-item label {
    display: inline-block;
    height: 25px;
    line-height: 25px;
    margin: 0;
    padding: 0;
}

preview: https://www.codeply.com/p/y47T4ylfib

The listener supports no services

for listener support no services you can use the following command to set local_listener paramter in your spfile use your listener port and server ip address

alter system set local_listener='(DESCRIPTION=(ADDRESS=(PROTOCOL=tcp)(HOST=192.168.1.101)(PORT=1520)))' sid='testdb' scope=spfile;

Difference between IsNullOrEmpty and IsNullOrWhiteSpace in C#

Short answer:

In common use, space " ", Tab "\t" and newline "\n" are the difference:

string.IsNullOrWhiteSpace("\t"); //true
string.IsNullOrEmpty("\t"); //false

string.IsNullOrWhiteSpace(" "); //true
string.IsNullOrEmpty(" "); //false

string.IsNullOrWhiteSpace("\n"); //true
string.IsNullOrEmpty("\n"); //false

https://dotnetfiddle.net/4hkpKM

also see this answer about: whitespace characters


Long answer:

There are also a few other white space characters, you probably never used before

https://docs.microsoft.com/en-us/dotnet/api/system.char.iswhitespace

Oracle 11g Express Edition for Windows 64bit?

This is a very useful question. It has 5 different helpful answers that say quite different but complementary things (surprising, eh?). This answer combines those answers into a more useful form as well as adding two more solutions.

There is no Oracle Express Edition for 64 bit Windows. See this official [but unanswered] forum thread. Therefore, these are the classes of solutions:

  • Pay. The paid versions of Oracle (Standard/Enterprise) support 64-bit Windows.
  • Hack. Many people have successfully installed the 32 bit Oracle XE software on 64 bit Windows. This blog post seems to be the one most often cited as helpful. This is unsupported, of course, and session trace is known to fail. But for many folks this is a good solution.
  • VM. If your goal is simply to run Oracle on a 64 bit Windows machine, then running Oracle in a Virtual Machine may be a good solution. VirtualBox is a natural choice because it's free and Oracle provides pre-configured VMs with Oracle DB installed. VMWare or other virtualization systems work equally well.
  • Develop only. Many users want Oracle XE just to learn Oracle or to test an application with Oracle. If that's your requirement, then Oracle Enterprise Edition (including support for 64-bit Windows) is free "only for the purpose of developing, testing, prototyping and demonstrating your application".

Difference between map, applymap and apply methods in Pandas

Just for additional context and intuition, here's an explicit and concrete example of the differences.

Assume you have the following function seen below. ( This label function, will arbitrarily split the values into 'High' and 'Low', based upon the threshold you provide as the parameter (x). )

def label(element, x):
    if element > x:
        return 'High'
    else:
        return 'Low'

In this example, lets assume our dataframe has one column with random numbers.

Df with one column that has random numbers

If you tried mapping the label function with map:

df['ColumnName'].map(label, x = 0.8)

You will result with the following error:

TypeError: map() got an unexpected keyword argument 'x'

Now take the same function and use apply, and you'll see that it works:

df['ColumnName'].apply(label, x=0.8)

Series.apply() can take additional arguments element-wise, while the Series.map() method will return an error.

Now, if you're trying to apply the same function to several columns in your dataframe simultaneously, DataFrame.applymap() is used.

df[['ColumnName','ColumnName2','ColumnName3','ColumnName4']].applymap(label)

Lastly, you can also use the apply() method on a dataframe, but the DataFrame.apply() method has different capabilities. Instead of applying functions element-wise, the df.apply() method applies functions along an axis, either column-wise or row-wise. When we create a function to use with df.apply(), we set it up to accept a series, most commonly a column.

Here is an example:

df.apply(pd.value_counts)

When we applied the pd.value_counts function to the dataframe, it calculated the value counts for all the columns.

Notice, and this is very important, when we used the df.apply() method to transform multiple columns. This is only possible because the pd.value_counts function operates on a series. If we tried to use the df.apply() method to apply a function that works element-wise to multiple columns, we'd get an error:

For example:

def label(element):
    if element > 1:
        return 'High'
    else:
        return 'Low'

df[['ColumnName','ColumnName2','ColumnName3','ColumnName4']].apply(label)

This will result with the following error:

ValueError: ('The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().', u'occurred at index Economy')

In general, we should only use the apply() method when a vectorized function does not exist. Recall that pandas uses vectorization, the process of applying operations to whole series at once, to optimize performance. When we use the apply() method, we're actually looping through rows, so a vectorized method can perform an equivalent task faster than the apply() method.

apply, applymap, map summarization

Here are some examples of vectorized functions that already exist that you do NOT want to recreate using any type of apply/map methods:

  1. Series.str.split() Splits each element in the Series
  2. Series.str.strip() Strips whitespace from each string in the Series.
  3. Series.str.lower() Converts strings in the Series to lowercase.
  4. Series.str.upper() Converts strings in the Series to uppercase.
  5. Series.str.get() Retrieves the ith element of each element in the Series.
  6. Series.str.replace() Replaces a regex or string in the Series with another string
  7. Series.str.cat() Concatenates strings in a Series.
  8. Series.str.extract() Extracts substrings from the Series matching a regex pattern.

Resize iframe height according to content height in it

I just spent the better part of 3 days wrestling with this. I'm working on an application that loads other applications into itself while maintaining a fixed header and a fixed footer. Here's what I've come up with. (I also used EasyXDM, with success, but pulled it out later to use this solution.)

Make sure to run this code AFTER the <iframe> exists in the DOM. Put it into the page that pulls in the iframe (the parent).

// get the iframe
var theFrame = $("#myIframe");
// set its height to the height of the window minus the combined height of fixed header and footer
theFrame.height(Number($(window).height()) - 80);

function resizeIframe() {
    theFrame.height(Number($(window).height()) - 80);
}

// setup a resize method to fire off resizeIframe.
// use timeout to filter out unnecessary firing.
var TO = false;
$(window).resize(function() {
    if (TO !== false) clearTimeout(TO);
    TO = setTimeout(resizeIframe, 500); //500 is time in miliseconds
});

CKEditor instance already exists

This is the fully working code for jquery .load() api and ckeditor, in my case I am loading a page with ckeditor into div with some jquery effects. I hope it will help you.

 $(function() {
            runEffect = function(fileload,lessonid,act) {
            var selectedEffect = 'drop';
            var options = {};
            $( "#effect" ).effect( selectedEffect, options, 200, callback(fileload,lessonid,act) );
        };
        function callback(fileload,lessonid,act) {
            setTimeout(function() {//load the page in effect div
                $( "#effect" ).load(fileload,{lessonid:lessonid,act:act});
                 $("#effect").show( "drop", 
                          {direction: "right"}, 200 );
                $("#effect").ajaxComplete(function(event, XMLHttpRequest, ajaxOptions) {
                    loadCKeditor(); //call the function after loading page
                });
            }, 100 );   
        };

        function loadCKeditor()
        {//you need to destroy  the instance if already exist
            if (CKEDITOR.instances['introduction']) 
            {
                CKEDITOR.instances['introduction'].destroy();
            }
            CKEDITOR.replace('introduction').getSelection().getSelectedText();
        }
    });

===================== button for call the function ================================

<input type="button" name="button" id="button" onclick="runEffect('lesson.php','','add')" >

How to set Sqlite3 to be case insensitive when string comparing?

SELECT * FROM ... WHERE name = 'someone' COLLATE NOCASE

How to thoroughly purge and reinstall postgresql on ubuntu?

I was facing same problem in my ubuntu 16.04

but i fixed that problem and it's very simple just follow these step and you will be able to install postgresql 10 in your system :

Add this to your sources.list:

sudo vim /etc/apt/sources.list

deb http://ftp.de.debian.org/debian/ wheezy main non-free contrib

deb-src http://ftp.de.debian.org/debian/ wheezy main non-free contrib

after that add these link to your pgdg.list file if it's not there you have to create && add link && save it.

sudo vim /etc/apt/sources.list.d/pgdg.list

deb http://apt.postgresql.org/pub/repos/apt/ xenial-pgdg main

deb http://apt.postgresql.org/pub/repos/apt/ precise-pgdg main

then update your system

sudo apt-get update

sudo apt-get upgrade

and install that unmet dependencies :

apt-get install ssl-cert

that's it. now Install postgresql using these command

sudo apt-get install postgresql-10

Parser Error Message: Could not load type 'TestMvcApplication.MvcApplication'

After spend almost 2 hour I resolve this Issue by just delete a line from .csproj file.

   <PlatformTarget>AnyCPU</PlatformTarget>

Namenode not getting started

Instead of formatting namenode, may be you can use the below command to restart the namenode. It worked for me:

sudo service hadoop-master restart

  1. hadoop dfsadmin -safemode leave

Deleting records before a certain date

This helped me delete data based on different attributes. This is dangerous so make sure you back up database or the table before doing it:

mysqldump -h hotsname -u username -p password database_name > backup_folder/backup_filename.txt

Now you can perform the delete operation:

delete from table_name where column_name < DATE_SUB(NOW() , INTERVAL 1 DAY)

This will remove all the data from before one day. For deleting data from before 6 months:

delete from table_name where column_name < DATE_SUB(NOW() , INTERVAL 6 MONTH)

What is jQuery Unobtrusive Validation?

With the unobtrusive way:

  • You don't have to call the validate() method.
  • You specify requirements using data attributes (data-val, data-val-required, etc.)

Jquery Validate Example:

<input type="text" name="email" class="required">
<script>
        $(function () {
            $("form").validate();
        });
</script>

Jquery Validate Unobtrusive Example:

<input type="text" name="email" data-val="true" 
data-val-required="This field is required.">  

<div class="validation-summary-valid" data-valmsg-summary="true">
    <ul><li style="display:none"></li></ul>
</div>

Java int to String - Integer.toString(i) vs new Integer(i).toString()

  1. new Integer(i).toString();

    This statement creates the object of the Integer and then call its methods toString(i) to return the String representation of Integer's value.

  2. Integer.toString(i);

    It returns the String object representing the specific int (integer), but here toString(int) is a static method.

Summary is in first case it returns the objects string representation, where as in second case it returns the string representation of integer.

Converting a character code to char (VB.NET)

The Chr function in VB.NET converts the integer back to the character:

Dim i As Integer = Asc("x") ' Convert to ASCII integer.
Dim x As Char = Chr(i)      ' Convert ASCII integer to char.

Printing the last column of a line in a file

Not the actual issue here, but might help some one: I was doing awk "{print $NF}", note the wrong quotes. Should be awk '{print $NF}', so that the shell doesn't expand $NF.

How do I remove the blue styling of telephone numbers on iPhone/iOS?

<meta name="format-detection" content="telephone=no">. This metatag works in the default Safari browser on iOS devices and will only work for telephone numbers that are not wrapped in a telephone link so

1-800-123-4567
<a href="tel:18001234567">1-800-123-4567</a>

the first line will not be formatted as a link if you specify the metatag but the second line will because it's wrapped in a telephone anchor.


You can forego the metatag all-together and use a mixin such as

a[href^=tel]{
    color:inherit;
    text-decoration:inherit;
    font-size:inherit;
    font-style:inherit;
    font-weight:inherit;
}

to maintain intended styling of your telephone numbers, but you must make sure you wrap them in a telephone anchor.

If you want to be extra cautious and protect against the event of a telephone number which is not properly formatted with a wrapping anchor tag you can drill through the DOM and adjust with this script. Adjust the replacement pattern as desired.

$('body').html($('body').html().replace(/^\D?(\d{3})\D?\D?(\d{3})\D?(\d{4})/g, '<a href="tel:+1$1$2$3">($1) $2-$3</a>'));

or even better without jQuery

document.body.innerHTML = document.body.innerHTML.replace(/^\D?(\d{3})\D?\D?(\d{3})\D?(\d{4})/g,'<a href="tel:+1$1$2$3">($1) $2-$3</a>');

How to copy std::string into std::vector<char>?

std::vector has a constructor that takes two iterators. You can use that:

std::string str = "hello";
std::vector<char> data(str.begin(), str.end());

If you already have a vector and want to add the characters at the end, you need a back inserter:

std::string str = "hello";
std::vector<char> data = /* ... */;
std::copy(str.begin(), str.end(), std::back_inserter(data));

Android Recyclerview vs ListView with Viewholder

I used a ListView with Glide image loader, having memory growth. Then I replaced the ListView with a RecyclerView. It is not only more difficult in coding, but also leads to a more memory usage than a ListView. At least, in my project.

In another activity I used a complex list with EditText's. In some of them an input method may vary, also a TextWatcher can be applied. If I used a ViewHolder, how could I replace a TextWatcher during scrolling? So, I used a ListView without a ViewHolder, and it works.

Normalizing images in OpenCV

When you normalize a matrix using NORM_L1, you are dividing every pixel value by the sum of absolute values of all the pixels in the image. As a result, all pixel values become much less than 1 and you get a black image. Try NORM_MINMAX instead of NORM_L1.

UIAlertView first deprecated IOS 9

-(void)showAlert{

    UIAlertController* alert = [UIAlertController alertControllerWithTitle:@"Title"
                                                                   message:"Message"
                                                            preferredStyle:UIAlertControllerStyleAlert];

    UIAlertAction* defaultAction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault
                                                          handler:^(UIAlertAction * action) {}];

    [alert addAction:defaultAction];
    [self presentViewController:alert animated:YES completion:nil];
}

[self showAlert]; // calling Method

Linux bash script to extract IP address

In my opinion the simplest and most elegant way to achieve what you need is this:

ip route get 8.8.8.8 | tr -s ' ' | cut -d' ' -f7

ip route get [host] - gives you the gateway used to reach a remote host e.g.:

8.8.8.8 via 192.168.0.1 dev enp0s3  src 192.168.0.109

tr -s ' ' - removes any extra spaces, now you have uniformity e.g.:

8.8.8.8 via 192.168.0.1 dev enp0s3 src 192.168.0.109

cut -d' ' -f7 - truncates the string into ' 'space separated fields, then selects the field #7 from it e.g.:

192.168.0.109

How do I erase an element from std::vector<> by index?

the fastest way (for programming contests by time complexity() = constant)

can erase 100M item in 1 second;

    vector<int> it = (vector<int>::iterator) &vec[pos];
    vec.erase(it);

and most readable way : vec.erase(vec.begin() + pos);

How can query string parameters be forwarded through a proxy_pass with nginx?

I use a slightly modified version of kolbyjack's second approach with ~ instead of ~*.

location ~ ^/service/ {
  proxy_pass http://apache/$uri$is_args$args;
}

Ansible: How to delete files and folders inside a directory?

Using shell module (idempotent too):

- shell: /bin/rm -rf /home/mydata/web/*

If there are dot/hidden files:

- shell: /bin/rm -rf /home/mydata/web/* /home/mydata/web/.*

Cleanest solution if you don't care about creation date and owner/permissions:

- file: path=/home/mydata/web state=absent
- file: path=/home/mydata/web state=directory

Volatile vs Static in Java

Declaring a static variable in Java, means that there will be only one copy, no matter how many objects of the class are created. The variable will be accessible even with no Objects created at all. However, threads may have locally cached values of it.

When a variable is volatile and not static, there will be one variable for each Object. So, on the surface it seems there is no difference from a normal variable but totally different from static. However, even with Object fields, a thread may cache a variable value locally.

This means that if two threads update a variable of the same Object concurrently, and the variable is not declared volatile, there could be a case in which one of the thread has in cache an old value.

Even if you access a static value through multiple threads, each thread can have its local cached copy! To avoid this you can declare the variable as static volatile and this will force the thread to read each time the global value.

However, volatile is not a substitute for proper synchronisation!
For instance:

private static volatile int counter = 0;

private void concurrentMethodWrong() {
  counter = counter + 5;
  //do something
  counter = counter - 5;
}

Executing concurrentMethodWrong concurrently many times may lead to a final value of counter different from zero!
To solve the problem, you have to implement a lock:

private static final Object counterLock = new Object();

private static volatile int counter = 0;

private void concurrentMethodRight() {
  synchronized (counterLock) {
    counter = counter + 5;
  }
  //do something
  synchronized (counterLock) {
    counter = counter - 5;
  }
}

Or use the AtomicInteger class.

How to install python-dateutil on Windows?

If dateutil is missing install it via:

pip install python-dateutil

Or on Ubuntu:

sudo apt-get install python-dateutil

How to increase the distance between table columns in HTML?

A better solution than selected answer would be to use border-size rather than border-spacing. The main problem with using border-spacing is that even the first column would have a spacing in the front.

For example,

_x000D_
_x000D_
table {_x000D_
  border-collapse: separate;_x000D_
  border-spacing: 80px 0;_x000D_
}_x000D_
_x000D_
td {_x000D_
  padding: 10px 0;_x000D_
}
_x000D_
<table>_x000D_
  <tr>_x000D_
    <td>First Column</td>_x000D_
    <td>Second Column</td>_x000D_
    <td>Third Column</td>_x000D_
  </tr>_x000D_
  <tr>_x000D_
    <td>1</td>_x000D_
    <td>2</td>_x000D_
    <td>3</td>_x000D_
  </tr>_x000D_
</table>
_x000D_
_x000D_
_x000D_

To avoid this use: border-left: 100px solid #FFF; and set border:0px for the first column.

For example,

_x000D_
_x000D_
td,th{_x000D_
  border-left: 100px solid #FFF;_x000D_
}_x000D_
_x000D_
 tr>td:first-child {_x000D_
   border:0px;_x000D_
 }
_x000D_
<table id="t">_x000D_
  <tr>_x000D_
    <td>Column1</td>_x000D_
    <td>Column2</td>_x000D_
    <td>Column3</td>_x000D_
  </tr>_x000D_
  <tr>_x000D_
    <td>1000</td>_x000D_
    <td>2000</td>_x000D_
    <td>3000</td>_x000D_
  </tr>_x000D_
</table>
_x000D_
_x000D_
_x000D_

Maven won't run my Project : Failed to execute goal org.codehaus.mojo:exec-maven-plugin:1.2.1:exec

Had the same problem, I worked around it by changing ${java.home}/../bin/javafxpackager to ${java.home}/bin/javafxpackager

Android runOnUiThread explanation

If you already have the data "for (Parcelable currentHeadline : allHeadlines)," then why are you doing that in a separate thread?

You should poll the data in a separate thread, and when it's finished gathering it, then call your populateTables method on the UI thread:

private void populateTable() {
    runOnUiThread(new Runnable(){
        public void run() {
            //If there are stories, add them to the table
            for (Parcelable currentHeadline : allHeadlines) {
                addHeadlineToTable(currentHeadline);
            }
            try {
                dialog.dismiss();
            } catch (final Exception ex) {
                Log.i("---","Exception in thread");
            }
        }
    });
}

java : non-static variable cannot be referenced from a static context Error

You probably want to add "static" to the declaration of con2.

In Java, things (both variables and methods) can be properties of the class (which means they're shared by all objects of that type), or they can be properties of the object (a different one in each object of the same class). The keyword "static" is used to indicate that something is a property of the class.

"Static" stuff exists all the time. The other stuff only exists after you've created an object, and even then each individual object has its own copy of the thing. And the flip side of this is key in this case: static stuff can't access non-static stuff, because it doesn't know which object to look in. If you pass it an object reference, it can do stuff like "thingie.con2", but simply saying "con2" is not allowed, because you haven't said which object's con2 is meant.

super() raises "TypeError: must be type, not classobj" for new-style class

super() can be used only in the new-style classes, which means the root class needs to inherit from the 'object' class.

For example, the top class need to be like this:

class SomeClass(object):
    def __init__(self):
        ....

not

class SomeClass():
    def __init__(self):
        ....

So, the solution is that call the parent's init method directly, like this way:

class TextParser(HTMLParser):
    def __init__(self):
        HTMLParser.__init__(self)
        self.all_data = []

Interview question: Check if one string is a rotation of other string

Join string1 with string2 and use KMP algorithm to check whether string2 is present in newly formed string. Because time complexity of KMP is lesser than substr.

How to refresh datagrid in WPF

How about

mydatagrid.UpdateLayout();

Missing artifact com.oracle:ojdbc6:jar:11.2.0 in pom.xml

oracle driver. `

<dependency>
    <groupId>com.hynnet</groupId>
    <artifactId>jdbc-fo</artifactId>
    <version>12.1.0.2</version>
</dependency>

`

MySQL SELECT last few days?

WHERE t.date >= DATE_ADD(CURDATE(), INTERVAL '-3' DAY);

use quotes on the -3 value

Laravel 5.4 redirection to custom url after login

you can add method in LoginController add line use App\User; on Top, after this add method, it is work for me wkwkwkwkw , but you must add {{ csrf_field() }} on view admin and user

protected function authenticated(Request $request, $user){

$user=User::where('email',$request->input('email'))->pluck('jabatan');
$c=" ".$user." ";
$a=strcmp($c,' ["admin"] ');

if ($a==0) {
    return redirect('admin');

}else{
    return redirect('user');

}}

Get index of selected option with jQuery

You can use the .prop(propertyName) function to get a property from the first element in the jQuery object.

var savedIndex = $(selectElement).prop('selectedIndex');

This keeps your code within the jQuery realm and also avoids the other option of using a selector to find the selected option. You can then restore it using the overload:

$(selectElement).prop('selectedIndex', savedIndex);

How to run Selenium WebDriver test cases in Chrome

You need to install the Chrome driver. You can install this package using NuGet as shown below:

Case-insensitive search in Rails model

Several comments refer to Arel, without providing an example.

Here is an Arel example of a case-insensitive search:

Product.where(Product.arel_table[:name].matches('Blue Jeans'))

The advantage of this type of solution is that it is database-agnostic - it will use the correct SQL commands for your current adapter (matches will use ILIKE for Postgres, and LIKE for everything else).

How to solve 'Redirect has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header'?

You can solve this temporarily by using the Firefox add-on, CORS Everywhere. Just open Firefox, press Ctrl+Shift+A , search the add-on and add it!

How do I change the font size of a UILabel in Swift?

You can use an extension.

import UIKit

extension UILabel {

    func sizeFont(_ size: CGFloat) {
        self.font = self.font.withSize(size)
    }
}

To use it:

self.myLabel.fontSize(100)

Adding click event listener to elements with the same class

The problem with using querySelectorAll and a for loop is that it creates a whole new event handler for each element in the array.

Sometimes that is exactly what you want. But if you have many elements, it may be more efficient to create a single event handler and attach it to a container element. You can then use event.target to refer to the specific element which triggered the event:

document.body.addEventListener("click", function (event) {
  if (event.target.classList.contains("delete")) {
    var title = event.target.getAttribute("title");

    if (!confirm("sure u want to delete " + title)) {
      event.preventDefault();
    }
  }
});

In this example we only create one event handler which is attached to the body element. Whenever an element inside the body is clicked, the click event bubbles up to our event handler.

How to get the background color code of an element in hex?

There's a bit of a hack for this, since the HTML5 canvas is required to parse color values when certain properties like strokeStyle and fillStyle are set:

var ctx = document.createElement('canvas').getContext('2d');
ctx.strokeStyle = 'rgb(64, 128, 192)';
var hexColor = ctx.strokeStyle;

Count a list of cells with the same background color

I just created this and it looks easier. You get these 2 functions:

=GetColorIndex(E5)  <- returns color number for the cell

from (cell)

=CountColorIndexInRange(C7:C24,14) <- returns count of cells C7:C24 with color 14

from (range of cells, color number you want to count)

example shows percent of cells with color 14

=ROUND(CountColorIndexInRange(C7:C24,14)/18, 4 )

Create these 2 VBA functions in a Module (hit Alt-F11)

open + folders. double-click on Module1

Just paste this text below in, then close the module window (it must save it then):

Function GetColorIndex(Cell As Range)
  GetColorIndex = Cell.Interior.ColorIndex
End Function

Function CountColorIndexInRange(Rng As Range, TestColor As Long)
  Dim cnt
  Dim cl As Range
  cnt = 0

  For Each cl In Rng
    If GetColorIndex(cl) = TestColor Then
      Rem Debug.Print ">" & TestColor & "<"
      cnt = cnt + 1
    End If
  Next

  CountColorIndexInRange = cnt

End Function

How to terminate process from Python using pid?

Using the awesome psutil library it's pretty simple:

p = psutil.Process(pid)
p.terminate()  #or p.kill()

If you don't want to install a new library, you can use the os module:

import os
import signal

os.kill(pid, signal.SIGTERM) #or signal.SIGKILL 

See also the os.kill documentation.


If you are interested in starting the command python StripCore.py if it is not running, and killing it otherwise, you can use psutil to do this reliably.

Something like:

import psutil
from subprocess import Popen

for process in psutil.process_iter():
    if process.cmdline() == ['python', 'StripCore.py']:
        print('Process found. Terminating it.')
        process.terminate()
        break
else:
    print('Process not found: starting it.')
    Popen(['python', 'StripCore.py'])

Sample run:

$python test_strip.py   #test_strip.py contains the code above
Process not found: starting it.
$python test_strip.py 
Process found. Terminating it.
$python test_strip.py 
Process not found: starting it.
$killall python
$python test_strip.py 
Process not found: starting it.
$python test_strip.py 
Process found. Terminating it.
$python test_strip.py 
Process not found: starting it.

Note: In previous psutil versions cmdline was an attribute instead of a method.

Difference between fprintf, printf and sprintf?

printf(...) is equivalent to fprintf(stdout,...).

fprintf is used to output to stream.

sprintf(buffer,...) is used to format a string to a buffer.

Note there is also vsprintf, vfprintf and vprintf

Git Pull is Not Possible, Unmerged Files

Say the remote is origin and the branch is master, and say you already have master checked out, might try the following:

git fetch origin
git reset --hard origin/master

This basically just takes the current branch and points it to the HEAD of the remote branch.

WARNING: As stated in the comments, this will throw away your local changes and overwrite with whatever is on the origin.

Or you can use the plumbing commands to do essentially the same:

git fetch <remote>
git update-ref refs/heads/<branch> $(git rev-parse <remote>/<branch>)
git reset --hard

EDIT: I'd like to briefly explain why this works.

The .git folder can hold the commits for any number of repositories. Since the commit hash is actually a verification method for the contents of the commit, and not just a randomly generated value, it is used to match commit sets between repositories.

A branch is just a named pointer to a given hash. Here's an example set:

$ find .git/refs -type f
.git/refs/tags/v3.8
.git/refs/heads/master
.git/refs/remotes/origin/HEAD
.git/refs/remotes/origin/master

Each of these files contains a hash pointing to a commit:

$ cat .git/refs/remotes/origin/master
d895cb1af15c04c522a25c79cc429076987c089b

These are all for the internal git storage mechanism, and work independently of the working directory. By doing the following:

git reset --hard origin/master

git will point the current branch at the same hash value that origin/master points to. Then it forcefully changes the working directory to match the file structure/contents at that hash.

To see this at work go ahead and try out the following:

git checkout -b test-branch
# see current commit and diff by the following
git show HEAD
# now point to another location
git reset --hard <remote>/<branch>
# see the changes again
git show HEAD

How can I check file size in Python?

#Get file size , print it , process it...
#Os.stat will provide the file size in (.st_size) property. 
#The file size will be shown in bytes.

import os

fsize=os.stat('filepath')
print('size:' + fsize.st_size.__str__())

#check if the file size is less than 10 MB

if fsize.st_size < 10000000:
    process it ....

JFrame Exit on close Java

You need the line

frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);

Because the default behaviour for the JFrame when you press the X button is the equivalent to

frame.setDefaultCloseOperation(WindowConstants.HIDE_ON_CLOSE);

So almost all the times you'll need to add that line manually when creating your JFrame

I am currently referring to constants in WindowConstants like WindowConstants.EXIT_ON_CLOSE instead of the same constants declared directly in JFrame as the prior reflect better the intent.

Passing command line arguments in Visual Studio 2010?

  • Right click your project in Solution Explorer and select Properties from the menu
  • Go to Configuration Properties -> Debugging
  • Set the Command Arguments in the property list.

Adding Command Line Arguments

What does 'git remote add upstream' help achieve?

The wiki is talking from a forked repo point of view. You have access to pull and push from origin, which will be your fork of the main diaspora repo. To pull in changes from this main repo, you add a remote, "upstream" in your local repo, pointing to this original and pull from it.

So "origin" is a clone of your fork repo, from which you push and pull. "Upstream" is a name for the main repo, from where you pull and keep a clone of your fork updated, but you don't have push access to it.

How can I edit a .jar file?

A jar file is a zip archive. You can extract it using 7zip (a great simple tool to open archives). You can also change its extension to zip and use whatever to unzip the file.

Now you have your class file. There is no easy way to edit class file, because class files are binaries (you won't find source code in there. maybe some strings, but not java code). To edit your class file you can use a tool like classeditor.

You have all the strings your class is using hard-coded in the class file. So if the only thing you would like to change is some strings you can do it without using classeditor.

How can I schedule a daily backup with SQL Server Express?

Just use this script to dynamically backup all databases on the server. Then create batch file according to the article. It is usefull to create two batch files, one for full backup a and one for diff backup. Then Create two tasks in Task Scheduler, one for full and one for diff.

-- // Copyright © Microsoft Corporation.  All Rights Reserved.
-- // This code released under the terms of the
-- // Microsoft Public License (MS-PL, http://opensource.org/licenses/ms-pl.html.)
USE [master] 
GO 
/****** Object:  StoredProcedure [dbo].[sp_BackupDatabases] ******/ 
SET ANSI_NULLS ON 
GO 
SET QUOTED_IDENTIFIER ON 
GO 

-- ============================================= 
-- Author: Microsoft 
-- Create date: 2010-02-06
-- Description: Backup Databases for SQLExpress
-- Parameter1: databaseName 
-- Parameter2: backupType F=full, D=differential, L=log
-- Parameter3: backup file location
-- =============================================

CREATE PROCEDURE [dbo].[sp_BackupDatabases]  
            @databaseName sysname = null,
            @backupType CHAR(1),
            @backupLocation nvarchar(200) 
AS 

       SET NOCOUNT ON; 

            DECLARE @DBs TABLE
            (
                  ID int IDENTITY PRIMARY KEY,
                  DBNAME nvarchar(500)
            )

             -- Pick out only databases which are online in case ALL databases are chosen to be backed up
             -- If specific database is chosen to be backed up only pick that out from @DBs
            INSERT INTO @DBs (DBNAME)
            SELECT Name FROM master.sys.databases
            where state=0
            AND name=@DatabaseName
            OR @DatabaseName IS NULL
            ORDER BY Name

            -- Filter out databases which do not need to backed up
            IF @backupType='F'
                  BEGIN
                  DELETE @DBs where DBNAME IN ('tempdb','Northwind','pubs','AdventureWorks')
                  END
            ELSE IF @backupType='D'
                  BEGIN
                  DELETE @DBs where DBNAME IN ('tempdb','Northwind','pubs','master','AdventureWorks')
                  END
            ELSE IF @backupType='L'
                  BEGIN
                  DELETE @DBs where DBNAME IN ('tempdb','Northwind','pubs','master','AdventureWorks')
                  END
            ELSE
                  BEGIN
                  RETURN
                  END

            -- Declare variables
            DECLARE @BackupName varchar(100)
            DECLARE @BackupFile varchar(100)
            DECLARE @DBNAME varchar(300)
            DECLARE @sqlCommand NVARCHAR(1000) 
        DECLARE @dateTime NVARCHAR(20)
            DECLARE @Loop int                  

            -- Loop through the databases one by one
            SELECT @Loop = min(ID) FROM @DBs

      WHILE @Loop IS NOT NULL
      BEGIN

-- Database Names have to be in [dbname] format since some have - or _ in their name
      SET @DBNAME = '['+(SELECT DBNAME FROM @DBs WHERE ID = @Loop)+']'

-- Set the current date and time n yyyyhhmmss format
      SET @dateTime = REPLACE(CONVERT(VARCHAR, GETDATE(),101),'/','') + '_' +  REPLACE(CONVERT(VARCHAR, GETDATE(),108),':','')  

-- Create backup filename in path\filename.extension format for full,diff and log backups
      IF @backupType = 'F'
            SET @BackupFile = @backupLocation+REPLACE(REPLACE(@DBNAME, '[',''),']','')+ '_FULL_'+ @dateTime+ '.BAK'
      ELSE IF @backupType = 'D'
            SET @BackupFile = @backupLocation+REPLACE(REPLACE(@DBNAME, '[',''),']','')+ '_DIFF_'+ @dateTime+ '.BAK'
      ELSE IF @backupType = 'L'
            SET @BackupFile = @backupLocation+REPLACE(REPLACE(@DBNAME, '[',''),']','')+ '_LOG_'+ @dateTime+ '.TRN'

-- Provide the backup a name for storing in the media
      IF @backupType = 'F'
            SET @BackupName = REPLACE(REPLACE(@DBNAME,'[',''),']','') +' full backup for '+ @dateTime
      IF @backupType = 'D'
            SET @BackupName = REPLACE(REPLACE(@DBNAME,'[',''),']','') +' differential backup for '+ @dateTime
      IF @backupType = 'L'
            SET @BackupName = REPLACE(REPLACE(@DBNAME,'[',''),']','') +' log backup for '+ @dateTime

-- Generate the dynamic SQL command to be executed

       IF @backupType = 'F' 
                  BEGIN
               SET @sqlCommand = 'BACKUP DATABASE ' +@DBNAME+  ' TO DISK = '''+@BackupFile+ ''' WITH INIT, NAME= ''' +@BackupName+''', NOSKIP, NOFORMAT'
                  END
       IF @backupType = 'D'
                  BEGIN
               SET @sqlCommand = 'BACKUP DATABASE ' +@DBNAME+  ' TO DISK = '''+@BackupFile+ ''' WITH DIFFERENTIAL, INIT, NAME= ''' +@BackupName+''', NOSKIP, NOFORMAT'        
                  END
       IF @backupType = 'L' 
                  BEGIN
               SET @sqlCommand = 'BACKUP LOG ' +@DBNAME+  ' TO DISK = '''+@BackupFile+ ''' WITH INIT, NAME= ''' +@BackupName+''', NOSKIP, NOFORMAT'        
                  END

-- Execute the generated SQL command
       EXEC(@sqlCommand)

-- Goto the next database
SELECT @Loop = min(ID) FROM @DBs where ID>@Loop

END

And batch file can look like this:

sqlcmd -S localhost\myDB -Q "EXEC sp_BackupDatabases @backupLocation='c:\Dropbox\backup\DB\', @backupType='F'"  >> c:\Dropbox\backup\DB\full.log 2>&1

and

sqlcmd -S localhost\myDB -Q "EXEC sp_BackupDatabases @backupLocation='c:\Dropbox\backup\DB\', @backupType='D'"  >> c:\Dropbox\backup\DB\diff.log 2>&1

The advantage of this method is that you don't need to change anything if you add new database or delete a database, you don't even need to list the databases in the script. Answer from JohnB is better/simpler for server with one database, this approach is more suitable for multi database servers.

IE9 JavaScript error: SCRIPT5007: Unable to get value of the property 'ui': object is null or undefined

Well, you should also try adding the Javascript code into a function, then calling the function after document body has loaded..it worked for me :)

How do I convert struct System.Byte byte[] to a System.IO.Stream object in C#?

You're looking for the MemoryStream.Write method.

For example, the following code will write the contents of a byte[] array into a memory stream:

byte[] myByteArray = new byte[10];
MemoryStream stream = new MemoryStream();
stream.Write(myByteArray, 0, myByteArray.Length);

Alternatively, you could create a new, non-resizable MemoryStream object based on the byte array:

byte[] myByteArray = new byte[10];
MemoryStream stream = new MemoryStream(myByteArray);

Returning boolean if set is empty

If you want to return True for an empty set, then I think it would be clearer to do:

return c == set()

i.e. "c is equal to an empty set".

(Or, for the other way around, return c != set()).

In my opinion, this is more explicit (though less idiomatic) than relying on Python's interpretation of an empty set as False in a boolean context.

How can I create 2 separate log files with one log4j config file?

Try the following configuration:

log4j.rootLogger=TRACE, stdout

log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d [%24F:%t:%L] - %m%n

log4j.appender.debugLog=org.apache.log4j.FileAppender
log4j.appender.debugLog.File=logs/debug.log
log4j.appender.debugLog.layout=org.apache.log4j.PatternLayout
log4j.appender.debugLog.layout.ConversionPattern=%d [%24F:%t:%L] - %m%n

log4j.appender.reportsLog=org.apache.log4j.FileAppender
log4j.appender.reportsLog.File=logs/reports.log
log4j.appender.reportsLog.layout=org.apache.log4j.PatternLayout
log4j.appender.reportsLog.layout.ConversionPattern=%d [%24F:%t:%L] - %m%n

log4j.category.debugLogger=TRACE, debugLog
log4j.additivity.debugLogger=false

log4j.category.reportsLogger=DEBUG, reportsLog
log4j.additivity.reportsLogger=false

Then configure the loggers in the Java code accordingly:

static final Logger debugLog = Logger.getLogger("debugLogger");
static final Logger resultLog = Logger.getLogger("reportsLogger");

Do you want output to go to stdout? If not, change the first line of log4j.properties to:

log4j.rootLogger=OFF

and get rid of the stdout lines.

Generate Java classes from .XSD files...?

Talking about JAXB limitation, a solution when having the same name for different attributes is adding inline jaxb customizations to the xsd:

+

. . binding declarations . .

or external customizations...

You can see further informations on : http://jaxb.java.net/tutorial/section_5_3-Overriding-Names.html

How to convert an object to JSON correctly in Angular 2 with TypeScript

You'll have to parse again if you want it in actual JSON:

JSON.parse(JSON.stringify(object))

List Git aliases

As other answers mentioned, git config -l lists all your configuration details from your config file. Here's a partial example of that output for my configuration:

...
alias.force=push -f
alias.wd=diff --color-words
alias.shove=push -f
alias.gitignore=!git ls-files -i --exclude-from=.gitignore | xargs git rm --cached
alias.branches=!git remote show origin | grep \w*\s*(new^|tracked) -E
core.repositoryformatversion=0
core.filemode=false
core.bare=false
...

So we can grep out the alias lines, using git config -l | grep alias:

alias.force=push -f
alias.wd=diff --color-words
alias.shove=push -f
alias.gitignore=!git ls-files -i --exclude-from=.gitignore | xargs git rm --cached
alias.branches=!git remote show origin | grep \w*\s*(new^|tracked) -E

We can make this prettier by just cutting out the alias. part of each line, leaving us with this command:

git config -l | grep alias | cut -c 7-

Which prints:

force=push -f
wd=diff --color-words
shove=push -f
gitignore=!git ls-files -i --exclude-from=.gitignore | xargs git rm --cached
branches=!git remote show origin | grep \w*\s*(new^|tracked) -E

Lastly, don't forget to add this as an alias:

git config --global alias.la "!git config -l | grep alias | cut -c 7-"

Enjoy!

Tomcat 8 is not able to handle get request with '|' in query parameters?

Since Tomcat 7.0.76, 8.0.42, 8.5.12 you can define property requestTargetAllow to allow forbiden characters.

Add this line in your catalina.properties

tomcat.util.http.parser.HttpParser.requestTargetAllow=|{}

How to play YouTube video in my Android application?

MediaPlayer mp=new MediaPlayer(); 
mp.setDataSource(path);
mp.setScreenOnWhilePlaying(true);
mp.setDisplay(holder);
mp.prepare();
mp.start();

Get min and max value in PHP Array

<?php 
$array = array (0 => 
  array (
    'id' => '20110209172713',
    'Date' => '2011-02-09',
    'Weight' => '200',
  ),
  1 => 
  array (
    'id' => '20110209172747',
    'Date' => '2011-02-09',
    'Weight' => '180',
  ),
  2 => 
  array (
    'id' => '20110209172827',
    'Date' => '2011-02-09',
    'Weight' => '175',
  ),
  3 => 
  array (
    'id' => '20110211204433',
    'Date' => '2011-02-11',
    'Weight' => '195',
  ),
);

foreach ($array as $key => $value) {
  $result[$key] = $value['Weight'];
}
$min = min($result);
$max = max($result);

echo " The array in Minnumum number :".$min."<br/>";
echo " The array in Maximum  number :".$max."<br/>";
?> 

Execution failed app:processDebugResources Android Studio

In my Case Problem solved with Instant Run Disable in Android Studio 3.1.2 Android Instant Raun Disable

How to use WinForms progress bar?

Since .NET 4.5 you can use combination of async and await with Progress for sending updates to UI thread:

private void Calculate(int i)
{
    double pow = Math.Pow(i, i);
}

public void DoWork(IProgress<int> progress)
{
    // This method is executed in the context of
    // another thread (different than the main UI thread),
    // so use only thread-safe code
    for (int j = 0; j < 100000; j++)
    {
        Calculate(j);

        // Use progress to notify UI thread that progress has
        // changed
        if (progress != null)
            progress.Report((j + 1) * 100 / 100000);
    }
}

private async void button1_Click(object sender, EventArgs e)
{
    progressBar1.Maximum = 100;
    progressBar1.Step = 1;

    var progress = new Progress<int>(v =>
    {
        // This lambda is executed in context of UI thread,
        // so it can safely update form controls
        progressBar1.Value = v;
    });

    // Run operation in another thread
    await Task.Run(() => DoWork(progress));

    // TODO: Do something after all calculations
}

Tasks are currently the preferred way to implement what BackgroundWorker does.

Tasks and Progress are explained in more detail here:

Java string replace and the NUL (NULL, ASCII 0) character?

Does replacing a character in a String with a null character even work in Java?

No.

Would this be the culprit to the funky characters?

Quite likely.

Update div with jQuery ajax response html

You are setting the html of #showresults of whatever data is, and then replacing it with itself, which doesn't make much sense ?
I'm guessing you where really trying to find #showresults in the returned data, and then update the #showresults element in the DOM with the html from the one from the ajax call :

$('#submitform').click(function () {
    $.ajax({
        url: "getinfo.asp",
        data: {
            txtsearch: $('#appendedInputButton').val()
        },
        type: "GET",
        dataType: "html",
        success: function (data) {
            var result = $('<div />').append(data).find('#showresults').html();
            $('#showresults').html(result);
        },
        error: function (xhr, status) {
            alert("Sorry, there was a problem!");
        },
        complete: function (xhr, status) {
            //$('#showresults').slideDown('slow')
        }
    });
});

Creating and returning Observable from Angular 2 Service

Notice that you're using Observable#map to convert the raw Response object your base Observable emits to a parsed representation of the JSON response.

If I understood you correctly, you want to map again. But this time, converting that raw JSON to instances of your Model. So you would do something like:

http.get('api/people.json')
  .map(res => res.json())
  .map(peopleData => peopleData.map(personData => new Person(personData)))

So, you started with an Observable that emits a Response object, turned that into an observable that emits an object of the parsed JSON of that response, and then turned that into yet another observable that turned that raw JSON into an array of your models.

How to check if a date is greater than another in Java?

Parse the two dates firstDate and secondDate using SimpleDateFormat.

firstDate.after(secondDate);

firstDate.before(secondDate);

Subclipse svn:ignore

It seems Subclipse only allows you to add a top-level folder to ignore list and not any sub folders under it. Not sure why it works this way. However, I found out by trial and error that if you directly add a sub-folder to version control, then it will allow you to add another folder at the same level to the ignore list.

alt text

For example, refer fig above, when I wanted to ignore the webapp folder without adding src, subclipse was not allowing me to do so. But when I added the java folder to version control, the "add to svn:ignore..." was enabled for webapp.

How to present UIAlertController when not in a view controller?

Shorthand way to do present the alert in Objective-C:

[[[[UIApplication sharedApplication] keyWindow] rootViewController] presentViewController:alertController animated:YES completion:nil];

Where alertController is your UIAlertController object.

NOTE: You'll also need to make sure your helper class extends UIViewController

Apache Spark: map vs mapPartitions?

What's the difference between an RDD's map and mapPartitions method?

The method map converts each element of the source RDD into a single element of the result RDD by applying a function. mapPartitions converts each partition of the source RDD into multiple elements of the result (possibly none).

And does flatMap behave like map or like mapPartitions?

Neither, flatMap works on a single element (as map) and produces multiple elements of the result (as mapPartitions).

How to make Java honor the DNS Caching Timeout?

So I decided to look at the java source code because I found official docs a bit confusing. And what I found (for OpenJDK 11) mostly aligns with what others have written. What is important is the order of evaluation of properties.

InetAddressCachePolicy.java (I'm omitting some boilerplate for readability):


String tmpString = Security.getProperty("networkaddress.cache.ttl");
if (tmpString != null) {
   tmp = Integer.valueOf(tmpString);
   return;
}
...
String tmpString = System.getProperty("sun.net.inetaddr.ttl");
if (tmpString != null) {
   tmp = Integer.valueOf(tmpString);
   return;
}
...
if (tmp != null) {
  cachePolicy = tmp < 0 ? FOREVER : tmp;
  propertySet = true;
} else {
  /* No properties defined for positive caching. If there is no
  * security manager then use the default positive cache value.
  */
  if (System.getSecurityManager() == null) {
    cachePolicy = 30;
  }
}

You can clearly see that the security property is evaluated first, system property second and if any of them is set cachePolicy value is set to that number or -1 (FOREVER) if they hold a value that is bellow -1. If nothing is set it defaults to 30 seconds. As it turns out for OpenJDK that is almost always the case because by default java.security does not set that value, only a negative one.

#networkaddress.cache.ttl=-1 <- this line is commented out
networkaddress.cache.negative.ttl=10

BTW if the networkaddress.cache.negative.ttl is not set (removed from the file) the default inside the java class is 0. Documentation is wrong in this regard. This is what tripped me over.

Unable to connect to SQL Server instance remotely

  1. Open the SQL Server Configuration Manager.... 2.Check wheather TCP and UDP are running or not.... 3.If not running , Please enable them and also check the SQL Server Browser is running or not.If not running turn it on.....

  2. Next you have to check which ports TCP and UDP is using. You have to open those ports from your windows firewall.....

5.Click here to see the steps to open a specific port in windows firewall....

  1. Now SQL Server is ready to access over LAN.......

  2. If you wan to access it remotely (over internet) , you have to do another job that is 'Port Forwarding'. You have open the ports TCP and UDP is using in SQL Server on your router. Now the configuration of routers are different. If you give me the details of your router (i. e name of the company and version ) , I can show you the steps how to forward a specific port.

How to break out of while loop in Python?

ans=(R)
while True:
    print('Your score is so far '+str(myScore)+'.')
    print("Would you like to roll or quit?")
    ans=input("Roll...")
    if ans=='R':
        R=random.randint(1, 8)
        print("You rolled a "+str(R)+".")
        myScore=R+myScore
    else:
        print("Now I'll see if I can break your score...")
        ans = False
        break

How to get first element in a list of tuples?

>>> a = [(1, u'abc'), (2, u'def')]
>>> [i[0] for i in a]
[1, 2]

IE8 support for CSS Media Query

IE8 (and lower versions) and Firefox prior to 3.5 do not support media query. Safari 3.2 partially supports it.

There are some workarounds that use JavaScript to add media query support to these browsers. Try these:

Media Queries jQuery plugin (only deals with max/min width)

css3-mediaqueries-js – a library that aims to add media query support to non-supporting browsers

How can I rollback an UPDATE query in SQL server 2005?

begin transaction

// execute SQL code here

rollback transaction

If you've already executed the query and want to roll it back, unfortunately your only real option is to restore a database backup. If you're using Full backups, then you should be able to restore the database to a specific point in time.

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:

Query to search all packages for table and/or column

Sometimes the column you are looking for may be part of the name of many other things that you are not interested in.

For example I was recently looking for a column called "BQR", which also forms part of many other columns such as "BQR_OWNER", "PROP_BQR", etc.

So I would like to have the checkbox that word processors have to indicate "Whole words only".

Unfortunately LIKE has no such functionality, but REGEXP_LIKE can help.

SELECT *
  FROM user_source
 WHERE regexp_like(text, '(\s|\.|,|^)bqr(\s|,|$)');

This is the regular expression to find this column and exclude the other columns with "BQR" as part of the name:

(\s|\.|,|^)bqr(\s|,|$)

The regular expression matches white-space (\s), or (|) period (.), or (|) comma (,), or (|) start-of-line (^), followed by "bqr", followed by white-space, comma or end-of-line ($).

Datatable select with multiple conditions

Try this,
I think ,this is one of the simple solutions.

int rowIndex = table.Rows.IndexOf(table.Select("A = 'foo' AND B = 'bar' AND C = 'baz'")[0]);
string strD= Convert.ToString(table.Rows[rowIndex]["D"]);

Make sure,combination of values for column A, B and C is unique in the datatable.

SQL Stored Procedure: If variable is not null, update statement

Use a T-SQL IF:

IF @ABC IS NOT NULL AND @ABC != -1
    UPDATE [TABLE_NAME] SET XYZ=@ABC

Take a look at the MSDN docs.

Rails: Why "sudo" command is not recognized?

That you are running Windows. Read:

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

It basically allows you to execute an application with elevated privileges. If you want to achieve a similar effect under Windows, open an administrative prompt and execute your command from there. Under Vista, this is easily done by opening the shortcut while holding Ctrl+Shift at the same time.

That being said, it might very well be possible that your account already has sufficient privileges, depending on how your OS is setup, and the Windows version used.

Create whole path automatically when writing to a new file

Something like:

File file = new File("C:\\user\\Desktop\\dir1\\dir2\\filename.txt");
file.getParentFile().mkdirs();
FileWriter writer = new FileWriter(file);

Annotations from javax.validation.constraints not working

So @Valid at service interface would work for only that object. If you have any more validations within the hierarchy of ServiceRequest object then you might to have explicitly trigger validations. So this is how I have done it:

public class ServiceRequestValidator {

      private static Validator validator;

      @PostConstruct
      public void init(){
         validator = Validation.buildDefaultValidatorFactory().getValidator();
      }

      public static <T> void validate(T t){
        Set<ConstraintViolation<T>> errors = validator.validate(t);
        if(CollectionUtils.isNotEmpty(errors)){
          throw new ConstraintViolationException(errors);
        }
     }

}

You need to have following annotations at the object level if you want to trigger validation for that object.

@Valid
@NotNull

Spring Boot - Handle to Hibernate SessionFactory

It works with Spring Boot 2.1.0 and Hibernate 5

@PersistenceContext
private EntityManager entityManager;

Then you can create new Session by using entityManager.unwrap(Session.class)

Session session = null;
if (entityManager == null
    || (session = entityManager.unwrap(Session.class)) == null) {

    throw new NullPointerException();
}

example create query:

session.createQuery("FROM Student");

application.properties:

spring.datasource.driver-class-name=oracle.jdbc.driver.OracleDriver
spring.datasource.url=jdbc:oracle:thin:@localhost:1521:db11g
spring.datasource.username=admin
spring.datasource.password=admin
spring.jpa.show-sql=true spring.jpa.hibernate.ddl-auto=create-drop
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.Oracle10gDialect

IE11 Document mode defaults to IE7. How to reset?

If the problem is happening on a specific computer,then please try the following fix provided you have Internet Explorer 11.

Please open regedit.exe as an Administrator. Navigate to the following path/paths:

  1. For 32 bit machine:

    HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Internet Explorer\Main\FeatureControl\FEATURE_BROWSER_EMULATION
    
  2. For 64 bit machine:

    HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Internet Explorer\Main\FeatureControl\FEATURE_BROWSER_EMULATION & 
    HKEY_LOCAL_MACHINE\SOFTWARE\WOW6432Node\Microsoft\Internet Explorer\Main\FeatureControl\FEATURE_BROWSER_EMULATION
    

And delete the REG_DWORD value iexplore.exe.

Please close and relaunch the website using Internet Explorer 11, it will default to Edge as Document Mode.

How to set up Automapper in ASP.NET Core

I am using AutoMapper 6.1.1 and asp.net Core 1.1.2.

First of all, define Profile classes inherited by Profile Class of Automapper. I Created IProfile interface which is empty, the purpose is only to find the classes of this type.

 public class UserProfile : Profile, IProfile
    {
        public UserProfile()
        {
            CreateMap<User, UserModel>();
            CreateMap<UserModel, User>();
        }
    }

Now create a separate class e.g Mappings

 public class Mappings
    {
     public static void RegisterMappings()
     {            
       var all =
       Assembly
          .GetEntryAssembly()
          .GetReferencedAssemblies()
          .Select(Assembly.Load)
          .SelectMany(x => x.DefinedTypes)
          .Where(type => typeof(IProfile).GetTypeInfo().IsAssignableFrom(type.AsType()));

            foreach (var ti in all)
            {
                var t = ti.AsType();
                if (t.Equals(typeof(IProfile)))
                {
                    Mapper.Initialize(cfg =>
                    {
                        cfg.AddProfiles(t); // Initialise each Profile classe
                    });
                }
            }         
        }

    }

Now in MVC Core web Project in Startup.cs file, in the constructor, call Mapping class which will initialize all mappings at the time of application loading.

Mappings.RegisterMappings();

Selenium Webdriver move mouse to Point

I am using JavaScript but some of the principles are common I am sure.

The code I am using is as follows:

    var s = new webdriver.ActionSequence(d);
    d.findElement(By.className('fc-time')).then(function(result){
        s.mouseMove(result,l).click().perform();
    });

the driver = d. The location = l is simply {x:300,y:500) - it is just an offset.

What I found during my testing was that I could not make it work without using the method to find an existing element first, using that at a basis from where to locate my click.

I suspect the figures in the locate are a bit more difficult to predict than I thought.

It is an old post but this response may help other newcomers like me.

Calculate distance in meters when you know longitude and latitude in java

You can use the Java Geodesy Library for GPS, it uses the Vincenty's formulae which takes account of the earths surface curvature.

Implementation goes like this:

import org.gavaghan.geodesy.*;

...

GeodeticCalculator geoCalc = new GeodeticCalculator();

Ellipsoid reference = Ellipsoid.WGS84;  

GlobalPosition pointA = new GlobalPosition(latitude, longitude, 0.0); // Point A

GlobalPosition userPos = new GlobalPosition(userLat, userLon, 0.0); // Point B

double distance = geoCalc.calculateGeodeticCurve(reference, userPos, pointA).getEllipsoidalDistance(); // Distance between Point A and Point B

The resulting distance is in meters.

How to configure Visual Studio to use Beyond Compare

I use BC3 for my git diff, but I'd also add vscode to the list of useful git diff tools. Some users prefer vscode over vs ide experience.

Using VS Code for Git Diff

git config --global diff.tool vscode
git config --global difftool.vscode.cmd "code --wait --diff $LOCAL $REMOTE"

JavaScript function in href vs. onclick

The top answer is a very bad practice, one should never ever link to an empty hash as it can create problems down the road.

Best is to bind an event handler to the element as numerous other people have stated, however, <a href="javascript:doStuff();">do stuff</a> works perfectly in every modern browser, and I use it extensively when rendering templates to avoid having to rebind for each instance. In some cases, this approach offers better performance. YMMV

Another interesting tid-bit....

onclick & href have different behaviors when calling javascript directly.

onclick will pass this context correctly, whereas href won't, or in other words <a href="javascript:doStuff(this)">no context</a> won't work, whereas <a onclick="javascript:doStuff(this)">no context</a> will.

Yes, I omitted the href. While that doesn't follow the spec, it will work in all browsers, although, ideally it should include a href="javascript:void(0);" for good measure

Disabling user input for UITextfield in swift

In swift 5, I used following code to disable the textfield

override func viewDidLoad() {
   super.viewDidLoad()
   self.textfield.isEnabled = false
   //e.g
   self.design.isEnabled = false
}

Detecting locked tables (locked by LOCK TABLE)

You could also get all relevant details from performance_schema:

SELECT
OBJECT_SCHEMA
,OBJECT_NAME
,GROUP_CONCAT(DISTINCT EXTERNAL_LOCK)
FROM performance_schema.table_handles 
WHERE EXTERNAL_LOCK IS NOT NULL

GROUP BY
OBJECT_SCHEMA
,OBJECT_NAME

This works similar as

show open tables WHERE In_use > 0

How to set fake GPS location on IOS real device

Working with GPX files with Xcode compatibility

I followed the link given by AlexWien and it was extremely useful: https://blackpixel.com/writing/2013/05/simulating-locations-with-xcode.html

But, I spent quite some time searching for how to generate .gpx files with waypoints (wpt tags), as Xcode only accepts wpt tags.

The following tool converts a Google Maps link (also works with Google Maps Directions) to a .gpx file.

https://mapstogpx.com/mobiledev.php

Simulating a trip duration is supported, custom durations can be specified. Just select Xcode and it gets the route as waypoints.

Any way to write a Windows .bat file to kill processes?

Here I wrote an example command that you can paste in your cmd command line prompt and is written for chrome.exe.

FOR /F "tokens=2 delims= " %P IN ('tasklist /FO Table /M "chrome*" /NH') DO (TASKKILL /PID %P)

The for just takes all the PIDs listed on the below tasklist command and executes TASKKILL /PID on every PID

tasklist /FO Table /M "chrome*" /NH

If you use the for in a batch file just use %%P instead of %P

Playing HTML5 video on fullscreen in android webview

It seems that in lollipop and up (or maybe just a different WebView Version) that calling cprcrack's onHideCustomView() method does not work. It works if it is called from the exit fullscreen button but when you specifically call the method it will only exit fullscreen but the webView stays blank. A way around it is to simply add these lines of code to onHideCustomView():

String js = "javascript:";
js += "var _ytrp_html5_video = document.getElementsByTagName('video')[0];";
js += "_ytrp_html5_video.webkitExitFullscreen();";
webView.loadUrl(js);

This will notify the webView that fullscreen has exited.

Show current assembly instruction in GDB

Setting the following option:

set  disassemble-next-line on
show disassemble-next-line

Will give you results that look like this:

(gdb) stepi
0x000002ce in ResetISR () at startup_gcc.c:245
245 {
   0x000002cc <ResetISR+0>: 80 b5   push    {r7, lr}
=> 0x000002ce <ResetISR+2>: 82 b0   sub sp, #8
   0x000002d0 <ResetISR+4>: 00 af   add r7, sp, #0
(gdb) stepi
0x000002d0  245 {
   0x000002cc <ResetISR+0>: 80 b5   push    {r7, lr}
   0x000002ce <ResetISR+2>: 82 b0   sub sp, #8
=> 0x000002d0 <ResetISR+4>: 00 af   add r7, sp, #0

How to make spring inject value into a static field

You have two possibilities:

  1. non-static setter for static property/field;
  2. using org.springframework.beans.factory.config.MethodInvokingFactoryBean to invoke a static setter.

In the first option you have a bean with a regular setter but instead setting an instance property you set the static property/field.

public void setTheProperty(Object value) {
    foo.bar.Class.STATIC_VALUE = value;
}

but in order to do this you need to have an instance of a bean that will expose this setter (its more like an workaround).

In the second case it would be done as follows:

<bean class="org.springframework.beans.factory.config.MethodInvokingFactoryBean">
    <property name="staticMethod" value="foo.bar.Class.setTheProperty"/>
    <property name="arguments">
        <list>
            <ref bean="theProperty"/>
        </list>
   </property>
</bean>

On you case you will add a new setter on the Utils class:

public static setDataBaseAttr(Properties p)

and in your context you will configure it with the approach exemplified above, more or less like:

<bean class="org.springframework.beans.factory.config.MethodInvokingFactoryBean">
    <property name="staticMethod" value="foo.bar.Utils.setDataBaseAttr"/>
    <property name="arguments">
        <list>
            <ref bean="dataBaseAttr"/>
        </list>
   </property>
</bean>

How do I view 'git diff' output with my preferred diff tool/ viewer?

I use kompare on ubuntu:

sudo apt-get install kompare

To compare two branches:

git difftool -t kompare <my_branch> master

what is the unsigned datatype?

Bringing my answer from another question.

From the C specification, section 6.7.2:

— unsigned, or unsigned int

Meaning that unsigned, when not specified the type, shall default to unsigned int. So writing unsigned a is the same as unsigned int a.