text:
Q: Deploy MVC Website as an application into MVC website I have an MVC web application deployed at the root of IIS but I have another MVC website application that needs to be deployed under the root web application.
I tried to add the child web application via 'Add Application' under website at the root but it is unable to read web.config of the inner application and giving some assembly errors that are included in the inner web application.
Please provide me procedure how I can deploy MVC web application under the MVC website. I hope the snapshot will clear the question.

A: I copied assemblies in the parent site that were being used by the child web application and it then worked.
One more solution seems possible, if the child web application routes are ignored by parent site. Though I haven't tried it.


text:
Q: How do I receive email in Excel how can I read email from my GMail account using Excel?
Here is what I have considered:

*

*Using the CDO object.
Problem: I don't think that this object can receive emails.

*Using web scraping with an IE or xmlHTTP object. This is one way to go, and I already have experience and VBA code to do much of the work but it's not simple.

*Interfacing with Microsoft Outlook. Problem: Why lock myself in to a more expensive product that Microsoft will want me to pay for when upgrading?

*Running an iMacros to scape the data. I have not explored this way properly (because I am hoping to stick to Excel) although it may be the simplest.

Any ideas? What is the simplest reliable way?
Thanks!
P.S. Google search shows many many pages with instructions to send emails using Excel. That's too easy :) . I am trying to retrieve/read emails using Excel.

A: I'm not sure what the overall goal here is, but I would suggest you are approaching it wrong.
If the goal is to put a list of emails into an Excel file, I would suggest you write the email code in Java, C#, VB, etc. and then generate an Excel file from that.
It's far easier to generate Excel files after getting email information than it is to get email information from VBA.

redpajama_set_name: RedPajamaStackExchange


text:
Q: ActionBarDrawerToggle event onClose when sliding I'm implementing an activity with two action bar drawers.
Right now I have two buttons in the action bar which show these drawers and they are working fine. Even they close the other if already opened.
These drawers are intended to be used as filters (cities and categories) for a listview, and my idea is to listen for the OnClose event, so I can get the checked items and filter the list.
With "onDrawerClosed" I can do it very easy, but the problem is when drawers are shown via sliding, as the event is not fired.
I have been dealing then with "onDrawerSlide" and finally got this code:
void initDrawer() {
    drawerToggle = new ActionBarDrawerToggle(this, drawerLayout, R.drawable.ic_home_up, R.string.app_name,
            R.string.app_name) {

        @Override
        public void onDrawerSlide(View drawerView, float slideOffset) {
            if (slideOffset == 0) {
                //if (!drawerLayout.isDrawerOpen(drawerView)) {
                    outputManager.showToast("Closed ");
                    //drawerClosed(drawerView);
                //}

                invalidateOptionsMenu(); // calls onPrepareOptionsMenu()
            }

            super.onDrawerSlide(drawerView, slideOffset);
        }

        public void onDrawerClosed(View drawerView) {
            // getActionBar().setTitle(mTitle);
            // calling onPrepareOptionsMenu() to show action bar icons
            invalidateOptionsMenu();
            drawerClosed(drawerView);
        }

        public void onDrawerOpened(View drawerView) {
            // getActionBar().setTitle(mDrawerTitle);
            // calling onPrepareOptionsMenu() to hide action bar icons
            invalidateOptionsMenu();
        }
    };
    drawerLayout.setDrawerListener(drawerToggle);
}

