Programs & Examples On #Getattr

getattr is a Python built-in function used to access a named attribute on an object.

What is getattr() exactly and how do I use it?

# getattr

class hithere():

    def french(self):
        print 'bonjour'

    def english(self):
        print 'hello'

    def german(self):
        print 'hallo'

    def czech(self):
        print 'ahoj'

    def noidea(self):
        print 'unknown language'


def dispatch(language):
    try:
        getattr(hithere(),language)()
    except:
        getattr(hithere(),'noidea')()
        # note, do better error handling than this

dispatch('french')
dispatch('english')
dispatch('german')
dispatch('czech')
dispatch('spanish')

Difference between __getattr__ vs __getattribute__

A key difference between __getattr__ and __getattribute__ is that __getattr__ is only invoked if the attribute wasn't found the usual ways. It's good for implementing a fallback for missing attributes, and is probably the one of two you want.

__getattribute__ is invoked before looking at the actual attributes on the object, and so can be tricky to implement correctly. You can end up in infinite recursions very easily.

New-style classes derive from object, old-style classes are those in Python 2.x with no explicit base class. But the distinction between old-style and new-style classes is not the important one when choosing between __getattr__ and __getattribute__.

You almost certainly want __getattr__.

How do I implement __getattribute__ without an infinite recursion error?

You get a recursion error because your attempt to access the self.__dict__ attribute inside __getattribute__ invokes your __getattribute__ again. If you use object's __getattribute__ instead, it works:

class D(object):
    def __init__(self):
        self.test=20
        self.test2=21
    def __getattribute__(self,name):
        if name=='test':
            return 0.
        else:
            return object.__getattribute__(self, name)

This works because object (in this example) is the base class. By calling the base version of __getattribute__ you avoid the recursive hell you were in before.

Ipython output with code in foo.py:

In [1]: from foo import *

In [2]: d = D()

In [3]: d.test
Out[3]: 0.0

In [4]: d.test2
Out[4]: 21

Update:

There's something in the section titled More attribute access for new-style classes in the current documentation, where they recommend doing exactly this to avoid the infinite recursion.

How to get a reference to an iframe's window object inside iframe's onload handler created from parent window

You're declaring everything in the parent page. So the references to window and document are to the parent page's. If you want to do stuff to the iframe's, use iframe || iframe.contentWindow to access its window, and iframe.contentDocument || iframe.contentWindow.document to access its document.

There's a word for what's happening, possibly "lexical scope": What is lexical scope?

The only context of a scope is this. And in your example, the owner of the method is doc, which is the iframe's document. Other than that, anything that's accessed in this function that uses known objects are the parent's (if not declared in the function). It would be a different story if the function were declared in a different place, but it's declared in the parent page.

This is how I would write it:

(function () {
  var dom, win, doc, where, iframe;

  iframe = document.createElement('iframe');
  iframe.src = "javascript:false";

  where = document.getElementsByTagName('script')[0];
  where.parentNode.insertBefore(iframe, where);

  win = iframe.contentWindow || iframe;
  doc = iframe.contentDocument || iframe.contentWindow.document;

  doc.open();
  doc._l = (function (w, d) {
    return function () {
      w.vanishing_global = new Date().getTime();

      var js = d.createElement("script");
      js.src = 'test-vanishing-global.js?' + w.vanishing_global;

      w.name = "foobar";
      d.foobar = "foobar:" + Math.random();
      d.foobar = "barfoo:" + Math.random();
      d.body.appendChild(js);
    };
  })(win, doc);
  doc.write('<body onload="document._l();"></body>');
  doc.close();
})();

The aliasing of win and doc as w and d aren't necessary, it just might make it less confusing because of the misunderstanding of scopes. This way, they are parameters and you have to reference them to access the iframe's stuff. If you want to access the parent's, you still use window and document.

I'm not sure what the implications are of adding methods to a document (doc in this case), but it might make more sense to set the _l method on win. That way, things can be run without a prefix...such as <body onload="_l();"></body>

PHP date() with timezone?

The answer above caused me to jump through some hoops/gotchas, so just posting the cleaner code that worked for me:

$dt = new DateTime();
$dt->setTimezone(new DateTimeZone('America/New_York'));
$dt->setTimestamp(123456789);

echo $dt->format('F j, Y @ G:i');

PHP random string generator

One very quick way is to do something like:

substr(md5(rand()),0,10);

This will generate a random string with the length of 10 chars. Of course, some might say it's a bit more heavy on the computation side, but nowadays processors are optimized to run md5 or sha256 algorithm very quickly. And of course, if the rand() function returns the same value, the result will be the same, having a 1 / 32767 chance of being the same. If security's the issue, then just change rand() to mt_rand()

receiving error: 'Error: SSL Error: SELF_SIGNED_CERT_IN_CHAIN' while using npm

You need to upgrade npm.

// Do this first, or the upgrade will fail
npm config set ca ""

npm install npm -g

// Undo the previous config change
npm config delete ca

You may need to prefix those commands with sudo.

Source: http://blog.npmjs.org/post/78085451721/npms-self-signed-certificate-is-no-more

C#: what is the easiest way to subtract time?

try this

namespace dateandtime
{

    class DatesTime
    {

        public static DateTime Substract(DateTime now, int hours,int minutes,int seconds)
        {
            TimeSpan T1 = new TimeSpan(hours, minutes, seconds);
            return now.Subtract(T1);
        }


        static void Main(string[] args)
        {
            Console.WriteLine(Substract(DateTime.Now, 36, 0, 0).ToString());

        }
    }
}

How to scp in Python?

if you install putty on win32 you get an pscp (putty scp).

so you can use the os.system hack on win32 too.

(and you can use the putty-agent for key-managment)


sorry it is only a hack (but you can wrap it in a python class)

href overrides ng-click in Angular.js

This example from the angular documentation site just does href without even assigning it to an empty string:

[<a href ng-click="colors.splice($index, 1)">X</a>]

http://docs.angularjs.org/api/ng.directive:select

Getting a link to go to a specific section on another page

To link from a page to another section just use

<a href="index.php#firstdiv">my first div</a>

Break statement in javascript array map method

That's not possible using the built-in Array.prototype.map. However, you could use a simple for-loop instead, if you do not intend to map any values:

var hasValueLessThanTen = false;
for (var i = 0; i < myArray.length; i++) {
  if (myArray[i] < 10) {
    hasValueLessThanTen = true;
    break;
  }
}

Or, as suggested by @RobW, use Array.prototype.some to test if there exists at least one element that is less than 10. It will stop looping when some element that matches your function is found:

var hasValueLessThanTen = myArray.some(function (val) { 
  return val < 10;
});

Can I use DIV class and ID together in CSS?

Yes, yes you can.

#y.x {
 /* will select element of id="y" that also has class="x" */
}

Similarly:

.x#y {
 /* will select elements of class="x" that also have an id="y" */
}

Incidentally this might be useful in some use cases (wherein classes are used to represent some form of event or interaction), but for the most part it's not necessarily that useful, since ids are unique in the document anyway. But if you're using classes for user-interaction then it can be useful to know.

smtp configuration for php mail

But now it is not working and I contacted our hosting team then they told me to use smtp

Newsflash - it was using SMTP before. They've not provided you with the information you need to solve the problem - or you've not relayed it accurately here.

Its possible that they've disabled the local MTA on the webserver, in which case you'll need to connect the SMTP port on a remote machine. There are lots of toolkits which will do the heavy lifting for you. Personally I like phpmailer because it adds other functionality.

Certainly if they've taken away a facility which was there before and your paying for a service then your provider should be giving you better support than that (there are also lots of programs to drop in in place of a full MTA which would do the job).

C.

JavaScript backslash (\) in variables is causing an error

The jsfiddle link to where i tried out your query http://jsfiddle.net/A8Dnv/1/ its working fine @Imrul as mentioned you are using C# on server side and you dont mind that either: http://msdn.microsoft.com/en-us/library/system.text.regularexpressions.regex.escape.aspx

Document directory path of Xcode Device Simulator

on my computer, the path is:

~/Library/Developer/CoreSimulator/Devices/1A8DF360-B0A6-4815-95F3-68A6AB0BCC78/data/Container/Data/Application/

NOTE: probably those long IDs (i.e UDIDs) are different on your computer.

Laravel 4 Eloquent Query Using WHERE with OR AND OR?

Another way without using Modal

Database: stocks Columns:id,name,company_name,exchange_name,status enter image description here

  $name ='aa'
  $stocks = DB::table('stocks')
            ->select('name', 'company_name', 'exchange_name')
            ->where(function($query) use ($name) {
                $query->where('name', 'like', '%' . $name . '%')
                ->orWhere('company_name', 'like', '%' . $name . '%');
            })
            ->Where('status', '=', 1)
            ->limit(20)
            ->get();

Installing tensorflow with anaconda in windows

1) Update conda

Run the anaconda prompt as administrator

conda update -n base -c defaults conda

2) Create an environment for python new version say, 3.6

conda create --name py36 python=3.6

3) Activate the new environment

conda activate py36

4) Upgrade pip

pip install --upgrade pip

5) Install tensorflow

pip install https://testpypi.python.org/packages/db/d2/876b5eedda1f81d5b5734277a155fa0894d394a7f55efa9946a818ad1190/tensorflow-0.12.1-cp36-cp36m-win_amd64.whl

If it doesn't work

If you have problem with wheel at the environment location, or pywrap_tensorflow problem,

 pip install tensorflow --upgrade --force-reinstall

How to use count and group by at the same select statement

The other way is:

/* Number of rows in a derived table called d1. */
select count(*) from
(
  /* Number of times each town appears in user. */
  select town, count(*)
  from user
  group by town
) d1

IIS7 URL Redirection from root to sub directory

Here it is. Add this code to your web.config file:

<system.webServer>
    <rewrite>
        <rules>
            <rule name="Root Hit Redirect" stopProcessing="true">
                <match url="^$" />
                <action type="Redirect" url="/menu_1/MainScreen.aspx" />
            </rule>
        </rules>
    </rewrite>
</system.webServer>

It will do 301 Permanent Redirect (URL will be changed in browser). If you want to have such "redirect" to be invisible (rewrite, internal redirect), then use this rule (the only difference is that "Redirect" has been replaced by "Rewrite"):

<system.webServer>
    <rewrite>
        <rules>
            <rule name="Root Hit Redirect" stopProcessing="true">
                <match url="^$" />
                <action type="Rewrite" url="/menu_1/MainScreen.aspx" />
            </rule>
        </rules>
    </rewrite>
</system.webServer>

GIT: Checkout to a specific folder

For a single file:

git show HEAD:abspath/to/file > file.copy

How to display a database table on to the table in the JSP page

The problem here is very simple. If you want to display value in JSP, you have to use <%= %> tag instead of <% %>, here is the solved code:

<tr> <td><%=rs.getInt("ID") %></td> <td><%=rs.getString("NAME") %></td> <td><%=rs.getString("SKILL") %></td> </tr>

Java optional parameters

Short version :

Using three dots:

public void foo(Object... x) {
    String first    =  x.length > 0 ? (String)x[0]  : "Hello";
    int duration    =  x.length > 1 ? Integer.parseInt((String) x[1])     : 888;
}   
foo("Hii", ); 
foo("Hii", 146); 

