text:
Q: Printing from Java fails with 'pstopdffilter/pstocupsraster failed with err number -31000' When trying to print a JPEG file with the Java code below on Mac OS X 10.8.0 I get
the error message:
Error: pstopdffilter/pstocupsraster failed with err number 31000

A Gooogle search brings suggestions that seem to hint that the problem is not directly to Java
e.g.
http://forum.parallels.com/showthread.php?t=106337
/**
 * http://stackoverflow.com/questions/7843338/printing-a-tif-file
 *
 * @param graphicFile
 * @throws PrintException
 * @throws IOException
 */
public void printGraphic(File graphicFile) throws PrintException,
        IOException {

    PrintRequestAttributeSet pras = new HashPrintRequestAttributeSet();
    pras.add(new Copies(1));
    pras.add(Chromaticity.COLOR);
    pras.add(MediaSizeName.ISO_A4);
    PrintService pss[] = PrintServiceLookup.lookupPrintServices(
            DocFlavor.INPUT_STREAM.JPEG, pras);

    if (pss.length == 0)
        throw new RuntimeException("No printer services available.");

    PrintService ps = pss[0];
    System.out.println("Printing to " + ps);
    DocPrintJob job = ps.createPrintJob();
    FileInputStream fin = new FileInputStream(graphicFile);
    Doc doc = new SimpleDoc(fin, DocFlavor.INPUT_STREAM.JPEG, null);
    job.print(doc, pras);
    fin.close();
}

A: As a workaround I would suggest to use jpeg instead of tiff.
/**
 * http://stackoverflow.com/questions/5338423/print-a-image-with-actual-size
 * -in-java
 *
 * @param graphicFile
 */
public void printG(File graphicFile) {
    final Image img = new ImageIcon(graphicFile.getAbsolutePath())
            .getImage();
    PrinterJob printJob = PrinterJob.getPrinterJob();
    Printable printable = new Printable() {
        public int print(Graphics graphics, PageFormat pageFormat,
                int pageIndex) throws PrinterException {
            if (pageIndex != 0) {
                return NO_SUCH_PAGE;
            }
            graphics.drawImage(img, 0, 0, img.getWidth(null),
                    img.getHeight(null), null);
            return PAGE_EXISTS;
        }
    };
    printJob.setPrintable(printable, getPageFormat());
    if (printJob.printDialog()) {
        try {
            printJob.print();
        } catch (Exception prt) {
            handle(prt);
        }
    }
}

A: You say you're "trying to print a JPEG file".
However, the error message suggests that CUPS (the Mac OS X print subsystem) tries to run the printjob through either pstopdffilter (a utility that converts PostScript to PDF) or through pstocupsraster (a utility that converts PostScript to CUPS-raster).
You should first enable LogLevel debug (edit /private/etc/cups/cupsd.conf and restart the CUPS print service).
Then, look in the CUPS log file (*/var/log/cups/error_log*) for the lines containing the following strings:
Auto-typing file...
Request file type is
Started filter
Started backend
exited with
failed with

Your findings could look similar to the following:
D [...timestamp...] [Job 9] Auto-typing file...
D [...timestamp...] [Job 9] Request file type is image/jpeg.
I [...timestamp...] [Job 9] Started filter /usr/libexec/cups/filter/imagetops (PID 25690)
I [...timestamp...] [Job 9] Started filter /usr/libexec/cups/filter/pstops (PID 25691)
I [...timestamp...] [Job 9] Started filter /usr/libexec/cups/filter/pstopdffilter (PID 25694)
I [...timestamp...] [Job 9] Started backend /usr/libexec/cups/backend/2dir (PID 25695)
D [...timestamp...] PID 25690 (/usr/libexec/cups/filter/imagetops) exited with no errors.
D [...timestamp...] PID 25691 (/usr/libexec/cups/filter/pstops) exited with no errors.
E [...timestamp...] PID 25694 (/usr/libexec/cups/filter/pstopdffilter) failed with err number -31000.
D [...timestamp...] PID 25695 (/usr/libexec/cups/backend/2dir) exited with no errors.

I said 'similar to the following' because my crystal ball is in repair right now, and you didn't provide any additional details about your print environment setup, without which it will not be possible to analyze your problem any further.
Also, look in the log file for lines that indicate a PostScript error, for example:
D [...timestamp...] [Job 9] %%[ Error: ioerror; OffendingCommand: image ]%%
D [...timestamp...] [Job 9]
D [...timestamp...] [Job 9] Stack:
D [...timestamp...] [Job 9] -dict-
D [...timestamp...] [Job 9]
D [...timestamp...] [Job 9] %%[ Flushing: rest of job (to end-of-file) will be ignored ]%%
D [...timestamp...] [Job 9]
D [...timestamp...] [Job 9] %%[ Warning: PostScript error. No PDF file produced. ] %%

In which case your input file may be faulty, may be too big or whatever...
In general, it would be important to know:

*

*What did the "auto-typing" function of the print service return for the print job's mime type?

*What filters have been running (if any) in the filter chain before pstopdffilter (or pstocupsraster) came into play?


text: Q: Reference Request: introductory text for advanced type of differential equation I am looking for an introductory reference to advanced differential equation, for example $x'(t) = x(t+1)$. The term "advanced" makes the search quite challenging using Google. The topic is sometimes introduced in-passing in other delay or functional textbook. Perhaps something at the level of "A First Course in Integral Equations" by Abdul-Majid Wazwaz is most appropriate. Thanks!

redpajama_set_name: RedPajamaStackExchange