It kept firing the event a lot (I think it's fired several times until sliding is completed), so I checked if slideOffset is 0. It neither works, one of the sliders works, but the other doesn't fire any event.
Any idea? Maybe I could block sliding and allow to display drawers only via buttons, but how?

A: Finally I removed the second drawer and came up with a different approach. I think I tried to use it in a way is not intended for.


text:
Q: Julia: Abstract-type field in struct for solving an ODE problem I'm learning Julia and particularly interested in solving differential equations using the DifferentialEquations package. I'm having a trouble with understanding how to make a good type-stable struct that is integrated. For example, I have this mutable struct to be integrated.
mutable struct State{T} <: DEDataVector{T}
    x::Vector{T}
    r::Region
end

where Region is custom-defined abstract type: abstract type Region end
The role of Region is to parameterize my ODE function with Callback functions. For instance,
function myODE(du, u, p, t)
    c = getCoeff(u.r)
    du[1] = c*u[1]
end

which is a simplified version of my actual code but I believe it exhibits what I'm trying to say well enough. Especially, which region r::Region should be in at each time t should be determined by t and it must be updated properly by Callback features.
I have a bunch of concrete-type structs whose supertype is Region, for example
struct myRegion1 <: Region
    property1::Int64
    property2::Float64
    ...
end

and so on similarly for the other myRegions. And I have well-defined overloaded functions getCoeff(r::myRegion1), getCoeff(r::myRegion2), … for each region. This woked fine, but I found the integration is not optimized unless I have type-stable fields in my State struct. It's tested with @code_warntype on myODE function. Since Region is an abstract type, the compiler has no solid inference on type, which leads to a performance hit for the integration.
After searching for the solution for this case, I found many people suggest to rather use parametric type struct or use Union of concrete-type structs. The former one can't be the solution for this case, because I have a mixed type for r in my State struct. For instance, say r is initialized to be myRegion1. But as the integration proceeds, it should be updated to myRegion2 or another when Callback is called. Therefore, I must not use a parametric State struct in terms of Region.
The second solution seemed like it'd work, but I end up facing another problem.
First I defined a Union type as following:
const myRegions = Union{myRegion1, myRegion2, ...}

Then I modified the definition of my State struct as
mutable struct State{T} <: DEDataVector{T}
    x::Vector{T}
    r::myRegions
end

and r is no longer abstract type. But when I run the integration by
prob = ODEProblem(myODE, u0, timeSpan, p)
solve(prob, algorithm, callback=callbacks)

I got an unexpected error:
type Union has no field mutable

Apparently, the integrator checks whether type of every field of u is mutable or not, which is not even defined in Union type. So I really got stuck here… any ideas or suggestions would be really appreciated. Thanks for reading this post.


text:
Q: XSLT 1.0 if, for each can you help me please.
I´d like to have from my XML two infos.

*

*If Qualifier CN (at ADD) add CONTACT/NUMBER to GRP

*If Qualifier ST (at ADD) add PARTY_NAME_1,... to GRP

I tried following XSLT: (but please find below my answer with new XSLT, if it´s correct?)

<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:msxsl="urn:schemas-microsoft-com:xslt" exclude-result-prefixes="msxsl">
    <xsl:output method="xml" indent="yes"/>

    <xsl:template match="@* | node()">
        <xsl:copy>
            <xsl:apply-templates select="@* | node()"/>
        </xsl:copy>
    </xsl:template>

   <xsl:template match="GRP">
    <xsl:copy>

      <xsl:for-each  select ="./ADD">
  <xsl:if test="./QUALIFIER='CN'">
    <CONTACT_NUMBER>
     <xsl:value-of select="CONTACT/NUMBER"/>
    </CONTACT_NUMBER>
        </xsl:if>
      </xsl:for-each>

      <xsl:apply-templates select="@* | node()"/>
    </xsl:copy>
  </xsl:template>

     <xsl:template match="GRP">
    <xsl:copy>

      <xsl:for-each  select ="./ADD">
  <xsl:if test="./QUALIFIER='ST'">
          <xsl:copy-of select="PARTY_NAME_1"/>
          <xsl:copy-of select="STREET_1"/>
    <xsl:copy-of select="CITY"/>
    <xsl:copy-of select="POSTAL_CODE"/>
    <xsl:copy-of select="COUNTRY_CODE"/>
        </xsl:if>
      </xsl:for-each>

      <xsl:apply-templates select="@* | node()"/>
    </xsl:copy>
  </xsl:template>

  <xsl:template match="IC" />

  <xsl:template match="FILTER_SET" />

  <xsl:template match="SEE_AG" />

  <xsl:template match="ME" />

  <xsl:template match="REF" />

  <xsl:template match="TRANSPORT_DETAILS" />

  <xsl:template match="PACKAGE_DETAILS" />

  <xsl:template match="AMOUNT_DETAILS" />

 <xsl:template match="node()|@*">
     <xsl:copy>
       <xsl:apply-templates select="node()|@*"/>
     </xsl:copy>
 </xsl:template>
 <xsl:template match="*[not(@*|*|comment()|processing-instruction()) and normalize-space()='']"/>

</xsl:stylesheet>

And here´s my XML:

<?xml version="1.0"?>
<SEEDELFOR>
 <SEE_AG COPYRIGHT="" CREATION_DATE="2007-05-09" MESSAGE="" MAPPING="" VERSION="1.1.54"/>
 <CNT>
  <TRANSMISSION_DATE>20181024</TRANSMISSION_DATE>
  <TRANSMISSION_TIME>060300</TRANSMISSION_TIME>
  <INTERCHANGE_CONTROL_NUMBER>1240</INTERCHANGE_CONTROL_NUMBER>
  <SENDER></SENDER>
  <SENDER_QUALIFIER>14</SENDER_QUALIFIER>
  <RECEIVER></RECEIVER>
  <RECEIVER_QUALIFIER>14</RECEIVER_QUALIFIER>
  <SYNTAX_IDENTIFIER>UNOC</SYNTAX_IDENTIFIER>
  <SYNTAX_VERSION>3</SYNTAX_VERSION>
  <GRP>
   <IDENTIFIER_BY></IDENTIFIER_BY>
   <IDENTIFIER_MF></IDENTIFIER_MF>
   <IDENTIFIER_ST></IDENTIFIER_ST>
   <IDENTIFIER_SU></IDENTIFIER_SU>
   <IDENTIFIER_UD></IDENTIFIER_UD>
   <IDENTIFIER_CA></IDENTIFIER_CA>
   <DATE_4></DATE_4>
   <REF_ON></REF_ON>
   <TXT_001>
    <QUALIFIER></QUALIFIER>
    <TEXT_LINE></TEXT_LINE>
   </TXT_001>
   <ADD>
    <QUALIFIER></QUALIFIER>
    <IDENTIFIER></IDENTIFIER>
    <AGENCY_CODE></AGENCY_CODE>
    <PARTY_NAME_1></PARTY_NAME_1>
    <STREET_1></STREET_1>
    <CITY></CITY>
    <POSTAL_CODE></POSTAL_CODE>
   </ADD>
   <ADD>
    <QUALIFIER></QUALIFIER>
    <IDENTIFIER></IDENTIFIER>
    <AGENCY_CODE></AGENCY_CODE>
    <PARTY_NAME_1></PARTY_NAME_1>
    <CITY></CITY>
    <POSTAL_CODE></POSTAL_CODE>
   </ADD>
   <ADD>
    <QUALIFIER></QUALIFIER>
    <IDENTIFIER></IDENTIFIER>
    <AGENCY_CODE></AGENCY_CODE>
    <PARTY_NAME_1></PARTY_NAME_1>
    <STREET_1></STREET_1>
    <CITY></CITY>
    <POSTAL_CODE></POSTAL_CODE>
   </ADD>
   <ADD>
    <QUALIFIER>CN</QUALIFIER>
    <IDENTIFIER></IDENTIFIER>
    <AGENCY_CODE></AGENCY_CODE>
    <PARTY_NAME_1>Name</PARTY_NAME_1>
    <STREET_1>Street</STREET_1>
    <CITY>City</CITY>
    <POSTAL_CODE>12345</POSTAL_CODE>
    <COUNTRY_CODE>DE</COUNTRY_CODE>
    <CONTACT>
     <QUALIFIER>TE</QUALIFIER>
     <NUMBER>012345/6789_CN</NUMBER>
    </CONTACT>
   </ADD>
   <ADD>
    <QUALIFIER></QUALIFIER>
    <IDENTIFIER></IDENTIFIER>
    <AGENCY_CODE></AGENCY_CODE>
    <PARTY_NAME_1></PARTY_NAME_1>
    <STREET_1></STREET_1>
    <CITY></CITY>
    <POSTAL_CODE></POSTAL_CODE>
   </ADD>
   <ADD>
    <QUALIFIER>ST</QUALIFIER>
    <IDENTIFIER></IDENTIFIER>
    <AGENCY_CODE></AGENCY_CODE>
    <PARTY_NAME_1>Name_ST</PARTY_NAME_1>
    <STREET_1>Street_ST</STREET_1>
    <CITY>City_ST</CITY>
    <POSTAL_CODE>12345_ST</POSTAL_CODE>
   </ADD>
   <ADD>
    <QUALIFIER></QUALIFIER>
    <IDENTIFIER></IDENTIFIER>
    <AGENCY_CODE></AGENCY_CODE>
   </ADD>
   <TRANSPORT_DETAILS>
    <ADDITIONAL_DETAILS>
     <QUALIFIER></QUALIFIER>

    </ADDITIONAL_DETAILS>
   </TRANSPORT_DETAILS>
   <ITEM>
    <ITEM_NUMBER_EN></ITEM_NUMBER_EN>
    <ITEM_NUMBER_IN></ITEM_NUMBER_IN>
    <ITEM_NUMBER_SA></ITEM_NUMBER_SA>
    <QUANTITY></QUANTITY>
    <QUANTITY_UNIT></QUANTITY_UNIT>
    <LINE_ITEM_NUMBER></LINE_ITEM_NUMBER>
    <AMOUNT_DETAILS>
     <QUALIFIER></QUALIFIER>
     <AMOUNT></AMOUNT>
     <CURRENCY></CURRENCY>
    </AMOUNT_DETAILS>
    <REF>
     <QUALIFIER></QUALIFIER>
     <REFERENCE></REFERENCE>
     <ADDITIONAL_INFO/>
    </REF>
    <REF>
     <QUALIFIER></QUALIFIER>
     <REFERENCE></REFERENCE>
     <ADDITIONAL_INFO/>
    </REF>
    <REF>
     <QUALIFIER></QUALIFIER>
     <REFERENCE></REFERENCE>
     <ADDITIONAL_INFO/>
    </REF>
    <PACKAGE_DETAILS>
     <NUMBER_OF_PACKAGES></NUMBER_OF_PACKAGES>
     <REF>
      <QUALIFIER></QUALIFIER>
      <REFERENCE></REFERENCE>
     </REF>
     <REF>
      <QUALIFIER></QUALIFIER>
      <REFERENCE></REFERENCE>
     </REF>
    </PACKAGE_DETAILS>
   </ITEM>
  </GRP>
 </CNT>
</SEEDELFOR>

Correct Output should be:

<?xml version="1.0"?>
<SEEDELFOR>
 <SEE_AG COPYRIGHT="" CREATION_DATE="2007-05-09" MESSAGE="" MAPPING="" VERSION="1.1.54"/>
 <CNT>
  <TRANSMISSION_DATE>20181024</TRANSMISSION_DATE>
  <TRANSMISSION_TIME>060300</TRANSMISSION_TIME>
  <INTERCHANGE_CONTROL_NUMBER>1240</INTERCHANGE_CONTROL_NUMBER>
  <SENDER></SENDER>
  <SENDER_QUALIFIER>14</SENDER_QUALIFIER>
  <RECEIVER></RECEIVER>
  <RECEIVER_QUALIFIER>14</RECEIVER_QUALIFIER>
  <SYNTAX_IDENTIFIER>UNOC</SYNTAX_IDENTIFIER>
  <SYNTAX_VERSION>3</SYNTAX_VERSION>
  <GRP>
   <CONTACT_NUMBER>012345/6789_CN</CONTACT_NUMBER>
   <PARTY_NAME_1>Name_ST</PARTY_NAME_1>
   <STREET_1>Street_ST</STREET_1>
   <CITY>City_ST</CITY>
   <POSTAL_CODE>12345_ST</POSTAL_CODE>
   <IDENTIFIER_BY></IDENTIFIER_BY>
   <IDENTIFIER_MF></IDENTIFIER_MF>
   <IDENTIFIER_ST></IDENTIFIER_ST>
   <IDENTIFIER_SU></IDENTIFIER_SU>
   <IDENTIFIER_UD></IDENTIFIER_UD>
   <IDENTIFIER_CA></IDENTIFIER_CA>
   <DATE_4></DATE_4>
   <REF_ON></REF_ON>
   <TXT_001>
    <QUALIFIER></QUALIFIER>
    <TEXT_LINE></TEXT_LINE>
   </TXT_001>
   <ADD>
    <QUALIFIER></QUALIFIER>
    <IDENTIFIER></IDENTIFIER>
    <AGENCY_CODE></AGENCY_CODE>
    <PARTY_NAME_1></PARTY_NAME_1>
    <STREET_1></STREET_1>
    <CITY></CITY>
    <POSTAL_CODE></POSTAL_CODE>
   </ADD>
   <ADD>
    <QUALIFIER></QUALIFIER>
    <IDENTIFIER></IDENTIFIER>
    <AGENCY_CODE></AGENCY_CODE>
    <PARTY_NAME_1></PARTY_NAME_1>
    <CITY></CITY>
    <POSTAL_CODE></POSTAL_CODE>
   </ADD>
   <ADD>
    <QUALIFIER></QUALIFIER>
    <IDENTIFIER></IDENTIFIER>
    <AGENCY_CODE></AGENCY_CODE>
    <PARTY_NAME_1></PARTY_NAME_1>
    <STREET_1></STREET_1>
    <CITY></CITY>
    <POSTAL_CODE></POSTAL_CODE>
   </ADD>
   <ADD>
    <QUALIFIER>CN</QUALIFIER>
    <IDENTIFIER></IDENTIFIER>
    <AGENCY_CODE></AGENCY_CODE>
    <PARTY_NAME_1>Name</PARTY_NAME_1>
    <STREET_1>Street</STREET_1>
    <CITY>City</CITY>
    <POSTAL_CODE>12345</POSTAL_CODE>
    <COUNTRY_CODE>DE</COUNTRY_CODE>
    <CONTACT>
     <QUALIFIER>TE</QUALIFIER>
     <NUMBER>012345/6789_CN</NUMBER>
    </CONTACT>
   </ADD>
   <ADD>
    <QUALIFIER></QUALIFIER>
    <IDENTIFIER></IDENTIFIER>
    <AGENCY_CODE></AGENCY_CODE>
    <PARTY_NAME_1></PARTY_NAME_1>
    <STREET_1></STREET_1>
    <CITY></CITY>
    <POSTAL_CODE></POSTAL_CODE>
   </ADD>
   <ADD>
    <QUALIFIER>ST</QUALIFIER>
    <IDENTIFIER></IDENTIFIER>
    <AGENCY_CODE></AGENCY_CODE>
    <PARTY_NAME_1>Name_ST</PARTY_NAME_1>
    <STREET_1>Street_ST</STREET_1>
    <CITY>City_ST</CITY>
    <POSTAL_CODE>12345_ST</POSTAL_CODE>
   </ADD>
   <ADD>
    <QUALIFIER></QUALIFIER>
    <IDENTIFIER></IDENTIFIER>
    <AGENCY_CODE></AGENCY_CODE>
   </ADD>
   <TRANSPORT_DETAILS>
    <ADDITIONAL_DETAILS>
     <QUALIFIER></QUALIFIER>

    </ADDITIONAL_DETAILS>
   </TRANSPORT_DETAILS>
   <ITEM>
    <ITEM_NUMBER_EN></ITEM_NUMBER_EN>
    <ITEM_NUMBER_IN></ITEM_NUMBER_IN>
    <ITEM_NUMBER_SA></ITEM_NUMBER_SA>
    <QUANTITY></QUANTITY>
    <QUANTITY_UNIT></QUANTITY_UNIT>
    <LINE_ITEM_NUMBER></LINE_ITEM_NUMBER>
    <AMOUNT_DETAILS>
     <QUALIFIER></QUALIFIER>
     <AMOUNT></AMOUNT>
     <CURRENCY></CURRENCY>
    </AMOUNT_DETAILS>
    <REF>
     <QUALIFIER></QUALIFIER>
     <REFERENCE></REFERENCE>
     <ADDITIONAL_INFO/>
    </REF>
    <REF>
     <QUALIFIER></QUALIFIER>
     <REFERENCE></REFERENCE>
     <ADDITIONAL_INFO/>
    </REF>
    <REF>
     <QUALIFIER></QUALIFIER>
     <REFERENCE></REFERENCE>
     <ADDITIONAL_INFO/>
    </REF>
    <PACKAGE_DETAILS>
     <NUMBER_OF_PACKAGES></NUMBER_OF_PACKAGES>
     <REF>
      <QUALIFIER></QUALIFIER>
      <REFERENCE></REFERENCE>
     </REF>
     <REF>
      <QUALIFIER></QUALIFIER>
      <REFERENCE></REFERENCE>
     </REF>
    </PACKAGE_DETAILS>
   </ITEM>
  </GRP>
 </CNT>
</SEEDELFOR>

Thanks, best regards
Julian

A: Is this correct?

<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:msxsl="urn:schemas-microsoft-com:xslt" exclude-result-prefixes="msxsl">
    <xsl:output method="xml" indent="yes"/>

    <xsl:template match="@* | node()">
        <xsl:copy>
            <xsl:apply-templates select="@* | node()"/>
        </xsl:copy>
    </xsl:template>

      <xsl:template match="GRP">
    <xsl:copy>

      <xsl:for-each  select ="./ADD">
  <xsl:if test="./QUALIFIER='ST'">
          <xsl:copy-of select="PARTY_NAME_1"/>
          <xsl:copy-of select="STREET_1"/>
    <xsl:copy-of select="CITY"/>
    <xsl:copy-of select="POSTAL_CODE"/>
    <xsl:copy-of select="COUNTRY_CODE"/>
        </xsl:if>
  <xsl:if test="./QUALIFIER='CN'">
    <CONTACT_NUMBER>
     <xsl:value-of select="CONTACT/NUMBER"/>
    </CONTACT_NUMBER>
        </xsl:if>
      </xsl:for-each>

      <xsl:apply-templates select="@* | node()"/>
    </xsl:copy>
  </xsl:template>

  <xsl:template match="IC" />

  <xsl:template match="FILTER_SET" />

  <xsl:template match="SEE_AG" />

  <xsl:template match="ME" />

  <xsl:template match="REF" />

  <xsl:template match="TRANSPORT_DETAILS" />

  <xsl:template match="PACKAGE_DETAILS" />

  <xsl:template match="AMOUNT_DETAILS" />

 <xsl:template match="node()|@*">
     <xsl:copy>
       <xsl:apply-templates select="node()|@*"/>
     </xsl:copy>
 </xsl:template>
 <xsl:template match="*[not(@*|*|comment()|processing-instruction()) and normalize-space()='']"/>

</xsl:stylesheet>


text:
Q: Which app has the focus when a global shortcut is triggered I use a global shortcut to popup a dialog.
But I would like to fill the dialog depending on the application having the focus at the moment the shortcut is triggered.
But I can not find a way to do it. I read the extension code here
but it's hard to know how to modify the code, and how to recompile electron.
If someone have a pointer, that will be greatly appreciated :)

A: I couldn't find a way to know which app had the focus before, but I was able to hide my app and return the focus to the previous one, simulating clicking the 'hide' option from the view menu:
const menu = require('electron').Menu;

menu.sendActionToFirstResponder('hide:');

I hope it helps.

A: I found an answer myself, it looks that the frontmost app (at least on OSX) it still the app that had the focus before the invokation.
Here is my ClojureScript code to find the app info
(defn- get-current-app-info-osx
  "Return info about the current frontmost application on OSX"
  []
  (let [remote  (js/require "remote")
        nodobjc (js/require "nodobjc")]
    (.framework nodobjc "AppKit")
    (let [workspace (.NSWorkspace nodobjc "sharedWorkspace")
      app       (workspace "frontmostApplication")
      app-name  (str (app "localizedName"))
      app-id    (str (app "bundleIdentifier"))]
  {:name app-name
   :id   app-id})))


