Programs & Examples On #Typelib

A type library is a standard format for interface descriptions. It can store interface or class meta-data and make them accessible for different clients. Type libraries enable clients to call interfaces without knowing their actual implementation.

How to kill a nodejs process in Linux?

You can use the killall command as follows:

killall node

How do I sort an observable collection?

I would like to Add to NeilW's answer. To incorporate a method that resembles the orderby. Add this method as an extension:

public static void Sort<T>(this ObservableCollection<T> collection, Func<T,T> keySelector) where T : IComparable
{
    List<T> sorted = collection.OrderBy(keySelector).ToList();
    for (int i = 0; i < sorted.Count(); i++)
        collection.Move(collection.IndexOf(sorted[i]), i);
}

And use like:

myCollection = new ObservableCollection<MyObject>();

//Sorts in place, on a specific Func<T,T>
myCollection.Sort(x => x.ID);

How to call a JavaScript function from PHP?

You may not be able to directly do this, but the Xajax library is pretty close to what you want. I will demonstrate with an example. Here's a button on a webpage:

<button onclick="xajax_addCity();">Add New City</button> 

Our intuitive guess would be that xajax_addCity() is a Javascript function, right? Well, right and wrong. The cool thing Xajax allows is that we don't have any JS function called xajax_addCity(), but what we do have is a PHP function called addCity() that can do whatever PHP does!

<?php function addCity() { echo "Wow!"; } ?>

Think about it for a minute. We are virtually invoking a PHP function from Javascript code! That over-simplified example was just to whet the appetite, a better explanation is on the Xajax site, have fun!

Shell Scripting: Using a variable to define a path

To add to the above correct answer :- For my case in shell, this code worked (working on sqoop)

ROOT_PATH="path/to/the/folder"
--options-file  $ROOT_PATH/query.txt

How do you clear a stringstream variable?

You can clear the error state and empty the stringstream all in one line

std::stringstream().swap(m); // swap m with a default constructed stringstream

This effectively resets m to a default constructed state

Find duplicate lines in a file and count how many time each line was duplicated?

Via :

awk '{dups[$1]++} END{for (num in dups) {print num,dups[num]}}' data

In awk 'dups[$1]++' command, the variable $1 holds the entire contents of column1 and square brackets are array access. So, for each 1st column of line in data file, the node of the array named dups is incremented.

And at the end, we are looping over dups array with num as variable and print the saved numbers first then their number of duplicated value by dups[num].

Note that your input file has spaces on end of some lines, if you clear up those, you can use $0 in place of $1 in command above :)

Create a Date with a set timezone without using a string representation

any mileage in

var d = new Date(xiYear, xiMonth, xiDate).toLocaleString();

YouTube URL in Video Tag

The most straight forward answer to this question is: You can't.

Youtube doesn't output their video's in the right format, thus they can't be embedded in a
<video/> element.

There are a few solutions posted using javascript, but don't trust on those, they all need a fallback, and won't work cross-browser.

How to convert Rows to Columns in Oracle?

 select * FROM doc_tab
    PIVOT
    (
    Min(document_id)
    FOR document_type IN ('Voters ID','Pan card','Drivers licence')
    ) 

outputs as this

enter image description here

sql fiddle demo here

PDOException SQLSTATE[HY000] [2002] No such file or directory

Step 1

Find the path to your unix_socket, to do that just run netstat -ln | grep mysql

You should get something like this

unix  2      [ ACC ]     STREAM     LISTENING     17397    /var/run/mysqld/mysqld.sock

Step 2

Take that and add it in your unix_socket param

'mysql' => array(
            'driver'    => 'mysql',
            'host'      => '67.25.71.187',
            'database'  => 'dbname',
            'username'  => 'username',
            'password'  => '***',
            'charset'   => 'utf8',
            'collation' => 'utf8_unicode_ci',
            'prefix'    => '',
            'unix_socket'    => '/var/run/mysqld/mysqld.sock' <-----
            ),
        ),

Hope it helps !!

Select Row number in postgres

SELECT tab.*,
    row_number() OVER () as rnum
  FROM tab;

Here's the relevant section in the docs.

P.S. This, in fact, fully matches the answer in the referenced question.

Correct way to use StringBuilder in SQL

You are correct in guessing that the aim of using string builder is not achieved, at least not to its full extent.

However, when the compiler sees the expression "select id1, " + " id2 " + " from " + " table" it emits code which actually creates a StringBuilder behind the scenes and appends to it, so the end result is not that bad afterall.

But of course anyone looking at that code is bound to think that it is kind of retarded.

Wait for page load in Selenium

Implicit and explicit wait is better.

But if you are handling an exception in Java, then you can use this for waiting for a page to reload:

Thead.sleep(1000);

MySQL: determine which database is selected?

slightly off-topic (using the CLI instead of PHP), but still worth knowing: You can set the prompt to display the default database by using any of the following

mysql --prompt='\d> '
export MYSQL_PS1='\d> '

or once inside

prompt \d>\_
\R \d>\_

Select a dummy column with a dummy value in SQL?

Try this:

select col1, col2, 'ABC' as col3 from Table1 where col1 = 0;

Proper Linq where clauses

EDIT: LINQ to Objects doesn't behave how I'd expected it to. You may well be interested in the blog post I've just written about this...


They're different in terms of what will be called - the first is equivalent to:

Collection.Where(x => x.Age == 10)
          .Where(x => x.Name == "Fido")
          .Where(x => x.Fat == true)

wheras the latter is equivalent to:

Collection.Where(x => x.Age == 10 && 
                      x.Name == "Fido" &&
                      x.Fat == true)

Now what difference that actually makes depends on the implementation of Where being called. If it's a SQL-based provider, I'd expect the two to end up creating the same SQL. If it's in LINQ to Objects, the second will have fewer levels of indirection (there'll be just two iterators involved instead of four). Whether those levels of indirection are significant in terms of speed is a different matter.

Typically I would use several where clauses if they feel like they're representing significantly different conditions (e.g. one is to do with one part of an object, and one is completely separate) and one where clause when various conditions are closely related (e.g. a particular value is greater than a minimum and less than a maximum). Basically it's worth considering readability before any slight performance difference.

How do you automatically resize columns in a DataGridView control AND allow the user to resize the columns on that same grid?

A C# version of Miroslav Zadravec's code

for (int i = 0; i < dataGridView1.Columns.Count-1; i++)
{
    dataGridView1.Columns[i].AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells;
}
dataGridView1.Columns[dataGridView1.Columns.Count - 1].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;

for (int i = 0; i < dataGridView1.Columns.Count; i++)
{
    int colw = dataGridView1.Columns[i].Width;
    dataGridView1.Columns[i].AutoSizeMode = DataGridViewAutoSizeColumnMode.None;
    dataGridView1.Columns[i].Width = colw;
}

Posted as Community Wiki so as to not mooch off of the reputation of others

What does "#pragma comment" mean?

These link in the libraries selected in MSVC++.

How can I search for a multiline pattern in a file?

grep -P also uses libpcre, but is much more widely installed. To find a complete title section of an html document, even if it spans multiple lines, you can use this:

grep -P '(?s)<title>.*</title>' example.html

Since the PCRE project implements to the perl standard, use the perl documentation for reference:

Javascript - sort array based on another array

I would use an intermediary object (itemsMap), thus avoiding quadratic complexity:

function createItemsMap(itemsArray) { // {"a": ["Anne"], "b": ["Bob", "Henry"], …}
  var itemsMap = {};
  for (var i = 0, item; (item = itemsArray[i]); ++i) {
    (itemsMap[item[1]] || (itemsMap[item[1]] = [])).push(item[0]);
  }
  return itemsMap;
}

function sortByKeys(itemsArray, sortingArr) {
  var itemsMap = createItemsMap(itemsArray), result = [];
  for (var i = 0; i < sortingArr.length; ++i) {
    var key = sortingArr[i];
    result.push([itemsMap[key].shift(), key]);
  }
  return result;
}

See http://jsfiddle.net/eUskE/

Better way to generate array of all letters in the alphabet

import java.util.*;
public class Experiments{


List uptoChar(int i){
       char c='a'; 
        List list = new LinkedList();
         for(;;) {
           list.add(c);
       if(list.size()==i){
             break;
           }
       c++;
            }
        return list;
      } 

    public static void main (String [] args) {

        Experiments experiments = new Experiments();
          System.out.println(experiments.uptoChar(26));
    } 

jQuery 'each' loop with JSON array

Try (untested):

$.getJSON("data.php", function(data){
    $.each(data.justIn, function() {
        $.each(this, function(k, v) {
            alert(k + ' ' + v);
        });
    });
    $.each(data.recent, function() {
        $.each(this, function(k, v) {
            alert(k + ' ' + v);
        });
    });
    $.each(data.old, function() {
        $.each(this, function(k, v) {
            alert(k + ' ' + v);
        });
    });    
});

I figured, three separate loops since you'll probably want to treat each dataset differently (justIn, recent, old). If not, you can do:

$.getJSON("data.php", function(data){
    $.each(data, function(k, v) {
        alert(k + ' ' + v);
        $.each(v, function(k1, v1) {
            alert(k1 + ' ' + v1);
        });
    });
}); 

Clear the cache in JavaScript

window.parent.caches.delete("call")

close and open the browser after executing the code in console.

Getting activity from context in android

And in Kotlin:

tailrec fun Context.activity(): Activity? = when {
  this is Activity -> this
  else -> (this as? ContextWrapper)?.baseContext?.activity()
}

How do I call a Django function on button click?

here is a pure-javascript, minimalistic approach. I use JQuery but you can use any library (or even no libraries at all).

<html>
    <head>
        <title>An example</title>
        <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
        <script>
            function call_counter(url, pk) {
                window.open(url);
                $.get('YOUR_VIEW_HERE/'+pk+'/', function (data) {
                    alert("counter updated!");
                });
            }
        </script>
    </head>
    <body>
        <button onclick="call_counter('http://www.google.com', 12345);">
            I update object 12345
        </button>
        <button onclick="call_counter('http://www.yahoo.com', 999);">
            I update object 999
        </button>
    </body>
</html>

Alternative approach

Instead of placing the JavaScript code, you can change your link in this way:

<a target="_blank" 
    class="btn btn-info pull-right" 
    href="{% url YOUR_VIEW column_3_item.pk %}/?next={{column_3_item.link_for_item|urlencode:''}}">
    Check It Out
</a>

and in your views.py:

def YOUR_VIEW_DEF(request, pk):
    YOUR_OBJECT.objects.filter(pk=pk).update(views=F('views')+1)
    return HttpResponseRedirect(request.GET.get('next')))

Can you overload controller methods in ASP.NET MVC?

There is only one public signature allowed for each controller method. If you try to overload it, it will compile, but you're getting the run-time error you've experienced.

If you're not willing to use different verbs (like the [HttpGet] and [HttpPost] attributes) to differentiate overloaded methods (which will work), or change the routing, then what remains is that you can either provide another method with a different name, or you can dispatch inside of the existing method. Here's how I did it:

I once came into a situation where I had to maintain backwards compatibility. The original method expected two parameters, but the new one had only one. Overloading the way I expected did not work because MVC didn't find the entry point any more.

To solve that, I did the following:

  1. Changed the 2 overloaded action methods from public to private
  2. Created one new public method which contained "just" 2 string parameters. That one acted as a dispatcher, i.e.:

    public ActionResult DoSomething(string param1, string param2)
    {
        if (string.IsNullOrEmpty(param2))
        {
            return DoSomething(ProductName: param1);
        }
        else
        {
            int oldId = int.Parse(param1);
            return DoSomething(OldParam: param1, OldId: oldId);
        }
    }
    
    
    private ActionResult DoSomething(string OldParam, int OldId)
    {
        // some code here
        return Json(result);
    }
    
    
    private ActionResult DoSomething(string ProductName)
    {
        // some code here
        return Json(result);
    }
    

Of course, this is a hack and should be refactored later. But for the time being, it worked for me.

You can also create a dispatcher like:

public ActionResult DoSomething(string action, string param1, string param2)
{
    switch (action)
    {
        case "update":
            return UpdateAction(param1, param2);
        case "remove":
            return DeleteAction(param1);
    }
}

You can see, that UpdateAction needs 2 parameters, while DeleteAction just needs one.

ALTER TABLE, set null in not null column, PostgreSQL 9.1

Execute the command in this format:

ALTER [ COLUMN ] column { SET | DROP } NOT NULL

Correct way to write loops for promise.

How about this one using BlueBird?

function fetchUserDetails(arr) {
    return Promise.each(arr, function(email) {
        return db.getUser(email).done(function(res) {
            logger.log(res);
        });
    });
}

How to create multiple output paths in Webpack config

Please don't use any workaround because it will impact build performance.

Webpack File Manager Plugin

Easy to install copy this tag on top of the webpack.config.js

const FileManagerPlugin = require('filemanager-webpack-plugin');

Install

npm install filemanager-webpack-plugin --save-dev

Add the plugin

module.exports = {
    plugins: [
        new FileManagerPlugin({
            onEnd: {
                copy: [
                    {source: 'www', destination: './vinod test 1/'},
                    {source: 'www', destination: './vinod testing 2/'},
                    {source: 'www', destination: './vinod testing 3/'},
                ],
            },
        }),
    ],
};

Screenshot

enter image description here

Why does Git tell me "No such remote 'origin'" when I try to push to origin?

I faced this issue when I was tring to link a locally created repo with a blank repo on github. Initially I was trying git remote set-url but I had to do git remote add instead.

git remote add origin https://github.com/VijayNew/NewExample.git

Bash checking if string does not contain other string

As mainframer said, you can use grep, but i would use exit status for testing, try this:

#!/bin/bash
# Test if anotherstring is contained in teststring
teststring="put you string here"
anotherstring="string"

echo ${teststring} | grep --quiet "${anotherstring}"
# Exit status 0 means anotherstring was found
# Exit status 1 means anotherstring was not found

if [ $? = 1 ]
then
  echo "$anotherstring was not found"
fi

How does the keyword "use" work in PHP and can I import classes with it?

use doesn't include anything. It just imports the specified namespace (or class) to the current scope

If you want the classes to be autoloaded - read about autoloading

How to log out user from web site using BASIC authentication?

Just for the record, there is a new HTTP Response Header called Clear-Site-Data. If your server reply includes a Clear-Site-Data: "cookies" header, then the authentication credentials (not only cookies) should be removed. I tested it on Chrome 77 but this warning shows on the console:

Clear-Site-Data header on 'https://localhost:9443/clear': Cleared data types:
"cookies". Clearing channel IDs and HTTP authentication cache is currently not
supported, as it breaks active network connections.

And the auth credentials aren't removed, so this doesn't works (for now) to implement basic auth logouts, but maybe in the future will. Didn't test on other browsers.

References:

https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Clear-Site-Data

https://www.w3.org/TR/clear-site-data/

https://github.com/w3c/webappsec-clear-site-data

https://caniuse.com/#feat=mdn-http_headers_clear-site-data_cookies

Images can't contain alpha channels or transparencies

You can remove the alpha channel from a PNG file from the command line with pngcrush, using the flag "-c 2":

$ file input.png
input.png: PNG image data, 1024 x 1024, 8-bit/color RGBA, non-interlaced
$ pngcrush -q -c 2 input.png output.png
libpng warning: iCCP: known incorrect sRGB profile
$ file output.png
output.png: PNG image data, 1024 x 1024, 8-bit/color RGB, non-interlaced

Note the change from RGBA to RGB: the Alpha channel is gone!

pngcrush lives at http://pmt.sourceforge.net/pngcrush/

Set height 100% on absolute div

Another solution without using any height but still fills 100% available height. Checkout this e.g on the codepen. http://codepen.io/gauravshankar/pen/PqoLLZ

For this html and body should have 100% height. This height is equal to the viewport height.

Make inner div position absolute and give top and bottom 0. This fills the div to available height. (height equal to body.)

html code:

<head></head>

<body>
  <div></div>
</body>

</html>

css code:

* {
  margin: 0;
  padding: 0;
}

html,
body {
  height: 100%;
  position: relative;
}

html {
  background-color: red;
}

body {
  background-color: green;
}

body> div {
  position: absolute;
  background-color: teal;
  width: 300px;
  top: 0;
  bottom: 0;
}

How to search through all Git and Mercurial commits in the repository for a certain string?

if you are a vim user, you can install tig (apt-get install tig), and use /, same command to search on vim

https://blogs.atlassian.com/2013/05/git-tig/

Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference

Make sure that while using : Button "varName" =findViewById("btID"); you put in the right "btID". I accidentally put in the id of a button from another similar activity and it showed the same error. Hope it helps.

How do I modify fields inside the new PostgreSQL JSON datatype?

UPDATE test
SET data = data::jsonb - 'a' || '{"a":5}'::jsonb
WHERE data->>'b' = '2'

This seems to be working on PostgreSQL 9.5

