Programs & Examples On #Coin change

All problems (regardless of currency) with making change from a given amount of currency into a specific number of coins and bills of varying denominations.

How to find all combinations of coins when given some dollar value

This is the improvement of Zihan's answer. The great deal of unnecessary loops comes when the denomination is just 1 cent.

It's intuitive and non-recursive.

    public static int Ways2PayNCents(int n)
    {
        int numberOfWays=0;
        int cent, nickel, dime, quarter;
        for (quarter = 0; quarter <= n/25; quarter++)
        {
            for (dime = 0; dime <= n/10; dime++)
            {
                for (nickel = 0; nickel <= n/5; nickel++)
                {
                    cent = n - (quarter * 25 + dime * 10 + nickel * 5);
                    if (cent >= 0)
                    {
                        numberOfWays += 1;
                        Console.WriteLine("{0},{1},{2},{3}", quarter, dime, nickel, cent);
                    }                   
                }
            }
        }
        return numberOfWays;            
    }

How to stop mongo DB in one command

mongod --dbpath /path/to/your/db --shutdown

More info at official: http://docs.mongodb.org/manual/tutorial/manage-mongodb-processes/

Alternative to iFrames with HTML5

I created a node module to solve this problem node-iframe-replacement. You provide the source URL of the parent site and CSS selector to inject your content into and it merges the two together.

Changes to the parent site are picked up every 5 minutes.

var iframeReplacement = require('node-iframe-replacement');

// add iframe replacement to express as middleware (adds res.merge method) 
app.use(iframeReplacement);

// create a regular express route 
app.get('/', function(req, res){

    // respond to this request with our fake-news content embedded within the BBC News home page 
    res.merge('fake-news', {
        // external url to fetch 
       sourceUrl: 'http://www.bbc.co.uk/news',
       // css selector to inject our content into 
       sourcePlaceholder: 'div[data-entityid="container-top-stories#1"]',
       // pass a function here to intercept the source html prior to merging 
       transform: null
    });
});

The source contains a working example of injecting content into the BBC News home page.

How to change angular port from 4200 to any other

Just Run

ng serve --port yourport

Example:

ng serve --port 4401

How do you remove columns from a data.frame?

From http://www.statmethods.net/management/subset.html

# exclude variables v1, v2, v3
myvars <- names(mydata) %in% c("v1", "v2", "v3") 
newdata <- mydata[!myvars]

# exclude 3rd and 5th variable 
newdata <- mydata[c(-3,-5)]

# delete variables v3 and v5
mydata$v3 <- mydata$v5 <- NULL

Thought it was really clever make a list of "not to include"

Get epoch for a specific date using Javascript

Number(new Date(2010, 6, 26))

Works the same way as things above. If you need seconds don't forget to / 1000

Loading scripts after page load?

Here is a code I am using and which is working for me.

window.onload = function(){
    setTimeout(function(){
        var scriptElement=document.createElement('script');
        scriptElement.type = 'text/javascript';
        scriptElement.src = "vendor/js/jquery.min.js";
        document.head.appendChild(scriptElement);

        setTimeout(function() {
            var scriptElement1=document.createElement('script');
            scriptElement1.type = 'text/javascript';
            scriptElement1.src = "gallery/js/lc_lightbox.lite.min.js";
            document.head.appendChild(scriptElement1);
        }, 100);
        setTimeout(function() {
            $(document).ready(function(e){
                lc_lightbox('.elem', {
                    wrap_class: 'lcl_fade_oc',
                    gallery : true, 
                    thumb_attr: 'data-lcl-thumb', 
                    slideshow_time  : 3000,
                    skin: 'minimal',
                    radius: 0,
                    padding : 0,
                    border_w: 0,
                }); 
            });
        }, 200);

    }, 150);
};

What Does This Mean in PHP -> or =>

The double arrow operator, =>, is used as an access mechanism for arrays. This means that what is on the left side of it will have a corresponding value of what is on the right side of it in array context. This can be used to set values of any acceptable type into a corresponding index of an array. The index can be associative (string based) or numeric.

$myArray = array(
    0 => 'Big',
    1 => 'Small',
    2 => 'Up',
    3 => 'Down'
);

The object operator, ->, is used in object scope to access methods and properties of an object. It’s meaning is to say that what is on the right of the operator is a member of the object instantiated into the variable on the left side of the operator. Instantiated is the key term here.

// Create a new instance of MyObject into $obj
$obj = new MyObject();
// Set a property in the $obj object called thisProperty
$obj->thisProperty = 'Fred';
// Call a method of the $obj object named getProperty
$obj->getProperty();

Concatenate chars to form String in java

Use str = ""+a+b+c;

Here the first + is String concat, so the result will be a String. Note where the "" lies is important.

Or (maybe) better, use a StringBuilder.

importing a CSV into phpmyadmin

In phpMyAdmin, click the table, and then click the Import tab at the top of the page.

Browse and open the csv file. Leave the charset as-is. Uncheck partial import unless you have a HUGE dataset (or slow server). The format should already have selected “CSV” after selecting your file, if not then select it (not using LOAD DATA). If you want to clear the whole table before importing, check “Replace table data with file”. Optionally check “Ignore duplicate rows” if you think you have duplicates in the CSV file. Now the important part, set the next four fields to these values:

Fields terminated by: ,
Fields enclosed by: “
Fields escaped by: \
Lines terminated by: auto

Currently these match the defaults except for “Fields terminated by”, which defaults to a semicolon.

Now click the Go button, and it should run successfully.

Binary Search Tree - Java Implementation


Here is the complete Implementation of Binary Search Tree In Java insert,search,countNodes,traversal,delete,empty,maximum & minimum node,find parent node,print all leaf node, get level,get height, get depth,print left view, mirror view


import java.util.NoSuchElementException;
import java.util.Scanner;

import org.junit.experimental.max.MaxCore;

class BSTNode {

    BSTNode left = null;
    BSTNode rigth = null;
    int data = 0;

    public BSTNode() {
        super();
    }

    public BSTNode(int data) {
        this.left = null;
        this.rigth = null;
        this.data = data;
    }

    @Override
    public String toString() {
        return "BSTNode [left=" + left + ", rigth=" + rigth + ", data=" + data + "]";
    }

}


class BinarySearchTree {

    BSTNode root = null;

    public BinarySearchTree() {

    }

    public void insert(int data) {
        BSTNode node = new BSTNode(data);
        if (root == null) {
            root = node;
            return;
        }

        BSTNode currentNode = root;
        BSTNode parentNode = null;

        while (true) {
            parentNode = currentNode;
            if (currentNode.data == data)
                throw new IllegalArgumentException("Duplicates nodes note allowed in Binary Search Tree");

            if (currentNode.data > data) {
                currentNode = currentNode.left;
                if (currentNode == null) {
                    parentNode.left = node;
                    return;
                }
            } else {
                currentNode = currentNode.rigth;
                if (currentNode == null) {
                    parentNode.rigth = node;
                    return;
                }
            }
        }
    }

    public int countNodes() {
        return countNodes(root);
    }

    private int countNodes(BSTNode node) {
        if (node == null) {
            return 0;
        } else {
            int count = 1;
            count += countNodes(node.left);
            count += countNodes(node.rigth);
            return count;
        }
    }

    public boolean searchNode(int data) {
        if (empty())
            return empty();
        return searchNode(data, root);
    }

    public boolean searchNode(int data, BSTNode node) {
        if (node != null) {
            if (node.data == data)
                return true;
            else if (node.data > data)
                return searchNode(data, node.left);
            else if (node.data < data)
                return searchNode(data, node.rigth);
        }
        return false;
    }

    public boolean delete(int data) {
        if (empty())
            throw new NoSuchElementException("Tree is Empty");

        BSTNode currentNode = root;
        BSTNode parentNode = root;
        boolean isLeftChild = false;

        while (currentNode.data != data) {
            parentNode = currentNode;
            if (currentNode.data > data) {
                isLeftChild = true;
                currentNode = currentNode.left;
            } else if (currentNode.data < data) {
                isLeftChild = false;
                currentNode = currentNode.rigth;
            }
            if (currentNode == null)
                return false;
        }

        // CASE 1: node with no child
        if (currentNode.left == null && currentNode.rigth == null) {
            if (currentNode == root)
                root = null;
            if (isLeftChild)
                parentNode.left = null;
            else
                parentNode.rigth = null;
        }

        // CASE 2: if node with only one child
        else if (currentNode.left != null && currentNode.rigth == null) {
            if (root == currentNode) {
                root = currentNode.left;
            }
            if (isLeftChild)
                parentNode.left = currentNode.left;
            else
                parentNode.rigth = currentNode.left;
        } else if (currentNode.rigth != null && currentNode.left == null) {
            if (root == currentNode)
                root = currentNode.rigth;
            if (isLeftChild)
                parentNode.left = currentNode.rigth;
            else
                parentNode.rigth = currentNode.rigth;
        }

        // CASE 3: node with two child
        else if (currentNode.left != null && currentNode.rigth != null) {

            // Now we have to find minimum element in rigth sub tree
            // that is called successor
            BSTNode successor = getSuccessor(currentNode);
            if (currentNode == root)
                root = successor;
            if (isLeftChild)
                parentNode.left = successor;
            else
                parentNode.rigth = successor;
            successor.left = currentNode.left;
        }

        return true;
    }

    private BSTNode getSuccessor(BSTNode deleteNode) {

        BSTNode successor = null;
        BSTNode parentSuccessor = null;
        BSTNode currentNode = deleteNode.left;

        while (currentNode != null) {
            parentSuccessor = successor;
            successor = currentNode;
            currentNode = currentNode.left;
        }

        if (successor != deleteNode.rigth) {
            parentSuccessor.left = successor.left;
            successor.rigth = deleteNode.rigth;
        }

        return successor;
    }

    public int nodeWithMinimumValue() {
        return nodeWithMinimumValue(root);
    }

    private int nodeWithMinimumValue(BSTNode node) {
        if (node.left != null)
            return nodeWithMinimumValue(node.left);
        return node.data;
    }

    public int nodewithMaximumValue() {
        return nodewithMaximumValue(root);
    }

    private int nodewithMaximumValue(BSTNode node) {
        if (node.rigth != null)
            return nodewithMaximumValue(node.rigth);
        return node.data;
    }

    public int parent(int data) {
        return parent(root, data);
    }

    private int parent(BSTNode node, int data) {
        if (empty())
            throw new IllegalArgumentException("Empty");
        if (root.data == data)
            throw new IllegalArgumentException("No Parent node found");

        BSTNode parent = null;
        BSTNode current = node;

        while (current.data != data) {
            parent = current;
            if (current.data > data)
                current = current.left;
            else
                current = current.rigth;
            if (current == null)
                throw new IllegalArgumentException(data + " is not a node in tree");
        }
        return parent.data;
    }

    public int sibling(int data) {
        return sibling(root, data);
    }

    private int sibling(BSTNode node, int data) {
        if (empty())
            throw new IllegalArgumentException("Empty");
        if (root.data == data)
            throw new IllegalArgumentException("No Parent node found");

        BSTNode cureent = node;
        BSTNode parent = null;
        boolean isLeft = false;

        while (cureent.data != data) {
            parent = cureent;
            if (cureent.data > data) {
                cureent = cureent.left;
                isLeft = true;
            } else {
                cureent = cureent.rigth;
                isLeft = false;
            }
            if (cureent == null)
                throw new IllegalArgumentException("No Parent node found");
        }
        if (isLeft) {
            if (parent.rigth != null) {
                return parent.rigth.data;
            } else
                throw new IllegalArgumentException("No Sibling is there");
        } else {
            if (parent.left != null)
                return parent.left.data;
            else
                throw new IllegalArgumentException("No Sibling is there");
        }
    }

    public void leafNodes() {
        if (empty())
            throw new IllegalArgumentException("Empty");
        leafNode(root);
    }

    private void leafNode(BSTNode node) {
        if (node == null)
            return;
        if (node.rigth == null && node.left == null)
            System.out.print(node.data + " ");
        leafNode(node.left);
        leafNode(node.rigth);
    }

    public int level(int data) {
        if (empty())
            throw new IllegalArgumentException("Empty");
        return level(root, data, 1);
    }

    private int level(BSTNode node, int data, int level) {
        if (node == null)
            return 0;
        if (node.data == data)
            return level;
        int result = level(node.left, data, level + 1);
        if (result != 0)
            return result;
        result = level(node.rigth, data, level + 1);
        return result;
    }

    public int depth() {
        return depth(root);
    }

    private int depth(BSTNode node) {
        if (node == null)
            return 0;
        else
            return 1 + Math.max(depth(node.left), depth(node.rigth));
    }

    public int height() {
        return height(root);
    }

    private int height(BSTNode node) {
        if (node == null)
            return 0;
        else
            return 1 + Math.max(height(node.left), height(node.rigth));
    }

    public void leftView() {
        leftView(root);
    }

    private void leftView(BSTNode node) {
        if (node == null)
            return;
        int height = height(node);

        for (int i = 1; i <= height; i++) {
            printLeftView(node, i);
        }
    }

    private boolean printLeftView(BSTNode node, int level) {
        if (node == null)
            return false;

        if (level == 1) {
            System.out.print(node.data + " ");
            return true;
        } else {
            boolean left = printLeftView(node.left, level - 1);
            if (left)
                return true;
            else
                return printLeftView(node.rigth, level - 1);
        }
    }

    public void mirroeView() {
        BSTNode node = mirroeView(root);
        preorder(node);
        System.out.println();
        inorder(node);
        System.out.println();
        postorder(node);
        System.out.println();
    }

    private BSTNode mirroeView(BSTNode node) {
        if (node == null || (node.left == null && node.rigth == null))
            return node;

        BSTNode temp = node.left;
        node.left = node.rigth;
        node.rigth = temp;

        mirroeView(node.left);
        mirroeView(node.rigth);
        return node;
    }

    public void preorder() {
        preorder(root);
    }

    private void preorder(BSTNode node) {
        if (node != null) {
            System.out.print(node.data + " ");
            preorder(node.left);
            preorder(node.rigth);
        }
    }

    public void inorder() {
        inorder(root);
    }

    private void inorder(BSTNode node) {
        if (node != null) {
            inorder(node.left);
            System.out.print(node.data + " ");
            inorder(node.rigth);
        }
    }

    public void postorder() {
        postorder(root);
    }

    private void postorder(BSTNode node) {
        if (node != null) {
            postorder(node.left);
            postorder(node.rigth);
            System.out.print(node.data + " ");
        }
    }

    public boolean empty() {
        return root == null;
    }

}

public class BinarySearchTreeTest {
    public static void main(String[] l) {
        System.out.println("Weleome to Binary Search Tree");
        Scanner scanner = new Scanner(System.in);
        boolean yes = true;
        BinarySearchTree tree = new BinarySearchTree();
        do {
            System.out.println("\n1. Insert");
            System.out.println("2. Search Node");
            System.out.println("3. Count Node");
            System.out.println("4. Empty Status");
            System.out.println("5. Delete Node");
            System.out.println("6. Node with Minimum Value");
            System.out.println("7. Node with Maximum Value");
            System.out.println("8. Find Parent node");
            System.out.println("9. Count no of links");
            System.out.println("10. Get the sibling of any node");
            System.out.println("11. Print all the leaf node");
            System.out.println("12. Get the level of node");
            System.out.println("13. Depth of the tree");
            System.out.println("14. Height of Binary Tree");
            System.out.println("15. Left View");
            System.out.println("16. Mirror Image of Binary Tree");
            System.out.println("Enter Your Choice :: ");
            int choice = scanner.nextInt();
            switch (choice) {
            case 1:
                try {
                    System.out.println("Enter Value");
                    tree.insert(scanner.nextInt());
                } catch (Exception e) {
                    System.out.println(e.getMessage());
                }
                break;

            case 2:
                System.out.println("Enter the node");
                System.out.println(tree.searchNode(scanner.nextInt()));
                break;

            case 3:
                System.out.println(tree.countNodes());
                break;

            case 4:
                System.out.println(tree.empty());
                break;

            case 5:
                try {
                    System.out.println("Enter the node");
                    System.out.println(tree.delete(scanner.nextInt()));
                } catch (Exception e) {
                    System.out.println(e.getMessage());
                }

            case 6:
                try {
                    System.out.println(tree.nodeWithMinimumValue());
                } catch (Exception e) {
                    System.out.println(e.getMessage());
                }
                break;

            case 7:
                try {
                    System.out.println(tree.nodewithMaximumValue());
                } catch (Exception e) {
                    System.out.println(e.getMessage());
                }
                break;

            case 8:
                try {
                    System.out.println("Enter the node");
                    System.out.println(tree.parent(scanner.nextInt()));
                } catch (Exception e) {
                    System.out.println(e.getMessage());
                }
                break;

            case 9:
                try {
                    System.out.println(tree.countNodes() - 1);
                } catch (Exception e) {
                    System.out.println(e.getMessage());
                }
                break;

            case 10:
                try {
                    System.out.println("Enter the node");
                    System.out.println(tree.sibling(scanner.nextInt()));
                } catch (Exception e) {
                    System.out.println(e.getMessage());
                }
                break;

            case 11:
                try {
                    tree.leafNodes();
                } catch (Exception e) {
                    System.out.println(e.getMessage());
                }

            case 12:
                try {
                    System.out.println("Enter the node");
                    System.out.println("Level is : " + tree.level(scanner.nextInt()));
                } catch (Exception e) {
                    System.out.println(e.getMessage());
                }
                break;

            case 13:
                try {
                    System.out.println(tree.depth());
                } catch (Exception e) {
                    System.out.println(e.getMessage());
                }
                break;

            case 14:
                try {
                    System.out.println(tree.height());
                } catch (Exception e) {
                    System.out.println(e.getMessage());
                }
                break;

            case 15:
                try {
                    tree.leftView();
                    System.out.println();
                } catch (Exception e) {
                    System.out.println(e.getMessage());
                }
                break;

            case 16:
                try {
                    tree.mirroeView();
                } catch (Exception e) {
                    System.out.println(e.getMessage());
                }
                break;

            default:
                break;
            }
            tree.preorder();
            System.out.println();
            tree.inorder();
            System.out.println();
            tree.postorder();
        } while (yes);
        scanner.close();
    }
}

