text:
Q: Import numpy from macOS Terminal running python launches but not from python script My goal is to be able to run NumPy through simple scripts. Being new at this, simple is not so simple. From the Terminal running python, NumPy works just fine. However, I can not import it from a script. The numpy sample runs from python with the following result.
>>> import numpy as np
>>> a = np.arange(15).reshape(3, 5)
>>> a
array([[ 0,  1,  2,  3,  4],
       [ 5,  6,  7,  8,  9],
       [10, 11, 12, 13, 14]])

However, from my script, runNumPy.py
#!/usr/bin/sh/env python3.6
print("Hello world! from runNumPy.py in python called by Terminal")
import sys, os
print("Current Working Directory: ", os.getcwd())
import numpy as np

I get
>>> a = np.arange(15).reshape(3, 5)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'np' is not defined

I have tried it with "import numpy as np" and without "as np."
My Terminal script is
#!/bin/sh
echo "Hello, world! Starts helloWorld.sh Terminal script."
source opt/anaconda3/etc/profile.d/conda.sh
conda activate bioETE
cd opt; cd anaconda3; cd envs; cd bioETE; cd lib; cd python3.6; cd site-packages
python ./runNumPyS.py  #This runs runNumPyS.py from the terminal
python ./runNumPy.py    #This runs the runNumPy.py from the terminal
python

It's output is
Hello, world! Starts helloWorld.sh Terminal script.
Hello world: from helloWorld.py in python script called by Terminal
Hello world! from runNumPy.py in python called by Terminal
Current Working Directory:  home/opt/anaconda3/envs/bioETE/lib/python3.6/site-packages
Python 3.6.12 |Anaconda, Inc.| (default, Sep  8 2020, 17:50:39)
[GCC Clang 10.0.0 ] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>>

As stated before my goal is to begin NumPy at the python prompt >>> without using another import statement. This shell script works fine. It calls the python scripts.
In the output above, the first "Hello World" was to show the shell script was working before I went any further. The other two, "Hello World", were to see if the python scripts were called.
You can see by th python script output the python print commands and sys and os import calls worked OK. The system call seems to tell me I am in the correct directory..??
The runNumPy.py script is
#!/usr/bin/sh/env python3.6
print("Hello world! from runNumPy.py in python called by Terminal")
import sys, os
print("Current Working Directory: ", os.getcwd())
import numpy as np

At the python prompt, I get the following error.
>>> a = np.arange(15).reshape(3, 5)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'np' is not defined

Clearly, numpy has not been imported. Again, at this same prompt, if I type in the "import numpy as np" first, NumPy works just fine.
NumPy's module numpy is located at
home/opt/anaconda3/envs/bioETE/lib/python3.6/site-packages/numpy

I've tried placing python script, runNumPy.py, in two places.
1)home/opt/anaconda3/envs/bioETE/lib/python3.6/site-packages
2)home/opt/anaconda3/envs/bioETE/lib/python3.6/

Neither place seems to work. I'm stuck for the moment. Any and all helpful suggestions or a solution or two will be appreciated.

A: You write:

As stated before my goal is to begin NumPy at the python prompt >>> without using another import statement. This shell script works fine. It calls the python scripts.

This is actually not a good goal. You should try to get out of the habit of running python from the interactive prompt. It's hard to develop significant programs that way. If you really want to run Python this way, you should look into use Jupyter Notebook or JupyterLab, both of which are included in your Python anaconda release.
The reason you don't want to just hack a bunch of stuff into your environment is that you won't be able to create scripts or programs that others can easily use. This is also the reason that you don't want to build a dependency on your current directory into your program. You should rely on site-packages being in sys.path; you should not be changing your current directory so that site-packages is your current directory.
Does this make sense?
However, if you really want to muck with the command line environment, you will find it useful to read this document:

*

*https://docs.python.org/3/using/cmdline.html
In particular, set the environment variable PYTHONSTARTUP to contain the python commands that you want executed before python starts up in interactive mode.


text:
Q: JCheckBoxTree initial state issue I m using a custom JTree that implements a drag and drop, and the cell renderer is a Jcheckbox
The issue is that my checkbox state differs from my jtree selection state, since I m updating the checkbox selection status in the cell renderer
@Override
public TreeCellRenderer getCellRenderer() {
    return (tree, value, selected, expanded, leaf, row, hasFocus) -> {

        selected = GridManager.getInstance().getDisplayableSources().containsKey(value+"");
        final String key = value + "";
        final JCheckBoxMenuItem jCheckBoxMenuItem = new JCheckBoxMenuItem(key);
        jCheckBoxMenuItem.setSelected(selected);
        return jCheckBoxMenuItem;
    };
}

I m well aware that there is some kind of inner state of selection that is triggered (fired) by click events which is reflected by the selected lambda parameter, that what explain my drag and drop miss-behavior
So how to update the JTree selection so I can use my renderer in a blind way like this
@Override
public TreeCellRenderer getCellRenderer() {
    return (tree, value, selected, expanded, leaf, row, hasFocus) -> {
        final String key = value + "";
        final JCheckBoxMenuItem jCheckBoxMenuItem = new JCheckBoxMenuItem(key);
        jCheckBoxMenuItem.setSelected(selected);
        return jCheckBoxMenuItem;
    };
}

Here is my full implementation
import java.util.HashMap;

import javax.swing.DropMode;
import javax.swing.JCheckBoxMenuItem;
import javax.swing.JTree;
import javax.swing.event.TreeSelectionEvent;
import javax.swing.event.TreeSelectionListener;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.TreeCellRenderer;
import javax.swing.tree.TreePath;

import com.wanasis.vlc.control.GridManager;
import com.wanasis.vlc.domain.SourceNode;

public class JCheckBoxDragableTree extends JTree {

    /**
     *
     */
    private static final long serialVersionUID = -7768978192373533316L;
    private HashMap<String, SourceNode> configurableSources;
    private static HashMap<String, String> displaySources = new HashMap<>();

    public JCheckBoxDragableTree(HashMap<String, SourceNode> configurableSources,
            HashMap<String, String> displaySources) {

        this.configurableSources = configurableSources;
        this.displaySources = displaySources;
        final DefaultTreeModel dtm = new DefaultTreeModel(new DefaultMutableTreeNode());

        final DefaultMutableTreeNode root = (DefaultMutableTreeNode) dtm.getRoot();
        configurableSources.values().stream().filter(s -> {
            return s.getParent().isEmpty();
        }).forEachOrdered(child -> {
            dtm.insertNodeInto(new DefaultMutableTreeNode(child.getId()), root, root.getChildCount());
        });
        setModel(dtm);

        setDragEnabled(true);
        setDropMode(DropMode.ON);
        setTransferHandler(new TreeTransferHandler());
        setSelectionModel(new SomativeSelectionModel());
        addTreeSelectionListener(new TreeSelectionListener() {

            @Override
            public void valueChanged(TreeSelectionEvent e) {

                String key = ""+e.getPath().getLastPathComponent();
                DefaultMutableTreeNode dmtn = (DefaultMutableTreeNode) e.getPath().getLastPathComponent();
                System.out.println(dmtn.getUserObject());
                System.out.println(key);
                GridManager gm = GridManager.getInstance();
                boolean isDisplayed = gm.getDisplayableSources().containsKey(key);
                if (isDisplayed) {
                    System.out.println("hiding selected element");
                    gm.getDisplayableSources().remove(key);
                    System.out.println(gm.getDisplayableSources().keySet());
                } else {
                    System.out.println("showing selected element");
                    gm.getDisplayableSources().put(key, gm.getConfigurableSources().get(key).getSource());

                    System.out.println(gm.getDisplayableSources().keySet());
                }
                gm.prepareDisplay();

            }
        });

    }

    @Override
    public void setSelectionPath(TreePath path) {

        addSelectionPath(path);

        return;
    }

    @Override
    public void setSelectionPaths(TreePath[] paths) {

        addSelectionPaths(paths);

        return;
    }

    @Override
    public void setSelectionRow(int row) {

        addSelectionRow(row);

        return;
    }

    @Override
    public void setSelectionRows(int[] rows) {

        addSelectionRows(rows);

        return;
    }

    @Override
    public TreeCellRenderer getCellRenderer() {
        return (tree, value, selected, expanded, leaf, row, hasFocus) -> {

            selected = GridManager.getInstance().getDisplayableSources().containsKey(value+"");
            final String key = value + "";
            final JCheckBoxMenuItem jCheckBoxMenuItem = new JCheckBoxMenuItem(key);
            jCheckBoxMenuItem.setSelected(selected);
            return jCheckBoxMenuItem;
        };
    }
}

A: In my case I updated all my code, the following jtree is drag and drop with checkboxes as cell renderer
I m also attaching some event logic to the D&D and the the checkbox selection event, all you have to do is to update it as you need
wish this will help
import java.awt.Color;
import java.awt.Component;
import java.awt.Font;
import java.awt.Insets;
import java.awt.Point;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.Transferable;
import java.awt.datatransfer.UnsupportedFlavorException;
import java.awt.dnd.DnDConstants;
import java.awt.dnd.DragGestureEvent;
import java.awt.dnd.DragGestureListener;
import java.awt.dnd.DragGestureRecognizer;
import java.awt.dnd.DragSource;
import java.awt.dnd.DragSourceDragEvent;
import java.awt.dnd.DragSourceDropEvent;
import java.awt.dnd.DragSourceEvent;
import java.awt.dnd.DragSourceListener;
import java.awt.dnd.DropTarget;
import java.awt.dnd.DropTargetContext;
import java.awt.dnd.DropTargetDragEvent;
import java.awt.dnd.DropTargetDropEvent;
import java.awt.dnd.DropTargetEvent;
import java.awt.dnd.DropTargetListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.awt.event.MouseEvent;
import java.io.IOException;
import java.util.EventObject;
import java.util.HashMap;

import javax.swing.AbstractCellEditor;
import javax.swing.Icon;
import javax.swing.JCheckBox;
import javax.swing.JTree;
import javax.swing.UIManager;
import javax.swing.border.LineBorder;
import javax.swing.event.TreeSelectionEvent;
import javax.swing.event.TreeSelectionListener;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeCellRenderer;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.TreeCellEditor;
import javax.swing.tree.TreeCellRenderer;
import javax.swing.tree.TreeNode;
import javax.swing.tree.TreePath;

import com.wanasis.vlc.control.GridManager;
import com.wanasis.vlc.domain.SourceNode;

public class JCheckBoxDragableTree extends JTree {

    /**
     *
     */
    private static final long serialVersionUID = -776897819237333316L;
    private HashMap<String, SourceNode> configurableSources;
    private static HashMap<String, String> displaySources = new HashMap<>();

    private static DefaultMutableTreeNode root = new DefaultMutableTreeNode("wanaDVR");

    TreeDragSource ds;

    TreeDropTarget dt;

    public JCheckBoxDragableTree(HashMap<String, SourceNode> configurableSources, HashMap<String, String> displaySources) {
        super(root);
        System.out.println("JCheckBoxDragableTree");
        setupTreeElements(configurableSources);

        this.configurableSources = configurableSources;
        this.displaySources = displaySources;

        setCellRenderer(new CheckBoxTreeNodeRenderer());
        setCellEditor(new CheckBoxTreeNodeEditor(this));
        setEditable(true);
        ds = new TreeDragSource(this, DnDConstants.ACTION_COPY_OR_MOVE);
        dt = new TreeDropTarget(this);

        addTreeSelectionListener(new TreeSelectionListener() {

            @Override
            public void valueChanged(TreeSelectionEvent e) {

                GridManager gm = GridManager.getInstance();
                String key = "" + e.getPath().getLastPathComponent();
                DefaultMutableTreeNode dmtn = (DefaultMutableTreeNode) e.getPath().getLastPathComponent();
                System.out.println(dmtn.getUserObject());
                System.out.println(key);

            }
        });
    }