Java - Convert image to Base64

 byte[] byteArray = new byte[102400];
 base64String = Base64.encode(byteArray);

That code will encode 102400 bytes, no matter how much data you actually use in the array.

while ((bytesRead = fis.read(byteArray)) != -1)

You need to use the value of bytesRead somewhere.

Also, this may not read the whole file into the array in one go (it only reads as much as is in the I/O buffer), so your loop will probably not work, you may end up with half an image in your array.

I'd use Apache Commons IOUtils here:

 Base64.encode(FileUtils.readFileToByteArray(file));

ERROR 1045 (28000): Access denied for user 'root'@'localhost' (using password: NO)

I had the same problem. mysql -u root -p worked for me. It later asks you for a password. You should then enter the password that you had set for mysql. The default password could be password, if you did not set one. More info here.

SoapFault exception: Could not connect to host

For me it was a certificate problem. Following worked for me

$context = stream_context_create([
    'ssl' => [
        // set some SSL/TLS specific options
        'verify_peer' => false,
        'verify_peer_name' => false,
        'allow_self_signed' => true
    ]
]);

$client  = new SoapClient(null, [
    'location' => 'https://...',
    'uri' => '...', 
    'stream_context' => $context
]);

How do I convert certain columns of a data frame to become factors?

Here's an example:

#Create a data frame
> d<- data.frame(a=1:3, b=2:4)
> d
  a b
1 1 2
2 2 3
3 3 4

#currently, there are no levels in the `a` column, since it's numeric as you point out.
> levels(d$a)
NULL

#Convert that column to a factor
> d$a <- factor(d$a)
> d
  a b
1 1 2
2 2 3
3 3 4

#Now it has levels.
> levels(d$a)
[1] "1" "2" "3"

You can also handle this when reading in your data. See the colClasses and stringsAsFactors parameters in e.g. readCSV().

Note that, computationally, factoring such columns won't help you much, and may actually slow down your program (albeit negligibly). Using a factor will require that all values are mapped to IDs behind the scenes, so any print of your data.frame requires a lookup on those levels -- an extra step which takes time.

Factors are great when storing strings which you don't want to store repeatedly, but would rather reference by their ID. Consider storing a more friendly name in such columns to fully benefit from factors.

How to Create simple drag and Drop in angularjs

I just posted this to my brand spanking new blog: http://jasonturim.wordpress.com/2013/09/01/angularjs-drag-and-drop/

Code here: https://github.com/logicbomb/lvlDragDrop

Demo here: http://logicbomb.github.io/ng-directives/drag-drop.html

Here are the directives these rely on a UUID service which I've included below:

var module = angular.module("lvl.directives.dragdrop", ['lvl.services']);

module.directive('lvlDraggable', ['$rootScope', 'uuid', function($rootScope, uuid) {
        return {
            restrict: 'A',
            link: function(scope, el, attrs, controller) {
                console.log("linking draggable element");

                angular.element(el).attr("draggable", "true");
                var id = attrs.id;
                if (!attrs.id) {
                    id = uuid.new()
                    angular.element(el).attr("id", id);
                }

                el.bind("dragstart", function(e) {
                    e.dataTransfer.setData('text', id);

                    $rootScope.$emit("LVL-DRAG-START");
                });

                el.bind("dragend", function(e) {
                    $rootScope.$emit("LVL-DRAG-END");
                });
            }
        }
    }]);

module.directive('lvlDropTarget', ['$rootScope', 'uuid', function($rootScope, uuid) {
        return {
            restrict: 'A',
            scope: {
                onDrop: '&'
            },
            link: function(scope, el, attrs, controller) {
                var id = attrs.id;
                if (!attrs.id) {
                    id = uuid.new()
                    angular.element(el).attr("id", id);
                }

                el.bind("dragover", function(e) {
                  if (e.preventDefault) {
                    e.preventDefault(); // Necessary. Allows us to drop.
                  }

                  e.dataTransfer.dropEffect = 'move';  // See the section on the DataTransfer object.
                  return false;
                });

                el.bind("dragenter", function(e) {
                  // this / e.target is the current hover target.
                  angular.element(e.target).addClass('lvl-over');
                });

                el.bind("dragleave", function(e) {
                  angular.element(e.target).removeClass('lvl-over');  // this / e.target is previous target element.
                });

                el.bind("drop", function(e) {
                  if (e.preventDefault) {
                    e.preventDefault(); // Necessary. Allows us to drop.
                  }

                  if (e.stopPropagation) {
                    e.stopPropagation(); // Necessary. Allows us to drop.
                  }
                    var data = e.dataTransfer.getData("text");
                    var dest = document.getElementById(id);
                    var src = document.getElementById(data);

                    scope.onDrop({dragEl: src, dropEl: dest});
                });

                $rootScope.$on("LVL-DRAG-START", function() {
                    var el = document.getElementById(id);
                    angular.element(el).addClass("lvl-target");
                });

                $rootScope.$on("LVL-DRAG-END", function() {
                    var el = document.getElementById(id);
                    angular.element(el).removeClass("lvl-target");
                    angular.element(el).removeClass("lvl-over");
                });
            }
        }
    }]);

UUID service

angular
.module('lvl.services',[])
.factory('uuid', function() {
    var svc = {
        new: function() {
            function _p8(s) {
                var p = (Math.random().toString(16)+"000000000").substr(2,8);
                return s ? "-" + p.substr(0,4) + "-" + p.substr(4,4) : p ;
            }
            return _p8() + _p8(true) + _p8(true) + _p8();
        },

        empty: function() {
          return '00000000-0000-0000-0000-000000000000';
        }
    };

    return svc;
});

Git: Pull from other remote

git pull is really just a shorthand for git pull <remote> <branchname>, in most cases it's equivalent to git pull origin master. You will need to add another remote and pull explicitly from it. This page describes it in detail:

http://help.github.com/forking/

C++ unordered_map using a custom class type as the key

check the following link https://www.geeksforgeeks.org/how-to-create-an-unordered_map-of-user-defined-class-in-cpp/ for more details.

  • the custom class must implement the == operator
  • must create a hash function for the class (for primitive types like int and also types like string the hash function is predefined)

Using multiple property files (via PropertyPlaceholderConfigurer) in multiple projects/modules

I tried the solution below, it works on my machine.

<context:property-placeholder location="classpath*:connection.properties" ignore-unresolvable="true" order="1" />

<context:property-placeholder location="classpath*:general.properties" order="2"/>

In case multiple elements are present in the Spring context, there are a few best practices that should be followed:

the order attribute needs to be specified to fix the order in which these are processed by Spring all property placeholders minus the last one (highest order) should have ignore-unresolvable=”true” to allow the resolution mechanism to pass to others in the context without throwing an exception

source: http://www.baeldung.com/2012/02/06/properties-with-spring/

What's the difference between align-content and align-items?

according to what I understood from here:

when you use align-item or justify-item, you are adjusting "the content inside a grid item along the column axis or row axis respectively.

But: if you use align-content or justify-content, you are setting the position a grid along the column axis or the row axis. it occurs when you have a grid in a bigger container and width or height are inflexible (using px).

Conversion of System.Array to List

I hope this is helpful.

enum TESTENUM
    {
        T1 = 0,
        T2 = 1,
        T3 = 2,
        T4 = 3
    }

get string value

string enumValueString = "T1";

        List<string> stringValueList =  typeof(TESTENUM).GetEnumValues().Cast<object>().Select(m => 
            Convert.ToString(m)
            ).ToList();

        if(!stringValueList.Exists(m => m == enumValueString))
        {
            throw new Exception("cannot find type");
        }

        TESTENUM testEnumValueConvertString;
        Enum.TryParse<TESTENUM>(enumValueString, out testEnumValueConvertString);

get integer value

        int enumValueInt = 1;

        List<int> enumValueIntList =  typeof(TESTENUM).GetEnumValues().Cast<object>().Select(m =>
            Convert.ToInt32(m)
            ).ToList();

        if(!enumValueIntList.Exists(m => m == enumValueInt))
        {
            throw new Exception("cannot find type");
        }

        TESTENUM testEnumValueConvertInt;
        Enum.TryParse<TESTENUM>(enumValueString, out testEnumValueConvertInt);

Android: Test Push Notification online (Google Cloud Messaging)

Postman is a good solution and so is php fiddle. However to avoid putting in the GCM URL and the header information every time, you can also use this nifty GCM Notification Test Tool

Where can I find MySQL logs in phpMyAdmin?

Open your PHPMyAdmin, don't select any database and look for Binary Log tab . You can select different logs from a drop down list and press GO Button to view them.

How do I check whether input string contains any spaces?

A simple answer, along similar lines to the previous ones is:

str.matches(".*\\s.*")
  • The first ".*" says that there can be zero or more instances of any character in front of the space.
  • The "\\s" says it must contain any whitespace character.
  • The last ".*" says there can be zero or more instances of any character after the space.

When you put all those together, this returns true if there are one or more whitespace characters anywhere in the string.

Here is a simple test you can run to benchmark your solution against:

boolean containsWhitespace(String str){
    return str.matches(".*\\s.*");
}

String[] testStrings = {"test", " test", "te st", "test ", "te   st", 
                        " t e s t ", " ", "", "\ttest"};
for (String eachString : testStrings) {
        System.out.println( "Does \"" + eachString + "\" contain whitespace? " + 
                             containsWhitespace(eachString));
}

sys.stdin.readline() reads without prompt, returning 'nothing in between'

stdin.read(1)

will not return when you press one character - it will wait for '\n'. The problem is that the second character is buffered in standard input, and the moment you call another input - it will return immediately because it gets its input from buffer.

How to get WooCommerce order details

ONLY FOR WOOCOMMERCE VERSIONS 2.5.x AND 2.6.x

For WOOCOMMERCE VERSION 3.0+ see THIS UPDATE

Here is a custom function I have made, to make the things clear for you, related to get the data of an order ID. You will see all the different RAW outputs you can get and how to get the data you need…

Using print_r() function (or var_dump() function too) allow to output the raw data of an object or an array.

So first I output this data to show the object or the array hierarchy. Then I use different syntax depending on the type of that variable (string, array or object) to output the specific data needed.

IMPORTANT: With $order object you can use most of WC_order or WC_Abstract_Order methods (using the object syntax)…


Here is the code:

function get_order_details($order_id){

    // 1) Get the Order object
    $order = wc_get_order( $order_id );

    // OUTPUT
    echo '<h3>RAW OUTPUT OF THE ORDER OBJECT: </h3>';
    print_r($order);
    echo '<br><br>';
    echo '<h3>THE ORDER OBJECT (Using the object syntax notation):</h3>';
    echo '$order->order_type: ' . $order->order_type . '<br>';
    echo '$order->id: ' . $order->id . '<br>';
    echo '<h4>THE POST OBJECT:</h4>';
    echo '$order->post->ID: ' . $order->post->ID . '<br>';
    echo '$order->post->post_author: ' . $order->post->post_author . '<br>';
    echo '$order->post->post_date: ' . $order->post->post_date . '<br>';
    echo '$order->post->post_date_gmt: ' . $order->post->post_date_gmt . '<br>';
    echo '$order->post->post_content: ' . $order->post->post_content . '<br>';
    echo '$order->post->post_title: ' . $order->post->post_title . '<br>';
    echo '$order->post->post_excerpt: ' . $order->post->post_excerpt . '<br>';
    echo '$order->post->post_status: ' . $order->post->post_status . '<br>';
    echo '$order->post->comment_status: ' . $order->post->comment_status . '<br>';
    echo '$order->post->ping_status: ' . $order->post->ping_status . '<br>';
    echo '$order->post->post_password: ' . $order->post->post_password . '<br>';
    echo '$order->post->post_name: ' . $order->post->post_name . '<br>';
    echo '$order->post->to_ping: ' . $order->post->to_ping . '<br>';
    echo '$order->post->pinged: ' . $order->post->pinged . '<br>';
    echo '$order->post->post_modified: ' . $order->post->post_modified . '<br>';
    echo '$order->post->post_modified_gtm: ' . $order->post->post_modified_gtm . '<br>';
    echo '$order->post->post_content_filtered: ' . $order->post->post_content_filtered . '<br>';
    echo '$order->post->post_parent: ' . $order->post->post_parent . '<br>';
    echo '$order->post->guid: ' . $order->post->guid . '<br>';
    echo '$order->post->menu_order: ' . $order->post->menu_order . '<br>';
    echo '$order->post->post_type: ' . $order->post->post_type . '<br>';
    echo '$order->post->post_mime_type: ' . $order->post->post_mime_type . '<br>';
    echo '$order->post->comment_count: ' . $order->post->comment_count . '<br>';
    echo '$order->post->filter: ' . $order->post->filter . '<br>';
    echo '<h4>THE ORDER OBJECT (again):</h4>';
    echo '$order->order_date: ' . $order->order_date . '<br>';
    echo '$order->modified_date: ' . $order->modified_date . '<br>';
    echo '$order->customer_message: ' . $order->customer_message . '<br>';
    echo '$order->customer_note: ' . $order->customer_note . '<br>';
    echo '$order->post_status: ' . $order->post_status . '<br>';
    echo '$order->prices_include_tax: ' . $order->prices_include_tax . '<br>';
    echo '$order->tax_display_cart: ' . $order->tax_display_cart . '<br>';
    echo '$order->display_totals_ex_tax: ' . $order->display_totals_ex_tax . '<br>';
    echo '$order->display_cart_ex_tax: ' . $order->display_cart_ex_tax . '<br>';
    echo '$order->formatted_billing_address->protected: ' . $order->formatted_billing_address->protected . '<br>';
    echo '$order->formatted_shipping_address->protected: ' . $order->formatted_shipping_address->protected . '<br><br>';
    echo '- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - <br><br>';

    // 2) Get the Order meta data
    $order_meta = get_post_meta($order_id);

    echo '<h3>RAW OUTPUT OF THE ORDER META DATA (ARRAY): </h3>';
    print_r($order_meta);
    echo '<br><br>';
    echo '<h3>THE ORDER META DATA (Using the array syntax notation):</h3>';
    echo '$order_meta[_order_key][0]: ' . $order_meta[_order_key][0] . '<br>';
    echo '$order_meta[_order_currency][0]: ' . $order_meta[_order_currency][0] . '<br>';
    echo '$order_meta[_prices_include_tax][0]: ' . $order_meta[_prices_include_tax][0] . '<br>';
    echo '$order_meta[_customer_user][0]: ' . $order_meta[_customer_user][0] . '<br>';
    echo '$order_meta[_billing_first_name][0]: ' . $order_meta[_billing_first_name][0] . '<br><br>';
    echo 'And so on ……… <br><br>';
    echo '- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - <br><br>';

    // 3) Get the order items
    $items = $order->get_items();

    echo '<h3>RAW OUTPUT OF THE ORDER ITEMS DATA (ARRAY): </h3>';

    foreach ( $items as $item_id => $item_data ) {

        echo '<h4>RAW OUTPUT OF THE ORDER ITEM NUMBER: '. $item_id .'): </h4>';
        print_r($item_data);
        echo '<br><br>';
        echo 'Item ID: ' . $item_id. '<br>';
        echo '$item_data["product_id"] <i>(product ID)</i>: ' . $item_data['product_id'] . '<br>';
        echo '$item_data["name"] <i>(product Name)</i>: ' . $item_data['name'] . '<br>';

        // Using get_item_meta() method
        echo 'Item quantity <i>(product quantity)</i>: ' . $order->get_item_meta($item_id, '_qty', true) . '<br><br>';
        echo 'Item line total <i>(product quantity)</i>: ' . $order->get_item_meta($item_id, '_line_total', true) . '<br><br>';
        echo 'And so on ……… <br><br>';
        echo '- - - - - - - - - - - - - <br><br>';
    }
    echo '- - - - - - E N D - - - - - <br><br>';
}

Code goes in function.php file of your active child theme (or theme) or also in any plugin file.

Usage (if your order ID is 159 for example):

get_order_details(159);

This code is tested and works.

Updated code on November 21, 2016

What is a callback?

A callback is a function that will be called when a process is done executing a specific task.

The usage of a callback is usually in asynchronous logic.

To create a callback in C#, you need to store a function address inside a variable. This is achieved using a delegate or the new lambda semantic Func or Action.

    public delegate void WorkCompletedCallBack(string result);

    public void DoWork(WorkCompletedCallBack callback)
    {
        callback("Hello world");
    }

    public void Test()
    {
        WorkCompletedCallBack callback = TestCallBack; // Notice that I am referencing a method without its parameter
        DoWork(callback);
    }

    public void TestCallBack(string result)
    {
        Console.WriteLine(result);
    }

In today C#, this could be done using lambda like:

    public void DoWork(Action<string> callback)
    {
        callback("Hello world");
    }

    public void Test()
    {
        DoWork((result) => Console.WriteLine(result));
    }