(based on @VitaliiFedorenko's answer)

The process cannot access the file because it is being used by another process (File is created but contains nothing)

Try This

string path = @"c:\mytext.txt";

if (File.Exists(path))
{
    File.Delete(path);
}

{ // Consider File Operation 1
    FileStream fs = new FileStream(path, FileMode.OpenOrCreate);
    StreamWriter str = new StreamWriter(fs);
    str.BaseStream.Seek(0, SeekOrigin.End);
    str.Write("mytext.txt.........................");
    str.WriteLine(DateTime.Now.ToLongTimeString() + " " + 
                  DateTime.Now.ToLongDateString());
    string addtext = "this line is added" + Environment.NewLine;
    str.Flush();
    str.Close();
    fs.Close();
    // Close the Stream then Individually you can access the file.
}

File.AppendAllText(path, addtext);  // File Operation 2

string readtext = File.ReadAllText(path); // File Operation 3

Console.WriteLine(readtext);

In every File Operation, The File will be Opened and must be Closed prior Opened. Like wise in the Operation 1 you must Close the File Stream for the Further Operations.

Data binding for TextBox

I Recommend you implement INotifyPropertyChanged and change your databinding code to this:

this.textBox.DataBindings.Add("Text",
                                this.Food,
                                "Name",
                                false,
                                DataSourceUpdateMode.OnPropertyChanged);

That'll fix it.

Note that the default DataSourceUpdateMode is OnValidation, so if you don't specify OnPropertyChanged, the model object won't be updated until after your validations have occurred.

How do you set the document title in React?

I haven't tested this too thoroughly, but this seems to work. Written in TypeScript.

interface Props {
    children: string|number|Array<string|number>,
}

export default class DocumentTitle extends React.Component<Props> {

    private oldTitle: string = document.title;

    componentWillUnmount(): void {
        document.title = this.oldTitle;
    }

    render() {
        document.title = Array.isArray(this.props.children) ? this.props.children.join('') : this.props.children;
        return null;
    }
}

Usage:

export default class App extends React.Component<Props, State> {

    render() {
        return <>
            <DocumentTitle>{this.state.files.length} Gallery</DocumentTitle>
            <Container>
                Lorem ipsum
            </Container>
        </>
    }
}

Not sure why others are keen on putting their entire app inside their <Title> component, that seems weird to me.

By updating the document.title inside render() it'll refresh/stay up to date if you want a dynamic title. It should revert the title when unmounted too. Portals are cute, but seem unnecessary; we don't really need to manipulate any DOM nodes here.

Generate .pem file used to set up Apple Push Notifications

There's much simpler solution today — pem. This tool makes life much easier.

For example, to generate or renew your push notification certificate just enter:

fastlane pem 

and it's done in under a minute. In case you need a sandbox certificate, enter:

fastlane pem --development

And that's pretty it.

Finding first blank row, then writing to it

Update

Inspired by Daniel's code above and the fact that this is WAY! more interesting to me now then the actual work I have to do, i created a hopefully full-proof function to find the first blank row in a sheet. Improvements welcome! Otherwise, this is going to my library :) Hopefully others benefit as well.

    Function firstBlankRow(ws As Worksheet) As Long
'returns the row # of the row after the last used row
'Or the first row with no data in it

    Dim rngSearch As Range, cel As Range

    With ws

        Set rngSearch = .UsedRange.Columns(1).Find("") '-> does blank exist in the first column of usedRange

        If Not rngSearch Is Nothing Then

            Set rngSearch = .UsedRange.Columns(1).SpecialCells(xlCellTypeBlanks)

            For Each cel In rngSearch

                If Application.WorksheetFunction.CountA(cel.EntireRow) = 0 Then

                    firstBlankRow = cel.Row
                    Exit For

                End If

            Next

        Else '-> no blanks in first column of used range

            If Application.WorksheetFunction.CountA(Cells(.Rows.Count, 1).EntireRow) = 0 Then '-> is the last row of the sheet blank?

                '-> yeap!, then no blank rows!
                MsgBox "Whoa! All rows in sheet are used. No blank rows exist!"


            Else

                '-> okay, blank row exists
                firstBlankRow = .UsedRange.SpecialCells(xlCellTypeBlanks).Row + 1

            End If

        End If

    End With

End Function

Original Answer

To find the first blank in a sheet, replace this part of your code:

Cells(1, 1).Select
For Each Cell In ws.UsedRange.Cells
    If Cell.Value = "" Then Cell = Num
    MsgBox "Checking cell " & Cell & " for value."
Next

With this code:

With ws

    Dim rngBlanks As Range, cel As Range

    Set rngBlanks = Intersect(.UsedRange, .Columns(1)).Find("")

    If Not rngBlanks Is Nothing Then '-> make sure blank cell exists in first column of usedrange
        '-> find all blank rows in column A within the used range
        Set rngBlanks = Intersect(.UsedRange, .Columns(1)).SpecialCells(xlCellTypeBlanks)

        For Each cel In rngBlanks '-> loop through blanks in column A

            '-> do a countA on the entire row, if it's 0, there is nothing in the row
            If Application.WorksheetFunction.CountA(cel.EntireRow) = 0 Then
                num = cel.Row
                Exit For
            End If

        Next
    Else

        num = usedRange.SpecialCells(xlCellTypeLastCell).Offset(1).Row                 

    End If


End With

Combine two or more columns in a dataframe into a new column with a new name

As already mentioned in comments by Uwe and UseR, a general solution in the tidyverse format would be to use the command unite:

library(tidyverse)

n = c(2, 3, 5) 
s = c("aa", "bb", "cc") 
b = c(TRUE, FALSE, TRUE) 

df = data.frame(n, s, b) %>% 
  unite(x, c(n, s), sep = " ", remove = FALSE)

ActionBarCompat: java.lang.IllegalStateException: You need to use a Theme.AppCompat

Just do it Build -> Clean Project. I think this will solve your problem.

How to apply Hovering on html area tag?

What I did was to create a canvas element that I then position in front of the image map. Then, whenever an area is moused-over, I call a func that gets the coord string for that shape and the shape-type. If it's a poly I use the coords to draw an outline on the canvas. If it's a rect I draw a rect outline. You could easily add code to deal with circles.

You could also set the opacity of the canvas to less than 100% before filling the poly/rect/circle. You could also change the reliance on a global for the canvas's context - this would mean you could deal with more than 1 image-map on the same page.

<!DOCTYPE html>
<html>
<head>
<script>

// stores the device context of the canvas we use to draw the outlines
// initialized in myInit, used in myHover and myLeave
var hdc;

// shorthand func
function byId(e){return document.getElementById(e);}

// takes a string that contains coords eg - "227,307,261,309, 339,354, 328,371, 240,331"
// draws a line from each co-ord pair to the next - assumes starting point needs to be repeated as ending point.
function drawPoly(coOrdStr)
{
    var mCoords = coOrdStr.split(',');
    var i, n;
    n = mCoords.length;

    hdc.beginPath();
    hdc.moveTo(mCoords[0], mCoords[1]);
    for (i=2; i<n; i+=2)
    {
        hdc.lineTo(mCoords[i], mCoords[i+1]);
    }
    hdc.lineTo(mCoords[0], mCoords[1]);
    hdc.stroke();
}

function drawRect(coOrdStr)
{
    var mCoords = coOrdStr.split(',');
    var top, left, bot, right;
    left = mCoords[0];
    top = mCoords[1];
    right = mCoords[2];
    bot = mCoords[3];
    hdc.strokeRect(left,top,right-left,bot-top); 
}

function myHover(element)
{
    var hoveredElement = element;
    var coordStr = element.getAttribute('coords');
    var areaType = element.getAttribute('shape');

    switch (areaType)
    {
        case 'polygon':
        case 'poly':
            drawPoly(coordStr);
            break;

        case 'rect':
            drawRect(coordStr);
    }
}

function myLeave()
{
    var canvas = byId('myCanvas');
    hdc.clearRect(0, 0, canvas.width, canvas.height);
}

function myInit()
{
    // get the target image
    var img = byId('img-imgmap201293016112');

    var x,y, w,h;

    // get it's position and width+height
    x = img.offsetLeft;
    y = img.offsetTop;
    w = img.clientWidth;
    h = img.clientHeight;

    // move the canvas, so it's contained by the same parent as the image
    var imgParent = img.parentNode;
    var can = byId('myCanvas');
    imgParent.appendChild(can);

    // place the canvas in front of the image
    can.style.zIndex = 1;

    // position it over the image
    can.style.left = x+'px';
    can.style.top = y+'px';

    // make same size as the image
    can.setAttribute('width', w+'px');
    can.setAttribute('height', h+'px');

    // get it's context
    hdc = can.getContext('2d');

    // set the 'default' values for the colour/width of fill/stroke operations
    hdc.fillStyle = 'red';
    hdc.strokeStyle = 'red';
    hdc.lineWidth = 2;
}
</script>

<style>
body
{
    background-color: gray;
}
canvas
{
    pointer-events: none;       /* make the canvas transparent to the mouse - needed since canvas is position infront of image */
    position: absolute;
}
</style>

<title></title>
</head>
<body onload='myInit()'>
    <canvas id='myCanvas'></canvas>     <!-- gets re-positioned in myInit(); -->
<center>
<img src='http://dailyaeen.com.pk/epaper/wp-content/uploads/2012/09/27+Sep+2012-1.jpg?1349003469874' usemap='#imgmap_css_container_imgmap201293016112' class='imgmap_css_container' title='imgmap201293016112' alt='imgmap201293016112' id='img-imgmap201293016112' />
<map id='imgmap201293016112' name='imgmap_css_container_imgmap201293016112'>
    <area shape="poly" onmouseover='myHover(this);' onmouseout='myLeave();' coords="2,0,604,-3,611,-3,611,166,346,165,345,130,-2,130,-2,124,1,128,1,126" href="" alt="imgmap201293016112-0" title="imgmap201293016112-0" class="imgmap201293016112-area" id="imgmap201293016112-area-0" />
    <area shape="rect" onmouseover='myHover(this);' onmouseout='myLeave();' coords="1,131,341,213" href="" alt="imgmap201293016112-1" title="imgmap201293016112-1" class="imgmap201293016112-area" id="imgmap201293016112-area-1" />
    <area shape="rect" onmouseover='myHover(this);' onmouseout='myLeave();' coords="346,166,614,241" href="" alt="imgmap201293016112-2" title="imgmap201293016112-2" class="imgmap201293016112-area" id="imgmap201293016112-area-2" />
    <area shape="poly" onmouseover='myHover(this);' onmouseout='myLeave();' coords="917,242,344,239,345,496,574,495,575,435,917,433" href="" alt="imgmap201293016112-3" title="imgmap201293016112-3" class="imgmap201293016112-area" id="imgmap201293016112-area-3" />
    <area shape="rect" onmouseover='myHover(this);' onmouseout='myLeave();' coords="1,416,341,494" href="" alt="imgmap201293016112-4" title="imgmap201293016112-4" class="imgmap201293016112-area" id="imgmap201293016112-area-4" />
    <area shape="rect" onmouseover='myHover(this);' onmouseout='myLeave();' coords="1,215,341,410" href="" alt="imgmap201293016112-5" title="imgmap201293016112-5" class="imgmap201293016112-area" id="imgmap201293016112-area-5" />
    <area shape="poly" onmouseover='myHover(this);' onmouseout='myLeave();' coords="916,533,916,436,578,436,576,495,806,496,807,535" href="" alt="imgmap201293016112-6" title="imgmap201293016112-6" class="imgmap201293016112-area" id="imgmap201293016112-area-6" />
    <area shape="rect" onmouseover='myHover(this);' onmouseout='myLeave();' coords="805,536,918,614" href="" alt="imgmap201293016112-7" title="imgmap201293016112-7" class="imgmap201293016112-area" id="imgmap201293016112-area-7" />
    <area shape="rect" onmouseover='myHover(this);' onmouseout='myLeave();' coords="461,494,803,616" href="" alt="imgmap201293016112-8" title="imgmap201293016112-8" class="imgmap201293016112-area" id="imgmap201293016112-area-8" />
    <area shape="rect" onmouseover='myHover(this);' onmouseout='myLeave();' coords="0,497,223,616" href="" alt="imgmap201293016112-9" title="imgmap201293016112-9" class="imgmap201293016112-area" id="imgmap201293016112-area-9" />
    <area shape="rect" onmouseover='myHover(this);' onmouseout='myLeave();' coords="230,494,456,614" href="" alt="imgmap201293016112-10" title="imgmap201293016112-10" class="imgmap201293016112-area" id="imgmap201293016112-area-10" />
    <area shape="rect" onmouseover='myHover(this);' onmouseout='myLeave();' coords="345,935,572,1082" href="" alt="imgmap201293016112-11" title="imgmap201293016112-11" class="imgmap201293016112-area" id="imgmap201293016112-area-11" />
    <area shape="rect" onmouseover='myHover(this);' onmouseout='myLeave();' coords="1,617,457,760" href="" alt="imgmap201293016112-12" title="imgmap201293016112-12" class="imgmap201293016112-area" id="imgmap201293016112-area-12" />
    <area shape="rect" onmouseover='myHover(this);' onmouseout='myLeave();' coords="345,760,577,847" href="" alt="imgmap201293016112-13" title="imgmap201293016112-13" class="imgmap201293016112-area" id="imgmap201293016112-area-13" />
    <area shape="rect" onmouseover='myHover(this);' onmouseout='myLeave();' coords="0,759,344,906" href="" alt="imgmap201293016112-14" title="imgmap201293016112-14" class="imgmap201293016112-area" id="imgmap201293016112-area-14" />
    <area shape="rect" onmouseover='myHover(this);' onmouseout='myLeave();' coords="346,850,571,935" href="" alt="imgmap201293016112-15" title="imgmap201293016112-15" class="imgmap201293016112-area" id="imgmap201293016112-area-15" />
    <area shape="rect" onmouseover='myHover(this);' onmouseout='myLeave();' coords="578,761,915,865" href="" alt="imgmap201293016112-16" title="imgmap201293016112-16" class="imgmap201293016112-area" id="imgmap201293016112-area-16" />
    <area shape="rect" onmouseover='myHover(this);' onmouseout='myLeave();' coords="0,1017,226,1085" href="" alt="imgmap201293016112-17" title="imgmap201293016112-17" class="imgmap201293016112-area" id="imgmap201293016112-area-17" />
    <area shape="rect" onmouseover='myHover(this);' onmouseout='myLeave();' coords="0,908,342,1017" href="" alt="imgmap201293016112-18" title="imgmap201293016112-18" class="imgmap201293016112-area" id="imgmap201293016112-area-18" />
    <area shape="rect" onmouseover='myHover(this);' onmouseout='myLeave();' coords="229,1010,342,1084" href="" alt="imgmap201293016112-19" title="imgmap201293016112-19" class="imgmap201293016112-area" id="imgmap201293016112-area-19" />
    <area shape="rect" onmouseover='myHover(this);' onmouseout='myLeave();' coords="0,1086,340,1206" href="" alt="imgmap201293016112-20" title="imgmap201293016112-20" class="imgmap201293016112-area" id="imgmap201293016112-area-20" />
    <area shape="rect" onmouseover='myHover(this);' onmouseout='myLeave();' coords="0,1209,224,1290" href="" alt="imgmap201293016112-21" title="imgmap201293016112-21" class="imgmap201293016112-area" id="imgmap201293016112-area-21" />
    <area shape="rect" onmouseover='myHover(this);' onmouseout='myLeave();' coords="0,1290,225,1432" href="" alt="imgmap201293016112-22" title="imgmap201293016112-22" class="imgmap201293016112-area" id="imgmap201293016112-area-22" />
    <area shape="rect" onmouseover='myHover(this);' onmouseout='myLeave();' coords="0,1432,340,1517" href="" alt="imgmap201293016112-23" title="imgmap201293016112-23" class="imgmap201293016112-area" id="imgmap201293016112-area-23" />
    <area shape="rect" onmouseover='myHover(this);' onmouseout='myLeave();' coords="346,1432,686,1517" href="" alt="imgmap201293016112-24" title="imgmap201293016112-24" class="imgmap201293016112-area" id="imgmap201293016112-area-24" />
    <area shape="rect" onmouseover='myHover(this);' onmouseout='myLeave();' coords="461,1266,686,1429" href="" alt="imgmap201293016112-25" title="imgmap201293016112-25" class="imgmap201293016112-area" id="imgmap201293016112-area-25" />
    <area shape="rect" onmouseover='myHover(this);' onmouseout='myLeave();' coords="230,1365,455,1430" href="" alt="imgmap201293016112-26" title="imgmap201293016112-26" class="imgmap201293016112-area" id="imgmap201293016112-area-26" />
    <area shape="rect" onmouseover='myHover(this);' onmouseout='myLeave();' coords="231,1291,457,1360" href="" alt="imgmap201293016112-27" title="imgmap201293016112-27" class="imgmap201293016112-area" id="imgmap201293016112-area-27" />
    <area shape="rect" onmouseover='myHover(this);' onmouseout='myLeave();' coords="230,1210,342,1289" href="" alt="imgmap201293016112-28" title="imgmap201293016112-28" class="imgmap201293016112-area" id="imgmap201293016112-area-28" />
    <area shape="rect" onmouseover='myHover(this);' onmouseout='myLeave();' coords="692,928,916,1016" href="" alt="imgmap201293016112-29" title="imgmap201293016112-29" class="imgmap201293016112-area" id="imgmap201293016112-area-29" />
    <area shape="rect" onmouseover='myHover(this);' onmouseout='myLeave();' coords="460,616,916,759" href="" alt="imgmap201293016112-30" title="imgmap201293016112-30" class="imgmap201293016112-area" id="imgmap201293016112-area-30" />
    <area shape="rect" onmouseover='myHover(this);' onmouseout='myLeave();' coords="693,1316,917,1518" href="" alt="imgmap201293016112-31" title="imgmap201293016112-31" class="imgmap201293016112-area" id="imgmap201293016112-area-31" />
    <area shape="rect" onmouseover='myHover(this);' onmouseout='myLeave();' coords="344,1150,572,1219" href="" alt="imgmap201293016112-32" title="imgmap201293016112-32" class="imgmap201293016112-area" id="imgmap201293016112-area-32" />
    <area shape="rect" onmouseover='myHover(this);' onmouseout='myLeave();' coords="693,1015,916,1171" href="" alt="imgmap201293016112-33" title="imgmap201293016112-33" class="imgmap201293016112-area" id="imgmap201293016112-area-33" />
    <area shape="rect" onmouseover='myHover(this);' onmouseout='myLeave();' coords="577,955,686,1032" href="" alt="imgmap201293016112-34" title="imgmap201293016112-34" class="imgmap201293016112-area" id="imgmap201293016112-area-34" />
    <area shape="rect" onmouseover='myHover(this);' onmouseout='myLeave();' coords="577,1036,687,1101" href="" alt="imgmap201293016112-35" title="imgmap201293016112-35" class="imgmap201293016112-area" id="imgmap201293016112-area-35" />
    <area shape="rect" onmouseover='myHover(this);' onmouseout='myLeave();' coords="576,1104,689,1172" href="" alt="imgmap201293016112-36" title="imgmap201293016112-36" class="imgmap201293016112-area" id="imgmap201293016112-area-36" />
    <area shape="rect" onmouseover='myHover(this);' onmouseout='myLeave();' coords="691,1232,918,1313" href="" alt="imgmap201293016112-37" title="imgmap201293016112-37" class="imgmap201293016112-area" id="imgmap201293016112-area-37" />
    <area shape="rect" onmouseover='myHover(this);' onmouseout='myLeave();' coords="341,1085,573,1151" href="" alt="imgmap201293016112-38" title="imgmap201293016112-38" class="imgmap201293016112-area" id="imgmap201293016112-area-38" />
    <area shape="poly" onmouseover='myHover(this);' onmouseout='myLeave();' coords="917,868,917,925,688,927,688,955,576,955,574,867,572,864" href="" alt="imgmap201293016112-39" title="imgmap201293016112-39" class="imgmap201293016112-area" id="imgmap201293016112-area-39" />
    <area shape="poly" onmouseover='myHover(this);' onmouseout='myLeave();' coords="919,1173,917,1231,688,1231,688,1266,574,1267,576,1175,576,1175" href="" alt="imgmap201293016112-40" title="imgmap201293016112-40" class="imgmap201293016112-area" id="imgmap201293016112-area-40" />
    <area shape="poly" onmouseover='myHover(this);' onmouseout='myLeave();' coords="572,1222,572,1265,459,1265,458,1289,339,1290,344,1225" href="" alt="imgmap201293016112-41" title="imgmap201293016112-41" class="imgmap201293016112-area" id="imgmap201293016112-area-41" />
</map>
</center>

</body>
</html>

Node.js: How to read a stream into a buffer?

You can easily do this using node-fetch if you are pulling from http(s) URIs.

From the readme:

fetch('https://assets-cdn.github.com/images/modules/logos_page/Octocat.png')
    .then(res => res.buffer())
    .then(buffer => console.log)

if...else within JSP or JSTL

If you want to do the following by using JSTL Tag Libe, please follow the following steps:

[Requirement] if a number is a grater than equal 40 and lower than 50 then display "Two digit number starting with 4" otherwise "Other numbers".

[Solutions]

1. Please Add the JSTL tag lib on the top of the page.`
     <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>`

2. Please Write the following code
`
<c:choose>
       <c:when test="${params.number >=40 && params.number <50}">
              <p> Two digit number starting with 4. </p>
       </c:when>
       <c:otherwise>
              <p> Other numbers. </p>
       </c:otherwise>
  </c:choose>`

How to set up tmux so that it starts up with specified windows opened?

Try bro, it is a project bootstrapper.

It provides easy apis to interact with tmux.

It looks something like this :

#!/bin/sh
# @ project_name/tasks/init.sh
structure project_name
  window editor
    run 'vim'
  window terminal
    run 'echo happy coding ...'
focus editor
connect project_name

To launch a project all one needs to do is run following command -

bro start <project_name>

Checkout the screencast below, it shows how to get started with bro and use its tmux api.

https://user-images.githubusercontent.com/8296449/50532502-2cf3e400-0b6e-11e9-84af-c5f77a04e5cc.gif

Height equal to dynamic width (CSS fluid layout)

[Update: Although I discovered this trick independently, I’ve since learned that Thierry Koblentz beat me to it. You can find his 2009 article on A List Apart. Credit where credit is due.]

I know this is an old question, but I encountered a similar problem that I did solve only with CSS. Here is my blog post that discusses the solution. Included in the post is a live example. Code is reposted below.

_x000D_
_x000D_
#container {
  display: inline-block;
  position: relative;
  width: 50%;
}

#dummy {
  margin-top: 75%;
  /* 4:3 aspect ratio */
}

#element {
  position: absolute;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  background-color: silver/* show me! */
}
_x000D_
<div id="container">
  <div id="dummy"></div>
  <div id="element">
    some text
  </div>
</div>
_x000D_
_x000D_
_x000D_

How to create and show common dialog (Error, Warning, Confirmation) in JavaFX 2.0?

Adapted from answer here: https://stackoverflow.com/a/7505528/921224

javafx.scene.control.Alert

For a an in depth description of how to use JavaFX dialogs see: JavaFX Dialogs (official) by code.makery. They are much more powerful and flexible than Swing dialogs and capable of far more than just popping up messages.

import javafx.scene.control.Alert
import javafx.scene.control.Alert.AlertType;
import javafx.application.Platform;

public class ClassNameHere
{

    public static void infoBox(String infoMessage, String titleBar)
    {
        /* By specifying a null headerMessage String, we cause the dialog to
           not have a header */
        infoBox(infoMessage, titleBar, null);
    }

    public static void infoBox(String infoMessage, String titleBar, String headerMessage)
    {
        Alert alert = new Alert(AlertType.INFORMATION);
        alert.setTitle(titleBar);
        alert.setHeaderText(headerMessage);
        alert.setContentText(infoMessage);
        alert.showAndWait();
    }
}

One thing to keep in mind is that JavaFX is a single threaded GUI toolkit, which means this method should be called directly from the JavaFX application thread. If you have another thread doing work, which needs a dialog then see these SO Q&As: JavaFX2: Can I pause a background Task / Service? and Platform.Runlater and Task Javafx.

To use this method call:

ClassNameHere.infoBox("YOUR INFORMATION HERE", "TITLE BAR MESSAGE");

or

ClassNameHere.infoBox("YOUR INFORMATION HERE", "TITLE BAR MESSAGE", "HEADER MESSAGE");

Making RGB color in Xcode

The values are determined by the bit of the image. 8 bit 0 to 255

16 bit...some ridiculous number..0 to 65,000 approx.

32 bit are 0 to 1

I use .004 with 32 bit images...this gives 1.02 as a result when multiplied by 255

How do I debug jquery AJAX calls?

Using pretty much any modern browser you need to learn the Network tab. See this SO post about How to debug AJAX calls.

How to use bootstrap-theme.css with bootstrap 3?

For an example of the css styles have a look at: http://getbootstrap.com/examples/theme/

If you want to see how the example looks without the bootstrap-theme.css file open up your browser developer tools and delete the link from the <head> of the example and then you can compare it.

I know this is an old question but posted it just in case anyone is looking for an example of how it looks like I was.

Update

bootstrap.css = main css framework (grids, basic styles, etc)

bootstrap-theme.css = extended styling (3D buttons, gradients etc). This file is optional and does not effect the functionality of bootstrap at all, it only enhances the appearance.

Update 2

With the release of v3.2.0 Bootstrap have added an option to view the theme css on the doc pages. If you go to one of the doc pages (css, components, javascript) you should see a "Preview theme" link at the bottom of the side nav which you can use to turn the theme css on and off.

Python : List of dict, if exists increment a dict value, if not append a new dict

That is a very strange way to organize things. If you stored in a dictionary, this is easy:

# This example should work in any version of Python.
# urls_d will contain URL keys, with counts as values, like: {'http://www.google.fr/' : 1 }
urls_d = {}
for url in list_of_urls:
    if not url in urls_d:
        urls_d[url] = 1
    else:
        urls_d[url] += 1

This code for updating a dictionary of counts is a common "pattern" in Python. It is so common that there is a special data structure, defaultdict, created just to make this even easier:

from collections import defaultdict  # available in Python 2.5 and newer

urls_d = defaultdict(int)
for url in list_of_urls:
    urls_d[url] += 1

If you access the defaultdict using a key, and the key is not already in the defaultdict, the key is automatically added with a default value. The defaultdict takes the callable you passed in, and calls it to get the default value. In this case, we passed in class int; when Python calls int() it returns a zero value. So, the first time you reference a URL, its count is initialized to zero, and then you add one to the count.

But a dictionary full of counts is also a common pattern, so Python provides a ready-to-use class: containers.Counter You just create a Counter instance by calling the class, passing in any iterable; it builds a dictionary where the keys are values from the iterable, and the values are counts of how many times the key appeared in the iterable. The above example then becomes:

from collections import Counter  # available in Python 2.7 and newer

urls_d = Counter(list_of_urls)

If you really need to do it the way you showed, the easiest and fastest way would be to use any one of these three examples, and then build the one you need.

from collections import defaultdict  # available in Python 2.5 and newer

urls_d = defaultdict(int)
for url in list_of_urls:
    urls_d[url] += 1

urls = [{"url": key, "nbr": value} for key, value in urls_d.items()]

If you are using Python 2.7 or newer you can do it in a one-liner:

from collections import Counter

urls = [{"url": key, "nbr": value} for key, value in Counter(list_of_urls).items()]

Maven 3 Archetype for Project With Spring, Spring MVC, Hibernate, JPA

With appFuse framework, you can create an Spring MVC archetype with jpa support, etc ...

Take a look at it's quickStart guide to see how to create an archetype based on this Framework.

Foundational frameworks in AppFuse:

  • Bootstrap and jQuery
  • Maven, Hibernate, Spring and Spring Security
  • Java 7, Annotations, JSP 2.1, Servlet 3.0
  • Web Frameworks: JSF, Struts 2, Spring MVC, Tapestry 5, Wicket
  • JPA Support

For example to create an appFuse light archetype :

mvn archetype:generate -B -DarchetypeGroupId=org.appfuse.archetypes 
-DarchetypeArtifactId=appfuse-light-struts-archetype -DarchetypeVersion=2.2.1 
-DgroupId=com.mycompany -DartifactId=myproject

Anaconda Installed but Cannot Launch Navigator

I had a similar issue today where only the prompt was available after installation. Finally solved this by un-installing my regular python installation and then install anaconda(anaconda 3 v5.2.0, with python 3.6).

Setting a checkbox as checked with Vue.js

I had similar requirements but I didn't want to use v-model to have the state in the parent component. Then I got this to work:

<input
  type="checkbox"
  :checked="checked"
  @input="checked = $event.target.checked"
/>

To pass down the value from the parent, I made a small change on this and it works.

<input
  type="checkbox"
  :checked="aPropFrom"
  @input="$emit('update:aPropFrom', $event.target.checked)"
/>

Android - get children inside a View?

I'm just going to provide this answer as an alternative @IHeartAndroid's recursive algorithm for discovering all child Views in a view hierarchy. Note that at the time of this writing, the recursive solution is flawed in that it will contains duplicates in its result.

For those who have trouble wrapping their head around recursion, here's a non-recursive alternative. You get bonus points for realizing this is also a breadth-first search alternative to the depth-first approach of the recursive solution.

private List<View> getAllChildrenBFS(View v) {
    List<View> visited = new ArrayList<View>();
    List<View> unvisited = new ArrayList<View>();
    unvisited.add(v);

    while (!unvisited.isEmpty()) {
        View child = unvisited.remove(0);
        visited.add(child);
        if (!(child instanceof ViewGroup)) continue;
        ViewGroup group = (ViewGroup) child;
        final int childCount = group.getChildCount();
        for (int i=0; i<childCount; i++) unvisited.add(group.getChildAt(i));
    }

    return visited;
}

A couple of quick tests (nothing formal) suggest this alternative is also faster, although that has most likely to do with the number of new ArrayList instances the other answer creates. Also, results may vary based on how vertical/horizontal the view hierarchy is.

Cross-posted from: Android | Get all children elements of a ViewGroup

Java 8, Streams to find the duplicate elements

A multiset is a structure maintaining the number of occurrences for each element. Using Guava implementation:

Set<Integer> duplicated =
        ImmutableMultiset.copyOf(numbers).entrySet().stream()
                .filter(entry -> entry.getCount() > 1)
                .map(Multiset.Entry::getElement)
                .collect(Collectors.toSet());

Expand div to max width when float:left is set

This might work:

    div{
    display:inline-block;
    width:100%;
    float:left;
    }

Getting Image from API in Angular 4/5+?

angular 5 :

 getImage(id: string): Observable<Blob> {
    return this.httpClient.get('http://myip/image/'+id, {responseType: "blob"});
}

Difference between h:button and h:commandButton

<h:button>

The <h:button> generates a HTML <input type="button">. The generated element uses JavaScript to navigate to the page given by the attribute outcome, using a HTTP GET request.

E.g.

<h:button value="GET button" outcome="otherpage" />

will generate

<input type="button" onclick="window.location.href='/contextpath/otherpage.xhtml'; return false;" value="GET button" />

Even though this ends up in a (bookmarkable) URL change in the browser address bar, this is not SEO-friendly. Searchbots won't follow the URL in the onclick. You'd better use a <h:outputLink> or <h:link> if SEO is important on the given URL. You could if necessary throw in some CSS on the generated HTML <a> element to make it to look like a button.

Do note that while you can put an EL expression referring a method in outcome attribute as below,

<h:button value="GET button" outcome="#{bean.getOutcome()}" />

it will not be invoked when you click the button. Instead, it is already invoked when the page containing the button is rendered for the sole purpose to obtain the navigation outcome to be embedded in the generated onclick code. If you ever attempted to use the action method syntax as in outcome="#{bean.action}", you would already be hinted by this mistake/misconception by facing a javax.el.ELException: Could not find property actionMethod in class com.example.Bean.

If you intend to invoke a method as result of a POST request, use <h:commandButton> instead, see below. Or if you intend to invoke a method as result of a GET request, head to Invoke JSF managed bean action on page load or if you also have GET request parameters via <f:param>, How do I process GET query string URL parameters in backing bean on page load?


<h:commandButton>

The <h:commandButton> generates a HTML <input type="submit"> button which submits by default the parent <h:form> using HTTP POST method and invokes the actions attached to action, actionListener and/or <f:ajax listener>, if any. The <h:form> is required.

E.g.

<h:form id="form">
    <h:commandButton id="button" value="POST button" action="otherpage" />
</h:form>

will generate

<form id="form" name="form" method="post" action="/contextpath/currentpage.xhtml" enctype="application/x-www-form-urlencoded">
    <input type="hidden" name="form" value="form" />
    <input type="submit" name="form:button" value="POST button" />
    <input type="hidden" name="javax.faces.ViewState" id="javax.faces.ViewState" value="...." autocomplete="off" />
</form>

Note that it thus submits to the current page (the form action URL will show up in the browser address bar). It will afterwards forward to the target page, without any change in the URL in the browser address bar. You could add ?faces-redirect=true parameter to the outcome value to trigger a redirect after POST (as per the Post-Redirect-Get pattern) so that the target URL becomes bookmarkable.

The <h:commandButton> is usually exclusively used to submit a POST form, not to perform page-to-page navigation. Normally, the action points to some business action, such as saving the form data in DB, which returns a String outcome.

<h:commandButton ... action="#{bean.save}" />

with

public String save() {
    // ...
    return "otherpage";
}

Returning null or void will bring you back to the same view. Returning an empty string also, but it would recreate any view scoped bean. These days, with modern JSF2 and <f:ajax>, more than often actions just return to the same view (thus, null or void) wherein the results are conditionally rendered by ajax.

public void save() {
    // ...
}

See also:

How do I get a list of all subdomains of a domain?

You can only do this if you are connecting to a DNS server for the domain -and- AXFR is enabled for your IP address. This is the mechanism that secondary systems use to load a zone from the primary. In the old days, this was not restricted, but due to security concerns, most primary name servers have a whitelist of: secondary name servers + a couple special systems.

If the nameserver you are using allows this then you can use dig or nslookup.

For example:

#nslookup

>ls domain.com

NOTE: because nslookup is being deprecated for dig and other newere tools, some versions of nslookup do not support "ls", most notably Mac OS X's bundled version.

Prolog "or" operator, query

you can 'invoke' alternative bindings on Y this way:

...registered(X, Y), (Y=ct101; Y=ct102; Y=ct103).

Note the parenthesis are required to keep the correct execution control flow. The ;/2 it's the general or operator. For your restricted use you could as well choice the more idiomatic

...registered(X, Y), member(Y, [ct101,ct102,ct103]).

that on backtracking binds Y to each member of the list.

edit I understood with a delay your last requirement. If you want that Y match all 3 values the or is inappropriate, use instead

...registered(X, ct101), registered(X, ct102), registered(X, ct103).

or the more compact

...findall(Y, registered(X, Y), L), sort(L, [ct101,ct102,ct103]).

findall/3 build the list in the very same order that registered/2 succeeds. Then I use sort to ensure the matching.

...setof(Y, registered(X, Y), [ct101,ct102,ct103]).

setof/3 also sorts the result list

Difference between checkout and export in SVN

Any chance the build process is looking into the subdirectories and including something it shouldn't? BTW, you can do a legal checkout, then remove the .svn and all it contains. That should give you the same as an export. Try compiling that, before and after removing the metadata, as it were.

SSL Proxy/Charles and Android trouble

Thanks for @bkurzius's answer and this update is for Charles 3.10+. (The reason is here)

  1. Open Charles
  2. Go to Proxy > SSL Proxy Settings...
  3. Check “Enable SSL Proxying”
  4. Select “Add location” and enter the host name and port (if needed)
  5. Click ok and make sure the option is checked
  6. Go to Help > SSL Proxying > Install Charles Root Certificate on a Mobile Device or Remote Browser..., and just follow the instruction. (use the Android's browser to download and install the certificate.)
  7. In “Name the certificate” enter whatever you want
  8. Click OK and you should get a message that the certificate was installed

Play audio as microphone input

Just as there are printer drivers that do not connect to a printer at all but rather write to a PDF file, analogously there are virtual audio drivers available that do not connect to a physical microphone at all but can pipe input from other sources such as files or other programs.

I hope I'm not breaking any rules by recommending free/donation software, but VB-Audio Virtual Cable should let you create a pair of virtual input and output audio devices. Then you could play an MP3 into the virtual output device and then set the virtual input device as your "microphone". In theory I think that should work.

If all else fails, you could always roll your own virtual audio driver. Microsoft provides some sample code but unfortunately it is not applicable to the older Windows XP audio model. There is probably sample code available for XP too.

Cannot find Dumpbin.exe

You probably need to open a command prompt with the PATH set up properly. Look for an icon in the start menu that says something like "Visual C++ 2005 Command Prompt". You should be able to run dumpbin (and all the other command line tools) from there.

A 'for' loop to iterate over an enum in Java

If you don't care about the order this should work:

Set<Direction> directions = EnumSet.allOf(Direction.class);
for(Direction direction : directions) {
    // do stuff
}

Has been compiled by a more recent version of the Java Runtime (class file version 57.0)

I was facing same problem when I installed JRE by Oracle and solved this problem after my research.

I moved the environment path C:\Program Files (x86)\Common Files\Oracle\Java\javapath below H:\Program Files\Java\jdk-13.0.1\bin

Like this:

Path

H:\Program Files\Java\jdk-13.0.1\bin
C:\Program Files (x86)\Common Files\Oracle\Java\javapath

OR

Path

%JAVA_HOME%
%JRE_HOME%

How can I use regex to get all the characters after a specific character, e.g. comma (",")

This should work

preg_match_all('@.*\,(.*)@', '{{your data}}', $arr, PREG_PATTERN_ORDER);

You can test it here: http://www.spaweditor.com/scripts/regex/index.php

RegEx: .*\,(.*)

Same RegEx test here for JavaScript: http://www.regular-expressions.info/javascriptexample.html

Check an integer value is Null in c#

Nullable<T> (or ?) exposes a HasValue flag to denote if a value is set or the item is null.

Also, nullable types support ==:

if (Age == null)

The ?? is the null coalescing operator and doesn't result in a boolean expression, but a value returned:

int i = Age ?? 0;

So for your example:

if (age == null || age == 0)

Or:

if (age.GetValueOrDefault(0) == 0)

Or:

if ((age ?? 0) == 0)

Or ternary:

int i = age.HasValue ? age.Value : 0;

Extracting substrings in Go

WARNING: operating on strings alone will only work with ASCII and will count wrong when input is a non-ASCII UTF-8 encoded character, and will probably even corrupt characters since it cuts multibyte chars mid-sequence.

Here's a UTF-8-aware version:

// NOTE: this isn't multi-Unicode-codepoint aware, like specifying skintone or
//       gender of an emoji: https://unicode.org/emoji/charts/full-emoji-modifiers.html
func substr(input string, start int, length int) string {
    asRunes := []rune(input)
    
    if start >= len(asRunes) {
        return ""
    }
    
    if start+length > len(asRunes) {
        length = len(asRunes) - start
    }
    
    return string(asRunes[start : start+length])
}

How do I add a Maven dependency in Eclipse?

Open the pom.xml file.

under the project tag add <dependencies> as another tag, and google for the Maven dependencies. I used this to search.

So after getting the dependency create another tag dependency inside <dependencies> tag.

So ultimately it will look something like this.

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>doc-examples</groupId>
  <artifactId>lambda-java-example</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <name>lambda-java-example</name>
  <dependencies>
      <!-- https://mvnrepository.com/artifact/com.amazonaws/aws-lambda-java-core -->
    <dependency>
        <groupId>com.amazonaws</groupId>
        <artifactId>aws-lambda-java-core</artifactId>
        <version>1.0.0</version>
    </dependency>
  </dependencies>
</project>

Hope it helps.

How to make a div center align in HTML

_x000D_
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
  <head>_x000D_
    <title>Center</title>_x000D_
  </head>_x000D_
  <body>_x000D_
_x000D_
    <div style="text-align: center;">_x000D_
      <div style="width: 500px; margin: 0 auto; background: #000; color: #fff;">This DIV is centered</div>_x000D_
    </div>_x000D_
_x000D_
  </body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

Tested and worked in IE, Firefox, Chrome, Safari and Opera. I did not test IE6. The outer text-align is needed for IE. Other browsers (and IE9?) will work when you give the DIV margin (left and right) value of auto. Margin "0 auto" is a shorthand for margin "0 auto 0 auto" (top right bottom left).

Note: the text is also centered inside the inner DIV, if you want it to remain on the left side just specify text-align: left; for the inner DIV.

Edit: IE 6, 7, 8 and 9 running on the Standards Mode will work with margins set to auto.

Open window in JavaScript with HTML inserted

Here's how to do it with an HTML Blob, so that you have control over the entire HTML document:

https://codepen.io/trusktr/pen/mdeQbKG?editors=0010

This is the code, but StackOverflow blocks the window from being opened (see the codepen example instead):

_x000D_
_x000D_
const winHtml = `<!DOCTYPE html>_x000D_
    <html>_x000D_
        <head>_x000D_
            <title>Window with Blob</title>_x000D_
        </head>_x000D_
        <body>_x000D_
            <h1>Hello from the new window!</h1>_x000D_
        </body>_x000D_
    </html>`;_x000D_
_x000D_
const winUrl = URL.createObjectURL(_x000D_
    new Blob([winHtml], { type: "text/html" })_x000D_
);_x000D_
_x000D_
const win = window.open(_x000D_
    winUrl,_x000D_
    "win",_x000D_
    `width=800,height=400,screenX=200,screenY=200`_x000D_
);
_x000D_
_x000D_
_x000D_

How to print SQL statement in codeigniter model

I try to @Chumillas's answer and @chhameed's answer, but it not work,because the sql is wrong.So I found new approach,like this:

  • Insert echo $sql; flush(); exit; into before return $sql; _compile_select function of DB_active_rec.php

Factorial using Recursion in Java

import java.util.Scanner;

public class Factorial {
    public static void main(String[] args) {
        Scanner keyboard = new Scanner(System.in);
        int n; 
        System.out.println("Enter number: ");
        n = keyboard.nextInt();
        int number = calculatefactorial(n);
        System.out.println("Factorial: " +number);
    }
    public static int calculatefactorial(int n){
        int factorialnumbers=1;
        while(n>0){
         factorialnumbers=(int)(factorialnumbers*n--);   
        }
        return factorialnumbers;
    }
}

Open URL in same window and in same tab

You can have it go to the same page without specifying the url:

window.open('?','_self');

Why is there still a row limit in Microsoft Excel?

Probably because of optimizations. Excel 2007 can have a maximum of 16 384 columns and 1 048 576 rows. Strange numbers?

14 bits = 16 384, 20 bits = 1 048 576

14 + 20 = 34 bits = more than one 32 bit register can hold.

But they also need to store the format of the cell (text, number etc) and formatting (colors, borders etc). Assuming they use two 32-bit words (64 bit) they use 34 bits for the cell number and have 30 bits for other things.

Why is that important? In memory they don't need to allocate all the memory needed for the whole spreadsheet but only the memory necessary for your data, and every data is tagged with in what cell it is supposed to be in.

Update 2016:

Found a link to Microsoft's specification for Excel 2013 & 2016

  • Open workbooks: Limited by available memory and system resources
  • Worksheet size: 1,048,576 rows (20 bits) by 16,384 columns (14 bits)
  • Column width: 255 characters (8 bits)
  • Row height: 409 points
  • Page breaks: 1,026 horizontal and vertical (unexpected number, probably wrong, 10 bits is 1024)
  • Total number of characters that a cell can contain: 32,767 characters (signed 16 bits)
  • Characters in a header or footer: 255 (8 bits)
  • Sheets in a workbook: Limited by available memory (default is 1 sheet)
  • Colors in a workbook: 16 million colors (32 bit with full access to 24 bit color spectrum)
  • Named views in a workbook: Limited by available memory
  • Unique cell formats/cell styles: 64,000 (16 bits = 65536)
  • Fill styles: 256 (8 bits)
  • Line weight and styles: 256 (8 bits)
  • Unique font types: 1,024 (10 bits) global fonts available for use; 512 per workbook
  • Number formats in a workbook: Between 200 and 250, depending on the language version of Excel that you have installed
  • Names in a workbook: Limited by available memory
  • Windows in a workbook: Limited by available memory
  • Hyperlinks in a worksheet: 66,530 hyperlinks (unexpected number, probably wrong. 16 bits = 65536)
  • Panes in a window: 4
  • Linked sheets: Limited by available memory
  • Scenarios: Limited by available memory; a summary report shows only the first 251 scenarios
  • Changing cells in a scenario: 32
  • Adjustable cells in Solver: 200
  • Custom functions: Limited by available memory
  • Zoom range: 10 percent to 400 percent
  • Reports: Limited by available memory
  • Sort references: 64 in a single sort; unlimited when using sequential sorts
  • Undo levels: 100
  • Fields in a data form: 32
  • Workbook parameters: 255 parameters per workbook
  • Items displayed in filter drop-down lists: 10,000

Javascript Click on Element by Class

I'd suggest:

document.querySelector('.rateRecipe.btns-one-small').click();

The above code assumes that the given element has both of those classes; otherwise, if the space is meant to imply an ancestor-descendant relationship:

document.querySelector('.rateRecipe .btns-one-small').click();

The method getElementsByClassName() takes a single class-name (rather than document.querySelector()/document.querySelectorAll(), which take a CSS selector), and you passed two (presumably class-names) to the method.

References:

How can I use delay() with show() and hide() in Jquery

The easiest way is to make a "fake show" by using jquery.

element.delay(1000).fadeIn(0); // This will work

Find all files with name containing string

If the string is at the beginning of the name, you can do this

$ compgen -f .bash
.bashrc
.bash_profile
.bash_prompt

How to get file_get_contents() to work with HTTPS?

Just add two lines in your php.ini file.

extension=php_openssl.dll

allow_url_include = On

its working for me.

Check element exists in array

In Python you might be in for some surprises if you ask for forgiveness in this case.

try-except is not the right paradigm here.

If you accidentally get negative indices your in for a surprise.

Better solution is to provide the test function yourself:

def index_in_array(M, index):
    return index[0] >= 0 and index[1] >= 0 and index[0]< M.shape[0] and index[1] < M.shape[1]

Transfer data from one database to another database

These solutions are working in case when target database is blank. In case when both databases already have some data you need something more complicated http://byalexblog.net/merge-sql-databases

Call function with setInterval in jQuery?

First of all: Yes you can mix jQuery with common JS :)