    public void setupTreeElements(HashMap<String, SourceNode> configurableSources) {
        final HashMap<String, DefaultMutableTreeNode> parents = new HashMap<>();
        final HashMap<String, SourceNode> reste = new HashMap<>();

        configurableSources.values().stream().filter(s -> {
            return s.getParent().isEmpty()||s.getParent().trim().toLowerCase().equals("wanadvr");
        }).forEachOrdered(child -> {
            String key = child.getId();
            DefaultMutableTreeNode newChild = new DefaultMutableTreeNode(key);
            parents.put(key, newChild);
            root.add(newChild);
        });
        configurableSources.values().stream().filter(s -> {
            return !s.getParent().isEmpty() && !s.getParent().trim().toLowerCase().equals("wanadvr");
        }).forEachOrdered(child -> {
            String parentKey = child.getParent();
            String key = child.getId();
            DefaultMutableTreeNode newChild = new DefaultMutableTreeNode(key);
            if (parents.keySet().contains(parentKey)) {
                parents.get(parentKey).add(newChild);
                parents.put(key, newChild);
            } else {
                reste.put(key, child);
            }
        });
        while (reste.size() > 0) {
            reste.values().stream().forEachOrdered(child -> {
                String parentKey = child.getParent();
                String key = child.getId();
                DefaultMutableTreeNode newChild = new DefaultMutableTreeNode(key);
                if (parents.keySet().contains(parentKey)) {
                    parents.get(parentKey).add(newChild);
                    parents.put(key, newChild);
                    reste.remove(key);
                }
            });
        }
    }
}

class TreeNodeCheckBox extends JCheckBox {

    public TreeNodeCheckBox() {
        this("", false);
    }

    public TreeNodeCheckBox(final String text, final boolean selected) {
        this(text, null, selected);
    }

    public TreeNodeCheckBox(final String text, final Icon icon, final boolean selected) {
        super(text, icon, selected);
        setMargin(new Insets(1, 1, 1, 1));

        System.out.println(text);
        System.out.println(isSelected());
        GridManager instance = GridManager.getInstance();
        if (isSelected()) {
            instance.getDisplayableSources().put(text, instance.getConfigurableSources().get(text).getSource());

        }else {
            instance.getDisplayableSources().remove(text);
        }
        instance.prepareDisplay();
    }
}

class CheckBoxTreeNodeRenderer implements TreeCellRenderer {
    Color selectionBorderColor, selectionForeground, selectionBackground, textForeground, textBackground;
    private TreeNodeCheckBox treeNodeCheckBox = new TreeNodeCheckBox();
    private DefaultTreeCellRenderer defaultRenderer = new DefaultTreeCellRenderer();

    public CheckBoxTreeNodeRenderer() {
        Font fontValue;
        fontValue = UIManager.getFont("Tree.font");
        if (fontValue != null) {
            treeNodeCheckBox.setFont(fontValue);
        }
        Boolean booleanValue = (Boolean) UIManager.get("Tree.drawsFocusBorderAroundIcon");
        treeNodeCheckBox.setFocusPainted((booleanValue != null) && (booleanValue.booleanValue()));

        selectionBorderColor = UIManager.getColor("Tree.selectionBorderColor");
        selectionForeground = UIManager.getColor("Tree.selectionForeground");
        selectionBackground = UIManager.getColor("Tree.selectionBackground");
        textForeground = UIManager.getColor("Tree.textForeground");
        textBackground = UIManager.getColor("Tree.textBackground");
    }

    protected TreeNodeCheckBox getCheckBoxRenderer() {
        return treeNodeCheckBox;
    }

    public Component getTreeCellRendererComponent(JTree tree, Object value, boolean selected, boolean expanded,
            boolean leaf, int row, boolean hasFocus) {
        Component component;
        if (leaf) {
            String stringValue = tree.convertValueToText(value, selected, expanded, leaf, row, false);

            treeNodeCheckBox.setText(stringValue);
            treeNodeCheckBox.setSelected(GridManager.getInstance().getDisplayableSources().keySet().contains(stringValue));
            treeNodeCheckBox.setEnabled(tree.isEnabled());
            if (selected) {
                treeNodeCheckBox.setBorder(new LineBorder(selectionBorderColor));
                treeNodeCheckBox.setForeground(selectionForeground);
                treeNodeCheckBox.setBackground(selectionBackground);
            } else {
                treeNodeCheckBox.setBorder(null);
                treeNodeCheckBox.setForeground(textForeground);
                treeNodeCheckBox.setBackground(textBackground);
            }
            if ((value != null) && (value instanceof DefaultMutableTreeNode)) {
                Object userObject = ((DefaultMutableTreeNode) value).getUserObject();
                if (userObject instanceof TreeNodeCheckBox) {
                    TreeNodeCheckBox node = (TreeNodeCheckBox) userObject;
                    treeNodeCheckBox.setText(node.getText());
                    treeNodeCheckBox.setSelected(node.isSelected());
                }
            }
            component = treeNodeCheckBox;
        } else {
            component = defaultRenderer.getTreeCellRendererComponent(tree, value, selected, expanded, leaf, row,
                    hasFocus);
        }
        return component;
    }
}

class CheckBoxTreeNodeEditor extends AbstractCellEditor implements TreeCellEditor {
    CheckBoxTreeNodeRenderer renderer = new CheckBoxTreeNodeRenderer();
    JTree tree;

    public CheckBoxTreeNodeEditor(JTree tree) {
        this.tree = tree;
    }

    public Object getCellEditorValue() {
        TreeNodeCheckBox checkBox = renderer.getCheckBoxRenderer();
        TreeNodeCheckBox checkBoxNode = new TreeNodeCheckBox(checkBox.getText(), checkBox.isSelected());
        return checkBoxNode;
    }

    public boolean isCellEditable(EventObject event) {
        boolean editable = false;
        if (event instanceof MouseEvent) {
            MouseEvent mouseEvent = (MouseEvent) event;
            TreePath path = tree.getPathForLocation(mouseEvent.getX(), mouseEvent.getY());
            if (path != null) {
                Object node = path.getLastPathComponent();
                if ((node != null) && (node instanceof DefaultMutableTreeNode)) {
                    DefaultMutableTreeNode treeNode = (DefaultMutableTreeNode) node;
                    editable = treeNode.isLeaf();
                }
            }
        }
        return editable;
    }

    public Component getTreeCellEditorComponent(JTree tree, Object value, boolean selected, boolean expanded,
            boolean leaf, int row) {
        Component editor = renderer.getTreeCellRendererComponent(tree, value, true, expanded, leaf, row, true);
        if (editor instanceof TreeNodeCheckBox) {
            ((TreeNodeCheckBox) editor).addItemListener(new ItemListener() {
                public void itemStateChanged(ItemEvent itemEvent) {
                    if (stopCellEditing()) {
                        fireEditingStopped();
                    }
                }
            });
        }
        return editor;
    }

}

class TreeDragSource implements DragSourceListener, DragGestureListener {

    DragSource source;

    DragGestureRecognizer recognizer;

    TransferableTreeNode transferable;

    DefaultMutableTreeNode oldNode;

    JTree sourceTree;

    public TreeDragSource(JTree tree, int actions) {
        sourceTree = tree;
        source = new DragSource();
        recognizer = source.createDefaultDragGestureRecognizer(sourceTree, actions, this);
    }

    /*
     * Drag Gesture Handler
     */
    public void dragGestureRecognized(DragGestureEvent dge) {
        TreePath path = sourceTree.getSelectionPath();
        if ((path == null) || (path.getPathCount() <= 1)) {
            // We can't move the root node or an empty selection
            return;
        }
        oldNode = (DefaultMutableTreeNode) path.getLastPathComponent();
        transferable = new TransferableTreeNode(path);
        // source.startDrag(dge, DragSource.DefaultMoveNoDrop, transferable, this);

        // If you support dropping the node anywhere, you should probably
        // start with a valid move cursor:
        source.startDrag(dge, DragSource.DefaultMoveDrop, transferable, this);
    }

    /*
     * Drag Event Handlers
     */
    public void dragEnter(DragSourceDragEvent dsde) {
    }

    public void dragExit(DragSourceEvent dse) {
    }

    public void dragOver(DragSourceDragEvent dsde) {
    }

    public void dropActionChanged(DragSourceDragEvent dsde) {
        System.out.println("Action: " + dsde.getDropAction());
        System.out.println("Target Action: " + dsde.getTargetActions());
        System.out.println("User Action: " + dsde.getUserAction());
    }

    public void dragDropEnd(DragSourceDropEvent dsde) {
        /*
         * to support move or copy, we have to check which occurred:
         */
        System.out.println("Drop Action: " + dsde.getDropAction());
        if (dsde.getDropSuccess() && (dsde.getDropAction() == DnDConstants.ACTION_MOVE)) {
            ((DefaultTreeModel) sourceTree.getModel()).removeNodeFromParent(oldNode);
        }

        /*
         * to support move only... if (dsde.getDropSuccess()) {
         * ((DefaultTreeModel)sourceTree.getModel()).removeNodeFromParent(oldNode); }
         */
    }
}

// TreeDropTarget.java
// A quick DropTarget that's looking for drops from draggable JTrees.
//

class TreeDropTarget implements DropTargetListener {

    DropTarget target;

    JTree targetTree;

    public TreeDropTarget(JTree tree) {
        targetTree = tree;
        target = new DropTarget(targetTree, this);
    }

    /*
     * Drop Event Handlers
     */
    private TreeNode getNodeForEvent(DropTargetDragEvent dtde) {
        Point p = dtde.getLocation();
        DropTargetContext dtc = dtde.getDropTargetContext();
        JTree tree = (JTree) dtc.getComponent();
        TreePath path = tree.getClosestPathForLocation(p.x, p.y);
        return (TreeNode) path.getLastPathComponent();
    }

    public void dragEnter(DropTargetDragEvent dtde) {
        TreeNode node = getNodeForEvent(dtde);
        if (node.isLeaf()) {
            dtde.rejectDrag();
        } else {
            // start by supporting move operations
            // dtde.acceptDrag(DnDConstants.ACTION_MOVE);
            dtde.acceptDrag(dtde.getDropAction());
        }
    }

    public void dragOver(DropTargetDragEvent dtde) {
        TreeNode node = getNodeForEvent(dtde);
        if (node.isLeaf()) {
            dtde.rejectDrag();
        } else {
            // start by supporting move operations
            // dtde.acceptDrag(DnDConstants.ACTION_MOVE);
            dtde.acceptDrag(dtde.getDropAction());
        }
    }

    public void dragExit(DropTargetEvent dte) {
    }

    public void dropActionChanged(DropTargetDragEvent dtde) {
    }

    public void drop(DropTargetDropEvent dtde) {
        Point pt = dtde.getLocation();
        DropTargetContext dtc = dtde.getDropTargetContext();
        JTree tree = (JTree) dtc.getComponent();
        TreePath parentpath = tree.getClosestPathForLocation(pt.x, pt.y);
        DefaultMutableTreeNode parent = (DefaultMutableTreeNode) parentpath.getLastPathComponent();

        if (parent.isLeaf()) {
            dtde.rejectDrop();
            return;
        }

        try {
            Transferable tr = dtde.getTransferable();
            DataFlavor[] flavors = tr.getTransferDataFlavors();
            for (int i = 0; i < flavors.length; i++) {
                if (tr.isDataFlavorSupported(flavors[i])) {
                    dtde.acceptDrop(dtde.getDropAction());
                    TreePath p = (TreePath) tr.getTransferData(flavors[i]);
                    DefaultMutableTreeNode node = (DefaultMutableTreeNode) p.getLastPathComponent();
                    DefaultTreeModel model = (DefaultTreeModel) tree.getModel();
                    model.insertNodeInto(node, parent, 0);
                    dtde.dropComplete(true);
                    System.out.println("dragged node : "+node);
                    System.out.println("dropped in parent : "+parent);
                    GridManager.getInstance().getConfigurableSources().get(""+node).setParent(""+parent);
                    System.out.println(GridManager.getInstance().getConfigurableSources().values());

                    return;
                }
            }
            dtde.rejectDrop();
        } catch (Exception e) {
            e.printStackTrace();
            dtde.rejectDrop();
        }
    }
}