text:
Q: Python lxml html builder hey guys i want to make a html in python. I read a xml with python requests. And i counted the elements of an attribute.
count = len(nodeData.xpath("//user[@condition='good']"))
print (count)`

like this.
but now i want to get a table in which the number of the count stays.
nodeRow = html.TR(html.TD(count , style="background-color:#FF0000")
nodeTable.append(nodeRow)

print etree.tostring(nodeTable)
with open("out3.html", "wb") as f:
    f.write(etree.tostring(nodeTable))

But that doesn't work. The error is

TypeError: bad argument type: int(2746)

A: The error-code is pretty clear - you can't put strings into the text-content of an Element. As you have an int, Python balks. Convert it to a string first:
nodeRow = html.TR(html.TD(str(count) , style="background-color:#FF0000")

You should consider using a template library though, it will make doing this much easier, as it takes care of these little obstacles, and allows a more natural writing of longer HTML snippets.


text:
Q: Quotient ring, quick question How do I read R \ {0}, R modulo zero? With R being the Real number ring. Is this just the Real number ring R without zero?

A: If $x \in \mathbb R - \{0\}$ then $x \in \mathbb R$ and $x \notin \{0\}$. That is, $x$ is a real number different from zero.
If otherwise you mean $\mathbb R/\langle0\rangle =\frac{\mathbb R}{\langle0\rangle}$ then is the set of equivalence classes such that $[x] = [y] \Leftrightarrow x - y \in \langle 0\rangle$.

A: The notation $\mathbb{R} \setminus \{0\}$ means all non-zero reals, often also written as $\mathbb{R}^{\ast}$.
A very technical way to read it would be the set difference of the set of reals numbers and the set containing zero. Yet hardly anybody would say it like this.
One might say the reals without $0$ or even the non-zero reals.
The noation $\mathbb{R} / \{0\}$ could be read as $\mathbb{R}$ modulo $0$ or also as the quotient group of the reals by the trivial subgroup. This however should appear rarely in practice as taking a quotient by the trivial subgroup is not very interesting, basically just yielding the original group.


text:
Q: C# .NET How to read continuously an input from a PLC through Modbus I am using the EasyModbus library from GitHub to communicate to the PLC, I tried the required functions and I accomplish to run them on visual studio 2019 individually, and worked fine.
I did a basic program to switch on and off an output of the PLC by using two buttons. And also reading/monitoring an output from the same PLC by changing two colors(yellow On and red Off) on C# form1.
Then, when I click the on and off buttons they work fine but on the other hand, the reading/monitoring function didn't work. I need someone to illustrate some modifications how to run these functions simultaneously and at the same time changing the on/off status of the output and also reading the status of an output of the PLC.
Thank you
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using EasyModbus;
using System.Windows.Forms;

namespace PLC
{
    public partial class Form1 : Form
    {
        ModbusClient modbusClient;

        public Form1()
        {
            InitializeComponent();
            ON.Visible = true; //yellow
            OFF.Visible = true;//red
            modbusClient = new ModbusClient("COM5");//communication settings
            modbusClient.UnitIdentifier = 1;
            modbusClient.Baudrate = 19200;
            modbusClient.Parity = System.IO.Ports.Parity.None;
            modbusClient.StopBits = System.IO.Ports.StopBits.One;
            modbusClient.Connect();

    // reading function begin
            var value = modbusClient.ReadCoils(0, 1);// read coil zero and if it is true change color yellow else change color to red

            if (value[0] == true)
            {
                ON.Visible = true;
                OFF.Visible = false;
            }
            else
            {
                ON.Visible = false;
                OFF.Visible = true;
            }

    // end of reading function

        }
        private void button1_Click(object sender, EventArgs e)// on button
        {
            modbusClient.WriteSingleCoil(0, true);//toggle coil zero to on
        }

        private void button2_Click(object sender, EventArgs e)// off button
        {
            modbusClient.WriteSingleCoil(0, false);// toggle coil zero to off
        }
    }
}

A: Try to use timers.
Here is your modified code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using EasyModbus;
using System.Windows.Forms;

namespace StackOverflowAnswer
{
    public partial class Form1 : Form
    {
        ModbusClient modbusClient;

        public Form1()
        {
            InitializeComponent();
            ON.Visible = true; //yellow
            OFF.Visible = true;//red
            // ### changed to TCP - I have no COM ports ###
            modbusClient = new ModbusClient("127.0.0.1", 502); //communication settings
            //modbusClient.UnitIdentifier = 1;
            //modbusClient.Baudrate = 19200;
            //modbusClient.Parity = System.IO.Ports.Parity.None;
            //modbusClient.StopBits = System.IO.Ports.StopBits.One;
            modbusClient.Connect();

            #region Modified section
            var readModBusTimer = new Timer()
            {
                Interval = 500,
                Enabled = true
            };

            readModBusTimer.Tick += ReadModBusTimer_Tick;
            readModBusTimer.Start();

            // reading function begin
            ReadCoils();

            // end of reading function

        }

        private void ReadCoils()
        {
            var value = modbusClient.ReadCoils(0, 1);// read coil zero and if it is true change color yellow else change color to red

            if (value[0] == true)
            {
                ON.Visible = true;
                OFF.Visible = false;
            }
            else
            {
                ON.Visible = false;
                OFF.Visible = true;
            }
        }

        private void ReadModBusTimer_Tick(object sender, EventArgs e)
        {
            ReadCoils();
        }
        #endregion
        private void button1_Click(object sender, EventArgs e)// on button
        {
            modbusClient.WriteSingleCoil(0, true);//toggle coil zero to on
        }

        private void button2_Click(object sender, EventArgs e)// off button
        {

            modbusClient.WriteSingleCoil(0, false);// toggle coil zero to off
        }

    }
}


text:
Q: On click next or previous button request should not go to data base or server in crystal report When I click on next page or previous page button to move crystal report pages, it goes to database each click.
I saw on once web app first time request goes to server then on click next or previous button this refresh report within mill seconds and it seems this request doesn't hit to data base.
Is it possible to make its cache or like something etc?


text:
Q: Entity Framework Is Null, Is Not Null Using DB2 I tried this:

var query = this.context.PERFIL_ALERTA.Where(x => x.CodigoEmpresa == EmpresaId && x.IdAtividade == null);

But Entity do this:
SELECT
CAST(NULL AS decimal(18,2)) AS C1,
CAST(NULL AS decimal(18,2)) AS C2,
CAST(NULL AS decimal(18,2)) AS C3,
CAST(NULL AS varchar(1)) AS C4,
CAST(NULL AS decimal(18,2)) AS C5,
CAST(NULL AS decimal(18,2)) AS C6,
CAST(NULL AS decimal(18,2)) AS C7,
CAST(NULL AS decimal(18,2)) AS C8,
CAST(NULL AS varchar(1)) AS C9,
CAST(NULL AS timestamp) AS C10
FROM  ( SELECT CAST(1 AS int) AS X FROM SYSIBM.SYSDUMMY1 ) AS SingleRowTable1
WHERE CAST('t' AS boolean) = CAST('f' AS boolean)

And Give-me an error:

exception -> ERROR [42846] [CLASS][DB2/NT64] SQL0461N  A value with
  data type "SYSCLASS.VARCHAR" cannot be CAST to type
  "SYSCLASS.BOOLEAN".
and on debug in DB2:
-- Failed in 355 ms with error: ERROR [42846] [CLASS][DB2/NT64] SQL0461N  A value with data type "SYSCLASS.VARCHAR" cannot be CAST to type
  "SYSCLASS.BOOLEAN".

I have a nullable field on DB2 Table. How Make Is Null Comparison?
On sqlserver works fine...but in db2....

A: A colleague at work helped me.
My map was wrong. The field idAtividade is nullable. The relation need be optional.
this.HasRequired (T => t.ATIVIDADE)
                 .WithMany (T => t.PERFIL_ALERTAs)
                 .HasForeignKey (T => t.IdAtividade);

correction
this.HasOptional (T => t.ATIVIDADE)
.WithMany (T => t.PERFIL_ALERTAs)
.HasForeignKey (T => t.IdAtividade);


text:
Q: How to programmatically select an item in a WPF TreeView? How is it possible to programmatically select an item in a WPF TreeView?  The ItemsControl model seems to prevent it.

A: This is not as simple as it looks, the link provided by Steven has a solution posted in 2008, which may still works but doesn't take care of Virtualized TreeViews. Moreover many other problems are mentioned in comments of that article. No offences, but I am also stuck with same problem and can't find a perfect solution. Here are the links to some of the articles/posts which helped me a lot-
How can I expand items in a TreeView? – Part III:
http://bea.stollnitz.com/blog/?p=59
Programmatically Selecting an Item in a TreeView:
http://blog.quantumbitdesigns.com/2008/07/22/programmatically-selecting-an-item-in-a-treeview/#respond
TreeView, TreeViewItem and IsSelected:
http://social.msdn.microsoft.com/Forums/en-US/wpf/thread/7e368b93-f509-4cd6-88e7-561e8d3246ae/

A: For those who are still looking for the right solution to this problem here is the one below. I found this one in the comments to the Code Project article "WPF TreeView Selection" http://www.codeproject.com/KB/WPF/TreeView_SelectionWPF.aspx by DaWanderer.
It was posted by Kenrae on Nov 25 2008. This worked great for me. Thanks Kenrae!
Here is his post:
Instead of walking the tree, have your own data object have the IsSelected property (and I recommend the IsExpanded property too). Define a style for the TreeViewItems of the tree using the ItemContainerStyle property on the TreeView that binds those properties from the TreeViewItem to your data objects. Something like this:

      </Style>

<TreeView ItemsSource="{Binding Path=YourCollection}"
               ItemContainerStyle="{StaticResource LibraryTreeViewItemStyle}"
               ItemTemplate={StaticResource YourHierarchicalDataTemplate}/>

A: It's a real pain for some strange reason, you have to use ContainerFromItem to get the container, then invoke the select method.
//  selectedItemObject is not a TreeViewItem, but an item from the collection that
//  populated the TreeView.

var tvi = treeView.ItemContainerGenerator.ContainerFromItem(selectedItemObject)
          as TreeViewItem;

if (tvi != null)
{
    tvi.IsSelected = true;
}

There once was a blog entry on how to do it here, but the link is dead now.

A: I wrote an extension method:
using System.Windows.Controls;

namespace Extensions
{
    public static class TreeViewEx
    {
        ///
        /// Select specified item in a TreeView
        ///
        public static void SelectItem(this TreeView treeView, object item)
        {
            var tvItem = treeView.ItemContainerGenerator.ContainerFromItem(item) as TreeViewItem;
            if (tvItem != null)
            {
                tvItem.IsSelected = true;
            }
        }
    }
}

Which I can use like this:
if (_items.Count > 0)
    _treeView.SelectItem(_items[0]);

A: You need to get the TreeViewItem and then set IsSelected to true.

A: I've succeeded with this code:
public static TreeViewItem FindTviFromObjectRecursive(ItemsControl ic, object o) {
  //Search for the object model in first level children (recursively)
  TreeViewItem tvi = ic.ItemContainerGenerator.ContainerFromItem(o) as TreeViewItem;
  if (tvi != null) return tvi;
  //Loop through user object models
  foreach (object i in ic.Items) {
    //Get the TreeViewItem associated with the iterated object model
    TreeViewItem tvi2 = ic.ItemContainerGenerator.ContainerFromItem(i) as TreeViewItem;
    tvi = FindTviFromObjectRecursive(tvi2, o);
    if (tvi != null) return tvi;
  }
  return null;
}

Usage:
var tvi = FindTviFromObjectRecursive(TheTreeView, TheModel);
if (tvi != null) tvi.IsSelected = true;

A: If you want to select item located withing children of child you can user recursion to do that.
public bool Select(TreeViewItem item, object select) // recursive function to set item selection in treeview
{
    if (item == null)
        return false;
    TreeViewItem child = item.ItemContainerGenerator.ContainerFromItem(select) as TreeViewItem;
    if (child != null)
    {
        child.IsSelected = true;
        return true;
    }
    foreach (object c in item.Items)
    {
        bool result = Select(item.ItemContainerGenerator.ContainerFromItem(c) as TreeViewItem, select);
        if (result == true)
            return true;
    }
    return false;
}

A: I have created a method VisualTreeExt.GetDescendants<T> that returns an enumerable collection of elements that match the specified type:
public static class VisualTreeExt
{
  public static IEnumerable<T> GetDescendants<T>(DependencyObject parent) where T : DependencyObject
  {
    var count = VisualTreeHelper.GetChildrenCount(parent);
    for (var i = 0; i < count; ++i)
    {
       // Obtain the child
       var child = VisualTreeHelper.GetChild(parent, i);
       if (child is T)
         yield return (T)child;

       // Return all the descendant children
       foreach (var subItem in GetDescendants<T>(child))
         yield return subItem;
    }
  }
}

When you ask for VisualTreeHelperExt.GetDescendants<TreeViewItem>(MyAmazingTreeView) you'll get all the TreeViewItem childs. You can select a particular value using the following piece of code:
var treeViewItem = VisualTreeExt.GetDescendants<TreeViewItem>(MyTreeView).FirstOrDefault(tvi => tvi.DataContext == newValue);
if (treeViewItem != null)
  treeViewItem.IsSelected = true;

It's a bit of a dirty solution (and probably not the most efficient) and won't work if you're using a virtualized TreeView, because it depends on the existance of the actual visual elements. But it works for my situation...

A: You can do it via code behind like
if (TreeView1.Items.Count > 0)
        (TreeView1.Items[0] as TreeViewItem).IsSelected = true;

A: The proposed answer doesn't work. @fandisusanto's answer probably does work, but it can be made simpler. This is the simplest answer I can come up with:
    private static void DeselectTreeViewItem(IEnumerable<TreeViewItem> treeViewItems)
    {
        foreach (var treeViewItem in treeViewItems)
        {
            if (treeViewItem.IsSelected)
            {
                treeViewItem.IsSelected = false;
                return;
            }

            DeselectTreeViewItem(treeViewItem.Items.Cast<TreeViewItem>());
        }
    }

Usage:
    private void ClearSelectedItem()
    {
        if (AssetTreeView.SelectedItem != null)
        {
            DeselectTreeViewItem(AssetTreeView.Items.Cast<TreeViewItem>());
        }
    }

A: Try with this
    ///
    /// Selects the tree view item.
    ///
    /// <param name="Collection">The collection.</param>
    /// <param name="Value">The value.</param>
    /// <returns></returns>
    private TreeViewItem SelectTreeViewItem(ItemCollection Collection, String Value)
    {
        if (Collection == null) return null;
        foreach(TreeViewItem Item in Collection)
        {
            /// Find in current
            if (Item.Header.Equals(Value))
            {
                Item.IsSelected = true;
                return Item;
            }
            /// Find in Childs
            if (Item.Items != null)
            {
                TreeViewItem childItem = this.SelectTreeViewItem(Item.Items, Value);
                if (childItem != null)
                {
                    Item.IsExpanded = true;
                    return childItem;
                }
            }
        }
        return null;
    }

Reference: http://amastaneh.blogspot.com/2011/06/wpf-selectedvalue-for-treeview.html

A: Just thought I would chime in with the solution I went with, in case this can help anyone.  Note that the best way to do this is using a bound property like 'IsSelected' as per kuninl's answer, but in my case it was a legacy application that did not follow MVVM, so I ended up with the below.
private void ChangeSessionSelection()
{
    foreach (SessionContainer item in this.treeActiveSessions.Items)
    {
        var treeviewItem = this.treeActiveSessions.ItemContainerGenerator.ContainerFromItem(item) as TreeViewItem;

        if (item.Session == this.selectedSession.Session)
        {
            treeviewItem.IsSelected = true;
            treeviewItem.IsExpanded = true;
        }
        else
        {
            treeviewItem.IsSelected = false;
            treeviewItem.IsExpanded = false;
        }
    }
}

What this does is select and expand the treeview item in the UI that represents the selected dataitem in the code behind.  The purpose of this was to have the selection change in the treeview when the users selection changed in an items control in the same window.

A: Yeah.. I know many years past since the question was asked but.. still no quick solution to this problem.. and So:
The following will do what the OP asked for.
What I basically done is reading all the answers in this page and following all the relevant links to create a once and for all solution to this irritating problem.
Benefits:

*

*It support Virtualizing TreeView as well.

*It using the behavior technique, so XAML is way easy.

*Adds a dependancy-property to allow binding to the selected TreeView Item.

This part is the only code you need to copy, the other parts are just to help complete an example.
public static class TreeViewSelectedItemExBehavior
{
    private static List<TreeView> isRegisteredToSelectionChanged = new List<TreeView>();

    public static readonly DependencyProperty SelectedItemExProperty =
        DependencyProperty.RegisterAttached("SelectedItemEx",
            typeof(object),
            typeof(TreeViewSelectedItemExBehavior),
            new FrameworkPropertyMetadata(new object(), FrameworkPropertyMetadataOptions.BindsTwoWayByDefault, OnSelectedItemExChanged, null));

    #region SelectedItemEx

    public static object GetSelectedItemEx(TreeView target)
    {
        return target.GetValue(SelectedItemExProperty);
    }

    public static void SetSelectedItemEx(TreeView target, object value)
    {
        target.SetValue(SelectedItemExProperty, value);
        var treeViewItemToSelect = GetTreeViewItem(target, value);
        if (treeViewItemToSelect == null)
        {
            if (target.SelectedItem == null)
                return;
            var treeViewItemToUnSelect = GetTreeViewItem(target, target.SelectedItem);
            treeViewItemToUnSelect.IsSelected = false;
        }
        else
            treeViewItemToSelect.IsSelected = true;
    }

    public static void OnSelectedItemExChanged(DependencyObject depObj, DependencyPropertyChangedEventArgs e)
    {
        var treeView = depObj as TreeView;
        if (treeView == null)
            return;
        if (!isRegisteredToSelectionChanged.Contains(treeView))
        {
            treeView.SelectedItemChanged += TreeView_SelectedItemChanged;
            isRegisteredToSelectionChanged.Add(treeView);
        }
    }

    #endregion

    private static void TreeView_SelectedItemChanged(object sender, RoutedPropertyChangedEventArgs<object> e)
    {
        var treeView = (TreeView)sender;
        SetSelectedItemEx(treeView, e.NewValue);
    }

    #region Helper Structures & Methods

    public class MyVirtualizingStackPanel : VirtualizingStackPanel
    {
        ///
        /// Publically expose BringIndexIntoView.
        ///
        public void BringIntoView(int index)
        {
            BringIndexIntoView(index);
        }
    }

    /// Recursively search for an item in this subtree.
    /// <param name="container">The parent ItemsControl. This can be a TreeView or a TreeViewItem.</param>
    /// <param name="item">The item to search for.</param>
    /// <returns>The TreeViewItem that contains the specified item.</returns>
    private static TreeViewItem GetTreeViewItem(ItemsControl container, object item)
    {
        if (container != null)
        {
            if (container.DataContext == item)
            {
                return container as TreeViewItem;
            }

            // Expand the current container
            if (container is TreeViewItem && !((TreeViewItem)container).IsExpanded)
            {
                container.SetValue(TreeViewItem.IsExpandedProperty, true);
            }

            // Try to generate the ItemsPresenter and the ItemsPanel.
            // by calling ApplyTemplate.  Note that in the
            // virtualizing case even if the item is marked
            // expanded we still need to do this step in order to
            // regenerate the visuals because they may have been virtualized away.

            container.ApplyTemplate();
            ItemsPresenter itemsPresenter =
                (ItemsPresenter)container.Template.FindName("ItemsHost", container);
            if (itemsPresenter != null)
            {
                itemsPresenter.ApplyTemplate();
            }
            else
            {
                // The Tree template has not named the ItemsPresenter,
                // so walk the descendents and find the child.
                itemsPresenter = FindVisualChild<ItemsPresenter>(container);
                if (itemsPresenter == null)
                {
                    container.UpdateLayout();

                    itemsPresenter = FindVisualChild<ItemsPresenter>(container);
                }
            }

            Panel itemsHostPanel = (Panel)VisualTreeHelper.GetChild(itemsPresenter, 0);

            // Ensure that the generator for this panel has been created.
            UIElementCollection children = itemsHostPanel.Children;

            MyVirtualizingStackPanel virtualizingPanel =
                itemsHostPanel as MyVirtualizingStackPanel;

            for (int i = 0, count = container.Items.Count; i < count; i++)
            {
                TreeViewItem subContainer;
                if (virtualizingPanel != null)
                {
                    // Bring the item into view so
                    // that the container will be generated.
                    virtualizingPanel.BringIntoView(i);

                    subContainer =
                        (TreeViewItem)container.ItemContainerGenerator.
                        ContainerFromIndex(i);
                }
                else
                {
                    subContainer =
                        (TreeViewItem)container.ItemContainerGenerator.
                        ContainerFromIndex(i);

                    // Bring the item into view to maintain the
                    // same behavior as with a virtualizing panel.
                    subContainer.BringIntoView();
                }

                if (subContainer != null)
                {
                    // Search the next level for the object.
                    TreeViewItem resultContainer = GetTreeViewItem(subContainer, item);
                    if (resultContainer != null)
                    {
                        return resultContainer;
                    }
                    else
                    {
                        // The object is not under this TreeViewItem
                        // so collapse it.
                        subContainer.IsExpanded = false;
                    }
                }
            }
        }

        return null;
    }

    /// Search for an element of a certain type in the visual tree.
    /// <typeparam name="T">The type of element to find.</typeparam>
    /// <param name="visual">The parent element.</param>
    /// <returns></returns>
    private static T FindVisualChild<T>(Visual visual) where T : Visual
    {
        for (int i = 0; i < VisualTreeHelper.GetChildrenCount(visual); i++)
        {
            Visual child = (Visual)VisualTreeHelper.GetChild(visual, i);
            if (child != null)
            {
                T correctlyTyped = child as T;
                if (correctlyTyped != null)
                {
                    return correctlyTyped;
                }

                T descendent = FindVisualChild<T>(child);
                if (descendent != null)
                {
                    return descendent;
                }
            }
        }
        return null;
    }

    #endregion
}

And this is an example of how the TreeView line looks like in XAML:
<TreeView x:Name="trvwSs"
    Grid.Column="2" Grid.Row="1" Margin="4" ItemsSource="{Binding ItemsTreeViewSs}"
    behaviors:TreeViewSelectedItemExBehavior.SelectedItemEx="{Binding SelectedItemTreeViewSs}" />

Only thing to worry about is to make sure your view-model property that you about to bound to SelectedItemEx is not null. But that is not a special case.. Just mentioned it in case people get confused.
public class VmMainContainer : INotifyPropertyChanged
{
    private object selectedItemTreeViewSs = new object();
    private ObservableCollection<object> selectedItemsTreeViewSs = new ObservableCollection<object>();
    private ObservableCollection<VmItem> itemsTreeViewSs = new ObservableCollection<VmItem>();

    public object SelectedItemTreeViewSs
    {
        get
        {
            return selectedItemTreeViewSs;
        }
        set
        {
            selectedItemTreeViewSs = value;
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(SelectedItemTreeViewSs)));
        }
    }

    public ObservableCollection<object> SelectedItemsTreeViewSs
    {
        get
        {
            return selectedItemsTreeViewSs;
        }
        set
        {
            selectedItemsTreeViewSs = value;
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(SelectedItemsTreeViewSs)));
        }
    }

    public ObservableCollection<VmItem> ItemsTreeViewSs
    {
        get { return itemsTreeViewSs; }
        set
        {
            itemsTreeViewSs = value;
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(ItemsTreeViewSs)));
        }
    }
}

And last thing.. example of selecting programmatically:
I created a button on my MainWindow.xaml and from its handler..
private void Button_Click(object sender, RoutedEventArgs e)
{
    TreeViewSelectedItemExBehavior.SetSelectedItemEx(trvwSs, trvwSs.Items[3]);
    //TreeViewSelectedItemExBehavior.SetSelectedItemEx(trvwSs, null);
}

Hope this helps someone :)

A: This is my solution.  The others failed for me in various ways.  You need to walk the tree from top to bottom, looking for the tree item at each level, expanding and updating the layout along the way.
This function takes a stack of nodes where the first one out of the stack is the top most node, and each subsequent node on the stack is a child of the previous parent.  The second argument is the TreeView.
As each item is found, that item is expanded, and the final item is returned, where the caller can select it.
    TreeViewItem FindTreeViewItem( Stack<object> nodeStack, TreeView treeView )
    {
        ItemsControl itemsControl = treeView;

        while (nodeStack.Count > 0) {
            object node = nodeStack.Pop();
            bool found = false;

            foreach (object item in itemsControl.Items) {
                if (item == node) {
                    found = true;

                    if (itemsControl.ItemContainerGenerator.ContainerFromItem( item ) is TreeViewItem treeViewItem) {
                        if (nodeStack.Count == 0) {
                            return treeViewItem;
                        }

                        itemsControl = treeViewItem;
                        treeViewItem.IsExpanded = true;
                        treeViewItem.UpdateLayout();
                        break;
                    }
                }
            }

            if (!found) {
                return null;
            }
        }

        return null;
    }

Example of how to call it:
    // Build nodeStack here from your data

    TreeViewItem treeViewItem = FindTreeViewItem( nodeStack, treeView );

    if (treeViewItem != null) {
        treeViewItem.IsSelected = true;
        treeViewItem.BringIntoView();
    }

A: I wrote a Helper class for this, which supports MVVM and lazy loaded items.
public class TreeViewHelper<TModel>
{
    public TreeViewHelper(TreeView treeView, Func<TModel, TModel> getParent, Func<TModel, IList<TModel>> getSubItems)
    {
        TreeView = treeView;
        GetParent = getParent;
        GetSubItems = getSubItems;
    }

    public TreeView TreeView { get; }
    public Func<TModel, TModel> GetParent { get; }
    public Func<TModel, IList<TModel>> GetSubItems { get; }

    public void SelectItemWhileLoaded(TModel node, IList<TModel> rootNodes)
    {
        if (TreeView.IsLoaded)
        {
            SelectItem(node, rootNodes);
        }
        else
        {
            TreeView.Loaded += TreeView_Loaded;
            void TreeView_Loaded(object sender, System.Windows.RoutedEventArgs e)
            {
                TreeView.Loaded -= TreeView_Loaded;
                SelectItem(node, rootNodes);
            }
        }
    }

    public void SelectItem(TModel node, IList<TModel> rootNodes)
    {
        Stack<TModel> nodes = new Stack<TModel>();
        //push into stack
        while (!rootNodes.Contains(node))
        {
            nodes.Push(node);
            node = GetParent(node);
        }
        TreeViewItem treeViewItem = TreeView.ItemContainerGenerator
            .ContainerFromItem(node) as TreeViewItem;
        if (nodes.Count == 0)
        {
            //Top level
            treeViewItem.IsSelected = true;
            treeViewItem.BringIntoView();
            return;
        }
        Expanded(true);
        void Expanded(bool top)
        {
            if (!top)
            {
                treeViewItem = treeViewItem.ItemContainerGenerator
                    .ContainerFromItem(node) as TreeViewItem;
                if (nodes.Count == 0)
                {
                    treeViewItem.IsSelected = true;
                    treeViewItem.BringIntoView();
                    return;
                }
            }
            node = nodes.Pop();
            treeViewItem.IsExpanded = true;
            if (treeViewItem.ItemContainerGenerator.Status == GeneratorStatus.ContainersGenerated)
            {
                Expanded(true);
            }
            else
            {
                //Lazy
                treeViewItem.ItemContainerGenerator.StatusChanged += ItemContainerGenerator_StatusChanged;
            }
        }
        void ItemContainerGenerator_StatusChanged(object sender, EventArgs e)
        {
            if (treeViewItem.ItemContainerGenerator.Status == GeneratorStatus.ContainersGenerated)
            {
                treeViewItem.ItemContainerGenerator.StatusChanged -= ItemContainerGenerator_StatusChanged;
                Expanded(false);
            }
        }
    }
}

A: I think this is the simplest solution:
private void MouseDownEventProcessing(TreeNodeMouseClickEventArgs e)
{
    tvEmployeeDirectory.SelectedNode = e.Node;
}


text:
Q: Compare 2 fields in 2 tables and extract data How do i compare 2 fields in 2 tables, find a match and use it ?
example:
table1: data1(id_data1,name,address,phone,account)
table2: data2(id_data2,name2)
now in php:
if (name2.table2 has a matching name in name.table1) { give me the address,phone,account }

A: I suppose you want to use JOINs
SELECT data FROM table1 INNER JOIN table2 ON table1.id=table2.id

There are different types of JOINs, which one to use will depend on what you need.
Here's a question on visualizing the different types of JOINs.
EDIT: I believe you are looking for something like this:
SELECT table1.name, phone, other_info_here
FROM table1 AS t1 RIGHT JOIN table2 AS t2 ON t1.name=t2.name
WHERE t1.name IS NOT NULL


text:
Q: Removing object array entry (2) [{…}, {…}]
0:  {id: "201158", salary: 2}
1:  {id: "1627761", salary: 5}
length:2
__proto__: Array(0)

Above is my object from console. I'm drawing a blank on something here. On click, I'm trying to remove an element by the value of the id.
So for example, if the div clicked has an id of 201158 the id and salary would be removed from this array. I've tried delete with no luck. I've tried iterating through the array and hitting it with the below, but nothing.
var id = $(this).attr('id').toString();

removeFunction(teamOneSalaries, "id", id);

function removeFunction (myObjects,prop,valu)
{
   return myObjects.filter(function (val) {
      return val[prop] !== valu;
   });
}

Any ideas as to what I could be doing wrong here?

A: Since the function returns a new filtered array you need to assign it back to the variable. i.e.:
teamOneSalaries = removeFunction(teamOneSalaries,"id",id);

For whatever reason if you don't want to do that and want to update the array passed into the function you will have to remove items directly from that array instead of returning a new one.
e.g.
function removeFunction(myObjects, prop, valu) {
  for (let i = myObjects.length - 1; i >= 0; i--) {
    if (myObjects[i][prop] === valu)
      myObjects.splice(i, 1);
  }
}

A:

var myArray = [{id: "201158", salary: 2},{id: "1627761", salary: 5}];

myArray = myArray.filter(function( obj ) {
    return obj.id !== '1627761';
});

console.log(myArray);

it's working fine with this code
var myArray = [{id: "201158", salary: 2},{id: "1627761", salary: 5}];

myArray = myArray.filter(function( obj ) {
   return obj.id !== '1627761';
});

console.log(myArray);


text:
Q: How to uninstall python package in win10 I want to uninstall one package named fp_growth
so I use this operation in command:
python -m pip uninstall fp_growth

I also use:
python -m pip uninstall fp_growth pip3

but it shows same errors here.
how to solve it?

ERROR: Cannot uninstall 'fp-growth'. It is a distutils installed
  project and thus we cannot accurately determine which files belong to
  it which would lead to only a partial uninstall.

A: Try using this
python -m pip uninstall fp_growth

If you are using Python3 then replace pip by pip3

A: Have you tried python -m pip uninstall fp_growth to uninstall using pip?
The pip command, when used with python -m (or python3 -m) doesn't require a version modifier like it does when used standalone as pip uninstall fp_growth or pip3 uninstall fp_growth.

A: Go to C:\Users\ (Current User Name)\AppData\Local\Programs.
Delete Python Folder.
Go to Control Panel >> Uninstall a Program.
Right Click on Python and then Change/Modify.
Click on Repair Python. Note: This will Fail but be Patient.
Now Again go to step 3.
Now, after step 3, uninstall Python.


text:
Q: How to update local data from rxdb to server database postgrasql through graphql in react we are trying rxdb as local database and postgresql as a server database and through graphql end point we are able to push and pull data from local to server and vice-versa but how to update and delete data so that it can replicate in both databases .

A: We tried with the graphql schema exactly same in rxdb. We have written pull and push requests using graphql end point, and we created rxdb documents name in database as on same as in the back-end database table for which we are writing push pull queries.

*

*Create graphql endpoint with database and back-end.

*Create database collection document in rxdb with the same name as in server/back-end database.

*Take queries from the graphql endpoint and create the same schema in rxdb data document collection.

*Write push and pull queries using graphql end point queries syncing with rxdb document data collection.

Read document for the exact code.


text:
Q: Setup USB File Transfer - Android on Galaxy S7 to Windows 7/8/10 So, I want to transfer files from my Galaxy S7 Edge Android to Windows 10.
The instructions are to connect the USB cable and wait for a dropdown notification that says, 'USB CHARGING OPTIONS' but fails to appear / does not show notification / just charges without notifying me.
I want to transfer pictures and transfer movies from my phone to my PC. Without that dropdown, it fails to show on windows box.

A: ((   TLDR; developer options.  ))
Details:  Unplug your phone from the USB cable. IMPORTANT.
Pull down top option bar, then gear icon for settings. Scroll to bottom to see 'Developer Options'. Scroll down thru that to "USB Configuration", press that and hold it, choose "MTP (Media Transfer Protocol)"
OPTIONALLY, doublecheck by repeating path and seeing that it's set correctly.
RESTART YOUR PHONE. Yes, necessary with developer options.
When phone starts, unlock. Plug in USB cable. YOU WILL NOW SEE DROPDOWN NOTIFICATION. Click on the USB charging option and set to media transfer.
you should hear windows chirp to say you've connected a new device.
Bingo! you're ready.
NOTES: don't transfer off more than your pictures and videos. The other non-picture and non-video files are important to Android, deleting them could harm your system.


text:
Q: LibGdx recording and playback sound I have an application which records for 10 seconds and playback the sound.but for some reason when I run it the application doesn't playback, only record and flip the screen when it hears sound at a certain volume (real phone).
I'm really out of ideas the code seems to be good, help will be appreciated.
package com.mygdx.game;

import com.badlogic.gdx.ApplicationAdapter;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.audio.AudioDevice;
import com.badlogic.gdx.audio.AudioRecorder;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;

 public class MyGdxGame extends ApplicationAdapter{

@Override
public void create () {
    AudioDevice playbackDevice = Gdx.audio.newAudioDevice(44100, true);
    AudioRecorder recordingDevice = Gdx.audio.newAudioRecorder(44100, true);
    short[] samples = new short[44100 * 10]; // 10 seconds mono audio
    recordingDevice.read(samples, 0, samples.length);
    playbackDevice.writeSamples(samples, 0, samples.length);
    recordingDevice.dispose();
    playbackDevice.dispose();

}

@Override
public void render () {

}

@Override
public void dispose () {
}
}

It's the only class in the program.

A: Don't use game thread for recording, create another thread and start recording in that new thread. I've added small example below that working fine in Android.
public class RecordingTest extends ApplicationAdapter{

   Stage stage;

   @Override
   public void create() {

      final AudioDevice playbackDevice = Gdx.audio.newAudioDevice(44100, true);
      final AudioRecorder recordingDevice = Gdx.audio.newAudioRecorder(44100, true);

      stage=new Stage();
      final Label labelStatus=new Label("NOTHING",new Label.LabelStyle(new BitmapFont(), Color.BLUE));

      final short[] samples = new short[44100 * 10]; // 10 seconds mono audio

      new Thread(new Runnable() {
          @Override
          public void run() {

            labelStatus.setText("Recording Started");
            recordingDevice.read(samples, 0, samples.length);
            recordingDevice.dispose();
            labelStatus.setText("Recording Ended");
            labelStatus.setText("Recorded sample start Playing");
            playbackDevice.writeSamples(samples, 0, samples.length);
            labelStatus.setText("Playing Ended");
            playbackDevice.dispose();

        }
    }).start();

    Table table=new Table();
    table.setFillParent(true);
    table.add(labelStatus);
    stage.addActor(table);
  }

  @Override
  public void render() {

    Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
    Gdx.gl.glClearColor(1,1,1,1);

    stage.draw();
    stage.act();
  }

  @Override
  public void dispose() {
      stage.dispose();
  }
}


text:
Q: Javascript prompt to display on PHP echo I asked this question before, and I'm trying to run it but I'm having a problem displaying the input from javascript prompt to php, I'm getting "UNDEFINED INDEX" on the PHP part. I think I've almost done everything that I saw on the internet, but still no luck. Here's my javascript and ajax (script src="jquery.js" is included):
<script type="text/javascript">
var name = prompt('Please enter your name');
$.ajax({
    url: 'index.php',
    type: 'POST',
    dataType: 'text',
    data: name,
    success: function(data){
      console.log(data);
    }
});
</script>

Everytime I try to alert "data", it just displays a bunch of HTML codes I have for this file. Here's my php file..
<?php
$response = $_POST['data'];
echo "Hello ".$response;
?>

I've tried enclosing my php file inside a form with a post action, but still the same error.
Thanks in advance!

A: <script type="text/javascript">

var name = prompt('Please enter your name');

$.ajax({
    url: 'index.php',
    type: 'POST',
    dataType: 'text',
    data: {name : name},
    success: function(data){
      console.log(data);
    }
});

<?php

if ($_SERVER['REQUEST_METHOD'] == 'POST') {

    // get post data name from ajax

    $response = $_POST['name'];

    echo "Hello ".$response;

    // stop executing other codes to test it
    die();
}

?>

A: change your data option data: name, to  data: { "data":name},
<script type="text/javascript">
    var name = prompt('Please enter your name');
    $.ajax({
        url: 'test5.php',
        type: 'POST',
        dataType: 'text',
        data: { "data":name},
        success: function(data){
          console.log(data);
        }
    });
    </script>

A: Try this will work for you,
You have to use name value pairs to pass data
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script type="text/javascript">
var name = prompt('Please enter your name');
$.ajax({
    url: 'test.php',
    type: 'POST',
    dataType: 'text',
    data: 'name='+name,
    success: function(data){
      console.log(data);
    }
});
</script>

test.php
<?php

echo $_POST['name'];

A: replace data: name with data: JSON.stringify({"name": name}) and use contentType: "application/json" instead of dataType:'text'
var name = prompt('Please enter your name');
$.ajax({
    url: 'index.php',
    type: 'POST',
    contentType: "application/json",
    data: JSON.stringify({"name": name}),
    success: function(data){
      console.log(data);
    }
});
</script>

and in your php script query for 'name', not data
<?php
$response = $_POST["name"];
echo "Hello ".$response;
?>

Edit: to solve the empty array problem
 <?php
    $temp = file_get_contents("php://input");
    $_POST = json_decode($temp, true);
    $response = $_POST["name"];
    echo "Hello ".$response;
    ?>

Another Edit: changing the contentType to not include json
The script:
var name = prompt('Please enter your name');
    $.ajax({
        url: 'index.php',
        type: 'POST',
        contentType: "application/x-www-form-urlencoded",
        data: $.param({"name": name}),
        success: function(data){
          console.log(data);
        }
    });

    </script>

In the server:
<?php
    $response = $_POST["name"];
    echo "Hello ".$response;
    ?>


text:
Q: How do I write the £ (GBP) sign in a CSV file from Ruby and read it back correctly in Excel? When I write a CSV file using Ruby containing the £ sign and I open it using Excel I see this symbol instead ¬£.
My understanding is that Ruby uses UTF-8, but Excel interprets this file using a different encoding (ASCII).
I tried to write a US-ASCII encoded CSV file and guessed the £ encoding in ASCII like this:
csv = CSV.open(filename, 'w:US-ASCII')
csv << "\xA3"
csv.close

but it fails with invalid byte sequence in UTF-8 somewhere deep into the CSV library.
What am I doing wrong?
Thank you

A: For sure, Excel is not bound to use ASCII. For instance, I can easily input japanese characters into an Excel cell, and these are certainly not representable by ASCII.
While Ruby, by default, uses Unicode in its internal representation, every String object incorporates its own encoding, so you could in theory mix strings with different encodings, if you want to. In your case, you want to force a certain encoding when writing a file. This can be done either by using the w: output option, as you did, or by using external_encoding: Encoding::US-ASCII. See here for the names of the constants in Encoding.
I don't think US-ASCII is a good choice for the encoding, simply because there is no pound symbol in the ASCII chart. I would have expected that you get a warning message on stderr, when trying to write a pound symbol. If you need an 8-bit-encoding, ISO-8859-1 should do the job, but my recommendation would be to write UTF-8 and tell Excel to use this encoding when reading the CSV file. The possibility to import UTF exists at least since Excel 2007.


text:
Q: Python: Nested List is not replacing values correctly I have a nested list containing nothing but 0's, defined by a size of 5 by 5, and I want to be able to set specific values int he nested list to 1 using direct indexing. This is the solution I currently have:
    Grid = [[0] * 5] * 5

    ObX = 2
    print(ObX)

    ObY = 3
    print(ObY)

    Grid[ObY][ObX] = 1
    print(Grid)

Expected output:
2
3
[[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 1, 0, 0], [0, 0, 0, 0, 0]]
Actual Output:
2
3
[[0, 0, 1, 0, 0], [0, 0, 1, 0, 0], [0, 0, 1, 0, 0], [0, 0, 1, 0, 0], [0, 0, 1, 0, 0]]
As far as I can tell, it's ignoring the "ObY" index and just deciding that it wants to replace every value in each list at index "ObX". What am I doing wrong?

A: The list of lists you created contains the same list 5 times, changing it once changes all of its copies
In [1]: Grid = [[0] * 5] * 5

In [2]: [id(x) for x in Grid]
Out[2]:
[140392398718848,
 140392398718848,
 140392398718848,
 140392398718848,
 140392398718848]

Use this to create 5 different lists
In [5]: Grid =[[0]*5 for _ in range(5)]

In [6]: [id(x) for x in Grid]
Out[6]:
[140392397938112,
 140392396267776,
 140392397478656,
 140392398276224,
 140392398427200]


text:
Q: Firebase Storage - StorageReference.getFile() crashes when device is offline When I try to download file from Firebase Storage by using method StorageReference.getFile(File) it crashes when device is offline and timeout is reached. Logcat shows NPE in DynamicModulesC:
java.lang.NullPointerException: null reference
at asn.a(:com.google.android.gms.DynamiteModulesC:27)

The same code works properly and file is downloaded when internet connection is available. I've tested it on devices and emulators with Android 4.1 and 6.0. Firebase SDK version 9.6.1.
Is this a bug in firebase SDK? Did I miss something?
Code simple:
FirebaseStorage firebaseStorage = FirebaseStorage.getInstance();
//firebaseStorage.setMaxDownloadRetryTimeMillis(15 * 1000);
StorageReference remoteDir= firebaseStorage.getReference().child("dir-with-files");
File destinationFile= new File("file-in-app-internal-storage");
StorageReference fileRef = remoteDir.child("file-from-firebase");
fileRef.getFile(destinationFile);

Full crash log:
10-02 10:49:57.577 9429-9464/com.github.lecho.mobilization W/System: ClassLoader referenced unknown path: /system/priv-app/PrebuiltGmsCore/lib/x86_64
10-02 10:49:57.610 9429-9464/com.github.lecho.mobilization I/DynamiteModule: Considering local module com.google.android.gms.firebasestorage:0 and remote module com.google.android.gms.firebasestorage:1
10-02 10:49:57.610 9429-9464/com.github.lecho.mobilization I/DynamiteModule: Selected remote version of com.google.android.gms.firebasestorage, version >= 1
10-02 10:49:57.628 9429-9464/com.github.lecho.mobilization W/System: ClassLoader referenced unknown path: /data/user/0/com.google.android.gms/app_chimera/m/00000002/n/x86_64

10-02 10:50:11.599 9429-9462/com.github.lecho.mobilization W/ExponenentialBackoff: network unavailable, sleeping.
10-02 10:50:11.599 9429-9462/com.github.lecho.mobilization E/StorageUtil: error getting token java.util.concurrent.ExecutionException: com.google.firebase.FirebaseApiNotAvailableException: firebase-auth is not linked, please fall back to unauthenticated mode.
10-02 10:50:12.234 9429-9464/com.github.lecho.mobilization W/ExponenentialBackoff: network unavailable, sleeping.
10-02 10:50:12.234 9429-9464/com.github.lecho.mobilization E/StorageUtil: error getting token java.util.concurrent.ExecutionException: com.google.firebase.FirebaseApiNotAvailableException: firebase-auth is not linked, please fall back to unauthenticated mode.

                                                                      --------- beginning of crash
10-02 10:50:12.236 9429-9464/com.github.lecho.mobilization E/AndroidRuntime: FATAL EXCEPTION: FirebaseStorage-Download-3
                                                                         Process: com.github.lecho.mobilization, PID: 9429
                                                                         java.lang.NullPointerException: null reference
                                                                             at asn.a(:com.google.android.gms.DynamiteModulesC:27)
                                                                             at bul.d(:com.google.android.gms.DynamiteModulesC:261)
                                                                             at buf.onTransact(:com.google.android.gms.DynamiteModulesC:76)
                                                                             at android.os.Binder.transact(Binder.java:387)
                                                                             at com.google.android.gms.internal.zzans$zza$zza.aE(Unknown Source)
                                                                             at com.google.android.gms.internal.zzanv.aE(Unknown Source)
                                                                             at com.google.firebase.storage.FileDownloadTask.run(Unknown Source)
                                                                             at com.google.firebase.storage.StorageTask$5.run(Unknown Source)
                                                                             at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113)
                                                                             at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588)
                                                                             at java.lang.Thread.run(Thread.java:818)
10-02 10:50:12.237 1540-1997/system_process W/ActivityManager:   Force finishing activity com.github.lecho.mobilization/.ui.MainActivity

                                                           [ 10-02     10:50:12.246  1540: 1997 D/         ]
                                                           HostConnection::get() New Host Connection established 0x7f39f896fc00, tid 1997

A: It turns out to be a bug in Google Play services. Firebase team has already fixed it. The fix is available in version 9.8.77 of Google Play services.
Now StorageReference.getFile(File) will not crash the app when device is offline. Instead you will receive following response:
E/StorageException: StorageException has occurred.
The operation retry limit has been exceeded.
Code: -13030 HttpResult: -2

A: Try this:
try{
    fileRef.getFile(destinationFile).addOnSuccessListener(new OnSuccessListener<FileDownloadTask.TaskSnapshot>() {
        @Override
        public void onSuccess(FileDownloadTask.TaskSnapshot taskSnapshot) {
            // Local temp file has been created
        }
    }).addOnFailureListener(new OnFailureListener() {
        @Override
        public void onFailure(@NonNull Exception exception) {
            // Handle any errors
        }
    });
} catch (Exception e){
// Error
}

Additionally, we can do below things:
1. add try catch block to handle any exception while downloading file is called.
2. Save storage ref as a reference in onSaveInstanceState.
3. Later, we can call onRestoreInstanceState.
StorageReference mStorageRef;  //mStorageRef was previously used to transfer data.

@Override
protected void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);

    // If there's a download in progress, save the reference so you can query it later
    if (mStorageRef != null) {
        outState.putString("reference", mStorageRef.toString());
    }
}

@Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
    super.onRestoreInstanceState(savedInstanceState);

    // If there was a download in progress, get its reference and create a new StorageReference
    final String stringRef = savedInstanceState.getString("reference");
    if (stringRef == null) {
        return;
    }
    mStorageRef = FirebaseStorage.getInstance().getReferenceFromUrl(stringRef);

    // Find all DownloadTasks under this StorageReference (in this example, there should be one)
    List tasks = mStorageRef.getActiveDownloadTasks();
    if (tasks.size() > 0) {
        // Get the task monitoring the download
        DownloadTask task = tasks.get(0);

        // Add new listeners to the task using an Activity scope
        task.addOnSuccessListener(this, new OnSuccessListener() {
          @Override
          public void onSuccess(DownloadTask.TaskSnapshot state) {
             handleSuccess(state); //call a user defined function to handle the event.
          }
        });
    }
}

A: You need to download the file once you are online using the getFile() method and save the file locally. Then use the locally saved file once you go offline. You cannot download the file using getFile() method when you are offline. Please read the documentation:
https://firebase.google.com/docs/storage/android/download-files


text:
Q: How to find representation matrix for linear maps? I know how to find which maps are linear, but how do I get representation matrix for linear maps? I know $f(x) := Ax$ . Any explanation would be highly appreciated. I'm really confused. Please help me!
For example, look at this problem.

A: Suppose you have a linear map. In general,
$$
\begin{pmatrix}x\\y\end{pmatrix}\mapsto \begin{pmatrix}ax + by\\cx + dy\end{pmatrix}.
$$
Then you know that that
$$
\begin{pmatrix}e & f \\ g & h\end{pmatrix}\begin{pmatrix}x\\y\end{pmatrix}= \begin{pmatrix}ex + fy\\gx + hy\end{pmatrix}=\begin{pmatrix}ax + by\\cx + dy\end{pmatrix}.
$$
In particular, you have that $e = a$, $f = b$, $g = c$, and $h = d$, thus your matrix is:
$$
A = \begin{pmatrix}a & b \\ c & d\end{pmatrix}.
$$
Once you have the matrix, the map is a rotation if the determinant of $A$ is $1$, and it is orientation preserving if the the determinant of $A$ is positive.
In the first instance of your example this yields:
$$
A_1 = \begin{pmatrix}0 & -2 \\ 1 & 0\end{pmatrix}.
$$
To verify just multiply:
$$
\begin{pmatrix}0 & -2 \\ 1 & 0\end{pmatrix}\begin{pmatrix}x \\ y\end{pmatrix} = \begin{pmatrix}0\cdot x +(-2)\cdot y \\ 1\cdot x + 0\cdot y\end{pmatrix} = \begin{pmatrix}-2y \\ x\end{pmatrix}
$$
as desired.


text:
Q: Decomposing a cycle into transpositions I am trying to go through some lecture notes found here, and am struggling with an assertion on page 21. It is meant to be a proof that any cycle $(a_1,..,a_k)$ can be written as a product of transpositions.
We have the identity
$(1,k)(1,k-1)...(1,3)(1,2) = (1,2,...,k)$.
Now consider a permutation $\phi$ taking
$1 \rightarrow a_1, ..., k\rightarrow a_k$. Using the above identity, we can write
$(a_1,..,a_k) = \phi \circ(1,k)...(1,2)\circ \phi^{-1}$.
The claim is that this is our desired decomposition. We have not shown that $\phi$ itself can be written as transpositions, so how do I see that the right-hand-side of the above equation is indeed just some transpositions?
EDIT: As pointed out in the comments, we just have that
$$
\begin{split}
(a_1,..,a_k) &= \phi \circ(1,k)...(1,2)\circ \phi^{-1} \\
&= \phi \circ(1,k)\circ\phi^{-1} \circ \phi\circ(1,k-1)...(1,2)\circ \phi^{-1} \\
&= (a_1,a_k)(a_1,a_{k-1})...(a_1,a_2),
\end{split}
$$
giving the result.


text:
Q: Avatica Calcite JDBC Driver issue I am getting the below error while trying to getConnection through Java Web App. Any one faced this issue ?
com.fasterxml.jackson.databind.JsonMappingException: Class
org.apache.calcite.avatica.remote.Service$ResultSetResponse not subtype of
[simple type, class
org.apache.calcite.avatica.remote.Service$RpcMetadataResponse]
at [Source: {"response":"openConnection","rpcMetadata":{"

Code:
Class.forName("org.apache.calcite.jdbc.Driver");
DriverManager.getConnection("jdbc:avatica:remote:url=XXXX ");

A: When you're using JDBC driver from Java web application, you're not supposed to give DriverManager a link to Avatica, but to specific database.
DriverManager.getConnection("jdbc:avatica:remote:url=XXXX ");

Instead, just use:
DriverManager.getConnection("jdbc:calcite:", info);

and it will work.


text:
Q: IntelliJ / Gradle - composite build project - how to import from different module? I'm new to Java and am currently trying to build a cucumber / selenium project in IntelliJ that contains two modules: A library project containing page definitions, and a test project that contains the cucumber features and step definitions that talk to those page definitions. The idea is that the page definitions are a shared resource, and the tests are specific to different projects / groups. Both modules are at the same level underneath the parent project. The build is using Gradle, and the settings.gradle file for the parent looks as follows:
rootProject.name = 'composite-builds'
includeBuild 'libraryproject'
includeBuild 'testproject'

Using Gradle includeBuild on the parent project works fine and the whole project imports. However I am having no luck using the library project in my import statements in the test project. It consistently returns me these kinds of error: java: package libraryproject.pageFactory.examplePages does not exist and is clearly not seeing the library module.
What do I need to do / add in order for the test project to recognise the library project? I did try to also add the includeBuild statement in the settings.gradle for the test project but this made no difference.
The library can be found here
Update: the real reason that I cannot see the modules from the library project is that they were held in the test folder, not main.

A: Go to your build.gradle file
Instead of includeBuild use dependencies{compile{project(':libraryproject')}}
Inside the Root Project of libraryproject which is in your case the composite-builds. Change includeBuild to include in the settings.gradle
rootProject.name = 'composite-builds'
include ':libraryproject'
include ':testproject'

If it is in the same root:
dependencies {
    compile(
        project(':libraryproject')
    )
}

Subfolder:
dependencies {
    compile(
        project(':myFolder1:myFolder2:libraryproject')
    )
}


text:
Q: c++ implicit conversion on user-defined operator for template classes I have a struct template A<x> and a + operator with int.
#include <iostream>
template<int x>
struct A{
    int a;
};
template<int x>
int operator+(A<x> a, int b){
    return a.a+b;
}

I created a struct template B<x>, which is convertible to A<x>.
template<int x>
struct B{
    int b=3;
    operator A<x>(){
        return {b+10};
    }
};

Now I want B<x> to be converted to A<x> when calling B<x> + int.
int main(){
    std::cout<<(A<12>{9}+10)<<std::endl;//OK
    std::cout<<(B<12>{9}+10)<<std::endl;//Error
    return 0;
}

I read Implicit conversion when overloading operators for template classes and wrote
template<int x>
struct B{
    int b=3;
    operator A<x>(){
        return {b+10};
    }
    friend int operator+(A<x> a, int b);
};

, but it didn't work because the declared friend int operator+(A<x> a, int b) does not match template<int x> int operator+(A<x> a, int b).
I read C++ - How to declare a function template friend for a class template and made friend declaration template, but it didn't work because the template parameter couldn't be deduced.
Of course I could write operator+ for both A and B, but I have dozens of operators and I don't want to do it.
What is the correct way to do this?

A: Looking at the two ways to make a non-member operator+ for A, we can either make it a function template:
template <int x>
int operator+(A<x>, int);

which won't match B<x> because we're just doing template deduction, which doesn't allow for conversions.
Or, we can make it a friend non-template:
template <int x>
struct A {
    friend int operator+(A a, int );
};

which also won't match B<x> because name lookup won't consider that function. Unless, that is, we tell it to:
template <int x>
struct B {
    friend int operator+(A<x>, int ); // NB: not a template
};

Now, our original non-template operator+ will be considered, the conversion will be performed as desired, and your code prints 29.

A: You maybe have seen this already, but at least it is still possible to do an explicit cast, and it might be useful:
int main(){
    std::cout<<(A<12>{9}+10)<<std::endl;                     // prints 19
    std::cout<<(static_cast<A<12>>(B<12>{9})+10)<<std::endl; // prints 29
    return 0;
}

A: I tried to edit Barrys answer with the following (runnable) code, that produces the correct output, but it was rejected there.
I'll add it here in case anyone else is curious.
#include <iostream>

template <int x>
struct A {
    int a;
    friend int operator+(A a, int b) { return a.a + b; }
};

template <int x>
struct B {
    int b;
    operator A<x>() { return {b+10}; }
    friend int operator+(A<x>, int );
};

int main() {
    std::cout << (A<12>{9} + 10) << std::endl;
    std::cout << (B<12>{9} + 10) << std::endl;
}

Which prints
19
29

A: I hope it may help you.
I have templated friend operator+
Derived from A<x> and it compiled, but after calling friend operator+ variable a was uninit so i got immediate values. You have to set a somehow and this seems to work.
#include <iostream>

template<int x>
struct A
{
    int a{x};
};

template<int x>
int operator+(A<x> a, int b)
{
    return a.a+b;
}

template<int x>
struct B : A<x>
{
    int b;

template<int U>
    friend int operator+(A<U> a, int b);
};

int main(void)
{
    std::cout<< (A<20>{}+10)<<std::endl; // prints 30
    std::cout<< (B<10>{}+10)<<std::endl; // prints 20
    return 0;
}


text:
Q: Numpy swap the values of nested columns Given the following data structure is there some way I can swap the first and last column such that each row is [3, 2, 1] (I don't wish to sort them) without looping through each row?
[[[1 2 3]
  [1 2 3]
  [1 2 3]
  ...
  [1 2 3]
  [1 2 3]
  [1 2 3]]

 [[1 2 3]
  [1 2 3]
  [1 2 3]
  ...
  [1 2 3]
  [1 2 3]
  [1 2 3]]]


text:
Q: Open Subsets of open sets How does one go about proving/disproving that given $(X,d)$ a metric space that a subset $S$ is open.
Given the following definitions:
A set $X$ is open $\iff \forall x \in X, x\in int(X)$ i.e. x is interior point
where an interior point is defined as:
$x$ is a interior point of $A \subset X$ if $\exists r>0, B(z,r)\subset A \land x \in B(z,r) $
I apologise if I am being to vague and/or general

A: Usually, you can prove a set is open by definition.
For example, in $\mathbb R^2$ with standard metric, the square $S=\{(x,y)| |x|<1, |y|<1\}$ is open. Why? Take any $(x,y)\in S$. Then $|x|<1$, therefore there exists some $\delta_x$ such that $(x-\delta_x, x+\delta_x)\subseteq(-1,1)$. In the same way, there exists some $\delta_y$ such that $(y-\delta_y, y+\delta_y)\subseteq(-1,1)$.
It is then easy to show that for $\delta=\min\{\delta_x,\delta_y\}$, the ball $B((x,y),\delta)$ is a subset of $S$.


text:
Q: Compiler error Parma Polyhedra Library: undefined reference to `Parma_Polyhedra_Library::Init::Init()' I downloaded last version gmp and ppl from their official websites and installed well. AFAIS, all of library files are in /usr/local/lib. But when I try to compile and run C++ file by including ppl.hh header, I get the error,
CMakeFiles/CLionProjects.dir/untitled/main.cpp.o:
In function `__static_initialization_and_destruction_0(int, int)':
/usr/local/include/ppl.hh:19804: undefined reference to `Parma_Polyhedra_Library::Init::Init()'
/usr/local/include/ppl.hh:19804: undefined reference to `Parma_Polyhedra_Library::Init::~Init()'
collect2: error: ld returned 1 exit status

Contents of /usr/local/lib,
soner@ubuntu:/usr/local/lib$ ls
libgmp.a          libgmpxx.la        libppl_c.la        libppl.so.14
libgmp.la         libgmpxx.so        libppl_c.so        libppl.so.14.0.0
libgmp.so         libgmpxx.so.4      libppl_c.so.4      python2.7
libgmp.so.10      libgmpxx.so.4.5.2  libppl_c.so.4.0.0  python3.5
libgmp.so.10.3.2  libppl.a           libppl.la
libgmpxx.a        libppl_c.a         libppl.so

Simple C++ file is,
#include <iostream>
#include "ppl.hh"

int main() {
    return 0;
}

Even if I tried to run it with set (CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++14 ")
, still appearing same error. Source
g++ on terminal on Mac OSX
Soners-MacBook-Pro:Documents soner$ g++ -c main.cpp
Soners-MacBook-Pro:Documents soner$ g++ -o test main.cpp
Undefined symbols for architecture x86_64:
  "Parma_Polyhedra_Library::Init::Init()", referenced from:
      ___cxx_global_var_init.6 in main-d99d55.o
  "Parma_Polyhedra_Library::Init::~Init()", referenced from:
      ___cxx_global_var_init.6 in main-d99d55.o
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation

g++ on Ubuntu
soner@ubuntu:~/Desktop$ cat main.cpp
#include <iostream>
#include "ppl.hh"

int main() {
    return 0;
}
soner@ubuntu:~/Desktop$ g++ -c main.cpp
soner@ubuntu:~/Desktop$ g++ -o test main.cpp
/tmp/ccQTNpxj.o: In function `__static_initialization_and_destruction_0(int, int)':
main.cpp:(.text+0xa9): undefined reference to `Parma_Polyhedra_Library::Init::Init()'
main.cpp:(.text+0xb8): undefined reference to `Parma_Polyhedra_Library::Init::~Init()'
collect2: error: ld returned 1 exit status