Allow User to input HTML in ASP.NET MVC - ValidateInput or AllowHtml

You Can Use [AllowHtml] To Your Project For Example

 [AllowHtml]
 public string Description { get; set; }

For Use This Code To Class Library You Instal This Package

Install-Package Microsoft.AspNet.Mvc

After Use This using

using System.Web.Mvc;

Remove privileges from MySQL database

As a side note, the reason revoke usage on *.* from 'phpmyadmin'@'localhost'; does not work is quite simple : There is no grant called USAGE.

The actual named grants are in the MySQL Documentation

The grant USAGE is a logical grant. How? 'phpmyadmin'@'localhost' has an entry in mysql.user where user='phpmyadmin' and host='localhost'. Any row in mysql.user semantically means USAGE. Running DROP USER 'phpmyadmin'@'localhost'; should work just fine. Under the hood, it's really doing this:

DELETE FROM mysql.user WHERE user='phpmyadmin' and host='localhost';
DELETE FROM mysql.db   WHERE user='phpmyadmin' and host='localhost';
FLUSH PRIVILEGES;

Therefore, the removal of a row from mysql.user constitutes running REVOKE USAGE, even though REVOKE USAGE cannot literally be executed.

How to read multiple Integer values from a single line of input in Java?

Using BufferedReader -

StringTokenizer st = new StringTokenizer(buf.readLine());

while(st.hasMoreTokens())
{
  arr[i++] = Integer.parseInt(st.nextToken());
}

Hiding and Showing TabPages in tabControl

There are at least two ways to code a solution in software... Thanks for posting answers. Just wanted to update this with another version. A TabPage array is used to shadow the Tab Control. During the Load event, the TabPages in the TabControl are copied to the shadow array. Later, this shadow array is used as the source to copy the TabPages into the TabControl...and in the desired presentation order.

    Private tabControl1tabPageShadow() As TabPage = Nothing

    Private Sub Form2_DailyReportPackageViewer_Load(sender As Object, e As EventArgs) Handles Me.Load
        LoadTabPageShadow()
    End Sub


    Private Sub LoadTabPageShadow()
        ReDim tabControl1tabPageShadow(TabControl1.TabPages.Count - 1)
        For Each tabPage In TabControl1.TabPages
            tabControl1tabPageShadow(tabPage.TabIndex) = tabPage
        Next
    End Sub

    Private Sub ViewAllReports(sender As Object, e As EventArgs) Handles Button8.Click
        TabControl1.TabPages.Clear()
        For Each tabPage In tabControl1tabPageShadow
            TabControl1.TabPages.Add(tabPage)
        Next
    End Sub


    Private Sub ViewOperationsReports(sender As Object, e As EventArgs) Handles Button10.Click
        TabControl1.TabPages.Clear()

        For tabCount As Integer = 0 To 9
            For Each tabPage In tabControl1tabPageShadow
                Select Case tabPage.Text
                    Case "Overview"
                        If tabCount = 0 Then TabControl1.TabPages.Add(tabPage)
                    Case "Production Days Under 110%"
                        If tabCount = 1 Then TabControl1.TabPages.Add(tabPage)
                    Case "Screening Status"
                        If tabCount = 2 Then TabControl1.TabPages.Add(tabPage)
                    Case "Rework Status"
                        If tabCount = 3 Then TabControl1.TabPages.Add(tabPage)
                    Case "Secondary by Machine"
                        If tabCount = 4 Then TabControl1.TabPages.Add(tabPage)
                    Case "Secondary Set Ups"
                        If tabCount = 5 Then TabControl1.TabPages.Add(tabPage)
                    Case "Secondary Run Times"
                        If tabCount = 6 Then TabControl1.TabPages.Add(tabPage)
                    Case "Primary Set Ups"
                        If tabCount = 7 Then TabControl1.TabPages.Add(tabPage)
                    Case "Variance"
                        If tabCount = 8 Then TabControl1.TabPages.Add(tabPage)
                    Case "Schedule Changes"
                        If tabCount = 9 Then TabControl1.TabPages.Add(tabPage)
                End Select
            Next
        Next


Is there a way to specify a max height or width for an image?

You could use some CSS and with the idea of kbrimington it should do the trick.

The CSS could be like this.

img {
  width:  75px;
  height: auto;
}

I got it from here: another post

How to get numbers after decimal point?

similar to the accepted answer, even easier approach using strings would be

def number_after_decimal(number1):
    number = str(number1)
    if 'e-' in number: # scientific notation
        number_dec = format(float(number), '.%df'%(len(number.split(".")[1].split("e-")[0])+int(number.split('e-')[1])))
    elif "." in number: # quick check if it is decimal
        number_dec = number.split(".")[1]
    return number_dec

How to remove title bar from the android activity?

Add in activity

requestWindowFeature(Window.FEATURE_NO_TITLE);

and add your style.xml file with the following two lines:

<item name="windowActionBar">false</item>
<item name="windowNoTitle">true</item>

How can I analyze a heap dump in IntelliJ? (memory leak)

You can just run "Java VisualVM" which is located at jdk/bin/jvisualvm.exe

This will open a GUI, use the "File" menu -> "Load..." then choose your *.hprof file

That's it, you're done!

Checking for #N/A in Excel cell from VBA code

First check for an error (N/A value) and then try the comparisation against cvErr(). You are comparing two different things, a value and an error. This may work, but not always. Simply casting the expression to an error may result in similar problems because it is not a real error only the value of an error which depends on the expression.

If IsError(ActiveWorkbook.Sheets("Publish").Range("G4").offset(offsetCount, 0).Value) Then
  If (ActiveWorkbook.Sheets("Publish").Range("G4").offset(offsetCount, 0).Value <> CVErr(xlErrNA)) Then
    'do something
  End If
End If

Line break (like <br>) using only css

It works like this:

h4 {
    display:inline;
}
h4:after {
    content:"\a";
    white-space: pre;
}

Example: http://jsfiddle.net/Bb2d7/

The trick comes from here: https://stackoverflow.com/a/66000/509752 (to have more explanation)

Spring AMQP + RabbitMQ 3.3.5 ACCESS_REFUSED - Login was refused using authentication mechanism PLAIN

To complete @cpu-100 answer,

in case you don't want to enable/use web interface, you can create a new credentials using command line like below and use it in your code to connect to RabbitMQ.

$ rabbitmqctl add_user YOUR_USERNAME YOUR_PASSWORD
$ rabbitmqctl set_user_tags YOUR_USERNAME administrator
$ rabbitmqctl set_permissions -p / YOUR_USERNAME ".*" ".*" ".*"

Undo git pull, how to bring repos to old state

If you have gitk (try running "gitk --all from your git command line"), it's simple. Just run it, select the commit you want to rollback to (right-click), and select "Reset master branch to here". If you have no uncommited changes, chose the "hard" option.

How to see top processes sorted by actual memory usage?

You can see memory usage by executing this code in your terminal:

$ watch -n2 free -m
$ htop

Beautiful way to remove GET-variables with PHP?

In my opinion, the best way would be this:

<? if(isset($_GET['i'])){unset($_GET['i']); header('location:/');} ?>

It checks if there is an 'i' GET parameter, and removes it if there is.

Modifying CSS class property values on the fly with JavaScript / jQuery

This solution modifies Cycne's to use ES6 syntax and exit the loop early for external stylesheets. This solution does not modify external stylesheets

_x000D_
_x000D_
function changeStyle(findSelector, newDeclarations) {_x000D_
    // Change original css style declaration._x000D_
    document.styleSheets.forEach((sheet) => {_x000D_
      if (sheet.href) return;_x000D_
      const cssRulesList = sheet.cssRules;_x000D_
      cssRulesList.forEach((styleRule) => {_x000D_
        if (styleRule.selectorText === findSelector) {_x000D_
          Object.keys(newDeclarations).forEach((cssProp) => {_x000D_
            styleRule.style[cssProp] = newDeclarations[cssProp];_x000D_
          });_x000D_
        }_x000D_
      });_x000D_
    });_x000D_
  }_x000D_
_x000D_
  const styleDeclarations = {_x000D_
    'width': '200px',_x000D_
    'height': '400px',_x000D_
    'color': '#F00'_x000D_
  };_x000D_
  changeStyle('.paintBox', styleDeclarations);
_x000D_
_x000D_
_x000D_

You must also have at least one style tag in your HTML head section, for example

<style> .paintBox {background-color: white;}</style>

Does IMDB provide an API?

https://deanclatworthy.com/tools.html is an IMDB API but has been down due to abuse.

In MySQL, can I copy one row to insert into the same table?

You almost had it with the your first query you just need to specify the columns, that way you can exclude your primary key in the insert which will enact the auto-increment you likely have on the table to automatically create a new primary key for the entry.

For example change this:

insert into table select * from table where primarykey=1

To this:

INSERT INTO table (col1, col2, col3) 
SELECT col1, col2, col3 
FROM table 
WHERE primarykey = 1

Just don't include the primarykey column in either the column list for the INSERT or for the SELECT portions of the query.

How do I Set Background image in Flutter?

You can use FractionallySizedBox

Sometimes decoratedBox doesn't cover the full-screen size. We can fix it by wrapping it with FractionallySizedBox Widget. In this widget we give widthfactor and heightfactor.

The widthfactor shows the [FractionallySizedBox]widget should take _____ percentage of the app's width.

The heightfactor shows the [FractionallySizedBox]widget should take _____ percentage of the app's height.

Example : heightfactor = 0.3 means 30% of app's height. widthfactor = 0.4 means 40% of app's width.

        Hence, for full screen set heightfactor = 1.0 and widthfactor = 1.0

Tip: FractionallySizedBox goes well with the stack widget. So that you can easily add buttons, avatars, texts over your background image in the stack widget whereas in rows and columns you cannot do that.

For more info check out this project's repository github repository link for this project

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        body: SafeArea(
          child: Stack(
            children: <Widget>[
              Container(
                child: FractionallySizedBox(
                  heightFactor: 1.0,
                  widthFactor: 1.0,
                  //for full screen set heightFactor: 1.0,widthFactor: 1.0,
                  child: DecoratedBox(
                    decoration: BoxDecoration(
                      image: DecorationImage(
                        image: AssetImage("images/1.jpg"),
                        fit: BoxFit.fill,
                      ),
                    ),
                  ),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
}



OutPut: enter image description here

LISTAGG function: "result of string concatenation is too long"

Short of using 12c overflow using the CLOB and substr will also work

rtrim(dbms_lob.substr(XMLAGG(XMLELEMENT(E,column_name,',').EXTRACT('//text()') ORDER BY column_name).GetClobVal(),1000,1),',')

npm install error - MSB3428: Could not load the Visual C++ component "VCBuild.exe"

1)install "lite server" and then try below command :
npm run lite

Convert String to double in Java

Try this, BigDecimal bdVal = new BigDecimal(str);

If you want Double only then try Double d = Double.valueOf(str); System.out.println(String.format("%.3f", new BigDecimal(d)));

How to read and write INI file with Python3?

There are some problems I found when used configparser such as - I got an error when I tryed to get value from param:

destination=\my-server\backup$%USERNAME%

It was because parser can't get this value with special character '%'. And then I wrote a parser for reading ini files based on 're' module:

import re

# read from ini file.
def ini_read(ini_file, key):
    value = None
    with open(ini_file, 'r') as f:
        for line in f:
            match = re.match(r'^ *' + key + ' *= *.*$', line, re.M | re.I)
            if match:
                value = match.group()
                value = re.sub(r'^ *' + key + ' *= *', '', value)
                break
    return value


# read value for a key 'destination' from 'c:/myconfig.ini'
my_value_1 = ini_read('c:/myconfig.ini', 'destination')

# read value for a key 'create_destination_folder' from 'c:/myconfig.ini'
my_value_2 = ini_read('c:/myconfig.ini', 'create_destination_folder')


# write to an ini file.
def ini_write(ini_file, key, value, add_new=False):
    line_number = 0
    match_found = False
    with open(ini_file, 'r') as f:
        lines = f.read().splitlines()
    for line in lines:
        if re.match(r'^ *' + key + ' *= *.*$', line, re.M | re.I):
            match_found = True
            break
        line_number += 1
    if match_found:
        lines[line_number] = key + ' = ' + value
        with open(ini_file, 'w') as f:
            for line in lines:
                f.write(line + '\n')
        return True
    elif add_new:
        with open(ini_file, 'a') as f:
            f.write(key + ' = ' + value)
        return True
    return False


# change a value for a key 'destination'.
ini_write('my_config.ini', 'destination', '//server/backups$/%USERNAME%')

# change a value for a key 'create_destination_folder'
ini_write('my_config.ini', 'create_destination_folder', 'True')

# to add a new key, we need to use 'add_new=True' option.
ini_write('my_config.ini', 'extra_new_param', 'True', True)

Use of symbols '@', '&', '=' and '>' in custom directive's scope binding: AngularJS

I had trouble binding a value with any of the symbols in AngularJS 1.6. I did not get any value at all, only undefined, even though I did it the exact same way as other bindings in the same file that did work.

Problem was: my variable name had an underscore.

This fails:

bindings: { import_nr: '='}

This works:

bindings: { importnr: '='}

(Not completely related to the original question, but that was one of the top search results when I looked, so hopefully this helps someone with the same problem.)

How to submit an HTML form without redirection

See jQuery's post function.

I would create a button, and set an onClickListener ($('#button').on('click', function(){});), and send the data in the function.

Also, see the preventDefault function, of jQuery!

How to write a CSS hack for IE 11?

You can use the following code inside the style tag:

@media screen and (-ms-high-contrast: active), (-ms-high-contrast: none) {  
/* IE10+ specific styles go here */  
}

Below is an example that worked for me:

<style type="text/css">

@media screen and (-ms-high-contrast: active), (-ms-high-contrast: none) {  
   /* IE10+ specific styles go here */  
   #flashvideo {
        width:320px;
        height:240;
        margin:-240px 0 0 350px;
        float:left;
    }

    #googleMap {
        width:320px;
        height:240;
        margin:-515px 0 0 350px;
        float:left;
        border-color:#000000;
    }
}

#nav li {
    list-style:none;
    width:240px;
    height:25px;
    }

#nav a {
    display:block;
    text-indent:-5000px;
    height:25px;
    width:240px;
    }
</style>

Please note that since (#nav li) and (#nav a) are outside of the @media screen ..., they are general styles.

log4j:WARN No appenders could be found for logger in web.xml

Or, you could be doing what I did and define the logger before the log configuration file has been loaded. This would be as they say: "Putting the cart before the horse."

In the code:

public static Logger logger = Logger.getLogger("RbReport");

... later on

PropertyConfigurator.configure(l4j);
logger = Logger.getLogger("RbReport");

Fix was to initialize the logger after the configuration was loaded.

For the geeks it was "Putting Descarte b4 d horse".

git rm - fatal: pathspec did not match any files

git stash 

did the job, It restored the files that I had deleted using rm instead of git rm.

I did first a checkout of the last hash, but I do not believe it is required.

Entity Framework Core: DbContextOptionsBuilder does not contain a definition for 'usesqlserver' and no extension method 'usesqlserver'

For anyone still having this problem: Use NuGet to install: Microsoft.EntityFrameworkCore.Proxies

This problem is related to the use of Castle Proxy with EFCore.

How do I request a file but not save it with Wget?

Use q flag for quiet mode, and tell wget to output to stdout with O- (uppercase o) and redirect to /dev/null to discard the output:

wget -qO- $url &> /dev/null

> redirects application output (to a file). if > is preceded by ampersand, shell redirects all outputs (error and normal) to the file right of >. If you don't specify ampersand, then only normal output is redirected.

./app &>  file # redirect error and standard output to file
./app >   file # redirect standard output to file
./app 2>  file # redirect error output to file

if file is /dev/null then all is discarded.

This works as well, and simpler:

wget -O/dev/null -q $url

Why maven? What are the benefits?

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

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

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

Facebook Graph API, how to get users email?

For me the problem with collecting user's email addres on PHP side (getGraphUser() method) was, that the default behavior of facebook-rendered button (on WEBSIDE side, created with xfbml=1) is to implicity calling FB.login() with the scope NOT including "email".

That means you MUST:

1) call


FB.login(....,{scope: email})

manifestly, creating your own button to start login process

OR

2) add scope="email" attribute to the xfbml button


<div class="fb-login-button" data-size="large" data-button-type="continue_with" data-
layout="rounded" data-auto-logout-link="false" data-use-continue-as="true" data-
width="1000px" scope="email"></div>

to be able to collect email address on PHP side.

Hope it helps.

LINQ .Any VS .Exists - What's the difference?

As a continuation on Matas' answer on benchmarking.

TL/DR: Exists() and Any() are equally fast.