// TransferableTreeNode.java
// A Transferable TreePath to be used with Drag & Drop applications.
//

class TransferableTreeNode implements Transferable {

    public static DataFlavor TREE_PATH_FLAVOR = new DataFlavor(TreePath.class, "Tree Path");

    DataFlavor flavors[] = { TREE_PATH_FLAVOR };

    TreePath path;

    public TransferableTreeNode(TreePath tp) {
        path = tp;
    }

    public synchronized DataFlavor[] getTransferDataFlavors() {
        return flavors;
    }

    public boolean isDataFlavorSupported(DataFlavor flavor) {
        return (flavor.getRepresentationClass() == TreePath.class);
    }

    public synchronized Object getTransferData(DataFlavor flavor) throws UnsupportedFlavorException, IOException {
        if (isDataFlavorSupported(flavor)) {
            return (Object) path;
        } else {
            throw new UnsupportedFlavorException(flavor);
        }
    }
}

NB My D&D event is attached after the success of dropping in the drop handler TreeDropTarget method drop, for the checkbox since the D&D are using a copy Jtree mode so You can inject your event logic in the constructor. finally this JTree is behaving as I need in a small context this is not a good idea for big datasets ( lot of events are always redrawing the tree)

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to div scroll

While running selenium code, need to scroll to the bottom of the div. How do update "style =height: 100px; top: 100px;".
How to accomplish this using Javascript?

A: Sorry there was little confusion ,but not not now. check out fiddle .See style properly.
Working fiddle
Use the following code , say you want to scroll to bottom of "round" div,
var scr = $('#box')[0].scrollHeight;
$('#box').animate({scrollTop: scr},2000);

CSS :
#box{
  overflow:auto;
  width:300px;
  height:200px;
}

Say HTML is

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Etiam non tellus nisi, at euismod lacus. Praesent elementum, purus vitae imperdiet bibendum, erat nisl congue libero, vitae bibendum diam quam sed orci. Integer magna justo, dapibus et sagittis et, porta sit amet augue. Ut sed felis et odio egestas sodales eget vel sapien. Vivamus laoreet fermentum odio, eu fringilla nisi pulvinar at. Cras quis mauris erat, et varius massa. Aenean sit amet consequat purus. Aenean at lectus sem.

Donec lobortis pulvinar ornare. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla vitae turpis massa, quis vehicula mauris. Fusce in ante libero. Aliquam consectetur suscipit dui eu vestibulum. Aenean felis purus, volutpat et sollicitudin at, feugiat non odio. Sed feugiat, augue non volutpat congue, ipsum magna vehicula dolor, non ornare mi mauris nec ipsum. Integer sed odio eget nisl posuere porttitor vitae suscipit lectus. Cras vehicula, justo nec ornare rhoncus, enim urna euismod justo, quis scelerisque metus dolor at leo.

Maecenas non elit sapien. Proin fringilla pellentesque ultrices. Proin rhoncus eleifend nisl, nec consequat dui porta id. Aliquam ut erat libero. Integer at tristique est. Duis iaculis, augue vel tempus congue, elit mi pellentesque felis, ut interdum risus tortor vitae nulla. Praesent malesuada mattis fermentum. Donec luctus pharetra nem, erat nisl congue libero, vitae bibendum diam quam sed orci. Integer magna justo, dapibus et sagittis et, porta sit amet augue. Ut sed felis et odio egestas sodales eget vel sapien. Vivamus laoreet fermentum odio, eu fringilla nisi pulvinar at. Cras quis mauris erat, et varius massa. Aenean sit amet consequat purus. Aenean at lectus sem.

Donec lobortis pulvinar ornare. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla vitae turpis massa, quis vehicula mauris. Fusce in ante libero. Aliquam consectetur suscipit dui eu vestibulum. Aenean felis purus, volutpat et sollicitudin at, feugiat non odio. Sed feugiat, augue non volutpat congue, ipsum magna vehicula dolor, non ornare mi mauris nec ipsum. Integer sed odio eget nisl posuere porttitor vitae suscipit lectus. Cras vehicula, justo nec ornare rhoncus, enim urna euismod justo, quis scelerisque metus dolor at leo.

Maecenas non elit sapien. Proin fringilla pellentesque ultrices. Proin rhoncus eleifend nisl, nec consequat dui porta id. Aliquam ut erat libero. Integer at tristique est. Duis iaculis, augue vel tempus congue, elit mi pellentesque felis, ut interdum risus tortor vitae nulla. Praesent malesuada mattis fermentum. Donec luctus pharetra nem, erat nisl congue libero, vitae bibendum diam quam sed orci. Integer magna justo, dapibus et sagittis et, porta sit amet augue. Ut sed felis et odio egestas sodales eget vel sapien. Vivamus laoreet fermentum odio, eu fringilla nisi pulvinar at. Cras quis mauris erat, et varius massa. Aenean sit amet consequat purus. Aenean at lectus sem.

Donec lobortis pulvinar ornare. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla vitae turpis massa, quis vehicula mauris. Fusce in ante libero. Aliquam consectetur suscipit dui eu vestibulum. Aenean felis purus, volutpat et sollicitudin at, feugiat non odio. Sed feugiat, augue non volutpat congue, ipsum magna vehicula dolor, non ornare mi mauris nec ipsum. Integer sed odio eget nisl posuere porttitor vitae suscipit lectus. Cras vehicula, justo nec ornare rhoncus, enim urna euismod justo, quis scelerisque metus dolor at leo.

Maecenas non elit sapien. Proin fringilla pellentesque ultrices. Proin rhoncus eleifend nisl, nec consequat dui porta id. Aliquam ut erat libero. Integer at tristique est. Duis iaculis, augue vel tempus congue, elit mi pellentesque felis, ut interdum risus tortor vitae nulla. Praesent malesuada mattis fermentum. Donec luctus pharetra nem, erat nisl congue libero, vitae bibendum diam quam sed orci. Integer magna justo, dapibus et sagittis et, porta sit amet augue. Ut sed felis et odio egestas sodales eget vel sapien. Vivamus laoreet fermentum odio, eu fringilla nisi pulvinar at. Cras quis mauris erat, et varius massa. Aenean sit amet consequat purus. Aenean at lectus sem.

Donec lobortis pulvinar ornare. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla vitae turpis massa, quis vehicula mauris. Fusce in ante libero. Aliquam consectetur suscipit dui eu vestibulum. Aenean felis purus, volutpat et sollicitudin at, feugiat non odio. Sed feugiat, augue non volutpat congue, ipsum magna vehicula dolor, non ornare mi mauris nec ipsum. Integer sed odio eget nisl posuere porttitor vitae suscipit lectus. Cras vehicula, justo nec ornare rhoncus, enim urna euismod justo, quis scelerisque metus dolor at leo.

Maecenas non elit sapien. Proin fringilla pellentesque ultrices. Proin rhoncus eleifend nisl, nec consequat dui porta id. Aliquam ut erat libero. Integer at tristique est. Duis iaculis, augue vel tempus congue, elit mi pellentesque felis, ut interdum risus tortor vitae nulla. Praesent malesuada mattis fermentum. Donec luctus pharetra nem, erat nisl congue libero, vitae bibendum diam quam sed orci. Integer magna justo, dapibus et sagittis et, porta sit amet augue. Ut sed felis et odio egestas sodales eget vel sapien. Vivamus laoreet fermentum odio, eu fringilla nisi pulvinar at. Cras quis mauris erat, et varius massa. Aenean sit amet consequat purus. Aenean at lectus sem.

Donec lobortis pulvinar ornare. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla vitae turpis massa, quis vehicula mauris. Fusce in ante libero. Aliquam consectetur suscipit dui eu vestibulum. Aenean felis purus, volutpat et sollicitudin at, feugiat non odio. Sed feugiat, augue non volutpat congue, ipsum magna vehicula dolor, non ornare mi mauris nec ipsum. Integer sed odio eget nisl posuere porttitor vitae suscipit lectus. Cras vehicula, justo nec ornare rhoncus, enim urna euismod justo, quis scelerisque metus dolor at leo.

Maecenas non elit sapien. Proin fringilla pellentesque ultrices. Proin rhoncus eleifend nisl, nec consequat dui porta id. Aliquam ut erat libero. Integer at tristique est. Duis iaculis, augue vel tempus congue, elit mi pellentesque felis, ut interdum risus tortor vitae nulla. Praesent malesuada mattis fermentum. Donec luctus pharetra neque, non dignissim sem condimentum vitae. Quisque varius nibh nec felis facilisis nec consectetur augue ultrices.

Nullam ut arcu nisi, eu volutpat neque. Etiam lobortis, erat vel mollis aliquam, sapien eros bibendum erat, vel mollis purus neque sit amet quam. Proin semper aliquet leo. Morbi erat ipsum, vehicula eget mattis sed, venenatis in lectus. Cras quis dui nunc. Vestibulum viverra tempus nisl pulvinar tempor. Donec vitae nunc quam, eu placerat nulla. Suspendisse potenti. Nulla ante dolor, varius eget porttitor eu, malesuada vel nisl. Vestibulum in justo eros. Maecenas id lorem metus, et auctor nibh. Maecenas ut porttitor felis.

Praesent blandit elementum fringilla. Curabitur tincidunt, libero in convallis volutpat, enim purus sodales lacus, vel euismod ante erat nec est. Nam non metus quis lorem ornare dictum sit amet et mauris. Curabitur molestie porta tortor vel adipiscing. Pellentesque sed nulla vel neque tempor sodales. Aliquam erat volutpat. Nullam nisl mauris, faucibus at blandit mollis, malesuada eu risus. Nunc urna lacus, egestas et euismod non, vehicula sed ligula.


text:
Q: Ada compilation "does not contain expected unit" I have a program that is written in Ada, and I need to compile it. When I do so, I get a "does not contain expected unit" error, and it says it is expecting a spec but found a body. I need it compile it, and I don't know about Ada. I am using the gnat compiler. and i cant put any code up but i can say that it is a adb file with other ads files in the folder.

A: The error :
"does not contain expected unit"

usually occurs when the name of the unit does not match the file name (package body aaa.bbb needs to be in file aaa-bbb.adb and package aaa.bbb needs to be in aaa-bbb.ads)
"expecting a spec but found a body"

probably means you have a mismatch between the contents of the file and the file extension (ads or adb)
Beyond this i can only upvote the comment by Marc C


text:
Q: Animate text change over time with JavaScript I need to animate text change over time that never stops.
I've found this simple example with jquery:
      $(function() {

    $('#header-text-change').fadeOut(500, function() {
        $(this).text('Some other text!').fadeIn(500);
    });

});

Now I need to have more than one predefined text and that animation loops forever.
Thanks.

A: You can use setInterval() function to loop every N milliseconds.
Look this code snippet:
This example reset the index variable to 0 when hits TEXTS.length

var TEXTS = ["Some other text!", "Lord of the Rings", "Avengers", "Whatever text"];

var index = 0;