text:
Q: UI won't update, when adding an item to an ObservableCollection with a Command (WPF, C#) I have a TreeView, where I want to add an item with a right click. Therefore I use a command, to insert a new item.
The problem is now that adding/removing items won't be reflected in the UI and I don't know why.
The ObersavableCollections are hold in a property in my MainWindow
public static ObservableCollection<PlantObject> PlantObjects { get; set; }

The code works the way I want thus if I check the property and the item itself, it will be added but the TreeView will not reflect the changes. This can be shown by setting the ItemsSource of the TreeView null and then again to PlantObjects, which then displays the added item.
I'm pretty sure it the problem is that I add an item to the property "parents". But I don't know how to solve it.
You can see my Xaml and my Class below. NotifyPropertyChanged is implemented.
Thanks for any advice.
XAML
<TreeView Name="ContextTreeView" Margin="0,9.8,0.8,5" Grid.Row="1" Grid.Column="0" ItemsSource="{Binding Source={x:Static local:MainWindow.PlantObjects} }">
        <TreeView.ItemContainerStyle>
            <Style TargetType="{x:Type TreeViewItem}">
                <Setter Property="IsSelected" Value="{Binding IsSelected, Mode=TwoWay}" />
            </Style>
        </TreeView.ItemContainerStyle>
        <TreeView.Resources>
            <HierarchicalDataTemplate   DataType="{x:Type local:PlantObject}" ItemsSource="{Binding PlantObjects}" >
                <StackPanel Orientation="Horizontal">
                    <StackPanel.ContextMenu>
                        <ContextMenu >
                            <MenuItem Header="Delete" Name="MenuItem_DeleteContextType" Command="{Binding DeleteContextTypeCommand}"/>
                            <MenuItem Header="Insert new object above" Name="ContextMenuItem_InsertAbovePlantObject" Command="{Binding InsertAboveCommand}"/>
                        </ContextMenu>
                    </StackPanel.ContextMenu>
                    <TextBlock Text="{Binding Name}"/>
                </StackPanel>
            </HierarchicalDataTemplate>
        </TreeView.Resources>
    </TreeView>

My Class
public class PlantObject : INotifyPropertyChanged
{
    public PlantObject()
    {
        CreateInsertAboveCommand();
    }

    private bool _IsSelected;
    private PlantObject parent;
    private string name;

    public byte[] ParentID { get; set; }
    public byte[] ChildID { get; set; }
    public byte[] ObjectID { get; set; }

    private ObservableCollection<PlantObject> plantObjects = new ObservableCollection<PlantObject>();

    public PlantObject Parent
    {
        get
        {
            return parent;
        }

        set
        {
            if (value != parent)
            {
                parent = value;
                NotifyPropertyChanged();
            }
        }
    }

    public string Name
    {
        get
        {
            return name;
        }

        set
        {
            if (value != name)
            {
                name = value;
                NotifyPropertyChanged();
            }
        }
    }

    public ObservableCollection<PlantObject> PlantObjects
    {
        get { return plantObjects; }
        set
        {
            //ignore if values are equal
            if (value == plantObjects) return;

            plantObjects = value;
            NotifyPropertyChanged();
        }
    }

    public bool IsSelected
    {
        get { return _IsSelected; }
        set
        {
            if (_IsSelected == value) return;
            _IsSelected = value;
            NotifyPropertyChanged();
        }
    }

    public int? GetPosition(PlantObject plantObject)
    {
        int count = 0;

        foreach (var childObject in this.plantObjects)
        {
            if (plantObject == childObject)
            {
                return count;
            }
            count++;
        }
        return null;
    }

    protected void Insert(int position, PlantObject plantObject)
    {
        Parent.PlantObjects.Insert(position, plantObject);
    }

    protected void Remove(PlantObject plantObject)
    {

     Parent.PlantObjects.RemoveAt(Parent.PlantObjects.IndexOf(plantObject));
    }

    public event PropertyChangedEventHandler PropertyChanged;

    private void NotifyPropertyChanged([CallerMemberName] String propertyName = "")
    {
        if (PropertyChanged != null)
        {
            PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }
    }

    #region commands

    #region InsertAbove Command
    public ICommand InsertAboveCommand
    {
        get;
        internal set;
    }

    private bool CanExecuteInsertAboveCommand()
    {
        return true;
    }

    private void CreateInsertAboveCommand()
    {
        InsertAboveCommand = new RelayCommand(InsertAbove);
    }

    public void InsertAbove(object obj)
    {
        //this.IsSelected = true;

        if (this.parent == null)
        {    //highest level

            MainWindow.PlantObjects.Insert(MainWindow.PlantObjects.IndexOf(this), new PlantObject {IsSelected = true, Parent = this.Parent });
            return;
        }

        int position = this.parent.GetPosition(this) ?? default(int);

        PlantObject newPlantObejct = new PlantObject { Parent = this.Parent, IsSelected = true };
        this.Insert(position, newPlantObejct);
    }

    #endregion

    #endregion
}


text:
Q: Google Maps Javascript SDK v3 or switch to Google Maps iOS SDK My iOS application is currently using Google Maps JavaScript Application v2 and since its getting deprecated, i have two possible solutions.
There is a need to either upgrade to next version i.e v3 or use the google SDK (say GMSMapView).
Although i can't use apple maps for various reasons.
Both from higher view seems to work, but not worked on both in depth till date.

*

*Upgrading my Google Maps JavaScript Application To v3 :  upgrading to v3 will require rewriting part of my map related code. and since a lot has changed between v2 and v3 of the Google Maps JavaScript API, which is not just an incremental upgrade. So, i need to research changes and check for all requirements are met and changes will not affect anything else.

*Google maps SDK : This will be a complete rework but usage seems more simple than upgrading to newer version and reliable. But don't know how complex it will be later. and all the things done using the Google Maps JavaScript Application v2 should work with SDK too.
Help me in choosing the best solution or tell me if you have any better solution.


text:
Q: How to import 2 copies of almost the same database in Oracle at the same time? I have a properly functioning up to date 10g database locally that I don't want to mess with.  I need to do some queries on a customer's database locally which is a couple versions behind from our current software.  I had exported their full db using expdp. The user is the same, and the structure is pretty much the same.  What is the proper way of having both databases loaded at the same time?
If I have worded this funny, or am going about this in the wrong way, please let me know!  Thanks!
Edit:
There is one main user, and another user for each component/application within the main app.

A: Use Import Data Pump (impdp) with the "remap schema" option to load the exported schema into another schema in your existing database:
http://www.database.fi/2011/05/using-expdp-impdp-and-changing-schemas-with-remap_schema/


text:
Q: Combining two dictionaries with sub-dictionaries and updating values? I have two dictionaries:
d1 = {'Cat': {'White': 1}, 'Dog': {'Brown': 4, 'White': 2}}
d2 = {'Cat': {'Grey': 6, 'White': 3}, 'Rabbit': {'Brown': 4, 'White': 2}}
And I want to combine these dictionaries into a single dictionary while updating values for common values in the sub-dictionaries of d1 and d2 for matching keys in d1 and d2.
So if I combine d1 and d2, I would like to get:
combined = {'Cat': {'Grey': 6, 'White': 4}, 'Dog': {'Brown': 4, 'White': 2}, 'Rabbit': {'Brown': 4, 'White': 2}}

I am new to python so any help is appreciated.

A: I guess there is also a module for that purpose (e.g. collections module -> counter) but this is one solution:
def combine_dicts(d1, d2):
    combined = {}
    for key in d1:
        combined[key] = {}
        for key2 in d1[key]:
            combined[key][key2] = d1[key][key2]
    for key in d2:
        if key in combined:
            for key2 in d2[key]:
                if key2 in combined[key]:
                    combined[key][key2] += d2[key][key2]
                else:
                    combined[key][key2] = d2[key][key2]
        else:
            combined[key] = {}
            for key2 in d2[key]:
                combined[key][key2] = d2[key][key2]
    return combined

d1 = {'Cat': {'White': 1}, 'Dog': {'Brown': 4, 'White': 2}}
d2 = {'Cat': {'Grey': 6, 'White': 3}, 'Rabbit': {'Brown': 4, 'White': 2}}

print(combine_dicts(d1, d2))

Output: {'Cat': {'White': 4, 'Grey': 6}, 'Dog': {'Brown': 4, 'White': 2}, 'Rabbit': {'Brown': 4, 'White': 2}}


text:
Q: Finding 5 numbers with some conditions Let $A=\{1,2,3,...,100\}$. In how many ways $a_1\lt a_2\lt a_3\lt a_4\lt a_5, a_i \in A$ can be chosen from $A$ such that $a_p -a_i \geqslant 2$ for $(p-i)=1$
My try: From $A$ we can choise 5 distinct element by ${100 \choose 5}$ ways. If distance of two $a_i$ is exactly 1 then first element can be chosen by ${96 \choose 1}$ ways and rest 4 can be chosen by the consecutive of one another. So the way to pick 5 elements such that $a_p -a_i \geqslant 2$ for $(p-i)=1$ is ${100 \choose 5} - {96 \choose 1}$.
Please see that am I right or wrong. Also another approches are also welcome. Thank you in advance

A: Here is  a way w/o explicitly using stars and bars

 - From $100$ unnumbered balls in a row, take out (say) the first five and color them.

 - $95$ balls are left with $96$ interstices including the two ends.

 - The colored balls can be replaced in $\binom{96}5$ "good" ways

 - Their indices in each arrangement are a valid choice


text:
Q: No screws at the front of my Bit Fenix Comrade Case for fan I am using the BitFenix Comrade which does feature slots in the front for fans but when trying to install a fan there I found out that there are no screw holes for a fan even though there is a dust collector for 2 possible fans. Does anyone know how I am supposed to install a fan into my BitFenix Comrade case?
Case:

A: Ok, after researching I found a review here:
http://www.pcgameware.co.uk/reviews/cases/bitfenix-comrade-case-review/
That appears to say the fans mount to the dust filter:

More interestingly this also shows a removable air filter with mounts for two optional 120mm fans.

and a picture:
http://www.pcgameware.co.uk/images/BitFenix-Comrade-Front-Panel-Removed.jpg
If that's not the answer then I don't know where they go.

A: You appear to be missing the plastic insert (aka "The Front Dust Filter") the fans mount to:

Go back to whomever supplied the chassis and ask them for the part. Otherwise, contact BenFenix's support directly to locate a source for the part.


text:
Q: rename files in folder containg special characters linux I have a lot of files containing percent signs other special characters
I ran this command in the current directory but its not working...
rename 's/%//g' *
on Linux centos

A: You expect perl's rename
Remove -n switch when the output looks good.
 There are other tools with the same name which may or may not be able to do this, so be careful.

If you run the following command (GNU)
$ file "$(readlink -f "$(type -p rename)")"

and you have a result that contains Perl script, ASCII text executable and not containing ELF, then this seems to be the right tool =)
If not, to make it the default (usually already the case) on Debian and derivative like Ubuntu :
$ sudo update-alternatives --set rename /path/to/rename

Replace /path/to/rename to the path of your perl rename executable.

If you don't have this command, search your package manager to install it or do it manually (no deps...)

This tool was originally written by Larry Wall, the Perl's dad.


