Programs & Examples On #Rtp

The Real-time Transport Protocol (RTP) defines a standardized packet format for delivering audio and video over IP networks.

Streaming via RTSP or RTP in HTML5

With VLC i'm able to transcode a live RTSP stream (mpeg4) to an HTTP stream in a OGG format (Vorbis/Theora). The quality is poor but the video work in Chrome 9. I have also tested with a trancoding in WEBM (VP8) but it's don't seem to work (VLC have the option but i don't know if it's really implemented for now..)

The first to have a doc on this should notify us ;)

What is the difference between RTP or RTSP in a streaming server?

RTSP (actually RTP) can be used for streaming video, but also many other types of media including live presentations. Rtsp is just the protocol used to setup the RTP session.

For all the details you can check out my open source RTSP Server implementation on the following address:

Or my article @

It supports re-sourcing streams as well as the dynamic creation of streams, various RFC's are implemented and the library achieves better performance and less memory then FFMPEG and just about any other solutions in the transport layer and thus makes it a good candidate to use as a centralized point of access for most scenarios.

Copy-item Files in Folders and subfolders in the same directory structure of source server using PowerShell

I wanted a solution to copy files modified after a certain date and time which mean't I need to use Get-ChildItem piped through a filter. Below is what I came up with:

$SourceFolder = "C:\Users\RCoode\Documents\Visual Studio 2010\Projects\MyProject"
$ArchiveFolder = "J:\Temp\Robin\Deploy\MyProject"
$ChangesStarted = New-Object System.DateTime(2013,10,16,11,0,0)
$IncludeFiles = ("*.vb","*.cs","*.aspx","*.js","*.css")