First off: Benchmarking using Stopwatch is not precise (see series0ne's answer on a different, but similiar, topic), but it is far more precise than DateTime.

The way to get really precise readings is by using Performance Profiling. But one way to get a sense of how the two methods' performance measure up to each other is by executing both methods loads of times and then comparing the fastest execution time of each. That way, it really doesn't matter that JITing and other noise gives us bad readings (and it does), because both executions are "equally misguiding" in a sense.

static void Main(string[] args)
    {
        Console.WriteLine("Generating list...");
        List<string> list = GenerateTestList(1000000);
        var s = string.Empty;

        Stopwatch sw;
        Stopwatch sw2;
        List<long> existsTimes = new List<long>();
        List<long> anyTimes = new List<long>();

        Console.WriteLine("Executing...");
        for (int j = 0; j < 1000; j++)
        {
            sw = Stopwatch.StartNew();
            if (!list.Exists(o => o == "0123456789012"))
            {
                sw.Stop();
                existsTimes.Add(sw.ElapsedTicks);
            }
        }

        for (int j = 0; j < 1000; j++)
        {
            sw2 = Stopwatch.StartNew();
            if (!list.Exists(o => o == "0123456789012"))
            {
                sw2.Stop();
                anyTimes.Add(sw2.ElapsedTicks);
            }
        }

        long existsFastest = existsTimes.Min();
        long anyFastest = anyTimes.Min();

        Console.WriteLine(string.Format("Fastest Exists() execution: {0} ticks\nFastest Any() execution: {1} ticks", existsFastest.ToString(), anyFastest.ToString()));
        Console.WriteLine("Benchmark finished. Press any key.");
        Console.ReadKey();
    }

    public static List<string> GenerateTestList(int count)
    {
        var list = new List<string>();
        for (int i = 0; i < count; i++)
        {
            Random r = new Random();
            int it = r.Next(0, 100);
            list.Add(new string('s', it));
        }
        return list;
    }

After executing the above code 4 times (which in turn do 1 000 Exists() and Any() on a list with 1 000 000 elements), it's not hard to see that the methods are pretty much equally fast.

Fastest Exists() execution: 57881 ticks
Fastest Any() execution: 58272 ticks

Fastest Exists() execution: 58133 ticks
Fastest Any() execution: 58063 ticks

Fastest Exists() execution: 58482 ticks
Fastest Any() execution: 58982 ticks

Fastest Exists() execution: 57121 ticks
Fastest Any() execution: 57317 ticks

There is a slight difference, but it's too small a difference to not be explained by background noise. My guess would be that if one would do 10 000 or 100 000 Exists() and Any() instead, that slight difference would disappear more or less.

Get output parameter value in ADO.NET

The other response shows this, but essentially you just need to create a SqlParameter, set the Direction to Output, and add it to the SqlCommand's Parameters collection. Then execute the stored procedure and get the value of the parameter.

Using your code sample:

// SqlConnection and SqlCommand are IDisposable, so stack a couple using()'s
using (SqlConnection conn = new SqlConnection(connectionString))
using (SqlCommand cmd = new SqlCommand("sproc", conn))
{
   // Create parameter with Direction as Output (and correct name and type)
   SqlParameter outputIdParam = new SqlParameter("@ID", SqlDbType.Int)
   { 
      Direction = ParameterDirection.Output 
   };

   cmd.CommandType = CommandType.StoredProcedure;
   cmd.Parameters.Add(outputIdParam);

   conn.Open();
   cmd.ExecuteNonQuery();

   // Some various ways to grab the output depending on how you would like to
   // handle a null value returned from the query (shown in comment for each).

   // Note: You can use either the SqlParameter variable declared
   // above or access it through the Parameters collection by name:
   //   outputIdParam.Value == cmd.Parameters["@ID"].Value

   // Throws FormatException
   int idFromString = int.Parse(outputIdParam.Value.ToString());

   // Throws InvalidCastException
   int idFromCast = (int)outputIdParam.Value; 

   // idAsNullableInt remains null
   int? idAsNullableInt = outputIdParam.Value as int?; 

   // idOrDefaultValue is 0 (or any other value specified to the ?? operator)
   int idOrDefaultValue = outputIdParam.Value as int? ?? default(int); 

   conn.Close();
}

Be careful when getting the Parameters[].Value, since the type needs to be cast from object to what you're declaring it as. And the SqlDbType used when you create the SqlParameter needs to match the type in the database. If you're going to just output it to the console, you may just be using Parameters["@Param"].Value.ToString() (either explictly or implicitly via a Console.Write() or String.Format() call).

EDIT: Over 3.5 years and almost 20k views and nobody had bothered to mention that it didn't even compile for the reason specified in my "be careful" comment in the original post. Nice. Fixed it based on good comments from @Walter Stabosz and @Stephen Kennedy and to match the update code edit in the question from @abatishchev.

How to both read and write a file in C#

Made an improvement code by @Ipsita - for use asynchronous read\write file I/O

readonly string logPath = @"FilePath";
...
public async Task WriteToLogAsync(string dataToWrite)
{
    TextReader tr = new StreamReader(logPath);
    string data = await tr.ReadLineAsync();
    tr.Close();

    TextWriter tw = new StreamWriter(logPath);
    await tw.WriteLineAsync(data + dataToWrite);
    tw.Close();
}
...
await WriteToLogAsync("Write this to file");

How do I split an int into its digits?

I don't necessarily recommend this (it's more efficient to work with the number rather than converting it to a string), but it's easy and it works :)

#include <algorithm>
#include <iostream>
#include <iterator>
#include <string>

#include <boost/lexical_cast.hpp>

int main()
{
    int n = 23984;
    std::string s = boost::lexical_cast<std::string>(n);
    std::copy(s.begin(), s.end(), std::ostream_iterator<char>(std::cout, "\n"));
    return 0;
}

Cannot start GlassFish 4.1 from within Netbeans 8.0.1 Service area

You will get like this error

error ss

Try the following steps

1. Open Command Prompt (Press Windows key and type "cmd" and hit Enter) Then type this command as show in picture

netstat -aon | find ":8080" | find "LISTENING" cmd command

  1. Now open Task Manager (Press Windows key and type "Task Manager" and hit Enter) In that, go to Details Tab and under PID Column, search for the number you found in cmd

task manager

  1. Right Click on that program and select end process

How do I set a value in CKEditor with Javascript?

Sets the editor data. The data must be provided in the raw format (HTML). CKEDITOR.instances.editor1.setData( 'Put your Data.' ); refer this page

Internet Explorer 11 disable "display intranet sites in compatibility view" via meta tag not working

For those who are building an ASP.NET MVC project, make sure that you add the:

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

tag into your Layout (template) page. I just spent two hours debugging and tweaking, only to realize that I had only added that meta tag into my child pages. As soon as I added it to my layout page, the browser loaded in EDGE mode perfectly.

Using Excel VBA to run SQL query

Below is code that I currently use to pull data from a MS SQL Server 2008 into VBA. You need to make sure you have the proper ADODB reference [VBA Editor->Tools->References] and make sure you have Microsoft ActiveX Data Objects 2.8 Library checked, which is the second from the bottom row that is checked (I'm using Excel 2010 on Windows 7; you might have a slightly different ActiveX version, but it will still begin with Microsoft ActiveX):

References required for SQL

Sub Module for Connecting to MS SQL with Remote Host & Username/Password

Sub Download_Standard_BOM()
'Initializes variables
Dim cnn As New ADODB.Connection
Dim rst As New ADODB.Recordset
Dim ConnectionString As String
Dim StrQuery As String

'Setup the connection string for accessing MS SQL database
   'Make sure to change:
       '1: PASSWORD
       '2: USERNAME
       '3: REMOTE_IP_ADDRESS
       '4: DATABASE
    ConnectionString = "Provider=SQLOLEDB.1;Password=PASSWORD;Persist Security Info=True;User ID=USERNAME;Data Source=REMOTE_IP_ADDRESS;Use Procedure for Prepare=1;Auto Translate=True;Packet Size=4096;Use Encryption for Data=False;Tag with column collation when possible=False;Initial Catalog=DATABASE"

    'Opens connection to the database
    cnn.Open ConnectionString
    'Timeout error in seconds for executing the entire query; this will run for 15 minutes before VBA timesout, but your database might timeout before this value
    cnn.CommandTimeout = 900

    'This is your actual MS SQL query that you need to run; you should check this query first using a more robust SQL editor (such as HeidiSQL) to ensure your query is valid
    StrQuery = "SELECT TOP 10 * FROM tbl_table"

    'Performs the actual query
    rst.Open StrQuery, cnn
    'Dumps all the results from the StrQuery into cell A2 of the first sheet in the active workbook
    Sheets(1).Range("A2").CopyFromRecordset rst
End Sub

Understanding checked vs unchecked exceptions in Java

1) No, a NumberFormatException is an unchecked Exception. Even though you caught it (you aren't required to) because it's unchecked. This is because it is a subclass of IllegalArgumentException which is a subclass of RuntimeException.

2) RuntimeException is the root of all unchecked Exceptions. Every subclass of RuntimeException is unchecked. All other Exceptions and Throwable are checked except for Errors ( Which comes under Throwable).

3/4) You could alert the user that they picked a non-existent file and ask for a new one. Or just quit informing the user that they entered something invalid.

5) Throwing and catching 'Exception' is bad practice. But more generally, you might throw other exceptions so the caller can decide how to deal with it. For example, if you wrote a library to handle reading some file input and your method was passed a non-existent file, you have no idea how to handle that. Does the caller want to ask again or quit? So you throw the Exception up the chain back to the caller.

In many cases, an unchecked Exception occurs because the programmer did not verify inputs (in the case of NumberFormatException in your first question). That's why its optional to catch them, because there are more elegant ways to avoid generating those exceptions.

Ping a site in Python?

You may find Noah Gift's presentation Creating Agile Commandline Tools With Python. In it he combines subprocess, Queue and threading to develop solution that is capable of pinging hosts concurrently and speeding up the process. Below is a basic version before he adds command line parsing and some other features. The code to this version and others can be found here

#!/usr/bin/env python2.5
from threading import Thread
import subprocess
from Queue import Queue

num_threads = 4
queue = Queue()
ips = ["10.0.1.1", "10.0.1.3", "10.0.1.11", "10.0.1.51"]
#wraps system ping command
def pinger(i, q):
    """Pings subnet"""
    while True:
        ip = q.get()
        print "Thread %s: Pinging %s" % (i, ip)
        ret = subprocess.call("ping -c 1 %s" % ip,
            shell=True,
            stdout=open('/dev/null', 'w'),
            stderr=subprocess.STDOUT)
        if ret == 0:
            print "%s: is alive" % ip
        else:
            print "%s: did not respond" % ip
        q.task_done()
#Spawn thread pool
for i in range(num_threads):

    worker = Thread(target=pinger, args=(i, queue))
    worker.setDaemon(True)
    worker.start()
#Place work in queue
for ip in ips:
    queue.put(ip)
#Wait until worker threads are done to exit    
queue.join()

He is also author of: Python for Unix and Linux System Administration

http://ecx.images-amazon.com/images/I/515qmR%2B4sjL._SL500_AA240_.jpg

Unit test naming best practices

Class Names. For test fixture names, I find that "Test" is quite common in the ubiquitous language of many domains. For example, in an engineering domain: StressTest, and in a cosmetics domain: SkinTest. Sorry to disagree with Kent, but using "Test" in my test fixtures (StressTestTest?) is confusing.

"Unit" is also used a lot in domains. E.g. MeasurementUnit. Is a class called MeasurementUnitTest a test of "Measurement" or "MeasurementUnit"?

Therefore I like to use the "Qa" prefix for all my test classes. E.g. QaSkinTest and QaMeasurementUnit. It is never confused with domain objects, and using a prefix rather than a suffix means that all the test fixtures live together visually (useful if you have fakes or other support classes in your test project)

Namespaces. I work in C# and I keep my test classes in the same namespace as the class they are testing. It is more convenient than having separate test namespaces. Of course, the test classes are in a different project.

Test method names. I like to name my methods WhenXXX_ExpectYYY. It makes the precondition clear, and helps with automated documentation (a la TestDox). This is similar to the advice on the Google testing blog, but with more separation of preconditions and expectations. For example:

WhenDivisorIsNonZero_ExpectDivisionResult
WhenDivisorIsZero_ExpectError
WhenInventoryIsBelowOrderQty_ExpectBackOrder
WhenInventoryIsAboveOrderQty_ExpectReducedInventory

Could not open ServletContext resource

Try to use classpath*: prefix instead.

http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/resources.html#resources-classpath-wildcards

Also please try to deploy exploded war, to ensure that all files are there.

What is a stack pointer used for in microprocessors?

Should you ever crave deeper understanding, I heartily recommend Patterson and Hennessy as an intro and Hennessy and Patterson as an intermediate to advanced text. They're pricey, but truly non-pareil; I just wish either or both were available when I got my Masters' degree and entered the workforce designing chips, systems, and parts of system software for them (but, alas!, that was WAY too long ago;-). Stack pointers are so crucial (and the distinction between a microprocessor and any other kind of CPU so utterly meaningful in this context... or, for that matter, in ANY other context, in the last few decades...!-) that I doubt anything but a couple of thorough from-the-ground-up refreshers can help!-)

Check substring exists in a string in C

if(strstr(sent, word) != NULL) {
    /* ... */
}

Note that strstr returns a pointer to the start of the word in sent if the word word is found.

