问:
How to pass a cmdlet as parameter value in .NET
How can I pass a cmdlet as a parameter value in C#? In other words, what would the the .NET equivalent of the following be?

```<code>PS> Get-Content -Path (Some-Cmdlet)
</code>```

I have the following code:

```<code>var ps = PowerShell.Create(session);
ps.AddComand("Get-Content").AddParameter("Path", "(Some-Cmdlet)");
</code>```

However, the string "(Some-Cmdlet)" gets passed verbatim. It is not interpreted. I have also tried:

```<code>var ps = PowerShell.Create(session);
var cmd = new Command("Some-Cmdlet");
ps.AddComand("Get-Content").AddParameter("Path", cmd);
</code>```

Unfortunately, it gives the same result. It seems to be calling ToString() on the Command object, rather than evaluating it.

答:
It appears that there is no way to have a parameter value evaluated. From what I can discover, you need to use AddScript instead of AddCommand. It's also necessary to alter the expression, from what you would write on the commandline, if you want to have parameters.

In my case, I used the form:

```<code>var flag = "xyz";
ps.AddScript(@"param([string]$Flag) Get-Content -Path (Some-Cmdlet -Flag $Flag)")
    .AddParameter("Flag", flag);
</code>```

There may be a better way, but this works.

Body:
How can I pass a cmdlet as a parameter value in C#? In other words, what would the the .NET equivalent of the following be?

PS> Get-Content -Path (Some-Cmdlet)

I have the following code:

var ps = PowerShell.Create(session);
ps.AddComand("Get-Content").AddParameter("Path", "(Some-Cmdlet)");

However, the string "(Some-Cmdlet)" gets passed verbatim. It is not interpreted. I have also tried:

var ps = PowerShell.Create(session);
var cmd = new Command("Some-Cmdlet");
ps.AddComand("Get-Content").AddParameter("Path", cmd);

Unfortunately, it gives the same result. It seems to be calling ToString() on the Command object, rather than evaluating it.

Body:
It appears that there is no way to have a parameter value evaluated. From what I can discover, you need to use AddScript instead of AddCommand. It's also necessary to alter the expression, from what you would write on the commandline, if you want to have parameters.

In my case, I used the form:

var flag = "xyz";
ps.AddScript(@"param([string]$Flag) Get-Content -Path (Some-Cmdlet -Flag $Flag)")
    .AddParameter("Flag", flag);

There may be a better way, but this works.


来源: stackexchange

问:
Ajax doesn't render SelectManyBox correctly, its rendered after page referesh
I am trying to render a h:selectManyBoxList upon a selectOneMenu choice, so the data of the selectManyBox comes when user selects a item from selectOneMenu

here is my code:

```<code><h:panelGroup rendered="#{exportManager.htmlExportSelected}">
                                    <div class="col-sm-7">
                                        <p:selectOneMenu styleClass="form-control" immediate="true"
                                            value="#{exportManager.selectedTemplateObjectTypeId}"
                                            required="true">
                                            <f:selectItems value="#{templateManager.templateDetails}"
                                                var="oneDetail"
                                                itemLabel="#{oneDetail.childObjectType.title}"
                                                itemValue="#{oneDetail.childObjectType.objectTypeId}" />
                                            <f:ajax event="change" render="multi-select-property" ></f:ajax>
                                        </p:selectOneMenu>
                                    </div>

                                    <div class="form-group">
                            <label></label>
                        </div>

                                    <div align="right" class="form-group">
                                        <div class="col-sm-12">
                                            <div class="col-sm-6" align="right">
                                                <b><label class="control-label">#{uiLabelManager.nonSelected}</label></b>
                                            </div>
                                            <div class="col-sm-4" align="center">
                                                <b><label class="control-label">#{uiLabelManager.selected}</label></b>
                                            </div>
                                        </div>
                                    </div>
                                    <label class="col-sm-4 control-label"></label>

                                    <div align="right" class="form-group"  >
                                        <h:panelGroup id="many-list-box" rendered="#{not empty exportManager.selectedObjects}">
<div class="col-sm-6" style="float:left">
                                            <h:selectManyListbox id="multi-select-property"
                                                value="#{exportManager.selectedObjects}"
                                                styleClass="form-control multi-select" immediate="true"
                                                style="width:250px;height:250px">
                                                <f:selectItems value="#{exportManager.loadObjectNodes()}"
                                                    var="oneDetail" itemLabel="#{oneDetail.title}"
                                                    itemValue="#{oneDetail.objectId}" />
                                                <p:ajax event="change" process="@this" execute="@this" partialSubmit="true"
                                                update=":content-form:multi-select-property"
                                                    render="@form"></p:ajax>
                                            </h:selectManyListbox>

                                            <h:selectOneMenu styleClass="form-control" style="width:250px"
                                                value="#{exportManager.selectedObjects}" required="true">
                                                <f:selectItems value="#{exportManager.selectedObjects}" />
                                            </h:selectOneMenu>
</div>
                                        </h:panelGroup>
                                    </div>
                                </h:panelGroup>
</code>```

here is a screen shot before I select a item from selectOneMenu

here is the screen shot after I select a item from selectOneMenu

as you can see the one newly rendered grayed-out box is the one with new data and the correctly render selectManyBox was also there below,so when I referesh page this happens, which you can see in image:

<img src="https://i.stack.imgur.com/rgNL6.png" alt="after page referesh selectManyBox is rendered correctly">

I can't find a way to fix this, only page refresh fixes this so I have to add

```<code>onchange="submit()"
</code>```

in the selectOneMenu this reloads whole page which is not user friendly and time consuming a bit as well.

答:
It appears that you're using a CSS or JS library to style your <h:selectManyListbox... which is rewriting the element in the DOM. You'll need to execute the necessary JS to stylize the <h:selectManyListbox... after the DOM has been updated with the re-rendered component from the AJAX call.

You may be able to leverage the oncomplete attribute of PrimeFaces
 to accomplish this.

ContentLicense: CC BY-SA 3.0

Body:
I am trying to render a h:selectManyBoxList upon a selectOneMenu choice, so the data of the selectManyBox comes when user selects a item from selectOneMenu

here is my code:

<h:panelGroup rendered="#{exportManager.htmlExportSelected}">

                                            <f:selectItems value="#{templateManager.templateDetails}"
                                                var="oneDetail"
                                                itemLabel="#{oneDetail.childObjectType.title}"
                                                itemValue="#{oneDetail.childObjectType.objectTypeId}" />
                                            <f:ajax event="change" render="multi-select-property" ></f:ajax>

                                                #{uiLabelManager.nonSelected}

                                                #{uiLabelManager.selected}

                                        <h:panelGroup id="many-list-box" rendered="#{not empty exportManager.selectedObjects}">

                                            <h:selectManyListbox id="multi-select-property"
                                                value="#{exportManager.selectedObjects}"
                                                styleClass="form-control multi-select" immediate="true"
                                                style="width:250px;height:250px">
                                                <f:selectItems value="#{exportManager.loadObjectNodes()}"
                                                    var="oneDetail" itemLabel="#{oneDetail.title}"
                                                    itemValue="#{oneDetail.objectId}" />

                                            </h:selectManyListbox>

                                            <h:selectOneMenu styleClass="form-control" style="width:250px"
                                                value="#{exportManager.selectedObjects}" required="true">
                                                <f:selectItems value="#{exportManager.selectedObjects}" />
                                            </h:selectOneMenu>

                                        </h:panelGroup>

                                </h:panelGroup>

here is a screen shot before I select a item from selectOneMenu

here is the screen shot after I select a item from selectOneMenu

as you can see the one newly rendered grayed-out box is the one with new data and the correctly render selectManyBox was also there below,so when I referesh page this happens, which you can see in image:

<img src="https://i.stack.imgur.com/rgNL6.png" alt="after page referesh selectManyBox is rendered correctly">

I can't find a way to fix this, only page refresh fixes this so I have to add

onchange="submit()"

in the selectOneMenu this reloads whole page which is not user friendly and time consuming a bit as well.

Body:
It appears that you're using a CSS or JS library to style your <h:selectManyListbox... which is rewriting the element in the DOM. You'll need to execute the necessary JS to stylize the <h:selectManyListbox... after the DOM has been updated with the re-rendered component from the AJAX call.

You may be able to leverage the oncomplete attribute of PrimeFaces <p:ajax/> to accomplish this.


问:
Choose and test java decompiler
Now I'm trying to find the best java decompiler, I found these:

http://java.decompiler.free.fr/

http://www.reversed-java.com/fernflower/

http://dj.navexpress.com/

http://cavaj-java-decompiler.en.softonic.com/

With these decompilers I handle byte code of this class:

```<code>public class ss
{
public static void main(String args[])
{
  try{
   System.out.println("try");

  }
  catch(Exception e)
  {
   System.out.println("catch");
  }
  finally
  {System.out.println("finally");}
}
}
</code>```

and I got the following results:

fernflower:

```<code>public class ss {

   public static void main(String[] var0) {
      try {
         System.out.println("try");
      } catch (Exception var5) {
         System.out.println("catch");
      } finally {
         System.out.println("finally");
      }

   }
}
</code>```

DJ Java Decompiler:

```<code>import java.io.PrintStream;

public class ss
{

    public ss()
    {
    }

    public static void main(String args[])
    {
        System.out.println("try");
        System.out.println("finally");
        break MISSING_BLOCK_LABEL_50;
        Exception exception;
        exception;
        System.out.println("catch");
        System.out.println("finally");
        break MISSING_BLOCK_LABEL_50;
        Exception exception1;
        exception1;
        System.out.println("finally");
        throw exception1;
    }
}
</code>```

cavaj:

```<code>import java.io.PrintStream;

public class ss
{

    public ss()
    {
    }

    public static void main(String args[])
    {
        System.out.println("try");
        System.out.println("finally");
        break MISSING_BLOCK_LABEL_50;
        Exception exception;
        exception;
        System.out.println("catch");
        System.out.println("finally");
        break MISSING_BLOCK_LABEL_50;
        Exception exception1;
        exception1;
        System.out.println("finally");
        throw exception1;
    }
}
</code>```

http://java.decompiler.free.fr/:

```<code>import java.io.PrintStream;
public class ss
{
  public static void main(String[] paramArrayOfString)
  {
    try
    {
      System.out.println("try");
    }
    catch (Exception localException)
    {
      System.out.println("catch");
    }
    finally {
      System.out.println("finally");
    }
  }
}
</code>```

I see that the best result in decompiler: http://java.decompiler.free.fr/

To test, I wrote very simple code. What do you think, what code to write to test decompilers? Maybe the idea is to better than a try{} catch(){} finally{}?

答:
I have been using http://java.decompiler.free.fr/ for a long time now and found it to be the best one. In particular I used it to decompile a third-party jar and I was able to modify the source code as well with it.

Its easy to use and the UI is also neat and clean.

Update: Java Decompiler is no longer available on http://java.decompiler.free.fr/. It has new link http://jd.benow.ca/ from where it can be downloaded.

Title: Choose and test java decompiler

Body:
Now I'm trying to find the best java decompiler, I found these:

http://java.decompiler.free.fr/

http://www.reversed-java.com/fernflower/

http://dj.navexpress.com/

http://cavaj-java-decompiler.en.softonic.com/

With these decompilers I handle byte code of this class:

public class ss
{
public static void main(String args[])
{
  try{
   System.out.println("try");

  }
  catch(Exception e)
  {
   System.out.println("catch");
  }
  finally
  {System.out.println("finally");}
}
}

and I got the following results:

fernflower:

public class ss {

