答:
Use delegate()(docs) to manage events inside the divid container.

```<code>$('#divid').delegate('img.img','mouseenter',function () {
    $(this).attr('src', 'GoNextArrowHover.jpg');
})
  .delegate('img.img','mouseleave', function () {
    $(this).attr('src', 'GoNextArrow.jpg');
});
</code>```

Or if possible, make the  an  element instead, and just do it with CSS using the background-image property:

```<code>#divid > div > a {
    background-image:url(GoNextArrow.jpg);
    background-repeate:no-repeat;
}
#divid > div > a:hover {
    background-image:url(GoNextArrowHover.jpg);
}
</code>```

You'll need a few more properties to make it just right

Title: jquery selector doesn't work when html is replaced!

Body:
Use delegate()(docs) to manage events inside the divid container.

$('#divid').delegate('img.img','mouseenter',function () {
    $(this).attr('src', 'GoNextArrowHover.jpg');
})
  .delegate('img.img','mouseleave', function () {
    $(this).attr('src', 'GoNextArrow.jpg');
});

Or if possible, make the <img> an <a> element instead, and just do it with CSS using the background-image property:

#divid > div > a {
    background-image:url(GoNextArrow.jpg);
    background-repeate:no-repeat;
}
#divid > div > a:hover {
    background-image:url(GoNextArrowHover.jpg);
}

You'll need a few more properties to make it just right


来源: stackexchange

问:
Recursive function returning bool
I can't understand the following recursive function returning a  bool.

```<code> bool p(int a[], int inf, int sup) {
    if(sup==inf)
        if(a[inf]>0)
            return true;
        else
            return false;
    int m=(inf+sup)/2;
    bool left=p(a,inf,m);
    bool right=p(a,m+1,sup);
    return left && right;
}
</code>```

It should return true if all the elements in (inf, sup) are positive or else false, but I can't see how the elements that are not at the two extrema of the array are considered, since the condition that is tested is that a[inf]>0 and inf is not changed during recursion for left, while it gets values only in the right part of the array for right.

So basically, since it is different from easier recursions (like the factorial or Fibonacci) I can't understand how recursion works here: I tried to start from the base case and go on to the second step but it is unclear how to proceed.

Can anyone suggest me how to follow the recursion in this case to understand how this function returns true iff all the elements in (inf, sup) are positive?

答:
but I can't see how the elements that are not at the two extrema of
  the array are considered, ...

One way to convince your self is to step through the code with a debugger.

I don't resist gdb, but sometimes I prefer make the code itself report.

I add reports to interesting places.

```<code>#include <iostream>
#include <fstream>
#include <iomanip>
#include <sstream>
#include <string>
#include <cassert>

class T547_t
{
   int depth = 0;

public:

   int exec()
      {
         //          0  1   2  3  4
         int a[5] = {2, 1, -3, 7, 4};

         std::cout << "\n  " << (p(a,0,4) ? "\n  true" : "\n  false")
                   << "\n" << std::endl;

         // repeat test with all positive values

         int b[5] = {2, 1,  3, 7, 4};

         std::cout << "\n  " << (p(b,0,4) ? "\n  true" : "\n  false")
                   << "\n" << std::endl;

         return 0;
      }

private: // methods

   std::string show(int a[], int inf, int sup)
      {
         std::stringstream ss;
         depth += 1;
         ss << "a[" << inf << "," << sup << "]  "
            << depth << std::setw(3+depth)<< "  ";
         for (int i = inf; i <= sup; ++i)
            ss << a[i] << " ";
         return ss.str();
      }

   bool p(int a[], int inf, int sup)
      {
         std::cout << "\n  " << show(a, inf, sup) << std::flush;
         if(sup==inf)
         {
            if(a[inf]>0) { depth -= 1; return true;  }
            else         { depth -= 1; return false; }
         }
         int      m = (inf+sup) / 2;
         bool  left = p (a, inf, m);
         bool right = p (a, m+1, sup);
         depth -= 1 ;
         return (left && right);
      }
    // 1 line added to beginning of method p

}; // class T547_t

int main(int , char** )
{
   T547_t   t547;
   return  t547.exec();
}
</code>```

The output shows:

```<code>  a[0,4]  1    2 1 -3 7 4
  a[0,2]  2     2 1 -3
  a[0,1]  3      2 1
  a[0,0]  4       2
  a[1,1]  4       1
  a[2,2]  3      -3
  a[3,4]  2     7 4
  a[3,3]  3      7
  a[4,4]  3      4

  false

  a[0,4]  1    2 1 3 7 4
  a[0,2]  2     2 1 3
  a[0,1]  3      2 1
  a[0,0]  4       2
  a[1,1]  4       1
  a[2,2]  3      3
  a[3,4]  2     7 4
  a[3,3]  3      7
  a[4,4]  3      4

  true
</code>```

Clearly all values are visited.

ContentLicense: CC BY-SA 3.0

Title: Recursive function returning bool

Body:
I can't understand the following recursive function returning a  bool.

 bool p(int a[], int inf, int sup) {
    if(sup==inf)
        if(a[inf]>0)
            return true;
        else
            return false;
    int m=(inf+sup)/2;
    bool left=p(a,inf,m);
    bool right=p(a,m+1,sup);
    return left && right;
}

It should return true if all the elements in (inf, sup) are positive or else false, but I can't see how the elements that are not at the two extrema of the array are considered, since the condition that is tested is that a[inf]>0 and inf is not changed during recursion for left, while it gets values only in the right part of the array for right.

So basically, since it is different from easier recursions (like the factorial or Fibonacci) I can't understand how recursion works here: I tried to start from the base case and go on to the second step but it is unclear how to proceed.

Can anyone suggest me how to follow the recursion in this case to understand how this function returns true iff all the elements in (inf, sup) are positive?

Body:
but I can't see how the elements that are not at the two extrema of
  the array are considered, ...

One way to convince your self is to step through the code with a debugger.

I don't resist gdb, but sometimes I prefer make the code itself report.

I add reports to interesting places.

#include <iostream>
#include <fstream>
#include <iomanip>
#include <sstream>
#include <string>
#include <cassert>

class T547_t
{
   int depth = 0;

public:

   int exec()
      {
         //          0  1   2  3  4
         int a[5] = {2, 1, -3, 7, 4};

         std::cout << "\n  " << (p(a,0,4) ? "\n  true" : "\n  false")
                   << "\n" << std::endl;

         // repeat test with all positive values

         int b[5] = {2, 1,  3, 7, 4};

         std::cout << "\n  " << (p(b,0,4) ? "\n  true" : "\n  false")
                   << "\n" << std::endl;

         return 0;
      }

private: // methods

   std::string show(int a[], int inf, int sup)
      {
         std::stringstream ss;
         depth += 1;
         ss << "a[" << inf << "," << sup << "]  "
            << depth << std::setw(3+depth)<< "  ";
         for (int i = inf; i <= sup; ++i)
            ss << a[i] << " ";
         return ss.str();
      }

   bool p(int a[], int inf, int sup)
      {
         std::cout << "\n  " << show(a, inf, sup) << std::flush;
         if(sup==inf)
         {
            if(a[inf]>0) { depth -= 1; return true;  }
            else         { depth -= 1; return false; }
         }
         int      m = (inf+sup) / 2;
         bool  left = p (a, inf, m);
         bool right = p (a, m+1, sup);
         depth -= 1 ;
         return (left && right);
      }
    // 1 line added to beginning of method p

}; // class T547_t

int main(int , char** )
{
   T547_t   t547;
   return  t547.exec();
}

The output shows:

  a[0,4]  1    2 1 -3 7 4
  a[0,2]  2     2 1 -3
  a[0,1]  3      2 1
  a[0,0]  4       2
  a[1,1]  4       1
  a[2,2]  3      -3
  a[3,4]  2     7 4
  a[3,3]  3      7
  a[4,4]  3      4

  false

  a[0,4]  1    2 1 3 7 4
  a[0,2]  2     2 1 3
  a[0,1]  3      2 1
  a[0,0]  4       2
  a[1,1]  4       1
  a[2,2]  3      3
  a[3,4]  2     7 4
  a[3,3]  3      7
  a[4,4]  3      4

  true

Clearly all values are visited.


问:
How to only include some directories in ctags?
there is an --exclude option but that to exclude the directories/files. I work on a big project and want to only include the directories that has source code and not build stuff.

How to do that? What should I include in my .ctags file?

答:
I use:

```<code>find FILES | ctags -L -
</code>```

where FILES is the appropriate arguments to make find return only the files I want to index.

Exuberant Ctags (5.8) is now old and unmaintained, though.  It still works for me, so I've not switched; but the last time I checked "Universal Ctags" appeared to be the way forwards, so I would suggest starting there:

https://ctags.io

https://github.com/universal-ctags/ctags

n.b. I experienced a curious bug with Exuberant Ctags 5.8 whereby find . resulted in some corrupted tag entries, but find * did not; so you might want to use the latter if using this approach. I didn't need to index any dot files at the root level, so I'm not sure offhand what happens for  .* -- I don't think I tried it. Absolute paths were also fine, but then the TAGS file isn't portable. Potentially not an issue in the newer fork.

Body:
I use:

find FILES | ctags -L -

where FILES is the appropriate arguments to make find return only the files I want to index.

Exuberant Ctags (5.8) is now old and unmaintained, though.  It still works for me, so I've not switched; but the last time I checked "Universal Ctags" appeared to be the way forwards, so I would suggest starting there:

https://ctags.io

https://github.com/universal-ctags/ctags

n.b. I experienced a curious bug with Exuberant Ctags 5.8 whereby find . resulted in some corrupted tag entries, but find * did not; so you might want to use the latter if using this approach. I didn't need to index any dot files at the root level, so I'm not sure offhand what happens for  .* -- I don't think I tried it. Absolute paths were also fine, but then the TAGS file isn't portable. Potentially not an issue in the newer fork.

ContentLicense: CC BY-SA 4.0


问:
Transfer mysql to access including relationships and foreign keys?
Is it possible to convert My ER diagram/database from MYSQL WORKBENCH to MS ACCESS?

Will it include all the tables with their relationships to each other?

(foreign keys, data types one to many designations etc. ?)

答:
You can check this for information on transferring from mysql to ms access.

https://dev.mysql.com/doc/connector-odbc/en/connector-odbc-examples-tools-with-access-import.html

These tools generally copy all table constraints as well.


问:
Oracle Application Framework, Flexfield References, view of Segment List
I have the problem with oracle OAF. At screen you see "about page".
4 field in red square: level_2016, branch_2016, group_2016, speciality_2016 - not visible in green square "Segment list".

About Page

1) This fields used in region. In personalization there is no field for tining "Segment list". See pictures:

Personalization
Personalization