text:
Q: What does "FormData was used before it was declared, which is illegal for const variables" mean? I don't understand why I am getting the error that "FormData was used before it was declared, which is illegal for const variables" in my Vue component....
<script>
    export default {
    ...
    methods: {
      async sendForm(){
        const FormData = new FormData(); // error occurs here
        await this.$axios.post('/upload', FormData).then(response => {
                console.log(response)
            }).catch(error => {console.log(error)})
      }

What am I doing wrong? I have searched for FormData elsewhere in the component and there is nothing. This is the only time is it constructed.

A: Since you're declaring a local variable FormData, then any code in this block that refers to FormData is referring to that. This includes the right hand side of the line: it's referring to the local variable, not whatever other variable you have in mind. So you're trying to inintialize the variable by newing up that exact same variable, and that would require using the variable before it is initialized which isn't allowed.
The fix is most likely just to use a different variable name
const example = new FormData();


text:
Q: Weird output using the scrollView and Constraint layout <android.support.constraint.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <android.support.v7.widget.Toolbar
        android:id="@+id/toolbar2"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:background="?attr/colorPrimary"
        android:minHeight="?attr/actionBarSize"
        android:theme="?attr/actionBarTheme"
        android:layout_marginRight="0dp"
        app:layout_constraintRight_toRightOf="parent"
        android:layout_marginLeft="0dp"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        android:layout_marginTop="0dp" />

    <ScrollView
        android:id="@+id/scrollView"
        android:layout_width="368dp"
        android:layout_height="wrap_content"
        android:layout_marginRight="0dp"
        app:layout_constraintRight_toRightOf="parent"
        android:layout_marginTop="8dp"
        app:layout_constraintTop_toBottomOf="@+id/toolbar2"
        android:layout_marginLeft="8dp"
        app:layout_constraintLeft_toLeftOf="parent">

        <android.support.constraint.ConstraintLayout
            android:layout_marginEnd="8dp"
            android:layout_marginRight="8dp"
            app:layout_constraintRight_toRightOf="parent"
            app:layout_constraintLeft_toLeftOf="parent"
            android:id="@+id/constraint_layout"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="@dimen/activity_horizontal_margin">

            <TextView
                android:id="@+id/textView5"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginLeft="8dp"
                android:layout_marginStart="8dp"
                android:paddingBottom="4dp"
                android:paddingTop="4dp"
                android:text="Customer Name"
                android:textAppearance="@style/TextAppearance.AppCompat.Medium"
                android:textColor="@color/black"
                app:layout_constraintBaseline_toBaselineOf="@+id/customer_name"
                app:layout_constraintLeft_toLeftOf="parent" />

            <EditText
                android:id="@+id/customer_name"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginLeft="8dp"
                android:layout_marginRight="0dp"
                android:layout_marginTop="0dp"
                android:ems="10"
                android:hint="Name"
                android:inputType="textPersonName"
                app:layout_constraintLeft_toRightOf="@+id/textView5"
                app:layout_constraintRight_toRightOf="parent"
                app:layout_constraintTop_toTopOf="parent" />
  </android.support.constraint.ConstraintLayout>

 </ScrollView>

Please check the output of this image .
Both side content is going out of the screen. I don't why? I am even specifying the margin left and right 16dp(8dp+8dp). But I don't think it is working out.
Why is it behaving weirdly? Is it because I am testing on android version 4.2.1?
Or there is any reason?
OS- 4.2.1
I have checked it on 5.1.1 it is working fine.

A: The output is like that because:

*

*No android:orientation was specified in the ConstraintLayout(which defaults to "horizontal")

*The android:layout_width value is set to "wrap_content"
Three solutions for you :

*

*Change android:orientation in your ConstraintLayout to "vertical" and set android:layout_width of your TextView and EditText to match_parent

*Set android:layout_width of your two Views to 0dp, and then use android:weight.

*(The best solution) Delete the TextView, set android:layout_width of the EditText to match_parent. Then use android:hint on the EditText like this :
android:hint = "Customer Name"


text:
Q: Which PHP date formatting is this Mon Jun 27 13:59:36 +1000 2016 As topic says, I'm looking for the date() markup of
Mon Jun 27 13:59:36 +1000 2016

I've got this so far but not getting the + in front of the forelast parameter.
date("D M d H:i:s Z Y");

which generates something like this:
Fri Jan 15 22:13:23 3600 2016

But I guess I need this + in order to be able to compare it with a future date like:
Mon Jun 27 13:59:36 +1000 2016

Any hints are highly appreciated!

A: Use O rather than Z as outlined here:
http://php.net/manual/en/function.date.php
echo date("D M d H:i:s O Y");


text:
Q: output my object as in css structure I have a procedure that create/update this object:
style={
    "p2":{
        'color':'#fff',
        'background':'red'

    },
    "p3":{
        'color':'#fff',
        'background':'red'

    },
    "h2":{
        'color':'#fff',
        'background':'red'

    }
}

How can I output this object for display in css structure to be able to copy and paste it into css file?

A: Just iterate through the object's keys and output it somewhere:
var output = "";
for (var key in style) {
    if (style.hasOwnProperty(key)) {
        output += key + " { \n";
        for (var prop in style[key]) {
            if (style[key].hasOwnProperty(prop)) {
                output += prop + ": " + style[key][prop] + ";\n";
            }
        }
        output += "}\n";
    }
}
console.log(output);
document.write(output);

// Not sure if below works
var styleEl = document.createElement("style");
styleEl.innerHTML = output;
document.body.appendChild(styleEl);

Here is a JSBin.


text:
Q: Using Soundcloud API I am trying to develop an app that features my private content from soundcloud.  When I make my tracks private, it also blocks access to my app.  I checked with soundclouds terms and conditions and it appears that what I'm trying to do is acceptable, but I don't know how to brodge the 2 together.
By using soundclouds api, is there a way to make my tracks private to the public yet grant access to an app?
Has anyone else he challenges with this?

A: Yes.  Per the document you must authenticate yourself within the application.  You will then have access to your private sounds and can stream them to the public.  Please see the documentation linked here


text:
Q: Realtime monitoring node.js server Basicly, I need a tool that can draw realtime graphs for a collected data that calculated by a node server.
I tried to install Graphite, but got no luck on the installation(newbie in linux results too much dependencies installation failures). So I'm looking for if there are other tools can do the similar jobb with easy install guide?
I also looked abit highcharts, but there is barely any documentation for node.js. If anyone has experienced these tools and give some advices would be much appreciated!

A: Without knowing what kind of analytics data you are calculating and what type of graph you are using it is a little difficult to give you a good example.  But here it is anyway, this is for a simple scenario.
When the server changes some analytics data, use socket.io to send a message to the client, containing the new analytics data.  Something like this:
io.sockets.emit('analyticsUpdate', x, y);

On the client, create your Highcharts graph as normal but then add a load() event to the chart options, and use socket.io to retrieve the new data and update your chart like so:
    var chart;
    chart = new Highcharts.Chart({
        chart: {
            renderTo: 'container',
            type: 'spline',
            events: {
                load: function() {
                    socket.on('analyticsUpdate', function (x, y) {
                         // Simple case where you have a single series
                         // and your data can simply be appended to the series

                         var series = this.series[0];
                         series.addPoint([x, y], true, true);
                    };
                }
            }
        }
    });

So whenever the server updates some analytics data, socket.io emits a message.  The client is always listening for messages from the server, and so whenever it receives a new message it updates the graph.


text:
Q: Use jailbroken iPhone as webserver I know that this already has an answer, it is outdated. I am running iOS 10.3.3 on an iPhone 5 (so its 32 bit), and I want to run a web server for no reason at all. I have tried install lighttpd and php, but I can't find a way to turn it on.

A: Download ios-lighttpdphp-mysql from the repo https://cydia.angelxwind.net/ and turn on the server in settings. Then open
http://localhost in Safari and your iPhone is now a webserver with PHP and mySQL.
This should work on all iOS versions and devices.
Source


text:
Q: Pip install is too slow Hello I am trying to install a few modules in Qpython but is really slow, I also tried using the alternative with Qpypi and its just really slow, my download rate is between 5KBs and 10KBs...
I am using a Samsung 10+
Android Version 11
QPython 3L
The modules that I am trying to download are numpy and pandas.
Here is a screenshot of the console...


text:
Q: Failing to import a CSV into PhpMyAdmin Im trying to get data from an sql server Database into a PHPMyAdmin Databse. Most of my attempts have failed in every way. Creating a Script, using MysqlWorkbench, etc.
So I decided maybe I could just recreate a table in PHPMyAdmin manually, dump the Sql Server Data into a .csv file and import it into my PHPMyAdmin Table. If that works I could technically recreate the whole databse manually.
Well this is where my main problem lies. Im sure some of you thought my question would be a duplicate of this one.
Well every result that comes up in my google search says something along the lines of:
"My .csv look like this: data, data, data, data, data, etc."
Well my .csv looks like this:

Im slightly confused as to what Im exactly doing wrong? Where should I put the seperators? Am I looking at it wrong? Should I use another application to open the csv file instead of excel?
Because if I try to import the file in its current state I get hit with an error "Invalid amount of columns in CSV-Import Row 1". Which apparently indicates that theres no seperators that PhpMyAdmin can recognize.
Does anybody see what Im doing wrong?

A: Well I received a downvote and assumed, that if somebody is willing to downvote me this quickly, I just didnt look hard enough on google.
So I went back to googling around and found an article that explains the most common .csv problems.
And one of them was that people open the file in excel and see the data and are confused as to why they dont seem to have the same file as everybody else.
So I had a "lightbulb over my head" moment and opened the file in Editor and there my missing seperators were.
Sorry for making an unnecessary post.


text:
Q: Multiple Database calls in an asynchronous request with Tornado I am currently using Tornado and asyncmongo to create a website that accesses a mongodb. Everything is working great except when I need to make multiple requests to mongodb within in a single request to my handler. I would like to keep all my database call asynchronous so that there is no blocking on the server.
How can I accomplish this? There are several cases in which I need to retrieve different documents from multiple collections. I also sometimes need to use data that I retrieved from my first query in the second such as a foreign key. I will also need the data from both requests when I render my template.
Thanks!

A: Have each request trigger a different callback?
e.g. (I didn't test this, and I'm not familiar with asyncmongo, so it probably contains errors):
import asyncmongo
import tornado.web

class Handler(tornado.web.RequestHandler):

    @tornado.web.asynchronous
    def get(self, id):
        self.id = id
        self.db = asyncmongo.Client(pool_id='mypool', host='localhost',
            port=27107, dbname='mydb')

        self.db.users.find_one({'username': self.current_user},
            callback=self.on_user)

    def on_user(self, response, error):
        if error:
            raise tornado.web.HTTPError(500)
        self.user = response
        self.db.documents.find_one({'id': self.id, 'user': self.user},
            callback=self.on_document)

    def on_document(self, response, error):
        if error:
            raise tornado.web.HTTPError(500)
        self.render('template', first_name=self.user['first_name'],
            document=response)


text:
Q: Architecture For Android Devices And Desktop Server Application I'm designing an application where one or more devices can control an other one device. In the middle there is a Desktop Server.
In few word:

*

*One of the "Controller Devices" through an Activity take a command from the user and communicate it to the Server;

*The "Controlled Device" has a Service that listen for commands from Server;

*When the Controlled Device answers the Server has to inform all the "Controller Devices".

Which is the best Pattern, or Architecture, that can i use?

A: It's mainly Observer pattern,but you don't need to build the architecture, google has already built it for you, using Google Cloud Messsaging (GCM).
Your client register/unregister to gcm and then sends data to your backend/server which in turn manipultes and sends data to gcm which in turn sends push notification to registered devices, then you device must has a receiver to send the data back to your application.
Here have a look GCM
And here is a sample diagram that represents the gsm architecture, note that you can use any server instead of app engine


text:
Q: How can i detect the tabbar item changes from Edit in 'More' tabbar item? I have 6 tab bar items, 4 titles shown directly and other 2 are in 'More'. I have added 'cell background image' on More tableview. Now the problem is, When i click "Edit" button in More tabbar item and change the tab bar items the tableview 'background image' not displaying after the changes. How can i detect the edit button pressed and the tabbar item changes? Please help me to find the solution. Thanks in advance.

A: I have found the answer for my question and completed the issues. Apple Document describes lot about this. Use this link
 My special thanks to mattjgalloway. Thanks.


text:
Q: Fade in elements after they've been created with Jquery I want to append a bunch of images to a div using Jquery:
elements = '';

for(var i = 0; i < 9; i++) {

  elements = elements + '';

}

$('#container').append(elements);

This looks terrible because it's showing each img being loaded one by one. Instead, I want to fade them in once all of them are loaded and rendered. They MUST be faded in together, not one by one.
I have tried:
$('#container').append(elements).hide(0).fadeIn(2000);

But that seems to start the fade in at the beginning of the process, not the end.
Any ideas from you good people? :)

A: You'll have to first preload all the images, then add them and fade them in when they have all loaded.
var deferreds = [];
var elements  = $.map(Array(9).fill(0), function(_,i) {
  var img = new Image();
  var def = $.Deferred();

  img.onload = def.resolve;
  img.src = 'img' + i + '.png';
  deferreds.push(def.promise());
  return img;
});

$.when.apply($, deferreds).then(function() {
    $(elements).hide().appendTo('#container').fadeIn(1000);
})

A: It's not about fading in after appending the images, but after all the images are loaded. Use .load() to check if images are loaded.
Example: https://codepen.io/anon/pen/brQrXV
I used code from this answer: https://stackoverflow.com/a/13893943

$( document ).ready(function() {
  elements = '';
  for(var i = 0; i < 9; i++) {
    elements = elements + '';
  }
  $('#container').append(elements);

  var $images = $('.appended');
  var loaded_images_count = 0;
  $images.load(function(){
    loaded_images_count++;
    if (loaded_images_count == $images.length) {
      $('#container').addClass('loaded');
    }
  });
});
#container img {
  opacity: 0;
  transition: all 1500ms ease;
}
#container.loaded img {
  opacity: 1;
}