Easier way to create circle div than using an image?

You can use radius but it will not work on IE: border-radius: 5px 5px;.

How to get a value inside an ArrayList java

The list may contain several elements, so the get method takes an argument : the index of the element you want to retrieve. If you want the first one, then it's 0.

The list contains Car instances, so you just have to do

Car firstCar = car.get(0);
String price = firstCar.getPrice();

or just

String price = car.get(0).getPrice();

The car variable should be named cars, since it's a list and thus contains several cars.

Read the tutorial about collections. And learn to use the javadoc: all the classes and methods are documented.

JCheckbox - ActionListener and ItemListener?

I've been testing this myself, and looking at all the answers on this post and I don't think they answer this question very well. I experimented myself in order to get a good answer (code below). You CAN fire either event with both ActionListener and ItemListener 100% of the time when a state is changed in either a radio button or a check box, or any other kind of Swing item I'm assuming since it is type Object. The ONLY difference I can tell between these two listeners is the type of Event Object that gets returned with the listener is different. AND you get a better event type with a checkbox using an ItemListener as opposed to an ActionListener.

The return types of an ActionEvent and an ItemEvent will have different methods stored that may be used when an Event Type gets fired. In the code below the comments show the difference in .get methods for each Class returned Event type.

The code below sets up a simple JPanel with JRadioButtons, JCheckBoxes, and a JLabel display that changes based on button configs. I set all the RadioButtons and CheckBoxes up with both an Action Listener and an Item Listener. Then I wrote the Listener classes below with ActionListener fully commented because I tested it first in this experiment. You will notice that if you add this panel to a frame and display, all radiobuttons and checkboxes always fire regardless of the Listener type, just comment out the methods in one and try the other and vice versa.

Return Type into the implemented methods is the MAIN difference between the two. Both Listeners fire events the same way. Explained a little better in comment above is the reason a checkbox should use an ItemListener over ActionListener due to the Event type that is returned.

package EventHandledClasses;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class RadioButtonsAndCheckBoxesTest extends JPanel{
JLabel display;
String funny, serious, political;
JCheckBox bold,italic;
JRadioButton funnyQuote, seriousQuote, politicalQuote;
ButtonGroup quotes;

    public RadioButtonsAndCheckBoxesTest(){
        funny = "You are not ugly, you were just born... different";
        serious = "Recommend powdered soap in prison!";
        political = "Trump can eat a little Bernie, but will choke on his     Birdie";

        display = new JLabel(funny);
        Font defaultFont = new Font("Ariel",Font.PLAIN,20);
        display.setFont(defaultFont);

        bold = new JCheckBox("Bold",false);
        bold.setOpaque(false);
        italic = new JCheckBox("Italic",false);
        italic.setOpaque(false);

        //Color itemBackground =

        funnyQuote = new JRadioButton("Funny",true);
        funnyQuote.setOpaque(false);
        seriousQuote = new JRadioButton("Serious");
        seriousQuote.setOpaque(false);
        politicalQuote = new JRadioButton("Political");
        politicalQuote.setOpaque(false);

        quotes = new ButtonGroup();
        quotes.add(funnyQuote);
        quotes.add(seriousQuote);
        quotes.add(politicalQuote);

        JPanel primary = new JPanel();
        primary.setPreferredSize(new Dimension(550, 100));

        Dimension standard = new Dimension(500, 30);

        JPanel radioButtonsPanel = new JPanel();
        radioButtonsPanel.setPreferredSize(standard);
        radioButtonsPanel.setBackground(Color.green);
        radioButtonsPanel.add(funnyQuote);
        radioButtonsPanel.add(seriousQuote);
        radioButtonsPanel.add(politicalQuote);

        JPanel checkBoxPanel = new JPanel();
        checkBoxPanel.setPreferredSize(standard);
        checkBoxPanel.setBackground(Color.green);
        checkBoxPanel.add(bold);
        checkBoxPanel.add(italic);

        primary.add(display);
        primary.add(radioButtonsPanel);
        primary.add(checkBoxPanel);

        //Add Action Listener To test Radio Buttons
        funnyQuote.addActionListener(new ActionListen());
        seriousQuote.addActionListener(new ActionListen());
        politicalQuote.addActionListener(new ActionListen());

        //Add Item Listener to test Radio Buttons
        funnyQuote.addItemListener(new ItemListen());
        seriousQuote.addItemListener(new ItemListen());
        politicalQuote.addItemListener(new ItemListen());

        //Add Action Listener to test Check Boxes
        bold.addActionListener(new ActionListen());
        italic.addActionListener(new ActionListen());

        //Add Item Listener to test Check Boxes
        bold.addItemListener(new ItemListen());
        italic.addItemListener(new ItemListen());

        //adds primary JPanel to this JPanel Object
        add(primary);   
    }

    private class ActionListen implements ActionListener{

        public void actionPerformed(ActionEvent e) {

         /*
         Different Get Methods from  ItemEvent 
         e.getWhen()
         e.getModifiers()
         e.getActionCommand()*/

            /*int font=Font.PLAIN;
            if(bold.isSelected()){
                font += Font.BOLD;
            }
            if(italic.isSelected()){
                font += Font.ITALIC;
            }
            display.setFont(new Font("Ariel",font,20));

            if(funnyQuote.isSelected()){
                display.setText(funny);
            }
            if(seriousQuote.isSelected()){
                display.setText(serious);
            }
            if(politicalQuote.isSelected()){
                display.setText(political);
            }*/
        }
    }
    private class ItemListen implements ItemListener {

        public void itemStateChanged(ItemEvent arg0) {

            /*
            Different Get Methods from ActionEvent
            arg0.getItemSelectable()
            arg0.getStateChange()
            arg0.getItem()*/


            int font=Font.PLAIN;
            if(bold.isSelected()){
                font += Font.BOLD;
            }
            if(italic.isSelected()){
                font += Font.ITALIC;
            }
            display.setFont(new Font("Ariel",font,20));

            if(funnyQuote.isSelected()){
                display.setText(funny);
            }
            if(seriousQuote.isSelected()){
                display.setText(serious);
            }
            if(politicalQuote.isSelected()){
                display.setText(political);
            }

        }

    }
}

Access nested dictionary items via a list of keys?

Use reduce() to traverse the dictionary:

from functools import reduce  # forward compatibility for Python 3
import operator

def getFromDict(dataDict, mapList):
    return reduce(operator.getitem, mapList, dataDict)

and reuse getFromDict to find the location to store the value for setInDict():

def setInDict(dataDict, mapList, value):
    getFromDict(dataDict, mapList[:-1])[mapList[-1]] = value

All but the last element in mapList is needed to find the 'parent' dictionary to add the value to, then use the last element to set the value to the right key.

Demo:

>>> getFromDict(dataDict, ["a", "r"])
1
>>> getFromDict(dataDict, ["b", "v", "y"])
2
>>> setInDict(dataDict, ["b", "v", "w"], 4)
>>> import pprint
>>> pprint.pprint(dataDict)
{'a': {'r': 1, 's': 2, 't': 3},
 'b': {'u': 1, 'v': {'w': 4, 'x': 1, 'y': 2, 'z': 3}, 'w': 3}}

Note that the Python PEP8 style guide prescribes snake_case names for functions. The above works equally well for lists or a mix of dictionaries and lists, so the names should really be get_by_path() and set_by_path():

from functools import reduce  # forward compatibility for Python 3
import operator

def get_by_path(root, items):
    """Access a nested object in root by item sequence."""
    return reduce(operator.getitem, items, root)

def set_by_path(root, items, value):
    """Set a value in a nested object in root by item sequence."""
    get_by_path(root, items[:-1])[items[-1]] = value

And for completion's sake, a function to delete a key:

def del_by_path(root, items):
    """Delete a key-value in a nested object in root by item sequence."""
    del get_by_path(root, items[:-1])[items[-1]]

Calling a particular PHP function on form submit

Assuming that your script is named x.php, try this

<?php 
   function display($s) {
      echo $s;
   }
?>
<html>
    <body>
        <form method="post" action="x.php">
            <input type="text" name="studentname">
            <input type="submit" value="click">
        </form>
        <?php
           if($_SERVER['REQUEST_METHOD']=='POST')
           {
               display();
           } 
        ?>
    </body>
</html>

Posting JSON Data to ASP.NET MVC

If you've got ther JSON data coming in as a string (e.g. '[{"id":1,"name":"Charles"},{"id":8,"name":"John"},{"id":13,"name":"Sally"}]')

Then I'd use JSON.net and use Linq to JSON to get the values out...

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{

    if (Request["items"] != null)
    {
        var items = Request["items"].ToString(); // Get the JSON string
        JArray o = JArray.Parse(items); // It is an array so parse into a JArray
        var a = o.SelectToken("[0].name").ToString(); // Get the name value of the 1st object in the array
        // a == "Charles"
    }
}
}

How to manipulate arrays. Find the average. Beginner Java

Using an enhanced for would be even nicer:

int sum = 0;
for (int d : data) sum += d;

Another thing that will probably give you a big surprise is the wrong result that you will obtain from

double average = sum / data.length;

Reason: on the right-hand side you have integer division and Java will not automatically promote it to floating-point division. It will calculate the integer quotient of sum/data.length and only then promote that integer to a double. A solution would be

double average = 1.0d * sum / data.length;

This will force the dividend into a double, which will automatically propagate to the divisor.

Refused to execute script, strict MIME type checking is enabled?

After searching for a while I realized that this error in my Windows 10 64 bits was related to JavaScript. In order to see this go to your browser DevTools and confirm that first. In my case it shows an error like "MIME type ('application/javascript') is not executable".

If that is the case I've found a solution. Here's the deal:

  1. Borrowing user "ilango100" on https://github.com/jupyterlab/jupyterlab/issues/6098:

I had the exact same issue a while ago. I think this issue is specific to Windows. It is due to the wrong MIME type being set in Windows registry for javascript files. I solved the issue by editing the Windows registry with correct content type:

regedit -> HKEY_LOCAL_MACHINE\Software\Classes -> You will see lot of folders for each file extension -> Just scroll down to ".js" registry and select it -> On the right, if the "Content Type" value is other than application/javascript, then this is causing the problem. Right click on Content Type and change the value to application/javascript

enter image description here

Try again in the browser."

After that I've realized that the error changes. It doesn't even open automatically in the browser anymore. PGAdmin, however, will be open on the side bar (close to the calendar/clock). By trying to open in the browser directly ("New PGAdmin 4 window...") it doesn't work either.

FINAL SOLUTION: click on "Copy server URL" and paste it on your browser. It worked for me!

EDIT: Copying server URL might not be necessary, as explained by Eric Mutta in the comment below.

How do you remove an invalid remote branch reference from Git?

All you need to do is

$ git branch -rd origin/whatever 

It's that simple. There is no reason to call a gc here.

Display all views on oracle database

SELECT * 
FROM DBA_OBJECTS  
WHERE OBJECT_TYPE = 'VIEW'

Make the first character Uppercase in CSS

<script type="text/javascript">
     $(document).ready(function() {
     var asdf = $('.capsf').text();

    $('.capsf').text(asdf.toLowerCase());
     });
     </script>
<div style="text-transform: capitalize;"  class="capsf">sd GJHGJ GJHgjh gh hghhjk ku</div>

Angular 2 / 4 / 5 - Set base href dynamically

In package.json set flag --base-href to relative path:

"script": {
    "build": "ng build --base-href ./"
}

How do I get the current date in Cocoa

You must use the following:

NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *dateComponents = [gregorian components:(NSHourCalendarUnit  | NSMinuteCalendarUnit | NSSecondCalendarUnit) fromDate:yourDateHere];
NSInteger hour = [dateComponents hour];
NSInteger minute = [dateComponents minute];
NSInteger second = [dateComponents second];
[gregorian release];

There is no difference between NSDate* now and NSDate *now, it's just a matter of preference. From the compiler perspective, nothing changes.

How do I create an average from a Ruby array?

Ruby versions >= 2.4 has an Enumerable#sum method.

And to get floating point average, you can use Integer#fdiv

arr = [0,4,8,2,5,0,2,6]

arr.sum.fdiv(arr.size)
# => 3.375

For older versions:

arr.reduce(:+).fdiv(arr.size)
# => 3.375

How to find substring from string?

As user1511510 has identified, there's an unusual case when abc is at the end of the file name. We need to look for either /abc/ or /abc followed by a string-terminator '\0'. A naive way to do this would be to check if either /abc/ or /abc\0 are substrings:

#include <stdio.h>
#include <string.h>

int main() {
    const char *str = "/user/desktop/abc";
    const int exists = strstr(str, "/abc/") || strstr(str, "/abc\0");
    printf("%d\n",exists);
    return 0;
}

but exists will be 1 even if abc is not followed by a null-terminator. This is because the string literal "/abc\0" is equivalent to "/abc". A better approach is to test if /abc is a substring, and then see if the character after this substring (indexed using the pointer returned by strstr()) is either a / or a '\0':

#include <stdio.h>
#include <string.h>

int main() {
    const char *str = "/user/desktop/abc", *substr;
    const int exists = (substr = strstr(str, "/abc")) && (substr[4] == '\0' || substr[4] == '/');
    printf("%d\n",exists);
    return 0;
}

This should work in all cases.

Invert "if" statement to reduce nesting

The idea of only returning at the end of a function came back from the days before languages had support for exceptions. It enabled programs to rely on being able to put clean-up code at the end of a method, and then being sure it would be called and some other programmer wouldn't hide a return in the method that caused the cleanup code to be skipped. Skipped cleanup code could result in a memory or resource leak.

However, in a language that supports exceptions, it provides no such guarantees. In a language that supports exceptions, the execution of any statement or expression can cause a control flow that causes the method to end. This means clean-up must be done through using the finally or using keywords.

Anyway, I'm saying I think a lot of people quote the 'only return at the end of a method' guideline without understanding why it was ever a good thing to do, and that reducing nesting to improve readability is probably a better aim.

Wget output document and headers to STDOUT

It works here:

    $ wget -S -O - http://google.com
HTTP request sent, awaiting response... 
  HTTP/1.1 301 Moved Permanently
  Location: http://www.google.com/
  Content-Type: text/html; charset=UTF-8
  Date: Sat, 25 Aug 2012 10:15:38 GMT
  Expires: Mon, 24 Sep 2012 10:15:38 GMT
  Cache-Control: public, max-age=2592000
  Server: gws
  Content-Length: 219
  X-XSS-Protection: 1; mode=block
  X-Frame-Options: SAMEORIGIN
Location: http://www.google.com/ [following]
--2012-08-25 12:20:29--  http://www.google.com/
Resolving www.google.com (www.google.com)... 173.194.69.99, 173.194.69.104, 173.194.69.106, ...

  ...skipped a few more redirections ...

    [<=>                                                                                                                                     ] 0           --.-K/s              
<!doctype html><html itemscope="itemscope" itemtype="http://schema.org/WebPage"><head><meta itemprop="image" content="/images/google_favicon_128.png"><ti 

... skipped ...

perhaps you need to update your wget (~$ wget --version GNU Wget 1.14 built on linux-gnu.)

Which characters make a URL invalid?

To add some clarification and directly address the question above, there are several classes of characters that cause problems for URLs and URIs.

There are some characters that are disallowed and should never appear in a URL/URI, reserved characters (described below), and other characters that may cause problems in some cases, but are marked as "unwise" or "unsafe". Explanations for why the characters are restricted are clearly spelled out in RFC-1738 (URLs) and RFC-2396 (URIs). Note the newer RFC-3986 (update to RFC-1738) defines the construction of what characters are allowed in a given context but the older spec offers a simpler and more general description of which characters are not allowed with the following rules.

Excluded US-ASCII Characters disallowed within the URI syntax:

   control     = <US-ASCII coded characters 00-1F and 7F hexadecimal>
   space       = <US-ASCII coded character 20 hexadecimal>
   delims      = "<" | ">" | "#" | "%" | <">

The character "#" is excluded because it is used to delimit a URI from a fragment identifier. The percent character "%" is excluded because it is used for the encoding of escaped characters. In other words, the "#" and "%" are reserved characters that must be used in a specific context.

