Programs & Examples On #Ide customization

Qt Creator color scheme

I found a way to change the Application Output theme and everything that can't be edited from .css.

If you use osX:

  1. Navigate to your Qt install directory.
  2. Right click Qt Creator application and select "Show Package Contents"
  3. Copy the following file to your desktop> Contents/Resources/themes/dark.creatortheme or /default.creatortheme. Depending on if you are using dark theme or default theme.
  4. Edit the file in text editor.
  5. Under [Palette], there is a line that says error=ffff0000.
  6. Set a new color, save, and override the original file.

How to get full file path from file name?

Directory.GetCurrentDirectory

string dirpath = Directory.GetCurrentDirectory();

Prepend this dirpath to the filename to get the complete path.

As @Dan Puzey indicated in the comments, it would be better to use Path.Combine

Path.Combine(Directory.GetCurrentDirectory(), filename)

Error: No default engine was specified and no extension was provided

If all that's needed is to send html code inline in the code, we can use below

var app = express();
app.get('/test.html', function (req, res) {
   res.header('Content-Type', 'text/html').send("<html>my html code</html>");
});

Java Calendar, getting current month value, clarification needed

as others said Calendar.MONTH returns int and is zero indexed.

to get the current month as a String use SimpleDateFormat.format() method

Calendar cal = Calendar.getInstance();
System.out.println(new SimpleDateFormat("MMM").format(cal.getTime()));

returns NOV

What is the difference between a Relational and Non-Relational Database?

The relational database uses a formal system of predicates to address data. The underlying physical implementation is of no substance and can vary to optimize for certain operations, but it must always assume the relational model. In layman's terms, that's just saying I know exactly how many values (attributes) each row (tuple) in my table (relation) has and now I want to exploit the fact accordingly, thoroughly and to it's extreme. That's the true nature of the beast. 

Since we're obviously the generation that has had a relational upbringing, if you look at NoSQL database models from the perspective of the relational model, again in layman's terms, the first obvious difference is that no assumptions about the number of values a row can contain is ever made. This is really oversimplifying the matter and does not cleanly apply to the intricacies of the physical models of every NoSQL database, but it's the pinnacle of the relational model and the first assumption we have to leave behind or, if you'd rather, the biggest leap we have to make.

We can agree to two things that are true for every DBMS: it can store any kind of data and has enough mathematical underpinnings to make it possible to manage the data in any way imaginable. The reality is that you'll never want to make the mistake of putting any of the two points to the test, but rather just stick with what the actual DBMS was really made for. In layman's terms: respect the beast within!

(Please note that I've avoided comparing the (obviously) well founded standards revolving around the relational model against the many flavors provided by NoSQL databases. If you'd like, consider NoSQL databases as an umbrella term for any DBMS that does not completely assume the relational model, in exclusion to everything else. The differences are too many, but that's the principal difference and the one I think would be of most use to you to understand the two.)

Output PowerShell variables to a text file

$computer,$Speed,$Regcheck will create an array, and run out-file ones per variable = they get seperate lines. If you construct a single string using the variables first, it will show up a single line. Like this:

"$computer,$Speed,$Regcheck" | out-file -filepath C:\temp\scripts\pshell\dump.txt -append -width 200

GIT: Checkout to a specific folder

Use git archive branch-index | tar -x -C your-folder-on-PC to clone a branch to another folder. I think, then you can copy any file that you need

Stopping a JavaScript function when a certain condition is met

Return is how you exit out of a function body. You are using the correct approach.

I suppose, depending on how your application is structured, you could also use throw. That would typically require that your calls to your function are wrapped in a try / catch block.

Python name 'os' is not defined

The problem is that you forgot to import os. Add this line of code:

import os

And everything should be fine. Hope this helps!

Jenkins Pipeline Wipe Out Workspace

We make sure we are working with a clean workspace by using a feature of the git plugin. You can add additional behaviors like 'Clean before checkout'. We use this as well for 'Prune stale remote-tracking branches'.

mkdir's "-p" option

mkdir [-switch] foldername

-p is a switch which is optional, it will create subfolder and parent folder as well even parent folder doesn't exist.

From the man page:

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

Example:

mkdir -p storage/framework/{sessions,views,cache}

This will create subfolder sessions,views,cache inside framework folder irrespective of 'framework' was available earlier or not.

How to get the latest record in each group using GROUP BY?

this query return last record for every Form_id:

    SELECT m1.*
     FROM messages m1 LEFT JOIN messages m2
     ON (m1.Form_id = m2.Form_id AND m1.id < m2.id)
     WHERE m2.id IS NULL;

Find files with size in Unix

Assuming you have GNU find:

find . -size +10000k -printf '%s %f\n'

If you want a constant width for the size field, you can do something like:

find . -size +10000k -printf '%10s %f\n'

Note that -size +1000k selects files of at least 10,240,000 bytes (k is 1024, not 1000). You said in a comment that you want files bigger than 1M; if that's 1024*1024 bytes, then this:

find . -size +1M ...

will do the trick -- except that it will also print the size and name of files that are exactly 1024*1024 bytes. If that matters, you could use:

find . -size +1048575c ...

You need to decide just what criterion you want.

Smooth scroll without the use of jQuery

Here is my solution. Works in most browsers

document.getElementById("scrollHere").scrollIntoView({behavior: "smooth"});

Docs

_x000D_
_x000D_
document.getElementById("end").scrollIntoView({behavior: "smooth"});
_x000D_
body {margin: 0px; display: block; height: 100%; background-image: linear-gradient(red, yellow);}_x000D_
.start {display: block; margin: 100px 10px 1000px 0px;}_x000D_
.end {display: block; margin: 0px 0px 100px 0px;}
_x000D_
<div class="start">Start</div>_x000D_
<div class="end" id="end">End</div>
_x000D_
_x000D_
_x000D_

Unioning two tables with different number of columns

if only 1 row, you can use join

Select t1.Col1, t1.Col2, t1.Col3, t2.Col4, t2.Col5 from Table1 t1 join Table2 t2;

Access elements in json object like an array

I found a straight forward way of solving this, with the use of JSON.parse.

Let's assume the json below is inside the variable jsontext.

[
  ["Blankaholm", "Gamleby"],
  ["2012-10-23", "2012-10-22"],
  ["Blankaholm. Under natten har det varit inbrott", "E22 i med Gamleby. Singelolycka. En bilist har.],
  ["57.586174","16.521841"], ["57.893162","16.406090"]
]

The solution is this:

var parsedData = JSON.parse(jsontext);

Now I can access the elements the following way:

var cities = parsedData[0];

SQL Error: ORA-12899: value too large for column

example : 1 and 2 table is available

1 table delete entry and select nor 2 table records and insert to no 1 table . when delete time no 1 table dont have second table records example emp id not available means this errors appeared

Location Services not working in iOS 8

Solution with backward compatibility:

SEL requestSelector = NSSelectorFromString(@"requestWhenInUseAuthorization");
if ([CLLocationManager authorizationStatus] == kCLAuthorizationStatusNotDetermined &&
    [self.locationManager respondsToSelector:requestSelector]) {
    [self.locationManager performSelector:requestSelector withObject:NULL];
} else {
    [self.locationManager startUpdatingLocation];
}

Setup NSLocationWhenInUseUsageDescription key in your Info.plist

How to use php serialize() and unserialize()

A PHP array or object or other complex data structure cannot be transported or stored or otherwise used outside of a running PHP script. If you want to persist such a complex data structure beyond a single run of a script, you need to serialize it. That just means to put the structure into a "lower common denominator" that can be handled by things other than PHP, like databases, text files, sockets. The standard PHP function serialize is just a format to express such a thing, it serializes a data structure into a string representation that's unique to PHP and can be reversed into a PHP object using unserialize. There are many other formats though, like JSON or XML.


Take for example this common problem:

How do I pass a PHP array to Javascript?

PHP and Javascript can only communicate via strings. You can pass the string "foo" very easily to Javascript. You can pass the number 1 very easily to Javascript. You can pass the boolean values true and false easily to Javascript. But how do you pass this array to Javascript?

Array ( [1] => elem 1 [2] => elem 2 [3] => elem 3 ) 

The answer is serialization. In case of PHP/Javascript, JSON is actually the better serialization format:

{ 1 : 'elem 1', 2 : 'elem 2', 3 : 'elem 3' }

Javascript can easily reverse this into an actual Javascript array.

This is just as valid a representation of the same data structure though:

a:3:{i:1;s:6:"elem 1";i:2;s:6:"elem 2";i:3;s:7:" elem 3";}

But pretty much only PHP uses it, there's little support for this format anywhere else.
This is very common and well supported as well though:

<array>
    <element key='1'>elem 1</element>
    <element key='2'>elem 2</element>
    <element key='3'>elem 3</element>
</array>

There are many situations where you need to pass complex data structures around as strings. Serialization, representing arbitrary data structures as strings, solves how to do this.

FATAL ERROR in native method: JDWP No transports initialized, jvmtiError=AGENT_ERROR_TRANSPORT_INIT(197)

I was getting the same error when i switched to STS version 3.8.3 And imported my entire workspace to the new STS.

Apparently the "Boot Spring App" instance was defective. (i run from STS)

If this is your problem, Simply create the Boot run configuration again.

jQuery hyperlinks - href value?

Add return false to the end of your click handler, this prevents the browser default handler occurring which attempts to redirect the page:

$('a').click(function() {
// do stuff
return false;
});

How to change the playing speed of videos in HTML5?

javascript:document.getElementsByClassName("video-stream html5-main-video")[0].playbackRate = 0.1;

you can put any number here just don't go to far so you don't overun your computer.

How to load external scripts dynamically in Angular?

You can use following technique to dynamically load JS scripts and libraries on demand in your Angular project.

script.store.ts will contain the path of the script either locally or on a remote server and a name that will be used to load the script dynamically

 interface Scripts {
    name: string;
    src: string;
}  
export const ScriptStore: Scripts[] = [
    {name: 'filepicker', src: 'https://api.filestackapi.com/filestack.js'},
    {name: 'rangeSlider', src: '../../../assets/js/ion.rangeSlider.min.js'}
];

script.service.ts is an injectable service that will handle the loading of script, copy script.service.ts as it is

import {Injectable} from "@angular/core";
import {ScriptStore} from "./script.store";

declare var document: any;

@Injectable()
export class ScriptService {

private scripts: any = {};

constructor() {
    ScriptStore.forEach((script: any) => {
        this.scripts[script.name] = {
            loaded: false,
            src: script.src
        };
    });
}

load(...scripts: string[]) {
    var promises: any[] = [];
    scripts.forEach((script) => promises.push(this.loadScript(script)));
    return Promise.all(promises);
}

loadScript(name: string) {
    return new Promise((resolve, reject) => {
        //resolve if already loaded
        if (this.scripts[name].loaded) {
            resolve({script: name, loaded: true, status: 'Already Loaded'});
        }
        else {
            //load script
            let script = document.createElement('script');
            script.type = 'text/javascript';
            script.src = this.scripts[name].src;
            if (script.readyState) {  //IE
                script.onreadystatechange = () => {
                    if (script.readyState === "loaded" || script.readyState === "complete") {
                        script.onreadystatechange = null;
                        this.scripts[name].loaded = true;
                        resolve({script: name, loaded: true, status: 'Loaded'});
                    }
                };
            } else {  //Others
                script.onload = () => {
                    this.scripts[name].loaded = true;
                    resolve({script: name, loaded: true, status: 'Loaded'});
                };
            }
            script.onerror = (error: any) => resolve({script: name, loaded: false, status: 'Loaded'});
            document.getElementsByTagName('head')[0].appendChild(script);
        }
    });
}

}

Inject this ScriptService wherever you need it and load js libs like this

this.script.load('filepicker', 'rangeSlider').then(data => {
    console.log('script loaded ', data);
}).catch(error => console.log(error));

how to get text from textview

You have to do the following:

a=a.replace("\n"," ");
a=a.trim();
String b[]=a.split("+");
int k=Integer.ValueOf(b[0]);
int l=Integer.ValueOf(b[1]);
int sum=k+l;

phpmyadmin "Not Found" after install on Apache, Ubuntu

Create a link in /var/www/html like this to fix the error:

sudo ln -s /usr/share/phpmyadmin /var/www/html

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

# This script fragment emits Cygwin rulez under bash/cygwin
if [[ $(uname -s) == CYGWIN* ]];then
    echo Cygwin rulez
else 
    echo Unix is king
fi

If the 6 first chars of uname -s command is "CYGWIN", a cygwin system is assumed

What's the best practice to "git clone" into an existing folder?

Just use the . at the end of the git clone command (being in that directory), like this:

cd your_dir_to_clone_in/
git clone [email protected]/somerepo/ .

'NOT LIKE' in an SQL query

After "AND" and after "OR" the QUERY has forgotten what it is all about.

I would also not know that it is about in any SQL / programming language.

if(SOMETHING equals "X" or SOMETHING equals "Y")

COLUMN NOT LIKE "A%" AND COLUMN NOT LIKE "B%"

AngularJS app.run() documentation?

Specifically...

How and where is app.run() used? After module definition or after app.config(), after app.controller()?

Where:

In your package.js E.g. /packages/dashboard/public/controllers/dashboard.js

How:

Make it look like this

var app = angular.module('mean.dashboard', ['ui.bootstrap']);

app.controller('DashboardController', ['$scope', 'Global', 'Dashboard',
    function($scope, Global, Dashboard) {
        $scope.global = Global;
        $scope.package = {
            name: 'dashboard'
        };
        // ...
    }
]);

app.run(function(editableOptions) {
    editableOptions.theme = 'bs3'; // bootstrap3 theme. Can be also 'bs2', 'default'
});

How do I parse a URL query parameters, in Javascript?

Today (2.5 years after this answer) you can safely use Array.forEach. As @ricosrealm suggests, decodeURIComponent was used in this function.

function getJsonFromUrl(url) {
  if(!url) url = location.search;
  var query = url.substr(1);
  var result = {};
  query.split("&").forEach(function(part) {
    var item = part.split("=");
    result[item[0]] = decodeURIComponent(item[1]);
  });
  return result;
}

actually it's not that simple, see the peer-review in the comments, especially:

  • hash based routing (@cmfolio)
  • array parameters (@user2368055)
  • proper use of decodeURIComponent and non-encoded = (@AndrewF)
  • non-encoded + (added by me)

For further details, see MDN article and RFC 3986.

Maybe this should go to codereview SE, but here is safer and regexp-free code:

function getJsonFromUrl(url) {
  if(!url) url = location.href;
  var question = url.indexOf("?");
  var hash = url.indexOf("#");
  if(hash==-1 && question==-1) return {};
  if(hash==-1) hash = url.length;
  var query = question==-1 || hash==question+1 ? url.substring(hash) : 
  url.substring(question+1,hash);
  var result = {};
  query.split("&").forEach(function(part) {
    if(!part) return;
    part = part.split("+").join(" "); // replace every + with space, regexp-free version
    var eq = part.indexOf("=");
    var key = eq>-1 ? part.substr(0,eq) : part;
    var val = eq>-1 ? decodeURIComponent(part.substr(eq+1)) : "";
    var from = key.indexOf("[");
    if(from==-1) result[decodeURIComponent(key)] = val;
    else {
      var to = key.indexOf("]",from);
      var index = decodeURIComponent(key.substring(from+1,to));
      key = decodeURIComponent(key.substring(0,from));
      if(!result[key]) result[key] = [];
      if(!index) result[key].push(val);
      else result[key][index] = val;
    }
  });
  return result;
}

This function can parse even URLs like

var url = "?foo%20e[]=a%20a&foo+e[%5Bx%5D]=b&foo e[]=c";
// {"foo e": ["a a",  "c",  "[x]":"b"]}

var obj = getJsonFromUrl(url)["foo e"];
for(var key in obj) { // Array.forEach would skip string keys here
  console.log(key,":",obj[key]);
}
/*
  0 : a a
  1 : c
  [x] : b
*/

Safely override C++ virtual functions

Your compiler may have a warning that it can generate if a base class function becomes hidden. If it does, enable it. That will catch const clashes and differences in parameter lists. Unfortunately this won't uncover a spelling error.

For example, this is warning C4263 in Microsoft Visual C++.

static function in C

C programmers use the static attribute to hide variable and function declarations inside modules, much as you would use public and private declarations in Java and C++. C source files play the role of modules. Any global variable or function declared with the static attribute is private to that module. Similarly, any global variable or function declared without the static attribute is public and can be accessed by any other module. It is good programming practice to protect your variables and functions with the static attribute wherever possible.

How can I get the index from a JSON object with value?

You will have to use Array.find or Array.filter or Array.forEach.

Since you value is array and you need position of element, you will have to iterate over it.

Array.find

_x000D_
_x000D_
var data = [{"name":"placeHolder","section":"right"},{"name":"Overview","section":"left"},{"name":"ByFunction","section":"left"},{"name":"Time","section":"left"},{"name":"allFit","section":"left"},{"name":"allbMatches","section":"left"},{"name":"allOffers","section":"left"},{"name":"allInterests","section":"left"},{"name":"allResponses","section":"left"},{"name":"divChanged","section":"right"}];
var index = -1;
var val = "allInterests"
var filteredObj = data.find(function(item, i){
  if(item.name === val){
    index = i;
    return i;
  }
});

console.log(index, filteredObj);
_x000D_
_x000D_
_x000D_

Array.findIndex() @Ted Hopp's suggestion

_x000D_
_x000D_
var data = [{"name":"placeHolder","section":"right"},{"name":"Overview","section":"left"},{"name":"ByFunction","section":"left"},{"name":"Time","section":"left"},{"name":"allFit","section":"left"},{"name":"allbMatches","section":"left"},{"name":"allOffers","section":"left"},{"name":"allInterests","section":"left"},{"name":"allResponses","section":"left"},{"name":"divChanged","section":"right"}];

var val = "allInterests"
var index = data.findIndex(function(item, i){
  return item.name === val
});

console.log(index);
_x000D_
_x000D_
_x000D_

Default Array.indexOf() will match searchValue to current element and not its properties. You can refer Array.indexOf - polyfill on MDN

using batch echo with special characters

another method:

@echo off

for /f "useback delims=" %%_ in (%0) do (
  if "%%_"=="___ATAD___" set $=
  if defined $ echo(%%_
  if "%%_"=="___DATA___" set $=1
)
pause
goto :eof

___DATA___
<?xml version="1.0" encoding="utf-8" ?>
 <root>
   <data id="1">
      hello world
   </data>
 </root>
___ATAD___


rem # 
rem # 

You must add a reference to assembly 'netstandard, Version=2.0.0.0

I was facing this problem when trying to add a .NETStandard dependency to a .NET4.6.1 library, and compiling it in Linux with Mono 4.6.2 (the version that comes with Ubuntu 16.04).

I finally solved it today; the solution requires to do both of these things:

  1. Change <TargetFrameworkVersion>v4.6.1</TargetFrameworkVersion> to <TargetFrameworkVersion>v4.7.1</TargetFrameworkVersion> in the .csproj file.
  2. Upgrade your mono to a newer version. I believe 5.x should work, but to be sure, you can just install Ubuntu 20.04 (which at the time of writing is only in preview), which includes Mono 6.8.0.105.

PHP salt and hash SHA256 for login password

You couldn't login because you did't get proper solt text at login time. There are two options, first is define static salt, second is if you want create dynamic salt than you have to store the salt somewhere (means in database) with associate with user. Than you concatenate user solt+password_hash string now with this you fire query with username in your database table.

Abort a Git Merge

Truth be told there are many, many resources explaining how to do this already out on the web:

Git: how to reverse-merge a commit?

Git: how to reverse-merge a commit?

Undoing Merges, from Git's blog (retrieved from archive.org's Wayback Machine)

So I guess I'll just summarize some of these:

  1. git revert <merge commit hash>
    This creates an extra "revert" commit saying you undid a merge

  2. git reset --hard <commit hash *before* the merge>
    This reset history to before you did the merge. If you have commits after the merge you will need to cherry-pick them on to afterwards.

But honestly this guide here is better than anything I can explain, with diagrams! :)

Hibernate Criteria Query to get specific columns

You can use multiselect function for this.

   CriteriaBuilder cb=session.getCriteriaBuilder();
            CriteriaQuery<Object[]> cquery=cb.createQuery(Object[].class);
            Root<Car> root=cquery.from(User.class);
            cquery.multiselect(root.get("id"),root.get("Name"));
            Query<Object[]> q=session.createQuery(cquery);
            List<Object[]> list=q.getResultList();
            System.out.println("id        Name");
            for (Object[] objects : list) {
                System.out.println(objects[0]+"        "+objects[1]);
             }
            

This is supported by hibernate 5. createCriteria is deprecated in further version of hibernate. So you can use criteria builder instead.

Executing JavaScript without a browser?

I found this really nifty open source ECMAScript compliant JS Engine completely written in C called duktape

Duktape is an embeddable Javascript engine, with a focus on portability and compact footprint.

Good luck!

Extract names of objects from list

You can just use:

> names(LIST)
[1] "A" "B"

Obviously the names of the first element is just

> names(LIST)[1]
[1] "A"

Return a value if no rows are found in Microsoft tSQL

You only have to replace the WHERE with a LEFT JOIN:

SELECT  CASE
        WHEN S.Id IS NOT NULL AND S.Status = 1 AND ...) THEN 1
        ELSE 0
    END AS [Value]

    FROM (SELECT @SiteId AS Id) R
    LEFT JOIN Sites S ON S.Id = R.Id