text:
Q: php variable $_SERVER['SERVER_ADDR'] is blank when using crontab I have a small script which gets basic information like the server IP-, and the MAC-address of the server the script is running on, I am then posting the results to a mysql database, this works fine and the code is shown below. However when I use a cronjob to execute the script everything but the IP address is being stored, for some reason the $_SERVER['SERVER_ADDR'] is blank when being executed as a cronjob.
This script runs every min, and is run on multi Raspberry PI's so I can tell which is connected to share job requests.
$mac_address    = getMacLinux();
$server_ip      = $config['server_ip'];
$client_ip      = $_SERVER['SERVER_ADDR'];
$client_name    = $config['client_name'];

$ch = curl_init();
$url = "{$server_ip}/checkin0.php";
echo "url = {$url}"."<br>";

curl_setopt($ch, CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, "client_ip={$client_ip}&client_name={$client_name}&client_mac={$mac_address}");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$output = curl_exec ($ch); // Execute

curl_close ($ch); // Close cURL handle

var_dump($output); // Show output

A: i found the following
function getServerAddress() {
    if(isset($_SERVER["SERVER_ADDR"]))
    return $_SERVER["SERVER_ADDR"];
    else {
    // Running CLI
    if(stristr(PHP_OS, 'WIN')) {
        //  Rather hacky way to handle windows servers
        exec('ipconfig /all', $catch);
        foreach($catch as $line) {
        if(eregi('IP Address', $line)) {
            // Have seen exec return "multi-line" content, so another hack.
            if(count($lineCount = split(':', $line)) == 1) {
            list($t, $ip) = split(':', $line);
                $ip = trim($ip);
            } else {
                $parts = explode('IP Address', $line);
                $parts = explode('Subnet Mask', $parts[1]);
                $parts = explode(': ', $parts[0]);
                $ip = trim($parts[1]);
            }
            if(ip2long($ip > 0)) {
            echo 'IP is '.$ip."\n";
            return $ip;
            } else
            ; // TODO: Handle this failure condition.
        }
        }
    } else {
        $ifconfig = shell_exec('/sbin/ifconfig eth0');
        preg_match('/addr:([\d\.]+)/', $ifconfig, $match);
        return $match[1];
    }

A: Look in the manual

$_SERVER is an array containing information such as headers, paths, and script locations. The entries in this array are created by the web server

PS. Also you can use your script as CGI script (and $_SERVER['SERVER_ADDRESS'] will be correct). You may try fetch, wget, curl... and call script from crontab i.e. (server-IP is 192.168.0.1):
1 * * * * fetch http://192.168.0.1/my_script.php


text:
Q: Format a date retrieved from xml file using jstl i have an XML file that contains

<date>2014-02-01T12:00:00</date>

then i retrive the date with JSTL XML parser
<c:import url="dtdict.xml" var="dtdict_dem" charEncoding="UTF-8"/>
<x:parse doc="${dtdict_dem}" var="dossier"/>
       <c:set scope="request" var="date">
<x:out select="$dossier/DT/date" />
</c:set>

then i use formatDate to format the date
<fmt:formatDate var="fmt_date" value="${date}"pattern="dd/MM/yyyy" />
        Date  : ${fmt_date}

but when i run i receive this error
javax.el.ELException: Cannot convert 2014-02-01T12:00:00 of type class java.lang.String to class java.util.Date

help please

A: You have to parse the date String first.
<fmt:parseDate value="${date}" pattern="yyyy-MM-dd'T'HH:mm:ss" var="myDate"/>
<fmt:formatDate var="fmt_date" value="${myDate}" pattern="yyyy-MM-dd" />
    Date  : ${fmt_date}


text:
Q: Emacs find-and-replace regex in multiple files (find-name-dired + Q), doesn't save my buffers? I can't figure out what's going on here.  I've done a search and replace across a whole directory, using:

*

*M-x find-name-dired RET

*Select root of my project

*Enter *.rb as the filenames to match

*Press "t" to select all files found

*Press "Q" (shift Q) to start the search/replace

*Enter "transaction" as the query, then enter "invoice" as the replacement

Now I've cycled through all the buffers it opens for me, selectively press "y" or "n" depending on the replacement.  When it finished, it just left me in the last buffer I had changed.
So, hitting C-z to background the emacs window and check what has changed, shows that none of the files are saved, which I expected.
So then I did M-x save-some-buffers RET, which tells me there are no files to be saved.  So I start rotating through my buffers with C-x b and verify that, yes indeed, the buffers do have changes compared to what is on disk.
So I repeat the process, this time with a completely fresh emacs process (no open buffers at all when I start the process).  At the end I have a bunch of buffers open, with changes (that I can see), yet again, emacs says there's nothing to save.
So I tried using C-x C-b to bring up IBuffer.  Marked all the files I wanted to save, then hit "S" to save them, at which point it shows "Operation finished; saved 27 buffers".  Awesome... except git is still telling me that emacs has in fact saved nothing.
What am I doing wrong?  I want to replace "transaction" with "invoice" across my entire project, though I do need to do it interactively, since there are some places where that replacement should not be done.
Emacs 23.

A: I've reproed the behaviour you describe.  Sure smells like a bug to me.  Please report it at bug-gnu-emacs@gnu.org.
The Emacs contributors are very responsive.
P.S.  Love the details you put into your question.


text:
Q: How to save query in multidimesional array? I have this script executing as a cron job everyday to update days remaining to pay invoices. I first query every row of my table and attempt to store the data in a multidimensional array but this seems to be storing everything I query in the first element of my array.
Here's my script:
<?php
  include '../inc/dbinfo.inc';

  ini_set("log_errors", 1);
  ini_set("error_log", "/tmp/php-error.log");
  error_log( "#################################################     UpdateVendorInvoiceDays.php    #################################################" );

  $three = 3;

  $fetchAllInvoices = "SELECT VENDORINVOICEID, VdrInvoiceReceived, PaymentDue, COUNT(*), DATEDIFF(PaymentDue, NOW()) FROM tblVendorInvoices WHERE VdrInvoiceStatusID != ?";
  $getInvoices = $conn->prepare($fetchAllInvoices);
  $getInvoices->bind_param("i", $three);
  $getInvoices->execute();
  $result = $getInvoices->get_result();

  $rows = array();
  $j = 0;

  while($row = $result->fetch_assoc())
  {
    $rows[$j][] = $row;
    $j++;
  }

  echo json_encode($rows[0][0]);    //Only outputs one row

  //UPDATE DAYS REMAINING IN EACH ENTRY THAT ISNT PAID
  $updateDaysRemaining = "UPDATE tblVendorInvoices SET DaysRemaining = ? WHERE VENDORINVOICEID = ? AND VdrInvoiceStatusID ! = ?";
  $setDays = $conn->prepare($updateDaysRemaining);

  $k = 0; //incrementor
  $numberOfEntries = $rows['COUNT(*)'];

  for($k;$k<$numberOfEntries;$k++){
     $setDays->bind_param("iii", $rows[$k]["DATEDIFF(PaymentDue, NOW())"],
     $rows[$k]['VENDORINVOICEID'], $three);
    if($setDays->execute()){
      error_log('Cron success');
    }else{
      error_log('Cron fail');
    }
  }
?>

Currently the output from my first query is:
[[{"VENDORINVOICEID":88,"VdrInvoiceReceived":"2018-08-21","PaymentDue":"2018-07-27","COUNT(*)":2,"DATEDIFF(PaymentDue, NOW())":-25}]]
and my error log only gives me a notice for $rows['COUNT(*)'] being undefined (which makes sense)
I've looked at other answers here but they don't seem to have the same structure as I do.
EDIT: I also have 2 rows in my database but this only puts out one. I forgot to mention this.

A: There are a couple of simplifications to get all of the rows.  Instead of...
while($row = $result->fetch_assoc())
  {
    $rows[$j][] = $row;
    $j++;
  }

  echo json_encode($rows[0][0]);

You can just return all rows using fetch_all()...
$rows = $result->fetch_all (MYSQLI_ASSOC);
echo json_encode($rows);

Then encode the whole array and not just the one element - which is what $rows[0][0] was showing you.
As for you other problem - change in your select statement to
COUNT(*) as rowCount

and then you can use this alias for the field reference...
$rows['COUNT(*)']

becomes
$rows['rowCount']


text:
Q: What is the new equivalent of DOMNodeInserted? The DOMNodeInserted event has been deprecated and all Mutation Events have been replaced with mutation observers.
But, within mutation observers there are only config options for watching mutations to the nodes attributes, content, and children.  Nothing about a mutation to it's placement in the DOM tree.
There is one "solution" I can think of which is to observe everything from document.body down searching for the one mutation which is my target node being added, but that's a pretty awful way of doing anything.
So what is the expected way to replace the deprecated DOMNodeInserted with Mutation Observers?
EDIT: found possible duplicate What is the most efficient way of detecting when an element with a particular ID is inserted in the DOM
Once Again, SO: The searchbar works better with Tags than Questions. Explaining this could reduce duplicates and save users time
Below is some code where you can see that none of the available mutation observer config options respond to the element being added to the page:

var addMe = document.createElement("div");
var config = {
  attributes: true,
  childList: true,
  characterData: true
}
var observer = new MutationObserver(function(mutations) {
  console.log(mutations);
});
observer.observe(addMe, config);

function appendAddMe() {
  document.body.appendChild(addMe);
}
div {
  height: 50px;
  width: 50px;
  background: #969;
}
<button onclick="appendAddMe()">Append addMe</button>

A: I don't really consider this to be the answer to the question, but I'd like to share it anyways because it's better than nothing.
This question has some good answers: What is the most efficient way of detecting when an element with a particular ID is inserted in the DOM
In particular, this answer: https://stackoverflow.com/a/25107064/4808079
from schettino72

iframe elements trigger load/unoad events. You can insert a dumb iframe in the element you want to watch... And trigger a 'load' event in the original element yourself.

function watch($ele){
    var $iframe = document.createElement('iframe');
    $iframe.style.display = 'none';
    $ele.appendChild($iframe);
    $iframe.addEventListener('load', function(){
      var event = new CustomEvent('load');
      $ele.dispatchEvent(event);
    });
}

I would still like to keep this question open as this is a hack and not a true answer.  DOMNodeInserted was probably not deprecated so everyone could do it this way instead.


text:
Q: How to do exact calculation when numbers are not in Safe Integer range? I found that JavaScript performs an exact calculation when numbers are in safe integer range
Number.MIN_SAFE_INTEGER = -9007199254740991 = Math.pow(2, 53) - 1
Number.MAX_SAFE_INTEGER = 9007199254740991 = -(Math.pow(2, 53) - 1)

Is it possible to do calculation beyond this range without rounding off and losing precision?

A: You may have to use something like big numbers. These numbers are represented as a string of decimal characters which are then operated by the library.
Check this out: StackOverflow link

A: According to ECMAScript 6 there is no function to handle the specified operation. Even if we write a function for the same, I think we can't hold the value of the variable, which is to be computed with precision in js.


text:
Q: API Level 11 min is 9, what can I do to fix this One of my classes has many errors because API level 11 (min is 9) is it better to fix it or change min. If so how do I fix it or how do I change min Im very new to this, also what is a good source to learn from with new-ish code
package com.ramos.science;
import android.os.Bundle;
import android.preference.PreferenceActivity;
import android.preference.PreferenceFragment;

public class Prefs extends PreferenceActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    getFragmentManager().beginTransaction().replace(android.R.id.content, new       MyPreferenceFragment()).commit();
}
public static class MyPreferenceFragment extends PreferenceFragment
{

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    addPreferencesFromResource(com.ramos.science.R.xml.prefs);
}

}
}