A: Append them all at first with a display:none style. After that give to all of them fadeIn();


text:
Q: How to dry up database code I have a database package that contains the following code.
package database

import (
    "log"

    "github.com/jinzhu/gorm"
    // required by gorm
    _ "github.com/mattn/go-sqlite3"
)

type Podcast struct {
    ID       int `sql:"index"`
    Title    string
    RssURL   string `sql:"unique_index"`
    Paused   bool
    Episodes []Episode
}

type Episode struct {
    ID           int `sql:"index"`
    PodcastID    int
    Title        string
    EnclosureURL string `sql:"unique_index"`
    Downloaded   bool
    GUID         string `sql:"unique_index"`
    PubDate      string
}

func DBSession() (db gorm.DB) {
    sqliteSession, err := gorm.Open("sqlite3", cache.db)
    if err != nil {
        log.Fatal(err)
    }

    return sqliteSession
}

Followed by a bunch of methods that all start with the following code.
FindSomethingByID(id int) {
    db := DBSession()
    db.LogMode(false)

    // code
}

FindSomethingElse {
    db := DBSession()
    db.LogMode(false)

    // code
}

Calling DBSession and setting LogMode in each func seems bad. I just don't know how to do it better. Could someone help?

A: Calling gorm.Open inside every function isn't very efficient: Open opens a new  connection pool, and should be called just once (see the database/sql docs, which gorm wraps).
A simple improvement is to establish a global gorm.DB, initialise it in init()  it from all of your functions - e.g.
package database

var db gorm.DB

func init() {
    var err error
    // Note we use an = and not a := as our variables
    // are already initialised
    db, err = gorm.Open("sqlite3", "cache.db")
    if err != nil {
        log.Fatal(err)
    }

    // Turn off logging globally
    db.LogMode(false)
}

FindSomethingByID(id int) {
    err := db.Query("...")
    // code
}

This is a quick win and reduces the repetition.
In a larger application it typically makes sense to pass dependencies (like DB pools, config params, etc.) more explicitly by wrapping them in types and creating custom handlers.
You also might initialise the connection in your package main and pass the *gorm.DB to your database package via a func New(db *gorm.DB) function that sets a private, package-level variable.

A: The most obvious simplification would be to move the db.LogMode(false) call into the DBSession() function, and give DBSession() a shorter name like DB():
func DB() (db gorm.DB) {
    sqliteSession, err := gorm.Open("sqlite3", cache.db)
    if err != nil {
        log.Fatal(err)
    }

    sqliteSession.LogMode(false)
    return sqliteSession
}

And using it:
FindSomethingByID(id int) {
    db := DB()
    // code
}

Now there's only 1 line in each of your functions using the db session, one simple function call. You can't really make it any shorter if you always need a new db session.


text:
Q: Is it possible to use CSS nth-child to follow this pattern? Here is what I'm currently using to select certain items...
            .col {
                &:nth-child(21),
                &:nth-child(22),
                &:nth-child(43),
                &:nth-child(44),
                &:nth-child(65),
                &:nth-child(66),
                &:nth-child(87),
                &:nth-child(88),
                &:nth-child(109),
                &:nth-child(110) {
                    width: 100%
                }
            }

Is it possible to create a :nth-child selector that allows me to select these same items without having to write them all out as I have here?
I tried 21n + various numbers, but I can't seem to figure it out without the grid breaking. I assume two nth-child selectors would be required as the pattern is generally an increment of 21 + 1 more (then repeated).
Thanks

A: The best way would be using a class for this purpose, this way produces more style only, which would have been so simplified by using a class.
the css selectors (22n-1) and (22n) should work here, in this case.


text:
Q: Trouble with Regex matching in Perl I'm having trouble matching a regex in Perl and was wondering if anyone had any insight:
Here is my regex: /^-MEMBER:\s+(\b[^,]+)(?:,\s(\b.{1,50}\b)\.?)?\s+ID#:\s+(\d+)$/
Here is what I'm matching:

-MEMBER:  Doe, John H                                             ID#: 3907

The regex works beautifully and matches the above line, but am having troubles with any lines that may not contain a Firstname and Middle. Example below:

-MEMBER:  Doe,                                             ID#: 3907

I'm having trouble matching with the current regex, both lines.
Thanks for any help!

A: Your have placed your comma match inside your optional firstname group, so you can only match a comma in the presence of a firstname. If commas will accompany surnames without firstnames, you need to move it to the surname group.
/^-MEMBER:\s+(\b[^,]+,)(?:\s(\b.{1,50}\b)\.?)?\s+ID#:\s+(\d+)$/

A: This regex will match both lines :
/
    ^-MEMBER:\s+         # the beginning of the line with "-MEMBER: "
    .*?                  # non greedy
    \s+ID#:\s+(\d+)$     # space and end ID part
/x

A: The trouble is that what you really what is a grammer describing your input. Attempting to describe it all in one go gets very complex, very fast. See the perl yapp module for an alternative.
However, if you insist in just using the regex, here we go:
/^-MEMBER: # start of line, match specific string
\s+ # must be followed by at least one whitespace char
(\b[^,]+) # now we need to match a word in a capture group
(?:,\s(\b.{1,50}\b)\.?)? # here's the pain, so lets deal with it below
\s+ # more whitespace
ID#: # match this string
\s+ # and some more whitespace
(\d+)$/ # digits at the end of the line

(
 ?: # cluster the following
 ,\s # comma, then a single space
 (
  \b.{1,50}\b # up to fifty "things" bounded by words
 ) # another capture group
 \.? # optional period
)? # zero or one of these I.E. optional capture

This is fragil, because it hard codes assumptions into your "language". Note how if we don't have a first/middle name, we are not allowed a comma since it is inside the optional group. That is the problem with your second test not matching.
Secondly, if we have a first/middle name section, it can include anything except a newline. This may not be what you want or expect.
The reason that parsers are useful is not necessarily because they allow you to have "context", though they do that. It is because it breaks your complex regex into small, manageable pieces connected together into a clearly defined whole. By learning such a tool the type of problem you have here become trivial to implement, and change.
Notice how your regex is attempting to define what is "valid" in each section. The last name (\b[^,]+) can have anything besides a comma! Is this what you want? What happens if valid names can only have [a-zA-Z_] in them? Is ;injectionattemptFTW!!;# a valid name? Design your program so that there is a limited, and obvious set of conditions. If a then valid, else fail is easy to reason about for simple as.
Unless you define all possible special cases, you will run into things that make this regex break. I can't define a perfect regex, so you have two options:

*

*Patch regex into even more complexity as special cases are identified

*Redesign to avoid need for complex regex

If you choose option one, then this regex fixes your current problem:
/^-MEMBER:\s+(\b[^,]+),?(?:\s(\b.{1,50}\b)\.?)?\s+ID#:\s+(\d+)$/


text:
Q: How to configure persistence.xml in Java project (without Spring) to use the cleardb_database_url in heroku I need advise how to configure persistence.xml in Java web project (without Spring) to use the cleardb_database_url so I could deploy succesffuly my database application to Heroku. I have found at Heroku site documentation how to use xml for configuring Spring, I even implemented that code to my persistence.xml but it didn't help.
I hope somebody can help me in configuring persistence.xml.
Many thanks in advance.
Regards, Sandra


text:
Q: Typesafe activator - Unable to open web browser I downloaded "typesafe activator" from play framework. Unfortunately, I have a small problem.
When I run the command "activator-1.0.8/activator ui" I get the following error message:
"Unable to open a web browser!
Please point your browser at:
"localhost"(the editor does not allow me to put down the ip)"
I searched here on the plattform and also googled the problem, but I could not find anything useful.
By the way, I am using linux.

A: I was having this problem too. Googling around I found typesafe activator checks if it can open an url in the default browser by invoking the Desktop.isDesktopSupported() or the Desktop.IsSupported(Desktop.Action action) methods in the java.awt package. These methods require the gnome libraries to work, which might not be installed in your version of Ubuntu.
For me installing the gnome libraries solved the problem:
sudo apt-get install libgnome2-0

See also: https://stackoverflow.com/a/11999764/599072
However a quick solution is just to ignore the error message and manually open the browser at the given url (which should be something like 127.0.0.1:8888).


text:
Q: shell script to check if program should be running and restart it if appropriate I have the following script
#!/bin/sh
if [cat stream_should_be_running.txt == 'true']; then #file will either contain true or false
    if [ps ax|grep -v grep|grep tracker_stream]; then # check if stream is currently running
        exit 0
    else
        /usr/local/bin/python2.7 ~/webapps/dashboard/fbadmin/manage.py tracker_stream; # restart stream
        exit 0
else
    exit 0
fi

This script should check if a daemon script is suppose to be running. If it is suppose to be running then it checks to see if the script is running and restarts it if it isn't.  Currently I get syntax error: unexpected end of file when I try to running the file manually.
So two questions:

*

*why am i pulling the syntax error

*outside of this should this script run properly?

Thanks

EDIT:
here is an updated version of the script and a few notes:
#!/bin/sh
set -vx; # turn on shell debugging

if [[ "$(cat stream_should_be_running.txt)" == "true" ]]; then
    if [ ps ax|grep -v grep|grep -q tracker_stream ]; then
        exit 0
    else
        /usr/local/bin/python2.7 ~/webapps/dashboard/fbadmin/manage.py tracker_stream;
        exit 0
    fi
else
    exit 0
fi

to note:

*

*vim marks $(...) as a syntax error ( i don't know if that matters)

*ps ax|grep -v grep|grep -q tracker_stream , ps ax|grep -v grep|grep tracker_stream , and cat stream_should_be_running.txt all execute properly from the command line

EDIT 2:
shell debugging gives the error
$ sh stream_checker.sh

+ $'\r'
: command not foundline 3:
if [[ "$(cat stream_should_be_running.txt)" == "true" ]]; then
    echo 'test';
    if [ ps ax|grep -v grep|grep -q tracker_stream ]; then
        exit 0
    else
    /usr/local/bin/python2.7 ~/webapps/dashboard/fbadmin/manage.py tracker_stream;
    exit 0
    fi
else
    exit 0
fi

stream_checker.sh: line 15: syntax error: unexpected end of file
so the only things that come before where the + $'\r' is returns are #!/bin/sh and set -vx.
This is running on a linux system. The my local machine is osx lion and the live machine is a linux server on webfaction.

A: 1) I think I got it...
I used the '-s' switch in pidof to only get one result.
The '-z' switch means "return true if the string is empty".
#!/bin/sh
PID=$(pidof -s tracker_stream);
if [ $(cat stream_should_be_running.txt) = "true"]; then #file will either contain true or false
    if [ -z $PID ]; then # check if stream is currently NOT running
        /usr/local/bin/python2.7 ~/webapps/dashboard/fbadmin/manage.py tracker_stream; # restart stream
        exit 0;
    fi