This solution allows you to return default values for each column also, for example:

SELECT
    CASE WHEN S.Id IS NULL THEN 0 ELSE S.Col1 END AS Col1,
    S.Col2,
    ISNULL(S.Col3, 0) AS Col3
FROM
    (SELECT @Id AS Id) R
    LEFT JOIN Sites S ON S.Id = R.Id AND S.Status = 1 AND ...

insert datetime value in sql database with c#

using (SqlConnection conn = new SqlConnection())
using (SqlCommand cmd = conn.CreateCommand())
{
    cmd.CommandText = "INSERT INTO <table> (<date_column>) VALUES ('2010-01-01 12:00')";
    cmd.ExecuteNonQuery();
}

It's been awhile since I wrote this stuff, so this may not be perfect. but the general idea is there.

WARNING: this is unsanitized. You should use parameters to avoid injection attacks.

EDIT: Since Jon insists.

How to filter WooCommerce products by custom attribute

On one of my sites I had to make a custom search by a lot of data some of it from custom fields here is how my $args look like for one of the options:

$args = array(
    'meta_query' => $meta_query,
    'tax_query' => array(
        $query_tax
    ),
    'posts_per_page' => 10,
    'post_type' => 'ad_listing',
    'orderby' => $orderby,
    'order' => $order,
    'paged' => $paged
);

where "$meta_query" is:

$key = "your_custom_key"; //custom_color for example
$value = "blue";//or red or any color
$query_color = array('key' => $key, 'value' => $value);
$meta_query[] = $query_color;

and after that:

query_posts($args);

so you would probably get more info here: http://codex.wordpress.org/Class_Reference/WP_Query and you can search for "meta_query" in the page to get to the info

How to run JUnit test cases from the command line

Actually you can also make the Junit test a runnable Jar and call the runnable jar as java -jar

TypeError: can't use a string pattern on a bytes-like object in re.findall()

The problem is that your regex is a string, but html is bytes:

>>> type(html)
<class 'bytes'>

Since python doesn't know how those bytes are encoded, it throws an exception when you try to use a string regex on them.

You can either decode the bytes to a string:

html = html.decode('ISO-8859-1')  # encoding may vary!
title = re.findall(pattern, html)  # no more error

Or use a bytes regex:

regex = rb'<title>(,+?)</title>'
#        ^

In this particular context, you can get the encoding from the response headers:

with urllib.request.urlopen(url) as response:
    encoding = response.info().get_param('charset', 'utf8')
    html = response.read().decode(encoding)

See the urlopen documentation for more details.

Django: Redirect to previous page after login

See django docs for views.login(), you supply a 'next' value (as a hidden field) on the input form to redirect to after a successful login.

Merging a lot of data.frames

Put them into a list and use merge with Reduce

Reduce(function(x, y) merge(x, y, all=TRUE), list(df1, df2, df3))
#    id v1 v2 v3
# 1   1  1 NA NA
# 2  10  4 NA NA
# 3   2  3  4 NA
# 4  43  5 NA NA
# 5  73  2 NA NA
# 6  23 NA  2  1
# 7  57 NA  3 NA
# 8  62 NA  5  2
# 9   7 NA  1 NA
# 10 96 NA  6 NA

You can also use this more concise version:

Reduce(function(...) merge(..., all=TRUE), list(df1, df2, df3))

How to prevent IFRAME from redirecting top-level window

Try using the onbeforeunload property, which will let the user choose whether he wants to navigate away from the page.

Example: https://developer.mozilla.org/en-US/docs/Web/API/Window.onbeforeunload

In HTML5 you can use sandbox property. Please see Pankrat's answer below. http://www.html5rocks.com/en/tutorials/security/sandboxed-iframes/

SQL Query - Using Order By in UNION

Browsing this comment section I came accross two different patterns answering the question. Sadly for SQL 2012, the second pattern doesn't work, so here's my "work around"


Order By on a Common Column

This is the easiest case you can encounter. Like many user pointed out, all you really need to do is add an Order By at the end of the query

SELECT a FROM table1
UNION
SELECT a FROM table2
ORDER BY field1

or

SELECT a FROM table1 ORDER BY field1
UNION
SELECT a FROM table2 ORDER BY field1

Order By on Different Columns

Here's where it actually gets tricky. Using SQL 2012, I tried the top post and it doesn't work.

SELECT * FROM 
(
  SELECT table1.field1 FROM table1 ORDER BY table1.field1
) DUMMY_ALIAS1

UNION ALL

SELECT * FROM
( 
  SELECT table2.field1 FROM table2 ORDER BY table2.field1
) DUMMY_ALIAS2

Following the recommandation in the comment I tried this

SELECT * FROM 
(
  SELECT TOP 100 PERCENT table1.field1 FROM table1 ORDER BY table1.field1
) DUMMY_ALIAS1

UNION ALL

SELECT * FROM
( 
  SELECT TOP 100 PERCENT table2.field1 FROM table2 ORDER BY table2.field1
) DUMMY_ALIAS2

This code did compile but the DUMMY_ALIAS1 and DUMMY_ALIAS2 override the Order By established in the Select statement which makes this unusable.

The only solution that I could think of, that worked for me was not using a union and instead making the queries run individually and then dealing with them. So basically, not using a Union when you want to Order By

Folder structure for a Node.js project

Concerning the folders you mentioned:

  • /libs is usually used for custom classes/functions/modules
  • /vendor or /support contains 3rd party libraries (added as git sub-module when using git as source control)
  • /spec contains specifications for BDD tests.
  • /tests contains the unit-tests for an application (using a testing framework, see here)

NOTE: both /vendor and /support are deprecated since NPM introduced a clean package management. It's recommended to handle all 3rd-party dependencies using NPM and a package.json file

When building a rather large application, I recommend the following additional folders (especially if you are using some kind of MVC- / ORM-Framework like express or mongoose):

  • /models contains all your ORM models (called Schemas in mongoose)
  • /views contains your view-templates (using any templating language supported in express)
  • /public contains all static content (images, style-sheets, client-side JavaScript)
    • /assets/images contains image files
    • /assets/pdf contains static pdf files
    • /css contains style sheets (or compiled output by a css engine)
    • /js contains client side JavaScript
  • /controllers contain all your express routes, separated by module/area of your application (note: when using the bootstrapping functionality of express, this folder is called /routes)

I got used to organize my projects this way and i think it works out pretty well.

Update for CoffeeScript-based Express applications (using connect-assets):

  • /app contains your compiled JavaScript
  • /assets/ contains all client-side assets that require compilation
    • /assets/js contains your client-side CoffeeScript files
    • /assets/css contains all your LESS/Stylus style-sheets
  • /public/(js|css|img) contains your static files that are not handled by any compilers
  • /src contains all your server-side specific CoffeeScript files
  • /test contains all unit testing scripts (implemented using a testing-framework of your choice)
  • /views contains all your express views (be it jade, ejs or any other templating engine)

Real world use of JMS/message queues?

