Programs & Examples On #Camelcasing

Camel case is a language-independent naming convention in which an identifier name will start with a lowercase letter and each additional word within the name will start uppercase, such as customerName, printInvoice, etc.

How can I return camelCase JSON serialized by JSON.NET from ASP.NET MVC controller methods?

Add Json NamingStrategy property to your class definition.

_x000D_
_x000D_
[JsonObject(NamingStrategyType = typeof(CamelCaseNamingStrategy))]
public class Person
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
}
_x000D_
_x000D_
_x000D_

Elegant Python function to convert CamelCase to snake_case?

Take a look at the excellent Schematics lib

https://github.com/schematics/schematics

It allows you to created typed data structures that can serialize/deserialize from python to Javascript flavour, eg:

class MapPrice(Model):
    price_before_vat = DecimalType(serialized_name='priceBeforeVat')
    vat_rate = DecimalType(serialized_name='vatRate')
    vat = DecimalType()
    total_price = DecimalType(serialized_name='totalPrice')

Converting any string into camel case

EDIT: Now working in IE8 without changes.

EDIT: I was in the minority about what camelCase actually is (Leading character lowercase vs. uppercase.). The community at large believes a leading lowercase is camel case and a leading capital is pascal case. I have created two functions that use regex patterns only. :) So we use a unified vocabulary I have changed my stance to match the majority.


All I believe you need is a single regex in either case:

var camel = " THIS is camel case "
camel = $.trim(camel)
    .replace(/[^A-Za-z]/g,' ') /* clean up non-letter characters */
    .replace(/(.)/g, function(a, l) { return l.toLowerCase(); })
    .replace(/(\s.)/g, function(a, l) { return l.toUpperCase(); })
    .replace(/[^A-Za-z\u00C0-\u00ff]/g,'');
// Returns "thisIsCamelCase"

or

var pascal = " this IS pascal case "
pascal = $.trim(pascal)
  .replace(/[^A-Za-z]/g,' ') /* clean up non-letter characters */
  .replace(/(.)/g, function(a, l) { return l.toLowerCase(); })
  .replace(/(^.|\s.)/g, function(a, l) { return l.toUpperCase(); })
  .replace(/[^A-Za-z\u00C0-\u00ff]/g,'');
// Returns "ThisIsPascalCase"

In functions: You will notice that in these functions the replace is swapping any non a-z with a space vs an empty string. This is to create word boundaries for capitalization. "hello-MY#world" -> "HelloMyWorld"

// remove \u00C0-\u00ff] if you do not want the extended letters like é
function toCamelCase(str) {
    var retVal = '';

    retVal = $.trim(str)
      .replace(/[^A-Za-z]/g, ' ') /* clean up non-letter characters */
      .replace(/(.)/g, function (a, l) { return l.toLowerCase(); })
      .replace(/(\s.)/g, function (a, l) { return l.toUpperCase(); })
      .replace(/[^A-Za-z\u00C0-\u00ff]/g, '');

    return retVal
}

function toPascalCase(str) {
    var retVal = '';

    retVal = $.trim(str)
      .replace(/[^A-Za-z]/g, ' ') /* clean up non-letter characters */
      .replace(/(.)/g, function (a, l) { return l.toLowerCase(); })
      .replace(/(^.|\s.)/g, function (a, l) { return l.toUpperCase(); })
      .replace(/[^A-Za-z\u00C0-\u00ff]/g, '');

    return retVal
}

Notes:

  • I left A-Za-z vs adding the case insensitivity flag (i) to the pattern (/[^A-Z]/ig) for readability.
  • This works in IE8 (srsly, who uses IE8 anymore.) Using the (F12) dev tools I have tested in IE11, IE10, IE9, IE8, IE7 and IE5. Works in all document modes.
  • This will correctly case the first letter of strings starting with or without whitespace.

Enjoy

JSON Naming Convention (snake_case, camelCase or PascalCase)

I think that there isn't a official naming convention to JSON, but you can follow some industry leaders to see how it is working.

Google, which is one of the biggest IT company of the world, has a JSON style guide: https://google.github.io/styleguide/jsoncstyleguide.xml

Taking advantage, you can find other styles guide, which Google defines, here: https://github.com/google/styleguide

Convert a String to Modified Camel Case in Java or Title Case as is otherwise called

You can easily write the method to do that :

  public static String toCamelCase(final String init) {
    if (init == null)
        return null;

    final StringBuilder ret = new StringBuilder(init.length());

    for (final String word : init.split(" ")) {
        if (!word.isEmpty()) {
            ret.append(Character.toUpperCase(word.charAt(0)));
            ret.append(word.substring(1).toLowerCase());
        }
        if (!(ret.length() == init.length()))
            ret.append(" ");
    }

    return ret.toString();
}

How can I change the user on Git Bash?

For Mac Users

I am using Mac and I was facing same problem while I was trying to push a project from Android Studio. The reason for that other user had previously logged into Github and his credentials were saved in Keychain Access.

You need to remove those credentials from Keychain Access and then try to push.

Hope it help to Mac users.

number of values in a list greater than a certain number