2) In controller where is same code (I don't see hide fields).

package oracle.apps.irc.candidateSelfService.webui;

import java.io.Serializable;
import oracle.apps.fnd.common.VersionInfo;
import oracle.apps.fnd.framework.OAApplicationModule;
import oracle.apps.fnd.framework.OAViewObject;
import oracle.apps.fnd.framework.webui.OAPageContext;
import oracle.apps.fnd.framework.webui.beans.OADescriptiveFlexBean;
import oracle.apps.fnd.framework.webui.beans.OAWebBean;
import oracle.apps.irc.common.webui.IrcOAControllerImpl;

public class IrcCandidateEduDetailsCO extends IrcOAControllerImpl
{
  public static final String RCS_ID = "$Header: IrcCandidateEduDetailsCO.java 120.3 2005/09/30 07:10:40 mmillmor noship $";
  public static final boolean RCS_ID_RECORDED = VersionInfo.recordClassVersion("$Header: IrcCandidateEduDetailsCO.java 120.3 2005/09/30 07:10:40 mmillmor noship $", "oracle.apps.irc.candidateSelfService.webui");

  public void processRequest(OAPageContext paramOAPageContext, OAWebBean paramOAWebBean)
  {
    super.processRequest(paramOAPageContext, paramOAWebBean);

    OADescriptiveFlexBean localOADescriptiveFlexBean1 = (OADescriptiveFlexBean)paramOAWebBean.findIndexedChildRecursive("IrcFlexField3");

    if ((localOADescriptiveFlexBean1 != null) && (localOADescriptiveFlexBean1.isRendered())) {
      localOADescriptiveFlexBean1.setFlexPrefix("Pea");
    }
    OADescriptiveFlexBean localOADescriptiveFlexBean2 = (OADescriptiveFlexBean)paramOAWebBean.findIndexedChildRecursive("QualFlexField");

    if ((localOADescriptiveFlexBean2 != null) && (localOADescriptiveFlexBean2.isRendered())) {
      localOADescriptiveFlexBean2.setFlexPrefix("Pqs");
    }

    OAViewObject localOAViewObject = (OAViewObject)paramOAPageContext.getApplicationModule(paramOAWebBean).findViewObject("IrcCandidateEduVO");
    if (localOAViewObject != null)
      localOAViewObject.invokeMethod("runQuery");
  }

  public void processFormRequest(OAPageContext paramOAPageContext, OAWebBean paramOAWebBean)
  {
    super.processFormRequest(paramOAPageContext, paramOAWebBean);

    String str1 = getIrcAction(paramOAPageContext);
    String str2;
    if ("DELETEEDU".equals(str1))
    {
      str2 = getIrcActionValue(paramOAPageContext);
      paramOAPageContext.getRootApplicationModule().invokeMethod("deleteEdu", new Serializable[] { str2 });
      super.refreshImmediately(paramOAPageContext);
    } else if ("AddEduQual".equals(str1))
    {
      str2 = getIrcActionValue(paramOAPageContext);
      paramOAPageContext.getRootApplicationModule().invokeMethod("addEduQual", new Serializable[] { str2 });
      super.refreshImmediately(paramOAPageContext);
    } else if ("DeleteEduQual".equals(str1))
    {
      str2 = paramOAPageContext.getParameter("IrcAttVal");
      String str3 = paramOAPageContext.getParameter("IrcQulVal");
      paramOAPageContext.getRootApplicationModule().invokeMethod("deleteEduQual", new Serializable[] { str2, str3 });

      super.refreshImmediately(paramOAPageContext);
    }
  }

  public boolean isAMStateSet(OAPageContext paramOAPageContext)
  {
    String str1 = getIrcAction(paramOAPageContext);
    if ("EduQuals".equals(str1))
    {
      String str2 = getIrcActionValue(paramOAPageContext);
      paramOAPageContext.getRootApplicationModule().invokeMethod("showEduQualInfo", new Serializable[] { str2 });
      return true;
    }
    return false;
  }
}
```

So, how can I view this 4 fiels?
Thanks.

答: I found a solution to my problem. It is necessary to export the region through the authority of the "Function Administrator". It rigidly spelled out the fields that you want to display. Let's edit the list of fields as we need. Then upload our personalization of the region.</p>

Body:
I have the problem with oracle OAF. At screen you see "about page".
4 field in red square: level_2016, branch_2016, group_2016, speciality_2016 - not visible in green square "Segment list".

About Page

1) This fields used in region. In personalization there is no field for tining "Segment list". See pictures:

Personalization
Personalization

2) In controller where is same code (I don't see hide fields).

package oracle.apps.irc.candidateSelfService.webui;

import java.io.Serializable;
import oracle.apps.fnd.common.VersionInfo;
import oracle.apps.fnd.framework.OAApplicationModule;
import oracle.apps.fnd.framework.OAViewObject;
import oracle.apps.fnd.framework.webui.OAPageContext;
import oracle.apps.fnd.framework.webui.beans.OADescriptiveFlexBean;
import oracle.apps.fnd.framework.webui.beans.OAWebBean;
import oracle.apps.irc.common.webui.IrcOAControllerImpl;

public class IrcCandidateEduDetailsCO extends IrcOAControllerImpl
{
  public static final String RCS_ID = "$Header: IrcCandidateEduDetailsCO.java 120.3 2005/09/30 07:10:40 mmillmor noship $";
  public static final boolean RCS_ID_RECORDED = VersionInfo.recordClassVersion("$Header: IrcCandidateEduDetailsCO.java 120.3 2005/09/30 07:10:40 mmillmor noship $", "oracle.apps.irc.candidateSelfService.webui");

  public void processRequest(OAPageContext paramOAPageContext, OAWebBean paramOAWebBean)
  {
    super.processRequest(paramOAPageContext, paramOAWebBean);

    OADescriptiveFlexBean localOADescriptiveFlexBean1 = (OADescriptiveFlexBean)paramOAWebBean.findIndexedChildRecursive("IrcFlexField3");

    if ((localOADescriptiveFlexBean1 != null) && (localOADescriptiveFlexBean1.isRendered())) {
      localOADescriptiveFlexBean1.setFlexPrefix("Pea");
    }
    OADescriptiveFlexBean localOADescriptiveFlexBean2 = (OADescriptiveFlexBean)paramOAWebBean.findIndexedChildRecursive("QualFlexField");

    if ((localOADescriptiveFlexBean2 != null) && (localOADescriptiveFlexBean2.isRendered())) {
      localOADescriptiveFlexBean2.setFlexPrefix("Pqs");
    }

    OAViewObject localOAViewObject = (OAViewObject)paramOAPageContext.getApplicationModule(paramOAWebBean).findViewObject("IrcCandidateEduVO");
    if (localOAViewObject != null)
      localOAViewObject.invokeMethod("runQuery");
  }

  public void processFormRequest(OAPageContext paramOAPageContext, OAWebBean paramOAWebBean)
  {
    super.processFormRequest(paramOAPageContext, paramOAWebBean);

    String str1 = getIrcAction(paramOAPageContext);
    String str2;
    if ("DELETEEDU".equals(str1))
    {
      str2 = getIrcActionValue(paramOAPageContext);
      paramOAPageContext.getRootApplicationModule().invokeMethod("deleteEdu", new Serializable[] { str2 });
      super.refreshImmediately(paramOAPageContext);
    } else if ("AddEduQual".equals(str1))
    {
      str2 = getIrcActionValue(paramOAPageContext);
      paramOAPageContext.getRootApplicationModule().invokeMethod("addEduQual", new Serializable[] { str2 });
      super.refreshImmediately(paramOAPageContext);
    } else if ("DeleteEduQual".equals(str1))
    {
      str2 = paramOAPageContext.getParameter("IrcAttVal");
      String str3 = paramOAPageContext.getParameter("IrcQulVal");
      paramOAPageContext.getRootApplicationModule().invokeMethod("deleteEduQual", new Serializable[] { str2, str3 });

      super.refreshImmediately(paramOAPageContext);
    }
  }

  public boolean isAMStateSet(OAPageContext paramOAPageContext)
  {
    String str1 = getIrcAction(paramOAPageContext);
    if ("EduQuals".equals(str1))
    {
      String str2 = getIrcActionValue(paramOAPageContext);
      paramOAPageContext.getRootApplicationModule().invokeMethod("showEduQualInfo", new Serializable[] { str2 });
      return true;
    }
    return false;
  }
}

So, how can I view this 4 fiels?
Thanks.


问:
JQuery to get input field value based on label

I need to copy the value of the first input box to the second input box.  The id and name of these input boxes are coming from tables.  What is fix will be the labels like 'Code' and 'Copy Code'

```<code><label>Code</label>
<input type="text" value="1234"  id="custcode_1" />

<label>Copy Code</label>
<input type="text" value=""  id="custcode_2" />
</code>```

For normal scenario it will be just

```<code>$('#custcode_2').val($('#custcode_1').val());
</code>```

But the id or name are generated on the fly so this is not possible.  How to achieve this using labels of the input boxes.

Thanks for the help.

答:
You could try something like this after giving id for both the label's.

HTML:

```<code><label id='Code'>Code</label>
<input type="text" value="1234"  id="custcode_1" />

<label id='CopyCode'>Copy Code</label>
<input type="text" value=""  id="custcode_2" />
</code>```

JQuery:

```<code>$(function(){

$('label').text('Copy Code').next('input[type=text]').val($('label').text('Code').next('input[type=text]').val());

});
</code>```

Body:
I need to copy the value of the first input box to the second input box.  The id and name of these input boxes are coming from tables.  What is fix will be the labels like 'Code' and 'Copy Code'

Code
<input type="text" value="1234"  id="custcode_1" />

Copy Code
<input type="text" value=""  id="custcode_2" />

For normal scenario it will be just

$('#custcode_2').val($('#custcode_1').val());

But the id or name are generated on the fly so this is not possible.  How to achieve this using labels of the input boxes.

Thanks for the help.

Body:
You could try something like this after giving id for both the label's.

HTML:

<label id='Code'>Code</label>
<input type="text" value="1234"  id="custcode_1" />

<label id='CopyCode'>Copy Code</label>
<input type="text" value=""  id="custcode_2" />

JQuery:

$(function(){

$('label').text('Copy Code').next('input[type=text]').val($('label').text('Code').next('input[type=text]').val());

});


问:
Add a class to the HTML  tag with React?
I'm making a modal in my React project that requires a class to be added to the body when the modal is open and removed when it is closed.

I could do this the old jQuery way by running some vanilla JavaScript which adds / removes a class, however this doesn't feel like the normal React philosophy.

Should I instead setState on my top level component to say whether the modal is open or closed? Even if I did this, as it's rendered into the div on the page it's still a side-effect to edit the body element, so is there any benefit for this extra wiring?

答:
TL;DR use document.body.classList.add and document.body.classList.remove

I would have two functions that toggle a piece of state to show/hide the modal within your outer component.

Inside these functions I would use the document.body.classList.add and document.body.classList.remove methods to manipulate the body class dependant on the modal's state like below:

```<code>openModal = (event) => {
  document.body.classList.add('modal-open');
  this.setState({ showModal: true });
}
hideModal = (event) => {
  document.body.classList.remove('modal-open');
  this.setState({ showModal: false });
}
</code>```

Title: Add a class to the HTML <body> tag with React?

Body:
TL;DR use document.body.classList.add and document.body.classList.remove

I would have two functions that toggle a piece of state to show/hide the modal within your outer component.

Inside these functions I would use the document.body.classList.add and document.body.classList.remove methods to manipulate the body class dependant on the modal's state like below:

openModal = (event) => {
  document.body.classList.add('modal-open');
  this.setState({ showModal: true });
}
hideModal = (event) => {
  document.body.classList.remove('modal-open');
  this.setState({ showModal: false });
}


问:
vb.net crystal report is asking for database login and password but logon failed
I'm new in making crystal reports and I'm done creating my crystal report but when running my program it asks for my logon information but after I log in, it says that

logon failed

I tried to look in other questions here in the site but I was not able to find an answer. My Visual Studio is 2013 Ultimate and my sql is sql-server 2014 express.

Here's my code:

```<code>Imports System.Data.SqlClient
Imports System.Data.Sql
Public Class Form1

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Dim show As String = String.Empty
        show &= "select * from fruit_stock "
        show &= "where date_received=@daterec"

        Using conn As New SqlConnection("server=WIN10;database=fruit_storage;user=fruit_admin;password=admin;")
            Using cmd As New SqlCommand
                With cmd
                    .Connection = conn
                    .CommandType = CommandType.Text
                    .CommandText = show
                    .Parameters.AddWithValue("@daterec", TextBox1.Text)
                End With

                Try
                    conn.Open()
                    Dim da As New SqlDataAdapter
                    Dim ds As New DataSet
                    da.SelectCommand = cmd
                    da.Fill(ds, "fruit_stock")
                    Dim report As New CrystalReport1
                    CrystalReportViewer1.ReportSource = report
                    CrystalReportViewer1.Refresh()

                    conn.Close()
                Catch ex As Exception
                    MsgBox(ex.Message)
                End Try

            End Using
        End Using
    End Sub
End Class
</code>```

答:
```<code>Dim report As New CrystalDecisions.CrystalReports.Engine.ReportDocument
report.Load("<physical filename of your report>")
report.SetDataSource(ds.Tables("fruit_stock"))

<your_crystal_report_viewer_in_your_form>.ReportSource = report
</code>```

if you are using an embedded report

```<code>Dim report As New <Name of your embedded crystal report>
report.SetDataSource(ds.Tables("fruit_stock"))

<your_crystal_report_viewer_in_your_form>.ReportSource = report
</code>```

Body:
I'm new in making crystal reports and I'm done creating my crystal report but when running my program it asks for my logon information but after I log in, it says that

logon failed

I tried to look in other questions here in the site but I was not able to find an answer. My Visual Studio is 2013 Ultimate and my sql is sql-server 2014 express.

Here's my code:

Imports System.Data.SqlClient
Imports System.Data.Sql
Public Class Form1

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Dim show As String = String.Empty
        show &= "select * from fruit_stock "
        show &= "where date_received=@daterec"

        Using conn As New SqlConnection("server=WIN10;database=fruit_storage;user=fruit_admin;password=admin;")
            Using cmd As New SqlCommand
                With cmd
                    .Connection = conn
                    .CommandType = CommandType.Text
                    .CommandText = show
                    .Parameters.AddWithValue("@daterec", TextBox1.Text)
                End With

                Try
                    conn.Open()
                    Dim da As New SqlDataAdapter
                    Dim ds As New DataSet
                    da.SelectCommand = cmd
                    da.Fill(ds, "fruit_stock")
                    Dim report As New CrystalReport1
                    CrystalReportViewer1.ReportSource = report
                    CrystalReportViewer1.Refresh()

                    conn.Close()
                Catch ex As Exception
                    MsgBox(ex.Message)
                End Try

            End Using
        End Using
    End Sub
End Class

Body:
Dim report As New CrystalDecisions.CrystalReports.Engine.ReportDocument
report.Load("<physical filename of your report>")
report.SetDataSource(ds.Tables("fruit_stock"))

<your_crystal_report_viewer_in_your_form>.ReportSource = report

if you are using an embedded report

Dim report As New <Name of your embedded crystal report>
report.SetDataSource(ds.Tables("fruit_stock"))

<your_crystal_report_viewer_in_your_form>.ReportSource = report


问:
replace a nested for loop with mapply
I am a beginner in R. I am working on linear programming using R studio's Cplex to solve a model. One of the constraint in my model is Xl(i,j,t) <= D(i,j,t). I am able to do this with nested for loop with a small dimension (16X16X6). But I want to run my model a lot bigger model, more like 2500X2500X60. I need to save memory and run it faster than the nested for loop.  I thought about using apply but I don't know how to make it work. Any help would be greatly appreciated!

```<code>location <-16
horizon <-6
Amat <- NULL
Xe_null <- array(0, dim = c(locations, locations, horizon))
Xl_null <- array(0, dim = c(locations, locations, horizon))
Xl      <- array(0, dim = c(locations, locations, horizon))
Xl <- Xl_null
for (t in 1:horizon) {
  for (j in 1:locations) {
    for (i in 1:locations) {
      Xl[i,j,t] <- 1
      Amat <- rbind(Amat, c(as.vector(Xe_null), as.vector(Xl)))
      Xl <- Xl_null
 } } }
dim(Amat) # 1536 3072
</code>```

Here is another constraint.

```<code>R       <- array(, dim=c(locations, horizon, horizon))
R_null  <- array(, dim=c(locations, horizon, horizon))
R <- R_null
Xe <- Xe_null
Xl <- Xl_null
#
for (t in 1:(horizon-1)) {
  for (tp in (t+1):horizon) {
    for (j in 1:locations)     {
      for (i in 1:locations)      {
        if ((tp-t) ==Travel_time[i,j])
        {
          Xe[i,j,t]=1
          Xl[i,j,t]=1
        }
      }
      R[j,tp,t] = 1
      R[j,tp,t+1] = -1
      Amat <- rbind(Amat, c(as.vector(Xe), as.vector(Xl),as.vector(R)))
      }
  }
}
</code>```

I try to do this:

```<code>Xl = function(ii,jj,tt){1}
t =c(1:horizon)
i =c(1:locations)
j =c(1:locations)
output_Xl = apply(expand.grid(i,j,t),1,function(x,y,h) Xl(x[1],x[2],x[3]))
Xl_new <- array(output_Xl, dim = c(locations, locations, horizon))
Amat <- rbind(Amat, c(as.vector(Xe_null), as.vector(Xl_new)))
dim(Amat) # 1 3072
</code>```

答:
I think what you need is to make a vectorized function giving the same output (see ?Vectorize). Below code is five hundred times as fast as yours.

At your real problems, maybe you need to use <<- instead of <- (see ?"<<-")

```<code>my_func <- function(a, b, c){
  Xl[a, b, c] <- 1
  c(as.vector(Xe_null), as.vector(Xl))
}

vectorized_my_func <- Vectorize(my_func, c("a", "b", "c"))

arg_df <- expand.grid(1:locations, 1:locations, 1:horizon)
res <- vectorized_my_func(arg_df[,1], arg_df[,2], arg_df[,3])

identical(Amat, t(res))    # TRUE

# your code
##   user  system elapsed
## 77.538  18.293  97.056

# my code
##   user  system elapsed
###  0.137   0.051   0.189
</code>```

Title: replace a nested for loop with mapply

Body:
I am a beginner in R. I am working on linear programming using R studio's Cplex to solve a model. One of the constraint in my model is Xl(i,j,t) <= D(i,j,t). I am able to do this with nested for loop with a small dimension (16X16X6). But I want to run my model a lot bigger model, more like 2500X2500X60. I need to save memory and run it faster than the nested for loop.  I thought about using apply but I don't know how to make it work. Any help would be greatly appreciated!

location <-16
horizon <-6
Amat <- NULL
Xe_null <- array(0, dim = c(locations, locations, horizon))
Xl_null <- array(0, dim = c(locations, locations, horizon))
Xl      <- array(0, dim = c(locations, locations, horizon))
Xl <- Xl_null
for (t in 1:horizon) {
  for (j in 1:locations) {
    for (i in 1:locations) {
      Xl[i,j,t] <- 1
      Amat <- rbind(Amat, c(as.vector(Xe_null), as.vector(Xl)))
      Xl <- Xl_null
 } } }
dim(Amat) # 1536 3072

Here is another constraint.

R       <- array(, dim=c(locations, horizon, horizon))
R_null  <- array(, dim=c(locations, horizon, horizon))
R <- R_null
Xe <- Xe_null
Xl <- Xl_null
#
for (t in 1:(horizon-1)) {
  for (tp in (t+1):horizon) {
    for (j in 1:locations)     {
      for (i in 1:locations)      {
        if ((tp-t) ==Travel_time[i,j])
        {
          Xe[i,j,t]=1
          Xl[i,j,t]=1
        }
      }
      R[j,tp,t] = 1
      R[j,tp,t+1] = -1
      Amat <- rbind(Amat, c(as.vector(Xe), as.vector(Xl),as.vector(R)))
      }
  }
}

I try to do this:

Xl = function(ii,jj,tt){1}
t =c(1:horizon)
i =c(1:locations)
j =c(1:locations)
output_Xl = apply(expand.grid(i,j,t),1,function(x,y,h) Xl(x[1],x[2],x[3]))
Xl_new <- array(output_Xl, dim = c(locations, locations, horizon))
Amat <- rbind(Amat, c(as.vector(Xe_null), as.vector(Xl_new)))
dim(Amat) # 1 3072

Body:
I think what you need is to make a vectorized function giving the same output (see ?Vectorize). Below code is five hundred times as fast as yours.

At your real problems, maybe you need to use <<- instead of <- (see ?"<<-")

my_func <- function(a, b, c){
  Xl[a, b, c] <- 1
  c(as.vector(Xe_null), as.vector(Xl))
}

vectorized_my_func <- Vectorize(my_func, c("a", "b", "c"))

arg_df <- expand.grid(1:locations, 1:locations, 1:horizon)
res <- vectorized_my_func(arg_df[,1], arg_df[,2], arg_df[,3])

identical(Amat, t(res))    # TRUE

# your code
##   user  system elapsed
## 77.538  18.293  97.056

# my code
##   user  system elapsed
###  0.137   0.051   0.189


问:
spark logistic regression for binary classification: apply new threshold for predicting 2 classes
I am new to both Spark and Python. I used Spark to train a Logistic Regression model with just two classes (0 and 1). I trained it using my train data frame.

This is how my pipeline model was defined:

```<code># Model definition:
lr = LogisticRegression(featuresCol = "lr_features", labelCol = "targetvar")
# Pipeline definition:
lr_pipeline = Pipeline(stages = indexStages + encodeStages +[lr_assembler, lr])
# Fit the logistic regression model:
lrModel = lr_pipeline.fit(train)
</code>```

Then I ran predictions using my test dataframe:

```<code>lr_predictions = lrModel.transform(test)
</code>```

Now, my lr_predictions has a column 'probability' that looks like a nested list to me. For example, its first cell contains:
[1,2,[],[0.88,0.11]]

I assume, it means: the probability for class 1 (which is = 0) is 0.88, the probability for class 2 (which is = 1) is 0.11.

By default (threshold = 0.5) this observation is predicted
as 0. However, I found a value (bestThreshold) that maximizes the F-measure (in my case it's 0.21):

```<code>fMeasure = lr_summary.fMeasureByThreshold
bestThreshold = fMeasure.orderBy(fMeasure['F-Measure'].desc()).first().threshold
</code>```

I would like to apply bestThreshold to the 'probability' column and get a new
column ('pred_new', for example) that contains the class assignments (0 or 1) based on bestThreshold as opposed to 0.5.

I cannot use the code below, because 'probability' column is too complex:

```<code>from pyspark.sql.functions import when
lr_predictions = lr_predictions.withColumn("prob_best", \
              when(lr_predictions["probability"] >= bestThreshold, 1).otherwise(0)
</code>```

I feel I need to need to map the 'probability' to a new column based on a new threshold. But I am not sure how to do it - given this complex (for me) structure of the 'probability' column.

Thank you so much for your advice!

答:
If lrModel is LogisticRegressionModel:

```<code>type(lrModel)
## pyspark.ml.classification.LogisticRegressionModel
</code>```

You can use internal Java object to set threshold

```<code>lrModel._java_obj.setThreshold(bestThreshold)
</code>```

and transform:

```<code>lrModel.transform(data)
</code>```

You can do the same to modify rawPredictionCol, predictionCol and probabilityCol.

This should become part of the public API in the future (2.3):

```<code>lrModel.transform(data, {lrModel.threshold: bestThreshold})
</code>```

You can also use UDF:

```<code>from pyspark.sql.functions import udf, lit

@udf("integer")
def predict(v, threshold):
    return 0 if v[0] >= bestThreshold  else 1

lr_predictions.withColumn(
   "prob_best",
   predict(lr_predictions["probability"], lit(bestThreshold)))
</code>```

Edit:

With PipelineModel you can try to access LogisticRegressionModel (as in your previous question) and do the same thing.

Body:
I am new to both Spark and Python. I used Spark to train a Logistic Regression model with just two classes (0 and 1). I trained it using my train data frame.

This is how my pipeline model was defined:

# Model definition:
lr = LogisticRegression(featuresCol = "lr_features", labelCol = "targetvar")
# Pipeline definition:
lr_pipeline = Pipeline(stages = indexStages + encodeStages +[lr_assembler, lr])
# Fit the logistic regression model:
lrModel = lr_pipeline.fit(train)

Then I ran predictions using my test dataframe:

lr_predictions = lrModel.transform(test)

Now, my lr_predictions has a column 'probability' that looks like a nested list to me. For example, its first cell contains:
[1,2,[],[0.88,0.11]]

I assume, it means: the probability for class 1 (which is = 0) is 0.88, the probability for class 2 (which is = 1) is 0.11.

By default (threshold = 0.5) this observation is predicted
as 0. However, I found a value (bestThreshold) that maximizes the F-measure (in my case it's 0.21):

fMeasure = lr_summary.fMeasureByThreshold
bestThreshold = fMeasure.orderBy(fMeasure['F-Measure'].desc()).first().threshold

I would like to apply bestThreshold to the 'probability' column and get a new
column ('pred_new', for example) that contains the class assignments (0 or 1) based on bestThreshold as opposed to 0.5.

I cannot use the code below, because 'probability' column is too complex:

from pyspark.sql.functions import when
lr_predictions = lr_predictions.withColumn("prob_best", \
              when(lr_predictions["probability"] >= bestThreshold, 1).otherwise(0)

I feel I need to need to map the 'probability' to a new column based on a new threshold. But I am not sure how to do it - given this complex (for me) structure of the 'probability' column.

Thank you so much for your advice!

Body:
If lrModel is LogisticRegressionModel:

type(lrModel)
## pyspark.ml.classification.LogisticRegressionModel

You can use internal Java object to set threshold

lrModel._java_obj.setThreshold(bestThreshold)

and transform:

lrModel.transform(data)

You can do the same to modify rawPredictionCol, predictionCol and probabilityCol.

This should become part of the public API in the future (2.3):

lrModel.transform(data, {lrModel.threshold: bestThreshold})

You can also use UDF:

from pyspark.sql.functions import udf, lit

@udf("integer")
def predict(v, threshold):
    return 0 if v[0] >= bestThreshold  else 1

lr_predictions.withColumn(
   "prob_best",
   predict(lr_predictions["probability"], lit(bestThreshold)))

Edit:

With PipelineModel you can try to access LogisticRegressionModel (as in your previous question) and do the same thing.


问:
Upload image to blog storage from mvc registration form
I'm trying to build the functionality where the user can upload a profile image to blob storage on registration and then i can be called and included in the manage index view.

I have been able to create the container but no blob is showing inside the container and the url is not being saved to the database either (just NULL) so I'm feeling like its the controller code that's the issue.

CONTROLLER

```<code>[HttpPost]
    [AllowAnonymous]
    [ValidateAntiForgeryToken]
    public async Task<ActionResult> Register(RegisterViewModel model,
    HttpPostedFileBase photo, PhotoService photoService)
    {
        if (ModelState.IsValid)
        {

           var user = new ApplicationUser { UserName = model.Email, Email = model.Email, PhotoUrl = model.PhotoUrl };

            ApplicationUser.PhotoUrl = await photoService.UploadPhotoAsync(photo);

            var result = await UserManager.CreateAsync(user, model.Password);
            if (result.Succeeded)
            {
                await SignInManager.SignInAsync(user, isPersistent: false, rememberBrowser: false);

                // For more information on how to enable account confirmation and password reset please visit https://go.microsoft.com/fwlink/?LinkID=320771
                // Send an email with this link
                // string code = await UserManager.GenerateEmailConfirmationTokenAsync(user.Id);
                // var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme);
                // await UserManager.SendEmailAsync(user.Id, "Confirm your account", "Please confirm your account by clicking <a href=\"" + callbackUrl + "\">here</a>");

                //var db = new ApplicationDbContext();
                //model.PhotoUrl = await photoService.UploadPhotoAsync(photo);
                //db.Users.Add(user);
                //db.SaveChanges();

                return RedirectToAction("Index", "Home");
            }
            AddErrors(result);

        }

        // If we got this far, something failed, redisplay form
        return View(model);
    }
</code>```

MODEL

```<code>public class RegisterViewModel
{
    [Required]
    [EmailAddress]
    [Display(Name = "Email")]
    public string Email { get; set; }

    [Required]
    [StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)]
    [DataType(DataType.Password)]
    [Display(Name = "Password")]
    public string Password { get; set; }

    [DataType(DataType.Password)]
    [Display(Name = "Confirm password")]
    [Compare("Password", ErrorMessage = "The password and confirmation password do not match.")]
    public string ConfirmPassword { get; set; }

    public string PhotoUrl { get; set; }
}
</code>```

SERVICE

```<code>public class PhotoService : IPhotoService
    {

        async public Task<string> UploadPhotoAsync(HttpPostedFileBase photoToUpload)
        {
            if (photoToUpload == null || photoToUpload.ContentLength == 0)
            {
                return null;
            }

            string fullPath = null;
            Stopwatch timespan = Stopwatch.StartNew();

            try
            {
                CloudStorageAccount storageAccount = StorageUtils.StorageAccount;

                // Create the blob client and reference the container
                CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();
                CloudBlobContainer container = blobClient.GetContainerReference("images");

                // Create a unique name for the images we are about to upload
                string imageName = String.Format("task-photo-{0}{1}",
                    Guid.NewGuid().ToString(),
                    Path.GetExtension(photoToUpload.FileName));

                // Upload image to Blob Storage
                CloudBlockBlob blockBlob = container.GetBlockBlobReference(imageName);
                blockBlob.Properties.ContentType = photoToUpload.ContentType;
                await blockBlob.UploadFromStreamAsync(photoToUpload.InputStream);

                fullPath = blockBlob.Uri.ToString();

                timespan.Stop();
                // log.TraceApi("Blob Service", "PhotoService.UploadPhoto", timespan.Elapsed, "imagepath={0}", fullPath);
            }
            catch (Exception ex)
            {
                // log.Error(ex, "Error upload photo blob to storage");
                throw;
            }

            return fullPath;
        }
</code>```

I'm working on this with this tutorial as a guide - https://learn.microsoft.com/en-us/aspnet/aspnet/overview/developing-apps-with-windows-azure/building-real-world-cloud-apps-with-windows-azure/unstructured-blob-storage

Would really appreciate it if someone could let me know how to get this working.

Thanks

答:
"an object reference is required for the nonstatic field method or property".

You need to init your user as follows:

```<code>var user = new ApplicationUser {
    UserName = model.Email,
    Email = model.Email,
    PhotoUrl = await photoService.UploadPhotoAsync(photo)
};

var result = await UserManager.CreateAsync(user, model.Password);
</code>```

Moreover, I found the tutorial defined a interface IPhotoService and implement it by the PhotoService class, but I found you define the PhotoService in your Register action. In order to leverage dependency injection, I would recommend you follow this tutorial.

Also, I would recommend you move the HttpPostedFileBase photo parameter from the Register method into your RegisterViewModel as follows:

public class RegisterViewModel
{
    [Required]
    [EmailAddress]
    [Display(Name = "Email")]
    public string Email { get; set; }

    [Required]
    [StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)]
    [DataType(DataType.Password)]
    [Display(Name = "Password")]
    public string Password { get; set; }

    [DataType(DataType.Password)]
    [Display(Name = "Confirm password")]
    [Compare("Password", ErrorMessage = "The password and confirmation password do not match.")]
    public string ConfirmPassword { get; set; }

    public HttpPostedFileBase Photo { get; set; }
}
```

<p>Then, you could init your <code>ApplicationUser</code> instance as follows:</p>

```var user = new ApplicationUser {
    UserName = model.Email,
    Email = model.Email,
    PhotoUrl = await photoService.UploadPhotoAsync(model.Photo)
};
```

<p>And for your register view, you could init the input file as follows:</p>

```@using (Html.BeginForm("Register", "Account", FormMethod.Post, new { @class = "form-horizontal", role = "form", enctype = "multipart/form-data" }))
{
   //other properties
   @Html.TextBoxFor(m => m.Photo, new {type = "file"})
}
```

TEST:

In general, you need to make sure you have set the multipart/form-data for your register form in the register view. And the parameter photoService in the Register method is not null. Also, you need to make sure your container name images exists, or you need to await container.CreateIfNotExistsAsync(). Additionally, you could leverage debugging via Visual Studio and step into your code to narrow this issue, details about how to debug, you could follow here.

Body:
I'm trying to build the functionality where the user can upload a profile image to blob storage on registration and then i can be called and included in the manage index view.

I have been able to create the container but no blob is showing inside the container and the url is not being saved to the database either (just NULL) so I'm feeling like its the controller code that's the issue.

CONTROLLER

[HttpPost]
    [AllowAnonymous]
    [ValidateAntiForgeryToken]
    public async Task<ActionResult> Register(RegisterViewModel model,
    HttpPostedFileBase photo, PhotoService photoService)
    {
        if (ModelState.IsValid)
        {

           var user = new ApplicationUser { UserName = model.Email, Email = model.Email, PhotoUrl = model.PhotoUrl };

            ApplicationUser.PhotoUrl = await photoService.UploadPhotoAsync(photo);

            var result = await UserManager.CreateAsync(user, model.Password);
            if (result.Succeeded)
            {
                await SignInManager.SignInAsync(user, isPersistent: false, rememberBrowser: false);

                // For more information on how to enable account confirmation and password reset please visit https://go.microsoft.com/fwlink/?LinkID=320771
                // Send an email with this link
                // string code = await UserManager.GenerateEmailConfirmationTokenAsync(user.Id);
                // var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme);
                // await UserManager.SendEmailAsync(user.Id, "Confirm your account", "Please confirm your account by clicking here");

                //var db = new ApplicationDbContext();
                //model.PhotoUrl = await photoService.UploadPhotoAsync(photo);
                //db.Users.Add(user);
                //db.SaveChanges();

                return RedirectToAction("Index", "Home");
            }
            AddErrors(result);

        }

        // If we got this far, something failed, redisplay form
        return View(model);
    }

MODEL

public class RegisterViewModel
{
    [Required]
    [EmailAddress]
    [Display(Name = "Email")]
    public string Email { get; set; }

    [Required]
    [StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)]
    [DataType(DataType.Password)]
    [Display(Name = "Password")]
    public string Password { get; set; }

    [DataType(DataType.Password)]
    [Display(Name = "Confirm password")]
    [Compare("Password", ErrorMessage = "The password and confirmation password do not match.")]
    public string ConfirmPassword { get; set; }

    public string PhotoUrl { get; set; }
}

SERVICE

public class PhotoService : IPhotoService
    {

        async public Task<string> UploadPhotoAsync(HttpPostedFileBase photoToUpload)
        {
            if (photoToUpload == null || photoToUpload.ContentLength == 0)
            {
                return null;
            }

            string fullPath = null;
            Stopwatch timespan = Stopwatch.StartNew();

            try
            {
                CloudStorageAccount storageAccount = StorageUtils.StorageAccount;

                // Create the blob client and reference the container
                CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();
                CloudBlobContainer container = blobClient.GetContainerReference("images");

                // Create a unique name for the images we are about to upload
                string imageName = String.Format("task-photo-{0}{1}",
                    Guid.NewGuid().ToString(),
                    Path.GetExtension(photoToUpload.FileName));

                // Upload image to Blob Storage
                CloudBlockBlob blockBlob = container.GetBlockBlobReference(imageName);
                blockBlob.Properties.ContentType = photoToUpload.ContentType;
                await blockBlob.UploadFromStreamAsync(photoToUpload.InputStream);

                fullPath = blockBlob.Uri.ToString();

                timespan.Stop();
                // log.TraceApi("Blob Service", "PhotoService.UploadPhoto", timespan.Elapsed, "imagepath={0}", fullPath);
            }
            catch (Exception ex)
            {
                // log.Error(ex, "Error upload photo blob to storage");
                throw;
            }

            return fullPath;
        }

I'm working on this with this tutorial as a guide - https://learn.microsoft.com/en-us/aspnet/aspnet/overview/developing-apps-with-windows-azure/building-real-world-cloud-apps-with-windows-azure/unstructured-blob-storage

Would really appreciate it if someone could let me know how to get this working.

Thanks

Body:
"an object reference is required for the nonstatic field method or property".

You need to init your user as follows:

var user = new ApplicationUser {
    UserName = model.Email,
    Email = model.Email,
    PhotoUrl = await photoService.UploadPhotoAsync(photo)
};

var result = await UserManager.CreateAsync(user, model.Password);

Moreover, I found the tutorial defined a interface IPhotoService and implement it by the PhotoService class, but I found you define the PhotoService in your Register action. In order to leverage dependency injection, I would recommend you follow this tutorial.

Also, I would recommend you move the HttpPostedFileBase photo parameter from the Register method into your RegisterViewModel as follows:

public class RegisterViewModel
{
    [Required]
    [EmailAddress]
    [Display(Name = "Email")]
    public string Email { get; set; }

    [Required]
    [StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)]
    [DataType(DataType.Password)]
    [Display(Name = "Password")]
    public string Password { get; set; }

    [DataType(DataType.Password)]
    [Display(Name = "Confirm password")]
    [Compare("Password", ErrorMessage = "The password and confirmation password do not match.")]
    public string ConfirmPassword { get; set; }

    public HttpPostedFileBase Photo { get; set; }
}

Then, you could init your ApplicationUser instance as follows:

var user = new ApplicationUser {
    UserName = model.Email,
    Email = model.Email,
    PhotoUrl = await photoService.UploadPhotoAsync(model.Photo)
};

And for your register view, you could init the input file as follows:

@using (Html.BeginForm("Register", "Account", FormMethod.Post, new { @class = "form-horizontal", role = "form", enctype = "multipart/form-data" }))
{
   //other properties
   @Html.TextBoxFor(m => m.Photo, new {type = "file"})
}

TEST:

In general, you need to make sure you have set the multipart/form-data for your register form in the register view. And the parameter photoService in the Register method is not null. Also, you need to make sure your container name images exists, or you need to await container.CreateIfNotExistsAsync(). Additionally, you could leverage debugging via Visual Studio and step into your code to narrow this issue, details about how to debug, you could follow here.


问:
Multiple inheritance using namedtuple
I intent to constuct a nested data structure by namedtuple as follows

```<code>from collections import namedtuple
BinaryDay = namedtuple('BinaryDay', ['AM', 'PM'])
QuaternaryDday = namedtuple('QuaternaryDday', ['Moring','Afternoon','Evening','Night'])
OctonaryDay = namedtuple('OctonaryDay', ['Sunrise', 'Sunshine', 'Hotnoon','Sunset', 'Goldenevening', 'Warmevening', 'Darknight', 'Refreshmorning'])
clock_day = OctonaryDay('07:00-10:00', '10:00-13:00', '13:00-16:00', '16:00-19:00', '19:00-22:00', '22:00-01:00','01:00-04:00', '04:00-07:00')
</code>```

Run in console to get such an output:

```<code>In [71]: clock_day._asdict()
Out[71]:
OrderedDict([('Sunrise', '07:00-10:00'),
             ('Sunshine', '10:00-13:00'),
             ('Hotnoon', '13:00-16:00'),
             ('Sunset', '16:00-19:00'),
             ('Goldenevening', '19:00-22:00'),
             ('Warmevening', '22:00-01:00'),
             ('Darknight', '01:00-04:00'),
             ('Refreshmorning', '04:00-07:00')])
</code>```

My desired result is such a data structure.

```<code>{'AM': {'Moring': {'Sunrise': '07:00-10:00',
                   'Sunshine': '10:00-13:00'}
        'Afternoon': {'Hotnoon': '13:00-16:00',
                      'Sunset': '16:00-19:00'},
        },
 'PM': {'Evening': {'Goldenevening': '19:00-22:00',
                    'Warmevening': '22:00-01:00'},
        'Night': {'Darknight': '01:00-04:00',
                  'Refreshmorning': '04:00-07:00'}}}
</code>```

How to accomplish it by multiple Inheritance?

答:
This isn't really a good use case for namedtuple, neither multiple inheritance.

There is a library that might be of use to you though, so pip install python-box and then:

```<code>>>> data = {'AM': {'Moring': {'Sunrise': '07:00-10:00',
...                           'Sunshine': '10:00-13:00'},
...         'Afternoon': {'Hotnoon': '13:00-16:00',
...                       'Sunset': '16:00-19:00'},
...         },
...  'PM': {'Evening': {'Goldenevening': '19:00-22:00',
...                     'Warmevening': '22:00-01:00'},
...         'Night': {'Darknight': '01:00-04:00',
...                   'Refreshmorning': '04:00-07:00'}}}
...
>>> from box import Box
>>> clock_day = Box(data)
>>> clock_day.AM.Afternoon
<Box: {'Hotnoon': '13:00-16:00', 'Sunset': '16:00-19:00'}>
>>> clock_day.AM.Afternoon.Sunset
'16:00-19:00'
</code>```

Title: Multiple inheritance using namedtuple

Body:
I intent to constuct a nested data structure by namedtuple as follows

from collections import namedtuple
BinaryDay = namedtuple('BinaryDay', ['AM', 'PM'])
QuaternaryDday = namedtuple('QuaternaryDday', ['Moring','Afternoon','Evening','Night'])
OctonaryDay = namedtuple('OctonaryDay', ['Sunrise', 'Sunshine', 'Hotnoon','Sunset', 'Goldenevening', 'Warmevening', 'Darknight', 'Refreshmorning'])
clock_day = OctonaryDay('07:00-10:00', '10:00-13:00', '13:00-16:00', '16:00-19:00', '19:00-22:00', '22:00-01:00','01:00-04:00', '04:00-07:00')

Run in console to get such an output:

In [71]: clock_day._asdict()
Out[71]:
OrderedDict([('Sunrise', '07:00-10:00'),
             ('Sunshine', '10:00-13:00'),
             ('Hotnoon', '13:00-16:00'),
             ('Sunset', '16:00-19:00'),
             ('Goldenevening', '19:00-22:00'),
             ('Warmevening', '22:00-01:00'),
             ('Darknight', '01:00-04:00'),
             ('Refreshmorning', '04:00-07:00')])

My desired result is such a data structure.

{'AM': {'Moring': {'Sunrise': '07:00-10:00',
                   'Sunshine': '10:00-13:00'}
        'Afternoon': {'Hotnoon': '13:00-16:00',
                      'Sunset': '16:00-19:00'},
        },
 'PM': {'Evening': {'Goldenevening': '19:00-22:00',
                    'Warmevening': '22:00-01:00'},
        'Night': {'Darknight': '01:00-04:00',
                  'Refreshmorning': '04:00-07:00'}}}

How to accomplish it by multiple Inheritance?

Body:
This isn't really a good use case for namedtuple, neither multiple inheritance.

There is a library that might be of use to you though, so pip install python-box and then:

>>> data = {'AM': {'Moring': {'Sunrise': '07:00-10:00',
...                           'Sunshine': '10:00-13:00'},
...         'Afternoon': {'Hotnoon': '13:00-16:00',
...                       'Sunset': '16:00-19:00'},
...         },
...  'PM': {'Evening': {'Goldenevening': '19:00-22:00',
...                     'Warmevening': '22:00-01:00'},
...         'Night': {'Darknight': '01:00-04:00',
...                   'Refreshmorning': '04:00-07:00'}}}
...
>>> from box import Box
>>> clock_day = Box(data)
>>> clock_day.AM.Afternoon
<Box: {'Hotnoon': '13:00-16:00', 'Sunset': '16:00-19:00'}>
>>> clock_day.AM.Afternoon.Sunset
'16:00-19:00'


问:
display values of array in listview
After watching many tutorials and trying out a lot of code snippets, i am still confused about when and how to use ObservableArray and binding. Trying to get a listview of values from my json array - alert shows them, console displays what i thought it would. the only thing not working is my listview. any assistance by anyone please! posted my javascript and corresponding xml below.

----updated my code. shows an array of six values with one of each in the itemTemplates. how to access every instance? and the keys? need to display key: value pairs and seemingly the keys are missing in the array. anything appreciated!

listview.js

```<code>testJsonArray = {
"results": [{
  "testName": "Multiplizieren",
  "testKlasse": 3,
  "testFach": "Mathematik"
  },
            {
  "testName": "Addieren",
  "testKlasse": 3,
  "testFach": "Mathematik"
  }]
};

function onPageLoaded(args) {
var page = args.object;

var observableArray = require("data/observable-array");
var i = testJsonArray.results.length;

var tests = new observableArray.ObservableArray([]);

while (i--) {
t = testJsonArray.results[i];
tests.push([t.testName, t.testKlasse, t.testFach]);
};

var c = tests.length;
while (c--) {
console.log(c);
};

alert(tests);

page.bindingContext = {myItems: tests};

}

exports.onPageLoaded = onPageLoaded;
</code>```

listview.xml

```<code><Page xmlns="http://www.nativescript.org/tns.xsd" loaded="onPageLoaded">
<ScrollView>
 <ListView id="listview" items="{{ myItems }}">
    <ListView.itemTemplate>
        <StackLayout orientation="horizontal">
        <Label text="{{ $value }}" />
        </StackLayout>
    </ListView.itemTemplate>
</ListView>
</ScrollView>
</Page>
</code>```

答:
Try changing your listview.xml to:</p>

```<code><Page xmlns="http://www.nativescript.org/tns.xsd" loaded="onPageLoaded">
    <ListView id="listview" items="{{ tests }}">
        <ListView.itemTemplate>
            <StackLayout orientation="horizontal">
            <Label text="{{ name }}" />
            </StackLayout>
        </ListView.itemTemplate>
    </ListView>
</Page>
</code>```

Title: display values of array in listview

Body:
After watching many tutorials and trying out a lot of code snippets, i am still confused about when and how to use ObservableArray and binding. Trying to get a listview of values from my json array - alert shows them, console displays what i thought it would. the only thing not working is my listview. any assistance by anyone please! posted my javascript and corresponding xml below.

----updated my code. shows an array of six values with one of each in the itemTemplates. how to access every instance? and the keys? need to display key: value pairs and seemingly the keys are missing in the array. anything appreciated!

listview.js

testJsonArray = {
"results": [{
  "testName": "Multiplizieren",
  "testKlasse": 3,
  "testFach": "Mathematik"
  },
            {
  "testName": "Addieren",
  "testKlasse": 3,
  "testFach": "Mathematik"
  }]
};

function onPageLoaded(args) {
var page = args.object;

var observableArray = require("data/observable-array");
var i = testJsonArray.results.length;

var tests = new observableArray.ObservableArray([]);

while (i--) {
t = testJsonArray.results[i];
tests.push([t.testName, t.testKlasse, t.testFach]);
};

var c = tests.length;
while (c--) {
console.log(c);
};

alert(tests);

page.bindingContext = {myItems: tests};

}

exports.onPageLoaded = onPageLoaded;

listview.xml

<Page xmlns="http://www.nativescript.org/tns.xsd" loaded="onPageLoaded">
<ScrollView>
 <ListView id="listview" items="{{ myItems }}">
    <ListView.itemTemplate>
        <StackLayout orientation="horizontal">

        </StackLayout>
    </ListView.itemTemplate>
</ListView>
</ScrollView>
</Page>

Body:
Try changing your listview.xml to:

<Page xmlns="http://www.nativescript.org/tns.xsd" loaded="onPageLoaded">
    <ListView id="listview" items="{{ tests }}">
        <ListView.itemTemplate>
            <StackLayout orientation="horizontal">
            <Label text="{{ name }}" />
            </StackLayout>
        </ListView.itemTemplate>
    </ListView>
</Page>


问:
TYPO3 RealURL Language Domain Configuration
We have following sceneario:

The website has 3 Domains.

domain.de

domain.eu

domain.com.tr

TYPO3 is already setup for multilanguage and the IDs for the languages are:

default (de) = 0

en = 1

tr = 2

Could somebody give us the proper RealURL configuration for this?

答:
Use below realurl configuration for multiple domain.</p>

```<code><?php
$GLOBALS['TYPO3_CONF_VARS']['EXTCONF']['realurl']=array (
  '_DEFAULT' =>
  array (
    'init' =>
    array (
      'appendMissingSlash' => 'ifNotFile,redirect',
    ),
    'pagePath' =>
    array (
      'rootpage_id' => '1',
    ),
    'fixedPostVars' => array(
    ),
    'fileName' =>
    array (
      'defaultToHTMLsuffixOnPrev' => 0,
      'acceptHTMLsuffix' => 1,
      'index' =>
      array (
        'print' =>
        array (
          'keyValues' =>
          array (
            'type' => 98,
          ),
        ),
      ),
    ),
    'preVars' =>
    array (
      0 =>
      array (
        'GETvar' => 'L',
        'valueMap' =>
        array (
          'en' => '1',
          'tr' => '2'
        ),
        'noMatch' => 'bypass',
      ),
    ),

    'postVarSets' =>array (
      '_DEFAULT' =>array (

      ),
    ),
  ),
);

$TYPO3_CONF_VARS['EXTCONF'] ['realurl'] ['domain.de'] = $TYPO3_CONF_VARS['EXTCONF']['realurl']['_DEFAULT'];
$TYPO3_CONF_VARS['EXTCONF'] ['realurl'] ['domain.de'] ['pagePath'] ['rootpage_id'] = '1'; //Root Page Id

$TYPO3_CONF_VARS['EXTCONF'] ['realurl'] ['domain.eu'] = $TYPO3_CONF_VARS['EXTCONF']['realurl']['_DEFAULT'];
$TYPO3_CONF_VARS['EXTCONF'] ['realurl'] ['domain.eu'] ['pagePath'] ['rootpage_id'] = '169'; //Root Page Id

$TYPO3_CONF_VARS['EXTCONF'] ['realurl'] ['domain.com.tr'] = $TYPO3_CONF_VARS['EXTCONF']['realurl']['_DEFAULT'];
$TYPO3_CONF_VARS['EXTCONF'] ['realurl'] ['domain.com.tr'] ['pagePath'] ['rootpage_id'] = '386'; //Root Page Id
</code>```

Body:
Use below realurl configuration for multiple domain.

<?php
$GLOBALS['TYPO3_CONF_VARS']['EXTCONF']['realurl']=array (
  '_DEFAULT' =>
  array (
    'init' =>
    array (
      'appendMissingSlash' => 'ifNotFile,redirect',
    ),
    'pagePath' =>
    array (
      'rootpage_id' => '1',
    ),
    'fixedPostVars' => array(
    ),
    'fileName' =>
    array (
      'defaultToHTMLsuffixOnPrev' => 0,
      'acceptHTMLsuffix' => 1,
      'index' =>
      array (
        'print' =>
        array (
          'keyValues' =>
          array (
            'type' => 98,
          ),
        ),
      ),
    ),
    'preVars' =>
    array (
      0 =>
      array (
        'GETvar' => 'L',
        'valueMap' =>
        array (
          'en' => '1',
          'tr' => '2'
        ),
        'noMatch' => 'bypass',
      ),
    ),

    'postVarSets' =>array (
      '_DEFAULT' =>array (

      ),
    ),
  ),
);

$TYPO3_CONF_VARS['EXTCONF'] ['realurl'] ['domain.de'] = $TYPO3_CONF_VARS['EXTCONF']['realurl']['_DEFAULT'];
$TYPO3_CONF_VARS['EXTCONF'] ['realurl'] ['domain.de'] ['pagePath'] ['rootpage_id'] = '1'; //Root Page Id

$TYPO3_CONF_VARS['EXTCONF'] ['realurl'] ['domain.eu'] = $TYPO3_CONF_VARS['EXTCONF']['realurl']['_DEFAULT'];
$TYPO3_CONF_VARS['EXTCONF'] ['realurl'] ['domain.eu'] ['pagePath'] ['rootpage_id'] = '169'; //Root Page Id

$TYPO3_CONF_VARS['EXTCONF'] ['realurl'] ['domain.com.tr'] = $TYPO3_CONF_VARS['EXTCONF']['realurl']['_DEFAULT'];
$TYPO3_CONF_VARS['EXTCONF'] ['realurl'] ['domain.com.tr'] ['pagePath'] ['rootpage_id'] = '386'; //Root Page Id


问:
What happen when we do AND operation of 4 byte number with 2 byte number
I am trying to write a piece of code to extract every single byte of data out of a 4 byte integer

after little bit of searching i actually found the code with which this can be achieved , but i am just curious to know why it behaves the way output is created , below is the code

```<code>#include <stdio.h>

int getByte(int x, int n);

void main()
{
    int x = 0xAABBCCDD;
    int n;

    for (n=0; n<=3; n++) {
        printf("byte %d of 0x%X is 0x%X\n",n,x,getByte(x,n));
    }

}

// extract byte n from word x
// bytes numbered from 0 (LSByte) to 3 (MSByte)
int getByte(int x, int n)
{
    return (x >> (n << 3)) & 0xFF;
}
</code>```

Output:

```<code>byte 0 of 0xAABBCCDD is 0xDD
byte 1 of 0xAABBCCDD is 0xCC
byte 2 of 0xAABBCCDD is 0xBB
byte 3 of 0xAABBCCDD is 0xAA
</code>```

the result is self explanatory but why the compiler didn't converted 0xFF into 0x000000FF , since it has to perform AND operation with a 4 byte number and instead generated the output consisting of only 1 byte of data and not 4 byte of data.

答:
The output is a 4-byte number, but printf("%X") doesn't print any leading zero digits.

If you do printf("foo 0x%X bar\n", 0x0000AA) you'll get foo 0xAA bar as output.

Body:
I am trying to write a piece of code to extract every single byte of data out of a 4 byte integer

after little bit of searching i actually found the code with which this can be achieved , but i am just curious to know why it behaves the way output is created , below is the code

#include <stdio.h>

int getByte(int x, int n);

void main()
{
    int x = 0xAABBCCDD;
    int n;

    for (n=0; n<=3; n++) {
        printf("byte %d of 0x%X is 0x%X\n",n,x,getByte(x,n));
    }

}

// extract byte n from word x
// bytes numbered from 0 (LSByte) to 3 (MSByte)
int getByte(int x, int n)
{
    return (x >> (n << 3)) & 0xFF;
}

Output:

byte 0 of 0xAABBCCDD is 0xDD
byte 1 of 0xAABBCCDD is 0xCC
byte 2 of 0xAABBCCDD is 0xBB
byte 3 of 0xAABBCCDD is 0xAA

the result is self explanatory but why the compiler didn't converted 0xFF into 0x000000FF , since it has to perform AND operation with a 4 byte number and instead generated the output consisting of only 1 byte of data and not 4 byte of data.


问:
Django : select all columns when innerjoin using extra without foreignkey
I have two tables and they do not have foreign key or relationship. However, I have to do join and get all columns from both tables. This is the query I've made.

```<code>query = Sms.objects \
        .extra(tables=['product'], where=['product.id=sms.sms_id'])
</code>```

When I printed raw query, I could check it only gets tables from Sms model, not from product model. Is there any way to get columns from product model?

答:
Sounds like you need some raw queries

Obviously you will need to customize your SQL depending on what your needs are and how you want/need to access the data. But here's a very simple example:

```<code>crsr = dbconnection.cursor()
myresults = crsr.execute("SELECT A.*, B.* FROM A,B WHERE A.ID=B.ID")
for myresult in myresults:
    print('{} {} {}'. format(myresult[0], myresult [1], myresult[2]))
crsr.close()
</code>```

The django documentation on this subject is very good. This is a powerful feature of Django. But with great power...

Body:
I have two tables and they do not have foreign key or relationship. However, I have to do join and get all columns from both tables. This is the query I've made.

query = Sms.objects \
        .extra(tables=['product'], where=['product.id=sms.sms_id'])

When I printed raw query, I could check it only gets tables from Sms model, not from product model. Is there any way to get columns from product model?

Body:
Sounds like you need some raw queries

Obviously you will need to customize your SQL depending on what your needs are and how you want/need to access the data. But here's a very simple example:

crsr = dbconnection.cursor()
myresults = crsr.execute("SELECT A.*, B.* FROM A,B WHERE A.ID=B.ID")
for myresult in myresults:
    print('{} {} {}'. format(myresult[0], myresult [1], myresult[2]))
crsr.close()

The django documentation on this subject is very good. This is a powerful feature of Django. But with great power...


问:
C++ modularization framework (like OSGi) ?
I found one SOF http://www.codeproject.com/KB/library/SOF_.aspx ,
Are there anyother stable frameworks for modularization in C++ ?</p>

答:
Apache Celix is an OSGi implementation for C and C++
http://celix.apache.org/</p>


问:
Font color of disabled buttons
How do I find the exact gray color of a font when the IsEnabled property of a button is false?  It appears that there are subtle differences between versions of windows, so I want to get this color from the system to ensure IsEnable colors match.</p>

答:
If you look at the control template here:

http://msdn.microsoft.com/en-us/library/ms753328.aspx

You can see that the foreground colour when the button is disabled is defined as follows:

```<code><Color x:Key="DisabledForegroundColor">#FF888888</Color>
</code>```

You should be able to look up DisabledForegroundColor (this.Resources["DisabledForegroundColor"]) from your code.

OwnerDisplayName: KHW

ContentLicense: CC BY-SA 2.5

Title: Font color of disabled buttons

Body:
If you look at the control template here:

http://msdn.microsoft.com/en-us/library/ms753328.aspx

You can see that the foreground colour when the button is disabled is defined as follows:

<Color x:Key="DisabledForegroundColor">#FF888888</Color>

You should be able to look up DisabledForegroundColor (this.Resources["DisabledForegroundColor"]) from your code.


问:
select box auto select
I want to create auto select box using jQuery or JavaScript.I have four select box. If I choose one select box from every select box, I want to choose auto select for other select box. Now, my design is depending on first select box. How can I do that ? Please help me.

html

```<code><select name="select1" id="select1">
    <option value="1">Fruit</option>
    <option value="2">Animal</option>
    <option value="3">Bird</option>
    <option value="4">Car</option>
</select>

<select name="select2" id="select2">
    <option value="1">Banana</option>
    <option value="1">Apple</option>
    <option value="1">Orange</option>
    <option value="2">Wolf</option>
    <option value="2">Fox</option>
    <option value="2">Bear</option>
    <option value="3">Eagle</option>
    <option value="3">Hawk</option>
    <option value="4">BWM<option>
</select>

<select name="select3" id="select3">
    <option value="1">Fruit</option>
    <option value="2">Animal</option>
    <option value="3">Bird</option>
    <option value="4">Car</option>
</select>
</code>```

javascript

```<code>var $select1 = $( '#select1' ),
    $select2 = $( '#select2' ),
    $select3 = $( '#select3' ),
    $select4 = $( '#select4' ),
$option2 = $select2.find( 'option' ),
$option3 = $select3.find( 'option' ),
$option4 = $select4.find( 'option' );
$select1.on( 'change', function() {
$select2.html( $option2.filter( '[value="' + this.value + '"]' ) ),
$select3.html( $option3.filter( '[value="' + this.value + '"]' ) ),
$select4.html( $option4.filter( '[value="' + this.value + '"]' ) );
} ).trigger( 'change' );
</code>```

答:
for me I think it's a bad thing to duplicate the options value .. so you need to use data attribute it will help you to get the right value in the next selection .. you can use the next code

$(document).ready(function(){
  $('#select1').on('change' , function(){
    var getVal = $(this).val();  // get value from the 1st select
    $('#select2 option').hide(); // hide all option for the 2nd select
    $('#select2 option[data-value="'+getVal+'"]').show().first().prop('selected' , true);  // show the options which data-value = the first select value and select the 1st one of them
    $('#select3 option').hide();  // while you don't have duplicated value on select3 you can just use value instead of using `data` attribute
    $('#select3 option[value="'+getVal+'"]').show().prop('selected' , true);
  }).change();
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select name="select1" id="select1">
      <option value="1">Fruit</option>
      <option value="2">Animal</option>
      <option value="3">Bird</option>
      <option value="4">Car</option>
  </select>

  <select name="select2" id="select2">
      <option data-value="1" value="1">Banana</option>
      <option data-value="1" value="2">Apple</option>
      <option data-value="1" value="3">Orange</option>
      <option data-value="2" value="4">Wolf</option>
      <option data-value="2" value="5">Fox</option>
      <option data-value="2" value="6">Bear</option>
      <option data-value="2" value="7">Eagle</option>
      <option data-value="3" value="8">Hawk</option>
      <option data-value="4" value="9">BWM<option>
  </select>

<select name="select3" id="select3">
  <option value="1">Fruit</option>
  <option value="2">Animal</option>
  <option value="3">Bird</option>
  <option value="4">Car</option>
</select></code>```

Explanation:  What code above doing When change select1

get the value selected

hide all options on 2nd select

show options which data-value attribute equal the value selected from the 1st select

select the first one of them

while you don't have duplicated values on select3 but if you've duplicated values you can use data attribute which used with select2

hide all options on 3rd select

show option which [value] attribute equal the value selected from the 1st select and select it

Title: select box auto select

Body:
I want to create auto select box using jQuery or JavaScript.I have four select box. If I choose one select box from every select box, I want to choose auto select for other select box. Now, my design is depending on first select box. How can I do that ? Please help me.

html

<select name="select1" id="select1">
    <option value="1">Fruit</option>
    <option value="2">Animal</option>
    <option value="3">Bird</option>
    <option value="4">Car</option>
</select>

<select name="select2" id="select2">
    <option value="1">Banana</option>
    <option value="1">Apple</option>
    <option value="1">Orange</option>
    <option value="2">Wolf</option>
    <option value="2">Fox</option>
    <option value="2">Bear</option>
    <option value="3">Eagle</option>
    <option value="3">Hawk</option>
    <option value="4">BWM<option>
</select>

<select name="select3" id="select3">
    <option value="1">Fruit</option>
    <option value="2">Animal</option>
    <option value="3">Bird</option>
    <option value="4">Car</option>
</select>

javascript

var $select1 = $( '#select1' ),
    $select2 = $( '#select2' ),
    $select3 = $( '#select3' ),
    $select4 = $( '#select4' ),
$option2 = $select2.find( 'option' ),
$option3 = $select3.find( 'option' ),
$option4 = $select4.find( 'option' );
$select1.on( 'change', function() {
$select2.html( $option2.filter( '[value="' + this.value + '"]' ) ),
$select3.html( $option3.filter( '[value="' + this.value + '"]' ) ),
$select4.html( $option4.filter( '[value="' + this.value + '"]' ) );
} ).trigger( 'change' );

Body:
for me I think it's a bad thing to duplicate the options value .. so you need to use data attribute it will help you to get the right value in the next selection .. you can use the next code

$(document).ready(function(){
  $('#select1').on('change' , function(){
    var getVal = $(this).val();  // get value from the 1st select
    $('#select2 option').hide(); // hide all option for the 2nd select
    $('#select2 option[data-value="'+getVal+'"]').show().first().prop('selected' , true);  // show the options which data-value = the first select value and select the 1st one of them
    $('#select3 option').hide();  // while you don't have duplicated value on select3 you can just use value instead of using `data` attribute
    $('#select3 option[value="'+getVal+'"]').show().prop('selected' , true);
  }).change();
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select name="select1" id="select1">
      <option value="1">Fruit</option>
      <option value="2">Animal</option>
      <option value="3">Bird</option>
      <option value="4">Car</option>
  </select>

  <select name="select2" id="select2">
      <option data-value="1" value="1">Banana</option>
      <option data-value="1" value="2">Apple</option>
      <option data-value="1" value="3">Orange</option>
      <option data-value="2" value="4">Wolf</option>
      <option data-value="2" value="5">Fox</option>
      <option data-value="2" value="6">Bear</option>
      <option data-value="2" value="7">Eagle</option>
      <option data-value="3" value="8">Hawk</option>
      <option data-value="4" value="9">BWM<option>
  </select>

<select name="select3" id="select3">
  <option value="1">Fruit</option>
  <option value="2">Animal</option>
  <option value="3">Bird</option>
  <option value="4">Car</option>
</select>

Explanation:  What code above doing When change select1

get the value selected

hide all options on 2nd select

show options which data-value attribute equal the value selected from the 1st select

select the first one of them

while you don't have duplicated values on select3 but if you've duplicated values you can use data attribute which used with select2

hide all options on 3rd select

show option which [value] attribute equal the value selected from the 1st select and select it


问:
How do I use the new C++17 execution policies?
I was reading through the std::algorithm documentation at cppreference.com and I noticed a C++17 tag on a lot of cool things I haven't used yet. What got my attention most was the new execution policies. What I gathered from reading about them is that I can make any for_each loop I want multi-threaded just by specifying an execution policy.

For example, I have a program which outputs an image with a 2D graphic on it.

```<code>int main(){
    std::for_each(
        img.buffer().begin(),
        img.buffer().end(),
        renderer(
            {-0.5, 0.0, 2.666, 2.0, M_PI / 2.0, 0.0},
            img,
            16
        )
    );
    fout << img;
}
</code>```

If I want to make this program multi-threaded I should be able to do it with one line.

```<code>int main(){
    std::for_each(
        std::execution::par_unseq, // c++17 feature
        img.buffer().begin(),
        img.buffer().end(),
        renderer(
            {-0.5, 0.0, 2.666, 2.0, M_PI / 2.0, 0.0},
            img,
            16
        )
    );
    fout << img;
}
</code>```

However when I first tried this (with g++ -std=c++17) I got an error telling me that ‘std::execution’ has not been declared, so I tried adding #include <execution> but it says execution: No such file or directory. I've also tried #include<experimental/algorithm> instead of #include<algorithm> but I get the same result. How do I use this new feature?

答:
If you're using g++ then you can try the non-standard extension:

https://gcc.gnu.org/onlinedocs/libstdc++/manual/parallel_mode.html

Body:
I was reading through the std::algorithm documentation at cppreference.com and I noticed a C++17 tag on a lot of cool things I haven't used yet. What got my attention most was the new execution policies. What I gathered from reading about them is that I can make any for_each loop I want multi-threaded just by specifying an execution policy.

For example, I have a program which outputs an image with a 2D graphic on it.

int main(){
    std::for_each(
        img.buffer().begin(),
        img.buffer().end(),
        renderer(
            {-0.5, 0.0, 2.666, 2.0, M_PI / 2.0, 0.0},
            img,
            16
        )
    );
    fout << img;
}

If I want to make this program multi-threaded I should be able to do it with one line.

int main(){
    std::for_each(
        std::execution::par_unseq, // c++17 feature
        img.buffer().begin(),
        img.buffer().end(),
        renderer(
            {-0.5, 0.0, 2.666, 2.0, M_PI / 2.0, 0.0},
            img,
            16
        )
    );
    fout << img;
}

However when I first tried this (with g++ -std=c++17) I got an error telling me that ‘std::execution’ has not been declared, so I tried adding #include <execution> but it says execution: No such file or directory. I've also tried #include<experimental/algorithm> instead of #include<algorithm> but I get the same result. How do I use this new feature?


答:
The compiler did convert 0xFF to 0x000000FF. Since the value is an integer constant, 0xFF gets converted internally to a 32-bit value (assuming that your platform has a 32-bit int).

Note that the values you get back, i.e. 0xDD, 0xCC, 0xBB, and 0xAA, are also ints, so they have leading zeros as well, so you actually get 0x000000DD, 0x000000CC, and so on. Leading zeros do not get printed automatically, though, so if you wish to see them, you'd need to change the format string to request leading zeros to be included:

```<code>for (n=0; n<=3; n++) {
    printf("byte %d of 0x%08X is 0x%08X\n", n, x, getByte(x,n));
}
</code>```

Demo.

Title: What happen when we do AND operation of 4 byte number with 2 byte number

Body:
The compiler did convert 0xFF to 0x000000FF. Since the value is an integer constant, 0xFF gets converted internally to a 32-bit value (assuming that your platform has a 32-bit int).

Note that the values you get back, i.e. 0xDD, 0xCC, 0xBB, and 0xAA, are also ints, so they have leading zeros as well, so you actually get 0x000000DD, 0x000000CC, and so on. Leading zeros do not get printed automatically, though, so if you wish to see them, you'd need to change the format string to request leading zeros to be included:

for (n=0; n<=3; n++) {
    printf("byte %d of 0x%08X is 0x%08X\n", n, x, getByte(x,n));
}

Demo.


问:
How to configure bazel to build C++ app using tensorflow installed in python site-packages
This question is primarily about using bazel to develop a C++ application that uses a 3rd party package of headers and built libraries, with the headers accessible as system includes, i.e. using angle brackets to specify the headers: #include

I expect this is a common use case but after an hour of searching documentation, I still don't see an obvious approach to try.

My particular use case is to use tensorflow 1.4 built from sources. Tensorflow was installed at this location on my system:

~/.pyenv/versions/3.6.3/envs/tensorflow14py36/lib/python3.6/site-packages/tensorflow

How do I modify my bazel BUILD and/or WORKSPACE so that I can compile (and eventually link) my application that includes tensorflow headers such as:

#include <tensorflow/core/public/session.h>

答:
I've found a related question: How to build and use Google Tensorflow It appears the recommended solution closest to my expectations is to simply copy the headers and libraries to /usr/local/. I'd prefer a different solution, but for now, I am successfully using that approach.

I've also filed an issue with the Tensorflow team: https://github.com/tensorflow/tensorflow/issues/15290


问:
Flask app can't find google module

I'm using a virtual environment to run a flask app. When I run pip freeze, I get the following:

```<code>google-api-core==0.1.1
google-auth==1.2.1
google-cloud-core==0.28.0
google-cloud-speech==0.30.0
google-gax==0.15.16
googleapis-common-protos==1.5.3
</code>```

However, during run time, I get the following error:

```<code>    from google.cloud import speech
ModuleNotFoundError: No module named 'google'
</code>```

I'm using the google speech APIs. They work just fine when I run them locally. I don't understand why the app can't find the modules even though they're listed as installed. Can someone suggest a fix? I've tried doing pip install google, and it downloaded a bunch of other stuff, but still no fix.

答: Well, removing the virtual environment and reinstalling all the dependencies worked. </p>

Title: Flask app can't find google module

Body:
I'm using a virtual environment to run a flask app. When I run pip freeze, I get the following:

google-api-core==0.1.1
google-auth==1.2.1
google-cloud-core==0.28.0
google-cloud-speech==0.30.0
google-gax==0.15.16
googleapis-common-protos==1.5.3

However, during run time, I get the following error:

    from google.cloud import speech
ModuleNotFoundError: No module named 'google'

I'm using the google speech APIs. They work just fine when I run them locally. I don't understand why the app can't find the modules even though they're listed as installed. Can someone suggest a fix? I've tried doing pip install google, and it downloaded a bunch of other stuff, but still no fix.


问:
Display border line in <ol> without duplicating css

Currently, i am trying to use  to create a grid view. I am able to have my desire output that display border only on the inside of the outer box. But this is achieve using duplicated style rules. So i hope someone could advice me a better way to achieve the same result. Here is the image of the result
Grid selector</p>

<p>       </p>

```<code>    .ui-draggable, .ui-droppable {
        background-position: top;
    }
    .ui-state-default, .ui-widget-content .ui-state-default, .ui-widget-header .ui-state-default, .ui-button, html .ui-button.ui-state-disabled:hover, html .ui-button.ui-state-disabled:active
    {
        border-bottom: 1px solid red;
        border-left: 1px solid red;
        background: #fff;
        font-weight: normal;

    }

    .ui-state-default-left, html .ui-button.ui-state-disabled:active
    {
        border-left: none;
        border-bottom: 1px solid red;
        background: #fff;
        font-weight: normal;
    }

    .ui-state-default-bottom, html .ui-button.ui-state-disabled:active
    {
        border-left: 1px solid red;
        border-bottom: none;
        background: #fff;
        font-weight: normal;
    }

    .ui-state-default-left-bottom, html .ui-button.ui-state-disabled:active
    {
        border-left: none;
        border-bottom: none;
        background: #fff;
        font-weight: normal;
    }

    #selectable .ui-selecting { background: #FECA40; }
    #selectable .ui-selected { background: #F39814; color: white; }
    #selectable { list-style-type: none; margin: 0; padding: 0; width: 20rem; }
    #selectable li { padding: 0.3rem; float: left; width: 2rem; height: 2rem; font-size: 1.5rem; text-align: center; }

    </style>

    <ol id="selectable">
              <li class="ui-state-default-left">01</li>
              <li class="ui-state-default">02</li>
              <li class="ui-state-default">03</li>
              <li class="ui-state-default">04</li>
              <li class="ui-state-default">05</li>
              <li class="ui-state-default">06</li>
              <li class="ui-state-default">07</li>
              <li class="ui-state-default-left">08</li>
              <li class="ui-state-default">09</li>
              <li class="ui-state-default">10</li>
              <li class="ui-state-default">11</li>
              <li class="ui-state-default">12</li>
              <li class="ui-state-default">13</li>
              <li class="ui-state-default">14</li>
              <li class="ui-state-default-left">15</li>
              <li class="ui-state-default">16</li>
              <li class="ui-state-default">17</li>
              <li class="ui-state-default">18</li>
              <li class="ui-state-default">19</li>
              <li class="ui-state-default">20</li>
              <li class="ui-state-default">21</li>
              <li class="ui-state-default-left">22</li>
              <li class="ui-state-default">23</li>
              <li class="ui-state-default">24</li>
              <li class="ui-state-default">25</li>
              <li class="ui-state-default">26</li>
              <li class="ui-state-default">27</li>
              <li class="ui-state-default">28</li>
              <li class="ui-state-default-left">29</li>
              <li class="ui-state-default">30</li>
              <li class="ui-state-default">31</li>
              <li class="ui-state-default">32</li>
              <li class="ui-state-default">33</li>
              <li class="ui-state-default">34</li>
              <li class="ui-state-default">35</li>
              <li class="ui-state-default-left">36</li>
              <li class="ui-state-default">37</li>
              <li class="ui-state-default">38</li>
              <li class="ui-state-default">39</li>
              <li class="ui-state-default">40</li>
              <li class="ui-state-default">41</li>
              <li class="ui-state-default">42</li>
              <li class="ui-state-default-left-bottom">43</li>
              <li class="ui-state-default-bottom">44</li>
              <li class="ui-state-default-bottom">45</li>
              <li class="ui-state-default-bottom">46</li>
              <li class="ui-state-default-bottom">47</li>
              <li class="ui-state-default-bottom">48</li>
              <li class="ui-state-default-bottom">49</li>
    </ol>
</code>```

答:
See this, there are no classes used and reduced the stylesheet size.

ol {
  width: 280px;
  height: 280px;
  float: left;
  list-style: none;
  padding: 0;
  margin: 0;
}

li {
  width: 40px;
  height: 40px;
  float: left;
  box-sizing: border-box;
  line-height: 40px;
  text-align: center;
  border-right: solid 1px red;
  border-bottom: solid 1px red;
}

li:nth-child(7n) {
  border-right: none;
}

li:nth-child(43),
li:nth-child(44),
li:nth-child(45),
li:nth-child(46),
li:nth-child(47),
li:nth-child(48),
li:nth-child(49) {
  border-bottom: none;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><ol>
  <li>01</li>
  <li>02</li>
  <li>03</li>
  <li>04</li>
  <li>05</li>
  <li>06</li>
  <li>07</li>
  <li>08</li>
  <li>09</li>
  <li>10</li>
  <li>11</li>
  <li>12</li>
  <li>13</li>
  <li>14</li>
  <li>15</li>
  <li>16</li>
  <li>17</li>
  <li>18</li>
  <li>19</li>
  <li>20</li>
  <li>21</li>
  <li>22</li>
  <li>23</li>
  <li>24</li>
  <li>25</li>
  <li>26</li>
  <li>27</li>
  <li>28</li>
  <li>29</li>
  <li>30</li>
  <li>31</li>
  <li>32</li>
  <li>33</li>
  <li>34</li>
  <li>35</li>
  <li>36</li>
  <li>37</li>
  <li>38</li>
  <li>39</li>
  <li>40</li>
  <li>41</li>
  <li>42</li>
  <li>43</li>
  <li>44</li>
  <li>45</li>
  <li>46</li>
  <li>47</li>
  <li>48</li>
  <li>49</li>
</ol></code>```

Body:
Currently, i am trying to use  to create a grid view. I am able to have my desire output that display border only on the inside of the outer box. But this is achieve using duplicated style rules. So i hope someone could advice me a better way to achieve the same result. Here is the image of the result
Grid selector

    .ui-draggable, .ui-droppable {
        background-position: top;
    }
    .ui-state-default, .ui-widget-content .ui-state-default, .ui-widget-header .ui-state-default, .ui-button, html .ui-button.ui-state-disabled:hover, html .ui-button.ui-state-disabled:active
    {
        border-bottom: 1px solid red;
        border-left: 1px solid red;
        background: #fff;
        font-weight: normal;

    }

    .ui-state-default-left, html .ui-button.ui-state-disabled:active
    {
        border-left: none;
        border-bottom: 1px solid red;
        background: #fff;
        font-weight: normal;
    }

    .ui-state-default-bottom, html .ui-button.ui-state-disabled:active
    {
        border-left: 1px solid red;
        border-bottom: none;
        background: #fff;
        font-weight: normal;
    }

    .ui-state-default-left-bottom, html .ui-button.ui-state-disabled:active
    {
        border-left: none;
        border-bottom: none;
        background: #fff;
        font-weight: normal;
    }

    #selectable .ui-selecting { background: #FECA40; }
    #selectable .ui-selected { background: #F39814; color: white; }
    #selectable { list-style-type: none; margin: 0; padding: 0; width: 20rem; }
    #selectable li { padding: 0.3rem; float: left; width: 2rem; height: 2rem; font-size: 1.5rem; text-align: center; }

    </style>

01

02

03

04

05

06

07

08

09

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

Body:
See this, there are no classes used and reduced the stylesheet size.

ol {
  width: 280px;
  height: 280px;
  float: left;
  list-style: none;
  padding: 0;
  margin: 0;
}

li {
  width: 40px;
  height: 40px;
  float: left;
  box-sizing: border-box;
  line-height: 40px;
  text-align: center;
  border-right: solid 1px red;
  border-bottom: solid 1px red;
}

li:nth-child(7n) {
  border-right: none;
}

li:nth-child(43),
li:nth-child(44),
li:nth-child(45),
li:nth-child(46),
li:nth-child(47),
li:nth-child(48),
li:nth-child(49) {
  border-bottom: none;
}

<ol>
  <li>01</li>
  <li>02</li>
  <li>03</li>
  <li>04</li>
  <li>05</li>
  <li>06</li>
  <li>07</li>
  <li>08</li>
  <li>09</li>
  <li>10</li>
  <li>11</li>
  <li>12</li>
  <li>13</li>
  <li>14</li>
  <li>15</li>
  <li>16</li>
  <li>17</li>
  <li>18</li>
  <li>19</li>
  <li>20</li>
  <li>21</li>
  <li>22</li>
  <li>23</li>
  <li>24</li>
  <li>25</li>
  <li>26</li>
  <li>27</li>
  <li>28</li>
  <li>29</li>
  <li>30</li>
  <li>31</li>
  <li>32</li>
  <li>33</li>
  <li>34</li>
  <li>35</li>
  <li>36</li>
  <li>37</li>
  <li>38</li>
  <li>39</li>
  <li>40</li>
  <li>41</li>
  <li>42</li>
  <li>43</li>
  <li>44</li>
  <li>45</li>
  <li>46</li>
  <li>47</li>
  <li>48</li>
  <li>49</li>
</ol>


问:
Pythonic way of sum of dot product of two list of lists
How can this be done elegantly (Pythonic way)

You have two matrices A and B represented each by a list of lists.

You would like to calculate the overall sum over the matrix of element-wise product of A and B.

sample code:

```<code>sum = 0
nrows = len(A)
ncols = len(A[0])
for i in range(nrows):
    for j in range(ncols):
        sum += A[i][j]*B[i][j]

# interested finally in the value of sum
# return sum
</code>```

for example if

A=[[1,2,3],[3,4,5]]

and

B=[[3,2,2],[1,1,1]]

the result is :

1*3 + 2*2 + 3*2 + 3*1 + 4*1 + 5*1 = 25

答:
You could also try something like this (assuming matrices are 2D):

```<code>import itertools

A=[[1,2,3],[3,4,5]]
B=[[3,2,2],[1,1,1]]

def flatten(lst):
    return itertools.chain.from_iterable(lst)

>>> print(sum(x * y for x, y in zip(flatten(A), flatten(B))))
25
</code>```

Or even:

```<code>>>> print(sum(x * y for x, y in zip(sum(A, []), sum(B, []))))
25
</code>```

Body:
How can this be done elegantly (Pythonic way)

You have two matrices A and B represented each by a list of lists.

You would like to calculate the overall sum over the matrix of element-wise product of A and B.

sample code:

sum = 0
nrows = len(A)
ncols = len(A[0])
for i in range(nrows):
    for j in range(ncols):
        sum += A[i][j]*B[i][j]

# interested finally in the value of sum
# return sum

for example if

A=[[1,2,3],[3,4,5]]

and

B=[[3,2,2],[1,1,1]]

the result is :

1*3 + 2*2 + 3*2 + 3*1 + 4*1 + 5*1 = 25

Body:
You could also try something like this (assuming matrices are 2D):

import itertools

A=[[1,2,3],[3,4,5]]
B=[[3,2,2],[1,1,1]]

def flatten(lst):
    return itertools.chain.from_iterable(lst)

>>> print(sum(x * y for x, y in zip(flatten(A), flatten(B))))
25

Or even:

>>> print(sum(x * y for x, y in zip(sum(A, []), sum(B, []))))
25