Distributed (a)synchronous computing.
A real world example could be an application-wide notification framework, which sends mails to the stakeholders at various points during the course of application usage. So the application would act as a Producer by create a Message object, putting it on a particular Queue, and moving forward.
There would be a set of Consumers who would subscribe to the Queue in question, and would take care handling the Message sent across. Note that during the course of this transaction, the Producers are decoupled from the logic of how a given Message would be handled.
Messaging frameworks (ActiveMQ and the likes) act as a backbone to facilitate such Message transactions by providing MessageBrokers.

How can I add a space in between two outputs?

System.out.println(Name + " " + Income);

Is that what you mean? That will put a space between the name and the income?

How to position a DIV in a specific coordinates?

You can also use position fixed css property.

<!-- html code --> 
<div class="box" id="myElement"></div>

/* css code */
.box {
    position: fixed;
}

// js code

document.getElementById('myElement').style.top = 0; //or whatever 
document.getElementById('myElement').style.left = 0; // or whatever

How could I create a function with a completion handler in Swift?

I'm a little confused about custom made completion handlers. In your example:

Say you have a download function to download a file from network,and want to be notified when download task has finished.

typealias CompletionHandler = (success:Bool) -> Void

func downloadFileFromURL(url: NSURL,completionHandler: CompletionHandler) {

    // download code.

    let flag = true // true if download succeed,false otherwise

    completionHandler(success: flag)
}

Your // download code will still be ran asynchronously. Why wouldn't the code go straight to your let flag = true and completion Handler(success: flag) without waiting for your download code to be finished?

How do I filter date range in DataTables?

Following one is working fine with moments js 2.10 and above

$.fn.dataTableExt.afnFiltering.push(
        function( settings, data, dataIndex ) {
            var min  = $('#min-date').val()
            var max  = $('#max-date').val()
            var createdAt = data[0] || 0; // Our date column in the table
            //createdAt=createdAt.split(" ");
            var startDate   = moment(min, "DD/MM/YYYY");
            var endDate     = moment(max, "DD/MM/YYYY");
            var diffDate = moment(createdAt, "DD/MM/YYYY");
            //console.log(startDate);
            if (
              (min == "" || max == "") ||
              (diffDate.isBetween(startDate, endDate))


            ) {  return true;  }
            return false;

        }
    );

REACT - toggle class onclick

You can also do this with hooks.

function MyComponent (props) {
  const [isActive, setActive] = useState(false);

  const toggleClass = () => {
    setActive(!isActive);
  };

  return (
    <div 
      className={isActive ? 'your_className': null} 
      onClick={toggleClass} 
    >
      <p>{props.text}</p>
    </div>
   );
}  

Processing Symbol Files in Xcode

xCode just copy all crashes logs. If you want to speed-up: delete number of crash reports after you analyze it, directly in this window.

Devices -> View Device Logs -> All Logs

screenshot

Java HotSpot(TM) 64-Bit Server VM warning: ignoring option MaxPermSize

-XX:MaxPermSize=size

Sets the maximum permanent generation space size (in bytes). This option was deprecated in JDK 8, and superseded by the -XX:MaxMetaspaceSize option.

-XX:PermSize=size

Sets the space (in bytes) allocated to the permanent generation that triggers a garbage collection if it is exceeded. This option was deprecated in JDK 8, and superseded by the -XX:MetaspaceSize option.

How can I serve static html from spring boot?

Static files should be served from resources, not from controller.

Spring Boot will automatically add static web resources located within any of the following directories:

/META-INF/resources/  
/resources/  
/static/  
/public/

refs:
https://spring.io/blog/2013/12/19/serving-static-web-content-with-spring-boot
https://spring.io/guides/gs/serving-web-content/

nano error: Error opening terminal: xterm-256color

I had this problem connecting to http://sdf.org through Mac OS X Lion. I changed under Terminal Preferences (?+,) > Advanced pane, Declare Terminal as to VT-100.

I also marked Delete Sends Ctrl-H because this Mac connection was confusing zsh.

It appears to be working for my use case.

How to find a value in an excel column by vba code Cells.Find

Just use

Dim Cell As Range
Columns("B:B").Select
Set cell = Selection.Find(What:="celda", After:=ActiveCell, LookIn:=xlFormulas, _
        LookAt:=xlWhole, SearchOrder:=xlByRows, SearchDirection:=xlNext, _
        MatchCase:=False, SearchFormat:=False)

If cell Is Nothing Then
    'do it something

Else
    'do it another thing
End If

libxml/tree.h no such file or directory

I solved in three steps inXcode 8.0 + Unit Test Project

1) I added libxml file to the Build Phases.follow this link

2) I added Other Linker Flags as -ObjC (For both project and test project targets)

3) I setup Header Search Path as "${SDKROOT}/usr/include/libxml2" (Don't forget double quote in either side) (For both project and test project targets)

One of them will solve the issue. If not you have to apply all three of the above.

How to create JSON object using jQuery

Just put your data into an Object like this:

var myObject = new Object();
myObject.name = "John";
myObject.age = 12;
myObject.pets = ["cat", "dog"];

Afterwards stringify it via:

var myString = JSON.stringify(myObject);

You don't need jQuery for this. It's pure JS.

Multidimensional arrays in Swift

Your problem may have been due to a deficiency in an earlier version of Swift or of the Xcode Beta. Working with Xcode Version 6.0 (6A279r) on August 21, 2014, your code works as expected with this output:

column: 0 row: 0 value:1.0
column: 0 row: 1 value:4.0
column: 0 row: 2 value:7.0
column: 1 row: 0 value:2.0
column: 1 row: 1 value:5.0
column: 1 row: 2 value:8.0
column: 2 row: 0 value:3.0
column: 2 row: 1 value:6.0
column: 2 row: 2 value:9.0

I just copied and pasted your code into a Swift playground and defined two constants:

let NumColumns = 3, NumRows = 3

Catch Ctrl-C in C

Set up a trap (you can trap several signals with one handler):

signal (SIGQUIT, my_handler);
signal (SIGINT, my_handler);

Handle the signal however you want, but be aware of limitations and gotchas:

void my_handler (int sig)
{
  /* Your code here. */
}

PHP Fatal error: Cannot access empty property

To access a variable in a class, you must use $this->myVar instead of $this->$myvar.

And, you should use access identifier to declare a variable instead of var.

Please read the doc here.

Does a favicon have to be 32x32 or 16x16?

As I learned, no one of those several solutions are perfects. Using a favicon generator is indeed a good solution but their number is overwhelming and it's hard to choose. I d'like to add that if you want your website to be PWA enabled, you need to provide also a 512x512 icon as stated by Google Devs :

icons including a 192px and a 512px version

I didn't met a lot of favicon generators enforcing that criteria (firebase does, but there is a lot of things it doesn't do). So the solution must be a mix of many other solutions.

I don't know, today at the begining of 2020 if providing a 16x16, 32x32 still relevant. I guess it still matters in certain context like, for example, if your users still use IE for some reason (this stills happen in some privates companies which doesn't migrate to a newer browser for some reasons)

How do I move focus to next input with jQuery?

Here is what worked in my case. Might be less performance intensive.

$('#myelement').siblings('input').first().focus();

Why should the static field be accessed in a static way?

There's actually a good reason:
The non-static access does not always work, for reasons of ambiguity.

Suppose we have two classes, A and B, the latter being a subclass of A, with static fields with the same name:

public class A {
    public static String VALUE = "Aaa";
}

public class B extends A {
    public static String VALUE = "Bbb";
}

Direct access to the static variable:

A.VALUE (="Aaa")
B.VALUE (="Bbb")

Indirect access using an instance (gives a compiler warning that VALUE should be statically accessed):

new B().VALUE (="Bbb")

So far, so good, the compiler can guess which static variable to use, the one on the superclass is somehow farther away, seems somehow logical.

Now to the point where it gets tricky: Interfaces can also have static variables.

public interface C {
    public static String VALUE = "Ccc";
}

public interface D {
    public static String VALUE = "Ddd";
}

Let's remove the static variable from B, and observe following situations:

  • B implements C, D
  • B extends A implements C
  • B extends A implements C, D
  • B extends A implements C where A implements D
  • B extends A implements C where C extends D
  • ...

The statement new B().VALUE is now ambiguous, as the compiler cannot decide which static variable was meant, and will report it as an error:

error: reference to VALUE is ambiguous
both variable VALUE in C and variable VALUE in D match

And that's exactly the reason why static variables should be accessed in a static way.

Jquery bind double click and single click separately

var singleClickTimer = 0; //define a var to hold timer event in parent scope
jqueryElem.click(function(e){ //using jquery click handler
    if (e.detail == 1) { //ensure this is the first click
        singleClickTimer = setTimeout(function(){ //create a timer
            alert('single'); //run your single click code
        },250); //250 or 1/4th second is about right
    }
});

jqueryElem.dblclick(function(e){ //using jquery dblclick handler
    clearTimeout(singleClickTimer); //cancel the single click
    alert('double'); //run your double click code
});

Fatal error: Out of memory, but I do have plenty of memory (PHP)

Hey I also got the same problem on my server. I just changed the following things :

change php.ini to...

memory_limit = 128M

and add to httpd.conf

RLimitMEM 1073741824 2147483648

and restart apache & i removed the error :

iPhone App Development on Ubuntu

There are several way to do it, may decide to go the native way by downloading a VM application for linux and the install Mac OS in your VM and then download the Xcode application for mac But the true is i tried this path but it was really long so i decide to get sencha touch and phonegap for mobile phone,here the sencha-touch is a javascript framework that will help you in developing the interfaces and the phonegap is also javascript library which will help to access the feature of your Iphone or any oher mobile platform I'm using sencha-touch and phonegap ,its really work for me

How to copy a string of std::string type in C++?

You shouldn't use strcpy() to copy a std::string, only use it for C-Style strings.

If you want to copy a to b then just use the = operator.

string a = "text";
string b = "image";
b = a;

CS0120: An object reference is required for the nonstatic field, method, or property 'foo'

I actually got this error because I was checking InnerHtml for some content that was generated dynamically - i.e. a control that is runat=server.

To solve this I had to remove the "static" keyword on my method, and it ran fine.

How to Validate a DateTime in C#?

One liner:

if (DateTime.TryParse(value, out _)) {//dostuff}

REST API Best practices: Where to put parameters?

I see a lot of REST APIs that don't handle parameters well. One example that comes up often is when the URI includes personally identifiable information.

http://software.danielwatrous.com/design-principles-for-rest-apis/

I think a corollary question is when a parameter shouldn't be a parameter at all, but should instead be moved to the HEADER or BODY of the request.

Binding ItemsSource of a ComboBoxColumn in WPF DataGrid

I realize this question is over a year old, but I just stumbled across it in dealing with a similar problem and thought I would share another potential solution in case it might help a future traveler (or myself, when I forget this later and find myself flopping around on StackOverflow between screams and throwings of the nearest object on my desk).

In my case I was able to get the effect I wanted by using a DataGridTemplateColumn instead of a DataGridComboBoxColumn, a la the following snippet. [caveat: I'm using .NET 4.0, and what I've been reading leads me to believe the DataGrid has done a lot of evolving, so YMMV if using earlier version]

<DataGridTemplateColumn Header="Identifier_TEMPLATED">
    <DataGridTemplateColumn.CellEditingTemplate>
        <DataTemplate>
            <ComboBox IsEditable="False" 
                Text="{Binding ComponentIdentifier,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}"
                ItemsSource="{Binding Path=ApplicableIdentifiers, Mode=OneWay, UpdateSourceTrigger=PropertyChanged}" />
        </DataTemplate>
    </DataGridTemplateColumn.CellEditingTemplate>
    <DataGridTemplateColumn.CellTemplate>
        <DataTemplate>
            <TextBlock Text="{Binding ComponentIdentifier}" />
        </DataTemplate>
    </DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>

Check if list is empty in C#

var dataSource = lst!=null && lst.Any() ? lst : null;
// bind dataSource to gird source

Converting string to tuple without splitting characters

Just in case someone comes here trying to know how to create a tuple assigning each part of the string "Quattro" and "TT" to an element of the list, it would be like this print tuple(a.split())

Button that refreshes the page on click

I noticed that all the answers here use inline onClick handlers. It's generally recommended to keep HTML and Javascript separate.

Here's an answer that adds a click event listener directly to the button. When it's clicked, it calls location.reload which causes the page to reload with the current URL.

_x000D_
_x000D_
const refreshButton = document.querySelector('.refresh-button');_x000D_
_x000D_
const refreshPage = () => {_x000D_
  location.reload();_x000D_
}_x000D_
_x000D_
refreshButton.addEventListener('click', refreshPage)
_x000D_
.demo-image {_x000D_
  display: block;_x000D_
}
_x000D_
<button class="refresh-button">Refresh!</button>_x000D_
<img class="demo-image" src="https://picsum.photos/200/300">
_x000D_
_x000D_
_x000D_

What is the meaning of @_ in Perl?

Never try to edit to @_ variable!!!! They must be not touched.. Or you get some unsuspected effect. For example...

my $size=1234;
sub sub1{
  $_[0]=500;
}
sub1 $size;

Before call sub1 $size contain 1234. But after 500(!!) So you Don't edit this value!!! You may pass two or more values and change them in subroutine and all of them will be changed! I've never seen this effect described. Programs I've seen also leave @_ array readonly. And only that you may safely pass variable don't changed internal subroutine You must always do that:

sub sub2{
  my @m=@_;
  ....
}

assign @_ to local subroutine procedure variables and next worked with them. Also in some deep recursive algorithms that returun array you may use this approach to reduce memory used for local vars. Only if return @_ array the same.

Inner join with 3 tables in mysql

SELECT
  student.firstname,
  student.lastname,
  exam.name,
  exam.date,
  grade.grade
FROM grade
 INNER JOIN student
   ON student.studentId = grade.fk_studentId
 INNER JOIN exam
   ON exam.examId = grade.fk_examId
 GROUP BY grade.gradeId
 ORDER BY exam.date

How to convert timestamps to dates in Bash?

In this answer I copy Dennis Williamson's answer and modify it slightly to allow a vast speed increase when piping a column of many timestamps to the script. For example, piping 1000 timestamps to the original script with xargs -n1 on my machine took 6.929s as opposed to 0.027s with this modified version:

#!/bin/bash
LANG=C
if [[ -z "$1" ]]
then
    if [[ -p /dev/stdin ]]    # input from a pipe
    then
        cat - | gawk '{ print strftime("%c", $1); }'
    else
        echo "No timestamp given." >&2
        exit
    fi
else
    date -d @$1 +%c
fi

HTML: How to make a submit button with text + image in it?

input type="submit" is the best way to have a submit button in a form. The downside of this is that you cannot put anything other than text as its value. The button element can contain other HTML elements and content.

Try putting type="submit" instead of type="button" in your button element (source).

Pay particular attention however to the following from that page:

If you use the button element in an HTML form, different browsers will submit different values. Internet Explorer will submit the text between the <button> and </button> tags, while other browsers will submit the content of the value attribute. Use the input element to create buttons in an HTML form.

How to POST a JSON object to a JAX-RS service

I faced the same 415 http error when sending objects, serialized into JSON, via PUT/PUSH requests to my JAX-rs services, in other words my server was not able to de-serialize the objects from JSON. In my case, the server was able to serialize successfully the same objects in JSON when sending them into its responses.

As mentioned in the other responses I have correctly set the Accept and Content-Type headers to application/json, but it doesn't suffice.

Solution

I simply forgot a default constructor with no parameters for my DTO objects. Yes this is the same reasoning behind @Entity objects, you need a constructor with no parameters for the ORM to instantiate objects and populate the fields later.

Adding the constructor with no parameters to my DTO objects solved my issue. Here follows an example that resembles my code:

Wrong

@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class NumberDTO {
    public NumberDTO(Number number) {
        this.number = number;
    }

    private Number number;

    public Number getNumber() {
        return number;
    }

    public void setNumber(Number string) {
        this.number = string;
    }
}

Right

@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class NumberDTO {

    public NumberDTO() {
    }

    public NumberDTO(Number number) {
        this.number = number;
    }

    private Number number;

    public Number getNumber() {
        return number;
    }

    public void setNumber(Number string) {
        this.number = string;
    }
}

I lost hours, I hope this'll save yours ;-)

How to load a resource from WEB-INF directory of a web archive

Here is how it works for me with no Servlet use.

Let's say I am trying to access web.xml in project/WebContent/WEB-INF/web.xml

  1. In project property Source-tab add source folder by pointing to the parent container for WEB-INF folder (in my case WebContent )

  2. Now let's use class loader:

    InputStream inStream = class.getClass().getClassLoader().getResourceAsStream("Web-INF/web.xml")
    

How to enable or disable an anchor using jQuery?

It's as simple as return false;

ex.

jQuery("li a:eq(0)").click(function(){
   return false;
})

or

jQuery("#menu a").click(function(){
   return false;
})

Converting string to numeric

As csgillespie said. stringsAsFactors is default on TRUE, which converts any text to a factor. So even after deleting the text, you still have a factor in your dataframe.

Now regarding the conversion, there's a more optimal way to do so. So I put it here as a reference :

> x <- factor(sample(4:8,10,replace=T))
> x
 [1] 6 4 8 6 7 6 8 5 8 4
Levels: 4 5 6 7 8
> as.numeric(levels(x))[x]
 [1] 6 4 8 6 7 6 8 5 8 4

To show it works.

The timings :

> x <- factor(sample(4:8,500000,replace=T))
> system.time(as.numeric(as.character(x)))
   user  system elapsed 
   0.11    0.00    0.11 
> system.time(as.numeric(levels(x))[x])
   user  system elapsed 
      0       0       0 

It's a big improvement, but not always a bottleneck. It gets important however if you have a big dataframe and a lot of columns to convert.

SOAP Action WSDL

SOAPAction is required in SOAP 1.1 but can be empty ("").

See https://www.w3.org/TR/2000/NOTE-SOAP-20000508/#_Toc478383528

"The header field value of empty string ("") means that the intent of the SOAP message is provided by the HTTP Request-URI."

Try setting SOAPAction=""

How to force view controller orientation in iOS 8?

On Xcode 8 the methods are converted to properties, so the following works with Swift:

override public var supportedInterfaceOrientations: UIInterfaceOrientationMask {
    return UIInterfaceOrientationMask.portrait
}

override public var preferredInterfaceOrientationForPresentation: UIInterfaceOrientation {
    return UIInterfaceOrientation.portrait
}

override public var shouldAutorotate: Bool {
    return true
}

*ngIf else if in template

Another alternative is to nest conditions

<ng-container *ngIf="foo === 1;else second"></ng-container>
<ng-template #second>
    <ng-container *ngIf="foo === 2;else third"></ng-container>
</ng-template>
<ng-template #third></ng-template>

Counting lines, words, and characters within a text file using Python

fname = "feed.txt"
feed = open(fname, 'r')

num_lines = len(feed.splitlines())
num_words = 0
num_chars = 0

for line in lines:
    num_words += len(line.split())

ipython notebook clear cell output in code

And in case you come here, like I did, looking to do the same thing for plots in a Julia notebook in Jupyter, using Plots, you can use:

    IJulia.clear_output(true)

so for a kind of animated plot of multiple runs

    if nrun==1  
      display(plot(x,y))         # first plot
    else 
      IJulia.clear_output(true)  # clear the window (as above)
      display(plot!(x,y))        # plot! overlays the plot
    end

Without the clear_output call, all plots appear separately.

How do I center an SVG in a div?

I had to use

display: inline-block;

What is the Windows version of cron?

There is NNCron for Windows. IT can schedule jobs to be run periodically.

How to read the Stock CPU Usage data

As other answers have pointed, on UNIX systems the numbers represent CPU load averages over 1/5/15 minute periods. But on Linux (and consequently Android), what it represents is something different.

After a kernel patch dating back to 1993 (a great in-depth article on the subject), in Linux the load average numbers no longer strictly represent the CPU load: as the calculation accounts not only for CPU bound processes, but also for processes in uninterruptible wait state - the original goal was to account for I/O bound processes this way, to represent more of a "system load" than just CPU load. The issue is that since 1993 the usage of uninterruptible state has grown in Linux kernel, and it no longer typically represents an I/O bound process. The problem is further exacerbated by some Linux devs using uninterruptible waits as an easy wait to avoid accommodating signals in their implementations. As a result, in Linux (and Android) we can see skewed high load average numbers that do not objectively represent the real load. There are Android user reports about unreasonable high load averages contrasting low CPU utilization. For example, my old Android phone (with 2 CPU cores) normally shown average load of ~12 even when the system and CPUs were idle. Hence, average load numbers in Linux (Android) does not turn out to be a reliable performance metric.

Concatenating strings in Razor

the plus works just fine, i personally prefer using the concat function.

var s = string.Concat(string 1, string 2, string, 3, etc)

cast or convert a float to nvarchar?

Float won't convert into NVARCHAR directly, first we need to convert float into money datatype and then convert into NVARCHAR, see the examples below.

Example1

SELECT CAST(CAST(1234567890.1234  AS FLOAT) AS NVARCHAR(100))

output

1.23457e+009

Example2

SELECT CAST(CAST(CAST(1234567890.1234  AS FLOAT) AS MONEY) AS NVARCHAR(100))

output

1234567890.12

In Example2 value is converted into float to NVARCHAR

How to group time by hour or by 10 minutes

For MySql:

GROUP BY
DATE(`your_date_field`),
HOUR(`your_date_field`),
FLOOR( MINUTE(`your_date_field`) / 10);

How to convert string to date to string in Swift iOS?

See answer from Gary Makin. And you need change the format or data. Because the data that you have do not fit under the chosen format. For example this code works correct:

let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "MM-dd-yyyy"
let dateObj = dateFormatter.dateFromString("10 10 2001")
print("Dateobj: \(dateObj)")

Export tables to an excel spreadsheet in same directory

For people who find this via search engines, you do not need VBA. You can just:

1.) select the query or table with your mouse
2.) click export data from the ribbon
3.) click excel from the export subgroup
4.) follow the wizard to select the output file and location.

What is the most efficient way to create HTML elements using jQuery?

personally i'd suggest (for readability):

$('<div>');

some numbers on the suggestions so far (safari 3.2.1 / mac os x):

var it = 50000;

var start = new Date().getTime();
for (i = 0; i < it; ++i)  {
  // test creation of an element 
  // see below statements
}
var end = new Date().getTime();
alert( end - start );                

var e = $( document.createElement('div') );  // ~300ms
var e = $('<div>');                          // ~3100ms
var e = $('<div></div>');                    // ~3200ms
var e = $('<div/>');                         // ~3500ms              

How can I scroll up more (increase the scroll buffer) in iTerm2?

macOS default termianl

macOS 10.15.7

  1. open Terminal
  2. click Prefrences...
  3. select Window tab
  4. just change Scrollback to Limit number of rows to: what your wanted.

my screenshots

enter image description here

enter image description here

enter image description here

What are the best PHP input sanitizing functions?

what about this

$string = htmlspecialchars(strip_tags($_POST['example']));

or this

$string = htmlentities($_POST['example'], ENT_QUOTES, 'UTF-8');

using sql count in a case statement

Close... try:

select 
   Sum(case when rsp_ind = 0 then 1 Else 0 End) as 'New',
   Sum(case when rsp_ind = 1 then 1 else 0 end) as 'Accepted'
from tb_a

tkinter: how to use after method

You need to give a function to be called after the time delay as the second argument to after:

after(delay_ms, callback=None, *args)

Registers an alarm callback that is called after a given time.

So what you really want to do is this:

tiles_letter = ['a', 'b', 'c', 'd', 'e']

def add_letter():
    rand = random.choice(tiles_letter)
    tile_frame = Label(frame, text=rand)
    tile_frame.pack()
    root.after(500, add_letter)
    tiles_letter.remove(rand)  # remove that tile from list of tiles


root.after(0, add_letter)  # add_letter will run as soon as the mainloop starts.
root.mainloop()

You also need to schedule the function to be called again by repeating the call to after inside the callback function, since after only executes the given function once. This is also noted in the documentation:

The callback is only called once for each call to this method. To keep calling the callback, you need to reregister the callback inside itself

Note that your example will throw an exception as soon as you've exhausted all the entries in tiles_letter, so you need to change your logic to handle that case whichever way you want. The simplest thing would be to add a check at the beginning of add_letter to make sure the list isn't empty, and just return if it is:

def add_letter():
    if not tiles_letter:
        return
    rand = random.choice(tiles_letter)
    tile_frame = Label(frame, text=rand)
    tile_frame.pack()
    root.after(500, add_letter)
    tiles_letter.remove(rand)  # remove that tile from list of tiles

Live-Demo: repl.it

Running an outside program (executable) in Python?

That's the correct usage, but perhaps the spaces in the path name are messing things up for some reason.

You may want to run the program under cmd.exe as well so you can see any output from flow.exe that might be indicating an error.

In a Dockerfile, How to update PATH environment variable?

This is discouraged (if you want to create/distribute a clean Docker image), since the PATH variable is set by /etc/profile script, the value can be overridden.

head /etc/profile:

if [ "`id -u`" -eq 0 ]; then
  PATH="/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"
else
  PATH="/usr/local/bin:/usr/bin:/bin:/usr/local/games:/usr/games"
fi
export PATH

At the end of the Dockerfile, you could add:

RUN echo "export PATH=$PATH" > /etc/environment

So PATH is set for all users.

c# dictionary one key many values

Use this:

Dictionary<TKey, Tuple<TValue1, TValue2, TValue3, ...>>

How do I get a PHP class constructor to call its parent's parent's constructor?

Ok, Yet another ugly solution:

Create a function in Papa like:

protected function call2Granpa() {
     return parent::__construct();
}

Then in Kiddo you use:

parent::call2Granpa(); //instead of calling constructor in Papa.

I think it could work... I haven't test it, so I'm not sure if the objects are created correctly.

I used this approach but with non-constructor functions.

Google Maps API v3: Can I setZoom after fitBounds?

To chime in with another solution - I found that the "listen for bounds_changed event and then set new zoom" approach didn't work reliably for me. I think that I was sometimes calling fitBounds before the map had been fully initialized, and the initialization was causing a bounds_changed event that would use up the listener, before fitBounds changed the boundaries and zoom level. I ended up with this code, which seems to work so far:

// If there's only one marker, or if the markers are all super close together,
// `fitBounds` can zoom in too far. We want to limit the maximum zoom it can
// use.
//
// `fitBounds` is asynchronous, so we need to wait until the bounds have
// changed before we know what the new zoom is, using an event handler.
//
// Sometimes this handler gets triggered by a different event, before
// `fitBounds` takes effect; that particularly seems to happen if the map
// hasn't been fully initialized yet. So we don't immediately remove the
// listener; instead, we wait until the 'idle' event, and remove it then.
//
// But 'idle' might happen before 'bounds_changed', so we can't set up the
// removal handler immediately. Set it up in the first event handler.

var removeListener = null;
var listener = google.maps.event.addListener(map, 'bounds_changed', () => {
  console.log(map.getZoom());
  if (map.getZoom() > 15) {
    map.setZoom(15);
  }

  if (!removeListener) {
    removeListener = google.maps.event.addListenerOnce(map, 'idle', () => {
      console.log('remove');
      google.maps.event.removeListener(listener);
    });
  }
});

Convert a char to upper case using regular expressions (EditPad Pro)

You can also capitalize the first letter of the match using \I1 and \I2 etc instead of $1 and $2.

Regular expression for 10 digit number without any special characters

An example of how to implement it:

public bool ValidateSocialSecNumber(string socialSecNumber)
{
    //Accepts only 10 digits, no more no less. (Like Mike's answer)
    Regex pattern = new Regex(@"(?<!\d)\d{10}(?!\d)");

    if(pattern.isMatch(socialSecNumber))
    {
        //Do something
        return true;
    }
    else
    {
        return false;
    }
}

You could've also done it in another way by e.g. using Match and then wrapping a try-catch block around the pattern matching. However, if a wrong input is given quite often, it's quite expensive to throw an exception. Thus, I prefer the above way, in simple cases at least.

Android: how to handle button click

Most used way is, anonymous declaration

    Button send = (Button) findViewById(R.id.buttonSend);
    send.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            // handle click
        }
    });