fi

EDIT: From the last note you posted it looks like you might have a Ctrl-M char (^M), somewhere on your file.
It's not merely a ^ followed by a M, it's a end of line character.
You could open your file with vim -b to check if you see any of those characters.
Then type:
:%s/^V^M//g

That command reads like "match all (^M) chars and substitute them with void".
In short it will remove all (^M) chars from your file.
The (^V^M) bit means that you have to hit CTRL-V CTRL-M, in order to insert the (^M) char.
2) what exactly do you mean by "outside of this"?

A: your square brackets need spaces around them, i.e.
if [ ps ax|grep -v grep|grep tracker_stream ] ;

AND more importantly, you need to use command substitution so your script can get the value inside stream_should_be_running.txt using $( cat ... ), i.e.
if [[ "$(cat stream_should_be_running.txt)" == 'true' ]] ; then
    #file will either contain true or false
    if[ ps ax|grep -v grep|grep -q tracker_stream ] ; then
        # check if stream is currently running
        exit 0
    else
        /usr/local/bin/python2.7 ~/webapps/dashboard/fbadmin/manage.py tracker_stream;
        # restart stream
        exit 0
else
    exit 0
fi

Also better to dbl-quote the value returned by $(cat ...) in case some how there are spaces in the file.
Finally, turn on shell debugging by adding set -vx near top script. Then you can each line/block of code as it being executed, AND the values that are substituted for variables.
I hope this helps.


text:
Q: Can't upgrade from 15.10 to 16.04 I am running into some trouble with this upgrade, I ran a "do-release-upgrade" and I guess that I wasn't paying attention and the system went from ubuntu 14.04 to 15.10 instead of 14.04 to 16.04. There was a problem with upgrading dconf, but I resolved that by creating a folder that the installer was unable to create for some reason. However, when I try to run the upgrade again for 16.04, it fails with the error "Could not calculate upgrade". Some google searches point to looking at the log "/var/log/dist-upgrade/.../apt.log". I can't determine what is causing the issue because of the magnitude of information in the file.
I used grep and cut to filter the apt.log with the command below and the output is...
"grep Broken /var/log/dist-upgrade/20160501-2239/apt.log |cut -d":" -f1|cut -d" " -f2 > /home/sam/Desktop/broken\ packages.txt"

perl-base
perl-base
findutils
libgtk-3-0
libgnutls30
libgnutls30
libgnome-desktop-3-12
libkf5akonadicore-bin
libkf5akonadicore-bin
libkf5libkdepim5
libmono-corlib2.0-cil
libkf5libkleo5
unity-control-center-faces
libmono-system2.0-cil
libmono-i18n-west2.0-cil
libmono-security2.0-cil
python3-aptdaemon.pkcompat
libmono-posix2.0-cil
libpimcommon5
libtext-charwidth-perl
libtext-wrapi18n-perl
libtext-iconv-perl
libmwaw-0.3-3
libodfgen-0.1-1
libkf5messageviewer5
dictionaries-common
libsocket6-perl
thumbnailer-service
thumbnailer-service
hunspell-en-us
libmailcommon5
buteo-sync-plugins-contacts-google
aspell
unity-lens-music
libmono-system-data2.0-cil
libmetacity-private3a
vlc
python3-click-package
libqca2
libmono-system-web2.0-cil
libclass-c3-xs-perl
libnet-libidn-perl
libmono-system-runtime2.0-cil
libmono-wcf3.0a-cil
libmono-data-tds2.0-cil
libvoikko1
libpython3.4-stdlib
libmono-system-data-linq2.0-cil
libmono-sqlite2.0-cil
address-book-updater
libidl-2-0
libkf5messagelist5
libkf5ksieveui5
libmono2.0-cil
libparams-util-perl
libopenobex2
libcalendarsupport5
qml-module-ubuntuone
libapt-pkg-perl
libtemplateparser5
libfcgi-perl
libcdr-0.1-1
libmessagecomposer5
libcheese7
libeventviews5
libmono-system-messaging2.0-cil
libmono-accessibility2.0-cil
libmono-sharpzip2.84-cil
tzdata-java
libincidenceeditorsng5
libmono-messaging2.0-cil
libmailimporter5
libtext-soundex-perl
libmono-webbrowser2.0-cil
libwpd-0.10-10v5
icedtea-7-plugin
xserver-xorg-input-mouse
libperl5.20
libnoteshared5
libcheese-gtk23
libgnutls28
libmono-winforms2.0-cil
mono-gmcs
libhunspell-1.3-0v5
checkbox-ng-service
findutils
debconf-i18n
debconf-i18n
debconf-i18n
aspell-en
aspell-en
libtext-charwidth-perl
libtext-wrapi18n-perl
libtext-iconv-perl
dictionaries-common
libio-socket-inet6-perl
libsocket6-perl
lintian
aspell
libcgi-fast-perl
address-book-service
openjdk-7-jre-headless
libdata-optlist-perl
libpython3.4-stdlib
libparams-util-perl
libapt-pkg-perl
libfcgi-perl
tzdata-java
findutils
debconf-i18n
debconf-i18n
debconf-i18n
aspell-en
aspell-en
libtext-charwidth-perl
libtext-wrapi18n-perl
libtext-iconv-perl
dictionaries-common
libio-socket-inet6-perl
libsocket6-perl
lintian
aspell
aspell
libcgi-fast-perl
qtcontact5-galera
openjdk-7-jre-headless
libdata-optlist-perl
libpython3.4-stdlib
libparams-util-perl
libapt-pkg-perl
libfcgi-perl
python3.4
python3.4-minimal
tzdata-java
libpython3.4
debconf-i18n
aspell-en
libio-socket-inet6-perl
lintian
ubuntu-minimal
libcgi-fast-perl
openjdk-7-jre-headless
libdata-optlist-perl
libnet-dns-perl
libemail-valid-perl
openjdk-7-jre
openjdk-7-jdk
libenchant1c2a
libenchant1c2a
libenchant1c2a
libenchant1c2a
libenchant1c2a
hunspell-en-us
libsub-exporter-perl
libgetopt-long-descriptive-perl
libdata-section-perl
libenchant1c2a
libenchant1c2a
libenchant1c2a
libenchant1c2a
libenchant1c2a
libenchant1c2a
libwebkit2gtk-4.0-37-gtk2
empathy
mcp-account-manager-uoa
enchant
libwebkitgtk-3.0-0
account-plugin-salut
account-plugin-jabber
gedit
gir1.2-webkit-3.0
libsoftware-license-perl
libpod-readme-perl
libgtkspell3-3-0
libwebkit2gtk-4.0-37
libenchant1c2a
libenchant1c2a
libenchant1c2a
libenchant1c2a
libenchant1c2a
libenchant1c2a
gnome-software
libhunspell-1.3-0v5
libenchant1c2a
libenchant1c2a
libenchant1c2a
libenchant1c2a
libenchant1c2a
ubuntu-software
libwebkit2gtk-4.0-37
yelp
unity-control-center
gnome-user-guide
libyelp0
librhythmbox-core9
unity-control-center-signon
rhythmbox
zenity
libgoa-backend-1.0-1
gir1.2-rb-3.0
rhythmbox-plugins
gnome-online-accounts
rhythmbox-plugin-zeitgeist
gir1.2-webkit2-4.0
metacity
apturl
shotwell
ubuntu-docs
software-center
nautilus-share
ubuntu-desktop
rhythmbox-plugin-magnatune
rhythmbox-plugin-cdrecorder
webaccounts-extension-common
webaccounts-extension-common
xul-ext-webaccounts
gnome-control-center
ubuntu-release-upgrader-gtk
ubuntu-release-upgrader-gtk
update-manager
gnome-session-flashback
gnome-session-fallback

Another file in that "dist-upgrade" log folder was main.log, but the only line that I found of interest was one "ERROR" line that reads...

2016-05-01 22:44:45,086 ERROR Dist-upgrade failed: 'E:Error, pkgProblemResolver::Resolve generated breaks, this may be caused by held packages.'

I don't see how there could be broken or held packages, because of the output of the following...

sam@sam-laptop:/var/log/dist-upgrade$ !349
sudo apt-get autoclean
Reading package lists... Done
Building dependency tree
Reading state information... Done
sam@sam-laptop:/var/log/dist-upgrade$ !350
sudo apt-get clean
sam@sam-laptop:/var/log/dist-upgrade$ !351
sudo apt-get autoremove
Reading package lists... Done
Building dependency tree
Reading state information... Done
0 upgraded, 0 newly installed, 0 to remove and 0 not upgraded.
sam@sam-laptop:/var/log/dist-upgrade$ !531
dpkg --get-selections | grep hold
sam@sam-laptop:/var/log/dist-upgrade$

More Troubleshooting:
I also tried the following, which completed without error.

sudo apt-get update --fix-missing
sudo dpkg --configure -a
sudo apt-get install -f

The next thing I thought of was to disable any non-essential repos, so I disabled multiverse and universe repos in sources.list

Full contents of logs and sources.list pastebin
/var/log/dist-upgrade/20160501-2239/main.log
/var/log/dist-upgrade/20160501-2239/apt.log
/etc/apt/sources.list
My last idea is to just boot into single user mode and force remove all the packages that are marked broken, and try the upgrade again. I am tempted to just install over my current install with 16.04 since /home is on a separate partition, but I really don't want to have to re-install all the software on this machine. Also that's the easy way out. Can somebody please help me analyze what is happening?

A: This is more of a redirect, but when I posted my broken package issue on launchpad (similarly trying to upgrade from 15.10 to 16.04), I got excellent support. In my case my issue was that I had used a foreign source (a ppa) to install some more recent graphics packages, specifically libgl1-mesa-dri, libegl1-mesa, and libgbm1. I had to downgrade those packages to the Ubuntu source versions, and then I was able to proceed with the upgrade. So my suggestion for handling broken package issues is to follow the steps in the OP, e.g.
sudo apt-get update --fix-missing
sudo dpkg --configure -a
sudo apt-get install -f

and if that fails, consider whether any ppas might be introducing package versions that would interfere with stock Ubuntu packages. Additionally, if you get extremely frustrated (like I did), get support on Launchpad.

A: I hate to do it, but because I needed a working system I just wiped and reinstalled. Luckily, I have my home folder on a separate partition, so all I needed to do was to format / and reinstall. Thank you to everyone who helped and hopefully this question can serve as valuable troubleshooting material.
Another file that I forgot to check was...sudo vi /etc/update-manager/release-upgradesI forgot that I had been changing the value of Prompt=lts  to Prompt=normal


text:
Q: Slim Framework Routes Do Not Work When Application Receives Requests from a Subfolder Resume: I need to do a request redirection using .htaccess, but my Slim Framework routes stop working when the redirection is executed.

I am developing a project for a company that has several institutional products. This company wants a custom website for each product, so each product will also have its own domain.
So for this case, I developed an application to manage the content of all websites from a single point.
I'll try to make it clear: When a user goes to product01.com, there will be a .htacces file at the root of this site that will send the request to an "app" folder. And it is in this folder "app" that my application will actually be located.
When a user accesses product02.com, the same should happen. And it's very important to make it clear that the URL that the user will access and that he will continue to see after access will be productX.com
Note that I will not have any code in the product folders. Everything will be located in the "app" folder.
I managed to make the requests work, but the problem started when I started using Slim Framework to manage my application routes.
When I access my "app" folder without going through any directions, everything works normally. But when I route requests from "product" to "app", Slim's routes stop working.
If I go from "productX" to a project that doesn't use Slim Framework to manage routes, everything works perfectly. So my difficulty is making this targeting work with Slim.
I have tried dozens of settings for the .htaccess files in all project folders and my result is the same: when I direct a request to the project that uses Slim Framework, the routes stop working. Error 404 is always returned.
My folder structure is as follows:
- localhost (or public_html)
  - app (my application where I manage everything and also use the Slim Framework)
      - src
      - libs
      - .htaccess
  - product01 (in this folder there is only one .htaccess file that directs requests to the "app" folder)
      - .htacess
  - product02 (another folder that has only one .htaccess file that directs requests to the "app" folder)
      - .htacess

