Programs & Examples On #Jtracert

HTML SELECT - Change selected option by VALUE using JavaScript

document.getElementById('drpSelectSourceLibrary').value = 'Seven';

Angularjs loading screen on ajax request

I use ngProgress for this.

Add 'ngProgress' to your dependencies once you've included the script/css files in your HTML. Once you do that you can set up something like this, which will trigger when a route change was detected.

angular.module('app').run(function($rootScope, ngProgress) {
  $rootScope.$on('$routeChangeStart', function(ev,data) {
    ngProgress.start();
  });
  $rootScope.$on('$routeChangeSuccess', function(ev,data) {
    ngProgress.complete();
  });
});

For AJAX requests you can do something like this:

$scope.getLatest = function () {
    ngProgress.start();

    $http.get('/latest-goodies')
         .success(function(data,status) {
             $scope.latest = data;
             ngProgress.complete();
         })
         .error(function(data,status) {
             ngProgress.complete();
         });
};

Just remember to add 'ngProgress' to the controllers dependencies before doing so. And if you are doing multiple AJAX requests use an incremental variable in the main app scope to keep track when your AJAX requests have finished before calling 'ngProgress.complete();'.

How to call a JavaScript function from PHP?

Per now (February 2012) there's a new feature for this. Check here

Code sample (taken from the web):

<?php

$v8 = new V8Js();

/* basic.js */
$JS = <<< EOT
len = print('Hello' + ' ' + 'World!' + "\\n");
len;
EOT;

try {
  var_dump($v8->executeString($JS, 'basic.js'));
} catch (V8JsException $e) {
  var_dump($e);
}

?>

PHP - SSL certificate error: unable to get local issuer certificate

If none of the solutions above are working for you try updating your XAMPP installation to a newer version.

I was running XAMPP with php 5.5.11, the same exact code didn't work, I upgraded to XAMPP with php 5.6.28 and the solutions above worked.

Additionally only updating PHP didn't work either seems like a combination of apache and php settings on that version of XAMPP.

Hope it helps someone.

How to flush output after each `echo` call?

Flushing seemingly failing to work is a side effect of automatic character set detection.

The browser will not display anything until it knows the character set to display it in, and if you don't specify the character set, it need tries to guess it. The problem being that it can't make a good guess without enough data, which is why browsers seem to have this 1024 byte (or similar) buffer they need filled before displaying anything.

The solution is therefore to make sure the browser doesn't have to guess the character set.

If you're sending text, add a '; charset=utf-8' to its content type, and if it's HTML, add the character set to the appropriate meta tag.

How do you automatically set text box to Uppercase?

Set following style to set all textbox to uppercase

input {text-transform: uppercase;}

Merge 2 DataTables and store in a new one

This is what i did for merging two datatables and bind the final result to the gridview

        DataTable dtTemp=new DataTable();
        for (int k = 0; k < GridView2.Rows.Count; k++)
        {
            string roomno = GridView2.Rows[k].Cells[1].Text;
            DataTable dtx = GetRoomDetails(chk, roomno, out msg);
            if (dtx.Rows.Count > 0)
            {
                dtTemp.Merge(dtx);
                dtTemp.AcceptChanges();

            }
        }

ARG or ENV, which one to use in this case?

So if want to set the value of an environment variable to something different for every build then we can pass these values during build time and we don't need to change our docker file every time.

While ENV, once set cannot be overwritten through command line values. So, if we want to have our environment variable to have different values for different builds then we could use ARG and set default values in our docker file. And when we want to overwrite these values then we can do so using --build-args at every build without changing our docker file.

For more details, you can refer this.

ImportError: No module named enum

Depending on your rights, you need sudo at beginning.

Call JavaScript function on DropDownList SelectedIndexChanged Event:

Or you can do it like as well:

<asp:DropDownList ID="ddl" runat="server"  AutoPostBack="true" onchange="javascript:CalcTotalAmt();" OnSelectedIndexChanged="ddl_SelectedIndexChanged"></asp:DropDownList>

Tooltips for cells in HTML table (no Javascript)

if (data[j] =='B'){
    row.cells[j].title="Basic";
}

In Java script conditionally adding title by comparing value of Data. The Table is generated by Java script dynamically.

How to get default gateway in Mac OSX

Using System Preferences:

Step 1: Click the Apple icon (at the top left of the screen) and select System Preferences.

Step 2: Click Network.

Step 3: Select your network connection and then click Advanced.

Step 4: Select the TCP/IP tab and find your gateway IP address listed next to Router.

Java default constructor

If a class doesn't have any constructor provided by programmer, then java compiler will add a default constructor with out parameters which will call super class constructor internally with super() call. This is called as default constructor.

In your case, there is no default constructor as you are adding them programmatically. If there are no constructors added by you, then compiler generated default constructor will look like this.

public Module()
{
   super();
}

Note: In side default constructor, it will add super() call also, to call super class constructor.

Purpose of adding default constructor:

Constructor's duty is to initialize instance variables, if there are no instance variables you could choose to remove constructor from your class. But when you are inheriting some class it is your class responsibility to call super class constructor to make sure that super class initializes all its instance variables properly.

That's why if there are no constructors, java compiler will add a default constructor and calls super class constructor.

Converting array to list in Java

In your example, it is because you can't have a List of a primitive type. In other words, List<int> is not possible.

You can, however, have a List<Integer> using the Integer class that wraps the int primitive. Convert your array to a List with the Arrays.asList utility method.

Integer[] spam = new Integer[] { 1, 2, 3 };
List<Integer> list = Arrays.asList(spam);

See this code run live at IdeOne.com.

How to delete session cookie in Postman?

I tried clearing the chrome cookies to get rid of postman cookies, as one of the answers given here. But it didn't work for me. I checked my postman version, found that it's an old version 5.5.4. So I just tried a Postman update to its latest version 7.3.4. Cool, the issue fixed !!

Find the maximum value in a list of tuples in Python

In addition to max, you can also sort:

>>> lis
[(101, 153), (255, 827), (361, 961)]
>>> sorted(lis,key=lambda x: x[1], reverse=True)[0]
(361, 961)

how to destroy an object in java?

Here is the code:

public static void main(String argso[]) {
int big_array[] = new int[100000];

// Do some computations with big_array and get a result. 
int result = compute(big_array);

// We no longer need big_array. It will get garbage collected when there
// are no more references to it. Since big_array is a local variable,
// it refers to the array until this method returns. But this method
// doesn't return. So we've got to explicitly get rid of the reference
// ourselves, so the garbage collector knows it can reclaim the array. 
big_array = null;

// Loop forever, handling the user's input
for(;;) handle_input(result);
}

Set the absolute position of a view

Try below code to set view on specific location :-

            TextView textView = new TextView(getActivity());
            textView.setId(R.id.overflowCount);
            textView.setText(count + "");
            textView.setGravity(Gravity.CENTER);
            textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, 12);
            textView.setTextColor(getActivity().getResources().getColor(R.color.white));
            textView.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    // to handle click 
                }
            });
            // set background 
            textView.setBackgroundResource(R.drawable.overflow_menu_badge_bg);

            // set apear

            textView.animate()
                    .scaleXBy(.15f)
                    .scaleYBy(.15f)
                    .setDuration(700)
                    .alpha(1)
                    .setInterpolator(new BounceInterpolator()).start();
            FrameLayout.LayoutParams layoutParams = new FrameLayout.LayoutParams(
                    FrameLayout.LayoutParams.WRAP_CONTENT,
                    FrameLayout.LayoutParams.WRAP_CONTENT);
            layoutParams.topMargin = 100; // margin in pixels, not dps
            layoutParams.leftMargin = 100; // margin in pixels, not dps
            textView.setLayoutParams(layoutParams);

            // add into my parent view
            mainFrameLaout.addView(textView);

How to iterate through range of Dates in Java?

public static final void generateRange(final Date dateFrom, final Date dateTo)
{
    final Calendar current = Calendar.getInstance();
    current.setTime(dateFrom);

    while (!current.getTime().after(dateTo))
    {
        // TODO

        current.add(Calendar.DATE, 1);
    }
}

VBA check if object is set

The (un)safe way to do this - if you are ok with not using option explicit - is...

Not TypeName(myObj) = "Empty"

This also handles the case if the object has not been declared. This is useful if you want to just comment out a declaration to switch off some behaviour...

Dim myObj as Object
Not TypeName(myObj) = "Empty"  '/ true, the object exists - TypeName is Object

'Dim myObj as Object
Not TypeName(myObj) = "Empty"  '/ false, the object has not been declared

This works because VBA will auto-instantiate an undeclared variable as an Empty Variant type. It eliminates the need for an auxiliary Boolean to manage the behaviour.

Adding null values to arraylist

Yes, you can always use null instead of an object. Just be careful because some methods might throw error.

It would be 1.

also nulls would be factored in in the for loop, but you could use

 for(Item i : itemList) {
        if (i!= null) {
               //code here
        }
 }

Counting the Number of keywords in a dictionary in python

If the question is about counting the number of keywords then would recommend something like

def countoccurrences(store, value):
    try:
        store[value] = store[value] + 1
    except KeyError as e:
        store[value] = 1
    return

in the main function have something that loops through the data and pass the values to countoccurrences function

if __name__ == "__main__":
    store = {}
    list = ('a', 'a', 'b', 'c', 'c')
    for data in list:
        countoccurrences(store, data)
    for k, v in store.iteritems():
        print "Key " + k + " has occurred "  + str(v) + " times"

The code outputs

Key a has occurred 2 times
Key c has occurred 2 times
Key b has occurred 1 times

QED symbol in latex

The question specifically mentions a full box and not an empty box and not using proof environment from amsthm package. Hence, an option may be to use the command \QED from the package stix. It reproduces the character U+220E (end of proof, ?).

Generics/templates in python?

Fortunately there has been some efforts for the generic programming in python . There is a library : generic

Here is the documentation for it: http://generic.readthedocs.org/en/latest/

It hasn't progress over years , but you can have a rough idea how to use & make your own library.

Cheers

Spring RestTemplate GET with parameters

I am providing a code snippet of RestTemplate GET method with path param example

public ResponseEntity<String> getName(int id) {
    final String url = "http://localhost:8080/springrestexample/employee/name?id={id}";
    Map<String, String> params = new HashMap<String, String>();
    params.put("id", id);
    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.APPLICATION_JSON);
    HttpEntity request = new HttpEntity(headers);
    ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.GET, String.class, params);
    return response;
}

Swift alert view with OK and Cancel: which button tapped?

If you are using iOS8, you should be using UIAlertController — UIAlertView is deprecated.

Here is an example of how to use it:

var refreshAlert = UIAlertController(title: "Refresh", message: "All data will be lost.", preferredStyle: UIAlertControllerStyle.Alert)

refreshAlert.addAction(UIAlertAction(title: "Ok", style: .Default, handler: { (action: UIAlertAction!) in
  print("Handle Ok logic here")
  }))

refreshAlert.addAction(UIAlertAction(title: "Cancel", style: .Cancel, handler: { (action: UIAlertAction!) in
  print("Handle Cancel Logic here")
  }))

presentViewController(refreshAlert, animated: true, completion: nil)

As you can see the block handlers for the UIAlertAction handle the button presses. A great tutorial is here (although this tutorial is not written using swift): http://hayageek.com/uialertcontroller-example-ios/

Swift 3 update:

let refreshAlert = UIAlertController(title: "Refresh", message: "All data will be lost.", preferredStyle: UIAlertControllerStyle.alert)

refreshAlert.addAction(UIAlertAction(title: "Ok", style: .default, handler: { (action: UIAlertAction!) in
    print("Handle Ok logic here")
}))

refreshAlert.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: { (action: UIAlertAction!) in
    print("Handle Cancel Logic here")
}))

present(refreshAlert, animated: true, completion: nil)

Swift 5 update:

let refreshAlert = UIAlertController(title: "Refresh", message: "All data will be lost.", preferredStyle: UIAlertControllerStyle.alert)

refreshAlert.addAction(UIAlertAction(title: "Ok", style: .default, handler: { (action: UIAlertAction!) in
      print("Handle Ok logic here")
}))

refreshAlert.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: { (action: UIAlertAction!) in
      print("Handle Cancel Logic here")
}))

present(refreshAlert, animated: true, completion: nil)

Swift 5.3 update:

let refreshAlert = UIAlertController(title: "Refresh", message: "All data will be lost.", preferredStyle: UIAlertController.Style.alert)

refreshAlert.addAction(UIAlertAction(title: "Ok", style: .default, handler: { (action: UIAlertAction!) in
      print("Handle Ok logic here")
}))

refreshAlert.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: { (action: UIAlertAction!) in
      print("Handle Cancel Logic here")
}))

present(refreshAlert, animated: true, completion: nil)

Running CMD command in PowerShell

You must use the Invoke-Command cmdlet to launch this external program. Normally it works without an effort.

If you need more than one command you should use the Invoke-Expression cmdlet with the -scriptblock option.

Install gitk on Mac

First you need to check which version of git you are running, the one installed with brew should be running on /usr/local/bin/git , you can verify this from a terminal using:

which git

In case git shows up on a different directory you need to run this from a terminal to add it to your path:

echo export PATH='/usr/local/bin:$PATH' >> ~/.bash_profile

After that you can close and open again your terminal or just run:

source ~/.bash_profile

And voila! In case you are running on OSX Mavericks you might need to install XQuartz.

Mix Razor and Javascript code

you can use the <text> tag for both cshtml code with javascript

What is stability in sorting algorithms and why is it important?

I know there are many answers for this, but to me, this answer, by Robert Harvey, summarized it much more clearly:

A stable sort is one which preserves the original order of the input set, where the [unstable] algorithm does not distinguish between two or more items.

Source

How to add new column to MYSQL table?

for WORDPRESS:

global $wpdb;


$your_table  = $wpdb->prefix. 'My_Table_Name';
$your_column =                'My_Column_Name'; 

if (!in_array($your_column, $wpdb->get_col( "DESC " . $your_table, 0 ) )){  $result= $wpdb->query(
    "ALTER     TABLE $your_table     ADD $your_column     VARCHAR(100)     CHARACTER SET utf8     NOT NULL     "  //you can add positioning phraze: "AFTER My_another_column"
);}

How to recursively download a folder via FTP on Linux

There is 'ncftp' which is available for installation in linux. This works on the FTP protocol and can be used to download files and folders recursively. works on linux. Has been used and is working fine for recursive folder/file transfer.

Check this link... http://www.ncftp.com/

Count number of 1's in binary representation

I saw the following solution from another website:

int count_one(int x){
    x = (x & (0x55555555)) + ((x >> 1) & (0x55555555));
    x = (x & (0x33333333)) + ((x >> 2) & (0x33333333));
    x = (x & (0x0f0f0f0f)) + ((x >> 4) & (0x0f0f0f0f));
    x = (x & (0x00ff00ff)) + ((x >> 8) & (0x00ff00ff));
    x = (x & (0x0000ffff)) + ((x >> 16) & (0x0000ffff));
    return x;
}

How do I run a PowerShell script when the computer starts?

enter image description hereA relatively short path to specifying a Powershell script to execute at startup in Windows could be:

  1. Click the Windows-button (Windows-button + r)
  2. Enter this:

shell:startup

  1. Create a new shortcut by rightclick and in context menu choose menu item: New=>Shortcut

  2. Create a shortcut to your script, e.g:

C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe -NoProfile -Command "C:\Users\someuser\Documents\WindowsPowerShell\Scripts\somesscript.ps1"

Note the use of -NoProfile In case you put a lot of initializing in your $profile file, it is inefficient to load this up to just run a Powershell script. The -NoProfile will skip loading your profile file and is smart to specify, if it is not necessary to run it before the Powershell script is to be executed.

Here you see such a shortcut created (.lnk file with a Powershell icon with shortcut glyph):

How can I have a newline in a string in sh?

I wasn't really happy with any of the options here. This is what worked for me.

str=$(printf "%s" "first line")
str=$(printf "$str\n%s" "another line")
str=$(printf "$str\n%s" "and another line")

How to get dictionary values as a generic list

Use this:

List<MyType> items = new List<MyType>()
foreach(var value in myDico.Values)
    items.AddRange(value);