Also you can create View.OnClickListener object and set it to button later, but you still need to override onClick method for example

View.OnClickListener listener = new View.OnClickListener(){
     @Override
        public void onClick(View v) {
            // handle click
        }
}   
Button send = (Button) findViewById(R.id.buttonSend);
send.setOnClickListener(listener);

When your activity implements OnClickListener interface you must override onClick(View v) method on activity level. Then you can assing this activity as listener to button, because it already implements interface and overrides the onClick() method

public class MyActivity extends Activity implements View.OnClickListener{


    @Override
    public void onClick(View v) {
        // handle click
    }


    @Override
    public void onCreate(Bundle b) {
        Button send = (Button) findViewById(R.id.buttonSend);
        send.setOnClickListener(this);
    }

}

(imho) 4-th approach used when multiple buttons have same handler, and you can declare one method in activity class and assign this method to multiple buttons in xml layout, also you can create one method for one button, but in this case I prefer to declare handlers inside activity class.

"You have mail" message in terminal, os X

As inspiredlife explained, you can figure out whats happening using mail command.

If you don't want to delete bunch of unrelated / auto-generated messages one by one (like me), simply run the command below to get rid of all messages:

echo -n > /var/mail/yourusername

Compiling with g++ using multiple cores

I'm not sure about g++, but if you're using GNU Make then "make -j N" (where N is the number of threads make can create) will allow make to run multple g++ jobs at the same time (so long as the files do not depend on each other).

How to set default font family in React Native?

The recommended way is to create your own component, such as MyAppText. MyAppText would be a simple component that renders a Text component using your universal style and can pass through other props, etc.

https://facebook.github.io/react-native/docs/text.html#limited-style-inheritance

Styling an input type="file" button

_x000D_
_x000D_
$('.new_Btn').click(function() {
  $('#html_btn').click();
});
_x000D_
.new_Btn {
  // your css propterties
}

#html_btn {
  display: none;
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="new_Btn">SelectPicture</div><br>
<input id="html_btn" type='file' " /><br>
_x000D_
_x000D_
_x000D_

You can reach your goals too without jQuery with normal JavaScript.

Now the newBtn is linkes with the html_btn and you can style your new btn like you want :D

Convert HashBytes to VarChar

Changing the datatype to varbinary seems to work the best for me.

Creating and Naming Worksheet in Excel VBA

http://www.mrexcel.com/td0097.html

Dim WS as Worksheet
Set WS = Sheets.Add

You don't have to know where it's located, or what it's name is, you just refer to it as WS.
If you still want to do this the "old fashioned" way, try this:

Sheets.Add.Name = "Test"

The ResourceConfig instance does not contain any root resource classes

I had the same issue, testing a bunch of different examples, and tried all the possible solutions. What finally got it working for me was when I added a @Path("") over the class line, I had left that out.

How can a Javascript object refer to values in itself?

This can be achieved by using constructor function instead of literal

var o = new function() {
  this.foo = "it";
  this.bar = this.foo + " works"
}

alert(o.bar)

Switch statement with returns -- code correctness

Keep the breaks - you're less likely to run into trouble if/when you edit the code later if the breaks are already in place.

Having said that, it's considered by many (including me) to be bad practice to return from the middle of a function. Ideally a function should have one entry point and one exit point.

Command for restarting all running docker containers?

To start all the containers:

  docker restart $(docker ps -a -q)

Use sudo if you don't have permission to perform this:

sudo docker restart $(sudo docker ps -a -q)

How to convert int to string on Arduino?

Serial.println(val) 
Serial.println(val, format)

for more you can visit to the site of arduino https://www.arduino.cc/en/Serial/Println

wish this will help you. thanks!

Subdomain on different host

You just need to add an "A" record in the DNS manager on Godaddy. In that "A" record put your IP from dreamhost.

I know this works since I'm doing the very same thing.

C# switch on type

See gjvdkamp's answer below; this feature now exists in C#


I usually use a dictionary of types and delegates.
var @switch = new Dictionary<Type, Action> {
    { typeof(Type1), () => ... },
    { typeof(Type2), () => ... },
    { typeof(Type3), () => ... },
};

@switch[typeof(MyType)]();

It's a little less flexible as you can't fall through cases, continue etc. But I rarely do so anyway.

How to display (print) vector in Matlab?

Here is a more generalized solution that prints all elements of x the vector x in this format:

x=randperm(3);
s = repmat('%d,',1,length(x));
s(end)=[]; %Remove trailing comma

disp(sprintf(['Answer: (' s ')'], x))

jQuery addClass onClick

$(document).ready(function() {
    $('#Button').click(function() {
        $(this).addClass('active');
    });
});

should do the trick. unless you're loading the button with ajax. In which case you could do:

$('#Button').live('click', function() {...

Also remember not to use the same id more than once in your html code.

Is there any way to debug chrome in any IOS device

If you don't need full debugging support, you can now view JavaScript console logs directly within Chrome for iOS at chrome://inspect.

https://blog.chromium.org/2019/03/debugging-websites-in-chrome-for-ios.html

Chrome for iOS Console

SQL JOIN - WHERE clause vs. ON clause

  • Does not matter for inner joins

  • Matters for outer joins

    a. WHERE clause: After joining. Records will be filtered after join has taken place.

    b. ON clause - Before joining. Records (from right table) will be filtered before joining. This may end up as null in the result (since OUTER join).



Example: Consider the below tables:

    1. documents:
     | id    | name        |
     --------|-------------|
     | 1     | Document1   |
     | 2     | Document2   |
     | 3     | Document3   |
     | 4     | Document4   |
     | 5     | Document5   |


    2. downloads:
     | id   | document_id   | username |
     |------|---------------|----------|
     | 1    | 1             | sandeep  |
     | 2    | 1             | simi     |
     | 3    | 2             | sandeep  |
     | 4    | 2             | reya     |
     | 5    | 3             | simi     |

a) Inside WHERE clause:

  SELECT documents.name, downloads.id
    FROM documents
    LEFT OUTER JOIN downloads
      ON documents.id = downloads.document_id
    WHERE username = 'sandeep'

 For above query the intermediate join table will look like this.

    | id(from documents) | name         | id (from downloads) | document_id | username |
    |--------------------|--------------|---------------------|-------------|----------|
    | 1                  | Document1    | 1                   | 1           | sandeep  |
    | 1                  | Document1    | 2                   | 1           | simi     |
    | 2                  | Document2    | 3                   | 2           | sandeep  |
    | 2                  | Document2    | 4                   | 2           | reya     |
    | 3                  | Document3    | 5                   | 3           | simi     |
    | 4                  | Document4    | NULL                | NULL        | NULL     |
    | 5                  | Document5    | NULL                | NULL        | NULL     |

  After applying the `WHERE` clause and selecting the listed attributes, the result will be: 

   | name         | id |
   |--------------|----|
   | Document1    | 1  |
   | Document2    | 3  | 

b) Inside JOIN clause

  SELECT documents.name, downloads.id
  FROM documents
    LEFT OUTER JOIN downloads
      ON documents.id = downloads.document_id
        AND username = 'sandeep'

For above query the intermediate join table will look like this.

    | id(from documents) | name         | id (from downloads) | document_id | username |
    |--------------------|--------------|---------------------|-------------|----------|
    | 1                  | Document1    | 1                   | 1           | sandeep  |
    | 2                  | Document2    | 3                   | 2           | sandeep  |
    | 3                  | Document3    | NULL                | NULL        | NULL     |
    | 4                  | Document4    | NULL                | NULL        | NULL     |
    | 5                  | Document5    | NULL                | NULL        | NULL     |

Notice how the rows in `documents` that did not match both the conditions are populated with `NULL` values.

After Selecting the listed attributes, the result will be: 

   | name       | id   |
   |------------|------|
   |  Document1 | 1    |
   |  Document2 | 3    | 
   |  Document3 | NULL |
   |  Document4 | NULL | 
   |  Document5 | NULL | 

Customize the Authorization HTTP header

You can create your own custom auth schemas that use the Authorization: header - for example, this is how OAuth works.

As a general rule, if servers or proxies don't understand the values of standard headers, they will leave them alone and ignore them. It is creating your own header keys that can often produce unexpected results - many proxies will strip headers with names they don't recognise.

Having said that, it is possibly a better idea to use cookies to transmit the token, rather than the Authorization: header, for the simple reason that cookies were explicitly designed to carry custom values, whereas the specification for HTTP's built in auth methods does not really say either way - if you want to see exactly what it does say, have a look here.

The other point about this is that many HTTP client libraries have built-in support for Digest and Basic auth but may make life more difficult when trying to set a raw value in the header field, whereas they will all provide easy support for cookies and will allow more or less any value within them.

How to validate email id in angularJs using ng-pattern

Spend some time to make it working for me.

Requirement:

single or comma separated list of e-mails with domains ending [email protected] or [email protected]

Controller:

$scope.email = {
   EMAIL_FORMAT:  /^\w+([\.-]?\w+)*@(list.)?gmail.com+((\s*)+,(\s*)+\w+([\.-]?\w+)*@(list.)?gmail.com)*$/,
   EMAIL_FORMAT_HELP: "format as '[email protected]' or comma separated '[email protected], [email protected]'"
};

HTML:

<ng-form name="emailModal">
    <div class="form-group row mb-3">
        <label for="to" class="col-sm-2 text-right col-form-label">
            <span class="form-required">*</span>
            To
        </label>
        <div class="col-sm-9">
            <input class="form-control" id="to"
                   name="To"
                   ng-required="true"
                   ng-pattern="email.EMAIL_FORMAT"
                   placeholder="{{email.EMAIL_FORMAT_HELP}}"
                   ng-model="mail.to"/>
            <small class="text-muted" ng-show="emailModal.To.$error.pattern">wrong</small>
        </div>
    </div>
</ng-form>

I found good online regex testing tool. Covered my regex with tests:

https://regex101.com/r/Dg2iAZ/6/tests

How to trigger SIGUSR1 and SIGUSR2?

They are signals that application developers use. The kernel shouldn't ever send these to a process. You can send them using kill(2) or using the utility kill(1).

If you intend to use signals for synchronization you might want to check real-time signals (there's more of them, they are queued, their delivery order is guaranteed etc).

Get name of current script in Python

For modern Python versions (3.4+), Path(__file__).name should be more idiomatic. Also, Path(__file__).stem gives you the script name without the .py extension.

When to create variables (memory management)

It's really a matter of opinion. In your example, System.out.println(5) would be slightly more efficient, as you only refer to the number once and never change it. As was said in a comment, int is a primitive type and not a reference - thus it doesn't take up much space. However, you might want to set actual reference variables to null only if they are used in a very complicated method. All local reference variables are garbage collected when the method they are declared in returns.

Angular 2 Routing run in new tab

In my use case, I wanted to asynchronously retrieve a url, and then follow that url to an external resource in a new window. A directive seemed overkill because I don't need reusability, so I simply did:

<button (click)="navigateToResource()">Navigate</button>

And in my component.ts

navigateToResource(): void {
  this.service.getUrl((result: any) => window.open(result.url));
}


Note:

Routing to a link indirectly like this will likely trigger the browser's popup blocker.

How to dynamically load a Python class

module = __import__("my_package/my_module")
the_class = getattr(module, "MyClass")
obj = the_class()

SVN icon overlays not showing properly

They showed up after installing Ankh SVN

Last executed queries for a specific database

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

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

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

Debugging the error "gcc: error: x86_64-linux-gnu-gcc: No such file or directory"

the error can be due to one of several missing package. Below command will install several packages like g++, gcc, etc.

sudo apt-get install build-essential

2 "style" inline css img tags?

Do not use more than one style attribute. Just seperate styles in the style attribute with ; It is a block of inline CSS, so think of this as you would do CSS in a separate stylesheet.

So in this case its: style="height:100px;width:100px;"

You can use this for any CSS style, so if you wanted to change the colour of the text to white: style="height:100px;width:100px;color:#ffffff" and so on.

However, it is worth using inline CSS sparingly, as it can make code less manageable in future. Using an external stylesheet may be a better option for this. It depends really on your requirements. Inline CSS does make for quicker coding.

Refreshing page on click of a button

<button type="button" onClick="refreshPage()">Close</button>

<script>
function refreshPage(){
    window.location.reload();
} 
</script>

or

<button type="button" onClick="window.location.reload();">Close</button>

Python string to unicode

Unicode escapes only work in unicode strings, so this

 a="\u2026"

is actually a string of 6 characters: '\', 'u', '2', '0', '2', '6'.

To make unicode out of this, use decode('unicode-escape'):

a="\u2026"
print repr(a)
print repr(a.decode('unicode-escape'))

## '\\u2026'
## u'\u2026'

Android ClassNotFoundException: Didn't find class on path

I had this issue, raised by several causes, but i see this in your stacktrace "**Unable to instantiate activity ComponentInfo{...}: java.lang.ClassNotFoundException: Didn't find class "..." on path: DexPathList[[**", I found a diference in my .classpath before it stop working.

 <?xml version="1.0" encoding="UTF-8"?>
<classpath>
    <classpathentry kind="src" path="src"/>
    <classpathentry kind="con" path="com.android.ide.eclipse.adt.ANDROID_FRAMEWORK"/>
    <classpathentry kind="con" path="com.android.ide.eclipse.adt.LIBRARIES"/>
    <classpathentry kind="src" path="gen"/>
    <classpathentry kind="output" path="bin/classes"/>
</classpath>

I've ADDED the line:

<classpathentry exported="true" kind="con" path="com.android.ide.eclipse.adt.DEPENDENCIES"/>

this is the final version:

  <?xml version="1.0" encoding="UTF-8"?>
<classpath>
    <classpathentry kind="src" path="src"/>
    <classpathentry kind="con" path="com.android.ide.eclipse.adt.ANDROID_FRAMEWORK"/>
    <classpathentry kind="con" path="com.android.ide.eclipse.adt.LIBRARIES"/>
    <classpathentry exported="true" kind="con" path="com.android.ide.eclipse.adt.DEPENDENCIES"/>
    <classpathentry kind="src" path="gen"/>
    <classpathentry kind="output" path="bin/classes"/>
</classpath>

Now it works! =)

Regex empty string or email

I prefer /^\s+$|^$/gi to match empty and empty spaces.

