Programs & Examples On #Aspnetdb

Web.Config Debug/Release

The web.config transforms that are part of Visual Studio 2010 use XSLT in order to "transform" the current web.config file into its .Debug or .Release version.

In your .Debug/.Release files, you need to add the following parameter in your connection string fields:

xdt:Transform="SetAttributes" xdt:Locator="Match(name)"

This will cause each connection string line to find the matching name and update the attributes accordingly.

Note: You won't have to worry about updating your providerName parameter in the transform files, since they don't change.

Here's an example from one of my apps. Here's the web.config file section:

<connectionStrings>
      <add name="EAF" connectionString="[Test Connection String]" />
</connectionString>

And here's the web.config.release section doing the proper transform:

<connectionStrings>
      <add name="EAF" connectionString="[Prod Connection String]"
           xdt:Transform="SetAttributes"
           xdt:Locator="Match(name)" />
</connectionStrings>

One added note: Transforms only occur when you publish the site, not when you simply run it with F5 or CTRL+F5. If you need to run an update against a given config locally, you will have to manually change your Web.config file for this.

For more details you can see the MSDN documentation

https://msdn.microsoft.com/en-us/library/dd465326(VS.100).aspx

keyword not supported data source

I know this is an old post but I got the same error recently so for what it's worth, here's another solution:

This is usually a connection string error, please check the format of your connection string, you can look up 'entity framework connectionstring' or follow the suggestions above.

However, in my case my connection string was fine and the error was caused by something completely different so I hope this helps someone:

  1. First I had an EDMX error: there was a new database table in the EDMX and the table did not exist in my database (funny thing is the error the error was not very obvious because it was not shown in my EDMX or output window, instead it was tucked away in visual studio in the 'Error List' window under the 'Warnings'). I resolved this error by adding the missing table to my database. But, I was actually busy trying to add a stored procedure and still getting the 'datasource' error so see below how i resolved it:

  2. Stored procedure error: I was trying to add a stored procedure and everytime I added it via the EDMX design window I got a 'datasource' error. The solution was to add the stored procedure as blank (I kept the stored proc name and declaration but deleted the contents of the stored proc and replaced it with 'select 1' and retried adding it to the EDMX). It worked! Presumably EF didn't like something inside my stored proc. Once I'd added the proc to EF I was then able to update the contents of the proc on my database to what I wanted it to be and it works, 'datasource' error resolved.

weirdness

How do I implement IEnumerable<T>

Note that the IEnumerable<T> allready implemented by the System.Collections so another approach is to derive your MyObjects class from System.Collections as a base class (documentation):

System.Collections: Provides the base class for a generic collection.

We can later make our own implemenation to override the virtual System.Collections methods to provide custom behavior (only for ClearItems, InsertItem, RemoveItem, and SetItem along with Equals, GetHashCode, and ToString from Object). Unlike the List<T> which is not designed to be easily extensible.

Example:

public class FooCollection : System.Collections<Foo>
{
    //...
    protected override void InsertItem(int index, Foo newItem)
    {
        base.InsertItem(index, newItem);     
        Console.Write("An item was successfully inserted to MyCollection!");
    }
}

public static void Main()
{
    FooCollection fooCollection = new FooCollection();
    fooCollection.Add(new Foo()); //OUTPUT: An item was successfully inserted to FooCollection!
}

Please note that driving from collection recommended only in case when custom collection behavior is needed, which is rarely happens. see usage.

How to add spacing between UITableViewCell

If you don't want to change the section and row number of your table view (like I did), here's what you do:

1) Add an ImageView to the bottom of your table cell view.

2) Make it the same colour as the background colour of the table view.

I've done this in my application and it works perfectly. Cheers! :D

How do you push a Git tag to a branch using a refspec?

I create the tag like this and then I push it to GitHub:

git tag -a v1.1 -m "Version 1.1 is waiting for review"
git push --tags

Counting objects: 1, done.
Writing objects: 100% (1/1), 180 bytes, done.
Total 1 (delta 0), reused 0 (delta 0)
To [email protected]:neoneye/triangle_draw.git
 * [new tag]         v1.1 -> v1.1

Match linebreaks - \n or \r\n?

This only applies to question 1.

I have an app that runs on Windows and uses a multi-line MFC editor box.
The editor box expects CRLF linebreaks, but I need to parse the text enterred
with some really big/nasty regexs'.

I didn't want to be stressing about this while writing the regex, so
I ended up normalizing back and forth between the parser and editor so that
the regexs' just use \n. I also trap paste operations and convert them for the boxes.

This does not take much time.
This is what I use.

 boost::regex  CRLFCRtoLF (
     " \\r\\n | \\r(?!\\n) "
     , MODx);

 boost::regex  CRLFCRtoCRLF (
     " \\r\\n?+ | \\n "
     , MODx);


 // Convert (All style) linebreaks to linefeeds 
 // ---------------------------------------
 void ReplaceCRLFCRtoLF( string& strSrc, string& strDest )
 {
    strDest  = boost::regex_replace ( strSrc, CRLFCRtoLF, "\\n" );
 }

 // Convert linefeeds to linebreaks (Windows) 
 // ---------------------------------------
 void ReplaceCRLFCRtoCRLF( string& strSrc, string& strDest )
 {
    strDest  = boost::regex_replace ( strSrc, CRLFCRtoCRLF, "\\r\\n" );
 }

How can I get a List from some class properties with Java 8 Stream?

You can use map :

List<String> names = 
    personList.stream()
              .map(Person::getName)
              .collect(Collectors.toList());

EDIT :

In order to combine the Lists of friend names, you need to use flatMap :

List<String> friendNames = 
    personList.stream()
              .flatMap(e->e.getFriends().stream())
              .collect(Collectors.toList());

How do I skip a header from CSV files in Spark?

In Spark 2.0 a CSV reader is build into Spark, so you can easily load a CSV file as follows:

spark.read.option("header","true").csv("filePath")

Convert alphabet letters to number in Python

What about something like this:

print [ord(char) - 96 for char in raw_input('Write Text: ').lower()]

ord
list comprehension
ASCII character codes

EDIT
Since you asked me to explain I will... though it has been explained pretty well in the comments already by [?].

Let's do this in more that one line to start.

input = raw_input('Write Text: ')
input = input.lower()
output = []
for character in input:
    number = ord(character) - 96
    output.append(number)
print output

This does the same thing, but is more readable. Make sure you can understand what is going on here before you try to understand my first answer. Everything here is pretty standard, simple Python. The one thing to note is the ord function. ord stand for ordinal, and pretty much every high level language will have this type of function available. It gives you a mapping to the numerical representation of any character. The inverse function of ord is called chr.

chr(ord('x')) == 'x' # for any character, not just x.

If you test for yourself, the ordinal of a is 97 (the third link I posted above will show the complete ASCII character set.) Each lower case letter is in the range 97-122 (26 characters.) So, if you just subtract 96 from the ordinal of any lower case letter, you will get its position in the alphabet assuming you take 'a' == 1. So, ordinal of 'b' == 98, 'c' == 99, etc. When you subtract 96, 'b' == 2, 'c' == 3, etc.

The rest of the initial solution I posted is just some Python trickery you can learn called list comprehension. But, I wouldn't focus on that as much as I would focus on learning to solve the problem in any language, where ord is your friend. I hope this helps.

how to console.log result of this ajax call?

Why not handle the error within the call?

i.e.

$.ajax({
    type: 'POST',
    url: 'loginCheck',
    data: $(formLogin).serialize(),
    dataType: 'json',
    error: function(req, err){ console.log('my message' + err); }
});

how to delete default values in text field using selenium?

The following function will delete the input character one by one till the input field is empty using PromiseWhile