The problem is that every key in your dictionary has a list of instances as value. Your code would work, if each key would have exactly one instance as value, as in the following example:

Dictionary<string, MyType> myDico = GetDictionary();
List<MyType> items = new List<MyType>(myDico.Values);

How can I check if the current date/time is past a set date/time?

Check PHP's strtotime-function to convert your set date/time to a timestamp: http://php.net/manual/en/function.strtotime.php

If strtotime can't handle your date/time format correctly ("4:00PM" will probably work but not "at 4PM"), you'll need to use string-functions, e.g. substr to parse/correct your format and retrieve your timestamp through another function, e.g. mktime.

Then compare the resulting timestamp with the current date/time (if ($calulated_timestamp > time()) { /* date in the future */ }) to see whether the set date/time is in the past or the future.

I suggest to read the PHP-doc on date/time-functions and get back here with some of your source-code once you get stuck.

What exactly is nullptr?

From nullptr: A Type-safe and Clear-Cut Null Pointer:

The new C++09 nullptr keyword designates an rvalue constant that serves as a universal null pointer literal, replacing the buggy and weakly-typed literal 0 and the infamous NULL macro. nullptr thus puts an end to more than 30 years of embarrassment, ambiguity, and bugs. The following sections present the nullptr facility and show how it can remedy the ailments of NULL and 0.

Other references:

How can I select an element with multiple classes in jQuery?

You can use getElementsByClassName() method for what you want.

_x000D_
_x000D_
var elems = document.getElementsByClassName("a b c");_x000D_
elems[0].style.color = "green";_x000D_
console.log(elems[0]);
_x000D_
<ul>_x000D_
  <li class="a">a</li>_x000D_
  <li class="a b">a, b</li>_x000D_
  <li class="a b c">a, b, c</li>_x000D_
</ul>
_x000D_
_x000D_
_x000D_

This is the fastest solution also. you can see a benchmark about that here.

Check if a file is executable

To test whether a file itself has ACL_EXECUTE bit set in any of permission sets (user, group, others) regardless of where it resides, i. e. even on a tmpfs with noexec option, use stat -c '%A' to get the permission string and then check if it contains at least a single “x” letter:

if [[ "$(stat -c '%A' 'my_exec_file')" == *'x'* ]] ; then
    echo 'Has executable permission for someone'
fi

The right-hand part of comparison may be modified to fit more specific cases, such as *x*x*x* to check whether all kinds of users should be able to execute the file when it is placed on a volume mounted with exec option.

How to select first and last TD in a row?

You could use the :first-child and :last-child pseudo-selectors:

tr td:first-child,
tr td:last-child {
    /* styles */
}