The contents of the product folders .htaccess file are as follows:
RewriteEngine On
RewriteRule ^$ ../app/ [L]
RewriteRule (.*) ../app/$1 [L]

The code above is enough to get a part of what I need: direct requests from productX.com to my "app" folder without changing the URL.
The code of the .htaccess file from the folder "app" is exactly the same that comes as suggested in Slim Framework library installation:
RewriteEngine On

# Some hosts may require you to use the `RewriteBase` directive.
# If you need to use the `RewriteBase` directive, it should be the
# absolute physical path to the directory that contains this htaccess file.
#
# RewriteBase /

RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.php [QSA,L]

In my "app" folder, where the Slim Framework library is installed, I am managing routes as follows:
<?php
require_once ('libs/vendor/autoload.php');

use \Slim\Slim;

$app = new Slim();

$app->get("/", function(){
    echo "Works!";
});

$app->get("/anything", function(){
    echo "Works Too!";
});

$app->run();

The whole problem I'm facing is not knowing how to set up .htaccess files correctly or because I'm not knowing how to set up routes.

To make it easier for you to visualize my problem I have uploaded my application to my own domain.
Visit the following links to see the application working normally (without any redirection):
Application working normally without .htaccess redirection: app
Application working normally without .htaccess redirection: app/anything
In the following link you can see the redirection working normally, just because I'm not using Slim Framwork to manage routes:
This link works normally because the folder that receives the requests does not make use of the Slim Framework.
In fact, from the link above you can see "product02", but there is no content in the "product02" folder. The only thing inside is a .htaccess file that directs you to a folder called "normal".
Now, on the link below, you will see the problem I am facing. I am trying to enter the "product01" folder, which has no file other than an .htaccess file by directing requests to the "app" folder. Note that app folder routes work normally when they are accessed directly, as I showed in the first two links. These same routes stop working when I try to direct from the "product01" folder to the "app" folder:
The routes that were working on the first two links stop working because I'm directing from "product01" to "app".

I apologize for such a large text. But I really have no idea how to achieve what I want, and the only way I can get help is by explaining my problem in detail.
I also created a folder with the files of this project. You can download it by clicking here. I am using Docker to create my development environment. So in this link are also the Dockerfile and docker-compose.yml that I use.
I appreciate any help or insight to solving this problem. Thank you!!!

P.S.¹: I don't know if I'm using the tags correctly. I apologize if I am exaggerating including issues that do not relate to the problem described above. I appreciate any clarification related to this and any suggestion to change or improve the text I wrote.
P.S.²: I am Brazilian and I wrote part of this text with the help of translators. I apologize for the misuse of language and expressions. My intention is to make me understand and get your help =)


text:
Q: Create a Loading Screen without a specific time Here is my problem, when I open an activity, it start to process an image using a native method (jni) and i dont want a black screen, i want to show a message of wait or a loading wheel.
I cant determite how long gonna take the image processing.

A: Did this and worked for me:
final ProgressDialog progress;
            progress = ProgressDialog.show(PlayStaff.this, "Loading",
                    "Processing Image", true);

        new Thread(new Runnable() {
            @Override
            public void run() {
                // do the thing that takes a long time
                processImageNativeMethodJNI();

                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        progress.dismiss();
                    }
                });
            }
        }).start();

A: You can use Handler here also.
private static int SPLASH_TIME_OUT = 3000;

 new Handler().postDelayed(new Runnable() {

        @Override
        public void run() {

            Intent i = new Intent(SplashScreen.this, MainActivity.class);
            startActivity(i);
        }
    }, SPLASH_TIME_OUT);

You can add any other animation, message and all in your Spalshscreen.java file and it's Layout file.


text:
Q: Show specific files to delete in Manage Storage app menu On the iPhone, when I go to Settings > General > Storage & iCloud Usage > Storage / Manage Storage > Music, I can see how much space is taken up by specific audiobooks, artists, etc, and delete any of those files or collections of files. Is presenting users with a per-file breakdown of how much space they are using within the context of my apps something I can do as well? If so, how?
Here's a screenshot of what I'm talking about:


text:
Q: Reduce helper window size I know this is a really trivial question but I'm struggling. Whenever I type something like
?(some_function)

my screen looks like this. I want to be able to see my code still but I don't know how to move it back.

So I can't see my code and I don't know how to move the window to be smaller again.

A: You can modify the windows size with ctrl+shift+number with various result based on the number you use. (see shortcuts)
Otherwise, under the Project none on the top right corner of the picture you provide, there is 2 rectangles which allow to reduce partly the current windows inside Rstudio.
Lastly, there are many options in the view panel or in Tools > Global options > Pane layout


text:
Q: regex in a $split() (jsonata) function giving "Regular expression matches zero length string" why? I'm  having a string text like below, i wanna split the text whenever there's a new line AND starts with a date dd/mm/yyyy.
I'm using jsonata $split() function in javascript. However, i get a jsonata error as the following "Regular expression matches zero length string". Please help how can i solve this.
text = "22/03/2012 intro 20/10/2019\n" +
       "22/03/2012 body\n" +
       "more body 22/04/2020\n" +
      "22/03/2012 stuff more stuff"

$split(text , /\\r?\\n(?=(?:0[1-9]|[12][0-9]|3[01])[- \\/.](?:0[1-9]|1[012])[- \\/.](?:19|20)\\d\\d)/))
//I want the output to be [ "22/03/2012 intro 20/10/2019",
//                           "22/03/2012 body more body 22/04/2020",
//                           "22/03/2012 stuff more stuff]
// But my output now is [ "22/03/2012 intro 20/10/2019",
//                           "22/03/2012 body/n + more body 22/04/2020",
//                           "22/03/2012 stuff more stuff]

A: Use
$split($replace(text, /(\r?\n)\s*\+\s*(?=\d{2}[- \/.]\d{2}[- \/.]\d{4})|\r?\n\s*\+\s*/g, '$1'), /\r?\n/)

See proof.
The first $replace removes plus symbols and newlines and replaces with a line ending where necessary.
The $split one splits with carriage return  + line feed or just line feed.

A:

const str = "22/03/2012 intro\n" +
"22/03/2012 body\n" +
"more body\n" +
"22/03/2012 stuff\n" +
"more stuff\n";

console.log(str.match(/^[0-9][0-9][- /.][0-9][0-9][- /.][0-9][0-9][0-9][0-9][a-zA-Z\s]+(?:[a-zA-Z\s]+)/gm));
// Will log ["22/03/2012 intro\n","22/03/2012 body\nmore body\n", "22/03/2012 stuff\nmore stuff\n"]


text:
Q: npm EER! Missing script: "build" with Github Action I tried to deploy my react app to the droplet in the digital ocean using Github action, but I faced a problem when Github Action try to run the build command, it always throws an error:
Run npm run build

npm ERR! Missing script: "build"
npm ERR!
npm ERR! To see a list of scripts, run:
npm ERR!   npm run

npm ERR! A complete log of this run can be found in:
npm ERR!     /home/gli/.npm/_logs/2022-11-24T06_58_48_588Z-debug-0.log
Error: Process completed with exit code 1.

My package.json file, I do not know why since I also have a build script in the package.json file as well.
"scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },

Github Action node.js.yml
name: Node.js CI

on:
  push:
    branches: [ "main" ]
  pull_request:
    branches: [ "main" ]

jobs:
  build:

    runs-on: self-hosted

    strategy:
      matrix:
        node-version: [16.x]
        # See supported Node.js release schedule at https://nodejs.org/en/about/releases/

    steps:
    - uses: actions/checkout@v3
    - name: Use Node.js ${{ matrix.node-version }}
      uses: actions/setup-node@v3
      with:
        node-version: ${{ matrix.node-version }}
    - run: npm i
    - run: cd frontend
    - run: npm i
    - run: npm run build # fail here......:(
    - run: cd ..
    - run: pm2 stop 0
    - run: pm2 start 0
    - run: pm2 save
    - run: sudo service nginx restart

Note: Other commands are running fine only the run: npm run build is fail.
Does anyone know what the problem is? I would appreciate your help and advice.


text:
Q: Como executar(interagir) comandos prompt pelo Java?(Linux e Windows) Eai galera.
Preciso desenvolver um programa java que execute comandos como se fosse no promt/cmd, e de certa forma ate mesmo interagir com o mesmo.
Sabe quando nós executamos algum tipo de comando no prompt e ele da uma resposta ou pede uma senha? Exatamente isso, preciso de uma função java que eu possa me conectar com um dispositivo via SSH, digitar a senha de acesso.
E na sequencia rodar todos os comandos que eu precisar para configuração desse dispositivo.
Pesquisando já encontrei algumas coisas, e já até consegui rodar um comando.
**Mas existe um caso, no meu cenário real, onde eu preciso rodar um comando, e logo em seguida o prompt fica esperando a senha, mas não consegui fazer com que o JAVA logo envia-se a senha e eu segui-se com os próximos comandos.
Segue abaixo oque eu já tenho.
    public static void main(String[] args) {
     String[] cmds = {
                "ssh -S none admin@ip_aqui"
                /*"admin",
                "enable",
                "senhaaqui",
                "configure terminal",
                "gpon",
                "gpon-olt 1",
                "show onu info" */
            };

     try {
                //ProcessBuilder a = new Proce
                ProcessBuilder builder = new ProcessBuilder("cmd", "/c",
                    String.join("& ", cmds));

                builder.redirectErrorStream(true);

                Process p = builder.start();
                if ( p.waitFor() == 0){
                    System.out.println("Executado.");
                }
                else{
                    System.out.println("ERRO");
                }
                BufferedReader r = new BufferedReader(new InputStreamReader(p.getInputStream()));
                String line;

                while (true) {
                    line = r.readLine();
                    if (line == null) {
                        break;
                    }

                    System.out.println(line);
                }
            } catch(Exception e) {
                System.err.println(e);
            }
    }

No meu array de comandos ali esta comentado pois eu estava testando, mas no caso, após o primeiro comando, o prompt fica esperando a senha, que é o segundo comando, mas o java não consegue enviar a senha no momento correto, ocasionando erro.


text:
Q: Delete rows in dataframe where a name value in dataframe column equals to the value in a list Dataframe name is df_buysellrcds:

Values in list. Name is remove_list

Hi all,
Below is my code logic. I want to loop the 5 records in remove_list to remove rows in df_buysellrcds if the Stock column value equals to the value in List, and value in Type column equals to 'Buy'.
for name in remove_list:
    for i, row in df_buysellrcds:
        if row["Stock"] == name and row["Type"]=="Buy":
            df_actualHoldings = df_buysellrcds.drop(df_buysellrcds.index[i])

However I got this error:
  File "<ipython-input-10-a399d857a077>", line 2, in <module>
    for i, row in df_buysellrcds:

ValueError: too many values to unpack (expected 2)

Any ideas how should I improve my code?
My objective is to

*

*Keep all rows with Type = 'Buy' where Stock value is not in the List

*Keep all row with Type = 'Sell'

*Remove rows with Type = 'Buy' if the Stock value exists in the list
For example, first 2 records are remove but 3rd record retains for Stock value 'Genting'
Thanks for the help.

A: Since you're deleting rows while iterating over the dataframe, a ValueError is raised. To overcome this for instance, simply keep track of the indices of the rows to be deleted. However in this situation, the expressiveness of pandas allows us to bypass the iteration.
To keep only the elements whose Type is not Buy or whose Stock is not present in remove_list,
df_filtered = df[(df.Type != "Buy") | ~df.Stock.isin(remove_list)]