$(function() {
  setInterval(function() {
    $('#header-text-change').fadeOut(500, function() {
      $(this).text(TEXTS[index++]).fadeIn(500);
      if (index === TEXTS.length)
        index = 0
    });
  }, 1000);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h1 id="header-text-change">
  Hellow World!!
</h1>

See? now your code is looping, in this case every one second (1000ms).

A: function fadeout(){$('#header-text-change').fadeOut(undefined,changeText)}
function changeText(){
    // implements your logic for changing the text
    fadein();
}
function fadein(){$('#header-text-change').fadeIn(undefined,fadeout)}

You call fadeout and it loops using the callbacks( and they are named so you can reference them). Passing undefined as the first argument to fadeOut/fadeIn will use the default value of 400ms, you could change that by passing a variable that stores how long you want the animation to take.


text:
Q: How do you diagonalize this matrix and find P and D such that A = PDP^-1?

 1   1   4
 0  -4   0
-5  -1  -8

I3 = 3x3 identity matrix

             λ   0   0
λI3  =       0   λ   0
             0   0   λ

    λ-1     -1      -4
=   0        λ+4     0
    5        1       λ+8

Rule of Sarrus to find determinant:

λ–1     -1      -4       λ–1    -1
0       λ+4      0       0       λ+4
5       1        λ+8     5       1

Eigenvalues:
λ = -3, λ = -4
Eigenvectors:
for λ = -3:

-1
 0
 1

for λ = -4:

 4
 0
-5

The thing is, when I put this in any online matrix calculator, it comes up with different eigenvectors.

       -4   0   0
D   =   0  -4   0
        0   0  -3

I am not coming up with any of the multiple choice answers, but I know it has to be one of them.  Any ideas?

A: If you solve $(A+4I)x=0$ by reducing the augmented matrix, you obtain
$\begin{bmatrix}1&1/5&4/5&0\\0&0&0&0\\0&0&0&0\end{bmatrix}$.
Letting $y=5s$ and $z=5t$ gives $x=-s-4t$, so
the vectors $\begin{bmatrix}-1\\5\\0\end{bmatrix}$ and $\begin{bmatrix}-4\\0\\5\end{bmatrix}$ are eigenvectors corresponding to $\lambda=-4$.
Therefore we could take these vectors as two columns of $P$; but since
the vectors $\begin{bmatrix} 1\\-9\\1\end{bmatrix}$ and $\begin{bmatrix}0\\-4\\1\end{bmatrix}$ are linear combinations of these vectors,  we can use them as the columns corresponding to $\lambda=-4$ instead.
Therefore C) is correct.

A quicker way to work this problem is to find the eigenvalues $\lambda=-3$ and $\lambda=-4$,
conclude that C) is the only possible correct answer,
and then check to see if $Av_1=-4v_1$, $Av_2=-4v_2$, and $Av_3=-3v_3$ where
$P=\begin{bmatrix}v_1 &|&v_2&|&v_3\end{bmatrix}$.


text:
Q: Realm dotnet where is RealmConfiguration.EncryptionKey Looking at the Realm dotnet documentation, it says we can encrypt a realm using
var config = new RealmConfiguration("Mine.realm");
config.EncryptionKey = new byte[64] // key MUST be exactly this size
{
  0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08,
  0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18,
  0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28,
  0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38,
  0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48,
  0x51, 0x52, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58,
  0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68,
  0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78
};

var realm = Realm.GetInstance(config);  // will create/open encrypted realm "Mine.realm"

The problem is that the RealmConfiguration class does not seem to have a property called EncryptionKey. Is this an extension or is it just missing in v0.74.1. The worrying thing is that the link to the api documentation for RealmConfiguration goes to a 404 page
Can someone from Realm let me know what I am doing wrong, or let me know whether this feature is available in Realm dotnet v0.74.1

A: Are you using Realm in a PCL project? I just checked and the RealmConfiguration class in the PCL project doesn't have the EncryptionKey, ReadOnly, ObjectClasses and SchemaVersion properties, whereas the actual RealmConfiguration does have them. Those properties missing on the PCL class is a bug, and I have filed an issue.
Since the properties are actually there during runtime because Realm uses the PCL bait and switch trick you can set them using reflection until a fix comes out.

A: This issue was fixed in the v0.75.0 release


text:
Q: Error in RecyclerViewAdapter's onBindViewHolder() Method ㅠㅠ An error occurred while creating and building the app. Looking at the logcat, it appears that onBindViewHolder() Method has a nullPointerError. But I can't fix it because it hasn't been long since I encountered Android. I saw other questions on this site, but I didn't understand because I don't know English well. I'd appreciate it if you could help me with how to modify it.
Logcat
2020-05-25 11:54:53.613 14798-14798/? E/Zygote: accessInfo : 1
2020-05-25 11:54:53.632 14798-14798/? E/mple.oryumatzi: Unknown bits set in runtime_flags: 0x8000
2020-05-25 11:55:04.170 14798-14798/com.example.oryumatzip E/TAG: OnCreate::
2020-05-25 11:55:04.209 14798-14798/com.example.oryumatzip E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.oryumatzip, PID: 14798
    java.lang.NullPointerException: Argument must not be null
        at com.bumptech.glide.util.Preconditions.checkNotNull(Preconditions.java:29)
        at com.bumptech.glide.util.Preconditions.checkNotNull(Preconditions.java:23)
        at com.bumptech.glide.RequestBuilder.into(RequestBuilder.java:669)
        at com.example.oryumatzip.CustomAdapter.onBindViewHolder(CustomAdapter.java:39)
        at com.example.oryumatzip.CustomAdapter.onBindViewHolder(CustomAdapter.java:17)
        at androidx.recyclerview.widget.RecyclerView$Adapter.onBindViewHolder(RecyclerView.java:7065)
        at androidx.recyclerview.widget.RecyclerView$Adapter.bindViewHolder(RecyclerView.java:7107)
        at androidx.recyclerview.widget.RecyclerView$Recycler.tryBindViewHolderByDeadline(RecyclerView.java:6012)
        at androidx.recyclerview.widget.RecyclerView$Recycler.tryGetViewHolderForPositionByDeadline(RecyclerView.java:6279)
        at androidx.recyclerview.widget.RecyclerView$Recycler.getViewForPosition(RecyclerView.java:6118)
        at androidx.recyclerview.widget.RecyclerView$Recycler.getViewForPosition(RecyclerView.java:6114)
        at androidx.recyclerview.widget.LinearLayoutManager$LayoutState.next(LinearLayoutManager.java:2303)
        at androidx.recyclerview.widget.LinearLayoutManager.layoutChunk(LinearLayoutManager.java:1627)
        at androidx.recyclerview.widget.LinearLayoutManager.fill(LinearLayoutManager.java:1587)
        at androidx.recyclerview.widget.LinearLayoutManager.onLayoutChildren(LinearLayoutManager.java:665)
        at androidx.recyclerview.widget.RecyclerView.dispatchLayoutStep2(RecyclerView.java:4134)
        at androidx.recyclerview.widget.RecyclerView.onMeasure(RecyclerView.java:3540)
        at android.view.View.measure(View.java:26415)
        at androidx.constraintlayout.widget.ConstraintLayout.internalMeasureChildren(ConstraintLayout.java:1227)
        at androidx.constraintlayout.widget.ConstraintLayout.onMeasure(ConstraintLayout.java:1572)
        at android.view.View.measure(View.java:26415)
        at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:7845)
        at android.widget.FrameLayout.onMeasure(FrameLayout.java:194)
        at androidx.appcompat.widget.ContentFrameLayout.onMeasure(ContentFrameLayout.java:143)
        at android.view.View.measure(View.java:26415)
        at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:7845)
        at androidx.appcompat.widget.ActionBarOverlayLayout.onMeasure(ActionBarOverlayLayout.java:403)
        at android.view.View.measure(View.java:26415)
        at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:7845)
        at android.widget.FrameLayout.onMeasure(FrameLayout.java:194)
        at android.view.View.measure(View.java:26415)
        at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:7845)
        at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1552)
        at android.widget.LinearLayout.measureVertical(LinearLayout.java:842)
        at android.widget.LinearLayout.onMeasure(LinearLayout.java:721)
        at android.view.View.measure(View.java:26415)
        at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:7845)
        at android.widget.FrameLayout.onMeasure(FrameLayout.java:194)
        at com.android.internal.policy.DecorView.onMeasure(DecorView.java:1011)
        at android.view.View.measure(View.java:26415)
        at android.view.ViewRootImpl.performMeasure(ViewRootImpl.java:3605)
        at android.view.ViewRootImpl.measureHierarchy(ViewRootImpl.java:2348)
        at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:2640)
        at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:2200)
        at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:8981)
        at android.view.Choreographer$CallbackRecord.run(Choreographer.java:996)
        at android.view.Choreographer.doCallbacks(Choreographer.java:794)
        at android.view.Choreographer.doFrame(Choreographer.java:729)
        at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:981)
        at android.os.Handler.handleCallback(Handler.java:883)
        at android.os.Handler.dispatchMessage(Handler.java:100)
2020-05-25 11:55:04.209 14798-14798/com.example.oryumatzip E/AndroidRuntime:     at android.os.Looper.loop(Looper.java:237)
        at android.app.ActivityThread.main(ActivityThread.java:7860)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1068)

MyAdapter File

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;

import java.util.ArrayList;

public class CustomAdapter extends RecyclerView.Adapter<CustomAdapter.CustomViewHolder> {

    private ArrayList<ListViewItem> arrayList;
    private Context context;

    public CustomAdapter(ArrayList<ListViewItem> arrayList, Context context) {
        this.arrayList = arrayList;
        this.context = context;
    }

    @NonNull
    @Override
    public CustomViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.activity_korean_food, parent, false);
        CustomViewHolder holder = new CustomViewHolder(view);
        return holder;
    }

    @Override
    public void onBindViewHolder(@NonNull CustomViewHolder holder, int position) {
        Glide.with(holder.itemView)
                .load(arrayList.get(position).getProfile())
                .into(holder.Iv_profile);
        holder.tv_title.setText(arrayList.get(position).getTitle());
        holder.tv_info.setText(arrayList.get(position).getInfo());
    }

    @Override
    public int getItemCount() {
        return (arrayList != null ? arrayList.size() : 0);
    }

    public class CustomViewHolder extends RecyclerView.ViewHolder {

        ImageView Iv_profile;
        TextView tv_title;
        TextView tv_info;

        public CustomViewHolder(@NonNull View itemView) {
            super(itemView);
            this.Iv_profile = itemView.findViewById(R.id.iv_profile);
            this.tv_title = itemView.findViewById(R.id.tv_title);
            this.tv_info = itemView.findViewById(R.id.tv_info);
        }
    }
}

XML File of RecyclerView
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".KoreanFood"
    android:background="#ffffff">

    <TextView
        android:id="@+id/tv_koreanFood"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:height="120dp"
        android:background="#ffffff"
        android:fontFamily="@font/ssflowerroadregular"
        android:gravity="center"
        android:text="한식"
        android:textSize="50sp"
        app:layout_constraintBottom_toTopOf="@+id/recyclerView"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="1.0"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/recyclerView"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.0"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/tv_koreanFood"
        app:layout_constraintVertical_bias="1.0" />

</androidx.constraintlayout.widget.ConstraintLayout>


text:
Q: Add data to Firebase ID token Is it possible to add small pieces of data to the Firebase ID Token? For example, it seems some fields like uid, email, displayName and phoneNumber are part of it. Could I add firstName and lastName fields too?
The use case is every now and then, I need to access the first and last names of the logged in user. If not the ID token, where else can I store them, if at all?
I was considering storing in custom claims, but it feels like I'd be abusing the feature.