This should work in all major browsers, but IE7 has some problems when elements are added dynamically (and it won't work in IE6).

How do I make background-size work in IE?

Even later, but this could be usefull too. There is the jQuery-backstretch-plugin you can use as a polyfill for background-size: cover. I guess it must be possible (and fairly simple) to grab the css-background-url property with jQuery and feed it to the jQuery-backstretch plugin. Good practice would be to test for background-size-support with modernizr and use this plugin as a fallback.

The backstretch-plugin was mentioned on SO here.The jQuery-backstretch-plugin-site is here.

In similar fashion you could make a jQuery-plugin or script that makes background-size work in your situation (background-size: 100%) and in IE8-. So to answer your question: Yes there is a way but atm there is no plug-and-play solution (ie you have to do some coding yourself).

(disclaimer: I didn't examine the backstretch-plugin thoroughly but it seems to do the same as background-size: cover)

Declare an array in TypeScript

Here are the different ways in which you can create an array of booleans in typescript:

let arr1: boolean[] = [];
let arr2: boolean[] = new Array();
let arr3: boolean[] = Array();

let arr4: Array<boolean> = [];
let arr5: Array<boolean> = new Array();
let arr6: Array<boolean> = Array();

let arr7 = [] as boolean[];
let arr8 = new Array() as Array<boolean>;
let arr9 = Array() as boolean[];

let arr10 = <boolean[]> [];
let arr11 = <Array<boolean>> new Array();
let arr12 = <boolean[]> Array();

let arr13 = new Array<boolean>();
let arr14 = Array<boolean>();

You can access them using the index:

console.log(arr[5]);

and you add elements using push:

arr.push(true);

When creating the array you can supply the initial values:

let arr1: boolean[] = [true, false];
let arr2: boolean[] = new Array(true, false);

convert string to date in sql server

I think style no. 111 (Japan) should work:

SELECT CONVERT(DATETIME, '2012-08-17', 111)

And if that doesn't work for some reason - you could always just strip out the dashes and then you have the totally reliable ISO-8601 format (YYYYMMDD) which works for any language and date format setting in SQL Server:

SELECT CAST(REPLACE('2012-08-17', '-', '') AS DATETIME)

trigger click event from angularjs directive

This is how I was able to trigger a button click when the page loads.

<li ng-repeat="a in array">
  <a class="button" id="btn" ng-click="function(a)" index="$index" on-load-clicker>
    {{a.name}}
  </a>
</li>

A simple directive that takes the index from the ng-repeat and uses a condition to call the first button in the index and click it when the page loads.

angular
    .module("myApp")
        .directive('onLoadClicker', function ($timeout) {
            return {
                restrict: 'A',
                scope: {
                    index: '=index'
                },
                link: function($scope, iElm) {
                    if ($scope.index == 0) {
                        $timeout(function() {

                            iElm.triggerHandler('click');

                        }, 0);
                    }
                }
            };
        });

This was the only way I was able to even trigger an auto click programmatically in the first place. angular.element(document.querySelector('#btn')).click(); Did not work from the controller so making this simple directive seems most effective if you are trying to run a click on page load and you can specify which button to click by passing in the index. I got help through this stack-overflow answer from another post reference: https://stackoverflow.com/a/26495541/4684183 onLoadClicker Directive.

Find duplicates and delete all in notepad++

You could use

Click TextFX ? Click TextFX Tools ? Click Sort lines case insensitive (at column) Duplicates and blank lines have been removed and the data has been sorted alphabetically.

as indicated above. However, the way I did it because I need to replace the duplicates by blank lines and not just remove the lines, once sorted alphabetically:

REPLACE:
((^.*$)(\n))(?=\k<1>)

by

$3

This will convert:

Shorts
Shorts
Shorts
Shorts
Shorts
Shorts Two Pack
Shorts Two Pack
Signature Braces
Signature Braces
Signature Cotton Trousers
Signature Cotton Trousers
Signature Cotton Trousers
Signature Cotton Trousers
Signature Cotton Trousers
Signature Cotton Trousers
Signature Cotton Trousers
Signature Cotton Trousers
Signature Cotton Trousers
Signature Cotton Trousers
Signature Cotton Trousers

to:

Shorts

Shorts Two Pack

Signature Braces










Signature Cotton Trousers

That's how I did it because I specifically needed those lines.

OpenCV TypeError: Expected cv::UMat for argument 'src' - What is this?

Is canny your own function? Do you use Canny from OpenCV inside it? If yes check if you feed suitable argument for Canny - first Canny argument should meet following criteria:

  • type: <type 'numpy.ndarray'>
  • dtype: dtype('uint8')
  • being single channel or simplyfing: grayscale, that is 2D array, i.e. its shape should be 2-tuple of ints (tuple containing exactly 2 integers)

You can check it by printing respectively

type(variable_name)
variable_name.dtype
variable_name.shape

Replace variable_name with name of variable you feed as first argument to Canny.

How do I sort a VARCHAR column in SQL server that contains numbers?

One possible solution is to pad the numeric values with a character in front so that all are of the same string length.

Here is an example using that approach:

select MyColumn
from MyTable
order by 
    case IsNumeric(MyColumn) 
        when 1 then Replicate('0', 100 - Len(MyColumn)) + MyColumn
        else MyColumn
    end

The 100 should be replaced with the actual length of that column.

substring of an entire column in pandas dataframe

case the column isn't string, use astype to convert:

df['col'] = df['col'].astype(str).str[:9]

How to center a subview of UIView

The easiest way:

child.center = parent.center

How to make a promise from setTimeout

const setTimeoutAsync = (cb, delay) =>
  new Promise((resolve) => {
    setTimeout(() => {
      resolve(cb());
    }, delay);
  });

We can pass custom 'cb fxn' like this one

What is the iOS 5.0 user agent string?

iPhone:

Mozilla/5.0 (iPhone; CPU iPhone OS 5_0 like Mac OS X) AppleWebKit/534.46 (KHTML, like Gecko) Version/5.1 Mobile/9A334 Safari/7534.48.3

iPad:

Mozilla/5.0 (iPad; CPU OS 5_0 like Mac OS X) AppleWebKit/534.46 (KHTML, like Gecko) Version/5.1 Mobile/9A334 Safari/7534.48.3

Port 443 in use by "Unable to open process" with PID 4

I got this same error and managed to fix it by closing Skype and running XAMP as Administrator, works perfectly now. So right click THE XAMP icon and click run as admin.

How do I get java logging output to appear on a single line?

I've figured out a way that works. You can subclass SimpleFormatter and override the format method

    public String format(LogRecord record) {
        return new java.util.Date() + " " + record.getLevel() + " " + record.getMessage() + "\r\n";
    }

A bit surprised at this API I would have thought that more functionality/flexibility would have been provided out of the box

pyplot scatter plot marker size

Because other answers here claim that s denotes the area of the marker, I'm adding this answer to clearify that this is not necessarily the case.

Size in points^2

The argument s in plt.scatter denotes the markersize**2. As the documentation says

s : scalar or array_like, shape (n, ), optional
size in points^2. Default is rcParams['lines.markersize'] ** 2.

This can be taken literally. In order to obtain a marker which is x points large, you need to square that number and give it to the s argument.

So the relationship between the markersize of a line plot and the scatter size argument is the square. In order to produce a scatter marker of the same size as a plot marker of size 10 points you would hence call scatter( .., s=100).

enter image description here

import matplotlib.pyplot as plt

fig,ax = plt.subplots()

ax.plot([0],[0], marker="o",  markersize=10)
ax.plot([0.07,0.93],[0,0],    linewidth=10)
ax.scatter([1],[0],           s=100)

ax.plot([0],[1], marker="o",  markersize=22)
ax.plot([0.14,0.86],[1,1],    linewidth=22)
ax.scatter([1],[1],           s=22**2)

plt.show()

Connection to "area"

So why do other answers and even the documentation speak about "area" when it comes to the s parameter?

Of course the units of points**2 are area units.

  • For the special case of a square marker, marker="s", the area of the marker is indeed directly the value of the s parameter.
  • For a circle, the area of the circle is area = pi/4*s.
  • For other markers there may not even be any obvious relation to the area of the marker.

enter image description here

In all cases however the area of the marker is proportional to the s parameter. This is the motivation to call it "area" even though in most cases it isn't really.

Specifying the size of the scatter markers in terms of some quantity which is proportional to the area of the marker makes in thus far sense as it is the area of the marker that is perceived when comparing different patches rather than its side length or diameter. I.e. doubling the underlying quantity should double the area of the marker.

enter image description here

What are points?

So far the answer to what the size of a scatter marker means is given in units of points. Points are often used in typography, where fonts are specified in points. Also linewidths is often specified in points. The standard size of points in matplotlib is 72 points per inch (ppi) - 1 point is hence 1/72 inches.

It might be useful to be able to specify sizes in pixels instead of points. If the figure dpi is 72 as well, one point is one pixel. If the figure dpi is different (matplotlib default is fig.dpi=100),

1 point == fig.dpi/72. pixels

While the scatter marker's size in points would hence look different for different figure dpi, one could produce a 10 by 10 pixels^2 marker, which would always have the same number of pixels covered:

enter image description here enter image description here enter image description here

import matplotlib.pyplot as plt

for dpi in [72,100,144]:

    fig,ax = plt.subplots(figsize=(1.5,2), dpi=dpi)
    ax.set_title("fig.dpi={}".format(dpi))

    ax.set_ylim(-3,3)
    ax.set_xlim(-2,2)

    ax.scatter([0],[1], s=10**2, 
               marker="s", linewidth=0, label="100 points^2")
    ax.scatter([1],[1], s=(10*72./fig.dpi)**2, 
               marker="s", linewidth=0, label="100 pixels^2")

    ax.legend(loc=8,framealpha=1, fontsize=8)

    fig.savefig("fig{}.png".format(dpi), bbox_inches="tight")

plt.show() 

If you are interested in a scatter in data units, check this answer.

Can I make a function available in every controller in angular?

You basically have two options, either define it as a service, or place it on your root scope. I would suggest that you make a service out of it to avoid polluting the root scope. You create a service and make it available in your controller like this:

<!doctype html>
<html ng-app="myApp">
<head>
    <script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
    <script src="http://code.angularjs.org/1.1.2/angular.min.js"></script>
    <script type="text/javascript">
    var myApp = angular.module('myApp', []);

    myApp.factory('myService', function() {
        return {
            foo: function() {
                alert("I'm foo!");
            }
        };
    });

    myApp.controller('MainCtrl', ['$scope', 'myService', function($scope, myService) {
        $scope.callFoo = function() {
            myService.foo();
        }
    }]);
    </script>
</head>
<body ng-controller="MainCtrl">
    <button ng-click="callFoo()">Call foo</button>
</body>
</html>

If that's not an option for you, you can add it to the root scope like this:

<!doctype html>
<html ng-app="myApp">
<head>
    <script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
    <script src="http://code.angularjs.org/1.1.2/angular.min.js"></script>
    <script type="text/javascript">
    var myApp = angular.module('myApp', []);

    myApp.run(function($rootScope) {
        $rootScope.globalFoo = function() {
            alert("I'm global foo!");
        };
    });

    myApp.controller('MainCtrl', ['$scope', function($scope){

    }]);
    </script>
</head>
<body ng-controller="MainCtrl">
    <button ng-click="globalFoo()">Call global foo</button>
</body>
</html>

That way, all of your templates can call globalFoo() without having to pass it to the template from the controller.

What is the Swift equivalent of respondsToSelector?

Functions are first-class types in Swift, so you can check whether an optional function defined in a protocol has been implemented by comparing it to nil:

if (someObject.someMethod != nil) {
    someObject.someMethod!(someArgument)
} else {
    // do something else
}

Why does adb return offline after the device string?

Check that the ADB version that you are running is newer than the version of the OS on the connected devices. For me, updating the ADB helped to get the device online.

laravel foreach loop in controller

Hi, this will throw an error:

foreach ($product->sku as $sku){ 
// Code Here
}

because you cannot loop a model with a specific column ($product->sku) from the table.
So you must loop on the whole model:

foreach ($product as $p) {
// code
}

Inside the loop you can retrieve whatever column you want just adding "->[column_name]"

foreach ($product as $p) {
echo $p->sku;
}

Have a great day

Fatal error: Call to undefined function pg_connect()

  1. Add 'PHPIniDir "C:/php"' into the httpd.conf file.(provided you have your PHP saved in C:, or else give the location where PHP is saved.)
  2. Uncomment following 'extension=php_pgsql.dll' in php.ini file
  3. Uncomment ';extension_dir = "ext"' in php.ini directory

Understanding passport serialize deserialize

For anyone using Koa and koa-passport:

Know that the key for the user set in the serializeUser method (often a unique id for that user) will be stored in:

this.session.passport.user

When you set in done(null, user) in deserializeUser where 'user' is some user object from your database:

this.req.user OR this.passport.user

for some reason this.user Koa context never gets set when you call done(null, user) in your deserializeUser method.

So you can write your own middleware after the call to app.use(passport.session()) to put it in this.user like so:

app.use(function * setUserInContext (next) {
  this.user = this.req.user
  yield next
})

If you're unclear on how serializeUser and deserializeUser work, just hit me up on twitter. @yvanscher

Where is the Global.asax.cs file?

It don't create normally; you need to add it by yourself.

After adding Global.asax by

  • Right clicking your website -> Add New Item -> Global Application Class -> Add

You need to add a class

  • Right clicking App_Code -> Add New Item -> Class -> name it Global.cs -> Add

Inherit the newly generated by System.Web.HttpApplication and copy all the method created Global.asax to Global.cs and also add an inherit attribute to the Global.asax file.

Your Global.asax will look like this: -

<%@ Application Language="C#" Inherits="Global" %>

Your Global.cs in App_Code will look like this: -

public class Global : System.Web.HttpApplication
{
    public Global()
    {
        //
        // TODO: Add constructor logic here
        //
    }

    void Application_Start(object sender, EventArgs e)
    {
        // Code that runs on application startup

    }
    /// Many other events like begin request...e.t.c, e.t.c
}

How do I fix 'Invalid character value for cast specification' on a date column in flat file?

In order to simulate the issue that you are facing, I created the following sample using SSIS 2008 R2 with SQL Server 2008 R2 backend. The example is based on what I gathered from your question. This example doesn't provide a solution but it might help you to identify where the problem could be in your case.

Created a simple CSV file with two columns namely order number and order date. As you had mentioned in your question, values of both the columns are qualified with double quotes (") and also the lines end with Line Feed (\n) with the date being the last column. The below screenshot was taken using Notepad++, which can display the special characters in a file. LF in the screenshot denotes Line Feed.

Orders file

Created a simple table named dbo.Destination in the SQL Server database to populate the CSV file data using SSIS package. Create script for the table is given below.

CREATE TABLE [dbo].[Destination](
    [OrderNumber] [varchar](50) NULL,
    [OrderDate] [date] NULL
) ON [PRIMARY]
GO

On the SSIS package, I created two connection managers. SQLServer was created using the OLE DB Connection to connect to the SQL Server database. FlatFile is a flat file connection manager.

Connections

Flat file connection manager was configured to read the CSV file and the settings are shown below. The red arrows indicate the changes made.

Provided a name to the flat file connection manager. Browsed to the location of the CSV file and selected the file path. Entered the double quote (") as the text qualifier. Changed the Header row delimiter from {CR}{LF} to {LF}. This header row delimiter change also reflects on the Columns section.

Flat File General

No changes were made in the Columns section.

Flat File Columns

Changed the column name from Column0 to OrderNumber.

Advanced column OrderNumber

Changed the column name from Column1 to OrderDate and also changed the data type to date [DT_DATE]

Advanced column OrderDate

Preview of the data within the flat file connection manager looks good.

Data Preview

On the Control Flow tab of the SSIS package, placed a Data Flow Task.

Control Flow

Within the Data Flow Task, placed a Flat File Source and an OLE DB Destination.

Data Flow Task

The Flat File Source was configured to read the CSV file data using the FlatFile connection manager. Below three screenshots show how the flat file source component was configured.

Flat File Source Connection Manager

Flat File Source Columns

Flat File Source Error Output

The OLE DB Destination component was configured to accept the data from Flat File Source and insert it into SQL Server database table named dbo.Destination. Below three screenshots show how the OLE DB Destination component was configured.

OLE DB Destination Connection Manager

OLE DB Destination Mappings

OLE DB Destination Error Output

Using the steps mentioned in the below 5 screenshots, I added a data viewer on the flow between the Flat File Source and OLE DB Destination.

Right click

Data Flow Path Editor New

Configure Data Viewer

Data Flow Path Editor Added

Data Viewer visible

Before running the package, I verified the initial data present in the table. It is currently empty because I created this using the script provided at the beginning of this post.

Empty Table

Executed the package and the package execution temporarily paused to display the data flowing from Flat File Source to OLE DB Destination in the data viewer. I clicked on the run button to proceed with the execution.

Data Viewer Pause

The package executed successfully.

Successful execution

Flat file source data was inserted successfully into the table dbo.Destination.

Data in table

Here is the layout of the table dbo.Destination. As you can see, the field OrderDate is of data type date and the package still continued to insert the data correctly.

Destination layout

This post even though is not a solution. Hopefully helps you to find out where the problem could be in your scenario.

When do you use map vs flatMap in RxJava?

The way I think about it is that you use flatMap when the function you wanted to put inside of map() returns an Observable. In which case you might still try to use map() but it would be unpractical. Let me try to explain why.

If in such case you decided to stick with map, you would get an Observable<Observable<Something>>. For example in your case, if we used an imaginary RxGson library, that returned an Observable<String> from it's toJson() method (instead of simply returning a String) it would look like this:

Observable.from(jsonFile).map(new Func1<File, Observable<String>>() {
    @Override public Observable<String>> call(File file) {
        return new RxGson().toJson(new FileReader(file), Object.class);
    }
}); // you get Observable<Observable<String>> here

At this point it would be pretty tricky to subscribe() to such an observable. Inside of it you would get an Observable<String> to which you would again need to subscribe() to get the value. Which is not practical or nice to look at.

So to make it useful one idea is to "flatten" this observable of observables (you might start to see where the name _flat_Map comes from). RxJava provides a few ways to flatten observables and for sake of simplicity lets assume merge is what we want. Merge basically takes a bunch of observables and emits whenever any of them emits. (Lots of people would argue switch would be a better default. But if you're emitting just one value, it doesn't matter anyway.)

So amending our previous snippet we would get:

Observable.from(jsonFile).map(new Func1<File, Observable<String>>() {
    @Override public Observable<String>> call(File file) {
        return new RxGson().toJson(new FileReader(file), Object.class);
    }
}).merge(); // you get Observable<String> here

This is a lot more useful, because subscribing to that (or mapping, or filtering, or...) you just get the String value. (Also, mind you, such variant of merge() does not exist in RxJava, but if you understand the idea of merge then I hope you also understand how that would work.)

So basically because such merge() should probably only ever be useful when it succeeds a map() returning an observable and so you don't have to type this over and over again, flatMap() was created as a shorthand. It applies the mapping function just as a normal map() would, but later instead of emitting the returned values it also "flattens" (or merges) them.

That's the general use case. It is most useful in a codebase that uses Rx allover the place and you've got many methods returning observables, which you want to chain with other methods returning observables.

In your use case it happens to be useful as well, because map() can only transform one value emitted in onNext() into another value emitted in onNext(). But it cannot transform it into multiple values, no value at all or an error. And as akarnokd wrote in his answer (and mind you he's much smarter than me, probably in general, but at least when it comes to RxJava) you shouldn't throw exceptions from your map(). So instead you can use flatMap() and

return Observable.just(value);

when all goes well, but

return Observable.error(exception);

when something fails.
See his answer for a complete snippet: https://stackoverflow.com/a/30330772/1402641

Display Images Inline via CSS

You have a line break <br> in-between the second and third images in your markup. Get rid of that, and it'll show inline.

Apache won't run in xampp

In my case the problem was that the logs folder did not exist resp. the error.log file in this folder.

Get the IP Address of local computer

Can't you just send to INADDR_BROADCAST? Admittedly, that'll send on all interfaces - but that's rarely a problem.

Otherwise, ioctl and SIOCGIFBRDADDR should get you the address on *nix, and WSAioctl and SIO_GET_BROADCAST_ADDRESS on win32.

Read Session Id using Javascript

The following can be used to retrieve JSESSIONID:

function getJSessionId(){
    var jsId = document.cookie.match(/JSESSIONID=[^;]+/);
    if(jsId != null) {
        if (jsId instanceof Array)
            jsId = jsId[0].substring(11);
        else
            jsId = jsId.substring(11);
    }
    return jsId;
}

How to push a new folder (containing other folders and files) to an existing git repo?

You need to git add my_project to stage your new folder. Then git add my_project/* to stage its contents. Then commit what you've staged using git commit and finally push your changes back to the source using git push origin master (I'm assuming you wish to push to the master branch).

How to get last inserted id?

You can create a SqlCommand with CommandText equal to

INSERT INTO aspnet_GameProfiles(UserId, GameId) OUTPUT INSERTED.ID VALUES(@UserId, @GameId)

and execute int id = (int)command.ExecuteScalar.

This MSDN article will give you some additional techniques.

How to import JSON File into a TypeScript file?

I had read some of the responses and they didn't seem to work for me. I am using Typescript 2.9.2, Angular 6 and trying to import JSON in a Jasmine Unit Test. This is what did the trick for me.

Add:

"resolveJsonModule": true,

To tsconfig.json

Import like:

import * as nameOfJson from 'path/to/file.json';

Stop ng test, start again.

Reference: https://blogs.msdn.microsoft.com/typescript/2018/05/31/announcing-typescript-2-9/#json-imports

npm install errors with Error: ENOENT, chmod

Be careful with invalid values for keys "directories" and "files" in package.json

If you start with a new application, and you want to start completely blank, you have to either start in a complete empty folder or have a valid package.json file in it.

If you do not want to create a package.json file first, just type: npm i some_package

Package with name "some_package" should be installed correctly in a new sub folder "node_modules".

If you create a package.json file first, type: npm init Keep all the defaults (by just clicking ENTER), you should end up with a valid file.

It should look like this:

{
  "name": "yourfoldername",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC"
}

Note that the following keys are missing: "directories", "repository" and "files". It looks like if you use incorrect values for "directories" and/or "files", you are not able to install the package. Leaving these keys out, solved the issue for me.

Also note key "main". This one is present, but it does contain an invalid value. No file "index.js" exists (yet). You can safely remove it.

Now type: npm i some_package and package with name "some_package" should be installed correctly in a new sub folder "node_modules".

Sorting list based on values from another list

Another alternative, combining several of the answers.

zip(*sorted(zip(Y,X)))[1]

In order to work for python3:

list(zip(*sorted(zip(B,A))))[1]

What is the right way to treat argparse.Namespace() as a dictionary?

Is it proper to "reach into" an object and use its dict property?

In general, I would say "no". However Namespace has struck me as over-engineered, possibly from when classes couldn't inherit from built-in types.

On the other hand, Namespace does present a task-oriented approach to argparse, and I can't think of a situation that would call for grabbing the __dict__, but the limits of my imagination are not the same as yours.

Google Maps setCenter()

I searched and searched and finally found that ie needs to know the map size. Set the map size to match the div size.

map = new GMap2(document.getElementById("map_canvas2"), { size: new GSize(850, 600) });

<div id="map_canvas2" style="width: 850px; height: 600px">
</div>

PHP DOMDocument loadHTML not encoding UTF-8 correctly

Make sure the real source file is saved as UTF-8 (You may even want to try the non-recommended BOM Chars with UTF-8 to make sure).

Also in case of HTML, make sure you have declared the correct encoding using meta tags:

<meta http-equiv="Content-Type" content="text/html; charset=utf-8">

If it's a CMS (as you've tagged your question with Joomla) you may need to configure appropriate settings for the encoding.

How can I do a line break (line continuation) in Python?

Taken from The Hitchhiker's Guide to Python (Line Continuation):

When a logical line of code is longer than the accepted limit, you need to split it over multiple physical lines. The Python interpreter will join consecutive lines if the last character of the line is a backslash. This is helpful in some cases, but should usually be avoided because of its fragility: a white space added to the end of the line, after the backslash, will break the code and may have unexpected results.

A better solution is to use parentheses around your elements. Left with an unclosed parenthesis on an end-of-line the Python interpreter will join the next line until the parentheses are closed. The same behaviour holds for curly and square braces.

However, more often than not, having to split a long logical line is a sign that you are trying to do too many things at the same time, which may hinder readability.

Having that said, here's an example considering multiple imports (when exceeding line limits, defined on PEP-8), also applied to strings in general:

from app import (
    app, abort, make_response, redirect, render_template, request, session
)

SQL SELECT everything after a certain character

select SUBSTRING_INDEX(supplier_reference,'=',-1) from ps_product;

Please use http://www.w3resource.com/mysql/string-functions/mysql-substring_index-function.php for further reference.

How to put two divs side by side

Have a look at CSS and HTML in depth you will figure this out. It just floating the boxes left and right and those boxes need to be inside a same div. http://www.w3schools.com/html/html_layout.asp might be a good resource.

String format currency

decimal value = 0.00M;
value = Convert.ToDecimal(12345.12345);
Console.WriteLine(".ToString(\"C\") Formates With Currency $ Sign");
Console.WriteLine(value.ToString("C"));
//OutPut : $12345.12
Console.WriteLine(value.ToString("C1"));
//OutPut : $12345.1
Console.WriteLine(value.ToString("C2"));
//OutPut : $12345.12
Console.WriteLine(value.ToString("C3"));
//OutPut : $12345.123
Console.WriteLine(value.ToString("C4"));
//OutPut : $12345.1234
Console.WriteLine(value.ToString("C5"));
//OutPut : $12345.12345
Console.WriteLine(value.ToString("C6"));
//OutPut : $12345.123450
Console.WriteLine();
Console.WriteLine(".ToString(\"F\") Formates With out Currency Sign");
Console.WriteLine(value.ToString("F"));
//OutPut : 12345.12
Console.WriteLine(value.ToString("F1"));
//OutPut : 12345.1
Console.WriteLine(value.ToString("F2"));
//OutPut : 12345.12
Console.WriteLine(value.ToString("F3"));
//OutPut : 12345.123
Console.WriteLine(value.ToString("F4"));
//OutPut : 12345.1234
Console.WriteLine(value.ToString("F5"));
//OutPut : 12345.12345
Console.WriteLine(value.ToString("F6"));
//OutPut : 12345.123450
Console.Read();

Output console screen:

Microsoft.ACE.OLEDB.12.0 provider is not registered

Basically, if you're on a 64-bit machine, IIS 7 is not (by default) serving 32-bit apps, which the database engine operates on. So here is exactly what you do:

1) ensure that the 2007 database engine is installed, this can be downloaded at: http://www.microsoft.com/downloads/details.aspx?FamilyID=7554F536-8C28-4598-9B72-EF94E038C891&displaylang=en

2) open IIS7 manager, and open the Application Pools area. On the right sidebar, you will see an option that says "Set application pool defaults". Click it, and a window will pop up with the options.

3) the second field down, which says 'Enable 32-bit applications' is probably set to FALSE by default. Simply click where it says 'false' to change it to 'true'.

4) Restart your app pool (you can do this by hitting RECYCLE instead of STOP then START, which will also work).

5) done, and your error message will go away.

CSS-moving text from left to right

Somehow I got it to work by using margin-right, and setting it to move from right to left. http://jsfiddle.net/gXdMc/

Don't know why for this case, margin-right 100% doesn't go off the screen. :D (tested on chrome 18)

EDIT: now left to right works too http://jsfiddle.net/6LhvL/

Class is inaccessible due to its protection level

Hi You need to change the Button properties from private to public. You can change Under Button >> properties >> Design >> Modifiers >> "public" Once change the protection error will gone.

Budi

What are the different types of indexes, what are the benefits of each?

Conventional wisdom suggests that index choice should be based on cardinality. They'll say,

For a low cardinality column like GENDER, use bitmap. For a high cardinality like LAST_NAME, use b-tree.

This is not the case with Oracle, where index choice should instead be based on the type of application (OLTP vs. OLAP). DML on tables with bitmap indexes can cause serious lock contention. On the other hand, the Oracle CBO can easily combine multiple bitmap indexes together, and bitmap indexes can be used to search for nulls. As a general rule:

For an OLTP system with frequent DML and routine queries, use btree. For an OLAP system with infrequent DML and adhoc queries, use bitmap.

I'm not sure if this applies to other databases, comments are welcome. The following articles discuss the subject further:

Datagridview full row selection but get single cell value

You can do like this:

private void datagridview1_SelectionChanged(object sender, EventArgs e)
{
  if (datagridview1.SelectedCells.Count > 0)
  {
    int selectedrowindex = datagridview1.SelectedCells[0].RowIndex;
    DataGridViewRow selectedRow = datagridview1.Rows[selectedrowindex];  
    string cellValue = Convert.ToString(selectedRow.Cells["enter column name"].Value);           
  }
}

SQL Server GROUP BY datetime ignore hour minute and a select with a date and sum value

SELECT CAST(Datetimefield AS DATE) as DateField, SUM(intfield) as SumField
FROM MyTable
GROUP BY CAST(Datetimefield AS DATE)

bower proxy configuration

Are you using Windows? Just set the environment variable http_proxy...

set http_proxy=http://your-proxy-address.com:port

... and bower will pick this up. Rather than dealing with a unique config file in your project folder - right? (side-note: when-the-F! will windows allow us to create a .file using explorer? c'mon windows!)

Web link to specific whatsapp contact

********* UPDATE ADDED AT THE END *********

I've tried many approaches and I have a winner (see Test 3), here is the result of each one:

(I think the Test 3 will also work for you because if the person visiting your site doesn't have you on their contact list, it's the only option that will allow it.)

In all tests, the number had to be complete, with country and location code without any initial zeros. Example:

  • +55(011) 99999-9999 (NOT)
  • +5511999999999 (YES)

On tests 1 and 2, it only worked with a plus sign on the country code: +5511999999999

Test 1:

<a href="whatsapp://send?abid=phonenumber&text=Hello%2C%20World!">Send Message</a>

This way you must have the phonenumber on your contact list. It doesn't work for me because I wanted to be able to send a message to a number which I may not have on my contact list.

If you don't have the number on your contact list, it opens the Whatsapp listing all your registered contacts, so you can choose one.

It's a good option for sharing stuff.

Test 2:

<a href="intent://send/phonenumber#Intent;scheme=smsto;package=com.whatsapp;action=android.intent.action.SENDTO;end">Send Message</a>

This approach only works on Android AND if you have the number on your contact list. If you don't have it, Android opens your SMS app, so you can invite the contact to use Whatsapp.

Test 3 (The Winner):

<a href="https://api.whatsapp.com/send?phone=15551234567">Send Message</a>

This was the only way that worked fully for me.

  • It works on Android, iOS and Web app on the desktop,
  • You can start a conversation with a number that you don't have on your contact list
  • You can create a link with one pre-built message adding &text=[message-url-encoded] like:

https://api.whatsapp.com/send?phone=15551234567&text=Send20%a20%quote

And if you wish to have a bookmarklet for additional ease of use, you may use this one:

javascript: (function() { var val= prompt("Enter phone number",""); if (val) location="https://api.whatsapp.com/send?phone="+escape('972' + val)+""; })()

Youll need to change the country code(or remove it) to you.r target country and paste it in the address field in a chrome/firefox link

Worth notice:

***************** UPDATE (START) *****************

Whatsapp made available other option, now you can create one link to a conversation like this:

https://wa.me/[phonenumber]

The phone number should be in international format:

Like this:

https://wa.me/552196312XXXX

NOT like this:

https://wa.me/+55(021)96312-XXXX

And if you want to add one pre-built message to your link, you can add ?text= at the end with the text URL Encoded:

https://wa.me/552196312XXXX?text=[message-url-encoded]

Exemple:

https://wa.me/552196312XXXX?text=Send20%a20%quote

More info here:

https://faq.whatsapp.com/general/chats/how-to-use-click-to-chat

***************** UPDATE (END) *****************

jQuery: find element by text

Fellas, I know this is old but hey I've this solution which I think works better than all. First and foremost overcomes the Case Sensitivity that the jquery :contains() is shipped with:

var text = "text";

var search = $( "ul li label" ).filter( function ()
{
    return $( this ).text().toLowerCase().indexOf( text.toLowerCase() ) >= 0;
}).first(); // Returns the first element that matches the text. You can return the last one with .last()

Hope someone in the near future finds it helpful.

Is it possible to use raw SQL within a Spring Repository

we can use createNativeQuery("Here Nagitive SQL Query ");

for Example :

Query q = em.createNativeQuery("SELECT a.firstname, a.lastname FROM Author a");
List<Object[]> authors = q.getResultList();

Error in Eclipse: "The project cannot be built until build path errors are resolved"

I also had this problem in my system, but after looking inside the project I saw the XML structure of the .classpath file in the project path was incorrect. After amending that file the problem was solved.

What is "String args[]"? parameter in main method Java

in public static void main(String args[]) args is an array of console line argument whose data type is String. in this array, you can store various string arguments by invoking them at the command line as shown below: java myProgram Shaan Royal then Shaan and Royal will be stored in the array as arg[0]="Shaan"; arg[1]="Royal"; you can do this manually also inside the program, when you don't call them at the command line.

No module named Image

Problem:

~$ simple-image-reducer

Traceback (most recent call last):

  File "/usr/bin/simple-image-reducer", line 28, in <module>
    import Image

**ImportError: No module named Image**

Reason:

Image != image

Solution:

1) make sure it is available

python -m pip install  Image

2) where is it available?

sudo find ~ -name image -type d

-->> directory /home/MyHomeDir/.local/lib/python2.7/site-packages/image ->> OK

3) make simple-image-reducer understand via link:

ln -s ~/.local/lib/python2.7/site-packages/image
~/.local/lib/python2.7/site-packages/Image

4) invoke simple-image-reducer again. Works:-)

Ternary operation in CoffeeScript

Multiline version (e.g. if you need to add comment after each line):

a = if b # a depends on b
then 5   # b is true 
else 10  # b is false

How to change Visual Studio 2012,2013 or 2015 License Key?

To see what's inside these HKCR\Licenses use API Monitor v2

API-Filter find 

    RegQueryValueExW 
        ^-Enable all from Advapi32.dll

    CryptUnprotectData
        ^- Enable all from Crypt32.dll
         + Breakpoint / after Call

sample data that'll come out from CryptUnprotectData:

HKEY_CLASSES_ROOT\Licenses\4D8CFBCB-2F6A-4AD2-BABF-10E28F6F2C8F\07078  [length 0x1C6 (0454.) ]
    00322-20000-00000-AA450                 <- PID2
    7d3cbcbb-90b1-411f-9981-6e28039a9b82    <- Ver
    7C3WXN74-VRMXH-J8X3H-M8F7W-CPQB8        <- PID3

HKEY_CLASSES_ROOT\Licenses\4D8CFBCB-2F6A-4AD2-BABF-10E28F6F2C8F\0bcad  [length 0xbcad (0534.) ]

    0000  00000025 ffffffff 7fffffff   07064. 00000007   07078. 00000007 ffffffff
    0020  7fffffff ffffffff 7fffffff ffffffff 7fffffff ffffffff 7fffffff ffffffff
    0040  7fffffff ffffffff 7fffffff ffffffff 7fffffff ffffffff 7fffffff ffffffff
    0060  7fffffff ffffffff 7fffffff ffffffff 7fffffff ffffffff 7fffffff ffffffff
    0080  7fffffff ffffffff 7fffffff ffffffff 7fffffff ffffffff 7fffffff ffffffff
    00a0  7fffffff ffffffff 7fffffff ffffffff 7fffffff ffffffff 7fffffff ffffffff
    00c0  7fffffff ffffffff 7fffffff ffffffff 7fffffff ffffffff 7fffffff ffffffff
    00e0  7fffffff ffffffff 7fffffff ffffffff 7fffffff ffffffff 7fffffff ffffffff
    0100  7fffffff ffffffff 7fffffff ffffffff 7fffffff ffffffff 7fffffff ffffffff
    0120  7fffffff ffffffff 7fffffff 10.2015. c2a6 11.
    0134                             ^installation date^

Useful here is maybe the Installation timestamp (11.10.2015 here ) Change this would required to call 'CryptProtectData'. Doing so needs some efforts like written a small program OR stop with ollydebug at this place and manually 'crafting' a CryptProtectData call ...

Note: In this example I'm using Microsoft® Visual Studio 2015

-> For a quick'n'dirty sneak into an expired VS I recommend to read this post. However that's just good for occasional use, till you get all the sign up and login crap properly done again ;)

Okay the real meat is here:
%LOCALAPPDATA%\Microsoft\VisualStudio\14.0\Licenses\ ^- This path comes from HKCU\Software\Microsoft\VisualStudio\14.0\Licenses\715f10eb-9e99-11d2-bfc2-00c04f990235\1

1_3jdh3uyw**.crtok**

-after some Base64 decoding:

<ClientRightsContainer 
    xmlns="http://schemas.datacontract.org/2004/07/Microsoft.VisualStudio.Services.Licensing" 
    xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
    <CertificateBytes>
        00000000   30 82 06 41 30 82 04 29  A0 03 02 01 02 02 13 5A   0‚ A0‚ )       Z
        00000010   00 00 BC CB 23 AC 52 9C  E8 93 F9 0A 00 01 00 00     ¼Ë#¬Rœè“ù     
        00000020   BC CB 30 0D 06 09 2A 86  48 86 F7 0D 01 01 0B 05   ¼Ë0   *†H†÷     
        00000030   00 30 81 8B 31 0B 30 09  06 03 55 04 06 13 02 55    0 ‹1 0   U    U
        00000040   53 31 13 30 11 06 03 55  04 08 13 0A 57 61 73 68   S1 0   U    Wash
        00000050   69 6E 67 74 6F 6E 31 10  30 0E 06 03 55 04 07 13   ington1 0   U   
        00000060   07 52 65 64 6D 6F 6E 64  31 1E 30 1C 06 03 55 04    Redmond1 0   U 
        00000070   0A 13 15 4D 69 63 72 6F  73 6F 66 74 20 43 6F 72      Microsoft Cor
        00000080   70 6F 72 61 74 69 6F 6E  31 15 30 13 06 03 55 04   poration1 0   U 
        00000090   0B 13 0C 4D 69 63 72 6F  73 6F 66 74 20 49 54 31      Microsoft IT1
        000000A0   1E 30 1C 06 03 55 04 03  13 15 4D 69 63 72 6F 73    0   U    Micros
        000000B0   6F 66 74 20 49 54 20 53  53 4C 20 53 48 41 32 30   oft IT SSL SHA20
        000000C0   1E 17 0D 31 35 30 33 30  35 32 31 32 39 35 36 5A      150305212956Z
        000000D0   17 0D 31 37 30 33 30 34  32 31 32 39 35 36 5A 30     170304212956Z0
        000000E0   25 31 23 30 21 06 03 55  04 03 13 1A 61 70 70 2E   %1#0!  U    app.
        000000F0   76 73 73 70 73 2E 76 69  73 75 61 6C 73 74 75 64   vssps.visualstud
        00000100   69 6F 2E 63 6F 6D 30 82  01 22 30 0D 06 09 2A 86   io.com0‚ "0   *†
        ...
        000002B0   6E 86 36 68 74 74 70 3A  2F 2F 6D 73 63 72 6C 2E   n†6http://mscrl.
        000002C0   6D 69 63 72 6F 73 6F 66  74 2E 63 6F 6D 2F 70 6B   microsoft.com/pk
        000002D0   69 2F 6D 73 63 6F 72 70  2F 63 72 6C 2F 6D 73 69   i/mscorp/crl/msi
        000002E0   74 77 77 77 32 2E 63 72  6C 86 34 68 74 74 70 3A   twww2.crl†4http:
        000002F0   2F 2F 63 72 6C 2E 6D 69  63 72 6F 73 6F 66 74 2E   //crl.microsoft.
        00000300   63 6F 6D 2F 70 6B 69 2F  6D 73 63 6F 72 70 2F 63   com/pki/mscorp/c
        00000310   72 6C 2F 6D 73 69 74 77  77 77 32 2E 63 72 6C 30   rl/msitwww2.crl0
        00000320   70 06 08 2B 06 01 05 05  07 01 01 04 64 30 62 30   p  +        d0b0
        00000330   3C 06 08 2B 06 01 05 05  07 30 02 86 30 68 74 74   <  +     0 †0htt
        00000340   70 3A 2F 2F 77 77 77 2E  6D 69 63 72 6F 73 6F 66   p://www.microsof
        00000350   74 2E 63 6F 6D 2F 70 6B  69 2F 6D 73 63 6F 72 70   t.com/pki/mscorp
        00000360   2F 6D 73 69 74 77 77 77  32 2E 63 72 74 30 22 06   /msitwww2.crt0" 
        00000370   08 2B 06 01 05 05 07 30  01 86 16 68 74 74 70 3A    +     0 † http:
        00000380   2F 2F 6F 63 73 70 2E 6D  73 6F 63 73 70 2E 63 6F   //ocsp.msocsp.co
        00000390   6D 30 4E 06 03 55 1D 20  04 47 30 45 30 43 06 09   m0N  U   G0E0C  
        000003A0   2B 06 01 04 01 82 37 2A  01 30 36 30 34 06 08 2B   +    ‚7* 0604  +
        000003B0   06 01 05 05 07 02 01 16  28 68 74 74 70 3A 2F 2F           (http://
        000003C0   77 77 77 2E 6D 69 63 72  6F 73 6F 66 74 2E 63 6F   www.microsoft.co
        000003D0   6D 2F 70 6B 69 2F 6D 73  63 6F 72 70 2F 63 70 73   m/pki/mscorp/cps
        000003E0   00 30 27 06 09 2B 06 01  04 01 82 37 15 0A 04 1A    0'  +    ‚7    
        000003F0   30 18 30 0A 06 08 2B 06  01 05 05 07 03 01 30 0A   0 0   +       0 
        00000400   06 08 2B 06 01 05 05 07  03 02 30 25 06 03 55 1D     +       0%  U 
        00000410   11 04 1E 30 1C 82 1A 61  70 70 2E 76 73 73 70 73      0 ‚ app.vssps
        00000420   2E 76 69 73 75 61 6C 73  74 75 64 69 6F 2E 63 6F   .visualstudio.co
        00000430   6D 30 0D 06 09 2A 86 48  86 F7 0D 01 01 0B 05 00   m0   *†H†÷      
        ...                                                U
    </CertificateBytes>
    <Token>
    {
        "typ":"JWT",
        "alg":"RS256",
        "x5t":"i7qX-NUrehXBYdQC5PSH-TdvzXA"
    }
    </Token>
</ClientRightsContainer>

Seems M$ is using JSON Web Token (JWT) to wrap in license data. I guess inside CertificateBytes will be somehow the payload - you're email and other details.

So far for the rough overview what's the data inside.

For more wishes get ILSpy + Reflexil (<- to changes/correct little things!) and then 'browser&correct' files like c:\Program Files (x86)\Microsoft Visual Studio 14.0\Common7\IDE**Microsoft.VisualStudio.Licensing.dll** or check out 'Microsoft.VisualStudio.Services.WebApi.dll'

How to use 'git pull' from the command line?

One more option is to add the path of the privatekey file like this in terminal:

ssh-add "path to the privatekeyfile"

and then execute the pull command

Create an instance of a class from a string

Probably my question should have been more specific. I actually know a base class for the string so solved it by:

ReportClass report = (ReportClass)Activator.CreateInstance(Type.GetType(reportClass));

The Activator.CreateInstance class has various methods to achieve the same thing in different ways. I could have cast it to an object but the above is of the most use to my situation.

Unix: How to delete files listed in a file

xargs -I{} sh -c 'rm {}' < 1.txt should do what you want. Be careful with this command as one incorrect entry in that file could cause a lot of trouble.

This answer was edited after @tdavies pointed out that the original did not do shell expansion.

Custom seekbar (thumb size, color and background)

All done in XML (no .png images). The clever bit is border_shadow.xml.

All about the vectors these days...

Screenshot:

seekbar
This is your SeekBar (res/layout/???.xml):

SeekBar

<SeekBar
    android:id="@+id/seekBar_luminosite"
    android:layout_width="300dp"
    android:layout_height="wrap_content"        
    android:progress="@integer/luminosite_defaut"
    android:progressDrawable="@drawable/seekbar_style"
    android:thumb="@drawable/custom_thumb"/>

Let's make it stylish (so you can easily customize it later):

style

res/drawable/seekbar_style.xml:

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android" >
    <item 
        android:id="@android:id/background" 
        android:drawable="@drawable/border_shadow" >
    </item>

    <item 
        android:id="@android:id/progress" > 
        <clip 
            android:drawable="@drawable/seekbar_progress" />
    </item>
</layer-list>

thumb

res/drawable/custom_thumb.xml:

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item>
        <shape android:shape="oval">
            <solid android:color="@color/colorDekraOrange"/>
            <size
                android:width="35dp"
                android:height="35dp"/>
        </shape>
    </item>   
</layer-list>

progress

res/drawable/seekbar_progress.xml:

<?xml version="1.0" encoding="utf-8"?>
<layer-list 
    xmlns:android="http://schemas.android.com/apk/res/android" >
    <item 
        android:id="@+id/progressshape" >
        <clip>
            <shape 
                android:shape="rectangle" >
                <size android:height="5dp"/>
                <corners 
                    android:radius="5dp" />
                <solid android:color="@color/colorDekraYellow"/>        
            </shape>
        </clip>
    </item>
</layer-list>

shadow

res/drawable/border_shadow.xml:

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">       
    <item>      
        <shape> 
            <corners 
                android:radius="5dp" />
            <gradient
                android:angle="270"
                android:startColor="#33000000"
                android:centerColor="#11000000"
                android:endColor="#11000000"
                android:centerY="0.2"
                android:type="linear"
            />          
        </shape> 
    </item>
</layer-list>

How do you define a class of constants in Java?

Or 4. Put them in the class that contains the logic that uses the constants the most

... sorry, couldn't resist ;-)

How to get client IP address using jQuery

function GetUserIP(){
  var ret_ip;
  $.ajaxSetup({async: false});
  $.get('http://jsonip.com/', function(r){ 
    ret_ip = r.ip; 
  });
  return ret_ip;
}

If you want to use the IP and assign it to a variable, Try this. Just call GetUserIP()

How to get text of an element in Selenium WebDriver, without including child element text?

Here's a general solution:

def get_text_excluding_children(driver, element):
    return driver.execute_script("""
    return jQuery(arguments[0]).contents().filter(function() {
        return this.nodeType == Node.TEXT_NODE;
    }).text();
    """, element)

The element passed to the function can be something obtained from the find_element...() methods (i.e. it can be a WebElement object).

Or if you don't have jQuery or don't want to use it you can replace the body of the function above above with this:

return self.driver.execute_script("""
var parent = arguments[0];
var child = parent.firstChild;
var ret = "";
while(child) {
    if (child.nodeType === Node.TEXT_NODE)
        ret += child.textContent;
    child = child.nextSibling;
}
return ret;
""", element) 

I'm actually using this code in a test suite.

Does Enter key trigger a click event?

Use (keyup.enter).

Angular can filter the key events for us. Angular has a special syntax for keyboard events. We can listen for just the Enter key by binding to Angular's keyup.enter pseudo-event.

python: SyntaxError: EOL while scanning string literal

I faced a similar problem. I had a string which contained path to a folder in Windows e.g. C:\Users\ The problem is that \ is an escape character and so in order to use it in strings you need to add one more \.

Incorrect: C:\Users\

Correct: C:\\\Users\\\

How to set aliases in the Git Bash for Windows?

You can add it manually in the .gitconfig file

[alias]
    cm = "commit -m"

Or using the script:

git config --global alias.cm "commit -m"

Here is a screenshot of the .gitconfig

enter image description here

How to log request and response body with Retrofit-Android?

This is not the best way to do it the better answers are above. This is just another way to check it by using Android Logs. Put them all in this helps to catch parsing errors.

 call.enqueue(new Callback<JsonObject>() {
                    @Override
                    public void onResponse(Call<JsonObject> call,
                                           Response<JsonObject> response) {

    // Catching Responses From Retrofit
    Log.d("TAG", "onResponseisSuccessful: "+response.isSuccessful());
    Log.d("TAG", "onResponsebody: "+response.body());
    Log.d("TAG", "onResponseerrorBody: "+response.errorBody());
    Log.d("TAG", "onResponsemessage: "+response.message());
    Log.d("TAG", "onResponsecode: "+response.code());
    Log.d("TAG", "onResponseheaders: "+response.headers());
    Log.d("TAG", "onResponseraw: "+response.raw());
    Log.d("TAG", "onResponsetoString: "+response.toString());

                    }

                    @Override
                    public void onFailure(Call<JsonObject> call,
                                          Throwable t) {

Log.d("TAG", "onFailuregetLocalizedMessage: " +t.getLocalizedMessage());
Log.d("TAG", "onFailuregetMessage: " +t.getMessage());
Log.d("TAG", "onFailuretoString: " +t.toString());
Log.d("TAG", "onFailurefillInStackTrace: " +t.fillInStackTrace());
Log.d("TAG", "onFailuregetCause: " +t.getCause());
Log.d("TAG", "onFailuregetStackTrace: " + Arrays.toString(t.getStackTrace()));
Log.d("TAG", "getSuppressed: " + Arrays.toString(t.getSuppressed()));

                    }
                });

Default instance name of SQL Server Express

You're right, it's localhost\SQLEXPRESS (just no $) and yes, it's the same for both 2005 and 2008 express versions.

Apply formula to the entire column

You can use Ctrl+Shift+Down+D to add the formula to every cell in the column as well.

Simply click/highlight the cell with the equation/formula you want to copy and then hold down Ctrl+Shift+Down+D and your formula will be added to each cell.

How do I change tab size in Vim?

As a one-liner into vim:

:set tabstop=4 shiftwidth=4

For permanent setup, add these lines to ~/.vimrc:

set tabstop=4
set shiftwidth=4

NOTE: Add set expandtab if you prefer 4-spaces indentation, instead of a tab indentation.

How to remove a key from HashMap while iterating over it?

Try:

Iterator<Map.Entry<String,String>> iter = testMap.entrySet().iterator();
while (iter.hasNext()) {
    Map.Entry<String,String> entry = iter.next();
    if("Sample".equalsIgnoreCase(entry.getValue())){
        iter.remove();
    }
}

With Java 1.8 and onwards you can do the above in just one line:

testMap.entrySet().removeIf(entry -> "Sample".equalsIgnoreCase(entry.getValue()));

How to set Internet options for Android emulator?

I've seen various suggestions how code can find out whether it runs on the emulator, but none are quite satisfactory, or "future-proof". For the time being I've settled on reading the device ID, which is all zeros for the emulator:

TelephonyManager telmgr = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE); boolean isEmulator = "000000000000000".equals(telmgr.getDeviceId());

But on a deployed app that requires the READ_PHONE_STATE permission

How to split a string in Java

import java.io.*;

public class BreakString {

  public static void main(String args[]) {

    String string = "004-034556-1234-2341";
    String[] parts = string.split("-");

    for(int i=0;i<parts.length;i++) {
      System.out.println(parts[i]);
    }
  }
}

What does from __future__ import absolute_import actually do?

The difference between absolute and relative imports come into play only when you import a module from a package and that module imports an other submodule from that package. See the difference:

$ mkdir pkg
$ touch pkg/__init__.py
$ touch pkg/string.py
$ echo 'import string;print(string.ascii_uppercase)' > pkg/main1.py
$ python2
Python 2.7.9 (default, Dec 13 2014, 18:02:08) [GCC] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import pkg.main1
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "pkg/main1.py", line 1, in <module>
    import string;print(string.ascii_uppercase)
AttributeError: 'module' object has no attribute 'ascii_uppercase'
>>> 
$ echo 'from __future__ import absolute_import;import string;print(string.ascii_uppercase)' > pkg/main2.py
$ python2
Python 2.7.9 (default, Dec 13 2014, 18:02:08) [GCC] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import pkg.main2
ABCDEFGHIJKLMNOPQRSTUVWXYZ
>>> 

In particular:

$ python2 pkg/main2.py
Traceback (most recent call last):
  File "pkg/main2.py", line 1, in <module>
    from __future__ import absolute_import;import string;print(string.ascii_uppercase)
AttributeError: 'module' object has no attribute 'ascii_uppercase'
$ python2
Python 2.7.9 (default, Dec 13 2014, 18:02:08) [GCC] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import pkg.main2
ABCDEFGHIJKLMNOPQRSTUVWXYZ
>>> 
$ python2 -m pkg.main2
ABCDEFGHIJKLMNOPQRSTUVWXYZ

Note that python2 pkg/main2.py has a different behaviour then launching python2 and then importing pkg.main2 (which is equivalent to using the -m switch).

If you ever want to run a submodule of a package always use the -m switch which prevents the interpreter for chaining the sys.path list and correctly handles the semantics of the submodule.

Also, I much prefer using explicit relative imports for package submodules since they provide more semantics and better error messages in case of failure.

What is the simplest way to write the contents of a StringBuilder to a text file in .NET 1.1?

You still have access to StreamWriter:

using (System.IO.StreamWriter file = new System.IO.StreamWriter(@"\hereIam.txt"))
{
    file.WriteLine(sb.ToString()); // "sb" is the StringBuilder
}

From the MSDN documentation: Writing to a Text File (Visual C#).

For newer versions of the .NET Framework (Version 2.0. onwards), this can be achieved with one line using the File.WriteAllText method.

System.IO.File.WriteAllText(@"C:\TextFile.txt", stringBuilder.ToString());

ADB Shell Input Events

Updating:

Using adb shell input:

Insert text:

adb shell input text "insert%syour%stext%shere"

(obs: %s means SPACE)

..

Event codes:

adb shell input keyevent 82

(82 ---> MENU_BUTTON)

"For more keyevents codes see list below"

..

Tap X,Y position:

adb shell input tap 500 1450

To find the exact X,Y position you want to Tap go to:

Settings > Developer Options > Check the option POINTER SLOCATION

..

Swipe X1 Y1 X2 Y2 [duration(ms)]:

adb shell input swipe 100 500 100 1450 100

in this example X1=100, Y1=500, X2=100, Y2=1450, Duration = 100ms

..

LongPress X Y:

adb shell input swipe 100 500 100 500 250

we utilise the same command for a swipe to emulate a long press

in this example X=100, Y=500, Duration = 250ms

..

Event Codes Updated List:

0 -->  "KEYCODE_0" 
1 -->  "KEYCODE_SOFT_LEFT" 
2 -->  "KEYCODE_SOFT_RIGHT" 
3 -->  "KEYCODE_HOME" 
4 -->  "KEYCODE_BACK" 
5 -->  "KEYCODE_CALL" 
6 -->  "KEYCODE_ENDCALL" 
7 -->  "KEYCODE_0" 
8 -->  "KEYCODE_1" 
9 -->  "KEYCODE_2" 
10 -->  "KEYCODE_3" 
11 -->  "KEYCODE_4" 
12 -->  "KEYCODE_5" 
13 -->  "KEYCODE_6" 
14 -->  "KEYCODE_7" 
15 -->  "KEYCODE_8" 
16 -->  "KEYCODE_9" 
17 -->  "KEYCODE_STAR" 
18 -->  "KEYCODE_POUND" 
19 -->  "KEYCODE_DPAD_UP" 
20 -->  "KEYCODE_DPAD_DOWN" 
21 -->  "KEYCODE_DPAD_LEFT" 
22 -->  "KEYCODE_DPAD_RIGHT" 
23 -->  "KEYCODE_DPAD_CENTER" 
24 -->  "KEYCODE_VOLUME_UP" 
25 -->  "KEYCODE_VOLUME_DOWN" 
26 -->  "KEYCODE_POWER" 
27 -->  "KEYCODE_CAMERA" 
28 -->  "KEYCODE_CLEAR" 
29 -->  "KEYCODE_A" 
30 -->  "KEYCODE_B" 
31 -->  "KEYCODE_C" 
32 -->  "KEYCODE_D" 
33 -->  "KEYCODE_E" 
34 -->  "KEYCODE_F" 
35 -->  "KEYCODE_G" 
36 -->  "KEYCODE_H" 
37 -->  "KEYCODE_I" 
38 -->  "KEYCODE_J" 
39 -->  "KEYCODE_K" 
40 -->  "KEYCODE_L" 
41 -->  "KEYCODE_M" 
42 -->  "KEYCODE_N" 
43 -->  "KEYCODE_O" 
44 -->  "KEYCODE_P" 
45 -->  "KEYCODE_Q" 
46 -->  "KEYCODE_R" 
47 -->  "KEYCODE_S" 
48 -->  "KEYCODE_T" 
49 -->  "KEYCODE_U" 
50 -->  "KEYCODE_V" 
51 -->  "KEYCODE_W" 
52 -->  "KEYCODE_X" 
53 -->  "KEYCODE_Y" 
54 -->  "KEYCODE_Z" 
55 -->  "KEYCODE_COMMA" 
56 -->  "KEYCODE_PERIOD" 
57 -->  "KEYCODE_ALT_LEFT" 
58 -->  "KEYCODE_ALT_RIGHT" 
59 -->  "KEYCODE_SHIFT_LEFT" 
60 -->  "KEYCODE_SHIFT_RIGHT" 
61 -->  "KEYCODE_TAB" 
62 -->  "KEYCODE_SPACE" 
63 -->  "KEYCODE_SYM" 
64 -->  "KEYCODE_EXPLORER" 
65 -->  "KEYCODE_ENVELOPE" 
66 -->  "KEYCODE_ENTER" 
67 -->  "KEYCODE_DEL" 
68 -->  "KEYCODE_GRAVE" 
69 -->  "KEYCODE_MINUS" 
70 -->  "KEYCODE_EQUALS" 
71 -->  "KEYCODE_LEFT_BRACKET" 
72 -->  "KEYCODE_RIGHT_BRACKET" 
73 -->  "KEYCODE_BACKSLASH" 
74 -->  "KEYCODE_SEMICOLON" 
75 -->  "KEYCODE_APOSTROPHE" 
76 -->  "KEYCODE_SLASH" 
77 -->  "KEYCODE_AT" 
78 -->  "KEYCODE_NUM" 
79 -->  "KEYCODE_HEADSETHOOK" 
80 -->  "KEYCODE_FOCUS" 
81 -->  "KEYCODE_PLUS" 
82 -->  "KEYCODE_MENU" 
83 -->  "KEYCODE_NOTIFICATION" 
84 -->  "KEYCODE_SEARCH" 
85 -->  "KEYCODE_MEDIA_PLAY_PAUSE"
86 -->  "KEYCODE_MEDIA_STOP"
87 -->  "KEYCODE_MEDIA_NEXT"
88 -->  "KEYCODE_MEDIA_PREVIOUS"
89 -->  "KEYCODE_MEDIA_REWIND"
90 -->  "KEYCODE_MEDIA_FAST_FORWARD"
91 -->  "KEYCODE_MUTE"
92 -->  "KEYCODE_PAGE_UP"
93 -->  "KEYCODE_PAGE_DOWN"
94 -->  "KEYCODE_PICTSYMBOLS"
...
122 -->  "KEYCODE_MOVE_HOME"
123 -->  "KEYCODE_MOVE_END"

The complete list of commands can be found on: http://developer.android.com/reference/android/view/KeyEvent.html

How to print Unicode character in C++?

Ultimately, this is completely platform-dependent. Unicode-support is, unfortunately, very poor in Standard C++. For GCC, you will have to make it a narrow string, as they use UTF-8, and Windows wants a wide string, and you must output to wcout.

// GCC
std::cout << "?";
// Windoze
wcout << L"?";

Swift_TransportException Connection could not be established with host smtp.gmail.com

I just had this issue and solved it by editing mail.php under config folder. Usually when using shared hosting, they hosting company allows you to create an email such as

[email protected]

. So go to email settings under you shared hosting cpanel and add new email. Take that email and password and set it in the

mail.php.

It should work!

XOR operation with two strings in java

the abs function is when the Strings are not the same length so the legth of the result will be the same as the min lenght of the two String a and b

public String xor(String a, String b){
    StringBuilder sb = new StringBuilder();
    for(int k=0; k < a.length(); k++)
       sb.append((a.charAt(k) ^ b.charAt(k + (Math.abs(a.length() - b.length()))))) ;
       return sb.toString();
}

htons() function in socket programing

the htons() function converts values between host and network byte orders. There is a difference between big-endian and little-endian and network byte order depending on your machine and network protocol in use.

Executing Javascript code "on the spot" in Chrome?

I'm not sure how far it will get you, but you can execute JavaScript one line at a time from the Developer Tool Console.

jQuery / Javascript code check, if not undefined

I like this:

if (wlocation !== undefined)

But if you prefer the second way wouldn't be as you posted. It would be:

if (typeof wlocation  !== "undefined")

C# Pass Lambda Expression as Method Parameter

You should use a delegate type and specify that as your command parameter. You could use one of the built in delegate types - Action and Func.

In your case, it looks like your delegate takes two parameters, and returns a result, so you could use Func:

List<IJob> GetJobs(Func<FullTimeJob, Student, FullTimeJob> projection)

You could then call your GetJobs method passing in a delegate instance. This could be a method which matches that signature, an anonymous delegate, or a lambda expression.

P.S. You should use PascalCase for method names - GetJobs, not getJobs.

Ways to eliminate switch in code

See the Switch Statements Smell:

Typically, similar switch statements are scattered throughout a program. If you add or remove a clause in one switch, you often have to find and repair the others too.

Both Refactoring and Refactoring to Patterns have approaches to resolve this.

If your (pseudo) code looks like:

class RequestHandler {

    public void handleRequest(int action) {
        switch(action) {
            case LOGIN:
                doLogin();
                break;
            case LOGOUT:
                doLogout();
                break;
            case QUERY:
               doQuery();
               break;
        }
    }
}

This code violates the Open Closed Principle and is fragile to every new type of action code that comes along. To remedy this you could introduce a 'Command' object:

interface Command {
    public void execute();
}

class LoginCommand implements Command {
    public void execute() {
        // do what doLogin() used to do
    }
}

class RequestHandler {
    private Map<Integer, Command> commandMap; // injected in, or obtained from a factory
    public void handleRequest(int action) {
        Command command = commandMap.get(action);
        command.execute();
    }
}

If your (pseudo) code looks like:

class House {
    private int state;

    public void enter() {
        switch (state) {
            case INSIDE:
                throw new Exception("Cannot enter. Already inside");
            case OUTSIDE:
                 state = INSIDE;
                 ...
                 break;
         }
    }
    public void exit() {
        switch (state) {
            case INSIDE:
                state = OUTSIDE;
                ...
                break;
            case OUTSIDE:
                throw new Exception("Cannot leave. Already outside");
        }
    }

Then you could introduce a 'State' object.

// Throw exceptions unless the behavior is overriden by subclasses
abstract class HouseState {
    public HouseState enter() {
        throw new Exception("Cannot enter");
    }
    public HouseState leave() {
        throw new Exception("Cannot leave");
    }
}

class Inside extends HouseState {
    public HouseState leave() {
        return new Outside();
    }
}

class Outside extends HouseState {
    public HouseState enter() {
        return new Inside();
    }
}

class House {
    private HouseState state;
    public void enter() {
        this.state = this.state.enter();
    }
    public void leave() {
        this.state = this.state.leave();
    }
}

Hope this helps.

How to detect current state within directive

Update:

This answer was for a much older release of Ui-Router. For the more recent releases (0.2.5+), please use the helper directive ui-sref-active. Details here.


Original Answer:

Include the $state service in your controller. You can assign this service to a property on your scope.

An example:

$scope.$state = $state;

Then to get the current state in your templates:

$state.current.name

To check if a state is current active:

$state.includes('stateName'); 

This method returns true if the state is included, even if it's part of a nested state. If you were at a nested state, user.details, and you checked for $state.includes('user'), it'd return true.

In your class example, you'd do something like this:

ng-class="{active: $state.includes('stateName')}"

How can I get a specific field of a csv file?

There is an interesting point you need to catch about csv.reader() object. The csv.reader object is not list type, and not subscriptable.

This works:

for r in csv.reader(file_obj): # file not closed
    print r

This does not:

r = csv.reader(file_obj) 
print r[0]

So, you first have to convert to list type in order to make the above code work.

r = list( csv.reader(file_obj) )
print r[0]          

What is a raw type and why shouldn't we use it?

What is saying is that your list is a List of unespecified objects. That is that Java does not know what kind of objects are inside the list. Then when you want to iterate the list you have to cast every element, to be able to access the properties of that element (in this case, String).

In general is a better idea to parametrize the collections, so you don't have conversion problems, you will only be able to add elements of the parametrized type and your editor will offer you the appropiate methods to select.

private static List<String> list = new ArrayList<String>();

File upload along with other object in Jersey restful web service

You can access the Image File and data from a form using MULTIPART FORM DATA By using the below code.

@POST
@Path("/UpdateProfile")
@Consumes(value={MediaType.APPLICATION_JSON,MediaType.MULTIPART_FORM_DATA})
@Produces(value={MediaType.APPLICATION_JSON,MediaType.APPLICATION_XML})
public Response updateProfile(
    @FormDataParam("file") InputStream fileInputStream,
    @FormDataParam("file") FormDataContentDisposition contentDispositionHeader,
    @FormDataParam("ProfileInfo") String ProfileInfo,
    @FormDataParam("registrationId") String registrationId) {

    String filePath= "/filepath/"+contentDispositionHeader.getFileName();

    OutputStream outputStream = null;
    try {
        int read = 0;
        byte[] bytes = new byte[1024];
        outputStream = new FileOutputStream(new File(filePath));

        while ((read = fileInputStream.read(bytes)) != -1) {
            outputStream.write(bytes, 0, read);
        }

        outputStream.flush();
        outputStream.close();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (outputStream != null) { 
            try {
                outputStream.close();
            } catch(Exception ex) {}
        }
    }
}

How do I use InputFilter to limit characters in an EditText in Android?

This simple solution worked for me when I needed to prevent the user from entering empty strings into an EditText. You can of course add more characters:

InputFilter textFilter = new InputFilter() {

@Override

public CharSequence filter(CharSequence c, int arg1, int arg2,

    Spanned arg3, int arg4, int arg5) {

    StringBuilder sbText = new StringBuilder(c);

    String text = sbText.toString();

    if (text.contains(" ")) {    
        return "";   
    }    
    return c;   
    }   
};

private void setTextFilter(EditText editText) {

    editText.setFilters(new InputFilter[]{textFilter});

}

How to make remote REST call inside Node.js? any CURL?

Axios

An example (axios_example.js) using Axios in Node.js:

const axios = require('axios');
const express = require('express');
const app = express();
const port = process.env.PORT || 5000;

app.get('/search', function(req, res) {
    let query = req.query.queryStr;
    let url = `https://your.service.org?query=${query}`;

    axios({
        method:'get',
        url,
        auth: {
            username: 'the_username',
            password: 'the_password'
        }
    })
    .then(function (response) {
        res.send(JSON.stringify(response.data));
    })
    .catch(function (error) {
        console.log(error);
    });
});

var server = app.listen(port);

Be sure in your project directory you do:

npm init
npm install express
npm install axios
node axios_example.js

You can then test the Node.js REST API using your browser at: http://localhost:5000/search?queryStr=xxxxxxxxx

Similarly you can do post, such as:

axios({
  method: 'post',
  url: 'https://your.service.org/user/12345',
  data: {
    firstName: 'Fred',
    lastName: 'Flintstone'
  }
});

SuperAgent

Similarly you can use SuperAgent.

superagent.get('https://your.service.org?query=xxxx')
.end((err, response) => {
    if (err) { return console.log(err); }
    res.send(JSON.stringify(response.body));
});

And if you want to do basic authentication:

superagent.get('https://your.service.org?query=xxxx')
.auth('the_username', 'the_password')
.end((err, response) => {
    if (err) { return console.log(err); }
    res.send(JSON.stringify(response.body));
});

Ref:

ASP.NET MVC View Engine Comparison

I know this doesn't really answer your question, but different View Engines have different purposes. The Spark View Engine, for example, aims to rid your views of "tag soup" by trying to make everything fluent and readable.

Your best bet would be to just look at some implementations. If it looks appealing to the intent of your solution, try it out. You can mix and match view engines in MVC, so it shouldn't be an issue if you decide to not go with a specific engine.

Uploading images using Node.js, Express, and Mongoose

For Express 3.0, if you want to use the formidable events, you must remove the multipart middleware, so you can create the new instance of it.

To do this:

app.use(express.bodyParser());

Can be written as:

app.use(express.json());
app.use(express.urlencoded());
app.use(express.multipart()); // Remove this line

And now create the form object:

exports.upload = function(req, res) {
    var form = new formidable.IncomingForm;
    form.keepExtensions = true;
    form.uploadDir = 'tmp/';

    form.parse(req, function(err, fields, files){
        if (err) return res.end('You found error');
        // Do something with files.image etc
        console.log(files.image);
    });

    form.on('progress', function(bytesReceived, bytesExpected) {
        console.log(bytesReceived + ' ' + bytesExpected);
    });

    form.on('error', function(err) {
        res.writeHead(400, {'content-type': 'text/plain'}); // 400: Bad Request
        res.end('error:\n\n'+util.inspect(err));
    });
    res.end('Done');
    return;
};

I have also posted this on my blog, Getting formidable form object in Express 3.0 on upload.

Maven Install on Mac OS X

macOS Sierra onwards

brew install maven

MySQL case sensitive query

Whilst the listed answer is correct, may I suggest that if your column is to hold case sensitive strings you read the documentation and alter your table definition accordingly.

In my case this amounted to defining my column as:

`tag` varchar(255) CHARACTER SET utf8 COLLATE utf8_bin NOT NULL DEFAULT ''

This is in my opinion preferential to adjusting your queries.

How do I enable logging for Spring Security?

By default Spring Security redirects user to the URL that he originally requested (/Load.do in your case) after login.

You can set always-use-default-target to true to disable this behavior:

 <security:http auto-config="true">

    <security:intercept-url pattern="/Admin**" access="hasRole('PROGRAMMER') or hasRole('ADMIN')"/>
    <security:form-login login-page="/Load.do"
        default-target-url="/Admin.do?m=loadAdminMain"
        authentication-failure-url="/Load.do?error=true"
        always-use-default-target = "true"
        username-parameter="j_username"
        password-parameter="j_password"
        login-processing-url="/j_spring_security_check"/>
    <security:csrf/><!-- enable Cross Site Request Forgery protection -->
</security:http>

Replace and overwrite instead of appending

import os#must import this library
if os.path.exists('TwitterDB.csv'):
        os.remove('TwitterDB.csv') #this deletes the file
else:
        print("The file does not exist")#add this to prevent errors

I had a similar problem, and instead of overwriting my existing file using the different 'modes', I just deleted the file before using it again, so that it would be as if I was appending to a new file on each run of my code.

How to display an alert box from C# in ASP.NET?

You can use Message box to show success message. This works great for me.

MessageBox.Show("Data inserted successfully");

Associating existing Eclipse project with existing SVN repository

I just wanted to add that if you don't see Team -> Share project, it's likely you have to remove the project from the workspace before importing it back in. This is what happened to me, and I had to remove and readd it to the workspace for it to fix itself. (This happened when moving from dramatically different Eclipse versions + plugins using the same workspace.)

subclipse not showing "share project" option on project context menu in eclipse

JQuery Calculate Day Difference in 2 date textboxes

Hi, This is my example of calculating the difference between two dates

    <!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <script src="https://code.jquery.com/jquery.min.js"></script>
  <title>JS Bin</title>
</head>
<body>
  <br>
<input class='fromdate' type="date"  />
<input class='todate' type="date" />
<div class='calculated' /><br>
<div class='minim' />  
<input class='todate' type="submit" onclick='showDays()' />

</body>
</html>

This is the function that calculates the difference :

function showDays(){

     var start = $('.fromdate').val();
     var end = $('.todate').val();

     var startDay = new Date(start);
     var endDay = new Date(end);
     var millisecondsPerDay = 1000 * 60 * 60 * 24;

     var millisBetween = endDay.getTime() - startDay.getTime();
     var days = millisBetween / millisecondsPerDay;

      // Round down.
       alert( Math.floor(days));

}

I hope I have helped you

How to parse XML using vba

Here is a short sub to parse a MicroStation Triforma XML file that contains data for structural steel shapes.

'location of triforma structural files
'c:\programdata\bentley\workspace\triforma\tf_imperial\data\us.xml

Sub ReadTriformaImperialData()
Dim txtFileName As String
Dim txtFileLine As String
Dim txtFileNumber As Long

Dim Shape As String
Shape = "w12x40"

txtFileNumber = FreeFile
txtFileName = "c:\programdata\bentley\workspace\triforma\tf_imperial\data\us.xml"

Open txtFileName For Input As #txtFileNumber

Do While Not EOF(txtFileNumber)
Line Input #txtFileNumber, txtFileLine
    If InStr(1, UCase(txtFileLine), UCase(Shape)) Then
        P1 = InStr(1, UCase(txtFileLine), "D=")
        D = Val(Mid(txtFileLine, P1 + 3))

        P2 = InStr(1, UCase(txtFileLine), "TW=")
        TW = Val(Mid(txtFileLine, P2 + 4))

        P3 = InStr(1, UCase(txtFileLine), "WIDTH=")
        W = Val(Mid(txtFileLine, P3 + 7))

        P4 = InStr(1, UCase(txtFileLine), "TF=")
        TF = Val(Mid(txtFileLine, P4 + 4))

        Close txtFileNumber
        Exit Do
    End If
Loop
End Sub

From here you can use the values to draw the shape in MicroStation 2d or do it in 3d and extrude it to a solid.

Writing MemoryStream to Response Object

Try with this

Response.Clear();
Response.AppendHeader("Content-Type", "application/vnd.openxmlformats-officedocument.presentationml.presentation");
Response.AppendHeader("Content-Disposition", string.Format("attachment;filename={0}.pptx;", getLegalFileName(CurrentPresentation.Presentation_NM)));
Response.Flush();                
Response.BinaryWrite(masterPresentation.ToArray());
Response.End();

Rails: How does the respond_to block work?

This is a little outdated, by Ryan Bigg does a great job explaining this here:

http://ryanbigg.com/2009/04/how-rails-works-2-mime-types-respond_to

In fact, it might be a bit more detail than you were looking for. As it turns out, there's a lot going on behind the scenes, including a need to understand how the MIME types get loaded.

Remove Item in Dictionary based on Value

Here is a method you can use:

    public static void RemoveAllByValue<K, V>(this Dictionary<K, V> dictionary, V value)
    {
        foreach (var key in dictionary.Where(
                kvp => EqualityComparer<V>.Default.Equals(kvp.Value, value)).
                Select(x => x.Key).ToArray())
            dictionary.Remove(key);
    }

403 Forbidden error when making an ajax Post request in Django framework

Another approach is to add X-CSRFTOKEN header with the "{{ csrf_token }}" value like in the following example:

$.ajax({
            url: "{% url 'register_lowresistancetyres' %}",
            type: "POST",
            headers: {//<==
                        "X-CSRFTOKEN": "{{ csrf_token }}"//<==
                },
            data: $(example_form).serialize(),
            success: function(data) {
                //Success code
            },
            error: function () {
                //Error code
            }
        });

Why am I seeing net::ERR_CLEARTEXT_NOT_PERMITTED errors after upgrading to Cordova Android 8?

Just add this line to platforms/android/app/src/main/AndroidManifest.xml file

<application android:hardwareAccelerated="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:supportsRtl="true" android:usesCleartextTraffic="true">

Why am I getting an Exception with the message "Invalid setup on a non-virtual (overridable in VB) member..."?

Moq cannot mock non-virtual methods and sealed classes. While running a test using mock object, MOQ actually creates an in-memory proxy type which inherits from your "XmlCupboardAccess" and overrides the behaviors that you have set up in the "SetUp" method. And as you know in C#, you can override something only if it is marked as virtual which isn't the case with Java. Java assumes every non-static method to be virtual by default.

Another thing I believe you should consider is introducing an interface for your "CupboardAccess" and start mocking the interface instead. It would help you decouple your code and have benefits in the longer run.

Lastly, there are frameworks like : TypeMock and JustMock which work directly with the IL and hence can mock non-virtual methods. Both however, are commercial products.

Show dialog from fragment?

For me, it was the following-

MyFragment:

public class MyFragment extends Fragment implements MyDialog.Callback
{
    ShowDialog activity_showDialog;

    @Override
    public void onAttach(Activity activity)
    {
        super.onAttach(activity);
        try
        {
            activity_showDialog = (ShowDialog)activity;
        }
        catch(ClassCastException e)
        {
            Log.e(this.getClass().getSimpleName(), "ShowDialog interface needs to be     implemented by Activity.", e);
            throw e;
        }
    }

    @Override
    public void onClick(View view) 
    {
        ...
        MyDialog dialog = new MyDialog();
        dialog.setTargetFragment(this, 1); //request code
        activity_showDialog.showDialog(dialog);
        ...
    }

    @Override
    public void accept()
    {
        //accept
    }

    @Override
    public void decline()
    {
        //decline
    }

    @Override
    public void cancel()
    {
        //cancel
    }

}

MyDialog:

public class MyDialog extends DialogFragment implements View.OnClickListener
{
    private EditText mEditText;
    private Button acceptButton;
    private Button rejectButton;
    private Button cancelButton;

    public static interface Callback
    {
        public void accept();
        public void decline();
        public void cancel();
    }

    public MyDialog()
    {
        // Empty constructor required for DialogFragment
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
    {
        View view = inflater.inflate(R.layout.dialogfragment, container);
        acceptButton = (Button) view.findViewById(R.id.dialogfragment_acceptbtn);
        rejectButton = (Button) view.findViewById(R.id.dialogfragment_rejectbtn);
        cancelButton = (Button) view.findViewById(R.id.dialogfragment_cancelbtn);
        acceptButton.setOnClickListener(this);
        rejectButton.setOnClickListener(this);
        cancelButton.setOnClickListener(this);
        getDialog().setTitle(R.string.dialog_title);
        return view;
    }

    @Override
    public void onClick(View v)
    {
        Callback callback = null;
        try
        {
            callback = (Callback) getTargetFragment();
        }
        catch (ClassCastException e)
        {
            Log.e(this.getClass().getSimpleName(), "Callback of this class must be implemented by target fragment!", e);
            throw e;
        }

        if (callback != null)
        {
            if (v == acceptButton)
            {   
                callback.accept();
                this.dismiss();
            }
            else if (v == rejectButton)
            {
                callback.decline();
                this.dismiss();
            }
            else if (v == cancelButton)
            {
                callback.cancel();
                this.dismiss();
            }
        }
    }
}

Activity:

public class MyActivity extends ActionBarActivity implements ShowDialog
{
    ..

    @Override
    public void showDialog(DialogFragment dialogFragment)
    {
        FragmentManager fragmentManager = getSupportFragmentManager();
        dialogFragment.show(fragmentManager, "dialog");
    }
}

DialogFragment layout:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="center"
    android:orientation="vertical" >

    <TextView
        android:id="@+id/dialogfragment_textview"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="20dp"
        android:layout_centerHorizontal="true"
        android:layout_marginBottom="10dp"
        android:text="@string/example"/>

    <Button
        android:id="@+id/dialogfragment_acceptbtn"
        android:layout_width="200dp"
        android:layout_height="wrap_content"
        android:layout_marginTop="20dp"
        android:layout_centerHorizontal="true"
        android:layout_below="@+id/dialogfragment_textview"
        android:text="@string/accept"
        />

    <Button
        android:id="@+id/dialogfragment_rejectbtn"
        android:layout_width="200dp"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp"
        android:layout_alignLeft="@+id/dialogfragment_acceptbtn"
        android:layout_below="@+id/dialogfragment_acceptbtn"
        android:text="@string/decline" />

     <Button
        android:id="@+id/dialogfragment_cancelbtn"
        android:layout_width="200dp"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp"
        android:layout_marginBottom="20dp"
        android:layout_alignLeft="@+id/dialogfragment_rejectbtn"
        android:layout_below="@+id/dialogfragment_rejectbtn"
        android:text="@string/cancel" />

     <Button
        android:id="@+id/dialogfragment_heightfixhiddenbtn"
        android:layout_width="200dp"
        android:layout_height="20dp"
        android:layout_marginTop="10dp"
        android:layout_marginBottom="20dp"
        android:layout_alignLeft="@+id/dialogfragment_cancelbtn"
        android:layout_below="@+id/dialogfragment_cancelbtn"
        android:background="@android:color/transparent"
        android:enabled="false"
        android:text=" " />
</RelativeLayout>

As the name dialogfragment_heightfixhiddenbtn shows, I just couldn't figure out a way to fix that the bottom button's height was cut in half despite saying wrap_content, so I added a hidden button to be "cut" in half instead. Sorry for the hack.

php var_dump() vs print_r()

print_r() and var_dump() are Array debugging functions used in PHP for debugging purpose. print_r() function returns the array keys and its members as Array([key] = value) whereas var_dump() function returns array list with its array keys with data type and length as well e.g Array(array_length){[0] = string(1)'a'}.

How to put an image next to each other

You don't need the div's.

HTML:

<div class="nav3" style="height:705px;">
    <a href="http://www.facebook.com/" class="icons"><img src="images/facebook.png"></a>
    <a href="https://twitter.com" class="icons"><img src="images/twitter.png"></a>
</div>

CSS:

.nav3 {
    background-color: #E9E8C7;
    height: auto;
    width: 150px;
    float: left;
    padding-left: 20px;
    font-family: Arial, Helvetica, sans-serif;
    font-size: 12px;
    color: #333333;
    padding-top: 20px;
    padding-right: 20px;
}

.icons{
    display:inline-block;
    width: 64px; 
    height: 64px; 
   }

 a.icons:hover {
     background: #C93;
 }

See this fiddle

How can I determine the status of a job?

This is what I'm using to get the running jobs (principally so I can kill the ones which have probably hung):

SELECT
    job.Name, job.job_ID
    ,job.Originating_Server
    ,activity.run_requested_Date
    ,datediff(minute, activity.run_requested_Date, getdate()) AS Elapsed
FROM
    msdb.dbo.sysjobs_view job 
        INNER JOIN msdb.dbo.sysjobactivity activity
        ON (job.job_id = activity.job_id)
WHERE
    run_Requested_date is not null 
    AND stop_execution_date is null
    AND job.name like 'Your Job Prefix%'

As Tim said, the MSDN / BOL documentation is reasonably good on the contents of the sysjobsX tables. Just remember they are tables in MSDB.

How to clear an EditText on click?

((EditText) findViewById(R.id.User)).setText("");
((EditText) findViewById(R.id.Password)).setText("");

Move a view up only when the keyboard covers an input field

The accepted anwser is nearly perfect. But I need to use UIKeyboardFrameEndUserInfoKey instead of UIKeyboardFrameBeginUserInfoKey, because the latter return keyborad height 0. And change the hittest point to the bottom not origin.

    var aRect : CGRect = self.view.frame
    aRect.size.height -= keyboardSize!.height
    if let activeField = self.activeField {
        var point = activeField.frame.origin
        point.y += activeField.frame.size.height
        if (!aRect.contains(point)){
            self.scrollView.scrollRectToVisible(activeField.frame, animated: true)
        }
    }

How to ensure that there is a delay before a service is started in systemd?

Combining the answers from @Ortomala Lokni and @rogerdpack, another alternative is to have the dependent service monitor when the first one has started / done the thing you're waiting for.

For example, here's how I am making the fail2ban service wait for Docker to open port 443 (so that fail2ban's iptables entries take priority over Docker's):

[Service]
ExecStartPre=/bin/bash -c '(while ! nc -z -v -w1 localhost 443 > /dev/null; do echo "Waiting for port 443 to open..."; sleep 2; done); sleep 2'

Simply replace nc -z -v -w1 localhost 443 with a command that fails (non-zero exit code) while the first service is starting and succeeds once it is up.

For the Cassandra case, the ideal would be a command that only returns 0 when the cluster is available.

Apply function to each element of a list

Sometimes you need to apply a function to the members of a list in place. The following code worked for me:

>>> def func(a, i):
...     a[i] = a[i].lower()
>>> a = ['TEST', 'TEXT']
>>> list(map(lambda i:func(a, i), range(0, len(a))))
[None, None]
>>> print(a)
['test', 'text']

Please note, the output of map() is passed to the list constructor to ensure the list is converted in Python 3. The returned list filled with None values should be ignored, since our purpose was to convert list a in place

Detect if an element is visible with jQuery

There's no need, just use fadeToggle() on the element:

$('#testElement').fadeToggle('fast');

Here's a demo.

How to get system time in Java without creating a new Date

As jzd says, you can use System.currentTimeMillis. If you need it in a Date object but don't want to create a new Date object, you can use Date.setTime to reuse an existing Date object. Personally I hate the fact that Date is mutable, but maybe it's useful to you in this particular case. Similarly, Calendar has a setTimeInMillis method.

If possible though, it would probably be better just to keep it as a long. If you only need a timestamp, effectively, then that would be the best approach.

Enable SQL Server Broker taking too long

Actually I am preferring to use NEW_BROKER ,it is working fine on all cases:

ALTER DATABASE [dbname] SET NEW_BROKER WITH ROLLBACK IMMEDIATE;

ASP.NET MVC Conditional validation

You need to validate at Person level, not on Senior level, or Senior must have a reference to its parent Person. It seems to me that you need a self validation mechanism that defines the validation on the Person and not on one of its properties. I'm not sure, but I don't think DataAnnotations supports this out of the box. What you can do create your own Attribute that derives from ValidationAttribute that can be decorated on class level and next create a custom validator that also allows those class-level validators to run.

I know Validation Application Block supports self-validation out-of the box, but VAB has a pretty steep learning curve. Nevertheless, here's an example using VAB:

[HasSelfValidation]
public class Person
{
    public string Name { get; set; }
    public bool IsSenior { get; set; }
    public Senior Senior { get; set; }

    [SelfValidation]
    public void ValidateRange(ValidationResults results)
    {
        if (this.IsSenior && this.Senior != null && 
            string.IsNullOrEmpty(this.Senior.Description))
        {
            results.AddResult(new ValidationResult(
                "A senior description is required", 
                this, "", "", null));
        }
    }
}

HTML input fields does not get focus when clicked

I just found another possible reason for this issue, some input textboxes were missing the closing "/", so i had <input ...> when the correct form is <input ... />. That fixed it for me.

Android Studio SDK location

Consider Using windows 7 64bits

C:\Users\Administrador\AppData\Local\Android\sdk

Checking host availability by using ping in bash scripts

There is advanced version of ping - "fping", which gives possibility to define the timeout in milliseconds.

#!/bin/bash
IP='192.168.1.1'
fping -c1 -t300 $IP 2>/dev/null 1>/dev/null
if [ "$?" = 0 ]
then
  echo "Host found"
else
  echo "Host not found"
fi

The character encoding of the HTML document was not declared

Well when you post, the browser only outputs $title - all your HTML tags and doctype go away. You need to include those in your insert.php file:

<!DOCTYPE html PUBLIC"-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<title>insert page</title></head>
<body>
<?php 

   $title = $_POST["title"];
   $price = $_POST["price"];

  echo $title;


 ?>  
</body>
</html>

How to do one-liner if else statement?

As the comments mentioned, Go doesn't support ternary one liners. The shortest form I can think of is this:

var c int
if c = b; a > b {
    c = a
}

But please don't do that, it's not worth it and will only confuse people who read your code.

Are there constants in JavaScript?

"use strict";

var constants = Object.freeze({
    "p": 3.141592653589793 ,
    "e": 2.718281828459045 ,
    "i": Math.sqrt(-1)
});

constants.p;        // -> 3.141592653589793
constants.p = 3;    // -> TypeError: Cannot assign to read only property 'p' …
constants.p;        // -> 3.141592653589793

delete constants.p; // -> TypeError: Unable to delete property.
constants.p;        // -> 3.141592653589793

See Object.freeze. You can use const if you want to make the constants reference read-only as well.

Last executed queries for a specific database

This works for me to find queries on any database in the instance. I'm sysadmin on the instance (check your privileges):

SELECT deqs.last_execution_time AS [Time], dest.text AS [Query], dest.*
FROM sys.dm_exec_query_stats AS deqs
CROSS APPLY sys.dm_exec_sql_text(deqs.sql_handle) AS dest
WHERE dest.dbid = DB_ID('msdb')
ORDER BY deqs.last_execution_time DESC

This is the same answer that Aaron Bertrand provided but it wasn't placed in an answer.

NHibernate.MappingException: No persister for: XYZ

This error occurs because of invalid mapping configuration. You should check where you set .Mappings for your session factory. Basically search for ".Mappings(" in your project and make sure you specified correct entity class in below line.

.Mappings(m => m.FluentMappings.AddFromAssemblyOf<YourEntityClassName>())

My docker container has no internet

I was using DOCKER_OPTS="--dns 8.8.8.8" and later discovered and that my container didn't have direct access to internet but could access my corporate intranet. I changed DOCKER_OPTS to the following:

DOCKER_OPTS="--dns <internal_corporate_dns_address"

replacing internal_corporate_dns_address with the IP address or FQDN of our DNS and restarted docker using

sudo service docker restart

and then spawned my container and checked that it had access to internet.

Where is GACUTIL for .net Framework 4.0 in windows 7?

There is no Gacutil included in the .net 4.0 standard installation. They have moved the GAC too, from %Windir%\assembly to %Windir%\Microsoft.NET\Assembly.

They havent' even bothered adding a "special view" for the folder in Windows explorer, as they have for the .net 1.0/2.0 GAC.

Gacutil is part of the Windows SDK, so if you want to use it on your developement machine, just install the Windows SDK for your current platform. Then you will find it somewhere like this (depending on your SDK version):

C:\Program Files\Microsoft SDKs\Windows\v7.0A\bin\NETFX 4.0 Tools

There is a discussion on the new GAC here: .NET 4.0 has a new GAC, why?

If you want to install something in GAC on a production machine, you need to do it the "proper" way (gacutil was never meant as a tool for installing stuff on production servers, only as a development tool), with a Windows Installer, or with other tools. You can e.g. do it with PowerShell and the System.EnterpriseServices dll.

On a general note, and coming from several years of experience, I would personally strongly recommend against using GAC at all. Your application will always work if you deploy the DLL with each application in its bin folder as well. Yes, you will get multiple copies of the DLL on your server if you have e.g. multiple web apps on one server, but it's definitely worth the flexibility of being able to upgrade one application without breaking the others (by introducing an incompatible version of the shared DLL in the GAC).

How to write a basic swap function in Java

You have to do it inline. But you really don't need that swap in Java.

Submitting the value of a disabled input field

I wanna Disable an Input Field on a form and when i submit the form the values from the disabled form is not submitted.

Use Case: i am trying to get Lat Lng from Google Map and wanna Display it.. but dont want the user to edit it.

You can use the readonly property in your input field

<input type="text" readonly="readonly" />

How can I search an array in VB.NET?

compare properties in the array if one matches the input then set something to the value of the loops current position, which is also the index of the current looked up item.

simple eg.

dim x,y,z as integer
dim aNames, aIndexes as array
dim sFind as string
for x = 1 to length(aNames)

    if aNames(x) = sFind then y = x

y is then the index of the item in the array, then loop could be used to store these in an array also so instead of the above you would have:

z = 1
for x = 1 to length(aNames)
    if aNames(x) = sFind then 
        aIndexes(z) = x 
        z = z + 1
    endif

Python 2.7 getting user input and manipulating as string without quotations

This is my work around to fail safe in case if i will need to move to python 3 in future.

def _input(msg):
  return raw_input(msg)

What is the difference between square brackets and parentheses in a regex?

Your team's advice is almost right, except for the mistake that was made. Once you find out why, you will never forget it. Take a look at this mistake.

/^(7|8|9)\d{9}$/

What this does:

  • ^ and $ denotes anchored matches, which asserts that the subpattern in between these anchors are the entire match. The string will only match if the subpattern matches the entirety of it, not just a section.
  • () denotes a capturing group.
  • 7|8|9 denotes matching either of 7, 8, or 9. It does this with alternations, which is what the pipe operator | does — alternating between alternations. This backtracks between alternations: If the first alternation is not matched, the engine has to return before the pointer location moved during the match of the alternation, to continue matching the next alternation; Whereas the character class can advance sequentially. See this match on a regex engine with optimizations disabled:
Pattern: (r|f)at
Match string: carat

alternations

Pattern: [rf]at
Match string: carat

class

  • \d{9} matches nine digits. \d is a shorthanded metacharacter, which matches any digits.
/^[7|8|9][\d]{9}$/

Look at what it does:

  • ^ and $ denotes anchored matches as well.
  • [7|8|9] is a character class. Any characters from the list 7, |, 8, |, or 9 can be matched, thus the | was added in incorrectly. This matches without backtracking.
  • [\d] is a character class that inhabits the metacharacter \d. The combination of the use of a character class and a single metacharacter is a bad idea, by the way, since the layer of abstraction can slow down the match, but this is only an implementation detail and only applies to a few of regex implementations. JavaScript is not one, but it does make the subpattern slightly longer.
  • {9} indicates the previous single construct is repeated nine times in total.

The optimal regex is /^[789]\d{9}$/, because /^(7|8|9)\d{9}$/ captures unnecessarily which imposes a performance decrease on most regex implementations ( happens to be one, considering the question uses keyword var in code, this probably is JavaScript). The use of which runs on PCRE for preg matching will optimize away the lack of backtracking, however we're not in PHP either, so using classes [] instead of alternations | gives performance bonus as the match does not backtrack, and therefore both matches and fails faster than using your previous regular expression.

Share cookie between subdomain and domain

In both cases yes it can, and this is the default behaviour for both IE and Edge.

The other answers add valuable insight but chiefly describe the behaviour in Chrome. it's important to note that the behaviour is completely different in IE. CMBuckley's very helpful test script demonstrates that in (say) Chrome, the cookies are not shared between root and subdomains when no domain is specified. However the same test in IE shows that they are shared. This IE case is closer to the take-home description in CMBuckley's www-or-not-www link. I know this to be the case because we have a system that used different servicestack cookies on both the root and subdomain. It all worked fine until someone accessed it in IE and the two systems fought over whose session cookie would win until we blew up the cache.

VBA EXCEL Multiple Nested FOR Loops that Set two variable for expression

I can't get to your google docs file at the moment but there are some issues with your code that I will try to address while answering

Sub stituterangersNEW()
Dim t As Range
Dim x As Range
Dim dify As Boolean
Dim difx As Boolean
Dim time2 As Date
Dim time1 As Date

    'You said time1 doesn't change, so I left it in a singe cell.
    'If that is not correct, you will have to play with this some more.
    time1 = Range("A6").Value

    'Looping through each of our output cells.
    For Each t In Range("B7:E9") 'Change these to match your real ranges.

        'Looping through each departure date/time.
        '(Only one row in your example. This can be adjusted if needed.)
        For Each x In Range("B2:E2") 'Change these to match your real ranges.
            'Check to see if our dep time corresponds to
            'the matching column in our output
            If t.Column = x.Column Then
                'If it does, then check to see what our time value is
                If x > 0 Then
                    time2 = x.Value
                    'Apply the change to the output cell.
                    t.Value = time1 - time2
                    'Exit out of this loop and move to the next output cell.
                    Exit For
                End If
            End If
            'If the columns don't match, or the x value is not a time
            'then we'll move to the next dep time (x)
        Next x
    Next t

End Sub

EDIT

I changed you worksheet to play with (see above for the new Sub). This probably does not suite your needs directly, but hopefully it will demonstrate the conept behind what I think you want to do. Please keep in mind that this code does not follow all the coding best preactices I would recommend (e.g. validating the time is actually a TIME and not some random other data type).

     A                      B                   C                   D                  E
1    LOAD_NUMBER            1                   2                   3                  4
2    DEPARTURE_TIME_DATE    11/12/2011 19:30    11/12/2011 19:30    11/12/2011 19:30    11/12/2011 20:00                
4    Dry_Refrig 7585.1  0   10099.8 16700
6    1/4/2012 19:30

Using the sub I got this output:

    A           B             C             D             E
7   Friday      1272:00:00    1272:00:00    1272:00:00    1271:30:00
8   Saturday    1272:00:00    1272:00:00    1272:00:00    1271:30:00
9   Thursday    1272:00:00    1272:00:00    1272:00:00    1271:30:00

.gitignore is ignored by Git

I had this problem, with a .gitignore file containing this line:

lib/ext/

I just realized that in fact, this directory is a symbolic link to a folder somewhere else:

ls -la lib/ext/
lrwxr-xr-x 1 roipoussiere users 47 Feb  6 14:16 lib/ext -> /home/roipoussiere/real/path/to/the/lib

On the line lib/ext/, Git actually looks for a folder, but a symbolic link is a file, so my lib folder is not ignored.

I fixed this by replacing lib/ext/ by lib/ext in my .gitignore file.

Initialization of an ArrayList in one line

Collection literals didn't make it into Java 8, but it is possible to use the Stream API to initialize a list in one rather long line:

List<String> places = Stream.of("Buenos Aires", "Córdoba", "La Plata").collect(Collectors.toList());

If you need to ensure that your List is an ArrayList:

ArrayList<String> places = Stream.of("Buenos Aires", "Córdoba", "La Plata").collect(Collectors.toCollection(ArrayList::new));

Match two strings in one line with grep

You should have grep like this:

$ grep 'string1' file | grep 'string2'

input() error - NameError: name '...' is not defined

Here is an input function which is compatible with both Python 2.7 and Python 3+: (Slightly modified answer by @Hardian) to avoid UnboundLocalError: local variable 'input' referenced before assignment error

def input_compatible(prompt=None):
    try:
        input_func = raw_input
    except NameError:
        input_func = input
    return input_func(prompt)

Making HTTP Requests using Chrome Developer tools

If your web page has jquery in your page, then you can do it writing on chrome developers console:

$.get(
    "somepage.php",
    {paramOne : 1, paramX : 'abc'},
    function(data) {
       alert('page content: ' + data);
    }
);

Its jquery way of doing it!

Declaring and using MySQL varchar variables

In Mysql, We can declare and use variables with set command like below

mysql> set @foo="manjeet";
mysql> select * from table where name = @foo;

How to print variables without spaces between values

>>> value=42

>>> print "Value is %s"%('"'+str(value)+'"') 

Value is "42"

How to get the last day of the month?

Considering there are unequal number of days in different months, here is the standard solution that works for every month.

import datetime
ref_date = datetime.today() # or what ever specified date

end_date_of_month = datetime.strptime(datetime.strftime(ref_date + relativedelta(months=1), '%Y-%m-01'),'%Y-%m-%d') + relativedelta(days=-1)

In the above code we are just adding a month to our selected date and then navigating to the first day of that month and then subtracting a day from that date.

MySQL Removing Some Foreign keys

first need to get actual constrain name by this query

SHOW CREATE TABLE TABLE_NAME

This query will result constrain name of the foreign key, now below query will drop it.

ALTER TABLE TABLE_NAME DROP FOREIGN KEY COLUMN_NAME_ibfk_1

last number in above constrain name depends how many foreign keys you have in table

How do I use 3DES encryption/decryption in Java?

I had hard times figuring it out myself and this post helped me to find the right answer for my case. When working with financial messaging as ISO-8583 the 3DES requirements are quite specific, so for my especial case the "DESede/CBC/PKCS5Padding" combinations wasn't solving the problem. After some comparative testing of my results against some 3DES calculators designed for the financial world I found the the value "DESede/ECB/Nopadding" is more suited for the the specific task.

Here is a demo implementation of my TripleDes class (using the Bouncy Castle provider)



    import java.security.InvalidKeyException;
    import java.security.NoSuchAlgorithmException;
    import java.security.NoSuchProviderException;
    import java.security.Security;
    import javax.crypto.BadPaddingException;
    import javax.crypto.Cipher;
    import javax.crypto.IllegalBlockSizeException;
    import javax.crypto.NoSuchPaddingException;
    import javax.crypto.SecretKey;
    import javax.crypto.spec.SecretKeySpec;
    import org.bouncycastle.jce.provider.BouncyCastleProvider;


    /**
     *
     * @author Jose Luis Montes de Oca
     */
    public class TripleDesCipher {
       private static String TRIPLE_DES_TRANSFORMATION = "DESede/ECB/Nopadding";
       private static String ALGORITHM = "DESede";
       private static String BOUNCY_CASTLE_PROVIDER = "BC";
       private Cipher encrypter;
       private Cipher decrypter;

       public TripleDesCipher(byte[] key) throws NoSuchAlgorithmException, NoSuchProviderException, NoSuchPaddingException,
             InvalidKeyException {
          Security.addProvider(new BouncyCastleProvider());
          SecretKey keySpec = new SecretKeySpec(key, ALGORITHM);
          encrypter = Cipher.getInstance(TRIPLE_DES_TRANSFORMATION, BOUNCY_CASTLE_PROVIDER);
          encrypter.init(Cipher.ENCRYPT_MODE, keySpec);
          decrypter = Cipher.getInstance(TRIPLE_DES_TRANSFORMATION, BOUNCY_CASTLE_PROVIDER);
          decrypter.init(Cipher.DECRYPT_MODE, keySpec);
       }

       public byte[] encode(byte[] input) throws IllegalBlockSizeException, BadPaddingException {
          return encrypter.doFinal(input);
       }

       public byte[] decode(byte[] input) throws IllegalBlockSizeException, BadPaddingException {
          return decrypter.doFinal(input);
       }
    }

MySQL IF ELSEIF in select query

As per Nawfal's answer, IF statements need to be in a procedure. I found this post that shows a brilliant example of using your script in a procedure while still developing and testing. Basically, you create, call then drop the procedure:

https://gist.github.com/jeremyjarrell/6083251

round a single column in pandas

For some reason the round() method doesn't work if you have float numbers with many decimal places, but this will.

decimals = 2    
df['column'] = df['column'].apply(lambda x: round(x, decimals))

How to add style from code behind?

You can use the CssClass property of the hyperlink:

LiteralControl ltr = new LiteralControl();
        ltr.Text = "<style type=\"text/css\" rel=\"stylesheet\">" +
                    @".d
                    {
                        background-color:Red;
                    }
                    .d:hover
                    {
                        background-color:Yellow;
                    }
                    </style>
                    ";
        this.Page.Header.Controls.Add(ltr);
        this.HyperLink1.CssClass = "d";

Defining constant string in Java?

Or another typical standard in the industry is to have a Constants.java named class file containing all the constants to be used all over the project.

DataTables: Uncaught TypeError: Cannot read property 'defaults' of undefined

var datatable_jquery_script = document.createElement("script");
datatable_jquery_script.src = "vendor/datatables/jquery.dataTables.min.js";
document.body.appendChild(datatable_jquery_script);
setTimeout(function(){
    var datatable_bootstrap_script = document.createElement("script");
    datatable_bootstrap_script.src = "vendor/datatables/dataTables.bootstrap4.min.js";
    document.body.appendChild(datatable_bootstrap_script);
},100);

I used setTimeOut to make sure datatables.min.js loads first. I inspected the waterfall loading of each, bootstrap4.min.js always loads first.

Convert Java Object to JsonNode in Jackson

As of Jackson 1.6, you can use:

JsonNode node = mapper.valueToTree(map);

or

JsonNode node = mapper.convertValue(object, JsonNode.class);

Source: is there a way to serialize pojo's directly to treemodel?

How to calculate distance from Wifi router using Signal Strength?

Don't care if you are a moderator. I wrote my text towards my audience not as a technical writer

All you guys need to learn to navigate with tools that predate GPS. Something like a sextant, octant, backstaff or an astrolabe.

If you have receive the signal from 3 different locations then you only need to measure the signal strength and make a ratio from those locations. Simple triangle calculation where a2+b2=c2. The stronger the signal strength the closer the device is to the receiver.

Compare two Byte Arrays? (Java)

Since I wanted to compare two arrays for a unit Test and I arrived on this answer I thought I could share.

You can also do it with:

@Test
public void testTwoArrays() {
  byte[] array = new BigInteger("1111000011110001", 2).toByteArray();
  byte[] secondArray = new BigInteger("1111000011110001", 2).toByteArray();

  Assert.assertArrayEquals(array, secondArray);
}

And you could check on Comparing arrays in JUnit assertions for more infos.

How to split the name string in mysql?

Combined a few answers here to create a SP that returns the parts of the string.

drop procedure if exists SplitStr;
DELIMITER ;;
CREATE PROCEDURE `SplitStr`(IN Str VARCHAR(2000), IN Delim VARCHAR(1))  
    BEGIN
        DECLARE inipos INT;
        DECLARE endpos INT;
        DECLARE maxlen INT;
        DECLARE fullstr VARCHAR(2000);
        DECLARE item VARCHAR(2000);
        create temporary table if not exists tb_split
        (
            item varchar(2000)
        );



        SET inipos = 1;
        SET fullstr = CONCAT(Str, delim);
        SET maxlen = LENGTH(fullstr);

        REPEAT
            SET endpos = LOCATE(delim, fullstr, inipos);
            SET item =  SUBSTR(fullstr, inipos, endpos - inipos);

            IF item <> '' AND item IS NOT NULL THEN           
                insert into tb_split values(item);
            END IF;
            SET inipos = endpos + 1;
        UNTIL inipos >= maxlen END REPEAT;

        SELECT * from tb_split;
        drop table tb_split;
    END;;
DELIMITER ;

Using Image control in WPF to display System.Drawing.Bitmap

I wrote a program with wpf and used Database for showing images and this is my code:

SqlConnection con = new SqlConnection(@"Data Source=HITMAN-PC\MYSQL;
                                      Initial Catalog=Payam;
                                      Integrated Security=True");

SqlDataAdapter da = new SqlDataAdapter("select * from news", con);

DataTable dt = new DataTable();
da.Fill(dt);

string adress = dt.Rows[i]["ImgLink"].ToString();
ImageSource imgsr = new BitmapImage(new Uri(adress));
PnlImg.Source = imgsr;

Pretty-print a Map in Java

String result = objectMapper.writeValueAsString(map) - as simple as this!

Result:

{"2019-07-04T03:00":1,"2019-07-04T04:00":1,"2019-07-04T01:00":1,"2019-07-04T02:00":1,"2019-07-04T13:00":1,"2019-07-04T06:00":1 ...}

P.S. add Jackson JSON to your classpath.

Best Way to Refresh Adapter/ListView on Android

Just write in your Custom ArrayAdaper this code:

private List<Cart_items> customListviewList ;

refreshEvents(carts);

public void refreshEvents(List<Cart_items> events)
{
    this.customListviewList.clear();
    this.customListviewList.addAll(events);
    notifyDataSetChanged();
}

How can I use console logging in Internet Explorer?

Since version 8, Internet Explorer has its own console, like other browsers. However, if the console is not enabled, the console object does not exist and a call to console.log will throw an error.

Another option is to use log4javascript (full disclosure: written by me), which has its own logging console that works in all mainstream browsers, including IE >= 5, plus a wrapper for the browser's own console that avoids the issue of an undefined console.

Understanding Linux /proc/id/maps

Each row in /proc/$PID/maps describes a region of contiguous virtual memory in a process or thread. Each row has the following fields:

address           perms offset  dev   inode   pathname
08048000-08056000 r-xp 00000000 03:0c 64593   /usr/sbin/gpm
  • address - This is the starting and ending address of the region in the process's address space
  • permissions - This describes how pages in the region can be accessed. There are four different permissions: read, write, execute, and shared. If read/write/execute are disabled, a - will appear instead of the r/w/x. If a region is not shared, it is private, so a p will appear instead of an s. If the process attempts to access memory in a way that is not permitted, a segmentation fault is generated. Permissions can be changed using the mprotect system call.
  • offset - If the region was mapped from a file (using mmap), this is the offset in the file where the mapping begins. If the memory was not mapped from a file, it's just 0.
  • device - If the region was mapped from a file, this is the major and minor device number (in hex) where the file lives.
  • inode - If the region was mapped from a file, this is the file number.
  • pathname - If the region was mapped from a file, this is the name of the file. This field is blank for anonymous mapped regions. There are also special regions with names like [heap], [stack], or [vdso]. [vdso] stands for virtual dynamic shared object. It's used by system calls to switch to kernel mode. Here's a good article about it: "What is linux-gate.so.1?"

You might notice a lot of anonymous regions. These are usually created by mmap but are not attached to any file. They are used for a lot of miscellaneous things like shared memory or buffers not allocated on the heap. For instance, I think the pthread library uses anonymous mapped regions as stacks for new threads.

Only one expression can be specified in the select list when the subquery is not introduced with EXISTS

You should return only one column and one row in the where query where you assign the returned value to a variable. Example:

select * from table1 where Date in (select * from Dates) -- Wrong
select * from table1 where Date in (select Column1,Column2 from Dates) -- Wrong
select * from table1 where Date in (select Column1 from Dates) -- OK