   public static void main(String[] var0) {
      try {
         System.out.println("try");
      } catch (Exception var5) {
         System.out.println("catch");
      } finally {
         System.out.println("finally");
      }

   }
}

DJ Java Decompiler:

import java.io.PrintStream;

public class ss
{

    public ss()
    {
    }

    public static void main(String args[])
    {
        System.out.println("try");
        System.out.println("finally");
        break MISSING_BLOCK_LABEL_50;
        Exception exception;
        exception;
        System.out.println("catch");
        System.out.println("finally");
        break MISSING_BLOCK_LABEL_50;
        Exception exception1;
        exception1;
        System.out.println("finally");
        throw exception1;
    }
}

cavaj:

import java.io.PrintStream;

public class ss
{

    public ss()
    {
    }

    public static void main(String args[])
    {
        System.out.println("try");
        System.out.println("finally");
        break MISSING_BLOCK_LABEL_50;
        Exception exception;
        exception;
        System.out.println("catch");
        System.out.println("finally");
        break MISSING_BLOCK_LABEL_50;
        Exception exception1;
        exception1;
        System.out.println("finally");
        throw exception1;
    }
}

http://java.decompiler.free.fr/:

import java.io.PrintStream;
public class ss
{
  public static void main(String[] paramArrayOfString)
  {
    try
    {
      System.out.println("try");
    }
    catch (Exception localException)
    {
      System.out.println("catch");
    }
    finally {
      System.out.println("finally");
    }
  }
}

I see that the best result in decompiler: http://java.decompiler.free.fr/

To test, I wrote very simple code. What do you think, what code to write to test decompilers? Maybe the idea is to better than a try{} catch(){} finally{}?


问:
calculate checksum hex in Python 3
I want to calculate checksum. The process I want to do like below;

Step-1

```<code>a="10F8000041303131303030353000000000000000"
</code>```

Step-2

```<code>10+F8+00+00+41+30+31+31+30+30+30+35+30+00+00+00+00+00+00+00 = D0
</code>```

Step-3

```<code>~D0 = 2F -> 2F + 1 = 30
</code>```

I tried that;

```<code>def calc_checksum_two(s):
return '%2X' % (-(sum(ord(c) for c in s) % 256) & 0xFF)
print(calc_checksum_two(a))
</code>```

Result;

```<code>3D
</code>```

Title: calculate checksum hex in Python 3

Body:
I want to calculate checksum. The process I want to do like below;

Step-1

a="10F8000041303131303030353000000000000000"

Step-2

10+F8+00+00+41+30+31+31+30+30+30+35+30+00+00+00+00+00+00+00 = D0

Step-3

~D0 = 2F -> 2F + 1 = 30

I tried that;

def calc_checksum_two(s):
return '%2X' % (-(sum(ord(c) for c in s) % 256) & 0xFF)
print(calc_checksum_two(a))

Result;

3D

Body:
b = [a[i:i+2] for i in range(0, len(a), 2)] # ['10', 'F8', '00', ...
c = [int(i, 16) for i in b] # [16, 248, 0, ...
d = 256 - sum(c) % 256 # 0x30
e = hex(d)[2:] # '30'


问:
The “prefs” URL Scheme not working in iOS 10
I can't get the "prefs" URL Scheme to work in iOS 10.

It's set up correctly since the same App works fine on iOS 9.

Is this a bug or did it get renamed / removed?

Code:

```<code>NSURL *url = [NSURL URLWithString:@"prefs:root=LOCATION_SERVICES"];
if (![[UIApplication sharedApplication]canOpenURL:url]) {
    [[UIApplication sharedApplication]openURL:url];
}
</code>```

答:
prefs:root=LOCATION_SERVICES is working for below iOS 10...so checked for UIApplicationOpenSettingsURLString and App-Prefs:root=Privacy&path=LOCATION. Both are working for me.... Got hint by @Rajan Balan.

```<code>if ([[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString]]) {
     if(SYSTEM_VERSION_GREATER_THAN(@"10")) {
          [[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"App-Prefs:root=Privacy&path=LOCATION"]];

          // Below code is also working in iOS 10 to open location services
          // [[UIApplication sharedApplication] openURL:[NSURL URLWithString: UIApplicationOpenSettingsURLString]];

     } else {
          [[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"prefs:root=LOCATION_SERVICES"]];
     }
}
</code>```

Where

```<code>#define SYSTEM_VERSION_EQUAL_TO(v)                  ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] == NSOrderedSame)
#define SYSTEM_VERSION_GREATER_THAN(v)              ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] == NSOrderedDescending)
#define SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(v)  ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] != NSOrderedAscending)
#define SYSTEM_VERSION_LESS_THAN(v)                 ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] == NSOrderedAscending)
#define SYSTEM_VERSION_LESS_THAN_OR_EQUAL_TO(v)     ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] != NSOrderedDescending)
</code>```

Body:
I can't get the "prefs" URL Scheme to work in iOS 10.

It's set up correctly since the same App works fine on iOS 9.

Is this a bug or did it get renamed / removed?

Code:

NSURL *url = [NSURL URLWithString:@"prefs:root=LOCATION_SERVICES"];
if (![[UIApplication sharedApplication]canOpenURL:url]) {
    [[UIApplication sharedApplication]openURL:url];
}

Body:
prefs:root=LOCATION_SERVICES is working for below iOS 10...so checked for UIApplicationOpenSettingsURLString and App-Prefs:root=Privacy&path=LOCATION. Both are working for me.... Got hint by @Rajan Balan.

if ([[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString]]) {
     if(SYSTEM_VERSION_GREATER_THAN(@"10")) {
          [[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"App-Prefs:root=Privacy&path=LOCATION"]];

          // Below code is also working in iOS 10 to open location services
          // [[UIApplication sharedApplication] openURL:[NSURL URLWithString: UIApplicationOpenSettingsURLString]];

     } else {
          [[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"prefs:root=LOCATION_SERVICES"]];
     }
}

Where

#define SYSTEM_VERSION_EQUAL_TO(v)                  ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] == NSOrderedSame)
#define SYSTEM_VERSION_GREATER_THAN(v)              ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] == NSOrderedDescending)
#define SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(v)  ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] != NSOrderedAscending)
#define SYSTEM_VERSION_LESS_THAN(v)                 ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] == NSOrderedAscending)
#define SYSTEM_VERSION_LESS_THAN_OR_EQUAL_TO(v)     ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] != NSOrderedDescending)


问:
PyQt and MatPlotLib - Connecting QComboBox to Plot Function
I need to connect a comboBox to a plot function defined within a method of a separate class as seen below. The desired result is that the range selected in the comboBox's items is what is plotted in the figure so it will also be necessary to refresh the canvas upon selection which I could also use advice on.

There are two ways I can think of attaining this result but both are problematic. Ideally, the comboBox would be defined within the class containing the plot function to avoid the difficulty of connecting it to the class(method(function))) from outside the class but I don't think this is possible. Alternatively, it could be defined in setupUI but then how would I connect it to the plot function? Is it possible to reach a class's method's function from outside that class? Advice on either approach will be appreciated. I have condensed the code as much as I can.

```<code>import math
import matplotlib
import numpy as np
from PyQt4 import QtCore, QtGui
import matplotlib.pyplot as plt
from matplotlib.figure import Figure
from mpl_toolkits.mplot3d import Axes3D
from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg as FigureCanvas

try:
    _fromUtf8 = QtCore.QString.fromUtf8
except AttributeError:
    def _fromUtf8(s):
        return s

try:
    _encoding = QtGui.QApplication.UnicodeUTF8
    def _translate(context, text, disambig):
        return QtGui.QApplication.translate(context, text, disambig, _encoding)
except AttributeError:
    def _translate(context, text, disambig):
        return QtGui.QApplication.translate(context, text, disambig)

class MyMplCanvas(FigureCanvas):

    def __init__(self, parent=None, width=5, height=4, dpi=100):
        fig = Figure(figsize=(width, height), dpi=dpi)
        self.axes = fig.add_subplot(111)

        self.compute_initial_figure()

        FigureCanvas.__init__(self, fig)
        self.setParent(parent)

        FigureCanvas.setSizePolicy(self,
                                   QtGui.QSizePolicy.Expanding,
                                   QtGui.QSizePolicy.Expanding)
        FigureCanvas.updateGeometry(self)

    def compute_initial_figure(self):
        pass

class UsersPerCountryAndPlatformBar(MyMplCanvas):

    def compute_initial_figure(self):

        A_B = [['Afghanistan', 'Albania', 'Algeria', 'American Samoa', 'Angola'], [1, 9, 7, 1, 1], [1, 7, 2, 0, 1], \
    [0, 4, 3, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]]
        C_F = [['Cambodia', 'Canada', 'Chile', 'China', 'Colombia'], [13, 189, 12, 5, 10], [5, 115, 6, 64, 7], \
    [1, 11, 1, 2, 4], [2, 12, 0, 2, 0], [2, 5, 0, 0, 0]]

        def plot(X_Y):
            summedX_Y = []
            for i in range(len(X_Y[0])):
                summedX_Y.append(X_Y[1][i] + X_Y[2][i] + X_Y[3][i] + X_Y[4][i] + X_Y[5][i])

            def roundup(x):
                return int(math.ceil(x / 10.0)) * 10

            N = len(X_Y[0])
            ind = np.arange(N)
            width = 0.75
            colors = ['yellowgreen', 'paleturquoise', 'royalblue', 'lightsteelblue', 'firebrick']

            print [x + y for x, y in zip(X_Y[1], X_Y[2])]
            print [x + y + z for x, y, z in zip(X_Y[1], X_Y[2], X_Y[3])]
            print [x + y + z + i for x, y, z, i in zip(X_Y[1], X_Y[2], X_Y[3], X_Y[4])]

            p1 = self.axes.bar(ind, X_Y[1], width, color = colors[0])
            p2 = self.axes.bar(ind, X_Y[2], width, bottom = X_Y[1], color = colors[1])
            p3 = self.axes.bar(ind, X_Y[3], width, bottom = [x + y for x, y in zip(X_Y[1], X_Y[2])], color = colors[2])
            p4 = self.axes.bar(ind, X_Y[4], width, bottom = [x + y + z for x, y, z in zip(X_Y[1], X_Y[2], X_Y[3])], color = colors[3])
            p5 = self.axes.bar(ind, X_Y[5], width, bottom = [x + y + z + i for x, y, z, i in zip(X_Y[1], X_Y[2], X_Y[3], X_Y[4])], color = colors[4])

            self.axes.set_ylabel('Count')
            self.axes.set_title('Users Per Country And Platform')
            self.axes.set_xticks(ind)
            self.axes.set_xticklabels(countrylabels, fontsize = 8)
            self.axes.set_yticklabels(np.arange(0, max(summedX_Y), roundup(max(summedX_Y) / 10)))
            self.axes.legend((p1[0], p2[0], p3[0], p4[0], p5[0]), ('Android', 'iOS', 'Windows', 'OS X', 'WebGL'))

            '''comboBox = QtGui.QComboBox(self)
            comboBox.addItem('A_B')
            comboBox.addItem('C_F')
            comboBox.activated[str].connect(compute_initial_figure(plot(text)))'''
            # should plot(A_B) or (C_F) as selected

class Ui_MainWindow(object):

    def setupUi(self, MainWindow):

        self.main_widget = QtGui.QWidget(MainWindow)
        l = QtGui.QVBoxLayout(self.main_widget)
        UPCP = UsersPerCountryAndPlatformBar(self.main_widget, width = 10, height = 5, dpi = 100)
        l.addWidget(UPCP)
        self.main_widget.setFocus()
        MainWindow.setCentralWidget(self.main_widget)
        QtCore.QMetaObject.connectSlotsByName(MainWindow)

if __name__ == "__main__":
    import sys
    app = QtGui.QApplication(sys.argv)
    MainWindow = QtGui.QMainWindow()
    ui = Ui_MainWindow()
    ui.setupUi(MainWindow)
    MainWindow.show()
    sys.exit(app.exec_())
</code>```