_x000D_
_x000D_
console.log("  ".match(/^\s+$|^$/gi));_x000D_
console.log("".match(/^\s+$|^$/gi));
_x000D_
_x000D_
_x000D_

Decimal precision and scale in EF Code First

[Column(TypeName = "decimal(18,2)")]

this will work with EF Core code first migrations as described here.

Add or change a value of JSON key with jquery or javascript

var y_axis_name=[];

 for(var point in jsonData[0].data)
              { 
                y_axis_name.push(point);

              }

y_axis_name is having all the key name

try on jsfiddle

Remove all occurrences of a value from a list?

All of the answers above (apart from Martin Andersson's) create a new list without the desired items, rather than removing the items from the original list.

>>> import random, timeit
>>> a = list(range(5)) * 1000
>>> random.shuffle(a)

>>> b = a
>>> print(b is a)
True

>>> b = [x for x in b if x != 0]
>>> print(b is a)
False
>>> b.count(0)
0
>>> a.count(0)
1000

>>> b = a
>>> b = filter(lambda a: a != 2, x)
>>> print(b is a)
False

This can be important if you have other references to the list hanging around.

To modify the list in place, use a method like this

>>> def removeall_inplace(x, l):
...     for _ in xrange(l.count(x)):
...         l.remove(x)
...
>>> removeall_inplace(0, b)
>>> b is a
True
>>> a.count(0)
0

As far as speed is concerned, results on my laptop are (all on a 5000 entry list with 1000 entries removed)

  • List comprehension - ~400us
  • Filter - ~900us
  • .remove() loop - 50ms

So the .remove loop is about 100x slower........ Hmmm, maybe a different approach is needed. The fastest I've found is using the list comprehension, but then replace the contents of the original list.

>>> def removeall_replace(x, l):
....    t = [y for y in l if y != x]
....    del l[:]
....    l.extend(t)
  • removeall_replace() - 450us

How to insert values in two dimensional array programmatically?

Think about it as array of array.

If you do this str[x][y], then there is array of length x where each element in turn contains array of length y. In java its not necessary for second dimension to have same length. So for x=i you can have y=m and x=j you can have y=n

For this your declaration looks like

String[][] test = new String[4][]; test[0] = new String[3]; test[1] = new String[2];

etc..

Extract the filename from a path

$file = Get-Item -Path "c:/foo/foobar.txt"
$file.Name

Works with both relative an absolute paths

Setting an image button in CSS - image:active

Check this link . You were missing . before myButton. It was a small error. :)

.myButton{
    background:url(./images/but.png) no-repeat;
    cursor:pointer;
    border:none;
    width:100px;
    height:100px;
}

.myButton:active  /* use Dot here */
{   
    background:url(./images/but2.png) no-repeat;
}

sql delete statement where date is greater than 30 days

Use DATEADD in your WHERE clause:

...
WHERE date < DATEADD(day, -30, GETDATE())

You can also use abbreviation d or dd instead of day.

angular.min.js.map not found, what is it exactly?

Monkey is right, according to the link given by monkey

Basically it's a way to map a combined/minified file back to an unbuilt state. When you build for production, along with minifying and combining your JavaScript files, you generate a source map which holds information about your original files. When you query a certain line and column number in your generated JavaScript you can do a lookup in the source map which returns the original location.

I am not sure if it is angular's fault that no map files were generated. But you can turn off source map files by unchecking this option in chrome console setting

enter image description here

PHP Unset Array value effect on other indexes

They are as they were. That one key is JUST DELETED

Accessing the index in 'for' loops?

As is the norm in Python there are several ways to do this. In all examples assume: lst = [1, 2, 3, 4, 5]

1. Using enumerate (considered most idiomatic)

for index, element in enumerate(lst):
    # do the things that need doing here

This is also the safest option in my opinion because the chance of going into infinite recursion has been eliminated. Both the item and its index are held in variables and there is no need to write any further code to access the item.

2. Creating a variable to hold the index (using for)

for index in range(len(lst)):   # or xrange
    # you will have to write extra code to get the element

3. Creating a variable to hold the index (using while)

index = 0
while index < len(lst):
    # you will have to write extra code to get the element
    index += 1  # escape infinite recursion

4. There is always another way

As explained before, there are other ways to do this that have not been explained here and they may even apply more in other situations. e.g using itertools.chain with for. It handles nested loops better than the other examples.

SQL JOIN vs IN performance?

Each database's implementation but you can probably guess that they all solve common problems in more or less the same way. If you are using MSSQL have a look at the execution plan that is generated. You can do this by turning on the profiler and executions plans. This will give you a text version when you run the command.

I am not sure what version of MSSQL you are using but you can get a graphical one in SQL Server 2000 in the query analyzer. I am sure that this functionality is lurking some where in SQL Server Studio Manager in later versions.

Have a look at the exeuction plan. As far as possible avoid table scans unless of course your table is small in which case a table scan is faster than using an index. Read up on the different join operations that each different scenario produces.

Set NOW() as Default Value for datetime datatype?