Get-ChildItem $SourceFolder -Recurse -Include $IncludeFiles | Where-Object {$_.LastWriteTime -gt $ChangesStarted} | ForEach-Object {
    $PathArray = $_.FullName.Replace($SourceFolder,"").ToString().Split('\') 

    $Folder = $ArchiveFolder

    for ($i=1; $i -lt $PathArray.length-1; $i++) {
        $Folder += "\" + $PathArray[$i]
        if (!(Test-Path $Folder)) {
            New-Item -ItemType directory -Path $Folder
    $NewPath = Join-Path $ArchiveFolder $_.FullName.Replace($SourceFolder,"")

    Copy-Item $_.FullName -Destination $NewPath  

Launching Spring application Address already in use

first, check that who uses port 8080.

if the port 8080 is in use, change the listening port to 8181.

if you use IDEA, modify start configuration, Run-> Edit Configuration enter image description here

if you use mvn spring-boot, then use the command:

mvn spring-boot:run -Dserver.port=8181

if you use java -jar, then use the command:

java -jar xxxx.jar --server.port=8181

Interface type check with Typescript

Working with string literals is difficult because if you want to refactor you method or interface names then it could be possible that your IDE don't refactor these string literals. I provide you mine solution which works if there is at least one method in the interface

export class SomeObject implements interfaceA {
  public methodFromA() {}

export interface interfaceA {

Check if object is of type interface:

const obj = new SomeObject();
const objAsAny = obj as any;
const objAsInterfaceA = objAsAny as interfaceA;
const isObjOfTypeInterfaceA = objAsInterfaceA.methodFromA != null;

Note: We will get true even if we remove 'implements interfaceA' because the method still exists in the SomeObject class

Sleep function in C++

The simplest way I found for C++ 11 was this:

Your includes:

#include <chrono>
#include <thread>

Your code (this is an example for sleep 1000 millisecond):

std::chrono::duration<int, std::milli> timespan(1000);

The duration could be configured to any of the following:

std::chrono::nanoseconds   duration</*signed integer type of at least 64 bits*/, std::nano>
std::chrono::microseconds  duration</*signed integer type of at least 55 bits*/, std::micro>
std::chrono::milliseconds  duration</*signed integer type of at least 45 bits*/, std::milli>
std::chrono::seconds       duration</*signed integer type of at least 35 bits*/, std::ratio<1>>  
std::chrono::minutes       duration</*signed integer type of at least 29 bits*/, std::ratio<60>>
std::chrono::hours         duration</*signed integer type of at least 23 bits*/, std::ratio<3600>>

Detect network connection type on Android

On top of Emil's awsome answer I'd like to add one more method, for checking if you actually have Internet access as you could have data set to off on your phone.

public static boolean hasInternetAccess(Context c){
    TelephonyManager tm = (TelephonyManager) c.getSystemService(Context.TELEPHONY_SERVICE);
    if(isConnected(c) && tm.getDataState() == TelephonyManager.DATA_CONNECTED)
       return true;
        return false;

Note that this is only for checking if theres a cellular data connection and will return false if you have WiFi connected, as the cellular data is off when WiFi is connected.

Remove Elements from a HashSet while Iterating

The reason you get a ConcurrentModificationException is because an entry is removed via Set.remove() as opposed to Iterator.remove(). If an entry is removed via Set.remove() while an iteration is being done, you will get a ConcurrentModificationException. On the other hand, removal of entries via Iterator.remove() while iteration is supported in this case.

The new for loop is nice, but unfortunately it does not work in this case, because you can't use the Iterator reference.

If you need to remove an entry while iteration, you need to use the long form that uses the Iterator directly.

for (Iterator<Integer> it = set.iterator(); it.hasNext();) {
    Integer element =;
    if (element % 2 == 0) {

How to request Location Permission at runtime

After having it defined in your manifest file, a friendlier alternative to the native solution would be using Aaper: like so:

@EnsurePermissions(permissions = [Manifest.permission.ACCESS_FINE_LOCATION])
private fun scanForLocation() {
    // Your code that needs the location permission granted.

Disclaimer, I'm the creator of Aaper.

All combinations of a list of lists

One can use base python for this. The code needs a function to flatten lists of lists:

def flatten(B):    # function needed for code below;
    A = []
    for i in B:
        if type(i) == list: A.extend(i)
        else: A.append(i)
    return A

Then one can run:

L = [[1,2,3],[4,5,6],[7,8,9,10]]

outlist =[]; templist =[[]]
for sublist in L:
    outlist = templist; templist = [[]]
    for sitem in sublist:
        for oitem in outlist:
            newitem = [oitem]
            if newitem == [[]]: newitem = [sitem]
            else: newitem = [newitem[0], sitem]

outlist = list(filter(lambda x: len(x)==len(L), templist))  # remove some partial lists that also creep in;


[[1, 4, 7], [2, 4, 7], [3, 4, 7], 
[1, 5, 7], [2, 5, 7], [3, 5, 7], 
[1, 6, 7], [2, 6, 7], [3, 6, 7], 
[1, 4, 8], [2, 4, 8], [3, 4, 8], 
[1, 5, 8], [2, 5, 8], [3, 5, 8], 
[1, 6, 8], [2, 6, 8], [3, 6, 8], 
[1, 4, 9], [2, 4, 9], [3, 4, 9], 
[1, 5, 9], [2, 5, 9], [3, 5, 9], 
[1, 6, 9], [2, 6, 9], [3, 6, 9], 
[1, 4, 10], [2, 4, 10], [3, 4, 10], 
[1, 5, 10], [2, 5, 10], [3, 5, 10], 
[1, 6, 10], [2, 6, 10], [3, 6, 10]]

Animate change of view background color on Android

best way is to use ValueAnimator and ColorUtils.blendARGB

 ValueAnimator valueAnimator = ValueAnimator.ofFloat(0.0f, 1.0f);
 valueAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
        public void onAnimationUpdate(ValueAnimator valueAnimator) {

              float fractionAnim = (float) valueAnimator.getAnimatedValue();

                                    , Color.parseColor("#000000")
                                    , fractionAnim));

Jackson overcoming underscores in favor of camel-case

If its a spring boot application, In file, just use

Or Annotate the model class with this annotation.


Java Timer vs ExecutorService?

Here's some more good practices around Timer use:

In general, I'd use Timer for quick and dirty stuff and Executor for more robust usage.

Google API for location, based on user IP address

Google already appends location data to all requests coming into GAE (see Request Header documentation for go, java, php and python). You should be interested X-AppEngine-Country, X-AppEngine-Region, X-AppEngine-City and X-AppEngine-CityLatLong headers.

An example looks like this:


CASE WHEN statement for ORDER BY clause

declare @OrderByCmd  nvarchar(2000)
declare @OrderByName nvarchar(100)
declare @OrderByCity nvarchar(100)
set @OrderByName='Name'    
set @OrderByCity='city'
set @OrderByCmd= 'select * from customer Order By '+@OrderByName+','+@OrderByCity+''
EXECUTE sp_executesql @OrderByCmd 

Send POST data using XMLHttpRequest


Select the below code and drag that into in BOOKMARK BAR (if you don't see it, enable from Browser Settings), then EDIT that link :

enter image description here

javascript:var my_params = prompt("Enter your parameters", "var1=aaaa&var2=bbbbb"); var Target_LINK = prompt("Enter destination", location.href); function post(path, params) { var xForm = document.createElement("form"); xForm.setAttribute("method", "post"); xForm.setAttribute("action", path); for (var key in params) { if (params.hasOwnProperty(key)) { var hiddenField = document.createElement("input"); hiddenField.setAttribute("name", key); hiddenField.setAttribute("value", params[key]); xForm.appendChild(hiddenField); } } var xhr = new XMLHttpRequest(); xhr.onload = function () { alert(xhr.responseText); };, xForm.action, true); xhr.send(new FormData(xForm)); return false; } parsed_params = {}; my_params.split("&").forEach(function (item) { var s = item.split("="), k = s[0], v = s[1]; parsed_params[k] = v; }); post(Target_LINK, parsed_params); void(0);

That's all! Now you can visit any website, and click that button in BOOKMARK BAR!


The above method sends data using XMLHttpRequest method, so, you have to be on the same domain while triggering the script. That's why I prefer sending data with a simulated FORM SUBMITTING, which can send the code to any domain - here is code for that:

 javascript:var my_params=prompt("Enter your parameters","var1=aaaa&var2=bbbbb"); var Target_LINK=prompt("Enter destination", location.href); function post(path, params) {   var xForm= document.createElement("form");   xForm.setAttribute("method", "post");   xForm.setAttribute("action", path); xForm.setAttribute("target", "_blank");   for(var key in params) {   if(params.hasOwnProperty(key)) {        var hiddenField = document.createElement("input");      hiddenField.setAttribute("name", key);      hiddenField.setAttribute("value", params[key]);         xForm.appendChild(hiddenField);     }   }   document.body.appendChild(xForm);  xForm.submit(); }   parsed_params={}; my_params.split("&").forEach(function(item) {var s = item.split("="), k=s[0], v=s[1]; parsed_params[k] = v;}); post(Target_LINK, parsed_params); void(0); 

Why have header files and .cpp files?

Because C++ inherited them from C. Unfortunately.

Validating a Textbox field for only numeric input.

Here is another simple solution

    int temp=Convert.ToInt32(txtEvDistance.Text);
catch(Exception h)
    MessageBox.Show("Please provide number only");

Pass variables to AngularJS controller, best practice?

You could use ng-init in an outer div:

<div ng-init="param='value';">
    <div ng-controller="BasketController" >
        <label>param: {{value}}</label>

The parameter will then be available in your controller's scope:

function BasketController($scope) {

Long Press in JavaScript?

$(document).ready(function () {
    var longpress = false;

    $("button").on('click', function () {
        (longpress) ? alert("Long Press") : alert("Short Press");

    var startTime, endTime;
    $("button").on('mousedown', function () {
        startTime = new Date().getTime();

    $("button").on('mouseup', function () {
        endTime = new Date().getTime();
        longpress = (endTime - startTime < 500) ? false : true;


Spring Boot - Cannot determine embedded database driver class for database type NONE

The same to @Anas. I can run it in Eclipse, but when i use "java -jar ..." run it, it giving me this error. Then i find my java build path is wrong, it missing the folder “src/main/resources”, so, the application can't find When i add the “src/main/resources” folder in java build path, it worked.

And, you need add "@PropertySource({""})" in your Application class.




I've personally never found it useful to set M2_HOME.

What counts is your $PATH environment. Hijacking part of the answer from Danix, all you need is:

export PATH=/Users/xxx/sdk/apache-maven-3.0.5/bin:$PATH

The mvn script computes M2_HOME for you anyway for what it's worth.

How can I get the last character in a string?

You should look at charAt function and take length of the string.

var b = 'I am a JavaScript hacker.';

Generate getters and setters in NetBeans

Position the cursor inside the class, then press ALT + Ins and select Getters and Setters from the contextual menu.

Swift error : signal SIGABRT how to solve it

Sometimes it also happens when the function need to be executed in main thread only, so you can fix it by assigning it to the main thread as follows :-

  your code here

Check if all values of array are equal

Yes, you can check it also using filter as below, very simple, checking every values are the same as the first one:

function sameValues(arr) {
  return arr.filter((v,i,a)=>v===a[0]).length === arr.length;

also can be done using every method on the array:

function sameValues(arr) {
  return arr.every((v,i,a)=>v===a[0]);

and you can check your arrays like below:

sameValues(['a', 'a', 'a', 'a']); // true
sameValues(['a', 'a', 'b', 'a']); // false

Or you can add it to native Array functionalities in JavaScript if you reuse it a lot:

Array.prototype.sameValues = Array.prototype.sameValues || function(){

and you can check your arrays like below:

['a', 'a', 'a', 'a'].sameValues(); // true
['a', 'a', 'b', 'a'].sameValues(); // false

How to get an array of unique values from an array containing duplicates in JavaScript?

It's 2014 now guys, and time complexity still matters!

array.filter(function() {
  var seen = {};
  return function(element, index, array) {
    return !(element in seen) && (seen[element] = 1);

What is the best way to connect and use a sqlite database from C#

ADO.NET 2.0 Provider for SQLite has over 200 downloads every day, so I think you are safe using that one.

How to select the last column of dataframe

Just to add to @Anshul Singh Suryan's answer:

When we split the dataframe to just get the last column:

If we split like:

y = df.iloc[:,-1:] - y remains a dataframe

However, if we split like

y = df.iloc[:,-1] - y becomes a Series.

This is a notable difference that I've found in the two approaches. If you don't care about the resultant type, you can use either of the two. Otherwise you need to take care of the above findings.

This is applicable for any number of rows you want to extract and not just the last row. For example, if you want last n number of rows of a dataframe, where n is any integer less than or equal to the number of columns present in the dataframe, then you can easily do the following:

y = df.iloc[:,n:]

Replace n by the number of columns you want. Same is true for rows as well.

bootstrap datepicker change date event doesnt fire up when manually editing dates or clearing date

Depending which date picker for Bootstrap you're using, this is a known bug currently with this one:



Here's a bug report:

If anyone has a solution/workaround for this one, would be great if you'd include it.

How to do join on multiple criteria, returning all combinations of both criteria

select one.*, two.meal
from table1 as one
left join table2 as two
on (one.weddingtable = two.weddingtable and one.tableseat = two.tableseat)

php random x digit number

rand or mt_rand will do...


rand(min, max);

mt_rand(min, max);

How to read integer values from text file

I would use nearly the same way but with list as buffer for read integers:

static Object[] readFile(String fileName) {
    Scanner scanner = new Scanner(new File(fileName));
    List<Integer> tall = new ArrayList<Integer>();
    while (scanner.hasNextInt()) {

    return tall.toArray();

In C# check that filename is *possibly* valid (not that it exists)

I don't know of anything out of the box that can just validate all of that for you, however the Path class in .NET can help you out tremendously.

For starters, it has:

char[] invalidChars = Path.GetInvalidFileNameChars(); //returns invalid charachters


Path.GetPathRoot(string); // will return the root.

How to Parse a JSON Object In Android

In your JSON format, it do not have starting JSON object

Like :

    "info" :       <!-- this is starting JSON object -->

Above Json starts with info as JSON object. So while executing :

JSONObject json = new JSONObject(result);    // create JSON obj from string
JSONObject json2 = json.getJSONObject("info");    // this will return correct

Now, we can access result field :

JSONObject jsonResult = json2.getJSONObject("results");
test = json2.getString("name"); // returns "Marina Rasche Werft GmbH & Co. KG"

I think this was missing and so the problem was solved while we use JSONTokener like answer of yours.

Your answer is very fine. Just i think i add this information so i answered

Thank you

Links in <select> dropdown options

Maybe this will help:

<select onchange="location = this.value;">
 <option value="home.html">Home</option>
 <option value="contact.html">Contact</option>
 <option value="about.html">About</option>

Disabling right click on images using jquery

This should work

     $('body').on('contextmenu', 'img', function(e){ 
         return false; 

C - function inside struct

It can't be done directly, but you can emulate the same thing using function pointers and explicitly passing the "this" parameter:

typedef struct client_t client_t, *pno;
struct client_t
        pid_t pid;
        char password[TAM_MAX]; // -> 50 chars
        pno next;

        pno (*AddClient)(client_t *);    

pno client_t_AddClient(client_t *self) { /* code */ }

int main()

    client_t client;
    client.AddClient = client_t_AddClient; // probably really done in some init fn

    //code ..



It turns out that doing this, however, doesn't really buy you an awful lot. As such, you won't see many C APIs implemented in this style, since you may as well just call your external function and pass the instance.

'printf' vs. 'cout' in C++

Of course you can write "something" a bit better to keep maintenance:

#include <iostream>
#include <cstdlib>

using namespace std;

class Something
        Something(int x, int y, int z) : a(x), b(y), c(z) { }
        int a;
        int b;
        int c;

        friend ostream& operator<<(ostream&, const Something&);

        void print() const { printf("%i, %i, %i\n", a, b, c); }

ostream& operator<<(ostream& o, const Something& s)
    o << s.a << ", " << s.b << ", " << s.c;
    return o;

int main(void)
    Something s(3, 2, 1);

    // Output with printf
    s.print(); // Simple as well, isn't it?

    // Output with cout
    cout << s << endl;

    return 0;

And a bit extended test of cout vs. printf, added a test of 'double', if anyone wants to do more testing (Visual Studio 2008, release version of the executable):

#include <stdio.h>
#include <iostream>
#include <ctime>

class TimedSection {
    char const *d_name;
    //timespec d_start;
    clock_t d_start;

        TimedSection(char const *name) :
            //clock_gettime(CLOCK_REALTIME, &d_start);
            d_start = clock();
        ~TimedSection() {
            clock_t end;
            //clock_gettime(CLOCK_REALTIME, &end);
            end = clock();
            double duration = /*1e3 * (end.tv_sec - d_start.tv_sec) +
                              1e-6 * (end.tv_nsec - d_start.tv_nsec);
                              (double) (end - d_start) / CLOCKS_PER_SEC;

            std::cerr << d_name << '\t' << std::fixed << duration * 1000.0 << " ms\n";

int main() {
    const int iters = 1000000;
    char const *text = "01234567890123456789";
        TimedSection s("cout with only endl");
        for (int i = 0; i < iters; ++i)
            std::cout << std::endl;
        TimedSection s("cout with only '\\n'");
        for (int i = 0; i < iters; ++i)
            std::cout << '\n';
        TimedSection s("printf with only '\\n'");
        for (int i = 0; i < iters; ++i)
        TimedSection s("cout with string constant and endl");
        for (int i = 0; i < iters; ++i)
            std::cout << "01234567890123456789" << std::endl;
        TimedSection s("cout with string constant and '\\n'");
        for (int i = 0; i < iters; ++i)
            std::cout << "01234567890123456789\n";
        TimedSection s("printf with string constant and '\\n'");
        for (int i = 0; i < iters; ++i)
        TimedSection s("cout with some stuff and endl");
        for (int i = 0; i < iters; ++i)
            std::cout << text << "01234567890123456789" << i << std::endl;
        TimedSection s("cout with some stuff and '\\n'");
        for (int i = 0; i < iters; ++i)
            std::cout << text << "01234567890123456789" << i << '\n';
        TimedSection s("printf with some stuff and '\\n'");
        for (int i = 0; i < iters; ++i)
            printf("%s01234567890123456789%i\n", text, i);
        TimedSection s("cout with formatted double (width & precision once)");
        std::cout << std::fixed << std::scientific << std::right << std::showpoint;
        for (int i = 0; i < iters; ++i)
            std::cout << text << 8.315 << i << '\n';
        TimedSection s("cout with formatted double (width & precision on each call)");
        std::cout << std::fixed << std::scientific << std::right << std::showpoint;

        for (int i = 0; i < iters; ++i)
            { std::cout.width(8);
              std::cout << text << 8.315 << i << '\n';
        TimedSection s("printf with formatted double");
        for (int i = 0; i < iters; ++i)
            printf("%8.3f%i\n", 8.315, i);

The result is:

cout with only endl    6453.000000 ms
cout with only '\n'    125.000000 ms
printf with only '\n'    156.000000 ms
cout with string constant and endl    6937.000000 ms
cout with string constant and '\n'    1391.000000 ms
printf with string constant and '\n'    3391.000000 ms
cout with some stuff and endl    9672.000000 ms
cout with some stuff and '\n'    7296.000000 ms
printf with some stuff and '\n'    12235.000000 ms
cout with formatted double (width & precision once)    7906.000000 ms
cout with formatted double (width & precision on each call)    9141.000000 ms
printf with formatted double    3312.000000 ms

When do you use varargs in Java?

In Java doc of Var-Args it is quite clear the usage of var args:

about usage it says:

"So when should you use varargs? As a client, you should take advantage of them whenever the API offers them. Important uses in core APIs include reflection, message formatting, and the new printf facility. As an API designer, you should use them sparingly, only when the benefit is truly compelling. Generally speaking, you should not overload a varargs method, or it will be difficult for programmers to figure out which overloading gets called. "

What are ODEX files in Android?


According to the docs: an .odex file:

contains AOT compiled code for methods in the APK.

Furthermore, they appear to be regular shared libraries, since if you get any app, and check:

file /data/app/*/oat/arm64/base.odex

it says:

base.odex: ELF shared object, 64-bit LSB arm64, stripped

and aarch64-linux-gnu-objdump -d base.odex seems to work and give some meaningful disassembly (but also some rubbish sections).

Update int column in table with unique incrementing values

DECLARE @IncrementValue int
SET @IncrementValue = 0 
UPDATE Samples SET qty = @IncrementValue,@IncrementValue=@IncrementValue+1

Eclipse gives “Java was started but returned exit code 13”

When I uninstalled Java 8 it worked fine.

Difference between multitasking, multithreading and multiprocessing?

Multi-programming :-

More than one task(job) process can reside into main memory at a time. It is basically design to reduce CPU wastage during I/O operation , example : if a job is executing currently and need I/O operation . I/O operation is done using DMA and processor assign to some Other job from the job queue till I/O operation of job1 completed . then job1 continue again . In this way it reduce CPU wastage .

How to reload page the page with pagination in Angular 2?

This should technically be achievable using window.location.reload():


<button (click)="refresh()">Refresh</button>


refresh(): void {


Here is a basic StackBlitz example showing the refresh in action. Notice the URL on "/hello" path is retained when window.location.reload() is executed.

Android Studio - Emulator - eglSurfaceAttrib not implemented

I've found the same thing, but only on emulators that have the Use Host GPU setting ticked. Try turning that off, you'll no longer see those warnings (and the emulator will run horribly, horribly slowly..)

In my experience those warnings are harmless. Notice that the "error" is EGL_SUCCESS, which would seem to indicate no error at all!

How can I create a progress bar in Excel VBA?

Hi modified version of another post by Marecki. Has 4 styles

1. dots ....
2  10 to 1 count down
3. progress bar (default)
4. just percentage.

Before you ask why I didn't edit that post is I did and it got rejected was told to post a new answer.

Sub ShowProgress()

  Const x As Long = 150000
  Dim i&, PB$

  For i = 1 To x
  UpdateProgress i, x
  Next i

  Application.StatusBar = ""
End Sub 'ShowProgress

Sub UpdateProgress(icurr As Long, imax As Long, Optional istyle As Integer = 3)
    Dim PB$
    PB = Format(icurr / imax, "00 %")
    If istyle = 1 Then ' text dots >>....    <<'
        Application.StatusBar = "Progress: " & PB & "  >>" & String(Val(PB), Chr(183)) & String(100 - Val(PB), Chr(32)) & "<<"
    ElseIf istyle = 2 Then ' 10 to 1 count down  (eight balls style)
        Application.StatusBar = "Progress: " & PB & "  " & ChrW$(10111 - Val(PB) / 11)
    ElseIf istyle = 3 Then ' solid progres bar (default)
        Application.StatusBar = "Progress: " & PB & "  " & String(100 - Val(PB), ChrW$(9608))
    Else ' just 00 %
        Application.StatusBar = "Progress: " & PB
    End If
End Sub

Create Django model or update if exists

This should be the answer you are looking for

    #id or any primary key:value to search for
    #if found update with the following or save/create if not found

How to delete a stash created with git stash create?

From git doc:

drop [-q|--quiet] []

Remove a single stashed state from the stash list. When no is given, it removes the latest one. i.e. stash@{0}, otherwise must be a valid stash log reference of the form stash@{}.


git stash drop stash@{5}

This would delete the stash entry 5. To see all the list of stashes:

git stash list

How to make a page redirect using JavaScript?


window.location = "";

Here's some quick-n-dirty code that uses jQuery to do what you want. I highly recommend using jQuery. It'll make things a lot more easier for you, especially since you're new to JavaScript.

<select id = "pricingOptions" name = "pricingOptions">
    <option value = "500">Option A</option>
    <option value = "1000">Option B</option>

<script type = "text/javascript" language = "javascript">
    jQuery(document).ready(function() {
        jQuery("#pricingOptions").change(function() {
            if(this.options[this.selectedIndex].value == "500") {
                window.location = "";

Python strftime - date without leading 0?

For %d you can convert to integer using int() then it'll automatically remove leading 0 and becomes integer. You can then convert back to string using str().

Hibernate table not mapped error in HQL query

hibernate3.HibernateQueryException: Books is not mapped [SELECT COUNT(*) FROM Books];

Hibernate is trying to say that it does not know an entity named "Books". Let's look at your entity:

@javax.persistence.Table(name = "Books")
public class Book {

Right. The table name for Book has been renamed to "Books" but the entity name is still "Book" from the class name. If you want to set the entity name, you should use the @Entity annotation's name instead:

// this allows you to use the entity Books in HQL queries
@javax.persistence.Entity(name = "Books")
public class Book {

That sets both the entity name and the table name.

The opposite problem happened to me when I was migrating from the Person.hbm.xml file to using the Java annotations to describe the hibernate fields. My old XML file had:

<hibernate-mapping package="...">
    <class name="Person" table="persons" lazy="true">

And my new entity had a @Entity(name=...) which I needed to set the name of the table.

// this renames the entity and sets the table name
@javax.persistence.Entity(name = "persons")
public class Person {

What I then was seeing was HQL errors like:

QuerySyntaxException: Person is not mapped
     [SELECT id FROM Person WHERE id in (:ids)]

The problem with this was that the entity name was being renamed to persons as well. I should have set the table name using:

// no name = here so the entity can be used as Person
// table name specified here
@javax.persistence.Table(name = "persons")
public class Person extends BaseGeneratedId {

Hope this helps others.

Making a drop down list using swift?

(Swift 3) Add text box and uipickerview to the storyboard then add delegate and data source to uipickerview and add delegate to textbox. Follow video for assistance

import UIKit

class ViewController: UIViewController, UIPickerViewDelegate, UIPickerViewDataSource, UITextFieldDelegate {

    @IBOutlet weak var textBox: UITextField!
    @IBOutlet weak var dropDown: UIPickerView!

    var list = ["1", "2", "3"]

    public func numberOfComponents(in pickerView: UIPickerView) -> Int{
        return 1

    public func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int{

        return list.count

    func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {

        return list[row]

    func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {

        self.textBox.text = self.list[row]
        self.dropDown.isHidden = true

    func textFieldDidBeginEditing(_ textField: UITextField) {

        if textField == self.textBox {
            self.dropDown.isHidden = false
            //if you don't want the users to se the keyboard type:


Responsive background image in div full width

Here is one way of getting the design that you want.

Start with the following HTML:

<div class="container">
    <div class="row-fluid">
        <div class="span12">
            <div class="nav">nav area</div>
            <div class="bg-image">
                <img src="">
                 <h1>This is centered text.</h1>
            <div class="main">main area</div>

Note that the background image is now part of the regular flow of the document.

Apply the following CSS:

.bg-image {
    position: relative;
.bg-image img {
    display: block;
    width: 100%;
    max-width: 1200px; /* corresponds to max height of 450px */
    margin: 0 auto;
.bg-image h1 {
    position: absolute;
    text-align: center;
    bottom: 0;
    left: 0;
    right: 0;
    color: white;
.nav, .main {
    background-color: #f6f6f6;
    text-align: center;

How This Works

The image is set an regular flow content with a width of 100%, so it will adjust itself responsively to the width of the parent container. However, you want the height to be no more than 450px, which corresponds to the image width of 1200px, so set the maximum width of the image to 1200px. You can keep the image centered by using display: block and margin: 0 auto.

The text is painted over the image by using absolute positioning. In the simplest case, I stretch the h1 element to be the full width of the parent and use text-align: center to center the text. Use the top or bottom offsets to place the text where it is needed.

If your banner images are going to vary in aspect ratio, you will need to adjust the maximum width value for .bg-image img dynamically using jQuery/Javascript, but otherwise, this approach has a lot to offer.

See demo at:

Send JSON data with jQuery

It gets serialized so that the URI can read the name value pairs in the POST request by default. You could try setting processData:false to your list of params. Not sure if that would help.

jQuery - How to dynamically add a validation rule

To validate all dynamically generated elements could add a special class to each of these elements and use each() function, something like

$("#DivIdContainer .classToValidate").each(function () {
    $(this).rules('add', {
        required: true

Shell - Write variable contents to a file

All of the above work, but also have to work around a problem (escapes and special characters) that doesn't need to occur in the first place: Special characters when the variable is expanded by the shell. Just don't do that (variable expansion) in the first place. Use the variable directly, without expansion.

Also, if your variable contains a secret and you want to copy that secret into a file, you might want to not have expansion in the command line as tracing/command echo of the shell commands might reveal the secret. Means, all answers which use $var in the command line may have a potential security risk by exposing the variable contents to tracing and logging of the shell.

Use this:

printenv var >file

That means, in case of the OP question:

printenv var >"$destfile"

Note: variable names are case sensitive.

How do I make flex box work in safari?

It works when you set the display value of your menu items from display: inline-block; to display: block;

See your updated code here:

#menu {
    clear: both;
    height: auto;
    font-family: Arial, Tahoma, Verdana;
    font-size: 1em;
    margin: 5px;
    display: -webkit-box; /* OLD - iOS 6-, Safari 3.1-6 */
    display: -moz-box;    /* OLD - Firefox 19- (buggy but mostly works) */
    display: -ms-flexbox;  /* TWEENER - IE 10 */
    display: -webkit-flex; /* NEW - Chrome */
    display: flex;         /* NEW, Spec - Opera 12.1, Firefox 20+ */
    justify-content: center;
    -webkit-box-align: center;
    -webkit-flex-align: center;
    -ms-flex-align: center;
    -webkit-align-items: center;
    align-items: center;fffff
    font-style: normal;
    font-weight: 400px;

#menu a:link {
    display: block; //here you need to change the display property
    width: 100px;
    height: 50px;
    padding: 5px;
    background-color: yellow;
    /*border: 1px solid #cccccc;*/
    margin: 5px;
    display: flex;
    flex-grow: 1;
    align-items: center;
    text-align: center;
    justify-content: center;
    font-weight: bold;
    color: #1689D6;
    font-size: 85%;
#menu a:visited {
    //no display property here                                                                       
    width: 100px;
    height: 50px;
    padding: 5px;
    background-color: yellow;
    /*border: 1px solid #cccccc;*/
    margin: 5px;
    display: flex;
    flex-grow: 1;
    align-items: center;
    text-align: center;
    justify-content: center;
    font-weight: bold;
    color: #1689D6;
    font-size: 85%;
#menu a:hover {
    //no display property here                                                                               
    color: #fff;
    width: 100px;
    height: 50px;
    padding: 5px;
    background-color: red;
    /*border: 1px solid #cccccc;*/
    margin: 5px;
    display: flex;
    flex-grow: 1;
    align-items: center;
    text-align: center;
    justify-content: center;
    font-weight: bold;
    font-size: 85%;
#menu a:active {
    //no display property here                                                                               
    color: #fff;
    width: 100px;
    height: 50px;
    padding-top: 5px;
    padding-right: 5px;
    padding-left: 5px;
    padding-bottom: 5px;
    background-color: red;
    /*border: 1px solid #cccccc;*/
    margin: 5px;
    display: flex;
    flex-grow: 1;
    align-items: center;
    text-align: center;
    justify-content: center;
    font-style: normal;
    font-weight: bold;
    font-size: 85%;

How to use pull to refresh in Swift?

Swift 5

private var pullControl = UIRefreshControl()

pullControl.attributedTitle = NSAttributedString(string: "Pull to refresh")
        pullControl.addTarget(self, action: #selector(refreshListData(_:)), for: .valueChanged)
        if #available(iOS 10.0, *) {
            tableView.refreshControl = pullControl
        } else {
// Actions
@objc private func refreshListData(_ sender: Any) {
        self.pullControl.endRefreshing() // You can stop after API Call
        // Call API

Create XML file using java

Just happened to work at this also, use the example from here, and read the explanations. Also I provide you my own example:

DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
        Document doc = dBuilder.newDocument();
        // root element

Element rootElement = doc.createElement("words");
while (ptbt.hasNext()) {
                CoreLabel label =;

                m = r1.matcher(label.toString());
                if (m.find() == true) {
                    Element w = doc.createElement("word");                  

TransformerFactory transformerFactory = TransformerFactory.newInstance();
        Transformer transformer = transformerFactory.newTransformer();
        DOMSource source = new DOMSource(doc);
        StreamResult result = new StreamResult(new File("C:\\Users\\workspace\\Tokenizer\\tokens.xml"));
        transformer.transform(source, result);
        // Output to console for testing
        StreamResult consoleResult = new StreamResult(System.out);
        transformer.transform(source, consoleResult);

This is in the context of using the tokenizer from Stanford for Natural Language Processing, just a part of it to make an idea on how to add elements. The output is: Billbuyedapples (I've read the sentence from a file)

Put content in HttpResponseMessage object?

For a string specifically, the quickest way is to use the StringContent constructor

response.Content = new StringContent("Your response text");

There are a number of additional HttpContent class descendants for other common scenarios.

How do you add an image?

Shouldn't that be:

<xsl:value-of select="/root/Image/img/@src"/>

? It looks like you are trying to copy the entire Image/img node to the attribute @src

Apache giving 403 forbidden errors

You can try disabling selinux and try once again using the following command

setenforce 0

Python Threading String Arguments

from threading import Thread
from time import sleep
def run(name):
    for x in range(10):
        print("helo "+name)
def run1():
    for x in range(10):

Parse v. TryParse

double.Parse("-"); raises an exception, while double.TryParse("-", out parsed); parses to 0 so I guess TryParse does more complex conversions.

How do I delete an item or object from an array using ng-click?

implementation Without a Controller.

<!DOCTYPE html>_x000D_
<script src=""></script>_x000D_
  var app = angular.module("myShoppingList", []); _x000D_
<div ng-app="myShoppingList"  ng-init="products = ['Milk','Bread','Cheese']">_x000D_
    <li ng-repeat="x in products track by $index">{{x}}_x000D_
      <span ng-click="products.splice($index,1)">×</span>_x000D_
  <input ng-model="addItem">_x000D_
  <button ng-click="products.push(addItem)">Add</button>_x000D_
<p>Click the little x to remove an item from the shopping list.</p>_x000D_

The splice() method adds/removes items to/from an array.

array.splice(index, howmanyitem(s), item_1, ....., item_n)

index: Required. An integer that specifies at what position to add/remove items, Use negative values to specify the position from the end of the array.

howmanyitem(s): Optional. The number of items to be removed. If set to 0, no items will be removed.

item_1, ..., item_n: Optional. The new item(s) to be added to the array

div background color, to change onhover

You can just put the anchor around the div.

<a class="big-link"><div>this is a div</div></a>

and then

a.big-link {
background-color: 888;
a.big-link:hover {
 background-color: f88;

How can I take a screenshot/image of a website using Python?

I created a library called pywebcapture that wraps selenium that will do just that:

pip install pywebcapture

Once you install with pip, you can do the following to easily get full size screenshots:

# import modules
from pywebcapture import loader, driver

# load csv with urls
csv_file = loader.CSVLoader("csv_file_with_urls.csv", has_header_bool, url_column, optional_filename_column)
uri_dict = csv_file.get_uri_dict()

# create instance of the driver and run
d = driver.Driver("path/to/webdriver/", output_filepath, delay, uri_dict)


What is the difference between RTP or RTSP in a streaming server?

I think thats correct. RTSP may use RTP internally.

How do you trigger a block after a delay, like -performSelector:withObject:afterDelay:?

I think you're looking for dispatch_after(). It requires your block to accept no parameters, but you can just let the block capture those variables from your local scope instead.

int parameter1 = 12;
float parameter2 = 144.1;

// Delay execution of my block for 10 seconds.
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 10 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
    NSLog(@"parameter1: %d parameter2: %f", parameter1, parameter2);


Append to string variable

var str1 = 'abc';
var str2 = str1+' def'; // str2 is now 'abc def'

Why so red? IntelliJ seems to think every declaration/method cannot be found/resolved

Tried invalidating cache, reimporting the project, switching to built-in Maven, removing the .m2 folder and its parts, - nothing worked. After I had completely broken Maven (while it had built the project successfully before, now it couldn't anymore), I had to reinstall it from scratch. It helped!

Using LINQ to group by multiple properties and sum

Linus is spot on in the approach, but a few properties are off. It looks like 'AgencyContractId' is your Primary Key, which is unrelated to the output you want to give the user. I think this is what you want (assuming you change your ViewModel to match the data you say you want in your view).

var agencyContracts = _agencyContractsRepository.AgencyContracts
    .GroupBy(ac => new
    .Select(ac => new AgencyContractViewModel
                       AgencyId = ac.Key.AgencyID,
                       VendorId = ac.Key.VendorID,
                       RegionId = ac.Key.RegionID,
                       Total = ac.Sum(acs => acs.Amount) + ac.Sum(acs => acs.Fee)

When is a CDATA section necessary within a script tag?

Basically it is to allow to write a document that is both XHTML and HTML. The problem is that within XHTML, the XML parser will interpret the &,<,> characters in the script tag and cause XML parsing error. So, you can write your JavaScript with entities, e.g.:

if (a &gt; b) alert('hello world');

But this is impractical. The bigger problem is that if you read the page in HTML, the tag script is considered CDATA 'by default', and such JavaScript will not run. Therefore, if you want the same page to be OK both using XHTML and HTML parsers, you need to enclose the script tag in CDATA element in XHTML, but NOT to enclose it in HTML.

This trick marks the start of a CDATA element as a JavaScript comment; in HTML the JavaScript parser ignores the CDATA tag (it's a comment). In XHTML, the XML parser (which is run before the JavaScript) detects it and treats the rest until end of CDATA as CDATA.

How to remove duplicate objects in a List<MyObject> without equals/hashcode?

If for some reasons you don't want to override the equals method and you want to remove duplicates based on multiple properties, then we can create a generic method to do that.

We can write it in 2 versions:

1. Modify the original list:

public static <T> void removeDuplicatesFromList(List<T> list, Function<T, ?>... keyFunctions) {

    Set<List<?>> set = new HashSet<>();

    ListIterator<T> iter = list.listIterator();
    while(iter.hasNext()) {
        T element =;

        List<?> functionResults =
                .map(function -> function.apply(element))

        if(!set.add(functionResults)) {

2. Return a new list:

public static <T> List<T> getListWithoutDuplicates(List<T> list, Function<T, ?>... keyFunctions) {

    List<T> result = new ArrayList<>();

    Set<List<?>> set = new HashSet<>();

    for(T element : list) {
        List<?> functionResults =
                .map(function -> function.apply(element))

        if(set.add(functionResults)) {

    return result;

In both cases we can consider any number of properties.

For example, to remove duplicates based on 4 properties title, author, url and description:

removeDuplicatesFromList(blogs, Blog::getTitle, Blog::getAuthor, Blog::getUrl, Blog::getDescription);

The methods work by leveraging the equals method of List, which will check the equality of its elements. In our case the elements of functionResults are the values retrieved from the passed getters and we can use that list as an element of the Set to check for duplicates.

Complete example:

public class Duplicates {

    public static void main(String[] args) {

        List<Blog> blogs = new ArrayList<>();
        blogs.add(new Blog("a", "a", "a", "a"));
        blogs.add(new Blog("b", "b", "b", "b"));
        blogs.add(new Blog("a", "a", "a", "a"));    // duplicate
        blogs.add(new Blog("a", "a", "b", "b"));
        blogs.add(new Blog("a", "b", "b", "b"));
        blogs.add(new Blog("a", "a", "b", "b"));    // duplicate

        List<Blog> blogsWithoutDuplicates = getListWithoutDuplicates(blogs, 
                Blog::getTitle, Blog::getAuthor, Blog::getUrl, Blog::getDescription);
        System.out.println(blogsWithoutDuplicates); // [a a a a, b b b b, a a b b, a b b b]
                Blog::getTitle, Blog::getAuthor, Blog::getUrl, Blog::getDescription);
        System.out.println(blogs);                  // [a a a a, b b b b, a a b b, a b b b]

    private static class Blog {
        private String title;
        private String author;
        private String url;
        private String description;

        public Blog(String title, String author, String url, String description) {
            this.title = title;
   = author;
            this.url = url;
            this.description = description;

        public String getTitle() {
            return title;

        public String getAuthor() {
            return author;

        public String getUrl() {
            return url;

        public String getDescription() {
            return description;

        public String toString() {
            return String.join(" ", title, author, url, description);

C# 'or' operator?

Or is || in C#.

You may have a look at this.

HTTP test server accepting GET/POST requests

If you want a local test server that accepts any URL and just dumps the request to the console, you can use node:

const http = require("http");

const hostname = "";
const port = 3000;

const server = http.createServer((req, res) => {
  console.log(`\n${req.method} ${req.url}`);

  req.on("data", function(chunk) {
    console.log("BODY: " + chunk);

  res.statusCode = 200;
  res.setHeader("Content-Type", "text/plain");
  res.end("Hello World\n");

server.listen(port, hostname, () => {
  console.log(`Server running at http://localhost:${port}/`);

Save it in a file 'echo.js' and run it as follows:

$ node echo.js
Server running at http://localhost:3000/

You can then submit data:

$ curl -d "[1,2,3]" -XPOST http://localhost:3000/foo/bar

which will be shown in the server's stdout:

POST /foo/bar
{ host: 'localhost:3000',
  'user-agent': 'curl/7.54.1',
  accept: '*/*',
  'content-length': '7',
  'content-type': 'application/x-www-form-urlencoded' }
BODY: [1,2,3]

Downloading a Google font and setting up an offline site that uses it

just download the font and extract it in a folder. then link that font. the below code worked for me properly.

body { 
  color: #000; 
  font-family:'Open Sans';

How to capture a backspace on the onkeydown event

Try this:

document.addEventListener("keydown", KeyCheck);  //or however you are calling your method
function KeyCheck(event)
   var KeyID = event.keyCode;
      case 8:
      case 46:

Wait for async task to finish

This will never work, because the JS VM has moved on from that async_call and returned the value, which you haven't set yet.

Don't try to fight what is natural and built-in the language behaviour. You should use a callback technique or a promise.

function f(input, callback) {
    var value;

    // Assume the async call always succeed
    async_call(input, function(result) { callback(result) };


The other option is to use a promise, have a look at Q. This way you return a promise, and then you attach a then listener to it, which is basically the same as a callback. When the promise resolves, the then will trigger.

How to set the background image of a html 5 canvas to .png image

As shown in this example, you can apply a background to a canvas element through CSS and this background will not be considered part the image, e.g. when fetching the contents through toDataURL().

Here are the contents of the example, for Stack Overflow posterity:

  <meta charset="utf-8">
  <title>Canvas Background through CSS</title>
  <style type="text/css" media="screen">
    canvas, img { display:block; margin:1em auto; border:1px solid black; }
    canvas { background:url(lotsalasers.jpg) }
<canvas width="800" height="300"></canvas>
<script type="text/javascript" charset="utf-8">
  var can = document.getElementsByTagName('canvas')[0];
  var ctx = can.getContext('2d');
  ctx.strokeStyle = '#f00';
  ctx.lineWidth   = 6;
  ctx.lineJoin    = 'round';
  var img = document.getElementsByTagName('img')[0];
  img.src = can.toDataURL();

Stack array using pop() and push()

Stack Implementation in Java

  class stack
  {  private int top;
     private int[] element;
      {element=new int[10];
      void push(int item)


      void pop()
      void display()

      public static void main(String args[])
        stack s1=new stack();



Top=0 Element=10 Top=1 Element=20 Top=2 Element=30 Top=1 Element=20

In Typescript, what is the ! (exclamation mark / bang) operator when dereferencing a member?

Louis' answer is great, but I thought I would try to sum it up succinctly:

The bang operator tells the compiler to temporarily relax the "not null" constraint that it might otherwise demand. It says to the compiler: "As the developer, I know better than you that this variable cannot be null right now".

DBNull if statement

This should work.

if (rsData["usr.ursrdaystime"] != System.DBNull.Value))
    strLevel = rsData["usr.ursrdaystime"].ToString();

also need to add using statement, like bellow:

using (var objConn = new SqlConnection(strConnection))
        using (var objCmd = new SqlCommand(strSQL, objConn))
           using (var rsData = objCmd.ExecuteReader())
              while (rsData.Read())
                 if (rsData["usr.ursrdaystime"] != System.DBNull.Value)
                    strLevel = rsData["usr.ursrdaystime"].ToString();

this'll automaticly dispose (close) resources outside of block { .. }.

What is the difference between visibility:hidden and display:none?

With visibility:hidden the object still takes up vertical height on the page. With display:none it is completely removed. If you have text beneath an image and you do display:none, that text will shift up to fill the space where the image was. If you do visibility:hidden the text will remain in the same location.

how do I query sql for a latest record date for each user

FROM assignment  
JOIN paper_submission_detail ON  assignment.PAPER_SUB_ID = 

CSS: How to remove pseudo elements (after, before,...)?

You need to add a css rule that removes the after content (through a class)..

An update due to some valid comments.

The more correct way to completely remove/disable the :after rule is to use{content:none;}

as Gillian Lo Wong answered.

Original answer

You need to add a css rule that removes the after content (through a class)..{content:"";}

and add that class to your p when you want to with this line

$('p').addClass('no-after'); // replace the p selector with what you need...

a working example at :

Constructing pandas DataFrame from values in variables gives "ValueError: If using all scalar values, you must pass an index"

Change your 'a' and 'b' values to a list, as follows:

a = [2]
b = [3]

then execute the same code as follows:

df2 = pd.DataFrame({'A':a,'B':b})

and you'll get:

    A   B
0   2   3

Copy text from nano editor to shell

First method

This method seems to work when the content doesn't include ?.

Install xsel or similar and assign a global shortcut key for this command in your WM or DE:

xsel -o | sed -r 's/^ ?[[:digit:]]+($| +)//g' | perl -pe 's/\n/?/g' | sed -r 's/??/\n\n/g; s/ ?? {1,}/ /g; s/?/\n/g' | xsel -b

Put this in your ~/.Xresources:

*selectToClipboard: false

Issue this in your xterm once to activate the above option:

xrdb -load ~/.Xresources

Now select the line(s) including the line numbers by pressing Shift while dragging the mouse. After the selection click your key combo; the line(s) are coppied and ready to be pasted anywhere you like.

Second method

Doesn't have the shortcoming of the first method.

Install xdotool and xsel or similar.

Put these two lines

Ctrl <Btn3Down>: select-start(PRIMARY, CLIPBOARD)
Ctrl <Btn3Up>: select-end(CLIPBOARD, PRIMARY)

in your ~/.Xresources like so:

*VT100*translations: #override \n\
    Alt <Key> 0xf6: exec-formatted("xdg-open '%t'", PRIMARY, CUT_BUFFER0) \n\                           
    Ctrl <Key>0x2bb: copy-selection(CLIPBOARD) \n\                              
    Alt <Key>0x2bb: insert-selection(CLIPBOARD) \n\                             
    Ctrl <Key> +:       larger-vt-font() \n\                                    
    Ctrl <Key> -:       smaller-vt-font() \n\
    Ctrl <Btn3Down>: select-start(PRIMARY, CLIPBOARD) \n\
    Ctrl <Btn3Up>: select-end(CLIPBOARD, PRIMARY) 

Issue this in your xterm once to activate the above option:

xrdb -load ~/.Xresources

Create this scrip in your path:


filepid=$(xdotool getwindowpid $(xdotool getactivewindow))                   
file=$(ps -p "$filepid" o cmd | grep -o --color=never "/.*")                   

firstline=$(xsel -b)                                                         

sed -n ""$firstline","$lastline"p" "$file" | xsel -b

Assign a global shortcut key to call this script in your WM or DE.

Now when you want to copy a line (paragraph), select only the line number of that line (paragraph) by right mouse button while pressing Shift+Ctrl. After the selection click your custom global key combo you've created before. The line (paragraph) is coppied and ready to be pasted anywhere you like.

If you want to copy multiple lines, do the above for the first line and then for the last line of the range, instead of Shift+Ctrl+Btn3 (right mouse button), just select the number by left mouse button while pressing only Shift. After this, again call the script by your custom global shortcut. The range of lines are coppied and ready to pasted anywhere you like.

Use a loop to plot n charts Python

Use a dictionary!!

You can also use dictionaries that allows you to have more control over the plots:

import matplotlib.pyplot as plt
#   plot 0     plot 1    plot 2   plot 3

plots = zip(x,y)
def loop_plot(plots):
    for idx,plot in enumerate(plots):
return figs, axs

figs, axs = loop_plot(plots)

Now you can select the plot that you want to modify easily:

axs[0].set_title("Now I can control it!")

Of course, is up to you to decide what to do with the plots. You can either save them to disk figs[idx].savefig("plot_%s.png" %idx) or show them Use the argument block=False only if you want to pop up all the plots together (this could be quite messy if you have a lot of plots). You can do this inside the loop_plot function or in a separate loop using the dictionaries that the function provided.

Check if record exists from controller in Rails

with 'exists?':

Business.exists? user_id: #=> 1 or nil

with 'any?':

Business.where(:user_id => #=> true or false

If you use something with .where, be sure to avoid trouble with scopes and better use .unscoped

Business.unscoped.where(:user_id =>

How can I convert a string to a number in Perl?

This is a simple solution:

Example 1

my $var1 = "123abc";
print $var1 + 0;



Example 2

my $var2 = "abc123";
print $var2 + 0;



how to split the ng-repeat data with three columns using bootstrap

Following is a more simple way:

    <tr ng-repeat="item in lists" ng-hide="$index%2!==0">
            <label>{{ lists[$index].name}}</label>
        <td ng-hide="!lists[$index+1]">
            <label>{{ lists[$index+1].name}}</label>

Cumulo Nimbus's answer is useful for me but I want this grid wrapped by a div which can show the scrollbar when the list is too long.

To achieve this I added style="height:200px; overflow:auto" to a div around the table which causes it to show as a single column.

Now works for array length of one.

Avoid duplicates in INSERT INTO SELECT query in SQL Server

A simple DELETE before the INSERT would suffice:

INSERT INTO Table2 (Id, name) SELECT Id, name FROM Table1

Switching Table1 for Table2 depending on which table's Id and name pairing you want to preserve.

How to run a program automatically as admin on Windows 7 at startup?

You need to plug it into the task scheduler, such that it is launched after login of a user, using a user account that has administrative access on the system, with the highest privileges that are afforded to processes launched by that account.

This is the implementation that is used to autostart processes with administrative privileges when logging in as an ordinary user.

I've used it to launch the 'OpenVPN GUI' helper process which needs elevated privileges to work correctly, and thus would not launch properly from the registry key.

From the command line, you can create the task from an XML description of what you want to accomplish; so for example we have this, exported from my system, which would start notepad with the highest privileges when i log in:

<?xml version="1.0" encoding="UTF-16"?>
<Task version="1.2" xmlns="">
    <Principal id="Author">
  <Actions Context="Author">

and it's registered by an administrator command prompt using:

schtasks /create /tn "start notepad on login" /xml startnotepad.xml

this answer should really be moved over to one of the other stackexchange sites, as it's not actually a programming question per se.

Java - Create a new String instance with specified length and filled with specific character. Best solution?

No need to do the loop, and using just standard Java library classes:

protected String getStringWithLengthAndFilledWithCharacter(int length, char charToFill) {
  if (length > 0) {
    char[] array = new char[length];
    Arrays.fill(array, charToFill);
    return new String(array);
  return "";

As you can see, I also added suitable code for the length == 0 case.

How to enter ssh password using bash?

Create a new keypair: (go with the defaults)


Copy the public key to the server: (password for the last time)

ssh-copy-id [email protected]

From now on the server should recognize your key and not ask you for the password anymore:

ssh [email protected]

Regular expression to match characters at beginning of line only

(?i)^[ \r\n]*CTR

(?i) -- case insensitive -- Remove if case sensitive.
[ \r\n]  -- ignore space and new lines
* -- 0 or more times the same
CTR - your starts with string.

Grep and Python

You might be interested in pyp. Citing my other answer:

"The Pyed Piper", or pyp, is a linux command line text manipulation tool similar to awk or sed, but which uses standard python string and list methods as well as custom functions evolved to generate fast results in an intense production environment.

Simple PHP Pagination script

Some of the tutorials I found that are easy to understand are:

It makes way more sense to break up your list into page-sized chunks, and only query your database one chunk at a time. This drastically reduces server processing time and page load time, as well as gives your user smaller pieces of info to digest, so he doesn't choke on whatever crap you're trying to feed him. The act of doing this is called pagination.

A basic pagination routine seems long and scary at first, but once you close your eyes, take a deep breath, and look at each piece of the script individually, you will find it's actually pretty easy stuff

The script:

// find out how many rows are in the table 
$sql = "SELECT COUNT(*) FROM numbers";
$result = mysql_query($sql, $conn) or trigger_error("SQL", E_USER_ERROR);
$r = mysql_fetch_row($result);
$numrows = $r[0];

// number of rows to show per page
$rowsperpage = 10;
// find out total pages
$totalpages = ceil($numrows / $rowsperpage);

// get the current page or set a default
if (isset($_GET['currentpage']) && is_numeric($_GET['currentpage'])) {
   // cast var as int
   $currentpage = (int) $_GET['currentpage'];
} else {
   // default page num
   $currentpage = 1;
} // end if

// if current page is greater than total pages...
if ($currentpage > $totalpages) {
   // set current page to last page
   $currentpage = $totalpages;
} // end if
// if current page is less than first page...
if ($currentpage < 1) {
   // set current page to first page
   $currentpage = 1;
} // end if

// the offset of the list, based on current page 
$offset = ($currentpage - 1) * $rowsperpage;

// get the info from the db 
$sql = "SELECT id, number FROM numbers LIMIT $offset, $rowsperpage";
$result = mysql_query($sql, $conn) or trigger_error("SQL", E_USER_ERROR);

// while there are rows to be fetched...
while ($list = mysql_fetch_assoc($result)) {
   // echo data
   echo $list['id'] . " : " . $list['number'] . "<br />";
} // end while

/******  build the pagination links ******/
// range of num links to show
$range = 3;

// if not on page 1, don't show back links
if ($currentpage > 1) {
   // show << link to go back to page 1
   echo " <a href='{$_SERVER['PHP_SELF']}?currentpage=1'><<</a> ";
   // get previous page num
   $prevpage = $currentpage - 1;
   // show < link to go back to 1 page
   echo " <a href='{$_SERVER['PHP_SELF']}?currentpage=$prevpage'><</a> ";
} // end if 

// loop to show links to range of pages around current page
for ($x = ($currentpage - $range); $x < (($currentpage + $range) + 1); $x++) {
   // if it's a valid page number...
   if (($x > 0) && ($x <= $totalpages)) {
      // if we're on current page...
      if ($x == $currentpage) {
         // 'highlight' it but don't make a link
         echo " [<b>$x</b>] ";
      // if not current page...
      } else {
         // make it a link
         echo " <a href='{$_SERVER['PHP_SELF']}?currentpage=$x'>$x</a> ";
      } // end else
   } // end if 
} // end for

// if not on last page, show forward and last page links        
if ($currentpage != $totalpages) {
   // get next page
   $nextpage = $currentpage + 1;
    // echo forward link for next page 
   echo " <a href='{$_SERVER['PHP_SELF']}?currentpage=$nextpage'>></a> ";
   // echo forward link for lastpage
   echo " <a href='{$_SERVER['PHP_SELF']}?currentpage=$totalpages'>>></a> ";
} // end if
/****** end build pagination links ******/

This tutorial is intended for developers who wish to give their users the ability to step through a large number of database rows in manageable chunks instead of the whole lot in one go.

Configuring angularjs with eclipse IDE

  1. Make sure the project is extracted on your hard disk.
  2. In Eclipse go to the menu: File->New->Project.
  3. Select "General->Project" and click on the next button.
  4. Enter the project name in the "Project name:" field
  5. Disable "Use default location" Click on the "Browse ..." button and select the folder that contains the project (the one from step 1)
  6. Click on the "Finish" button
  7. Right-click with the mouse on you're new project and click "Configure->Convert to AngularJS Project.."
  8. Enable you're project goodies and click on the "OK" button.

List the queries running on SQL Server

I would suggest querying the sys views. something similar to

   sys.dm_exec_sessions s
   LEFT  JOIN sys.dm_exec_connections c
        ON  s.session_id = c.session_id
   LEFT JOIN sys.dm_db_task_space_usage tsu
        ON  tsu.session_id = s.session_id
   LEFT JOIN sys.dm_os_tasks t
        ON  t.session_id = tsu.session_id
        AND t.request_id = tsu.request_id
   LEFT JOIN sys.dm_exec_requests r
        ON  r.session_id = tsu.session_id
        AND r.request_id = tsu.request_id
   OUTER APPLY sys.dm_exec_sql_text(r.sql_handle) TSQL

This way you can get a TotalPagesAllocated which can help you figure out the spid that is taking all the server resources. There has lots of times when I can't even bring up activity monitor and use these sys views to see what's going on.

I would recommend you reading the following article. I got this reference from here.

Bootstrap: Open Another Modal in Modal

I also had some trouble with my scrollable modals, so I did something like this:

  $('.modal').on('', function () {
    // BS adds some padding-right to acomodate the scrollbar at right

  $(".modal [data-toggle='modal']").click(function(){

It will serve for any modal whithin a modal that comes to appear. Note that the first its closed so the second can appear. No changes in the Bootstrap structure.

how to get domain name from URL


ldap query for group members

Active Directory does not store the group membership on user objects. It only stores the Member list on the group. The tools show the group membership on user objects by doing queries for it.

How about:


(You forgot the (& ) bit in your example in the question as well).

How do I compute the intersection point of two lines?

Can't stand aside,

So we have linear system:

A1 * x + B1 * y = C1
A2 * x + B2 * y = C2

let's do it with Cramer's rule, so solution can be found in determinants:

x = Dx/D
y = Dy/D

where D is main determinant of the system:

A1 B1
A2 B2

and Dx and Dy can be found from matricies:

C1 B1
C2 B2


A1 C1
A2 C2

(notice, as C column consequently substitues the coef. columns of x and y)

So now the python, for clarity for us, to not mess things up let's do mapping between math and python. We will use array L for storing our coefs A, B, C of the line equations and intestead of pretty x, y we'll have [0], [1], but anyway. Thus, what I wrote above will have the following form further in the code:

for D

L1[0] L1[1]
L2[0] L2[1]

for Dx

L1[2] L1[1]
L2[2] L2[1]

for Dy

L1[0] L1[2]
L2[0] L2[2]

Now go for coding:

line - produces coefs A, B, C of line equation by two points provided,
intersection - finds intersection point (if any) of two lines provided by coefs.

from __future__ import division 

def line(p1, p2):
    A = (p1[1] - p2[1])
    B = (p2[0] - p1[0])
    C = (p1[0]*p2[1] - p2[0]*p1[1])
    return A, B, -C

def intersection(L1, L2):
    D  = L1[0] * L2[1] - L1[1] * L2[0]
    Dx = L1[2] * L2[1] - L1[1] * L2[2]
    Dy = L1[0] * L2[2] - L1[2] * L2[0]
    if D != 0:
        x = Dx / D
        y = Dy / D
        return x,y
        return False

Usage example:

L1 = line([0,1], [2,3])
L2 = line([2,3], [0,4])

R = intersection(L1, L2)
if R:
    print "Intersection detected:", R
    print "No single intersection point detected"

OpenVPN failed connection / All TAP-Win32 adapters on this system are currently in use

It seems to me you are using the wrong version...

TAP-Win32 should not be installed on the 64bit version. Download the right one and try again!

Cordova app not displaying correctly on iPhone X (Simulator)

In my case where each splash screen was individually designed instead of autogenerated or laid out in a story board format, I had to stick with my Legacy Launch screen configuration and add portrait and landscape images to target iPhoneX 1125×2436 orientations to the config.xml like so:

<splash height="2436" src="resources/ios/splash/Default-2436h.png" width="1125" />
<splash height="1125" src="resources/ios/splash/Default-Landscape-2436h.png" width="2436" />

After adding these to config.xml ("viewport-fit=cover" was already set in index.hml) my app built with Ionic Pro fills the entire screen on iPhoneX devices.

How to change TextField's height and width?

If you want to increase the height of TextFormField dynamically while typing the text in it. Set maxLines to null. Like

          onSaved: (newText) {
            enteredTextEmail = newText;

          obscureText: false,
          keyboardType: TextInputType.emailAddress,
          validator: validateName,
          maxLines: null,
          // style: style,
          decoration: InputDecoration(
              contentPadding: EdgeInsets.fromLTRB(5.0, 10.0, 5.0, 10.0),
              hintText: "Enter Question",
              labelText: "Enter Question",
              border: OutlineInputBorder(
                  borderRadius: BorderRadius.circular(10.0))),

Rails :include vs. :joins

.joins will just joins the tables and brings selected fields in return. if you call associations on joins query result, it will fire database queries again

:includes will eager load the included associations and add them in memory. :includes loads all the included tables attributes. If you call associations on include query result, it will not fire any queries

how to clear the screen in python

If you mean the screen where you have that interpreter prompt >>> you can do CTRL+L on Bash shell can help. Windows does not have equivalent. You can do

import os
os.system('cls')  # on windows


os.system('clear')  # on linux / os x

Python Finding Prime Factors

def prime(n):
    for i in range(2,n):
        if n%i==0:
            return False
    return True

def primefactors():
    m=int(input('enter the number:'))
    for i in range(2,m):
        if (prime(i)):
            if m%i==0:
    return print('end of it')


change array size

This worked well for me to create a dynamic array from a class array.

var s = 0;
var songWriters = new SongWriterDetails[1];
foreach (var contributor in Contributors)
    Array.Resize(ref songWriters, s++);
    songWriters[s] = new SongWriterDetails();
    songWriters[s].DisplayName = contributor.Name;
    songWriters[s].PartyId = contributor.Id;

Extract source code from .jar file

Use JD GUI. Open the application, drag and drop your JAR file into it.

Python 3.2 Unable to import urllib2 (ImportError: No module named urllib2)

In python 3 urllib2 was merged into urllib. See also another Stack Overflow question and the urllib PEP 3108.

To make Python 2 code work in Python 3:

    import urllib.request as urllib2
except ImportError:
    import urllib2

jQuery scrollTop() doesn't seem to work in Safari or Chrome (Windows)

I was having this problem in Safari and Chrome (Mac) and discovered that .scrollTop would work on $("body") but not $("html, body"), FF and IE however works the other way round. A simple browser detect fixes the issue:

    bodyelem = $("body")
    bodyelem = $("html,body")


The jQuery browser value for Chrome is Safari, so you only need to do a detect on that.

Hope this helps someone.

Search for a particular string in Oracle clob column

You can use the way like @Florin Ghita has suggested. But remember dbms_lob.substr has a limit of 4000 characters in the function For example :


Otherwise you will find ORA-22835 (buffer too small)

You can also use the other sql way :

SELECT * FROM   your_table WHERE  clob_value_column LIKE '%your string%';

Note : There are performance problems associated with both the above ways like causing Full Table Scans, so please consider about Oracle Text Indexes as well:

How do I get the RootViewController from a pushed controller?

I encounter a strange condition.

self.viewControllers.first is not root viewController always.

Generally, self.viewControllers.first is root viewController indeed. But sometimes it's not.

class MyCustomMainNavigationController: UINavigationController {

    function configureForView(_ v: UIViewController, animated: Bool) {
        let root = self.viewControllers.first
        let isRoot = (v == root)
        // Update UI based on isRoot
        // ....

extension MyCustomMainNavigationController: UINavigationControllerDelegate {
    func navigationController(_ navigationController: UINavigationController, 
        willShow viewController: UIViewController, 
        animated: Bool) {

        self.configureForView(viewController, animated: animated)

My issue:

Generally, self.viewControllers.first is root viewController. But, when I call popToRootViewController(animated:), and then it triggers navigationController(_:willShow:animated:). At this moment, self.viewControllers.first is NOT root viewController, it's the last viewController which will disappear.


  • self.viewControllers.first is not always root viewController. Sometime, it will be the last viewController.

So, I suggest to keep rootViewController by property when self.viewControllers have ONLY one viewController. I get root viewController in viewDidLoad() of custom UINavigationController.

class MyCustomMainNavigationController: UINavigationController {
    fileprivate var myRoot: UIViewController!
    override func viewDidLoad() {


        // My UINavigationController is defined in storyboard. 
        // So at this moment, 
        // I can get root viewController by `self.topViewController!`
        let v = self.topViewController!
        self.myRoot = v



  • iPhone 7 with iOS 14.0.1
  • Xcode 12.0.1 (12A7300)

Get current time in hours and minutes

With bash version >= 4.2:

printf "%(%H:%M)T\n"


printf -v foo "%(%H:%M)T\n"
echo "$foo"

See: man bash

MATLAB error: Undefined function or method X for input arguments of type 'double'

You get this error when the function isn't on the MATLAB path or in pwd.

First, make sure that you are able to find the function using:

>> which divrat

If it returns:

>> which divrat
'divrat' not found.

It is not on the MATLAB path or in PWD.

Second, make sure that the directory that contains divrat is on the MATLAB path using the PATH command. It may be that a directory that you thought was on the path isn't actually on the path.

Finally, make sure you aren't using a "private" directory. If divrat is in a directory named private, it will be accessible by functions in the parent directory, but not from the MATLAB command line:

>> foo

ans =


>> divrat(1,1)
??? Undefined function or method 'divrat' for input arguments of type 'double'.

>> which -all divrat
c:\work\divrat\private\divrat.m  % Private to divrat

nginx error connect to php5-fpm.sock failed (13: Permission denied)

Consideration must also be given to your individual FPM pools, if any.

I couldn't figure out why none of these answers was working for me today. This had been a set-and-forget scenario for me, where I had forgotten that listen.user and were duplicated on a per-pool basis.

If you used pools for different user accounts like I did, where each user account owns their FPM processes and sockets, setting only the default listen.owner and configuration options to 'nginx' will simply not work. And obviously, letting 'nginx' own them all is not acceptable either.

For each pool, make sure that = nginx

Otherwise, you can leave the pool's ownership and such alone.

Finding longest string in array

Modern browsers support a for...of loop. The fastest and shortest way to solve this problem in Chrome, Safari, Edge, and Firefox is also the clearest:

let largest = '';
for (let item of arr) {
  if (item.length > largest.length) largest = item

In IE, you can use Array.forEach; that's still faster and clearer than sorting or reducing the array.

var largest = '';
arr.forEach(function(item) {
  if (item.length > largest.length) largest = item

unix diff side-to-side results?

Enhanced diff command with color, side by side and alias

Let's say the file contents are like:

cat /tmp/test1.txt


cat /tmp/test2.txt

Now comparing side-by-side

diff --width=$COLUMNS --suppress-common-lines --side-by-side --color=always /tmp/test1.txt /tmp/test2.txt
                                                                              > 1.5
3                                                                             <
8                                                                             | 6
9                                                                             | 7

You can define alias to use

alias diff='diff --width=$COLUMNS --suppress-common-lines --side-by-side --color=always'

Then new diff result:

diff /tmp/test1.txt /tmp/test2.txt
                                                                              > 1.5
3                                                                             <
8                                                                             | 6
9                                                                             | 7

Installing and Running MongoDB on OSX

Assuming you have created the data/db directory under bin after install.

  1. Start a terminal for your mongo server
  2. Go to <mongodb-install-directory>/bin directory
  3. Run the command


  4. Start a terminal for your mongo shell

  5. Go to <mongodb-install-directory>/bin directory
  6. Run the command (make sure you put the name of the database)

    ./mongo test

What is define([ , function ]) in JavaScript?

That's probably a requireJS module definition

Check here for more details

RequireJS is a JavaScript file and module loader. It is optimized for in-browser use, but it can be used in other JavaScript environments, like Rhino and Node. Using a modular script loader like RequireJS will improve the speed and quality of your code.

Join between tables in two different databases?

Yes, assuming the account has appropriate permissions you can use:

SELECT <...>
FROM A.table1 t1 JOIN B.table2 t2 ON t2.column2 = t1.column1;

You just need to prefix the table reference with the name of the database it resides in.

How to get CRON to call in the correct PATHs

The simplest workaround I've found looks like this:

* * * * * root su -l -c command

This example invokes su as root user and starts the shell with the user's full environment, including $PATH, set as if they were logged in. It works the same on different distros, is more reliable than sourcing .bashrc (which hasn't worked for me) and avoids hardcoding specific paths which can be a problem if you're providing an example or setup tool and don't know what distro or file layout on the user's system.

You can also specify the username after su if you want a different user than root, but you should probably leave the root parameter before su command since this ensures su has sufficient privileges to switch to any user you specify.

How can I get current location from user in iOS

In iOS 6, the

- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation

is deprecated.

Use following code instead

- (void)locationManager:(CLLocationManager *)manager
     didUpdateLocations:(NSArray *)locations {
    CLLocation *location = [locations lastObject];
    NSLog(@"lat%f - lon%f", location.coordinate.latitude, location.coordinate.longitude);

For iOS 6~8, the above method is still necessary, but you have to handle authorization.

_locationManager = [CLLocationManager new];
_locationManager.delegate = self;
_locationManager.distanceFilter = kCLDistanceFilterNone;
_locationManager.desiredAccuracy = kCLLocationAccuracyBest;

if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0 &&
    [CLLocationManager authorizationStatus] != kCLAuthorizationStatusAuthorizedWhenInUse
    //[CLLocationManager authorizationStatus] != kCLAuthorizationStatusAuthorizedAlways
   ) {
     // Will open an confirm dialog to get user's approval 
    [_locationManager requestWhenInUseAuthorization]; 
    //[_locationManager requestAlwaysAuthorization];
} else {
    [_locationManager startUpdatingLocation]; //Will update location immediately 

This is the delegate method which handle user's authorization

#pragma mark - CLLocationManagerDelegate
- (void)locationManager:(CLLocationManager*)manager didChangeAuthorizationStatus:(CLAuthorizationStatus)status
    switch (status) {
    case kCLAuthorizationStatusNotDetermined: {
        NSLog(@"User still thinking..");
    } break;
    case kCLAuthorizationStatusDenied: {
        NSLog(@"User hates you");
    } break;
    case kCLAuthorizationStatusAuthorizedWhenInUse:
    case kCLAuthorizationStatusAuthorizedAlways: {
        [_locationManager startUpdatingLocation]; //Will update location immediately
    } break;

Find an element in a list of tuples

The filter function can also provide an interesting solution:

result = list(filter(lambda x: x.count(1) > 0, a))

which searches the tuples in the list a for any occurrences of 1. If the search is limited to the first element, the solution can be modified into:

result = list(filter(lambda x: x[0] == 1, a))

Radio buttons and label to display in same line

I was having the similar issue of keeping all radio buttons on the same line. After trying all the things I could, nothing worked for me except the following. What I mean is simply using table resolved the issue allowing radio buttons to appear in the same line.

            @Html.RadioButton("p_sortForPatch", "byName", new { @checked = "checked", @class = "radio" }) By Name
            @Html.RadioButton("p_sortForPatch", "byDate", new { @class = "radio" }) By Date

change text of button and disable button in iOS

SWIFT 4 with extension


// set button label for all states
extension UIButton {
    public func setAllStatesTitle(_ newTitle: String){
        self.setTitle(newTitle, for: .normal)
        self.setTitle(newTitle, for: .selected)
        self.setTitle(newTitle, for: .disabled)

and use:

yourBtn.setAllStatesTitle("btn title")

How can I strip HTML tags from a string in ASP.NET?

I've looked at the Regex based solutions suggested here, and they don't fill me with any confidence except in the most trivial cases. An angle bracket in an attribute is all it would take to break, let alone mal-formmed HTML from the wild. And what about entities like &amp;? If you want to convert HTML into plain text, you need to decode entities too.

So I propose the method below.

Using HtmlAgilityPack, this extension method efficiently strips all HTML tags from an html fragment. Also decodes HTML entities like &amp;. Returns just the inner text items, with a new line between each text item.

public static string RemoveHtmlTags(this string html)
        if (String.IsNullOrEmpty(html))
            return html;

        var doc = new HtmlAgilityPack.HtmlDocument();

        if (doc.DocumentNode == null || doc.DocumentNode.ChildNodes == null)
            return WebUtility.HtmlDecode(html);

        var sb = new StringBuilder();

        var i = 0;

        foreach (var node in doc.DocumentNode.ChildNodes)
            var text = node.InnerText.SafeTrim();

            if (!String.IsNullOrEmpty(text))

                if (i < doc.DocumentNode.ChildNodes.Count - 1)


        var result = sb.ToString();

        return WebUtility.HtmlDecode(result);

public static string SafeTrim(this string str)
    if (str == null)
        return null;

    return str.Trim();

If you are really serious, you'd want to ignore the contents of certain HTML tags too (<script>, <style>, <svg>, <head>, <object> come to mind!) because they probably don't contain readable content in the sense we are after. What you do there will depend on your circumstances and how far you want to go, but using HtmlAgilityPack it would be pretty trivial to whitelist or blacklist selected tags.

If you are rendering the content back to an HTML page, make sure you understand XSS vulnerability & how to prevent it - i.e. always encode any user-entered text that gets rendered back onto an HTML page (> becomes &gt; etc).

Stop mouse event propagation

I used

<... (click)="..;..; ..someOtherFunctions(mybesomevalue); $event.stopPropagation();" ...>...

in short just seperate other things/function calls with ';' and add $event.stopPropagation()

How to assign colors to categorical variables in ggplot2 that have stable mapping?

For simple situations like the exact example in the OP, I agree that Thierry's answer is the best. However, I think it's useful to point out another approach that becomes easier when you're trying to maintain consistent color schemes across multiple data frames that are not all obtained by subsetting a single large data frame. Managing the factors levels in multiple data frames can become tedious if they are being pulled from separate files and not all factor levels appear in each file.

One way to address this is to create a custom manual colour scale as follows:

#Some test data
dat <- data.frame(x=runif(10),y=runif(10),
        grp = rep(LETTERS[1:5],each = 2),stringsAsFactors = TRUE)

#Create a custom color scale
myColors <- brewer.pal(5,"Set1")
names(myColors) <- levels(dat$grp)
colScale <- scale_colour_manual(name = "grp",values = myColors)

and then add the color scale onto the plot as needed:

#One plot with all the data
p <- ggplot(dat,aes(x,y,colour = grp)) + geom_point()
p1 <- p + colScale

#A second plot with only four of the levels
p2 <- p %+% droplevels(subset(dat[4:10,])) + colScale

The first plot looks like this:

enter image description here

and the second plot looks like this:

enter image description here

This way you don't need to remember or check each data frame to see that they have the appropriate levels.

Best way to represent a fraction in Java?

If you're feeling adventurous, take a look at JScience. It has a Rational class that represents fractions.

How to scroll to top of page with JavaScript/jQuery?

Seeint the hash should do the job. If you have a header, you can use

window.location.href = "#headerid";

otherwise, the # alone will work

window.location.href = "#";

And as it get written into the url, it'll stay if you refresh.

In fact, you don't event need JavaScript for that if you want to do it on an onclick event, you should just put a link arround you element and give it # as href.

How to remove MySQL root password

You need to set the password for root@localhost to be blank. There are two ways:

  1. The MySQL SET PASSWORD command:

    SET PASSWORD FOR root@localhost=PASSWORD('');
  2. Using the command-line mysqladmin tool:

    mysqladmin -u root -pType_in_your_current_password_here password ''

HttpWebRequest using Basic authentication

If you can use the WebClient class, using basic authentication becomes simple:

var client = new WebClient {Credentials = new NetworkCredential("user_name", "password")};
var response = client.DownloadString("");

How to return a value from try, catch, and finally?

It is because you are in a try statement. Since there could be an error, sum might not get initialized, so put your return statement in the finally block, that way it will for sure be returned.

Make sure that you initialize sum outside the try/catch/finally so that it is in scope.

Passing command line arguments from Maven as properties in pom.xml

I used the properties plugin to solve this.

Properties are defined in the pom, and written out to a file, where they can then be accessed from your Java code.

In my case it is test code that needs to access this properties file, so in the pom the properties file is written to maven's testOutputDirectory:


Use outputDirectory if you want properties to be accessible by your app code:


For those looking for a fuller example (it took me a bit of fiddling to get this working as I didn't understand how naming of properties tags affects ability to retrieve them elsewhere in the pom file), my pom looks as follows:





And on the command line:

mvn clean test -Dapp.env=LOCAL -Dapp.domain=localhost -Dapp.port=9901

So these properties can be accessed from the Java code: inputStream = Thread.currentThread().getContextClassLoader().getResourceAsStream("");
 java.util.Properties properties = new Properties();
 appPort = properties.getProperty("app.port");
 appDomain = properties.getProperty("app.domain");

Twitter bootstrap scrollable table

Don't need the wrap it in a div...


tr {
width: 100%;
display: inline-table;
table-layout: fixed;

 height:300px;              // <-- Select the height of the table
 display: -moz-groupbox;    // Firefox Bad Effect
  overflow-y: scroll;      
  height: 200px;            //  <-- Select the height of the body
  width: 100%;
  position: absolute;

Bootply :

How to Completely Uninstall Xcode and Clear All Settings

For a complete removal of Xcode 10 delete the following:

  1. /Applications/
  2. ~/Library/Caches/
  3. ~/Library/Developer
  4. ~/Library/MobileDevice
  5. ~/Library/Preferences/
  6. /Library/Preferences/
  7. /System/Library/Receipts/
  8. /System/Library/Receipts/
  9. /System/Library/Receipts/
  10. /System/Library/Receipts/
  11. /private/var/db/receipts/

But instead of 11, open up /private/var/in the Finder and search for "Xcode" to see all the 'dna' left behind... and selectively clean that out too. I would post the pathnames but they will include randomized folder names which will not be the same from my Mac to yours.

but if you don't want to lose all of your customizations, consider saving these files or folders before deleting anything:

  1. ~/Library/Developer/Xcode/UserData/CodeSnippets
  2. ~/Library/Developer/Xcode/UserData/FontAndColorThemes
  3. ~/Library/Developer/Xcode/UserData/KeyBindings
  4. ~/Library/Developer/Xcode/Templates
  5. ~/Library/Preferences/
  6. ~/Library/MobileDevice/Provisioning Profiles

In HTML I can make a checkmark with &#x2713; . Is there a corresponding X-mark?

A corresponding cross for ✓ &#x2713; would be ✗ &#x2717; I think (Dingbats).

ActiveMQ connection refused

I had also similar problem. In my case brokerUrl was not configured properly. So that's way I received following Error:

Cause: Error While attempting to add new Connection to the pool: nested exception is javax.jms.JMSException: Could not connect to broker URL : tcp://localhost:61616. Reason: Connection refused

& I resolved it following way.

   ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory();


error : expected unqualified-id before return in c++

Just for the sake of people who landed here for the same reason I did:

Don't use reserved keywords

I named a function in my class definition delete(), which is a reserved keyword and should not be used as a function name. Renaming it to deletion() (which also made sense semantically in my case) resolved the issue.

For a list of reserved keywords:

I quote: "Since they are used by the language, these keywords are not available for re-definition or overloading. "

How to get the absolute coordinates of a view

First you have to get the localVisible rectangle of the view

For eg:

Rect rectf = new Rect();

//For coordinates location relative to the parent

//For coordinates location relative to the screen/display

Log.d("WIDTH        :", String.valueOf(rectf.width()));
Log.d("HEIGHT       :", String.valueOf(rectf.height()));
Log.d("left         :", String.valueOf(rectf.left));
Log.d("right        :", String.valueOf(rectf.right));
Log.d("top          :", String.valueOf(;
Log.d("bottom       :", String.valueOf(rectf.bottom));

Hope this will help

How do you develop Java Servlets using Eclipse?

You need to install a plugin, There is a free one from the eclipse foundation called the Web Tools Platform. It has all the development functionality that you'll need.

You can get the Java EE Edition of eclipse with has it pre-installed.

To create and run your first servlet:

  1. New... Project... Dynamic Web Project.
  2. Right click the project... New Servlet.
  3. Write some code in the doGet() method.
  4. Find the servers view in the Java EE perspective, it's usually one of the tabs at the bottom.
  5. Right click in there and select new Server.
  6. Select Tomcat X.X and a wizard will point you to finding the installation.
  7. Right click the server you just created and select Add and Remove... and add your created web project.
  8. Right click your servlet and select Run > Run on Server...

That should do it for you. You can use ant to build here if that's what you'd like but eclipse will actually do the build and automatically deploy the changes to the server. With Tomcat you might have to restart it every now and again depending on the change.

How to concatenate columns in a Postgres SELECT?

The problem was in nulls in the values; then the concatenation does not work with nulls. The solution is as follows:

SELECT coalesce(a, '') || coalesce(b, '') FROM foo;

batch file to list folders within a folder to one level

I tried this command to display the list of files in the directory.

dir /s /b > List.txt

In the file it displays the list below.

C:\Program Files (x86)\Cisco Systems\Cisco Jabber\XmppMgr.dll

C:\Program Files (x86)\Cisco Systems\Cisco Jabber\XmppSDK.dll

C:\Program Files (x86)\Cisco Systems\Cisco Jabber\accessories\Plantronics

C:\Program Files (x86)\Cisco Systems\Cisco Jabber\accessories\SennheiserJabberPlugin.dll

C:\Program Files (x86)\Cisco Systems\Cisco Jabber\accessories\Logitech\LogiUCPluginForCisco

C:\Program Files (x86)\Cisco Systems\Cisco Jabber\accessories\Logitech\LogiUCPluginForCisco\lucpcisco.dll

What is want to do is only to display sub-directory not the full directory path.

Just like this:

Cisco Jabber\XmppMgr.dll Cisco Jabber\XmppSDK.dll

Cisco Jabber\accessories\JabraJabberPlugin.dll

Cisco Jabber\accessories\Logitech

Cisco Jabber\accessories\Plantronics

Cisco Jabber\accessories\SennheiserJabberPlugin.dll

How to convert a list of numbers to jsonarray in Python

import json
row = [1L,[0.1,0.2],[[1234L,1],[134L,2]]]
row_json = json.dumps(row)

Node.js - get raw request body using Express

// Change the way body-parser is used
const bodyParser = require('body-parser');

var rawBodySaver = function (req, res, buf, encoding) {
  if (buf && buf.length) {
    req.rawBody = buf.toString(encoding || 'utf8');
app.use(bodyParser.json({ verify: rawBodySaver, extended: true }));

// Now we can access raw-body any where in out application as follows

What is the worst real-world macros/pre-processor abuse you've ever come across?

From memory, it looked something like this:

#define RETURN(result) return (result);}

int myfunction1(args) {
    int x = 0;
    // do something

int myfunction2(args) {
    int y = 0;
    // do something

int myfunction3(args) {
    int z = 0;
    // do something

Yes that's right, no closing braces in any of the functions. Syntax highlighting was a mess, so he used vi to edit (not vim, it has syntax coloring!)

He was a Russian programmer who had mostly worked in assembly language. He was fanatical about saving as many bytes as possible because he had previously worked on systems with very limited memory. "It was for satellite. Only very few byte, so we use each byte over for many things." (bit fiddling, reusing machine instruction bytes for their numeric values) When I tried to find out what kinds of satellites, I was only able to get "Orbiting satellite. For making to orbit."

He had two other quirks: A convex mirror mounted above his monitor "For knowing who is watching", and an occasional sudden exit from his chair to do a quick ten pushups. He explained this last one as "Compiler found error in code. This is punishment".

WPF Add a Border to a TextBlock

No, you need to wrap your TextBlock in a Border. Example:

<Border BorderThickness="1" BorderBrush="Black">
    <TextBlock ... />

Of course, you can set these properties (BorderThickness, BorderBrush) through styles as well:

<Style x:Key="notCalledBorder" TargetType="{x:Type Border}">
    <Setter Property="BorderThickness" Value="1" />
    <Setter Property="BorderBrush" Value="Black" />

<Border Style="{StaticResource notCalledBorder}">
    <TextBlock ... />

Is it possible to output a SELECT statement from a PL/SQL block?

Create a function in a package and return a SYS_REFCURSOR:

       l_cursor SYS_REFCURSOR;
          open l_cursor for SELECT foo,bar FROM foobar; 
          return l_cursor; 
END Function1;

Format date to MM/dd/yyyy in JavaScript

ISO compliant dateString

If your dateString is RFC282 and ISO8601 compliant:
pass your string into the Date Constructor:

const dateString = "2020-10-30T12:52:27+05:30"; // ISO8601 compliant dateString
const D = new Date(dateString);                 // {object Date}

from here you can extract the desired values by using Date Getters:

D.getMonth() + 1  // 10 (PS: +1 since Month is 0-based)
D.getDate()       // 30
D.getFullYear()   // 2020

Non-standard date string

If you use a non standard date string:
destructure the string into known parts, and than pass the variables to the Date Constructor:

new Date(year, monthIndex [, day [, hours [, minutes [, seconds [, milliseconds]]]]])

const dateString = "30/10/2020 12:52:27";
const [d, M, y, h, m, s] = dateString.match(/\d+/g);

// PS: M-1 since Month is 0-based
const D = new Date(y, M-1, d, h, m, s);  // {object Date}

D.getMonth() + 1  // 10 (PS: +1 since Month is 0-based)
D.getDate()       // 30
D.getFullYear()   // 2020

Running a CMD or BAT in silent mode

Use Advanced BAT to EXE Converter from

This will allow you to embed any additional binaries with your batch file in to one stand alone completely silent EXE and its freeware

When to use: Java 8+ interface default method, vs. abstract method

Although its an old question let me give my input on it as well.

  1. abstract class: Inside abstract class we can declare instance variables, which are required to the child class

    Interface: Inside interface every variables is always public static and final we cannot declare instance variables

  2. abstract class: Abstract class can talk about state of object

    Interface: Interface can never talk about state of object

  3. abstract class: Inside Abstract class we can declare constructors

    Interface: Inside interface we cannot declare constructors as purpose of
    constructors is to initialize instance variables. So what is the need of constructor there if we cannot have instance variables in interfaces.

  4. abstract class: Inside abstract class we can declare instance and static blocks

    Interface: Interfaces cannot have instance and static blocks.

  5. abstract class: Abstract class cannot refer lambda expression

    Interfaces: Interfaces with single abstract method can refer lambda expression

  6. abstract class: Inside abstract class we can override OBJECT CLASS methods

    Interfaces: We cannot override OBJECT CLASS methods inside interfaces.

I will end on the note that:

Default method concepts/static method concepts in interface came just to save implementation classes but not to provide meaningful useful implementation. Default methods/static methods are kind of dummy implementation, "if you want you can use them or you can override them (in case of default methods) in implementation class" Thus saving us from implementing new methods in implementation classes whenever new methods in interfaces are added. Therefore interfaces can never be equal to abstract classes.

What is the purpose of nameof?

Another use-case where nameof feature of C# 6.0 becomes handy - Consider a library like Dapper which makes DB retrievals much easier. Albeit this is a great library, you need to hardcode property/field names within query. What this means is that if you decide to rename your property/field, there are high chances that you will forget to update query to use new field names. With string interpolation and nameof features, code becomes much easier to maintain and typesafe.

From the example given in link

without nameof

var dog = connection.Query<Dog>("select Age = @Age, Id = @Id", new { Age = (int?)null, Id = guid });

with nameof

var dog = connection.Query<Dog>($"select {nameof(Dog.Age)} = @Age, {nameof(Dog.Id)} = @Id", new { Age = (int?)null, Id = guid });

Parallel foreach with asynchronous lambda

My lightweight implementation of ParallelForEach async.


  1. Throttling (max degree of parallelism).
  2. Exception handling (aggregation exception will be thrown at completion).
  3. Memory efficient (no need to store the list of tasks).

public static class AsyncEx
    public static async Task ParallelForEachAsync<T>(this IEnumerable<T> source, Func<T, Task> asyncAction, int maxDegreeOfParallelism = 10)
        var semaphoreSlim = new SemaphoreSlim(maxDegreeOfParallelism);
        var tcs = new TaskCompletionSource<object>();
        var exceptions = new ConcurrentBag<Exception>();
        bool addingCompleted = false;

        foreach (T item in source)
            await semaphoreSlim.WaitAsync();
            asyncAction(item).ContinueWith(t =>

                if (t.Exception != null)

                if (Volatile.Read(ref addingCompleted) && semaphoreSlim.CurrentCount == maxDegreeOfParallelism)

        Volatile.Write(ref addingCompleted, true);
        await tcs.Task;
        if (exceptions.Count > 0)
            throw new AggregateException(exceptions);

Usage example:

await Enumerable.Range(1, 10000).ParallelForEachAsync(async (i) =>
    var data = await GetData(i);
}, maxDegreeOfParallelism: 100);

How to check if a file is empty in Bash?

I came here looking for how to delete empty files as they are implicit in Python 3.3+ and ended up using:

find -depth '(' -type f  -name ')' -print0 |
  while IFS= read -d '' -r file; do if [[ ! -s $file ]]; then rm $file; fi; done

Also (at least in zsh) using $path as the variable also breaks your $PATH env and so it'll break your open shell. Anyway, thought I'd share!

Replacing instances of a character in a string

You can do the below, to replace any char with a respective char at a given index, if you wish not to use .replace()

word = 'python'
index = 4
char = 'i'

word = word[:index] + char + word[index + 1:]
print word

o/p: pythin

Can scripts be inserted with innerHTML?

Gabriel Garcia's mention of MutationObservers is on the right track, but didn't quite work for me. I am not sure if that was because of a browser quirk or due to a mistake on my end, but the version that ended up working for me was the following:

document.addEventListener("DOMContentLoaded", function(event) {
    var observer = new MutationObserver(mutations=>{>{
                if (node.tagName === "SCRIPT") {
                    var s = document.createElement("script");
                    if (typeof(node.parentElement.added) === 'undefined')
                        node.parentElement.added = [];
                    node.parentElement.added[node.parentElement.added.length] = s;
    observer.observe(document.getElementById("element_to_watch"), {childList: true, subtree: true,attributes: false});

Of course, you should replace element_to_watch with the name of the element that is being modified.

node.parentElement.added is used to store the script tags that are added to document.head. In the function used to load the external page, you can use something like the following to remove no longer relevant script tags:

function freeScripts(node){
    if (node === null)
    if (typeof(node.added) === 'object') {
        for (var script in node.added) {
        node.added = {};
    for (var child in node.children) {

And an example of the beginning of a load function:

function load(url, id, replace) {
    if (document.getElementById(id) === null) {
        console.error("Element of ID "+id + " does not exist!");
    var xhttp = new XMLHttpRequest();
    // proceed to load in the page and modify innerHTML

Initialize a string in C to empty string

To achieve this you can use:

strcpy(string, "");

Delete topic in Kafka

Deleting topic isn't always working in

Deletion should be working in the next release, 0.8.2 --delete --zookeeper localhost:2181 --topic your_topic_name

  Topic your_topic_name is marked for deletion.
  Note: This will have no impact if delete.topic.enable is not set to true.

Is it possible to delete a topic?

Jira KAFKA-1397

Ruby: How to iterate over a range, but in set increments?

Here's another, perhaps more familiar-looking way to do it:

for i in (0..10).step(2) do
    puts i

Pass props to parent component in React.js

Basically you use props to send information to and from Child and Parent.

Adding to all the wonderful answers, let me give a simple example that explains passing values from child to parent component in React


class App extends React.Component {
            this.handleFilterUpdate = this.handleFilterUpdate.bind(this);
      handleFilterUpdate(filterValue) {
                  name: filterValue
   render() {
      return (
            <Header change={this.handleFilterUpdate} name={} />


class Header extends React.Component {
                  names: 'jessy'
      Change(event) {

      // this.props.change(this.state.names);

   render() {
      return (
       <button onClick={this.Change.bind(this)}>click</button>



import React from 'react';
import ReactDOM from 'react-dom';

import App from './App.jsx';

ReactDOM.render(<App />, document.getElementById('app'));

Thats it , now you can pass values from your client to the server.

Take a look at the Change function in the Header.js

Change(event) {
      // this.props.change(this.state.names);

This is how you push values into the props from client to the server

dropping rows from dataframe based on a "not in" condition

You can use pandas.Dataframe.isin.

pandas.Dateframe.isin will return boolean values depending on whether each element is inside the list a or not. You then invert this with the ~ to convert True to False and vice versa.

import pandas as pd

a = ['2015-01-01' , '2015-02-01']

df = pd.DataFrame(data={'date':['2015-01-01' , '2015-02-01', '2015-03-01' , '2015-04-01', '2015-05-01' , '2015-06-01']})

#         date
#0  2015-01-01
#1  2015-02-01
#2  2015-03-01
#3  2015-04-01
#4  2015-05-01
#5  2015-06-01

df = df[~df['date'].isin(a)]

#         date
#2  2015-03-01
#3  2015-04-01
#4  2015-05-01
#5  2015-06-01

SSH Port forwarding in a ~/.ssh/config file?

You can use the LocalForward directive in your host yam section of ~/.ssh/config:

LocalForward 5901

css divide width 100% to 3 column

.selector{width:calc(100% / 3);}

Fetch API request timeout?

Building on Endless' excellent answer, I created a helpful utility function.

const fetchTimeout = (url, ms, { signal, ...options } = {}) => {
    const controller = new AbortController();
    const promise = fetch(url, { signal: controller.signal, ...options });
    if (signal) signal.addEventListener("abort", () => controller.abort());
    const timeout = setTimeout(() => controller.abort(), ms);
    return promise.finally(() => clearTimeout(timeout));
  1. If the timeout is reached before the resource is fetched then the fetch is aborted.
  2. If the resource is fetched before the timeout is reached then the timeout is cleared.
  3. If the input signal is aborted then the fetch is aborted and the timeout is cleared.
const controller = new AbortController();

document.querySelector("button.cancel").addEventListener("click", () => controller.abort());

fetchTimeout("example.json", 5000, { signal: controller.signal })
    .then(response => response.json())
    .catch(error => {
        if ( === "AbortError") {
            // fetch aborted either due to timeout or due to user clicking the cancel button
        } else {
            // network error or json parsing error

Hope that helps.

Reading specific columns from a text file in python

You can use a zip function with a list comprehension :

with open('ex.txt') as f:
    print zip(*[line.split() for line in f])[1]

result :

('10', '20', '30', '40', '23', '13')

Android layout replacing a view with another view on run time

it work in my case, oldSensor and newSnsor - oldView and newView:

private void replaceSensors(View oldSensor, View newSensor) {
            ViewGroup parent = (ViewGroup) oldSensor.getParent();

            if (parent == null) {

            int indexOldSensor = parent.indexOfChild(oldSensor);
            int indexNewSensor = parent.indexOfChild(newSensor);
            parent.addView(oldSensor, indexNewSensor);
            parent.addView(newSensor, indexOldSensor);

"CSV file does not exist" for a filename with embedded quotes

Sometimes we ignore a little bit issue which is not a Python or IDE fault its logical error We assumed a file .csv which is not a .csv file its a Excell Worksheet file have a look

Tiktok file which is worksheet file not a CSV file Shown in Green border

When you try to open that file using Import compiler will through the error have a look enter image description here

To Resolve the issue

open your Target file into Microsoft Excell and save that file in .csv format it is important to note that Encoding is important because it will help you to open the file when you try to open it with

with open('YourTargetFile.csv','r',encoding='UTF-8') as file:

enter image description here

So you are set to go now Try to open your file as this

import csv
with open('plain.csv','r',encoding='UTF-8') as file:
load = csv.reader(file)
for line in load:

Here is the Output Plain.csv File Running

Change a Django form field to a hidden field

If you want the field to always be hidden, use the following:

class MyForm(forms.Form):
    hidden_input = forms.CharField(widget=forms.HiddenInput(), initial="value")

If you want the field to be conditionally hidden, you can do the following:

form = MyForm()
if condition:
    form.fields["field_name"].widget = forms.HiddenInput()
    form.fields["field_name"].initial = "value"

Correct way to remove plugin from Eclipse

I would like to propose my solution,that worked for me.

It's reverting Eclipse and its plugins versions, to the version just before the plugin was installed.

How to check all versions of python installed on osx and centos


yum list installed
command to find the packages you installed.

How to debug a referenced dll (having pdb)

When you want to set a breakpoint in source code of a referenced dll, first make sure that you have a pdb file available for it. Then you can just open the related source code file and set a breakpoint over there. The source file does not need to be part of your solution. As explained in How can I set a breakpoint in referenced code in Visual Studio?

You can review your breakpoints through the breakpoints window, available via Debug -> Windows -> Breakpoints.

This approach has the benefit that you are not required to add an existing project to your solution just for debugging purposes as leaving it out has saved me a lot of build time. Evidently, building a solution with only one project in it is much faster than building a solution with lots of them.

Left padding a String with Zeros

If your string contains numbers only, you can make it an integer and then do padding:

String.format("%010d", Integer.parseInt(mystring));

If not I would like to know how it can be done.

How can I return pivot table output in MySQL?

My solution is in T-SQL without any pivots:

    SUM(CASE WHEN (action='EMAIL') THEN 1 ELSE 0 END) AS Email,
    SUM(CASE WHEN (action='PRINT' AND pagecount=1) THEN 1 ELSE 0 END) AS Print1Pages,
    SUM(CASE WHEN (action='PRINT' AND pagecount=2) THEN 1 ELSE 0 END) AS Print2Pages,
    SUM(CASE WHEN (action='PRINT' AND pagecount=3) THEN 1 ELSE 0 END) AS Print3Pages

Docker compose port mapping

If you want to access redis from the host (, you have to use the ports command.

    context: .
    dockerfile: Dockerfile-redis
    - "6379:6379"

Angular 2 Checkbox Two Way Data Binding

I'm working with Angular5 and I had to add the "name" attribute to get the binding to work... The "id" is not required for binding.

<input type="checkbox" id="rememberMe" name="rememberMe" [(ngModel)]="rememberMe">

What is the difference between CloseableHttpClient and HttpClient in Apache HttpClient API?

CloseableHttpClient is the base class of the httpclient library, the one all implementations use. Other subclasses are for the most part deprecated.

The HttpClient is an interface for this class and other classes.

You should then use the CloseableHttpClient in your code, and create it using the HttpClientBuilder. If you need to wrap the client to add specific behaviour you should use request and response interceptors instead of wrapping with the HttpClient.

This answer was given in the context of httpclient-4.3.

How to serialize object to CSV file?

You can use gererics to work for any class

public class FileUtils<T> {
public String createReport(String filePath, List<T> t) {
    if (t.isEmpty()) {
        return null;

    List<String> reportData = new ArrayList<String>();

    addDataToReport(t.get(0), reportData, 0);

    for (T k : t) {
        addDataToReport(k, reportData, 1);
    return !dumpReport(filePath, reportData) ? null : filePath;

public static Boolean dumpReport(String filePath, List<String> lines) {
    Boolean isFileCreated = false;

    String[] dirs = filePath.split(File.separator);
    String baseDir = "";
    for (int i = 0; i < dirs.length - 1; i++) {
        baseDir += " " + dirs[i];
    baseDir = baseDir.replace(" ", "/");
    File base = new File(baseDir);

    File file = new File(filePath);
    try {
        if (!file.exists())
    } catch (Exception e) {
        return isFileCreated;

    try (BufferedWriter writer = new BufferedWriter(
            new OutputStreamWriter(new FileOutputStream(file), System.getProperty("file.encoding")))) {
        for (String line : lines) {
            writer.write(line + System.lineSeparator());
    } catch (IOException e) {
        return false;
    return true;

void addDataToReport(T t, List<String> reportData, int index) {
    String[] jsonObjectAsArray = new Gson().toJson(t).replace("{", "").replace("}", "").split(",\"");
    StringBuilder row = new StringBuilder();

    for (int i = 0; i < jsonObjectAsArray.length; i++) {
        String str = jsonObjectAsArray[i];
        str = str.replaceFirst(":", "_").split("_")[index];

        if (i == 0) {
            if (str != null) {
                row.append(str.replace("\"", ""));
            } else {
        } else {
            if (str != null) {
                row.append(", " + str.replace("\"", ""));
            } else {
                row.append(", N/A");

How do I run two commands in one line in Windows CMD?

Try to create a .bat ot .cmd file with those lines using doskey key and $T which is equivalent to & to do several command line in just one line :

touch=echo off $T echo. ^> $* $T dir /B $T echo on

It'll create an empty file.


touch myfile

In cmd you'll get something like this:

enter image description here

But as mentioned previously by others, it is really advised to use & operator to do many command line in one line from CMD prompt.

Enjoy =)

How to pip or easy_install tkinter on Windows

The Tkinter library is built-in with every Python installation. And since you are on Windows, I believe you installed Python through the binaries on their website?

If so, Then most probably you are typing the command wrong. It should be:

import Tkinter as tk

Note the capital T at the beginning of Tkinter.

For Python 3,

import tkinter as tk

Creating a DateTime in a specific Time Zone in c#

The other answers here are useful but they don't cover how to access Pacific specifically - here you go:

public static DateTime GmtToPacific(DateTime dateTime)
    return TimeZoneInfo.ConvertTimeFromUtc(dateTime,
        TimeZoneInfo.FindSystemTimeZoneById("Pacific Standard Time"));

Oddly enough, although "Pacific Standard Time" normally means something different from "Pacific Daylight Time," in this case it refers to Pacific time in general. In fact, if you use FindSystemTimeZoneById to fetch it, one of the properties available is a bool telling you whether that timezone is currently in daylight savings or not.

You can see more generalized examples of this in a library I ended up throwing together to deal with DateTimes I need in different TimeZones based on where the user is asking from, etc:

This won't work outside of Windows (for example Mono on Linux) since the list of times comes from the Windows Registry: HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Time Zones\

Underneath that you'll find keys (folder icons in Registry Editor); the names of those keys are what you pass to FindSystemTimeZoneById. On Linux you have to use a separate Linux-standard set of timezone definitions, which I've not adequately explored.

How to remove all white spaces in java


  string output = YourString.replaceAll("\\s","")

s - indicates space character (tab characters etc)

Java: notify() vs. notifyAll() all over again

To summarize the excellent detailed explanations above, and in the simplest way I can think of, this is due to the limitations of the JVM built-in monitor, which 1) is acquired on the entire synchronization unit (block or object) and 2) does not discriminate about the specific condition being waited/notified on/about.

This means that if multiple threads are waiting on different conditions and notify() is used, the selected thread may not be the one which would make progress on the newly fulfilled condition - causing that thread (and other currently still waiting threads which would be able to fulfill the condition, etc..) not to be able to make progress, and eventually starvation or program hangup.

In contrast, notifyAll() enables all waiting threads to eventually re-acquire the lock and check for their respective condition, thereby eventually allowing progress to be made.

So notify() can be used safely only if any waiting thread is guaranteed to allow progress to be made should it be selected, which in general is satisfied when all threads within the same monitor check for only one and the same condition - a fairly rare case in real world applications.

Convert .pfx to .cer

openssl rsa -in f.pem -inform PEM -out f.der -outform DER

Multiline input form field using Bootstrap

The answer by Nick Mitchinson is for Bootstrap version 2.

If you are using Bootstrap version 3, then forms have changed a bit. For bootstrap 3, use the following instead:

<div class="form-horizontal">
    <div class="form-group">
        <div class="col-md-6">
            <textarea class="form-control" rows="3" placeholder="What's up?" required></textarea>

Where, col-md-6 will target medium sized devices. You can add col-xs-6 etc to target smaller devices.

Chrome Dev Tools - Modify javascript and reload

This is a bit of a work around, but one way you can achieve this is by adding a breakpoint at the start of the javascript file or block you want to manipulate.

Then when you reload, the debugger will pause on that breakpoint, and you can make any changes you want to the source, save the file and then run the debugger through the modified code.

But as everyone has said, next reload the changes will be gone - at least it let's you run some slightly modified JS client side.

Tree view of a directory/folder in Windows?

I recommend WinDirStat.

I frequently use WinDirStat to create screen shots for user documentation of open folders and their contents.

It even uses the correct icons for Windows registered file types.

All I would say is missing is an option to display the files without their icons. I can live without it personally, since I am usually pasting the image into a paint program or Visio to edit it, but it would still be a useful feature. error in opening zip file

Simply to overcome the ZipException's, i have used a wrapper for commons-compress1.14 called jarchivelibwritten by thrau that makes it easy to extract or compress from and into File objects.


public static void main(String[] args) {
        String zipfilePath = 
        String outdir = "E:/Selenium_Server/";
        exratctFileList(zipfilePath, outdir );
public void exratctFileList( String zipfilePath, String outdir ) throws IOException {
    File archive = new File( zipfilePath );
    File destinationDir = new File( outdir );

    Archiver archiver = null;
    if( zipfilePath.endsWith(".zip") ) {
        archiver = ArchiverFactory.createArchiver( ArchiveFormat.ZIP );
    } else if ( zipfilePath.endsWith(".tar.gz") ) {
        archiver = ArchiverFactory.createArchiver( ArchiveFormat.TAR, CompressionType.GZIP );
    archiver.extract(archive, destinationDir);

    ArchiveStream stream = archive );
    ArchiveEntry entry;

    while( (entry = stream.getNextEntry()) != null ) {
        String entryName = entry.getName();
        System.out.println("Entery Name : "+ entryName );

Maven dependency « You can download the jars from the Sonatype Maven Repository at org/rauschig/jarchivelib/.



Java optional parameters

VarArgs and overloading have been mentioned. Another option is a Bloch Builder pattern, which would look something like this:

 MyObject my = new MyObjectBuilder().setParam1(value)

Although that pattern would be most appropriate for when you need optional parameters in a constructor.

How to remove the URL from the printing page?

Chrome headless now supports an extra options --print-to-pdf-no-header which removed header and footer from the printed PDF file

Gson: Directly convert String to JsonObject (no POJO)

The JsonParser constructor has been deprecated. Use the static method instead:

JsonObject asJsonObject = JsonParser.parseString(request.schema).getAsJsonObject();

Phone: numeric keyboard for text input

For me the best solution was:

For integer numbers, which brings up the 0-9 pad on android and iphone

<label for="ting">
<input id="ting" name="ting" type="number" pattern="[\d]*" />

You also may want to do this to hide the spinners in firefox/chrome/safari, most clients think they look ugly

 input[type=number]::-webkit-outer-spin-button {
      -webkit-appearance: none;
      margin: 0;

 input[type=number] {

And add novalidate='novalidate' to your form element, if your doing custom validation

Ps just in case you actually wanted floating point numbers after all,step to whatever precision you fancy, will add '.' to android

<label for="ting">
<input id="ting" name="ting" type="number" pattern="[\d\.]*" step="0.01" />

pass **kwargs argument to another function with **kwargs

The ** syntax tells Python to collect keyword arguments into a dictionary. The save2 is passing it down as a non-keyword argument (a dictionary object). The openX is not seeing any keyword arguments so the **args doesn't get used. It's instead getting a third non-keyword argument (the dictionary). To fix that change the definition of the openX function.

def openX(filename, mode, kwargs):