text:
Q: Exception in thread "main" java.lang.NoClassDefFoundError: org/apache/commons/io/FileUtils error I am facing a difficulty with my maven project. When I compile it in Eclipse, it works fine, but when I compile it through cmd and try to run it there, I get an error: Exception in thread "main" java.lang.NoClassDefFoundError: org/apache/commons/io/FileUtils. My POM file:
<project xmlns="http://maven.apache.org/POM/4.0.0"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <properties>
        <maven.compiler.source>1.8</maven.compiler.source>
        <maven.compiler.target>1.8</maven.compiler.target>
        <maven.compiler.bootclasspath>C:\Program
            Files\Java\jdk1.8.0_211\jre\lib\rt.jar${path.separator}C:\Program
            Files\Java\jdk1.8.0_211\jre\lib\jsse.jar${path.separator}C:\Program
            Files\Java\jdk1.8.0_211\jre\lib\jce.jar</maven.compiler.bootclasspath>
    </properties>

    <groupId>si.posta</groupId>
    <artifactId>espremnica</artifactId>
    <version>1.0.0</version>

    <dependencies>
        <!-- https://mvnrepository.com/artifact/commons-io/commons-io -->
        <dependency>
            <groupId>commons-io</groupId>
            <artifactId>commons-io</artifactId>
            <version>2.6</version>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.codehaus.mojo</groupId>
                <artifactId>jaxws-maven-plugin</artifactId>
                <version>2.5</version>
                <executions>
                    <execution>
                        <id>wsdltoJava</id>
                        <goals>
                            <goal>wsimport</goal>
                        </goals>
                        <configuration>
                            <wsdlUrls>
                                <wsdlUrl>https://tsteportal.posta.si/Services/eSpremnica.Provider/WCF/eOddaja.svc?wsdl</wsdlUrl>
                            </wsdlUrls>
                            <vmArgs>
                                <vmArg>-Djavax.xml.accessExternalSchema=all</vmArg>
                            </vmArgs>
                            <keep>true</keep>
                            <packageName>si.posta.espremnica.generated</packageName>
                            <sourceDestDir>${basedir}/src/main/java/generated</sourceDestDir>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-jar-plugin</artifactId>
                <version>3.1.0</version>
                <configuration>
                    <archive>
                        <manifest>
                            <addClasspath>true</addClasspath>
                            <classpathPrefix>lib/</classpathPrefix>
                            <mainClass>si.posta.espremnica.client.Client</mainClass>
                        </manifest>
                    </archive>
                </configuration>
            </plugin>
        </plugins>
    </build>

</project>

Can anyone suggest, where did I go wrong, or what did I not include here?


text:
Q: Exclude is not working on djnago queryset
        usr_all_friends_shw = Friend.objects.filter(profile_id__in = request.user.profile.friends.all())

uzr_al_cnfr_frn = FriendRequestSave.objects.filter(receiver_request=request.user.profile)

sugges= Friend.objects.exclude(profile_id__in=usr_all_friends_shw).exclude(profile_id=request.user.pk)
        for i in uzr_al_cnfr_frn:
            bdhc63=Friend.objects.filter(profile_id=i.sender_request.pk)
            print(bdhc63)
        sugestion_aftr=sugges.exclude(profile_id__in=bdhc63)

It does not show any error but still not excluding elements


text:
Q: Find the customers who bought ProductA in any month and then bought ProductB in the immediate next month Consider this table,
CREATE TABLE ProductSale
(
     cust INT,
     [Month] INT,
     amt INT,
     product VARCHAR(255)
)

INSERT INTO ProductSale (cust, Month, amt, product)
VALUES (103, 11, 493, 'pizza'), (103, 12, 304, 'drink'),
       (103, 10, 189, 'drink'), (100, 12, 270, 'pizza'),
       (100, 11, 187, 'drink'), (102, 8, 378, 'drink'),
       (101, 10, 490, 'drink'), (101, 9, 123, 'Pizza')

Customer buy one product in a month and followup with buying another product next month.
I would like to get records of customers who bought Pizza in any month and then bought drink in the immediate next month.
For example, 103 is such customer. 100 looks like one, but he is not.
How can I achieve this using a SQL query?

A: You may achieve this by using cross apply.
select p.* from ProductSale as p
cross apply (
    select * from ProductSale as ps
    where p.cust=ps.cust
    and p.month+1=ps.month
    and ps.product = 'drink'
    and p.product='pizza' ) as pg


text:
Q: How to manage memory when I want to keep some data from an object, but not all? I'm not experienced in memory management in C++. I have a Magick::Image class that holds large images (400MB) and I never need more than one whole image bitmap loaded at a time. I do want to have many objects loaded that contain metadata such as resolution, bit-depth and other small info that are related to the images and I want to be able to somehow retrieve the bitmap data (or a pointer to the bitmap data) from a call within those objects.
My solution was to have an ImageFile class that holds the metadata and a pointer to the bitmap and also has load() and unload() methods that allow me to load and unload the bitmap data. Then I can have many objects with the metadata and when I need a bitmap from any of them I can just call load() and when I'm done I can just call unload().
Unfortunately, this leads me to a problem: it's possible to pass an ImageFile pointer to a function and access it's bitmap while it's in the unloaded state. In that case I can either (1) throw an exception or (2) I can automatically load the image. Both of these seem bad to me for the following reasons:

*

*It seems to me that, philosophically speaking, if you have an instance of some class then that instance should always be in a functional/working state. Having instances that can be in a non-working state seems to require adding additional code and checks and increase program complexity. I might be mistaken here.

*If I automatically load the image after a method call that requires the bitmap, then when do I unload? The object can't know whether or not the bitmap will be used again soon, so it can't be done automatically (can it?). It seems that manual unloading will be required every time, and at that point automatic loading is pointless since we have to do manual work anyways.

For those reasons I am led to believe that my ImageFile solution is a bad practice. How do I implement what I need in a more robust way?


text:
Q: Picking one element from each of the two sets We have a bunch of people, say P1, P2, P3, P4. We have two set. Say one set is {1, 2, 3, 4} and the other set is {A, B, C}. Each person has a list of elements he can choose from each of the two sets. When a person has both elements from the two sets, we say this person is ready. We want to maximized the number of ready people. The same element cannot be used twice. Like the following example:
People: P1, P2, P3, P4
Set1: {1, 2, 3, 4}
Set2: {A, B, C}

P1 can pick from {1, 2} and {B, C}
P2 can pick from {1, 2, 3} and {C}
P3 can pick from {1, 2} and {B, C}
P4 can pick from {1} and {A, B, C}

One possible solution for the above example would be:

P1 picks none
P2 picks 3 and C
P3 picks 2 and B
P4 picks 1 and A
Thought of using greedy for each set separately, but in fact to get the optimal solution, the solution for one set sometimes has to compromise for the other set.
Edit:
Max flow solution solves the original problem. Now what if each person has his own preference when choosing from {1, 2, 3, 4}? For example, P1 prefers 2 over 1. When P1 has a choice to pick either 1 or 2, he will always pick 2.

A: This can be solved by computing the maximum flow on a flow network constructed as follows:

*

*Construct a source node Source

*Construct one node for elements of the first set #1 through #4; connect each node to the Source.

*Construct one node for each person. Connect each person to noodes #1..#4 based on their compatibility lists (i.e. P1 gets connected to #1 and #2, P2 to #1, #2 and #3, and so on)

*Construct one node for each element of the second set A..C. Connect each node to person nodes according to their compatibility lists.

*Construct a node Drain, and connect each node from A..C to the drain.

All edges and all vertices have capacity of 1. Here is an illustration based on your compatibility lists:

Now run one of several max flow algorithms on the flow network defined by this graph. The max flow that you obtain provides an optimal assignment:


text:
Q: Give two polynomials in $\mathbb Q[x]$ (of degree 2 and 3) such that their product is an irreducible polynomial in $\mathbb Q[x]$ of degree 5 I know that $$x^k - p, \ \ \forall k>0\in N$$
is irreducible in $\mathbb Q[x]$ (Eisenstein theorem). I need two polynomials in $\mathbb Q[x]$ (one of degree 2 and another of degree 3) such that their product is a irreducible polynomial in $\mathbb Q[x]$. Any clue?

A: If that is exactly what the exercise says, then the answer is that it is not possible because, by definition, the product of two nonconstant polynomials is reducible.


text:
Q: Yup: Como fazer uma regra condicional? Estou tentando fazer uma regra condicional com Yup, mas seguindo os passos da documentação, eu recebo esse erro:

TypeError: ref must be a string, got: true if (typeof key !==
  'string') throw new TypeError('ref must be a string, got: ' + key); |
  ^ 17 | this.key = key.trim(); 18 | if (key === '') throw new
  TypeError('ref must be a non-empty string'); 19 | this.isContext =
  this.key[0] === prefixes.context;

Essa é minha definição de regras:
const schema = Yup.object().shape({
    login: Yup.string()
        .email('Email don't valid')
        .required('Fill the email!'),
    password: Yup.string().required('You need to fill the password').when(user.hasOwnProperty('id'), {
        is: false
    }),
})

Quero fazer uma regra condicional que quando meu objeto user não possuir a propriedade id, tornar o password required. Alguma ideia?

A: Tente isso.
const schema = Yup.object().shape({
    login: Yup.string()
        .email('Email don"t valid')
        .required('Fill the email!'),
    password: Yup.string().when('userId', (user.hasOwnProperty('id'), field) =>
          user.hasOwnProperty('id') ? field.required() : field
    ),
})


text:
Q: Parse number from an image pytesseract I am trying to parse a number from an image. Here's an example of the images

I tried first to extract all the text to have a look at the final result but the code didn't recognize the desired number
This is my try
from PyPDF2 import PdfFileWriter, PdfFileReader
import fitz, pytesseract, os, re
import cv2

def readNumber(img):
    img = cv2.imread(img)
    gry = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    txt = pytesseract.image_to_string(gry)
    return txt

I am trying to parse the number after the slash in the second line. Here the expected is 502630
Here's another sample picture that Ahx's code failed to parse the number from it

A: I think you are missing the image processing part.
You could apply adaptive thresholding.
For example:

Now, you want 22 / 502630, so you need to check whether / is in the current line, then if the line contains the '/' character, then take the right part.
for line in text.split('\n'):
    if '/' in line:
        line = line.split('/')[1].split(' ')[0]
        print(line)

The result will be:
502630

Code:
import cv2
import pytesseract

bgr_image = cv2.imread("C8EE6.png")
scaled_image = cv2.resize(bgr_image, (0, 0), fx=3, fy=3)
gray_image = cv2.cvtColor(scaled_image, cv2.COLOR_BGR2GRAY)
thresh = cv2.adaptiveThreshold(gray_image, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY, 61, 93)
text = pytesseract.image_to_string(thresh, config="psm 6")

for line in text.split('\n'):
    if '/' in line:
        line = line.split('/')[1].split(' ')[0]
        print(line)

For the second image, if we apply the previous solution, the result will be:

We need different parameters for this solution since the output is not a clear image. We need to change the constant C and the block size
From the documentation:

The blockSize determines the size of the neighborhood area and C is a constant that is subtracted from the mean or weighted sum of the neighborhood pixels.

If we set blockSize=13 and C=2, the output image will be:

If you compare the 2-images, the latter will be more readable than the previous image. Now if you read it:
502630

Updated Code:
import cv2
import pytesseract

bgr_image = cv2.imread("UVetb.png")
gray_image = cv2.cvtColor(bgr_image, cv2.COLOR_BGR2GRAY)
thresh = cv2.adaptiveThreshold(gray_image, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY, 13, 2)
text = pytesseract.image_to_string(thresh, config="psm 6")

for line in text.split('\n'):
    if '/' in line:
        line = line.split('/')[1].split(' ')[0]
        print(line)

Will the updated code work on every image?
Can't guarantee, since each image requires a different block sizes and C parameters for getting the desired result.