Spring 3.0 - Unable to locate Spring NamespaceHandler for XML schema namespace [http://www.springframework.org/schema/security]

I got this error while deploying to Virgo. The solution was to add this to my bundle imports:

org.springframework.transaction.config;version="[3.1,3.2)",

I noticed in the Spring jars under META-INF there is a spring.schemas and a spring.handlers section, and the class that they point to (in this case org.springframework.transaction.config.TxNamespaceHandler) must be imported.

iOS Detection of Screenshot?

Swift 4+

NotificationCenter.default.addObserver(forName: UIApplication.userDidTakeScreenshotNotification, object: nil, queue: OperationQueue.main) { notification in
           //you can do anything you want here. 
        }

by using this observer you can find out when user takes a screenshot, but you can not prevent him.

How do I get current date/time on the Windows command line in a suitable format for usage in a file/folder name?

:: GetDate.cmd -> Uses WMIC.exe to get current date and time in ISO 8601 format
:: - Sets environment variables %_isotime% and %_now% to current time
:: - On failure, clears these environment variables
:: Inspired on -> https://ss64.com/nt/syntax-getdate.html
:: - (cX) 2017 [email protected]
:: - http://stackoverflow.com/questions/203090
@echo off

set _isotime=
set _now=

:: Check that WMIC.exe is available
WMIC.exe Alias /? >NUL 2>&1 || goto _WMIC_MISSING_

if not (%1)==() goto _help
SetLocal EnableDelayedExpansion

:: Use WMIC.exe to retrieve date and time
FOR /F "skip=1 tokens=1-6" %%G IN ('WMIC.exe Path Win32_LocalTime Get Day^,Hour^,Minute^,Month^,Second^,Year /Format:table') DO (
    IF "%%~L"=="" goto  _WMIC_done_
        set _yyyy=%%L
        set _mm=00%%J
        set _dd=00%%G
        set _hour=00%%H
        set _minute=00%%I
        set _second=00%%K
)
:_WMIC_done_

::   1    2     3       4      5      6
:: %%G  %%H    %%I     %%J    %%K    %%L
:: Day  Hour  Minute  Month  Second  Year
:: 27   9     35      4      38      2017

:: Remove excess leading zeroes
        set _mm=%_mm:~-2%
        set _dd=%_dd:~-2%
        set _hour=%_hour:~-2%
        set _minute=%_minute:~-2%
        set _second=%_second:~-2%
:: Syntax -> %variable:~num_chars_to_skip,num_chars_to_keep%

:: Set date/time in ISO 8601 format:
        Set _isotime=%_yyyy%-%_mm%-%_dd%T%_hour%:%_minute%:%_second%
:: -> http://google.com/search?num=100&q=ISO+8601+format

if 1%_hour% LSS 112 set _now=%_isotime:~0,10% %_hour%:%_minute%:%_second%am
if 1%_hour% LSS 112 goto _skip_12_
    set /a _hour=1%_hour%-12
    set _hour=%_hour:~-2%
    set _now=%_isotime:~0,10% %_hour%:%_minute%:%_second%pm
    :: -> https://ss64.com/nt/if.html
    :: -> http://google.com/search?num=100&q=SetLocal+EndLocal+Windows
    :: 'if () else ()' will NOT set %_now% correctly !?
:_skip_12_

EndLocal & set _isotime=%_isotime% & set _now=%_now%
goto _out

:_WMIC_MISSING_
echo.
echo WMIC.exe command not available
echo - WMIC.exe needs Administrator privileges to run in Windows
echo - Usually the path to WMIC.exe is "%windir%\System32\wbem\WMIC.exe"

:_help
echo.
echo GetDate.cmd: Uses WMIC.exe to get current date and time in ISO 8601 format
echo.
echo    %%_now%%     environment variable set to current date and time
echo    %%_isotime%% environment variable to current time in ISO format
echo    set _today=%%_isotime:~0,10%%
echo.

:_out
:: EOF: GetDate.cmd

Regular expression for excluding special characters

I strongly suspect it's going to be easier to come up with a list of the characters that ARE allowed vs. the ones that aren't -- and once you have that list, the regex syntax becomes quite straightforward. So put me down as another vote for "whitelist".

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

Try Foo.instance_methods.include? :bar

How to obtain values of request variables using Python and Flask

Adding more to Jason's more generalized way of retrieving the POST data or GET data

from flask_restful import reqparse

def parse_arg_from_requests(arg, **kwargs):
    parse = reqparse.RequestParser()
    parse.add_argument(arg, **kwargs)
    args = parse.parse_args()
    return args[arg]

form_field_value = parse_arg_from_requests('FormFieldValue')

How to put a UserControl into Visual Studio toolBox

Using VS 2010:

Let's say you have a Windows.Forms project. You add a UserControl (say MyControl) to the project, and design it all up. Now you want to add it to your toolbox.

As soon as the project is successfully built once, it will appear in your Framework Components. Right click the Toolbox to get the context menu, select "Choose Items...", and browse to the name of your control (MyControl) under the ".NET Framework Components" tab.

Advantage over using dlls: you can edit the controls in the same project as your form, and the form will build with the new controls. However, the control will only be avilable to this project.

Note: If the control has build errors, resolve them before moving on to the containing forms, or the designer has a heart attack.

How can I set the default timezone in node.js?

Another approach which seemed to work for me at least in Linux environment is to run your Node.js application like this:

env TZ='Europe/Amsterdam' node server.js

This should at least ensure that the timezone is correctly set already from the beginning.

Jquery select change not firing

$(document).on('change','#multiid',function(){
  // you desired code 
});

reference on

Add new line in text file with Windows batch file

I believe you are using the

echo Text >> Example.txt 

function?

If so the answer would be simply adding a "." (Dot) directly after the echo with nothing else there.

Example:

echo Blah
echo Blah 2
echo. #New line is added
echo Next Blah

How to align this span to the right of the div?

If you can modify the HTML: http://jsfiddle.net/8JwhZ/3/

<div class="title">
  <span class="name">Cumulative performance</span>
  <span class="date">20/02/2011</span>
</div>

.title .date { float:right }
.title .name { float:left }

T-SQL How to create tables dynamically in stored procedures?

This is a way to create tables dynamically using T-SQL stored procedures:

declare @cmd nvarchar(1000), @MyTableName nvarchar(100);
set @MyTableName = 'CustomerDetails';
set @cmd = 'CREATE TABLE dbo.' + quotename(@MyTableName, '[') + '(ColumnName1 int not null,ColumnName2 int not null);';

Execute it as:

exec(@cmd);

Run a batch file with Windows task scheduler

  1. Don't use double quotes in your cmd/batch file
  2. Make sure you go to the full path start in (optional):
    C:\Necessary_file\Reqular_task\QDE\cmd_practice\

enter image description here

Assign a variable inside a Block to a variable outside a Block

When I saw the same error, I tried to resolve it like:

   __block CGFloat docHeight = 0.0;


    [self evaluateJavaScript:@"document.height" completionHandler:^(id height, NSError *error) {
        //height
        NSLog(@"=========>document.height:@%@",height);
        docHeight = [height floatValue];
    }];

and its working fine

Just add "__block" before Variable.

Count immediate child div elements using jQuery

var n_numTabs = $("#superpics div").size();

or

var n_numTabs = $("#superpics div").length;

As was already said, both return the same result.
But the size() function is more jQuery "P.C".
I had a similar problem with my page.
For now on, just omit the > and it should work fine.

What's wrong with overridable method calls in constructors?

In the specific case of Wicket: This is the very reason why I asked the Wicket devs to add support for an explicit two phase component initialization process in the framework's lifecycle of constructing a component i.e.

  1. Construction - via constructor
  2. Initialization - via onInitilize (after construction when virtual methods work!)

There was quite an active debate about whether it was necessary or not (it fully is necessary IMHO) as this link demonstrates http://apache-wicket.1842946.n4.nabble.com/VOTE-WICKET-3218-Component-onInitialize-is-broken-for-Pages-td3341090i20.html)

The good news is that the excellent devs at Wicket did end up introducing two phase initialization (to make the most aweseome Java UI framework even more awesome!) so with Wicket you can do all your post construction initialization in the onInitialize method that is called by the framework automatically if you override it - at this point in the lifecycle of your component its constructor has completed its work so virtual methods work as expected.

delete image from folder PHP

<?php

    require 'database.php';

    $id = $_GET['id'];

    $image = "SELECT * FROM slider WHERE id = '$id'";
    $query = mysqli_query($connect, $image);
    $after = mysqli_fetch_assoc($query);

    if ($after['image'] != 'default.png') {
        unlink('../slider/'.$after['image']);
    }

    $delete = "DELETE FROM slider WHERE id = $id";
    $query = mysqli_query($connect, $delete);

    if ($query) {
        header('location: slider.php');
    }

?>

Is there a numpy builtin to reject outliers from a list

For a set of images (each image has 3 dimensions), where I wanted to reject outliers for each pixel I used:

mean = np.mean(imgs, axis=0)
std = np.std(imgs, axis=0)
mask = np.greater(0.5 * std + 1, np.abs(imgs - mean))
masked = np.multiply(imgs, mask)

Then it is possible to compute the mean:

masked_mean = np.divide(np.sum(masked, axis=0), np.sum(mask, axis=0))

(I use it for Background Subtraction)

pip installs packages successfully, but executables not found from command line

check your $PATH

tox has a command line mode:

audrey:tests jluc$ pip list | grep tox
tox (2.3.1)

where is it?

(edit: the 2.7 stuff doesn't matter much here, sub in any 3.x and pip's behaving pretty much the same way)

audrey:tests jluc$ which tox
/opt/local/Library/Frameworks/Python.framework/Versions/2.7/bin/tox

and what's in my $PATH?

audrey:tests jluc$ echo $PATH
/opt/chefdk/bin:/opt/chefdk/embedded/bin:/opt/local/bin:..../opt/local/Library/Frameworks/Python.framework/Versions/2.7/bin...

Notice the /opt/local/Library/Frameworks/Python.framework/Versions/2.7/bin? That's what allows finding my pip-installed stuff

Now, to see where things are from Python, try doing this (substitute rosdep for tox).

$python
>>> import tox
>>> tox.__file__

that prints out:

'/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/tox/__init__.pyc'

Now, cd to the directory right above lib in the above. Do you see a bin directory? Do you see rosdep in that bin? If so try adding the bin to your $PATH.

audrey:2.7 jluc$ cd /opt/local/Library/Frameworks/Python.framework/Versions/2.7
audrey:2.7 jluc$ ls -1

output:

Headers
Python
Resources
bin
include
lib
man
share

How to style child components from parent component's CSS file?

Update - Newest Way

Don't do it, if you can avoid it. As Devon Sans points out in the comments: This feature will most likely be deprecated.

#Update - Newer Way From Angular 4.3.0, all piercing css combinators were deprecated. Angular team introduced a new combinator ::ng-deep (still it is experimental and not the full and final way) as shown below,

DEMO : https://plnkr.co/edit/RBJIszu14o4svHLQt563?p=preview

styles: [
    `
     :host { color: red; }
     
     :host ::ng-deep parent {
       color:blue;
     }
     :host ::ng-deep child{
       color:orange;
     }
     :host ::ng-deep child.class1 {
       color:yellow;
     }
     :host ::ng-deep child.class2{
       color:pink;
     }
    `
],



template: `
      Angular2                                //red
      <parent>                                //blue
          <child></child>                     //orange
          <child class="class1"></child>      //yellow
          <child class="class2"></child>      //pink
      </parent>      
    `

# Old way

You can use encapsulation mode and/or piercing CSS combinators >>>, /deep/ and ::shadow

working example : http://plnkr.co/edit/1RBDGQ?p=preview

styles: [
    `
     :host { color: red; }
     :host >>> parent {
       color:blue;
     }
     :host >>> child{
       color:orange;
     }
     :host >>> child.class1 {
       color:yellow;
     }
     :host >>> child.class2{
       color:pink;
     }
    `
    ],

template: `
  Angular2                                //red
  <parent>                                //blue
      <child></child>                     //orange
      <child class="class1"></child>      //yellow
      <child class="class2"></child>      //pink
  </parent>      
`

How to read strings from a Scanner in a Java console application?

You are entering a null value to nextInt, it will fail if you give a null value...

i have added a null check to the piece of code

Try this code:

import java.util.Scanner;
class MyClass
{
     public static void main(String args[]){

                Scanner scanner = new Scanner(System.in);
                int eid,sid;
                String ename;
                System.out.println("Enter Employeeid:");
                     eid=(scanner.nextInt());
                System.out.println("Enter EmployeeName:");
                     ename=(scanner.next());
                System.out.println("Enter SupervisiorId:");
                    if(scanner.nextLine()!=null&&scanner.nextLine()!=""){//null check
                     sid=scanner.nextInt();
                     }//null check
        }
}

How can I convert a Timestamp into either Date or DateTime object?

java.time

Modern answer: use java.time, the modern Java date and time API, for your date and time work. Back in 2011 it was right to use the Timestamp class, but since JDBC 4.2 it is no longer advised.

For your work we need a time zone and a couple of formatters. We may as well declare them static:

static ZoneId zone = ZoneId.of("America/Marigot");
static DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("MM/dd/uuuu");
static DateTimeFormatter timeFormatter = DateTimeFormatter.ofPattern("HH:mm xx");

Now the code could be for example:

    while(resultSet.next()) {
        ZonedDateTime dtStart = resultSet.getObject("dtStart", OffsetDateTime.class)
                 .atZoneSameInstant(zone);

        // I would like to then have the date and time
        // converted into the formats mentioned...
        String dateFormatted = dtStart.format(dateFormatter);
        String timeFormatted = dtStart.format(timeFormatter);
        System.out.format("Date: %s; time: %s%n", dateFormatted, timeFormatted);
    }

Example output (using the time your question was asked):

Date: 09/20/2011; time: 18:13 -0400

In your database timestamp with time zone is recommended for timestamps. If this is what you’ve got, retrieve an OffsetDateTime as I am doing in the code. I am also converting the retrieved value to the user’s time zone before formatting date and time separately. As time zone I supplied America/Marigot as an example, please supply your own. You may also leave out the time zone conversion if you don’t want any, of course.

If the datatype in SQL is a mere timestamp without time zone, retrieve a LocalDateTime instead. For example:

        ZonedDateTime dtStart = resultSet.getObject("dtStart", LocalDateTime.class)
                 .atZone(zone);

No matter the details I trust you to do similarly for dtEnd.

I wasn’t sure what you meant by the xx in HH:MM xx. I just left it in the format pattern string, which yields the UTC offset in hours and minutes without colon.

Link: Oracle tutorial: Date Time explaining how to use java.time.

Force IE10 to run in IE10 Compatibility View?

While you should fix your site so it works without Compatibility View, try putting the X-UA-Compatible meta tag as the very first thing after the opening <head>, before the title

Insert new item in array on any position in PHP

There is no native PHP function (that I am aware of) that can do exactly what you requested.

I've written 2 methods that I believe are fit for purpose:

function insertBefore($input, $index, $element) {
    if (!array_key_exists($index, $input)) {
        throw new Exception("Index not found");
    }
    $tmpArray = array();
    $originalIndex = 0;
    foreach ($input as $key => $value) {
        if ($key === $index) {
            $tmpArray[] = $element;
            break;
        }
        $tmpArray[$key] = $value;
        $originalIndex++;
    }
    array_splice($input, 0, $originalIndex, $tmpArray);
    return $input;
}

function insertAfter($input, $index, $element) {
    if (!array_key_exists($index, $input)) {
        throw new Exception("Index not found");
    }
    $tmpArray = array();
    $originalIndex = 0;
    foreach ($input as $key => $value) {
        $tmpArray[$key] = $value;
        $originalIndex++;
        if ($key === $index) {
            $tmpArray[] = $element;
            break;
        }
    }
    array_splice($input, 0, $originalIndex, $tmpArray);
    return $input;
}

While faster and probably more memory efficient, this is only really suitable where it is not necessary to maintain the keys of the array.

If you do need to maintain keys, the following would be more suitable;

function insertBefore($input, $index, $newKey, $element) {
    if (!array_key_exists($index, $input)) {
        throw new Exception("Index not found");
    }
    $tmpArray = array();
    foreach ($input as $key => $value) {
        if ($key === $index) {
            $tmpArray[$newKey] = $element;
        }
        $tmpArray[$key] = $value;
    }
    return $input;
}

function insertAfter($input, $index, $newKey, $element) {
    if (!array_key_exists($index, $input)) {
        throw new Exception("Index not found");
    }
    $tmpArray = array();
    foreach ($input as $key => $value) {
        $tmpArray[$key] = $value;
        if ($key === $index) {
            $tmpArray[$newKey] = $element;
        }
    }
    return $tmpArray;
}

How do you obtain a Drawable object from a resource id in android package?

Following a solution for Kotlin programmers (from API 22)

val res = context?.let { ContextCompat.getDrawable(it, R.id.any_resource }

Transfer data between iOS and Android via Bluetooth?

Maybe a bit delayed, but technologies have evolved since so there is certainly new info around which draws fresh light on the matter...

As iOS has yet to open up an API for WiFi Direct and Multipeer Connectivity is iOS only, I believe the best way to approach this is to use BLE, which is supported by both platforms (some better than others).

On iOS a device can act both as a BLE Central and BLE Peripheral at the same time, on Android the situation is more complex as not all devices support the BLE Peripheral state. Also the Android BLE stack is very unstable (to date).

If your use case is feature driven, I would suggest to look at Frameworks and Libraries that can achieve cross platform communication for you, without you needing to build it up from scratch.

For example: http://p2pkit.io or google nearby

Disclaimer: I work for Uepaa, developing p2pkit.io for Android and iOS.

Backup a single table with its data from a database in sql server 2008

Put the table in its own filegroup. You can then use regular SQL Server built in backup to backup the filegroup in which in effect backs up the table.

To backup a filegroup see: https://docs.microsoft.com/en-us/sql/relational-databases/backup-restore/back-up-files-and-filegroups-sql-server

To create a table on a non-default filegroup (its easy) see: Create a table on a filegroup other than the default

check if directory exists and delete in one command unix

Try:

bash -c '[ -d my_mystery_dirname ] && run_this_command'

This will work if you can run bash on the remote machine....

In bash, [ -d something ] checks if there is directory called 'something', returning a success code if it exists and is a directory. Chaining commands with && runs the second command only if the first one succeeded. So [ -d somedir ] && command runs the command only if the directory exists.

Writing handler for UIAlertAction

In Swift 4 :

let alert=UIAlertController(title:"someAlert", message: "someMessage", preferredStyle:UIAlertControllerStyle.alert )

alert.addAction(UIAlertAction(title: "ok", style: UIAlertActionStyle.default, handler: {
        _ in print("FOO ")
}))

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

How to get the hours difference between two date objects?

Try using getTime (mdn doc) :

var diff = Math.abs(date1.getTime() - date2.getTime()) / 3600000;
if (diff < 18) { /* do something */ }

Using Math.abs() we don't know which date is the smallest. This code is probably more relevant :

var diff = (date1 - date2) / 3600000;
if (diff < 18) { array.push(date1); }

Disable resizing of a Windows Forms form

More precisely, add the code below to the private void InitializeComponent() method of the Form class:

this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedSingle;

CodeIgniter Active Record - Get number of returned rows

You can do this in two different ways:

  1. $this->db->query(); //execute the query
     $query = $this->db->get() // get query result
     $count = $query->num_rows() //get current query record.

  2.  $this->db->query(); //execute the query
      $query = $this->db->get() // get query result
      $count = count($query->results()) 
          or   count($query->row_array())  //get current query record.

#1025 - Error on rename of './database/#sql-2e0f_1254ba7' to './database/table' (errno: 150)

I had this problem, it is for foreign-key

Click on the Relation View (like the image below) then find name of the field you are going to remove it, and under the Foreign key constraint (INNODB) column, just put the select to nothing! Means no foreign-key

enter image description here

Hope that works!

How to get a .csv file into R?

You can use

df <- read.csv("filename.csv", header=TRUE)

# To loop each column
for (i in 1:ncol(df))
    {
    dosomething(df[,i])
    }
# To loop each row
for (i in 1:nrow(df))
    {
    dosomething(df[i,])
    }

Also, you may want to have a look to the apply function (type ?apply or help(apply))if you want to use the same function on each row/column

New features in java 7

New Feature of Java Standard Edition (JSE 7)

  1. Decorate Components with the JLayer Class:

    The JLayer class is a flexible and powerful decorator for Swing components. The JLayer class in Java SE 7 is similar in spirit to the JxLayer project project at java.net. The JLayer class was initially based on the JXLayer project, but its API evolved separately.

  2. Strings in switch Statement:

    In the JDK 7 , we can use a String object in the expression of a switch statement. The Java compiler generates generally more efficient bytecode from switch statements that use String objects than from chained if-then-else statements.

  3. Type Inference for Generic Instance:

    We can replace the type arguments required to invoke the constructor of a generic class with an empty set of type parameters (<>) as long as the compiler can infer the type arguments from the context. This pair of angle brackets is informally called the diamond. Java SE 7 supports limited type inference for generic instance creation; you can only use type inference if the parameterized type of the constructor is obvious from the context. For example, the following example does not compile:

    List<String> l = new ArrayList<>();
    l.add("A");
    l.addAll(new ArrayList<>());
    

    In comparison, the following example compiles:

    List<? extends String> list2 = new ArrayList<>();
    l.addAll(list2);
    
  4. Catching Multiple Exception Types and Rethrowing Exceptions with Improved Type Checking:

    In Java SE 7 and later, a single catch block can handle more than one type of exception. This feature can reduce code duplication. Consider the following code, which contains duplicate code in each of the catch blocks:

    catch (IOException e) {
        logger.log(e);
        throw e;
    }
    catch (SQLException e) {
        logger.log(e);
        throw e;
    }
    

    In releases prior to Java SE 7, it is difficult to create a common method to eliminate the duplicated code because the variable e has different types. The following example, which is valid in Java SE 7 and later, eliminates the duplicated code:

    catch (IOException|SQLException e) {
        logger.log(e);
        throw e;
    }
    

    The catch clause specifies the types of exceptions that the block can handle, and each exception type is separated with a vertical bar (|).

  5. The java.nio.file package

    The java.nio.file package and its related package, java.nio.file.attribute, provide comprehensive support for file I/O and for accessing the file system. A zip file system provider is also available in JDK 7.

Source: http://ohmjavaclasses.blogspot.com/

How do I use arrays in C++?

Arrays on the type level

An array type is denoted as T[n] where T is the element type and n is a positive size, the number of elements in the array. The array type is a product type of the element type and the size. If one or both of those ingredients differ, you get a distinct type:

#include <type_traits>

static_assert(!std::is_same<int[8], float[8]>::value, "distinct element type");
static_assert(!std::is_same<int[8],   int[9]>::value, "distinct size");

Note that the size is part of the type, that is, array types of different size are incompatible types that have absolutely nothing to do with each other. sizeof(T[n]) is equivalent to n * sizeof(T).

Array-to-pointer decay

The only "connection" between T[n] and T[m] is that both types can implicitly be converted to T*, and the result of this conversion is a pointer to the first element of the array. That is, anywhere a T* is required, you can provide a T[n], and the compiler will silently provide that pointer:

                  +---+---+---+---+---+---+---+---+
the_actual_array: |   |   |   |   |   |   |   |   |   int[8]
                  +---+---+---+---+---+---+---+---+
                    ^
                    |
                    |
                    |
                    |  pointer_to_the_first_element   int*

This conversion is known as "array-to-pointer decay", and it is a major source of confusion. The size of the array is lost in this process, since it is no longer part of the type (T*). Pro: Forgetting the size of an array on the type level allows a pointer to point to the first element of an array of any size. Con: Given a pointer to the first (or any other) element of an array, there is no way to detect how large that array is or where exactly the pointer points to relative to the bounds of the array. Pointers are extremely stupid.

Arrays are not pointers

The compiler will silently generate a pointer to the first element of an array whenever it is deemed useful, that is, whenever an operation would fail on an array but succeed on a pointer. This conversion from array to pointer is trivial, since the resulting pointer value is simply the address of the array. Note that the pointer is not stored as part of the array itself (or anywhere else in memory). An array is not a pointer.

static_assert(!std::is_same<int[8], int*>::value, "an array is not a pointer");

One important context in which an array does not decay into a pointer to its first element is when the & operator is applied to it. In that case, the & operator yields a pointer to the entire array, not just a pointer to its first element. Although in that case the values (the addresses) are the same, a pointer to the first element of an array and a pointer to the entire array are completely distinct types:

static_assert(!std::is_same<int*, int(*)[8]>::value, "distinct element type");

The following ASCII art explains this distinction:

      +-----------------------------------+
      | +---+---+---+---+---+---+---+---+ |
+---> | |   |   |   |   |   |   |   |   | | int[8]
|     | +---+---+---+---+---+---+---+---+ |
|     +---^-------------------------------+
|         |
|         |
|         |
|         |  pointer_to_the_first_element   int*
|
|  pointer_to_the_entire_array              int(*)[8]

Note how the pointer to the first element only points to a single integer (depicted as a small box), whereas the pointer to the entire array points to an array of 8 integers (depicted as a large box).

The same situation arises in classes and is maybe more obvious. A pointer to an object and a pointer to its first data member have the same value (the same address), yet they are completely distinct types.

If you are unfamiliar with the C declarator syntax, the parenthesis in the type int(*)[8] are essential:

  • int(*)[8] is a pointer to an array of 8 integers.
  • int*[8] is an array of 8 pointers, each element of type int*.

Accessing elements

C++ provides two syntactic variations to access individual elements of an array. Neither of them is superior to the other, and you should familiarize yourself with both.

Pointer arithmetic

Given a pointer p to the first element of an array, the expression p+i yields a pointer to the i-th element of the array. By dereferencing that pointer afterwards, one can access individual elements:

std::cout << *(x+3) << ", " << *(x+7) << std::endl;

If x denotes an array, then array-to-pointer decay will kick in, because adding an array and an integer is meaningless (there is no plus operation on arrays), but adding a pointer and an integer makes sense:

   +---+---+---+---+---+---+---+---+
x: |   |   |   |   |   |   |   |   |   int[8]
   +---+---+---+---+---+---+---+---+
     ^           ^               ^
     |           |               |
     |           |               |
     |           |               |
x+0  |      x+3  |          x+7  |     int*

(Note that the implicitly generated pointer has no name, so I wrote x+0 in order to identify it.)

If, on the other hand, x denotes a pointer to the first (or any other) element of an array, then array-to-pointer decay is not necessary, because the pointer on which i is going to be added already exists:

   +---+---+---+---+---+---+---+---+
   |   |   |   |   |   |   |   |   |   int[8]
   +---+---+---+---+---+---+---+---+
     ^           ^               ^
     |           |               |
     |           |               |
   +-|-+         |               |
x: | | |    x+3  |          x+7  |     int*
   +---+

Note that in the depicted case, x is a pointer variable (discernible by the small box next to x), but it could just as well be the result of a function returning a pointer (or any other expression of type T*).

Indexing operator

Since the syntax *(x+i) is a bit clumsy, C++ provides the alternative syntax x[i]:

std::cout << x[3] << ", " << x[7] << std::endl;

Due to the fact that addition is commutative, the following code does exactly the same:

std::cout << 3[x] << ", " << 7[x] << std::endl;

The definition of the indexing operator leads to the following interesting equivalence:

&x[i]  ==  &*(x+i)  ==  x+i

However, &x[0] is generally not equivalent to x. The former is a pointer, the latter an array. Only when the context triggers array-to-pointer decay can x and &x[0] be used interchangeably. For example:

T* p = &array[0];  // rewritten as &*(array+0), decay happens due to the addition
T* q = array;      // decay happens due to the assignment

On the first line, the compiler detects an assignment from a pointer to a pointer, which trivially succeeds. On the second line, it detects an assignment from an array to a pointer. Since this is meaningless (but pointer to pointer assignment makes sense), array-to-pointer decay kicks in as usual.

Ranges

An array of type T[n] has n elements, indexed from 0 to n-1; there is no element n. And yet, to support half-open ranges (where the beginning is inclusive and the end is exclusive), C++ allows the computation of a pointer to the (non-existent) n-th element, but it is illegal to dereference that pointer:

   +---+---+---+---+---+---+---+---+....
x: |   |   |   |   |   |   |   |   |   .   int[8]
   +---+---+---+---+---+---+---+---+....
     ^                               ^
     |                               |
     |                               |
     |                               |
x+0  |                          x+8  |     int*

For example, if you want to sort an array, both of the following would work equally well:

std::sort(x + 0, x + n);
std::sort(&x[0], &x[0] + n);

Note that it is illegal to provide &x[n] as the second argument since this is equivalent to &*(x+n), and the sub-expression *(x+n) technically invokes undefined behavior in C++ (but not in C99).

Also note that you could simply provide x as the first argument. That is a little too terse for my taste, and it also makes template argument deduction a bit harder for the compiler, because in that case the first argument is an array but the second argument is a pointer. (Again, array-to-pointer decay kicks in.)

Are there any worse sorting algorithms than Bogosort (a.k.a Monkey Sort)?

Randomsubsetsort.

Given an array of n elements, choose each element with probability 1/n, randomize these elements, and check if the array is sorted. Repeat until sorted.

Expected time is left as an exercise for the reader.

How can I send a Firebase Cloud Messaging notification without use the Firebase Console?

Examples using curl

Send messages to specific devices

To send messages to specific devices, set the to the registration token for the specific app instance

curl -H "Content-type: application/json" -H "Authorization:key=<Your Api key>"  -X POST -d '{ "data": { "score": "5x1","time": "15:10"},"to" : "<registration token>"}' https://fcm.googleapis.com/fcm/send

Send messages to topics

here the topic is : /topics/foo-bar

curl -H "Content-type: application/json" -H "Authorization:key=<Your Api key>"  -X POST -d '{ "to": "/topics/foo-bar","data": { "message": "This is a Firebase Cloud Messaging Topic Message!"}}' https://fcm.googleapis.com/fcm/send

Send messages to device groups

Sending messages to a device group is very similar to sending messages to an individual device. Set the to parameter to the unique notification key for the device group

curl -H "Content-type: application/json" -H "Authorization:key=<Your Api key>"  -X POST -d '{"to": "<aUniqueKey>","data": {"hello": "This is a Firebase Cloud Messaging Device Group Message!"}}' https://fcm.googleapis.com/fcm/send

Examples using Service API

API URL : https://fcm.googleapis.com/fcm/send

Headers

Content-type: application/json
Authorization:key=<Your Api key>

Request Method : POST

Request Body

Messages to specific devices

{
  "data": {
    "score": "5x1",
    "time": "15:10"
  },
  "to": "<registration token>"
}

Messages to topics

{
  "to": "/topics/foo-bar",
  "data": {
    "message": "This is a Firebase Cloud Messaging Topic Message!"
  }
}

Messages to device groups

{
  "to": "<aUniqueKey>",
  "data": {
    "hello": "This is a Firebase Cloud Messaging Device Group Message!"
  }
}

Spring schemaLocation fails when there is no internet connection

I had the same problem when I'm using spring-context version 4.0.6 and spring-security version 4.1.0.

When changing spring-security version to 4.0.4 (because 4.0.6 of spring-security not available) in my pom and security xml-->schemaLocation, it gets compiled without internet.

So that mean you can also solve this by:

  • changing spring-security to a older or same version than spring-context.

  • changing spring-context to a newer or same version than spring-security.

(any way spring-context to be newer or same version to spring-security)

Does MS SQL Server's "between" include the range boundaries?

It does includes boundaries.

declare @startDate date = cast('15-NOV-2016' as date) 
declare @endDate date = cast('30-NOV-2016' as date)
create table #test (c1 date)
insert into #test values(cast('15-NOV-2016' as date))
insert into #test values(cast('20-NOV-2016' as date))
insert into #test values(cast('30-NOV-2016' as date))
select * from #test where c1 between @startDate and @endDate
drop table #test
RESULT    c1
2016-11-15
2016-11-20
2016-11-30


declare @r1 int  = 10
declare @r2 int  = 15
create table #test1 (c1 int)
insert into #test1 values(10)
insert into #test1 values(15)
insert into #test1 values(11)
select * from #test1 where c1 between @r1 and @r2
drop table #test1
RESULT c1
10
11
15

How to put sshpass command inside a bash script?

1 - You can script sshpass's ssh command like this:

#!/bin/bash

export SSHPASS=password
sshpass -e ssh -oBatchMode=no user@host

2 - You can script sshpass's sftp commandlike this:

#!/bin/bash

export SSHPASS=password

sshpass -e sftp -oBatchMode=no -b - user@host << !
   put someFile
   get anotherFile
   bye
!

Selenium WebDriver.get(url) does not open the URL

I was getting similar problem and Stating string for URL worked for me. :)

package Chrome_Example;

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;

public class Launch_Chrome {

    public static void main(String[] args) {

        System.setProperty("webdriver.chrome.driver", "C:\\Users\\doyes\\Downloads\\chromedriver_win324\\chromedriver.exe");
        String URL = "http://www.google.com";
        WebDriver driver = new ChromeDriver();
        driver.get(URL);
    }

}

Open JQuery Datepicker by clicking on an image w/ no input field

Turns out that a simple hidden input field does the job:

<input type="hidden" id="dp" />

And then use the buttonImage attribute for your image, like normal:

    $("#dp").datepicker({
        buttonImage: '../images/icon_star.gif',
        buttonImageOnly: true,
        changeMonth: true,
        changeYear: true,
        showOn: 'both',
     });

Initially I tried a text input field and then set a display:none style on it, but that caused the calendar to emerge from the top of the browser, rather than from where the user clicked. But the hidden field works as desired.

API vs. Webservice

API is code based integration while web service is message based integration with interoperable standards having a contract such as WSDL.

Warning comparison between pointer and integer

In this line ...

if (*message == "\0") {

... as you can see in the warning ...

warning: comparison between pointer and integer
      ('int' and 'char *')

... you are actually comparing an int with a char *, or more specifically, an int with an address to a char.

To fix this, use one of the following:

if(*message == '\0') ...
if(message[0] == '\0') ...
if(!*message) ...

On a side note, if you'd like to compare strings you should use strcmp or strncmp, found in string.h.

Android Animation Alpha

Try this

AlphaAnimation animation1 = new AlphaAnimation(0.2f, 1.0f);
animation1.setDuration(1000);
animation1.setStartOffset(5000);
animation1.setFillAfter(true);
iv.startAnimation(animation1);

How to pass a PHP variable using the URL

just put

$a='Link1';
$b='Link2';

in your pass.php and you will get your answer and do a double quotation in your link.php:

echo '<a href="pass.php?link=' . $a . '">Link 1</a>';

How to take a first character from the string

Try this:

Dim s = "RAJAN"
Dim firstChar = s(0)

You can even do this:

Dim firstChar = "RAJAN"(0)

SQL Server: Best way to concatenate multiple columns?

Through discourse it's clear that the problem lies in using VS2010 to write the query, as it uses the canonical CONCAT() function which is limited to 2 parameters. There's probably a way to change that, but I'm not aware of it.

An alternative:

SELECT '1'+'2'+'3'

This approach requires non-string values to be cast/converted to strings, as well as NULL handling via ISNULL() or COALESCE():

SELECT  ISNULL(CAST(Col1 AS VARCHAR(50)),'')
      + COALESCE(CONVERT(VARCHAR(50),Col2),'')

How to extract text from the PDF document?

I know that this topic is quite old, but this need is still alive. I read many documents, forum and script and build a new advanced one which supports compressed and uncompressed pdf :

https://gist.github.com/smalot/6183152

Hope it helps everone

Validate select box

if (select == "") {
    alert("Please select a selection");
    return false;

That should work for you. It just did for me.

MySQL - select data from database between two dates

Maybe use in between better. It worked for me to get range then filter it

python pip on Windows - command 'cl.exe' failed

This is easily the simplest solution. For those who don't know how to do this:

  1. Install the C++ compiler https://visualstudio.microsoft.com/downloads/#build-tools-for-visual-studio-2019

  2. Go to the installation folder (In my case it is): C:\Program Files (x86)\Microsoft Visual C++ Build Tools

  3. Open Visual C++ 2015 x86 x64 Cross Build Tools Command Prompt

  4. Type: pip install package_name

C++ Passing Pointer to Function (Howto) + C++ Pointer Manipulation

To pass a pointer to an int it should be void Fun(int* pointer).

Passing a reference to an int would look like this...

void Fun(int& ref) {
   ref = 10;
}

int main() {
   int test = 5;
   cout << test << endl;  // prints 5

   Fun(test);
   cout << test << endl;  // prints 10 because Fun modified the value

   return 1;
}

.NET Format a string with fixed spaces

it seems like you want something like this, that will place you string at a fixed point in a string of constant length:

Dim totallength As Integer = 100
Dim leftbuffer as Integer = 5
Dim mystring As String = "string goes here"
Dim Formatted_String as String = mystring.PadLeft(leftbuffer + mystring.Length, "-") + String.Empty.PadRight(totallength - (mystring.Length + leftbuffer), "-")

note that this will have problems if mystring.length + leftbuffer exceeds totallength

Facebook API - How do I get a Facebook user's profile image through the Facebook API (without requiring the user to "Allow" the application)

There is way to do that ;)

Thanks to "http://it.toolbox.com/wiki/index.php/Use_curl_from_PHP_-_processing_response_headers":

<?php

    /**
     * Facebook user photo downloader
     */

    class sfFacebookPhoto {

        private $useragent = 'Loximi sfFacebookPhoto PHP5 (cURL)';
        private $curl = null;
        private $response_meta_info = array();
        private $header = array(
                "Accept-Encoding: gzip,deflate",
                "Accept-Charset: utf-8;q=0.7,*;q=0.7",
                "Connection: close"
            );

        public function __construct() {
            $this->curl = curl_init();
            register_shutdown_function(array($this, 'shutdown'));
        }

        /**
         * Get the real URL for the picture to use after
         */
        public function getRealUrl($photoLink) {
            curl_setopt($this->curl, CURLOPT_HTTPHEADER, $this->header);
            curl_setopt($this->curl, CURLOPT_RETURNTRANSFER, false);
            curl_setopt($this->curl, CURLOPT_HEADER, false);
            curl_setopt($this->curl, CURLOPT_USERAGENT, $this->useragent);
            curl_setopt($this->curl, CURLOPT_CONNECTTIMEOUT, 10);
            curl_setopt($this->curl, CURLOPT_TIMEOUT, 15);
            curl_setopt($this->curl, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
            curl_setopt($this->curl, CURLOPT_URL, $photoLink);

            //This assumes your code is into a class method, and
            //uses $this->readHeader as the callback function.
            curl_setopt($this->curl, CURLOPT_HEADERFUNCTION, array(&$this, 'readHeader'));
            $response = curl_exec($this->curl);
            if (!curl_errno($this->curl)) {
                $info = curl_getinfo($this->curl);
                var_dump($info);
                if ($info["http_code"] == 302) {
                    $headers = $this->getHeaders();
                    if (isset($headers['fileUrl'])) {
                        return $headers['fileUrl'];
                    }
                }
            }
            return false;
        }


        /**
         * Download Facebook user photo
         *
         */
        public function download($fileName) {
            curl_setopt($this->curl, CURLOPT_HTTPHEADER, $this->header);
            curl_setopt($this->curl, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($this->curl, CURLOPT_HEADER, false);
            curl_setopt($this->curl, CURLOPT_USERAGENT, $this->useragent);
            curl_setopt($this->curl, CURLOPT_CONNECTTIMEOUT, 10);
            curl_setopt($this->curl, CURLOPT_TIMEOUT, 15);
            curl_setopt($this->curl, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
            curl_setopt($this->curl, CURLOPT_URL, $fileName);
            $response = curl_exec($this->curl);
            $return = false;
            if (!curl_errno($this->curl)) {
                $parts = explode('.', $fileName);
                $ext = array_pop($parts);
                $return = sfConfig::get('sf_upload_dir') . '/tmp/' . uniqid('fbphoto') . '.' . $ext;
                file_put_contents($return, $response);
            }
            return $return;
        }

        /**
         * cURL callback function for reading and processing headers.
         * Override this for your needs.
         *
         * @param object $ch
         * @param string $header
         * @return integer
         */
        private function readHeader($ch, $header) {

            //Extracting example data: filename from header field Content-Disposition
            $filename = $this->extractCustomHeader('Location: ', '\n', $header);
            if ($filename) {
                $this->response_meta_info['fileUrl'] = trim($filename);
            }
            return strlen($header);
        }

        private function extractCustomHeader($start, $end, $header) {
            $pattern = '/'. $start .'(.*?)'. $end .'/';
            if (preg_match($pattern, $header, $result)) {
                return $result[1];
            }
            else {
                return false;
            }
        }

        public function getHeaders() {
            return $this->response_meta_info;
        }

        /**
         * Cleanup resources
         */
        public function shutdown() {
            if($this->curl) {
                curl_close($this->curl);
            }
        }
    }

How to display a pdf in a modal window?

You can have an iframe inside the modal markup and give the src attribute of it as the link to your pdf. On click of the link you can show this modal markup.

Angular2 - TypeScript : Increment a number after timeout in AppComponent

This is not valid TypeScript code. You can not have method invocations in the body of a class.

// INVALID CODE
export class AppComponent {
  public n: number = 1;
  setTimeout(function() {
    n = n + 10;
  }, 1000);
}

Instead move the setTimeout call to the constructor of the class. Additionally, use the arrow function => to gain access to this.

export class AppComponent {
  public n: number = 1;

  constructor() {
    setTimeout(() => {
      this.n = this.n + 10;
    }, 1000);
  }

}

In TypeScript, you can only refer to class properties or methods via this. That's why the arrow function => is important.

Parser Error when deploy ASP.NET application

I have solved it this way.

Go to your project file let's say project/name/bin and delete everything within the bin folder. (this will then give you another error which you can solve this way)

then in your visual studio right click project's References folder, to open NuGet Package Manager.

Go to browse and install "DotNetCompilerPlatform".

What does AngularJS do better than jQuery?

Data-Binding

You go around making your webpage, and keep on putting {{data bindings}} whenever you feel you would have dynamic data. Angular will then provide you a $scope handler, which you can populate (statically or through calls to the web server).

This is a good understanding of data-binding. I think you've got that down.

DOM Manipulation

For simple DOM manipulation, which doesnot involve data manipulation (eg: color changes on mousehover, hiding/showing elements on click), jQuery or old-school js is sufficient and cleaner. This assumes that the model in angular's mvc is anything that reflects data on the page, and hence, css properties like color, display/hide, etc changes dont affect the model.

I can see your point here about "simple" DOM manipulation being cleaner, but only rarely and it would have to be really "simple". I think DOM manipulation is one the areas, just like data-binding, where Angular really shines. Understanding this will also help you see how Angular considers its views.

I'll start by comparing the Angular way with a vanilla js approach to DOM manipulation. Traditionally, we think of HTML as not "doing" anything and write it as such. So, inline js, like "onclick", etc are bad practice because they put the "doing" in the context of HTML, which doesn't "do". Angular flips that concept on its head. As you're writing your view, you think of HTML as being able to "do" lots of things. This capability is abstracted away in angular directives, but if they already exist or you have written them, you don't have to consider "how" it is done, you just use the power made available to you in this "augmented" HTML that angular allows you to use. This also means that ALL of your view logic is truly contained in the view, not in your javascript files. Again, the reasoning is that the directives written in your javascript files could be considered to be increasing the capability of HTML, so you let the DOM worry about manipulating itself (so to speak). I'll demonstrate with a simple example.

This is the markup we want to use. I gave it an intuitive name.

<div rotate-on-click="45"></div>

First, I'd just like to comment that if we've given our HTML this functionality via a custom Angular Directive, we're already done. That's a breath of fresh air. More on that in a moment.

Implementation with jQuery

live demo here (click).

function rotate(deg, elem) {
  $(elem).css({
    webkitTransform: 'rotate('+deg+'deg)', 
    mozTransform: 'rotate('+deg+'deg)', 
    msTransform: 'rotate('+deg+'deg)', 
    oTransform: 'rotate('+deg+'deg)', 
    transform: 'rotate('+deg+'deg)'    
  });
}

function addRotateOnClick($elems) {
  $elems.each(function(i, elem) {
    var deg = 0;
    $(elem).click(function() {
      deg+= parseInt($(this).attr('rotate-on-click'), 10);
      rotate(deg, this);
    });
  });
}

addRotateOnClick($('[rotate-on-click]'));

Implementation with Angular

live demo here (click).

app.directive('rotateOnClick', function() {
  return {
    restrict: 'A',
    link: function(scope, element, attrs) {
      var deg = 0;
      element.bind('click', function() {
        deg+= parseInt(attrs.rotateOnClick, 10);
        element.css({
          webkitTransform: 'rotate('+deg+'deg)', 
          mozTransform: 'rotate('+deg+'deg)', 
          msTransform: 'rotate('+deg+'deg)', 
          oTransform: 'rotate('+deg+'deg)', 
          transform: 'rotate('+deg+'deg)'    
        });
      });
    }
  };
});

Pretty light, VERY clean and that's just a simple manipulation! In my opinion, the angular approach wins in all regards, especially how the functionality is abstracted away and the dom manipulation is declared in the DOM. The functionality is hooked onto the element via an html attribute, so there is no need to query the DOM via a selector, and we've got two nice closures - one closure for the directive factory where variables are shared across all usages of the directive, and one closure for each usage of the directive in the link function (or compile function).

Two-way data binding and directives for DOM manipulation are only the start of what makes Angular awesome. Angular promotes all code being modular, reusable, and easily testable and also includes a single-page app routing system. It is important to note that jQuery is a library of commonly needed convenience/cross-browser methods, but Angular is a full featured framework for creating single page apps. The angular script actually includes its own "lite" version of jQuery so that some of the most essential methods are available. Therefore, you could argue that using Angular IS using jQuery (lightly), but Angular provides much more "magic" to help you in the process of creating apps.

This is a great post for more related information: How do I “think in AngularJS” if I have a jQuery background?

General differences.

The above points are aimed at the OP's specific concerns. I'll also give an overview of the other important differences. I suggest doing additional reading about each topic as well.

Angular and jQuery can't reasonably be compared.

Angular is a framework, jQuery is a library. Frameworks have their place and libraries have their place. However, there is no question that a good framework has more power in writing an application than a library. That's exactly the point of a framework. You're welcome to write your code in plain JS, or you can add in a library of common functions, or you can add a framework to drastically reduce the code you need to accomplish most things. Therefore, a more appropriate question is:

Why use a framework?

Good frameworks can help architect your code so that it is modular (therefore reusable), DRY, readable, performant and secure. jQuery is not a framework, so it doesn't help in these regards. We've all seen the typical walls of jQuery spaghetti code. This isn't jQuery's fault - it's the fault of developers that don't know how to architect code. However, if the devs did know how to architect code, they would end up writing some kind of minimal "framework" to provide the foundation (achitecture, etc) I discussed a moment ago, or they would add something in. For example, you might add RequireJS to act as part of your framework for writing good code.

Here are some things that modern frameworks are providing:

  • Templating
  • Data-binding
  • routing (single page app)
  • clean, modular, reusable architecture
  • security
  • additional functions/features for convenience

Before I further discuss Angular, I'd like to point out that Angular isn't the only one of its kind. Durandal, for example, is a framework built on top of jQuery, Knockout, and RequireJS. Again, jQuery cannot, by itself, provide what Knockout, RequireJS, and the whole framework built on top them can. It's just not comparable.

If you need to destroy a planet and you have a Death Star, use the Death star.

Angular (revisited).

Building on my previous points about what frameworks provide, I'd like to commend the way that Angular provides them and try to clarify why this is matter of factually superior to jQuery alone.

DOM reference.

In my above example, it is just absolutely unavoidable that jQuery has to hook onto the DOM in order to provide functionality. That means that the view (html) is concerned about functionality (because it is labeled with some kind of identifier - like "image slider") and JavaScript is concerned about providing that functionality. Angular eliminates that concept via abstraction. Properly written code with Angular means that the view is able to declare its own behavior. If I want to display a clock:

<clock></clock>

Done.

Yes, we need to go to JavaScript to make that mean something, but we're doing this in the opposite way of the jQuery approach. Our Angular directive (which is in it's own little world) has "augumented" the html and the html hooks the functionality into itself.

MVW Architecure / Modules / Dependency Injection

Angular gives you a straightforward way to structure your code. View things belong in the view (html), augmented view functionality belongs in directives, other logic (like ajax calls) and functions belong in services, and the connection of services and logic to the view belongs in controllers. There are some other angular components as well that help deal with configuration and modification of services, etc. Any functionality you create is automatically available anywhere you need it via the Injector subsystem which takes care of Dependency Injection throughout the application. When writing an application (module), I break it up into other reusable modules, each with their own reusable components, and then include them in the bigger project. Once you solve a problem with Angular, you've automatically solved it in a way that is useful and structured for reuse in the future and easily included in the next project. A HUGE bonus to all of this is that your code will be much easier to test.

It isn't easy to make things "work" in Angular.

THANK GOODNESS. The aforementioned jQuery spaghetti code resulted from a dev that made something "work" and then moved on. You can write bad Angular code, but it's much more difficult to do so, because Angular will fight you about it. This means that you have to take advantage (at least somewhat) to the clean architecture it provides. In other words, it's harder to write bad code with Angular, but more convenient to write clean code.

Angular is far from perfect. The web development world is always growing and changing and there are new and better ways being put forth to solve problems. Facebook's React and Flux, for example, have some great advantages over Angular, but come with their own drawbacks. Nothing's perfect, but Angular has been and is still awesome for now. Just as jQuery once helped the web world move forward, so has Angular, and so will many to come.

Asynchronous Function Call in PHP

I think if the HTML and other UI stuff needs the data returned then there is not going to be a way to async it.

I believe the only way to do this in PHP would be to log a request in a database and have a cron check every minute, or use something like Gearman queue processing, or maybe exec() a command line process

In the meantime you php page would have to generate some html or js that makes it reload every few seconds to check on progress, not ideal.

To sidestep the issue, how many different requests are you expecting? Could you download them all automatically every hour or so and save to a database?

Select an Option from the Right-Click Menu in Selenium Webdriver - Java

Instead of attempting to do a right click on a mouse use the keyboard shortcut:

Double click on the element -> hold shift and press F10.

Actions action = new Actions(driver);

//Hold left shift and press F10
action.MoveToElement(element).DoubleClick().KeyDown(Keys.LeftShift).SendKeys(Keys.F10).KeyUp(Keys.LeftShift).Build().Perform();

jQuery autocomplete with callback ajax json

Perfectly good example in the Autocomplete docs with source code.

jQuery

<script>
  $(function() {
    function log( message ) {
      $( "<div>" ).text( message ).prependTo( "#log" );
      $( "#log" ).scrollTop( 0 );
    }

    $( "#city" ).autocomplete({
      source: function( request, response ) {
        $.ajax({
          url: "http://gd.geobytes.com/AutoCompleteCity",
          dataType: "jsonp",
          data: {
            q: request.term
          },
          success: function( data ) {
            response( data );
          }
        });
      },
      minLength: 3,
      select: function( event, ui ) {
        log( ui.item ?
          "Selected: " + ui.item.label :
          "Nothing selected, input was " + this.value);
      },
      open: function() {
        $( this ).removeClass( "ui-corner-all" ).addClass( "ui-corner-top" );
      },
      close: function() {
        $( this ).removeClass( "ui-corner-top" ).addClass( "ui-corner-all" );
      }
    });
  });
</script>

HTML

<div class="ui-widget">
  <label for="city">Your city: </label>
  <input id="city">
  Powered by <a href="http://geonames.org">geonames.org</a>
</div>

<div class="ui-widget" style="margin-top:2em; font-family:Arial">
  Result:
  <div id="log" style="height: 200px; width: 300px; overflow: auto;" class="ui-widget-content"></div>
</div>

Throwing exceptions in a PHP Try Catch block

Throw needs an object instantiated by \Exception. Just the $e catched can play the trick.

throw $e

How to clear cache in Yarn?

Also note that the cached directory is located in ~/.yarn-cache/:

yarn cache clean: cleans that directory

yarn cache list: shows the list of cached dependencies

yarn cache dir: prints out the path of your cached directory

How can you get the build/version number of your Android application?

Using Gradle and BuildConfig

Getting the VERSION_NAME from BuildConfig

BuildConfig.VERSION_NAME

Yep, it's that easy now.

Is it returning an empty string for VERSION_NAME?

If you're getting an empty string for BuildConfig.VERSION_NAME then read on.

I kept getting an empty string for BuildConfig.VERSION_NAME, because I wasn't setting the versionName in my Grade build file (I migrated from Ant to Gradle). So, here are instructions for ensuring you're setting your VERSION_NAME via Gradle.

File build.gradle

def versionMajor = 3
def versionMinor = 0
def versionPatch = 0
def versionBuild = 0 // Bump for dogfood builds, public betas, etc.

android {

  defaultConfig {
    versionCode versionMajor * 10000 + versionMinor * 1000 + versionPatch * 100 + versionBuild

    versionName "${versionMajor}.${versionMinor}.${versionPatch}"
  }

}

Note: This is from the masterful Jake Wharton.

Removing versionName and versionCode from AndroidManifest.xml

And since you've set the versionName and versionCode in the build.gradle file now, you can also remove them from your AndroidManifest.xml file, if they are there.

Regular expression for validating names and surnames?

I'll try to give a proper answer myself:

The only punctuations that should be allowed in a name are full stop, apostrophe and hyphen. I haven't seen any other case in the list of corner cases.

Regarding numbers, there's only one case with an 8. I think I can safely disallow that.

Regarding letters, any letter is valid.

I also want to include space.

This would sum up to this regex:

^[\p{L} \.'\-]+$

This presents one problem, i.e. the apostrophe can be used as an attack vector. It should be encoded.

So the validation code should be something like this (untested):

var name = nameParam.Trim();
if (!Regex.IsMatch(name, "^[\p{L} \.\-]+$")) 
    throw new ArgumentException("nameParam");
name = name.Replace("'", "&#39;");  //&apos; does not work in IE

Can anyone think of a reason why a name should not pass this test or a XSS or SQL Injection that could pass?


complete tested solution

using System;
using System.Text.RegularExpressions;

namespace test
{
    class MainClass
    {
        public static void Main(string[] args)
        {
            var names = new string[]{"Hello World", 
                "John",
                "João",
                "???",
                "???",
                "??",
                "??",
                "??????",
                "Te???e?a",
                "?????????",
                "???? ?????",
                "?????????",
                "??????",
                "?",
                "D'Addario",
                "John-Doe",
                "P.A.M.",
                "' --",
                "<xss>",
                "\""
            };
            foreach (var nameParam in names)
            {
                Console.Write(nameParam+" ");
                var name = nameParam.Trim();
                if (!Regex.IsMatch(name, @"^[\p{L}\p{M}' \.\-]+$"))
                {
                    Console.WriteLine("fail");
                    continue;
                }
                name = name.Replace("'", "&#39;");
                Console.WriteLine(name);
            }
        }
    }
}

What's the difference between event.stopPropagation and event.preventDefault?

_x000D_
_x000D_
$("#but").click(function(event){_x000D_
console.log("hello");_x000D_
  event.preventDefault();_x000D_
 });_x000D_
_x000D_
_x000D_
$("#foo").click(function(){_x000D_
 alert("parent click event fired !");_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<div id="foo">_x000D_
  <button id="but">button</button>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How do I connect to my existing Git repository using Visual Studio Code?

  1. Open Vs Code
  2. Go to view
  3. Click on terminal to open a terminal in VS Code
  4. Copy the link for your existing repository from your GitHub page.
  5. Type “git clone” and paste the link in addition i.e “git clone https://github.com/...”
  6. This will open the repository in your Vs Code Editor.

Best implementation for Key Value Pair Data Structure?

I think what you might be after (as a literal implementation of your question), is:

public class TokenTree
{
    public TokenTree()
    {
        tree = new Dictionary<string, IDictionary<string,string>>();
    }

    IDictionary<string, IDictionary<string, string>> tree; 
}

You did actually say a "list" of key-values in your question, so you might want to swap the inner IDictionary with a:

IList<KeyValuePair<string, string>>

align text center with android

Set also android:gravity parameter in TextView to center.

For testing the effects of different layout parameters I recommend to use different background color for every element, so you can see how your layout changes with parameters like gravity, layout_gravity or others.

How to make FileFilter in java?

Another simple example:

public static void listFilesInDirectory(String pathString) {
  // A local class (a class defined inside a block, here a method).
  class MyFilter implements FileFilter {
    @Override
    public boolean accept(File file) {
      return !file.isHidden() && file.getName().endsWith(".txt");
    }
  }

  File directory = new File(pathString);
  File[] files = directory.listFiles(new MyFilter());

  for (File fileLoop : files) {
    System.out.println(fileLoop.getName());
  }
}

// Call it
listFilesInDirectory("C:\\Users\\John\\Documents\\zTemp");

// Output
Cool.txt
RedditKinsey.txt
...

HTTP redirect: 301 (permanent) vs. 302 (temporary)

Status 301 means that the resource (page) is moved permanently to a new location. The client/browser should not attempt to request the original location but use the new location from now on.

Status 302 means that the resource is temporarily located somewhere else, and the client/browser should continue requesting the original url.

Html ordered list 1.1, 1.2 (Nested counters and scope) not working

I encountered similar problem recently. The fix is to set the display property of the li items in the ordered list to list-item, and not display block, and ensure that the display property of ol is not list-item. i.e

li { display: list-item;}

With this, the html parser sees all li as the list item and assign the appropriate value to it, and sees the ol, as an inline-block or block element based on your settings, and doesn't try to assign any count value to it.

Can I set variables to undefined or pass undefined as an argument?

The for if (something) and if (!something) is commonly used to check if something is defined or not defined. For example:

if (document.getElementById)

The identifier is converted to a boolean value, so undefined is interpreted as false. There are of course other values (like 0 and '') that also are interpreted as false, but either the identifier should not reasonably have such a value or you are happy with treating such a value the same as undefined.

Javascript has a delete operator that can be used to delete a member of an object. Depending on the scope of a variable (i.e. if it's global or not) you can delete it to make it undefined.

There is no undefined keyword that you can use as an undefined literal. You can omit parameters in a function call to make them undefined, but that can only be used by sending less paramters to the function, you can't omit a parameter in the middle.

Drop columns whose name contains a specific string from pandas DataFrame

Question states 'I want to drop all the columns whose name contains the word "Test".'

test_columns = [col for col in df if 'Test' in col]
df.drop(columns=test_columns, inplace=True)

Ternary operator in PowerShell

$result = If ($condition) {"true"} Else {"false"}

Everything else is incidental complexity and thus to be avoided.

For use in or as an expression, not just an assignment, wrap it in $(), thus:

write-host  $(If ($condition) {"true"} Else {"false"}) 

Vim delete blank lines

:g/^$/d

:g will execute a command on lines which match a regex. The regex is 'blank line' and the command is :d (delete)

How to printf a 64-bit integer as hex?

The warning from your compiler is telling you that your format specifier doesn't match the data type you're passing to it.

Try using %lx or %llx. For more portability, include inttypes.h and use the PRIx64 macro.

For example: printf("val = 0x%" PRIx64 "\n", val); (note that it's string concatenation)

How to validate date with format "mm/dd/yyyy" in JavaScript?

It's ok if you want to check validate dd/MM/yyyy

_x000D_
_x000D_
function isValidDate(date) {_x000D_
    var temp = date.split('/');_x000D_
    var d = new Date(temp[1] + '/' + temp[0] + '/' + temp[2]);_x000D_
     return (d && (d.getMonth() + 1) == temp[1] && d.getDate() == Number(temp[0]) && d.getFullYear() == Number(temp[2]));_x000D_
}_x000D_
_x000D_
alert(isValidDate('29/02/2015')); // it not exist ---> false_x000D_
            
_x000D_
_x000D_
_x000D_

file_put_contents - failed to open stream: Permission denied

Realise this is pretty old now, but there's no need to manually write queries to a file like this. MySQL has logging support built in, you just need to enable it within your dev environment.

Take a look at the documentation for the 'general query log':

http://dev.mysql.com/doc/refman/5.1/en/query-log.html

SQL Error with Order By in Subquery

This is the error you get (emphasis mine):

The ORDER BY clause is invalid in views, inline functions, derived tables, subqueries, and common table expressions, unless TOP or FOR XML is also specified.

So, how can you avoid the error? By specifying TOP, would be one possibility, I guess.

SELECT (
  SELECT TOP 100 PERCENT
  COUNT(1) FROM Seanslar WHERE MONTH(tarihi) = 4
  GROUP BY refKlinik_id
  ORDER BY refKlinik_id
) as dorduncuay

Custom seekbar (thumb size, color and background)

android:minHeight android:maxHeight is important for that.

<SeekBar
    android:id="@+id/pb"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:maxHeight="2dp"
    android:minHeight="2dp"
    android:progressDrawable="@drawable/seekbar_bg"
    android:thumb="@drawable/seekbar_thumb"
    android:max="100"
    android:progress="50"/>

seekbar_bg.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">
        <shape>
            <corners android:radius="3dp" />
            <solid android:color="#ECF0F1" />
        </shape>
    </item>
    <item android:id="@android:id/secondaryProgress">
        <clip>
            <shape>
                <corners android:radius="3dp" />
                <solid android:color="#C6CACE" />
            </shape>
        </clip>
    </item>
    <item android:id="@android:id/progress">
        <clip>
            <shape>
                <corners android:radius="3dp" />
                <solid android:color="#16BC5C" />
            </shape>
        </clip>
    </item>
</layer-list>

seekbar_thumb.xml

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="oval">
    <solid android:color="#16BC5C" />
    <stroke
        android:width="1dp"
        android:color="#16BC5C" />
    <size
        android:height="20dp"
        android:width="20dp" />
</shape>

What are enums and why are they useful?

From Java documents -

You should use enum types any time you need to represent a fixed set of constants. That includes natural enum types such as the planets in our solar system and data sets where you know all possible values at compile time—for example, the choices on a menu, command line flags, and so on.

A common example is to replace a class with a set of private static final int constants (within reasonable number of constants) with an enum type. Basically if you think you know all possible values of "something" at compile time you can represent that as an enum type. Enums provide readability and flexibility over a class with constants.

Few other advantages that I can think of enum types. They is always one instance of a particular enum class (hence the concept of using enums as singleton arrives). Another advantage is you can use enums as a type in switch-case statement. Also you can use toString() on the enum to print them as readable strings.

Printing a java map Map<String, Object> - How?

There is a get method in HashMap:

for (String keys : objectSet.keySet())  
{
   System.out.println(keys + ":"+ objectSet.get(keys));
}

How can I add a background thread to flask?

Your additional threads must be initiated from the same app that is called by the WSGI server.

The example below creates a background thread that executes every 5 seconds and manipulates data structures that are also available to Flask routed functions.

import threading
import atexit
from flask import Flask

POOL_TIME = 5 #Seconds

# variables that are accessible from anywhere
commonDataStruct = {}
# lock to control access to variable
dataLock = threading.Lock()
# thread handler
yourThread = threading.Thread()

def create_app():
    app = Flask(__name__)

    def interrupt():
        global yourThread
        yourThread.cancel()

    def doStuff():
        global commonDataStruct
        global yourThread
        with dataLock:
        # Do your stuff with commonDataStruct Here

        # Set the next thread to happen
        yourThread = threading.Timer(POOL_TIME, doStuff, ())
        yourThread.start()   

    def doStuffStart():
        # Do initialisation stuff here
        global yourThread
        # Create your thread
        yourThread = threading.Timer(POOL_TIME, doStuff, ())
        yourThread.start()

    # Initiate
    doStuffStart()
    # When you kill Flask (SIGTERM), clear the trigger for the next thread
    atexit.register(interrupt)
    return app

app = create_app()          

Call it from Gunicorn with something like this:

gunicorn -b 0.0.0.0:5000 --log-config log.conf --pid=app.pid myfile:app

GROUP BY to combine/concat a column

SELECT
     [User], Activity,
     STUFF(
         (SELECT DISTINCT ',' + PageURL
          FROM TableName
          WHERE [User] = a.[User] AND Activity = a.Activity
          FOR XML PATH (''))
          , 1, 1, '')  AS URLList
FROM TableName AS a
GROUP BY [User], Activity

What is the meaning of "operator bool() const"

I'd like to give more codes to make it clear.

struct A
{
    operator bool() const { return true; }
};

struct B
{
    explicit operator bool() const { return true; }
};

int main()
{
    A a1;
    if (a1) cout << "true" << endl; // OK: A::operator bool()
    bool na1 = a1; // OK: copy-initialization selects A::operator bool()
    bool na2 = static_cast<bool>(a1); // OK: static_cast performs direct-initialization

    B b1;     
    if (b1) cout << "true" << endl; // OK: B::operator bool()
    // bool nb1 = b1; // error: copy-initialization does not consider B::operator bool()
    bool nb2 = static_cast<bool>(b1); // OK: static_cast performs direct-initialization
}

successful/fail message pop up box after submit?

Instead of using a submit button, try using a <button type="button">Submit</button>

You can then call a javascript function in the button, and after the alert popup is confirmed, you can manually submit the form with document.getElementById("form").submit(); ... so you'll need to name and id your form for that to work.

How to check if running in Cygwin, Mac or Linux?

Usually, uname with its various options will tell you what environment you're running in:

pax> uname -a
CYGWIN_NT-5.1 IBM-L3F3936 1.5.25(0.156/4/2) 2008-06-12 19:34 i686 Cygwin

pax> uname -s
CYGWIN_NT-5.1

And, according to the very helpful schot (in the comments), uname -s gives Darwin for OSX and Linux for Linux, while my Cygwin gives CYGWIN_NT-5.1. But you may have to experiment with all sorts of different versions.

So the bash code to do such a check would be along the lines of:

unameOut="$(uname -s)"
case "${unameOut}" in
    Linux*)     machine=Linux;;
    Darwin*)    machine=Mac;;
    CYGWIN*)    machine=Cygwin;;
    MINGW*)     machine=MinGw;;
    *)          machine="UNKNOWN:${unameOut}"
esac
echo ${machine}

Note that I'm assuming here that you're actually running within CygWin (the bash shell of it) so paths should already be correctly set up. As one commenter notes, you can run the bash program, passing the script, from cmd itself and this may result in the paths not being set up as needed.

If you are doing that, it's your responsibility to ensure the correct executables (i.e., the CygWin ones) are being called, possibly by modifying the path beforehand or fully specifying the executable locations (e.g., /c/cygwin/bin/uname).

jQuery checkbox onChange

There is no need to use :checkbox, also replace #activelist with #inactivelist:

$('#inactivelist').change(function () {
    alert('changed');
 });

Parsing a JSON string in Ruby

This is a bit late but I ran into something interesting that seems important to contribute.

I accidentally wrote this code, and it seems to work:

require 'yaml'
CONFIG_FILE = ENV['CONFIG_FILE'] # path to a JSON config file 
configs = YAML.load_file("#{CONFIG_FILE}")
puts configs['desc']['someKey']

I was surprised to see it works since I am using the YAML library, but it works.

The reason why it is important is that yaml comes built-in with Ruby so there's no gem install.

I am using versions 1.8.x and 1.9.x - so the json library is not built in, but it is in version 2.x.

So technically - this is the easiest way to extract the data in version lower than 2.0.

GridView - Show headers on empty data source

I found a very simple solution to the problem. I simply created two GridViews. The first GridView called a DataSource with a query that was designed to return no rows. It simply contained the following:

    <Columns>
        <asp:TemplateField HeaderStyle-HorizontalAlign="Left">
            <HeaderTemplate>

               <asp:Label ID="lbl0" etc.>  </asp:Label>
               <asp:Label ID="lbl1" etc.>  </asp:Label>

            </HeaderTemplate>
        </asp:TemplateField>
    </Columns>

Then I created a div with the following characteristics and I place a GridView inside of it with ShowHeader="false" so that the top row is the same size as all the other rows.

<div style="overflow: auto; height: 29.5em; width: 100%">
    <asp:GridView ID="Rollup" runat="server" ShowHeader="false" DataSourceID="ObjectDataSource">
        <Columns>
            <asp:TemplateField HeaderStyle-HorizontalAlign="Left">
                <ItemTemplate>

               <asp:Label ID="lbl0" etc.>  </asp:Label>
               <asp:Label ID="lbl1" etc.>  </asp:Label>

                </ItemTemplate>
            </asp:TemplateField>
        </Columns>
    </asp:GridView>
</div>

Generating sql insert into for Oracle

If you have an empty table the Export method won't work. As a workaround. I used the Table View of Oracle SQL Developer. and clicked on Columns. Sorted by Nullable so NO was on top. And then selected these non nullable values using shift + select for the range.

This allowed me to do one base insert. So that Export could prepare a proper all columns insert.

Start an Activity with a parameter

I like to do it with a static method in the second activity:

private static final String EXTRA_GAME_ID = "your.package.gameId";

public static void start(Context context, String gameId) {
    Intent intent = new Intent(context, SecondActivity.class);
    intent.putExtra(EXTRA_GAME_ID, gameId);
    context.startActivity(intent);
}

@Override
protected void onCreate(Bundle savedInstanceState) {
    ... 
    Intent intent = this.getIntent();
    String gameId = intent.getStringExtra(EXTRA_GAME_ID);
}

Then from your first activity (and for anywhere else), you just do:

SecondActivity.start(this, "the.game.id");

convert datetime to date format dd/mm/yyyy

DateTime.ToString("dd/MM/yyyy") may give the date in dd-MM-yyyy format. This depends on your short date format. If short date format is not as per format, we have to replace character '-' with '/' as below:

 date = DateTime.Now.ToString("dd/MM/yyyy").Replace('-','/');

AWS - Disconnected : No supported authentication methods available (server sent :publickey)

There is another cause that would impact a previously working system. I re-created my instances (using AWS OpsWorks) to use Amazon Linux instead of Ubuntu, and received this error after doing so. Switching to use "ec2-user" as the username instead of "ubuntu" resolved the issue for me.

Count number of times value appears in particular column in MySQL

SELECT column_name, COUNT(column_name)
FROM table_name
GROUP BY column_name