`ALTER TABLE  `table_name` CHANGE `column_name` 
    timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP 
    ON UPDATE CURRENT_TIMESTAMP

Can be used to update the timestamp on update.

More elegant "ps aux | grep -v grep"

You could use preg_split instead of explode and split on [ ]+ (one or more spaces). But I think in this case you could go with preg_match_all and capturing:

preg_match_all('/[ ]php[ ]+\S+[ ]+(\S+)/', $input, $matches);
$result = $matches[1];

The pattern matches a space, php, more spaces, a string of non-spaces (the path), more spaces, and then captures the next string of non-spaces. The first space is mostly to ensure that you don't match php as part of a user name but really only as a command.

An alternative to capturing is the "keep" feature of PCRE. If you use \K in the pattern, everything before it is discarded in the match:

preg_match_all('/[ ]php[ ]+\S+[ ]+\K\S+/', $input, $matches);
$result = $matches[0];

I would use preg_match(). I do something similar for many of my system management scripts. Here is an example:

$test = "user     12052  0.2  0.1 137184 13056 ?        Ss   10:00   0:00 php /home/user/public_html/utilities/runProcFile.php cust1 cron
user     12054  0.2  0.1 137184 13064 ?        Ss   10:00   0:00 php /home/user/public_html/utilities/runProcFile.php cust3 cron
user     12055  0.6  0.1 137844 14220 ?        Ss   10:00   0:00 php /home/user/public_html/utilities/runProcFile.php cust4 cron
user     12057  0.2  0.1 137184 13052 ?        Ss   10:00   0:00 php /home/user/public_html/utilities/runProcFile.php cust89 cron
user     12058  0.2  0.1 137184 13052 ?        Ss   10:00   0:00 php /home/user/public_html/utilities/runProcFile.php cust435 cron
user     12059  0.3  0.1 135112 13000 ?        Ss   10:00   0:00 php /home/user/public_html/utilities/runProcFile.php cust16 cron
root     12068  0.0  0.0 106088  1164 pts/1    S+   10:00   0:00 sh -c ps aux | grep utilities > /home/user/public_html/logs/dashboard/currentlyPosting.txt
root     12070  0.0  0.0 103240   828 pts/1    R+   10:00   0:00 grep utilities";

$lines = explode("\n", $test);

foreach($lines as $line){
        if(preg_match("/.php[\s+](cust[\d]+)[\s+]cron/i", $line, $matches)){
                print_r($matches);
        }

}

The above prints:

Array
(
    [0] => .php cust1 cron
    [1] => cust1
)
Array
(
    [0] => .php cust3 cron
    [1] => cust3
)
Array
(
    [0] => .php cust4 cron
    [1] => cust4
)
Array
(
    [0] => .php cust89 cron
    [1] => cust89
)
Array
(
    [0] => .php cust435 cron
    [1] => cust435
)
Array
(
    [0] => .php cust16 cron
    [1] => cust16
)

You can set $test to equal the output from exec. the values you are looking for would be in the if statement under the foreach. $matches[1] will have the custx value.

What is the perfect counterpart in Python for "while not EOF"

The Python idiom for opening a file and reading it line-by-line is:

with open('filename') as f:
    for line in f:
        do_something(line)

The file will be automatically closed at the end of the above code (the with construct takes care of that).

Finally, it is worth noting that line will preserve the trailing newline. This can be easily removed using:

line = line.rstrip()

How to pick element inside iframe using document.getElementById

You need to make sure the frame is fully loaded the best way to do it is to use onload:

<iframe id="nesgt" src="" onload="custom()"></iframe>

function custom(){
    document.getElementById("nesgt").contentWindow.document;
    }

this function will run automatically when the iframe is fully loaded.

it could be done with setTimeout but we can't get the exact time of the frame load.

hope this helps someone.

Finding what methods a Python object has

The problem with all methods indicated here is that you can't be sure that a method doesn't exist.

In Python you can intercept the dot calling through __getattr__ and __getattribute__, making it possible to create method "at runtime"

Example:

class MoreMethod(object):
    def some_method(self, x):
        return x
    def __getattr__(self, *args):
        return lambda x: x*2

If you execute it, you can call non-existing methods in the object dictionary...

>>> o = MoreMethod()
>>> o.some_method(5)
5
>>> dir(o)
['__class__', '__delattr__', '__dict__', '__doc__', '__format__', '__getattr__', '__getattribute__', '__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'some_method']
>>> o.i_dont_care_of_the_name(5)
10

And it's why you use the Easier to ask for forgiveness than permission paradigms in Python.

AngularJS - pass function to directive

In your 'test' directive Html tag, the attribute name of the function should not be camelCased, but dash-based.

so - instead of :

<test color1="color1" updateFn="updateFn()"></test>

write:

<test color1="color1" update-fn="updateFn()"></test>

This is angular's way to tell the difference between directive attributes (such as update-fn function) and functions.

How to export data to an excel file using PHPExcel

Try the below complete example for the same

<?php
  $objPHPExcel = new PHPExcel();
  $query1 = "SELECT * FROM employee";
  $exec1 = mysql_query($query1) or die ("Error in Query1".mysql_error());
  $serialnumber=0;
  //Set header with temp array
  $tmparray =array("Sr.Number","Employee Login","Employee Name");
  //take new main array and set header array in it.
  $sheet =array($tmparray);

  while ($res1 = mysql_fetch_array($exec1))
  {
    $tmparray =array();
    $serialnumber = $serialnumber + 1;
    array_push($tmparray,$serialnumber);
    $employeelogin = $res1['employeelogin'];
    array_push($tmparray,$employeelogin);
    $employeename = $res1['employeename'];
    array_push($tmparray,$employeename);   
    array_push($sheet,$tmparray);
  }
   header('Content-type: application/vnd.ms-excel');
   header('Content-Disposition: attachment; filename="name.xlsx"');
  $worksheet = $objPHPExcel->getActiveSheet();
  foreach($sheet as $row => $columns) {
    foreach($columns as $column => $data) {
        $worksheet->setCellValueByColumnAndRow($column, $row + 1, $data);
    }
  }

  //make first row bold
  $objPHPExcel->getActiveSheet()->getStyle("A1:I1")->getFont()->setBold(true);
  $objPHPExcel->setActiveSheetIndex(0);
  $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
  $objWriter->save(str_replace('.php', '.xlsx', __FILE__));
?>

How do I get to IIS Manager?

You need to make sure the IIS Management Console is installed.

Unable to resolve dependency for ':app@debug/compileClasspath': Could not resolve com.android.support:appcompat-v7:26.1.0

Adding this in project gradle worked for me

allprojects {
 repositories {
     jcenter()
     maven {
         url "https://maven.google.com" // specifically this worked 
     }
 }}

Twitter - share button, but with image

Look into twitter cards.

The trick is not in the button but rather the page you are sharing. Twitter Cards pull the image from the meta tags similar to facebook sharing.

Example:

<meta name="twitter:card" content="summary_large_image">
<meta name="twitter:site" content="@site_username">
<meta name="twitter:title" content="Top 10 Things Ever">
<meta name="twitter:description" content="Up than 200 characters.">
<meta name="twitter:creator" content="@creator_username">
<meta name="twitter:image" content="http://placekitten.com/250/250">
<meta name="twitter:domain" content="YourDomain.com">

In SQL how to compare date values?

You could add the time component

WHERE mydate<='2008-11-25 23:59:59'

but that might fail on DST switchover dates if mydate is '2008-11-25 24:59:59', so it's probably safest to grab everything before the next date:

WHERE mydate < '2008-11-26 00:00:00'

Scala best way of turning a Collection into a Map-by-key?

Another solution (might not work for all types)

import scala.collection.breakOut
val m:Map[P, T] = c.map(t => (t.getP, t))(breakOut)

this avoids the creation of the intermediary list, more info here: Scala 2.8 breakOut

keypress, ctrl+c (or some combo like that)

Simple way to do it in jQuery :

/* The elements we'll bind the shortcut keys to. */
var elements = "body, input, select, checkbox, textarea";

/* Bind the key short-cut 'Ctrl+S' to the save function. */
$(elements).bind ("keydown", "ctrl+space", function (e) {
    // Prevent the default operation.
    e.preventDefault ();
    // Stop processing if we're already doing something.
    console.log ("That's right , you pressed correct shortcut!");
});

Replace one character with another in Bash

Try this

 echo "hello world" | sed 's/ /./g' 

How to convert a file into a dictionary?

Simple Option

Most methods for storing a dictionary use JSON, Pickle, or line reading. Providing you're not editing the dictionary outside of Python, this simple method should suffice for even complex dictionaries. Although Pickle will be better for larger dictionaries.

x = {1:'a', 2:'b', 3:'c'}
f = 'file.txt'
print(x, file=open(f,'w'))    # file.txt >>> {1:'a', 2:'b', 3:'c'}
y = eval(open(f,'r').read())
print(x==y)                   # >>> True

How to get the current time in YYYY-MM-DD HH:MI:Sec.Millisecond format in Java?

tl;dr

Instant.now()
       .toString()

2016-05-06T23:24:25.694Z

ZonedDateTime
.now
( 
    ZoneId.of( "America/Montreal" ) 
)
.format(  DateTimeFormatter.ISO_LOCAL_DATE_TIME )
.replace( "T" , " " )

2016-05-06 19:24:25.694

java.time

In Java 8 and later, we have the java.time framework built into Java 8 and later. These new classes supplant the troublesome old java.util.Date/.Calendar classes. The new classes are inspired by the highly successful Joda-Time framework, intended as its successor, similar in concept but re-architected. Defined by JSR 310. Extended by the ThreeTen-Extra project. See the Tutorial.

Be aware that java.time is capable of nanosecond resolution (9 decimal places in fraction of second), versus the millisecond resolution (3 decimal places) of both java.util.Date & Joda-Time. So when formatting to display only 3 decimal places, you could be hiding data.

If you want to eliminate any microseconds or nanoseconds from your data, truncate.

Instant instant2 = instant.truncatedTo( ChronoUnit.MILLIS ) ;

The java.time classes use ISO 8601 format by default when parsing/generating strings. A Z at the end is short for Zulu, and means UTC.

An Instant represents a moment on the timeline in UTC with resolution of up to nanoseconds. Capturing the current moment in Java 8 is limited to milliseconds, with a new implementation in Java 9 capturing up to nanoseconds depending on your computer’s hardware clock’s abilities.

Instant instant = Instant.now (); // Current date-time in UTC.
String output = instant.toString ();

2016-05-06T23:24:25.694Z

Replace the T in the middle with a space, and the Z with nothing, to get your desired output.

String output = instant.toString ().replace ( "T" , " " ).replace( "Z" , "" ; // Replace 'T', delete 'Z'. I recommend leaving the `Z` or any other such [offset-from-UTC][7] or [time zone][7] indicator to make the meaning clear, but your choice of course.

2016-05-06 23:24:25.694

As you don't care about including the offset or time zone, make a "local" date-time unrelated to any particular locality.

String output = LocalDateTime.now ( ).toString ().replace ( "T", " " );

Joda-Time

The highly successful Joda-Time library was the inspiration for the java.time framework. Advisable to migrate to java.time when convenient.

The ISO 8601 format includes milliseconds, and is the default for the Joda-Time 2.4 library.

System.out.println( "Now: " + new DateTime ( DateTimeZone.UTC ) );

When run…

Now: 2013-11-26T20:25:12.014Z

Also, you can ask for the milliseconds fraction-of-a-second as a number, if needed:

int millisOfSecond = myDateTime.getMillisOfSecond ();

Reinitialize Slick js after successful ajax call

I was facing an issue where Slick carousel wasn't refreshing on new data, it was appending new slides to previous ones, I found an answer which solved my problem, it's very simple.

try unslick, then assign your new data which is being rendered inside slick carousel, and then initialize slick again. these were the steps for me:

jQuery('.class-or-#id').slick('unslick');
myData = my-new-data;
jQuery('.class-or-#id').slick({slick options});

Note: check slick website for syntax just in case. also make sure you are not using unslick before slick is even initialized, what that means is simply initialize (like this jquery('.my-class').slick({options}); the first ajax call and once it is initialized then follow above steps, you may wanna use if else

Execution failed for task ':app:processDebugResources' even with latest build tools

as a quick fix to this question, make sure your compile Sdk verion, your buildtoolsversion, your appcompat, and finally your support library are all running on the same sdk version, for further clarity take a look at the image i just uploaded. Cheers. Follow the red annotations and get rid of that trouble.

enter image description here

How to get input from user at runtime

you can try this too And it will work:

DECLARE
  a NUMBER;
  b NUMBER;
BEGIN
  a :=: a; --this will take input from user
  b :=: b;
  DBMS_OUTPUT.PUT_LINE('a = '|| a);
  DBMS_OUTPUT.PUT_LINE('b = '|| b);
END;

How to parse JSON response from Alamofire API in Swift?

Swift 5

class User: Decodable {

    var name: String
    var email: String
    var token: String

    enum CodingKeys: String, CodingKey {
        case name
        case email
        case token
    }

    public required init(from decoder: Decoder) throws {
        let container = try decoder.container(keyedBy: CodingKeys.self)
        self.name = try container.decode(String.self, forKey: .name)
        self.email = try container.decode(String.self, forKey: .email)
        self.token = try container.decode(String.self, forKey: .token)
    }
}

Alamofire API

    Alamofire.request("url.endpoint/path", method: .get, parameters: params, encoding: URLEncoding.queryString, headers: nil)
     .validate()
     .responseJSON { response in

        switch (response.result) {

            case .success( _):

            do {
                let users = try JSONDecoder().decode([User].self, from: response.data!)
                print(users)

            } catch let error as NSError {
                print("Failed to load: \(error.localizedDescription)")
            }

             case .failure(let error):
                print("Request error: \(error.localizedDescription)")
         }

What is the best way to trigger onchange event in react js

The Event type input did not work for me on <select> but changing it to change works

useEffect(() => {
    var event = new Event('change', { bubbles: true });
    selectRef.current.dispatchEvent(event); // ref to the select control
}, [props.items]);

Can Json.NET serialize / deserialize to / from a stream?

public static void Serialize(object value, Stream s)
{
    using (StreamWriter writer = new StreamWriter(s))
    using (JsonTextWriter jsonWriter = new JsonTextWriter(writer))
    {
        JsonSerializer ser = new JsonSerializer();
        ser.Serialize(jsonWriter, value);
        jsonWriter.Flush();
    }
}

public static T Deserialize<T>(Stream s)
{
    using (StreamReader reader = new StreamReader(s))
    using (JsonTextReader jsonReader = new JsonTextReader(reader))
    {
        JsonSerializer ser = new JsonSerializer();
        return ser.Deserialize<T>(jsonReader);
    }
}

Selenium WebDriver can't find element by link text

The problem might be in the rest of the html, the part that you didn't post.

With this example (I just closed the open tags):

<a class="item" ng-href="#/catalog/90d9650a36988e5d0136988f03ab000f/category/DATABASE_SERVERS/service/90cefc7a42b3d4df0142b52466810026" href="#/catalog/90d9650a36988e5d0136988f03ab000f/category/DATABASE_SERVERS/service/90cefc7a42b3d4df0142b52466810026">
<div class="col-lg-2 col-sm-3 col-xs-4 item-list-image">
<img ng-src="csa/images/library/Service_Design.png" src="csa/images/library/Service_Design.png">
</div>
<div class="col-lg-8 col-sm-9 col-xs-8">
<div class="col-xs-12">
    <p>
    <strong class="ng-binding">Smoke Sequential</strong>
    </p>
    </div>
</div>
</a>

I was able to find the element without trouble with:

driver.findElement(By.linkText("Smoke Sequential")).click();

If there is more text inside the element, you could try a find by partial link text:

driver.findElement(By.partialLinkText("Sequential")).click();

How can I create an Asynchronous function in Javascript?

Here is a function that takes in another function and outputs a version that runs async.

var async = function (func) {
  return function () {
    var args = arguments;
    setTimeout(function () {
      func.apply(this, args);
    }, 0);
  };
};

It is used as a simple way to make an async function:

var anyncFunction = async(function (callback) {
    doSomething();
    callback();
});

This is different from @fider's answer because the function itself has its own structure (no callback added on, it's already in the function) and also because it creates a new function that can be used.

CONVERT Image url to Base64

imageToBase64 = (URL) => {
    let image;
    image = new Image();
    image.crossOrigin = 'Anonymous';
    image.addEventListener('load', function() {
        let canvas = document.createElement('canvas');
        let context = canvas.getContext('2d');
        canvas.width = image.width;
        canvas.height = image.height;
        context.drawImage(image, 0, 0);
        try {
            localStorage.setItem('saved-image-example', canvas.toDataURL('image/png'));
        } catch (err) {
            console.error(err)
        }
    });
    image.src = URL;
};

imageToBase64('image URL')

How can my iphone app detect its own version number?

You can try using dictionary as:-

NSDictionary *infoDictionary = [[NSBundle mainBundle]infoDictionary];

NSString *buildVersion = infoDictionary[(NSString*)kCFBundleVersionKey];
NSString *bundleName = infoDictionary[(NSString *)kCFBundleNameKey]

Replace all non-alphanumeric characters in a string

Try:

s = filter(str.isalnum, s)

in Python3:

s = ''.join(filter(str.isalnum, s))

Edit: realized that the OP wants to replace non-chars with '*'. My answer does not fit

How to allocate aligned memory only using the standard library?

long add;   
mem = (void*)malloc(1024 +15);
add = (long)mem;
add = add - (add % 16);//align to 16 byte boundary
ptr = (whatever*)(add);

Spring Boot - Loading Initial Data

I created a library that facilitates initial/demo data loading in a Spring Boot application. You can find it at https://github.com/piotrpolak/spring-boot-data-fixtures

Once the data fixtures starter is on the classpath, it will automatically try to load DICTIONARY data upon application startup (this behavior can be controlled by properties) - all you need to do is to register a bean implementing DataFixture.

I find loading initial data by code superior to loading it using SQL scripts:

  • the logic of your fixtures lives close to your application logic/domain model and it is subject to refactoring as your domain evolves
  • you benefit from incremental demo data updates - imagine a QA environment with some user data (that needs not to be lost after application deploy) but at the same time you want to add data for the new features you developed

Example data fixture:

/**
 * You can have as many fixture classes as you want.
 * @Order annotation is respected for the fixtures belonging to the same set.
 * You can make your demo database to be incrementally updated with fresh data
 * each time the application is redeployed - all you need to do is to write
 * a good condition in `canBeLoaded()` method.
 */
@Component
public class InitialDataFixture implements DataFixture {

    private final LanguageRepository languageRepository;

    // ...

    @Override
    public DataFixtureSet getSet() {
      return DataFixtureSet.DICTIONARY;
    }

    /**
     * We want to make sure the fixture is applied once and once only.
     * A more sophisticated condition can be used to create incremental demo data
     * over time without the need to reset the QA database (for example).
     */
    @Override
    public boolean canBeLoaded() {
      return languageRepository.size() == 0;
    }

    /**
     * The actual application of the fixture.
     * Assuming that data fixtures are registered as beans, this method can call
     * other services and/or repositories.
     */
    @Override
    public void load() {
      languageRepository.saveAll(Arrays.asList(
          new Language("en-US"), new Language("pl-PL")));
    }
}

The concept is inspired by the Symfony Doctrine Data Fixtures bundle.

Dynamically create Bootstrap alerts box through JavaScript

Found this today, made a few tweaks and combined the features of the other answers while updating it to bootstrap 3.x. NB: This answer requires jQuery.

In html:

<div id="form_errors" class="alert alert-danger fade in" style="display:none">

In JS:

<script>
//http://stackoverflow.com/questions/10082330/dynamically-create-bootstrap-alerts-box-through-javascript
function bootstrap_alert(elem, message, timeout) {
  $(elem).show().html('<div class="alert"><button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button><span>'+message+'</span></div>');

  if (timeout || timeout === 0) {
    setTimeout(function() { 
      $(elem).alert('close');
    }, timeout);    
  }
};
</script>?

Then you can invoke this either as:

bootstrap_alert('#form_errors', 'This message will fade out in 1 second', 1000)
bootstrap_alert('#form_errors', 'User must dismiss this message manually')

How do I check for vowels in JavaScript?

Lots of answers available, speed is irrelevant for such small functions unless you are calling them a few hundred thousand times in a short period of time. For me, a regular expression is best, but keep it in a closure so you don't build it every time:

Simple version:

function vowelTest(s) {
  return (/^[aeiou]$/i).test(s);
}

More efficient version:

var vowelTest = (function() {
  var re = /^[aeiou]$/i;
  return function(s) {
    return re.test(s);
  }
})();

Returns true if s is a single vowel (upper or lower case) and false for everything else.

Get width/height of SVG element

From Firefox 33 onwards you can call getBoundingClientRect() and it will work normally, i.e. in the question above it will return 300 x 100.

Firefox 33 will be released on 14th October 2014 but the fix is already in Firefox nightlies if you want to try it out.

Define css class in django Forms

You could also use Django Crispy Forms, it's a great tool to define forms in case you'd like to use some CSS framework like Bootstrap or Foundation. And it's easy to specify classes for your form fields there.

Your form class would like this then:

from django import forms

from crispy_forms.helper import FormHelper
from crispy_forms.layout import Layout, Div, Submit, Field
from crispy_forms.bootstrap import FormActions

class SampleClass(forms.Form):
    name = forms.CharField(max_length=30)
    age = forms.IntegerField()
    django_hacker = forms.BooleanField(required=False)

    helper = FormHelper()
    helper.form_class = 'your-form-class'
    helper.layout = Layout(
        Field('name', css_class='name-class'),
        Field('age', css_class='age-class'),
        Field('django_hacker', css-class='hacker-class'),
        FormActions(
            Submit('save_changes', 'Save changes'),
        )
    )

git pull from master into the development branch

The steps you listed will work, but there's a longer way that gives you more options:

git checkout dmgr2      # gets you "on branch dmgr2"
git fetch origin        # gets you up to date with origin
git merge origin/master

The fetch command can be done at any point before the merge, i.e., you can swap the order of the fetch and the checkout, because fetch just goes over to the named remote (origin) and says to it: "gimme everything you have that I don't", i.e., all commits on all branches. They get copied to your repository, but named origin/branch for any branch named branch on the remote.

At this point you can use any viewer (git log, gitk, etc) to see "what they have" that you don't, and vice versa. Sometimes this is only useful for Warm Fuzzy Feelings ("ah, yes, that is in fact what I want") and sometimes it is useful for changing strategies entirely ("whoa, I don't want THAT stuff yet").

Finally, the merge command takes the given commit, which you can name as origin/master, and does whatever it takes to bring in that commit and its ancestors, to whatever branch you are on when you run the merge. You can insert --no-ff or --ff-only to prevent a fast-forward, or merge only if the result is a fast-forward, if you like.

When you use the sequence:

git checkout dmgr2
git pull origin master

the pull command instructs git to run git fetch, and then the moral equivalent of git merge origin/master. So this is almost the same as doing the two steps by hand, but there are some subtle differences that probably are not too concerning to you. (In particular the fetch step run by pull brings over only origin/master, and it does not update the ref in your repo:1 any new commits winds up referred-to only by the special FETCH_HEAD reference.)

If you use the more-explicit git fetch origin (then optionally look around) and then git merge origin/master sequence, you can also bring your own local master up to date with the remote, with only one fetch run across the network:

git fetch origin
git checkout master
git merge --ff-only origin/master
git checkout dmgr2
git merge --no-ff origin/master

for instance.


1This second part has been changed—I say "fixed"—in git 1.8.4, which now updates "remote branch" references opportunistically. (It was, as the release notes say, a deliberate design decision to skip the update, but it turns out that more people prefer that git update it. If you want the old remote-branch SHA-1, it defaults to being saved in, and thus recoverable from, the reflog. This also enables a new git 1.9/2.0 feature for finding upstream rebases.)

Best way to make WPF ListView/GridView sort on column-header clicking?

I use MVVM, so I created some attached properties of my own, using Thomas's as a reference. It does sorting on one column at a time when you click on the header, toggling between Ascending and Descending. It sorts from the very beginning using the first column. And it shows Win7/8 style glyphs.

Normally, all you have to do is set the main property to true (but you have to explicitly declare the GridViewColumnHeaders):

<Window xmlns:local="clr-namespace:MyProjectNamespace">
  <Grid>
    <ListView local:App.EnableGridViewSort="True" ItemsSource="{Binding LVItems}">
      <ListView.View>
        <GridView>
          <GridViewColumn DisplayMemberBinding="{Binding Property1}">
            <GridViewColumnHeader Content="Prop 1" />
          </GridViewColumn>
          <GridViewColumn DisplayMemberBinding="{Binding Property2}">
            <GridViewColumnHeader Content="Prop 2" />
          </GridViewColumn>
        </GridView>
      </ListView.View>
    </ListView>
  </Grid>
<Window>

If you want to sort on a different property than the display, than you have to declare that:

<GridViewColumn DisplayMemberBinding="{Binding Property3}"
                local:App.GridViewSortPropertyName="Property4">
    <GridViewColumnHeader Content="Prop 3" />
</GridViewColumn>

Here's the code for the attached properties, I like to be lazy and put them in the provided App.xaml.cs:

using System;
using System.ComponentModel;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data.
using System.Windows.Media;
using System.Windows.Media.Media3D;

namespace MyProjectNamespace
{
  public partial class App : Application
  {
      #region GridViewSort
      public static DependencyProperty GridViewSortPropertyNameProperty =
          DependencyProperty.RegisterAttached(
              "GridViewSortPropertyName", 
              typeof(string), 
              typeof(App), 
              new UIPropertyMetadata(null)
          );

      public static string GetGridViewSortPropertyName(GridViewColumn gvc)
      {
          return (string)gvc.GetValue(GridViewSortPropertyNameProperty);
      }

      public static void SetGridViewSortPropertyName(GridViewColumn gvc, string n)
      {
          gvc.SetValue(GridViewSortPropertyNameProperty, n);
      }

      public static DependencyProperty CurrentSortColumnProperty =
          DependencyProperty.RegisterAttached(
              "CurrentSortColumn", 
              typeof(GridViewColumn), 
              typeof(App), 
              new UIPropertyMetadata(
                  null, 
                  new PropertyChangedCallback(CurrentSortColumnChanged)
              )
          );

      public static GridViewColumn GetCurrentSortColumn(GridView gv)
      {
          return (GridViewColumn)gv.GetValue(CurrentSortColumnProperty);
      }

      public static void SetCurrentSortColumn(GridView gv, GridViewColumn value)
      {
          gv.SetValue(CurrentSortColumnProperty, value);
      }

      public static void CurrentSortColumnChanged(
          object sender, DependencyPropertyChangedEventArgs e)
      {
          GridViewColumn gvcOld = e.OldValue as GridViewColumn;
          if (gvcOld != null)
          {
              CurrentSortColumnSetGlyph(gvcOld, null);
          }
      }

      public static void CurrentSortColumnSetGlyph(GridViewColumn gvc, ListView lv)
      {
          ListSortDirection lsd;
          Brush brush;
          if (lv == null)
          {
              lsd = ListSortDirection.Ascending;
              brush = Brushes.Transparent;
          }
          else
          {
              SortDescriptionCollection sdc = lv.Items.SortDescriptions;
              if (sdc == null || sdc.Count < 1) return;
              lsd = sdc[0].Direction;
              brush = Brushes.Gray;
          }

          FrameworkElementFactory fefGlyph = 
              new FrameworkElementFactory(typeof(Path));
          fefGlyph.Name = "arrow";
          fefGlyph.SetValue(Path.StrokeThicknessProperty, 1.0);
          fefGlyph.SetValue(Path.FillProperty, brush);
          fefGlyph.SetValue(StackPanel.HorizontalAlignmentProperty, 
              HorizontalAlignment.Center);

          int s = 4;
          if (lsd == ListSortDirection.Ascending)
          {
              PathFigure pf = new PathFigure();
              pf.IsClosed = true;
              pf.StartPoint = new Point(0, s);
              pf.Segments.Add(new LineSegment(new Point(s * 2, s), false));
              pf.Segments.Add(new LineSegment(new Point(s, 0), false));

              PathGeometry pg = new PathGeometry();
              pg.Figures.Add(pf);

              fefGlyph.SetValue(Path.DataProperty, pg);
          }
          else
          {
              PathFigure pf = new PathFigure();
              pf.IsClosed = true;
              pf.StartPoint = new Point(0, 0);
              pf.Segments.Add(new LineSegment(new Point(s, s), false));
              pf.Segments.Add(new LineSegment(new Point(s * 2, 0), false));

              PathGeometry pg = new PathGeometry();
              pg.Figures.Add(pf);

              fefGlyph.SetValue(Path.DataProperty, pg);
          }

          FrameworkElementFactory fefTextBlock = 
              new FrameworkElementFactory(typeof(TextBlock));
          fefTextBlock.SetValue(TextBlock.HorizontalAlignmentProperty,
              HorizontalAlignment.Center);
          fefTextBlock.SetValue(TextBlock.TextProperty, new Binding());

          FrameworkElementFactory fefDockPanel = 
              new FrameworkElementFactory(typeof(StackPanel));
          fefDockPanel.SetValue(StackPanel.OrientationProperty,
              Orientation.Vertical);
          fefDockPanel.AppendChild(fefGlyph);
          fefDockPanel.AppendChild(fefTextBlock);

          DataTemplate dt = new DataTemplate(typeof(GridViewColumn));
          dt.VisualTree = fefDockPanel;

          gvc.HeaderTemplate = dt;
      }

      public static DependencyProperty EnableGridViewSortProperty =
          DependencyProperty.RegisterAttached(
              "EnableGridViewSort", 
              typeof(bool), 
              typeof(App), 
              new UIPropertyMetadata(
                  false, 
                  new PropertyChangedCallback(EnableGridViewSortChanged)
              )
          );

      public static bool GetEnableGridViewSort(ListView lv)
      {
          return (bool)lv.GetValue(EnableGridViewSortProperty);
      }

      public static void SetEnableGridViewSort(ListView lv, bool value)
      {
          lv.SetValue(EnableGridViewSortProperty, value);
      }

      public static void EnableGridViewSortChanged(
          object sender, DependencyPropertyChangedEventArgs e)
      {
          ListView lv = sender as ListView;
          if (lv == null) return;

          if (!(e.NewValue is bool)) return;
          bool enableGridViewSort = (bool)e.NewValue;

          if (enableGridViewSort)
          {
              lv.AddHandler(
                  GridViewColumnHeader.ClickEvent,
                  new RoutedEventHandler(EnableGridViewSortGVHClicked)
              );
              if (lv.View == null)
              {
                  lv.Loaded += new RoutedEventHandler(EnableGridViewSortLVLoaded);
              }
              else
              {
                  EnableGridViewSortLVInitialize(lv);
              }
          }
          else
          {
              lv.RemoveHandler(
                  GridViewColumnHeader.ClickEvent,
                  new RoutedEventHandler(EnableGridViewSortGVHClicked)
              );
          }
      }

      public static void EnableGridViewSortLVLoaded(object sender, RoutedEventArgs e)
      {
          ListView lv = e.Source as ListView;
          EnableGridViewSortLVInitialize(lv);
          lv.Loaded -= new RoutedEventHandler(EnableGridViewSortLVLoaded);
      }

      public static void EnableGridViewSortLVInitialize(ListView lv)
      {
          GridView gv = lv.View as GridView;
          if (gv == null) return;

          bool first = true;
          foreach (GridViewColumn gvc in gv.Columns)
          {
              if (first)
              {
                  EnableGridViewSortApplySort(lv, gv, gvc);
                  first = false;
              }
              else
              {
                  CurrentSortColumnSetGlyph(gvc, null);
              }
          }
      }

      public static void EnableGridViewSortGVHClicked(
          object sender, RoutedEventArgs e)
      {
          GridViewColumnHeader gvch = e.OriginalSource as GridViewColumnHeader;
          if (gvch == null) return;
          GridViewColumn gvc = gvch.Column;
          if(gvc == null) return;            
          ListView lv = VisualUpwardSearch<ListView>(gvch);
          if (lv == null) return;
          GridView gv = lv.View as GridView;
          if (gv == null) return;

          EnableGridViewSortApplySort(lv, gv, gvc);
      }

      public static void EnableGridViewSortApplySort(
          ListView lv, GridView gv, GridViewColumn gvc)
      {
          bool isEnabled = GetEnableGridViewSort(lv);
          if (!isEnabled) return;

          string propertyName = GetGridViewSortPropertyName(gvc);
          if (string.IsNullOrEmpty(propertyName))
          {
              Binding b = gvc.DisplayMemberBinding as Binding;
              if (b != null && b.Path != null)
              {
                  propertyName = b.Path.Path;
              }

              if (string.IsNullOrEmpty(propertyName)) return;
          }

          ApplySort(lv.Items, propertyName);
          SetCurrentSortColumn(gv, gvc);
          CurrentSortColumnSetGlyph(gvc, lv);
      }

      public static void ApplySort(ICollectionView view, string propertyName)
      {
          if (string.IsNullOrEmpty(propertyName)) return;

          ListSortDirection lsd = ListSortDirection.Ascending;
          if (view.SortDescriptions.Count > 0)
          {
              SortDescription sd = view.SortDescriptions[0];
              if (sd.PropertyName.Equals(propertyName))
              {
                  if (sd.Direction == ListSortDirection.Ascending)
                  {
                      lsd = ListSortDirection.Descending;
                  }
                  else
                  {
                      lsd = ListSortDirection.Ascending;
                  }
              }
              view.SortDescriptions.Clear();
          }

          view.SortDescriptions.Add(new SortDescription(propertyName, lsd));
      }
      #endregion

      public static T VisualUpwardSearch<T>(DependencyObject source) 
          where T : DependencyObject
      {
          return VisualUpwardSearch(source, x => x is T) as T;
      }

      public static DependencyObject VisualUpwardSearch(
                          DependencyObject source, Predicate<DependencyObject> match)
      {
          DependencyObject returnVal = source;

          while (returnVal != null && !match(returnVal))
          {
              DependencyObject tempReturnVal = null;
              if (returnVal is Visual || returnVal is Visual3D)
              {
                  tempReturnVal = VisualTreeHelper.GetParent(returnVal);
              }
              if (tempReturnVal == null)
              {
                  returnVal = LogicalTreeHelper.GetParent(returnVal);
              }
              else
              {
                  returnVal = tempReturnVal;
              }
          }

          return returnVal;
      }
  }
}

How to add element in Python to the end of list using list.insert?

You'll have to pass the new ordinal position to insert using len in this case:

In [62]:

a=[1,2,3,4]
a.insert(len(a),5)
a
Out[62]:
[1, 2, 3, 4, 5]

Normal arguments vs. keyword arguments

There is one last language feature where the distinction is important. Consider the following function:

def foo(*positional, **keywords):
    print "Positional:", positional
    print "Keywords:", keywords

The *positional argument will store all of the positional arguments passed to foo(), with no limit to how many you can provide.

>>> foo('one', 'two', 'three')
Positional: ('one', 'two', 'three')
Keywords: {}

The **keywords argument will store any keyword arguments:

>>> foo(a='one', b='two', c='three')
Positional: ()
Keywords: {'a': 'one', 'c': 'three', 'b': 'two'}

And of course, you can use both at the same time:

>>> foo('one','two',c='three',d='four')
Positional: ('one', 'two')
Keywords: {'c': 'three', 'd': 'four'}

These features are rarely used, but occasionally they are very useful, and it's important to know which arguments are positional or keywords.

How can I execute Shell script in Jenkinsfile?

There's the Managed Script Plugin which provides an easy way of managing user scripts. It also adds a build step action which allows you to select which user script to execute.

Calling the base constructor in C#

public class MyExceptionClass : Exception
{
    public MyExceptionClass(string message,
      Exception innerException): base(message, innerException)
    {
        //other stuff here
    }
}

You can pass inner exception to one of the constructors.

HashMap: One Key, multiple Values

Thinking about a Map with 2 keys immediately compelled me to use a user-defined key, and that would probably be a Class. Following is the key Class:

public class MapKey {
    private Object key1;
    private Object key2;

    public Object getKey1() {
        return key1;
    }

    public void setKey1(Object key1) {
        this.key1 = key1;
    }

    public Object getKey2() {
        return key2;
    }

    public void setKey2(Object key2) {
        this.key2 = key2;
    }
}


// Create first map entry with key <A,B>.
        MapKey mapKey1 = new MapKey();
        mapKey1.setKey1("A");
        mapKey1.setKey2("B");

Getting data-* attribute for onclick event for an html element

I simply use this jQuery trick:

$("a:focus").attr('data-id');

It gets the focused a element and gets the data-id attribute from it.

Get the string value from List<String> through loop for display

pst = con.createStatement(); ResultSet resultSet= pst.executeQuery(query);

     String str1 = "<table>";
     int i = 1;
    while(resultSet.next()) {
             str1+= "</tr><td>"+i+"</td>"+
             "<td>"+resultSet.getString("first_name")+"</td>"+
             "<td>"+resultSet.getString("last_name")+"</td>"+
             "<td>"+resultSet.getString("email_id")+"</td>"+
             "<td>"+resultSet.getString("dob") +"</td>"+

             "</tr>";
        i++;

    }
        str1 =str1+"<table>";

    model.addAttribute("list",str1);

    return "userlist";  //Sending to views .jsp