A: You can't add fields to an ID token other than what's listed in the documentation.  The only way you can provide additional information is through using custom claims.  A custom claims payload is restricted to 1000 bytes, so it's not very flexible.
Sometimes it's more appropriate to simply store additional information about the user in a database, keyed off the user's UID.

A: You can add personal info to a custom token.
Then, use this custom token for authentication.
Custom token:
https://firebase.google.com/docs/auth/admin/create-custom-tokens
JSON Web Token:
https://jwt.io/
JSON Web Token for Java and Android
https://github.com/jwtk/jjwt


text:
Q: Search files for text matching format of a Unix directory I am attempting to search through all the files in a directory for text matching the pattern of any arbitrary directory. The output of this I hope to use to make a list of all directories referenced in the files (this part I think I can figure out on my own).
I have looked at various regex resources and made my own expression that seems to work in the browser based tool but not with grep in the command line.
/\w+[(/\w+)]+

My understanding so far is the above expression will look for the beginning / of a directory then look for an indeterminate number of characters before looking for a repeating block of the same thing.
Any guidance would be greatly appreciated.

A: If I understand you correctly, you want a regex that will allow you to use grep to identify paths. I am not sure what you are trying to do with the regex you have posted. Why do you want something to be repeated? Paths only need a single slash: /etc.
Anyway, if you want any kind of path (paths can also contain non-word characters like {,[,( spaces and new lines etc), try this:
grep -E '/[^/]+' *txt
          _____
           |  |--------> one or more
           |-----------> A character class, '^' in a character class means NOT,
                         so this class means "anything that is not /".

The -E tells grep that the pattern you will give it shoujld be interpreted as an Extended Regular Expression rather than it's default, Basic Regular Expression. EREs support + for "one or more" which is needed to find only strings with at least one non-slash character after the first slash.
If you want to find only paths with more than a single /, you can do something like
grep -E '/[^/]+/[^/]+' *txt

Paths can also end with a slash, if for some reason you want to keep such trailing slashes use (/? means "find zero or one /):
grep -E '/[^/]+/[^/]+/?' *txt

More specifically, the regex you are using fails for various reasons. First of all, as @erewok pointed out, you are using parentheses and a + inside brackets. Since brackets specify a character class, anything within them is treated as one of the characters to be found (with the exception of ^ which makes it a negated character class).
So, [(/\w+)]+ means find any of (,/, any word character (\w),+ or ) one or more times. In any case, \w is not recognized by grep unless you use Perl Compatible Regular Expressions. You can activate these in grep with the -P flag. For example, this will match a path like /etc:
grep -P '/\w+' *txt

If you know that your paths will always consist of word characters (ie a-z,A-Z,0-9, and _), you can use an expression like the above but since one can never be sure, using something less strict, lke my fist suggestion is preferable.


text:
Q: What are the MySql, FlatFile Database Differences? I mean whats the difference between mysql and flat file database is it really slower to have "ff db"?

A: A flat file database has far less functionality than a relational database.  To name a couple of things, you lose explicit typing and indexing on columns, since the information in the file consists only of the rows of the table (and since you asked about speed, remember that indexing is what allows us to make fast queries).

A: Basic differences:
A relational db removes redundancy in the data, flat file you are stuck with redundant data.
A relational db moves towards solving inconsistent update problems, flat file you need to do this yourself
A relational db has a lot of work done to increase speed, provide optimal searching and storage systems, type your data, etc. A flatfile system has none of this.
You may find more interest in the features of more advanced RDBMSes too, as MySQL is actually a pretty basic relational db. The extra features of PostgreSQL for example, with it's much improved concurrent access controls, etc.


text:
Q: Simple SSIS Question - Best Practice: Running same code with different variables I have written an SSIS package that essentially takes data from multiple sources and writes it to an Excel file (it is a bit more complicated than this, but I do not think the specifics really matter at this point).
Now, I need to run this DTSX package every week (on a Monday), and every month (on the 1st) and save the excel file to a name specified by a variable within the package, having run several simple SQL stored procedures, which have either 'Weekly' or 'Monthly' passed in to work out the dates needed to get the right data.
The initial plan was to copy the DTSX package and have a SQL Job just run the first package every Monday and the 2nd package on the 1st of each month.
Is there a way I can use the same package to do both things (for example, can I pass 'Monthly' or 'Weekly' into the DTSX package from the SQL Job somehow) and if so, how do I do this?
Thanks,
Bob

A: Create a variable in the package called ExecutionMode. Use this variable as a parameter to the appropriate stored procedures.  Set ExecutionMode to "Weekly" or "Monthly" and run your package. Make sure that all procs run correctly.
Use Package Configurations and put ExecutionMode in the config file for the package. Now, the ExecutionMode can be passed as a parameter.
Create two jobs for the SSIS package of type "SQL Server Integration Services". In each one, specify the package and the configuration file. On the SET VALUES tab, choose the ExecutionMode variable and set it to "Weekly" or "Monthly" depending on the schedule.
Here is how to run it command line (including setting variables):
http://www.sqlservercentral.com/articles/SQL+Server+2005+-+SSIS/2999/

A: Thanks again for the help Raj.
My final answer was to create the job of type SQL Server Integration Services, then set a variable ('TimeScale') within the SSIS package.
Once I set the job type to SSIS I could then 'Set Values' as follows (note that it is exactly as below - 'package' should be 'package', NOT the name of your package!):
Property Path: \package.Variables[TimeScale].Value
Value: Monthly
Full sample code to import into a job if you need the example. :)
USE [msdb]
GO
/****** Object:  Job [Sample]    Script Date: 10/28/2009 16:04:22 ******/
BEGIN TRANSACTION
DECLARE @ReturnCode INT
SELECT @ReturnCode = 0
/****** Object:  JobCategory [[Uncategorized (Local)]]]    Script Date: 10/28/2009 16:04:22 ******/
IF NOT EXISTS (SELECT name FROM msdb.dbo.syscategories WHERE name=N'[Uncategorized (Local)]' AND category_class=1)
BEGIN
EXEC @ReturnCode = msdb.dbo.sp_add_category @class=N'JOB', @type=N'LOCAL', @name=N'[Uncategorized (Local)]'
IF (@@ERROR  0 OR @ReturnCode  0) GOTO QuitWithRollback

END

DECLARE @jobId BINARY(16)
EXEC @ReturnCode =  msdb.dbo.sp_add_job @job_name=N'Sample',
        @enabled=1,
        @notify_level_eventlog=0,
        @notify_level_email=0,
        @notify_level_netsend=0,
        @notify_level_page=0,
        @delete_level=0,
        @description=N'No description available.',
        @category_name=N'[Uncategorized (Local)]',
        @owner_login_name=N'NTWK\FrostbiteXIII', @job_id = @jobId OUTPUT
IF (@@ERROR  0 OR @ReturnCode  0) GOTO QuitWithRollback
/****** Object:  Step [Sample Step]    Script Date: 10/28/2009 16:04:22 ******/
EXEC @ReturnCode = msdb.dbo.sp_add_jobstep @job_id=@jobId, @step_name=N'Sample Step',
        @step_id=1,
        @cmdexec_success_code=0,
        @on_success_action=1,
        @on_success_step_id=0,
        @on_fail_action=2,
        @on_fail_step_id=0,
        @retry_attempts=0,
        @retry_interval=0,
        @os_run_priority=0, @subsystem=N'SSIS',
        @command=N'/DTS "TestPackage.dtsx" /SERVER MyServer /MAXCONCURRENT " -1 " /CHECKPOINTING OFF /SET "\package.Variables[TimeScale].Value";Monthly',
        @database_name=N'master',
        @flags=0
IF (@@ERROR  0 OR @ReturnCode  0) GOTO QuitWithRollback
EXEC @ReturnCode = msdb.dbo.sp_update_job @job_id = @jobId, @start_step_id = 1
IF (@@ERROR  0 OR @ReturnCode  0) GOTO QuitWithRollback
EXEC @ReturnCode = msdb.dbo.sp_add_jobschedule @job_id=@jobId, @name=N'Weekly Step',
        @enabled=1,
        @freq_type=8,
        @freq_interval=3,
        @freq_subday_type=1,
        @freq_subday_interval=0,
        @freq_relative_interval=0,
        @freq_recurrence_factor=1,
        @active_start_date=20091028,
        @active_end_date=99991231,
        @active_start_time=80000,
        @active_end_time=235959
IF (@@ERROR  0 OR @ReturnCode  0) GOTO QuitWithRollback
EXEC @ReturnCode = msdb.dbo.sp_add_jobserver @job_id = @jobId, @server_name = N'(local)'
IF (@@ERROR  0 OR @ReturnCode  0) GOTO QuitWithRollback
COMMIT TRANSACTION
GOTO EndSave
QuitWithRollback:
    IF (@@TRANCOUNT > 0) ROLLBACK TRANSACTION
EndSave:


text:
Q: getopt argument depends on another is there a builtin way to make an argument depend on another when using getopt? For example, I have my switch case setup and everything works fine, but I need my -m argument (the length of the markov chain) before I read a text file (-i).
In other words, I would like to make sure that other arguments aren't set when processing my input arg.
Small excerpt:
    while ((opt = getopt_long(argc, argv, "i:shm:", long_options, &option_index))
       != -1)
{
    switch (opt) {
        case 'i':
            inputEnglish.ReadFile((string)optarg);
            break;

        case 'm':
            inputEnglish.setMarkovLength(atoi(optarg));
            break;

        case 's':
            break;

        case 'h':
            printHelp();
            break;

        case '?':
            cout << "dfgdfgdf" << endl;
            return 0;
            break;

        default:
            printHelp();
            return 0;
            break;
    }
}

If there aren't any built-in ways, do you have a clean way of doing this? Clean code being more important than efficiency here. Thank you for any help!

A: Save the file name and only process it after you have processed all the command line arguments. This is generally the best approach -- the getopt code should only parse, not process.
Alternatively, and this is the way most commands work, don't use a flag for the filename ... so the usage is pgm -m foo filename. Then you just process the remaining arguments (argv[optind] through argv[argc-1]) as filenames after you've processed all the flags. This is conducive to the common situation -- like yours -- of the processing of a file depending on the flag values.


text:
Q: Improve Row Append Performance On Pandas DataFrames I am running a basic script that loops over a nested dictionary, grabs data from each record, and appends it to a Pandas DataFrame. The data looks something like this:
data = {"SomeCity": {"Date1": {record1, record2, record3, ...}, "Date2": {}, ...}, ...}

In total it has a few million records. The script itself looks like this:
city = ["SomeCity"]
df = DataFrame({}, columns=['Date', 'HouseID', 'Price'])
for city in cities:
    for dateRun in data[city]:
        for record in data[city][dateRun]:
            recSeries = Series([record['Timestamp'],
                                record['Id'],
                                record['Price']],
                                index = ['Date', 'HouseID', 'Price'])
            FredDF = FredDF.append(recSeries, ignore_index=True)

This runs painfully slow, however. Before I look for a way to parallelize it, I just want to make sure I'm not missing something obvious that would make this perform faster as it is, as I'm still quite new to Pandas.

A: Another way is to make it into a list and then use pd.concat
import pandas as pd

df = pd.DataFrame({'num_legs': [2, 4, 8, 0],

                   'num_wings': [2, 0, 0, 0],

                   'num_specimen_seen': [10, 2, 1, 8]},

                  index=['falcon', 'dog', 'spider', 'fish'])

def append(df):
    df_out = df.copy()
    for i in range(1000):
        df_out = df_out.append(df)
    return df_out

def concat(df):
    df_list = []
    for i in range(1001):
        df_list.append(df)

    return pd.concat(df_list)

# some testing
df2 = concat(df)
df3 = append(df)

pd.testing.assert_frame_equal(df2,df3)

%timeit concat(df):
20.2 ms ± 794 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
%timeit append(df)
275 ms ± 2.54 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
It is the recommended way to concatenate rows in pandas now:

Iteratively appending rows to a DataFrame can be more computationally intensive than a single concatenate. A better solution is to append those rows to a list and then concatenate the list with the original DataFrame all at once. link

A: I also used the dataframe's append function inside a loop and I was perplexed how slow it ran.
A useful example for those who are suffering, based on the correct answer on this page.
Python version: 3
Pandas version: 0.20.3
# the dictionary to pass to pandas dataframe
d = {}

# a counter to use to add entries to "dict"
i = 0

# Example data to loop and append to a dataframe
data = [{"foo": "foo_val_1", "bar": "bar_val_1"},
       {"foo": "foo_val_2", "bar": "bar_val_2"}]

# the loop
for entry in data:

    # add a dictionary entry to the final dictionary
    d[i] = {"col_1_title": entry['foo'], "col_2_title": entry['bar']}

    # increment the counter
    i = i + 1

# create the dataframe using 'from_dict'
# important to set the 'orient' parameter to "index" to make the keys as rows
df = DataFrame.from_dict(d, "index")

The "from_dict" function: https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.from_dict.html

A: I think the best way to do it is, if you know the data you are going to receive, allocate before hand.
import numpy as np
import pandas as pd

random_matrix = np.random.randn(100, 100)
insert_df = pd.DataFrame(random_matrix)

df = pd.DataFrame(columns=range(100), index=range(200))
df.loc[range(100), df.columns] = random_matrix
df.loc[range(100, 200), df.columns] = random_matrix

This is the pattern that I think makes the most sense.  append will be faster if
you have a very small dataframe, but it doesn't scale.
In [1]: import numpy as np; import pandas as pd

In [2]: random_matrix = np.random.randn(100, 100)
   ...: insert_df = pd.DataFrame(random_matrix)
   ...: df = pd.DataFrame(np.random.randn(100, 100))

In [2]: %timeit df.append(insert_df)
272 µs ± 2.36 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

In [3]: %timeit df.loc[range(100), df.columns] = random_matrix
493 µs ± 4.25 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

In [4]: %timeit df.loc[range(100), df.columns] = insert_df
821 µs ± 8.68 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

When we run this with a 100,000 row dataframe, we see much more dramatic results.
In [1]: df = pd.DataFrame(np.random.randn(100_000, 100))

In [2]: %timeit df.append(insert_df)
17.9 ms ± 253 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)

In [3]: %timeit df.loc[range(100), df.columns] = random_matrix
465 µs ± 13.7 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

In [4]: %timeit df.loc[range(99_900, 100_000), df.columns] = random_matrix
465 µs ± 5.75 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

In [5]: %timeit df.loc[range(99_900, 100_000), df.columns] = insert_df
1.02 ms ± 3.42 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

So we can see an append is about 17 times slower than an insert with a dataframe, and 35 times slower than an insert with a numpy array.

A: I ran into a similar problem where I had to append many times to a DataFrame, but did not know the values in advance of the appends. I wrote a lightweight DataFrame like data structure that is just blists() under the hood. I use that to accumulate all of the data and then when it is complete transform the output into a Pandas DataFrame. Here is a link to my project, all open source so I hope it helps others:
https://pypi.python.org/pypi/raccoon

A: Appending rows to lists is far more efficient than to a DataFrame.
Hence you would want to

*

*append the rows to a list.

*Then convert it into DataFrame and

*set the index as required.

A: In my case I was loading a large number of dataframes with the same columns from different files and wanted to append them to create one large data frame.
My solution was to first load all the dataframes into a list, and then use
all_dfs = []
for i in all_files:
  all_dfs.append(/* load df from file */)

master_df = pd.concat(all_dfs, ignore_index=True)

A: N=100000

t0=time.time()
d=[]
for i in range(N):
    d.append([i, i+1,i+2,i+3,i+0.1,1+0.2])
testdf=pd.DataFrame.from_records(d, columns=["x1","x2","x3","x4", "x5", "x6"])
print(time.time()-t0)

t0=time.time()
d={}
for i in range(N):
    d[len(d)+1]={"x1":i, "x2":i+1, "x3":i+2,"x4":i+3,"x5":i+0.1,"x6":1+0.2}
testdf=pd.DataFrame.from_dict(d, "index")
print(time.time()-t0)

t0=time.time()
testdf=pd.DataFrame()
for i in range(N):
    testdf=testdf.append({"x1":i, "x2":i+1, "x3":i+2,"x4":i+3,"x5":i+0.1,"x6":1+0.2}, ignore_index=True)
print(time.time()-t0)

=== result for N=10000 ===
list:0.016329050064086914
dict:0.03952217102050781
DataFrame:10.598219871520996

=== result for N=100000 ===
list: 0.4076499938964844
dict: 0.45696187019348145
DataFrame: 187.6609809398651


text:
Q: How to publish dynamic components in SDL Deployer file system maintaining the folder structure as in CME? I have a scenario where my dynamic components available in CME should be published to the same folder path as in CME. Can I control the path where these dynamic components are published?
e.g) CME Path - C020 Global Content US English/Building Blocks/Dynamic Content/Article/Component1.xml
Deployer File System Path - D:\C020 Global Content US English/Building Blocks/Dynamic Content/Article/Component1.xml
CME Path - C050 Local Content Spanish/Building Blocks/Dynamic Content/Communication/Component2.xml
Deployer File System Path - D:\C050 Local Content Spanish\Building Blocks\Dynamic Content\Communication\Component2.xml

A: You can define the path in the stroage config file on CDA Server in below tag.
 <ItemTypes defaultStorageId="defaultdb" cached="false">

    <Item typeMapping="Page" cached="false" storageId="defaultFile"/>
    <Item typeMapping="ComponentPresentation" itemExtension=".Xml" cached="true" storageId="defaultDataFile" />
    <Item typeMapping="ComponentPresentation" itemExtension=".rel" cached="true" storageId="defaultDataFile" />
    <Item typeMapping="ComponentPresentation" itemExtension=".ascx" cached="true" storageId="defaultDataFile" />
    <Item typeMapping="ComponentPresentation" itemExtension=".html" cached="true" storageId="defaultDataFile" />
    <Item typeMapping="Binary" itemExtension=".jpg" storageId="defaultFile" cached="true"/>
    <Item typeMapping="Binary" itemExtension=".gif" storageId="defaultFile" cached="true"/>
    <Item typeMapping="Binary" itemExtension=".pdf" storageId="defaultFile" cached="true"/>
    <Item typeMapping="Binary" itemExtension=".jpeg" storageId="defaultFile" cached="true"/>
    <Item typeMapping="Binary" itemExtension=".png" storageId="defaultFile" cached="true"/>
    <Item typeMapping="Binary" itemExtension=".ico" storageId="defaultFile" cached="true"/>
    <Item typeMapping="Comment" cached="false" storageId="Ugcdb" />
  <Item typeMapping="Rating" cached="false" storageId="Ugcdb" />
  <Item typeMapping="UGCUser" cached="false" storageId="Ugcdb" />
 <Item typeMapping="UGCItemStats" cached="false" storageId="Ugcdb" />

and if you want to save on physical path then also define the below tag value
<Storage Type="filesystem" Class="com.tridion.storage.filesystem.FSDAOFactory" Id="defaultDataFile" defaultFilesystem="true" defaultStorage="true">
            <Root Path="c:\websites\Staging\data" />
        </Storage>

Let me know if it is not clear


text:
Q: passport.authenticate() is not being executed via $http.get I have the following angular controller
angular.module('app').controller('mvNavBarLoginCtrl', function($scope, $http){
    $scope.login = function(){
        $http.get('/auth/twitter').then(function(response){
            if(response.data.success)
            {
                alert(response);
            }
        });
    }
});

My routes.js has the following:
app.get('/auth/twitter', passport.authenticate('twitter'));

I can verify that I am getting here, however it doesn't seem the passport.authenticate is being executed.
More over if I try to hit the same route from html markup using (href="/auth/twitter" target="_self") everything works great.
Any idea what I am missing?

A: just looking at your code without checking passport api. I think passport. authenticate return 302 redirect as response. 302 redirect has empty body. your callback function will not follow 302. when you do this in a link, the browser do follow 302.


text:
Q: onTouchStart event triggering Parent OnClick Event in react js Hey i'm Creating a Calendar using reactjs with Custom Drag and Drop . I'm facing issue on Ipad and Touch mobiles . my code is working perfect on desktop but if I open chrome dev tool and change screen resolution to 768px tablet . my events doesn't work in it either. please Help i've used cursor:pointer and e.stopPropagation() in parent event and child event both but didn't work . i use  onTouchStart={this.handleTouchStart}
here is the code i'm using The parent Event is

  Sectiondoubletap(e) {
    debugger
    var now = new Date().getTime();
    var timesince = now - this.state.mylatesttap;
    if((timesince < 300) && (timesince > 0)){

     // double tap checking
     this._handleDoubleClickSpaltenBody(e)
     console.log("Sectiondoubletap worked")

    }

    this.state.mylatesttap = new Date().getTime();

 }

The child event is

  handleTouchStart(ev) {

    ev.stopPropagation();

    console.log("handleTouchStart");
    var now = new Date().getTime();
    var timesince = now - this.state.mylatesttap;
    // checking double tap
    if((timesince < 300) && (timesince > 0)){

     // double tap checking
     this._handleDoubleClickItem(ev)
     console.log("Appoinmentdoubletap worked")

    }else{
      this.handleDrag(ev);
    }

    this.state.mylatesttap = new Date().getTime();

  }

A: Did you try to change
e.stopPropagation()

by
e.stopImmediatePropagation()


text:
Q: MongoDB group by multiple fields in a way to not affect each other result I have the following query, what I want is to have a combined group of custom group field names, with field value.
db.getCollection('mycollection').aggregate([
  {"$match":{
     "expireDate":{"$gte":"2018-02-06T00:00:00.000Z"},
     "publishDate":{"$lte":"2018-02-06T00:00:00.000Z"},
     "isPublished":true,"isDrafted":false,
     "deletedAt":{"$eq":null},"deleted":false
  }},
  {"$group":{
     "twentyFourHourAgo":{
        "$sum":{
           "$cond":[
             {"$gt":["$publishDate","2018-02-04T08:48:16.892Z"]},1,0
           ]
        }
      },
      "fortyEightHourAgo":{
        "$sum":{
            "$cond":[
               {"$gt":["$publishDate","2018-02-01T08:48:16.892Z"]},1,0
            ]
        }
      },
      "thirtyDaysAgo":{
         "$sum":{
            "$cond":[
               {"$gt":["$publishDate","2017-12-31T08:48:16.892Z"]},1,0
            ]
         }
      },
      "_id":{
        "position":{"$ifNull":["$position","Unknown"]},
        "workType":{"$ifNull":["$workType","Unknown"]},
        "functionalArea":{"$ifNull":["$functionalArea","Unknown"]},
        "minimumEducation":{"$ifNull":["$minimumEducation","Unknown"]},
        "gender":{"$ifNull":["$gender","Unknown"]},
        "contractType":{"$ifNull":["$contractType","Unknown"]},
        "locations":{"$ifNull":["$locations","Unknown"]},
        "requiredLanguages":{"$ifNull":["$requiredLanguages","Unknown"]},
        "company":{"$ifNull":["$company.name","Unknown"]}},"count":{"$sum":1}
     }
 },
 {"$group":{
     "_id":null,
     "twentyFourHourAgo":{
        "$sum":"twentyFourHourAgo"
     },
     "fortyEightHourAgo":{
        "$sum":"$fortyEightHourAgo"
     },
     "thirtyDaysAgo":{
        "$sum":"$thirtyDaysAgo"
     },
     "position":{"$addToSet":{"Name":"$_id.position","Count":"$count"}},
     "workType":{"$addToSet":{"Name":"$_id.workType","Count":"$count"}},
     "functionalArea":{
        "$addToSet":{"Name":"$_id.functionalArea","Count":"$count"}
     },
     "minimumEducation":{
        "$addToSet":{"Name":"$_id.minimumEducation","Count":"$count"}
     },
     "gender":{"$addToSet":{"Name":"$_id.gender","Count":"$count"}},"contractType":{"$addToSet":{"Name":"$_id.contractType","Count":"$count"}},"locations":{"$addToSet":{"Name":"$_id.locations","Count":"$count"}},"requiredLanguages":{"$addToSet":{"Name":"$_id.requiredLanguages","Count":"$count"}},"company":{"$addToSet":{"Name":"$_id.company","Count":"$count"}}}}]
)

my document inside collection schema is like:
/* 1 */
{
    "_id" : ObjectId("59e4540bf14f1607b90ffb81"),
    "vacancyNumber" : "1",
    "position" : "Software Tester",
    "publishDate" : ISODate("2018-01-02T00:00:00.000Z"),
    "expireDate" : ISODate("2018-05-29T00:00:00.000Z"),
    "yearsOfExperience" : 40,
    "minimumEducation" : "Doctorate",
    "functionalArea" : "Education",
    "company" : {
        "id" : ObjectId("59e453fbf14f1607b90ffb80"),
        "name" : "First Company",
        "profile" : "profile",
        "logo" : {
            "container" : "companyFiles",
            "name" : "abbbff58cd3fda2c59ab2ee620ea5aa0",
            "mime" : ".png",
            "size" : 5806
        }
    },
    "durations" : {
        "years" : 3,
        "months" : 4
    },
    "probationPeriod" : {
        "duration" : 34,
        "unit" : "month"
    },
    "salary" : {
        "minSalary" : 1000,
        "maxSalary" : 2000,
        "currency" : "USD",
        "period" : "monthly",
        "isNegotiable" : true
    },
    "locations" : [
        "Germany",
        "Itly",
        "Iran"
    ],
    "canApplyOnline" : true,
    "skills" : [
        "Skill1",
        "Skill2",
        "Skill3",
        "Skill4"
    ],
    "requiredLanguages" : [
        "Arabic",
        "English",
        "Russian",
        "Dari",
        "French"
    ],
    "keywords" : [
        "Key1",
        "Key2"
    ],
    "deleted" : false,
    "deletedAt" : null,
    "isDrafted" : false,
    "isPublished" : true,
    "requiresTravel" : true,
    "gender" : "male",
    "nationalities" : [
        "afghan"
    ],
    "workType" : "Full Time",
    "contractType" : "Permanent",
}

/* 2 */
{
    "_id" : ObjectId("59f9402e05d04ebe5653d98f"),
    "vacancyNumber" : "1",
    "position" : "Software Engineer",
    "publishDate" : ISODate("2018-01-03T00:00:00.000Z"),
    "expireDate" : ISODate("2018-11-10T00:00:00.000Z"),
    "yearsOfExperience" : 40,
    "minimumEducation" : "Doctorate",
    "functionalArea" : "Education",
    "company" : {
        "id" : ObjectId("59e453fbf14f1607b90ffb80"),
        "name" : "First Company",
        "profile" : "profile",
        "logo" : {
            "container" : "logo container",
            "name" : "logo name",
            "mime" : "logo mime type",
            "size" : 1
        }
    },
    "durations" : {
        "years" : 3,
        "months" : 4
    },
    "probationPeriod" : {
        "duration" : 34,
        "unit" : "month"
    },
    "salary" : {
        "minSalary" : 1000,
        "maxSalary" : 2000,
        "currency" : "USD",
        "period" : "monthly",
        "isNegotiable" : true
    },
    "locations" : [
        "Afghanistan",
        "Itly",
        "Iran"
    ],
    "skills" : [
        "Skill1",
        "Another Skill"
    ],
    "requiredLanguages" : [
        "Arabic",
        "English",
        "Russian",
        "Dari",
        "French"
    ],
    "keywords" : [
        "Keyword",
        "Key1"
    ],
    "deleted" : false,
    "deletedAt" : null,
    "isDrafted" : false,
    "isPublished" : true,
    "gender" : "male",
    "nationalities" : [
        "afghan",
        "iranian"
    ],
    "workType" : "Full Time",
    "contractType" : "Short-Term",
}

/* 3 */
{
    "_id" : ObjectId("5a03235234f7504f13970abd"),
    "vacancyNumber" : "1",
    "position" : "Software Tester",
    "publishDate" : ISODate("2017-10-10T00:00:00.000Z"),
    "expireDate" : ISODate("2018-11-25T00:00:00.000Z"),
    "yearsOfExperience" : 40,
    "minimumEducation" : "Doctorate",
    "functionalArea" : "IT Software",
    "company" : {
        "id" : ObjectId("59e453fbf14f1607b90ffb80"),
        "name" : "My First Company",
        "profile" : "profile",
        "logo" : {
            "container" : "logo container",
            "name" : "logo name",
            "mime" : "logo mime type",
            "size" : 1
        }
    },
    "durations" : {
        "years" : 3,
        "months" : 4
    },
    "probationPeriod" : {
        "duration" : 34,
        "unit" : "month"
    },
    "salary" : {
        "minSalary" : 1000,
        "maxSalary" : 2000,
        "currency" : "USD",
        "period" : "monthly",
        "isNegotiable" : true
    },
    "locations" : [
        "Germany",
        "Itly",
        "Iran"
    ],
    "skills" : [
        "Skill1",
        "Test Skill"
    ],
    "requiredLanguages" : [
        "Arabic",
        "English",
        "Russian",
        "Dari",
        "French"
    ],
    "keywords" : [
        "Test Key",
        "Keyword"
    ],
    "deleted" : false,
    "deletedAt" : null,
    "isDrafted" : false,
    "isPublished" : true,
    "gender" : "female",
    "nationalities" : [
        "afghan"
    ],
    "workType" : "Part Time",
    "contractType" : "Permanent",
}

Now I want to count the group of data by my custom expression check 'twentyFourHourAgo, fortyEightHourAgo, thirtyDaysAgo', and also by the value of a field (functionalArea, position, locations, keywords, workType).
My current query result is
{
    "_id" : null,
    "twentyFourHourAgo" : 0,
    "fortyEightHourAgo" : 0.0,
    "thirtyDaysAgo" : 2.0,
    "position" : [
        {
            "Name" : "Software Engineer",
            "Count" : 1.0
        },
        {
            "Name" : "Software Tester",
            "Count" : 1.0
        }
    ],
    "workType" : [
        {
            "Name" : "Full Time",
            "Count" : 1.0
        },
        {
            "Name" : "Part Time",
            "Count" : 1.0
        }
    ],
    "functionalArea" : [
        {
            "Name" : "Education",
            "Count" : 1.0
        },
        {
            "Name" : "IT Software",
            "Count" : 1.0
        }
    ],
    "minimumEducation" : [
        {
            "Name" : "Doctorate",
            "Count" : 1.0
        }
    ],
    "gender" : [
        {
            "Name" : "male",
            "Count" : 1.0
        },
        {
            "Name" : "female",
            "Count" : 1.0
        }
    ],
    "contractType" : [
        {
            "Name" : "Short-Term",
            "Count" : 1.0
        },
        {
            "Name" : "Permanent",
            "Count" : 1.0
        }
    ],
    "locations" : [
        {
            "Name" : [
                "Afghanistan",
                "Itly",
                "Iran"
            ],
            "Count" : 1.0
        },
        {
            "Name" : [
                "Germany",
                "Itly",
                "Iran"
            ],
            "Count" : 1.0
        }
    ],
    "requiredLanguages" : [
        {
            "Name" : [
                "Arabic",
                "English",
                "Russian",
                "Dari",
                "French"
            ],
            "Count" : 1.0
        }
    ],
    "company" : [
        {
            "Name" : "First Company",
            "Count" : 1.0
        },
        {
            "Name" : "My First Company",
            "Count" : 1.0
        }
    ]
}

As you see, I have three document that has following properties:

*

*Two document that has the same position Software Tester, but query return 1 Software Tester (It means if I have multiple documents that have some common values in specific columns, their count result is wrong). The same problem exists for other fields 'contractType, workType, etc...'.

*In array-type fields such as locations, my first document has Germany, Italy, Iran values in locations array, my second document has Afghanistan, Italy, Iran, and my third document has Germany, Italy, Iran. But query result is like this:
"locations" : [
  {
    "Name" : [
      "Afghanistan",
      "Itly",
      "Iran"
    ],
    "Count" : 1.0
  },
  {
    "Name" : [
      "Germany",
      "Itly",
      "Iran"
    ],
    "Count" : 1.0
  }
 ],

This should be like: Germany => 2, Italy,Iran => 3, and Afghanistan => 1
The same problem exists for other array type fields.

A: Apologies I misunderstood your question earlier. To be able to $unwind the location array, but NOT effect your twentyFourHourAgo etc you could look at using $first.
You'll need to $unwind any array if you wish count/sum  the individual elements.
Example of how using $first.
db.getCollection('foo').aggregate([
{ $unwind : "$locations" },
{ "$group" : { "_id" : "$_id",
        "twentyFourHourAgo":{ $first : {
            "$sum" : { "$cond":[
                {"$gt":["$publishDate", ISODate("2016-10-10T00:00:00.000Z")]},1,0 ] } } },
        "fortyEightHourAgo" : { $first : {
            "$sum" : { "$cond" : [
                { "$gt" : [ "$publishDate","2018-01-02T00:00:00.000Z"]},1,0 ] } } },
        "thirtyDaysAgo" : { $first : {
            "$sum" : { "$cond" : [
                { "$gt" : [ "$publishDate","2017-12-31T08:48:16.892Z"]},1,0 ] } } },
        } },
{ "$group" : { "_id" : null,
     "twentyFourHourAgo" : { "$sum" : "$twentyFourHourAgo" },
     "fortyEightHourAgo" : { "$sum" : "$fortyEightHourAgo" },
     "thirtyDaysAgo" : { "$sum" : "$thirtyDaysAgo" },
 }}
])

Output:
"_id" : null,
"twentyFourHourAgo" : 0,
"fortyEightHourAgo" : 3.0,
"thirtyDaysAgo" : 3.0,

Please see here $first for further information on why I think it might be of use. I've stuck an $unwind at the beginning to help prove that it will solve the problem in your OP.


text:
Q: Disable "Priveleged user popup" in fedora 8 Problem Statement :-  Automatic Login as "root" in fedora 8. I tried with "/etc/gdm/config..."  file . (working in linux)
                                 But in fedora 8  there is a pop up showing " Please login as normal user ........"
Is there any way of disabling this pop up so that I can get the desktop and start my application without pressing any key.
I know it's a security issue but still i want to do it.

A: Perhaps you need to allow root login in gdm configuration,
Edit /etc/gdm/custom.conf,
In the [daemon] section, add a line AllowRoot=true


text:
Q: How to prove $X\subseteq Z,Y\subseteq Z,Z\setminus X\subseteq Y$ implies $ Z\subseteq X\cup Y$ I have no idea to prove
$$
X\subseteq Z,Y\subseteq Z,Z\setminus X\subseteq Y\text{, then } Z\subseteq X\cup Y
$$
Can anyone help me? Thanks.

A: Take $x\in Z$. If $x\in X$, then $x\in X\cup Y$. If $x\notin X$, then $x \in Z \setminus X$, and since $Z \setminus X \subseteq Y$, we have $x\in Y$, which means $x\in X\cup Y$. Then, we conclude $Z \subseteq X\cup Y$.

A: Suppose that $ x \in Z$ and $ x \notin X$ so that $ x \in Z \setminus X$.
By hypothesis, $Z \setminus X \subset Y$, so $x \in Y$.

A: $Z\setminus X\subseteq Y \iff z\in Z\wedge z\not\in X \rightarrow z\in Y$
So $z\in Z\iff (z\in Z \wedge z\in X) \vee (z\in Z \vee z\not\in x)  \implies z\in X \vee z \in Y\iff z\in X\cup Y$


text:
Q: linux mdadm: recover overridden array I had 2 3TB disks in a RAID1 array as /dev/md2.
I tried to recover that array, by recreating it (which was probably stupid).
I issued
mdadm --create /dev/md2 --assume-clean --raid-devices=2 --level=1 /dev/md2 /dev/sdc1 /dev/sdd1

I followed some guide on the net, but I think I screwed up, or the guide screwed up. Anyway, I have now a new array, with a new UUID, that does have neither a filesystem nor the data I had stored there.
Haven't touched it otherwise..
I saved the output of mdadm --examine of the old array to files. So I got the original metadata, and I have not touched or formatted the new array.
Can I, somehow, recover the old array?


text:
Q: Angular directive in ng-repeat, $http.get re-runs on filter Using ng-repeat on a directive to display a collection of customer photos from an array of customer objects. The directive takes a customer id and makes an $http.get request to an api that returns the image data. I also have a search input to filter the displayed customer objects. Every time I start to clear the search input and more items return to the view, angular makes the $http.get request again for each instance of the directive and re downloads the image data. How do I avoid this? Thanks!
HTML:

            <contact-photo ng-repeat="customer in customers.customerList | filter:customers.search" id="customer.id" />

Controller:
function Customers($http) {
    var vm = this;

    $http.get('/api/customers')
       .then(function (response) {
           vm.customerList = response.data;
       });
};

Directive:
function contactPhoto() {
    return {
        scope: {},
        bindToController: {
            id: '='
        },
        templateUrl: 'app/common/contactPhoto.vbhtml',
        controller: function ($http, $scope) {
            var vm = this;

            //vm.imgSrc
            $scope.$watch('vm.id', function (newval, oldval) {
                if (newval) {
                    $http.get('/api/Customers/' + vm.id + '/photo?shape=square')
                        .then(function (response) {
                            if (response.data != null) {
                                vm.imgSrc = 'data:image/jpeg;base64,' + response.data;
                            } else {
                                vm.imgSrc = "content/img/DefaultUser.png"
                            }
                        });
                }
            });
        },
        controllerAs: 'vm'
    };
}

UPDATE 1:
I changed my directive controller to remove the $watch on the variable in question. I still get the same problem, where it re-runs on every filter.
function contactPhoto() {
    return {
        scope: {},
        bindToController: {
            id: '='
        },
        templateUrl: 'app/common/contactPhoto.vbhtml',
        controller: function ($http, $scope, $timeout) {
            var vm = this;

            //vm.imgSrc
            $timeout(function () {
                $http.get('/api/Customers/' + vm.id + '/photo?shape=square')
                    .then(function (response) {
                        if (response.data != null) {
                            vm.imgSrc = 'data:image/jpeg;base64,' + response.data;
                        } else {
                            vm.imgSrc = "content/img/DefaultUser.png"
                        }
                });
            })
        },
        controllerAs: 'vm'
    };
}


text:
Q: Can the dual boot start be changed from grub to something else?

Could the dual boot be changed from the usual Grub menu to making a selection with the keyboard?
The idea is to select between, say, Windows and Ubuntu with a key instead of having Grub to appear.
For example: on PC start up, press F1 to load Windows, or F2 if I want to star Ubuntu.
Could this be done so nobody knows there are two different Operating Systems installed?

A: You can easily remove the timeout in /etc/defaults/grub. You change GRUB_TIMEOUT from 10 to 0. If you want something else than Ubuntu to be booted by default you can follow this solution. After changing you need to open a terminal and run sudo update-grub. (if you did it in this order you probably already have)
Then every time the machine starts, you can hold down SHIFT the menu will show up and you can choose what to boot. If you don't it automatically boots the default OS without showing anything.


text:
Q: Unexpected "Bitmap Region is already Locked" exception with GetEncoderParameterList. Any ideas? I'm trying to use this sample code from Microsoft to determine what encoder options are available for the JPEG encoder. (The real problem I'm trying to solve is to see if I can set the Chroma subsampling parameters explicitly)
http://msdn.microsoft.com/en-us/library/bb882589.aspx
private void GetSupportedParameters(PaintEventArgs e)
{
    Bitmap bitmap1 = new Bitmap(1, 1);
    ImageCodecInfo jpgEncoder = GetEncoder(ImageFormat.Jpeg);
    EncoderParameters paramList = bitmap1.GetEncoderParameterList(jpgEncoder.Clsid);
    EncoderParameter[] encParams = paramList.Param;
    StringBuilder paramInfo = new StringBuilder();

    for (int i = 0; i < encParams.Length; i++)
    {
        paramInfo.Append("Param " + i + " holds " + encParams[i].NumberOfValues +
            " items of type " +
            encParams[i].ValueType + "\r\n" + "Guid category: " + encParams[i].Encoder.Guid + "\r\n");

    }
    e.Graphics.DrawString(paramInfo.ToString(), this.Font, Brushes.Red, 10.0F, 10.0F);
}