List of unwise characters are allowed but may cause problems:

   unwise      = "{" | "}" | "|" | "\" | "^" | "[" | "]" | "`"

Characters that are reserved within a query component and/or have special meaning within a URI/URL:

  reserved    = ";" | "/" | "?" | ":" | "@" | "&" | "=" | "+" | "$" | ","

The "reserved" syntax class above refers to those characters that are allowed within a URI, but which may not be allowed within a particular component of the generic URI syntax. Characters in the "reserved" set are not reserved in all contexts. The hostname, for example, can contain an optional username so it could be something like ftp://user@hostname/ where the '@' character has special meaning.

Here is an example of a URL that has invalid and unwise characters (e.g. '$', '[', ']') and should be properly encoded:

http://mw1.google.com/mw-earth-vectordb/kml-samples/gp/seattle/gigapxl/$[level]/r$[y]_c$[x].jpg

Some of the character restrictions for URIs and URLs are programming language-dependent. For example, the '|' (0x7C) character although only marked as "unwise" in the URI spec will throw a URISyntaxException in the Java java.net.URI constructor so a URL like http://api.google.com/q?exp=a|b is not allowed and must be encoded instead as http://api.google.com/q?exp=a%7Cb if using Java with a URI object instance.

How to get Android crash logs?

If your app is being downloaded by other people and crashing on remote devices, you may want to look into an Android error reporting library (referenced in this SO post). If it's just on your own local device, you can use LogCat. Even if the device wasn't connected to a host machine when the crash occurred, connecting the device and issuing an adb logcat command will download the entire logcat history (at least to the extent that it is buffered which is usually a loooot of log data, it's just not infinite). Do either of those options answer your question? If not can you attempt to clarify what you're looking for a bit more?

Best HTTP Authorization header type for JWT

Short answer

The Bearer authentication scheme is what you are looking for.

Long answer

Is it related to bears?

Errr... No :)

According to the Oxford Dictionaries, here's the definition of bearer:

bearer /'b??r?/
noun

  1. A person or thing that carries or holds something.

  2. A person who presents a cheque or other order to pay money.

The first definition includes the following synonyms: messenger, agent, conveyor, emissary, carrier, provider.

And here's the definition of bearer token according to the RFC 6750:

1.2. Terminology

Bearer Token

A security token with the property that any party in possession of the token (a "bearer") can use the token in any way that any other party in possession of it can. Using a bearer token does not require a bearer to prove possession of cryptographic key material (proof-of-possession).

The Bearer authentication scheme is registered in IANA and originally defined in the RFC 6750 for the OAuth 2.0 authorization framework, but nothing stops you from using the Bearer scheme for access tokens in applications that don't use OAuth 2.0.

Stick to the standards as much as you can and don't create your own authentication schemes.


An access token must be sent in the Authorization request header using the Bearer authentication scheme:

2.1. Authorization Request Header Field

When sending the access token in the Authorization request header field defined by HTTP/1.1, the client uses the Bearer authentication scheme to transmit the access token.

For example:

GET /resource HTTP/1.1
Host: server.example.com
Authorization: Bearer mF_9.B5f-4.1JqM

[...]

Clients SHOULD make authenticated requests with a bearer token using the Authorization request header field with the Bearer HTTP authorization scheme. [...]

In case of invalid or missing token, the Bearer scheme should be included in the WWW-Authenticate response header:

3. The WWW-Authenticate Response Header Field

If the protected resource request does not include authentication credentials or does not contain an access token that enables access to the protected resource, the resource server MUST include the HTTP WWW-Authenticate response header field [...].

All challenges defined by this specification MUST use the auth-scheme value Bearer. This scheme MUST be followed by one or more auth-param values. [...].

For example, in response to a protected resource request without authentication:

HTTP/1.1 401 Unauthorized
WWW-Authenticate: Bearer realm="example"

And in response to a protected resource request with an authentication attempt using an expired access token:

HTTP/1.1 401 Unauthorized
WWW-Authenticate: Bearer realm="example",
                         error="invalid_token",
                         error_description="The access token expired"

Are (non-void) self-closing tags valid in HTML5?

In practice, using self-closing tags in HTML should work just like you'd expect. But if you are concerned about writing valid HTML5, you should understand how the use of such tags behaves within the two different two syntax forms you can use. HTML5 defines both an HTML syntax and an XHTML syntax, which are similar but not identical. Which one is used depends on the media type sent by the web server.

More than likely, your pages are being served as text/html, which follows the more lenient HTML syntax. In these cases, HTML5 allows certain start tags to have an optional / before it's terminating >. In these cases, the / is optional and ignored, so <hr> and <hr /> are identical. The HTML spec calls these "void elements", and gives a list of valid ones. Strictly speaking, the optional / is only valid within the start tags of these void elements; for example, <br /> and <hr /> are valid HTML5, but <p /> is not.

The HTML5 spec makes a clear distinction between what is correct for HTML authors and for web browser developers, with the second group being required to accept all kinds of invalid "legacy" syntax. In this case, it means that HTML5-compliant browsers will accept illegal self-closed tags, like <p />, and render them as you probably expect. But for an author, that page would not be valid HTML5. (More importantly, the DOM tree you get from using this kind of illegal syntax can be seriously screwed up; self-closed <span /> tags, for example, tend to mess things up a lot).

(In the unusual case that your server knows how to send XHTML files as an XML MIME type, the page needs to conform to the XHTML DTD and XML syntax. That means self-closing tags are required for those elements defined as such.)

How to refer to Excel objects in Access VBA?

Inside a module

Option Explicit
dim objExcelApp as Excel.Application
dim wb as Excel.Workbook

sub Initialize()
   set objExcelApp = new Excel.Application
end sub

sub ProcessDataWorkbook()
    dim ws as Worksheet
    set wb = objExcelApp.Workbooks.Open("path to my workbook")
    set ws = wb.Sheets(1)

    ws.Cells(1,1).Value = "Hello"
    ws.Cells(1,2).Value = "World"

    'Close the workbook
    wb.Close
    set wb = Nothing
end sub

sub Release()
   set objExcelApp = Nothing
end sub

Setting Django up to use MySQL

To the very first please run the below commands to install python dependencies otherwise python runserver command will throw error.

sudo apt-get install libmysqlclient-dev
sudo pip install MySQL-python

Then configure the settings.py file as defined by #Andy and at the last execute :

python manage.py runserver

Have fun..!!

How to deal with certificates using Selenium?

    ChromeOptions options = new ChromeOptions().addArguments("--proxy-server=http://" + proxy);
    options.setAcceptInsecureCerts(true);

Upgrading PHP on CentOS 6.5 (Final)

For CentOS 6, PHP 5.3.3 is the latest version of PHP available through the official CentOS package repository. Keep in mind, even though PHP 5.3.3 was released July 22, 2010, the official CentOS 6 PHP package was updated November 24, 2013. Why? Critical bug fixes are backported. See this question for more information: "Why are outdated packages installed by yum on CentOS? (specifically PHP 5.1) How to fix?"

If you'd like to use a more recent version of PHP, Les RPM de Remi offers CentOS PHP packages via a repository that you can add to the yum package manager. To add it as a yum repository, follow the site's instructions.

Note: Questions of this variety are probably better suited for Server Fault.

How do I use popover from Twitter Bootstrap to display an image?

Sort of similar to what mattbtay said, but a few changes. needed html:true.
Put this script on bottom of the page towards close body tag.

<script type="text/javascript">
 $(document).ready(function() {
  $("[rel=drevil]").popover({
      placement : 'bottom', //placement of the popover. also can use top, bottom, left or right
      title : '<div style="text-align:center; color:red; text-decoration:underline; font-size:14px;"> Muah ha ha</div>', //this is the top title bar of the popover. add some basic css
      html: 'true', //needed to show html of course
      content : '<div id="popOverBox"><img src="http://www.hd-report.com/wp-content/uploads/2008/08/mr-evil.jpg" width="251" height="201" /></div>' //this is the content of the html box. add the image here or anything you want really.
});
});
</script>


Then HTML is:

<a href="#" rel="drevil">mischief</a>

How to display .svg image using swift

You can use SVGKit for example.

1) Integrate it according to instructions. Drag&dropping the .framework file is fast and easy.

2) Make sure you have an Objective-C to Swift bridge file bridging-header.h with import code in it:

#import <SVGKit/SVGKit.h>
#import <SVGKit/SVGKImage.h>

3) Use the framework like this, assuming that dataFromInternet is NSData, previously downloaded from network:

let anSVGImage: SVGKImage = SVGKImage(data: dataFromInternet)
myIUImageView.image = anSVGImage.UIImage

The framework also allows to init an SVGKImage from other different sources, for example it can download image for you when you provide it with URL. But in my case it was crashing in case of unreachable url, so it turned out to be better to manage networking by myself. More info on it here.

Immutable array in Java

As of Java 9 you can use List.of(...), JavaDoc.

This method returns an immutable List and is very efficient.

PSQLException: current transaction is aborted, commands ignored until end of transaction block

In Ruby on Rails PG, I had created a migration, migrated my DB, but forgot to restart my development server. I restarted my server and it worked.

Python - A keyboard command to stop infinite loop?

Ctrl+C is what you need. If it didn't work, hit it harder. :-) Of course, you can also just close the shell window.

Edit: You didn't mention the circumstances. As a last resort, you could write a batch file that contains taskkill /im python.exe, and put it on your desktop, Start menu, etc. and run it when you need to kill a runaway script. Of course, it will kill all Python processes, so be careful.

Create pandas Dataframe by appending one row at a time

This is not an answer to the OP question but a toy example to illustrate the answer of @ShikharDua above which I found very useful.

While this fragment is trivial, in the actual data I had 1,000s of rows, and many columns, and I wished to be able to group by different columns and then perform the stats below for more than one taget column. So having a reliable method for building the data frame one row at a time was a great convenience. Thank you @ShikharDua !

import pandas as pd 

BaseData = pd.DataFrame({ 'Customer' : ['Acme','Mega','Acme','Acme','Mega','Acme'],
                          'Territory'  : ['West','East','South','West','East','South'],
                          'Product'  : ['Econ','Luxe','Econ','Std','Std','Econ']})
BaseData

columns = ['Customer','Num Unique Products', 'List Unique Products']

rows_list=[]
for name, group in BaseData.groupby('Customer'):
    RecordtoAdd={} #initialise an empty dict 
    RecordtoAdd.update({'Customer' : name}) #
    RecordtoAdd.update({'Num Unique Products' : len(pd.unique(group['Product']))})      
    RecordtoAdd.update({'List Unique Products' : pd.unique(group['Product'])})                   

    rows_list.append(RecordtoAdd)

AnalysedData = pd.DataFrame(rows_list)

print('Base Data : \n',BaseData,'\n\n Analysed Data : \n',AnalysedData)

Get sum of MySQL column in PHP

$sql = "SELECT SUM(Value) FROM Codes";

$result = mysql_query($query);

while($row = mysql_fetch_array($result)){

    sum = $row['SUM(price)'];

}

echo sum;

Sort an ArrayList based on an object field

You can use the Bean Comparator to sort on any property in your custom class.

How to call a PHP file from HTML or Javascript

You just need to post the form data to the insert php file function, see below :)

class DbConnect
{
// Database login vars
private $dbHostname = '';
private $dbDatabase = '';
private $dbUsername = '';
private $dbPassword = '';
public $db = null;

public function connect()
{

    try
    {
        $this->db = new PDO("mysql:host=".$this->dbHostname.";dbname=".$this->dbDatabase, $this->dbUsername, $this->dbPassword);
        $this->db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    }
    catch(PDOException $e)
    {
        echo "It seems there was an error.  Please refresh your browser and try again. ".$e->getMessage();
    }
}

public function store($email)
{
    $stm = $this->db->prepare('INSERT INTO subscribers (email) VALUES ?');
    $stm->bindValue(1, $email);

    return $stm->execute();
}
}

How do I get the resource id of an image if I know its name?

With something like this:

String mDrawableName = "myappicon";
int resID = getResources().getIdentifier(mDrawableName , "drawable", getPackageName());

How to count the NaN values in a column in pandas DataFrame

You can use value_counts method and print values of np.nan

s.value_counts(dropna = False)[np.nan]

How to calculate distance between two locations using their longitude and latitude value

in build.gradle:

compile 'com.google.maps.android:android-maps-utils:0.4'

and then:

public static Double distanceBetween(LatLng point1, LatLng point2) {
    if (point1 == null || point2 == null) {
        return null;
    }

    return SphericalUtil.computeDistanceBetween(point1, point2);
}

Format Date/Time in XAML in Silverlight

<TextBlock Text="{Binding Date, StringFormat='{}{0:MM/dd/yyyy a\\t h:mm tt}'}" />

will return you

04/07/2011 at 1:28 PM (-04)

How can I embed a YouTube video on GitHub wiki pages?

If you like HTML tags more than markdown + center alignment:

_x000D_
_x000D_
<div align="center">_x000D_
  <a href="https://www.youtube.com/watch?v=YOUTUBE_VIDEO_ID_HERE"><img src="https://img.youtube.com/vi/YOUTUBE_VIDEO_ID_HERE/0.jpg" alt="IMAGE ALT TEXT"></a>_x000D_
</div>
_x000D_
_x000D_
_x000D_

HTTP Basic Authentication credentials passed in URL and encryption

Will the username and password be automatically SSL encrypted? Is the same true for GETs and POSTs

Yes, yes yes.

The entire communication (save for the DNS lookup if the IP for the hostname isn't already cached) is encrypted when SSL is in use.

What does if [ $? -eq 0 ] mean for shell scripts?

$? is the exit status of the most recently-executed command; by convention, 0 means success and anything else indicates failure. That line is testing whether the grep command succeeded.

The grep manpage states:

The exit status is 0 if selected lines are found, and 1 if not found. If an error occurred the exit status is 2. (Note: POSIX error handling code should check for '2' or greater.)

So in this case it's checking whether any ERROR lines were found.

Preventing multiple clicks on button

We can use on and off click for preventing Multiple clicks. i tried it to my application and it's working as expected.

$(document).ready(function () {     
    $("#disable").on('click', function () {
        $(this).off('click'); 
        // enter code here
    });
})

Wait for shell command to complete

Add the following Sub:

Sub SyncShell(ByVal Cmd As String, ByVal WindowStyle As VbAppWinStyle)
VBA.CreateObject("WScript.Shell").Run Cmd, WindowStyle, True
End Sub

If you add a reference to C:\Windows\system32\wshom.ocx you can also use:

Sub SyncShell(ByVal Cmd As String, ByVal WindowStyle As VbAppWinStyle)
Static wsh As New WshShell
wsh.Run Cmd, WindowStyle, True
End Sub

This version should be more efficient.

How to convert a SVG to a PNG with ImageMagick?

I haven't been able to get good results from ImageMagick in this instance, but Inkscape does a nice job of scaling an SVG on Linux and Windows:

inkscape -z -w 1024 -h 1024 input.svg -e output.png

Note that you can omit one of the width/height parameters to have the other parameter scaled automatically based on the input image dimensions.

Edit (May 2020): Inkscape 1.0 users, please note that the command line arguments have changed:

inkscape -w 1024 -h 1024 input.svg -o output.png

Here's the result of scaling a 16x16 SVG to a 200x200 PNG using this command:

enter image description here

enter image description here

Just for reference, my Inkscape version (on Ubuntu 12.04) is:

Inkscape 0.48.3.1 r9886 (Mar 29 2012)

and on Windows 7, it is:

Inkscape 0.48.4 r9939 (Dec 17 2012)

How can I get the full/absolute URL (with domain) in Django?

You can also use:

import socket
socket.gethostname()

This is working fine for me,

I'm not entirely sure how it works. I believe this is a bit more low level and will return your server hostname, which might be different than the hostname used by your user to get to your page.

ORA-00972 identifier is too long alias column name

I'm using Argos reporting system as a front end and Oracle in back. I just encountered this error and it was caused by a string with a double quote at the start and a single quote at the end. Replacing the double quote with a single solved the issue.

Cannot create cache directory .. or directory is not writable. Proceeding without cache in Laravel

When you installed composer pretty sure you used $ sudo command because of that the ~/.composer folder was created by the root.

Run this to fix the issue:

$ sudo chown -R $USER $HOME/.composer

How do I use SELECT GROUP BY in DataTable.Select(Expression)?

dt = dt.AsEnumerable().GroupBy(r => r.Field<int>("ID")).Select(g => g.First()).CopyToDataTable();

Spring @Transactional - isolation, propagation

We can add for this:

@Transactional(readOnly = true)
public class Banking_CustomerService implements CustomerService {

    public Customer getDetail(String customername) {
        // do something
    }

    // these settings have precedence for this method
    @Transactional(readOnly = false, propagation = Propagation.REQUIRES_NEW)
    public void updateCustomer(Customer customer) {
        // do something
    }
}

How to link a folder with an existing Heroku app

Don't forget, if you are also on a machine where you haven't set up heroku before

heroku keys:add

Or you won't be able to push or pull to the repo.

AngularJS : When to use service instead of factory

allernhwkim originally posted an answer on this question linking to his blog, however a moderator deleted it. It's the only post I've found which doesn't just tell you how to do the same thing with service, provider and factory, but also tells you what you can do with a provider that you can't with a factory, and with a factory that you can't with a service.

Directly from his blog:

app.service('CarService', function() {
   this.dealer="Bad";
    this.numCylinder = 4;
});

app.factory('CarFactory', function() {
    return function(numCylinder) {
      this.dealer="Bad";
        this.numCylinder = numCylinder
    };
});

app.provider('CarProvider', function() {
    this.dealerName = 'Bad';
    this.$get = function() {
        return function(numCylinder) {
            this.numCylinder = numCylinder;
            this.dealer = this.dealerName;
        }
    };
    this.setDealerName = function(str) {
      this.dealerName = str;
    }      
});

This shows how the CarService will always a produce a car with 4 cylinders, you can't change it for individual cars. Whereas CarFactory returns a function so you can do new CarFactory in your controller, passing in a number of cylinders specific to that car. You can't do new CarService because CarService is an object not a function.

The reason factories don't work like this:

app.factory('CarFactory', function(numCylinder) {
      this.dealer="Bad";
      this.numCylinder = numCylinder
});

And automatically return a function for you to instantiate, is because then you can't do this (add things to the prototype/etc):

app.factory('CarFactory', function() {
    function Car(numCylinder) {
        this.dealer="Bad";
        this.numCylinder = numCylinder
    };
    Car.prototype.breakCylinder = function() {
        this.numCylinder -= 1;
    };
    return Car;
});

See how it is literally a factory producing a car.

The conclusion from his blog is pretty good:

In conclusion,

---------------------------------------------------  
| Provider| Singleton| Instantiable | Configurable|
---------------------------------------------------  
| Factory | Yes      | Yes          | No          |
---------------------------------------------------  
| Service | Yes      | No           | No          |
---------------------------------------------------  
| Provider| Yes      | Yes          | Yes         |       
---------------------------------------------------  
  1. Use Service when you need just a simple object such as a Hash, for example {foo;1, bar:2} It’s easy to code, but you cannot instantiate it.

  2. Use Factory when you need to instantiate an object, i.e new Customer(), new Comment(), etc.

  3. Use Provider when you need to configure it. i.e. test url, QA url, production url.

If you find you're just returning an object in factory you should probably use service.

Don't do this:

app.factory('CarFactory', function() {
    return {
        numCylinder: 4
    };
});

Use service instead:

app.service('CarService', function() {
    this.numCylinder = 4;
});

How to get Time from DateTime format in SQL?

If you want date something in this style: Oct 23 2013 10:30AM

Use this

SELECT CONVERT(NVARCHAR(30),getdate(), 100)

convert() method takes 3 parameters

  1. datatype
  2. Column/Value
  3. Style: Available styles are from 100 to 114. You can choose within range from. Choose one by one to change the date format.

How to make a floated div 100% height of its parent?

This helped me.

#outer {
    position:relative;
}
#inner {
    position:absolute;
    top:0;
    left:0px;
    right:0px;
    height:100%;
}

Change right: and left: to set preferable #inner width.

What to gitignore from the .idea folder?

While maintaining the proper .gitignore file is helpful, I found this alternate approach is way cleaner and easier to use.

  • Create dummy folder my_project and inside that git clone my_real_project the actual project repo.
  • Now while opening the project in IDE (Intellij/Pycharm) open the folder my_project and mark my_project/my_real_project as the VCS root.
  • You can see my_project/.idea wouldn't pollute your git repo because it happily lives outside the git repo which is what you want. This way your .gitignore files stays clean as well.

This approach works better due to the below reasons.

1 - .gitignore file stays clean and we don't have to insert lines related to JetBrains products, that file is better used for binaries and libraries and autogen contents.

2 - Intellij keeps updating their projects and the files inside .idea keep changing every significant release from JB. What this means is we have to keep updating our .gitignore accordingly which is not an ideal use of time.

3 - Intellij has the flawed pattern here, most editors Atom, VS Code, Eclipse... nobody stores their IDE contents right inside project root. JB shouldn't be an exception either. It's the onus of Jetbrains to keep those files tracked outside project root. They have to refrain from polluting VCS root. This approach does just that. The .idea folder is kept outside the PROJECT_ROOT

Hope this helps.

Parsing JSON in Excel VBA

If you want to build on top of ScriptControl, you can add a few helper method to get at the required information. The JScriptTypeInfo object is a bit unfortunate: it contains all the relevant information (as you can see in the Watch window) but it seems impossible to get at it with VBA. However, the Javascript engine can help us:

Option Explicit

Private ScriptEngine As ScriptControl

Public Sub InitScriptEngine()
    Set ScriptEngine = New ScriptControl
    ScriptEngine.Language = "JScript"
    ScriptEngine.AddCode "function getProperty(jsonObj, propertyName) { return jsonObj[propertyName]; } "
    ScriptEngine.AddCode "function getKeys(jsonObj) { var keys = new Array(); for (var i in jsonObj) { keys.push(i); } return keys; } "
End Sub

Public Function DecodeJsonString(ByVal JsonString As String)
    Set DecodeJsonString = ScriptEngine.Eval("(" + JsonString + ")")
End Function

Public Function GetProperty(ByVal JsonObject As Object, ByVal propertyName As String) As Variant
    GetProperty = ScriptEngine.Run("getProperty", JsonObject, propertyName)
End Function

Public Function GetObjectProperty(ByVal JsonObject As Object, ByVal propertyName As String) As Object
    Set GetObjectProperty = ScriptEngine.Run("getProperty", JsonObject, propertyName)
End Function

Public Function GetKeys(ByVal JsonObject As Object) As String()
    Dim Length As Integer
    Dim KeysArray() As String
    Dim KeysObject As Object
    Dim Index As Integer
    Dim Key As Variant

    Set KeysObject = ScriptEngine.Run("getKeys", JsonObject)
    Length = GetProperty(KeysObject, "length")
    ReDim KeysArray(Length - 1)
    Index = 0
    For Each Key In KeysObject
        KeysArray(Index) = Key
        Index = Index + 1
    Next
    GetKeys = KeysArray
End Function


Public Sub TestJsonAccess()
    Dim JsonString As String
    Dim JsonObject As Object
    Dim Keys() As String
    Dim Value As Variant
    Dim j As Variant

    InitScriptEngine

    JsonString = "{""key1"": ""val1"", ""key2"": { ""key3"": ""val3"" } }"
    Set JsonObject = DecodeJsonString(CStr(JsonString))
    Keys = GetKeys(JsonObject)

    Value = GetProperty(JsonObject, "key1")
    Set Value = GetObjectProperty(JsonObject, "key2")
End Sub

A few notes:

  • If the JScriptTypeInfo instance refers to a Javascript object, For Each ... Next won't work. However, it does work if it refers to a Javascript array (see GetKeys function).
  • The access properties whose name is only known at run-time, use the functions GetProperty and GetObjectProperty.
  • The Javascript array provides the properties length, 0, Item 0, 1, Item 1 etc. With the VBA dot notation (jsonObject.property), only the length property is accessible and only if you declare a variable called length with all lowercase letters. Otherwise the case doesn't match and it won't find it. The other properties are not valid in VBA. So better use the GetProperty function.
  • The code uses early binding. So you have to add a reference to "Microsoft Script Control 1.0".
  • You have to call InitScriptEngine once before using the other functions to do some basic initialization.

Define css class in django Forms

Simply add the classes to your form as follows.

class UserLoginForm(forms.Form):
    username = forms.CharField(widget=forms.TextInput(
        attrs={
        'class':'form-control',
        'placeholder':'Username'
        }
    ))
    password = forms.CharField(widget=forms.PasswordInput(
        attrs={
        'class':'form-control',
        'placeholder':'Password'
        }
    ))

Vertical align in bootstrap table

vetrical-align: middle did not work for me for some reason (and it was being applied). I used this:

table.vertical-align > tbody > tr > td {
  display: flex;
  align-items: center;
}

Opening Android Settings programmatically

Send User to Settings With located Package, example for WRITE_SETTINGS permission:

startActivityForResult(new Intent(Settings.ACTION_MANAGE_WRITE_SETTINGS).setData(Uri.parse("package:"+getPackageName()) ),0);

C#: Limit the length of a string?

Here is another alternative answer to this issue. This extension method works quite well. This solves the issues of the string being shorter than the maximum length and also the maximum length being negative.

public static string Left( this string str, int length ) {
  if (str == null)
    return str;
  return str.Substring(0, Math.Min(Math.Abs(length), str.Length));
}

Another solution would be to limit the length to be non-negative values, and just zero-out negative values.

public static string Left( this string str, int length ) {
  if (str == null)
    return str;
  return str.Substring(0, Math.Min(Math.Max(0,length), str.Length));
}

How can I add a key/value pair to a JavaScript object?

arr.key3 = value3;

because your arr is not really an array... It's a prototype object. The real array would be:

var arr = [{key1: value1}, {key2: value2}];

but it's still not right. It should actually be:

var arr = [{key: key1, value: value1}, {key: key2, value: value2}];

Animate change of view background color on Android

I've found that the implementation used by ArgbEvaluator in the Android source code does best job in transitioning colors. When using HSV, depending on the two colors, the transition was jumping through too many hues for me. But this method's doesn't.

If you are trying to simply animate, use ArgbEvaluator with ValueAnimator as suggested here:

ValueAnimator colorAnimation = ValueAnimator.ofObject(new ArgbEvaluator(), colorFrom, colorTo);
colorAnimation.addUpdateListener(new AnimatorUpdateListener() {

    @Override
    public void onAnimationUpdate(ValueAnimator animator) {
        view.setBackgroundColor((int) animator.getAnimatedValue());
    }

});
colorAnimation.start();

However, if you are like me and want to tie your transition with some user gesture or other value passed from an input, the ValueAnimator is not of much help (unless your are targeting for API 22 and above, in which case you can use the ValueAnimator.setCurrentFraction() method). When targeting below API 22, wrap the code found in ArgbEvaluator source code in your own method, as shown below:

public static int interpolateColor(float fraction, int startValue, int endValue) {
    int startA = (startValue >> 24) & 0xff;
    int startR = (startValue >> 16) & 0xff;
    int startG = (startValue >> 8) & 0xff;
    int startB = startValue & 0xff;
    int endA = (endValue >> 24) & 0xff;
    int endR = (endValue >> 16) & 0xff;
    int endG = (endValue >> 8) & 0xff;
    int endB = endValue & 0xff;
    return ((startA + (int) (fraction * (endA - startA))) << 24) |
            ((startR + (int) (fraction * (endR - startR))) << 16) |
            ((startG + (int) (fraction * (endG - startG))) << 8) |
            ((startB + (int) (fraction * (endB - startB))));
}

And use it however you wish.

npm ERR! network getaddrinfo ENOTFOUND

I also faced this error but I was not working behind a proxy server at the moment so using npm config set proxy=http://address:8080 couldn't help and ~/.npmrc didn't contain any proxy setting either. The solution in my case was just to restart my computer.

When should I use Kruskal as opposed to Prim (and vice versa)?

Prim's is better for more dense graphs, and in this we also do not have to pay much attention to cycles by adding an edge, as we are primarily dealing with nodes. Prim's is faster than Kruskal's in the case of complex graphs.

How to change cursor from pointer to finger using jQuery?

How do you change your cursor to the finger (like for clicking on links) instead of the regular pointer?

This is very simple to achieve using the CSS property cursor, no jQuery needed.

You can read more about in: CSS cursor property and cursor - CSS | MDN

_x000D_
_x000D_
.default {_x000D_
  cursor: default;_x000D_
}_x000D_
.pointer {_x000D_
  cursor: pointer;_x000D_
}
_x000D_
<a class="default" href="#">default</a>_x000D_
_x000D_
<a class="pointer" href="#">pointer</a>
_x000D_
_x000D_
_x000D_

When do you use varargs in Java?

Varargs can be used when we are unsure about the number of arguments to be passed in a method. It creates an array of parameters of unspecified length in the background and such a parameter can be treated as an array in runtime.

If we have a method which is overloaded to accept different number of parameters, then instead of overloading the method different times, we can simply use varargs concept.

Also when the parameters' type is going to vary then using "Object...test" will simplify the code a lot.

For example:

public int calculate(int...list) {
    int sum = 0;
    for (int item : list) {
        sum += item;
    }
    return sum;
}

Here indirectly an array of int type (list) is passed as parameter and is treated as an array in the code.

For a better understanding follow this link(it helped me a lot in understanding this concept clearly): http://www.javadb.com/using-varargs-in-java

P.S: Even I was afraid of using varargs when I didn't knw abt it. But now I am used to it. As it is said: "We cling to the known, afraid of the unknown", so just use it as much as you can and you too will start liking it :)

Good way of getting the user's location in Android

I scoured the internet for an updated (past year) answer using the latest location pulling methods suggested by google (to use FusedLocationProviderClient). I finally landed on this:

https://github.com/googlesamples/android-play-location/tree/master/LocationUpdates

I created a new project and copied in most of this code. Boom. It works. And I think without any deprecated lines.

Also, the simulator doesn't seem to get a GPS location, that I know of. It did get as far as reporting this in the log: "All location settings are satisfied."

And finally, in case you wanted to know (I did), you DO NOT need a google maps api key from the google developer console, if all you want is the GPS location.

Also useful is their tutorial. But I wanted a full one page tutorial/code example, and that. Their tutorial stacks but is confusing when you're new to this because you don't know what pieces you need from earlier pages.

https://developer.android.com/training/location/index.html

And finally, remember things like this:

I not only had to modify the mainActivity.Java. I also had to modify Strings.xml, androidmanifest.xml, AND the correct build.gradle. And also your activity_Main.xml (but that part was easy for me).

I needed to add dependencies like this one: implementation 'com.google.android.gms:play-services-location:11.8.0', and update the settings of my android studio SDK to include google play services. (file settings appearance system settings android SDK SDK Tools check google play services).

update: the android simulator did seem to get a location and location change events (when I changed the value in the settings of the sim). But my best and first results were on an actual device. So it's probably easiest to test on actual devices.

How to add text to a WPF Label in code?

Try DesrLabel.Content. Its the WPF way.

How do I specify different layouts for portrait and landscape orientations?

Create a new directory layout-land, then create xml file with same name in layout-land as it was layout directory and align there your content for Landscape mode.

Note that id of content in both xml is same.

Maven plugin in Eclipse - Settings.xml file is missing

Working on Mac I followed the answer of Sean Patrick Floyd placing a settings.xml like above in my user folder /Users/user/.m2/

But this did not help. So I opened a Terminal and did a ls -la on the folder. This was showing

-rw-r--r--@

thus staff and everone can at least read the file. So I wondered if the message isn't wrong and if the real cause is the lack of write permissions. I set the file to:

-rw-r--rw-@

This did it. The message disappeared.

Escaping special characters in Java Regular Expressions

Agree with Gray, as you may need your pattern to have both litrals (\[, \]) and meta-characters ([, ]). so with some utility you should be able to escape all character first and then you can add meta-characters you want to add on same pattern.

Is there a program to decompile Delphi?

Here's a list : http://delphi.about.com/od/devutilities/a/decompiling_3.htm (and this page mentions some more : http://www.program-transformation.org/Transform/DelphiDecompilers )

I've used DeDe on occasion, but it's not really all that powerfull, and it's not up-to-date with current Delphi versions (latest version it supports is Delphi 7 I believe)

Getting RSA private key from PEM BASE64 Encoded private key file

This is PKCS#1 format of a private key. Try this code. It doesn't use Bouncy Castle or other third-party crypto providers. Just java.security and sun.security for DER sequece parsing. Also it supports parsing of a private key in PKCS#8 format (PEM file that has a header "-----BEGIN PRIVATE KEY-----").

import sun.security.util.DerInputStream;
import sun.security.util.DerValue;

import java.io.File;
import java.io.IOException;
import java.math.BigInteger;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.security.GeneralSecurityException;
import java.security.KeyFactory;
import java.security.PrivateKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.RSAPrivateCrtKeySpec;
import java.util.Base64;

public static PrivateKey pemFileLoadPrivateKeyPkcs1OrPkcs8Encoded(File pemFileName) throws GeneralSecurityException, IOException {
        // PKCS#8 format
        final String PEM_PRIVATE_START = "-----BEGIN PRIVATE KEY-----";
        final String PEM_PRIVATE_END = "-----END PRIVATE KEY-----";

        // PKCS#1 format
        final String PEM_RSA_PRIVATE_START = "-----BEGIN RSA PRIVATE KEY-----";
        final String PEM_RSA_PRIVATE_END = "-----END RSA PRIVATE KEY-----";

        Path path = Paths.get(pemFileName.getAbsolutePath());

        String privateKeyPem = new String(Files.readAllBytes(path));

        if (privateKeyPem.indexOf(PEM_PRIVATE_START) != -1) { // PKCS#8 format
            privateKeyPem = privateKeyPem.replace(PEM_PRIVATE_START, "").replace(PEM_PRIVATE_END, "");
            privateKeyPem = privateKeyPem.replaceAll("\\s", "");

            byte[] pkcs8EncodedKey = Base64.getDecoder().decode(privateKeyPem);

            KeyFactory factory = KeyFactory.getInstance("RSA");
            return factory.generatePrivate(new PKCS8EncodedKeySpec(pkcs8EncodedKey));

        } else if (privateKeyPem.indexOf(PEM_RSA_PRIVATE_START) != -1) {  // PKCS#1 format

            privateKeyPem = privateKeyPem.replace(PEM_RSA_PRIVATE_START, "").replace(PEM_RSA_PRIVATE_END, "");
            privateKeyPem = privateKeyPem.replaceAll("\\s", "");

            DerInputStream derReader = new DerInputStream(Base64.getDecoder().decode(privateKeyPem));

            DerValue[] seq = derReader.getSequence(0);

            if (seq.length < 9) {
                throw new GeneralSecurityException("Could not parse a PKCS1 private key.");
            }

            // skip version seq[0];
            BigInteger modulus = seq[1].getBigInteger();
            BigInteger publicExp = seq[2].getBigInteger();
            BigInteger privateExp = seq[3].getBigInteger();
            BigInteger prime1 = seq[4].getBigInteger();
            BigInteger prime2 = seq[5].getBigInteger();
            BigInteger exp1 = seq[6].getBigInteger();
            BigInteger exp2 = seq[7].getBigInteger();
            BigInteger crtCoef = seq[8].getBigInteger();

            RSAPrivateCrtKeySpec keySpec = new RSAPrivateCrtKeySpec(modulus, publicExp, privateExp, prime1, prime2, exp1, exp2, crtCoef);

            KeyFactory factory = KeyFactory.getInstance("RSA");

            return factory.generatePrivate(keySpec);
        }

        throw new GeneralSecurityException("Not supported format of a private key");
    }

Reactjs setState() with a dynamic key name?

Thanks to @Cory's hint, i used this:

inputChangeHandler : function (event) {
    var stateObject = function() {
      returnObj = {};
      returnObj[this.target.id] = this.target.value;
         return returnObj;
    }.bind(event)();

    this.setState( stateObject );    
},

If using ES6 or the Babel transpiler to transform your JSX code, you can accomplish this with computed property names, too:

inputChangeHandler : function (event) {
    this.setState({ [event.target.id]: event.target.value });
    // alternatively using template strings for strings
    // this.setState({ [`key${event.target.id}`]: event.target.value });
}

What's the difference between SoftReference and WeakReference in Java?

SoftReference is designed for caches. When it is found that a WeakReference references an otherwise unreachable object, then it will get cleared immediately. SoftReference may be left as is. Typically there is some algorithm relating to the amount of free memory and the time last used to determine whether it should be cleared. The current Sun algorithm is to clear the reference if it has not been used in as many seconds as there are megabytes of memory free on the Java heap (configurable, server HotSpot checks against maximum possible heap as set by -Xmx). SoftReferences will be cleared before OutOfMemoryError is thrown, unless otherwise reachable.

Word wrap for a label in Windows Forms

Have a better one based on @hypo 's answer

public class GrowLabel : Label {
    private bool mGrowing;
    public GrowLabel() {
        this.AutoSize = false;
    }
    private void resizeLabel() {
        if (mGrowing)
            return;
        try {
            mGrowing = true;
            int width = this.Parent == null ? this.Width : this.Parent.Width;

            Size sz = new Size(this.Width, Int32.MaxValue);
            sz = TextRenderer.MeasureText(this.Text, this.Font, sz, TextFormatFlags.WordBreak);
            this.Height = sz.Height + Padding.Bottom + Padding.Top;
        } finally {
            mGrowing = false;
        }
    }
    protected override void OnTextChanged(EventArgs e) {
        base.OnTextChanged(e);
        resizeLabel();
    }
    protected override void OnFontChanged(EventArgs e) {
        base.OnFontChanged(e);
        resizeLabel();
    }
    protected override void OnSizeChanged(EventArgs e) {
        base.OnSizeChanged(e);
        resizeLabel();
    }
}

int width = this.Parent == null ? this.Width : this.Parent.Width; this allows you to use auto-grow label when docked to a parent, e.g. a panel.

this.Height = sz.Height + Padding.Bottom + Padding.Top; here we take care of padding for top and bottom.

Save Dataframe to csv directly to s3 Python

If you pass None as the first argument to to_csv() the data will be returned as a string. From there it's an easy step to upload that to S3 in one go.

It should also be possible to pass a StringIO object to to_csv(), but using a string will be easier.

PHP call Class method / function

$f = new Functions;
$var = $f->filter($_GET['params']);

Have a look at the PHP manual section on Object Oriented programming

Multiple connections to a server or shared resource by the same user, using more than one user name, are not allowed

Follow these steps:

  • Select the Start button, then type cmd.
  • Right-click the Command Prompt option, then choose Run as administrator.
  • Type net use, then press Enter.
  • Look for any drives listed that may be questionable. In many cases where this problem occurs, the drive may not be assigned a letter. You’ll want to remove that drive.
  • From the Command Prompt, type net use /delete \\servername\foldername where the servername\foldername is the drive that you wish to delete.

Should I use encodeURI or encodeURIComponent for encoding URLs?

Here is a summary.

  1. escape() will not encode @ * _ + - . /

    Do not use it.

  2. encodeURI() will not encode A-Z a-z 0-9 ; , / ? : @ & = + $ - _ . ! ~ * ' ( ) #

    Use it when your input is a complete URL like 'https://searchexample.com/search?q=wiki'

  3. encodeURIComponent() will not encode A-Z a-z 0-9 - _ . ! ~ * ' ( ) Use it when your input is part of a complete URL e.g const queryStr = encodeURIComponent(someString)

How to print a date in a regular format?

With type-specific datetime string formatting (see nk9's answer using str.format().) in a Formatted string literal (since Python 3.6, 2016-12-23):

>>> import datetime
>>> f"{datetime.datetime.now():%Y-%m-%d}"
'2017-06-15'

The date/time format directives are not documented as part of the Format String Syntax but rather in date, datetime, and time's strftime() documentation. The are based on the 1989 C Standard, but include some ISO 8601 directives since Python 3.6.

What are the differences between a superkey and a candidate key?

Candidate key is a super key from which you cannot remove any fields.

For instance, a software release can be identified either by major/minor version, or by the build date (we assume nightly builds).

Storing date in three fields is not a good idea of course, but let's pretend it is for demonstration purposes:

year  month date  major  minor
2008  01    13     0      1
2008  04    23     0      2
2009  11    05     1      0
2010  04    05     1      1

So (year, major, minor) or (year, month, date, major) are super keys (since they are unique) but not candidate keys, since you can remove year or major and the remaining set of columns will still be a super key.

(year, month, date) and (major, minor) are candidate keys, since you cannot remove any of the fields from them without breaking uniqueness.

C: printf a float value

You can do it like this:

printf("%.6f", myFloat);

6 represents the number of digits after the decimal separator.

sqlite3.ProgrammingError: Incorrect number of bindings supplied. The current statement uses 1, and there are 74 supplied

cursor.execute(sql,array)

Only takes two arguments.
It will iterate the "array"-object and match ? in the sql-string.
(with sanity checks to avoid sql-injection)

jquery toggle slide from left to right and back

Use this...

$('#cat_icon').click(function () {
    $('#categories').toggle("slow");
    //$('#cat_icon').hide();
});
$('.panel_title').click(function () {
    $('#categories').toggle("slow");
    //$('#cat_icon').show();
});

See this Example

Greetings.

How do I turn a String into a InputStreamReader in java?

ByteArrayInputStream also does the trick:

InputStream is = new ByteArrayInputStream( myString.getBytes( charset ) );

Then convert to reader:

InputStreamReader reader = new InputStreamReader(is);

How to draw a checkmark / tick using CSS?

only css, quite simple I find it:

_x000D_
_x000D_
.checkmark {_x000D_
      display: inline-block;_x000D_
      transform: rotate(45deg);_x000D_
      height: 25px;_x000D_
      width: 12px;_x000D_
      margin-left: 60%; _x000D_
      border-bottom: 7px solid #78b13f;_x000D_
      border-right: 7px solid #78b13f;_x000D_
    }
_x000D_
<div class="checkmark"></div>
_x000D_
_x000D_
_x000D_

Why shouldn't I use "Hungarian Notation"?

Most people use Hungarian notation in a wrong way and are getting wrong results.

Read this excellent article by Joel Spolsky: Making Wrong Code Look Wrong.

In short, Hungarian Notation where you prefix your variable names with their type (string) (Systems Hungarian) is bad because it's useless.

Hungarian Notation as it was intended by its author where you prefix the variable name with its kind (using Joel's example: safe string or unsafe string), so called Apps Hungarian has its uses and is still valuable.

How can I send mail from an iPhone application

Swift 2.0

func mailComposeController(controller: MFMailComposeViewController, didFinishWithResult result: MFMailComposeResult, error: NSError?){
    if let error = error{
        print("Error: \(error)")
    }else{
        //NO Error
        //------------------------------------------------
        var feedbackMsg = ""

        switch result.rawValue {
        case MFMailComposeResultCancelled.rawValue:
            feedbackMsg = "Mail Cancelled"
        case MFMailComposeResultSaved.rawValue:
            feedbackMsg = "Mail Saved"
        case MFMailComposeResultSent.rawValue:
            feedbackMsg = "Mail Sent"
        case MFMailComposeResultFailed.rawValue:
            feedbackMsg = "Mail Failed"
        default:
            feedbackMsg = ""
        }

        print("Mail: \(feedbackMsg)")

        //------------------------------------------------
    }
}

How to add a classname/id to React-Bootstrap Component?

If you look at the code for the component you can see that it uses the className prop passed to it to combine with the row class to get the resulting set of classes (<Row className="aaa bbb"... works).Also, if you provide the id prop like <Row id="444" ... it will actually set the id attribute for the element.

adb uninstall failed

Maybe you're trying to uninstall an app that is a phone administrator.

To be able to uninstall it, go to Seetings > Security > Phone Administrators. If the app is listed, uncheck it and confirm the operation.

After that, you should be able to uninstall it using the App settings area or adb.

Angular2: Cannot read property 'name' of undefined

In order to avoid this, you could as well initialize the selectedHero member of your component to an empty object (instead of leaving it undefined).

In your example code, that would give something like this :

export class AppComponent {
  title = 'Tour of Heroes';
  heroes = HEROES;
  selectedHero:Hero = new Hero();

  onSelect(hero: Hero):void{
      this.selectedHero = hero;
  }
}

How do I override nested NPM dependency versions?

For those using yarn.

I tried using npm shrinkwrap until I discovered the yarn cli ignored my npm-shrinkwrap.json file.

Yarn has https://yarnpkg.com/lang/en/docs/selective-version-resolutions/ for this. Neat.

Check out this answer too: https://stackoverflow.com/a/41082766/3051080

An efficient way to Base64 encode a byte array?

You could use the String Convert.ToBase64String(byte[]) to encode the byte array into a base64 string, then Byte[] Convert.FromBase64String(string) to convert the resulting string back into a byte array.

Is bool a native C type?

C99 has it in stdbool.h, but in C90 it must be defined as a typedef or enum:

typedef int bool;
#define TRUE  1
#define FALSE 0

bool f = FALSE;
if (f) { ... }

Alternatively:

typedef enum { FALSE, TRUE } boolean;

boolean b = FALSE;
if (b) { ... }

JMS Topic vs Queues

A JMS topic is the type of destination in a 1-to-many model of distribution. The same published message is received by all consuming subscribers. You can also call this the 'broadcast' model. You can think of a topic as the equivalent of a Subject in an Observer design pattern for distributed computing. Some JMS providers efficiently choose to implement this as UDP instead of TCP. For topic's the message delivery is 'fire-and-forget' - if no one listens, the message just disappears. If that's not what you want, you can use 'durable subscriptions'.

A JMS queue is a 1-to-1 destination of messages. The message is received by only one of the consuming receivers (please note: consistently using subscribers for 'topic client's and receivers for queue client's avoids confusion). Messages sent to a queue are stored on disk or memory until someone picks it up or it expires. So queues (and durable subscriptions) need some active storage management, you need to think about slow consumers.

In most environments, I would argue, topics are the better choice because you can always add additional components without having to change the architecture. Added components could be monitoring, logging, analytics, etc. You never know at the beginning of the project what the requirements will be like in 1 year, 5 years, 10 years. Change is inevitable, embrace it :-)

How do browser cookie domains work?

The RFCs are known not to reflect reality.

Better check draft-ietf-httpstate-cookie, work in progress.

Remove values from select list based on condition

Removing an option

$("#val option[value='A']").remove();

How to display a range input slider vertically

First, set height greater than width. In theory, this is all you should need. The HTML5 Spec suggests as much:

... the UA determined the orientation of the control from the ratio of the style-sheet-specified height and width properties.

Opera had it implemented this way, but Opera is now using WebKit Blink. As of today, no browser implements a vertical slider based solely on height being greater than width.

Regardless, setting height greater than width is needed to get the layout right between browsers. Applying left and right padding will also help with layout and positioning.

For Chrome, use -webkit-appearance: slider-vertical.

For IE, use writing-mode: bt-lr.

For Firefox, add an orient="vertical" attribute to the html. Pity that they did it this way. Visual styles should be controlled via CSS, not HTML.

_x000D_
_x000D_
input[type=range][orient=vertical]
{
    writing-mode: bt-lr; /* IE */
    -webkit-appearance: slider-vertical; /* WebKit */
    width: 8px;
    height: 175px;
    padding: 0 5px;
}
_x000D_
<input type="range" orient="vertical" />
_x000D_
_x000D_
_x000D_


Disclaimers:

This solution is based on current browser implementations of as yet undefined or unfinalized CSS properties. If you intend to use it in your code, be prepared to make code adjustments as newer browser versions are released and w3c recommendations are completed.

MDN contains an explicit warning against using -webkit-appearance on the web:

Do not use this property on Web sites: not only is it non-standard, but its behavior change from one browser to another. Even the keyword none has not the same behavior on each form element on different browsers, and some doesn't support it at all.

The caption for the vertical slider demo in the IE documentation erroneously indicates that setting height greater than width will display a range slider vertically, but this does not work. In the code section, it plainly does not set height or width, and instead uses writing-mode. The writing-mode property, as implemented by IE, is very robust. Sadly, the values defined in the current working draft of the spec as of this writing, are much more limited. Should future versions of IE drop support of bt-lr in favor of the currently proposed vertical-lr (which would be the equivalent of tb-lr), the slider would display upside down. Most likely, future versions would extend the writing-mode to accept new values rather than drop support for existing values. But, it's good to know what you are dealing with.

How to find the cumulative sum of numbers in a list?

This would be Haskell-style:

def wrand(vtlg):

    def helpf(lalt,lneu): 

        if not lalt==[]:
            return helpf(lalt[1::],[lalt[0]+lneu[0]]+lneu)
        else:
            lneu.reverse()
            return lneu[1:]        

    return helpf(vtlg,[0])

Test if number is odd or even

Another option is a simple bit checking.

n & 1

for example:

if ( $num & 1 ) {
  //odd
} else {
  //even
}

I want to compare two lists in different worksheets in Excel to locate any duplicates

Without VBA...

If you can use a helper column, you can use the MATCH function to test if a value in one column exists in another column (or in another column on another worksheet). It will return an Error if there is no match

To simply identify duplicates, use a helper column

Assume data in Sheet1, Column A, and another list in Sheet2, Column A. In your helper column, row 1, place the following formula:

=If(IsError(Match(A1, 'Sheet2'!A:A,False)),"","Duplicate")

Drag/copy this forumla down, and it should identify the duplicates.

To highlight cells, use conditional formatting:

With some tinkering, you can use this MATCH function in a Conditional Formatting rule which would highlight duplicate values. I would probably do this instead of using a helper column, although the helper column is a great way to "see" results before you make the conditional formatting rule.

Something like:

=NOT(ISERROR(MATCH(A1, 'Sheet2'!A:A,FALSE)))

Conditional formatting for Excel 2010

For Excel 2007 and prior, you cannot use conditional formatting rules that reference other worksheets. In this case, use the helper column and set your formatting rule in column A like:

=B1="Duplicate"

This screenshot is from the 2010 UI, but the same rule should work in 2007/2003 Excel.

Conditional formatting using helper column for rule

Whether a variable is undefined

if (var === undefined)

or more precisely

if (typeof var === 'undefined')

Note the === is used

How to transition to a new view controller with code only using Swift

Your code is just fine. The reason you're getting a black screen is because there's nothing on your second view controller.

Try something like:

secondViewController.view.backgroundColor = UIColor.redColor();

Now the view controller it shows should be red.

To actually do something with secondViewController, create a subclass of UIViewController and instead of

let secondViewController:UIViewController = UIViewController()

create an instance of your second view controller:

//If using code
let secondViewController = MyCustomViewController.alloc()

//If using storyboard, assuming you have a view controller with storyboard ID "MyCustomViewController"
let secondViewController = self.storyboard.instantiateViewControllerWithIdentifier("MyCustomViewController") as UIViewController

Check which element has been clicked with jQuery

$("#news_gallery li .over").click(function() {
    article = $("#news-article .news-article");
});

How to picture "for" loop in block representation of algorithm

What's a "block scheme"?

If I were drawing it, I might draw a box with "for each x in y" written in it.

If you're drawing a flowchart, there's always a loop with a decision box.

Nassi-Schneiderman diagrams have a loop construct you could use.

What is the @Html.DisplayFor syntax for?

DisplayFor is also useful for templating. You could write a template for your Model, and do something like this:

@Html.DisplayFor(m => m)

Similar to @Html.EditorFor(m => m). It's useful for the DRY principal so that you don't have to write the same display logic over and over for the same Model.

Take a look at this blog on MVC2 templates. It's still very applicable to MVC3:

http://www.dalsoft.co.uk/blog/index.php/2010/04/26/mvc-2-templates/


It's also useful if your Model has a Data annotation. For instance, if the property on the model is decorated with the EmailAddress data annotation, DisplayFor will render it as a mailto: link.

Create two blank lines in Markdown

If you are using a library like markdown-it or PythonMarkdown this can also be solved by replacing two line breaks (in Regex /\n\n$/gm) with a line break and an invisible character (\n ) before rendering. Note that the character after \n is an Alt+0160 or an invisible character.

For example, using markdown-it (although it work for any other lib too) with the input:

1

2


3


4



5

Rendered with md.render(string.data.replace(/\n\n$/gm, "\n ")) you will get:

enter image description here

fatal error: iostream.h no such file or directory

Using standard C++ calling (note that you should use namespace std for cout or add using namespace std;)

#include <iostream>

int main()
{
    std::cout<<"Hello World!\n";
    return 0;
}

syntaxerror: unexpected character after line continuation character in python

Replace

f = open(D\\python\\HW\\2_1 - Copy.cp,"r");

by

f = open("D:\\python\\HW\\2_1 - Copy.cp", "r")

  1. File path needs to be a string (constant)
  2. need colon in Windows file path
  3. space after comma for better style
  4. ; after statement is allowed but fugly.

What tutorial are you using?

Empty set literal?

It depends on if you want the literal for a comparison, or for assignment.

If you want to make an existing set empty, you can use the .clear() metod, especially if you want to avoid creating a new object. If you want to do a comparison, use set() or check if the length is 0.

example:

#create a new set    
a=set([1,2,3,'foo','bar'])
#or, using a literal:
a={1,2,3,'foo','bar'}

#create an empty set
a=set()
#or, use the clear method
a.clear()

#comparison to a new blank set
if a==set():
    #do something

#length-checking comparison
if len(a)==0:
    #do something

How is a CSS "display: table-column" supposed to work?

The CSS table model is based on the HTML table model http://www.w3.org/TR/CSS21/tables.html

A table is divided into ROWS, and each row contains one or more cells. Cells are children of ROWS, they are NEVER children of columns.

"display: table-column" does NOT provide a mechanism for making columnar layouts (e.g. newspaper pages with multiple columns, where content can flow from one column to the next).

Rather, "table-column" ONLY sets attributes that apply to corresponding cells within the rows of a table. E.g. "The background color of the first cell in each row is green" can be described.

The table itself is always structured the same way it is in HTML.

In HTML (observe that "td"s are inside "tr"s, NOT inside "col"s):

<table ..>
  <col .. />
  <col .. />
  <tr ..>
    <td ..></td>
    <td ..></td>
  </tr>
  <tr ..>
    <td ..></td>
    <td ..></td>
  </tr>
</table>

Corresponding HTML using CSS table properties (Note that the "column" divs do not contain any contents -- the standard does not allow for contents directly in columns):

_x000D_
_x000D_
.mytable {_x000D_
  display: table;_x000D_
}_x000D_
.myrow {_x000D_
  display: table-row;_x000D_
}_x000D_
.mycell {_x000D_
  display: table-cell;_x000D_
}_x000D_
.column1 {_x000D_
  display: table-column;_x000D_
  background-color: green;_x000D_
}_x000D_
.column2 {_x000D_
  display: table-column;_x000D_
}
_x000D_
<div class="mytable">_x000D_
  <div class="column1"></div>_x000D_
  <div class="column2"></div>_x000D_
  <div class="myrow">_x000D_
    <div class="mycell">contents of first cell in row 1</div>_x000D_
    <div class="mycell">contents of second cell in row 1</div>_x000D_
  </div>_x000D_
  <div class="myrow">_x000D_
    <div class="mycell">contents of first cell in row 2</div>_x000D_
    <div class="mycell">contents of second cell in row 2</div>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_



OPTIONAL: both "rows" and "columns" can be styled by assigning multiple classes to each row and cell as follows. This approach gives maximum flexibility in specifying various sets of cells, or individual cells, to be styled:

_x000D_
_x000D_
//Useful css declarations, depending on what you want to affect, include:_x000D_
_x000D_
/* all cells (that have "class=mycell") */_x000D_
.mycell {_x000D_
}_x000D_
_x000D_
/* class row1, wherever it is used */_x000D_
.row1 {_x000D_
}_x000D_
_x000D_
/* all the cells of row1 (if you've put "class=mycell" on each cell) */_x000D_
.row1 .mycell {_x000D_
}_x000D_
_x000D_
/* cell1 of row1 */_x000D_
.row1 .cell1 {_x000D_
}_x000D_
_x000D_
/* cell1 of all rows */_x000D_
.cell1 {_x000D_
}_x000D_
_x000D_
/* row1 inside class mytable (so can have different tables with different styles) */_x000D_
.mytable .row1 {_x000D_
}_x000D_
_x000D_
/* all the cells of row1 of a mytable */_x000D_
.mytable .row1 .mycell {_x000D_
}_x000D_
_x000D_
/* cell1 of row1 of a mytable */_x000D_
.mytable .row1 .cell1 {_x000D_
}_x000D_
_x000D_
/* cell1 of all rows of a mytable */_x000D_
.mytable .cell1 {_x000D_
}
_x000D_
<div class="mytable">_x000D_
  <div class="column1"></div>_x000D_
  <div class="column2"></div>_x000D_
  <div class="myrow row1">_x000D_
    <div class="mycell cell1">contents of first cell in row 1</div>_x000D_
    <div class="mycell cell2">contents of second cell in row 1</div>_x000D_
  </div>_x000D_
  <div class="myrow row2">_x000D_
    <div class="mycell cell1">contents of first cell in row 2</div>_x000D_
    <div class="mycell cell2">contents of second cell in row 2</div>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

In today's flexible designs, which use <div> for multiple purposes, it is wise to put some class on each div, to help refer to it. Here, what used to be <tr> in HTML became class myrow, and <td> became class mycell. This convention is what makes the above CSS selectors useful.

PERFORMANCE NOTE: putting class names on each cell, and using the above multi-class selectors, is better performance than using selectors ending with *, such as .row1 * or even .row1 > *. The reason is that selectors are matched last first, so when matching elements are being sought, .row1 * first does *, which matches all elements, and then checks all the ancestors of each element, to find if any ancestor has class row1. This might be slow in a complex document on a slow device. .row1 > * is better, because only the immediate parent is examined. But it is much better still to immediately eliminate most elements, via .row1 .cell1. (.row1 > .cell1 is an even tighter spec, but it is the first step of the search that makes the biggest difference, so it usually isn't worth the clutter, and the extra thought process as to whether it will always be a direct child, of adding the child selector >.)

The key point to take away re performance is that the last item in a selector should be as specific as possible, and should never be *.

Eloquent: find() and where() usage laravel

To add to craig_h's comment above (I currently don't have enough rep to add this as a comment to his answer, sorry), if your primary key is not an integer, you'll also want to tell your model what data type it is, by setting keyType at the top of the model definition.

public $keyType = 'string'

Eloquent understands any of the types defined in the castAttribute() function, which as of Laravel 5.4 are: int, float, string, bool, object, array, collection, date and timestamp.

This will ensure that your primary key is correctly cast into the equivalent PHP data type.

Inconsistent accessibility: property type is less accessible

make your class public access modifier,

just add public keyword infront of your class name

 namespace Test
{
  public  class Delivery
    {
        private string name;
        private string address;
        private DateTime arrivalTime;

        public string Name
        {
            get { return name; }
            set { name = value; }
        }

        public string Address
        {
            get { return address; }
            set { address = value; }
        }

        public DateTime ArrivlaTime
        {
            get { return arrivalTime; }
            set { arrivalTime = value; }
        }

        public string ToString()
        {
            { return name + address + arrivalTime.ToString(); }
        }
    }
}

Convert floats to ints in Pandas?

To convert all float columns to int

>>> df = pd.DataFrame(np.random.rand(5, 4) * 10, columns=list('PQRS'))
>>> print(df)
...     P           Q           R           S
... 0   4.395994    0.844292    8.543430    1.933934
... 1   0.311974    9.519054    6.171577    3.859993
... 2   2.056797    0.836150    5.270513    3.224497
... 3   3.919300    8.562298    6.852941    1.415992
... 4   9.958550    9.013425    8.703142    3.588733

>>> float_col = df.select_dtypes(include=['float64']) # This will select float columns only
>>> # list(float_col.columns.values)

>>> for col in float_col.columns.values:
...     df[col] = df[col].astype('int64')

>>> print(df)
...     P   Q   R   S
... 0   4   0   8   1
... 1   0   9   6   3
... 2   2   0   5   3
... 3   3   8   6   1
... 4   9   9   8   3

How to check if object has been disposed in C#

A good way is to derive from TcpClient and override the Disposing(bool) method:

class MyClient : TcpClient {
    public bool IsDead { get; set; }
    protected override void Dispose(bool disposing) {
        IsDead = true;
        base.Dispose(disposing);
    }
}

Which won't work if the other code created the instance. Then you'll have to do something desperate like using Reflection to get the value of the private m_CleanedUp member. Or catch the exception.

Frankly, none is this is likely to come to a very good end. You really did want to write to the TCP port. But you won't, that buggy code you can't control is now in control of your code. You've increased the impact of the bug. Talking to the owner of that code and working something out is by far the best solution.

EDIT: A reflection example:

using System.Reflection;
public static bool SocketIsDisposed(Socket s)
{
   BindingFlags bfIsDisposed = BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.GetProperty;
   // Retrieve a FieldInfo instance corresponding to the field
   PropertyInfo field = s.GetType().GetProperty("CleanedUp", bfIsDisposed);
   // Retrieve the value of the field, and cast as necessary
   return (bool)field.GetValue(s, null);
}

StringLength vs MaxLength attributes ASP.NET MVC with Entity Framework EF Code First

I have resolved it by adding below line in my context:

modelBuilder.Entity<YourObject>().Property(e => e.YourColumn).HasMaxLength(4000);

Somehow, [MaxLength] didn't work for me.

Calculate mean across dimension in a 2D array

a.mean() takes an axis argument:

In [1]: import numpy as np

In [2]: a = np.array([[40, 10], [50, 11]])

In [3]: a.mean(axis=1)     # to take the mean of each row
Out[3]: array([ 25. ,  30.5])

In [4]: a.mean(axis=0)     # to take the mean of each col
Out[4]: array([ 45. ,  10.5])

Or, as a standalone function:

In [5]: np.mean(a, axis=1)
Out[5]: array([ 25. ,  30.5])

The reason your slicing wasn't working is because this is the syntax for slicing:

In [6]: a[:,0].mean() # first column
Out[6]: 45.0

In [7]: a[:,1].mean() # second column
Out[7]: 10.5

UITextView that expands to text using auto layout

This more of a very important comment

Key to understanding why vitaminwater's answer works are three things:

  1. Know that UITextView is a subclass of UIScrollView class
  2. Understand how ScrollView works and how its contentSize is calculated. For more see this here answer and its various solutions and comments.
  3. Understand what contentSize is and how its calculated. See here and here. It might also help that setting contentOffset is likely nothing but:

func setContentOffset(offset: CGPoint)
{
    CGRect bounds = self.bounds
    bounds.origin = offset
    self.bounds = bounds
}

For more see objc scrollview and understanding scrollview


Combining the three together you'd easily understand that you need allow the the textView's intrinsic contentSize to work along AutoLayout constraints of the textView to drive the logic. It's almost as if you're textView is functioning like a UILabel

To make that happen you need to disable scrolling which basically means the scrollView's size, the contentSize's size and in case of adding a containerView, then the containerView's size would all be the same. When they're the same you have NO scrolling. And you'd have 0 contentOffset. Having 0 contentOffSet means you've not scrolled down. Not even a 1 point down! As a result the textView will be all stretched out.

It's also worth nothing that 0 contentOffset means that the scrollView's bounds and frame are identical. If you scroll down 5 points then your contentOffset would be 5, while your scrollView.bounds.origin.y - scrollView.frame.origin.y would be equal to 5

ip address validation in python using regex

Why not use a library function to validate the ip address?

>>> ip="241.1.1.112343434" 
>>> socket.inet_aton(ip)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
socket.error: illegal IP address string passed to inet_aton

Can't load AMD 64-bit .dll on a IA 32-bit platform

Uninstall(delete) this: jre, jdk, eclipse. Download 32 bit(x86) version of this programs:jre, jdk, eclipse. And install it.

How print out the contents of a HashMap<String, String> in ascending order based on its values?

You aren't going to be able to do this from the HashMap class alone.

I would take the Map<String, String> codes, construct a reverse map of TreeMap<String, String> reversedMap where you map the values of the codes Map to the keys (this would require your original Map to have a one-to-one mapping from key-to-value). Since the TreeMap provides Iterators which returns entries in ascending key order, this will give you the value/key combination of the first map in the order (sorted by values) you desire.

Map<String, String> reversedMap = new TreeMap<String, String>(codes);

//then you just access the reversedMap however you like...
for (Map.Entry entry : reversedMap.entrySet()) {
    System.out.println(entry.getKey() + ", " + entry.getValue());
}

There are several collections libraries (commons-collections, Google Collections, etc) which have similar bidirectional Map implementations.

"405 method not allowed" in IIS7.5 for "PUT" method

For whatever reason, marking WebDAVModule as "remove" in my web.config wasn't enough to fix the problem in my case.

I've found another approach that did solve the problem. If you're in the same boat, try this:

  1. In the IIS Manager, select the application that needs to support PUT.
  2. In the Features View, find WebDAV Authoring Rules. Double-click it, or select Open Feature from the context menu (right-click).
  3. In the Actions pane, find and click on WebDAV Settings....
  4. In the WebDAV Settings, find Request Filtering Behavior, and under that, find Allow Verb Filtering. Set Allow Verb Filtering to False.
  5. In the Actions pane, click Apply.

This prevents WebDAV from rejecting verbs that it doesn't support, thus allowing a PUT to flow through to your RESTful handler unmolested.

How to make a div with a circular shape?

Use a border-radius property of 50%.

So for example:

.example-div {

    border-radius: 50%

}

How do I call an Angular 2 pipe with multiple arguments?

Since beta.16 the parameters are not passed as array to the transform() method anymore but instead as individual parameters:

{{ myData | date:'fullDate':'arg1':'arg2' }}


export class DatePipe implements PipeTransform {    
  transform(value:any, arg1:any, arg2:any):any {
        ...
}

https://github.com/angular/angular/blob/master/CHANGELOG.md#200-beta16-2016-04-26

pipes now take a variable number of arguments, and not an array that contains all arguments.

How to find Max Date in List<Object>?

Comparator<User> cmp = new Comparator<User>() {
    @Override
    public int compare(User user1, User user2) {
        return user1.date.compareTo(user2.date);
    }
};

Collections.max(list, cmp);

<ng-container> vs <template>

The documentation (https://angular.io/guide/template-syntax#!#star-template) gives the following example. Say we have template code like this:

<hero-detail *ngIf="currentHero" [hero]="currentHero"></hero-detail>

Before it will be rendered, it will be "de-sugared". That is, the asterix notation will be transcribed to the notation:

<template [ngIf]="currentHero">
  <hero-detail [hero]="currentHero"></hero-detail>
</template>

If 'currentHero' is truthy this will be rendered as

<hero-detail> [...] </hero-detail>

But what if you want an conditional output like this:

<h1>Title</h1><br>
<p>text</p>

.. and you don't want the output be wrapped in a container.

You could write the de-sugared version directly like so:

<template [ngIf]="showContent">
  <h1>Title</h1>
  <p>text</p><br>
</template>

And this will work fine. However, now we need ngIf to have brackets [] instead of an asterix *, and this is confusing (https://github.com/angular/angular.io/issues/2303)

For that reason a different notation was created, like so:

<ng-container *ngIf="showContent"><br>
  <h1>Title</h1><br>
  <p>text</p><br>
</ng-container>

Both versions will produce the same results (only the h1 and p tag will be rendered). The second one is preferred because you can use *ngIf like always.

How do I use arrays in C++?

Programmers often confuse multidimensional arrays with arrays of pointers.

Multidimensional arrays

Most programmers are familiar with named multidimensional arrays, but many are unaware of the fact that multidimensional array can also be created anonymously. Multidimensional arrays are often referred to as "arrays of arrays" or "true multidimensional arrays".

Named multidimensional arrays

When using named multidimensional arrays, all dimensions must be known at compile time:

int H = read_int();
int W = read_int();

int connect_four[6][7];   // okay

int connect_four[H][7];   // ISO C++ forbids variable length array
int connect_four[6][W];   // ISO C++ forbids variable length array
int connect_four[H][W];   // ISO C++ forbids variable length array

This is how a named multidimensional array looks like in memory:

              +---+---+---+---+---+---+---+
connect_four: |   |   |   |   |   |   |   |
              +---+---+---+---+---+---+---+
              |   |   |   |   |   |   |   |
              +---+---+---+---+---+---+---+
              |   |   |   |   |   |   |   |
              +---+---+---+---+---+---+---+
              |   |   |   |   |   |   |   |
              +---+---+---+---+---+---+---+
              |   |   |   |   |   |   |   |
              +---+---+---+---+---+---+---+
              |   |   |   |   |   |   |   |
              +---+---+---+---+---+---+---+

Note that 2D grids such as the above are merely helpful visualizations. From the point of view of C++, memory is a "flat" sequence of bytes. The elements of a multidimensional array are stored in row-major order. That is, connect_four[0][6] and connect_four[1][0] are neighbors in memory. In fact, connect_four[0][7] and connect_four[1][0] denote the same element! This means that you can take multi-dimensional arrays and treat them as large, one-dimensional arrays:

int* p = &connect_four[0][0];
int* q = p + 42;
some_int_sequence_algorithm(p, q);

Anonymous multidimensional arrays

With anonymous multidimensional arrays, all dimensions except the first must be known at compile time:

int (*p)[7] = new int[6][7];   // okay
int (*p)[7] = new int[H][7];   // okay

int (*p)[W] = new int[6][W];   // ISO C++ forbids variable length array
int (*p)[W] = new int[H][W];   // ISO C++ forbids variable length array

This is how an anonymous multidimensional array looks like in memory:

              +---+---+---+---+---+---+---+
        +---> |   |   |   |   |   |   |   |
        |     +---+---+---+---+---+---+---+
        |     |   |   |   |   |   |   |   |
        |     +---+---+---+---+---+---+---+
        |     |   |   |   |   |   |   |   |
        |     +---+---+---+---+---+---+---+
        |     |   |   |   |   |   |   |   |
        |     +---+---+---+---+---+---+---+
        |     |   |   |   |   |   |   |   |
        |     +---+---+---+---+---+---+---+
        |     |   |   |   |   |   |   |   |
        |     +---+---+---+---+---+---+---+
        |
      +-|-+
   p: | | |
      +---+

Note that the array itself is still allocated as a single block in memory.

Arrays of pointers

You can overcome the restriction of fixed width by introducing another level of indirection.

Named arrays of pointers

Here is a named array of five pointers which are initialized with anonymous arrays of different lengths:

int* triangle[5];
for (int i = 0; i < 5; ++i)
{
    triangle[i] = new int[5 - i];
}

// ...

for (int i = 0; i < 5; ++i)
{
    delete[] triangle[i];
}

And here is how it looks like in memory:

          +---+---+---+---+---+
          |   |   |   |   |   |
          +---+---+---+---+---+
            ^
            | +---+---+---+---+
            | |   |   |   |   |
            | +---+---+---+---+
            |   ^
            |   | +---+---+---+
            |   | |   |   |   |
            |   | +---+---+---+
            |   |   ^
            |   |   | +---+---+
            |   |   | |   |   |
            |   |   | +---+---+
            |   |   |   ^
            |   |   |   | +---+
            |   |   |   | |   |
            |   |   |   | +---+
            |   |   |   |   ^
            |   |   |   |   |
            |   |   |   |   |
          +-|-+-|-+-|-+-|-+-|-+
triangle: | | | | | | | | | | |
          +---+---+---+---+---+

Since each line is allocated individually now, viewing 2D arrays as 1D arrays does not work anymore.

Anonymous arrays of pointers

Here is an anonymous array of 5 (or any other number of) pointers which are initialized with anonymous arrays of different lengths:

int n = calculate_five();   // or any other number
int** p = new int*[n];
for (int i = 0; i < n; ++i)
{
    p[i] = new int[n - i];
}

// ...

for (int i = 0; i < n; ++i)
{
    delete[] p[i];
}
delete[] p;   // note the extra delete[] !

And here is how it looks like in memory:

          +---+---+---+---+---+
          |   |   |   |   |   |
          +---+---+---+---+---+
            ^
            | +---+---+---+---+
            | |   |   |   |   |
            | +---+---+---+---+
            |   ^
            |   | +---+---+---+
            |   | |   |   |   |
            |   | +---+---+---+
            |   |   ^
            |   |   | +---+---+
            |   |   | |   |   |
            |   |   | +---+---+
            |   |   |   ^
            |   |   |   | +---+
            |   |   |   | |   |
            |   |   |   | +---+
            |   |   |   |   ^
            |   |   |   |   |
            |   |   |   |   |
          +-|-+-|-+-|-+-|-+-|-+
          | | | | | | | | | | |
          +---+---+---+---+---+
            ^
            |
            |
          +-|-+
       p: | | |
          +---+

Conversions

Array-to-pointer decay naturally extends to arrays of arrays and arrays of pointers:

int array_of_arrays[6][7];
int (*pointer_to_array)[7] = array_of_arrays;

int* array_of_pointers[6];
int** pointer_to_pointer = array_of_pointers;

However, there is no implicit conversion from T[h][w] to T**. If such an implicit conversion did exist, the result would be a pointer to the first element of an array of h pointers to T (each pointing to the first element of a line in the original 2D array), but that pointer array does not exist anywhere in memory yet. If you want such a conversion, you must create and fill the required pointer array manually:

int connect_four[6][7];

int** p = new int*[6];
for (int i = 0; i < 6; ++i)
{
    p[i] = connect_four[i];
}

// ...

delete[] p;

Note that this generates a view of the original multidimensional array. If you need a copy instead, you must create extra arrays and copy the data yourself:

int connect_four[6][7];

int** p = new int*[6];
for (int i = 0; i < 6; ++i)
{
    p[i] = new int[7];
    std::copy(connect_four[i], connect_four[i + 1], p[i]);
}

// ...

for (int i = 0; i < 6; ++i)
{
    delete[] p[i];
}
delete[] p;

How to get the index of an element in an IEnumerable?

I'd question the wisdom, but perhaps:

source.TakeWhile(x => x != value).Count();

(using EqualityComparer<T>.Default to emulate != if needed) - but you need to watch to return -1 if not found... so perhaps just do it the long way

public static int IndexOf<T>(this IEnumerable<T> source, T value)
{
    int index = 0;
    var comparer = EqualityComparer<T>.Default; // or pass in as a parameter
    foreach (T item in source)
    {
        if (comparer.Equals(item, value)) return index;
        index++;
    }
    return -1;
}

VBA Public Array : how to?

This worked for me, seems to work as global :

Dim savePos(2 To 8) As Integer

And can call it from every sub, for example getting first element :

MsgBox (savePos(2))

How to to send mail using gmail in Laravel?

The problem for me is that for some reason the username/password came NULL from mail config. To check that before sending a email check with the follow code:

dd(Config::get('mail'));

If your username/password came nulled just set with:

Config::set('mail.username', 'yourusername');
Config::set('mail.password', 'yourpassword');

A SELECT statement that assigns a value to a variable must not be combined with data-retrieval operations

declare @cur cursor
declare @idx int       
declare @Approval_No varchar(50) 

declare @ReqNo varchar(100)
declare @M_Id  varchar(100)
declare @Mail_ID varchar(100)
declare @temp  table
(
val varchar(100)
)
declare @temp2  table
(
appno varchar(100),
mailid varchar(100),
userod varchar(100)
)


    declare @slice varchar(8000)       
    declare @String varchar(100)
    --set @String = '1200096,1200095,1200094,1200093,1200092,1200092'
set @String = '20131'


    select @idx = 1       
        if len(@String)<1 or @String is null  return       

    while @idx!= 0       
    begin       
        set @idx = charindex(',',@String)       
        if @idx!=0       
            set @slice = left(@String,@idx - 1)       
        else       
            set @slice = @String

            --select @slice       
            insert into @temp values(@slice)
        set @String = right(@String,len(@String) - @idx)       
        if len(@String) = 0 break


    end
    -- select distinct(val) from @temp


SET @cur = CURSOR FOR select distinct(val) from @temp


--open cursor    
OPEN @cur    
--fetchng id into variable    
FETCH NEXT    
    FROM @cur into @Approval_No 

      --
    --loop still the end    
     while @@FETCH_STATUS = 0  
    BEGIN   


select distinct(Approval_Sr_No) as asd, @ReqNo=Approval_Sr_No,@M_Id=AM_ID,@Mail_ID=Mail_ID from WFMS_PRAO,WFMS_USERMASTER where  WFMS_PRAO.AM_ID=WFMS_USERMASTER.User_ID
and Approval_Sr_No=@Approval_No

   insert into @temp2 values(@ReqNo,@M_Id,@Mail_ID)  

FETCH NEXT    
      FROM @cur into @Approval_No    
 end  
    --close cursor    
    CLOSE @cur    

select * from @tem

Convert a List<T> into an ObservableCollection<T>

ObservableCollection < T > has a constructor overload which takes IEnumerable < T >

Example for a List of int:

ObservableCollection<int> myCollection = new ObservableCollection<int>(myList);

One more example for a List of ObjectA:

ObservableCollection<ObjectA> myCollection = new ObservableCollection<ObjectA>(myList as List<ObjectA>);

Postgresql - change the size of a varchar column to lower length

Adding new column and replacing new one with old worked for me, on redshift postgresql, refer this link for more details https://gist.github.com/mmasashi/7107430

BEGIN;
LOCK users;
ALTER TABLE users ADD COLUMN name_new varchar(512) DEFAULT NULL;
UPDATE users SET name_new = name;
ALTER TABLE users DROP name;
ALTER TABLE users RENAME name_new TO name;
END;

If statement within Where clause

CASE might help you out:

SELECT t.first_name,
       t.last_name,
       t.employid,
       t.status
  FROM employeetable t
 WHERE t.status = (CASE WHEN status_flag = STATUS_ACTIVE THEN 'A'
                        WHEN status_flag = STATUS_INACTIVE THEN 'T'
                        ELSE null END)
   AND t.business_unit = (CASE WHEN source_flag = SOURCE_FUNCTION THEN 'production'
                               WHEN source_flag = SOURCE_USER THEN 'users'
                               ELSE null END)
   AND t.first_name LIKE firstname
   AND t.last_name LIKE lastname
   AND t.employid LIKE employeeid;

The CASE statement evaluates multiple conditions to produce a single value. So, in the first usage, I check the value of status_flag, returning 'A', 'T' or null depending on what it's value is, and compare that to t.status. I do the same for the business_unit column with a second CASE statement.

HTML table needs spacing between columns, not rows

The better approach uses Shredder's css rule: padding: 0 15px 0 15px only instead of inline css, define a css rule that applies to all tds. Do This by using a style tag in your page:

<style type="text/css">
td
{
    padding:0 15px;
}
</style>

or give the table a class like "paddingBetweenCols" and in the site css use

.paddingBetweenCols td
{
    padding:0 15px;
}

The site css approach defines a central rule that can be reused by all pages.

If your doing to use the site css approach, it would be best to define a class like above and apply the padding to the class...unless you want all td's on the entire site to have the same rule applied.

Fiddle for using style tag

Fiddle for using site css

Where to place the 'assets' folder in Android Studio?

Simply, double shift then type Assets Folder

choose it to be created in the correct place

How to add a class to body tag?

Use:

$(document.body).addClass('about');

What's the difference between @JoinColumn and mappedBy when using a JPA @OneToMany association

I disagree with the accepted answer here by Óscar López. That answer is inaccurate!

It is NOT @JoinColumn which indicates that this entity is the owner of the relationship. Instead, it is the @ManyToOne annotation which does this (in his example).

The relationship annotations such as @ManyToOne, @OneToMany and @ManyToMany tell JPA/Hibernate to create a mapping. By default, this is done through a seperate Join Table.


@JoinColumn

The purpose of @JoinColumn is to create a join column if one does not already exist. If it does, then this annotation can be used to name the join column.


MappedBy

The purpose of the MappedBy parameter is to instruct JPA: Do NOT create another join table as the relationship is already being mapped by the opposite entity of this relationship.



Remember: MappedBy is a property of the relationship annotations whose purpose is to generate a mechanism to relate two entities which by default they do by creating a join table. MappedBy halts that process in one direction.

The entity not using MappedBy is said to be the owner of the relationship because the mechanics of the mapping are dictated within its class through the use of one of the three mapping annotations against the foreign key field. This not only specifies the nature of the mapping but also instructs the creation of a join table. Furthermore, the option to suppress the join table also exists by applying @JoinColumn annotation over the foreign key which keeps it inside the table of the owner entity instead.

So in summary: @JoinColumn either creates a new join column or renames an existing one; whilst the MappedBy parameter works collaboratively with the relationship annotations of the other (child) class in order to create a mapping either through a join table or by creating a foreign key column in the associated table of the owner entity.

To illustrate how MapppedBy works, consider the code below. If MappedBy parameter were to be deleted, then Hibernate would actually create TWO join tables! Why? Because there is a symmetry in many-to-many relationships and Hibernate has no rationale for selecting one direction over the other.

We therefore use MappedBy to tell Hibernate, we have chosen the other entity to dictate the mapping of the relationship between the two entities.

@Entity
public class Driver {
    @ManyToMany(mappedBy = "drivers")
    private List<Cars> cars;
}

@Entity
public class Cars {
    @ManyToMany
    private List<Drivers> drivers;
}

Adding @JoinColumn(name = "driverID") in the owner class (see below), will prevent the creation of a join table and instead, create a driverID foreign key column in the Cars table to construct a mapping:

@Entity
public class Driver {
    @ManyToMany(mappedBy = "drivers")
    private List<Cars> cars;
}

@Entity
public class Cars {
    @ManyToMany
    @JoinColumn(name = "driverID")
    private List<Drivers> drivers;
}

Why Python 3.6.1 throws AttributeError: module 'enum' has no attribute 'IntFlag'?

It's because your enum is not the standard library enum module. You probably have the package enum34 installed.

One way check if this is the case is to inspect the property enum.__file__

import enum
print(enum.__file__)  
# standard library location should be something like 
# /usr/local/lib/python3.6/enum.py

Since python 3.6 the enum34 library is no longer compatible with the standard library. The library is also unnecessary, so you can simply uninstall it.

pip uninstall -y enum34

If you need the code to run on python versions both <=3.4 and >3.4, you can try having enum-compat as a requirement. It only installs enum34 for older versions of python without the standard library enum.

Two div blocks on same line

Use Simple HTML

<frameset cols="25%,*">
  <frame src="frame_a.htm">
  <frame src="frame_b.htm">
</frameset>

How is VIP swapping + CNAMEs better than IP swapping + A records?

A VIP swap is an internal change to Azure's routers/load balancers, not an external DNS change. They're just routing traffic to go from one internal [set of] server[s] to another instead. Therefore the DNS info for mysite.cloudapp.net doesn't change at all. Therefore the change for people accessing via the IP bound to mysite.cloudapp.net (and CNAME'd by you) will see the change as soon as the VIP swap is complete.

Best way to repeat a character in C#

The answer really depends on the complexity you want. For example, I want to outline all my indents with a vertical bar, so my indent string is determined as follows:

return new string(Enumerable.Range(0, indentSize*indent).Select(
  n => n%4 == 0 ? '|' : ' ').ToArray());

Laravel Check If Related Model Exists

As Hemerson Varela already said in Php 7.1 count(null) will throw an error and hasOne returns null if no row exists. Since you have a hasOnerelation I would use the empty method to check:

$model = RepairItem::find($id);
if (!empty($temp = $request->input('option'))) {
   $option = $model->option;

   if(empty($option)){
      $option = $model->option()->create();
   }

   $option->someAttribute = temp;
   $option->save();
};

But this is superfluous. There is no need to check if the relation exists, to determine if you should do an update or a create call. Simply use the updateOrCreate method. This is equivalent to the above:

$model = RepairItem::find($id);
if (!empty($temp = $request->input('option'))) {  
   $model->option()
         ->updateOrCreate(['repair_item_id' => $model->id],
                          ['option' => $temp]);
}

How to duplicate a git repository? (without forking)

See https://help.github.com/articles/duplicating-a-repository

Short version:

In order to make an exact duplicate, you need to perform both a bare-clone and a mirror-push:

mkdir foo; cd foo 
# move to a scratch dir

git clone --bare https://github.com/exampleuser/old-repository.git
# Make a bare clone of the repository

cd old-repository.git
git push --mirror https://github.com/exampleuser/new-repository.git
# Mirror-push to the new repository

cd ..
rm -rf old-repository.git  
# Remove our temporary local repository

NOTE: the above will work fine with any remote git repo, the instructions are not specific to github

The above creates a new remote copy of the repo. Then clone it down to your working machine.

E: Unable to locate package mongodb-org

sudo apt-get install -y mongodb 

it works for 32-bit ubuntu, try it.best of luck.

update query with join on two tables

Using table aliases in the join condition:

update addresses a
set cid = b.id 
from customers b 
where a.id = b.id

How to validate phone number in laravel 5.2?

$request->validate([
    'phone' => 'numeric|required',
    'body' => 'required',
]);

Find row in datatable with specific id

You can use LINQ to DataSet/DataTable

var rows = dt.AsEnumerable()
               .Where(r=> r.Field<int>("ID") == 5);

Since each row has a unique ID, you should use Single/SingleOrDefault which would throw exception if you get multiple records back.

DataRow dr = dt.AsEnumerable()
               .SingleOrDefault(r=> r.Field<int>("ID") == 5);

(Substitute int for the type of your ID field)

reactjs giving error Uncaught TypeError: Super expression must either be null or a function, not undefined

Not correct for this answer but for others with same error my ridiculously silly mistake could potentially help.

Stupidly,my issue was using function notation by including () following the class name.

Make sure your syntax is correct. And you've imported & exported any external components/modules with the correct names and paths.

This template should work fine if you have a newish version of react installed:

import React, { Component } from 'react'

class ExampleClass extends Component {

    render(){
        return(
            <div>

            </div>
        )
    }
}

export default ExampleClass 

Why use @PostConstruct?

Consider the following scenario:

public class Car {
  @Inject
  private Engine engine;  

  public Car() {
    engine.initialize();  
  }
  ...
}

Since Car has to be instantiated prior to field injection, the injection point engine is still null during the execution of the constructor, resulting in a NullPointerException.

This problem can be solved either by JSR-330 Dependency Injection for Java constructor injection or JSR 250 Common Annotations for the Java @PostConstruct method annotation.

@PostConstruct

JSR-250 defines a common set of annotations which has been included in Java SE 6.

The PostConstruct annotation is used on a method that needs to be executed after dependency injection is done to perform any initialization. This method MUST be invoked before the class is put into service. This annotation MUST be supported on all classes that support dependency injection.

JSR-250 Chap. 2.5 javax.annotation.PostConstruct

The @PostConstruct annotation allows for the definition of methods to be executed after the instance has been instantiated and all injects have been performed.

public class Car {
  @Inject
  private Engine engine;  

  @PostConstruct
  public void postConstruct() {
    engine.initialize();  
  }
  ...
} 

Instead of performing the initialization in the constructor, the code is moved to a method annotated with @PostConstruct.

The processing of post-construct methods is a simple matter of finding all methods annotated with @PostConstruct and invoking them in turn.

private  void processPostConstruct(Class type, T targetInstance) {
  Method[] declaredMethods = type.getDeclaredMethods();

  Arrays.stream(declaredMethods)
      .filter(method -> method.getAnnotation(PostConstruct.class) != null) 
      .forEach(postConstructMethod -> {
         try {
           postConstructMethod.setAccessible(true);
           postConstructMethod.invoke(targetInstance, new Object[]{});
        } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException ex) {      
          throw new RuntimeException(ex);
        }
      });
}

The processing of post-construct methods has to be performed after instantiation and injection have been completed.

How to find all tables that have foreign keys that reference particular table.column and have values for those foreign keys?

MySQL 5.5 Reference Manual: "InnoDB and FOREIGN KEY Constraints"

SELECT
  ke.REFERENCED_TABLE_SCHEMA parentSchema,
  ke.referenced_table_name parentTable,
  ke.REFERENCED_COLUMN_NAME parentColumnName,
  ke.TABLE_SCHEMA ChildSchema,
  ke.table_name childTable,
  ke.COLUMN_NAME ChildColumnName
FROM
  information_schema.KEY_COLUMN_USAGE ke
WHERE
  ke.referenced_table_name IS NOT NULL
  AND ke.REFERENCED_COLUMN_NAME = 'ci_id' ## Find Foreign Keys linked to this Primary Key
ORDER BY
  ke.referenced_table_name;

WPF C# button style

<!--Customize button -->

<LinearGradientBrush x:Key="Buttongradient" StartPoint="0.500023,0.999996" EndPoint="0.500023,4.37507e-006">
    <GradientStop Color="#5e5e5e" Offset="1" />
    <GradientStop Color="#0b0b0b" Offset="0" />
</LinearGradientBrush> 

<Style x:Key="hhh" TargetType="{x:Type Button}">
    <Setter Property="Background" Value="{DynamicResource Buttongradient}"/>
    <Setter Property="Foreground" Value="White" />
    <Setter Property="FontSize" Value="15" />
    <Setter Property="SnapsToDevicePixels" Value="True" />
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="{x:Type Button}">
                <Border CornerRadius="4" Background="{TemplateBinding Background}" BorderBrush="Black" BorderThickness="0.5">
                    <Border.Effect>
                        <DropShadowEffect ShadowDepth="0" BlurRadius="2"></DropShadowEffect>
                    </Border.Effect>

                    <Grid>

                        <Path Width="9" Height="16.5" Stretch="Fill" Fill="#000"  HorizontalAlignment="Left" Margin="16.5,0,0,0" Data="F1 M 30.0833,22.1667L 50.6665,37.6043L 50.6665,38.7918L 30.0833,53.8333L 30.0833,22.1667 Z " Opacity="0.2">

                        </Path>
                        <Path x:Name="PathIcon" Width="8" Height="15"  Stretch="Fill" Fill="#4C87B3" HorizontalAlignment="Left" Margin="17,0,0,0" Data="F1 M 30.0833,22.1667L 50.6665,37.6043L 50.6665,38.7918L 30.0833,53.8333L 30.0833,22.1667 Z ">
                            <Path.Effect>
                                <DropShadowEffect ShadowDepth="0" BlurRadius="5"></DropShadowEffect>
                            </Path.Effect>
                        </Path>


                        <Line  HorizontalAlignment="Left" Margin="40,0,0,0" Name="line4" Stroke="Black" VerticalAlignment="Top" Width="2" Y1="0" Y2="640" Opacity="0.5" />
                        <ContentPresenter x:Name="MyContentPresenter" Content="{TemplateBinding Content}" HorizontalAlignment="Center" VerticalAlignment="Center" Margin="0,0,0,0" />
                    </Grid>
                </Border>

                <ControlTemplate.Triggers>
                    <Trigger Property="IsMouseOver" Value="True">
                        <Setter Property="Background" Value="#E59400" />
                        <Setter Property="Foreground" Value="White" />
                        <Setter TargetName="PathIcon" Property="Fill" Value="Black" />
                    </Trigger>

                    <Trigger Property="IsPressed" Value="True">
                        <Setter Property="Background" Value="OrangeRed" />
                        <Setter Property="Foreground" Value="White" />
                    </Trigger>
                </ControlTemplate.Triggers>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>  

In javascript, how do you search an array for a substring match

The simplest vanilla javascript code to achieve this is

var windowArray = ["item", "thing", "id-3-text", "class", "3-id-text"];
var textToFind = "id-";

//if you only want to match id- as prefix 
var matches = windowArray.filter(function(windowValue){
  if(windowValue) {
      return (windowValue.substring(0, textToFind.length) === textToFind);
  }
}); //["id-3-text"]

//if you want to match id- string exists at any position
var matches = windowArray.filter(function(windowValue){
  if(windowValue) {
      return windowValue.indexOf(textToFind) >= 0;
  }
}); //["id-3-text", "3-id-text"]

How do I URL encode a string

After reading all the answers for this topic and the (wrong) accepted one, I want to add my contribution.

IF the target is iOS7+, and in 2017 it should since XCode makes really hard to deliver compatibility under iOS8, the best way, thread safe, fast, amd will full UTF-8 support to do this is:

(Objective C code)

@implementation NSString (NSString_urlencoding)

- (NSString *)urlencode {
    static NSMutableCharacterSet *chars = nil;
    static dispatch_once_t pred;

    if (chars)
        return [self stringByAddingPercentEncodingWithAllowedCharacters:chars];

    // to be thread safe
    dispatch_once(&pred, ^{
        chars = NSCharacterSet.URLQueryAllowedCharacterSet.mutableCopy;
        [chars removeCharactersInString:@"!*'();:@&=+$,/?%#[]"];
    });
    return [self stringByAddingPercentEncodingWithAllowedCharacters:chars];
}
@end

This will extend NSString, will exclude RFC forbidden characters, support UTF-8 characters, and let you use things like:

NSString *myusername = "I'm[evil]&want(to)break!!!$->àéìòù";
NSLog(@"Source: %@ -> Dest: %@", myusername, [myusername urlencode]);

That will print on your debug console:

Source: I'm[evil]&want(to)break!!!$->àéìòù -> Dest: I%27m%5Bevil%5D%26want%28to%29break%21%21%21%24-%3E%C3%A0%C3%A9%C3%AC%C3%B2%C3%B9

... note also the use of dispatch_once to avoid multiple initializations in multithread environments.

RuntimeWarning: DateTimeField received a naive datetime

You can also override settings, particularly useful in tests:

from django.test import override_settings

with override_settings(USE_TZ=False):
    # Insert your code that causes the warning here
    pass

This will prevent you from seeing the warning, at the same time anything in your code that requires a timezone aware datetime may give you problems. If this is the case, see kravietz answer.

How to center the content inside a linear layout?

android:gravity handles the alignment of its children,

android:layout_gravity handles the alignment of itself.

So use one of these.

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#000"
    android:baselineAligned="false"
    android:gravity="center"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".Main" >

    <LinearLayout
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:gravity="center" >

        <ImageView
            android:id="@+id/imageButton_speak"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:background="@drawable/image_bg"
            android:src="@drawable/ic_speak" />
    </LinearLayout>

    <LinearLayout
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:gravity="center" >

        <ImageView
            android:id="@+id/imageButton_readtext"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:background="@drawable/image_bg"
            android:src="@drawable/ic_readtext" />
    </LinearLayout>

    ...
</LinearLayout>

or

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#000"
    android:baselineAligned="false"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".Main" >

    <LinearLayout
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:layout_weight="1" >

        <ImageView
            android:id="@+id/imageButton_speak"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:background="@drawable/image_bg"
            android:src="@drawable/ic_speak" />
    </LinearLayout>

    <LinearLayout
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:layout_weight="1" >

        <ImageView
            android:id="@+id/imageButton_readtext"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:background="@drawable/image_bg"
            android:src="@drawable/ic_readtext" />
    </LinearLayout>

    ...
</LinearLayout>

Mongodb: Failed to connect to 127.0.0.1:27017, reason: errno:10061

Here are the steps to solve this issue:

  1. Just go to your MongoDB bin folder and run the mongod.exe file.
  2. Navigate to your mongodb bin folder via Command prompt and start mongo by typing "mongo"

Runtime vs. Compile time

Compile Time:

Things that are done at compile time incur (almost) no cost when the resulting program is run, but might incur a large cost when you build the program. Run-Time:

More or less the exact opposite. Little cost when you build, more cost when the program is run.

From the other side; If something is done at compile time, it runs only on your machine and if something is run-time, it run on your users machine.

How do you display code snippets in MS Word preserving format and syntax highlighting?

enter image description here

Code Format Addin is now available in Office Addins with Office 365 ! Just select the code and click convert it and it converts the code text to formatted color code with line numbers !!!

Bit Rejoice!

Code Format is available here: https://appsource.microsoft.com/en-us/product/office/WA104379501?tab=Overview

window.onbeforeunload and window.onunload is not working in Firefox, Safari, Opera?

The onunload event is not called in all browsers. Worse, you cannot check the return value of onbeforeunload event. That prevents us from actually preforming a logout function.

However, you can hack around this.

Call logout first thing in the onbeforeunload event. then prompt the user. If the user cancels their logout, automatically login them back in, by using the onfocus event. Kinda backwards, but I think it should work.

'use strict';

var reconnect = false;

window.onfocus = function () {
  if (reconnect) {
    reconnect = false;
    alert("Perform an auto-login here!");
  }
};

window.onbeforeunload = function () {
  //logout();
  var msg = "Are you sure you want to leave?";
  reconnect = true;
  return msg;
};

What is an MDF file?

Just to make this absolutely clear for all:

A .MDF file is “typically” a SQL Server data file however it is important to note that it does NOT have to be.

This is because .MDF is nothing more than a recommended/preferred notation but the extension itself does not actually dictate the file type.

To illustrate this, if someone wanted to create their primary data file with an extension of .gbn they could go ahead and do so without issue.

To qualify the preferred naming conventions:

  • .mdf - Primary database data file.
  • .ndf - Other database data files i.e. non Primary.
  • .ldf - Log data file.

How do I store the select column in a variable?

This is how to assign a value to a variable:

SELECT @EmpID = Id
  FROM dbo.Employee

However, the above query is returning more than one value. You'll need to add a WHERE clause in order to return a single Id value.

SQL Server 2005 Setting a variable to the result of a select query

You could use:

declare @foo as nvarchar(25)

select @foo = 'bar'

select @foo

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

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

How to break out from foreach loop in javascript

Use a for loop instead of .forEach()

var myObj = [{"a": "1","b": null},{"a": "2","b": 5}]
var result = false

for(var call of myObj) {
    console.log(call)
    
    var a = call['a'], b = call['b']
     
    if(a == null || b == null) {
        result = false
        break
    }
}

What's the difference between & and && in MATLAB?

As already mentioned by others, & is a logical AND operator and && is a short-circuit AND operator. They differ in how the operands are evaluated as well as whether or not they operate on arrays or scalars:

  • & (AND operator) and | (OR operator) can operate on arrays in an element-wise fashion.
  • && and || are short-circuit versions for which the second operand is evaluated only when the result is not fully determined by the first operand. These can only operate on scalars, not arrays.

SQL, Postgres OIDs, What are they and why are they useful?

To remove all OIDs from your database tables, you can use this Linux script:

First, login as PostgreSQL superuser:

sudo su postgres

Now run this script, changing YOUR_DATABASE_NAME with you database name:

for tbl in `psql -qAt -c "select schemaname || '.' || tablename from pg_tables WHERE schemaname <> 'pg_catalog' AND schemaname <> 'information_schema';" YOUR_DATABASE_NAME` ; do  psql -c "alter table $tbl SET WITHOUT OIDS" YOUR_DATABASE_NAME ; done

I used this script to remove all my OIDs, since Npgsql 3.0 doesn't work with this, and it isn't important to PostgreSQL anymore.

How to open Console window in Eclipse?

Window > Perspective > Reset Perspective

Replace a character at a specific index in a string?

String is an immutable class in java. Any method which seems to modify it always returns a new string object with modification.

If you want to manipulate a string, consider StringBuilder or StringBuffer in case you require thread safety.

Convert object to JSON string in C#

Use .net inbuilt class JavaScriptSerializer

  JavaScriptSerializer js = new JavaScriptSerializer();
  string json = js.Serialize(obj);

How to connect to a remote Windows machine to execute commands using python?

I have personally found pywinrm library to be very effective. However, it does require some commands to be run on the machine and some other setup before it will work.

Query to select data between two dates with the format m/d/yyyy

SELECT * FROM tablename WHERE STR_TO_DATE(columnname, '%d/%m/%Y')
  BETWEEN STR_TO_DATE('29/05/2017', '%d/%m/%Y')
    AND STR_TO_DATE('30/05/2017', '%d/%m/%Y')

It works perfectly :)

How to match hyphens with Regular Expression?

The hyphen is usually a normal character in regular expressions. Only if it’s in a character class and between two other characters does it take a special meaning.

Thus:

  • [-] matches a hyphen.
  • [abc-] matches a, b, c or a hyphen.
  • [-abc] matches a, b, c or a hyphen.
  • [ab-d] matches a, b, c or d (only here the hyphen denotes a character range).

no default constructor exists for class

You declared the constructor blowfish as this:

Blowfish(BlowfishAlgorithm algorithm);

So this line cannot exist (without further initialization later):

Blowfish _blowfish;

since you passed no parameter. It does not understand how to handle a parameter-less declaration of object "BlowFish" - you need to create another constructor for that.

Doctrine2: Best way to handle many-to-many with extra columns in reference table

I was getting from a conflict with join table defined in an association class ( with additional custom fields ) annotation and a join table defined in a many-to-many annotation.

The mapping definitions in two entities with a direct many-to-many relationship appeared to result in the automatic creation of the join table using the 'joinTable' annotation. However the join table was already defined by an annotation in its underlying entity class and I wanted it to use this association entity class's own field definitions so as to extend the join table with additional custom fields.

The explanation and solution is that identified by FMaz008 above. In my situation, it was thanks to this post in the forum 'Doctrine Annotation Question'. This post draws attention to the Doctrine documentation regarding ManyToMany Uni-directional relationships. Look at the note regarding the approach of using an 'association entity class' thus replacing the many-to-many annotation mapping directly between two main entity classes with a one-to-many annotation in the main entity classes and two 'many-to-one' annotations in the associative entity class. There is an example provided in this forum post Association models with extra fields:

public class Person {

  /** @OneToMany(targetEntity="AssignedItems", mappedBy="person") */
  private $assignedItems;

}

public class Items {

    /** @OneToMany(targetEntity="AssignedItems", mappedBy="item") */
    private $assignedPeople;
}

public class AssignedItems {

    /** @ManyToOne(targetEntity="Person")
    * @JoinColumn(name="person_id", referencedColumnName="id")
    */
private $person;

    /** @ManyToOne(targetEntity="Item")
    * @JoinColumn(name="item_id", referencedColumnName="id")
    */
private $item;

}

Creating composite primary key in SQL Server

it simple, select columns want to insert primary key and click on Key icon on header and save tablesql composite key

happy coding..,

MaxLength Attribute not generating client-side validation attributes

I tried this for all the inputs in my html document(textarea,inputs,etc) that had the data-val-length-max property and it works correctly.

$(document).ready(function () {
    $(":input[data-val-length-max]").each(function (index, element) {
        var length = parseInt($(this).attr("data-val-length-max"));
        $(this).prop("maxlength", length);
    });
});

document.getElementById().value and document.getElementById().checked not working for IE

Jin Yong - IE has an issue with polluting the global scope with object references to any DOM elements with a "name" or "id" attribute set on the "initial" page load.

Thus you may have issues due to your variable name.

Try this and see if it works.

var someOtherName="abc";
//  ^^^^^^^^^^^^^
document.getElementById('msg').value = someOtherName;
document.getElementById('sp_100').checked = true;

There is a chance (in your original code) that IE attempts to set the value of the input to a reference to that actual element (ignores the error) but leaves you with no new value.

Keep in mind that in IE6/IE7 case doesn't matter for naming objects. IE believes that "foo" "Foo" and "FOO" are all the same object.

Convert columns to string in Pandas

Here's the other one, particularly useful to convert the multiple columns to string instead of just single column:

In [76]: import numpy as np
In [77]: import pandas as pd
In [78]: df = pd.DataFrame({
    ...:     'A': [20, 30.0, np.nan],
    ...:     'B': ["a45a", "a3", "b1"],
    ...:     'C': [10, 5, np.nan]})
    ...: 

In [79]: df.dtypes ## Current datatype
Out[79]: 
A    float64
B     object
C    float64
dtype: object

## Multiple columns string conversion
In [80]: df[["A", "C"]] = df[["A", "C"]].astype(str) 

In [81]: df.dtypes ## Updated datatype after string conversion
Out[81]: 
A    object
B    object
C    object
dtype: object

Pass Arraylist as argument to function

It depends on how and where you declared your array list. If it is an instance variable in the same class like your AnalyseArray() method you don't have to pass it along. The method will know the list and you can simply use the A in whatever purpose you need.

If they don't know each other, e.g. beeing a local variable or declared in a different class, define that your AnalyseArray() method needs an ArrayList parameter

public void AnalyseArray(ArrayList<Integer> theList){}

and then work with theList inside that method. But don't forget to actually pass it on when calling the method.AnalyseArray(A);

PS: Some maybe helpful Information to Variables and parameters.

text-align: right; not working for <label>

Label is an inline element - so, unless a width is defined, its width is exact the same which the letters span. Your div element is a block element so its width is by default 100%.

You will have to place the text-align: right; on the div element in your case, or applying display: block; to your label

Another option is to set a width for each label and then use text-align. The display: block method will not be necessary using this.

Create folder with batch but only if it doesn't already exist

This should work for you:

IF NOT EXIST "\path\to\your\folder" md \path\to\your\folder

However, there is another method, but it may not be 100% useful:

md \path\to\your\folder >NUL 2>NUL

This one creates the folder, but does not show the error output if folder exists. I highly recommend that you use the first one. The second one is if you have problems with the other.

Is there something like Codecademy for Java

Check out CodingBat! It really helped me learn java way back when (although it used to be JavaBat back then). It's a lot like Codecademy.

how to bind img src in angular 2 in ngFor?

Angular 2, 4 and Angular 5 compatible!

You have provided so few details, so I'll try to answer your question without them.

You can use Interpolation:

<img src={{imagePath}} />

Or you can use a template expression:

<img [src]="imagePath" />

In a ngFor loop it might look like this:

<div *ngFor="let student of students">
   <img src={{student.ImagePath}} />
</div>

for each inside a for each - Java

If I understand correctly, what you want to do, in pseudo-code is the following:

for (Tweet tweet : tweets) {
    if (!db.containsTweet(tweet.getId())) {
        db.insertTweet(tweet.getText(), tweet.getId());
    }
}

I assume your db class actually uses an sqlite database as a backend? What you could do is implement containsTweet directly and just query the database each time, but that seems less than perfect. The easiest solution if we go by your base code is to just keep a Set around that indexes the tweets. Since I can't be sure what the equals() method of Tweet looks like, I'll just store the identifiers in there. Then you get:

Set<Integer> tweetIds = new HashSet<Integer>(); // or long, whatever
for (Tweet tweet : tweets) {
    if (!tweetIds.contains(tweet.getId())) {
        db.insertTweet(tweet.getText(), tweet.getId());
        tweetIds.add(tweet.getId());
    }
}

It would probably be better to save a tiny bit of this work, by sorting the list of tweets to begin with and then just filtering out duplicate tweets. You could use:

// if tweets is a List
Collections.sort(tweets, new Comparator() {
    public int compare (Object t1, Object t2) {
        // might be the wrong way around
        return ((Tweet)t1).getId() - ((Tweet)t2).getId();
    }
}

Then process it

Integer oldId;
for (Tweet tweet : tweets) {
    if (oldId == null || oldId != tweet.getId()) {
        db.insertTweet(tweet.getText(), tweet.getId());
    }
    oldId = tweet.getId();
}

Yes, you could do this using a second for-loop, but you'll run into performance problems much more quickly than with this approach (although what we're doing here is trading time for memory performance, of course).

API vs. Webservice

Basically, a webservice is a method of communication between two machines while an API is an exposed layer allowing you to program against something.

You could very well have an API and the main method of interacting with that API is via a webservice.

The technical definitions (courtesy of Wikipedia) are:

API

An application programming interface (API) is a set of routines, data structures, object classes and/or protocols provided by libraries and/or operating system services in order to support the building of applications.

Webservice

A Web service (also Web Service) is defined by the W3C as "a software system designed to support interoperable machine-to-machine interaction over a network"

Understanding the grid classes ( col-sm-# and col-lg-# ) in Bootstrap 3

"If I want two columns for anything over 768px, should I apply both classes?"

This should be as simple as:

<div class="row">
      <div class="col-sm-6"></div>
      <div class="col-sm-6"></div>    
</div>

No need to add the col-lg-6 too.

Demo: http://www.bootply.com/73119

creating a new list with subset of list using index in python

The following definition might be more efficient than the first solution proposed

def new_list_from_intervals(original_list, *intervals):
    n = sum(j - i for i, j in intervals)
    new_list = [None] * n
    index = 0
    for i, j in intervals :
        for k in range(i, j) :
            new_list[index] = original_list[k]
            index += 1

    return new_list

then you can use it like below

new_list = new_list_from_intervals(original_list, (0,2), (4,5), (6, len(original_list)))

Error including image in Latex

I've had the same problems including jpegs in LaTeX. The engine isn't really built to gather all the necessary size and scale information from JPGs. It is often better to take the JPEG and convert it into a PDF (on a mac) or EPS (on a PC). GraphicsConvertor on a mac will do that for you easily. Whereas a PDF includes DPI and size, a JPEG has only a size in terms of pixels.

( I know this is not the answer you wanted, but it's probably better to give them EPS/PDF that they can use than to worry about what happens when they try to scale your JPG).