Best way to build up an intervall call of a function is to use setTimeout methode:

For example, if you have a function called test() and want to repeat it all 5 seconds, you could build it up like this:

function test(){
    console.log('test called');
    setTimeout(test, 5000);
}

Finally you have to trigger the function once:

$(document).ready(function(){
    test();
});

This document ready function is called automatically, after all html is loaded.

warning about too many open figures

This is also useful if you only want to temporarily suppress the warning:

import matplotlib.pyplot as plt
       
with plt.rc_context(rc={'figure.max_open_warning': 0}):
    lots_of_plots()

jQuery UI Sortable, then write order into a database

Thought this might help as well. A) it was designed to keep payload to its minimum while sending back to server, after each sort. (instead of sending all elements each time or iterating through many elements that server might chuck out) B) I needed to send back custom id without compromising the id / name of the element. This code will get the list from asp.net server and then upon sorting only 2 values will be sent back: The db id of sorted element and db id of the element next to which it was dropped. Based on those 2 values, server can easily identify the new postion.

<div id="planlist" style="width:1000px">
    <ul style="width:1000px">
       <li plid="listId1"><a href="#pl-1">List 1</a></li>
       <li plid="listId2"><a href="#pl-2">List 1</a></li>
       <li plid="listId3"><a href="#pl-3">List 1</a></li>
       <li plid="listId4"><a href="#pl-4">List 1</a></li>
    </ul>
    <div id="pl-1"></div>
    <div id="pl-2"></div>
    <div id="pl-3"></div>
    <div id="pl-4"></div>
</div>
<script type="text/javascript" language="javascript">
    $(function () {
        var tabs = $("#planlist").tabs();
        tabs.find(".ui-tabs-nav").sortable({
            axis: "x",
            stop: function () {
                tabs.tabs("refresh");
            },
            update: function (event, ui) {
                //db id of the item sorted
                alert(ui.item.attr('plid'));
                //db id of the item next to which the dragged item was dropped
                alert(ui.item.prev().attr('plid'));

                //make ajax call
            }
        });
    });
</script>

install / uninstall APKs programmatically (PackageManager vs Intents)

On a rooted device, you might use:

String pkg = context.getPackageName();
String shellCmd = "rm -r /data/app/" + pkg + "*.apk\n"
                + "rm -r /data/data/" + pkg + "\n"
                // TODO remove data on the sd card
                + "sync\n"
                + "reboot\n";
Util.sudo(shellCmd);

Util.sudo() is defined here.

Wrapping long text without white space inside of a div

white-space: pre-wrap

is what worked for me for <span> and <div>.

Passing html values into javascript functions