private ImageCodecInfo GetEncoder(ImageFormat format)
{

    ImageCodecInfo[] codecs = ImageCodecInfo.GetImageDecoders();

    foreach (ImageCodecInfo codec in codecs)
    {
        if (codec.FormatID == format.Guid)
        {
            return codec;
        }
    }
    return null;
}

The problem is, "GetEncoderParameterList" always throws an exception: Bitmap Region Is already Locked.
I tried putting the code at the very beginning of my program, and not in an on-paint event handler. Same thing. I tried changing the bit depth on the bitmap, and creating bitmaps in other ways, no difference.
Any idea why .NET would think a freshly created bitmap has a locked region?

Update! Some more info: If I use a TIFF encoder, it doesn't fail:
    Bitmap bitmap1 = new Bitmap(1, 1);
    ImageCodecInfo jpgEncoder = GetEncoder(ImageFormat.TIFF);  // TIFF instead of JPEG
    EncoderParameters paramList = bitmap1.GetEncoderParameterList(jpgEncoder.Clsid);
    EncoderParameter[] encParams = paramList.Param;

So I think this may just be a bug/limitation of GetEncoderparameterList for jpeg....

A: I repro this.  The exception message is bogus, that's common for GDI+ exceptions.  The source of the problem is the jpeg codec, GetEncoderParameterList() queries it for the list of parameters it supports.  The list it gets back contains one bad entry, the NumberOfValues is 0.  That causes Marshal.AllocHGlobal() to return a NULL, misinterpreted as an out-of-memory exception, which is turn is misinterpreted as a "Bitmap region is already locked" exception.
Ugh, GDI+ sure is a mess.  This problem is almost certainly specific to GDI+ version 1.10, the version that first shipped with Vista.  Could be Win7 specific too, I've seen several forum posting about problems with the JPEG codec on that operating system.
Well, nothing you can do about it until the next Windows service pack becomes available, if then.  To address your specific query, no, probably not.  The list of encoder parameters that GDI+ knows about is listed in the GdiPlusImaging.h SDK header file.  The only one that's close is "EncoderChrominanceTable", available as Encoder.ChrominanceTable.Guid in the .NET framework.  No idea if that's close to what you are looking for.
You should really consider the WPF JpegBitmapEncoder class, a major improvement over GDI=.

