Programs & Examples On #Vaadin

Vaadin is a client-server framework, that builds on GWT (Google Web Toolkit) and uses Java to code all of the server and clientside code. Vaadin tries to improve the clientside presentation layer and the rapid application development factor over GWT.

How to query DATETIME field using only date in Microsoft SQL Server?

select * from invoice where TRANS_DATE_D>= to_date  ('20170831115959','YYYYMMDDHH24MISS')
and TRANS_DATE_D<= to_date  ('20171031115959','YYYYMMDDHH24MISS');

Check whether $_POST-value is empty

isset() will return true if the variable has been initialised. If you have a form field with its name value set to userName, when that form is submitted the value will always be "set", although there may not be any data in it.

Instead, trim() the string and test its length

if("" == trim($_POST['userName'])){
    $username = 'Anonymous';

What is the minimum I have to do to create an RPM file?

I often do binary rpm per packaging proprietary apps - also moster as websphere - on linux. So my experience could be useful also a you, besides that it would better to do a TRUE RPM if you can. But i digress.

So the a basic step for packaging your (binary) program is as follow - in which i suppose the program is toybinprog with version 1.0, have a conf to be installed in /etc/toybinprog/toybinprog.conf and have a bin to be installed in /usr/bin called tobinprog :

1. create your rpm build env for RPM < 4.6,4.7

mkdir -p ~/rpmbuild/{RPMS,SRPMS,BUILD,SOURCES,SPECS,tmp}

cat <<EOF >~/.rpmmacros
%_topdir   %(echo $HOME)/rpmbuild
%_tmppath  %{_topdir}/tmp

cd ~/rpmbuild

2. create the tarball of your project

mkdir toybinprog-1.0
mkdir -p toybinprog-1.0/usr/bin
mkdir -p toybinprog-1.0/etc/toybinprog
install -m 755 toybinprog toybinprog-1.0/usr/bin
install -m 644 toybinprog.conf toybinprog-1.0/etc/toybinprog/

tar -zcvf toybinprog-1.0.tar.gz toybinprog-1.0/

3. Copy to the sources dir

cp toybinprog-1.0.tar.gz SOURCES/

cat <<EOF > SPECS/toybinprog.spec
# Don't try fancy stuff like debuginfo, which is useless on binary-only
# packages. Don't strip binary too
# Be sure buildpolicy set to do nothing
%define        __spec_install_post %{nil}
%define          debug_package %{nil}
%define        __os_install_post %{_dbpath}/brp-compress

Summary: A very simple toy bin rpm package
Name: toybinprog
Version: 1.0
Release: 1
License: GPL+
Group: Development/Tools
SOURCE0 : %{name}-%{version}.tar.gz

BuildRoot: %{_tmppath}/%{name}-%{version}-%{release}-root


%setup -q

# Empty section.

rm -rf %{buildroot}
mkdir -p  %{buildroot}

# in builddir
cp -a * %{buildroot}

rm -rf %{buildroot}

%config(noreplace) %{_sysconfdir}/%{name}/%{name}.conf

* Thu Apr 24 2009  Elia Pinto <[email protected]> 1.0-1
- First Build


4. build the source and the binary rpm

rpmbuild -ba SPECS/toybinprog.spec

And that's all.

Hope this help

Angular : Manual redirect to route

This should work

import { Router } from "@angular/router"

export class YourClass{

   constructor(private router: Router) { }

   YourFunction() {


What is the best way to paginate results in SQL Server

These are my solutions for paging the result of query in SQL server side. these approaches are different between SQL Server 2008 and 2012. Also, I have added the concept of filtering and order by with one column. It is very efficient when you are paging and filtering and ordering in your Gridview.

Before testing, you have to create one sample table and insert some row in this table : (In real world you have to change Where clause considering your table fields and maybe you have some join and subquery in main part of select)

Create Table VLT
    ID int IDentity(1,1),
    Name nvarchar(50),
    Tel Varchar(20)

    ('NAME' + Convert(varchar(10),@@identity),'FAMIL' + Convert(varchar(10),@@identity))
GO 500000

In all of these sample, I want to query 200 rows per page and I am fetching the row for page number 1200.

In SQL server 2008, you can use the CTE concept. Because of that, I have written two type of query for SQL server 2008+

-- SQL Server 2008+

DECLARE @PageNumber Int = 1200
DECLARE @PageSize INT = 200
DECLARE @SortByField int = 1 --The field used for sort by
DECLARE @SortOrder nvarchar(255) = 'ASC' --ASC or DESC
DECLARE @FilterType nvarchar(255) = 'None' --The filter type, as defined on the client side (None/Contain/NotContain/Match/NotMatch/True/False/)
DECLARE @FilterValue nvarchar(255) = '' --The value the user gave for the filter
DECLARE @FilterColumn int = 1 --The column to wich the filter is applied, represents the column number like when we send the information.

        OVER( ORDER BY 
                CASE WHEN @SortByField = 1 AND @SortOrder = 'ASC'
                      THEN VLT.ID END ASC,
                CASE WHEN @SortByField = 1 AND @SortOrder = 'DESC'
                      THEN VLT.ID END DESC,
                CASE WHEN @SortByField = 2 AND @SortOrder = 'ASC'
                      THEN VLT.Name END ASC,
                CASE WHEN @SortByField = 2 AND @SortOrder = 'DESC'
                      THEN VLT.Name END ASC,
                CASE WHEN @SortByField = 3 AND @SortOrder = 'ASC'
                      THEN VLT.Tel END ASC,
                CASE WHEN @SortByField = 3 AND @SortOrder = 'DESC'
                      THEN VLT.Tel END ASC
         ) AS RowNum
      ( -- We apply the filter logic here
          WHEN @FilterType = 'None' THEN 1

          -- Name column filter
          WHEN @FilterType = 'Contain' AND @FilterColumn = 1
            AND ( -- In this case, when the filter value is empty, we want to show everything.
                VLT.ID LIKE '%' + @FilterValue + '%'
                @FilterValue = ''
               ) THEN 1
          WHEN @FilterType = 'NotContain' AND @FilterColumn = 1
            AND ( -- In this case, when the filter value is empty, we want to show everything.
                VLT.ID NOT LIKE '%' + @FilterValue + '%'
                @FilterValue = ''
               ) THEN 1
          WHEN @FilterType = 'Match' AND @FilterColumn = 1
            AND VLT.ID = @FilterValue THEN 1
          WHEN @FilterType = 'NotMatch' AND @FilterColumn = 1
            AND VLT.ID <> @FilterValue THEN 1               

          -- Name column filter
          WHEN @FilterType = 'Contain' AND @FilterColumn = 2
            AND ( -- In this case, when the filter value is empty, we want to show everything.
                VLT.Name LIKE '%' + @FilterValue + '%'
                @FilterValue = ''
               ) THEN 1
          WHEN @FilterType = 'NotContain' AND @FilterColumn = 2
            AND ( -- In this case, when the filter value is empty, we want to show everything.
                VLT.Name NOT LIKE '%' + @FilterValue + '%'
                @FilterValue = ''
               ) THEN 1
          WHEN @FilterType = 'Match' AND @FilterColumn = 2
            AND VLT.Name = @FilterValue THEN 1
          WHEN @FilterType = 'NotMatch' AND @FilterColumn = 2
            AND VLT.Name <> @FilterValue THEN 1         

         -- Tel column filter   
         WHEN @FilterType = 'Contain' AND @FilterColumn = 3
            AND ( -- In this case, when the filter value is empty, we want to show everything.
                VLT.Tel LIKE '%' + @FilterValue + '%'
                @FilterValue = ''
               ) THEN 1
          WHEN @FilterType = 'NotContain' AND @FilterColumn = 3
            AND ( -- In this case, when the filter value is empty, we want to show everything.
                VLT.Tel NOT LIKE '%' + @FilterValue + '%'
                @FilterValue = ''
               ) THEN 1
          WHEN @FilterType = 'Match' AND @FilterColumn = 3
            AND VLT.Tel = @FilterValue THEN 1
          WHEN @FilterType = 'NotMatch' AND @FilterColumn = 3
            AND VLT.Tel <> @FilterValue THEN 1    

      ) = 1   
  ) AS Data
WHERE Data.RowNum > @PageSize * (@PageNumber - 1)
  AND Data.RowNum <= @PageSize * @PageNumber
ORDER BY Data.RowNum


And second solution with CTE in SQL server 2008+

DECLARE @PageNumber Int = 1200
DECLARE @PageSize INT = 200
DECLARE @SortByField int = 1 --The field used for sort by
DECLARE @SortOrder nvarchar(255) = 'ASC' --ASC or DESC
DECLARE @FilterType nvarchar(255) = 'None' --The filter type, as defined on the client side (None/Contain/NotContain/Match/NotMatch/True/False/)
DECLARE @FilterValue nvarchar(255) = '' --The value the user gave for the filter
DECLARE @FilterColumn int = 1 --The column to wich the filter is applied, represents the column number like when we send the information.

        OVER( ORDER BY 
                CASE WHEN @SortByField = 1 AND @SortOrder = 'ASC'
                      THEN VLT.ID END ASC,
                CASE WHEN @SortByField = 1 AND @SortOrder = 'DESC'
                      THEN VLT.ID END DESC,
                CASE WHEN @SortByField = 2 AND @SortOrder = 'ASC'
                      THEN VLT.Name END ASC,
                CASE WHEN @SortByField = 2 AND @SortOrder = 'DESC'
                      THEN VLT.Name END ASC,
                CASE WHEN @SortByField = 3 AND @SortOrder = 'ASC'
                      THEN VLT.Tel END ASC,
                CASE WHEN @SortByField = 3 AND @SortOrder = 'DESC'
                      THEN VLT.Tel END ASC
         ) AS RowNum
      ( -- We apply the filter logic here
          WHEN @FilterType = 'None' THEN 1

          -- Name column filter
          WHEN @FilterType = 'Contain' AND @FilterColumn = 1
            AND ( -- In this case, when the filter value is empty, we want to show everything.
                VLT.ID LIKE '%' + @FilterValue + '%'
                @FilterValue = ''
               ) THEN 1
          WHEN @FilterType = 'NotContain' AND @FilterColumn = 1
            AND ( -- In this case, when the filter value is empty, we want to show everything.
                VLT.ID NOT LIKE '%' + @FilterValue + '%'
                @FilterValue = ''
               ) THEN 1
          WHEN @FilterType = 'Match' AND @FilterColumn = 1
            AND VLT.ID = @FilterValue THEN 1
          WHEN @FilterType = 'NotMatch' AND @FilterColumn = 1
            AND VLT.ID <> @FilterValue THEN 1               

          -- Name column filter
          WHEN @FilterType = 'Contain' AND @FilterColumn = 2
            AND ( -- In this case, when the filter value is empty, we want to show everything.
                VLT.Name LIKE '%' + @FilterValue + '%'
                @FilterValue = ''
               ) THEN 1
          WHEN @FilterType = 'NotContain' AND @FilterColumn = 2
            AND ( -- In this case, when the filter value is empty, we want to show everything.
                VLT.Name NOT LIKE '%' + @FilterValue + '%'
                @FilterValue = ''
               ) THEN 1
          WHEN @FilterType = 'Match' AND @FilterColumn = 2
            AND VLT.Name = @FilterValue THEN 1
          WHEN @FilterType = 'NotMatch' AND @FilterColumn = 2
            AND VLT.Name <> @FilterValue THEN 1         

         -- Tel column filter   
         WHEN @FilterType = 'Contain' AND @FilterColumn = 3
            AND ( -- In this case, when the filter value is empty, we want to show everything.
                VLT.Tel LIKE '%' + @FilterValue + '%'
                @FilterValue = ''
               ) THEN 1
          WHEN @FilterType = 'NotContain' AND @FilterColumn = 3
            AND ( -- In this case, when the filter value is empty, we want to show everything.
                VLT.Tel NOT LIKE '%' + @FilterValue + '%'
                @FilterValue = ''
               ) THEN 1
          WHEN @FilterType = 'Match' AND @FilterColumn = 3
            AND VLT.Tel = @FilterValue THEN 1
          WHEN @FilterType = 'NotMatch' AND @FilterColumn = 3
            AND VLT.Tel <> @FilterValue THEN 1    

      ) = 1     

WHERE Data.RowNum > @PageSize * (@PageNumber - 1)
  AND Data.RowNum <= @PageSize * @PageNumber
ORDER BY Data.RowNum

-- SQL Server 2012+

DECLARE @PageNumber Int = 1200
DECLARE @PageSize INT = 200
DECLARE @SortByField int = 1 --The field used for sort by
DECLARE @SortOrder nvarchar(255) = 'ASC' --ASC or DESC
DECLARE @FilterType nvarchar(255) = 'None' --The filter type, as defined on the client side (None/Contain/NotContain/Match/NotMatch/True/False/)
DECLARE @FilterValue nvarchar(255) = '' --The value the user gave for the filter
DECLARE @FilterColumn int = 1 --The column to wich the filter is applied, represents the column number like when we send the information.

      ( -- We apply the filter logic here
          WHEN @FilterType = 'None' THEN 1

          -- Name column filter
          WHEN @FilterType = 'Contain' AND @FilterColumn = 1
            AND ( -- In this case, when the filter value is empty, we want to show everything.
                VLT.ID LIKE '%' + @FilterValue + '%'
                @FilterValue = ''
               ) THEN 1
          WHEN @FilterType = 'NotContain' AND @FilterColumn = 1
            AND ( -- In this case, when the filter value is empty, we want to show everything.
                VLT.ID NOT LIKE '%' + @FilterValue + '%'
                @FilterValue = ''
               ) THEN 1
          WHEN @FilterType = 'Match' AND @FilterColumn = 1
            AND VLT.ID = @FilterValue THEN 1
          WHEN @FilterType = 'NotMatch' AND @FilterColumn = 1
            AND VLT.ID <> @FilterValue THEN 1               

          -- Name column filter
          WHEN @FilterType = 'Contain' AND @FilterColumn = 2
            AND ( -- In this case, when the filter value is empty, we want to show everything.
                VLT.Name LIKE '%' + @FilterValue + '%'
                @FilterValue = ''
               ) THEN 1
          WHEN @FilterType = 'NotContain' AND @FilterColumn = 2
            AND ( -- In this case, when the filter value is empty, we want to show everything.
                VLT.Name NOT LIKE '%' + @FilterValue + '%'
                @FilterValue = ''
               ) THEN 1
          WHEN @FilterType = 'Match' AND @FilterColumn = 2
            AND VLT.Name = @FilterValue THEN 1
          WHEN @FilterType = 'NotMatch' AND @FilterColumn = 2
            AND VLT.Name <> @FilterValue THEN 1         

         -- Tel column filter   
         WHEN @FilterType = 'Contain' AND @FilterColumn = 3
            AND ( -- In this case, when the filter value is empty, we want to show everything.
                VLT.Tel LIKE '%' + @FilterValue + '%'
                @FilterValue = ''
               ) THEN 1
          WHEN @FilterType = 'NotContain' AND @FilterColumn = 3
            AND ( -- In this case, when the filter value is empty, we want to show everything.
                VLT.Tel NOT LIKE '%' + @FilterValue + '%'
                @FilterValue = ''
               ) THEN 1
          WHEN @FilterType = 'Match' AND @FilterColumn = 3
            AND VLT.Tel = @FilterValue THEN 1
          WHEN @FilterType = 'NotMatch' AND @FilterColumn = 3
            AND VLT.Tel <> @FilterValue THEN 1    

      ) = 1         

    CASE WHEN @SortByField = 1 AND @SortOrder = 'ASC'
        THEN Data.ID END ASC,
    CASE WHEN @SortByField = 1 AND @SortOrder = 'DESC'
        THEN Data.ID END DESC,
    CASE WHEN @SortByField = 2 AND @SortOrder = 'ASC'
        THEN Data.Name END ASC,
    CASE WHEN @SortByField = 2 AND @SortOrder = 'DESC'
        THEN Data.Name END ASC,
    CASE WHEN @SortByField = 3 AND @SortOrder = 'ASC'
        THEN Data.Tel END ASC,
    CASE WHEN @SortByField = 3 AND @SortOrder = 'DESC'
        THEN Data.Tel END ASC
OFFSET @PageSize * (@PageNumber - 1) ROWS FETCH NEXT @PageSize ROWS ONLY;

react-native: command not found

If who have error , try it with sudo:

sudo npm install -g react-native-cli

Write bytes to file

This example reads 6 bytes into a byte array and writes it to another byte array. It does an XOR operation with the bytes so that the result written to the file is the same as the original starting values. The file is always 6 bytes in size, since it writes at position 0.

using System;
using System.IO;

namespace ConsoleApplication1
    class Program
        static void Main()
        byte[] b1 = { 1, 2, 4, 8, 16, 32 };
        byte[] b2 = new byte[6];
        byte[] b3 = new byte[6];
        byte[] b4 = new byte[6];

        FileStream f1;
        f1 = new FileStream("test.txt", FileMode.Create, FileAccess.Write);

        // write the byte array into a new file
        f1.Write(b1, 0, 6);

        // read the byte array
        f1 = new FileStream("test.txt", FileMode.Open, FileAccess.Read);

        f1.Read(b2, 0, 6);

        // make changes to the byte array
        for (int i = 1; i < b2.Length; i++)
            b2[i] = (byte)(b2[i] ^ (byte)10); //xor 10

        f1 = new FileStream("test.txt", FileMode.Open, FileAccess.Write);
        // write the new byte array into the file
        f1.Write(b2, 0, 6);

        f1 = new FileStream("test.txt", FileMode.Open, FileAccess.Read);

        // read the byte array
        f1.Read(b3, 0, 6);

        // make changes to the byte array
        for (int i = 1; i < b3.Length; i++)
            b4[i] = (byte)(b3[i] ^ (byte)10); //xor 10

        f1 = new FileStream("test.txt", FileMode.Open, FileAccess.Write);

        // b4 will have the same values as b1
        f1.Write(b4, 0, 6);

Removing a model in rails (reverse of "rails g model Title...")

Try this

rails destroy model Rating

It will remove model, migration, tests and fixtures

Open Url in default web browser

You should use Linking.

Example from the docs:

class OpenURLButton extends React.Component {
  static propTypes = { url: React.PropTypes.string };
  handleClick = () => {
    Linking.canOpenURL(this.props.url).then(supported => {
      if (supported) {
      } else {
        console.log("Don't know how to open URI: " + this.props.url);
  render() {
    return (
      <TouchableOpacity onPress={this.handleClick}>
        {" "}
        <View style={styles.button}>
          {" "}<Text style={styles.text}>Open {this.props.url}</Text>{" "}
        {" "}

Here's an example you can try on Expo Snack:

import React, { Component } from 'react';
import { View, StyleSheet, Button, Linking } from 'react-native';
import { Constants } from 'expo';

export default class App extends Component {
  render() {
    return (
      <View style={styles.container}>
       <Button title="Click me" onPress={ ()=>{ Linking.openURL('')}} />

const styles = StyleSheet.create({
  container: {
    flex: 1,
    alignItems: 'center',
    justifyContent: 'center',
    paddingTop: Constants.statusBarHeight,
    backgroundColor: '#ecf0f1',

What tool to use to draw file tree diagram

Graphviz - from the web page:

The Graphviz layout programs take descriptions of graphs in a simple text language, and make diagrams in several useful formats such as images and SVG for web pages, Postscript for inclusion in PDF or other documents; or display in an interactive graph browser. (Graphviz also supports GXL, an XML dialect.)

It's the simplest and most productive tool I've found to create a variety of boxes-and-lines diagrams. I have and use Visio and OmniGraffle, but there's always the temptation to make "just one more adjustment".

It's also quite easy to write code to produce the "dot file" format that Graphiz consumes, so automated diagram production is also nicely within reach.

How to make full screen background in a web page

Use this CSS to make full screen backgound in a web page.

body {
    background:url("") no-repeat center center fixed;
    -webkit-background-size: cover;
    -moz-background-size: cover;
    -o-background-size: cover;
    background-size: cover;

WHERE Clause to find all records in a specific month

I think the function you're looking for is MONTH(date). You'll probably want to use 'YEAR' too.

Let's assume you have a table named things that looks something like this:

id happend_at
-- ----------------
1  2009-01-01 12:08
2  2009-02-01 12:00
3  2009-01-12 09:40
4  2009-01-29 17:55

And let's say you want to execute to find all the records that have a happened_at during the month 2009/01 (January 2009). The SQL query would be:

SELECT id FROM things 
   WHERE MONTH(happened_at) = 1 AND YEAR(happened_at) = 2009

Which would return:


Getting URL hash location, and using it in jQuery

Editor's note: the approach below has serious security implications and, depending upon the version of jQuery you are using, may expose your users to XSS attacks. For more detail, see the discussion of the possible attack in the comments on this answer or this explanation on Security Stack Exchange.

You can use the location.hash property to grab the hash of the current page:

var hash = window.location.hash;

Note that this property already contains the # symbol at the beginning.

Actually you don't need the :first pseudo-selector since you are using the ID selector, is assumed that IDs are unique within the DOM.

In case you want to get the hash from an URL string, you can use the String.substring method:

var url = "";
var hash = url.substring(url.indexOf('#')); // '#foo'

Advice: Be aware that the user can change the hash as he wants, injecting anything to your selector, you should check the hash before using it.

Run Function After Delay

$(document).ready(function() {

  // place this within dom ready function
  function showpanel() {     

 // use setTimeout() to execute
 setTimeout(showpanel, 1000)


For more see here

Can't install laravel installer via composer

zip extension is missing, You can avoid this error by simple running below command, It will take version by default

sudo apt-get install php-zip

In case you need any specific version, You need to mention a specific version of your php, Suppose I need to install X version of php-zip then the command will be.

sudo apt-get install phpX-zip  

Replace X with your required version, In my case, it is X = 7.3

How do I commit only some files?

I think you may also use the command line :

git add -p

This allows you to review all your uncommited files, one by one and choose if you want to commit them or not.

Then you have some options that will come up for each modification: I use the "y" for "yes I want to add this file" and the "n" for "no, I will commit this one later".

Stage this hunk [y,n,q,a,d,K,g,/,e,?]?

As for the other options which are ( q,a,d,K,g,/,e,? ), I'm not sure what they do, but I guess the "?" might help you out if you need to go deeper into details.

The great thing about this is that you can then push your work, and create a new branch after and all the uncommited work will follow you on that new branch. Very useful if you have coded many different things and that you actually want to reorganise your work on github before pushing it.

Hope this helps, I have not seen it said previously (if it was mentionned, my bad)

invalid byte sequence for encoding "UTF8"

I ran into this problem under Windows while working exclusively with psql (no graphical tools). To fix this problem, permanently change the default encoding of psql (client) to match the default encoding of the PostgreSQL server. Run the following command in CMD or Powershell:


Close and reopen you command prompt/Powershell for the change to take effect.

Change the encoding of the backup file from Unicode to UTF8 by opening it with Notepad and going to File -> Save As. Change the Encoding dropdown from Unicode to UTF8. (Also change the Save as type from Text Documents (.txt) to All Files in order to avoid adding the .txt extension to your backup file's name). You should now be able to restore your backup.

Simple argparse example wanted: 1 argument, 3 results

Here's what I came up with in my learning project thanks mainly to @DMH...

Demo code:

import argparse

def main():
    parser = argparse.ArgumentParser()
    parser.add_argument('-f', '--flag', action='store_true', default=False)  # can 'store_false' for no-xxx flags
    parser.add_argument('-r', '--reqd', required=True)
    parser.add_argument('-o', '--opt', default='fallback')
    parser.add_argument('arg', nargs='*') # use '+' for 1 or more args (instead of 0 or more)
    parsed = parser.parse_args()
    # NOTE: args with '-' have it replaced with '_'
    print('Result:',  vars(parsed))
    print('parsed.reqd:', parsed.reqd)

if __name__ == "__main__":

This may have evolved and is available online:

Script to give this code a workout:

Export to csv/excel from kibana

FYI : How to download data in CSV from Kibana:

In Kibana--> 1. Go to 'Discover' in left side

  1. Select Index Field (based on your dashboard data) (*** In case if you are not sure which index to select-->go to management tab-->Saved Objects-->Dashboard-->select dashboard name-->scroll down to JSON-->you will see the Index name )

  2. left side you see all the variables available in the data-->click over the variable name that you want to have in csv-->click add-->this variable will be added on the right side of the columns avaliable

  3. Top right section of the kibana-->there is the time filter-->click -->select the duration for which you want the csv

  4. Top upper right -->Reporting-->save this time/variable selection with a new report-->click generate CSV

  5. Go to 'Management' in left side--> 'Reporting'-->download your csv

Response.Redirect with POST instead of Get?

The GET (and HEAD) method should never be used to do anything that has side-effects. A side-effect might be updating the state of a web application, or it might be charging your credit card. If an action has side-effects another method (POST) should be used instead.

So, a user (or their browser) shouldn't be held accountable for something done by a GET. If some harmful or expensive side-effect occurred as the result of a GET, that would be the fault of the web application, not the user. According to the spec, a user agent must not automatically follow a redirect unless it is a response to a GET or HEAD request.

Of course, a lot of GET requests do have some side-effects, even if it's just appending to a log file. The important thing is that the application, not the user, should be held responsible for those effects.

The relevant sections of the HTTP spec are 9.1.1 and 9.1.2, and 10.3.

How can I capture the result of var_dump to a string?

Also echo json_encode($dataobject); might be helpful

What is the difference between char s[] and char *s?

This declaration:

char s[] = "hello";

Creates one object - a char array of size 6, called s, initialised with the values 'h', 'e', 'l', 'l', 'o', '\0'. Where this array is allocated in memory, and how long it lives for, depends on where the declaration appears. If the declaration is within a function, it will live until the end of the block that it is declared in, and almost certainly be allocated on the stack; if it's outside a function, it will probably be stored within an "initialised data segment" that is loaded from the executable file into writeable memory when the program is run.

On the other hand, this declaration:

char *s ="hello";

Creates two objects:

  • a read-only array of 6 chars containing the values 'h', 'e', 'l', 'l', 'o', '\0', which has no name and has static storage duration (meaning that it lives for the entire life of the program); and
  • a variable of type pointer-to-char, called s, which is initialised with the location of the first character in that unnamed, read-only array.

The unnamed read-only array is typically located in the "text" segment of the program, which means it is loaded from disk into read-only memory, along with the code itself. The location of the s pointer variable in memory depends on where the declaration appears (just like in the first example).

How to check if a string starts with one of several prefixes?

Of course, be mindful that your program will only be useful in english speaking countries if you detect dates this way. You might want to consider:

Set<String> dayNames = Calendar.getInstance()

From there you can use .startsWith or .matches or whatever other method that others have mentioned above. This way you get the default locale for the jvm. You could always pass in the locale (and maybe default it to the system locale if it's null) as well to be more robust.

Deserialize from string instead TextReader

static T DeserializeXml<T>(string sourceXML) where T : class
    var serializer = new XmlSerializer(typeof(T));
    T result = null;

    using (TextReader reader = new StringReader(sourceXML))
        result = (T) serializer.Deserialize(reader);

    return result;

How can I color dots in a xy scatterplot according to column value?

I see there is a VBA solution and a non-VBA solution, which both are really good. I wanted to propose my Javascript solution.

There is an Excel add-in called Funfun that allows you to use javascript, HTML and css in Excel. It has an online editor with an embedded spreadsheet where you can build your chart.

I have written this code for you with Chart.js:

To create this chart, I entered my data on the spreadsheet and read it with a json file, it is the short file.

I make sure to put it in the right format, in script.js, so I can add it to my chart:

var data = [];
var color = [];
var label = [];

for (var i = 1; i < $; i++)
    data.push([$[i][1], $[i][2]]);

I then create the scatter chart with each dot having his designated color and position:

 var dataset = [];
  for (var i = 0; i < data.length; i++) {   
      data: [{
        x: data[i][0],
        y: data[i][1] 
      pointBackgroundColor: color[i],
      pointStyle: "cercle",
      radius: 6  

After I've created my scatter chart I can upload it in Excel by pasting the URL in the funfun Excel add-in. Here is how it looks like with my example:


Once this is done You can change the color or the position of a dot instantly, in Excel, by changing the values in the spreadsheet.

If you want to add extra dots in the charts you just need to modify the radius of data in the short json file.

Hope this Javascript solution helps !

Disclosure : I’m a developer of funfun

Creating random numbers with no duplicates

There is algorithm of card batch: you create ordered array of numbers (the "card batch") and in every iteration you select a number at random position from it (removing the selected number from the "card batch" of course).

IOError: [Errno 32] Broken pipe: Python

A "Broken Pipe" error occurs when you try to write to a pipe that has been closed on the other end. Since the code you've shown doesn't involve any pipes directly, I suspect you're doing something outside of Python to redirect the standard output of the Python interpreter to somewhere else. This could happen if you're running a script like this:

python | someothercommand

The issue you have is that someothercommand is exiting without reading everything available on its standard input. This causes your write (via print) to fail at some point.

I was able to reproduce the error with the following command on a Linux system:

python -c 'for i in range(1000): print i' | less

If I close the less pager without scrolling through all of its input (1000 lines), Python exits with the same IOError you have reported. :connection timed out: connect?

If you're pointing the config at a domain (eg, do an NSLOOKUP to ensure all the responding IPs are valid, and can be connected to on port 389:


Test-NetConnection <IP returned from NSLOOKUP> -port 389

recyclerview No adapter attached; skipping layout

Just add the following to RecyclerView



   < xmlns:android=""


Running Bash commands in Python

You can use subprocess, but I always felt that it was not a 'Pythonic' way of doing it. So I created Sultan (shameless plug) that makes it easy to run command line functions.

Send a SMS via intent

I have developed this functionality from one Blog. There are 2 ways you can send SMS.

  1. Open native SMS composer
  2. write your message and send from your Android application

This is the code of 1st method.


<?xml version="1.0" encoding="utf-8"?>  

               android:text="Send SMS"  


public class SendSMSActivity extends Activity {  
     /** Called when the activity is first created. */  
     public void onCreate(Bundle savedInstanceState) {  

     public void sendSMS(View v)  
         String number = "12346556";  // The number on which you want to send SMS  
         startActivity(new Intent(Intent.ACTION_VIEW, Uri.fromParts("sms", number, null)));  
    /* or 
     public void sendSMS(View v) 
     Uri uri = Uri.parse("smsto:12346556"); 
         Intent it = new Intent(Intent.ACTION_SENDTO, uri); 
         it.putExtra("sms_body", "Here you can set the SMS text to be sent"); 
      } */  

NOTE:- In this method, you don’t require SEND_SMS permission inside the AndroidManifest.xml file.

For 2nd method refer to this BLOG. You will find a good explanation from here.

Hope this will help you...

LINQ: "contains" and a Lambda query

Use Any() instead of Contains():

buildingStatus.Any(item => item.GetCharValue() == v.Status)

What is the difference between Left, Right, Outer and Inner Joins?

SQL JOINS difference:

Very simple to remember :

INNER JOIN only show records common to both tables.

OUTER JOIN all the content of the both tables are merged together either they are matched or not.

LEFT JOIN is same as LEFT OUTER JOIN - (Select records from the first (left-most) table with matching right table records.)

RIGHT JOIN is same as RIGHT OUTER JOIN - (Select records from the second (right-most) table with matching left table records.)

enter image description here

How to configure Docker port mapping to use Nginx as an upstream proxy?

Just found an article from Anand Mani Sankar wich shows a simple way of using nginx upstream proxy with docker composer.

Basically one must configure the instance linking and ports at the docker-compose file and update upstream at nginx.conf accordingly.

Get all files modified in last 30 days in a directory

A couple of issues

  • You're not limiting it to files, so when it finds a matching directory it will list every file within it.
  • You can't use > in -exec without something like bash -c '... > ...'. Though the > will overwrite the file, so you want to redirect the entire find anyway rather than each -exec.
  • +30 is older than 30 days, -30 would be modified in last 30 days.
  • -exec really isn't needed, you could list everything with various -printf options.

Something like below should work

find . -type f -mtime -30 -exec ls -l {} \; > last30days.txt

Example with -printf

find . -type f -mtime -30 -printf "%M %u %g %TR %TD %p\n" > last30days.txt

This will list files in format "permissions owner group time date filename". -printf is generally preferable to -exec in cases where you don't have to do anything complicated. This is because it will run faster as a result of not having to execute subshells for each -exec. Depending on the version of find, you may also be able to use -ls, which has a similar format to above.

Changing width property of a :before css selector using JQuery

Pseudo-elements are not part of the DOM, so they can't be manipulated using jQuery or Javascript.

But as pointed out in the accepted answer, you can use the JS to append a style block which ends of styling the pseudo-elements.

How do I exit the results of 'git diff' in Git Bash on windows?

Using WIN + Q worked for me. Just q alone gave me "command not found" and eventually it jumped back into the git diff insanity.

Determine if a cell (value) is used in any formula

On Excel 2010 try this:

  1. select the cell you want to check if is used somewhere in a formula;
  2. Formulas -> Trace Dependents (on Formula Auditing menu)

Convert HTML5 into standalone Android App

You could use PhoneGap.

This has the benefit of being a cross-platform solution. Be warned though that you may need to pay subscription fees. The simplest solution is to just embed a WebView as detailed in @Enigma's answer.

Using Javascript: How to create a 'Go Back' link that takes the user to a link if there's no history for the tab or window?

The reason on using the return:false; is well explained on this other question.

For the other issue, you can check for the referrer to see if it is empty:

    function backAway(){
        if (document.referrer == "") { //alternatively, window.history.length == 0
            window.location = "";
        } else {

<a href="#" onClick="backAway()">Back Button Here.</a>

How do I read from parameters.yml in a controller in symfony2?

In Symfony 4, you can use the ParameterBagInterface:

use Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface;

class MessageGenerator
    private $params;

    public function __construct(ParameterBagInterface $params)
        $this->params = $params;

    public function someMethod()
        $parameterValue = $this->params->get('parameter_name');
        // ...

and in app/config/services.yaml:

    locale: 'en'
    dir: '%kernel.project_dir%'

It works for me in both controller and form classes. More details can be found in the Symfony blog.

What is the meaning of git reset --hard origin/master?

In newer version of git (2.23+) you can use:

git switch -C master origin/master

-C is same as --force-create. Related Reference Docs

Python: Select subset from list based on index set

Matlab and Scilab languages offer a simpler and more elegant syntax than Python for the question you're asking, so I think the best you can do is to mimic Matlab/Scilab by using the Numpy package in Python. By doing this the solution to your problem is very concise and elegant:

from numpy import *
property_a = array([545., 656., 5.4, 33.])
property_b = array([ 1.2,  1.3, 2.3, 0.3])
good_objects = [True, False, False, True]
good_indices = [0, 3]
property_asel = property_a[good_objects]
property_bsel = property_b[good_indices]

Numpy tries to mimic Matlab/Scilab but it comes at a cost: you need to declare every list with the keyword "array", something which will overload your script (this problem doesn't exist with Matlab/Scilab). Note that this solution is restricted to arrays of number, which is the case in your example.

Create a SQL query to retrieve most recent records

The derived table would work, but if this is SQL 2005, a CTE and ROW_NUMBER might be cleaner:

WITH UserStatus (User, Date, Status, Notes, Ord)
SELECT Date, User, Status, Notes, 

SELECT User, Date, Status, Notes from UserStatus where Ord = 1

This would also facilitate the display of the most recent x statuses from each user.

Setting property 'source' to 'org.eclipse.jst.jee.server:JSFTut' did not find a matching property

This is not an error. This is a warning. The difference is pretty huge. This particular warning basically means that the <Context> element in Tomcat's server.xml contains an unknown attribute source and that Tomcat doesn't know what to do with this attribute and therefore will ignore it.

Eclipse WTP adds a custom attribute source to the project related <Context> element in the server.xml of Tomcat which identifies the source of the context (the actual project in the workspace which is deployed to the particular server). This way Eclipse can correlate the deployed webapplication with an project in the workspace. Since Tomcat version 6.0.16, any unspecified XML tags and attributes in the server.xml will produce a warning during Tomcat's startup, even though there is no DTD nor XSD for server.xml.

Just ignore it. Your web project is fine. It should run fine. This issue is completely unrelated to JSF.

Concatenate String in String Objective-c

Variations on a theme:

NSString *varying = @"whatever it is";
NSString *final = [NSString stringWithFormat:@"first part %@ third part", varying];

NSString *varying = @"whatever it is";
NSString *final = [[@"first part" stringByAppendingString:varying] stringByAppendingString:@"second part"];

NSMutableString *final = [NSMutableString stringWithString:@"first part"];
[final appendFormat:@"%@ third part", varying];

NSMutableString *final = [NSMutableString stringWithString:@"first part"];
[final appendString:varying];
[final appendString:@"third part"];

How would I get a cron job to run every 30 minutes?

Try this:

0,30 * * * * your command goes here

According to the official Mac OS X crontab(5) manpage, the / syntax is supported. Thus, to figure out why it wasn't working for you, you'll need to look at the logs for cron. In those logs, you should find a clear failure message.

Note: Mac OS X appears to use Vixie Cron, the same as Linux and the BSDs. MVC ModelState.Clear

Well the ModelState basically holds the current State of the model in terms of validation, it holds

ModelErrorCollection: Represent the errors when the model try to bind the values. ex.


or like a parameter in the ActionResult

public ActionResult Create(Person person)

ValueProviderResult: Hold the details about the attempted bind to the model. ex. AttemptedValue, Culture, RawValue.

Clear() method must be use with caution because it can lead to unspected results. And you will lose some nice properties of the ModelState like AttemptedValue, this is used by MVC in the background to repopulate the form values in case of error.


Bootstrap 3 - Responsive mp4-video

Tip for MULTIPLE VIDEOS on a page: I recently solved an issue with no mp4 playback in Chrome or Firefox (played fine in IE) in a page with 16 videos in modals (bootstrap 3) after discovering the frame rates of all the videos must be identical. I had 6 videos at 25fps and 12 at 29.97fps... after rendering all to 25fps versions, everything runs smooth across all browsers.

How can I open Java .class files in a human-readable way?

you can also use the online java decompilers available. For e.g.

A function to convert null to string

You can use Convert.ToString((object)value). You need to cast your value to an object first, otherwise the conversion will result in a null.

using System;

public class Program
    public static void Main()
        string format = "    Convert.ToString({0,-20}) == null? {1,-5},  == empty? {2,-5}";
        object nullObject = null;
        string nullString = null;

        string convertedString = Convert.ToString(nullObject);
        Console.WriteLine(format, "nullObject", convertedString == null, convertedString == "");

        convertedString = Convert.ToString(nullString);
        Console.WriteLine(format, "nullString", convertedString == null, convertedString == "");

        convertedString = Convert.ToString((object)nullString);
        Console.WriteLine(format, "(object)nullString", convertedString == null, convertedString == "");



Convert.ToString(nullObject          ) == null? False,  == empty? True 
Convert.ToString(nullString          ) == null? True ,  == empty? False
Convert.ToString((object)nullString  ) == null? False,  == empty? True

If you pass a System.DBNull.Value to Convert.ToString() it will be converted to an empty string too.

Which is better, return value or out parameter?

You should generally prefer a return value over an out param. Out params are a necessary evil if you find yourself writing code that needs to do 2 things. A good example of this is the Try pattern (such as Int32.TryParse).

Let's consider what the caller of your two methods would have to do. For the first example I can write this...

int foo = GetValue();

Notice that I can declare a variable and assign it via your method in one line. FOr the 2nd example it looks like this...

int foo;
GetValue(out foo);

I'm now forced to declare my variable up front and write my code over two lines.


A good place to look when asking these types of question is the .NET Framework Design Guidelines. If you have the book version then you can see the annotations by Anders Hejlsberg and others on this subject (page 184-185) but the online version is here...

If you find yourself needing to return two things from an API then wrapping them up in a struct/class would be better than an out param.

How to add a new column to an existing sheet and name it?

For your question as asked

Range("c1:c4") = Application.Transpose(Array("Loc", "uk", "us", "nj"))

If you had a way of automatically looking up the data (ie matching uk against employer id) then you could do that in VBA

Selenium Webdriver: Entering text into text field

Use this code.


ES6 Map in Typescript

Yes Map is now available in typescript.. if you look in lib.es6.d.ts, you will see the interface:

interface Map<K, V> {
  clear(): void;
  delete(key: K): boolean;
  forEach(callbackfn: (value: V, key: K, map: Map<K, V>) => void,thisArg?: any): void;
  get(key: K): V | undefined;
  has(key: K): boolean;
  set(key: K, value: V): this;
  readonly size: number;} 

Its great to use as a dictionary of string,object pairs.. the only annoyance is that if you are using it to assign values elsewhere with Map.get(key) the IDE like Code gives you problems about being possible undefined.. rather than creating a variable with an is-defined check .. simply cast the type (assuming you know for sure the map has the key-value pair)

class myclass {
   mymap = new Map<string,object>()
   let objectref = <AnObject>mymap.get("akey")

How to modify a text file?

Wrote a small class for doing this cleanly.

import tempfile

class FileModifierError(Exception):

class FileModifier(object):

    def __init__(self, fname):
        self.__write_dict = {}
        self.__filename = fname
        self.__tempfile = tempfile.TemporaryFile()
        with open(fname, 'rb') as fp:
            for line in fp:

    def write(self, s, line_number = 'END'):
        if line_number != 'END' and not isinstance(line_number, (int, float)):
            raise FileModifierError("Line number %s is not a valid number" % line_number)
        except KeyError:
            self.__write_dict[line_number] = [s]

    def writeline(self, s, line_number = 'END'):
        self.write('%s\n' % s, line_number)

    def writelines(self, s, line_number = 'END'):
        for ln in s:
            self.writeline(s, line_number)

    def __popline(self, index, fp):
            ilines = self.__write_dict.pop(index)
            for line in ilines:
        except KeyError:

    def close(self):
        self.__exit__(None, None, None)

    def __enter__(self):
        return self

    def __exit__(self, type, value, traceback):
        with open(self.__filename,'w') as fp:
            for index, line in enumerate(self.__tempfile.readlines()):
                self.__popline(index, fp)
            for index in sorted(self.__write_dict):
                for line in self.__write_dict[index]:

Then you can use it this way:

with FileModifier(filename) as fp:
    fp.writeline("String 1", 0)
    fp.writeline("String 2", 20)
    fp.writeline("String 3")  # To write at the end of the file

Accessing localhost (xampp) from another computer over LAN network - how to?

Just try:

http://ipaddressofpcwhichhasdatabase:portnumber(80 by default)/filename.extension

How to unapply a migration in ASP.NET Core with EF Core

Note: It might be troublesome later on, I used it as a last resort since non of the solutions provided above and others did not work in my case:

  1. Copy the code from the body of previous successful migration's down() method.
  2. Add a new migration using Add-Migration "migration-name"
  3. Paste the copied code from the down() method of previous migration to the new migration's Up() method:
    Up(){ //paste here }
  4. Run Update-Database
  5. Done, your changes from the previous migration should now have been reverted!


In IMPALA, not having order in the GROUP_CONCAT can be problematic, over at Coders'Co. we have some sort of a workaround for that (we need it for Rax/Impala). If you need the GROUP_CONCAT result with an ORDER BY clause in IMPALA, take a look at this blog post:

How can I select the record with the 2nd highest salary in database Oracle?

select max(Salary) from EmployeeTest where Salary < ( select max(Salary) from EmployeeTest ) ;

this will work for all DBs.

Tracing XML request/responses with JAX-WS

There are a couple of answers using SoapHandlers in this thread. You should know that SoapHandlers modify the message if writeTo(out) is called.

Calling SOAPMessage's writeTo(out) method automatically calls saveChanges() method also. As a result all attached MTOM/XOP binary data in a message is lost.

I am not sure why this is happening, but it seems to be a documented feature.

In addition, this method marks the point at which the data from all constituent AttachmentPart objects are pulled into the message.

Array.size() vs Array.length

The property 'length' returns the (last_key + 1) for arrays with numeric keys:

var  nums  =  new  Array ();
nums [ 10 ]  =  10 ; 
nums [ 11 ]  =  11 ; nums.length );

will print 12!

This will work:

var  nums  =  new  Array ();
nums [ 10 ]  =  10 ; 
nums [ 11 ]  =  11 ;
nums [ 12 ]  =  12 ; nums.length + '  /  '+ Object.keys(nums).length );

Get yesterday's date using Date

changed from your code :

private String toDate(long timestamp) {
    Date date = new Date (timestamp * 1000 -  24 * 60 * 60 * 1000);
   return new SimpleDateFormat("yyyy-MM-dd").format(date).toString();


but you do better using calendar.

Location of ini/config files in linux/unix?

  1. Generally system/global config is stored somewhere under /etc.
  2. User-specific config is stored in the user's home directory, often as a hidden file, sometimes as a hidden directory containing non-hidden files (and possibly more subdirectories).

Generally speaking, command line options will override environment variables which will override user defaults which will override system defaults.

How to get Client location using Google Maps API v3?

Try this :)

    <script type="text/javascript" src=""></script>
    <script type="text/javascript">
    function initialize() {
        var loc = {};
        var geocoder = new google.maps.Geocoder();
        if(google.loader.ClientLocation) {
   = google.loader.ClientLocation.latitude;
            loc.lng = google.loader.ClientLocation.longitude;

            var latlng = new google.maps.LatLng(, loc.lng);
            geocoder.geocode({'latLng': latlng}, function(results, status) {
                if(status == google.maps.GeocoderStatus.OK) {

    google.load("maps", "3.x", {other_params: "sensor=false", callback:initialize});


SQL Error with Order By in Subquery

Try moving the order by clause outside sub select and add the order by field in sub select


(SELECT COUNT(1) ,refKlinik_id FROM Seanslar WHERE MONTH(tarihi) = 4 GROUP BY refKlinik_id)
as dorduncuay 

ORDER BY refKlinik_id 

Can we instantiate an abstract class directly?

No, abstract class can never be instantiated.

How do you force a CIFS connection to unmount

I had a very similar problem with davfs. In the man page of umount.davfs, I found that the -f -l -n -r -v options are ignored by umount.davfs. To force-unmount my davfs mount, I had to use umount -i -f -l /media/davmount.

How can I change the color of a Google Maps marker?

This relatively recent article provides a simple example with a limited Google Maps set of colored icons.

lists and arrays in VBA

You will have to change some of your data types but the basics of what you just posted could be converted to something similar to this given the data types I used may not be accurate.

Dim DateToday As String: DateToday = Format(Date, "yyyy/MM/dd")
Dim Computers As New Collection
Dim disabledList As New Collection
Dim compArray(1 To 1) As String

'Assign data to first item in array
compArray(1) = "asdf"

'Format = Item, Key
Computers.Add "ErrorState", "Computer Name"

'Prints "ErrorState"
Debug.Print Computers("Computer Name")

Collections cannot be sorted so if you need to sort data you will probably want to use an array.

Here is a link to the outlook developer reference.

Another great site to help you get started is

Moving everything over to VBA from VB.Net is not going to be simple since not all the data types are the same and you do not have the .Net framework. If you get stuck just post the code you're stuck converting and you will surely get some help!


Sub ArrayExample()
    Dim subject As String
    Dim TestArray() As String
    Dim counter As Long

    subject = "Example"
    counter = Len(subject)

    ReDim TestArray(1 To counter) As String

    For counter = 1 To Len(subject)
        TestArray(counter) = Right(Left(subject, counter), 1)
End Sub

In Python, how do you convert seconds since epoch to a `datetime` object?

From the docs, the recommended way of getting a timezone aware datetime object from seconds since epoch is:

Python 3:

from datetime import datetime, timezone
datetime.fromtimestamp(timestamp, timezone.utc)

Python 2, using pytz:

from datetime import datetime
import pytz
datetime.fromtimestamp(timestamp, pytz.utc)

Change x axes scale in matplotlib

The scalar formatter supports collecting the exponents. The docs are as follows:

class matplotlib.ticker.ScalarFormatter(useOffset=True, useMathText=False, useLocale=None) Bases: matplotlib.ticker.Formatter

Tick location is a plain old number. If useOffset==True and the data range is much smaller than the data average, then an offset will be determined such that the tick labels are meaningful. Scientific notation is used for data < 10^-n or data >= 10^m, where n and m are the power limits set using set_powerlimits((n,m)). The defaults for these are controlled by the axes.formatter.limits rc parameter.

your technique would be:

from matplotlib.ticker import ScalarFormatter
xfmt = ScalarFormatter()
xfmt.set_powerlimits((-3,3))  # Or whatever your limits are . . .
{{ Make your plot }}

To get the exponent displayed in the format x10^5, instantiate the ScalarFormatter with useMathText=True.

After Image

You could also use:


To get a result like this:

enter image description here

how to run a winform from console application?

If you want to escape from Form Freeze and use editing (like text for a button) use this code

Form form = new Form();
Form.Button.Text = "randomText";

How do you change video src using jQuery?

What worked for me was issuing the 'play' command after changing the source. Strangely you cannot use 'play()' through a jQuery instance so you just use getElementByID as follows:


<video id="videoplayer" width="480" height="360"></video>


$("#videoplayer").html('<source src="'+strSRC+'" type="'+strTYPE+'"></source>' );

Find row number of matching value

For your first method change ws.Range("A") to ws.Range("A:A") which will search the entirety of column a, like so:

Sub Find_Bingo()

        Dim wb As Workbook
        Dim ws As Worksheet
        Dim FoundCell As Range
        Set wb = ActiveWorkbook
        Set ws = ActiveSheet

            Const WHAT_TO_FIND As String = "Bingo"

            Set FoundCell = ws.Range("A:A").Find(What:=WHAT_TO_FIND)
            If Not FoundCell Is Nothing Then
                MsgBox (WHAT_TO_FIND & " found in row: " & FoundCell.Row)
                MsgBox (WHAT_TO_FIND & " not found")
            End If
End Sub

For your second method, you are using Bingo as a variable instead of a string literal. This is a good example of why I add Option Explicit to the top of all of my code modules, as when you try to run the code it will direct you to this "variable" which is undefined and not intended to be a variable at all.

Additionally, when you are using With...End With you need a period . before you reference Cells, so Cells should be .Cells. This mimics the normal qualifying behavior (i.e. Sheet1.Cells.Find..)

Change Bingo to "Bingo" and change Cells to .Cells

With Sheet1
        Set FoundCell = .Cells.Find(What:="Bingo", After:=.Cells(1, 1), _
        LookIn:=xlValues, lookat:=xlPart, SearchOrder:=xlByRows, _
        SearchDirection:=xlNext, MatchCase:=False, SearchFormat:=False)
    End With

If Not FoundCell Is Nothing Then
        MsgBox ("""Bingo"" found in row " & FoundCell.Row)
        MsgBox ("Bingo not found")
End If


In my

With Sheet1
End With

The Sheet1 refers to a worksheet's code name, not the name of the worksheet itself. For example, say I open a new blank Excel workbook. The default worksheet is just Sheet1. I can refer to that in code either with the code name of Sheet1 or I can refer to it with the index of Sheets("Sheet1"). The advantage to using a codename is that it does not change if you change the name of the worksheet.

Continuing this example, let's say I renamed Sheet1 to Data. Using Sheet1 would continue to work, as the code name doesn't change, but now using Sheets("Sheet1") would return an error and that syntax must be updated to the new name of the sheet, so it would need to be Sheets("Data").

In the VB Editor you would see something like this:

code object explorer example

Notice how, even though I changed the name to Data, there is still a Sheet1 to the left. That is what I mean by codename.

The Data worksheet can be referenced in two ways:

Debug.Print Sheet1.Name
Debug.Print Sheets("Data").Name

Both should return Data

More discussion on worksheet code names can be found here.

What does the Excel range.Rows property really do?

Range.Rows, Range.Columns and Range.Cells are Excel.Range objects, according to the VBA Type() functions:

However, that's not the whole story: those returned objects are extended types that inherit every property and method from Excel::Range - but .Columns and .Rows have a special For... Each iterator, and a special .Count property that aren't quite the same as the parent Range object's iterator and count.

So .Cells is iterated and counted as a collection of single-cell ranges, just like the default iterator of the parent range.

But .Columns is iterated and counted as a collection of vertical subranges, each of them a single column wide;

...And .Rows is iterated and counted as a collection of horizontal subranges, each of them a single row high.

The easiest way to understand this is to step through this code and watch what's selected:

Public Sub Test() 
Dim SubRange As Range Dim ParentRange As Range
Set ParentRange = ActiveSheet.Range("B2:E5")

For Each SubRange In ParentRange.Cells SubRange.Select Next
For Each SubRange In ParentRange.Rows SubRange.Select Next
For Each SubRange In ParentRange.Columns SubRange.Select Next
For Each SubRange In ParentRange SubRange.Select Next
End Sub
Enjoy. And try it with a couple of merged cells in there, just to see how odd merged ranges can be.

Remove the complete styling of an HTML button/submit

I think this provides a more thorough approach:

button, input[type="submit"], input[type="reset"] {_x000D_
 background: none;_x000D_
 color: inherit;_x000D_
 border: none;_x000D_
 padding: 0;_x000D_
 font: inherit;_x000D_
 cursor: pointer;_x000D_
 outline: inherit;_x000D_

Convert dictionary to list collection in C#

If you want to pass the Dictionary keys collection into one method argument.

List<string> lstKeys = Dict.Keys;
void MethodName(List<String> lstkeys)
    `enter code here`
    //Do ur task

How do I remove all non-ASCII characters with regex and Notepad++?

Click on View/Show Symbol/Show All Character - to show the [SOH] characters in the file Click on the [SOH] symbol in the file CTRL=H to bring up the replace Leave the 'Find What:' as is Change the 'Replace with:' to the character of your choosing (comma,semicolon, other...) Click 'Replace All' Done and done!

AngularJS - value attribute for select

It appears it's not possible to actually use the "value" of a select in any meaningful way as a normal HTML form element and also hook it up to Angular in the approved way with ng-options. As a compromise, I ended up having to put a hidden input alongside my select and have it track the same model as my select, like this (all very much simplified from real production code for brevity):


<select ng-model="profile" ng-options=" as for o in profiles" name="something_i_dont_care_about">
<input name="profile_id" type="text" style="margin-left:-10000px;" ng-model="profile"/>


App.controller('ConnectCtrl',function ConnectCtrl($scope) {
$scope.profiles = [{id:'xyz', name:'a profile'},{id:'abc', name:'another profile'}];
$scope.profile = -1;

Then, in my server-side code I just looked for params[:profile_id] (this happened to be a Rails app, but the same principle applies anywhere). Because the hidden input tracks the same model as the select, they stay in sync automagically (no additional javascript necessary). This is the cool part of Angular. It almost makes up for what it does to the value attribute as a side effect.

Interestingly, I found this technique only worked with input tags that were not hidden (which is why I had to use the margin-left:-10000px; trick to move the input off the page). These two variations did not work:

<input name="profile_id" type="text" style="display:none;" ng-model="profile"/>


<input name="profile_id" type="hidden" ng-model="profile"/>

I feel like that must mean I'm missing something. It seems too weird for it to be a problem with Angular.

Javascript call() & apply() vs bind()?

Use bind for future calls to the function. Both apply and call invoke the function.

bind() also allows for additional arguments to be perpended to the args array.

Change type of varchar field to integer: "cannot be cast automatically to type integer"

this worked for me.

change varchar column to int

change_column :table_name, :column_name, :integer


PG::DatatypeMismatch: ERROR:  column "column_name" cannot be cast automatically to type integer
HINT:  Specify a USING expression to perform the conversion.

chnged to

change_column :table_name, :column_name, 'integer USING CAST(column_name AS integer)'

C++11 rvalues and move semantics confusion (return statement)

The simple answer is you should write code for rvalue references like you would regular references code, and you should treat them the same mentally 99% of the time. This includes all the old rules about returning references (i.e. never return a reference to a local variable).

Unless you are writing a template container class that needs to take advantage of std::forward and be able to write a generic function that takes either lvalue or rvalue references, this is more or less true.

One of the big advantages to the move constructor and move assignment is that if you define them, the compiler can use them in cases were the RVO (return value optimization) and NRVO (named return value optimization) fail to be invoked. This is pretty huge for returning expensive objects like containers & strings by value efficiently from methods.

Now where things get interesting with rvalue references, is that you can also use them as arguments to normal functions. This allows you to write containers that have overloads for both const reference (const foo& other) and rvalue reference (foo&& other). Even if the argument is too unwieldy to pass with a mere constructor call it can still be done:

std::vector vec;
for(int x=0; x<10; ++x)
    // automatically uses rvalue reference constructor if available
    // because MyCheapType is an unamed temporary variable

std::vector vec;
for(int x=0; x<10; ++x)
    MyExpensiveType temp(1.0, 3.0);

    // old way, passed via const reference, expensive copy

    // new way, passed via rvalue reference, cheap move
    // just don't use temp again,  not difficult in a loop like this though . . .

The STL containers have been updated to have move overloads for nearly anything (hash key and values, vector insertion, etc), and is where you will see them the most.

You can also use them to normal functions, and if you only provide an rvalue reference argument you can force the caller to create the object and let the function do the move. This is more of an example than a really good use, but in my rendering library, I have assigned a string to all the loaded resources, so that it is easier to see what each object represents in the debugger. The interface is something like this:

TextureHandle CreateTexture(int width, int height, ETextureFormat fmt, string&& friendlyName)
    std::unique_ptr<TextureObject> tex = D3DCreateTexture(width, height, fmt);
    tex->friendlyName = std::move(friendlyName);
    return tex;

It is a form of a 'leaky abstraction' but allows me to take advantage of the fact I had to create the string already most of the time, and avoid making yet another copying of it. This isn't exactly high-performance code but is a good example of the possibilities as people get the hang of this feature. This code actually requires that the variable either be a temporary to the call, or std::move invoked:

// move from temporary
TextureHandle htex = CreateTexture(128, 128, A8R8G8B8, string("Checkerboard"));


// explicit move (not going to use the variable 'str' after the create call)
string str("Checkerboard");
TextureHandle htex = CreateTexture(128, 128, A8R8G8B8, std::move(str));


// explicitly make a copy and pass the temporary of the copy down
// since we need to use str again for some reason
string str("Checkerboard");
TextureHandle htex = CreateTexture(128, 128, A8R8G8B8, string(str));

but this won't compile!

string str("Checkerboard");
TextureHandle htex = CreateTexture(128, 128, A8R8G8B8, str);

How to determine whether a Pandas Column contains a particular value



If x is present in id then it'll return the list of indices where it is present, else it gives an empty list.


I had this issue and none of the above solutions worked for me.

For some reason, the permissions weren't set correctly on my /data/local/tmp directory (only root had rwx). I fixed the issue using ADB (you'll need a rooted device):

  1. Connect your phone via USB
  2. Launch ADB using adb shell
  3. Move to /data/local using cd /data/local
  4. Switch to root mode using su
  5. Allow read/write/execute on tmp directory using chmod 777 tmp
  6. Disconnect, restart Android Studio and plug in device again

shorthand If Statements: C#

To use shorthand to get the direction:

int direction = column == 0
                ? 0
                : (column == _gridSize - 1 ? 1 : rand.Next(2));

To simplify the code entirely:

if (column == gridSize - 1 || rand.Next(2) == 1)

How to install OpenJDK 11 on Windows?

From the comment by @ZhekaKozlov: ojdkbuild has OpenJDK builds (currently 8 and 11) for Windows (zip and msi).

Illegal character in path at index 16

Did you try this?

new File("<PATH OF YOUR FILE>").toURI().toString();

set initial viewcontroller in appdelegate - swift

Well all the answers above/below are producing a warning about no entry point in storyboard.

If you want to have 2 (or more) entry view controllers that depend on some condition (say conditionVariable) then what you should do is:

  • In your Main.storyboard create UINavigationController without rootViewController, set it as entry point
  • Create 2 (or more) "Show" segues into view controllers, assign them some id, say id1 and id2
  • Use next code:

    class AppDelegate: UIResponder, UIApplicationDelegate {
       var window: UIWindow?
       func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
           let navigationController = window!.rootViewController! as! UINavigationController
           navigationController.performSegueWithIdentifier(conditionVariable ? "id1" : "id2")
           return true

Hope this helps.

How to ignore whitespace in a regular expression subject string?

While the accepted answer is technically correct, a more practical approach, if possible, is to just strip whitespace out of both the regular expression and the search string.

If you want to search for "my cats", instead of:


Just do:


Warning: You can't automate this on the regular expression by just replacing all spaces with empty strings because they may occur in a negation or otherwise make your regular expression invalid.

How to format time since xxx e.g. “4 minutes ago” similar to Stack Exchange sites

Here is a slight modification on Sky Sander's solution that allows the date to be input as a string and is capable of displaying spans like "1 minute" instead of "73 seconds"

var timeSince = function(date) {_x000D_
  if (typeof date !== 'object') {_x000D_
    date = new Date(date);_x000D_
  var seconds = Math.floor((new Date() - date) / 1000);_x000D_
  var intervalType;_x000D_
  var interval = Math.floor(seconds / 31536000);_x000D_
  if (interval >= 1) {_x000D_
    intervalType = 'year';_x000D_
  } else {_x000D_
    interval = Math.floor(seconds / 2592000);_x000D_
    if (interval >= 1) {_x000D_
      intervalType = 'month';_x000D_
    } else {_x000D_
      interval = Math.floor(seconds / 86400);_x000D_
      if (interval >= 1) {_x000D_
        intervalType = 'day';_x000D_
      } else {_x000D_
        interval = Math.floor(seconds / 3600);_x000D_
        if (interval >= 1) {_x000D_
          intervalType = "hour";_x000D_
        } else {_x000D_
          interval = Math.floor(seconds / 60);_x000D_
          if (interval >= 1) {_x000D_
            intervalType = "minute";_x000D_
          } else {_x000D_
            interval = seconds;_x000D_
            intervalType = "second";_x000D_
  if (interval > 1 || interval === 0) {_x000D_
    intervalType += 's';_x000D_
  return interval + ' ' + intervalType;_x000D_
var aDay = 24 * 60 * 60 * 1000;_x000D_
console.log(timeSince(new Date( - aDay)));_x000D_
console.log(timeSince(new Date( - aDay * 2)));

Can someone post a well formed crossdomain.xml sample?

If you're using webservices, you'll also need the 'allow-http-request-headers-from' element. Here's our default, development, 'allow everything' policy.

<?xml version="1.0" ?>
  <site-control permitted-cross-domain-policies="master-only"/>
  <allow-access-from domain="*"/>
  <allow-http-request-headers-from domain="*" headers="*"/>

Postgresql: password authentication failed for user "postgres"

i had a similar problem. Ubuntu was left me log in in console with any password for superuser. Except when i connected with -h localhost in psql line command.

I Observed too that "localhost:8080/MyJSPSiteLogIn" - showed: Fatal: autentication error with user "user".

pg_hba.conf was ok.

I noted had two versions of postgres running in the same service.

Solved - uninstalling inutil version.

How to make flutter app responsive according to different screen size?

After much research and testing, I have developed a solution for an app I'm currently converting from Android/iOS to Flutter.

With Android and iOS I used a 'Scaling Factor' applied to base font sizes, rendering text sizes that were relative to the screen size.

This article was very helpful:

I created a StatelessWidget to get the font sizes of the Material Design typographical styles. Getting device dimensions using MediaQuery, calculating a scaling factor, then resetting the Material Design text sizes. The Widget can be used to define a custom Material Design Theme.

Emulators used:

  • Pixel C - 9.94" Tablet
  • Pixel 3 - 5.46" Phone
  • iPhone 11 Pro Max - 5.8" Phone

With standard font sizes

With scaled font sizes

set_app_theme.dart (SetAppTheme Widget)

import 'package:flutter/material.dart';
import 'dart:math';

class SetAppTheme extends StatelessWidget {

  final Widget child;


  Widget build(BuildContext context) {

    final _divisor = 400.0;

    final MediaQueryData _mediaQueryData = MediaQuery.of(context);

    final _screenWidth = _mediaQueryData.size.width;
    final _factorHorizontal = _screenWidth / _divisor;

    final _screenHeight = _mediaQueryData.size.height;
    final _factorVertical = _screenHeight / _divisor;

    final _textScalingFactor = min(_factorVertical, _factorHorizontal);

    final _safeAreaHorizontal = _mediaQueryData.padding.left + _mediaQueryData.padding.right;
    final _safeFactorHorizontal = (_screenWidth - _safeAreaHorizontal) / _divisor;

    final _safeAreaVertical = + _mediaQueryData.padding.bottom;
    final _safeFactorVertical = (_screenHeight - _safeAreaVertical) / _divisor;

    final _safeAreaTextScalingFactor = min(_safeFactorHorizontal, _safeFactorHorizontal);

    print('Screen Scaling Values:' + '_screenWidth: $_screenWidth');
    print('Screen Scaling Values:' + '_factorHorizontal: $_factorHorizontal ');

    print('Screen Scaling Values:' + '_screenHeight: $_screenHeight');
    print('Screen Scaling Values:' + '_factorVertical: $_factorVertical ');

    print('_textScalingFactor: $_textScalingFactor ');

    print('Screen Scaling Values:' + '_safeAreaHorizontal: $_safeAreaHorizontal ');
    print('Screen Scaling Values:' + '_safeFactorHorizontal: $_safeFactorHorizontal ');

    print('Screen Scaling Values:' + '_safeAreaVertical: $_safeAreaVertical ');
    print('Screen Scaling Values:' + '_safeFactorVertical: $_safeFactorVertical ');

    print('_safeAreaTextScalingFactor: $_safeAreaTextScalingFactor ');

    print('Default Material Design Text Themes');
    print('display4: ${Theme.of(context).textTheme.display4}');
    print('display3: ${Theme.of(context).textTheme.display3}');
    print('display2: ${Theme.of(context).textTheme.display2}');
    print('display1: ${Theme.of(context).textTheme.display1}');
    print('headline: ${Theme.of(context).textTheme.headline}');
    print('title: ${Theme.of(context).textTheme.title}');
    print('subtitle: ${Theme.of(context).textTheme.subtitle}');
    print('body2: ${Theme.of(context).textTheme.body2}');
    print('body1: ${Theme.of(context).textTheme.body1}');
    print('caption: ${Theme.of(context).textTheme.caption}');
    print('button: ${Theme.of(context).textTheme.button}');

    TextScalingFactors _textScalingFactors = TextScalingFactors(
        display4ScaledSize: (Theme.of(context).textTheme.display4.fontSize * _safeAreaTextScalingFactor),
        display3ScaledSize: (Theme.of(context).textTheme.display3.fontSize * _safeAreaTextScalingFactor),
        display2ScaledSize: (Theme.of(context).textTheme.display2.fontSize * _safeAreaTextScalingFactor),
        display1ScaledSize: (Theme.of(context).textTheme.display1.fontSize * _safeAreaTextScalingFactor),
        headlineScaledSize: (Theme.of(context).textTheme.headline.fontSize * _safeAreaTextScalingFactor),
        titleScaledSize: (Theme.of(context).textTheme.title.fontSize * _safeAreaTextScalingFactor),
        subtitleScaledSize: (Theme.of(context).textTheme.subtitle.fontSize * _safeAreaTextScalingFactor),
        body2ScaledSize: (Theme.of(context).textTheme.body2.fontSize * _safeAreaTextScalingFactor),
        body1ScaledSize: (Theme.of(context).textTheme.body1.fontSize * _safeAreaTextScalingFactor),
        captionScaledSize: (Theme.of(context).textTheme.caption.fontSize * _safeAreaTextScalingFactor),
        buttonScaledSize: (Theme.of(context).textTheme.button.fontSize * _safeAreaTextScalingFactor));

    return Theme(
      child: child,
      data: _buildAppTheme(_textScalingFactors),

final ThemeData customTheme = ThemeData(
  primarySwatch: appColorSwatch,
  // fontFamily: x,

final MaterialColor appColorSwatch = MaterialColor(0xFF3787AD, appSwatchColors);

Map<int, Color> appSwatchColors =
  50  : Color(0xFFE3F5F8),
  100 : Color(0xFFB8E4ED),
  200 : Color(0xFF8DD3E3),
  300 : Color(0xFF6BC1D8),
  400 : Color(0xFF56B4D2),
  500 : Color(0xFF48A8CD),
  600 : Color(0xFF419ABF),
  700 : Color(0xFF3787AD),
  800 : Color(0xFF337799),
  900 : Color(0xFF285877),

_buildAppTheme (TextScalingFactors textScalingFactors) {

  return customTheme.copyWith(

    accentColor: appColorSwatch[300],
    buttonTheme: customTheme.buttonTheme.copyWith(buttonColor: Colors.grey[500],),
    cardColor: Colors.white,
    inputDecorationTheme: InputDecorationTheme(border: OutlineInputBorder(),),
    primaryColor: appColorSwatch[700],
    primaryIconTheme: customTheme.iconTheme.copyWith(color: appColorSwatch),
    scaffoldBackgroundColor: Colors.grey[100],
    textSelectionColor: appColorSwatch[300],
    textTheme: _buildAppTextTheme(customTheme.textTheme, textScalingFactors),
    appBarTheme: customTheme.appBarTheme.copyWith(
        textTheme: _buildAppTextTheme(customTheme.textTheme, textScalingFactors)),

//    accentColorBrightness: ,
//    accentIconTheme: ,
//    accentTextTheme: ,
//    appBarTheme: ,
//    applyElevationOverlayColor: ,
//    backgroundColor: ,
//    bannerTheme: ,
//    bottomAppBarColor: ,
//    bottomAppBarTheme: ,
//    bottomSheetTheme: ,
//    brightness: ,
//    buttonBarTheme: ,
//    buttonColor: ,
//    canvasColor: ,
//    cardTheme: ,
//    chipTheme: ,
//    colorScheme: ,
//    cupertinoOverrideTheme: ,
//    cursorColor: ,
//    dialogBackgroundColor: ,
//    dialogTheme: ,
//    disabledColor: ,
//    dividerColor: ,
//    dividerTheme: ,
//    floatingActionButtonTheme: ,
//    focusColor: ,
//    highlightColor: ,
//    hintColor: ,
//    hoverColor: ,
//    iconTheme: ,
//    indicatorColor: ,
//    materialTapTargetSize: ,
//    pageTransitionsTheme: ,
//    platform: ,
//    popupMenuTheme: ,
//    primaryColorBrightness: ,
//    primaryColorDark: ,
//    primaryColorLight: ,
//    primaryTextTheme: ,
//    secondaryHeaderColor: ,
//    selectedRowColor: ,
//    sliderTheme: ,
//    snackBarTheme: ,
//    splashColor: ,
//    splashFactory: ,
//    tabBarTheme: ,
//    textSelectionHandleColor: ,
//    toggleableActiveColor: ,
//    toggleButtonsTheme: ,
//    tooltipTheme: ,
//    typography: ,
//    unselectedWidgetColor: ,

class TextScalingFactors {

  final double display4ScaledSize;
  final double display3ScaledSize;
  final double display2ScaledSize;
  final double display1ScaledSize;
  final double headlineScaledSize;
  final double titleScaledSize;
  final double subtitleScaledSize;
  final double body2ScaledSize;
  final double body1ScaledSize;
  final double captionScaledSize;
  final double buttonScaledSize;


    @required this.display4ScaledSize,
    @required this.display3ScaledSize,
    @required this.display2ScaledSize,
    @required this.display1ScaledSize,
    @required this.headlineScaledSize,
    @required this.titleScaledSize,
    @required this.subtitleScaledSize,
    @required this.body2ScaledSize,
    @required this.body1ScaledSize,
    @required this.captionScaledSize,
    @required this.buttonScaledSize

TextTheme _buildAppTextTheme(

    TextTheme _customTextTheme,
    TextScalingFactors _scaledText) {

  return _customTextTheme.copyWith(

    display4: _customTextTheme.display4.copyWith(fontSize: _scaledText.display4ScaledSize),
    display3: _customTextTheme.display3.copyWith(fontSize: _scaledText.display3ScaledSize),
    display2: _customTextTheme.display2.copyWith(fontSize: _scaledText.display2ScaledSize),
    display1: _customTextTheme.display1.copyWith(fontSize: _scaledText.display1ScaledSize),
    headline: _customTextTheme.headline.copyWith(fontSize: _scaledText.headlineScaledSize),
    title: _customTextTheme.title.copyWith(fontSize: _scaledText.titleScaledSize),
    subtitle: _customTextTheme.subtitle.copyWith(fontSize: _scaledText.subtitleScaledSize),
    body2: _customTextTheme.body2.copyWith(fontSize: _scaledText.body2ScaledSize),
    body1: _customTextTheme.body1.copyWith(fontSize: _scaledText.body1ScaledSize),
    caption: _customTextTheme.caption.copyWith(fontSize: _scaledText.captionScaledSize),
    button: _customTextTheme.button.copyWith(fontSize: _scaledText.buttonScaledSize),


main.dart (Demo App)

import 'package:flutter/material.dart';
import 'package:scaling/set_app_theme.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {

  Widget build(BuildContext context) {

    return MaterialApp(
      home: SetAppTheme(child: HomePage()),

class HomePage extends StatelessWidget {

  final demoText = '0123456789';

  Widget build(BuildContext context) {

    return SafeArea(
      child: Scaffold(
        appBar: AppBar(
          title: Text('Text Scaling with SetAppTheme',
            style: TextStyle(color: Colors.white),),
        body: SingleChildScrollView(
          child: Center(
            child: Padding(
              padding: const EdgeInsets.all(8.0),
              child: Column(
                children: <Widget>[
                    style: TextStyle(
                      fontSize: Theme.of(context).textTheme.display4.fontSize,
                    style: TextStyle(
                      fontSize: Theme.of(context).textTheme.display3.fontSize,
                    style: TextStyle(
                      fontSize: Theme.of(context).textTheme.display2.fontSize,
                    style: TextStyle(
                      fontSize: Theme.of(context).textTheme.display1.fontSize,
                    style: TextStyle(
                      fontSize: Theme.of(context).textTheme.headline.fontSize,
                    style: TextStyle(
                      fontSize: Theme.of(context).textTheme.title.fontSize,
                    style: TextStyle(
                      fontSize: Theme.of(context).textTheme.subtitle.fontSize,
                    style: TextStyle(
                      fontSize: Theme.of(context).textTheme.body2.fontSize,
                    style: TextStyle(
                      fontSize: Theme.of(context).textTheme.body1.fontSize,
                    style: TextStyle(
                      fontSize: Theme.of(context).textTheme.caption.fontSize,
                    style: TextStyle(
                      fontSize: Theme.of(context).textTheme.button.fontSize,

How to make a transparent border using CSS?

Well if you want fully transparent than you can use

border: 5px solid transparent;

If you mean opaque/transparent, than you can use

border: 5px solid rgba(255, 255, 255, .5);

Here, a means alpha, which you can scale, 0-1.

Also some might suggest you to use opacity which does the same job as well, the only difference is it will result in child elements getting opaque too, yes, there are some work arounds but rgba seems better than using opacity.

For older browsers, always declare the background color using #(hex) just as a fall back, so that if old browsers doesn't recognize the rgba, they will apply the hex color to your element.


Demo 2 (With a background image for nested div)

Demo 3 (With an img tag instead of a background-image)

body {
    background: url(;   

div.wrap {
    border: 5px solid #fff; /* Fall back, not used in fiddle */
    border: 5px solid rgba(255, 255, 255, .5);
    height: 400px;
    width: 400px;
    margin: 50px;
    border-radius: 50%;

div.inner {
    background: #fff; /* Fall back, not used in fiddle */
    background: rgba(255, 255, 255, .5);
    height: 380px;
    width: 380px;
    border-radius: 50%; 
    margin: auto; /* Horizontal Center */
    margin-top: 10px; /* Vertical Center ... Yea I know, that's 
                         manually calculated*/

Note (For Demo 3): Image will be scaled according to the height and width provided so make sure it doesn't break the scaling ratio.

What causes HttpHostConnectException?

A "connection refused" error happens when you attempt to open a TCP connection to an IP address / port where there is nothing currently listening for connections. If nothing is listening, the OS on the server side "refuses" the connection.

If this is happening intermittently, then the most likely explanations are (IMO):

  • the server you are talking ("" / port 60) to is going up and down, OR
  • there is something1 between your client and the proxy that is intermittently sending requests to a non-functioning host, or something.

Is this possible that this exception is caused when a search request is made from Android applications as our website don't support a request is being made from android applications.

It seems unlikely. You said that the "connection refused" exception message says that it is the proxy that is refusing the connection, not your server. Besides if a server was going to not handle certain kinds of request, it still has to accept the TCP connection to find out what the request is ... before it can reject it.

1 - For example, it could be a DNS that round-robin resolves the DNS name to different IP addresses. Or it could be an IP-based load balancer.

Download Excel file via AJAX MVC

First Create the controller action that will create the Excel File

public JsonResult ExportExcel()
    DataTable dt = DataService.GetData();
    var fileName = "Excel_" + DateTime.Now.ToString("yyyyMMddHHmm") + ".xls";

    //save the file to server temp folder
    string fullPath = Path.Combine(Server.MapPath("~/temp"), fileName);

    using (var exportData = new MemoryStream())
        //I don't show the detail how to create the Excel, this is not the point of this article,
        //I just use the NPOI for Excel handler
        Utility.WriteDataTableToExcel(dt, ".xls", exportData);

        FileStream file = new FileStream(fullPath, FileMode.Create, FileAccess.Write);

    var errorMessage = "you can return the errors in here!";

    //return the Excel file name
    return Json(new { fileName = fileName, errorMessage = "" });

then create the Download action

[DeleteFileAttribute] //Action Filter, it will auto delete the file after download, 
                      //I will explain it later
public ActionResult Download(string file)
    //get the temp folder and file path in server
    string fullPath = Path.Combine(Server.MapPath("~/temp"), file);

    //return the file for download, this is an Excel 
    //so I set the file content type to "application/"
    return File(fullPath, "application/", file);

if you want to delete the file after downloaded create this

public class DeleteFileAttribute : ActionFilterAttribute
    public override void OnResultExecuted(ResultExecutedContext filterContext)

        //convert the current filter context to file and get the file path
        string filePath = (filterContext.Result as FilePathResult).FileName;

        //delete the file after download

and finally ajax call from you MVC Razor view

//I use blockUI for loading...
$.blockUI({ message: '<h3>Please wait a moment...</h3>' });    
    type: "POST",
    url: '@Url.Action("ExportExcel","YourController")', //call your controller and action
    contentType: "application/json; charset=utf-8",
    dataType: "json",
}).done(function (data) {

    //get the file name for download
    if (data.fileName != "") {
        //use window.location.href for redirect to download action for download the file
        window.location.href = "@Url.RouteUrl(new 
            { Controller = "YourController", Action = "Download"})/?file=" + data.fileName;

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

While we are working with tomcat 6 and jdk 1.8 versions, some of the features will not work and this error you are getting is one. you need to change the jdk version to stable version(preferable jdk 1.6 or jdk 1.8_65) in eclipse to resolve this error.

in eclipse step 1: properties -> java build path -> jre system library(remove) step 2: add -> jre system library -> alternate jre -> installed jre -> add -> Standard VM -> (in jre home, place jdk path) -> finish

now clean and check the project

How to loop through key/value object in Javascript?

for (var key in data) {
    alert("User " + data[key] + " is #" + key); // "User john is #234"

How to convert comma separated string into numeric array in javascript

You can use split() to get string array from comma separated string. If you iterate and perform mathematical operation on element of string array then that element will be treated as number by run-time cast but still you have string array. To convert comma separated string int array see the edit.

arr = strVale.split(',');

Live Demo

var strVale = "130,235,342,124";
arr = strVale.split(',');
for(i=0; i < arr.length; i++)
    console.log(arr[i] + " * 2 = " + (arr[i])*2);


130 * 2 = 260
235 * 2 = 470
342 * 2 = 684
124 * 2 = 248

Edit, Comma separated string to int Array In the above example the string are casted to numbers in expression but to get the int array from string array you need to convert it to number.

var strVale = "130,235,342,124";
var strArr = strVale.split(',');
var intArr = [];
for(i=0; i < strArr.length; i++)

How to make a <button> in Bootstrap look like a normal link in nav-tabs?

Just add remove_button_css as class to your button tag. You can verify the code for Link 1

.remove_button_css { 
  outline: none;
  padding: 5px; 
  border: 0px; 
  box-sizing: none; 
  background-color: transparent; 

enter image description here

Extra Styles Edit

Add color: #337ab7; and :hover and :focus to match OOTB (bootstrap3)

.remove_button_css:hover {
    color: #23527c;
    text-decoration: underline;

Reading text files using read.table

From ?read.table: The number of data columns is determined by looking at the first five lines of input (or the whole file if it has less than five lines), or from the length of col.names if it is specified and is longer. This could conceivably be wrong if fill or blank.lines.skip are true, so specify col.names if necessary.

So, perhaps your data file isn't clean. Being more specific will help the data import:

d = read.table("foobar.txt", 
               col.names=c("id", "name"), 

will specify exact columns and fill=FALSE will force a two column data frame.

Link to the issue number on GitHub within a commit message

github adds a reference to the commit if it contains #issuenbr (discovered this by chance).

Convert array into csv

My solution requires the array be formatted differently than provided in the question:

    $data = array(
        array( 'row_1_col_1', 'row_1_col_2', 'row_1_col_3' ),
        array( 'row_2_col_1', 'row_2_col_2', 'row_2_col_3' ),
        array( 'row_3_col_1', 'row_3_col_2', 'row_3_col_3' ),

We define our function:

    function outputCSV($data) {
        $outputBuffer = fopen("php://output", 'w');
        foreach($data as $val) {
            fputcsv($outputBuffer, $val);

Then we output our data as a CSV:

    $filename = "example";

    header("Content-type: text/csv");
    header("Content-Disposition: attachment; filename={$filename}.csv");
    header("Pragma: no-cache");
    header("Expires: 0");


I have used this with several projects, and it works well. I should note that the outputCSV code is more clever than I am, so I am sure I am not the original author. Unfortunately I have lost track of where I got it, so I can't give the credit to whom it is due.

Sort collection by multiple fields in Kotlin

Use sortedWith to sort a list with Comparator.

You can then construct a comparator using several ways:

  • compareBy, thenBy construct the comparator in a chain of calls:

    list.sortedWith(compareBy<Person> { it.age }.thenBy { }.thenBy { it.address })
  • compareBy has an overload which takes multiple functions:

    list.sortedWith(compareBy({ it.age }, { }, { it.address }))

Round a divided number in Bash

To do rounding up in truncating arithmetic, simply add (denom-1) to the numerator.

Example, rounding down:


Example, rounding up:


To do round-to-nearest, add (denom/2) to the numerator (halves will round up):


How to enable scrolling of content inside a modal?

Set height for modal-body and not for the whole modal to get a perfect scroll on modal overlay. I get it work like this:

.MyModal {
    height: 450px;
    overflow-y: auto;

Here you can set height as per your requirements.

How to find the length of a string in R

See ?nchar. For example:

> nchar("foo")
[1] 3
> set.seed(10)
> strn <- paste(sample(LETTERS, 10), collapse = "")
> strn
> nchar(strn)
[1] 10

IndexError: list index out of range and python

In Python, indexing starts at 0. Therefore, if you have a list with 53 items, list[52] will be the last item in the list.

Animation fade in and out

I´ve been working in Kotlin (recommend to everyone), so the syntax might be a bit off. What I do is to simply to call:

v.animate().alpha(0f).duration = 200

I think that, in Java, it would be the following.:



private void hide(View v, int duration) {

private void show(View v, int duration) {

Angular 2 - How to navigate to another route using this.router.parent.navigate('/about')?

import { Router } from '@angular/router';
//in your constructor
constructor(public router: Router){}


What are the git concepts of HEAD, master, origin?

I highly recommend the book "Pro Git" by Scott Chacon. Take time and really read it, while exploring an actual git repo as you do.

HEAD: the current commit your repo is on. Most of the time HEAD points to the latest commit in your current branch, but that doesn't have to be the case. HEAD really just means "what is my repo currently pointing at".

In the event that the commit HEAD refers to is not the tip of any branch, this is called a "detached head".

master: the name of the default branch that git creates for you when first creating a repo. In most cases, "master" means "the main branch". Most shops have everyone pushing to master, and master is considered the definitive view of the repo. But it's also common for release branches to be made off of master for releasing. Your local repo has its own master branch, that almost always follows the master of a remote repo.

origin: the default name that git gives to your main remote repo. Your box has its own repo, and you most likely push out to some remote repo that you and all your coworkers push to. That remote repo is almost always called origin, but it doesn't have to be.

HEAD is an official notion in git. HEAD always has a well-defined meaning. master and origin are common names usually used in git, but they don't have to be.

How do I position a div at the bottom center of the screen

If you aren't comfortable with using negative margins, check this out.

div {
  position: fixed;
  left: 50%;
  bottom: 20px;
  transform: translate(-50%, -50%);
  margin: 0 auto;
  Your Text

Especially useful when you don't know the width of the div.

align="center" has no effect.

Since you have position:absolute, I would recommend positioning it 50% from the left and then subtracting half of its width from its left margin.

#manipulate {

PHPExcel - set cell type before writing a value in it

When the text is a number with leading zeros, then do: (Cuando el texto es un número que empieza por ceros, hacer)

$objPHPExcel->getActiveSheet()->setCellValueExplicit('A1', $val,PHPExcel_Cell_DataType::TYPE_STRING);

In C#, why is String a reference type that behaves like a value type?

At the risk of getting yet another mysterious down-vote...the fact that many mention the stack and memory with respect to value types and primitive types is because they must fit into a register in the microprocessor. You cannot push or pop something to/from the stack if it takes more bits than a register has....the instructions are, for example "pop eax" -- because eax is 32 bits wide on a 32-bit system.

Floating-point primitive types are handled by the FPU, which is 80 bits wide.

This was all decided long before there was an OOP language to obfuscate the definition of primitive type and I assume that value type is a term that has been created specifically for OOP languages.

Simple Java Client/Server Program

My try to do client socket program

server reads file and print it to console and copies it to output file

Server Program:

package SocketProgramming.copy;


public class ServerRecieveFile {
    public static void main(String[] args) throws IOException {
        // TODO Auto-enerated method stub
        int filesize = 1022386;
        int bytesRead;
        int currentTot;
        ServerSocket s = new ServerSocket(0);
        int port = s.getLocalPort();
        ServerSocket serverSocket = new ServerSocket(15123);
        while (true) {
            Socket socket = serverSocket.accept();
            byte[] bytearray = new byte[filesize];
            InputStream is = socket.getInputStream();
            File copyFileName = new File("C:/Users/Username/Desktop/Output_file.txt");
            FileOutputStream fos = new FileOutputStream(copyFileName);
            BufferedOutputStream bos = new BufferedOutputStream(fos);
            bytesRead =, 0, bytearray.length);
            currentTot = bytesRead;
            do {
                bytesRead =, currentTot,
                        (bytearray.length - currentTot));
                if (bytesRead >= 0)
                    currentTot += bytesRead;
            } while (bytesRead > -1);
            bos.write(bytearray, 0, currentTot);

Client program:

package SocketProgramming.copy;


public class ClientSendFile {
    public static void main(String[] args) throws UnknownHostException,
            IOException {
        // final String FILE_NAME="C:/Users/Username/Desktop/Input_file.txt";
        final String FILE_NAME = "C:/Users/Username/Desktop/Input_file.txt";
        ServerSocket s = new ServerSocket(0);
        int port = s.getLocalPort();
        Socket socket = new Socket(InetAddress.getLocalHost(), 15123);
        System.out.println("Accepted connection : " + socket);
        File transferFile = new File(FILE_NAME);
        byte[] bytearray = new byte[(int) transferFile.length()];
        FileInputStream fin = new FileInputStream(transferFile);
        BufferedInputStream bin = new BufferedInputStream(fin);, 0, bytearray.length);
        OutputStream os = socket.getOutputStream();
        System.out.println("Sending Files...");

        os.write(bytearray, 0, bytearray.length);

        BufferedReader r = new BufferedReader(new FileReader(FILE_NAME));
        String as = "", line = null;
        while ((line = r.readLine()) != null) {
            as += line + "\n";
            // as += line;

        System.out.print("Input File contains following data: " + as);

        System.out.println("File transfer complete");

How to add to the end of lines containing a pattern with sed or awk?

Here is another simple solution using sed.

$ sed -i 's/all.*/& anotherthing/g' filename.txt


all.* means all lines started with 'all'.

& represent the match (ie the complete line that starts with 'all')

then sed replace the former with the later and appends the ' anotherthing' word

UICollectionView - Horizontal scroll, horizontal layout?

Just for fun, another approach would be to just leave the paging and horizontal scrolling set, add a method that changes the order of the array items to convert from 'top to bottom, left to right' to visually 'left to right, top to bottom' and fill the in-between cells with empty hidden cells to make the spacing right. In case of 7 items in a grid of 9, this would go like this:

[2][5][ ]
[3][6][ ]

should become

[7][ ][ ]

so 1=1, 2=4, 3=7 etc. and 6=empty. You can reorder them by calculating the total number of rows and columns, then calculate the row and column number for each cell, change the row for the column and vice versa and then you have the new indexes. When the cell doesn't have a value corresponding to the image you can return an empty cell and set cell.hidden = YES; to it.

It works quite well in a soundboard app I built, so if anyone would like working code I'll add it. Only little code is required to make this trick work, it sounds harder than it is!


I doubt this is the best solution, but by request here's working code:

- (void)viewDidLoad {
    // Fill an `NSArray` with items in normal order
    items = [NSMutableArray arrayWithObjects:
             [NSDictionary dictionaryWithObjectsAndKeys:@"Some label 1", @"label", @"Some value 1", @"value", nil],
             [NSDictionary dictionaryWithObjectsAndKeys:@"Some label 2", @"label", @"Some value 2", @"value", nil],
             [NSDictionary dictionaryWithObjectsAndKeys:@"Some label 3", @"label", @"Some value 3", @"value", nil],
             [NSDictionary dictionaryWithObjectsAndKeys:@"Some label 4", @"label", @"Some value 4", @"value", nil],
             [NSDictionary dictionaryWithObjectsAndKeys:@"Some label 5", @"label", @"Some value 5", @"value", nil],

    // Calculate number of rows and columns based on width and height of the `UICollectionView` and individual cells (you might have to add margins to the equation based on your setup!)
    CGFloat w = myCollectionView.frame.size.width;
    CGFloat h = myCollectionView.frame.size.height;
    rows = floor(h / cellHeight);
    columns = floor(w / cellWidth);

// Calculate number of sections
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    return ceil((float)items.count / (float)(rows * columns));

// Every section has to have every cell filled, as we need to add empty cells as well to correct the spacing
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return rows*columns;

// And now the most important one
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier@"myIdentifier" forIndexPath:indexPath];

    // Convert rows and columns
    int row = indexPath.row % rows;
    int col = floor(indexPath.row / rows);
    // Calculate the new index in the `NSArray`
    int newIndex = ((int)indexPath.section * rows * columns) + col + row * columns;

    // If the newIndex is within the range of the items array we show the cell, if not we hide it
    if(newIndex < items.count) {
        NSDictionary *item = [items objectAtIndex:newIndex];
        cell.label.text = [item objectForKey:@"label"];
        cell.hidden = NO;
    } else {
        cell.hidden = YES;

    return cell;

If you'd like to use the didSelectItemAtIndexPath method you have to use the same conversion that is used in cellForItemAtIndexPath to get the corresponding item. If you have cell margins you need to add them to the rows and columns calculation, as those have to be correct in order for this to work.

C# DataRow Empty-check

AFAIK, there is no method that does this in the framework. Even if there was support for something like this in the framework, it would essentially be doing the same thing. And that would be looking at each cell in the DataRow to see if it is empty.

How to control the width and height of the default Alert Dialog in Android?

For those who will find this thread like me, here is IMO better solution (note the 70% which sets min width of the dialog in percent of screen width):

<style name="my_dialog" parent="Theme.AppCompat.Dialog.Alert">
    <item name="windowMinWidthMajor">70%</item>
    <item name="windowMinWidthMinor">70%</item>

And then apply this style to dialog:

AlertDialog.Builder builder = new AlertDialog.Builder(context,;

Convert Float to Int in Swift

var floatValue = 10.23
var intValue = Int(floatValue)

This is enough to convert from float to Int

How do I read a large csv file with pandas?

The function read_csv and read_table is almost the same. But you must assign the delimiter “,” when you use the function read_table in your program.

def get_from_action_data(fname, chunk_size=100000):
    reader = pd.read_csv(fname, header=0, iterator=True)
    chunks = []
    loop = True
    while loop:
            chunk = reader.get_chunk(chunk_size)[["user_id", "type"]]
        except StopIteration:
            loop = False
            print("Iteration is stopped")

    df_ac = pd.concat(chunks, ignore_index=True)

What event handler to use for ComboBox Item Selected (Selected Item not necessarily changed)

You can use "ComboBoxItem.PreviewMouseDown" event. So each time when mouse is down on some item this event will be fired.

To add this event in XAML use "ComboBox.ItemContainerStyle" like in next example:

   <ComboBox x:Name="MyBox"
        ItemsSource="{Binding MyList}"
        SelectedValue="{Binding MyItem, Mode=OneWayToSource}" >
                <EventSetter Event="ComboBoxItem.PreviewMouseDown"

and handle it as usual

void cmbItem_PreviewMouseDown(object sender, MouseButtonEventArgs e)
    // your item selection code here...

Thanks to MSDN

Most efficient way to increment a Map value in Java

The Functional Java library's TreeMap datastructure has an update method in the latest trunk head:

public TreeMap<K, V> update(final K k, final F<V, V> f)

Example usage:

import static;
import static fj.function.Integers.add;
import static fj.pre.Ord.stringOrd;

public class TreeMap_Update
  {public static void main(String[] a)
    {TreeMap<String, Integer> map = empty(stringOrd);
     map = map.set("foo", 1);
     map = map.update("foo", add.f(1));

This program prints "2".

Advantages of std::for_each over for loop

The advantage of writing functional for beeing more readable, might not show up when for(...) and for_each(...).

If you utilize all algorithms in functional.h, instead of using for-loops, the code gets a lot more readable;

iterator longest_tree = std::max_element(forest.begin(), forest.end(), ...);
iterator first_leaf_tree = std::find_if(forest.begin(), forest.end(), ...);
std::transform(forest.begin(), forest.end(), firewood.begin(), ...);
std::for_each(forest.begin(), forest.end(), make_plywood);

is much more readable than;

Forest::iterator longest_tree = it.begin();
for (Forest::const_iterator it = forest.begin(); it != forest.end(); ++it{
   if (*it > *longest_tree) {
     longest_tree = it;

Forest::iterator leaf_tree = it.begin();
for (Forest::const_iterator it = forest.begin(); it != forest.end(); ++it{
   if (it->type() == LEAF_TREE) {
     leaf_tree  = it;

for (Forest::const_iterator it = forest.begin(), jt = firewood.begin(); 
     it != forest.end(); 
     it++, jt++) {
          *jt = boost::transformtowood(*it);

for (Forest::const_iterator it = forest.begin(); it != forest.end(); ++it{

And that is what I think is so nice, generalize the for-loops to one line functions =)

How can I add raw data body to an axios request?

Here is my solution:

  method: "POST",
  url: "",
  headers: {
    "x-access-key": data,
    "x-access-token": token,
  data: {
    quiz_name: quizname,
.then(res => {
.catch(err => {
  console.log("error in request", err);

This should help

Remove all HTMLtags in a string (with the jquery text() function)

var myContent = '<div id="test">Hello <span>world!</span></div>';


That results in hello world. Does that answer your question? for an example

How to create CSV Excel file C#?

I added ExportToStream so the csv didn't have to save to the hard drive first.

public Stream ExportToStream()
    MemoryStream stream = new MemoryStream();
    StreamWriter writer = new StreamWriter(stream);
    stream.Position = 0;
    return stream;

What's the difference between a Future and a Promise?

Not sure if this can be an answer but as I see what others have said for someone it may look like you need two separate abstractions for both of these concepts so that one of them (Future) is just a read-only view of the other (Promise) ... but actually this is not needed.

For example take a look at how promises are defined in javascript:

The focus is on the composability using the then method like:

  // do something
  return asyncOp2();
  // do something more
  return asyncOp3();
  // do something even more
  return syncOp4(op3Result);

which makes asynchronous computation to look like synchronous:

try {
  op1Result = syncOp1();
  // do something
  op1Result = syncOp2();
  // do something more
  op3Result = syncOp3();
  // do something even more
} catch(error) {

which is pretty cool. (Not as cool as async-await but async-await just removes the boilerplate ....then(function(result) {.... from it).

And actually their abstraction is pretty good as the promise constructor

new Promise( function(resolve, reject) { /* do it */ } );

allows you to provide two callbacks which can be used to either complete the Promise successfully or with an error. So that only the code that constructs the Promise can complete it and the code that receives an already constructed Promise object has the read-only view.

With inheritance the above can be achieved if resolve and reject are protected methods.

Test if a vector contains a given element

The any() function makes for readable code

> w <- c(1,2,3)
> any(w==1)
[1] TRUE

> v <- c('a','b','c')
> any(v=='b')
[1] TRUE

> any(v=='f')

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

To return a value when using try/catch you can use a temporary variable, e.g.

public static double add(String[] values) {
    double sum = 0.0;
    try {
        int length = values.length;
        double arrayValues[] = new double[length];
        for(int i = 0; i < length; i++) {
            arrayValues[i] = Double.parseDouble(values[i]);
            sum += arrayValues[i];
    } catch(NumberFormatException e) {
    } catch(RangeException e) {
        throw e;
    } finally {
        System.out.println("Thank you for using the program!");
    return sum;

Else you need to have a return in every execution path (try block or catch block) that has no throw.

What's the best way to test SQL Server connection programmatically?

See the following project on GitHub:

    Console.WriteLine("Connecting to: {0}", AppConfig.ConnectionString);
    using (var connection = new SqlConnection(AppConfig.ConnectionString))
        var query = "select 1";
        Console.WriteLine("Executing: {0}", query);

        var command = new SqlCommand(query, connection);

        Console.WriteLine("SQL Connection successful.");

        Console.WriteLine("SQL Query execution successful.");
catch (Exception ex)
    Console.WriteLine("Failure: {0}", ex.Message);

How do I fix a Git detached head?

A solution without creating a temporary branch.

How to exit (“fix”) detached HEAD state when you already changed something in this mode and, optionally, want to save your changes:

  1. Commit changes you want to keep. If you want to take over any of the changes you made in detached HEAD state, commit them. Like:

    git commit -a -m "your commit message"
  2. Discard changes you do not want to keep. The hard reset will discard any uncommitted changes that you made in detached HEAD state:

    git reset --hard

    (Without this, step 3 would fail, complaining about modified uncommitted files in the detached HEAD.)

  3. Check out your branch. Exit detached HEAD state by checking out the branch you worked on before, for example:

    git checkout master
  4. Take over your commits. You can now take over the commits you made in detached HEAD state by cherry-picking, as shown in my answer to another question.

    git reflog
    git cherry-pick <hash1> <hash2> <hash3> …

How to compare different branches in Visual Studio Code

Update: As of November, 2020, Gitlens appears within VSCode's builtin Source Control Panel

I would recommend to use: Git Lens.

enter image description here

Update Git submodule to latest commit on origin

If you are looking to checkout master branch for each submodule -- you can use the following command for that purpose:

git submodule foreach git checkout master

How to return dictionary keys as a list in Python?

If you need to store the keys separately, here's a solution that requires less typing than every other solution presented thus far, using Extended Iterable Unpacking (python3.x+).

newdict = {1: 0, 2: 0, 3: 0}
*k, = newdict

# [1, 2, 3]

            ¦ k = list(d)   ¦   9 characters (excluding whitespace)   ¦
            ¦ k = [*d]      ¦   6 characters                          ¦
            ¦ *k, = d       ¦   5 characters                          ¦

OpenCV resize fails on large image with "error: (-215) ssize.area() > 0 in function cv::resize"

In my case I did a wrong modification in the image.

I was able to find the problem checking the image shape.

print img.shape

Converting from IEnumerable to List

In case you're working with a regular old System.Collections.IEnumerable instead of IEnumerable<T> you can use enumerable.Cast<object>().ToList()

Convert date to day name e.g. Mon, Tue, Wed

Your code works for me

$date = '15-12-2016';
$nameOfDay = date('D', strtotime($date));
echo $nameOfDay;

Use l instead of D, if you prefer the full textual representation of the name

Find something in column A then show the value of B for that row in Excel 2010

I figured out such data design:

Main sheet: Column A: Pump codes (numbers)

Column B: formula showing a corresponding row in sheet 'Ruhrpumpen'


Formulae have ";" instead of ",", it should be also German notation. If not, pleace replace.

Column C: formula showing data in 'Ruhrpumpen' column A from a row found by formula in col B


Column D: formula showing data in 'Ruhrpumpen' column B from a row found by formula in col B:


Sheet 'Ruhrpumpen':

Column A: some data about a certain pump

Column B: some more data

Column I: pump codes. Beginning of the list includes defined name 'Pump_codes' used by the formula in column B of the main sheet.

Spreadsheet example:

Removing spaces from string

Try this:

String urle = HOST + url + value;

Then return the values from:

urle.replace(" ", "%20").trim();

jQuery SVG vs. Raphael

I've recently used both Raphael and jQuery SVG - and here are my thoughts:


Pros: a good starter library, easy to do a LOT of things with SVG quickly. Well written and documented. Lots of examples and Demos. Very extensible architecture. Great with animation.

Cons: is a layer over the actual SVG markup, makes it difficult to do more complex things with SVG - such as grouping (it supports Sets, but not groups). Doesn't do great w/ editing of already existing elements.

jQuery SVG

Pros: a jquery plugin, if you're already using jQuery. Well written and documented. Lots of examples and demos. Supports most SVG elements, allows native access to elements easily

Cons: architecture not as extensible as Raphael. Some things could be better documented (like configure of SVG element). Doesn't do great w/ editing of already existing elements. Relies on SVG semantics for animation - which is not that great.

SnapSVG as a pure SVG version of Raphael

SnapSVG is the successor of Raphael. It is supported only in the SVG enabled browsers and supports almost all the features of SVG.


If you're doing something quick and easy, Raphael is an easy choice. If you're going to do something more complex, I chose to use jQuery SVG because I can manipulate the actual markup significantly easier than with Raphael. And if you want a non-jQuery solution then SnapSVG is a good option.

Module is not available, misspelled or forgot to load (but I didn't)

I had the same error but i resolved it, it was a syntax error in the AngularJS provider

mysql data directory location

If you are using macOS {mine 'High Sierra'} and Installed XAMPP

You can find mysql data files;

Go to : /Applications/XAMPP/xamppfiles/var/mysql/

SVN commit command

First add the new files:

svn add fileName

Then commit all new and modified files

svn ci <files_separated_by_space> -m "Commit message|ReviewID:XXXX"

If non source files are to be committed then

svn ci <files> -m "Commit msg|ReviewID:NON-SOURCE"

How to Generate Barcode using PHP and Display it as an Image on the same page

There is a library for this BarCode PHP. You just need to include a few files:


You can generate many types of barcodes, namely 1D or 2D. Add the required library:


Generate the colours:

// The arguments are R, G, and B for color.
$colorFront = new BCGColor(0, 0, 0);
$colorBack = new BCGColor(255, 255, 255);

After you have added all the codes, you will get this way:


Since several have asked for an example here is what I was able to do to get it done



header('Content-Type: image/png');

$color_white = new BCGColor(255, 255, 255);

$code = new BCGcode128();

$drawing = new BCGDrawing('', $color_white);


If you want to actually create the image file so you can save it then change

$drawing = new BCGDrawing('', $color_white);


$drawing = new BCGDrawing('image.png', $color_white);

are there dictionaries in javascript like python?

There were no real associative arrays in Javascript until 2015 (release of ECMAScript 6). Since then you can use the Map object as Robocat states. Look up the details in MDN. Example:

let map = new Map();
map.set('key', {'value1', 'value2'});
let values = map.get('key');

Without support for ES6 you can try using objects:

var x = new Object();
x["Key"] = "Value";

However with objects it is not possible to use typical array properties or methods like array.length. At least it is possible to access the "object-array" in a for-in-loop.

RegEx to match stuff between parentheses

var getMatchingGroups = function(s) {
  var r=/\((.*?)\)/g, a=[], m;
  while (m = r.exec(s)) {
  return a;

getMatchingGroups("something/([0-9])/([a-z])"); // => ["[0-9]", "[a-z]"]

Sorting list based on values from another list

The most obvious solution to me is to use the key keyword arg.

>>> X = ["a", "b", "c", "d", "e", "f", "g", "h", "i"]
>>> Y = [ 0,   1,   1,    0,   1,   2,   2,   0,   1]
>>> keydict = dict(zip(X, Y))
>>> X.sort(key=keydict.get)
>>> X
['a', 'd', 'h', 'b', 'c', 'e', 'i', 'f', 'g']

Note that you can shorten this to a one-liner if you care to:

>>> X.sort(key=dict(zip(X, Y)).get)

As Wenmin Mu and Jack Peng have pointed out, this assumes that the values in X are all distinct. That's easily managed with an index list:

>>> Z = ["A", "A", "C", "C", "C", "F", "G", "H", "I"]
>>> Z_index = list(range(len(Z)))
>>> Z_index.sort(key=keydict.get)
>>> Z = [Z[i] for i in Z_index]
>>> Z
['A', 'C', 'H', 'A', 'C', 'C', 'I', 'F', 'G']

Since the decorate-sort-undecorate approach described by Whatang is a little simpler and works in all cases, it's probably better most of the time. (This is a very old answer!)

"PKIX path building failed" and "unable to find valid certification path to requested target"

Try copying java cacerts:

cp /usr/lib/jvm/java-1.8.0-openjdk- $JAVA_HOME/jre/lib/security/cacerts

What does the Visual Studio "Any CPU" target mean?

"Any CPU" means that when the program is started, the .NET Framework will figure out, based on the OS bitness, whether to run your program in 32 bits or 64 bits.

There is a difference between x86 and Any CPU: on a x64 system, your executable compiled for X86 will run as a 32-bit executable.

As far as your suspicions go, just go to the Visual Studio 2008 command line and run the following.

dumpbin YourProgram.exe /headers

It will tell you the bitness of your program, plus a whole lot more.

JavaScript vs for

A shorter and best code according to jsperf is

keys  = Object.keys(obj);
for (var i = keys.length; i--;){
   value = obj[keys[i]];// or other action

jquery stop child triggering parent event

Or, rather than having an extra event handler to prevent another handler, you can use the Event Object argument passed to your click event handler to determine whether a child was clicked. target will be the clicked element and currentTarget will be the .header div:

     //Do nothing if .header was not directly clicked
     if( !== e.currentTarget) return;


SQL Statement using Where clause with multiple values

Select t1.SongName
From tablename t1
left join tablename t2
 on t1.SongName = t2.SongName
    and t1.PersonName <> t2.PersonName
    and t1.Status = 'Complete' -- my assumption that this is necessary
    and t2.Status = 'Complete' -- my assumption that this is necessary
    and t1.PersonName IN ('Holly', 'Ryan')
    and t2.PersonName IN ('Holly', 'Ryan')

AutoComplete TextBox in WPF

I have published a WPF Auto Complete Text Box in WPF at You can download and try it from

Transparent color of Bootstrap-3 Navbar

The class is .navbar-default. You need to create a class on your custom css .navbar-default.And follow the css code. Also if you don’t want box-shadow on your menu, you can put on the same class.

 .navbar-default {
      background-color:transparent !important;

enter image description here

To change font navbar color, the class is to change – .navbar-default .navbar-nav>li>a see the code bellow:

  .navbar-default .navbar-nav>li>a {

ref :

CSS rotate property in IE

Scroll down to '.box_rotate' for the Microsoft IE9+ prefix. Similar discussion here: Rotating a Div Element in jQuery

Css height in percent not working

This is what you need in the CSS:

html, body {
    height: 100%; 
    width: 100%; 
    margin: 0; 

Get max and min value from array in JavaScript

Find largest and smallest number in an array with lodash.

var array = [1, 3, 2];_x000D_
var func = _.over(Math.max, Math.min);_x000D_
var [max, min] = func(...array);_x000D_
// => [3, 1]_x000D_
<script src=""></script>

PATH issue with pytest 'ImportError: No module named YadaYadaYada'

I was getting this error due to something even simpler (you could even say trivial). I hadn't installed the pytest module. So a simple apt install python-pytest fixed it for me.

'pytest' would have been listed in as a test dependency. Make sure you install the test requirements as well.

How to convert rdd object to dataframe in spark

SparkSession has a number of createDataFrame methods that create a DataFrame given an RDD. I imagine one of these will work for your context.

For example:

def createDataFrame(rowRDD: RDD[Row], schema: StructType): DataFrame

Creates a DataFrame from an RDD containing Rows using the given schema.

How to reset or change the passphrase for a GitHub SSH key?

  1. Log in to your github account.
  2. Go to the "Settings" page (the "wrench and screwdriver" icon in the top right corner of the page).
  3. Go to "SSH keys" page.
  4. Generate a new SSH key (probably studying the links provided by github on that page).
  5. Add your new key using the "Add SSH key" link.
  6. Verify your new key works.
  7. Make gitub forget your old key by using the "Delete" link next to it in the list of known keys.

Converting integer to digit list

num = list(str(100))
index = len(num)
while index > 0:
    index -= 1
    num[index] = int(num[index])

It prints [1, 0, 0] object.

Converting char* to float or double

You are missing an include : #include <stdlib.h>, so GCC creates an implicit declaration of atof and atod, leading to garbage values.

And the format specifier for double is %f, not %d (that is for integers).

#include <stdlib.h>
#include <stdio.h>

int main()
  char *test = "12.11";
  double temp = strtod(test,NULL);
  float ftemp = atof(test);
  printf("price: %f, %f",temp,ftemp);
  return 0;
/* Output */
price: 12.110000, 12.110000

Angular.js directive dynamic templateURL

I have an example about this.

<!DOCTYPE html>
<html ng-app="app">

    <link rel="stylesheet" href="">

    <div class="container-fluid body-content" ng-controller="formView">
        <div class="row">
            <div class="col-md-12">
                <h4>Register Form</h4>
                <form class="form-horizontal" ng-submit="" name="f" novalidate>
                    <div ng-repeat="item in elements" class="form-group">
                        <element type="{{item.Type}}" model="item"></element>
                    <input ng-show="f.$valid" type="submit" id="submit" value="Submit" class="" />
    <script src=""></script>
    <script src=""></script>
    <script src=""></script>
    <script src="app.js"></script>


angular.module('app', [])
    .controller('formView', function ($scope) {
        $scope.elements = [{
            "PlaceHolder":"Place Holder Text",
            "PlaceHolder":"Place Holder Text",
    .directive('element', function () {
        return {
            restrict: 'E',
            link: function (scope, element, attrs) {
                scope.contentUrl = attrs.type + '.html';
                attrs.$observe("ver", function (v) {
                    scope.contentUrl = v + '.html';
            template: '<div ng-include="contentUrl"></div>'

File opens instead of downloading in internet explorer in a href link

It should be fixed on server side. Your server should return this headers for this file types:

Content-Type: application/octet-stream
Content-Disposition: attachment;filename=\"\"

How to write a shell script that runs some commands as superuser and some commands not as superuser, without having to babysit it?

File sutest

echo "uid is ${UID}"
echo "user is ${USER}"
echo "username is ${USERNAME}"

run it: `./sutest' gives me

uid is 500
user is stephenp
username is stephenp

but using sudo: sudo ./sutest gives

uid is 0
user is root
username is stephenp

So you retain the original user name in $USERNAME when running as sudo. This leads to a solution similar to what others posted:

sudo -u ${USERNAME} normal_command_1
sudo -u ${USERNAME} normal_command_2
# etc.

Just sudo to invoke your script in the first place, it will prompt for the password once.

I originally wrote this answer on Linux, which does have some differences with OS X

OS X (I'm testing this on Mountain Lion 10.8.3) has an environment variable SUDO_USER when you're running sudo, which can be used in place of USERNAME above, or to be more cross-platform the script could check to see if SUDO_USER is set and use it if so, or use USERNAME if that's set.

Changing the original script for OS X, it becomes...

sudo -u ${SUDO_USER} normal_command_1
sudo -u ${SUDO_USER} normal_command_2
# etc.

A first stab at making it cross-platform could be...

# set "THE_USER" to SUDO_USER if that's set,
#  else set it to USERNAME if THAT is set,
#   else set it to the string "unknown"
# should probably then test to see if it's "unknown"

sudo -u ${THE_USER} normal_command_1
sudo -u ${THE_USER} normal_command_2
# etc.

How do I get the number of elements in a list?

Besides len you can also use operator.length_hint (requires Python 3.4+). For a normal list both are equivalent, but length_hint makes it possible to get the length of a list-iterator, which could be useful in certain circumstances:

>>> from operator import length_hint
>>> l = ["apple", "orange", "banana"]
>>> len(l)
>>> length_hint(l)

>>> list_iterator = iter(l)
>>> len(list_iterator)
TypeError: object of type 'list_iterator' has no len()
>>> length_hint(list_iterator)

But length_hint is by definition only a "hint", so most of the time len is better.

I've seen several answers suggesting accessing __len__. This is all right when dealing with built-in classes like list, but it could lead to problems with custom classes, because len (and length_hint) implement some safety checks. For example, both do not allow negative lengths or lengths that exceed a certain value (the sys.maxsize value). So it's always safer to use the len function instead of the __len__ method!

Recursive Lock (Mutex) vs Non-Recursive Lock (Mutex)

The answer is not efficiency. Non-reentrant mutexes lead to better code.

Example: A::foo() acquires the lock. It then calls B::bar(). This worked fine when you wrote it. But sometime later someone changes B::bar() to call A::baz(), which also acquires the lock.

Well, if you don't have recursive mutexes, this deadlocks. If you do have them, it runs, but it may break. A::foo() may have left the object in an inconsistent state before calling bar(), on the assumption that baz() couldn't get run because it also acquires the mutex. But it probably shouldn't run! The person who wrote A::foo() assumed that nobody could call A::baz() at the same time - that's the entire reason that both of those methods acquired the lock.

The right mental model for using mutexes: The mutex protects an invariant. When the mutex is held, the invariant may change, but before releasing the mutex, the invariant is re-established. Reentrant locks are dangerous because the second time you acquire the lock you can't be sure the invariant is true any more.

If you are happy with reentrant locks, it is only because you have not had to debug a problem like this before. Java has non-reentrant locks these days in java.util.concurrent.locks, by the way.

How can I get stock quotes using Google Finance API?

The Google stock quote API has gone away. However, Investor's Exchange offers an API that's very easy to use for quote data.

Reloading submodules in IPython

My standard practice for reloading is to combine both methods following first opening of IPython:

from IPython.lib.deepreload import reload
%load_ext autoreload
%autoreload 2

Loading modules before doing this will cause them not to be reloaded, even with a manual reload(module_name). I still, very rarely, get inexplicable problems with class methods not reloading that I've not yet looked into.

Count number of records returned by group by

In PostgreSQL this works for me:

select count(count.counts) 
    (select count(*) as counts 
     from table 
     group by concept) as count;

C++ How do I convert a std::chrono::time_point to long and back

I would also note there are two ways to get the number of ms in the time point. I'm not sure which one is better, I've benchmarked them and they both have the same performance, so I guess it's a matter of preference. Perhaps Howard could chime in:

auto now = system_clock::now();

//Cast the time point to ms, then get its duration, then get the duration's count.
auto ms = time_point_cast<milliseconds>(now).time_since_epoch().count();

//Get the time point's duration, then cast to ms, then get its count.
auto ms = duration_cast<milliseconds>(tpBid.time_since_epoch()).count();

The first one reads more clearly in my mind going from left to right.

How do you get the string length in a batch file?

I like the two line approach of jmh_gr.

It won't work with single digit numbers unless you put () around the portion of the command before the redirect. since 1> is a special command "Echo is On" will be redirected to the file.

This example should take care of single digit numbers but not the other special characters such as < that may be in the string.

(ECHO %strvar%)> tempfile.txt

Composer Update Laravel

When you run composer update, composer generates a file called composer.lock which lists all your packages and the currently installed versions. This allows you to later run composer install, which will install the packages listed in that file, recreating the environment that you were last using.

It appears from your log that some of the versions of packages that are listed in your composer.lock file are no longer available. Thus, when you run composer install, it complains and fails. This is usually no big deal - just run composer update and it will attempt to build a set of packages that work together and write a new composer.lock file.

However, you're running into a different problem. It appears that, in your composer.json file, the original developer has added some pre- or post- update actions that are failing, specifically a php artisan migrate command. This can be avoided by running the following: composer update --no-scripts

This will run the composer update but will skip over the scripts added to the file. You should be able to successfully run the update this way.

However, this does not solve the problem long-term. There are two problems:

  1. A migration is for database changes, not random stuff like compiling assets. Go through the migrations and remove that code from there.

  2. Assets should not be compiled each time you run composer update. Remove that step from the composer.json file.

From what I've read, best practice seems to be compiling assets on an as-needed basis during development (ie. when you're making changes to your LESS files - ideally using a tool like gulp.js) and before deployment.

Arguments to main in C

Imagine it this way

*main() is also a function which is called by something else (like another FunctioN)

*the arguments to it is decided by the FunctioN

*the second argument is an array of strings

*the first argument is a number representing the number of strings

*do something with the strings

Maybe a example program woluld help.

int main(int argc,char *argv[])

    printf("you entered in reverse order:\n");


return 0;

it just prints everything you enter as args in reverse order but YOU should make new programs that do something more useful.

compile it (as say hello) run it from the terminal with the arguments like

./hello am i here

then try to modify it so that it tries to check if two strings are reverses of each other or not then you will need to check if argc parameter is exactly three if anything else print an error

if(argc!=3)/*3 because even the executables name string is on argc*/
    printf("unexpected number of arguments\n");
    return -1;

then check if argv[2] is the reverse of argv[1] and print the result

./hello asdf fdsa

should output

they are exact reverses of each other

the best example is a file copy program try it it's like cp

cp file1 file2

cp is the first argument (argv[0] not argv[1]) and mostly you should ignore the first argument unless you need to reference or something

if you made the cp program you understood the main args really...

What is the syntax to insert one list into another list in python?

The question does not make clear what exactly you want to achieve.

List has the append method, which appends its argument to the list:

>>> list_one = [1,2,3]
>>> list_two = [4,5,6]
>>> list_one.append(list_two)
>>> list_one
[1, 2, 3, [4, 5, 6]]

There's also the extend method, which appends items from the list you pass as an argument:

>>> list_one = [1,2,3]
>>> list_two = [4,5,6]
>>> list_one.extend(list_two)
>>> list_one
[1, 2, 3, 4, 5, 6]

And of course, there's the insert method which acts similarly to append but allows you to specify the insertion point:

>>> list_one.insert(2, list_two)
>>> list_one
[1, 2, [4, 5, 6], 3, 4, 5, 6]

To extend a list at a specific insertion point you can use list slicing (thanks, @florisla):

>>> l = [1, 2, 3, 4, 5]
>>> l[2:2] = ['a', 'b', 'c']
>>> l
[1, 2, 'a', 'b', 'c', 3, 4, 5]

List slicing is quite flexible as it allows to replace a range of entries in a list with a range of entries from another list:

>>> l = [1, 2, 3, 4, 5]
>>> l[2:4] = ['a', 'b', 'c'][1:3]
>>> l
[1, 2, 'b', 'c', 5]

Quoting backslashes in Python string literals

Use a raw string:

>>> foo = r'baz "\"'
>>> foo
'baz "\\"'

Note that although it looks wrong, it's actually right. There is only one backslash in the string foo.

This happens because when you just type foo at the prompt, python displays the result of __repr__() on the string. This leads to the following (notice only one backslash and no quotes around the printed string):

>>> foo = r'baz "\"'
>>> foo
'baz "\\"'
>>> print(foo)
baz "\"

And let's keep going because there's more backslash tricks. If you want to have a backslash at the end of the string and use the method above you'll come across a problem:

>>> foo = r'baz \'
  File "<stdin>", line 1
    foo = r'baz \'
SyntaxError: EOL while scanning single-quoted string

Raw strings don't work properly when you do that. You have to use a regular string and escape your backslashes:

>>> foo = 'baz \\'
>>> print(foo)
baz \

However, if you're working with Windows file names, you're in for some pain. What you want to do is use forward slashes and the os.path.normpath() function:

myfile = os.path.normpath('c:/folder/subfolder/file.txt')

This will save a lot of escaping and hair-tearing. This page was handy when going through this a while ago.

Convert an enum to List<string>

I want to add another solution: In my case, I need to use a Enum group in a drop down button list items. So they might have space, i.e. more user friendly descriptions needed:

  public enum CancelReasonsEnum
    [Description("In rush")]
    [Description("Need more coffee")]
    [Description("Call me back in 5 minutes!")]

In a helper class (HelperMethods) I created the following method:

 public static List<string> GetListOfDescription<T>() where T : struct
        Type t = typeof(T);
        return !t.IsEnum ? null : Enum.GetValues(t).Cast<Enum>().Select(x => x.GetDescription()).ToList();

When you call this helper you will get the list of item descriptions.

 List<string> items = HelperMethods.GetListOfDescription<CancelReasonEnum>();

ADDITION: In any case, if you want to implement this method you need :GetDescription extension for enum. This is what I use.

 public static string GetDescription(this Enum value)
        Type type = value.GetType();
        string name = Enum.GetName(type, value);
        if (name != null)
            FieldInfo field = type.GetField(name);
            if (field != null)
                DescriptionAttribute attr =Attribute.GetCustomAttribute(field,typeof(DescriptionAttribute)) as DescriptionAttribute;
                if (attr != null)
                    return attr.Description;
        return null;
        /* how to use
            MyEnum x = MyEnum.NeedMoreCoffee;
            string description = x.GetDescription();


How to access a dictionary element in a Django template?

Similar to the answer by @russian_spy :

{% for choice in choices.items %} 
  <li>{{choice.0}} - {{choice.1}}</li>
{% endfor %}

This might be suitable for breaking down more complex dictionaries.

Capturing count from an SQL query

SqlConnection conn = new SqlConnection("ConnectionString");
SqlCommand comm = new SqlCommand("SELECT COUNT(*) FROM table_name", conn);
Int32 count = (Int32) comm .ExecuteScalar();

Properties file in python (similar to Java Properties)

For .ini files there is the ConfigParser module that provides a format compatible with .ini files.

Anyway there's nothing available for parsing complete .properties files, when I have to do that I simply use jython (I'm talking about scripting).

Ruby Array find_first object?

use array detect method if you wanted to return first value where block returns true

[1,2,3,11,34].detect(&:even?) #=> 2


[1,2,3,11,34].detect{|i| i.even?} #=> 2

If you wanted to return all values where block returns true then use select

[1,2,3,11,34].select(&:even?)  #=> [2, 34]

How to get logged-in user's name in Access vba?

Try this:

Function UserNameWindows() As String
     UserName = Environ("USERNAME")
End Function

Substitute multiple whitespace with single whitespace in Python

For completeness, you can also use:

mystring = mystring.strip()  # the while loop will leave a trailing space, 
                  # so the trailing whitespace must be dealt with
                  # before or after the while loop
while '  ' in mystring:
    mystring = mystring.replace('  ', ' ')

which will work quickly on strings with relatively few spaces (faster than re in these situations).

In any scenario, Alex Martelli's split/join solution performs at least as quickly (usually significantly more so).

In your example, using the default values of timeit.Timer.repeat(), I get the following times:

str.replace: [1.4317800167340238, 1.4174888149192384, 1.4163512401715934]
re.sub:      [3.741931446594549,  3.8389395858970374, 3.973777672860706]
split/join:  [0.6530919432498195, 0.6252146571700905, 0.6346594329726258]


Just came across this post which provides a rather long comparison of the speeds of these methods.

Calling a class method raises a TypeError in Python

In python member function of a class need explicit self argument. Same as implicit this pointer in C++. For more details please check out this page.

Get scroll position using jquery

Older IE and Firefox browsers attach the scrollbar to the documentElement, or what would be the <html> tag in HTML.

All other browsers attach the scrollbar to document.body, or what would be the <body> tag in HTML.

The correct solution would be to check which one to use, depending on browser

var doc = document.documentElement.clientHeight ? document.documentElement : document.body;
var s   = $(doc).scrollTop();

jQuery does make this a little easier, when passing in either window or document jQuery's scrollTop does a similar check and figures it out, so either of these should work cross-browser

var s = $(document).scrollTop();


var s = $(window).scrollTop();

jQuery scrollTop() docs

Description: Get the current vertical position of the scroll bar for the first element in the set of matched elements or set the vertical position of the scroll bar for every matched element.

...nothing that works for my div, just the full page

If it's for a DIV, you'd have to target the element that has the scrollbar attached, to get the scrolled amount


If you need to get the elements distance from the top of the document, you can also do


Display PDF file inside my android application

Highly recommend you check out PDF.js which is able to render PDF documents in a standard a WebView component.

Also see for a sample implementation of this.

How do I find out which DOM element has the focus?

If you want to get a object that is instance of Element, you must use document.activeElement, but if you want to get a object that is instance of Text, you must to use document.getSelection().focusNode.

I hope helps.

How to change the interval time on bootstrap carousel?

You can use the options when initializing the carousel, like this:

// interval is in milliseconds. 1000 = 1 second -> so 1000 * 10 = 10 seconds
  interval: 1000 * 10

or you can use the interval attribute directly on the HTML tag, like this:

<div class="carousel" data-interval="10000">

The advantage of the latter approach is that you do not have to write any JS for it - while the advantage of the former is that you can compute the interval and initialize it with a variable value at run time.

Streaming video from Android camera to server

I am able to send the live camera video from mobile to my server.using this link see the link

Refer the above link.there is a sample application in that link. Just you need to set your service url in RecordActivity.class.

Example as: ffmpeg_link="rtmp://yourserveripaddress:1935/live/venkat";

we can able to send H263 and H264 type videos using that link.

Why does my 'git branch' have no master?

It seems there must be at least one local commit on the master branch to do:

git push -u origin master

So if you did git init . and then git remote add origin ..., you still need to do:

git add ...
git commit -m "..."

How to pass arguments to entrypoint in docker-compose.yml

To override the default entrypoint, use entrypoint option. To pass the arguments use command.

Here is the example of replacing bash with sh in ubuntu image:

version: '3'
    entrypoint: /bin/sh
    command: -c "ps $$(echo $$$$)"
    image: ubuntu
    tty: true
    entrypoint: /bin/bash
    command: -c "ps $$(echo $$$$)"
    image: ubuntu
    tty: true

Here is the output:

$ docker-compose up   
Starting test_sh_1                ... done
Starting 020211508a29_test_bash_1 ... done
Attaching to test_sh_1, 020211508a29_test_bash_1
sh_1    |   PID TTY      STAT   TIME COMMAND
sh_1    |     1 pts/0    Ss+    0:00 /bin/sh -c ps $(echo $$)
020211508a29_test_bash_1 |   PID TTY      STAT   TIME COMMAND
020211508a29_test_bash_1 |     1 pts/0    Rs+    0:00 ps 1

What is "stdafx.h" used for in Visual Studio?

"Stdafx.h" is a precompiled header.It include file for standard system include files and for project-specific include files that are used frequently but are changed infrequently.which reduces compile time and Unnecessary Processing.

Precompiled Header stdafx.h is basically used in Microsoft Visual Studio to let the compiler know the files that are once compiled and no need to compile it from scratch. You can read more about it