Try: if(parseInt(order)>0){....

What exactly is LLVM?

LLVM is basically a library used to build compilers and/or language oriented software. The basic gist is although you have gcc which is probably the most common suite of compilers, it is not built to be re-usable ie. it is difficult to take components from gcc and use it to build your own application. LLVM addresses this issue well by building a set of "modular and reusable compiler and toolchain technologies" which anyone could use to build compilers and language oriented software.

What's the difference between Git Revert, Checkout and Reset?

Let's say you had commits:

C
B
A

git revert B, will create a commit that undoes changes in B.

git revert A, will create a commit that undoes changes in A, but will not touch changes in B

Note that if changes in B are dependent on changes in A, the revert of A is not possible.

git reset --soft A, will change the commit history and repository; staging and working directory will still be at state of C.

git reset --mixed A, will change the commit history, repository, and staging; working directory will still be at state of C.

git reset --hard A, will change the commit history, repository, staging and working directory; you will go back to the state of A completely.

How do I stretch a background image to cover the entire HTML element?

To expand on @PhiLho answer, you can center a very large image (or any size image) on a page with:

{ 
background-image: url(_images/home.jpg);
background-repeat:no-repeat;
background-position:center; 
}

Or you could use a smaller image with a background color that matches the background of the image (if it is a solid color). This may or may not suit your purposes.

{ 
background-color: green;
background-image: url(_images/home.jpg);
background-repeat:no-repeat;
background-position:center; 
}

How to draw a rectangle around a region of interest in python

please don't try with the old cv module, use cv2:

import cv2

cv2.rectangle(img, (x1, y1), (x2, y2), (255,0,0), 2)


x1,y1 ------
|          |
|          |
|          |
--------x2,y2

[edit] to append the follow-up questions below:

cv2.imwrite("my.png",img)

cv2.imshow("lalala", img)
k = cv2.waitKey(0) # 0==wait forever

start/play embedded (iframe) youtube-video on click of an image

This should work perfect just copy this div code

<div onclick="thevid=document.getElementById('thevideo'); thevid.style.display='block'; this.style.display='none'">
<img style="cursor: pointer;" alt="" src="http://oi59.tinypic.com/33trpyo.jpg" />
</div>
<div id="thevideo" style="display: none;">
<embed width="631" height="466" type="application/x-shockwave-flash" src="https://www.youtube.com/v/26EpwxkU5js?version=3&amp;hl=en_US&amp;autoplay=1" allowFullScreen="true" allowscriptaccess="always" allowfullscreen="true" />
</div>

ReferenceError: describe is not defined NodeJs

To run tests with node/npm without installing Mocha globally, you can do this:

• Install Mocha locally to your project (npm install mocha --save-dev)

• Optionally install an assertion library (npm install chai --save-dev)

• In your package.json, add a section for scripts and target the mocha binary

"scripts": {
  "test": "node ./node_modules/mocha/bin/mocha"
}

• Put your spec files in a directory named /test in your root directory

• In your spec files, import the assertion library

var expect = require('chai').expect;

• You don't need to import mocha, run mocha.setup, or call mocha.run()

• Then run the script from your project root:

npm test

Android Fragment handle back button press

When you are transitioning between Fragments, call addToBackStack() as part of your FragmentTransaction:

FragmentTransaction tx = fragmentManager.beginTransation();
tx.replace( R.id.fragment, new MyFragment() ).addToBackStack( "tag" ).commit();

If you require more detailed control (i.e. when some Fragments are visible, you want to suppress the back key) you can set an OnKeyListener on the parent view of your fragment:

//You need to add the following line for this solution to work; thanks skayred
fragment.getView().setFocusableInTouchMode(true);
fragment.getView().requestFocus();
fragment.getView().setOnKeyListener( new OnKeyListener()
{
    @Override
    public boolean onKey( View v, int keyCode, KeyEvent event )
    {
        if( keyCode == KeyEvent.KEYCODE_BACK )
        {
            return true;
        }
        return false;
    }
} );

T-SQL string replace in Update

update YourTable
    set YourColumn = replace(YourColumn, '@domain2', '@domain1')
    where charindex('@domain2', YourColumn) <> 0

Map.Entry: How to use it?

Map.Entry interface helps us iterating a Map class

Check this simple example:

public class MapDemo {
    public static void main(String[] args) {
     Map<Integer,String> map=new HashMap();
     map.put(1, "Kamran");
        map.put(2, "Ali");
        map.put(3, "From");
        map.put(4, "Dir");
        map.put(5, "Lower");
        for(Map.Entry m:map.entrySet()){
        System.out.println(m.getKey()+"  "+m.getValue());
        }
    }
}

@RequestParam vs @PathVariable

@PathVariable - must be placed in the endpoint uri and access the query parameter value from the request
@RequestParam - must be passed as method parameter (optional based on the required property)
 http://localhost:8080/employee/call/7865467

 @RequestMapping(value=“/call/{callId}", method = RequestMethod.GET)
 public List<Calls> getAgentCallById(
            @PathVariable(“callId") int callId,
            @RequestParam(value = “status", required = false) String callStatus) {

    }

http://localhost:8080/app/call/7865467?status=Cancelled

@RequestMapping(value=“/call/{callId}", method = RequestMethod.GET)
public List<Calls> getAgentCallById(
            @PathVariable(“callId") int callId,
            @RequestParam(value = “status", required = true) String callStatus) {

}

Spring security CORS Filter

According the CORS filter documentation:

"Spring MVC provides fine-grained support for CORS configuration through annotations on controllers. However when used with Spring Security it is advisable to rely on the built-in CorsFilter that must be ordered ahead of Spring Security’s chain of filters"

Something like this will allow GET access to the /ajaxUri:

@Component
@Order(Ordered.HIGHEST_PRECEDENCE)
public class AjaxCorsFilter extends CorsFilter {
    public AjaxCorsFilter() {
        super(configurationSource());
    }

    private static UrlBasedCorsConfigurationSource configurationSource() {
        CorsConfiguration config = new CorsConfiguration();

        // origins
        config.addAllowedOrigin("*");

        // when using ajax: withCredentials: true, we require exact origin match
        config.setAllowCredentials(true);

        // headers
        config.addAllowedHeader("x-requested-with");

        // methods
        config.addAllowedMethod(HttpMethod.OPTIONS);
        config.addAllowedMethod(HttpMethod.GET);

        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/startAsyncAuthorize", config);
        source.registerCorsConfiguration("/ajaxUri", config);
        return source;
    }
}

Of course, your SpringSecurity configuration must allow access to the URI with the listed methods. See @Hendy Irawan answer.

Does Python's time.time() return the local or UTC timestamp?

The time.time() function returns the number of seconds since the epoch, as seconds. Note that the "epoch" is defined as the start of January 1st, 1970 in UTC. So the epoch is defined in terms of UTC and establishes a global moment in time. No matter where you are "seconds past epoch" (time.time()) returns the same value at the same moment.

Here is some sample output I ran on my computer, converting it to a string as well.

Python 2.7.3 (default, Apr 24 2012, 00:00:54) 
[GCC 4.7.0 20120414 (prerelease)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import time
>>> ts = time.time()
>>> print ts
1355563265.81
>>> import datetime
>>> st = datetime.datetime.fromtimestamp(ts).strftime('%Y-%m-%d %H:%M:%S')
>>> print st
2012-12-15 01:21:05
>>>

The ts variable is the time returned in seconds. I then converted it to a string using the datetime library making it a string that is human readable.

Android Design Support Library expandable Floating Action Button(FAB) menu

Got a better approach to implement the animating FAB menu without using any library or to write huge xml code for animations. hope this will help in future for someone who needs a simple way to implement this.

Just using animate().translationY() function, you can animate any view up or down just I did in my below code, check complete code in github. In case you are looking for the same code in kotlin, you can checkout the kotlin code repo Animating FAB Menu.

first define all your FAB at same place so they overlap each other, remember on top the FAB should be that you want to click and to show other. eg:

    <android.support.design.widget.FloatingActionButton
    android:id="@+id/fab3"
    android:layout_width="@dimen/standard_45"
    android:layout_height="@dimen/standard_45"
    android:layout_gravity="bottom|end"
    android:layout_margin="@dimen/standard_21"
    app:srcCompat="@android:drawable/ic_btn_speak_now" />

<android.support.design.widget.FloatingActionButton
    android:id="@+id/fab2"
    android:layout_width="@dimen/standard_45"
    android:layout_height="@dimen/standard_45"
    android:layout_gravity="bottom|end"
    android:layout_margin="@dimen/standard_21"
    app:srcCompat="@android:drawable/ic_menu_camera" />

<android.support.design.widget.FloatingActionButton
    android:id="@+id/fab1"
    android:layout_width="@dimen/standard_45"
    android:layout_height="@dimen/standard_45"
    android:layout_gravity="bottom|end"
    android:layout_margin="@dimen/standard_21"
    app:srcCompat="@android:drawable/ic_dialog_map" />

<android.support.design.widget.FloatingActionButton
    android:id="@+id/fab"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="bottom|end"
    android:layout_margin="@dimen/fab_margin"
    app:srcCompat="@android:drawable/ic_dialog_email" />

Now in your java class just define all your FAB and perform the click like shown below:

 FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
    fab1 = (FloatingActionButton) findViewById(R.id.fab1);
    fab2 = (FloatingActionButton) findViewById(R.id.fab2);
    fab3 = (FloatingActionButton) findViewById(R.id.fab3);
    fab.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            if(!isFABOpen){
                showFABMenu();
            }else{
                closeFABMenu();
            }
        }
    });

Use the animation().translationY() to animate your FAB,I prefer you to use the attribute of this method in DP since only using an int will effect the display compatibility with higher resolution or lower resolution. as shown below:

 private void showFABMenu(){
    isFABOpen=true;
    fab1.animate().translationY(-getResources().getDimension(R.dimen.standard_55));
    fab2.animate().translationY(-getResources().getDimension(R.dimen.standard_105));
    fab3.animate().translationY(-getResources().getDimension(R.dimen.standard_155));
}

private void closeFABMenu(){
    isFABOpen=false;
    fab1.animate().translationY(0);
    fab2.animate().translationY(0);
    fab3.animate().translationY(0);
}

Now define the above mentioned dimension inside res->values->dimens.xml as shown below:

    <dimen name="standard_55">55dp</dimen>
<dimen name="standard_105">105dp</dimen>
<dimen name="standard_155">155dp</dimen>

That's all hope this solution will help the people in future, who are searching for simple solution.

EDITED

If you want to add label over the FAB then simply take a horizontal LinearLayout and put the FAB with textview as label, and animate the layouts if find any issue doing this, you can check my sample code in github, I have handelled all backward compatibility issues in that sample code. check my sample code for FABMenu in Github

to close the FAB on Backpress, override onBackPress() as showen below:

    @Override
public void onBackPressed() {
    if(!isFABOpen){
        this.super.onBackPressed();
    }else{
        closeFABMenu();
    }
}

The Screenshot have the title as well with the FAB,because I take it from my sample app present ingithub

enter image description here

Is null check needed before calling instanceof?

Using a null reference as the first operand to instanceof returns false.

How to select into a variable in PL/SQL when the result might be null?

From all the answers above, Björn's answer seems to be the most elegant and short. I personally used this approach many times. MAX or MIN function will do the job equally well. Complete PL/SQL follows, just the where clause should be specified.

declare v_column my_table.column%TYPE;
begin
    select MIN(column) into v_column from my_table where ...;
    DBMS_OUTPUT.PUT_LINE('v_column=' || v_column);
end;

HTML form with multiple "actions"

the best way (for me) to make it it's the next infrastructure:

<form method="POST">
<input type="submit" formaction="default_url_when_press_enter" style="visibility: hidden; display: none;">
<!-- all your inputs -->
<input><input><input>
<!-- all your inputs -->
<button formaction="action1">Action1</button>
<button formaction="action2">Action2</button>
<input type="submit" value="Default Action">
</form>

with this structure you will send with enter a direction and the infinite possibilities for the rest of buttons.

Better way to right align text in HTML Table

If it's always the third column, you can use this (assuming table class of "products"). It's kinda hacky though, and not robust if you add a new column.

table.products td+td+td {
  text-align: right;
}
table.products td,
table.products td+td+td+td {
  text-align: left;
}

But honestly, the best idea is to use a class on each cell. You can use the col element to set the width, border, background or visibility of a column, but not any other properties. Reasons discussed here.

git add, commit and push commands in one?

As mentioned in this answer, you can create a git alias and assign a set of commands for it. In this case, it would be:

git config --global alias.add-com-push '!git add . && git commit -a -m "commit" && git push'

and use it with

git add-com-push

GlobalConfiguration.Configure() not present after Web API 2 and .NET 4.5.1 migration

GlobalConfiguration class is part of Microsoft.AspNet.WebApi.WebHost nuget package...Have you upgraded this package to Web API 2?

Simple PHP calculator

$first = doubleval($_POST['first']);
$second = doubleval($_POST['second']);

if($_POST['group1'] == 'add') {
    echo "$first + $second = ".($first + $second);
}

// etc

Range with step of type float

Probably because you can't have part of an iterable. Also, floats are imprecise.

showDialog deprecated. What's the alternative?

From http://developer.android.com/reference/android/app/Activity.html

public final void showDialog (int id) Added in API level 1

This method was deprecated in API level 13. Use the new DialogFragment class with FragmentManager instead; this is also available on older platforms through the Android compatibility package.

Simple version of showDialog(int, Bundle) that does not take any arguments. Simply calls showDialog(int, Bundle) with null arguments.

Why

  • A fragment that displays a dialog window, floating on top of its activity's window. This fragment contains a Dialog object, which it displays as appropriate based on the fragment's state. Control of the dialog (deciding when to show, hide, dismiss it) should be done through the API here, not with direct calls on the dialog.
  • Here is a nice discussion Android DialogFragment vs Dialog
  • Another nice discussion DialogFragment advantages over AlertDialog

How to solve?

More

git commit error: pathspec 'commit' did not match any file(s) known to git

Please try adding the double quotes git commit -m "initial commit". This will solve your problem.

how to convert from int to char*?

Converting our integer value to std::string so we can know how long (how long number of digits).

Then we creating char array length of string letter size +1, so we can copy our value to string then char array.

#include <string>

char* intToStr(int data) {
    std::string strData = std::to_string(data);

    char* temp = new char[strData.length() + 1];
    strcpy(temp, strData.c_str());

   return temp;
}

Modify SVG fill color when being served as Background-Image

In some (very specific) situations this might be achieved by using a filter. For example, you can change a blue SVG image to purple by rotating the hue 45 degrees using filter: hue-rotate(45deg);. Browser support is minimal but it's still an interesting technique.

Demo

Creating an empty bitmap and drawing though canvas in Android

Do not use Bitmap.Config.ARGB_8888

Instead use int w = WIDTH_PX, h = HEIGHT_PX;

Bitmap.Config conf = Bitmap.Config.ARGB_4444; // see other conf types
Bitmap bmp = Bitmap.createBitmap(w, h, conf); // this creates a MUTABLE bitmap
Canvas canvas = new Canvas(bmp);

// ready to draw on that bitmap through that canvas

ARGB_8888 can land you in OutOfMemory issues when dealing with more bitmaps or large bitmaps. Or better yet, try avoiding usage of ARGB option itself.

Loading .sql files from within PHP

phpBB uses a few functions to parse their files. They are rather well-commented (what an exception!) so you can easily know what they do (I got this solution from http://www.frihost.com/forums/vt-8194.html). here is the solution an I've used it a lot:

<php
ini_set('memory_limit', '5120M');
set_time_limit ( 0 );
/***************************************************************************
*                             sql_parse.php
*                              -------------------
*     begin                : Thu May 31, 2001
*     copyright            : (C) 2001 The phpBB Group
*     email                : [email protected]
*
*     $Id: sql_parse.php,v 1.8 2002/03/18 23:53:12 psotfx Exp $
*
****************************************************************************/

/***************************************************************************
 *
 *   This program is free software; you can redistribute it and/or modify
 *   it under the terms of the GNU General Public License as published by
 *   the Free Software Foundation; either version 2 of the License, or
 *   (at your option) any later version.
 *
 ***************************************************************************/

/***************************************************************************
*
*   These functions are mainly for use in the db_utilities under the admin
*   however in order to make these functions available elsewhere, specifically
*   in the installation phase of phpBB I have seperated out a couple of
*   functions into this file.  JLH
*
\***************************************************************************/

//
// remove_comments will strip the sql comment lines out of an uploaded sql file
// specifically for mssql and postgres type files in the install....
//
function remove_comments(&$output)
{
   $lines = explode("\n", $output);
   $output = "";

   // try to keep mem. use down
   $linecount = count($lines);

   $in_comment = false;
   for($i = 0; $i &lt; $linecount; $i++)
   {
      if( preg_match("/^\/\*/", preg_quote($lines[$i])) )
      {
         $in_comment = true;
      }

      if( !$in_comment )
      {
         $output .= $lines[$i] . "\n";
      }

      if( preg_match("/\*\/$/", preg_quote($lines[$i])) )
      {
         $in_comment = false;
      }
   }

   unset($lines);
   return $output;
}

//
// remove_remarks will strip the sql comment lines out of an uploaded sql file
//
function remove_remarks($sql)
{
   $lines = explode("\n", $sql);

   // try to keep mem. use down
   $sql = "";

   $linecount = count($lines);
   $output = "";

   for ($i = 0; $i &lt; $linecount; $i++)
   {
      if (($i != ($linecount - 1)) || (strlen($lines[$i]) > 0))
      {
         if (isset($lines[$i][0]) && $lines[$i][0] != "#")
         {
            $output .= $lines[$i] . "\n";
         }
         else
         {
            $output .= "\n";
         }
         // Trading a bit of speed for lower mem. use here.
         $lines[$i] = "";
      }
   }

   return $output;

}

//
// split_sql_file will split an uploaded sql file into single sql statements.
// Note: expects trim() to have already been run on $sql.
//
function split_sql_file($sql, $delimiter)
{
   // Split up our string into "possible" SQL statements.
   $tokens = explode($delimiter, $sql);

   // try to save mem.
   $sql = "";
   $output = array();

   // we don't actually care about the matches preg gives us.
   $matches = array();

   // this is faster than calling count($oktens) every time thru the loop.
   $token_count = count($tokens);
   for ($i = 0; $i &lt; $token_count; $i++)
   {
      // Don't wanna add an empty string as the last thing in the array.
      if (($i != ($token_count - 1)) || (strlen($tokens[$i] > 0)))
      {
         // This is the total number of single quotes in the token.
         $total_quotes = preg_match_all("/'/", $tokens[$i], $matches);
         // Counts single quotes that are preceded by an odd number of backslashes,
         // which means they're escaped quotes.
         $escaped_quotes = preg_match_all("/(?&lt;!\\\\)(\\\\\\\\)*\\\\'/", $tokens[$i], $matches);

         $unescaped_quotes = $total_quotes - $escaped_quotes;

         // If the number of unescaped quotes is even, then the delimiter did NOT occur inside a string literal.
         if (($unescaped_quotes % 2) == 0)
         {
            // It's a complete sql statement.
            $output[] = $tokens[$i];
            // save memory.
            $tokens[$i] = "";
         }
         else
         {
            // incomplete sql statement. keep adding tokens until we have a complete one.
            // $temp will hold what we have so far.
            $temp = $tokens[$i] . $delimiter;
            // save memory..
            $tokens[$i] = "";

            // Do we have a complete statement yet?
            $complete_stmt = false;

            for ($j = $i + 1; (!$complete_stmt && ($j &lt; $token_count)); $j++)
            {
               // This is the total number of single quotes in the token.
               $total_quotes = preg_match_all("/'/", $tokens[$j], $matches);
               // Counts single quotes that are preceded by an odd number of backslashes,
               // which means they're escaped quotes.
               $escaped_quotes = preg_match_all("/(?&lt;!\\\\)(\\\\\\\\)*\\\\'/", $tokens[$j], $matches);

               $unescaped_quotes = $total_quotes - $escaped_quotes;

               if (($unescaped_quotes % 2) == 1)
               {
                  // odd number of unescaped quotes. In combination with the previous incomplete
                  // statement(s), we now have a complete statement. (2 odds always make an even)
                  $output[] = $temp . $tokens[$j];

                  // save memory.
                  $tokens[$j] = "";
                  $temp = "";

                  // exit the loop.
                  $complete_stmt = true;
                  // make sure the outer loop continues at the right point.
                  $i = $j;
               }
               else
               {
                  // even number of unescaped quotes. We still don't have a complete statement.
                  // (1 odd and 1 even always make an odd)
                  $temp .= $tokens[$j] . $delimiter;
                  // save memory.
                  $tokens[$j] = "";
               }

            } // for..
         } // else
      }
   }

   return $output;
}

$dbms_schema = 'yourfile.sql';

$sql_query = @fread(@fopen($dbms_schema, 'r'), @filesize($dbms_schema)) or die('problem ');
$sql_query = remove_remarks($sql_query);
$sql_query = split_sql_file($sql_query, ';');

$host = 'localhost';
$user = 'user';
$pass = 'pass';
$db = 'database_name';

//In case mysql is deprecated use mysqli functions. 
mysqli_connect($host,$user,$pass) or die('error connection');
mysqli_select_db($db) or die('error database selection');

$i=1;
foreach($sql_query as $sql){
echo $i++;
echo "<br />";
mysql_query($sql) or die('error in query');
}

?>

Plot correlation matrix using pandas

Along with other methods it is also good to have pairplot which will give scatter plot for all the cases-

import pandas as pd
import numpy as np
import seaborn as sns
rs = np.random.RandomState(0)
df = pd.DataFrame(rs.rand(10, 10))
sns.pairplot(df)

Best approach to converting Boolean object to string in java

If you're looking for a quick way to do this, for example debugging, you can simply concatenate an empty string on to the boolean:

System.out.println(b+"");

However, I strongly recommend using another method for production usage. This is a simple quick solution which is useful for debugging.

Adding an .env file to React Project

1. Create the .env file on your root folder

some sources prefere to use .env.development and .env.production but that's not obligatory.

2. The name of your VARIABLE -must- begin with REACT_APP_YOURVARIABLENAME

it seems that if your environment variable does not start like that so you will have problems

3. Include your variable

to include your environment variable just put on your code process.env.REACT_APP_VARIABLE

You don't have to install any external dependency

reading HttpwebResponse json response, C#

First you need an object

public class MyObject {
  public string Id {get;set;}
  public string Text {get;set;}
  ...
}

Then in here

    using (var twitpicResponse = (HttpWebResponse)request.GetResponse()) {

        using (var reader = new StreamReader(twitpicResponse.GetResponseStream())) {
            JavaScriptSerializer js = new JavaScriptSerializer();
            var objText = reader.ReadToEnd();
            MyObject myojb = (MyObject)js.Deserialize(objText,typeof(MyObject));
        }

    }

I haven't tested with the hierarchical object you have, but this should give you access to the properties you want.

JavaScriptSerializer System.Web.Script.Serialization

Dropdownlist width in IE

BalusC's answer above works great, but there is a small fix I would add if the content of your dropdown has a smaller width than what you define in your CSS select.expand, add this to the mouseover bind:

.bind('mouseover', function() { $(this).addClass('expand').removeClass('clicked');
                                if ($(this).width() < 300) // put your desired minwidth here
                                {
                                    $(this).removeClass('expand');
                                }})

Insertion sort vs Bubble Sort Algorithms

Number of swap in each iteration

  • Insertion-sort does at most 1 swap in each iteration.
  • Bubble-sort does 0 to n swaps in each iteration.

Accessing and changing sorted part

  • Insertion-sort accesses(and changes when needed) the sorted part to find the correct position of a number in consideration.
  • When optimized, Bubble-sort does not access what is already sorted.

Online or not

  • Insertion-sort is online. That means Insertion-sort takes one input at a time before it puts in appropriate position. It does not have to compare only adjacent-inputs.
  • Bubble-sort is not-online. It does not operate one input at a time. It handles a group of inputs(if not all) in each iteration. Bubble-sort only compare and swap adjacent-inputs in each iteration.

Update style of a component onScroll in React.js

Here is another example using HOOKS fontAwesomeIcon and Kendo UI React
[![screenshot here][1]][1]

import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';


const ScrollBackToTop = () => {
  const [show, handleShow] = useState(false);

  useEffect(() => {
    window.addEventListener('scroll', () => {
      if (window.scrollY > 1200) {
        handleShow(true);
      } else handleShow(false);
    });
    return () => {
      window.removeEventListener('scroll');
    };
  }, []);

  const backToTop = () => {
    window.scroll({ top: 0, behavior: 'smooth' });
  };

  return (
    <div>
      {show && (
      <div className="backToTop text-center">
        <button className="backToTop-btn k-button " onClick={() => backToTop()} >
          <div className="d-none d-xl-block mr-1">Top</div>
          <FontAwesomeIcon icon="chevron-up"/>
        </button>
      </div>
      )}
    </div>
  );
};

export default ScrollBackToTop;```


  [1]: https://i.stack.imgur.com/ZquHI.png

How to convert Java String to JSON Object

You are passing into the JSONObject constructor an instance of a StringBuilder class.

This is using the JSONObject(Object) constructor, not the JSONObject(String) one.

Your code should be:

JSONObject jsonObj = new JSONObject(jsonString.toString());

Printing Java Collections Nicely (toString Doesn't Return Pretty Output)

With Apache Commons 3, you want to call

StringUtils.join(myCollection, ",")

What GRANT USAGE ON SCHEMA exactly do?

For a production system, you can use this configuration :

--ACCESS DB
REVOKE CONNECT ON DATABASE nova FROM PUBLIC;
GRANT  CONNECT ON DATABASE nova  TO user;

--ACCESS SCHEMA
REVOKE ALL     ON SCHEMA public FROM PUBLIC;
GRANT  USAGE   ON SCHEMA public  TO user;

--ACCESS TABLES
REVOKE ALL ON ALL TABLES IN SCHEMA public FROM PUBLIC ;
GRANT SELECT                         ON ALL TABLES IN SCHEMA public TO read_only ;
GRANT SELECT, INSERT, UPDATE, DELETE ON ALL TABLES IN SCHEMA public TO read_write ;
GRANT ALL                            ON ALL TABLES IN SCHEMA public TO admin ;

What does ':' (colon) do in JavaScript?

You guys are forgetting that the colon is also used in the ternary operator (though I don't know if jquery uses it for this purpose).

the ternary operator is an expression form (expressions return a value) of an if/then statement. it's used like this:

var result = (condition) ? (value1) : (value2) ;

A ternary operator could also be used to produce side effects just like if/then, but this is profoundly bad practice.

How do I change the string representation of a Python class?

This is not as easy as it seems, some core library functions don't work when only str is overwritten (checked with Python 2.7), see this thread for examples How to make a class JSON serializable Also, try this

import json

class A(unicode):
    def __str__(self):
        return 'a'
    def __unicode__(self):
        return u'a'
    def __repr__(self):
        return 'a'

a = A()
json.dumps(a)

produces

'""'

and not

'"a"'

as would be expected.

EDIT: answering mchicago's comment:

unicode does not have any attributes -- it is an immutable string, the value of which is hidden and not available from high-level Python code. The json module uses re for generating the string representation which seems to have access to this internal attribute. Here's a simple example to justify this:

b = A('b') print b

produces

'a'

while

json.dumps({'b': b})

produces

{"b": "b"}

so you see that the internal representation is used by some native libraries, probably for performance reasons.

See also this for more details: http://www.laurentluce.com/posts/python-string-objects-implementation/

Show only two digit after decimal

Many other answers only do formatting. This approach will return value instead of only print format.

double number1 = 10.123456;
double number2 = (int)(Math.round(number1 * 100))/100.0;
System.out.println(number2);

Fill background color left to right CSS

A single css code on hover can do the trick: box-shadow: inset 100px 0 0 0 #e0e0e0;

A complete demo can be found in my fiddle:

https://jsfiddle.net/shuvamallick/3o0h5oka/

SQLite table constraint - unique on multiple columns

Put the UNIQUE declaration within the column definition section; working example:

CREATE TABLE a (
    i INT,
    j INT,
    UNIQUE(i, j) ON CONFLICT REPLACE
);

How to recognize vehicle license / number plate (ANPR) from an image?

try this Simple Automatic Number Plate Recognition System

http://opos.codeplex.com/

Open source and written with C#

How to copy only a single worksheet to another workbook using vba

The much longer example below combines some of the useful snippets above:

  • You can specify any number of sheets you want to copy across
  • You can copy entire sheets, i.e. like dragging the tab across, or you can copy over the contents of cells as values-only but preserving formatting.

It could still do with a lot of work to make it better (better error-handling, general cleaning up), but it hopefully provides a good start.

Note that not all formatting is carried across because the new sheet uses its own theme's fonts and colours. I can't work out how to copy those across when pasting as values only.

 Option Explicit

Sub copyDataToNewFile()
    Application.ScreenUpdating = False

    ' Allow different ways of copying data:
    ' sheet = copy the entire sheet
    ' valuesWithFormatting = create a new sheet with the same name as the
    '                        original, copy values from the cells only, then
    '                        apply original formatting. Formatting is only as
    '                        good as the Paste Special > Formats command - theme
    '                        colours and fonts are not preserved.
    Dim copyMethod As String
    copyMethod = "valuesWithFormatting"

    Dim newFilename As String           ' Name (+optionally path) of new file
    Dim themeTempFilePath As String     ' To temporarily save the source file's theme

    Dim sourceWorkbook As Workbook      ' This file
    Set sourceWorkbook = ThisWorkbook

    Dim newWorkbook As Workbook         ' New file

    Dim sht As Worksheet                ' To iterate through sheets later on.
    Dim sheetFriendlyName As String     ' To store friendly sheet name
    Dim sheetCount As Long              ' To avoid having to count multiple times

    ' Sheets to copy over, using internal code names as more reliable.
    Dim colSheetObjectsToCopy As New Collection
    colSheetObjectsToCopy.Add Sheet1
    colSheetObjectsToCopy.Add Sheet2

    ' Get filename of new file from user.
    Do
        newFilename = InputBox("Please Specify the name of your new workbook." & vbCr & vbCr & "Either enter a full path or just a filename, in which case the file will be saved in the same location (" & sourceWorkbook.Path & "). Don't use the name of a workbook that is already open, otherwise this script will break.", "New Copy")
        If newFilename = "" Then MsgBox "You must enter something.", vbExclamation, "Filename needed"
    Loop Until newFilename > ""

    ' If they didn't supply a path, assume same location as the source workbook.
    ' Not perfect - simply assumes a path has been supplied if a path separator
    ' exists somewhere. Could still be a badly-formed path. And, no check is done
    ' to see if the path actually exists.
    If InStr(1, newFilename, Application.PathSeparator, vbTextCompare) = 0 Then
        newFilename = sourceWorkbook.Path & Application.PathSeparator & newFilename
    End If

    ' Create a new workbook and save as the user requested.
    ' NB This fails if the filename is the same as a workbook that's
    ' already open - it should check for this.
    Set newWorkbook = Application.Workbooks.Add(xlWBATWorksheet)
    newWorkbook.SaveAs Filename:=newFilename, _
        FileFormat:=xlWorkbookDefault

    ' Theme fonts and colours don't get copied over with most paste-special operations.
    ' This saves the theme of the source workbook and then loads it into the new workbook.
    ' BUG: Doesn't work!
    'themeTempFilePath = Environ("temp") & Application.PathSeparator & sourceWorkbook.Name & " - Theme.xml"
    'sourceWorkbook.Theme.ThemeFontScheme.Save themeTempFilePath
    'sourceWorkbook.Theme.ThemeColorScheme.Save themeTempFilePath
    'newWorkbook.Theme.ThemeFontScheme.Load themeTempFilePath
    'newWorkbook.Theme.ThemeColorScheme.Load themeTempFilePath
    'On Error Resume Next
    'Kill themeTempFilePath  ' kill = delete in VBA-speak
    'On Error GoTo 0


    ' getWorksheetNameFromObject returns null if the worksheet object doens't
    ' exist
    For Each sht In colSheetObjectsToCopy
        sheetFriendlyName = getWorksheetNameFromObject(sourceWorkbook, sht)
        Application.StatusBar = "VBL Copying " & sheetFriendlyName
        If Not IsNull(sheetFriendlyName) Then
            Select Case copyMethod
                Case "sheet"
                    sourceWorkbook.Sheets(sheetFriendlyName).Copy _
                        After:=newWorkbook.Sheets(newWorkbook.Sheets.count)
                Case "valuesWithFormatting"
                    newWorkbook.Sheets.Add After:=newWorkbook.Sheets(newWorkbook.Sheets.count), _
                        Type:=sourceWorkbook.Sheets(sheetFriendlyName).Type
                    sheetCount = newWorkbook.Sheets.count
                    newWorkbook.Sheets(sheetCount).Name = sheetFriendlyName
                    ' Copy all cells in current source sheet to the clipboard. Could copy straight
                    ' to the new workbook by specifying the Destination parameter but in this case
                    ' we want to do a paste special as values only and the Copy method doens't allow that.
                    sourceWorkbook.Sheets(sheetFriendlyName).Cells.Copy ' Destination:=newWorkbook.Sheets(newWorkbook.Sheets.Count).[A1]
                    newWorkbook.Sheets(sheetCount).[A1].PasteSpecial Paste:=xlValues
                    newWorkbook.Sheets(sheetCount).[A1].PasteSpecial Paste:=xlFormats
                    newWorkbook.Sheets(sheetCount).Tab.Color = sourceWorkbook.Sheets(sheetFriendlyName).Tab.Color
                    Application.CutCopyMode = False
            End Select
        End If
    Next sht

    Application.StatusBar = False
    Application.ScreenUpdating = True
    ActiveWorkbook.Save

How can I add 1 day to current date?

Inspired by jpmottin in this question, here's the one line code:

_x000D_
_x000D_
var dateStr = '2019-01-01';_x000D_
var days = 1;_x000D_
_x000D_
var result = new Date(new Date(dateStr).setDate(new Date(dateStr).getDate() + days));_x000D_
_x000D_
document.write('Date: ', result); // Wed Jan 02 2019 09:00:00 GMT+0900 (Japan Standard Time)_x000D_
document.write('<br />');_x000D_
document.write('Trimmed Date: ', result.toISOString().substr(0, 10)); // 2019-01-02
_x000D_
_x000D_
_x000D_

Hope this helps

Is there any standard for JSON API response format?

There is no lawbreaking or outlaw standard other than common sense. If we abstract this like two people talking, the standard is the best way they can accurately understand each other in minimum words in minimum time. In our case, 'minimum words' is optimizing bandwidth for transport efficiency and 'accurately understand' is the structure for parser efficiency; which ultimately ends up with the less the data, and the common the structure; so that it can go through a pin hole and can be parsed through a common scope (at least initially).

Almost in every cases suggested, I see separate responses for 'Success' and 'Error' scenario, which is kind of ambiguity to me. If responses are different in these two cases, then why do we really need to put a 'Success' flag there? Is it not obvious that the absence of 'Error' is a 'Success'? Is it possible to have a response where 'Success' is TRUE with an 'Error' set? Or the way, 'Success' is FALSE with no 'Error' set? Just one flag is not enough? I would prefer to have the 'Error' flag only, because I believe there will be less 'Error' than 'Success'.

Also, should we really make the 'Error' a flag? What about if I want to respond with multiple validation errors? So, I find it more efficient to have an 'Error' node with each error as child to that node; where an empty (counts to zero) 'Error' node would denote a 'Success'.

Looping over arrays, printing both index and value

users=("kamal" "jamal" "rahim" "karim" "sadia")
index=()
t=-1

for i in ${users[@]}; do
  t=$(( t + 1 ))
  if [ $t -eq 0 ]; then
    for j in ${!users[@]}; do
      index[$j]=$j
    done
  fi
  echo "${index[$t]} is $i"
done

Find the number of downloads for a particular app in apple appstore

Updated answer now that xyo.net has been bought and shut down.

appannie.com and similarweb.com are the best options now. Thanks @rinogo for the original suggestion!

Outdated answer:

Site is still buggy, but this is by far the best that I've found. Not sure if it's accurate, but at least they give you numbers that you can guess off of! They have numbers for Android, iOS (iPhone and iPad) and even Windows!

xyo.net

How to automatically update your docker containers, if base-images are updated

I had the same issue and thought it can be simply solved by a cron job calling unattended-upgrade daily.

My intention is to have this as an automatic and quick solution to ensure that production container is secure and updated because it can take me sometime to update my images and deploy a new docker image with the latest security updates.

It is also possible to automate the image build and deployment with Github hooks

I've created a basic docker image with that automatically checks and installs security updates daily (can run directly by docker run itech/docker-unattended-upgrade ).

I also came across another different approach to check if the container needs an update.

My complete implementation:

Dockerfile

FROM ubuntu:14.04   

RUN apt-get update \
&& apt-get install -y supervisor unattended-upgrades \
&& rm -rf /var/lib/apt/lists/*

COPY install /install
RUN chmod 755 install
RUN /install

COPY start /start
RUN chmod 755 /start

Helper scripts

install

#!/bin/bash
set -e

cat > /etc/supervisor/conf.d/cron.conf <<EOF
[program:cron]
priority=20
directory=/tmp
command=/usr/sbin/cron -f
user=root
autostart=true
autorestart=true
stdout_logfile=/var/log/supervisor/%(program_name)s.log
stderr_logfile=/var/log/supervisor/%(program_name)s.log
EOF

rm -rf /var/lib/apt/lists/*

ENTRYPOINT ["/start"]

start

#!/bin/bash

set -e

echo "Adding crontab for unattended-upgrade ..."
echo "0 0 * * * root /usr/bin/unattended-upgrade" >> /etc/crontab

# can also use @daily syntax or use /etc/cron.daily

echo "Starting supervisord ..."
exec /usr/bin/supervisord -n -c /etc/supervisor/supervisord.conf

Edit

I developed a small tool docker-run that runs as docker container and can be used to update packages inside all or selected running containers, it can also be used to run any arbitrary commands.

Can be easily tested with the following command:

docker run --rm -v /var/run/docker.sock:/tmp/docker.sock itech/docker-run exec

which by default will execute date command in all running containers and display the results. If you pass update instead of exec it will execute apt-get update followed by apt-get upgrade -y in all running containers

Does java.util.List.isEmpty() check if the list itself is null?

Invoking any method on any null reference will always result in an exception. Test if the object is null first:

List<Object> test = null;
if (test != null && !test.isEmpty()) {
    // ...
}

Alternatively, write a method to encapsulate this logic:

public static <T> boolean IsNullOrEmpty(Collection<T> list) {
    return list == null || list.isEmpty();
}

Then you can do:

List<Object> test = null;
if (!IsNullOrEmpty(test)) {
    // ...
}

Most recent previous business day in Python

timeboard package does this.

Suppose your date is 04 Sep 2017. In spite of being a Monday, it was a holiday in the US (the Labor Day). So, the most recent business day was Friday, Sep 1.

>>> import timeboard.calendars.US as US
>>> clnd = US.Weekly8x5()
>>> clnd('04 Sep 2017').rollback().to_timestamp().date()
datetime.date(2017, 9, 1)

In UK, 04 Sep 2017 was the regular business day, so the most recent business day was itself.

>>> import timeboard.calendars.UK as UK
>>> clnd = UK.Weekly8x5()
>>> clnd('04 Sep 2017').rollback().to_timestamp().date()
datetime.date(2017, 9, 4)

DISCLAIMER: I am the author of timeboard.

What is the difference between bool and Boolean types in C#

Note that Boolean will only work were you have using System; (which is usually, but not necessarily, included) (unless you write it out as System.Boolean). bool does not need using System;

Creating a simple login form

<html>
<head>
<meta charset="utf-8">
<title>Best Login Page design in html and css</title>
<style type="text/css">
body {
background-color: #f4f4f4;
color: #5a5656;
font-family: 'Open Sans', Arial, Helvetica, sans-serif;
font-size: 16px;
line-height: 1.5em;
}
a { text-decoration: none; }
h1 { font-size: 1em; }
h1, p {
margin-bottom: 10px;
}
strong {
font-weight: bold;
}
.uppercase { text-transform: uppercase; }

/* ---------- LOGIN ---------- */
#login {
margin: 50px auto;
width: 300px;
}
form fieldset input[type="text"], input[type="password"] {
background-color: #e5e5e5;
border: none;
border-radius: 3px;
-moz-border-radius: 3px;
-webkit-border-radius: 3px;
color: #5a5656;
font-family: 'Open Sans', Arial, Helvetica, sans-serif;
font-size: 14px;
height: 50px;
outline: none;
padding: 0px 10px;
width: 280px;
-webkit-appearance:none;
}
form fieldset input[type="submit"] {
background-color: #008dde;
border: none;
border-radius: 3px;
-moz-border-radius: 3px;
-webkit-border-radius: 3px;
color: #f4f4f4;
cursor: pointer;
font-family: 'Open Sans', Arial, Helvetica, sans-serif;
height: 50px;
text-transform: uppercase;
width: 300px;
-webkit-appearance:none;
}
form fieldset a {
color: #5a5656;
font-size: 10px;
}
form fieldset a:hover { text-decoration: underline; }
.btn-round {
background-color: #5a5656;
border-radius: 50%;
-moz-border-radius: 50%;
-webkit-border-radius: 50%;
color: #f4f4f4;
display: block;
font-size: 12px;
height: 50px;
line-height: 50px;
margin: 30px 125px;
text-align: center;
text-transform: uppercase;
width: 50px;
}
.facebook-before {
background-color: #0064ab;
border-radius: 3px 0px 0px 3px;
-moz-border-radius: 3px 0px 0px 3px;
-webkit-border-radius: 3px 0px 0px 3px;
color: #f4f4f4;
display: block;
float: left;
height: 50px;
line-height: 50px;
text-align: center;
width: 50px;
}
.facebook {
background-color: #0079ce;
border: none;
border-radius: 0px 3px 3px 0px;
-moz-border-radius: 0px 3px 3px 0px;
-webkit-border-radius: 0px 3px 3px 0px;
color: #f4f4f4;
cursor: pointer;
height: 50px;
text-transform: uppercase;
width: 250px;
}
.twitter-before {
background-color: #189bcb;
border-radius: 3px 0px 0px 3px;
-moz-border-radius: 3px 0px 0px 3px;
-webkit-border-radius: 3px 0px 0px 3px;
color: #f4f4f4;
display: block;
float: left;
height: 50px;
line-height: 50px;
text-align: center;
width: 50px;
}
.twitter {
background-color: #1bb2e9;
border: none;
border-radius: 0px 3px 3px 0px;
-moz-border-radius: 0px 3px 3px 0px;
-webkit-border-radius: 0px 3px 3px 0px;
color: #f4f4f4;
cursor: pointer;
height: 50px;
text-transform: uppercase;
width: 250px;
}
</style>
</head>
<body>
<div id="login">
<h1><strong>Welcome.</strong> Please login.</h1>
<form action="javascript:void(0);" method="get">
<fieldset>
<p><input type="text" required value="Username" onBlur="if(this.value=='')this.value='Username'" onFocus="if(this.value=='Username')this.value='' "></p>
<p><input type="password" required value="Password" onBlur="if(this.value=='')this.value='Password'" onFocus="if(this.value=='Password')this.value='' "></p>
<p><a href="#">Forgot Password?</a></p>
<p><input type="submit" value="Login"></p>
</fieldset>
</form>
<p><span class="btn-round">or</span></p>
<p>
<a class="facebook-before"></a>
<button class="facebook">Login Using Facbook</button>
</p>
<p>
<a class="twitter-before"></a>
<button class="twitter">Login Using Twitter</button>
</p>
</div> <!-- end login -->
</body>
</html>

How to iterate through XML in Powershell?

You can also do it without the [xml] cast. (Although xpath is a world unto itself. https://www.w3schools.com/xml/xml_xpath.asp)

$xml = (select-xml -xpath / -path stack.xml).node
$xml.objects.object.property

Or just this, xpath is case sensitive. Both have the same output:

$xml = (select-xml -xpath /Objects/Object/Property -path stack.xml).node
$xml


Name         Type                                                #text
----         ----                                                -----
DisplayName  System.String                                       SQL Server (MSSQLSERVER)
ServiceState Microsoft.SqlServer.Management.Smo.Wmi.ServiceState Running
DisplayName  System.String                                       SQL Server Agent (MSSQLSERVER)
ServiceState Microsoft.SqlServer.Management.Smo.Wmi.ServiceState Stopped

How to send a header using a HTTP request through a curl call?

You can also send multiple headers, data (JSON for example), and specify Call method (POST,GET) into a single CUrl call like this:

curl -X POST(Get or whatever) \
  http://your_url.com/api/endpoint \
  -H 'Content-Type: application/json' \
  -H 'header-element1: header-data1' \
  -H 'header-element2: header-data2' \

......more headers................

  -d '{
  "JsonExArray": [
    {
      "json_prop": "1",
    },
    {
      "json_prop": "2",
    }
  ]
}'

Exclude subpackages from Spring autowiring?

This works in Spring 3.0.5. So, I would think it would work in 3.1

<context:component-scan base-package="com.example">  
    <context:exclude-filter type="aspectj" expression="com.example.dontscanme.*" />  
</context:component-scan> 

How to make System.out.println() shorter

As Bakkal explained, for the keyboard shortcuts, in netbeans you can go to tools->options->editor->code templates and add or edit your own shortcuts.

In Eclipse it's on templates.

Updating user data - ASP.NET Identity

Excellent!!!

IdentityResult result = await UserManager.UpdateAsync(user);

Resolve absolute path from relative path and/or file name

In your example, from Bar\test.bat, DIR /B /S ..\somefile.txt would return the full path.

What is the coolest thing you can do in <10 lines of simple code? Help me inspire beginners!

This PHP code only works on a Mac through the command-line, but it's very useful when everyone wants to play Twister

$lr = array('left', 'right');
$hf = array('hand', 'foot');
$colour = array('red', 'yellow', 'blue', 'green');
while(true) {
    $a = $lr[array_rand($lr)];
    $b = $hf[array_rand($hf)];
    $c = $colour[array_rand($colour)];
    system("say $a $b $c");
    sleep(5);
}

How to get an element's top position relative to the browser's viewport?

You can try:

node.offsetTop - window.scrollY

It works on Opera with viewport meta tag defined.

Best Way to Refresh Adapter/ListView on Android

Simply add these code before setting Adapter it's working for me:

    listView.destroyDrawingCache();
    listView.setVisibility(ListView.INVISIBLE);
    listView.setVisibility(ListView.VISIBLE);

Or Directly you can use below method after change Data resource.

   adapter.notifyDataSetChanged()

GZIPInputStream reading line by line

The basic setup of decorators is like this:

InputStream fileStream = new FileInputStream(filename);
InputStream gzipStream = new GZIPInputStream(fileStream);
Reader decoder = new InputStreamReader(gzipStream, encoding);
BufferedReader buffered = new BufferedReader(decoder);

The key issue in this snippet is the value of encoding. This is the character encoding of the text in the file. Is it "US-ASCII", "UTF-8", "SHIFT-JIS", "ISO-8859-9", …? there are hundreds of possibilities, and the correct choice usually cannot be determined from the file itself. It must be specified through some out-of-band channel.

For example, maybe it's the platform default. In a networked environment, however, this is extremely fragile. The machine that wrote the file might sit in the neighboring cubicle, but have a different default file encoding.

Most network protocols use a header or other metadata to explicitly note the character encoding.

In this case, it appears from the file extension that the content is XML. XML includes the "encoding" attribute in the XML declaration for this purpose. Furthermore, XML should really be processed with an XML parser, not as text. Reading XML line-by-line seems like a fragile, special case.

Failing to explicitly specify the encoding is against the second commandment. Use the default encoding at your peril!

How to export html table to excel or pdf in php

If all you want is a simple excel worksheet try this:

header('Content-type: application/excel');
$filename = 'filename.xls';
header('Content-Disposition: attachment; filename='.$filename);

$data = '<html xmlns:x="urn:schemas-microsoft-com:office:excel">
<head>
    <!--[if gte mso 9]>
    <xml>
        <x:ExcelWorkbook>
            <x:ExcelWorksheets>
                <x:ExcelWorksheet>
                    <x:Name>Sheet 1</x:Name>
                    <x:WorksheetOptions>
                        <x:Print>
                            <x:ValidPrinterInfo/>
                        </x:Print>
                    </x:WorksheetOptions>
                </x:ExcelWorksheet>
            </x:ExcelWorksheets>
        </x:ExcelWorkbook>
    </xml>
    <![endif]-->
</head>

<body>
   <table><tr><td>Cell 1</td><td>Cell 2</td></tr></table>
</body></html>';

echo $data;

The key here is the xml data. This will keep excel from complaining about the file.

AJAX POST and Plus Sign ( + ) -- How to Encode?

The hexadecimal value you are looking for is %2B

To get it automatically in PHP run your string through urlencode($stringVal). And then run it rhough urldecode($stringVal) to get it back.

If you want the JavaScript to handle it, use escape( str )

Edit

After @bobince's comment I did more reading and he is correct. Use encodeURIComponent(str) and decodeURIComponent(str). Escape will not convert the characters, only escape them with \'s

How can I query a value in SQL Server XML column

select
  Roles
from
  MyTable
where
  Roles.value('(/root/role)[1]', 'varchar(max)') like 'StringToSearchFor'

In case your column is not XML, you need to convert it. You can also use other syntax to query certain attributes of your XML data. Here is an example...

Let's suppose that data column has this:

<Utilities.CodeSystems.CodeSystemCodes iid="107" CodeSystem="2" Code="0001F" CodeTags="-19-"..../>

... and you only want the ones where CodeSystem = 2 then your query will be:

select 
  [data] 
from
  [dbo].[CodeSystemCodes_data]
  
where
  CAST([data] as XML).value('(/Utilities.CodeSystems.CodeSystemCodes/@CodeSystem)[1]', 'varchar(max)') = '2'

These pages will show you more about how to query XML in T-SQL:

Querying XML fields using t-sql

Flattening XML Data in SQL Server

EDIT

After playing with it a little bit more, I ended up with this amazing query that uses CROSS APPLY. This one will search every row (role) for the value you put in your like expression...

Given this table structure:

create table MyTable (Roles XML)

insert into MyTable values
('<root>
   <role>Alpha</role>
   <role>Gamma</role>
   <role>Beta</role>
</root>')

We can query it like this:

select * from 

(select 
       pref.value('(text())[1]', 'varchar(32)') as RoleName
from 
       MyTable CROSS APPLY

       Roles.nodes('/root/role') AS Roles(pref)
)  as Result

where RoleName like '%ga%'

You can check the SQL Fiddle here: http://sqlfiddle.com/#!18/dc4d2/1/0

jQuery UI Dialog individual CSS styling

The standard way to do this is with jQuery UI's CSS Scopes:

<div class="myCssScope">
   <!-- dialog goes here -->
</div>

Unfortunately, the jQuery UI dialog moves the dialog DOM elements to the end of the document, to fix potential z-index issues. This means the scoping won't work (it will no longer have a ".myCssScope" ancestor).

Christoph Herold designed a workaround which I've implemented as a jQuery plugin, maybe that will help.

Can a website detect when you are using Selenium with chromedriver?

Example of how it's implemented on wellsfargo.com:

try {
 if (window.document.documentElement.getAttribute("webdriver")) return !+[]
} catch (IDLMrxxel) {}
try {
 if ("_Selenium_IDE_Recorder" in window) return !+""
} catch (KknKsUayS) {}
try {
 if ("__webdriver_script_fn" in document) return !+""

Nexus 5 USB driver

Is it your first android connected to your computer? Sometimes windows drivers need to be erased. Refer http://forum.xda-developers.com/showthread.php?t=2512549

HTML tag inside JavaScript

<div id="demo"></div>

<input type="submit" name="submit" id="submit" value="Submit" onClick="return empty()">


<script type="text/javascript">
        function empty()
        {
          var x;
          x = document.getElementById("feedbackpost").value;
          if (x == "")
           {
             var demo = document.getElementById("demo");
             demo.innerHTML =document.write='<h1>Hello member</h1>';
              return false;
           };
        }
    </script>

Alter a MySQL column to be AUTO_INCREMENT

Since SQL tag is attached to the question I really think all answers missed one major point.

MODIFY command does not exist in SQL server So you will be getting an error when you run the

ALTER TABLE Satellites MODIFY COLUMN SatelliteID INT auto_increment PRIMARY KEY;

enter image description here

In this case you can either add new column as INT IDENTITY

ALTER TABLE Satellites
   ADD ID INT IDENTITY
       CONSTRAINT PK_YourTable PRIMARY KEY CLUSTERED;

OR


Fill the existing null index with incremental numbers using this method,
DECLARE @id INT
SET @id = 0 
UPDATE Satellites SET @id = SatelliteID = @id + 1 

Python basics printing 1 to 100

consider the following:

def gukan(count):
    while count < 100:
      print(count)
      count=count+3;
gukan(0) #prints ..., 93, 96, 99


def gukan(count):
    while count < 100:
      print(count)
      count=count+9;
gukan(0) # prints ..., 81, 90, 99

you should use count < 100 because count will never reach the exact number 100 if you use 3 or 9 as the increment, thus creating an infinite loop.

Good luck!~ :)

SyntaxError: multiple statements found while compiling a single statement

A (partial) practical work-around is to put things into a throw-away function.

Pasting

x = 1
x += 1
print(x)

results in

>>> x = 1
x += 1
print(x)
  File "<stdin>", line 1
    x += 1
print(x)

    ^
SyntaxError: multiple statements found while compiling a single statement
>>>

However, pasting

def abc():
  x = 1
  x += 1
  print(x)

works:

>>> def abc():
  x = 1
  x += 1
  print(x)
>>> abc()
2
>>>

Of course, this is OK for a quick one-off, won't work for everything you might want to do, etc. But then, going to ipython / jupyter qtconsole is probably the next simplest option.

Begin, Rescue and Ensure in Ruby?

Yes, ensure is called in any circumstances. For more information see "Exceptions, Catch, and Throw" of the Programming Ruby book and search for "ensure".

set column width of a gridview in asp.net

I know this is an old Question, but it popped up when I was looking for a solution to the same issue, so I thought that I would post what worked for me.

<asp:BoundField DataField="Description" HeaderText="Bond Event" ItemStyle-Width="300px" />

I used the ItemStyle-Width attribute on my BoundField and it worked very nicely I haven't had any issues yet.

I didn't need to add anything else to the rest of the code to make this work either.

How to keep a VMWare VM's clock in sync?

The CPU speed varies due to power saving. I originally noticed this because VMware gave me a helpful tip on my laptop, but this page mentions the same thing:

Quote from : VMWare tips and tricks Power saving (SpeedStep, C-states, P-States,...)

Your power saving settings may interfere significantly with vmware's performance. There are several levels of power saving.

CPU frequency

This should not lead to performance degradation, outside of having the obvious lower performance when running the CPU at a lower frequency (either manually of via governors like "ondemand" or "conservative"). The only problem with varying the CPU speed while vmware is running is that the Windows clock will gain of lose time. To prevent this, specify your full CPU speed in kHz in /etc/vmware/config

host.cpukHz = 2167000

How to detect if CMD is running as Administrator/has elevated privileges?

I read many (most?) of the responses, then developed a bat file that works for me in Win 8.1. Thought I'd share it.

setlocal
set runState=user
whoami /groups | findstr /b /c:"Mandatory Label\High Mandatory Level" > nul && set runState=admin
whoami /groups | findstr /b /c:"Mandatory Label\System Mandatory Level" > nul && set runState=system
echo Running in state: "%runState%"
if not "%runState%"=="user" goto notUser
  echo Do user stuff...
  goto end
:notUser
if not "%runState%"=="admin" goto notAdmin
  echo Do admin stuff...
  goto end
:notAdmin
if not "%runState%"=="system" goto notSystem
  echo Do admin stuff...
  goto end
:notSystem
echo Do common stuff...
:end

Hope someone finds this useful :)

git: 'credential-cache' is not a git command

We had the same issue with our Azure DevOps repositories after our domain changed, i.e. from @xy.com to @xyz.com. To fix this issue, we generated a fresh personal access token with the following permissions:

Code: read & write Packaging: read

Then we opened the Windows Credential Manager, added a new generic windows credential with the following details:

Internet or network address: "git:{projectname}@dev.azure.com/{projectname}" - alternatively you should use your git repository name here.
User name: "Personal Access Token"
Password: {The generated Personal Access Token}

Afterwards all our git operations were working again. Hope this helps someone else!

How to change scroll bar position with CSS?

Here is another way, by rotating element with the scrollbar for 180deg, wrapping it's content into another element, and rotating that wrapper for -180deg. Check the snippet below

_x000D_
_x000D_
div {_x000D_
  display: inline-block;_x000D_
  width: 100px;_x000D_
  height: 100px;_x000D_
  border: 2px solid black;_x000D_
  margin: 15px;_x000D_
}_x000D_
#vertical {_x000D_
  direction: rtl;_x000D_
  overflow-y: scroll;_x000D_
  overflow-x: hidden;_x000D_
  background: gold;_x000D_
}_x000D_
#vertical p {_x000D_
  direction: ltr;_x000D_
  margin-bottom: 0;_x000D_
}_x000D_
#horizontal {_x000D_
  direction: rtl;_x000D_
  transform: rotate(180deg);_x000D_
  overflow-y: hidden;_x000D_
  overflow-x: scroll;_x000D_
  background: tomato;_x000D_
  padding-top: 30px;_x000D_
}_x000D_
#horizontal span {_x000D_
  direction: ltr;_x000D_
  display: inline-block;_x000D_
  transform: rotate(-180deg);_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<div id=vertical>_x000D_
  <p>content_x000D_
    <br>content_x000D_
    <br>content_x000D_
    <br>content_x000D_
    <br>content_x000D_
    <br>content_x000D_
    <br>content_x000D_
    <br>content_x000D_
    <br>content_x000D_
    <br>content_x000D_
    <br>content_x000D_
    <br>content_x000D_
    <br>content</p>_x000D_
</div>_x000D_
<div id=horizontal><span> content_content_content_content_content_content_content_content_content_content_content_content_content_content</span>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Detect viewport orientation, if orientation is Portrait display alert message advising user of instructions

I combined two solutions and it works fine for me.

window.addEventListener("orientationchange", function() {                   
    if (window.matchMedia("(orientation: portrait)").matches) {
       alert("PORTRAIT")
     }
    if (window.matchMedia("(orientation: landscape)").matches) {
      alert("LANSCAPE")
     }
}, false);

When to use std::size_t?

size_t is the result type of the sizeof operator.

Use size_t for variables that model size or index in an array. size_t conveys semantics: you immediately know it represents a size in bytes or an index, rather than just another integer.

Also, using size_t to represent a size in bytes helps making the code portable.

Return a 2d array from a function

#include <iostream>
using namespace std ;

typedef int (*Type)[3][3] ;

Type Demo_function( Type ); //prototype

int main (){
    cout << "\t\t!!!!!Passing and returning 2D array from function!!!!!\n"

    int array[3][3] ;
    Type recieve , ptr = &array;
    recieve = Demo_function( ptr ) ;

    for ( int i = 0 ;  i < 3 ; i ++ ){
        for ( int j = 0 ; j < 3 ; j ++ ){
            cout <<  (*recieve)[i][j] << " " ;
        }
    cout << endl ; 
    }

return 0 ;
}


Type Demo_function( Type array ){/*function definition */

    cout << "Enter values : \n" ;
    for (int i =0 ;  i < 3 ; i ++)
        for ( int j = 0 ; j < 3 ; j ++ )
            cin >> (*array)[i][j] ;

    return array ; 
}

Argument Exception "Item with Same Key has already been added"

If you want "insert or replace" semantics, use this syntax:

A[key] = value;     // <-- insert or replace semantics

It's more efficient and readable than calls involving "ContainsKey()" or "Remove()" prior to "Add()".

So in your case:

rct3Features[items[0]] = items[1];

How to sort an array of objects with jquery or javascript

//This will sort your array
function SortByName(a, b){
  var aName = a.name.toLowerCase();
  var bName = b.name.toLowerCase(); 
  return ((aName < bName) ? -1 : ((aName > bName) ? 1 : 0));
}

array.sort(SortByName);

Image scaling causes poor quality in firefox/internet explorer but not chrome

IE Scaling Depends on Amount of Downsize

Some people said that an even fraction downsize avoids the problem. I disagree.

In IE11 I find that reducing an image by 50% (e.g. 300px to 150px) yields a jagged resize (like it's using nearest-neighbor). A resize to ~99% or 73% (e.g. 300px to 276px) yields a smoother image: bilinear or bicubic etc.

In response I've been using images that are just retina-ish: maybe 25% bigger than would be used on a traditional 1:1 pixel mapping screen, so that IE only resizes a bit and doesn't trigger the ugliness.

How to get element by classname or id

If you want to find the button only by its class name and using jQLite only, you can do like below:

var myListButton = $document.find('button').filter(function() {
    return angular.element(this).hasClass('multi-files');
});

Hope this helps. :)

Array.size() vs Array.length

The .size() function is available in Jquery and many other libraries.

The .length property works only when the index is an integer.

The length property will work with this type of array:

var nums = new Array();
nums[0] = 1; 
nums[1] = 2;
print(nums.length); // displays 2

The length property won't work with this type of array:

var pbook = new Array(); 
pbook["David"] = 1; 
pbook["Jennifer"] = 2;
print(pbook.length); // displays 0

So in your case you should be using the .length property.

Remove portion of a string after a certain character

By using regular expression: $string = preg_replace('/\s+By.*$/', '', $string)

Algorithm for Determining Tic Tac Toe Game Over

Constant time solution, runs in O(8).

Store the state of the board as a binary number. The smallest bit (2^0) is the top left row of the board. Then it goes rightwards, then downwards.

I.E.

+-----------------+
| 2^0 | 2^1 | 2^2 |
|-----------------|
| 2^3 | 2^4 | 2^5 |
|-----------------|
| 2^6 | 2^7 | 2^8 |
+-----------------+

Each player has their own binary number to represent the state (because tic-tac-toe) has 3 states (X, O & blank) so a single binary number won't work to represent the state of the board for multiple players.

For example, a board like:

+-----------+
| X | O | X |
|-----------|
| O | X |   |
|-----------|
|   | O |   |
+-----------+

   0 1 2 3 4 5 6 7 8
X: 1 0 1 0 1 0 0 0 0
O: 0 1 0 1 0 0 0 1 0

Notice that the bits for player X are disjoint from the bits for player O, this is obvious because X can't put a piece where O has a piece and vice versa.

To check whether a player has won, we need to compare all the positions covered by that player to a position we know is a win-position. In this case, the easiest way to do that would be by AND-gating the player-position and the win-position and seeing if the two are equal.

boolean isWinner(short X) {
    for (int i = 0; i < 8; i++)
        if ((X & winCombinations[i]) == winCombinations[i])
            return true;
    return false;
}

eg.

X: 111001010
W: 111000000 // win position, all same across first row.
------------
&: 111000000

Note: X & W = W, so X is in a win state.

This is a constant time solution, it depends only on the number of win-positions, because applying AND-gate is a constant time operation and the number of win-positions is finite.

It also simplifies the task of enumerating all valid board states, their just all the numbers representable by 9 bits. But of course you need an extra condition to guarantee a number is a valid board state (eg. 0b111111111 is a valid 9-bit number, but it isn't a valid board state because X has just taken all the turns).

The number of possible win positions can be generated on the fly, but here they are anyways.

short[] winCombinations = new short[] {
  // each row
  0b000000111,
  0b000111000,
  0b111000000,
  // each column
  0b100100100,
  0b010010010,
  0b001001001,
  // each diagonal
  0b100010001,
  0b001010100
};

To enumerate all board positions, you can run the following loop. Although I'll leave determining whether a number is a valid board state upto someone else.

NOTE: (2**9 - 1) = (2**8) + (2**7) + (2**6) + ... (2**1) + (2**0)

for (short X = 0; X < (Math.pow(2,9) - 1); X++)
   System.out.println(isWinner(X));

SELECT * FROM multiple tables. MySQL

In order to get rid of duplicates, you can group by drinks.id. But that way you'll get only one photo for each drinks.id (which photo you'll get depends on database internal implementation).

Though it is not documented, in case of MySQL, you'll get the photo with lowest id (in my experience I've never seen other behavior).

SELECT name, price, photo 
FROM drinks, drinks_photos 
WHERE drinks.id = drinks_id
GROUP BY drinks.id

How can I enable Assembly binding logging?

A good place to start your investigation into any failed binding is to use the "fuslogvw.exe" utility. This may give you the information you need related to the binding failure so that you don't have to go messing around with any registry values to turn binding logging on.

Fuslogvw MSDN page

The utility should be in your Microsoft SDKs folder, which would be something like this, depending on your operating system: "C:\Program Files (x86)\Microsoft SDKs\Windows\v{SDK version}A\Bin\FUSLOGVW.exe"

  1. Run this utility as Administrator, from Developer Command Prompt (as Admin) type FUSLOGVW a new screen appears

  2. Go to Settings to and select Enable all binds to disk also select Enable custom log path and select the path of the folder of your choice to store the binding log.

  3. Restart IIS.

  4. From the FUSLOGVW window click Delete all to clear the list of any previous bind failures

  5. Reproduce the binding failure in your application

  6. In the utility, click Refresh. You should then see the bind failure logged in the list.

  7. You can view information about the bind failure by selecting it in the list and clicking View Log

The first thing I look for is the path in which the application is looking for the assembly. You should also make sure the version number of the assembly in question is what you expect.

Pass multiple optional parameters to a C# function

1.You can make overload functions.

SomeF(strin s){}   
SomeF(string s, string s2){}    
SomeF(string s1, string s2, string s3){}   

More info: http://csharpindepth.com/Articles/General/Overloading.aspx

2.or you may create one function with params

SomeF( params string[] paramArray){}
SomeF("aa","bb", "cc", "dd", "ff"); // pass as many as you like

More info: https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/params

3.or you can use simple array

Main(string[] args){}

How to update attributes without validation

try using

@record.assign_attributes({ ... })
@record.save(validate: false)

works for me

.aspx vs .ashx MAIN difference

.aspx is a rendered page. If you need a view, use an .aspx page. If all you need is backend functionality but will be staying on the same view, use an .ashx page.

Can I get Unix's pthread.h to compile in Windows?

Just pick up the TDM-GCC 64x package. (It constains both the 32 and 64 bit versions of the MinGW toolchain and comes within a neat installer.) More importantly, it contains something called the "winpthread" library.

It comprises of the pthread.h header, libwinpthread.a, libwinpthread.dll.a static libraries for both 32-bit and 64-bit and the required .dlls libwinpthread-1.dll and libwinpthread_64-1.dll(this, as of 01-06-2016).

You'll need to link to the libwinpthread.a library during build. Other than that, your code can be the same as for native Pthread code on Linux. I've so far successfully used it to compile a few basic Pthread programs in 64-bit on windows.

Alternatively, you can use the following library which wraps the windows threading API into the pthreads API: pthreads-win32.

The above two seem to be the most well known ways for this.

Hope this helps.

Accept server's self-signed ssl certificate in Java client

There's a better alternative to trusting all certificates: Create a TrustStore that specifically trusts a given certificate and use this to create a SSLContext from which to get the SSLSocketFactory to set on the HttpsURLConnection. Here's the complete code:

File crtFile = new File("server.crt");
Certificate certificate = CertificateFactory.getInstance("X.509").generateCertificate(new FileInputStream(crtFile));

KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
keyStore.load(null, null);
keyStore.setCertificateEntry("server", certificate);

TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
trustManagerFactory.init(keyStore);

SSLContext sslContext = SSLContext.getInstance("TLS");
sslContext.init(null, trustManagerFactory.getTrustManagers(), null);

HttpsURLConnection connection = (HttpsURLConnection) new URL(url).openConnection();
connection.setSSLSocketFactory(sslContext.getSocketFactory());

You can alternatively load the KeyStore directly from a file or retrieve the X.509 Certificate from any trusted source.

Note that with this code, the certificates in cacerts will not be used. This particular HttpsURLConnection will only trust this specific certificate.

Strict Standards: Only variables should be assigned by reference PHP 5.4

It's because you're trying to assign an object by reference. Remove the ampersand and your script should work as intended.

Parsing a YAML file in Python, and accessing the data?

Since PyYAML's yaml.load() function parses YAML documents to native Python data structures, you can just access items by key or index. Using the example from the question you linked:

import yaml
with open('tree.yaml', 'r') as f:
    doc = yaml.load(f)

To access branch1 text you would use:

txt = doc["treeroot"]["branch1"]
print txt
"branch1 text"

because, in your YAML document, the value of the branch1 key is under the treeroot key.

Remove Safari/Chrome textinput/textarea glow

This is the solution for people that do care about accessibility.

Please, don't use outline:none; for disabling the focus outline. You are killing accessibility of the web if you do this. There is a accessible way of doing this.

Check out this article that I've written to explain how to remove the border in an accessible way.

The idea in short is to only show the outline border when we detect a keyboard user. Once a user starts using his mouse we disable the outline. As a result you get the best of the two.

Commands out of sync; you can't run this command now

You can't have two simultaneous queries because mysqli uses unbuffered queries by default (for prepared statements; it's the opposite for vanilla mysql_query). You can either fetch the first one into an array and loop through that, or tell mysqli to buffer the queries (using $stmt->store_result()).

See here for details.

How to git ignore subfolders / subdirectories?

Have you tried wildcards?

Solution/*/bin/Debug
Solution/*/bin/Release

With version 1.8.2 of git, you can also use the ** wildcard to match any level of subdirectories:

**/bin/Debug/
**/bin/Release/

Docker expose all ports or range of ports from 7000 to 8000

For anyone facing this issue and ending up on this post...the issue is still open - https://github.com/moby/moby/issues/11185

What is the difference between .text, .value, and .value2?

.Text gives you a string representing what is displayed on the screen for the cell. Using .Text is usually a bad idea because you could get ####

.Value2 gives you the underlying value of the cell (could be empty, string, error, number (double) or boolean)

.Value gives you the same as .Value2 except if the cell was formatted as currency or date it gives you a VBA currency (which may truncate decimal places) or VBA date.

Using .Value or .Text is usually a bad idea because you may not get the real value from the cell, and they are slower than .Value2

For a more extensive discussion see my Text vs Value vs Value2

What is the best regular expression to check if a string is a valid URL?

I think I found a more general regexp to validate urls, particularly websites

?(https?:\/\/)?(www\.)[-a-zA-Z0-9@:%._\+~#=]{2,256}\.[a-z]{2,4}\b([-a-zA-Z0-9@:%_\+.~#?&//=]*)|(https?:\/\/)?(www\.)?(?!ww)[-a-zA-Z0-9@:%._\+~#=]{2,256}\.[a-z]{2,4}\b([-a-zA-Z0-9@:%_\+.~#?&//=]*)

it does not allow for instance www.something or http://www or http://www.something

Check it here: http://regexr.com/3e4a2

Find the unique values in a column and then sort them

I prefer the oneliner:

print(sorted(df['Column Name'].unique()))

How do I start/stop IIS Express Server?

You can stop any IIS Express application or you can stop all application. Right click on IIS express icon , which is located at right bottom corner of task bar. Then Select Show All Application

enter image description here

NotificationCenter issue on Swift 3

For all struggling around with the #selector in Swift 3 or Swift 4, here a full code example:

// WE NEED A CLASS THAT SHOULD RECEIVE NOTIFICATIONS
    class MyReceivingClass {

    // ---------------------------------------------
    // INIT -> GOOD PLACE FOR REGISTERING
    // ---------------------------------------------
    init() {
        // WE REGISTER FOR SYSTEM NOTIFICATION (APP WILL RESIGN ACTIVE)

        // Register without parameter
        NotificationCenter.default.addObserver(self, selector: #selector(MyReceivingClass.handleNotification), name: .UIApplicationWillResignActive, object: nil)

        // Register WITH parameter
        NotificationCenter.default.addObserver(self, selector: #selector(MyReceivingClass.handle(withNotification:)), name: .UIApplicationWillResignActive, object: nil)
    }

    // ---------------------------------------------
    // DE-INIT -> LAST OPTION FOR RE-REGISTERING
    // ---------------------------------------------
    deinit {
        NotificationCenter.default.removeObserver(self)
    }

    // either "MyReceivingClass" must be a subclass of NSObject OR selector-methods MUST BE signed with '@objc'

    // ---------------------------------------------
    // HANDLE NOTIFICATION WITHOUT PARAMETER
    // ---------------------------------------------
    @objc func handleNotification() {
        print("RECEIVED ANY NOTIFICATION")
    }

    // ---------------------------------------------
    // HANDLE NOTIFICATION WITH PARAMETER
    // ---------------------------------------------
    @objc func handle(withNotification notification : NSNotification) {
        print("RECEIVED SPECIFIC NOTIFICATION: \(notification)")
    }
}

In this example we try to get POSTs from AppDelegate (so in AppDelegate implement this):

// ---------------------------------------------
// WHEN APP IS GOING TO BE INACTIVE
// ---------------------------------------------
func applicationWillResignActive(_ application: UIApplication) {

    print("POSTING")

    // Define identifiyer
    let notificationName = Notification.Name.UIApplicationWillResignActive

    // Post notification
    NotificationCenter.default.post(name: notificationName, object: nil)
}

passing object by reference in C++

What seems to be confusing you is the fact that functions that are declared to be pass-by-reference (using the &) aren't called using actual addresses, i.e. &a.

The simple answer is that declaring a function as pass-by-reference:

void foo(int& x);

is all we need. It's then passed by reference automatically.

You now call this function like so:

int y = 5;
foo(y);

and y will be passed by reference.

You could also do it like this (but why would you? The mantra is: Use references when possible, pointers when needed) :

#include <iostream>
using namespace std;

class CDummy {
public:
    int isitme (CDummy* param);
};


int CDummy::isitme (CDummy* param)
{
    if (param == this) return true;
    else return false;
}

int main () {
    CDummy a;
    CDummy* b = &a;             // assigning address of a to b
    if ( b->isitme(&a) )        // Called with &a (address of a) instead of a
        cout << "yes, &a is b";
    return 0;
}

Output:

yes, &a is b

Accessing variables from other functions without using global variables

Another approach is one that I picked up from a Douglas Crockford forum post(http://bytes.com/topic/javascript/answers/512361-array-objects). Here it is...

Douglas Crockford wrote:

Jul 15 '06

"If you want to retrieve objects by id, then you should use an object, not an array. Since functions are also objects, you could store the members in the function itself."

function objFacility(id, name, adr, city, state, zip) {

    return objFacility[id] = {

        id: id,
        name: name,
        adr: adr,
        city: city,
        state: state,
        zip: zip

    }
}

objFacility('wlevine', 'Levine', '23 Skid Row', 'Springfield', 'Il', 10010);

"The object can be obtained with"

objFacility.wlevine

The objects properties are now accessable from within any other function.

Entity Framework Query for inner join

from s in db.Services
join sa in db.ServiceAssignments on s.Id equals sa.ServiceId
where sa.LocationId == 1
select s

Where db is your DbContext. Generated query will look like (sample for EF6):

SELECT [Extent1].[Id] AS [Id]
       -- other fields from Services table
FROM [dbo].[Services] AS [Extent1]
INNER JOIN [dbo].[ServiceAssignments] AS [Extent2]
    ON [Extent1].[Id] = [Extent2].[ServiceId]
WHERE [Extent2].[LocationId] = 1

Selecting pandas column by location

You can also use df.icol(n) to access a column by integer.

Update: icol is deprecated and the same functionality can be achieved by:

df.iloc[:, n]  # to access the column at the nth position

React.js, wait for setState to finish before triggering a function?

setState() has an optional callback parameter that you can use for this. You only need to change your code slightly, to this:

// Form Input
this.setState(
  {
    originId: input.originId,
    destinationId: input.destinationId,
    radius: input.radius,
    search: input.search
  },
  this.findRoutes         // here is where you put the callback
);

Notice the call to findRoutes is now inside the setState() call, as the second parameter.
Without () because you are passing the function.

How to make audio autoplay on chrome

You could use <iframe src="link/to/file.mp3" allow="autoplay">, if the origin has an autoplay permission. More info here.

How to make a class JSON serializable

I see no mention here of serial versioning or backcompat, so I will post my solution which I've been using for a bit. I probably have a lot more to learn from, specifically Java and Javascript are probably more mature than me here but here goes

https://gist.github.com/andy-d/b7878d0044a4242c0498ed6d67fd50fe

TypeError: sequence item 0: expected string, int found

Replace

values = ",".join(value_list)

with

values = ','.join([str(i) for i in value_list])

OR

values = ','.join(str(value_list)[1:-1])

Hide div by default and show it on click with bootstrap

I realize this question is a bit dated and since it shows up on Google search for similar issue I thought I will expand a little bit more on top of @CowWarrior's answer. I was looking for somewhat similar solution, and after scouring through countless SO question/answers and Bootstrap documentations the solution was pretty simple. Again, this would be using inbuilt Bootstrap collapse class to show/hide divs and Bootstrap's "Collapse Event".

What I realized is that it is easy to do it using a Bootstrap Accordion, but most of the time even though the functionality required is "somewhat" similar to an Accordion, it's different in a way that one would want to show hide <div> based on, lets say, menu buttons on a navbar. Below is a simple solution to this. The anchor tags (<a>) could be navbar items and based on a collapse event the corresponding div will replace the existing div. It looks slightly sloppy in CodeSnippet, but it is pretty close to achieving the functionality-

All that the JavaScript does is makes all the other <div> hide using

$(".main-container.collapse").not($(this)).collapse('hide');

when the loaded <div> is displayed by checking the Collapse event shown.bs.collapse. Here's the Bootstrap documentation on Collapse Event.

Note: main-container is just a custom class.

Here it goes-

_x000D_
_x000D_
$(".main-container.collapse").on('shown.bs.collapse', function () {    _x000D_
//when a collapsed div is shown hide all other collapsible divs that are visible_x000D_
       $(".main-container.collapse").not($(this)).collapse('hide');_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>_x000D_
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
_x000D_
<a href="#Foo" class="btn btn-default" data-toggle="collapse">Toggle Foo</a>_x000D_
<a href="#Bar" class="btn btn-default" data-toggle="collapse">Toggle Bar</a>_x000D_
_x000D_
<div id="Bar" class="main-container collapse in">_x000D_
    This div (#Bar) is shown by default and can toggle_x000D_
</div>_x000D_
<div id="Foo" class="main-container collapse">_x000D_
    This div (#Foo) is hidden by default_x000D_
</div>
_x000D_
_x000D_
_x000D_

How to use "svn export" command to get a single file from the repository?

You don't have to do this locally either. You can do it through a remote repository, for example:

svn export http://<repo>/process/test.txt /path/to/code/

Histogram Matplotlib

If you're willing to use pandas:

pandas.DataFrame({'x':hist[1][1:],'y':hist[0]}).plot(x='x',kind='bar')

Symfony 2 EntityManager injection in service

For modern reference, in Symfony 2.4+, you cannot name the arguments for the Constructor Injection method anymore. According to the documentation You would pass in:

services:
    test.common.userservice:
        class:  Test\CommonBundle\Services\UserService
        arguments: [ "@doctrine.orm.entity_manager" ]

And then they would be available in the order they were listed via the arguments (if there are more than 1).

public function __construct(EntityManager $entityManager) {
    $this->em = $entityManager;
}

Executing a stored procedure within a stored procedure

T-SQL is not asynchronous, so you really have no choice but to wait until SP2 ends. Luckily, that's what you want.

CREATE PROCEDURE SP1 AS
   EXEC SP2
   PRINT 'Done'

How to automatically redirect HTTP to HTTPS on Apache servers?

Searched for apache redirect http to https and landed here. This is what i did on ubuntu:

1) Enable modules

sudo a2enmod rewrite
sudo a2enmod ssl

2) Edit your site config

Edit file

/etc/apache2/sites-available/000-default.conf

Content should be:

<VirtualHost *:80>
    RewriteEngine On
    RewriteCond %{HTTPS} off
    RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI}
</VirtualHost>

<VirtualHost *:443>
    SSLEngine on
    SSLCertificateFile    <path to your crt file>
    SSLCertificateKeyFile   <path to your private key file>

    # Rest of your site config
    # ...
</VirtualHost>

3) Restart apache2

sudo service apache2 restart

Remove All Event Listeners of Specific Type

 var events = [event_1, event_2,event_3]  // your events

//make a for loop of your events and remove them all in a single instance

 for (let i in events){
    canvas_1.removeEventListener("mousedown", events[i], false)
}