A: This is being adressed for .NET Core 5.0 - see https://github.com/dotnet/runtime/pull/32873.


text:
Q: dd: different unit for bs, skip and count? I am trying to copy a partition from an entire disk image.
This command is working: dd if=image.iso of=test bs=512 skip=1161215 count=32768
In order to increase the speed, I'd like to set a bigger bs.
dd if=image.iso of=test bs=1M skip=1161215 count=32768
skip and count's unit is bs, is it possible to set a separate unit ?
I could then make this command:
dd if=image.iso of=test bs=4M skip=1161215*512 bytes count=32768*512 bytes

A: Specify Different Units
Yes, it is possible to specifiy different units for bs and skip and count. However, there are only two choices for the skip and count units. skip and count must match the bs value or be specified in bytes. To set the units to bytes you must add an additional operand of iflag=skip_bytes for skip and iflag=count_bytes for count or iflag=skip_bytes,count_bytes for both.
In your case, this command should accomplish your goal:
dd if=image.iso of=test iflag=skip_bytes,count_bytes bs=4M \
  skip=$((1161215*512)) count=$((32768*512))

It appears you want to extract exactly 16M. Set bs=4M count=4 and use only skip_bytes:
dd if=input.file of=output.file iflag=skip_bytes bs=4M \
  skip=$((1161215*512)) count=4