A: modify AndroidManifest.xml  file
add
 <uses-sdk
        android:minSdkVersion="11"
        android:targetSdkVersion="17"/>

A: It really just depends on what you want and who you are targeting. Since Fragment was introduced in API 11, if you want to use them then you should make your minimum >= 11. If you look at the DashBoard Docs you can see that the majority of devices which download apps from the Play Store are Gingerbread (API 9). If you want to reach the broadest amount of people then you may not want to use Fragments but if you want to program for the future then I would suggest using a minimum of 11.
It really kind of depends on who you are targeting. But ICS has gained a lot of ground in the last 6 months or so. My recommendation would be to program for those newer devices because their slice is only going to get bigger. Unless, of course, you know that a lot of your users will have older devices
Supporting different versions

A: Inside of class you can use Android annotations like so:
@TargetApi(11)
public void functionName() {
   ...
}

A: In additional to what codeMagic has explained. This is an add-on resources for what you need:
What API level should I target.

Besides I have difficulties when I first kick-started android, here's some really good android books for beginner:

*

*Pro Android 3 (Android developer would keep this in their bookshelf)

*Head First Android Development (It guides you by example)

*Learning Android
 (Perfect book to master your fundamentals)

To master the best android practices, learn from his code:
yuriykulikov/AlarmClock
After all, I hoped it helps :) Good luck.