答:
You can have a look at the code down below. I removed the doubly subclassing for better readability.

compute_initial_figure is called when the FigureCanvas is initialized.

The combo sits in the mainwindow class and is connected to an update function. This function converts the text from the combobox to some data which is passed to the plot function.

```<code>import math
import numpy as np
from PyQt4 import QtGui

from matplotlib.figure import Figure
from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg as FigureCanvas

class UsersPerCountryAndPlatformBar(FigureCanvas):

    def __init__(self, parent=None, width=5, height=4, dpi=100):
        fig = Figure(figsize=(width, height), dpi=dpi)
        FigureCanvas.__init__(self, fig)

        self.axes = fig.add_subplot(111)
        self.compute_initial_figure()

    def compute_initial_figure(self):

        A_B = [['Afghanistan', 'Albania', 'Algeria', 'American Samoa', 'Angola'], [1, 9, 7, 1, 1], [1, 7, 2, 0, 1], \
                [0, 4, 3, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]]
        C_F = [['Cambodia', 'Canada', 'Chile', 'China', 'Colombia'], [13, 189, 12, 5, 10], [5, 115, 6, 64, 7], \
                [1, 11, 1, 2, 4], [2, 12, 0, 2, 0], [2, 5, 0, 0, 0]]
        self.data = {"A_B" : A_B, "C_F" : C_F}
        self.updatefig("A_B")

    def updatefig(self, text):
        self.plot(self.data[text])

    def plot(self, X_Y):
        self.axes.clear()
        summedX_Y = []
        for i in range(len(X_Y[0])):
            summedX_Y.append(X_Y[1][i] + X_Y[2][i] + X_Y[3][i] + X_Y[4][i] + X_Y[5][i])

        def roundup(x):
            return int(math.ceil(x / 10.0)) * 10

        N = len(X_Y[0])
        ind = np.arange(N)
        width = 0.75
        colors = ['yellowgreen', 'paleturquoise', 'royalblue', 'lightsteelblue', 'firebrick']

        print [x + y for x, y in zip(X_Y[1], X_Y[2])]
        print [x + y + z for x, y, z in zip(X_Y[1], X_Y[2], X_Y[3])]
        print [x + y + z + i for x, y, z, i in zip(X_Y[1], X_Y[2], X_Y[3], X_Y[4])]

        p1 = self.axes.bar(ind, X_Y[1], width, color = colors[0])
        p2 = self.axes.bar(ind, X_Y[2], width, bottom = X_Y[1], color = colors[1])
        p3 = self.axes.bar(ind, X_Y[3], width, bottom = [x + y for x, y in zip(X_Y[1], X_Y[2])], color = colors[2])
        p4 = self.axes.bar(ind, X_Y[4], width, bottom = [x + y + z for x, y, z in zip(X_Y[1], X_Y[2], X_Y[3])], color = colors[3])
        p5 = self.axes.bar(ind, X_Y[5], width, bottom = [x + y + z + i for x, y, z, i in zip(X_Y[1], X_Y[2], X_Y[3], X_Y[4])], color = colors[4])

        self.axes.set_ylabel('Count')
        self.axes.set_title('Users Per Country And Platform')
        self.axes.set_xticks(ind)
        #self.axes.set_xticklabels(countrylabels, fontsize = 8)
        self.axes.set_yticklabels(np.arange(0, max(summedX_Y), roundup(max(summedX_Y) / 10)))
        self.axes.legend((p1[0], p2[0], p3[0], p4[0], p5[0]), ('Android', 'iOS', 'Windows', 'OS X', 'WebGL'))
        self.draw_idle()

class Ui_MainWindow(object):

    def setupUi(self, MainWindow):

        self.main_widget = QtGui.QWidget(MainWindow)
        l = QtGui.QVBoxLayout(self.main_widget)

        self.main_widget.setFocus()
        MainWindow.setCentralWidget(self.main_widget)

        self.UPCP = UsersPerCountryAndPlatformBar(self.main_widget, width = 10, height = 5, dpi = 100)

        comboBox = QtGui.QComboBox(MainWindow)
        comboBox.addItem('A_B')
        comboBox.addItem('C_F')
        comboBox.activated[str].connect(self.UPCP.updatefig)
        l.addWidget(comboBox)
        l.addWidget(self.UPCP)

if __name__ == "__main__":
    import sys
    app = QtGui.QApplication(sys.argv)
    MainWindow = QtGui.QMainWindow()
    ui = Ui_MainWindow()
    ui.setupUi(MainWindow)
    MainWindow.show()
    sys.exit(app.exec_())
</code>```

Body:
I need to connect a comboBox to a plot function defined within a method of a separate class as seen below. The desired result is that the range selected in the comboBox's items is what is plotted in the figure so it will also be necessary to refresh the canvas upon selection which I could also use advice on.

There are two ways I can think of attaining this result but both are problematic. Ideally, the comboBox would be defined within the class containing the plot function to avoid the difficulty of connecting it to the class(method(function))) from outside the class but I don't think this is possible. Alternatively, it could be defined in setupUI but then how would I connect it to the plot function? Is it possible to reach a class's method's function from outside that class? Advice on either approach will be appreciated. I have condensed the code as much as I can.

import math
import matplotlib
import numpy as np
from PyQt4 import QtCore, QtGui
import matplotlib.pyplot as plt
from matplotlib.figure import Figure
from mpl_toolkits.mplot3d import Axes3D
from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg as FigureCanvas

try:
    _fromUtf8 = QtCore.QString.fromUtf8
except AttributeError:
    def _fromUtf8(s):
        return s

try:
    _encoding = QtGui.QApplication.UnicodeUTF8
    def _translate(context, text, disambig):
        return QtGui.QApplication.translate(context, text, disambig, _encoding)
except AttributeError:
    def _translate(context, text, disambig):
        return QtGui.QApplication.translate(context, text, disambig)

class MyMplCanvas(FigureCanvas):

    def __init__(self, parent=None, width=5, height=4, dpi=100):
        fig = Figure(figsize=(width, height), dpi=dpi)
        self.axes = fig.add_subplot(111)

        self.compute_initial_figure()

        FigureCanvas.__init__(self, fig)
        self.setParent(parent)

        FigureCanvas.setSizePolicy(self,
                                   QtGui.QSizePolicy.Expanding,
                                   QtGui.QSizePolicy.Expanding)
        FigureCanvas.updateGeometry(self)

    def compute_initial_figure(self):
        pass

class UsersPerCountryAndPlatformBar(MyMplCanvas):

    def compute_initial_figure(self):

        A_B = [['Afghanistan', 'Albania', 'Algeria', 'American Samoa', 'Angola'], [1, 9, 7, 1, 1], [1, 7, 2, 0, 1], \
    [0, 4, 3, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]]
        C_F = [['Cambodia', 'Canada', 'Chile', 'China', 'Colombia'], [13, 189, 12, 5, 10], [5, 115, 6, 64, 7], \
    [1, 11, 1, 2, 4], [2, 12, 0, 2, 0], [2, 5, 0, 0, 0]]

        def plot(X_Y):
            summedX_Y = []
            for i in range(len(X_Y[0])):
                summedX_Y.append(X_Y[1][i] + X_Y[2][i] + X_Y[3][i] + X_Y[4][i] + X_Y[5][i])

            def roundup(x):
                return int(math.ceil(x / 10.0)) * 10

            N = len(X_Y[0])
            ind = np.arange(N)
            width = 0.75
            colors = ['yellowgreen', 'paleturquoise', 'royalblue', 'lightsteelblue', 'firebrick']

            print [x + y for x, y in zip(X_Y[1], X_Y[2])]
            print [x + y + z for x, y, z in zip(X_Y[1], X_Y[2], X_Y[3])]
            print [x + y + z + i for x, y, z, i in zip(X_Y[1], X_Y[2], X_Y[3], X_Y[4])]

            p1 = self.axes.bar(ind, X_Y[1], width, color = colors[0])
            p2 = self.axes.bar(ind, X_Y[2], width, bottom = X_Y[1], color = colors[1])
            p3 = self.axes.bar(ind, X_Y[3], width, bottom = [x + y for x, y in zip(X_Y[1], X_Y[2])], color = colors[2])
            p4 = self.axes.bar(ind, X_Y[4], width, bottom = [x + y + z for x, y, z in zip(X_Y[1], X_Y[2], X_Y[3])], color = colors[3])
            p5 = self.axes.bar(ind, X_Y[5], width, bottom = [x + y + z + i for x, y, z, i in zip(X_Y[1], X_Y[2], X_Y[3], X_Y[4])], color = colors[4])

            self.axes.set_ylabel('Count')
            self.axes.set_title('Users Per Country And Platform')
            self.axes.set_xticks(ind)
            self.axes.set_xticklabels(countrylabels, fontsize = 8)
            self.axes.set_yticklabels(np.arange(0, max(summedX_Y), roundup(max(summedX_Y) / 10)))
            self.axes.legend((p1[0], p2[0], p3[0], p4[0], p5[0]), ('Android', 'iOS', 'Windows', 'OS X', 'WebGL'))

            '''comboBox = QtGui.QComboBox(self)
            comboBox.addItem('A_B')
            comboBox.addItem('C_F')
            comboBox.activated[str].connect(compute_initial_figure(plot(text)))'''
            # should plot(A_B) or (C_F) as selected

class Ui_MainWindow(object):

    def setupUi(self, MainWindow):

        self.main_widget = QtGui.QWidget(MainWindow)
        l = QtGui.QVBoxLayout(self.main_widget)
        UPCP = UsersPerCountryAndPlatformBar(self.main_widget, width = 10, height = 5, dpi = 100)
        l.addWidget(UPCP)
        self.main_widget.setFocus()
        MainWindow.setCentralWidget(self.main_widget)
        QtCore.QMetaObject.connectSlotsByName(MainWindow)

if __name__ == "__main__":
    import sys
    app = QtGui.QApplication(sys.argv)
    MainWindow = QtGui.QMainWindow()
    ui = Ui_MainWindow()
    ui.setupUi(MainWindow)
    MainWindow.show()
    sys.exit(app.exec_())

Body:
You can have a look at the code down below. I removed the doubly subclassing for better readability.

compute_initial_figure is called when the FigureCanvas is initialized.

The combo sits in the mainwindow class and is connected to an update function. This function converts the text from the combobox to some data which is passed to the plot function.

import math
import numpy as np
from PyQt4 import QtGui

from matplotlib.figure import Figure
from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg as FigureCanvas