Example for testing:
An input file with the contents:
aabbccddeeffgghhiijjkkllmmnnooppqqrrssttuuvvwwxxyyzz

With count_bytes (extract exactly count bytes):
$ dd if=input.file of=output.file iflag=skip_bytes,count_bytes bs=8 skip=5 count=20

yields 20 characters:
cddeeffgghhiijjkkllm

Without count_bytes (count is multiplied by bs):
dd if=input.file of=output.file iflag=skip_bytes bs=8 skip=5 count=3

yields 24 characters:
cddeeffgghhiijjkkllmmnno

Your version of dd may not include iflag, skip_bytes, or count_bytes.
These examples were tested on Debian 9 using dd (coreutils) 8.26.
Update: skip_bytes and count_bytes are supported from coreutils v8.16(March 2012), so nearly all distributions will support it by default

A: It is possible by combining dd commands.
dd if=image.iso bs=4M | { dd bs=1161215 count=1 of=/dev/null; dd bs=${16*512} count=${32768/16} of=partition.dump; }
We can just use the count size as a dividable without remainder instead of both, offset and size.
Or use the end sectors.

A: What you want to achieve seems impossible to me.
From man dd:
   bs=BYTES
          read and write up to BYTES bytes at a time

   ibs=BYTES
          read up to BYTES bytes at a time (default: 512)

   obs=BYTES
          write BYTES bytes at a time (default: 512)

   count=N
          copy only N input blocks

   skip=N skip N ibs-sized blocks at start of input

While bs (or ibs and obs) has an argument BYTES which determines the block size i.e. the amount of bytes that gets processed at once, the count and seek parameters have an argument N which determines the number of blocks to process/skip.
So as dd can always only copy or skip whole blocks of data (block size determined by bs/ibs&obs), you must set the block size to a value by which the skip offset and the count size are dividable without remainder.

A:
is it possible to set a separate unit?

AFAIK, with dd only, no.
but you can use losetup to achieve your goal, like this:
dd if=$(losetup --sector-size 512 --offset $((1161215*512)) --sizelimit $((32768*512)) --find --show image.iso) of=test bs=4M

or, more concisely, like this:
dd if=$(losetup -b 512 -o $((1161215*512)) --sizelimit $((32768*512)) -f --show image.iso) of=test bs=4M

Even more...

In order to increase the speed, I'd like to set a bigger bs

if you just want to 'forget about' "blocksize optimization",
and it's available for you, simply use pv, like this:
pv $(losetup -b 512 -o $((1161215*512)) --sizelimit $((32768*512)) -f --show image.iso) > test