text:
Q: How can I see the OP's new comments if the OP deleted his question after commenting? Quick question:
So a user asked a question which did not get any answers, so I was helping him in the comments. Then he commented further questions but deleted the question right after. I think he does not know that now I can't respond. Anyway I see the notification and part of the comment in my inbox in the upper panel however I can't see it all.
It says Page Not Found if I press on the notification. Is there anyway I can still view his added comments if the question is deleted now?

A: No, you won't be able to view the question or the OP's comments unless you have 10K reputation.
However, if you feel the person self-deleted their question after getting help and did so in an abusive way, you can flag for moderator attention to ask the moderators to undelete the question.  They might or might not grant such a request:

*

*If the question got an answer and then the OP self-deleted (e.g., before the answer could get any upvotes), that's considered abusive and moderators will typically undelete in that case.

*If the question didn't get an answer and only got comments, that's a bit different and moderators might not choose to forcibly undelete.
[ Yes, this is good motivation to either answer in an answer (if the question is clear enough to provide a full answer) or vote/flag to put it on hold as 'unclear' until the question is clarified enough to be answerable (if the question isn't clear enough to provide a full answer). ]
Since the post is deleted, you won't be able to flag it yourself.  Instead, if you want to flag it, find some other post (e.g., one of your own posts) and flag it for moderator attention with a custom message, and link to the deleted question.


text:
Q: Building open source library (liblo) for iPhone I've got an iPhone project using liblo (liblo.sourceforge.net). My project's been working fine in the simulator, but as soon as I went to build for the device, ld fails:
ld: library not found for -llo
I suspect that this is because I just ran make install when I downloaded liblo. I found a thread that suggested cross compiling by running ./configure --host=arm-apple-darwin before make install, but that doesn't seem to have fixed the problem.
[/usr/local/lib]$ file liblo.dylib
liblo.dylib: Mach-O dynamically linked shared library i386

Is there a simple solution?

A: Well here's the file, compiled for OS 3.0.
http://www.samvermette.com/files/liblo.a.zip
Just add it to your XCode project and you're ready to go!

A: I wrote a small tutorial on building cross platform iPhone libs that run both on the device and the simulator.

A: Here's an updated version of jkooker's config script, for iOS 4: http://gist.github.com/519121

A: Bringing this up again...
Xcode 12.3+ has deprecated manually-linked fat libs generated via lipo in favor of XCFrameworks. Basically, M1 macs now share the same arm64 arch as iDevices and Xcode is not able to tell which arch to use within the fat lib, so will fail to link the arm64 slice when running in the simulator. If you only run on device via Xcode on an M1 mac, it does work but it's less than ideal to not have the Simulator as an option.
As noted in my comment to the @mikewoz answer, I have updated the fat lib script and used it for many years. I attempted to use this approach and generate an XCFramework via
xcodebuild -create-xcframework -library liblo-ios.a -library liblo-sim.a -output liblo.xcframework

...however I was not able to get this to work.
In the end, I have opted for building the liblo sources myself via a manually-created liblo static lib Xcode project. This works fine and just requires setting the required defines, either via config.h generated via configure, or setting them manually on the Xcode project. So far I opted for using configure and set the following defines: -DHAVE_CONFIG_H -DAC_APPLE_UNIVERSAL_BUILD -Qunused-arguments -fno-common -DPIC. The AC_APPLE_UNIVERSAL_BUILD define is used to enable a compile-time endinaness check in config.h. That being said, I have only tested on my M1 MacBook Pro 13, so I hope this approach works on Intel machines.
If anyone needs the working liblo.xcodeproj, you can find it here: https://github.com/danomatika/PdParty/tree/master/libs/liblo
The steps used to automate the downloading and configuring of the liblo sources are in the main libs Makefile: https://github.com/danomatika/PdParty/blob/master/libs/Makefile


text:
Q: How to extract string using RE in python? this is a string:
'ObjectId("5a60a394ac73c233ba1acc55")'

I want to get "5a60a394ac73c233ba1acc55",How do I use the regex?

A: seems like a crazy question but why not
>>> myval = 'ObjectId("5a60a394ac73c233ba1acc55")'
>>> myval.split("(")[1]
'"5a60a394ac73c233ba1acc55")'
>>> myval.split("(")[1].split(")")[0]
'"5a60a394ac73c233ba1acc55"'
>>> import re

>>> re.findall('[a-zA-z0-9]', myval.split("(")[1].split(")")[0])
['5', 'a', '6', '0', 'a', '3', '9', '4', 'a', 'c', '7', '3', 'c', '2', '3', '3', 'b', 'a', '1', 'a', 'c', 'c', '5', '5']

>>> "".join(re.findall('[a-zA-z0-9]', myval.split("(")[1].split(")")[0]))
'5a60a394ac73c233ba1acc55'


text:
Q: PHP - Mysql Server Error I am having a problem with my sql query. I am creating a social networking site like facebook and  trying to make the chat. I have included the error message below.
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'to = '2' && to_viewed = '0' && to_deleted = '0' ORDER BY created DESC' at line 1
Here is my sql query
function getmessages($type=0) {
    switch($type) {
        case "0": $sql = "SELECT * FROM messages WHERE to = '".$this->userid."' && `to_viewed` = '0' && `to_deleted` = '0' ORDER BY `created` DESC"; break; // New messages
        case "1": $sql = "SELECT * FROM messages WHERE to = '".$this->userid."' && `to_viewed` = '1' && `to_deleted` = '0' ORDER BY `to_vdate` DESC"; break; // Read messages
        case "2": $sql = "SELECT * FROM messages WHERE from = '".$this->userid."' ORDER BY `created` DESC"; break; // Send messages
        case "3": $sql = "SELECT * FROM messages WHERE to = '".$this->userid."' && `to_deleted` = '1' ORDER BY `to_ddate` DESC"; break; // Deleted messages
        default: $sql = "SELECT * FROM messages WHERE to = '".$this->userid."' && `to_viewed` = '0' ORDER BY `created` DESC"; break; // New messages
    }
    $result = mysql_query($sql) or die (mysql_error());

    if(mysql_num_rows($result)) {
        $i=0;

        $this->messages = array();

        while($row = mysql_fetch_assoc($result)) {
            $this->messages[$i]['id'] = $row['id'];
            $this->messages[$i]['title'] = $row['title'];
            $this->messages[$i]['message'] = $row['message'];
            $this->messages[$i]['fromid'] = $row['from'];
            $this->messages[$i]['toid'] = $row['to'];
            $this->messages[$i]['from'] = $this->getusername($row['from']);
            $this->messages[$i]['to'] = $this->getusername($row['to']);
            $this->messages[$i]['from_viewed'] = $row['from_viewed'];
            $this->messages[$i]['to_viewed'] = $row['to_viewed'];
            $this->messages[$i]['from_deleted'] = $row['from_deleted'];
            $this->messages[$i]['to_deleted'] = $row['to_deleted'];
            $this->messages[$i]['from_vdate'] = date($this->dateformat, strtotime($row['from_vdate']));
            $this->messages[$i]['to_vdate'] = date($this->dateformat, strtotime($row['to_vdate']));
            $this->messages[$i]['from_ddate'] = date($this->dateformat, strtotime($row['from_ddate']));
            $this->messages[$i]['to_ddate'] = date($this->dateformat, strtotime($row['to_ddate']));
            $this->messages[$i]['created'] = date($this->dateformat, strtotime($row['created']));
            $i++;
        }
    } else {

        return false;
    }
}

Here is my database schema

CREATE TABLE `messages` (
`id` INT( 11 ) NOT NULL AUTO_INCREMENT PRIMARY KEY ,
`title` VARCHAR( 255 ) NULL
`message` TEXT NOT NULL ,
`from` INT( 11 ) NOT NULL ,
`to` INT( 11 ) NOT NULL ,
`from_viewed` BOOL NOT NULL DEFAULT '0',
`to_viewed` BOOL NOT NULL DEFAULT '0',
`from_deleted` BOOL NOT NULL DEFAULT '0',
`to_deleted` BOOL NOT NULL DEFAULT '0',
`from_vdate` DATETIME NULL ,
`to_vdate` DATETIME NULL ,
`from_ddate` DATETIME NULL ,
`to_ddate` DATETIME NULL ,
`created` DATETIME NOT NULL
) ENGINE = MYISAM ;

A: List of Errors found on your query:

*

*&& should be written as AND in SQL.

ex,
SELECT * FROM messages WHERE `to` = '' AND ....
                                       ^ this one

*

*to and from should be escaped with backtick as it is a RESERVED Keyword.

ex,
SELECT * FROM messages WHERE `to` = ...
SELECT * FROM messages WHERE `from` = ...
                             ^ this one

A: try changing "&&" to "AND"

A: Replace  && with AND like below in all SQL queries
SELECT * FROM messages WHERE to = '".$this->userid."' AND `to_viewed` = '0' AND `to_deleted` = '0' ORDER BY `created` DESC

A: SELECT * FROM messages WHERE to = $this->userid AND to_viewed = 0 AND to_deleted = 0 ORDER BY created DESC
And I think to which you are mention in a query it may may be reserved keyword so try some diff field instead of that.


text:
Q: Adaptar texto al ancho de una imagen con PHP Estoy desarrollando un script en PHP, para escribir arriba de unas imagenes, lo que necesito es que el texto que ingrese el usuario ocupe el 100% del ancho de la imagen, he intentando con algo como esto:
$tam_fuente=floor($width/$cant_caracteres);

Donde $width es el ancho (en pixeles) de la imagen y $cant_caracteres, es la cantidad de caracteres que escribio el usuario, lo obtengo con strlen(). Pero el resultado no logra lo que busco. ¿Es posible hacer lo que quiero?. Gracias
He logrado hacerlo con un bucle, no me parece lo mas optimo pero me quedo de esta manera:
$tam_texto=imagettfbbox (12,0,$fuente,$string);
for($i=13;$tam_texto[2]<=$width && $i<$height;$i++)
{
    $tam_texto=imagettfbbox ($i,0,$fuente,$string);
    if($tam_texto[2]<$width)
    {
        $tam_fuente=$i;
    }

}