class UsersPerCountryAndPlatformBar(FigureCanvas):

    def __init__(self, parent=None, width=5, height=4, dpi=100):
        fig = Figure(figsize=(width, height), dpi=dpi)
        FigureCanvas.__init__(self, fig)

        self.axes = fig.add_subplot(111)
        self.compute_initial_figure()

    def compute_initial_figure(self):

        A_B = [['Afghanistan', 'Albania', 'Algeria', 'American Samoa', 'Angola'], [1, 9, 7, 1, 1], [1, 7, 2, 0, 1], \
                [0, 4, 3, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]]
        C_F = [['Cambodia', 'Canada', 'Chile', 'China', 'Colombia'], [13, 189, 12, 5, 10], [5, 115, 6, 64, 7], \
                [1, 11, 1, 2, 4], [2, 12, 0, 2, 0], [2, 5, 0, 0, 0]]
        self.data = {"A_B" : A_B, "C_F" : C_F}
        self.updatefig("A_B")

    def updatefig(self, text):
        self.plot(self.data[text])

    def plot(self, X_Y):
        self.axes.clear()
        summedX_Y = []
        for i in range(len(X_Y[0])):
            summedX_Y.append(X_Y[1][i] + X_Y[2][i] + X_Y[3][i] + X_Y[4][i] + X_Y[5][i])

        def roundup(x):
            return int(math.ceil(x / 10.0)) * 10

        N = len(X_Y[0])
        ind = np.arange(N)
        width = 0.75
        colors = ['yellowgreen', 'paleturquoise', 'royalblue', 'lightsteelblue', 'firebrick']

        print [x + y for x, y in zip(X_Y[1], X_Y[2])]
        print [x + y + z for x, y, z in zip(X_Y[1], X_Y[2], X_Y[3])]
        print [x + y + z + i for x, y, z, i in zip(X_Y[1], X_Y[2], X_Y[3], X_Y[4])]

        p1 = self.axes.bar(ind, X_Y[1], width, color = colors[0])
        p2 = self.axes.bar(ind, X_Y[2], width, bottom = X_Y[1], color = colors[1])
        p3 = self.axes.bar(ind, X_Y[3], width, bottom = [x + y for x, y in zip(X_Y[1], X_Y[2])], color = colors[2])
        p4 = self.axes.bar(ind, X_Y[4], width, bottom = [x + y + z for x, y, z in zip(X_Y[1], X_Y[2], X_Y[3])], color = colors[3])
        p5 = self.axes.bar(ind, X_Y[5], width, bottom = [x + y + z + i for x, y, z, i in zip(X_Y[1], X_Y[2], X_Y[3], X_Y[4])], color = colors[4])

        self.axes.set_ylabel('Count')
        self.axes.set_title('Users Per Country And Platform')
        self.axes.set_xticks(ind)
        #self.axes.set_xticklabels(countrylabels, fontsize = 8)
        self.axes.set_yticklabels(np.arange(0, max(summedX_Y), roundup(max(summedX_Y) / 10)))
        self.axes.legend((p1[0], p2[0], p3[0], p4[0], p5[0]), ('Android', 'iOS', 'Windows', 'OS X', 'WebGL'))
        self.draw_idle()

class Ui_MainWindow(object):

    def setupUi(self, MainWindow):

        self.main_widget = QtGui.QWidget(MainWindow)
        l = QtGui.QVBoxLayout(self.main_widget)

        self.main_widget.setFocus()
        MainWindow.setCentralWidget(self.main_widget)

        self.UPCP = UsersPerCountryAndPlatformBar(self.main_widget, width = 10, height = 5, dpi = 100)

        comboBox = QtGui.QComboBox(MainWindow)
        comboBox.addItem('A_B')
        comboBox.addItem('C_F')
        comboBox.activated[str].connect(self.UPCP.updatefig)
        l.addWidget(comboBox)
        l.addWidget(self.UPCP)

if __name__ == "__main__":
    import sys
    app = QtGui.QApplication(sys.argv)
    MainWindow = QtGui.QMainWindow()
    ui = Ui_MainWindow()
    ui.setupUi(MainWindow)
    MainWindow.show()
    sys.exit(app.exec_())


问:
How to fix with statement deprecation warning
I have some Python code, using Fabric context managers, like:

```<code>with settings(warn_only=True), hide('running', 'stdout', 'stderr', 'warnings'):
    do_stuff()
</code>```

and every time I run this, Python gives me the DeprecationWarning:

```<code>With-statements now directly support multiple context managers
  with settings(warn_only=True), hide('running', 'stdout', 'stderr', 'warnings'):
</code>```

Why am I getting this warning and how do I fix it?

I'm a bit confused, because this similar question implies I'm using nested managers, and that the fix is to rewrite them into the single line version that I'm already using.

I've tried re-writing it like:

```<code>with settings(warn_only=True) as a, hide('running', 'stdout', 'stderr', 'warnings') as b:
    do_stuff()
</code>```

and:

```<code>with settings(warn_only=True):
    with hide('running', 'stdout', 'stderr', 'warnings'):
        do_stuff()
</code>```

but both give me the same warning.

答:
It seems to be that Fabric itself is using the deprecated contextlib.nested.

See https://github.com/fabric/fabric/issues/1364

The only suggestion on the ticket seems to be to ignore it as they want to maintain backward compatibility with older versions of Python.

Body:
I have some Python code, using Fabric context managers, like:

with settings(warn_only=True), hide('running', 'stdout', 'stderr', 'warnings'):
    do_stuff()

and every time I run this, Python gives me the DeprecationWarning:

With-statements now directly support multiple context managers
  with settings(warn_only=True), hide('running', 'stdout', 'stderr', 'warnings'):

Why am I getting this warning and how do I fix it?

I'm a bit confused, because this similar question implies I'm using nested managers, and that the fix is to rewrite them into the single line version that I'm already using.

I've tried re-writing it like:

with settings(warn_only=True) as a, hide('running', 'stdout', 'stderr', 'warnings') as b:
    do_stuff()

and:

with settings(warn_only=True):
    with hide('running', 'stdout', 'stderr', 'warnings'):
        do_stuff()

but both give me the same warning.


问:
Can I add a wrapper to my layout that has a pure CSS dynamic sticky footer?
After countless hours trying to find a way to implement a sticky footer with fluid height without resorting to using javascript, I finally found a way. No matter how much content I add to the .footer, it remains stuck to the bottom of the viewport, regardless of whether there is enough in the .content div to push it down. None of the javascript solutions I tried worked as smoothly as this, and I'd like to keep using this method if possible.

My problem is that due to an issue with various mobile browsers not accepting the overflow-x:hidden; rule on the body tag, I'm now having to add a wrapper to my layout. This fixes the mobile browser issue, but unfortunately stops the .footer from sticking to the bottom of the viewport when the .content div is empty.

I have of course tried to move several of the CSS rules from the body to the wrapper to see if this works, but I haven't had any success. Is there a way around this?

Here are two jsFiddle examples to show the problem, one with a .wrapper and one without.

Example 1: Without wrapper (Sticky footer works) – https://jsfiddle.net/v5h2f5wd/

Example 2: With wrapper (Sticky footer does not work) – https://jsfiddle.net/v5h2f5wd/1/

Code from Example 2:

```<code><div class="wrapper">
    <header class="header"></header>
        <div class="content">
            <button>Click here to insert content into footer.</button>
        </div>
    <footer class="footer"></footer>
</div>

html {
    position:relative;
    height:100%;
}

body {
    position:relative;
    width:100%;
    min-height:100%;
    margin:0;
    padding:0;
    overflow-x:hidden;
    background-color:#eee;
    display:-webkit-box;
    display:-webkit-flex;
    display:-ms-flexbox;
    display:flex;
    -webkit-box-orient: vertical;
    -webkit-box-direction: normal;
    -webkit-flex-direction: column;
    -ms-flex-direction: column;
    flex-direction: column;
}

.header {
    position:absolute;
    width:100%;
    height:55px;
    background-color:#fff;
}

.content {
    -webkit-box-flex:1;
    -webkit-flex:1;
    -ms-flex:1;
    flex:1;
    width:100%;
    height:auto;
    background-color:pink;
}

button {
    margin:65px 0 0 10px;
}

.footer {
    width:100%;
    background-color:#fff;
    padding:25px 0;
}
</code>```

答:
If you want to use it with your wrapper, maybe this would work for you.