driver.clearKeys = function(element, value){
  return element.getAttribute('value').then(function(val) {
    if (val.length > 0) {
      return new Promise(function(resolve, reject) {
        var len;
        len = val.length;
        return promiseWhile(function() { 
          return 0 < len;
        }, function() {
          return new Promise(function(resolve, reject) {
            len--;
            return element.sendKeys(webdriver.Key.BACK_SPACE).then(function()              {
              return resolve(true);
            });
          });
        }).then(function() {
          return resolve(true);
        });
      });
    }

How to urlencode data for curl command?

I've found the following snippet useful to stick it into a chain of program calls, where URI::Escape might not be installed:

perl -p -e 's/([^A-Za-z0-9])/sprintf("%%%02X", ord($1))/seg'

(source)

Does "display:none" prevent an image from loading?

we're talking about images not loading on mobile, right? so what if you just did an @media (min-width: 400px){background-image:thing.jpg}

wouldn't it then only look for the image at above a certain screen width?

How do I test if a recordSet is empty? isNull?

I would check the "End of File" flag:

If temp_rst1.EOF Or temp_rst2.EOF Then MsgBox "null"

Meaning of end='' in the statement print("\t",end='')?

The default value of end is \n meaning that after the print statement it will print a new line. So simply stated end is what you want to be printed after the print statement has been executed

Eg: - print ("hello",end=" +") will print hello +

ASP.NET MVC passing an ID in an ActionLink to the controller

Doesn't look like you are using the correct overload of ActionLink. Try this:-

<%=Html.ActionLink("Modify Villa", "Modify", new {id = "1"})%>

This assumes your view is under the /Views/Villa folder. If not then I suspect you need:-

<%=Html.ActionLink("Modify Villa", "Modify", "Villa", new {id = "1"}, null)%>

AttributeError: 'numpy.ndarray' object has no attribute 'append'

Use numpy.concatenate(list1 , list2) or numpy.append() Look into the thread at Append a NumPy array to a NumPy array.

Convert string to buffer Node

Note: Just reposting John Zwinck's comment as answer.

One issue might be that you are using a older version of Node (for the moment, I cannot upgrade, codebase struck with v4.3.1). Simple solution here is, using the deprecated way:

new Buffer(bufferStr)

Note #2: This is for people struck in older version, for whom Buffer.from does not work

The specified DSN contains an architecture mismatch between the Driver and Application. JAVA

Have you created the DSN first in Control Panel>Administrative Tools>ODBC>System DSN. Name it same as "myDatabase" and if i is asking for locating the database/access file specify the path using browse option. Once ur DSN will be created successfully you will be easily able to access ur DB.

Import JavaScript file and call functions using webpack, ES6, ReactJS

import * as utils from './utils.js'; 

If you do the above, you will be able to use functions in utils.js as

utils.someFunction()

Defining constant string in Java?

simply use

final String WELCOME_MESSAGE = "Hello, welcome to the server";

the main part of this instruction is the 'final' keyword.

Convert an NSURL to an NSString

Try this in Swift :

var urlString = myUrl.absoluteString

Objective-C:

NSString *urlString = [myURL absoluteString];

Group query results by month and year in postgresql

bma answer is great! I have used it with ActiveRecords, here it is if anybody needs it in Rails:

Model.find_by_sql(
  "SELECT TO_CHAR(created_at, 'Mon') AS month,
   EXTRACT(year from created_at) as year,
   SUM(desired_value) as desired_value
   FROM desired_table
   GROUP BY 1,2
   ORDER BY 1,2"
)

fatal: could not create work tree dir 'kivy'

I had the same error on Debian and all I had to do was:

sudo su

and then run the command again and it worked.

How do I convert number to string and pass it as argument to Execute Process Task?

Expression: "Total Count: " + (DT_WSTR, 5)@[User::Cnt]

Facebook Like-Button - hide count?

If you're using Facebook's javascript like button (so you can capture like events), here's what we had to do:

Due to a change Facebook recently made in the way comment dialogs display, we had to change how we were hiding it. The way they show the comment dialog has been 'moving' the content inside of the my overflow:hidden element so that the button looks really odd to the user after they click the like button.

In addition to adding a wrapping element with an 'overflow:none' style, you will need to hide the comment element that Facebook is putting onto your page:

Styles:

span.no_overflow {
  overflow: none;
  width: 50px;
}

.no_overflow span.fb_edge_comment_widget.fb_iframe_widget {
  display: none;
}

Markup:

<span class="no_overflow">
<fb:like></fb:like>
</span>

We're still using the fb:like markup though. I have not tested this with the new div-based markup that Facebook is providing on their site now.

How to replace multiple patterns at once with sed?

This might work for you (GNU sed):

sed -r '1{x;s/^/:abbc:bcab/;x};G;s/^/\n/;:a;/\n\n/{P;d};s/\n(ab|bc)(.*\n.*:(\1)([^:]*))/\4\n\2/;ta;s/\n(.)/\1\n/;ta' file

This uses a lookup table which is prepared and held in the hold space (HS) and then appended to each line. An unique marker (in this case \n) is prepended to the start of the line and used as a method to bump-along the search throughout the length of the line. Once the marker reaches the end of the line the process is finished and is printed out the lookup table and markers being discarded.

N.B. The lookup table is prepped at the very start and a second unique marker (in this case :) chosen so as not to clash with the substitution strings.

With some comments:

sed -r '
  # initialize hold with :abbc:bcab
  1 {
    x
    s/^/:abbc:bcab/
    x
  }

  G        # append hold to patt (after a \n)

  s/^/\n/  # prepend a \n

  :a

  /\n\n/ {
    P      # print patt up to first \n
    d      # delete patt & start next cycle
  }

  s/\n(ab|bc)(.*\n.*:(\1)([^:]*))/\4\n\2/
  ta       # goto a if sub occurred

  s/\n(.)/\1\n/  # move one char past the first \n
  ta       # goto a if sub occurred
'

The table works like this:

   **   **   replacement
:abbc:bcab
 **   **     pattern

Efficient way to apply multiple filters to pandas DataFrame or Series

Why not do this?

def filt_spec(df, col, val, op):
    import operator
    ops = {'eq': operator.eq, 'neq': operator.ne, 'gt': operator.gt, 'ge': operator.ge, 'lt': operator.lt, 'le': operator.le}
    return df[ops[op](df[col], val)]
pandas.DataFrame.filt_spec = filt_spec

Demo:

df = pd.DataFrame({'a': [1,2,3,4,5], 'b':[5,4,3,2,1]})
df.filt_spec('a', 2, 'ge')

Result:

   a  b
 1  2  4
 2  3  3
 3  4  2
 4  5  1

You can see that column 'a' has been filtered where a >=2.

This is slightly faster (typing time, not performance) than operator chaining. You could of course put the import at the top of the file.

iTerm 2: How to set keyboard shortcuts to jump to beginning/end of line?

I used Travis answer and I created a dynamic profile you can import based on its instructions.

GabLeRoux/iterm2-macos-dynamic-profile

Instructions are in the readme and it's a lot faster to import this than it is to add them all manually. I made this an answer as per @gooli's request because this was hidden in a comment. Hope you enjoy this

How to set Java environment path in Ubuntu

Create/Open ~/.bashrc file $vim ~/.bashrc Add JAVA_HOME and PATH as refering to your JDK path

export JAVA_HOME=/usr/java/<your version of java>
export PATH=${PATH}:${JAVA_HOME}/bin

Save file

Now type java - version it should display what you set in .bashrc file. This will persisted over session as wel.

Example :

enter image description here

enter image description here

jQuery: select an element's class and id at the same time?

How about this code?

$("a.save#country")

How to pass a PHP variable using the URL

All the above answers are correct, but I noticed something very important. Leaving a space between the variable and the equal sign might result in a problem. For example, (?variablename =value)

ErrorActionPreference and ErrorAction SilentlyContinue for Get-PSSessionConfiguration

Tip #2

Can't you use the classical 2> redirection operator.

(Get-PSSessionConfiguration -Name "MyShellUri" -ErrorAction SilentlyContinue) 2> $NULL
if(!$?){
   'foo'
}

I don't like errors so I avoid them at all costs.

How to get the seconds since epoch from the time + date output of gmtime()?

ep = datetime.datetime(1970,1,1,0,0,0)
x = (datetime.datetime.utcnow()- ep).total_seconds()

This should be different from int(time.time()), but it is safe to use something like x % (60*60*24)

datetime — Basic date and time types:

Unlike the time module, the datetime module does not support leap seconds.

Android : Capturing HTTP Requests with non-rooted android device

SandroProxy seems to be better than Drony (by the same developer): You can (but do not have to) conveniently view and analyze the traffic in your PC's browser.

Should work in emulators as well.

How to run a function when the page is loaded?

Rather than using jQuery or window.onload, native JavaScript has adopted some great functions since the release of jQuery. All modern browsers now have their own DOM ready function without the use of a jQuery library.

I'd recommend this if you use native Javascript.

document.addEventListener('DOMContentLoaded', function() {
    alert("Ready!");
}, false);

How to scroll HTML page to given anchor?

Most answers are unnecessarily complicated.

If you just want to jump to the target element, you don't need JavaScript:

# the link:
<a href="#target">Click here to jump.</a>

# target element:
<div id="target">Any kind of element.</div>

If you want to scroll to the target animatedly, please refer to @Shahil's answer.

Where to install Android SDK on Mac OS X?

I put mine in /Developer/SDKs I had to authenticate to do that…but since there's no consensus I thought that it sounded like a place I'd remember.

How can I use jQuery to move a div across the screen

In jQuery 1.2 and newer you no longer have to position the element absolutely; you can use normal relative positioning and use += or -= to add to or subtract from properties, e.g.

$("#startAnimation").click(function(){
    $(".toBeAnimated").animate({ 
        marginLeft: "+=250px",
    }, 1000 );
});

And to echo the guy who answered first's advice: Javascript is not performant. Don't overuse animations, or expect things than run nice and fast on your high performance PC on Chrome to look good on a bog-standard PC running IE. Test it, and make sure it degrades well!

how to make twitter bootstrap submenu to open on the left side?

Only thing you have to do is

 <ul style='left:-100%'> 

of the menu which you want to display on RIGHT side.

How to output only captured groups with sed?

you can use grep

grep -Eow "[0-9]+" file

Define an <img>'s src attribute in CSS

just this as img tag is a content element

img {
    content:url(http://example.com/image.png);
}

npm command to uninstall or prune unused packages in Node.js

If you're not worried about a couple minutes time to do so, a solution would be to rm -rf node_modules and npm install again to rebuild the local modules.

Checking for empty or null List<string>

For anyone who doesn't have the guarantee that the list will not be null, you can use the null-conditional operator to safely check for null and empty lists in a single conditional statement:

if (list?.Any() != true)
{
    // Handle null or empty list
}

Aggregate function in SQL WHERE-Clause

UPDATED query:

select id from t where id < (select max(id) from t);

It'll select all but the last row from the table t.

Git command to checkout any branch and overwrite local changes

You could follow a solution similar to "How do I force “git pull” to overwrite local files?":

git fetch --all
git reset --hard origin/abranch
git checkout $branch 

That would involve only one fetch.

With Git 2.23+, git checkout is replaced here with git switch (presented here) (still experimental).

git switch -f $branch

(with -f being an alias for --discard-changes, as noted in Jan's answer)

Proceed even if the index or the working tree differs from HEAD.
Both the index and working tree are restored to match the switching target.

SQL Server 2008 Insert with WHILE LOOP

First of all I'd like to say that I 100% agree with John Saunders that you must avoid loops in SQL in most cases especially in production.

But occasionally as a one time thing to populate a table with a hundred records for testing purposes IMHO it's just OK to indulge yourself to use a loop.

For example in your case to populate your table with records with hospital ids between 16 and 100 and make emails and descriptions distinct you could've used

CREATE PROCEDURE populateHospitals
AS
DECLARE @hid INT;
SET @hid=16;
WHILE @hid < 100
BEGIN 
    INSERT hospitals ([Hospital ID], Email, Description) 
    VALUES(@hid, 'user' + LTRIM(STR(@hid)) + '@mail.com', 'Sample Description' + LTRIM(STR(@hid))); 
    SET @hid = @hid + 1;
END

And result would be

ID   Hospital ID Email            Description          
---- ----------- ---------------- ---------------------
1    16          [email protected]  Sample Description16 
2    17          [email protected]  Sample Description17 
...                                                    
84   99          [email protected]  Sample Description99 

How do I get whole and fractional parts from double in JSP/Java?

The original question asked for the exponent and mantissa, rather than the fractional and whole part.

To get the exponent and mantissa from a double you can convert it into the IEEE 754 representation and extract the bits like this:

long bits = Double.doubleToLongBits(3.25);

boolean isNegative = (bits & 0x8000000000000000L) != 0; 
long exponent      = (bits & 0x7ff0000000000000L) >> 52;
long mantissa      =  bits & 0x000fffffffffffffL;

How do you tell if a string contains another string in POSIX sh?

Here is a link to various solutions of your issue.

This is my favorite as it makes the most human readable sense:

The Star Wildcard Method

if [[ "$string" == *"$substring"* ]]; then
    return 1
fi
return 0

How to call a function in shell Scripting?

Example of using a function() in bash:

#!/bin/bash
# file.sh: a sample shell script to demonstrate the concept of Bash shell functions
# define usage function
usage(){
    echo "Usage: $0 filename"
    exit 1
}

# define is_file_exists function
# $f -> store argument passed to the script
is_file_exists(){
    local f="$1"
    [[ -f "$f" ]] && return 0 || return 1
}
# invoke  usage
# call usage() function if filename not supplied
[[ $# -eq 0 ]] && usage

# Invoke is_file_exits
if ( is_file_exists "$1" )
then
 echo "File found: $1"
else
 echo "File not found: $1"
fi

How to get a function name as a string?

my_function.func_name

There are also other fun properties of functions. Type dir(func_name) to list them. func_name.func_code.co_code is the compiled function, stored as a string.

import dis
dis.dis(my_function)

will display the code in almost human readable format. :)

ERROR: Google Maps API error: MissingKeyMapError

As per Google recent announcement, usage of the Google Maps APIs now requires a key. If you are using the Google Maps API on localhost or your domain was not active prior to June 22nd, 2016, it will require a key going forward. Please see the Google Maps APIs documentation to get a key and add it to your application.

Is it possible to include one CSS file in another?

In some cases it is possible using @import "file.css", and most modern browsers should support this, older browsers such as NN4, will go slightly nuts.

Note: the import statement must precede all other declarations in the file, and test it on all your target browsers before using it in production.

Access multiple elements of list knowing their index

Kind of pythonic way:

c = [x for x in a if a.index(x) in b]

How to get the body's content of an iframe in Javascript?

AFAIK, an Iframe cannot be used that way. You need to point its src attribute to another page.

Here's how to get its body content using plane old javascript. This works with both IE and Firefox.

function getFrameContents(){
   var iFrame =  document.getElementById('id_description_iframe');
   var iFrameBody;
   if ( iFrame.contentDocument ) 
   { // FF
     iFrameBody = iFrame.contentDocument.getElementsByTagName('body')[0];
   }
   else if ( iFrame.contentWindow ) 
   { // IE
     iFrameBody = iFrame.contentWindow.document.getElementsByTagName('body')[0];
   }
    alert(iFrameBody.innerHTML);
 }

How do I include inline JavaScript in Haml?

You can actually do what Chris Chalmers does in his answer, but you must make sure that HAML doesn't parse the JavaScript. This approach is actually useful when you need to use a different type than text/javascript, which is was I needed to do for MathJax.

You can use the plain filter to keep HAML from parsing the script and throwing an illegal nesting error:

%script{type: "text/x-mathjax-config"}
  :plain
    MathJax.Hub.Config({
      tex2jax: {
        inlineMath: [["$","$"],["\\(","\\)"]]
      }
    });

What's the difference between including files with JSP include directive, JSP include action and using JSP Tag Files?

Main advantage of <jsp:include /> over <%@ include > is:

<jsp:include /> allows to pass parameters

<jsp:include page="inclusion.jsp">
    <jsp:param name="menu" value="objectValue"/>
</jsp:include>

which is not possible in <%@include file="somefile.jsp" %>

The smallest difference between 2 Angles

I rise to the challenge of providing the signed answer:

def f(x,y):
  import math
  return min(y-x, y-x+2*math.pi, y-x-2*math.pi, key=abs)

Can you issue pull requests from the command line on GitHub?

Git now ships with a subcommand 'git request-pull' [-p] <start> <url> [<end>]

You can see the docs here

You may find this useful but it is not exactly the same as GitHub's feature.

How to add a new object (key-value pair) to an array in javascript?

.push() will add elements to the end of an array.

Use .unshift() if need to add some element to the beginning of array i.e:

items.unshift({'id':5});

Demo:

_x000D_
_x000D_
items = [{'id': 1}, {'id': 2}, {'id': 3}, {'id': 4}];_x000D_
items.unshift({'id': 0});_x000D_
console.log(items);
_x000D_
_x000D_
_x000D_

And use .splice() in case you want to add object at a particular index i.e:

items.splice(2, 0, {'id':5});
           // ^ Given object will be placed at index 2...

Demo:

_x000D_
_x000D_
items = [{'id': 1}, {'id': 2}, {'id': 3}, {'id': 4}];_x000D_
items.splice(2, 0, {'id': 2.5});_x000D_
console.log(items);
_x000D_
_x000D_
_x000D_

string.split - by multiple character delimiter

More fast way using directly a no-string array but a string:

string[] StringSplit(string StringToSplit, string Delimitator)
{
    return StringToSplit.Split(new[] { Delimitator }, StringSplitOptions.None);
}

StringSplit("E' una bella giornata oggi", "giornata");
/* Output
[0] "E' una bella giornata"
[1] " oggi"
*/

Tensorflow set CUDA_VISIBLE_DEVICES within jupyter

You can do it faster without any imports just by using magics:

%env CUDA_DEVICE_ORDER=PCI_BUS_ID
%env CUDA_VISIBLE_DEVICES=0

Notice that all env variable are strings, so no need to use ". You can verify that env-variable is set up by running: %env <name_of_var>. Or check all of them with %env.

JavaScript adding decimal numbers issue

function add(){
    var first=parseFloat($("#first").val());
    var second=parseFloat($("#second").val());
    $("#result").val(+(first+second).toFixed(2));
}

DEMO.

How to logout and redirect to login page using Laravel 5.4?

I recommend you stick with Laravel auth routes in web.php: Auth::routes()

It will create the following route:

POST | logout | App\Http\Controllers\Auth\LoginController@logout

You will need to logout using a POST form. This way you will also need the CSRF token which is recommended.

<form method="POST" action="{{ route('logout') }}">
  @csrf
  <button type="submit">Logout</button>
</form>

OkHttp Post Body as JSON

You can create your own JSONObject then toString().

Remember run it in the background thread like doInBackground in AsyncTask.

OkHttp version > 4:

// create your json here
JSONObject jsonObject = new JSONObject();
try {
    jsonObject.put("KEY1", "VALUE1");
    jsonObject.put("KEY2", "VALUE2");
} catch (JSONException e) {
    e.printStackTrace();
}

val client = OkHttpClient()
val mediaType = "application/json; charset=utf-8".toMediaType()
val body = jsonObject.toString().toRequestBody(mediaType)
val request: Request = Request.Builder()
            .url("https://YOUR_URL/")
            .post(body)
            .build()

var response: Response? = null
try {
    response = client.newCall(request).execute()
    val resStr = response.body!!.string()
} catch (e: IOException) {
    e.printStackTrace()
}
   

OkHttp version 3:

// create your json here
JSONObject jsonObject = new JSONObject();
try {
    jsonObject.put("KEY1", "VALUE1");
    jsonObject.put("KEY2", "VALUE2");
} catch (JSONException e) {
    e.printStackTrace();
}

  OkHttpClient client = new OkHttpClient();
  MediaType JSON = MediaType.parse("application/json; charset=utf-8");
  // put your json here
  RequestBody body = RequestBody.create(JSON, jsonObject.toString());
  Request request = new Request.Builder()
                    .url("https://YOUR_URL/")
                    .post(body)
                    .build();

  Response response = null;
  try {
      response = client.newCall(request).execute();
      String resStr = response.body().string();
  } catch (IOException e) {
      e.printStackTrace();
  }

JavaScript operator similar to SQL "like"

You can use regular expressions in Javascript to do pattern matching of strings.

For example:

var s = "hello world!";
if (s.match(/hello.*/)) {
  // do something
}

The match() test is much like WHERE s LIKE 'hello%' in SQL.

How to change values in a tuple?

As Hunter McMillen mentioned, tuples are immutable, you need to create a new tuple in order to achieve this. For instance:

>>> tpl = ('275', '54000', '0.0', '5000.0', '0.0')
>>> change_value = 200
>>> tpl = (change_value,) + tpl[1:]
>>> tpl
(200, '54000', '0.0', '5000.0', '0.0')

How can I change column types in Spark SQL's DataFrame?

Using Spark Sql 2.4.0 you can do that:

spark.sql("SELECT STRING(NULLIF(column,'')) as column_string")

ASP.NET Custom Validator Client side & Server Side validation not firing

Thanks for that info on the ControlToValidate LukeH!

What I was trying to do in my code was to only ensure that some text field A has some text in the field when text field B has a particular value. Otherwise, A can be blank or whatever else. Getting rid of the ControlToValidate="A" in my mark up fixed the issue for me.

Cheers!

How to default to other directory instead of home directory

Right-click the Git Bash application link go to Properties and modify the Start in location to be the location you want it to start from.

Split bash string by newline characters

Another way:

x=$'Some\nstring'
readarray -t y <<<"$x"

Or, if you don't have bash 4, the bash 3.2 equivalent:

IFS=$'\n' read -rd '' -a y <<<"$x"

You can also do it the way you were initially trying to use:

y=(${x//$'\n'/ })

This, however, will not function correctly if your string already contains spaces, such as 'line 1\nline 2'. To make it work, you need to restrict the word separator before parsing it:

IFS=$'\n' y=(${x//$'\n'/ })

...and then, since you are changing the separator, you don't need to convert the \n to space anymore, so you can simplify it to:

IFS=$'\n' y=($x)

This approach will function unless $x contains a matching globbing pattern (such as "*") - in which case it will be replaced by the matched file name(s). The read/readarray methods require newer bash versions, but work in all cases.

How to check whether Kafka Server is running?

The good option is to use AdminClient as below before starting to produce or consume the messages

private static final int ADMIN_CLIENT_TIMEOUT_MS = 5000;           
 try (AdminClient client = AdminClient.create(properties)) {
            client.listTopics(new ListTopicsOptions().timeoutMs(ADMIN_CLIENT_TIMEOUT_MS)).listings().get();
        } catch (ExecutionException ex) {
            LOG.error("Kafka is not available, timed out after {} ms", ADMIN_CLIENT_TIMEOUT_MS);
            return;
        }

Javascript: getFullyear() is not a function

Try this...

 var start = new Date(document.getElementById('Stardate').value);
 var y = start.getFullYear();

Get protocol, domain, and port from URL

As has already been mentioned there is the as yet not fully supported window.location.origin but instead of either using it or creating a new variable to use, I prefer to check for it and if it isn't set to set it.

For example;

if (!window.location.origin) {
  window.location.origin = window.location.protocol + "//" + window.location.hostname + (window.location.port ? ':' + window.location.port: '');
}

I actually wrote about this a few months back A fix for window.location.origin

Are types like uint32, int32, uint64, int64 defined in any stdlib header?

If you are using C99 just include stdint.h. BTW, the 64bit types are there iff the processor supports them.

How do I profile memory usage in Python?

Below is a simple function decorator which allows to track how much memory the process consumed before the function call, after the function call, and what is the difference:

import time
import os
import psutil
 
 
def elapsed_since(start):
    return time.strftime("%H:%M:%S", time.gmtime(time.time() - start))
 
 
def get_process_memory():
    process = psutil.Process(os.getpid())
    mem_info = process.memory_info()
    return mem_info.rss
 
 
def profile(func):
    def wrapper(*args, **kwargs):
        mem_before = get_process_memory()
        start = time.time()
        result = func(*args, **kwargs)
        elapsed_time = elapsed_since(start)
        mem_after = get_process_memory()
        print("{}: memory before: {:,}, after: {:,}, consumed: {:,}; exec time: {}".format(
            func.__name__,
            mem_before, mem_after, mem_after - mem_before,
            elapsed_time))
        return result
    return wrapper

Here is my blog which describes all the details. (archived link)

What does [object Object] mean?

It's the value returned by that object's toString() function.


I understand what you're trying to do, because I answered your question yesterday about determining which div is visible. :)
The whichIsVisible() function returns an actual jQuery object, because I thought that would be more programmatically useful. If you want to use this function for debugging purposes, you can just do something like this:

function whichIsVisible_v2()
{
    if (!$1.is(':hidden')) return '#1';
    if (!$2.is(':hidden')) return '#2';
}

That said, you really should be using a proper debugger rather than alert() if you're trying to debug a problem. If you're using Firefox, Firebug is excellent. If you're using IE8, Safari, or Chrome, they have built-in debuggers.

Check if url contains string with JQuery

use href with indexof

<script type="text/javascript">
 $(document).ready(function () {
   if(window.location.href.indexOf("added-to-cart=555") > -1) {
   alert("your url contains the added-to-cart=555");
  }
});
</script>

Kotlin unresolved reference in IntelliJ

Sometimes this could happen because you are trying to use a project with incompatible versions of Kotlin plugin in Gradle with plugin in your IDE. Check the versions of org.jetbrains.kotlin.jvm and other Kotlin plugins in build.gradle, and version of installed kotlin plugin in your IDE, and try to make it similar:

enter image description here

enter image description here

Adding options to select with javascript

Often you have an array of related records, I find it easy and fairly declarative to fill select this way:

selectEl.innerHTML = array.map(c => '<option value="'+c.id+'">'+c.name+'</option>').join('');

This will replace existing options.
You can use selectEl.insertAdjacentHTML('afterbegin', str); to add them to the top instead.
And selectEl.insertAdjacentHTML('beforeend', str); to add them to the bottom of the list.

IE11 compatible syntax:

array.map(function (c) { return '<option value="'+c.id+'">'+c.name+'</option>'; }).join('');

How to find the number of days between two dates

As @Forte L. mentioned you can do the following as well;

SELECT dtCreated
    , bActive
    , dtLastPaymentAttempt
    , dtLastUpdated
    , dtLastVisit

    , DATEDIFF(day, dtCreated, dtLastUpdated) Difference

FROM Customers
WHERE (bActive = 'true') 
    AND (dtLastUpdated > CONVERT(DATETIME, '2012-01-0100:00:00', 102))

Problems with entering Git commit message with Vim

I am assuming you are using msys git. If you are, the editor that is popping up to write your commit message is vim. Vim is not friendly at first. You may prefer to switch to a different editor. If you want to use a different editor, look at this answer: How do I use Notepad++ (or other) with msysgit?

If you want to use vim, type i to type in your message. When happy hit ESC. Then type :wq, and git will then be happy.

Or just type git commit -m "your message here" to skip the editor altogether.

Masking password input from the console : Java

If you're dealing with a Java character array (such as password characters that you read from the console), you can convert it to a JRuby string with the following Ruby code:

# GIST: "pw_from_console.rb" under "https://gist.github.com/drhuffman12"

jconsole = Java::java.lang.System.console()
password = jconsole.readPassword()
ruby_string = ''
password.to_a.each {|c| ruby_string << c.chr}

# .. do something with 'password' variable ..    
puts "password_chars: #{password_chars.inspect}"
puts "password_string: #{password_string}"

See also "https://stackoverflow.com/a/27628738/4390019" and "https://stackoverflow.com/a/27628756/4390019"

How to install Jdk in centos

I advise you to use the same JDK as you may use with Windows: the Oracle one.

http://www.oracle.com/technetwork/java/javase/downloads/index.html
Go to the Java SE 7u67 section and click on JDK7 Download button on the right.

On the new page select the option "(¤) Accept License Agreement"
Then click on jdk-7u67-linux-x64.rpm

On your CentOS, as root, run:

$ rpm -Uvh jdk-7u67-linux-x64.rpm
$ alternatives --install /usr/bin/java java /usr/java/latest/bin/java 2

You may already have a Java 5 installed on your box... before installing the downloaded rpm remove previous Java by running this command yum remove java

Javascript loop through object array?

To reference the contents of the single array containing one or more objects i.e. everything in the brackets of something like this {messages: [{"a":1,"b":2}] } ,just add [0] to the query to get the first array element

e.g. messages[0] will reference the object {"a":1,"b":2} as opposed to just messages which would reference the entire array [{"a":1,"b":2}]

from there you can work with the result as typical object and use Object.keys for example to get "a" and "b".

unsigned APK can not be installed

You can test the unsigned-apk only on Emulator. And as its step of application deployment and distribution, you should read this article atleast once, i suggest: http://developer.android.com/guide/publishing/app-signing.html.

For your question, you can find the below line in above article:

All applications must be signed. The system will not install an application that is not signed.

so you have to have signed-apk before the distribution of your application.

To generate Signed-apk of your application, there is a simple wizard procedure, click on File -> Export -> Android -> Export Android application.

enter image description here

What is the best way to get all the divisors of a number?

To expand on what Shimi has said, you should only be running your loop from 1 to the square root of n. Then to find the pair, do n / i, and this will cover the whole problem space.

As was also noted, this is a NP, or 'difficult' problem. Exhaustive search, the way you are doing it, is about as good as it gets for guaranteed answers. This fact is used by encryption algorithms and the like to help secure them. If someone were to solve this problem, most if not all of our current 'secure' communication would be rendered insecure.

Python code:

import math

def divisorGenerator(n):
    large_divisors = []
    for i in xrange(1, int(math.sqrt(n) + 1)):
        if n % i == 0:
            yield i
            if i*i != n:
                large_divisors.append(n / i)
    for divisor in reversed(large_divisors):
        yield divisor

print list(divisorGenerator(100))

Which should output a list like:

[1, 2, 4, 5, 10, 20, 25, 50, 100]

Order by descending date - month, day and year

what is the type of the field EventDate, since the ordering isn't correct i assume you don't have it set to some Date/Time representing type, but a string. And then the american way of writing dates is nasty to sort

How to strip a specific word from a string?

Use str.replace.

>>> papa.replace('papa', '')
' is a good man'
>>> app.replace('papa', '')
'app is important'

Alternatively use re and use regular expressions. This will allow the removal of leading/trailing spaces.

>>> import re
>>> papa = 'papa is a good man'
>>> app = 'app is important'
>>> papa3 = 'papa is a papa, and papa'
>>>
>>> patt = re.compile('(\s*)papa(\s*)')
>>> patt.sub('\\1mama\\2', papa)
'mama is a good man'
>>> patt.sub('\\1mama\\2', papa3)
'mama is a mama, and mama'
>>> patt.sub('', papa3)
'is a, and'

How do I cancel form submission in submit button onclick event?

You need onSubmit. Not onClick otherwise someone can just press enter and it will bypass your validation. As for canceling. you need to return false. Here's the code:

<form onSubmit="return btnClick()">
<input type='submit' value='submit request'>

function btnClick() {
    if (!validData()) return false;
}

Edit onSubmit belongs in the form tag.

Configuring ObjectMapper in Spring

SOLUTION 1

First working solution (tested) useful especially when using @EnableWebMvc:

@Configuration
@EnableWebMvc
public class WebConfig implements WebMvcConfigurer {
    @Autowired
    private ObjectMapper objectMapper;// created elsewhere
    @Override
    public void extendMessageConverters(List<HttpMessageConverter<?>> converters) {
        // this won't add a 2nd MappingJackson2HttpMessageConverter 
        // as the SOLUTION 2 is doing but also might seem complicated
        converters.stream().filter(c -> c instanceof MappingJackson2HttpMessageConverter).forEach(c -> {
            // check default included objectMapper._registeredModuleTypes,
            // e.g. Jdk8Module, JavaTimeModule when creating the ObjectMapper
            // without Jackson2ObjectMapperBuilder
            ((MappingJackson2HttpMessageConverter) c).setObjectMapper(this.objectMapper);
        });
    }

SOLUTION 2

Of course the common approach below works too (also working with @EnableWebMvc):

@Configuration
@EnableWebMvc
public class WebConfig implements WebMvcConfigurer {
    @Autowired
    private ObjectMapper objectMapper;// created elsewhere
    @Override
    public void extendMessageConverters(List<HttpMessageConverter<?>> converters) {
        // this will add a 2nd MappingJackson2HttpMessageConverter 
        // (additional to the default one) but will work and you 
        // won't lose the default converters as you'll do when overwriting
        // configureMessageConverters(List<HttpMessageConverter<?>> converters)
        // 
        // you still have to check default included
        // objectMapper._registeredModuleTypes, e.g.
        // Jdk8Module, JavaTimeModule when creating the ObjectMapper
        // without Jackson2ObjectMapperBuilder
        converters.add(new MappingJackson2HttpMessageConverter(this.objectMapper));
    }

Why @EnableWebMvc usage is a problem?

@EnableWebMvc is using DelegatingWebMvcConfiguration which extends WebMvcConfigurationSupport which does this:

if (jackson2Present) {
    Jackson2ObjectMapperBuilder builder = Jackson2ObjectMapperBuilder.json();
    if (this.applicationContext != null) {
        builder.applicationContext(this.applicationContext);
    }
    messageConverters.add(new MappingJackson2HttpMessageConverter(builder.build()));
}

which means that there's no way of injecting your own ObjectMapper with the purpose of preparing it to be used for creating the default MappingJackson2HttpMessageConverter when using @EnableWebMvc.

Assign format of DateTime with data annotations?

If your data field is already a DateTime datatype, you don't need to use [DataType(DataType.Date)] for the annotation; just use:

[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:MM/dd/yyyy}")]

on the jQuery, use datepicker for you calendar

    $(document).ready(function () {
        $('#StartDate').datepicker();
    });

on your HTML, use EditorFor helper:

    @Html.EditorFor(model => model.StartDate)

PostgreSQL INSERT ON CONFLICT UPDATE (upsert) use all excluded values

Postgres hasn't implemented an equivalent to INSERT OR REPLACE. From the ON CONFLICT docs (emphasis mine):

It can be either DO NOTHING, or a DO UPDATE clause specifying the exact details of the UPDATE action to be performed in case of a conflict.

Though it doesn't give you shorthand for replacement, ON CONFLICT DO UPDATE applies more generally, since it lets you set new values based on preexisting data. For example:

INSERT INTO users (id, level)
VALUES (1, 0)
ON CONFLICT (id) DO UPDATE
SET level = users.level + 1;

position: fixed doesn't work on iPad and iPhone

here is my solution to this...

CSS

#bgimg_top {
    background: url(images/bg.jpg) no-repeat 50% 0%; 
    position: fixed; 
    top:0; 
    left: 0; 
    right:0 ; 
    bottom:0;
}

HTML

<body>
<div id="bgimg_top"></div>
....
</body>

Explanation is that position fixed for the div will keep the div on the background at all time, then we stretch the div to go on all corners of the browser (provided the body margin = 0) using the (left,right,top,bottom) simultaneously.

Please make sure you do not use the width and height as this will override the top,left,right,bottom options.

How to properly use the "choices" field option in Django

For Django3.0+, use models.TextChoices (see docs-v3.0 for enumeration types)

from django.db import models

class MyModel(models.Model):
    class Month(models.TextChoices):
        JAN = '1', "JANUARY"
        FEB = '2', "FEBRUARY"
        MAR = '3', "MAR"
        # (...)

    month = models.CharField(
        max_length=2,
        choices=Month.choices,
        default=Month.JAN
    )

Usage::

>>> obj = MyModel.objects.create(month='1')
>>> assert obj.month == obj.Month.JAN
>>> assert MyModel.Month(obj.month).label == 'JANUARY'
>>> assert MyModel.objects.filter(month=MyModel.Month.JAN).count() >= 1

>>> obj2 = MyModel(month=MyModel.Month.FEB)
>>> assert obj2.get_month_display() == obj2.Month(obj2.month).label

How to create cron job using PHP?

Added to Alister, you can edit the crontab usually (not always the case) by entering crontab -e in a ssh session on the server.

The stars represent (* means every of this unit):

[Minute] [Hour] [Day] [Month] [Day of week (0 =sunday to 6 =saturday)] [Command]

You could read some more about this here.

What's the Linq to SQL equivalent to TOP or LIMIT/OFFSET?

Use the Take(int n) method:

var q = query.Take(10);

GUI-based or Web-based JSON editor that works like property explorer

Update: In an effort to answer my own question, here is what I've been able to uncover so far. If anyone else out there has something, I'd still be interested to find out more.

Based on JSON Schema

Commercial (No endorsement intended or implied, may or may not meet requirement)

jQuery

YAML

See Also

How to post object and List using postman

{
    "preOrderData" : [
        {
            "pname": "xyz",
            "quantity": "1",
            "unit": "Peice",
            "description": "xyz 100 gram",
            "preferred_brand": "xyz",
            "entry_date": "2020-10-05 11:11:27",
            "creation_date": "2020-10-05 11:11:27",
            "updated_date": "2020-10-05 11:11:27",
            "user": "[email protected]",
            "user_type": "individual"
        },
        {
            "productname": "abc cream",
            "quantity": "1",
            "unit": "Peice",
            "description": "abc 100 gram",
            "preferred_brand": "abccream",
            "entry_date": "2020-10-05 11:11:27",
            "creation_date": "2020-10-05 11:11:27",
            "updated_date": "2020-10-05 11:11:27",
            "user": "[email protected]",
            "user_type": "individual"
        }
    ]
}

AngularJS : Why ng-bind is better than {{}} in angular?

ng-bind is also safer because it represents html as a string.

So for example, '<script on*=maliciousCode()></script>' will be displayed as a string and not be executed.

What is the difference between git pull and git fetch + git rebase?

TLDR:

git pull is like running git fetch then git merge
git pull --rebase is like git fetch then git rebase

In reply to your first statement,

git pull is like a git fetch + git merge.

"In its default mode, git pull is shorthand for git fetch followed by git merge FETCH_HEAD" More precisely, git pull runs git fetch with the given parameters and then calls git merge to merge the retrieved branch heads into the current branch"

(Ref: https://git-scm.com/docs/git-pull)


For your second statement/question:

'But what is the difference between git pull VS git fetch + git rebase'

Again, from same source:
git pull --rebase

"With --rebase, it runs git rebase instead of git merge."


Now, if you wanted to ask

'the difference between merge and rebase'

that is answered here too:
https://git-scm.com/book/en/v2/Git-Branching-Rebasing
(the difference between altering the way version history is recorded)

delete image from folder PHP

You can try this code. This is Simple PHP Image Deleting code from the server.

<form method="post">
<input type="text" name="photoname"> // You can type your image name here...
<input type="submit" name="submit" value="Delete">
</form>

<?php
if (isset($_POST['submit'])) 
{
$photoname = $_POST['photoname'];
if (!unlink($photoname))
  {
  echo ("Error deleting $photoname");
  }
else
  {
  echo ("Deleted $photoname");
  }
}
?>

dropping a global temporary table

-- First Truncate temporary table
SQL> TRUNCATE TABLE test_temp1;

-- Then Drop temporary table
SQL> DROP TABLE test_temp1;

How to get the number of days of difference between two dates on mysql?

SELECT md.*, DATEDIFF(md.end_date, md.start_date) AS days FROM  membership_dates md

output::

id  entity_id    start_date            end_date             days

1   1236      2018-01-16 00:00:00     2018-08-31 00:00:00    227
2   2876      2015-06-26 00:00:00     2019-06-30 00:00:00   1465
3   3880      1990-06-05 00:00:00     2018-07-04 00:00:00   10256
4   3882      1993-07-05 00:00:00     2018-07-04 00:00:00   9130

hope it helps someone in future

How to do a https request with bad certificate?

The correct way to do this if you want to maintain the default transport settings is now (as of Go 1.13):

customTransport := http.DefaultTransport.(*http.Transport).Clone()
customTransport.TLSClientConfig = &tls.Config{InsecureSkipVerify: true}
client = &http.Client{Transport: customTransport}

Transport.Clone makes a deep copy of the transport. This way you don't have to worry about missing any new fields that get added to the Transport struct over time.

AddTransient, AddScoped and AddSingleton Services Differences

This image illustrates this concept well. Unfortunately, I could not find the original source of this image, but someone made it, he has shown this concept very well in the form of an image. enter image description here

What are file descriptors, explained in simple terms?

Any operating system has processes (p's) running, say p1, p2, p3 and so forth. Each process usually makes an ongoing usage of files.

Each process is consisted of a process tree (or a process table, in another phrasing).

Usually, Operating systems represent each file in each process by a number (that is to say, in each process tree/table).

The first file used in the process is file0, second is file1, third is file2, and so forth.

Any such number is a file descriptor.

File descriptors are usually integers (0, 1, 2 and not 0.5, 1.5, 2.5).

Given we often describe processes as "process-tables", and given that tables has rows (entries) we can say that the file descriptor cell in each entry, uses to represent the whole entry.

In a similar way, when you open a network socket, it has a socket descriptor.

In some operating systems, you can run out of file descriptors, but such case is extremely rare, and the average computer user shouldn't worry from that.

File descriptors might be global (process A starts in say 0, and ends say in 1 ; Process B starts say in 2, and ends say in 3) and so forth, but as far as I know, usually in modern operating systems, file descriptors are not global, and are actually process-specific (process A starts in say 0 and ends say in 5, while process B starts in 0 and ends say in 10).

JSONDecodeError: Expecting value: line 1 column 1

If you look at the output you receive from print() and also in your Traceback, you'll see the value you get back is not a string, it's a bytes object (prefixed by b):

b'{\n  "note":"This file    .....

If you fetch the URL using a tool such as curl -v, you will see that the content type is

Content-Type: application/json; charset=utf-8

So it's JSON, encoded as UTF-8, and Python is considering it a byte stream, not a simple string. In order to parse this, you need to convert it into a string first.

Change the last line of code to this:

info = json.loads(js.decode("utf-8"))

vertical-align with Bootstrap 3

Flexible box layout

With the advent of the CSS Flexible Box, many of web designers' nightmares1 have been resolved. One of the most hacky ones, the vertical alignment. Now it is possible even in unknown heights.

"Two decades of layout hacks are coming to an end. Maybe not tomorrow, but soon, and for the rest of our lives."

— CSS Legendary Eric Meyer at W3Conf 2013

Flexible Box (or in short, Flexbox), is a new layout system that is specifically designed for layout purposes. The specification states:

Flex layout is superficially similar to block layout. It lacks many of the more complex text- or document-centric properties that can be used in block layout, such as floats and columns. In return it gains simple and powerful tools for distributing space and aligning content in ways that webapps and complex web pages often need.

How can it help in this case? Well, let's see.


Vertical aligned columns

Using Twitter Bootstrap we have .rows having some .col-*s. All we need to do is to display the desired .row2 as a flex container box and then align all its flex items (the columns) vertically by align-items property.

EXAMPLE HERE (Please read the comments with care)

<div class="container">
    <div class="row vertical-align"> <!--
                    ^--  Additional class -->
        <div class="col-xs-6"> ... </div>
        <div class="col-xs-6"> ... </div>
    </div>
</div>
.vertical-align {
    display: flex;
    align-items: center;
}

The Output

Vertical aligned columns in Twitter Bootstrap

Colored area displays the padding-box of columns.

Clarifying on align-items: center

8.3 Cross-axis Alignment: the align-items property

Flex items can be aligned in the cross axis of the current line of the flex container, similar to justify-content but in the perpendicular direction. align-items sets the default alignment for all of the flex container’s items, including anonymous flex items.

align-items: center; By center value, the flex item’s margin box is centered in the cross axis within the line.


Big Alert

Important note #1: Twitter Bootstrap doesn't specify the width of columns in extra small devices unless you give one of .col-xs-# classes to the columns.

Therefore in this particular demo, I have used .col-xs-* classes in order for columns to be displayed properly in mobile mode, because it specifies the width of the column explicitly.

But alternatively you could switch off the Flexbox layout simply by changing display: flex; to display: block; in specific screen sizes. For instance:

/* Extra small devices (767px and down) */
@media (max-width: 767px) {
    .row.vertical-align {
        display: block; /* Turn off the flexible box layout */
    }
}

Or you could specify .vertical-align only on specific screen sizes like so:

/* Small devices (tablets, 768px and up) */
@media (min-width: 768px) {
    .row.vertical-align {
        display: flex;
        align-items: center;
    }
}

In that case, I'd go with @KevinNelson's approach.

Important note #2: Vendor prefixes omitted due to brevity. Flexbox syntax has been changed during the time. The new written syntax won't work on older versions of web browsers (but not that old as Internet Explorer 9! Flexbox is supported on Internet Explorer 10 and later).

This means you should also use vendor-prefixed properties like display: -webkit-box and so on in production mode.

If you click on "Toggle Compiled View" in the Demo, you'll see the prefixed version of CSS declarations (thanks to Autoprefixer).


Full-height columns with vertical aligned contents

As you see in the previous demo, columns (the flex items) are no longer as high as their container (the flex container box. i.e. the .row element).

This is because of using center value for align-items property. The default value is stretch so that the items can fill the entire height of the parent element.

In order to fix that, you can add display: flex; to the columns as well:

EXAMPLE HERE (Again, mind the comments)

.vertical-align {
  display: flex;
  flex-direction: row;
}

.vertical-align > [class^="col-"],
.vertical-align > [class*=" col-"] {
  display: flex;
  align-items: center;     /* Align the flex-items vertically */
  justify-content: center; /* Optional, to align inner flex-items
                              horizontally within the column  */
}

The Output

Full-height columns with vertical aligned contents in Twitter Bootstrap

Colored area displays the padding-box of columns.

Last, but not least, notice that the demos and code snippets here are meant to give you a different idea, to provide a modern approach to achieve the goal. Please mind the "Big Alert" section if you are going to use this approach in real world websites or applications.


For further reading including browser support, these resources would be useful:


1. Vertically align an image inside a div with responsive height 2. It's better to use an additional class in order not to alter Twitter Bootstrap's default .row.

How can I convert a date to GMT?

You can simply use the toUTCString (or toISOString) methods of the date object.

Example:

new Date("Fri Jan 20 2012 11:51:36 GMT-0500").toUTCString()

// Output:  "Fri, 20 Jan 2012 16:51:36 GMT"

If you prefer better control of the output format, consider using a library such as date-fns or moment.js.

Also, in your question, you've actually converted the time incorrectly. When an offset is shown in a timestamp string, it means that the date and time values in the string have already been adjusted from UTC by that value. To convert back to UTC, invert the sign before applying the offset.

11:51:36 -0300  ==  14:51:36Z

To delay JavaScript function call using jQuery

Very easy, just call the function within a specific amount of milliseconds using setTimeout()

setTimeout(myFunction, 2000)

function myFunction() {
    alert('Was called after 2 seconds');
}

Or you can even initiate the function inside the timeout, like so:

setTimeout(function() {
    alert('Was called after 2 seconds');
}, 2000)

TypeError: 'list' object is not callable while trying to access a list

Check your file name in which you have saved your program. If the file name is wordlists then you will get an error. Your filename should not be same as any of methods{functions} that you use in your program.

Rename Files and Directories (Add Prefix)

Thanks to Peter van der Heijden, here's one that'll work for filenames with spaces in them:

for f in * ; do mv -- "$f" "PRE_$f" ; done

("--" is needed to succeed with files that begin with dashes, whose names would otherwise be interpreted as switches for the mv command)

How do I convert a single character into it's hex ascii value in python

To use the hex encoding in Python 3, use

>>> import codecs
>>> codecs.encode(b"c", "hex")
b'63'

In legacy Python, there are several other ways of doing this:

>>> hex(ord("c"))
'0x63'
>>> format(ord("c"), "x")
'63'
>>> "c".encode("hex")
'63'

Reduce size of legend area in barplot

The cex parameter will do that for you.

a <- c(3, 2, 2, 2, 1, 2 )
barplot(a, beside = T,
        col = 1:6, space = c(0, 2))
legend("topright", 
       legend = c("a", "b", "c", "d", "e", "f"), 
       fill = 1:6, ncol = 2,
       cex = 0.75)

The plot

A TypeScript GUID class?

I found this https://typescriptbcl.codeplex.com/SourceControl/latest

here is the Guid version they have in case the link does not work later.

module System {
    export class Guid {
        constructor (public guid: string) {
            this._guid = guid;
        }

        private _guid: string;

        public ToString(): string {
            return this.guid;
        }

        // Static member
        static MakeNew(): Guid {
            var result: string;
            var i: string;
            var j: number;

            result = "";
            for (j = 0; j < 32; j++) {
                if (j == 8 || j == 12 || j == 16 || j == 20)
                    result = result + '-';
                i = Math.floor(Math.random() * 16).toString(16).toUpperCase();
                result = result + i;
            }
            return new Guid(result);
        }
    }
}

How to write oracle insert script with one field as CLOB?

Keep in mind that SQL strings can not be larger than 4000 bytes, while Pl/SQL can have strings as large as 32767 bytes. see below for an example of inserting a large string via an anonymous block which I believe will do everything you need it to do.

note I changed the varchar2(32000) to CLOB

set serveroutput ON 
CREATE TABLE testclob 
  ( 
     id NUMBER, 
     c  CLOB, 
     d  VARCHAR2(4000) 
  ); 

DECLARE 
    reallybigtextstring CLOB := '123'; 
    i                   INT; 
BEGIN 
    WHILE Length(reallybigtextstring) <= 60000 LOOP 
        reallybigtextstring := reallybigtextstring 
                               || '000000000000000000000000000000000'; 
    END LOOP; 

    INSERT INTO testclob 
                (id, 
                 c, 
                 d) 
    VALUES     (0, 
                reallybigtextstring, 
                'done'); 

    dbms_output.Put_line('I have finished inputting your clob: ' 
                         || Length(reallybigtextstring)); 
END; 

/ 
SELECT * 
FROM   testclob; 


 "I have finished inputting your clob: 60030"

You seem to not be depending on "@angular/core". This is an error

After trying to no avail:

  • npm install
  • npm update
  • ng serve

npm install -g @angular/cli worked for me

How to set environment variable for everyone under my linux system?

Amazingly, Unix and Linux do not actually have a place to set global environment variables. The best you can do is arrange for any specific shell to have a site-specific initialization.

If you put it in /etc/profile, that will take care of things for most posix-compatible shell users. This is probably "good enough" for non-critical purposes.

But anyone with a csh or tcsh shell won't see it, and I don't believe csh has a global initialization file.

How to format a numeric column as phone number in SQL

I found that this works if wanting in a (123) - 456-7890 format.

UPDATE table 
SET Phone_number =  '(' +  
                    SUBSTRING(Phone_number, 1, 3) 
                    + ') ' 
                    + '- ' +
                    SUBSTRING(Phone_number, 4, 3) 
                    + '-' +
                    SUBSTRING(Phone_number, 7, 4) 

cut or awk command to print first field of first row

Try

sed 'NUMq;d'  /etc/*release | awk {'print $1}'

where NUM is line number

ex. sed '1q;d'  /etc/*release | awk {'print $1}'

How to create a directory in Java?

if you want to be sure its created then this:

final String path = "target/logs/";
final File logsDir = new File(path);
final boolean logsDirCreated = logsDir.mkdir();
if (!logsDirCreated) {
    final boolean logsDirExists = logsDir.exists();
    assertThat(logsDirExists).isTrue();
}

beacuse mkDir() returns a boolean, and findbugs will cry for it if you dont use the variable. Also its not nice...

mkDir() returns only true if mkDir() creates it. If the dir exists, it returns false, so to verify the dir you created, only call exists() if mkDir() return false.

assertThat() will checks the result and fails if exists() returns false. ofc you can use other things to handle the uncreated directory.

How to check if a Constraint exists in Sql server?

I use this to check for and remote constraints on a column. It should have everything you need.

DECLARE
  @ps_TableName VARCHAR(300)
  , @ps_ColumnName VARCHAR(300)

SET @ps_TableName = 'mytable'
SET @ps_ColumnName = 'mycolumn'

DECLARE c_ConsList CURSOR LOCAL STATIC FORWARD_ONLY FOR
    SELECT
    'ALTER TABLE ' + RTRIM(tb.name) + ' drop constraint ' + sco.name AS csql
    FROM
        sys.Objects tb
        INNER JOIN sys.Columns tc on (tb.Object_id = tc.object_id)
        INNER JOIN sys.sysconstraints sc ON (tc.Object_ID = sc.id and tc.column_id = sc.colid)
        INNER JOIN sys.objects sco ON (sc.Constid = sco.object_id)
    where
        tb.name=@ps_TableName
        AND tc.name=@ps_ColumnName
OPEN c_ConsList
FETCH c_ConsList INTO @ls_SQL
WHILE (@@FETCH_STATUS = 0) BEGIN

    IF RTRIM(ISNULL(@ls_SQL, '')) <> '' BEGIN
        EXECUTE(@ls_SQL)
    END
    FETCH c_ConsList INTO @ls_SQL
END
CLOSE c_ConsList
DEALLOCATE c_ConsList

How to convert this var string to URL in Swift

In Swift3:
let fileUrl = Foundation.URL(string: filePath)

getCurrentPosition() and watchPosition() are deprecated on insecure origins

Use FireFox or any other browser instead of Chrome if you want to test it on your development environment, for production there is no way except using https.

For development environment just open http://localhost:8100/ on FireFox and alas no such error.

Why can't I define my workbook as an object?

You'll need to open the workbook to refer to it.

Sub Setwbk()

    Dim wbk As Workbook

    Set wbk = Workbooks.Open("F:\Quarterly Reports\2012 Reports\New Reports\ _
        Master Benchmark Data Sheet.xlsx")

End Sub

* Follow Doug's answer if the workbook is already open. For the sake of making this answer as complete as possible, I'm including my comment on his answer:

Why do I have to "set" it?

Set is how VBA assigns object variables. Since a Range and a Workbook/Worksheet are objects, you must use Set with these.

How to enable Logger.debug() in Log4j

If you are coming here because you are using Apache commons logging with log4j and log4j isn't working as you expect then check that you actually have a log4j.jar in your run-time classpath. That one had me puzzled for a little while. I have now configured the runner in my dev environment to include -Dlog4j.debug in the Java command line so I can always see that Log4j is being initialized correctly

How do I set a fixed background image for a PHP file?

You should consider have other php files included if you're going to derive a website from it. Instead of doing all the css/etc in that file, you can do

<head>
    <?php include_once('C:\Users\George\Documents\HTML\style.css'); ?>
    <title>Title</title>
</hea>

Then you can have a separate CSS file that is just being pulled into your php file. It provides some "neater" coding.

Add a CSS class to <%= f.submit %>

<%= f.submit 'name of button here', :class => 'submit_class_name_here' %>

This should do. If you're getting an error, chances are that you're not supplying the name.

Alternatively, you can style the button without a class:

form#form_id_here input[type=submit]

Try that, as well.

Find if value in column A contains value from column B?

You could try this

=IF(ISNA(VLOOKUP(<single column I value>,<entire column E range>,1,FALSE)),FALSE, TRUE)

-or-

=IF(ISNA(VLOOKUP(<single column I value>,<entire column E range>,1,FALSE)),"FALSE", "File found in row "   & MATCH(<single column I value>,<entire column E range>,0))

you could replace <single column I value> and <entire column E range> with named ranged. That'd probably be the easiest.

Just drag that formula all the way down the length of your I column in whatever column you want.

Ignore .pyc files in git repository

i try to use the sentence of a prior post and don't work recursively, then read some help and get this line:

find . -name "*.pyc" -exec git rm -f "{}" \;

p.d. is necessary to add *.pyc in .gitignore file to maintain git clean

echo "*.pyc" >> .gitignore

Enjoy.

How to set a class attribute to a Symfony2 form input

Renders the HTML widget of a given field. If you apply this to an entire form or collection of fields, each underlying form row will be rendered.

{# render a field row, but display a label with text "foo" #} {{ form_row(form.name, {'label': 'foo'}) }}

The second argument to form_row() is an array of variables. The templates provided in Symfony only allow to override the label as shown in the example above.

See "More about Form Variables" to learn about the variables argument.

Auto-expanding layout with Qt-Designer

Once you have add your layout with at least one widget in it, select your window and click the "Update" button of QtDesigner. The interface will be resized at the most optimized size and your layout will fit the whole window. Then when resizing the window, the layout will be resized in the same way.

Chart.js v2 - hiding grid lines

If you want them gone by default, you can set:

Chart.defaults.scale.gridLines.display = false;

Apply style to parent if it has child with css

It's not possible with CSS3. There is a proposed CSS4 selector, $, to do just that, which could look like this (Selecting the li element):

ul $li ul.sub { ... }

See the list of CSS4 Selectors here.

As an alternative, with jQuery, a one-liner you could make use of would be this:

$('ul li:has(ul.sub)').addClass('has_sub');

You could then go ahead and style the li.has_sub in your CSS.

How can I render repeating React elements?

To expand on Ross Allen's answer, here is a slightly cleaner variant using ES6 arrow syntax.

{this.props.titles.map(title =>
  <th key={title}>{title}</th>
)}

It has the advantage that the JSX part is isolated (no return or ;), making it easier to put a loop around it.

Android Studio and android.support.v4.app.Fragment: cannot resolve symbol

For me : Build->Clean Project solved this question

How do I clear the dropdownlist values on button click event using jQuery?

If you want to reset bootstrap page with button click using jQuery :

function resetForm(){
        var validator = $( "#form_ID" ).validate();
        validator.resetForm();
}

Using above code you also have change the field colour as red to normal.

If you want to reset only fielded value then :

$("#form_ID")[0].reset();

How to Store Historical Data

In SQL Server 2016 and above, there is a new feature called Temporal Tables that aims to solve this challenge with minimal effort from developer. The concept of temporal table is similar to Change Data Capture (CDC), with the difference that temporal table has abstracted most of the things that you had to do manually if you were using CDC.

How to loop through all the files in a directory in c # .net?

string[] files = 
    Directory.GetFiles(txtPath.Text, "*ProfileHandler.cs", SearchOption.AllDirectories);

That last parameter effects exactly what you're referring to. Set it to AllDirectories for every file including in subfolders, and set it to TopDirectoryOnly if you only want to search in the directory given and not subfolders.

Refer to MDSN for details: https://msdn.microsoft.com/en-us/library/ms143316(v=vs.110).aspx

Create a text file for download on-the-fly

Check out this SO question's accepted solution. Substitute your own filename for basename($File) and change filesize($File) to strlen($your_string). (You may want to use mb_strlen just in case the string contains multibyte characters.)

How to disable SSL certificate checking with Spring RestTemplate?

Disabling certificate checking is the wrong solution, and radically insecure.

The correct solution is to import the self-signed certificate into your truststore. An even more correct solution is to get the certificate signed by a CA.

If this is 'only for testing' it is still necessary to test the production configuration. Testing something else isn't a test at all, it's just a waste of time.

PHP create key => value pairs within a foreach

Something like this?

foreach ($Offer as $key => $value) { 
  $offerArray[$key] = $value[4];
}

Parsing JSON array into java.util.List with Gson

Below code is using com.google.gson.JsonArray. I have printed the number of element in list as well as the elements in List

import java.util.ArrayList;

import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;


public class Test {

    static String str = "{ "+ 
            "\"client\":\"127.0.0.1\"," + 
            "\"servers\":[" + 
            "    \"8.8.8.8\"," + 
            "    \"8.8.4.4\"," + 
            "    \"156.154.70.1\"," + 
            "    \"156.154.71.1\" " + 
            "    ]" + 
            "}";

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        try {

            JsonParser jsonParser = new JsonParser();
            JsonObject jo = (JsonObject)jsonParser.parse(str);
            JsonArray jsonArr = jo.getAsJsonArray("servers");
            //jsonArr.
            Gson googleJson = new Gson();
            ArrayList jsonObjList = googleJson.fromJson(jsonArr, ArrayList.class);
            System.out.println("List size is : "+jsonObjList.size());
                    System.out.println("List Elements are  : "+jsonObjList.toString());


        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

}

OUTPUT

List size is : 4

List Elements are  : [8.8.8.8, 8.8.4.4, 156.154.70.1, 156.154.71.1]

How to get a specific output iterating a hash in Ruby?

You can also refine Hash::each so it will support recursive enumeration. Here is my version of Hash::each(Hash::each_pair) with block and enumerator support:

module HashRecursive
    refine Hash do
        def each(recursive=false, &block)
            if recursive
                Enumerator.new do |yielder|
                    self.map do |key, value|
                        value.each(recursive=true).map{ |key_next, value_next| yielder << [[key, key_next].flatten, value_next] } if value.is_a?(Hash)
                        yielder << [[key], value]
                    end
                end.entries.each(&block)
            else
                super(&block)
            end
        end
        alias_method(:each_pair, :each)
    end
end

using HashRecursive

Here are usage examples of Hash::each with and without recursive flag:

hash = {
    :a => {
        :b => {
            :c => 1,
            :d => [2, 3, 4]
        },
        :e => 5
    },
    :f => 6
}

p hash.each, hash.each {}, hash.each.size
# #<Enumerator: {:a=>{:b=>{:c=>1, :d=>[2, 3, 4]}, :e=>5}, :f=>6}:each>
# {:a=>{:b=>{:c=>1, :d=>[2, 3, 4]}, :e=>5}, :f=>6}
# 2

p hash.each(true), hash.each(true) {}, hash.each(true).size
# #<Enumerator: [[[:a, :b, :c], 1], [[:a, :b, :d], [2, 3, 4]], [[:a, :b], {:c=>1, :d=>[2, 3, 4]}], [[:a, :e], 5], [[:a], {:b=>{:c=>1, :d=>[2, 3, 4]}, :e=>5}], [[:f], 6]]:each>
# [[[:a, :b, :c], 1], [[:a, :b, :d], [2, 3, 4]], [[:a, :b], {:c=>1, :d=>[2, 3, 4]}], [[:a, :e], 5], [[:a], {:b=>{:c=>1, :d=>[2, 3, 4]}, :e=>5}], [[:f], 6]]
# 6

hash.each do |key, value|
    puts "#{key} => #{value}"
end
# a => {:b=>{:c=>1, :d=>[2, 3, 4]}, :e=>5}
# f => 6

hash.each(true) do |key, value|
    puts "#{key} => #{value}"
end
# [:a, :b, :c] => 1
# [:a, :b, :d] => [2, 3, 4]
# [:a, :b] => {:c=>1, :d=>[2, 3, 4]}
# [:a, :e] => 5
# [:a] => {:b=>{:c=>1, :d=>[2, 3, 4]}, :e=>5}
# [:f] => 6

hash.each_pair(recursive=true) do |key, value|
    puts "#{key} => #{value}" unless value.is_a?(Hash)
end
# [:a, :b, :c] => 1
# [:a, :b, :d] => [2, 3, 4]
# [:a, :e] => 5
# [:f] => 6

Here is example from the question itself:

hash = {
    1   =>  ["a", "b"], 
    2   =>  ["c"], 
    3   =>  ["a", "d", "f", "g"], 
    4   =>  ["q"]
}

hash.each(recursive=false) do |key, value|
    puts "#{key} => #{value}"
end
# 1 => ["a", "b"]
# 2 => ["c"]
# 3 => ["a", "d", "f", "g"]
# 4 => ["q"]

Also take a look at my recursive version of Hash::merge(Hash::merge!) here.

What is float in Java?

Make it

float b= 3.6f;

A floating-point literal is of type float if it is suffixed with an ASCII letter F or f; otherwise its type is double and it can optionally be suffixed with an ASCII letter D or d

Displaying a webcam feed using OpenCV and Python

As in the opencv-doc you can get video feed from a camera which is connected to your computer by following code.

import numpy as np
import cv2
cap = cv2.VideoCapture(0)
while(True):
    # Capture frame-by-frame
    ret, frame = cap.read()
    # Our operations on the frame come here
    gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
    # Display the resulting frame
    cv2.imshow('frame',gray)
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break
# When everything done, release the capture
cap.release()
cv2.destroyAllWindows()

You can change cap = cv2.VideoCapture(0) index from 0 to 1 to access the 2nd camera.
Tested in opencv-3.2.0

Creating a very simple 1 username/password login in php

Your code could look more like:

<?php
session_start();
$errorMsg = "";
$validUser = $_SESSION["login"] === true;
if(isset($_POST["sub"])) {
  $validUser = $_POST["username"] == "admin" && $_POST["password"] == "password";
  if(!$validUser) $errorMsg = "Invalid username or password.";
  else $_SESSION["login"] = true;
}
if($validUser) {
   header("Location: /login-success.php"); die();
}
?>
<!DOCTYPE html>
<html>
<head>
  <meta http-equiv="content-type" content="text/html;charset=utf-8" />
  <title>Login</title>
</head>
<body>
  <form name="input" action="" method="post">
    <label for="username">Username:</label><input type="text" value="<?= $_POST["username"] ?>" id="username" name="username" />
    <label for="password">Password:</label><input type="password" value="" id="password" name="password" />
    <div class="error"><?= $errorMsg ?></div>
    <input type="submit" value="Home" name="sub" />
  </form>
</body>
</html>

Now, when the page is redirected based on the header('LOCATION:wherever.php), put session_start() at the top of the page and test to make sure $_SESSION['login'] === true. Remember that == would be true if $_SESSION['login'] == 1 as well. Of course, this is a bad idea for security reasons, but my example may teach you a different way of using PHP.

Error: the entity type requires a primary key

None of the answers worked until I removed the HasNoKey() method from the entity. Dont forget to remove this from your data context or the [Key] attribute will not fix anything.

How do I use itertools.groupby()?

How do I use Python's itertools.groupby()?

You can use groupby to group things to iterate over. You give groupby an iterable, and a optional key function/callable by which to check the items as they come out of the iterable, and it returns an iterator that gives a two-tuple of the result of the key callable and the actual items in another iterable. From the help:

groupby(iterable[, keyfunc]) -> create an iterator which returns
(key, sub-iterator) grouped by each value of key(value).

Here's an example of groupby using a coroutine to group by a count, it uses a key callable (in this case, coroutine.send) to just spit out the count for however many iterations and a grouped sub-iterator of elements:

import itertools


def grouper(iterable, n):
    def coroutine(n):
        yield # queue up coroutine
        for i in itertools.count():
            for j in range(n):
                yield i
    groups = coroutine(n)
    next(groups) # queue up coroutine

    for c, objs in itertools.groupby(iterable, groups.send):
        yield c, list(objs)
    # or instead of materializing a list of objs, just:
    # return itertools.groupby(iterable, groups.send)

list(grouper(range(10), 3))

prints

[(0, [0, 1, 2]), (1, [3, 4, 5]), (2, [6, 7, 8]), (3, [9])]

Is there a math nCr function in python?

The following program calculates nCr in an efficient manner (compared to calculating factorials etc.)

import operator as op
from functools import reduce

def ncr(n, r):
    r = min(r, n-r)
    numer = reduce(op.mul, range(n, n-r, -1), 1)
    denom = reduce(op.mul, range(1, r+1), 1)
    return numer // denom  # or / in Python 2

As of Python 3.8, binomial coefficients are available in the standard library as math.comb:

>>> from math import comb
>>> comb(10,3)
120

How to read file contents into a variable in a batch file?

Read file contents into a variable:

for /f "delims=" %%x in (version.txt) do set Build=%%x

or

set /p Build=<version.txt

Both will act the same with only a single line in the file, for more lines the for variant will put the last line into the variable, while set /p will use the first.

Using the variable – just like any other environment variable – it is one, after all:

%Build%

So to check for existence:

if exist \\fileserver\myapp\releasedocs\%Build%.doc ...

Although it may well be that no UNC paths are allowed there. Can't test this right now but keep this in mind.

get current url in twig template?

{{ path(app.request.attributes.get('_route'),
     app.request.attributes.get('_route_params')) }}

If you want to read it into a view variable:

{% set currentPath = path(app.request.attributes.get('_route'),
                       app.request.attributes.get('_route_params')) %}

The app global view variable contains all sorts of useful shortcuts, such as app.session and app.security.token.user, that reference the services you might use in a controller.

How to view the contents of an Android APK file?

You have several tools available:

  • Aapt (which is part of the Android SDK)

    $ aapt dump badging MyApk.apk
    $ aapt dump permissions MyApk.apk
    $ aapt dump xmltree MyApk.apk
    
  • Apktool

    $ java -jar apktool.jar -q decode -f MyApk.apk -o myOutputDir
    
  • Android Multitool

  • Apk Viewer

  • ApkShellext

  • Dex2Jar

    $ dex2jar/d2j-dex2jar.sh -f MyApk.apk -o myOutputDir/MyApk.jar
    
  • NinjaDroid

    $ ninjadroid MyApk.apk
    $ ninjadroid MyApk.apk --all --extract myOutputDir/
    
  • AXMLParser

    $ apkinfo MyApk.apk
    

Why I am getting Cannot pass parameter 2 by reference error when I am using bindParam with a constant value?

Based on the other answers but with a little more clarity on how to actually use this solution.

If for example you have an empty string for a time value but you want to save it as a null:

  if($endtime == ""){
    $db->bind(":endtime",$endtime=NULL,PDO::PARAM_STR);
  }else{
    $db->bind("endtime",$endtime);
  }

Notice that for time values you would use PARAM_STR, as times are stored as strings.

How to Resize image in Swift?

All of the listed answers so far seem to result in an image of a reduced size, however the size isn't measured in pixels. Here's a Swift 5, pixel-based resize.

extension UIImage {
    func resize(_ max_size: CGFloat) -> UIImage {
        // adjust for device pixel density
        let max_size_pixels = max_size / UIScreen.main.scale
        // work out aspect ratio
        let aspectRatio =  size.width/size.height
        // variables for storing calculated data
        var width: CGFloat
        var height: CGFloat
        var newImage: UIImage
        if aspectRatio > 1 {
            // landscape
            width = max_size_pixels
            height = max_size_pixels / aspectRatio
        } else {
            // portrait
            height = max_size_pixels
            width = max_size_pixels * aspectRatio
        }
        // create an image renderer of the correct size
        let renderer = UIGraphicsImageRenderer(size: CGSize(width: width, height: height), format: UIGraphicsImageRendererFormat.default())
        // render the image
        newImage = renderer.image {
            (context) in
            self.draw(in: CGRect(x: 0, y: 0, width: width, height: height))
        }
        // return the image
        return newImage
    }
} 

Usage:

image.resize(500)

What is w3wp.exe?

  • A worker process runs as an executables file named W3wp.exe
  • A Worker Process is user mode code whose role is to process requests, such as processing requests to return a static page.

  • The worker process is controlled by the www service.

  • worker processes also run application code, Such as ASP .NET applications and XML web Services.

  • When Application pool receive the request, it simply pass the request to worker process (w3wp.exe) . The worker process“w3wp.exe” looks up the URL of the request in order to load the correct ISAPI extension. ISAPI extensions are the IIS way to handle requests for different resources. Once ASP.NET is installed, it installs its own ISAPI extension (aspnet_isapi.dll)and adds the mapping into IIS.

  • When Worker process loads the aspnet_isapi.dll, it start an HTTPRuntime, which is the entry point of an application. HTTPRuntime is a class which calls the ProcessRequest method to start Processing.

For more detail refer URL http://aspnetnova.blogspot.in/2011/12/how-iis-process-for-aspnet-requests.htmlenter image description here

How to check Django version

If you want to make Django version comparison, you could use django-nine (pip install django-nine). For example, if Django version installed in your environment is 1.7.4, then the following would be true.

from nine import versions

versions.DJANGO_1_7 # True
versions.DJANGO_LTE_1_7 # True
versions.DJANGO_GTE_1_7 # True
versions.DJANGO_GTE_1_8 # False
versions.DJANGO_GTE_1_4 # True
versions.DJANGO_LTE_1_6 # False

How to set a primary key in MongoDB?

The other way is to create Indexes for your collection and make sure that they are unique.

You can find more on the following link

I actually find this pretty simple and easy to implement.

JSON library for C#

You should also try my ServiceStack JsonSerializer - it's the fastest .NET JSON serializer at the moment based on the benchmarks of the leading JSON serializers and supports serializing any POCO Type, DataContracts, Lists/Dictionaries, Interfaces, Inheritance, Late-bound objects including anonymous types, etc.

Basic Example

var customer = new Customer { Name="Joe Bloggs", Age=31 };
var json = customer.ToJson();
var fromJson = json.FromJson<Customer>(); 

Note: Only use Microsofts JavaScriptSerializer if performance is not important to you as I've had to leave it out of my benchmarks since its up to 40x-100x slower than the other JSON serializers.

How do I delete everything in Redis?

you can use following approach in python

def redis_clear_cache(self):

    try:
        redis_keys = self.redis_client.keys('*')
    except Exception as e:
        # print('redis_client.keys() raised exception => ' + str(e))
        return 1

    try:
        if len(redis_keys) != 0:
            self.redis_client.delete(*redis_keys)
    except Exception as e:
        # print('redis_client.delete() raised exception => ' + str(e))
        return 1

    # print("cleared cache")
    return 0

Confirm button before running deleting routine from website

You can do it with an confirm() message using Javascript.

Make Font Awesome icons in a circle?

UPDATE:

Upon learning flex recently, there is a cleaner way (no tables and less css). Set the wrapper as display: flex; and to center it's children give it the properties align-items: center; for (vertical) and justify-content: center; (horizontal) centering.

See this updated JS Fiddle


Strange that nobody suggested this before.. I always use tables to do this.
Simply make a wrapper have display: table and center stuff inside it with text-align: center for horizontal and vertical-align: middle for vertical alignment.

<div class='wrapper'>
  <i class='icon fa fa-bars'></i>
</div>

and some sass like this

.wrapper{
  display: table; 

  i{
    display: table-cell;
    vertical-align: middle;
    text-align: center;
  }

}

or see this JS Fiddle

Best way to define error codes/strings in Java?

I'd recommend that you take a look at java.util.ResourceBundle. You should care about I18N, but it's worth it even if you don't. Externalizing the messages is a very good idea. I've found that it was useful to be able to give a spreadsheet to business folks that allowed them to put in the exact language they wanted to see. We wrote an Ant task to generate the .properties files at compile time. It makes I18N trivial.

If you're also using Spring, so much the better. Their MessageSource class is useful for these sorts of things.

Making a request to a RESTful API using python

Using requests:

import requests
url = 'http://ES_search_demo.com/document/record/_search?pretty=true'
data = '''{
  "query": {
    "bool": {
      "must": [
        {
          "text": {
            "record.document": "SOME_JOURNAL"
          }
        },
        {
          "text": {
            "record.articleTitle": "farmers"
          }
        }
      ],
      "must_not": [],
      "should": []
    }
  },
  "from": 0,
  "size": 50,
  "sort": [],
  "facets": {}
}'''
response = requests.post(url, data=data)

Depending on what kind of response your API returns, you will then probably want to look at response.text or response.json() (or possibly inspect response.status_code first). See the quickstart docs here, especially this section.

Plotting a 2D heatmap with Matplotlib

I would use matplotlib's pcolor/pcolormesh function since it allows nonuniform spacing of the data.

Example taken from matplotlib:

import matplotlib.pyplot as plt
import numpy as np

# generate 2 2d grids for the x & y bounds
y, x = np.meshgrid(np.linspace(-3, 3, 100), np.linspace(-3, 3, 100))

z = (1 - x / 2. + x ** 5 + y ** 3) * np.exp(-x ** 2 - y ** 2)
# x and y are bounds, so z should be the value *inside* those bounds.
# Therefore, remove the last value from the z array.
z = z[:-1, :-1]
z_min, z_max = -np.abs(z).max(), np.abs(z).max()

fig, ax = plt.subplots()

c = ax.pcolormesh(x, y, z, cmap='RdBu', vmin=z_min, vmax=z_max)
ax.set_title('pcolormesh')
# set the limits of the plot to the limits of the data
ax.axis([x.min(), x.max(), y.min(), y.max()])
fig.colorbar(c, ax=ax)

plt.show()

pcolormesh plot output

jQuery if Element has an ID?

Like this:

var $aWithId = $('.parent a[id]');

Following OP's comment, test it like this:

if($aWithId.length) //or without using variable: if ($('.parent a[id]').length)

Will return all anchor tags inside elements with class parent which have an attribute ID specified

How to fix "Attempted relative import in non-package" even with __init__.py

For me only this worked: I had to explicitly set the value of package to the parent directory, and add the parent directory to sys.path

from os import path
import sys
if __package__ is None:
    sys.path.append( path.dirname( path.dirname( path.abspath(__file__) ) ) )
    __package__= "myparent"

from .subdir import something # the . can now be resolved

I can now directly run my script with python myscript.py.

PostgreSQL query to list all table names?

What bout this query (based on the description from manual)?

SELECT table_name
  FROM information_schema.tables
 WHERE table_schema='public'
   AND table_type='BASE TABLE';

How to speed up insertion performance in PostgreSQL

In addition to excellent Craig Ringer's post and depesz's blog post, if you would like to speed up your inserts through ODBC (psqlodbc) interface by using prepared-statement inserts inside a transaction, there are a few extra things you need to do to make it work fast:

  1. Set the level-of-rollback-on-errors to "Transaction" by specifying Protocol=-1 in the connection string. By default psqlodbc uses "Statement" level, which creates a SAVEPOINT for each statement rather than an entire transaction, making inserts slower.
  2. Use server-side prepared statements by specifying UseServerSidePrepare=1 in the connection string. Without this option the client sends the entire insert statement along with each row being inserted.
  3. Disable auto-commit on each statement using SQLSetConnectAttr(conn, SQL_ATTR_AUTOCOMMIT, reinterpret_cast<SQLPOINTER>(SQL_AUTOCOMMIT_OFF), 0);
  4. Once all rows have been inserted, commit the transaction using SQLEndTran(SQL_HANDLE_DBC, conn, SQL_COMMIT);. There is no need to explicitly open a transaction.

Unfortunately, psqlodbc "implements" SQLBulkOperations by issuing a series of unprepared insert statements, so that to achieve the fastest insert one needs to code up the above steps manually.

Is there a way to include commas in CSV columns without breaking the formatting?

You can use the Text_Qualifier field in your Flat file connection manager to as ". This should wrap your data in quotes and only separate by commas which are outside the quotes.

Python how to plot graph sine wave

The window of usefulness has likely come and gone, but I was working at a similar problem. Here is my attempt at plotting sine using the turtle module.

from turtle import *
from math import *

#init turtle
T=Turtle()

#sample size
T.screen.setworldcoordinates(-1,-1,1,1) 

#speed up the turtle
T.speed(-1)

#range of hundredths from -1 to 1
xcoords=map(lambda x: x/100.0,xrange(-100,101))

#setup the origin
T.pu();T.goto(-1,0);T.pd()

#move turtle
for x in xcoords:
    T.goto(x,sin(xcoords.index(x)))

No @XmlRootElement generated by JAXB

This is mentioned at the bottom of the blog post already linked above but this works like a treat for me:

Marshaller marshaller = jc.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
marshaller.marshal(new JAXBElement<MyClass>(new QName("uri","local"), MyClass.class, myClassInstance), System.out);

:before and background-image... should it work?

@michi; define height in your before pseudo class

CSS:

#videos-part:before{
    width: 16px;
    content: " ";
    background-image: url(/img/border-left3.png);
    position: absolute;
    left: -16px;
    top: -6px;
    height:20px;
}

Check element CSS display with JavaScript

To find out if it's visible with plain JavaScript, check whether the display property is 'none' (don't check for 'block', it could also be blank or 'inline' and still be visible):

var isVisible = (elt.style.display != "none");

If you are using jQuery, you can use this instead:

var isVisible = $elt.is(":visible");

setup.py examples?

Here is the utility I wrote to generate a simple setup.py file (template) with useful comments and links. I hope, it will be useful.

Installation

sudo pip install setup-py-cli

Usage

To generate setup.py file just type in the terminal.

setup-py

Now setup.py file should occur in the current directory.

Generated setup.py

from distutils.core import setup
from setuptools import find_packages
import os


# User-friendly description from README.md
current_directory = os.path.dirname(os.path.abspath(__file__))
try:
    with open(os.path.join(current_directory, 'README.md'), encoding='utf-8') as f:
        long_description = f.read()
except Exception:
    long_description = ''

setup(
    # Name of the package
    name=<name of current directory>,

    # Packages to include into the distribution
    packages=find_packages('.'), 

    # Start with a small number and increase it with every change you make
    # https://semver.org
    version='1.0.0',

    # Chose a license from here: https://help.github.com/articles/licensing-a-repository
    # For example: MIT
    license='',

    # Short description of your library
    description='',

    # Long description of your library
    long_description = long_description,
    long_description_context_type = 'text/markdown',

    # Your name
    author='', 

    # Your email
    author_email='',     

    # Either the link to your github or to your website
    url='',

    # Link from which the project can be downloaded
    download_url='',

    # List of keyword arguments
    keywords=[],

    # List of packages to install with this one
    install_requires=[],

    # https://pypi.org/classifiers/
    classifiers=[]  
)

Content of the generated setup.py:

  • automatically fulfilled package name based on the name of the current directory.
  • some basic fields to fulfill.
  • clarifying comments and links to useful resources.
  • automatically inserted description from README.md or an empty string if there is no README.md.

Here is the link to the repository. Fill free to enhance the solution.

How to find the Git commit that introduced a string in any branch?

While this doesn't directly answer you question, I think it might be a good solution for you in the future. I saw a part of my code, which was bad. Didn't know who wrote it or when. I could see all changes from the file, but it was clear that the code had been moved from some other file to this one. I wanted to find who actually added it in the first place.

To do this, I used Git bisect, which quickly let me find the sinner.

I ran git bisect start and then git bisect bad, because the revision checked out had the issue. Since I didn't know when the problem occured, I targetted the first commit for the "good", git bisect good <initial sha>.

Then I just kept searching the repo for the bad code. When I found it, I ran git bisect bad, and when it wasn't there: git bisect good.

In ~11 steps, I had covered ~1000 commits and found the exact commit, where the issue was introduced. Pretty great.

How to get the changes on a branch in Git

Throw a -p in there to see some FILE CHANGES

git log -p master..branch

Make some aliases:

alias gbc="git branch --no-color | sed -e '/^[^\*]/d' -e 's/* \\(.*\\)/\1/'"

alias gbl='git log -p master..\`gbc\`'

See a branch's unique commits:

gbl

Space between Column's children in Flutter

The sized box will not help in the case, the phone is in landscape mode.

body: Column(
      mainAxisAlignment: MainAxisAlignment.spaceBetween,
      crossAxisAlignment: CrossAxisAlignment.stretch,
      children: <Widget>[
        Expanded(
           child: Container(
            margin: EdgeInsets.all(15.0),
            decoration: BoxDecoration(
              color: Color(0xFF1D1E33),
              borderRadius: BorderRadius.circular(10.0),
            ),
          ),
        ),
        Expanded(
           child: Container(
            margin: EdgeInsets.all(15.0),
            decoration: BoxDecoration(
              color: Color(0xFF1D1E33),
              borderRadius: BorderRadius.circular(10.0),
            ),
          ),
        ),
        Expanded(
           child: Container(
            margin: EdgeInsets.all(15.0),
            decoration: BoxDecoration(
              color: Color(0xFF1D1E33),
              borderRadius: BorderRadius.circular(10.0),
            ),
          ),
        ),
      ],
     )

Usage of the backtick character (`) in JavaScript

Apart from string interpolation, you can also call a function using back-tick.


var sayHello = function () {
    console.log('Hello', arguments);
}

// To call this function using ``

sayHello`some args`; // Check console for the output

// Or
sayHello`
    some args
`;

Check styled component. They use it heavily.

Splitting a table cell into two columns in HTML

Please try the following way.

<table>
  <tr>
    <th>Month</th>
    <th>Savings</th>
  </tr>
  <tr>
    <td>January</td>
    <td>$100</td>
  </tr>
  <tr>
    <td>February</td>
    <td>$80</td>
  </tr>
  <tr>
    <td colspan="2">Sum: $180</td>
  </tr>
</table>

What is the Maximum Size that an Array can hold?

Here is an answer to your question that goes into detail: http://www.velocityreviews.com/forums/t372598-maximum-size-of-byte-array.html

You may want to mention which version of .NET you are using and your memory size.

You will be stuck to a 2G, for your application, limit though, so it depends on what is in your array.

jquery: animate scrollLeft

You'll want something like this:


$("#next").click(function(){
      var currentElement = currentElement.next();
      $('html, body').animate({scrollLeft: $(currentElement).offset().left}, 800);
      return false;
   }); 
I believe this should work, it's adopted from a scrollTop function.

What's an Aggregate Root?

From Evans DDD:

An AGGREGATE is a cluster of associated objects that we treat as a unit for the purpose of data changes. Each AGGREGATE has a root and a boundary. The boundary defines what is inside the AGGREGATE. The root is a single, specific ENTITY contained in the AGGREGATE.

And:

The root is the only member of the AGGREGATE that outside objects are allowed to hold references to[.]

This means that aggregate roots are the only objects that can be loaded from a repository.

An example is a model containing a Customer entity and an Address entity. We would never access an Address entity directly from the model as it does not make sense without the context of an associated Customer. So we could say that Customer and Address together form an aggregate and that Customer is an aggregate root.

Calling a JSON API with Node.js

Unirest library simplifies this a lot. If you want to use it, you have to install unirest npm package. Then your code could look like this:

unirest.get("http://graph.facebook.com/517267866/?fields=picture")
  .send()
  .end(response=> {
    if (response.ok) {
      console.log("Got a response: ", response.body.picture)
    } else {
      console.log("Got an error: ", response.error)
    }
  })

Convert string into integer in bash script - "Leading Zero" number error

You could also use bc

hour=8
result=$(echo "$hour + 1" | bc)
echo $result
9

Bootstrap DatePicker, how to set the start date for tomorrow?

If you are using bootstrap-datepicker you may use this style:

$('#datepicker').datepicker('setStartDate', "01-01-1900");

Chrome says my extension's manifest file is missing or unreadable

Mine also was funny. While copypasting " manifest.json" from the tutorial, i also managed to copy a leading space. Couldn't get why it's not finding it.

Error: [ng:areq] from angular controller

Check the name of your angular module...what is the name of your module in your app.js?

In your TransportersController, you have:

angular.module('mean.transporters')

and in your TransportersService you have:

angular.module('transporterService', [])

You probably want to reference the same module in each:

angular.module('myApp')

Centering a background image, using CSS

background-repeat:no-repeat;
background-position:center center;

Does not vertically center the background image when using a html 4.01 'STRICT' doctype.

Adding:

background-attachment: fixed;

Should fix the problem

(So Alexander is right)

How can I find script's directory?

This worked for me (and I found it via the this stackoverflow question)

os.path.realpath(__file__)

How to get the position of a character in Python?

A solution with numpy for quick access to all indexes:

string_array = np.array(list(my_string))
char_indexes = np.where(string_array == 'C')

how to add background image to activity?

You can set the "background image" to an activity by setting android:background xml attributes as followings:

(Here, for example, Take a LinearLayout for an activity and setting a background image for the layout(i.e. indirectly to an activity))

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout android:id="@+id/LinearLayout01" 
              android:layout_width="fill_parent" 
              android:layout_height="fill_parent" 
              xmlns:android="http://schemas.android.com/apk/res/android"
              android:background="@drawable/icon">
 </LinearLayout>

Cannot use Server.MapPath

System.Web.HttpContext.Current.Server.MapPath("~/") gives null if we call it from a thread.

So, Try to use

System.Web.Hosting.HostingEnvironment.MapPath("~/")

Java Compare Two List's object values?

It's not the most efficient solution but the most terse code would be:

boolean equalLists = listA.size() == listB.size() && listA.containsAll(listB);

Update:

@WesleyPorter is right. The solution above will not work if duplicate objects are in the collection.
For a complete solution you need to iterate over a collection so duplicate objects are handled correctly.

private static boolean cmp( List<?> l1, List<?> l2 ) {
    // make a copy of the list so the original list is not changed, and remove() is supported
    ArrayList<?> cp = new ArrayList<>( l1 );
    for ( Object o : l2 ) {
        if ( !cp.remove( o ) ) {
            return false;
        }
    }
    return cp.isEmpty();
}

Update 28-Oct-2014:

@RoeeGavriel is right. The return statement needs to be conditional. The code above is updated.

Add custom message to thrown exception while maintaining stack trace in Java

you can use super while extending Exception

if (pass.length() < minPassLength)
    throw new InvalidPassException("The password provided is too short");
 } catch (NullPointerException e) {
    throw new InvalidPassException("No password provided", e);
 }


// A custom business exception
class InvalidPassException extends Exception {

InvalidPassException() {

}

InvalidPassException(String message) {
    super(message);
}
InvalidPassException(String message, Throwable cause) {
   super(message, cause);
}

}

}

source

C# Checking if button was clicked

Click is an event that fires immediately after you release the mouse button. So if you want to check in the handler for button2.Click if button1 was clicked before, all you could do is have a handler for button1.Click which sets a bool flag of your own making to true.

private bool button1WasClicked = false;

private void button1_Click(object sender, EventArgs e)
{
    button1WasClicked = true;
}

private void button2_Click(object sender, EventArgs e)
{
    if (textBox2.Text == textBox3.Text && button1WasClicked)
    { 
        StreamWriter myWriter = File.CreateText(@"c:\Program Files\text.txt");
        myWriter.WriteLine(textBox1.Text);
        myWriter.WriteLine(textBox2.Text);
        button1WasClicked = false;
    }
}

How do I know the script file name in a Bash script?

You can use $0 to determine your script name (with full path) - to get the script name only you can trim that variable with

basename $0

Sending email with gmail smtp with codeigniter email library

Another option I have working, in a linux server with Postfix:

First, configure CI email to use your server's email system: eg, in email.php, for example

# alias to postfix in a typical Postfix server
$config['protocol'] = 'sendmail'; 
$config['mailpath'] = '/usr/sbin/sendmail'; 

Then configure your postfix to relay the mail to google (perhaps depending on the sender address). You'll probably need to put you user-password settings in /etc/postfix/sasl_passwd (docs)

This is much simpler (and less fragmente) if you have a linux box, already configured to send some/all of its outgoing emails to Google.

Swift - iOS - Dates and times in different format

new Date(year,month,day,0,0,0,0) is local time (as input) new Date(year,month,day) is UTC

I was using a function to attain YYYY-MM-DD format to be compatible on iOS web, but that is also UTC when used in comparisons (not chained by getFullYear or similar) I've found it is best to use only the above with strong (hours,minutes,seconds,milliseconds) building a calendar, calculating with a Date objects and local references

export const zeroPad = (num) => {
  var res = "0";
  if (String(num).length === 1) {
    res = `0${num}`;
  } else {
    res = num;
  }
  return res;
};

How do I find Waldo with Mathematica?

My guess at a "bulletproof way to do this" (think CIA finding Waldo in any satellite image any time, not just a single image without competing elements, like striped shirts)... I would train a Boltzmann machine on many images of Waldo - all variations of him sitting, standing, occluded, etc.; shirt, hat, camera, and all the works. You don't need a large corpus of Waldos (maybe 3-5 will be enough), but the more the better.

This will assign clouds of probabilities to various elements occurring in whatever the correct arrangement, and then establish (via segmentation) what an average object size is, fragment the source image into cells of objects which most resemble individual people (considering possible occlusions and pose changes), but since Waldo pictures usually include a LOT of people at about the same scale, this should be a very easy task, then feed these segments of the pre-trained Boltzmann machine. It will give you probability of each one being Waldo. Take one with the highest probability.

This is how OCR, ZIP code readers, and strokeless handwriting recognition work today. Basically you know the answer is there, you know more or less what it should look like, and everything else may have common elements, but is definitely "not it", so you don't bother with the "not it"s, you just look of the likelihood of "it" among all possible "it"s you've seen before" (in ZIP codes for example, you'd train BM for just 1s, just 2s, just 3s, etc., then feed each digit to each machine, and pick one that has most confidence). This works a lot better than a single neural network learning features of all numbers.