If you are using NumPy (as in ludaavic's answer), for large arrays you'll probably want to use NumPy's sum function rather than Python's builtin sum for a significant speedup -- e.g., a >1000x speedup for 10 million element arrays on my laptop:

>>> import numpy as np
>>> ten_million = 10 * 1000 * 1000
>>> x, y = (np.random.randn(ten_million) for _ in range(2))
>>> %timeit sum(x > y)  # time Python builtin sum function
1 loops, best of 3: 24.3 s per loop
>>> %timeit (x > y).sum()  # wow, that was really slow! time NumPy sum method
10 loops, best of 3: 18.7 ms per loop
>>> %timeit np.sum(x > y)  # time NumPy sum function
10 loops, best of 3: 18.8 ms per loop

(above uses IPython's %timeit "magic" for timing)

SQL "between" not inclusive

cast(created_at as date)

That will work only in 2008 and newer versions of SQL Server

If you are using older version then use

convert(varchar, created_at, 101)

Replace String in all files in Eclipse

Strange but it is a two step task:

  1. Search what you want
  2. In the search tab right click and select replace , or replace all:

A demo at:

http://www.avajava.com/tutorials/lessons/how-do-i-do-a-find-and-replace-in-multiple-files-in-eclipse.html

Why is this jQuery click function not working?

Try adding $(document).ready(function(){ to the beginning of your script, and then });. Also, does the div have the id in it properly, i.e., as an id, not a class, etc.?

How to add the JDBC mysql driver to an Eclipse project?

if you are getting this exception again and again then download my-sql connector and paste in tomcat/WEB-INF/lib folder...note that some times WEB-INF folder does not contains lib folder, at that time manually create lib folder and paste mysql connector in that folder..definitely this will work.if still you got problem then check that your jdk must match your system. i.e if your system is 64 bit then jdk must be 64 bit

How can I check if an argument is defined when starting/calling a batch file?

IF "%1"=="" will fail, all versions of this will fail under certain poison character conditions. Only IF DEFINED or IF NOT DEFINED are safe

Convert json to a C# array?

just take the string and use the JavaScriptSerializer to deserialize it into a native object. For example, having this json:

string json = "[{Name:'John Simith',Age:35},{Name:'Pablo Perez',Age:34}]"; 

You'd need to create a C# class called, for example, Person defined as so:

public class Person
{
 public int Age {get;set;}
 public string Name {get;set;}
}

You can now deserialize the JSON string into an array of Person by doing:

JavaScriptSerializer js = new JavaScriptSerializer();
Person [] persons =  js.Deserialize<Person[]>(json);

Here's a link to JavaScriptSerializer documentation.

Note: my code above was not tested but that's the idea Tested it. Unless you are doing something "exotic", you should be fine using the JavascriptSerializer.

How do you add multi-line text to a UIButton?

Roll your own button class. It's by far the best solution in the long run. UIButton and other UIKit classes are very restrictive in how you can customize them.

Is there a way to link someone to a YouTube Video in HD 1080p quality?

To link to a YouTube video so it plays in HD by default, use the following URL:

https://www.youtube.com/v/VIDEOID?version=3&vq=hd1080

Change VIDEOID to the YouTube video ID that you want to link to. When someone follows the link, it will display the highest-resolution available (up to 1080p) in full-screen mode. Unfortunately, vq=hd1080 does not work on the normal YouTube site (with comments and related videos).

Solve Cross Origin Resource Sharing with Flask

I struggled a lot with something similar. Try the following:

  1. Use some sort of browser plugin which can display the HTML headers.
  2. Enter the URL to your service, and view the returned header values.
  3. Make sure Access-Control-Allow-Origin is set to one and only one domain, which should be the request origin. Do not set Access-Control-Allow-Origin to *.

If this doesn't help, take a look at this article. It's on PHP, but it describes exactly which headers must be set to which values for CORS to work.

CORS That Works In IE, Firefox, Chrome And Safari

How can I determine if a .NET assembly was built for x86 or x64?

Another way to check the target platform of a .NET assembly is inspecting the assembly with .NET Reflector...

@#~#€~! I've just realized that the new version is not free! So, correction, if you have a free version of .NET reflector, you can use it to check the target platform.

Getting year in moment.js

The year() function just retrieves the year component of the underlying Date object, so it returns a number.

Calling format('YYYY') will invoke moment's string formatting functions, which will parse the format string supplied, and build a new string containing the appropriate data. Since you only are passing YYYY, then the result will be a string containing the year.

If all you need is the year, then use the year() function. It will be faster, as there is less work to do.

Do note that while years are the same in this regard, months are not! Calling format('M') will return months in the range 1-12. Calling month() will return months in the range 0-11. This is due to the same behavior of the underlying Date object.

Run a PHP file in a cron job using CPanel

I've had problems using /usr/bin/php on CPanel as it is compiled as a "cgi-fcgi" binary and not "cli". Try using /usr/local/bin/php or, as it is first in the path anyway, just use 'php' instead:

php /path/to/script.php

If you want to run the script as an executable, give it +x perms and use the following as the first line of the script:

#!/usr/bin/env php

How to extract one column of a csv file

You could use GNU Awk, see this article of the user guide. As an improvement to the solution presented in the article (in June 2015), the following gawk command allows double quotes inside double quoted fields; a double quote is marked by two consecutive double quotes ("") there. Furthermore, this allows empty fields, but even this can not handle multiline fields. The following example prints the 3rd column (via c=3) of textfile.csv:

#!/bin/bash
gawk -- '
BEGIN{
    FPAT="([^,\"]*)|(\"((\"\")*[^\"]*)*\")"
}
{
    if (substr($c, 1, 1) == "\"") {
        $c = substr($c, 2, length($c) - 2) # Get the text within the two quotes
        gsub("\"\"", "\"", $c)  # Normalize double quotes
    }
    print $c
}
' c=3 < <(dos2unix <textfile.csv)

Note the use of dos2unix to convert possible DOS style line breaks (CRLF i.e. "\r\n") and UTF-16 encoding (with byte order mark) to "\n" and UTF-8 (without byte order mark), respectively. Standard CSV files use CRLF as line break, see Wikipedia.

If the input may contain multiline fields, you can use the following script. Note the use of special string for separating records in output (since the default separator newline could occur within a record). Again, the following example prints the 3rd column (via c=3) of textfile.csv:

#!/bin/bash
gawk -- '
BEGIN{
    RS="\0" # Read the whole input file as one record;
    # assume there is no null character in input.
    FS="" # Suppose this setting eases internal splitting work.
    ORS="\n####\n" # Use a special output separator to show borders of a record.
}
{
    nof=patsplit($0, a, /([^,"\n]*)|("(("")*[^"]*)*")/, seps)
    field=0;
    for (i=1; i<=nof; i++){
        field++
        if (field==c) {
            if (substr(a[i], 1, 1) == "\"") {
                a[i] = substr(a[i], 2, length(a[i]) - 2) # Get the text within 
                # the two quotes.
                gsub(/""/, "\"", a[i])  # Normalize double quotes.
            }
            print a[i]
        }
        if (seps[i]!=",") field=0
    }
}
' c=3 < <(dos2unix <textfile.csv)

There is another approach to the problem. csvquote can output contents of a CSV file modified so that special characters within field are transformed so that usual Unix text processing tools can be used to select certain column. For example the following code outputs the third column:

csvquote textfile.csv | cut -d ',' -f 3 | csvquote -u

csvquote can be used to process arbitrary large files.

Git merge is not possible because I have unmerged files

Another potential cause for this (Intellij was involved in my case, not sure that mattered though): trying to merge in changes from a main branch into a branch off of a feature branch.

In other words, merging "main" into "current" in the following arrangement:

main
  |
  --feature
      |
      --current

I resolved all conflicts and GiT reported unmerged files and I was stuck until I merged from main into feature, then feature into current.

Detect user scroll down or scroll up in jQuery

To differentiate between scroll up/down in jQuery, you could use:

var mousewheelevt = (/Firefox/i.test(navigator.userAgent)) ? "DOMMouseScroll" : "mousewheel" //FF doesn't recognize mousewheel as of FF3.x
$('#yourDiv').bind(mousewheelevt, function(e){

    var evt = window.event || e //equalize event object     
    evt = evt.originalEvent ? evt.originalEvent : evt; //convert to originalEvent if possible               
    var delta = evt.detail ? evt.detail*(-40) : evt.wheelDelta //check for detail first, because it is used by Opera and FF

    if(delta > 0) {
        //scroll up
    }
    else{
        //scroll down
    }   
});

This method also works in divs that have overflow:hidden.

I successfully tested it in FireFox, IE and Chrome.

jQuery $.ajax(), $.post sending "OPTIONS" as REQUEST_METHOD in Firefox

I have posted a clear example of how to solve this if control the server code of the domain you are POSTing to. This answer is touched on in this thread, but this more clearly explains it IMO.

How do I send a cross-domain POST request via JavaScript?

Import data.sql MySQL Docker Container

Mount your sql-dump under/docker-entrypoint-initdb.d/yourdump.sql utilizing a volume mount

mysql:
  image: mysql:latest
  container_name: mysql-container
  ports:
    - 3306:3306
  volumes:
    - ./dump.sql:/docker-entrypoint-initdb.d/dump.sql
  environment:
    MYSQL_ROOT_PASSWORD: secret
    MYSQL_DATABASE: name_db
    MYSQL_USER: user
    MYSQL_PASSWORD: password

This will trigger an import of the sql-dump during the start of the container, see https://hub.docker.com/_/mysql/ under "Initializing a fresh instance"

EOFException - how to handle?

While reading from the file, your are not terminating your loop. So its read all the values and correctly throws EOFException on the next iteration of the read at line below:

 price = in.readDouble();

If you read the documentation, it says:

Throws:

EOFException - if this input stream reaches the end before reading eight bytes.

IOException - the stream has been closed and the contained input stream does not support reading after close, or another I/O error occurs.

Put a proper termination condition in your while loop to resolve the issue e.g. below:

     while(in.available() > 0)  <--- if there are still bytes to read

What can I use for good quality code coverage for C#/.NET?

I am not sure what the difference is with the retail NCover, but there is also an NCover project on SourceForge that is of course open source and free.

How to get position of a certain element in strings vector, to use it as an index in ints vector?

If you want an index, you can use std::find in combination with std::distance.

auto it = std::find(Names.begin(), Names.end(), old_name_);
if (it == Names.end())
{
  // name not in vector
} else
{
  auto index = std::distance(Names.begin(), it);
}

Two-way SSL clarification

What you call "Two-Way SSL" is usually called TLS/SSL with client certificate authentication.

In a "normal" TLS connection to example.com only the client verifies that it is indeed communicating with the server for example.com. The server doesn't know who the client is. If the server wants to authenticate the client the usual thing is to use passwords, so a client needs to send a user name and password to the server, but this happens inside the TLS connection as part of an inner protocol (e.g. HTTP) it's not part of the TLS protocol itself. The disadvantage is that you need a separate password for every site because you send the password to the server. So if you use the same password on for example PayPal and MyPonyForum then every time you log into MyPonyForum you send this password to the server of MyPonyForum so the operator of this server could intercept it and try it on PayPal and can issue payments in your name.

Client certificate authentication offers another way to authenticate the client in a TLS connection. In contrast to password login, client certificate authentication is specified as part of the TLS protocol. It works analogous to the way the client authenticates the server: The client generates a public private key pair and submits the public key to a trusted CA for signing. The CA returns a client certificate that can be used to authenticate the client. The client can now use the same certificate to authenticate to different servers (i.e. you could use the same certificate for PayPal and MyPonyForum without risking that it can be abused). The way it works is that after the server has sent its certificate it asks the client to provide a certificate too. Then some public key magic happens (if you want to know the details read RFC 5246) and now the client knows it communicates with the right server, the server knows it communicates with the right client and both have some common key material to encrypt and verify the connection.

The request was aborted: Could not create SSL/TLS secure channel

The solution to this, in .NET 4.5 is

ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;

If you don’t have .NET 4.5 then use

ServicePointManager.SecurityProtocol = (SecurityProtocolType)3072;

Equal sized table cells to fill the entire width of the containing table

Using table-layout: fixed as a property for table and width: calc(100%/3); for td (assuming there are 3 td's). With these two properties set, the table cells will be equal in size.

Refer to the demo.

var functionName = function() {} vs function functionName() {}

.

  1. Availability (scope) of the function

The following works because function add() is scoped to the nearest block:

_x000D_
_x000D_
try {
  console.log("Success: ", add(1, 1));
} catch(e) {
  console.log("ERROR: " + e);
}

function add(a, b){
  return a + b;
}
_x000D_
_x000D_
_x000D_

The following does not work because the variable is called before a function value is assigned to the variable add.

_x000D_
_x000D_
try {
  console.log("Success: ", add(1, 1));
} catch(e) {
  console.log("ERROR: " + e);
}

var add=function(a, b){
  return a + b;
}
_x000D_
_x000D_
_x000D_

The above code is identical in functionality to the code below. Note that explicitly assigning add = undefined is superfluous because simply doing var add; is the exact same as var add=undefined.

_x000D_
_x000D_
var add = undefined;

try {
  console.log("Success: ", add(1, 1));
} catch(e) {
  console.log("ERROR: " + e);
}

add = function(a, b){
  return a + b;
}
_x000D_
_x000D_
_x000D_

The following does not work because var add= begins an expression and causes the following function add() to be an expression instead of a block. Named functions are only visible to themselves and their surrounding block. As function add() is an expression here, it has no surrounding block, so it is only visible to itself.

_x000D_
_x000D_
try {
  console.log("Success: ", add(1, 1));
} catch(e) {
  console.log("ERROR: " + e);
}

var add=function add(a, b){
  return a + b;
}
_x000D_
_x000D_
_x000D_

  1. (function).name

The name of a function function thefuncname(){} is thefuncname when it is declared this way.

_x000D_
_x000D_
function foobar(a, b){}

console.log(foobar.name);
_x000D_
_x000D_
_x000D_

_x000D_
_x000D_
var a = function foobar(){};

console.log(a.name);
_x000D_
_x000D_
_x000D_

Otherwise, if a function is declared as function(){}, the function.name is the first variable used to store the function.

_x000D_
_x000D_
var a = function(){};
var b = (function(){ return function(){} });

console.log(a.name);
console.log(b.name);
_x000D_
_x000D_
_x000D_

If there are no variables set to the function, then the functions name is the empty string ("").

_x000D_
_x000D_
console.log((function(){}).name === "");
_x000D_
_x000D_
_x000D_

Lastly, while the variable the function is assigned to initially sets the name, successive variables set to the function do not change the name.

_x000D_
_x000D_
var a = function(){};
var b = a;
var c = b;

console.log(a.name);
console.log(b.name);
console.log(c.name);
_x000D_
_x000D_
_x000D_

  1. Performance

In Google's V8 and Firefox's Spidermonkey there might be a few microsecond JIST compilation difference, but ultimately the result is the exact same. To prove this, let's examine the efficiency of JSPerf at microbenchmarks by comparing the speed of two blank code snippets. The JSPerf tests are found here. And, the jsben.ch testsare found here. As you can see, there is a noticable difference when there should be none. If you are really a performance freak like me, then it might be more worth your while trying to reduce the number of variables and functions in the scope and especially eliminating polymorphism (such as using the same variable to store two different types).

  1. Variable Mutability

When you use the var keyword to declare a variable, you can then reassign a different value to the variable like so.

_x000D_
_x000D_
(function(){
    "use strict";
    var foobar = function(){}; // initial value
    try {
        foobar = "Hello World!"; // new value
        console.log("[no error]");
    } catch(error) {
        console.log("ERROR: " + error.message);
    }
    console.log(foobar, window.foobar);
})();
_x000D_
_x000D_
_x000D_

However, when we use the const-statement, the variable reference becomes immutable. This means that we cannot assign a new value to the variable. Please note, however, that this does not make the contents of the variable immutable: if you do const arr = [], then you can still do arr[10] = "example". Only doing something like arr = "new value" or arr = [] would throw an error as seen below.

_x000D_
_x000D_
(function(){
    "use strict";
    const foobar = function(){}; // initial value
    try {
        foobar = "Hello World!"; // new value
        console.log("[no error]");
    } catch(error) {
        console.log("ERROR: " + error.message);
    }
    console.log(foobar, window.foobar);
})();
_x000D_
_x000D_
_x000D_

Interestingly, if we declare the variable as function funcName(){}, then the immutability of the variable is the same as declaring it with var.

_x000D_
_x000D_
(function(){
    "use strict";
    function foobar(){}; // initial value
    try {
        foobar = "Hello World!"; // new value
        console.log("[no error]");
    } catch(error) {
        console.log("ERROR: " + error.message);
    }
    console.log(foobar, window.foobar);
})();
_x000D_
_x000D_
_x000D_

" "

The "nearest block" is the nearest "function," (including asynchronous functions, generator functions, and asynchronous generator functions). However, interestingly, a function functionName() {} behaves like a var functionName = function() {} when in a non-closure block to items outside said closure. Observe.

  • Normal var add=function(){}

_x000D_
_x000D_
try {
  // typeof will simply return "undefined" if the variable does not exist
  if (typeof add !== "undefined") {
    add(1, 1); // just to prove it
    console.log("Not a block");
  }else if(add===undefined){ // this throws an exception if add doesn't exist
    console.log('Behaves like var add=function(a,b){return a+b}');
  }
} catch(e) {
  console.log("Is a block");
}
var add=function(a, b){return a + b}
_x000D_
_x000D_
_x000D_

  • Normal function add(){}

_x000D_
_x000D_
try {
  // typeof will simply return "undefined" if the variable does not exist
  if (typeof add !== "undefined") {
    add(1, 1); // just to prove it
    console.log("Not a block");
  }else if(add===undefined){ // this throws an exception if add doesn't exist
    console.log('Behaves like var add=function(a,b){return a+b}')
  }
} catch(e) {
  console.log("Is a block");
}
function add(a, b){
  return a + b;
}
_x000D_
_x000D_
_x000D_

  • Function

_x000D_
_x000D_
try {
  // typeof will simply return "undefined" if the variable does not exist
  if (typeof add !== "undefined") {
    add(1, 1); // just to prove it
    console.log("Not a block");
  }else if(add===undefined){ // this throws an exception if add doesn't exist
    console.log('Behaves like var add=function(a,b){return a+b}')
  }
} catch(e) {
  console.log("Is a block");
}
(function () {
    function add(a, b){
      return a + b;
    }
})();
_x000D_
_x000D_
_x000D_

  • Statement (such as if, else, for, while, try/catch/finally, switch, do/while, with)

_x000D_
_x000D_
try {
  // typeof will simply return "undefined" if the variable does not exist
  if (typeof add !== "undefined") {
    add(1, 1); // just to prove it
    console.log("Not a block");
  }else if(add===undefined){ // this throws an exception if add doesn't exist
    console.log('Behaves like var add=function(a,b){return a+b}')
  }
} catch(e) {
  console.log("Is a block");
}
{
    function add(a, b){
      return a + b;
    }
}
_x000D_
_x000D_
_x000D_

  • Arrow Function with var add=function()

_x000D_
_x000D_
try {
  // typeof will simply return "undefined" if the variable does not exist
  if (typeof add !== "undefined") {
    add(1, 1); // just to prove it
    console.log("Not a block");
  }else if(add===undefined){ // this throws an exception if add doesn't exist
    console.log('Behaves like var add=function(a,b){return a+b}')
  }
} catch(e) {
  console.log("Is a block");
}
(() => {
    var add=function(a, b){
      return a + b;
    }
})();
_x000D_
_x000D_
_x000D_

  • Arrow Function With function add()

_x000D_
_x000D_
try {
  // typeof will simply return "undefined" if the variable does not exist
  if (typeof add !== "undefined") {
    add(1, 1); // just to prove it
    console.log("Not a block");
  }else if(add===undefined){ // this throws an exception if add doesn't exist
    console.log('Behaves like var add=function(a,b){return a+b}')
  }
} catch(e) {
  console.log("Is a block");
}
(() => {
    function add(a, b){
      return a + b;
    }
})();
_x000D_
_x000D_
_x000D_

How can I make a UITextField move up when the keyboard is present - on starting to edit?

Note: this answer assumes your textField is in a scrollView.

I prefer to deal with this using scrollContentInset and scrollContentOffset instead of messing with the frames of my view.

First let's listen for the keyboard notifications

//call this from viewWillAppear
-(void)addKeyboardNotifications
{
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWillShow:)
                                                 name:UIKeyboardWillShowNotification
                                               object:nil];

    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWillHide:)
                                                 name:UIKeyboardWillHideNotification
                                               object:nil];
}
//call this from viewWillDisappear
-(void)removeKeyboardNotifications{
    [[NSNotificationCenter default
    Center] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
}

Next step is to keep a property that represents the current first responder (UITextfield/ UITextVIew that currently has the keyboard).

We use the delegate methods to set this property. If you're using another component, you will need something similar.

Note that for textfield we set it in didBeginEditing and for textView in shouldBeginEditing. This is because textViewDidBeginEditing gets called after UIKeyboardWillShowNotification for some reason.

-(BOOL)textViewShouldBeginEditing:(UITextView * )textView{
    self.currentFirstResponder = textView;
    return YES;
}

-(void)textFieldDidBeginEditing:(UITextField *)textField{
    self.currentFirstResponder = textField;
}

Finally, here's the magic

- (void)keyboardWillShow:(NSNotification*)aNotification{
    NSDictionary* info = [aNotification userInfo];
    CGRect kbFrame = [[info objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue];


    /*if currentFirstResponder is overlayed by the keyboard, move it so it bottom ends where the keyboard begins*/
    if(self.currentFirstResponder){

        //keyboard origin in currentFirstResponderFrame
        CGPoint keyboardOrigin = [self.currentFirstResponder convertPoint:kbFrame.origin fromView:nil];

        float spaceBetweenFirstResponderAndKeyboard = abs(self.currentFirstResponder.frame.size.height-keyboardOrigin.y);

        //only scroll the scrollview if keyboard overlays the first responder
        if(spaceBetweenFirstResponderAndKeyboard>0){
            //if i call setContentOffset:animate:YES it behaves differently, not sure why
            [UIView animateWithDuration:0.25 animations:^{
                [self.scrollView setContentOffset:CGPointMake(0,self.scrollView.contentOffset.y+spaceBetweenFirstResponderAndKeyboard)];
            }];
        }
    }

    //set bottom inset to the keyboard height so you can still scroll the whole content

    UIEdgeInsets contentInsets = UIEdgeInsetsMake(0.0, 0.0, kbFrame.size.height, 0.0);
    _scrollView.contentInset = contentInsets;
    _scrollView.scrollIndicatorInsets = contentInsets;

}

- (void)keyboardWillHide:(NSNotification*)aNotification{
    UIEdgeInsets contentInsets = UIEdgeInsetsZero;
    _scrollView.contentInset = contentInsets;
    _scrollView.scrollIndicatorInsets = contentInsets;
}

did you register the component correctly? For recursive components, make sure to provide the "name" option

In my case (quasar and command quasar dev for testing), I just forgot to restart dev Quasar command.

It seemed to me that components was automatically loaded when any change was done. But in this case, I reused component in another page and I got this message.

Adding git branch on the Bash command prompt

At first, open your Bash Profile in your home directory. The easiest way to open & edit your bash_profile using your default editor.

For example, I open it using the VS Code using this command: code .bash_profile.

Then just paste the following codes to your Bash.

parse_git_branch() {
     git branch 2> /dev/null | sed -e '/^[^*]/d' -e 's/* \(.*\)/ (\1)/'
}

export PS1="\u@\h \W\[\033[32m\]\$(parse_git_branch)\[\033[00m\] $ "

The function

parse_git_branch()

will fetch the branch name & then through PS1 you can show it in your terminal.

Here,

\u = Username

@ = Static Text

\h = Computer Name

\w = Current Directory

$ = Static Text

You can change or remove these variables for more customization.


If you use Git for the first time in terminal or instantly after configuration, maybe sometimes you can not see the branch name.

If you get this problem, don't worry. In that case, just make a sample repository and commit it after some changes. When the commit command will execute once, the terminal will find git branch from then.


Screenshot: Git Branch in Terminal

How to know which is running in Jupyter notebook?

from platform import python_version

print(python_version())

This will give you the exact version of python running your script. eg output:

3.6.5

Why do I get AttributeError: 'NoneType' object has no attribute 'something'?

NoneType means that instead of an instance of whatever Class or Object you think you're working with, you've actually got None. That usually means that an assignment or function call up above failed or returned an unexpected result.

JavaScript style.display="none" or jQuery .hide() is more efficient?

Efficiency isn't going to matter for something like this in 99.999999% of situations. Do whatever is easier to read and or maintain.

In my apps I usually rely on classes to provide hiding and showing, for example .addClass('isHidden')/.removeClass('isHidden') which would allow me to animate things with CSS3 if I wanted to. It provides more flexibility.

How do you make a div follow as you scroll?

The post is old but I found a perfect CSS for the purpose and I want to share it.

A sticky element toggles between relative and fixed, depending on the scroll position. It is positioned relative until a given offset position is met in the viewport - then it "sticks" in place (like position:fixed).

    div.sticky {
        position: -webkit-sticky; /* Safari */
        position: sticky;
        top: 0;
        background-color: green;
        border: 2px solid #4CAF50;
    }

Source: https://www.w3schools.com/css/css_positioning.asp

How do you add an array to another array in Ruby and not end up with a multi-dimensional result?

You can just use the + operator!

irb(main):001:0> a = [1,2]
=> [1, 2]
irb(main):002:0> b = [3,4]
=> [3, 4]
irb(main):003:0> a + b
=> [1, 2, 3, 4]

You can read all about the array class here: http://ruby-doc.org/core/classes/Array.html

How to keep the console window open in Visual C++?

Put a breakpoint on the return line.

You are running it in the debugger, right?

Limit number of characters allowed in form input text field

The following code includes a counted...

_x000D_
_x000D_
var count = 1;_x000D_
_x000D_
do {_x000D_
    function count_down(obj, count){_x000D_
_x000D_
    let element = document.getElementById('count'+ count);_x000D_
_x000D_
    element.innerHTML = 80 - obj.value.length;_x000D_
_x000D_
    if(80 - obj.value.length < 5){_x000D_
        element.style.color = "firebrick";_x000D_
    }else{_x000D_
        element.style.color = "#333";_x000D_
    }_x000D_
}_x000D_
count++;_x000D_
} while (count < 20); 
_x000D_
.text-input {_x000D_
    padding: 8px 16px;_x000D_
    width: 50%;_x000D_
    margin-bottom: 5px;_x000D_
    margin-top: 10px;_x000D_
    font-size: 20px;_x000D_
    font-weight: 700;_x000D_
    font-family: Raleway;_x000D_
    border: 1px solid dodgerblue;_x000D_
  }
_x000D_
<p><input placeholder="Title" id="bike-input-title" onkeyup="count_down(this, 3)" maxlength="80"  class="text-input" name="bikeTitle" ></p>_x000D_
        <span id="count3" style="float: right; font-family: Raleway; font-size:20px; font-weight:600; margin-top:-5px;">80</span><br>
_x000D_
_x000D_
_x000D_

How to add "active" class to Html.ActionLink in ASP.NET MVC

Add '.ToString' to improve comparing on ASP.NET MVC

<ul class="nav navbar-nav">
<li class="@(ViewContext.RouteData.Values["Action"].ToString() == "Index" ? "active" : "")">@Html.ActionLink("Home", "Index", "Home")</li>
<li class="@(ViewContext.RouteData.Values["Action"].ToString() == "About" ? "active" : "")">@Html.ActionLink("About", "About", "Home")</li>
<li class="@(ViewContext.RouteData.Values["Action"].ToString() == "Contact" ? "active" : "")">@Html.ActionLink("Contact", "Contact", "Home")</li>

--

Syntax error on print with Python 3

It looks like you're using Python 3.0, in which print has turned into a callable function rather than a statement.

print('Hello world!')

How to bind DataTable to Datagrid

In cs file

DataTable employeeData = CreateDataTable();
gridEmployees.DataContext = employeeData.DefaultView;

In xaml file

<DataGrid Name="gridEmployees" ItemsSource="{Binding}">

Can an ASP.NET MVC controller return an Image?

I also encountered similar requirement,

So in my case I make a request to Controller with the image folder path, which in return sends back a ImageResult object.

Following code snippet illustrate the work:

var src = string.Format("/GenericGrid.mvc/DocumentPreviewImageLink?fullpath={0}&routingId={1}&siteCode={2}", fullFilePath, metaInfo.RoutingId, da.SiteCode);

                if (enlarged)
                    result = "<a class='thumbnail' href='#thumb'>" +
                        "<img src='" + src + "' height='66px' border='0' />" +
                        "<span><img src='" + src + "' /></span>" +
                        "</a>";
                else
                    result = "<span><img src='" + src + "' height='150px' border='0' /></span>";

And in the Controller from the the image path I produce the image and return it back to the caller

try
{
  var file = new FileInfo(fullpath);
  if (!file.Exists)
     return string.Empty;


  var image = new WebImage(fullpath);
  return new ImageResult(new MemoryStream(image.GetBytes()), "image/jpg");


}
catch(Exception ex)
{
  return "File Error : "+ex.ToString();
}

MongoDb query condition on comparing 2 fields

You can use $expr ( 3.6 mongo version operator ) to use aggregation functions in regular query.

Compare query operators vs aggregation comparison operators.

Regular Query:

db.T.find({$expr:{$gt:["$Grade1", "$Grade2"]}})

Aggregation Query:

db.T.aggregate({$match:{$expr:{$gt:["$Grade1", "$Grade2"]}}})

Copy data into another table

INSERT INTO table1 (col1, col2, col3)
SELECT column1, column2, column3
FROM table2                                        

How to Get a Layout Inflater Given a Context?

You can use the static from() method from the LayoutInflater class:

 LayoutInflater li = LayoutInflater.from(context);

How is a JavaScript hash map implemented?

Should you try this class Map:

_x000D_
_x000D_
var myMap = new Map();_x000D_
_x000D_
// setting the values_x000D_
myMap.set("1", 'value1');_x000D_
myMap.set("2", 'value2');_x000D_
myMap.set("3", 'value3');_x000D_
_x000D_
myMap.size; // 3_x000D_
_x000D_
// getting the values_x000D_
myMap.get("1");    // "value associated with "value1"_x000D_
myMap.get("2");       // "value associated with "value1"_x000D_
myMap.get("3");      // "value associated with "value3"
_x000D_
_x000D_
_x000D_

Notice: key and value can be any type.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map

VB.NET Connection string (Web.Config, App.Config)

Not clear where My_ConnectionString is coming from in your example, but try this

System.Configuration.ConfigurationManager.ConnectionStrings("My_ConnectionString").ConnectionString

like this

Dim DBConnection As New SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings("My_ConnectionString").ConnectionString)

<input type="file"> limit selectable files by extensions

NOTE: This answer is from 2011. It was a really good answer back then, but as of 2015, native HTML properties are supported by most browsers, so there's (usually) no need to implement such custom logic in JS. See Edi's answer and the docs.


Before the file is uploaded, you can check the file's extension using Javascript, and prevent the form being submitted if it doesn't match. The name of the file to be uploaded is stored in the "value" field of the form element.

Here's a simple example that only allows files that end in ".gif" to be uploaded:

<script type="text/javascript">
    function checkFile() {
        var fileElement = document.getElementById("uploadFile");
        var fileExtension = "";
        if (fileElement.value.lastIndexOf(".") > 0) {
            fileExtension = fileElement.value.substring(fileElement.value.lastIndexOf(".") + 1, fileElement.value.length);
        }
        if (fileExtension.toLowerCase() == "gif") {
            return true;
        }
        else {
            alert("You must select a GIF file for upload");
            return false;
        }
    }
</script>

<form action="upload.aspx" enctype="multipart/form-data" onsubmit="return checkFile();">
    <input name="uploadFile" id="uploadFile" type="file" />

    <input type="submit" />
</form>

However, this method is not foolproof. Sean Haddy is correct that you always want to check on the server side, because users can defeat your Javascript checking by turning off javascript, or editing your code after it arrives in their browser. Definitely check server-side in addition to the client-side check. Also I recommend checking for size server-side too, so that users don't crash your server with a 2 GB file (there's no way that I know of to check file size on the client side without using Flash or a Java applet or something).

However, checking client side before hand using the method I've given here is still useful, because it can prevent mistakes and is a minor deterrent to non-serious mischief.

Insert new column into table in sqlite?

I was facing the same problem and the second method proposed in the accepted answer, as noted in the comments, can be problematic when dealing with foreign keys.

My workaround is to export the database to a sql file making sure that the INSERT statements include column names. I do it using DB Browser for SQLite which has an handy feature for that. After that you just have to edit the create table statement and insert the new column where you want it and recreate the db.

In *nix like systems is just something along the lines of

cat db.sql | sqlite3 database.db

I don't know how feasible this is with very big databases, but it worked in my case.

Float a div in top right corner without overlapping sibling header

Another problem solved by the rubber duck:

The css is right but you still have to remember that the HTML elements order matters: the div has to come before the header. http://jsfiddle.net/Fq2Na/1/ enter image description here

Change your HTML code to have the div before the header:

<section>
<div><button>button</button></div>
<h1>some long long long long header, a whole line, 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6</h1>
</section>

And keep your CSS to the simple div { float: right; }.

What does the regex \S mean in JavaScript?

/\S/.test(string) returns true if and only if there's a non-space character in string. Tab and newline count as spaces.

c#: getter/setter

public string Type { get; set; } 

is no different than doing

private string _Type;

public string Type
{    
  get { return _Type; }
  set { _Type = value; }
}

Which regular expression operator means 'Don't' match this character?

You can use negated character classes to exclude certain characters: for example [^abcde] will match anything but a,b,c,d,e characters.

Instead of specifying all the characters literally, you can use shorthands inside character classes: [\w] (lowercase) will match any "word character" (letter, numbers and underscore), [\W] (uppercase) will match anything but word characters; similarly, [\d] will match the 0-9 digits while [\D] matches anything but the 0-9 digits, and so on.

If you use PHP you can take a look at the regex character classes documentation.

Print a div content using Jquery

Some jQuery research has failed, so I moved to JavaScript (thanks for your suggestion Anders).

And it is working well...

HTML

<div id='DivIdToPrint'>
    <p>This is a sample text for printing purpose.</p>
</div>
<p>Do not print.</p>
<input type='button' id='btn' value='Print' onclick='printDiv();'>

JavaScript

function printDiv() 
{

  var divToPrint=document.getElementById('DivIdToPrint');

  var newWin=window.open('','Print-Window');

  newWin.document.open();

  newWin.document.write('<html><body onload="window.print()">'+divToPrint.innerHTML+'</body></html>');

  newWin.document.close();

  setTimeout(function(){newWin.close();},10);

}

Allow anonymous authentication for a single folder in web.config?

I added web.config to the specific folder say "Users" (VS 2015, C#) and the added following code

<?xml version="1.0"?>
 <configuration>
  <system.web>
    <authorization>     
    <deny users="?"/>
  </authorization>
</system.web>
</configuration>

Initially i used location tag but that didn't worked.

Amazon AWS Filezilla transfer permission denied

if you are using centOs then use

sudo chown -R centos:centos /var/www/html

sudo chmod -R 755 /var/www/html

For Ubuntu

sudo chown -R ubuntu:ubuntu /var/www/html

sudo chmod -R 755 /var/www/html

For Amazon ami

sudo chown -R ec2-user:ec2-user /var/www/html

sudo chmod -R 755 /var/www/html

Convert Java Array to Iterable

With Java 8, you can do this.

final int[] arr = {1, 2, 3};
final PrimitiveIterator.OfInt i1 = Arrays.stream(arr).iterator();
final PrimitiveIterator.OfInt i2 = IntStream.of(arr).iterator();
final Iterator<Integer> i3 = IntStream.of(arr).boxed().iterator();

Command /usr/bin/codesign failed with exit code 1

One solution more works with me, If you installed two versions of XCode and you install the second without uninstalling the first in the same directory (/Developer/), you did it wrong. So the solution that works for me was:

1 - Uninstall the current Xcode version with the command sudo /Developer/Library/uninstall-devtools --mode=all.

2 - Install the first Xcode version you had first.

3 - Again sudo /Developer/Library/uninstall-devtools --mode=all.

4 - Then, all is clean and you are able to install the version you want.

More things: maybe you need to restart the computer after install the Xcode or even (in some cases) install two times the Xcode.

I hope I works it take me a lot of time to know that, good luck!!!

PL/SQL ORA-01422: exact fetch returns more than requested number of rows

A SELECT INTO statement will throw an error if it returns anything other than 1 row. If it returns 0 rows, you'll get a no_data_found exception. If it returns more than 1 row, you'll get a too_many_rows exception. Unless you know that there will always be exactly 1 employee with a salary greater than 3000, you do not want a SELECT INTO statement here.

Most likely, you want to use a cursor to iterate over (potentially) multiple rows of data (I'm also assuming that you intended to do a proper join between the two tables rather than doing a Cartesian product so I'm assuming that there is a departmentID column in both tables)

BEGIN
  FOR rec IN (SELECT EMPLOYEE.EMPID, 
                     EMPLOYEE.ENAME, 
                     EMPLOYEE.DESIGNATION, 
                     EMPLOYEE.SALARY,  
                     DEPARTMENT.DEPT_NAME 
                FROM EMPLOYEE, 
                     DEPARTMENT 
               WHERE employee.departmentID = department.departmentID
                 AND EMPLOYEE.SALARY > 3000)
  LOOP
    DBMS_OUTPUT.PUT_LINE ('Employee Nnumber: ' || rec.EMPID);
    DBMS_OUTPUT.PUT_LINE ('---------------------------------------------------');
    DBMS_OUTPUT.PUT_LINE ('Employee Name: ' || rec.ENAME);
    DBMS_OUTPUT.PUT_LINE ('---------------------------------------------------');
    DBMS_OUTPUT.PUT_LINE ('Employee Designation: ' || rec.DESIGNATION);
    DBMS_OUTPUT.PUT_LINE ('----------------------------------------------------');
    DBMS_OUTPUT.PUT_LINE ('Employee Salary: ' || rec.SALARY);
    DBMS_OUTPUT.PUT_LINE ('----------------------------------------------------');
    DBMS_OUTPUT.PUT_LINE ('Employee Department: ' || rec.DEPT_NAME);
  END LOOP;
END;

I'm assuming that you are just learning PL/SQL as well. In real code, you'd never use dbms_output like this and would not depend on anyone seeing data that you write to the dbms_output buffer.

Is there a PowerShell "string does not contain" cmdlet or syntax?

To exclude the lines that contain any of the strings in $arrayOfStringsNotInterestedIn, you should use:

(Get-Content $FileName) -notmatch [String]::Join('|',$arrayofStringsNotInterestedIn)

The code proposed by Chris only works if $arrayofStringsNotInterestedIn contains the full lines you want to exclude.

Testing if a site is vulnerable to Sql Injection

Any input from a client are ways to be vulnerable. Including all forms and the query string. This includes all HTTP verbs.

There are 3rd party solutions that can crawl an application and detect when an injection could happen.

How do I retrieve query parameters in Spring Boot?

I was interested in this as well and came across some examples on the Spring Boot site.

   // get with query string parameters e.g. /system/resource?id="rtze1cd2"&person="sam smith" 
// so below the first query parameter id is the variable and name is the variable
// id is shown below as a RequestParam
    @GetMapping("/system/resource")
    // this is for swagger docs
    @ApiOperation(value = "Get the resource identified by id and person")
    ResponseEntity<?> getSomeResourceWithParameters(@RequestParam String id, @RequestParam("person") String name) {

        InterestingResource resource = getMyInterestingResourc(id, name);
        logger.info("Request to get an id of "+id+" with a name of person: "+name);

        return new ResponseEntity<Object>(resource, HttpStatus.OK);
    }

See here also

Check folder size in Bash

if you just want to see the aggregate size of the folder and probably in MB or GB format, please try the below script

$du -s --block-size=M /path/to/your/directory/

Matplotlib tight_layout() doesn't take into account figure suptitle

The only thing that worked for me was modifying the call to suptitle:

fig.suptitle("title", y=.995)

VBA (Excel) Initialize Entire Array without Looping

I want to initialize every single element of the array to some initial value. So if I have an array Dim myArray(300) As Integer of 300 integers, for example, all 300 elements would hold the same initial value (say, the number 13).

Can anyone explain how to do this, without looping? I'd like to do it in one statement if possible.

What do I win?

Sub SuperTest()
   Dim myArray
   myArray = Application.Transpose([index(Row(1:300),)-index(Row(1:300),)+13])
End Sub

Android Studio: Drawable Folder: How to put Images for Multiple dpi?

Simply go to project Explorer and change your View from Android to project from drop Down and you are good to go.There you can simply create folder like we do in Eclipse. And in android project view it is hidden but when you switch to project. You can create folder like drawable-hdpi,drawable-xhdpi.

enter image description here

mingw-w64 threads: posix vs win32

Note that it is now possible to use some of C++11 std::thread in the win32 threading mode. These header-only adapters worked out of the box for me: https://github.com/meganz/mingw-std-threads

From the revision history it looks like there is some recent attempt to make this a part of the mingw64 runtime.

How to call a method after bean initialization is complete?

There are three different approaches to consider, as described in the reference

Use init-method attribute

Pros:

  • Does not require bean to implement an interface.

Cons:

  • No immediate indication this method is required after construction to ensure the bean is correctly configured.

Implement InitializingBean

Pros:

  • No need to specify init-method, or turn on component scanning / annotation processing.
  • Appropriate for beans supplied with a library, where we don't want the application using this library to concern itself with bean lifecycle.

Cons:

  • More invasive than the init-method approach.

Use JSR-250 @PostConstruct lifecyle annotation

Pros:

  • Useful when using component scanning to autodetect beans.
  • Makes it clear that a specific method is to be used for initialisation. Intent is closer to the code.

Cons:

  • Initialisation no longer centrally specified in configuration.
  • You must remember to turn on annotation processing (which can sometimes be forgotten)

Duplicate Entire MySQL Database

This won't work for InnoDB. Use this workaround only if you are trying to copy MyISAM databases.

If locking the tables during backup, and, possibly, pausing MySQL during the database import is acceptable, mysqlhotcopy may work faster.

E.g.

Backup:

# mysqlhotcopy -u root -p password db_name /path/to/backup/directory

Restore:

cp /path/to/backup/directory/* /var/lib/mysql/db_name

mysqlhotcopy can also transfer files over SSH (scp), and, possibly, straight into the duplicate database directory.

E.g.

# mysqlhotcopy -u root -p password db_name /var/lib/mysql/duplicate_db_name

Excel - programm cells to change colour based on another cell

Use conditional formatting.

You can enter a condition using any cell you like and a format to apply if the formula is true.

How do I download a file with Angular2 or greater

Downloading file through ajax is always a painful process and In my view it is best to let server and browser do this work of content type negotiation.

I think its best to have

<a href="api/sample/download"></a> 

to do it. This doesn't even require any new windows opening and stuff like that.

The MVC controller as in your sample can be like the one below:

[HttpGet("[action]")]
public async Task<FileContentResult> DownloadFile()
{
    // ...
    return File(dataStream.ToArray(), "text/plain", "myblob.txt");
}

node.js TypeError: path must be absolute or specify root to res.sendFile [failed to parse JSON]

I solve this by using path variable. The sample code will look like below.

var path = require("path");

app.get('/', (req, res) => {
    res.sendFile(path.join(__dirname + '/index.html'));
})

How to populate HTML dropdown list with values from database

I'd suggest following a few debugging steps.

First run the query directly against the DB. Confirm it is bringing results back. Even with something as simple as this you can find you've made a mistake, or the table is empty, or somesuch oddity.

If the above is ok, then try looping and echoing out the contents of $row just directly into the HTML to see what you've getting back in the mysql_query - see if it matches what you got directly in the DB.

If your data is output onto the page, then look at what's going wrong in your HTML formatting.

However, if nothing is output from $row, then figure out why the mysql_query isn't working e.g. does the user have permission to query that DB, do you have an open DB connection, can the webserver connect to the DB etc [something on these lines can often be a gotcha]

Changing your query slightly to

$sql = mysql_query("SELECT username FROM users") or die(mysql_error());  

may help to highlight any errors: php manual

How do I install TensorFlow's tensorboard?

Adding this just for the sake of completeness of this question (some questions may get closed as duplicate of this one).

I usually use user mode for pip ie. pip install --user even if instructions assume root mode. That way, my tensorboard installation was in ~/.local/bin/tensorboard, and it was not in my path (which shouldn't be ideal either). So I was not able to access it.

In this case, running

sudo ln -s ~/.local/bin/tensorboard /usr/bin

should fix it.

Python Pylab scatter plot error bars (the error on each point is unique)

>>> import matplotlib.pyplot as plt
>>> a = [1,3,5,7]
>>> b = [11,-2,4,19]
>>> plt.pyplot.scatter(a,b)
>>> plt.scatter(a,b)
<matplotlib.collections.PathCollection object at 0x00000000057E2CF8>
>>> plt.show()
>>> c = [1,3,2,1]
>>> plt.errorbar(a,b,yerr=c, linestyle="None")
<Container object of 3 artists>
>>> plt.show()

where a is your x data b is your y data c is your y error if any

note that c is the error in each direction already

Getting the HTTP Referrer in ASP.NET

Belonging to other reply, I have added condition clause for getting null.

string ComingUrl = "";
if (Request.UrlReferrer != null)
{
    ComingUrl = System.Web.HttpContext.Current.Request.UrlReferrer.ToString();
}
else
{
    ComingUrl = "Direct"; // Your code
}

How can I convert a stack trace to a string?

Print the stack trace to a PrintStream, then convert it to a String:

// ...

catch (Exception e)
{
    ByteArrayOutputStream out = new ByteArrayOutputStream(); 
    e.printStackTrace(new PrintStream(out));
    String str = new String(out.toByteArray());

    System.out.println(str);
}

Turn off iPhone/Safari input element rounding

If you use normalize.css, that stylesheet will do something like input[type="search"] { -webkit-appearance: textfield; }.

This has a higher specificity than a single class selector like .foo, so be aware that you then can't do just .my-field { -webkit-appearance: none; }. If you have no better way to achieve the right specificity, this will help:

.my-field { -webkit-appearance: none !important; }

What are the most common naming conventions in C?

Here's an (apparently) uncommon one, which I've found useful: module name in CamelCase, then an underscore, then function or file-scope name in CamelCase. So for example:

Bluetooth_Init()
CommsHub_Update()
Serial_TxBuffer[]

Replacing Pandas or Numpy Nan with a None to use with MysqlDB

Just an addition to @Andy Hayden's answer:

Since DataFrame.mask is the opposite twin of DataFrame.where, they have the exactly same signature but with opposite meaning:

  • DataFrame.where is useful for Replacing values where the condition is False.
  • DataFrame.mask is used for Replacing values where the condition is True.

So in this question, using df.mask(df.isna(), other=None, inplace=True) might be more intuitive.

What does 'corrupted double-linked list' mean

I have found the answer to my question myself:)

So what I didn't understand was how the glibc could differentiate between a Segfault and a corrupted double-linked list, because according to my understanding, from perspective of glibc they should look like the same thing. Because if I implement a double-linked list inside my program, how could the glibc possibly know that this is a double-linked list, instead of any other struct? It probably can't, so thats why i was confused.

Now I've looked at malloc/malloc.c inside the glibc's code, and I see the following:

1543 /* Take a chunk off a bin list */
1544 #define unlink(P, BK, FD) {                                            \
1545   FD = P->fd;                                                          \
1546   BK = P->bk;                                                          \
1547   if (__builtin_expect (FD->bk != P || BK->fd != P, 0))                \
1548     malloc_printerr (check_action, "corrupted double-linked list", P); \
1549   else {                                                               \
1550     FD->bk = BK;                                                       \
1551     BK->fd = FD;                                                       \

So now this suddenly makes sense. The reason why glibc can know that this is a double-linked list is because the list is part of glibc itself. I've been confused because I thought glibc can somehow detect that some programming is building a double-linked list, which I wouldn't understand how that works. But if this double-linked list that it is talking about, is part of glibc itself, of course it can know it's a double-linked list.

I still don't know what has triggered this error. But at least I understand the difference between corrupted double-linked list and a Segfault, and how the glibc can know this struct is supposed to be a double-linked list:)

How to allow only numeric (0-9) in HTML inputbox using jQuery?

Here is a quick solution I created some time ago. you can read more about it in my article:

http://ajax911.com/numbers-numeric-field-jquery/

$("#textfield").bind("keyup paste", function(){
    setTimeout(jQuery.proxy(function() {
        this.val(this.val().replace(/[^0-9]/g, ''));
    }, $(this)), 0);
});

Crontab Day of the Week syntax

0 and 7 both stand for Sunday, you can use the one you want, so writing 0-6 or 1-7 has the same result.

Also, as suggested by @Henrik, it is possible to replace numbers by shortened name of days, such as MON, THU, etc:

0 - Sun      Sunday
1 - Mon      Monday
2 - Tue      Tuesday
3 - Wed      Wednesday
4 - Thu      Thursday
5 - Fri      Friday
6 - Sat      Saturday
7 - Sun      Sunday

Graphically:

 +---------- minute (0 - 59)
 ¦ +-------- hour (0 - 23)
 ¦ ¦ +------ day of month (1 - 31)
 ¦ ¦ ¦ +---- month (1 - 12)
 ¦ ¦ ¦ ¦ +-- day of week (0 - 6 => Sunday - Saturday, or
 ¦ ¦ ¦ ¦ ¦                1 - 7 => Monday - Sunday)
 ? ? ? ? ?
 * * * * * command to be executed

Finally, if you want to specify day by day, you can separate days with commas, for example SUN,MON,THU will exectute the command only on sundays, mondays on thursdays.

You can read further details in Wikipedia's article about Cron.

How to group pandas DataFrame entries by date in a non-unique column

This might be easier to explain with a sample dataset.

Create Sample Data

Let's assume we have a single column of Timestamps, date and another column we would like to perform an aggregation on, a.

df = pd.DataFrame({'date':pd.DatetimeIndex(['2012-1-1', '2012-6-1', '2015-1-1', '2015-2-1', '2015-3-1']),
                   'a':[9,5,1,2,3]}, columns=['date', 'a'])

df

        date  a
0 2012-01-01  9
1 2012-06-01  5
2 2015-01-01  1
3 2015-02-01  2
4 2015-03-01  3

There are several ways to group by year

  • Use the dt accessor with year property
  • Put date in index and use anonymous function to access year
  • Use resample method
  • Convert to pandas Period

.dt accessor with year property

When you have a column (and not an index) of pandas Timestamps, you can access many more extra properties and methods with the dt accessor. For instance:

df['date'].dt.year

0    2012
1    2012
2    2015
3    2015
4    2015
Name: date, dtype: int64

We can use this to form our groups and calculate some aggregations on a particular column:

df.groupby(df['date'].dt.year)['a'].agg(['sum', 'mean', 'max'])

      sum  mean  max
date                
2012   14     7    9
2015    6     2    3

put date in index and use anonymous function to access year

If you set the date column as the index, it becomes a DateTimeIndex with the same properties and methods as the dt accessor gives normal columns

df1 = df.set_index('date')
df1.index.year

Int64Index([2012, 2012, 2015, 2015, 2015], dtype='int64', name='date')

Interestingly, when using the groupby method, you can pass it a function. This function will be implicitly passed the DataFrame's index. So, we can get the same result from above with the following:

df1.groupby(lambda x: x.year)['a'].agg(['sum', 'mean', 'max'])

      sum  mean  max
2012   14     7    9
2015    6     2    3

Use the resample method

If your date column is not in the index, you must specify the column with the on parameter. You also need to specify the offset alias as a string.

df.resample('AS', on='date')['a'].agg(['sum', 'mean', 'max'])

             sum  mean  max
date                       
2012-01-01  14.0   7.0  9.0
2013-01-01   NaN   NaN  NaN
2014-01-01   NaN   NaN  NaN
2015-01-01   6.0   2.0  3.0

Convert to pandas Period

You can also convert the date column to a pandas Period object. We must pass in the offset alias as a string to determine the length of the Period.

df['date'].dt.to_period('A')

0   2012
1   2012
2   2015
3   2015
4   2015
Name: date, dtype: object

We can then use this as a group

df.groupby(df['date'].dt.to_period('Y'))['a'].agg(['sum', 'mean', 'max'])


      sum  mean  max
2012   14     7    9
2015    6     2    3

Python string.join(list) on object array rather than string array

another solution is to override the join operator of the str class.

Let us define a new class my_string as follows

class my_string(str):
    def join(self, l):
        l_tmp = [str(x) for x in l]
        return super(my_string, self).join(l_tmp)

Then you can do

class Obj:
    def __str__(self):
        return 'name'

list = [Obj(), Obj(), Obj()]
comma = my_string(',')

print comma.join(list)

and you get

name,name,name

BTW, by using list as variable name you are redefining the list class (keyword) ! Preferably use another identifier name.

Hope you'll find my answer useful.

Javascript: How to loop through ALL DOM elements on a page?

Here is another example on how you can loop through a document or an element:

function getNodeList(elem){
var l=new Array(elem),c=1,ret=new Array();
//This first loop will loop until the count var is stable//
for(var r=0;r<c;r++){
    //This loop will loop thru the child element list//
    for(var z=0;z<l[r].childNodes.length;z++){

         //Push the element to the return array.
        ret.push(l[r].childNodes[z]);

        if(l[r].childNodes[z].childNodes[0]){
            l.push(l[r].childNodes[z]);c++;
        }//IF           
    }//FOR
}//FOR
return ret;
}

How can I debug a .BAT script?

I found 'running steps' (win32) software doing exactly what I was looking for: http://www.steppingsoftware.com/

You can load a bat file, place breakpoints / start stepping through it while seeing the output and environment variables.

The evaluation version only allows to step through 50 lines... Does anyone have a free alternative with similar functionality?

How to explicitly obtain post data in Spring MVC?

Spring MVC runs on top of the Servlet API. So, you can use HttpServletRequest#getParameter() for this:

String value1 = request.getParameter("value1");
String value2 = request.getParameter("value2");

The HttpServletRequest should already be available to you inside Spring MVC as one of the method arguments of the handleRequest() method.

How can I discard remote changes and mark a file as "resolved"?

git checkout has the --ours option to check out the version of the file that you had locally (as opposed to --theirs, which is the version that you pulled in). You can pass . to git checkout to tell it to check out everything in the tree. Then you need to mark the conflicts as resolved, which you can do with git add, and commit your work once done:

git checkout --ours .  # checkout our local version of all files
git add -u             # mark all conflicted files as merged
git commit             # commit the merge

Note the . in the git checkout command. That's very important, and easy to miss. git checkout has two modes; one in which it switches branches, and one in which it checks files out of the index into the working copy (sometimes pulling them into the index from another revision first). The way it distinguishes is by whether you've passed a filename in; if you haven't passed in a filename, it tries switching branches (though if you don't pass in a branch either, it will just try checking out the current branch again), but it refuses to do so if there are modified files that that would effect. So, if you want a behavior that will overwrite existing files, you need to pass in . or a filename in order to get the second behavior from git checkout.

It's also a good habit to have, when passing in a filename, to offset it with --, such as git checkout --ours -- <filename>. If you don't do this, and the filename happens to match the name of a branch or tag, Git will think that you want to check that revision out, instead of checking that filename out, and so use the first form of the checkout command.

I'll expand a bit on how conflicts and merging work in Git. When you merge in someone else's code (which also happens during a pull; a pull is essentially a fetch followed by a merge), there are few possible situations.

The simplest is that you're on the same revision. In this case, you're "already up to date", and nothing happens.

Another possibility is that their revision is simply a descendent of yours, in which case you will by default have a "fast-forward merge", in which your HEAD is just updated to their commit, with no merging happening (this can be disabled if you really want to record a merge, using --no-ff).

Then you get into the situations in which you actually need to merge two revisions. In this case, there are two possible outcomes. One is that the merge happens cleanly; all of the changes are in different files, or are in the same files but far enough apart that both sets of changes can be applied without problems. By default, when a clean merge happens, it is automatically committed, though you can disable this with --no-commit if you need to edit it beforehand (for instance, if you rename function foo to bar, and someone else adds new code that calls foo, it will merge cleanly, but produce a broken tree, so you may want to clean that up as part of the merge commit in order to avoid having any broken commits).

The final possibility is that there's a real merge, and there are conflicts. In this case, Git will do as much of the merge as it can, and produce files with conflict markers (<<<<<<<, =======, and >>>>>>>) in your working copy. In the index (also known as the "staging area"; the place where files are stored by git add before committing them), you will have 3 versions of each file with conflicts; there is the original version of the file from the ancestor of the two branches you are merging, the version from HEAD (your side of the merge), and the version from the remote branch.

In order to resolve the conflict, you can either edit the file that is in your working copy, removing the conflict markers and fixing the code up so that it works. Or, you can check out the version from one or the other sides of the merge, using git checkout --ours or git checkout --theirs. Once you have put the file into the state you want it, you indicate that you are done merging the file and it is ready to commit using git add, and then you can commit the merge with git commit.

Display number with leading zeros

You can do this with f strings.

import numpy as np

print(f'{np.random.choice([1, 124, 13566]):0>8}')

This will print constant length of 8, and pad the rest with leading 0.

00000001
00000124
00013566

Adding and using header (HTTP) in nginx

To add a header just add the following code to the location block where you want to add the header:

location some-location {
  add_header X-my-header my-header-content;      
}

Obviously, replace the x-my-header and my-header-content with what you want to add. And that's all there is to it.

JSchException: Algorithm negotiation fail

Make sure that you're using the latest version of JSch. I had this exact same problem when using JSch 0.1.31 and trying to connect to a RedHat 5 server. Updating to the latest version solved the problem.

Excel error HRESULT: 0x800A03EC while trying to get range with cell's name

I found a possible solution here: http://www.made4dotnet.com/Default.aspx?tabid=141&aid=15

Edit:

If you automate Microsoft Excel with Microsoft Visual Basic .NET, Microsoft Visual C# .NET, or Microsoft Visual C++, you may receive the following errors when calling certain methods because the machine has the locale set to something other than US English (locale ID or LCID 1033):

Exception from HRESULT: 0x800A03EC

and/or

Old format or invalid type library

SOLUTION 1:


To get around this error you can set CurrentCulture to en-US when executing code related to Excel and reset back to your originale by using these 2 functions.

//declare a variable to hold the CurrentCulture
System.Globalization.CultureInfo oldCI;
//get the old CurrenCulture and set the new, en-US
void SetNewCurrentCulture()
{
  oldCI = System.Threading.Thread.CurrentThread.CurrentCulture;
  System.Threading.Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo("en-US");
}
//reset Current Culture back to the originale
void ResetCurrentCulture()
{
  System.Threading.Thread.CurrentThread.CurrentCulture = oldCI;
}

SOLUTION 2:


Another solution that could work, create a 1033 directory under Microsoft Office\Office11 (or your corresponding office-version), copy excel.exe to the 1033 directory, and rename it to xllex.dll.

Although you might solve the problem using one off these solutions, when you call the Excel object model in locales other than US English, the Excel object model can act differently and your code can fail in ways you may not have thought of. For example, you might have code that sets the value of a range to a date:

yourRange.Value2 = "10/10/09"

Depending on the locale this code can act differently resulting in Excel putting into the range any of the following values:

October 10, 2009 September 10, 2009 October 9, 2010

Angular 6: saving data to local storage

You should define a key name while storing data to local storage which should be a string and value should be a string

 localStorage.setItem('dataSource', this.dataSource.length);

and to print, you should use getItem

console.log(localStorage.getItem('dataSource'));

How to inspect Javascript Objects

Use your console:

console.log(object);

Or if you are inspecting html dom elements use console.dir(object). Example:

let element = document.getElementById('alertBoxContainer');
console.dir(element);

Or if you have an array of js objects you could use:

console.table(objectArr);

If you are outputting a lot of console.log(objects) you can also write

console.log({ objectName1 });
console.log({ objectName2 });

This will help you label the objects written to console.

CKEditor, Image Upload (filebrowserUploadUrl)

This simple demo may help you in getting what you want. Here is the html/php code from where you want to upload the image:

<html>
<head>
 <script src="http://cdn.ckeditor.com/4.6.2/standard-all/ckeditor.js"></script>
  </head>
<body>
<form  action="index.php" method="POST"  style="width:500xp;">

<textarea rows="5" name="content" id="content"></textarea>

<br>
<input type="submit" name="submit" value="Post">

</form>
<script>
 CKEDITOR.replace( 'content', {
  height: 300,
  filebrowserUploadUrl: "upload.php"
 });
</script>
</body>
</html>

and here is the code for upload.php file.

 <?php
if(isset($_FILES['upload']['name']))
{
 $file = $_FILES['upload']['tmp_name'];
 $file_name = $_FILES['upload']['name'];
 $file_name_array = explode(".", $file_name);
 $extension = end($file_name_array);
 //we want to save the image with timestamp and randomnumber
 $new_image_name = time() . rand(). '.' . $extension;
 chmod('upload', 0777);
 $allowed_extension = array("jpg", "gif", "png");
 if(in_array($extension, $allowed_extension))
 {
  move_uploaded_file($file, 'upload/' . $new_image_name);
  $function_number = $_GET['CKEditorFuncNum'];
  $url = 'upload/' . $new_image_name;
  $message = '';
  echo "<script type='text/javascript'>window.parent.CKEDITOR.tools.callFunction($function_number, '$url', '$message');</script>";
 }
}
?>

Note: Don't forget to create a folder "upload" in the same folder and keep all the three files in the same directory. Later you may change their directories once you understand how it works. Also not forget to press send it to the server as shown in picture below.

screenshot

Output data from all columns in a dataframe in pandas

In ipython, I use this to print a part of the dataframe that works quite well (prints the first 100 rows):

print paramdata.head(100).to_string()

What is a lambda expression in C++11?

Well, one practical use I've found out is reducing boiler plate code. For example:

void process_z_vec(vector<int>& vec)
{
  auto print_2d = [](const vector<int>& board, int bsize)
  {
    for(int i = 0; i<bsize; i++)
    {
      for(int j=0; j<bsize; j++)
      {
        cout << board[bsize*i+j] << " ";
      }
      cout << "\n";
    }
  };
  // Do sth with the vec.
  print_2d(vec,x_size);
  // Do sth else with the vec.
  print_2d(vec,y_size);
  //... 
}

Without lambda, you may need to do something for different bsize cases. Of course you could create a function but what if you want to limit the usage within the scope of the soul user function? the nature of lambda fulfills this requirement and I use it for that case.

The 'json' native gem requires installed build tools

Followed the steps.

  1. Extract DevKit to path C:\Ruby193\DevKit
  2. cd C:\Ruby192\DevKit
  3. ruby dk.rb init
  4. ruby dk.rb review
  5. ruby dk.rb install

Then I wrote the command

gem install rails -r -y

Get Wordpress Category from Single Post

How about get_the_category?

You can then do

$category = get_the_category();
$firstCategory = $category[0]->cat_name;

java.util.NoSuchElementException: No line found

Need to use top comment but also pay attention to nextLine(). To eliminate this error only call

sc.nextLine()

Once from inside your while loop

 while (sc.hasNextLine()) {sc.nextLine()...}

You are using while to look ahead only 1 line. Then using sc.nextLine() to read 2 lines ahead of the single line you asked the while loop to look ahead.

Also change the multiple IF statements to IF, ELSE to avoid reading more than one line also.

overlay two images in android to set an imageview

Its a bit late answer, but it covers merging images from urls using Picasso

MergeImageView

import android.annotation.TargetApi;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Build;
import android.util.AttributeSet;
import android.util.SparseArray;
import android.widget.ImageView;
import com.squareup.picasso.Picasso;

import java.io.IOException;
import java.util.List;

public class MergeImageView extends ImageView {

    private SparseArray<Bitmap> bitmaps = new SparseArray<>();
    private Picasso picasso;
    private final int DEFAULT_IMAGE_SIZE = 50;
    private int MIN_IMAGE_SIZE = DEFAULT_IMAGE_SIZE;
    private int MAX_WIDTH = DEFAULT_IMAGE_SIZE * 2, MAX_HEIGHT = DEFAULT_IMAGE_SIZE * 2;
    private String picassoRequestTag = null;

    public MergeImageView(Context context) {
        super(context);
    }

    public MergeImageView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public MergeImageView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    @TargetApi(Build.VERSION_CODES.LOLLIPOP)
    public MergeImageView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        super(context, attrs, defStyleAttr, defStyleRes);
    }

    @Override
    public boolean isInEditMode() {
        return true;
    }

    public void clearResources() {
        if (bitmaps != null) {
            for (int i = 0; i < bitmaps.size(); i++)
                bitmaps.get(i).recycle();
            bitmaps.clear();
        }
        // cancel picasso requests
        if (picasso != null && AppUtils.ifNotNullEmpty(picassoRequestTag))
            picasso.cancelTag(picassoRequestTag);
        picasso = null;
        bitmaps = null;
    }

    public void createMergedBitmap(Context context, List<String> imageUrls, String picassoTag) {
        picasso = Picasso.with(context);
        int count = imageUrls.size();
        picassoRequestTag = picassoTag;

        boolean isEven = count % 2 == 0;
        // if url size are not even make MIN_IMAGE_SIZE even
        MIN_IMAGE_SIZE = DEFAULT_IMAGE_SIZE + (isEven ? count / 2 : (count / 2) + 1);
        // set MAX_WIDTH and MAX_HEIGHT to twice of MIN_IMAGE_SIZE
        MAX_WIDTH = MAX_HEIGHT = MIN_IMAGE_SIZE * 2;
        // in case of odd urls increase MAX_HEIGHT
        if (!isEven) MAX_HEIGHT = MAX_WIDTH + MIN_IMAGE_SIZE;

        // create default bitmap
        Bitmap bitmap = Bitmap.createScaledBitmap(BitmapFactory.decodeResource(context.getResources(), R.drawable.ic_wallpaper),
                MIN_IMAGE_SIZE, MIN_IMAGE_SIZE, false);

        // change default height (wrap_content) to MAX_HEIGHT
        int height = Math.round(AppUtils.convertDpToPixel(MAX_HEIGHT, context));
        setMinimumHeight(height * 2);

        // start AsyncTask
        for (int index = 0; index < count; index++) {
            // put default bitmap as a place holder
            bitmaps.put(index, bitmap);
            new PicassoLoadImage(index, imageUrls.get(index)).execute();
            // if you want parallel execution use
            // new PicassoLoadImage(index, imageUrls.get(index)).(AsyncTask.THREAD_POOL_EXECUTOR);
        }
    }

    private class PicassoLoadImage extends AsyncTask<String, Void, Bitmap> {

        private int index = 0;
        private String url;

        PicassoLoadImage(int index, String url) {
            this.index = index;
            this.url = url;
        }

        @Override
        protected Bitmap doInBackground(String... params) {
            try {
                // synchronous picasso call
                return picasso.load(url).resize(MIN_IMAGE_SIZE, MIN_IMAGE_SIZE).tag(picassoRequestTag).get();
            } catch (IOException e) {
            }
            return null;
        }

        @Override
        protected void onPostExecute(Bitmap output) {
            super.onPostExecute(output);
            if (output != null)
                bitmaps.put(index, output);

            // create canvas
            Bitmap.Config conf = Bitmap.Config.RGB_565;
            Bitmap canvasBitmap = Bitmap.createBitmap(MAX_WIDTH, MAX_HEIGHT, conf);
            Canvas canvas = new Canvas(canvasBitmap);
            canvas.drawColor(Color.WHITE);

            // if height and width are equal we have even images
            boolean isEven = MAX_HEIGHT == MAX_WIDTH;
            int imageSize = bitmaps.size();
            int count = imageSize;

            // we have odd images
            if (!isEven) count = imageSize - 1;
            for (int i = 0; i < count; i++) {
                Bitmap bitmap = bitmaps.get(i);
                canvas.drawBitmap(bitmap, bitmap.getWidth() * (i % 2), bitmap.getHeight() * (i / 2), null);
            }
            // if images are not even set last image width to MAX_WIDTH
            if (!isEven) {
                Bitmap scaledBitmap = Bitmap.createScaledBitmap(bitmaps.get(count), MAX_WIDTH, MIN_IMAGE_SIZE, false);
                canvas.drawBitmap(scaledBitmap, scaledBitmap.getWidth() * (count % 2), scaledBitmap.getHeight() * (count / 2), null);
            }
            // set bitmap
            setImageBitmap(canvasBitmap);
        }
    }
}

xml

<com.example.MergeImageView
    android:id="@+id/iv_thumb"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" />

Example

List<String> urls = new ArrayList<>();
String picassoTag = null;
// add your urls
((MergeImageView)findViewById(R.id.iv_thumb)).
        createMergedBitmap(MainActivity.this, urls,picassoTag);

I need an unordered list without any bullets

 <div class="custom-control custom-checkbox left">
    <ul class="list-unstyled">
        <li>
         <label class="btn btn-secondary text-left" style="width:100%;text-align:left;padding:2px;">
           <input type="checkbox" style="zoom:1.7;vertical-align:bottom;" asp-for="@Model[i].IsChecked" class="custom-control-input" /> @Model[i].Title
         </label>
        </li>
     </ul>
</div>

How can I parse a YAML file in Python

First install pyyaml using pip3.

Then import yaml module and load the file into a dictionary called 'my_dict':

import yaml
with open('filename.yaml') as f:
    my_dict = yaml.safe_load(f)

That's all you need. Now the entire yaml file is in 'my_dict' dictionary.

DevTools failed to load SourceMap: Could not load content for chrome-extension

Extensions without enough permission on chrome can cause these warnings, for example for React developer tools, check if the following procedure solves your problem:

  1. Right click on the extension icon.

Or

  1. Go to extensions.
  2. Click the three-dot in the row of React developer tool.

Then choose "this can read and write site data". You should see 3 options in the list, pick one that is strict enough based on how much you trust the extension and also satisfies the extensions's needs.

setTimeout in for-loop does not print consecutive values

I had the same problem once this is how I solved it.

Suppose I want 12 delays with an interval of 2 secs

    function animate(i){
         myVar=setTimeout(function(){
            alert(i);
            if(i==12){
              clearTimeout(myVar);
              return;
            }
           animate(i+1)
         },2000)
    }

    var i=1; //i is the start point 1 to 12 that is
    animate(i); //1,2,3,4..12 will be alerted with 2 sec delay

An "and" operator for an "if" statement in Bash

Quote:

The "-a" operator also doesn't work:

if [ $STATUS -ne 200 ] -a [[ "$STRING" != "$VALUE" ]]

For a more elaborate explanation: [ and ] are not Bash reserved words. The if keyword introduces a conditional to be evaluated by a job (the conditional is true if the job's return value is 0 or false otherwise).

For trivial tests, there is the test program (man test).

As some find lines like if test -f filename; then foo bar; fi, etc. annoying, on most systems you find a program called [ which is in fact only a symlink to the test program. When test is called as [, you have to add ] as the last positional argument.

So if test -f filename is basically the same (in terms of processes spawned) as if [ -f filename ]. In both cases the test program will be started, and both processes should behave identically.

Here's your mistake: if [ $STATUS -ne 200 ] -a [[ "$STRING" != "$VALUE" ]] will parse to if + some job, the job being everything except the if itself. The job is only a simple command (Bash speak for something which results in a single process), which means the first word ([) is the command and the rest its positional arguments. There are remaining arguments after the first ].

Also not, [[ is indeed a Bash keyword, but in this case it's only parsed as a normal command argument, because it's not at the front of the command.

How to redirect 'print' output to a file using python?

The most obvious way to do this would be to print to a file object:

with open('out.txt', 'w') as f:
    print >> f, 'Filename:', filename     # Python 2.x
    print('Filename:', filename, file=f)  # Python 3.x

However, redirecting stdout also works for me. It is probably fine for a one-off script such as this:

import sys

orig_stdout = sys.stdout
f = open('out.txt', 'w')
sys.stdout = f

for i in range(2):
    print('i = ', i)

sys.stdout = orig_stdout
f.close()

Since Python 3.4 there's a simple context manager available to do this in the standard library:

from contextlib import redirect_stdout

with open('out.txt', 'w') as f:
    with redirect_stdout(f):
        print('data')

Redirecting externally from the shell itself is another option, and often preferable:

./script.py > out.txt

Other questions:

What is the first filename in your script? I don't see it initialized.

My first guess is that glob doesn't find any bamfiles, and therefore the for loop doesn't run. Check that the folder exists, and print out bamfiles in your script.

Also, use os.path.join and os.path.basename to manipulate paths and filenames.

How to upload (FTP) files to server in a bash script?

if you want to use it inside a 'for' to copy the last generated files for a every-day bacakup...

j=0  
var="`find /backup/path/ -name 'something*' -type f -mtime -1`"  
#we have in $var some files with last day change date

for i in $var  
  do  
  j=$(( $j + 1 ))  
  dirname="`dirname $i`"  
  filename="`basename $i`"  
  /usr/bin/ftp -in >> /tmp/ftp.good 2>> /tmp/ftp.bad << EOF  
    open 123.456.789.012  
    user user_name passwd  
    bin  
    lcd $dirname  
    put $filename  
    quit  
  EOF      #end of ftp  
done       #end of for iteration

R : how to simply repeat a command?

It's not clear whether you're asking this because you are new to programming, but if that's the case then you should probably read this article on loops and indeed read some basic materials on programming.

If you already know about control structures and you want the R-specific implementation details then there are dozens of tutorials around, such as this one. The other answer uses replicate and colMeans, which is idiomatic when writing in R and probably blazing fast as well, which is important if you want 10,000 iterations.

However, one more general and (for beginners) straightforward way to approach problems of this sort would be to use a for loop.

> for (ii in 1:5) { + print(ii) + } [1] 1 [1] 2 [1] 3 [1] 4 [1] 5 > 

So in your case, if you just wanted to print the mean of your Tandem object 5 times:

for (ii in 1:5) {     Tandem <- sample(OUT, size = 815, replace = TRUE, prob = NULL)     TandemMean <- mean(Tandem)     print(TandemMean) } 

As mentioned above, replicate is a more natural way to deal with this specific problem using R. Either way, if you want to store the results - which is surely the case - you'll need to start thinking about data structures like vectors and lists. Once you store something you'll need to be able to access it to use it in future, so a little knowledge is vital.

set.seed(1234) OUT <- runif(100000, 1, 2) tandem <- list() for (ii in 1:10000) {     tandem[[ii]] <- mean(sample(OUT, size = 815, replace = TRUE, prob = NULL)) }  tandem[1] tandem[100] tandem[20:25] 

...creates this output:

> set.seed(1234) > OUT <- runif(100000, 1, 2) > tandem <- list() > for (ii in 1:10000) { +     tandem[[ii]] <- mean(sample(OUT, size = 815, replace = TRUE, prob = NULL)) + } >  > tandem[1] [[1]] [1] 1.511923  > tandem[100] [[1]] [1] 1.496777  > tandem[20:25] [[1]] [1] 1.500669  [[2]] [1] 1.487552  [[3]] [1] 1.503409  [[4]] [1] 1.501362  [[5]] [1] 1.499728  [[6]] [1] 1.492798  >  

Installing NumPy via Anaconda in Windows

The above answers seem to resolve the issue. If it doesn't, then you may also try to update conda using the following command.

conda update conda

And then try to install numpy using

conda install numpy

Append an object to a list in R in amortized constant time, O(1)?

There is also list.append from the rlist (link to the documentation)

require(rlist)
LL <- list(a="Tom", b="Dick")
list.append(LL,d="Pam",f=c("Joe","Ann"))

It's very simple and efficient.

Difference between char* and const char*?

The first you can actually change if you want to, the second you can't. Read up about const correctness (there's some nice guides about the difference). There is also char const * name where you can't repoint it.

D3 Appending Text to a SVG Rectangle

Have you tried the SVG text element?

.append("text").text(function(d, i) { return d[whichevernode];})

rect element doesn't permit text element inside of it. It only allows descriptive elements (<desc>, <metadata>, <title>) and animation elements (<animate>, <animatecolor>, <animatemotion>, <animatetransform>, <mpath>, <set>)

Append the text element as a sibling and work on positioning.

UPDATE

Using g grouping, how about something like this? fiddle

You can certainly move the logic to a CSS class you can append to, remove from the group (this.parentNode)

How many threads is too many?

In most cases you should allow the thread pool to handle this. If you post some code or give more details it might be easier to see if there is some reason the default behavior of the thread pool would not be best.

You can find more information on how this should work here: http://en.wikipedia.org/wiki/Thread_pool_pattern

How can I create an object based on an interface file definition in TypeScript?

If you are using React, the parser will choke on the traditional cast syntax so an alternative was introduced for use in .tsx files

let a = {} as MyInterface;

https://www.typescriptlang.org/docs/handbook/jsx.html

How to center the content inside a linear layout?

If you are looking for an answer in java code,

LinearLayout linearLayout = new LinearLayout(context);
linearLayout.setGravity(Gravity.CENTER);
// add children

MySQL and PHP - insert NULL rather than empty string

All you have to do is: $variable =NULL; // and pass it in the insert query. This will store the value as NULL in mysql db

How to start http-server locally

To start server locally paste the below code in package.json and run npm start in command line.

"scripts": { "start": "http-server -c-1 -p 8081" },

Correct way to remove plugin from Eclipse

Inspired by sergionni's answer, I ended up doing the following steps:

Help --> Installation Details --> Installation History tab

In the Previous configurations table, you can select a configuration and see in the Configuration contents exactly which plugins were installed and are included in it.

It's easy to find the configuration that contains the plugin you want to remove, using the Compare button. This button is enabled when two configurations are selected.

After tracking the configuration that's responsible for that plugin, select the previous configuration and press the Revert button.

Note that if you revert to a configuration that isn't the one just right before the Current Installation, it causes any other plugins that were installed since, to be uninstalled as well.

Finding import static statements for Mockito constructs

The problem is that static imports from Hamcrest and Mockito have similar names, but return Matchers and real values, respectively.

One work-around is to simply copy the Hamcrest and/or Mockito classes and delete/rename the static functions so they are easier to remember and less show up in the auto complete. That's what I did.

Also, when using mocks, I try to avoid assertThat in favor other other assertions and verify, e.g.

assertEquals(1, 1);
verify(someMock).someMethod(eq(1));

instead of

assertThat(1, equalTo(1));
verify(someMock).someMethod(eq(1));

If you remove the classes from your Favorites in Eclipse, and type out the long name e.g. org.hamcrest.Matchers.equalTo and do CTRL+SHIFT+M to 'Add Import' then autocomplete will only show you Hamcrest matchers, not any Mockito matchers. And you can do this the other way so long as you don't mix matchers.

Rails: Get Client IP address

I found request.env['HTTP_X_FORWARDED_FOR'] very useful too in cases when request.remote_ip returns 127.0.0.1

Query to search all packages for table and/or column

By the way, if you need to add other characters such as "(" or ")" because the column may be used as "UPPER(bqr)", then those options can be added to the lists of before and after characters.

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

JSONDecodeError: Expecting value: line 1 column 1 (char 0)

For me, it was not using authentication in the request.

Setting background images in JFrame

Try this :

import java.io.File;
import java.io.IOException;

import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;


public class Test {

    public static void main(String[] args) {
        JFrame f = new JFrame();
        try {
            f.setContentPane(new JLabel(new ImageIcon(ImageIO.read(new File("test.jpg")))));
        } catch (IOException e) {
            e.printStackTrace();
        }
        f.pack();
        f.setVisible(true);
    }

}

By the way, this will result in the content pane not being a container. If you want to add things to it you have to subclass a JPanel and override the paintComponent method.

The container 'Maven Dependencies' references non existing library - STS

I finally found my maven repo mirror is down. I changed to another one, problem solved.

Go install fails with error: no install location for directory xxx outside GOPATH

You'll want to have 3 directories inside your chosen GOPATH directory.

GOPATH
     /bin
     /src
       /someProgram
        program.go
       /someLibrary
        library.go
     /pkg

Then you'll run go install from inside either someProgram (which puts an executable in bin) or someLibrary (which puts a library in pkg).

Error: Local workspace file ('angular.json') could not be found

I was getting the same error messages. It was a silly mistake on my end, I was not running ng serve in the directory where my Angular project is. Make sure you are in the correct directory (project directory) before running this command.

How to apply color in Markdown?

I have started using Markdown to post some of my documents to an internal web site for in-house users. It is an easy way to have a document shared but not able to be edited by the viewer.

So, this marking of text in color is “Great”. I have use several like this and works wonderful.

<span style="color:blue">some *This is Blue italic.* text</span>

Turns into This is Blue italic.

And

<span style="color:red">some **This is Red Bold.** text</span>

Turns into This is Red Bold.

I love the flexibility and ease of use.

Which is faster: multiple single INSERTs or one multiple-row INSERT?

MYSQL 5.5 One sql insert statement took ~300 to ~450ms. while the below stats is for inline multiple insert statments.

(25492 row(s) affected)
Execution Time : 00:00:03:343
Transfer Time  : 00:00:00:000
Total Time     : 00:00:03:343

I would say inline is way to go :)

Get the name of an object's type

You should use somevar.constructor.name like a:

_x000D_
_x000D_
    _x000D_
    const getVariableType = a => a.constructor.name.toLowerCase();_x000D_
_x000D_
    const d = new Date();_x000D_
    const res1 = getVariableType(d); // 'date'_x000D_
    const num = 5;_x000D_
    const res2 = getVariableType(num); // 'number'_x000D_
    const fn = () => {};_x000D_
    const res3 = getVariableType(fn); // 'function'_x000D_
_x000D_
    console.log(res1); // 'date'_x000D_
    console.log(res2); // 'number'_x000D_
    console.log(res3); // 'function'
_x000D_
_x000D_
_x000D_

Using GZIP compression with Spring Boot/MVC/JavaConfig with RESTful

I have added for this:

Server compression

server.compression.enabled=true
server.compression.min-response-size=2048
server.compression.mime-types=application/json,application/xml,text/html,text/xml,text/plain

taken from http://bisaga.com/blog/programming/web-compression-on-spring-boot-application/

Sorting Python list based on the length of the string

Write a function lensort to sort a list of strings based on length.

def lensort(a):
    n = len(a)
    for i in range(n):
        for j in range(i+1,n):
            if len(a[i]) > len(a[j]):
                temp = a[i]
                a[i] = a[j]
                a[j] = temp
    return a
print lensort(["hello","bye","good"])

Where is the list of predefined Maven properties

This link shows how to list all the active properties: http://skillshared.blogspot.co.uk/2012/11/how-to-list-down-all-maven-available.html

In summary, add the following plugin definition to your POM, then run mvn install:

<plugin>
    <artifactId>maven-antrun-plugin</artifactId>
    <version>1.7</version>
    <executions>
        <execution>
            <phase>install</phase>
            <configuration>
                <target>
                    <echoproperties />
                </target>
            </configuration>
            <goals>
                <goal>run</goal>
            </goals>
        </execution>
    </executions>
</plugin>

How can I add items to an empty set in python

D = {} is a dictionary not set.

>>> d = {}
>>> type(d)
<type 'dict'>

Use D = set():

>>> d = set()
>>> type(d)
<type 'set'>
>>> d.update({1})
>>> d.add(2)
>>> d.update([3,3,3])
>>> d
set([1, 2, 3])

Where to place $PATH variable assertions in zsh?

I had similar problem (in bash terminal command was working correctly but zsh showed command not found error)

Solution:


just paste whatever you were earlier pasting in ~/.bashrc to:

~/.zshrc

How to get an input text value in JavaScript

as your lol is local variable now, its good practice to use var keyword for declaring any variables.

this may work for you :

function kk(){
  var lol = document.getElementById('lolz').value;
  alert(lol);
}

Abort Ajax requests using jQuery

This is my implementation based on many answers above:

  var activeRequest = false; //global var
  var filters = {...};
  apply_filters(filters);

  //function triggering the ajax request
  function apply_filters(filters){
        //prepare data and other functionalities
        var data = {};
        //limit the ajax calls
        if (activeRequest === false){
          activeRequest = true;
        }else{
          //abort if another ajax call is pending
          $request.abort();
          //just to be sure the ajax didn't complete before and activeRequest it's already false
          activeRequest = true;        
        }

        $request = $.ajax({ 
          url : window.location.origin + '/your-url.php',
          data: data,
          type:'POST',
          beforeSend: function(){
            $('#ajax-loader-custom').show();
            $('#blur-on-loading').addClass('blur');
          },            
          success:function(data_filters){

              data_filters = $.parseJSON(data_filters);
              
              if( data_filters.posts ) {
                  $(document).find('#multiple-products ul.products li:last-child').after(data_filters.posts).fadeIn();
              }
              else{ 
                return;
              }
              $('#ajax-loader-custom').fadeOut();
          },
          complete: function() {
            activeRequest = false;
          }          
        }); 
  } 

How to update array value javascript?

So I had a problem I needed solved. I had an array object with values. One of those values I needed to update if the value == X.I needed X value to be updated to the Y value. Looking over examples here none of them worked for what I needed or wanted. I finally figured out a simple solution to the problem and was actually surprised it worked. Now normally I like to put the full code solution into these answers but due to its complexity I wont do that here. If anyone finds they cant make this solution work or need more code let me know and I will attempt to update this at some later date to help. For the most part if the array object has named values this solution should work.

            $scope.model.ticketsArr.forEach(function (Ticket) {
                if (Ticket.AppointmentType == 'CRASH_TECH_SUPPORT') {
                    Ticket.AppointmentType = '360_SUPPORT'
                }
            });

Full example below _____________________________________________________

   var Students = [
        { ID: 1, FName: "Ajay", LName: "Test1", Age: 20 },
        { ID: 2, FName: "Jack", LName: "Test2", Age: 21 },
        { ID: 3, FName: "John", LName: "Test3", age: 22 },
        { ID: 4, FName: "Steve", LName: "Test4", Age: 22 }
    ]

    Students.forEach(function (Student) {
        if (Student.LName == 'Test1') {
            Student.LName = 'Smith'
        }
        if (Student.LName == 'Test2') {
            Student.LName = 'Black'
        }
    });

    Students.forEach(function (Student) {
        document.write(Student.FName + " " + Student.LName + "<BR>");
    });

Using for loop inside of a JSP

Do this

    <% for(int i = 0; i < allFestivals.size(); i+=1) { %>
        <tr>      
            <td><%=allFestivals.get(i).getFestivalName()%></td>
        </tr>
    <% } %>

Better way is to use c:foreach see link jstl for each

Python subprocess/Popen with a modified environment

With Python 3.5 you could do it this way:

import os
import subprocess

my_env = {**os.environ, 'PATH': '/usr/sbin:/sbin:' + os.environ['PATH']}

subprocess.Popen(my_command, env=my_env)

Here we end up with a copy of os.environ and overridden PATH value.

It was made possible by PEP 448 (Additional Unpacking Generalizations).

Another example. If you have a default environment (i.e. os.environ), and a dict you want to override defaults with, you can express it like this:

my_env = {**os.environ, **dict_with_env_variables}

How to make div same height as parent (displayed as table-cell)

The child can only take a height if the parent has one already set. See this exaple : Vertical Scrolling 100% height

 html, body {
        height: 100%;
        margin: 0;
    }
    .header{
        height: 10%;
        background-color: #a8d6fe;
    }
    .middle {
        background-color: #eba5a3;
        min-height: 80%;
    }
    .footer {
        height: 10%;
        background-color: #faf2cc;
    }

_x000D_
_x000D_
    $(function() {_x000D_
      $('a[href*="#nav-"]').click(function() {_x000D_
        if (location.pathname.replace(/^\//, '') == this.pathname.replace(/^\//, '') && location.hostname == this.hostname) {_x000D_
          var target = $(this.hash);_x000D_
          target = target.length ? target : $('[name=' + this.hash.slice(1) + ']');_x000D_
          if (target.length) {_x000D_
            $('html, body').animate({_x000D_
              scrollTop: target.offset().top_x000D_
            }, 500);_x000D_
            return false;_x000D_
          }_x000D_
        }_x000D_
      });_x000D_
    });
_x000D_
html,_x000D_
body {_x000D_
  height: 100%;_x000D_
  margin: 0;_x000D_
}_x000D_
.header {_x000D_
  height: 100%;_x000D_
  background-color: #a8d6fe;_x000D_
}_x000D_
.middle {_x000D_
  background-color: #eba5a3;_x000D_
  min-height: 100%;_x000D_
}_x000D_
.footer {_x000D_
  height: 100%;_x000D_
  background-color: #faf2cc;_x000D_
}_x000D_
nav {_x000D_
  position: fixed;_x000D_
  top: 10px;_x000D_
  left: 0px;_x000D_
}_x000D_
nav li {_x000D_
  display: inline-block;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
_x000D_
<body>_x000D_
  <nav>_x000D_
    <ul>_x000D_
      <li>_x000D_
        <a href="#nav-a">got to a</a>_x000D_
      </li>_x000D_
      <li>_x000D_
        <a href="#nav-b">got to b</a>_x000D_
      </li>_x000D_
      <li>_x000D_
        <a href="#nav-c">got to c</a>_x000D_
      </li>_x000D_
    </ul>_x000D_
  </nav>_x000D_
  <div class="header" id="nav-a">_x000D_
_x000D_
  </div>_x000D_
  <div class="middle" id="nav-b">_x000D_
_x000D_
  </div>_x000D_
  <div class="footer" id="nav-c">_x000D_
_x000D_
  </div>
_x000D_
_x000D_
_x000D_

How to pause in C?

Is it a console program, running in Windows? If so, run it from a console you've already opened. i.e. run "cmd", then change to your directory that has the .exe in it (using the cd command), then type in the exe name. Your console window will stay open.

Android: show soft keyboard automatically when focus is on an EditText

I know this question is old by I think using an extension function is a prettier way to show keyboard for an edit text

here is the method I use to show keyboard for an edittext.

kotlin code: just need to call edittext.showKeyboard()

fun EditText.showKeyboard() {
  post {
    requestFocus()
    val imm = context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
    imm.showSoftInput(this, InputMethodManager.SHOW_IMPLICIT)
  }
}

the java code:

public static void showKeyboard(EditText editText) {
    editText.post(new Runnable() {
      @Override
      public void run() {
        editText.requestFocus();
        InputMethodManager imm = (InputMethodManager) editText.getContext()
            .getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.showSoftInput(editText, InputMethodManager.SHOW_IMPLICIT);
      }
    });
  }

Joda DateTime to Timestamp conversion

Actually this is not a duplicate question. And this how i solve my problem after several times :

   int offset = DateTimeZone.forID("anytimezone").getOffset(new DateTime());

This is the way to get offset from desired timezone.

Let's return to our code, we were getting timestamp from a result set of query, and using it with timezone to create our datetime.

   DateTime dt = new DateTime(rs.getTimestamp("anytimestampcolumn"),
                         DateTimeZone.forID("anytimezone"));

Now we will add our offset to the datetime, and get the timestamp from it.

    dt = dt.plusMillis(offset);
    Timestamp ts = new Timestamp(dt.getMillis());

May be this is not the actual way to get it, but it solves my case. I hope it helps anyone who is stuck here.

How to use QTimer

Other way is using of built-in method start timer & event TimerEvent.

Header:

#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include <QMainWindow>

namespace Ui {
class MainWindow;
}

class MainWindow : public QMainWindow
{
    Q_OBJECT

public:
    explicit MainWindow(QWidget *parent = 0);
    ~MainWindow();

private:
    Ui::MainWindow *ui;
    int timerId;

protected:
    void timerEvent(QTimerEvent *event);
};

#endif // MAINWINDOW_H

Source:

#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QDebug>

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    timerId = startTimer(1000);
}

MainWindow::~MainWindow()
{
    killTimer(timerId);
    delete ui;
}

void MainWindow::timerEvent(QTimerEvent *event)
{
    qDebug() << "Update...";
}

Fixing Xcode 9 issue: "iPhone is busy: Preparing debugger support for iPhone"

I have been using my iPhone X to debug via Network and suddenly had this problem.

Disable "Connect via network" and try again with USB. This trick worked for me.

enter image description here

Can a for loop increment/decrement by more than one?

Use the += assignment operator:

for (var i = 0; i < myVar.length; i += 3) {

Technically, you can place any expression you'd like in the final expression of the for loop, but it is typically used to update the counter variable.

For more information about each step of the for loop, check out the MDN article.

Python pandas Filtering out nan from a data selection of a column of strings

Simplest of all solutions:

filtered_df = df[df['name'].notnull()]

Thus, it filters out only rows that doesn't have NaN values in 'name' column.

For multiple columns:

filtered_df = df[df[['name', 'country', 'region']].notnull().all(1)]

How to access the request body when POSTing using Node.js and Express?

Starting from express v4.16 there is no need to require any additional modules, just use the built-in JSON middleware:

app.use(express.json())

Like this:

const express = require('express')

app.use(express.json())    // <==== parse request body as JSON

app.listen(8080)

app.post('/test', (req, res) => {
  res.json({requestBody: req.body})  // <==== req.body will be a parsed JSON object
})

Note - body-parser, on which this depends, is already included with express.

Also don't forget to send the header Content-Type: application/json

html select only one checkbox in a group

Building up on billyonecan's answer, you can use the following code if you need that snippet for more than one checkbox (assuming they have different names).

    $('input.one').on('change', function() {
        var name = $(this).attr('name');
        $('input[name='+name+'].one').not(this).prop('checked', false);
    }); 

Inserting Data into Hive Table

to insert ad-hoc value like (12,"xyz), do this:

insert into table foo select * from (select 12,"xyz")a;

How to check if a file is a valid image file?

I have just found the builtin imghdr module. From python documentation:

The imghdr module determines the type of image contained in a file or byte stream.

This is how it works:

>>> import imghdr
>>> imghdr.what('/tmp/bass')
'gif'

Using a module is much better than reimplementing similar functionality

How big can a MySQL database get before performance starts to degrade

In general this is a very subtle issue and not trivial whatsoever. I encourage you to read mysqlperformanceblog.com and High Performance MySQL. I really think there is no general answer for this.

I'm working on a project which has a MySQL database with almost 1TB of data. The most important scalability factor is RAM. If the indexes of your tables fit into memory and your queries are highly optimized, you can serve a reasonable amount of requests with a average machine.

The number of records do matter, depending of how your tables look like. It's a difference to have a lot of varchar fields or only a couple of ints or longs.

The physical size of the database matters as well: think of backups, for instance. Depending on your engine, your physical db files on grow, but don't shrink, for instance with innodb. So deleting a lot of rows, doesn't help to shrink your physical files.

There's a lot to this issues and as in a lot of cases the devil is in the details.

Secure random token in Node.js

The up-to-date right way to do this asynchronously using ES 2016 standards of async and await (as of Node 7) would be the following:

const crypto = require('crypto');

function generateToken({ stringBase = 'base64', byteLength = 48 } = {}) {
  return new Promise((resolve, reject) => {
    crypto.randomBytes(byteLength, (err, buffer) => {
      if (err) {
        reject(err);
      } else {
        resolve(buffer.toString(stringBase));
      }
    });
  });
}

async function handler(req, res) {
   // default token length
   const newToken = await generateToken();
   console.log('newToken', newToken);

   // pass in parameters - adjust byte length
   const shortToken = await generateToken({byteLength: 20});
   console.log('newToken', shortToken);
}

This works out of the box in Node 7 without any Babel transformations

How can I link a photo in a Facebook album to a URL

Unfortunately, no. This feature is not available for facebook albums.

PHP error: php_network_getaddresses: getaddrinfo failed: (while getting information from other site.)

In my case this was being issued by wp cli, and the problem was that I didn't have php7.3-curl installed. Fixed with: apt-get install -y --quiet php7.3-curl

Protecting cells in Excel but allow these to be modified by VBA script

Try using

Worksheet.Protect "Password", UserInterfaceOnly := True

If the UserInterfaceOnly parameter is set to true, VBA code can modify protected cells.

fatal: Not a valid object name: 'master'

You need to commit at least one time on master before creating a new branch.

String, StringBuffer, and StringBuilder

The Basics:

String is an immutable class, it can't be changed. StringBuilder is a mutable class that can be appended to, characters replaced or removed and ultimately converted to a String StringBuffer is the original synchronized version of StringBuilder

You should prefer StringBuilder in all cases where you have only a single thread accessing your object.

The Details:

Also note that StringBuilder/Buffers aren't magic, they just use an Array as a backing object and that Array has to be re-allocated when ever it gets full. Be sure and create your StringBuilder/Buffer objects large enough originally where they don't have to be constantly re-sized every time .append() gets called.

The re-sizing can get very degenerate. It basically re-sizes the backing Array to 2 times its current size every time it needs to be expanded. This can result in large amounts of RAM getting allocated and not used when StringBuilder/Buffer classes start to grow large.

In Java String x = "A" + "B"; uses a StringBuilder behind the scenes. So for simple cases there is no benefit of declaring your own. But if you are building String objects that are large, say less than 4k, then declaring StringBuilder sb = StringBuilder(4096); is much more efficient than concatenation or using the default constructor which is only 16 characters. If your String is going to be less than 10k then initialize it with the constructor to 10k to be safe. But if it is initialize to 10k then you write 1 character more than 10k, it will get re-allocated and copied to a 20k array. So initializing high is better than to low.

In the auto re-size case, at the 17th character the backing Array gets re-allocated and copied to 32 characters, at the 33th character this happens again and you get to re-allocated and copy the Array into 64 characters. You can see how this degenerates to lots of re-allocations and copies which is what you really are trying to avoid using StringBuilder/Buffer in the first place.

This is from the JDK 6 Source code for AbstractStringBuilder

   void expandCapacity(int minimumCapacity) {
    int newCapacity = (value.length + 1) * 2;
        if (newCapacity < 0) {
            newCapacity = Integer.MAX_VALUE;
        } else if (minimumCapacity > newCapacity) {
        newCapacity = minimumCapacity;
    }
        value = Arrays.copyOf(value, newCapacity);
    }

A best practice is to initialize the StringBuilder/Buffer a little bit larger than you think you are going to need if you don't know right off hand how big the String will be but you can guess. One allocation of slightly more memory than you need is going to be better than lots of re-allocations and copies.

Also beware of initializing a StringBuilder/Buffer with a String as that will only allocated the size of the String + 16 characters, which in most cases will just start the degenerate re-allocation and copy cycle that you are trying to avoid. The following is straight from the Java 6 source code.

public StringBuilder(String str) {
    super(str.length() + 16);
    append(str);
    }

If you by chance do end up with an instance of StringBuilder/Buffer that you didn't create and can't control the constructor that is called, there is a way to avoid the degenerate re-allocate and copy behavior. Call .ensureCapacity() with the size you want to ensure your resulting String will fit into.

The Alternatives:

Just as a note, if you are doing really heavy String building and manipulation, there is a much more performance oriented alternative called Ropes.

Another alternative, is to create a StringList implemenation by sub-classing ArrayList<String>, and adding counters to track the number of characters on every .append() and other mutation operations of the list, then override .toString() to create a StringBuilder of the exact size you need and loop through the list and build the output, you can even make that StringBuilder an instance variable and 'cache' the results of .toString() and only have to re-generate it when something changes.

Also don't forget about String.format() when building fixed formatted output, which can be optimized by the compiler as they make it better.

How to use sbt from behind proxy?

Add both http and https configuration:

export JAVA_OPTS="$JAVA_OPTS -Dhttp.proxyHost=yourserver -Dhttp.proxyPort=8080 -Dhttp.proxyUser=username -Dhttp.proxyPassword=password"

export JAVA_OPTS="$JAVA_OPTS -Dhttps.proxyHost=yourserver -Dhttps.proxyPort=8080 -Dhttps.proxyUser=username -Dhttps.proxyPassword=password"

(https config is must, since many urls referred by the sbt libraries are https)

In fact, I even had an extra setting 'http.proxySet' to 'true' in both configuration entries.

Unable to create Android Virtual Device

I want to update this question with a screenshot of a recent Android Studio. It took a bit of poking around to find where to install new system images.

You get to the SDK Manager through one of two paths. Option 1. Tools > Android > SDK Manager Option 2. Android Studio > Preferences > Appearance & Behavior > System Settings > Android SDK (This is for Mac; adapt for others.)

In the pane "SDK Platforms," check the "Show Packages" box to see the system images.

Select the ones you want, click "Apply" and voilà!

enter image description here

How do I install a custom font on an HTML site

there is a simple way to do this: in the html file add:

<link rel="stylesheet" href="fonts/vermin_vibes.ttf" />

Note: you put the name of .ttf file you have. then go to to your css file and add:

h1 {
    color: blue;
    font-family: vermin vibes;
}

Note: you put the font family name of the font you have.

Note: do not write the font-family name as your font.ttf name example: if your font.ttf name is: "vermin_vibes.ttf" your font-family will be: "vermin vibes" font family doesn't contain special chars as "-,_"...etc it only can contain spaces.

How to toggle font awesome icon on click?

You can toggle the class of the i element within the clicked anchor like

<i class="fa fa-plus-circle"></i>

then

$('#category-tabs li a').click(function(){
    $(this).next('ul').slideToggle('500');
    $(this).find('i').toggleClass('fa-plus-circle fa-minus-circle')
});

Demo: Fiddle

How to disable anchor "jump" when loading a page?

None of answers do not work good enough for me, I see page jumping to anchor and then to top for some solutions, some answers do not work at all, may be things changed for years. Hope my function will help to someone.

/**
 * Prevent automatic scrolling of page to anchor by browser after loading of page.
 * Do not call this function in $(...) or $(window).on('load', ...),
 * it should be called earlier, as soon as possible.
 */
function preventAnchorScroll() {
    var scrollToTop = function () {
        $(window).scrollTop(0);
    };
    if (window.location.hash) {
        // handler is executed at most once
        $(window).one('scroll', scrollToTop);
    }

    // make sure to release scroll 1 second after document readiness
    // to avoid negative UX
    $(function () {
        setTimeout(
            function () {
                $(window).off('scroll', scrollToTop);
            },
            1000
        );
    });
}

Create a custom View by inflating a layout?

In practice, I have found that you need to be a bit careful, especially if you are using a bit of xml repeatedly. Suppose, for example, that you have a table that you wish to create a table row for each entry in a list. You've set up some xml:

In my_table_row.xml:

<?xml version="1.0" encoding="utf-8"?>
<TableRow xmlns:android="http://schemas.android.com/apk/res/android" 
  android:orientation="vertical"
  android:layout_width="match_parent"
  android:layout_height="match_parent" android:id="@+id/myTableRow">
    <ImageButton android:src="@android:drawable/ic_menu_delete" android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/rowButton"/>
    <TextView android:layout_height="wrap_content" android:layout_width="wrap_content" android:textAppearance="?android:attr/textAppearanceMedium" android:text="TextView" android:id="@+id/rowText"></TextView>
</TableRow>

Then you want to create it once per row with some code. It assume that you have defined a parent TableLayout myTable to attach the Rows to.

for (int i=0; i<numRows; i++) {
    /*
     * 1. Make the row and attach it to myTable. For some reason this doesn't seem
     * to return the TableRow as you might expect from the xml, so you need to
     * receive the View it returns and then find the TableRow and other items, as
     * per step 2.
     */
    LayoutInflater inflater = (LayoutInflater)getBaseContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    View v =  inflater.inflate(R.layout.my_table_row, myTable, true);

    // 2. Get all the things that we need to refer to to alter in any way.
    TableRow    tr        = (TableRow)    v.findViewById(R.id.profileTableRow);
    ImageButton rowButton = (ImageButton) v.findViewById(R.id.rowButton);
    TextView    rowText   = (TextView)    v.findViewById(R.id.rowText);

    // 3. Configure them out as you need to
    rowText.setText("Text for this row");
    rowButton.setId(i); // So that when it is clicked we know which one has been clicked!
    rowButton.setOnClickListener(this); // See note below ...           

    /*
     * To ensure that when finding views by id on the next time round this
     * loop (or later) gie lots of spurious, unique, ids.
     */
    rowText.setId(1000+i);
    tr.setId(3000+i);
}

For a clear simple example on handling rowButton.setOnClickListener(this), see Onclicklistener for a programatically created button.

How to get cumulative sum

Select *, (Select SUM(SOMENUMT) From @t S Where S.id <= M.id) From @t M

How can I check for IsPostBack in JavaScript?

The solution didn't work for me, I had to adapt it:

protected void Page_Load(object sender, EventArgs e)
{
    string script;
    if (IsPostBack)
    {
        script = "var isPostBack = true;";
    }
    else
    {
        script = "var isPostBack = false;";
    }
    Page.ClientScript.RegisterStartupScript(GetType(), "IsPostBack", script, true);
}

Hope this helps.

Android statusbar icons color

if you have API level smaller than 23 than you must use it this way. it worked for me declare this under v21/style.

<item name="colorPrimaryDark" tools:targetApi="23">@color/colorPrimary</item>
        <item name="android:windowLightStatusBar" tools:targetApi="23">true</item>

Best way to check for null values in Java?

We can use Object.requireNonNull static method of Object class. Implementation is below

public void someMethod(SomeClass obj) {
    Objects.requireNonNull(obj, "Validation error, obj cannot be null");
}

HTTP Status 504

One thing I have observed regarding this error is that is appears only for the first response from the server, which in case of http should be the handshake response. Once an immediate response is sent from the server to the gateway, if after the main response takes time it does not give an error. The key here is that the first response on a request by a server should be fast.

cURL equivalent in Node.js?

You can use request npm module . Super simple to use. Request is designed to be the simplest way possible to make http calls. It supports HTTPS and follows redirects by default.

var request = require('request');
request('http://www.google.com', function (error, response, body) {
  console.log('error:', error); // Print the error if one occurred
  console.log('statusCode:', response && response.statusCode); // Print the response status code if a response was received
  console.log('body:', body); // Print the HTML for the Google homepage.
});

How to get year/month/day from a date object?

let dateObj = new Date();

let myDate = (dateObj.getUTCFullYear()) + "/" + (dateObj.getMonth() + 1)+ "/" + (dateObj.getUTCDate());

For reference you can see the below details

new Date().getDate()          // Return the day as a number (1-31)
new Date().getDay()           // Return the weekday as a number (0-6)
new Date().getFullYear()      // Return the four digit year (yyyy)
new Date().getHours()         // Return the hour (0-23)
new Date().getMilliseconds()  // Return the milliseconds (0-999)
new Date().getMinutes()       // Return the minutes (0-59)
new Date().getMonth()         // Return the month (0-11)
new Date().getSeconds()       // Return the seconds (0-59)
new Date().getTime()          // Return the time (milliseconds since January 1, 1970)

_x000D_
_x000D_
let dateObj = new Date();_x000D_
_x000D_
let myDate = (dateObj.getUTCFullYear()) + "/" + (dateObj.getMonth() + 1)+ "/" + (dateObj.getUTCDate());_x000D_
_x000D_
console.log(myDate)
_x000D_
_x000D_
_x000D_

// Return the minutes (0-59) new Date().getMonth() // Return the month (0-11) new Date().getSeconds() // Return the seconds (0-59) new Date().getTime() // Return the time (milliseconds since January 1, 1970)

Parse Json string in C#

Instead of an arraylist or dictionary you can also use a dynamic. Most of the time I use EasyHttp for this, but sure there will by other projects that do the same. An example below:

var http = new HttpClient();
http.Request.Accept = HttpContentTypes.ApplicationJson;
var response = http.Get("url");
var body = response.DynamicBody;
Console.WriteLine("Name {0}", body.AppName.Description);
Console.WriteLine("Name {0}", body.AppName.Value);

On NuGet: EasyHttp

Check if one list contains element from the other

With java 8, we can do like below to check if one list contains any element of other list

boolean var = lis1.stream().filter(element -> list2.contains(element)).findFirst().isPresent();

How to obtain Signing certificate fingerprint (SHA1) for OAuth 2.0 on Android?

Open terminal (in Unix, in MAC), (cmd in Windows) and cd to this (your java) path:

C:\Program Files\Java\jdk1.6.0_43\bin>

Run this command:

keytool -list -v -keystore C:\Users\leon\.android\debug.keystore -alias androiddebugkey -storepass android -keypass android

Just change the path to debug.keystore and you will get both MD5 and SHA-1 fingerprints.

How do I convert from int to Long in Java?

 //Suppose you have int and you wan to convert it to Long
 int i=78;
 //convert to Long
 Long l=Long.valueOf(i)

HTML form input tag name element array with JavaScript

Try this something like this:

var p_ids = document.forms[0].elements["p_id[]"];
alert(p_ids.length);
for (var i = 0, len = p_ids.length; i < len; i++) {
  alert(p_ids[i].value);
}

CSS: Responsive way to center a fluid div (without px width) while limiting the maximum width?

This might sound really simplistic...

But this will center the div inside the div, exactly in the center in relation to left and right margin or parent container, but you can adjust percentage symmetrically on left and right.

margin-right: 10%;
margin-left: 10%;

Then you can adjust % to make it as wide as you want it.

In Spring MVC, how can I set the mime type header when using @ResponseBody

Use ResponseEntity instead of ResponseBody. This way you have access to the response headers and you can set the appropiate content type. According to the Spring docs:

The HttpEntity is similar to @RequestBody and @ResponseBody. Besides getting access to the request and response body, HttpEntity (and the response-specific subclass ResponseEntity) also allows access to the request and response headers

The code will look like:

@RequestMapping(method=RequestMethod.GET, value="/fooBar")
public ResponseEntity<String> fooBar2() {
    String json = "jsonResponse";
    HttpHeaders responseHeaders = new HttpHeaders();
    responseHeaders.setContentType(MediaType.APPLICATION_JSON);
    return new ResponseEntity<String>(json, responseHeaders, HttpStatus.CREATED);
}

What is the pythonic way to detect the last element in a 'for' loop?

There can be multiple ways. slicing will be fastest. Adding one more which uses .index() method:

>>> l1 = [1,5,2,3,5,1,7,43]                                                 
>>> [i for i in l1 if l1.index(i)+1==len(l1)]                               
[43]

#ifdef in C#

I would recommend you using the Conditional Attribute!

Update: 3.5 years later

You can use #if like this (example copied from MSDN):

// preprocessor_if.cs
#define DEBUG
#define VC_V7
using System;
public class MyClass 
{
    static void Main() 
    {
#if (DEBUG && !VC_V7)
        Console.WriteLine("DEBUG is defined");
#elif (!DEBUG && VC_V7)
        Console.WriteLine("VC_V7 is defined");
#elif (DEBUG && VC_V7)
        Console.WriteLine("DEBUG and VC_V7 are defined");
#else
        Console.WriteLine("DEBUG and VC_V7 are not defined");
#endif
    }
}

Only useful for excluding parts of methods.

If you use #if to exclude some method from compilation then you will have to exclude from compilation all pieces of code which call that method as well (sometimes you may load some classes at runtime and you cannot find the caller with "Find all references"). Otherwise there will be errors.

If you use conditional compilation on the other hand you can still leave all pieces of code that call the method. All parameters will still be validated by the compiler. The method just won't be called at runtime. I think that it is way better to hide the method just once and not have to remove all the code that calls it as well. You are not allowed to use the conditional attribute on methods which return value - only on void methods. But I don't think this is a big limitation because if you use #if with a method that returns a value you have to hide all pieces of code that call it too.

Here is an example:


    // calling Class1.ConditionalMethod() will be ignored at runtime 
    // unless the DEBUG constant is defined


    using System.Diagnostics;
    class Class1 
    {
       [Conditional("DEBUG")]
       public static void ConditionalMethod() {
          Console.WriteLine("Executed Class1.ConditionalMethod");
       }
    }

Summary:

I would use #ifdef in C++ but with C#/VB I would use Conditional attribute. This way you hide the method definition without having to hide the pieces of code that call it. The calling code is still compiled and validated by the compiler, the method is not called at runtime though. You may want to use #if to avoid dependencies because with Conditional attribute your code is still compiled.

Java project in Eclipse: The type java.lang.Object cannot be resolved. It is indirectly referenced from required .class files

However trivial this might be, check your Java installation. For me, rt.jar was missing.

I found this after fiddling for half a day with Eclipse settings and getting nowhere. Desperate, I finally decided to try compiling the project from the command line. I wasn't expecting to see anything wrong since I thought it's an Eclipse issue but to my astonishment I saw this:

Error occurred during initialization of VM
java/lang/NoClassDefFoundError: java/lang/Object

I don't know what happened to my Java installation and where did rt.jar go. Anyway this comes as a reminder to go through the fail checklist and tick all the boxes no matter how unbelievable they are. It would have saved me a lot of time.

How to return images in flask response?

You use something like

from flask import send_file

@app.route('/get_image')
def get_image():
    if request.args.get('type') == '1':
       filename = 'ok.gif'
    else:
       filename = 'error.gif'
    return send_file(filename, mimetype='image/gif')

to send back ok.gif or error.gif, depending on the type query parameter. See the documentation for the send_file function and the request object for more information.

keycloak Invalid parameter: redirect_uri

Your redirect URI in your code(keycloak.init) should be the same as the redirect URI set on Keycloak server (client -> Valid Uri) click to view image of my code click to view my keycloak settings

How to get the android Path string to a file on Assets folder?

You can use this method.

    public static File getRobotCacheFile(Context context) throws IOException {
        File cacheFile = new File(context.getCacheDir(), "robot.png");
        try {
            InputStream inputStream = context.getAssets().open("robot.png");
            try {
                FileOutputStream outputStream = new FileOutputStream(cacheFile);
                try {
                    byte[] buf = new byte[1024];
                    int len;
                    while ((len = inputStream.read(buf)) > 0) {
                        outputStream.write(buf, 0, len);
                    }
                } finally {
                    outputStream.close();
                }
            } finally {
                inputStream.close();
            }
        } catch (IOException e) {
            throw new IOException("Could not open robot png", e);
        }
        return cacheFile;
    }

You should never use InputStream.available() in such cases. It returns only bytes that are buffered. Method with .available() will never work with bigger files and will not work on some devices at all.

In Kotlin (;D):

@Throws(IOException::class)
fun getRobotCacheFile(context: Context): File = File(context.cacheDir, "robot.png")
    .also {
        it.outputStream().use { cache -> context.assets.open("robot.png").use { it.copyTo(cache) } }
    }

What does $1 mean in Perl?

The variables $1 .. $9 are also read only variables so you can't implicitly assign a value to them:

$1 = 'foo'; print $1;

That will return an error: Modification of a read-only value attempted at script line 1.

You also can't use numbers for the beginning of variable names:

$1foo = 'foo'; print $1foo;

The above will also return an error.

How to solve Notice: Undefined index: id in C:\xampp\htdocs\invmgt\manufactured_goods\change.php on line 21

if you are getting id from url try

$id = (isset($_GET['id']) ? $_GET['id'] : '');

if getting from form you need to use POST method cause your form has method="post"

 $id = (isset($_POST['id']) ? $_POST['id'] : '');

For php notices use isset() or empty() to check values exist or not or initialize variable first with blank or a value

$id= '';

How can I draw circle through XML Drawable - Android?

no need for the padding or the corners.

here's a sample:

<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="oval" >
    <gradient android:startColor="#FFFF0000" android:endColor="#80FF00FF"
        android:angle="270"/>
</shape>

based on :

https://stackoverflow.com/a/10104037/878126

Positioning the colorbar

using padding pad

In order to move the colorbar relative to the subplot, one may use the pad argument to fig.colorbar.

import matplotlib.pyplot as plt
import numpy as np; np.random.seed(1)

fig, ax = plt.subplots(figsize=(4,4))
im = ax.imshow(np.random.rand(11,16))
ax.set_xlabel("x label")

fig.colorbar(im, orientation="horizontal", pad=0.2)
plt.show()

enter image description here

using an axes divider

One can use an instance of make_axes_locatable to divide the axes and create a new axes which is perfectly aligned to the image plot. Again, the pad argument would allow to set the space between the two axes.

import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1 import make_axes_locatable
import numpy as np; np.random.seed(1)

fig, ax = plt.subplots(figsize=(4,4))
im = ax.imshow(np.random.rand(11,16))
ax.set_xlabel("x label")

divider = make_axes_locatable(ax)
cax = divider.new_vertical(size="5%", pad=0.7, pack_start=True)
fig.add_axes(cax)
fig.colorbar(im, cax=cax, orientation="horizontal")

plt.show()

enter image description here

using subplots

One can directly create two rows of subplots, one for the image and one for the colorbar. Then, setting the height_ratios as gridspec_kw={"height_ratios":[1, 0.05]} in the figure creation, makes one of the subplots much smaller in height than the other and this small subplot can host the colorbar.

import matplotlib.pyplot as plt
import numpy as np; np.random.seed(1)

fig, (ax, cax) = plt.subplots(nrows=2,figsize=(4,4), 
                  gridspec_kw={"height_ratios":[1, 0.05]})
im = ax.imshow(np.random.rand(11,16))
ax.set_xlabel("x label")

fig.colorbar(im, cax=cax, orientation="horizontal")

plt.show()

enter image description here

Python: Get HTTP headers from urllib2.urlopen call?

Actually, it appears that urllib2 can do an HTTP HEAD request.

The question that @reto linked to, above, shows how to get urllib2 to do a HEAD request.

Here's my take on it:

import urllib2

# Derive from Request class and override get_method to allow a HEAD request.
class HeadRequest(urllib2.Request):
    def get_method(self):
        return "HEAD"

myurl = 'http://bit.ly/doFeT'
request = HeadRequest(myurl)

try:
    response = urllib2.urlopen(request)
    response_headers = response.info()

    # This will just display all the dictionary key-value pairs.  Replace this
    # line with something useful.
    response_headers.dict

except urllib2.HTTPError, e:
    # Prints the HTTP Status code of the response but only if there was a 
    # problem.
    print ("Error code: %s" % e.code)

If you check this with something like the Wireshark network protocol analazer, you can see that it is actually sending out a HEAD request, rather than a GET.

This is the HTTP request and response from the code above, as captured by Wireshark:

HEAD /doFeT HTTP/1.1
Accept-Encoding: identity
Host: bit.ly
Connection: close
User-Agent: Python-urllib/2.7

HTTP/1.1 301 Moved
Server: nginx
Date: Sun, 19 Feb 2012 13:20:56 GMT
Content-Type: text/html; charset=utf-8
Cache-control: private; max-age=90
Location: http://www.kidsidebyside.org/?p=445
MIME-Version: 1.0
Content-Length: 127
Connection: close
Set-Cookie: _bit=4f40f738-00153-02ed0-421cf10a;domain=.bit.ly;expires=Fri Aug 17 13:20:56 2012;path=/; HttpOnly

However, as mentioned in one of the comments in the other question, if the URL in question includes a redirect then urllib2 will do a GET request to the destination, not a HEAD. This could be a major shortcoming, if you really wanted to only make HEAD requests.

The request above involves a redirect. Here is request to the destination, as captured by Wireshark:

GET /2009/05/come-and-draw-the-circle-of-unity-with-us/ HTTP/1.1
Accept-Encoding: identity
Host: www.kidsidebyside.org
Connection: close
User-Agent: Python-urllib/2.7

An alternative to using urllib2 is to use Joe Gregorio's httplib2 library:

import httplib2

url = "http://bit.ly/doFeT"
http_interface = httplib2.Http()

try:
    response, content = http_interface.request(url, method="HEAD")
    print ("Response status: %d - %s" % (response.status, response.reason))

    # This will just display all the dictionary key-value pairs.  Replace this
    # line with something useful.
    response.__dict__

except httplib2.ServerNotFoundError, e:
    print (e.message)

This has the advantage of using HEAD requests for both the initial HTTP request and the redirected request to the destination URL.

Here's the first request:

HEAD /doFeT HTTP/1.1
Host: bit.ly
accept-encoding: gzip, deflate
user-agent: Python-httplib2/0.7.2 (gzip)

Here's the second request, to the destination:

HEAD /2009/05/come-and-draw-the-circle-of-unity-with-us/ HTTP/1.1
Host: www.kidsidebyside.org
accept-encoding: gzip, deflate
user-agent: Python-httplib2/0.7.2 (gzip)

How to remove trailing whitespaces with sed?

I have a script in my .bashrc that works under OSX and Linux (bash only !)

function trim_trailing_space() {
  if [[ $# -eq 0 ]]; then
    echo "$FUNCNAME will trim (in place) trailing spaces in the given file (remove unwanted spaces at end of lines)"
    echo "Usage :"
    echo "$FUNCNAME file"
    return
  fi
  local file=$1
  unamestr=$(uname)
  if [[ $unamestr == 'Darwin' ]]; then
    #specific case for Mac OSX
    sed -E -i ''  's/[[:space:]]*$//' $file
  else
    sed -i  's/[[:space:]]*$//' $file
  fi
}

to which I add:

SRC_FILES_EXTENSIONS="js|ts|cpp|c|h|hpp|php|py|sh|cs|sql|json|ini|xml|conf"

function find_source_files() {
  if [[ $# -eq 0 ]]; then
    echo "$FUNCNAME will list sources files (having extensions $SRC_FILES_EXTENSIONS)"
    echo "Usage :"
    echo "$FUNCNAME folder"
    return
  fi
  local folder=$1

  unamestr=$(uname)
  if [[ $unamestr == 'Darwin' ]]; then
    #specific case for Mac OSX
    find -E $folder -iregex '.*\.('$SRC_FILES_EXTENSIONS')'
  else
    #Rhahhh, lovely
    local extensions_escaped=$(echo $SRC_FILES_EXTENSIONS | sed s/\|/\\\\\|/g)
    #echo "extensions_escaped:$extensions_escaped"
    find $folder -iregex '.*\.\('$extensions_escaped'\)$'
  fi
}

function trim_trailing_space_all_source_files() {
  for f in $(find_source_files .); do trim_trailing_space $f;done
}

Base 64 encode and decode example code

something like

String source = "password"; 
byte[] byteArray;
try {
    byteArray = source.getBytes("UTF-16");
    System.out.println(new String(Base64.decode(Base64.encode(byteArray,
           Base64.DEFAULT), Base64.DEFAULT)));
} catch (UnsupportedEncodingException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}

How to export data as CSV format from SQL Server using sqlcmd?

You can run something like this:

sqlcmd -S MyServer -d myDB -E -Q "select col1, col2, col3 from SomeTable" 
       -o "MyData.csv" -h-1 -s"," -w 700
  • -h-1 removes column name headers from the result
  • -s"," sets the column seperator to ,
  • -w 700 sets the row width to 700 chars (this will need to be as wide as the longest row or it will wrap to the next line)

What's the fastest way to delete a large folder in Windows?

The worst way is to send to Recycle Bin: you still need to delete them. Next worst is shift+delete with Windows Explorer: it wastes loads of time checking the contents before starting deleting anything.

Next best is to use rmdir /s/q foldername from the command line. del /f/s/q foldername is good too, but it leaves behind the directory structure.

The best I've found is a two line batch file with a first pass to delete files and outputs to nul to avoid the overhead of writing to screen for every singe file. A second pass then cleans up the remaining directory structure:

del /f/s/q foldername > nul
rmdir /s/q foldername

This is nearly three times faster than a single rmdir, based on time tests with a Windows XP encrypted disk, deleting ~30GB/1,000,000 files/15,000 folders: rmdir takes ~2.5 hours, del+rmdir takes ~53 minutes. More info at Super User.

This is a regular task for me, so I usually move the stuff I need to delete to C:\stufftodelete and have those del+rmdir commands in a deletestuff.bat batch file. This is scheduled to run at night, but sometimes I need to run it during the day so the quicker the better.

Technet documentation for del command can be found here. Additional info on the parameters used above:

  • /f - Force (i.e. delete files even if they're read only)
  • /s - Recursive / Include Subfolders (this definition from SS64, as technet simply states "specified files", which isn't helpful).
  • /q - Quiet (i.e. do not prompt user for confirmation)

Documentation for rmdir here. Parameters are:

  • /s - Recursive (i.e. same as del's /s parameter)
  • /q - Quiet (i.e. same as del's /q parameter)

String Concatenation in EL

With EL 2 you can do the following:

#{'this'.concat(' is').concat(' a').concat(' test!')}