$(document).ready(function(){
    $("button").click(function(){
        $(".footer").append("Some text to make me taller.");
    });
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>html {
  position:relative;
 height:100%;
  height: 100%; margin: 0px; padding: 0px;
}

body {
 position:relative;
  height: 100%; margin: 0px; padding: 0px;
 width:100%;
 min-height:100%;
  margin:0;
  padding:0;
 overflow-x:hidden;
 background-color:#eee;
 display:-webkit-box;
  display:-webkit-flex;
  display:-ms-flexbox;
  display:flex;
  -webkit-box-orient: vertical;
  -webkit-box-direction: normal;
  -webkit-flex-direction: column;
  -ms-flex-direction: column;
    flex-direction: column;
    margin:0;
  padding:0;
  height:100%;
}

.wrapper {
  height: 100%;
}

.header {
  position:absolute;
 width:100%;
 height:55px;
  background-color:#fff;
}

.content {
  -webkit-box-flex:1;
 -webkit-flex:1;
 -ms-flex:1;
 flex:1;
 width:100%;
 height:auto;
  background-color:pink;
  height: 100%;
}

button {
  margin:65px 0 0 10px;
}

.footer {
  width:100%;
 background-color:#fff;
  padding:25px 0;
  bottom: 0;
  position:absolute;
}</code>```

    <button>Click here to insert content into footer.</button>

```

Body:
After countless hours trying to find a way to implement a sticky footer with fluid height without resorting to using javascript, I finally found a way. No matter how much content I add to the .footer, it remains stuck to the bottom of the viewport, regardless of whether there is enough in the .content div to push it down. None of the javascript solutions I tried worked as smoothly as this, and I'd like to keep using this method if possible.

My problem is that due to an issue with various mobile browsers not accepting the overflow-x:hidden; rule on the body tag, I'm now having to add a wrapper to my layout. This fixes the mobile browser issue, but unfortunately stops the .footer from sticking to the bottom of the viewport when the .content div is empty.

I have of course tried to move several of the CSS rules from the body to the wrapper to see if this works, but I haven't had any success. Is there a way around this?

Here are two jsFiddle examples to show the problem, one with a .wrapper and one without.

Example 1: Without wrapper (Sticky footer works) – https://jsfiddle.net/v5h2f5wd/

Example 2: With wrapper (Sticky footer does not work) – https://jsfiddle.net/v5h2f5wd/1/

Code from Example 2:

            <button>Click here to insert content into footer.</button>

html {
    position:relative;
    height:100%;
}

body {
    position:relative;
    width:100%;
    min-height:100%;
    margin:0;
    padding:0;
    overflow-x:hidden;
    background-color:#eee;
    display:-webkit-box;
    display:-webkit-flex;
    display:-ms-flexbox;
    display:flex;
    -webkit-box-orient: vertical;
    -webkit-box-direction: normal;
    -webkit-flex-direction: column;
    -ms-flex-direction: column;
    flex-direction: column;
}

.header {
    position:absolute;
    width:100%;
    height:55px;
    background-color:#fff;
}

.content {
    -webkit-box-flex:1;
    -webkit-flex:1;
    -ms-flex:1;
    flex:1;
    width:100%;
    height:auto;
    background-color:pink;
}

button {
    margin:65px 0 0 10px;
}

.footer {
    width:100%;
    background-color:#fff;
    padding:25px 0;
}

Body:
If you want to use it with your wrapper, maybe this would work for you.

$(document).ready(function(){
    $("button").click(function(){
        $(".footer").append("Some text to make me taller.");
    });
});

html {
  position:relative;
 height:100%;
  height: 100%; margin: 0px; padding: 0px;
}

body {
 position:relative;
  height: 100%; margin: 0px; padding: 0px;
 width:100%;
 min-height:100%;
  margin:0;
  padding:0;
 overflow-x:hidden;
 background-color:#eee;
 display:-webkit-box;
  display:-webkit-flex;
  display:-ms-flexbox;
  display:flex;
  -webkit-box-orient: vertical;
  -webkit-box-direction: normal;
  -webkit-flex-direction: column;
  -ms-flex-direction: column;
    flex-direction: column;
    margin:0;
  padding:0;
  height:100%;
}

.wrapper {
  height: 100%;
}

.header {
  position:absolute;
 width:100%;
 height:55px;
  background-color:#fff;
}

.content {
  -webkit-box-flex:1;
 -webkit-flex:1;
 -ms-flex:1;
 flex:1;
 width:100%;
 height:auto;
  background-color:pink;
  height: 100%;
}

button {
  margin:65px 0 0 10px;
}

.footer {
  width:100%;
 background-color:#fff;
  padding:25px 0;
  bottom: 0;
  position:absolute;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script>
<div class="wrapper">

 <header class="header"></header>
  <div class="content">
    <button>Click here to insert content into footer.</button>
  </div>
  <footer class="footer"></footer>

</div>


问:
byte swapping and C++/C
I did a post on comp.lang.c++ and got this

http://groups.google.com/group/comp.lang.c++/browse_thread/thread/afc946826945bdb1/90850f6a0e0edd2d#90850f6a0e0edd2d

but that is still not the answer.

I have a little confusion for a binary read operation.

I am trying to read a binary file with the stream functions. This is a result file of a commercial program(ANSYS), and I know the structure of the file, at least from the manual.

The file is structured as records and the program is written in fortran. So the structure is like

record Length (int)
dummy integer
data (could be int, double)
dummy integer

The first record is a 100 integer block, where this corresponds to data in the above representation.

If I start reading the file and read the first value which is the record length (an integer), I have to swap the bytes to get the correct value of 100.

I did not understand why I have to swap the bytes, because this file is generated on the same machine and they should be using the same system specific routines so that should not be a problem, but it does not seem that is the case. There is  sth else going on. I could not understand this. Can the software be forcing to swap the bytes which I would have hard time to understand the reason?

Any comments are appreciated.

Here is a naive test case

```<code>int main () {
  ifstream myfile;
  char intBuffer[4];
  myfile.open ("truss.rst", ios::binary);
  myfile.read(intBuffer, sizeof(int));
  //cout << *((int*)intBuffer) << endl;
  // if I do not use this portion-
  // I do not get what I want
  char *cptr, tmp;
  tmp = intBuffer[0];
  intBuffer[0] = intBuffer[3];
  intBuffer[3] = tmp;
  tmp = intBuffer[1];
  intBuffer[1] = intBuffer[2];
  intBuffer[2] = tmp;
  // -----------------------------
  cout << *((int*)intBuffer) << endl;

  myfile.close();
  return 0;
}
</code>```

Best,
U.

答:
There is some well known times when you voluntarily force one byte order : when the data is intended to be exchanged between machines whose endianness is unknown at start, like through network. That is why there is C primitives like ntohl and htonl : if network endianess is the same as machine endianness these do nothing, otherwise they swap bytes. There could be something similar involved here if the files are supposed to be exchanged between machines.

But the true question is: is there also the same byte swapping in data block. If not there is indeed something strange, and the 0 could just be padding, not at all part of the format. If the byte swapping also occurs in data block, it's probably done on purpose.

The most portable solution is certainly to read file byte by byte and assemble your data by hand, thus you may be able to handle integers of size bigger than uint32_t.

Be also ready to get into some troubles when reading doubles, as the byte ordering is also probably swapped, and they are not as easy to assemble by hand.

The code below should work as a template for any type whose you want to change endianness, including double.

```<code>#include <stdio.h>
#include <arpa/inet.h>
#include <stdint.h>

template <class builtin>
builtin ntoh(const builtin input) {
    if ((int)ntohs(1) != 1){
        union {
            char buffer[sizeof(builtin)];
            builtin data;
        } in, out;
        in.data = input;
        for (int i = 0 ; i < sizeof(builtin); i++){
            out.buffer[i] = in.buffer[sizeof(builtin) - i - 1];
        }
        return out.data;
    }
    return input;
}

main(){
    printf ("78563412 expected, got: output= %x\n", ntoh<uint32_t>(0x12345678));
}
</code>```

It will not provide the best performance, look here to get better performance for native types.

ContentLicense: CC BY-SA 2.5

Title: byte swapping and C++/C

Body:
I did a post on comp.lang.c++ and got this

http://groups.google.com/group/comp.lang.c++/browse_thread/thread/afc946826945bdb1/90850f6a0e0edd2d#90850f6a0e0edd2d

but that is still not the answer.

I have a little confusion for a binary read operation.

I am trying to read a binary file with the stream functions. This is a result file of a commercial program(ANSYS), and I know the structure of the file, at least from the manual.

The file is structured as records and the program is written in fortran. So the structure is like

record Length (int)
dummy integer
data (could be int, double)
dummy integer

The first record is a 100 integer block, where this corresponds to data in the above representation.

If I start reading the file and read the first value which is the record length (an integer), I have to swap the bytes to get the correct value of 100.

I did not understand why I have to swap the bytes, because this file is generated on the same machine and they should be using the same system specific routines so that should not be a problem, but it does not seem that is the case. There is  sth else going on. I could not understand this. Can the software be forcing to swap the bytes which I would have hard time to understand the reason?

Any comments are appreciated.

Here is a naive test case

int main () {
  ifstream myfile;
  char intBuffer[4];
  myfile.open ("truss.rst", ios::binary);
  myfile.read(intBuffer, sizeof(int));
  //cout << *((int*)intBuffer) << endl;
  // if I do not use this portion-
  // I do not get what I want
  char *cptr, tmp;
  tmp = intBuffer[0];
  intBuffer[0] = intBuffer[3];
  intBuffer[3] = tmp;
  tmp = intBuffer[1];
  intBuffer[1] = intBuffer[2];
  intBuffer[2] = tmp;
  // -----------------------------
  cout << *((int*)intBuffer) << endl;

  myfile.close();
  return 0;
}

Best,
U.

Body:
There is some well known times when you voluntarily force one byte order : when the data is intended to be exchanged between machines whose endianness is unknown at start, like through network. That is why there is C primitives like ntohl and htonl : if network endianess is the same as machine endianness these do nothing, otherwise they swap bytes. There could be something similar involved here if the files are supposed to be exchanged between machines.

But the true question is: is there also the same byte swapping in data block. If not there is indeed something strange, and the 0 could just be padding, not at all part of the format. If the byte swapping also occurs in data block, it's probably done on purpose.

The most portable solution is certainly to read file byte by byte and assemble your data by hand, thus you may be able to handle integers of size bigger than uint32_t.

Be also ready to get into some troubles when reading doubles, as the byte ordering is also probably swapped, and they are not as easy to assemble by hand.

The code below should work as a template for any type whose you want to change endianness, including double.

#include <stdio.h>
#include <arpa/inet.h>
#include <stdint.h>

template <class builtin>
builtin ntoh(const builtin input) {
    if ((int)ntohs(1) != 1){
        union {
            char buffer[sizeof(builtin)];
            builtin data;
        } in, out;
        in.data = input;
        for (int i = 0 ; i < sizeof(builtin); i++){
            out.buffer[i] = in.buffer[sizeof(builtin) - i - 1];
        }
        return out.data;
    }
    return input;
}

main(){
    printf ("78563412 expected, got: output= %x\n", ntoh<uint32_t>(0x12345678));
}

It will not provide the best performance, look here to get better performance for native types.


问:
Passing parameters to public void run() from the parent
I'm 50% hopeless :P. I tried (at the beginning) to update the GUI from the code of a Thread, and got NullException. After reading for a while, I understood that the Thread flooded the JavaFX application window and in order for me to update the GUI from a Thread, I need to use the following code:

```<code>Platform.runLater(new Runnable() {
            @Override public void run() {

            //Update UI here
            for (int i=0; i<2000;i++)
                {
                 MyMainClass.leftPaneTextArea.appendText("Goodi!\n");
                }

            }
        });
</code>```

So I did use this code, and it indeed allow me to edit the GUI of my main class. However, my question is simple. => this code, which I'm running from a thread, is a code which sits inside a public void run()  (of the thread I run the code from). It looks something like this:

```<code>@Override
    public void run() {

    String tmpVar;

    ... (Some code)
    ... (Some code)
    ... (Some code)

        Platform.runLater(new Runnable() {
            @Override public void run() {

            //Update UI here
            for (int i=0; i<2000;i++)
                {
                 MyMainClass.leftPaneTextArea.appendText("Goodi!\n");
                }

            }
        });

    ... (Some code)
    ... (Some code)
    ... (Some code)
}
</code>```

How can I pass parameters from the parent's public void run() into this one?.
For example, the String tmpString (I want to pass it on).

Do note that if I declare it outside the public void run() as a static (for example) => I run a lot of threads, so updating a static var might not always be accurate (cause lots of threads will update it simultaneity)

Thank you!.

答:
What you are trying to do is against overriding rules.
If you were to pass any argument in the run() method, you are actually overloading the run() method and it will not be called anyway as
when a new thread is created, the no-arg run() method is the one called.

I will suggest storing the information somewhere else in a static context, and then retrieve it in the run() method.

Body:
I'm 50% hopeless :P. I tried (at the beginning) to update the GUI from the code of a Thread, and got NullException. After reading for a while, I understood that the Thread flooded the JavaFX application window and in order for me to update the GUI from a Thread, I need to use the following code:

Platform.runLater(new Runnable() {
            @Override public void run() {

            //Update UI here
            for (int i=0; i<2000;i++)
                {
                 MyMainClass.leftPaneTextArea.appendText("Goodi!\n");
                }

            }
        });

So I did use this code, and it indeed allow me to edit the GUI of my main class. However, my question is simple. => this code, which I'm running from a thread, is a code which sits inside a public void run()  (of the thread I run the code from). It looks something like this:

@Override
    public void run() {

    String tmpVar;

    ... (Some code)
    ... (Some code)
    ... (Some code)

        Platform.runLater(new Runnable() {
            @Override public void run() {

            //Update UI here
            for (int i=0; i<2000;i++)
                {
                 MyMainClass.leftPaneTextArea.appendText("Goodi!\n");
                }

            }
        });

    ... (Some code)
    ... (Some code)
    ... (Some code)
}

How can I pass parameters from the parent's public void run() into this one?.
For example, the String tmpString (I want to pass it on).

Do note that if I declare it outside the public void run() as a static (for example) => I run a lot of threads, so updating a static var might not always be accurate (cause lots of threads will update it simultaneity)

Thank you!.


问:
SQL - retrieve maximum date from other related table
I have  table T1 with data:

```<code>ID GROUP
1  L1
2  L1
3  L2
4  L3
</code>```

I have table T2 with data:

```<code>ID  GROUP  DATE
1   L1     03.03.2017
1   L2     01.01.2017
2   L1     03.03.2017
2   L2     02.02.2017
2   L1     01.01.2017
3   L2     03.03.2017
3   L1     02.02.2017
4   L3     05.03.2017
4   L2     02.02.2017
4   L3     05.01.2017
4   L1     01.01.2017
</code>```

As result I want to get a full list from T1 (ID and current group value) but to have additional column which will be populated only if current GROUP from T1 is not L1 and in that column I want to have maximum DATE from T2 for that ID where GROUP is not L1 and it matches with GROUP value from T1.

So result of the SELECT (joined L1 and L2) should be:

```<code>ID GROUP DATE
1  L1    null
2  L1    null
3  L2    03.03.2017
4  L3    05.03.2017
</code>```

I tried with this sql but it throws error:

```<code>        select t1.id,t1.group,t21.date from t1
        left outer join t2
     AS T21 on t21.id=t1.id and t1.group=t21.group
     and T21.group not in ('L1')
        AND T21.DATE IN (SELECT MAX(T22.DATE)
     FROM t2 AS T22
WHERE T22.id=T21.id and T21.group=t22.group)
</code>```

答:
Wouldn't a simple join and group by be enough?</p>

```<code>select t1.id,t1.group, max(t2.date)
from t1 left outer join t2 on
     t2.id=t1.id and
     t1.group=t2.group and
     T2.group <> 'L1'
group by t1.id,t1.group
</code>```

Body:
I have  table T1 with data:

ID GROUP
1  L1
2  L1
3  L2
4  L3

I have table T2 with data:

ID  GROUP  DATE
1   L1     03.03.2017
1   L2     01.01.2017
2   L1     03.03.2017
2   L2     02.02.2017
2   L1     01.01.2017
3   L2     03.03.2017
3   L1     02.02.2017
4   L3     05.03.2017
4   L2     02.02.2017
4   L3     05.01.2017
4   L1     01.01.2017

As result I want to get a full list from T1 (ID and current group value) but to have additional column which will be populated only if current GROUP from T1 is not L1 and in that column I want to have maximum DATE from T2 for that ID where GROUP is not L1 and it matches with GROUP value from T1.

So result of the SELECT (joined L1 and L2) should be:

ID GROUP DATE
1  L1    null
2  L1    null
3  L2    03.03.2017
4  L3    05.03.2017

I tried with this sql but it throws error:

        select t1.id,t1.group,t21.date from t1
        left outer join t2
     AS T21 on t21.id=t1.id and t1.group=t21.group
     and T21.group not in ('L1')
        AND T21.DATE IN (SELECT MAX(T22.DATE)
     FROM t2 AS T22
WHERE T22.id=T21.id and T21.group=t22.group)

Body:
Wouldn't a simple join and group by be enough?

select t1.id,t1.group, max(t2.date)
from t1 left outer join t2 on
     t2.id=t1.id and
     t1.group=t2.group and
     T2.group <> 'L1'
group by t1.id,t1.group


问:
Alfresco - Integration with Ofiice 365?
I need to integrate office 365 with Alfresco community 5.x for editing a document. Is there any way to do that or any addOns available for that?

Thanks in advance.

答:
Refer to the Supported Platforms page to understand what versions of various components are supported for different versions of Alfresco. These apply to both Enterprise and Community.

Office 365 is not listed for any version.

ContentLicense: CC BY-SA 4.0

Title: Alfresco - Integration with Ofiice 365?


答: It's not uncommon for software to adopt a specific byte order to make the binary files more portable, even if the software doesn't support other platforms yet, or might never.  Similarly, software may use a serialisation library that's designed for portability.  Routines like ntohl() may help you restore the order you want.

Title: byte swapping and C++/C


问:
How much space is required to install OpenCV on Raspberry Pi 3
I am new user to the Raspberry Pi 3.
How much space is required to install OpenCV on Raspberry?</p>

答:
Mmmm... how long is a piece of string?

It depends on what/how you install and what/how you count. The following factors, and others, will affect the answer:

debug or release versions

examples installed or not

documentation installed or not

contrib code installed or not

It also depends on whether you count the fact that to build it, you will need a compiler and all its associated stuff, cmake and a bunch of V4L, video formats and image formats and libraries.

Also, you can build it and install it and then delete the source yet continue to use the product.

FWIW, my build area on a Raspberry Pi amounts to 2.1GB - that is the source and a release build without contrib.


问:
Accessing a tuple element from a list of tuples
So I've been making a little program in Python and the logic seems to work fine up until the final step where it retrieves the result. Codewise, it's similiar to this:

```<code>...
list1 = [(string,string,int),(string,string,int)...]
print(list1[0[0]])
</code>```

This throws up a TypeError: 'int' object is not subscriptable error and I'm struggling to figure out why. Surely this is only meant to print index 0 of the list (tuple 1) and then index 0 of that (the string)? How would I go about getting this value out the list?

答:
Issue is with your formatting:
update print statement.

```<code>list1 = [(string,string,int),(string,string,int)...]
print(list1[0][0])
</code>```

[0[0]] - wrong format to access a tuple element
[0][0] - correct format for accessing the first element of the first tuple.

Body:
So I've been making a little program in Python and the logic seems to work fine up until the final step where it retrieves the result. Codewise, it's similiar to this:

...
list1 = [(string,string,int),(string,string,int)...]
print(list1[0[0]])

This throws up a TypeError: 'int' object is not subscriptable error and I'm struggling to figure out why. Surely this is only meant to print index 0 of the list (tuple 1) and then index 0 of that (the string)? How would I go about getting this value out the list?

Body:
Issue is with your formatting:
update print statement.

list1 = [(string,string,int),(string,string,int)...]
print(list1[0][0])

[0[0]] - wrong format to access a tuple element
[0][0] - correct format for accessing the first element of the first tuple.


问:
Convert local IST time to unix timestamp using Moment.js
I want to convert the following datetime into unix timestamp.

```<code>Tue Feb 28 2017 00:00:00 GMT+0530 (IST)
</code>```

How can I do so using Moment.js

答:
Have you tried this?</p>

```<code>var date = moment('Tue Feb 28 2017 00:00:00 GMT+0530 (IST)').unix();
</code>```

Body:
I want to convert the following datetime into unix timestamp.

Tue Feb 28 2017 00:00:00 GMT+0530 (IST)

How can I do so using Moment.js

Body:
Have you tried this?

var date = moment('Tue Feb 28 2017 00:00:00 GMT+0530 (IST)').unix();


问:
WooCommerce Search Form From Revolution Slider
I am using the following to place a search form in a slider revolution hero slide. However it searches the entire site. I would like it to only search woocommerce products. Any ideas what I need to change to make that work?</p>

```<code><form role="search" method="get" id="searchform" class="revtp-searchform" action="http://mywebsiteURL.com/"/>
    <input type="text" value="" name="s" id="s" placeholder="What are you looking for?" />
    <input type="submit" id="searchsubmit" value="Find" />
</form>
</code>```

答:
You can solve it using codex: pre_get_posts and developer: pre_get_posts

```<code>add_action( 'pre_get_posts', 'search_woocommerce_product' );

function search_woocommerce_product( $query ) {
  if( ! is_admin() && is_search() && $query->is_main_query() ) {
    $query->set( 'post_type', 'product' );
  }
}
</code>```

You can add further condition to this hook function like include in particular page only is_page

Or with certain short code like this

```<code>$pattern = get_shortcode_regex();
$patternToken = 'masterslider';

if (preg_match_all('/' . $pattern . '/s', get_the_content(), $matches) &&
array_key_exists(2, $matches) &&
in_array($patternToken, $matches[2])) {
//Your code logic
}
</code>```

Body:
I am using the following to place a search form in a slider revolution hero slide. However it searches the entire site. I would like it to only search woocommerce products. Any ideas what I need to change to make that work?

<form role="search" method="get" id="searchform" class="revtp-searchform" action="http://mywebsiteURL.com/"/>
    <input type="text" value="" name="s" id="s" placeholder="What are you looking for?" />
    <input type="submit" id="searchsubmit" value="Find" />
</form>

Body:
You can solve it using codex: pre_get_posts and developer: pre_get_posts

add_action( 'pre_get_posts', 'search_woocommerce_product' );

function search_woocommerce_product( $query ) {
  if( ! is_admin() && is_search() && $query->is_main_query() ) {
    $query->set( 'post_type', 'product' );
  }
}

You can add further condition to this hook function like include in particular page only is_page

Or with certain short code like this

$pattern = get_shortcode_regex();
$patternToken = 'masterslider';

if (preg_match_all('/' . $pattern . '/s', get_the_content(), $matches) &&
array_key_exists(2, $matches) &&
in_array($patternToken, $matches[2])) {
//Your code logic
}


问:
Output matching lines in linux
I want to match the numbers in the first file with the 2nd column of second file and get the matching lines in a separate output file. Kindly let me know what is wrong with the code?

I have a list of numbers in a file IDS.txt

```<code>10028615
1003
10096344
10100
10107393
10113978
10163178
118747520
</code>```

I have a second File  called src1src22.txt

```<code>From src:'1'    To src:'22'
CHEMBL3549542   118747520
CHEMBL548732    44526300
CHEMBL1189709   11740251
CHEMBL405440    44297517
CHEMBL310280    10335685
</code>```

expected newoutput.txt

```<code>CHEMBL3549542   118747520
</code>```

I have written this code

```<code>while read line; do cat src1src22.txt | grep -i -w "$line"  >> newoutput.txt done<IDS.txt
</code>```

答:
Your command line works - except you're missing a semicolon:</p>

```<code>while read line; do grep -i -w "$line" src1src22.txt; done < IDS.txt >> newoutput.txt
</code>```

Title: Output matching lines in linux

Body:
I want to match the numbers in the first file with the 2nd column of second file and get the matching lines in a separate output file. Kindly let me know what is wrong with the code?

I have a list of numbers in a file IDS.txt

10028615
1003
10096344
10100
10107393
10113978
10163178
118747520

I have a second File  called src1src22.txt

From src:'1'    To src:'22'
CHEMBL3549542   118747520
CHEMBL548732    44526300
CHEMBL1189709   11740251
CHEMBL405440    44297517
CHEMBL310280    10335685

expected newoutput.txt

CHEMBL3549542   118747520

I have written this code

while read line; do cat src1src22.txt | grep -i -w "$line"  >> newoutput.txt done<IDS.txt

Body:
Your command line works - except you're missing a semicolon:

while read line; do grep -i -w "$line" src1src22.txt; done < IDS.txt >> newoutput.txt


问:
Scrape Div's content loading dynamically via ajax using Simple Html Dom
I want scrape data from other website page which loading table's data dynamically.
I am using Php and Simple Html Dom for scraping after searching lot did not find any solutions how to scrape dynamic data from web page? Or there is another way to do this?

I have to scrape table data from this url->https://fantasy.premierleague.com/a/leagues/standings/313/classic.

I am using below code to do this.

```<code>$url = "https://fantasy.premierleague.com/a/leagues/standings/313/classic";
$html = file_get_html($url);
$html->find('div#ismr-classic-standings');
foreach($html->find('table.ism-table--standings tr') as $row){
//But count($row)=0 due to late loading html in table.
}
</code>```

答:
Your page is calling another link and retrieving JSON data; try this code:</p>

```<code>include "simple_html_dom.php";
$MyWebsite = 'https://fantasy.premierleague.com/drf/leagues-classic-standings/313?phase=1&le-page=1&ls-page=1';
$html = file_get_html($MyWebsite);
$JSON_value = json_decode($html, true);
$results = $JSON_value['standings']['results'];

foreach($results as $result) {
    echo    $result['entry_name'] . '->' . $result['event_total'] . '<br/>';
}
</code>```

Body:
I want scrape data from other website page which loading table's data dynamically.
I am using Php and Simple Html Dom for scraping after searching lot did not find any solutions how to scrape dynamic data from web page? Or there is another way to do this?

I have to scrape table data from this url->https://fantasy.premierleague.com/a/leagues/standings/313/classic.

I am using below code to do this.

$url = "https://fantasy.premierleague.com/a/leagues/standings/313/classic";
$html = file_get_html($url);
$html->find('div#ismr-classic-standings');
foreach($html->find('table.ism-table--standings tr') as $row){
//But count($row)=0 due to late loading html in table.
}

Body:
Your page is calling another link and retrieving JSON data; try this code:

include "simple_html_dom.php";
$MyWebsite = 'https://fantasy.premierleague.com/drf/leagues-classic-standings/313?phase=1&le-page=1&ls-page=1';
$html = file_get_html($MyWebsite);
$JSON_value = json_decode($html, true);
$results = $JSON_value['standings']['results'];

foreach($results as $result) {
    echo    $result['entry_name'] . '->' . $result['event_total'] . '<br/>';
}


问:
UITextfield text position not animating while width constraint is animated
I have three UITextField aligned in a container used to choose a date.

At first only the month textfield is shown in the container and takes the full width, then when the user chose the month, the day textfield appear and they both take half of the container.

The text alignement in these textfields is centered.

My problem is that when I animate their size, the text doesn't animate and jumps directly to the final position while the width of the textfields animate correctly.

Step 1 : The TextField Before Animation

Step 2 : The TexField width is animating but the text is already in the final position

Step 3 : The TexField Finished Animating

My code used to animate the constraint :

```<code>monthTextfieldTrailingConstraint.priority = currentDateSelectionType == .month ? UILayoutPriorityDefaultHigh : UILayoutPriorityDefaultLow
dayTextfieldTrailingConstraint.priority = currentDateSelectionType == .day ? UILayoutPriorityDefaultHigh : UILayoutPriorityDefaultLow
yearTextfieldTrailingConstraint.priority = currentDateSelectionType == .year ? UILayoutPriorityDefaultHigh : UILayoutPriorityDefaultLow

UIView.animate(withDuration: nextStepAnimationDuration) {
    self.layoutIfNeeded()
}
</code>```

答:
I had almost the exact same question. Please see my question and its answer for reference: UITextField text jumps when animating width constraint

Solution Demo

The solution is to embed your textfields within another view (e.g. another UITextField or a UIView). In the gif below, I put a textfield within a textfield. Note that helloWorldTextField has a blue border to show its location within the second textfield behind it.

Instructions

For each field (month, day), make two textfields, e.g. monthTextField and monthBorderTextField.

Remove monthTextField's border and background color. Keep borderTextField's border and background color.

Center monthTextField within borderTextField.

Animate the width of borderTextField as needed.

Github link and Code

Here is the link to my project on Github: https://github.com/starkindustries/ConstraintAnimationTest

Here is the code for my test project for my MyViewController class. Everything else is setup in the storyboard which can be viewed on Github at the link above.

```<code>class MyViewController: UIViewController {

    // Hello World TextField Border var
    @IBOutlet weak var borderTextFieldWidth: NSLayoutConstraint!

    // Button Vars
    @IBOutlet weak var myButton: UIButton!
    var grow: Bool = false

    func animateGrowShrinkTextFields(grow: Bool, duration: TimeInterval) {
        if grow {
            UIView.animate(withDuration: duration, animations: {
                self.borderTextFieldWidth.constant = 330
                self.view.layoutIfNeeded()
            }, completion: { (finished: Bool) in
                print("Grow animation complete!")
            })
        } else {
            UIView.animate(withDuration: duration, animations: {
                self.borderTextFieldWidth.constant = 115
                self.view.layoutIfNeeded()
            }, completion: { (finished: Bool) in
                print("Shrink animation complete!")
            })
        }
    }

    @IBAction func toggle(){
        let duration: TimeInterval = 1.0
        grow = !grow
        let title = grow ? "Shrink" : "Grow"
        myButton.setTitle(title, for: UIControlState.normal)
        animateGrowShrinkTextFields(grow: grow, duration: duration)
    }
}
</code>```

Notes and References

What led me to this solution was @JimmyJames's comment: "You are just animating the UITextField width, but the content inside is not animated."

I researched how to animate font changes and came across this question: Is there a way to animate changing a UILabel's textAlignment?

In that question @CSmith mentioned that "you can animate the FRAME, not the textAlignment" https://stackoverflow.com/a/19251634/2179970

The accepted answer in that question suggests to use a UILabel within another frame. https://stackoverflow.com/a/19251735/2179970

Body:
I have three UITextField aligned in a container used to choose a date.

At first only the month textfield is shown in the container and takes the full width, then when the user chose the month, the day textfield appear and they both take half of the container.

The text alignement in these textfields is centered.

My problem is that when I animate their size, the text doesn't animate and jumps directly to the final position while the width of the textfields animate correctly.

Step 1 : The TextField Before Animation

Step 2 : The TexField width is animating but the text is already in the final position

Step 3 : The TexField Finished Animating

My code used to animate the constraint :

monthTextfieldTrailingConstraint.priority = currentDateSelectionType == .month ? UILayoutPriorityDefaultHigh : UILayoutPriorityDefaultLow
dayTextfieldTrailingConstraint.priority = currentDateSelectionType == .day ? UILayoutPriorityDefaultHigh : UILayoutPriorityDefaultLow
yearTextfieldTrailingConstraint.priority = currentDateSelectionType == .year ? UILayoutPriorityDefaultHigh : UILayoutPriorityDefaultLow

UIView.animate(withDuration: nextStepAnimationDuration) {
    self.layoutIfNeeded()
}

Body:
I had almost the exact same question. Please see my question and its answer for reference: UITextField text jumps when animating width constraint

Solution Demo

The solution is to embed your textfields within another view (e.g. another UITextField or a UIView). In the gif below, I put a textfield within a textfield. Note that helloWorldTextField has a blue border to show its location within the second textfield behind it.

Instructions

For each field (month, day), make two textfields, e.g. monthTextField and monthBorderTextField.

Remove monthTextField's border and background color. Keep borderTextField's border and background color.

Center monthTextField within borderTextField.

Animate the width of borderTextField as needed.

Github link and Code

Here is the link to my project on Github: https://github.com/starkindustries/ConstraintAnimationTest

Here is the code for my test project for my MyViewController class. Everything else is setup in the storyboard which can be viewed on Github at the link above.

class MyViewController: UIViewController {

    // Hello World TextField Border var
    @IBOutlet weak var borderTextFieldWidth: NSLayoutConstraint!

    // Button Vars
    @IBOutlet weak var myButton: UIButton!
    var grow: Bool = false

    func animateGrowShrinkTextFields(grow: Bool, duration: TimeInterval) {
        if grow {
            UIView.animate(withDuration: duration, animations: {
                self.borderTextFieldWidth.constant = 330
                self.view.layoutIfNeeded()
            }, completion: { (finished: Bool) in
                print("Grow animation complete!")
            })
        } else {
            UIView.animate(withDuration: duration, animations: {
                self.borderTextFieldWidth.constant = 115
                self.view.layoutIfNeeded()
            }, completion: { (finished: Bool) in
                print("Shrink animation complete!")
            })
        }
    }

    @IBAction func toggle(){
        let duration: TimeInterval = 1.0
        grow = !grow
        let title = grow ? "Shrink" : "Grow"
        myButton.setTitle(title, for: UIControlState.normal)
        animateGrowShrinkTextFields(grow: grow, duration: duration)
    }
}

Notes and References

What led me to this solution was @JimmyJames's comment: "You are just animating the UITextField width, but the content inside is not animated."

I researched how to animate font changes and came across this question: Is there a way to animate changing a UILabel's textAlignment?

In that question @CSmith mentioned that "you can animate the FRAME, not the textAlignment" https://stackoverflow.com/a/19251634/2179970

The accepted answer in that question suggests to use a UILabel within another frame. https://stackoverflow.com/a/19251735/2179970


问:
Preloading images and transition for CSS row with only one image
I've tried out this solution for rotating background images:

Original Article: Preloading images and transition for my simple Javascript option for CSS row

Now i'm trying to find out how to avoid the flickering if there is only one image.

答:
I believe what you're asking for is a smooth way of loading an image.  Here's an example on how to do that.  If it's not what you're looking for just comment.

$("#background").load(function () {
  $(this).fadeIn(500)
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#background {
  display:none;
  position:fixed;
  z-index:0; /* modify this number acording to how your page is layed out, so -1 will work for some webpages */
  object-fit: cover;
}</code>```

```
</div>
</div>
</p>

<p>Without the fading effect:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>$("#background").load(function () {
  $(this).show();
});</code>```

body {
  padding:0;
  margin:0;
}
#background {
  display:none;
  position:fixed;
  z-index:0; /* modify this number acording to how your page is layed out, so -1 will work for some webpages */
  object-fit: cover;
}```
<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>
<img id="background" src="http://neil.computer/stack/bg3.jpg" /></code>```

Body:
I believe what you're asking for is a smooth way of loading an image.  Here's an example on how to do that.  If it's not what you're looking for just comment.

$("#background").load(function () {
  $(this).fadeIn(500)
});

#background {
  display:none;
  position:fixed;
  z-index:0; /* modify this number acording to how your page is layed out, so -1 will work for some webpages */
  object-fit: cover;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<img id="background" src="http://neil.computer/stack/bg3.jpg" />

Without the fading effect:

$("#background").load(function () {
  $(this).show();
});

body {
  padding:0;
  margin:0;
}
#background {
  display:none;
  position:fixed;
  z-index:0; /* modify this number acording to how your page is layed out, so -1 will work for some webpages */
  object-fit: cover;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<img id="background" src="http://neil.computer/stack/bg3.jpg" />


问:
Send url to src other page
In the index page flowplayer if I change the value of the src = url with another, I view any video might be of interest to me, I wanted to make a page with a video playlist with several links where to click, send me to the index.html page of the player the new link and let me go then the player with the new source. I am new in programming, but with a great desire to learn, how can I pass several links to the value of src on the index.html page and simultaneously recall? I tried to send this way:

```<code>Send Page:

<html>
<body>
<a href="index.html?var="Http://mystreaming.com/video1.m3u8">Send Video 1</a>
<a href="index.html?var="Http://mystreaming.com/video2.m3u8">Send Video 1</a>
</body>
<html>
</code>```

while the index page I have:

```<code>index page:
<?php
$variabile_get = $_GET['var'];
?>

<head>
   <!-- Flowplayer library -->
   <script src="//releases.flowplayer.org/7.0.2/flowplayer.min.js"></script>
   <!-- Flowplayer hlsjs engine -->
   <script src="//releases.flowplayer.org/hlsjs/flowplayer.hlsjs.min.js"></script>
   <!-- player skin -->
   <link rel="stylesheet" href="skin/skin.css">

   <!-- site specific styling -->
   <style>
   body { font: 12px "Myriad Pro", "Lucida Grande", sans-serif; text-align: center; }
   .flowplayer { width: 80%; }
   </style>

   <!-- for video tag based installs flowplayer depends on jQuery 1.7.2+ -->
   <script src="https://code.jquery.com/jquery-1.11.2.min.js"></script>

   <!-- include flowplayer -->
   <script src="flowplayer.min.js"></script>

</head>

<body>

<div data-live="true" data-ratio="0.5625" class="flowplayer">

   <video data-title="Live stream">
   <source type="application/x-mpegurl"
        src=$_GET['var']>
   </video>

   </div>

</body>
</code>```

I realize that if it does not work, or you mess up your submission method of varibile url or the method in which the index page should recognize the url that will start in the src =, can you help me and make me understand where and why not? thank you.

答:
First off your index page should have a .php extention if you want to use php code.

Secondly you're not using $variabile_get in your code

in your src you'll need to echo the variable you made at the top like so:

src="<?php echo $variabile_get ?>"

or

src="<?= $variabile_get ?>" for short

Title: Send url to src other page

Body:
In the index page flowplayer if I change the value of the src = url with another, I view any video might be of interest to me, I wanted to make a page with a video playlist with several links where to click, send me to the index.html page of the player the new link and let me go then the player with the new source. I am new in programming, but with a great desire to learn, how can I pass several links to the value of src on the index.html page and simultaneously recall? I tried to send this way:

Send Page:

Send Video 1
Send Video 1

while the index page I have:

index page:
<?php
$variabile_get = $_GET['var'];
?>

   <link rel="stylesheet" href="skin/skin.css">

   <video data-title="Live stream">
   <source type="application/x-mpegurl"
        src=$_GET['var']>
   </video>

I realize that if it does not work, or you mess up your submission method of varibile url or the method in which the index page should recognize the url that will start in the src =, can you help me and make me understand where and why not? thank you.


问:
Hide Item in WPF ListView
I have a WPF XAML ListView which contains a GridView with two GridViewColumns.
The ListView has its ItemsSource bound to my class like so:

```<code><ListView Name="MyListView" ItemsSource="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type mynameSpace:MyClass}}, Path=ItemsSource}" >

<ListView.ItemContainerStyle>
    <Style TargetType="{x:Type ListViewItem}" BasedOn="{StaticResource ListViewItemStyle}">
        <Setter Property="HorizontalContentAlignment" Value="Stretch"/>
        <Setter Property="VerticalContentAlignment" Value="Stretch"/>
        <!--<Setter Property="Visibility" Value="{Binding RelativeSource={RelativeSource Self}, Path=IsEnabled, Converter={StaticResource BoolToVisibility}}"></Setter>-->
        <Setter Property="Visibility" Value="{Binding Path=IsEnabled, Converter={StaticResource BoolToVisibility}}"/>
    </Style>
</ListView.ItemContainerStyle>
<ListView.View>
   <GridView>
        // blah blah
   </GridView>
</ListView>
</code>```

I am attempting to hide a ListView item based on a property IsEnabled so I have tried the two methods above but neither work as the item still appears in the ListView:

```<code><Setter Property="Visibility" Value="{Binding RelativeSource={RelativeSource Self}, Path=IsEnabled, Converter={StaticResource BoolToVisibility}}"></Setter>
<Setter Property="Visibility" Value="{Binding Path=IsEnabled, Converter={StaticResource BoolToVisibility}}"/>
</code>```

How can I hide an item in a list view like this?

答:
Instead of :

```<code><Setter Property="Visibility" Value="{Binding Path=IsEnabled, Converter={StaticResource BoolToVisibility}}"/>
</code>```

Write this :

```<code><Setter Property="Visibility" Value="{Binding IsEnabled, Converter={StaticResource BoolToVisibility}, Mode=TwoWay}"/>
</code>```

Be sure to have a RaisePropertyChanged("IsEnabled"); in your ViewModel :

```<code>    private bool _isEnabled;
    public bool IsEnabled
    {
        get { return _isEnabled; }
        set
        {
            _isEnabled = value;

            RaisePropertyChanged("IsEnabled");
        }
    }
</code>```

Also, don't forget to write this where "XXX" is your current View as a UserControl, Window and so on :

```<code><XXX.Resources>
    <BooleanToVisibilityConverter x:Key="BoolToVis"></BooleanToVisibilityConverter>
</XXX.Resources>
</code>```

EDIT 1

Don't forget to link the right ViewModel as a DataContext in your View (using a ViewModelLocator) like :

```<code><XXX
    ...
    DataContext="{Binding MyCustomViewModel, Mode=OneWay, Source={StaticResource Locator}}"
      ...>
</code>```

where your Locator is set in your App.xaml as a ResourceDictionnary :

```<code>...
<ResourceDictionary>
   ...
   <XX:ViewModelLocator x:Key="Locator" d:IsDataSource="True" />
   ...
</ResourceDictionary>
...
</code>```

Title: Hide Item in WPF ListView

Body:
I have a WPF XAML ListView which contains a GridView with two GridViewColumns.
The ListView has its ItemsSource bound to my class like so:

<ListView Name="MyListView" ItemsSource="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type mynameSpace:MyClass}}, Path=ItemsSource}" >

<ListView.ItemContainerStyle>

</ListView.ItemContainerStyle>
<ListView.View>
   <GridView>
        // blah blah
   </GridView>
</ListView>

I am attempting to hide a ListView item based on a property IsEnabled so I have tried the two methods above but neither work as the item still appears in the ListView:

<Setter Property="Visibility" Value="{Binding RelativeSource={RelativeSource Self}, Path=IsEnabled, Converter={StaticResource BoolToVisibility}}"></Setter>
<Setter Property="Visibility" Value="{Binding Path=IsEnabled, Converter={StaticResource BoolToVisibility}}"/>

How can I hide an item in a list view like this?

Body:
Instead of :

<Setter Property="Visibility" Value="{Binding Path=IsEnabled, Converter={StaticResource BoolToVisibility}}"/>

Write this :

<Setter Property="Visibility" Value="{Binding IsEnabled, Converter={StaticResource BoolToVisibility}, Mode=TwoWay}"/>

Be sure to have a RaisePropertyChanged("IsEnabled"); in your ViewModel :

    private bool _isEnabled;
    public bool IsEnabled
    {
        get { return _isEnabled; }
        set
        {
            _isEnabled = value;

            RaisePropertyChanged("IsEnabled");
        }
    }

Also, don't forget to write this where "XXX" is your current View as a UserControl, Window and so on :

<XXX.Resources>
    <BooleanToVisibilityConverter x:Key="BoolToVis"></BooleanToVisibilityConverter>
</XXX.Resources>

EDIT 1

Don't forget to link the right ViewModel as a DataContext in your View (using a ViewModelLocator) like :

<XXX
    ...
    DataContext="{Binding MyCustomViewModel, Mode=OneWay, Source={StaticResource Locator}}"
      ...>

where your Locator is set in your App.xaml as a ResourceDictionnary :

...
<ResourceDictionary>
   ...
   <XX:ViewModelLocator x:Key="Locator" d:IsDataSource="True" />
   ...
</ResourceDictionary>
...


问:
Read and get item value of a remote json
how can I output the items "total_sales" or totals.orders from a remote json like http://www.example.com/api/stats.json in asp.net (4.5) with vb?</p>

```<code>{
  "sales": {
    "total_sales": "556.20",
    "net_sales": "402.35",
    "average_sales": "402.35",
    "total_orders": 12,
    "total_items": 24,
    "total_tax": "88.81",
    "total_shipping": "65.04",
    "total_refunds": 0,
    "total_discount": "0.00",
    "totals_grouped_by": "day",
    "totals": {
      "2017-03-17": {
        "sales": "556.20",
        "orders": 12,
        "items": 24,
        "tax": "88.80",
        "shipping": "65.04",
        "discount": "0.00",
        "customers": 0
      }
    },
    "total_customers": 0
  }
}
</code>```

答:
I believe this is what you're looking for.  Using your JSON string, I retrieve total sales.

First add references:

```<code>Imports System.Web.HttpContext
Imports System.Runtime.Serialization.Json
</code>```

Next Get the remote JSON, I'll assume that the response is the string you provide.  We use HttpWebRequest to get remote JSON.

```<code>    Dim req As HttpWebRequest = WebRequest.Create("www.SomeURL.com/?Parameter=somevalue")
    Dim resp As HttpWebResponse = req.GetResponse()

    Dim enc As Encoding = System.Text.Encoding.GetEncoding(1252)
    Dim loResponseStream As StreamReader = New StreamReader(resp.GetResponseStream(), enc)
    Dim Response As String = loResponseStream.ReadToEnd()
    Dim jss As JavaScriptSerializer = New JavaScriptSerializer()
    Dim dict As Object = jss.Deserialize(Of Dictionary(Of String, Object))(Response)
    Dim KeyValue As String = (dict("sales")("total_sales"))
    loResponseStream.Close()
</code>```

R/
Prescott ...

Body:
how can I output the items "total_sales" or totals.orders from a remote json like http://www.example.com/api/stats.json in asp.net (4.5) with vb?

{
  "sales": {
    "total_sales": "556.20",
    "net_sales": "402.35",
    "average_sales": "402.35",
    "total_orders": 12,
    "total_items": 24,
    "total_tax": "88.81",
    "total_shipping": "65.04",
    "total_refunds": 0,
    "total_discount": "0.00",
    "totals_grouped_by": "day",
    "totals": {
      "2017-03-17": {
        "sales": "556.20",
        "orders": 12,
        "items": 24,
        "tax": "88.80",
        "shipping": "65.04",
        "discount": "0.00",
        "customers": 0
      }
    },
    "total_customers": 0
  }
}

Body:
I believe this is what you're looking for.  Using your JSON string, I retrieve total sales.

First add references:

Imports System.Web.HttpContext
Imports System.Runtime.Serialization.Json

Next Get the remote JSON, I'll assume that the response is the string you provide.  We use HttpWebRequest to get remote JSON.

    Dim req As HttpWebRequest = WebRequest.Create("www.SomeURL.com/?Parameter=somevalue")
    Dim resp As HttpWebResponse = req.GetResponse()

    Dim enc As Encoding = System.Text.Encoding.GetEncoding(1252)
    Dim loResponseStream As StreamReader = New StreamReader(resp.GetResponseStream(), enc)
    Dim Response As String = loResponseStream.ReadToEnd()
    Dim jss As JavaScriptSerializer = New JavaScriptSerializer()
    Dim dict As Object = jss.Deserialize(Of Dictionary(Of String, Object))(Response)
    Dim KeyValue As String = (dict("sales")("total_sales"))
    loResponseStream.Close()

R/
Prescott ...


问:
Fortran `read(*,*)` in a DLL causes "run time error(39)" when called from VB6.0
Code in VB6.0 is:

```<code>Private Declare Sub suba Lib "D:\try_vb\c_dll\Dll1\Dll1\Debug\Dll1.dll" (ByRef a As Single, ByRef b As Single, ByRef c As Single)
Private Sub Command1_Click()
    Dim a As Single
    Dim b As Single
    Dim c As Single
    a = 10#
    b = 2#
    Call suba(a, b, c)
    Text1.Text = c
End Sub
</code>```

Code in Fortran's DLL is:

```<code>subroutine suba(a,b,c)
!DEC$ ATTRIBUTES stdcall,DLLEXPORT ::suba
!DEC$ ATTRIBUTES ALIAS:"suba"::suba
!DEC$ ATTRIBUTES reference :: a,b,c
    implicit none
    real::a
    real::b
    real::c
    real::aaa

    c=a+b
    read(*,*)aaa       !This sentence seems wrong
end subroutine
</code>```

If the line read(*,*)aaa doesn't exist, the program can return the right answer c=12, see below:

But when read(*,*)aaa exists, an error happens, that is

```<code>forrtl:severe(39):error during read,unit -4,file CONIN$
</code>```

What should I do?

答:
The most appropriate method is to do all I/O in one language(like helpers said).

Howerver,as a temporary solution,I find the function "AllocConsole()" can avoid the errors because a console window can be set.

Body:
Code in VB6.0 is:

Private Declare Sub suba Lib "D:\try_vb\c_dll\Dll1\Dll1\Debug\Dll1.dll" (ByRef a As Single, ByRef b As Single, ByRef c As Single)
Private Sub Command1_Click()
    Dim a As Single
    Dim b As Single
    Dim c As Single
    a = 10#
    b = 2#
    Call suba(a, b, c)
    Text1.Text = c
End Sub

Code in Fortran's DLL is:

subroutine suba(a,b,c)
!DEC$ ATTRIBUTES stdcall,DLLEXPORT ::suba
!DEC$ ATTRIBUTES ALIAS:"suba"::suba
!DEC$ ATTRIBUTES reference :: a,b,c
    implicit none
    real::a
    real::b
    real::c
    real::aaa

    c=a+b
    read(*,*)aaa       !This sentence seems wrong
end subroutine

If the line read(*,*)aaa doesn't exist, the program can return the right answer c=12, see below:

But when read(*,*)aaa exists, an error happens, that is

forrtl:severe(39):error during read,unit -4,file CONIN$

What should I do?