问:
JLabels only appear after resize of window
```<code>import javax.swing.*;
import java.awt.*;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;

public class Gui extends JFrame {

    JPanel panel1;
    JMenuBar daysMenu;
    JMenu[] days;
    JMenu chestMenu, backMenu, legsMenu, armsMenu, shouldersMenu;
    JMenuItem[] chest, back, legs, arms, shoulders;
    JLabel[] abs1, abs2;

    public Gui() {
        setResizable(true);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        // setSize(1000,1000);
        setTitle("Gym Workout Program");
        setLocationRelativeTo(null);

        days = new JMenu[7];
        for (int i = 0; i < days.length; i++) {
            days[i] = new JMenu();
        }
        days[0].setText("MONDAY");
        days[1].setText("TUESDAY");
        days[2].setText("WEDNESDAY");
        days[3].setText("THURSDAY");
        days[4].setText("FRIDAY");
        days[5].setText("SATURDAY");
        days[6].setText("SUNDAY");
        daysMenu = new JMenuBar();
        for (JMenu day : days) {
            daysMenu.add(day);
        }
        setJMenuBar(daysMenu);

        // bodyPartsMenu
        chestMenu = new JMenu("Chest(1X12,2X10,2X8)");
        chest = new JMenuItem[5];
        for (int i = 0; i < chest.length; i++) {
            chest[i] = new JMenuItem();
        }
        chest[0].setText("Bench Press");
        chest[1].setText("Incline Press w/ Dumbbells");
        chest[2].setText("Chest Flyes w/ Dumbbells 180˚");
        chest[3].setText("Pullover w/ Dumbbells");
        chest[4].setText("Dips(Reps till failure/3X10)");
        for (JMenuItem item : chest) {
            chestMenu.add(item);
        }
        days[0].add(chestMenu);

        backMenu = new JMenu("Back(1X12,2X10,2X8)");
        back = new JMenuItem[4];
        for (int i = 0; i < back.length; i++) {
            back[i] = new JMenuItem();
        }
        back[0].setText("Pullups 3X10 TRYHARD/ Κ.Λ. Front Pulldowns");
        back[1].setText("Bend Over Row with Bar");
        back[2].setText("Lat Pulldowns");
        back[3].setText("Rowing Machine");
        for (JMenuItem item : back) {
            backMenu.add(item);
        }
        days[1].add(backMenu);

        days[2].add("KENO");

        legsMenu = new JMenu("Legs (1X12,2X10,2X8)");
        legs = new JMenuItem[5];
        for (int i = 0; i < legs.length; i++) {
            legs[i] = new JMenuItem();
        }
        legs[0].setText("Body Squat/Smith Machine/ w/Dumbbells");
        legs[1].setText("Leg Extensions Machine");
        legs[2].setText("Leg Curls Machine");
        legs[3].setText("Leg Press/ Walking Lunges w/ Dumbbells");
        legs[4].setText("Calves Machine 4X15");
        for (JMenuItem item : legs) {
            legsMenu.add(item);
        }
        days[3].add(legsMenu);

        armsMenu = new JMenu("Arms (1X12,2X10,2X8)");
        arms = new JMenuItem[6];
        for (int i = 0; i < arms.length; i++) {
            arms[i] = new JMenuItem();
        }
        arms[0].setText("Dumbbell Curls w/ twist");
        arms[1].setText("Larry Scot");
        arms[2].setText("Dumbbell Hammer Curls");
        arms[3].setText("SkullCrushers w/ Bar/Dumbbells");
        arms[4].setText("Triceps Press Downs");
        arms[5].setText("Reverse Triceps Press Downs");
        int countSeperator = 0;
        for (JMenuItem item : arms) {
            countSeperator++;
            armsMenu.add(item);
            if (countSeperator == 3) {
                armsMenu.addSeparator();
            }
        }
        days[4].add(armsMenu);

        shouldersMenu = new JMenu("Shoulders(1X12,2X10,2X8)");
        shoulders = new JMenuItem[4];
        for (int i = 0; i < shoulders.length; i++) {
            shoulders[i] = new JMenuItem();
        }
        shoulders[0].setText("Military Press Smith Machine");
        shoulders[1].setText("Lateral Raises");
        shoulders[2].setText("Shoulder Press Machine");
        shoulders[3].setText("Traps");
        for (JMenuItem item : shoulders) {
            shouldersMenu.add(item);
        }
        days[5].add(shouldersMenu);

        days[6].add("KENO");

        abs1 = new JLabel[5];
        for (int i = 0; i < abs1.length; i++) {
            abs1[i] = new JLabel();
        }
        abs1[0].setText("Full and Elbow Plank(1min each)");
        abs1[1].setText("Both Sides Plank(35-50 sec)");
        abs1[2].setText("Knee Up-LsitHold High Bar(1min each)");
        abs1[3].setText("HollowBodyHold(2X1min) LowerBackDown");
        abs1[4].setText("Wheel(2X8reps)");

        abs2 = new JLabel[3];
        for (int i = 0; i < abs2.length; i++) {
            abs2[i] = new JLabel();
        }
        abs2[0].setText("Leg Raises(3X12)");
        abs2[1].setText("Knee Raises(3X12)");
        abs2[2].setText("Side and Obliques(3X12)");

        JLabel abs3 = new JLabel("Free Choice");

        JLabel abs = new JLabel("Abs(3/3+ Times/week)");
        add(abs, BorderLayout.NORTH);

        JRadioButton b1 = new JRadioButton("Style 1");
        JRadioButton b2 = new JRadioButton("Style 2");
        JRadioButton b3 = new JRadioButton("Style 3");
        ButtonGroup group = new ButtonGroup();
        group.add(b1);
        group.add(b2);
        group.add(b3);
        JPanel panel2 = new JPanel(new GridLayout(0, 1));

        b1.addItemListener(new ItemListener() {
            @Override
            public void itemStateChanged(ItemEvent e) {
                if (e.getStateChange() == ItemEvent.SELECTED) {
                    for (JLabel label : abs1) {
                        panel2.add(label);
                    }
                }
                if (e.getStateChange() == ItemEvent.DESELECTED) {
                    for (JLabel label : abs1) {
                        panel2.remove(label);
                    }
                }
            }
        });
        b2.addItemListener(new ItemListener() {
            @Override
            public void itemStateChanged(ItemEvent e) {
                if (e.getStateChange() == ItemEvent.SELECTED) {
                    for (JLabel label : abs2) {
                        panel2.add(label);
                    }
                }
                if (e.getStateChange() == ItemEvent.DESELECTED) {
                    for (JLabel label : abs2) {
                        panel2.remove(label);
                    }
                }
            }
        });
        b3.addItemListener(new ItemListener() {
            @Override
            public void itemStateChanged(ItemEvent e) {
                if (e.getStateChange() == ItemEvent.SELECTED) {
                    panel2.add(abs3);
                }
                if (e.getStateChange() == ItemEvent.DESELECTED) {
                    panel2.remove(abs3);
                }
            }
        });

        add(panel2, BorderLayout.LINE_END);
        panel1 = new JPanel(new GridLayout(0, 1, 50, 50));
        panel1.add(b1);
        panel1.add(b2);
        panel1.add(b3);

        add(panel1, BorderLayout.LINE_START);
        pack();
        setVisible(true);
    }
}
</code>```

I am trying to display my "abs workout" programme using JLabels and JRadioButtons.

I have used pack before setVisible and setVisible(true) after adding all the components but still my items(abs1 or abs2 or abs3) won't be displayed unless I resize my window.

When I click on Style 1 for example nothing happens and then if I resize my window everything seems to work fine.
Any help?

答: After changed the components in a container, you need to call revalidate() to schedule a re-layout of the container.</p>

Body:
import javax.swing.*;
import java.awt.*;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;

public class Gui extends JFrame {

    JPanel panel1;
    JMenuBar daysMenu;
    JMenu[] days;
    JMenu chestMenu, backMenu, legsMenu, armsMenu, shouldersMenu;
    JMenuItem[] chest, back, legs, arms, shoulders;
    JLabel[] abs1, abs2;

    public Gui() {
        setResizable(true);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        // setSize(1000,1000);
        setTitle("Gym Workout Program");
        setLocationRelativeTo(null);

        days = new JMenu[7];
        for (int i = 0; i < days.length; i++) {
            days[i] = new JMenu();
        }
        days[0].setText("MONDAY");
        days[1].setText("TUESDAY");
        days[2].setText("WEDNESDAY");
        days[3].setText("THURSDAY");
        days[4].setText("FRIDAY");
        days[5].setText("SATURDAY");
        days[6].setText("SUNDAY");
        daysMenu = new JMenuBar();
        for (JMenu day : days) {
            daysMenu.add(day);
        }
        setJMenuBar(daysMenu);

        // bodyPartsMenu
        chestMenu = new JMenu("Chest(1X12,2X10,2X8)");
        chest = new JMenuItem[5];
        for (int i = 0; i < chest.length; i++) {
            chest[i] = new JMenuItem();
        }
        chest[0].setText("Bench Press");
        chest[1].setText("Incline Press w/ Dumbbells");
        chest[2].setText("Chest Flyes w/ Dumbbells 180˚");
        chest[3].setText("Pullover w/ Dumbbells");
        chest[4].setText("Dips(Reps till failure/3X10)");
        for (JMenuItem item : chest) {
            chestMenu.add(item);
        }
        days[0].add(chestMenu);

        backMenu = new JMenu("Back(1X12,2X10,2X8)");
        back = new JMenuItem[4];
        for (int i = 0; i < back.length; i++) {
            back[i] = new JMenuItem();
        }
        back[0].setText("Pullups 3X10 TRYHARD/ Κ.Λ. Front Pulldowns");
        back[1].setText("Bend Over Row with Bar");
        back[2].setText("Lat Pulldowns");
        back[3].setText("Rowing Machine");
        for (JMenuItem item : back) {
            backMenu.add(item);
        }
        days[1].add(backMenu);

        days[2].add("KENO");

        legsMenu = new JMenu("Legs (1X12,2X10,2X8)");
        legs = new JMenuItem[5];
        for (int i = 0; i < legs.length; i++) {
            legs[i] = new JMenuItem();
        }
        legs[0].setText("Body Squat/Smith Machine/ w/Dumbbells");
        legs[1].setText("Leg Extensions Machine");
        legs[2].setText("Leg Curls Machine");
        legs[3].setText("Leg Press/ Walking Lunges w/ Dumbbells");
        legs[4].setText("Calves Machine 4X15");
        for (JMenuItem item : legs) {
            legsMenu.add(item);
        }
        days[3].add(legsMenu);

        armsMenu = new JMenu("Arms (1X12,2X10,2X8)");
        arms = new JMenuItem[6];
        for (int i = 0; i < arms.length; i++) {
            arms[i] = new JMenuItem();
        }
        arms[0].setText("Dumbbell Curls w/ twist");
        arms[1].setText("Larry Scot");
        arms[2].setText("Dumbbell Hammer Curls");
        arms[3].setText("SkullCrushers w/ Bar/Dumbbells");
        arms[4].setText("Triceps Press Downs");
        arms[5].setText("Reverse Triceps Press Downs");
        int countSeperator = 0;
        for (JMenuItem item : arms) {
            countSeperator++;
            armsMenu.add(item);
            if (countSeperator == 3) {
                armsMenu.addSeparator();
            }
        }
        days[4].add(armsMenu);

        shouldersMenu = new JMenu("Shoulders(1X12,2X10,2X8)");
        shoulders = new JMenuItem[4];
        for (int i = 0; i < shoulders.length; i++) {
            shoulders[i] = new JMenuItem();
        }
        shoulders[0].setText("Military Press Smith Machine");
        shoulders[1].setText("Lateral Raises");
        shoulders[2].setText("Shoulder Press Machine");
        shoulders[3].setText("Traps");
        for (JMenuItem item : shoulders) {
            shouldersMenu.add(item);
        }
        days[5].add(shouldersMenu);

        days[6].add("KENO");

        abs1 = new JLabel[5];
        for (int i = 0; i < abs1.length; i++) {
            abs1[i] = new JLabel();
        }
        abs1[0].setText("Full and Elbow Plank(1min each)");
        abs1[1].setText("Both Sides Plank(35-50 sec)");
        abs1[2].setText("Knee Up-LsitHold High Bar(1min each)");
        abs1[3].setText("HollowBodyHold(2X1min) LowerBackDown");
        abs1[4].setText("Wheel(2X8reps)");

        abs2 = new JLabel[3];
        for (int i = 0; i < abs2.length; i++) {
            abs2[i] = new JLabel();
        }
        abs2[0].setText("Leg Raises(3X12)");
        abs2[1].setText("Knee Raises(3X12)");
        abs2[2].setText("Side and Obliques(3X12)");

        JLabel abs3 = new JLabel("Free Choice");

        JLabel abs = new JLabel("Abs(3/3+ Times/week)");
        add(abs, BorderLayout.NORTH);

        JRadioButton b1 = new JRadioButton("Style 1");
        JRadioButton b2 = new JRadioButton("Style 2");
        JRadioButton b3 = new JRadioButton("Style 3");
        ButtonGroup group = new ButtonGroup();
        group.add(b1);
        group.add(b2);
        group.add(b3);
        JPanel panel2 = new JPanel(new GridLayout(0, 1));

        b1.addItemListener(new ItemListener() {
            @Override
            public void itemStateChanged(ItemEvent e) {
                if (e.getStateChange() == ItemEvent.SELECTED) {
                    for (JLabel label : abs1) {
                        panel2.add(label);
                    }
                }
                if (e.getStateChange() == ItemEvent.DESELECTED) {
                    for (JLabel label : abs1) {
                        panel2.remove(label);
                    }
                }
            }
        });
        b2.addItemListener(new ItemListener() {
            @Override
            public void itemStateChanged(ItemEvent e) {
                if (e.getStateChange() == ItemEvent.SELECTED) {
                    for (JLabel label : abs2) {
                        panel2.add(label);
                    }
                }
                if (e.getStateChange() == ItemEvent.DESELECTED) {
                    for (JLabel label : abs2) {
                        panel2.remove(label);
                    }
                }
            }
        });
        b3.addItemListener(new ItemListener() {
            @Override
            public void itemStateChanged(ItemEvent e) {
                if (e.getStateChange() == ItemEvent.SELECTED) {
                    panel2.add(abs3);
                }
                if (e.getStateChange() == ItemEvent.DESELECTED) {
                    panel2.remove(abs3);
                }
            }
        });

        add(panel2, BorderLayout.LINE_END);
        panel1 = new JPanel(new GridLayout(0, 1, 50, 50));
        panel1.add(b1);
        panel1.add(b2);
        panel1.add(b3);

        add(panel1, BorderLayout.LINE_START);
        pack();
        setVisible(true);
    }
}

I am trying to display my "abs workout" programme using JLabels and JRadioButtons.

I have used pack before setVisible and setVisible(true) after adding all the components but still my items(abs1 or abs2 or abs3) won't be displayed unless I resize my window.

When I click on Style 1 for example nothing happens and then if I resize my window everything seems to work fine.
Any help?


来源: stackexchange

问:
Unable to store parsed items as dictionary
I've written a tiny script in python using BeautifulSoup to parse some items out of some element stored within content variable within the below script. I do not wish to append items to the previously created empty dictionary; rather, i wish to parse it on the fly. However, I tried but could not achieve that. Any help would be highly appreciated.

This is my attempt:

```<code>from bs4 import BeautifulSoup

content="""
<table class="data">
    <tbody>
        <tr class="blue">
            <td>hot</td>
            <td>cold</td>
        </tr>
        <tr>
            <td>day</td>
            <td>night</td>
        </tr>
    </tbody>
</table>
"""
soup = BeautifulSoup(content,'lxml')
for items in soup.select('tr'):
    data = [item.text for item in items.select("td")]
    dict_val = {data[0] : data[1]}
    print(dict_val)
</code>```

The way I'm getting the output:

```<code>{'hot': 'cold'}
{'day': 'night'}
</code>```

The way I expect to have the output:

```<code>{'hot': 'cold','day': 'night'}
</code>```

答:
You can create a dictionary outside the for-loop:

```<code>soup = BeautifulSoup(content,'lxml')
d = {}
for items in soup.select('tr'):
   data = [item.text for item in items.select("td")]
   d[data[0]] = data[1]
print(d)
</code>```

Or, you can create a dictionary in one line:

```<code>from bs4 import BeautifulSoup as soup
s = [i.text for i in soup(content, 'lxml').findAll('td')]
new_s = dict([s[i:i+2] for i in range(0, len(s), 2)])
</code>```

Output:

```<code>{u'hot': u'cold', u'day': u'night'}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I've written a tiny script in python using BeautifulSoup to parse some items out of some element stored within content variable within the below script. I do not wish to append items to the previously created empty dictionary; rather, i wish to parse it on the fly. However, I tried but could not achieve that. Any help would be highly appreciated.

This is my attempt:

from bs4 import BeautifulSoup

content="""

            hot
            cold

            day
            night

"""
soup = BeautifulSoup(content,'lxml')
for items in soup.select('tr'):
    data = [item.text for item in items.select("td")]
    dict_val = {data[0] : data[1]}
    print(dict_val)

The way I'm getting the output:

{'hot': 'cold'}
{'day': 'night'}

The way I expect to have the output:

{'hot': 'cold','day': 'night'}

Body:
You can create a dictionary outside the for-loop:

soup = BeautifulSoup(content,'lxml')
d = {}
for items in soup.select('tr'):
   data = [item.text for item in items.select("td")]
   d[data[0]] = data[1]
print(d)

Or, you can create a dictionary in one line:

from bs4 import BeautifulSoup as soup
s = [i.text for i in soup(content, 'lxml').findAll('td')]
new_s = dict([s[i:i+2] for i in range(0, len(s), 2)])

Output:

{u'hot': u'cold', u'day': u'night'}


问:
Qt Creator Nothing happen when call a static library from an application
Qt Creator Nothing happen when call a static library from an application.
I have these line of codes as my main.cpp main app file:

```<code>#include "mainwindow.h"
#include <QApplication>
#include<src/main.cpp>
#include <src/john.cpp>

int main(int argc, char *argv[])
{
//John ll;
main2;

//    QApplication a2(argc, argv);
//    MainWindow w2;
//    w2.show();

//    MainWindow mainWindow;
//  //mainWindow.parseCmdLine();   //modified
//   // mainWindow.show();

   // return a2.exec();
//return 1;

}
</code>```

and that's .Pro file:

```<code>#-------------------------------------------------
#
# Project created by QtCreator 2017-12-08T05:51:54
#
#-------------------------------------------------

QT       += core gui

greaterThan(QT_MAJOR_VERSION, 4): QT += widgets

TARGET = untitled
TEMPLATE = app

SOURCES += main.cpp\
        mainwindow.cpp

HEADERS  += mainwindow.h

FORMS    += mainwindow.ui

INCLUDEPATH += ../application
LIBS += -L../application/release/ -lApplication
#TARGET = ../app17-exe # move executable one dire up
</code>```

and my main2.cpp static library file is as below:

```<code>/*****************************************************************************
 *                                                                           *
 *  Elmer, A Finite Element Software for Multiphysical Problems              *
 *                                                                           *
 *  Copyright 1st April 1995 - , CSC - IT Center for Science Ltd., Finland    *
 *                                                                           *
 *  This program is free software; you can redistribute it and/or            *
 *  modify it under the terms of the GNU General Public License              *
 *  as published by the Free Software Foundation; either version 2           *
 *  of the License, or (at your option) any later version.                   *
 *                                                                           *
 *  This program is distributed in the hope that it will be useful,          *
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of           *
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the            *
 *  GNU General Public License for more details.                             *
 *                                                                           *
 *  You should have received a copy of the GNU General Public License        *
 *  along with this program (in file fem/GPL-2); if not, write to the        *
 *  Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,         *
 *  Boston, MA 02110-1301, USA.                                              *
 *                                                                           *
 *****************************************************************************/

/*****************************************************************************
 *                                                                           *
 *  ElmerGUI main                                                            *
 *                                                                           *
 *****************************************************************************
 *                                                                           *
 *  Authors: Mikko Lyly, Juha Ruokolainen and Peter Råback                   *
 *  Email:   Juha.Ruokolainen@csc.fi                                         *
 *  Web:     http://www.csc.fi/elmer                                         *
 *  Address: CSC - IT Center for Science Ltd.                                 *
 *           Keilaranta 14                                                   *
 *           02101 Espoo, Finland                                            *
 *                                                                           *
 *  Original Date: 15 Mar 2008                                               *
 *                                                                           *
 *****************************************************************************/

//#include "mainwindow.h"
//#include <QApplication>
//#include<src/main.cpp>

//int main(int argc, char *argv[])
//{

//main2;
//    return a.exec();
//}

#include <QApplication>
//#include <iostream>
#include "mainwindow.h"

using namespace std;
/*
#ifdef __APPLE__
#include <mach-o/dyld.h>
#include <stdlib.h>
#endif

int main2(int argc, char *argv[])
{
    MainWindow mainWindow2;
  //mainWindow.parseCmdLine();   //modified
    mainWindow2.showFullScreen();

#ifdef __APPLE__
// we'll change ENVIRONMENT so that the Elmer binaries and libraries
// hidden wihtin the application bundle will be correctly found

  char executablePath[MAXPATHLENGTH] = {0};
  uint32_t len = MAXPATHLENGTH;
  if(! _NSGetExecutablePath( (char*) executablePath, &len)){
    // remove executable name from path:
    *(strrchr(executablePath,'/'))='\0';
    char *oldValue = 0, *newValue = 0;

    oldValue = getenv("PATH");
    asprintf(&newValue, "%s/../bin:%s",executablePath,oldValue);
    setenv("PATH",newValue,1);
    free(newValue);

    oldValue = getenv("DYLD_LIBRARY_PATH");
    asprintf(&newValue,"%s/../lib:%s",executablePath,oldValue);
    setenv("DYLD_LIBRARY_PATH",newValue,0);
    free(newValue);

    asprintf(&newValue,"%s/..",executablePath);
    setenv("ELMER_HOME",newValue,0);
    free(newValue);

    asprintf(&newValue,"%s/../share/elmerpost",executablePath);
    setenv("ELMER_POST_HOME",newValue,0);
    free(newValue);

#ifdef DEBUG
    printf("PATH = %s\nDYLD_LIBRARY_PATH=%s\nELMER_HOME=%s\n",
       getenv("PATH"),
       getenv("DYLD_LIBRARY_PATH"),
       getenv("ELMER_HOME"));
#endif
  }
#endif

  //========================================================================

  QApplication app(argc, argv);

  QStringList argList = QCoreApplication::arguments();

  cout << "Usage:" << endl;

  if(argList.contains("-h") || argList.contains("--help")) {
    cout << "Usage:" << endl;
    cout << "  ElmerGUI [OPTION [FILE|DIR]]..." << endl;
    cout << endl;
    cout << "Graphical user interface and mesh generator for Elmer" << endl;
    cout << endl;
    cout << "Application options:" << endl;
    cout << " -h, --help       Show help options" << endl;
    cout << " -i <string>      Select input file" << endl;
    cout << " -o <string>      Select output dir" << endl;
    cout << " -nogui           Disable GUI" << endl;
    cout << " -e               Exit after saving" << endl;
    cout << endl;
    return 0;
  }

  MainWindow mainWindow;
//mainWindow.parseCmdLine();   //modified
  mainWindow.showFullScreen();

  QApplication a(argc, argv);
  MainWindow w;
  w.show();

  printf("sss");
  char o;
  scanf("%c",o);

 //  return a.exec();

 // return app.exec();
  return 900;
}
*/
int main2(int argc, char *argv[])
{
//John ll;
//main2;

    QApplication a2(argc, argv);
    MainWindow w2;
    w2.show();

   // MainWindow mainWindow;
  //mainWindow.parseCmdLine();   //modified
   // mainWindow.show();

    return a2.exec();
//return 1;

}
</code>```

and it's .pro file:

```<code>#==============================================================================
#
#      ElmerGUI: qmake project file for Unix, Win32, and MacX
#
#==============================================================================

include(../ElmerGUI.pri)

#------------------------------------------------------------------------------
# Target:
#------------------------------------------------------------------------------
TARGET = Application
TEMPLATE = app
CONFIG += release

#------------------------------------------------------------------------------
# Installation directory and files:
#------------------------------------------------------------------------------
target.path = $${ELMERGUI_HOME}
INSTALLS += target
edf.path = $${ELMERGUI_HOME}/edf
edf.files = edf/*
INSTALLS += edf
edf-extra.path = $${ELMERGUI_HOME}/edf-extra
edf-extra.files = edf-extra/*
INSTALLS += edf-extra

#------------------------------------------------------------------------------
# Compiler flags:
#------------------------------------------------------------------------------
#CONFIG += warn_off

 #QMAKE_LFLAGS += -Wl,-rpath,$$(VTKHOME)/lib/vtk-5.2

#win32 {
 # QMAKE_LFLAGS += /NODEFAULTLIB:library
#}

TEMPLATE = lib
CONFIG += staticlib
#CONFIG += warn_off

 QMAKE_LFLAGS += -Wl,-rpath,$$(VTKHOME)/lib/vtk-5.2

win32 {
 QMAKE_LFLAGS += /NODEFAULTLIB:library
}

#win32 {
 #       TARGET = test
  #      LIBS += -lliba.lib \
   #             libb.lib
#
 #       CONFIG(release, debug|release){
  #              QMAKE_LFLAGS += /NODEFAULTLIB:libcmt
   #     }
    #    CONFIG(debug, debug|release){
     #           QMAKE_LFLAGS += /NODEFAULTLIB:libcmtd
      #  }
#}

QMAKE_CXXFLAGS_DEBUG += -g
QMAKE_CXXFLAGS += -g

#------------------------------------------------------------------------------
# Directories:
#------------------------------------------------------------------------------
DEPENDPATH += . src forms plugins vtkpost cad twod
INCLUDEPATH += .
MOC_DIR = tmp
OBJECTS_DIR = tmp
RCC_DIR = tmp
UI_DIR = tmp
DESTDIR = .

#------------------------------------------------------------------------------
# QT:
#------------------------------------------------------------------------------
QT += opengl xml script
CONFIG += uitools
QT+=uitools
#------------------------------------------------------------------------------
# MATC (see ../matc/README for more details):
#------------------------------------------------------------------------------
contains(DEFINES, EG_MATC) {
   LIBPATH += ../matc/lib
   LIBS += -lmatc
}

#------------------------------------------------------------------------------
# NETGEN (see ../netgen/README for more details):
#------------------------------------------------------------------------------
INCLUDEPATH += ../netgen/libsrc/interface
LIBPATH += ../netgen/ngcore
LIBS += -lng

#------------------------------------------------------------------------------
# QWT:
#------------------------------------------------------------------------------
contains(DEFINES, EG_QWT) {
   INCLUDEPATH += $${QWT_INCLUDEPATH}
   LIBPATH += $${QWT_LIBPATH}
   LIBS += $${QWT_LIBS}
}

#------------------------------------------------------------------------------
# VTK:
#------------------------------------------------------------------------------
contains(DEFINES, EG_VTK) {
   INCLUDEPATH += $${VTK_INCLUDEPATH}
   LIBPATH += $${VTK_LIBPATH}
   LIBS += $${VTK_LIBS}
}

#------------------------------------------------------------------------------
# OpenCASCADE:
#------------------------------------------------------------------------------
contains(DEFINES, EG_OCC) {
   contains(BITS, 64):  DEFINES += _OCC64

   unix: DEFINES += HAVE_CONFIG_H HAVE_IOSTREAM HAVE_FSTREAM HAVE_LIMITS_H
   win32: DEFINES += WNT CSFDB
   macx: DEFINED -= EG_OCC         # not supported at the moment

   INCLUDEPATH += $${OCC_INCLUDEPATH}
   LIBPATH += $${OCC_LIBPATH}
   LIBS += $${OCC_LIBS}
}

#------------------------------------------------------------------------------
# PYTHONQT (see ../PythonQt/README for more details):
#------------------------------------------------------------------------------
contains(DEFINES, EG_PYTHONQT) {
   INCLUDEPATH += $${PY_INCLUDEPATH} ../PythonQt/src
   LIBPATH += $${PY_LIBPATH} ../PythonQt/lib
   LIBS += $${PY_LIBS} -lPythonQt
}

#------------------------------------------------------------------------------
# Process info query on win32:
#------------------------------------------------------------------------------
win32: LIBS += -lpsapi

#------------------------------------------------------------------------------
# OpenGL GLU
#------------------------------------------------------------------------------
unix:  LIBS += -lGLU
#------------------------------------------------------------------------------
# Input files:
#------------------------------------------------------------------------------
HEADERS += src/bodypropertyeditor.h \
           src/boundarydivision.h \
           src/boundarypropertyeditor.h \
           src/checkmpi.h \
           src/dynamiceditor.h \
           src/edfeditor.h \
           src/egini.h \
           src/generalsetup.h \
           src/glcontrol.h \
           src/glwidget.h \
           src/helpers.h \
           src/mainwindow.h \
           src/materiallibrary.h \
           src/maxlimits.h \
           src/meshcontrol.h \
           src/meshingthread.h \
           src/meshtype.h \
           src/meshutils.h \
           src/operation.h \
           src/parallel.h \
           src/projectio.h \
           src/sifgenerator.h \
           src/sifwindow.h \
           src/solverparameters.h \
           src/summaryeditor.h \
           plugins/egconvert.h \
           plugins/egdef.h \
           plugins/egmain.h \
           plugins/egmesh.h \
           plugins/egnative.h \
           plugins/egtypes.h \
           plugins/egutils.h \
           plugins/elmergrid_api.h \
           plugins/nglib_api.h \
           plugins/tetgen.h \
           plugins/tetlib_api.h \
           twod/renderarea.h \
           twod/twodview.h \
           twod/curveeditor.h \
    src/john.h

FORMS += forms/bodypropertyeditor.ui \
         forms/boundarydivision.ui \
         forms/boundarypropertyeditor.ui \
         forms/generalsetup.ui \
         forms/glcontrol.ui \
         forms/materiallibrary.ui \
         forms/meshcontrol.ui \
         forms/parallel.ui \
         forms/solverparameters.ui \
         forms/summaryeditor.ui

SOURCES += src/bodypropertyeditor.cpp \
           src/boundarydivision.cpp \
           src/boundarypropertyeditor.cpp \
           src/checkmpi.cpp \
           src/dynamiceditor.cpp \
           src/edfeditor.cpp \
           src/egini.cpp \
           src/generalsetup.cpp \
           src/glcontrol.cpp \
           src/glwidget.cpp \
           src/helpers.cpp \
           src/main.cpp \
           src/mainwindow.cpp \
           src/materiallibrary.cpp \
           src/maxlimits.cpp \
           src/meshcontrol.cpp \
           src/meshingthread.cpp \
           src/meshtype.cpp \
           src/meshutils.cpp \
           src/operation.cpp \
           src/parallel.cpp \
           src/projectio.cpp \
           src/sifgenerator.cpp \
           src/sifwindow.cpp \
           src/solverparameters.cpp \
           src/summaryeditor.cpp \
           plugins/egconvert.cpp \
           plugins/egmain.cpp \
           plugins/egmesh.cpp \
           plugins/egnative.cpp \
           plugins/egutils.cpp \
           plugins/elmergrid_api.cpp \
           plugins/nglib_api.cpp \
           plugins/tetlib_api.cpp \
           twod/renderarea.cpp \
           twod/twodview.cpp \
           twod/curveeditor.cpp \
    src/john.cpp

#------------------------------------------------------------------------------
# Optional input files:
#------------------------------------------------------------------------------
contains(DEFINES, EG_QWT) {
   HEADERS += src/convergenceview.h
   SOURCES += src/convergenceview.cpp
}

contains(DEFINES, EG_VTK) {
   HEADERS += vtkpost/axes.h \
              vtkpost/featureedge.h \
              vtkpost/vtkpost.h \
              vtkpost/isosurface.h \
              vtkpost/isocontour.h \
              vtkpost/epmesh.h \
              vtkpost/colorbar.h \
              vtkpost/meshpoint.h \
              vtkpost/meshedge.h \
              vtkpost/surface.h \
              vtkpost/preferences.h \
              vtkpost/vector.h \
              vtkpost/readepfile.h \
              vtkpost/streamline.h \
              vtkpost/timestep.h \
              vtkpost/ecmaconsole.h \
              vtkpost/text.h

   FORMS += vtkpost/axes.ui \
            vtkpost/featureedge.ui \
            vtkpost/isosurface.ui \
            vtkpost/isocontour.ui \
            vtkpost/colorbar.ui \
            vtkpost/surface.ui \
            vtkpost/meshpoint.ui \
            vtkpost/meshedge.ui \
            vtkpost/preferences.ui \
            vtkpost/vector.ui \
            vtkpost/readepfile.ui \
            vtkpost/streamline.ui \
            vtkpost/timestep.ui \
            vtkpost/text.ui

   SOURCES += vtkpost/axes.cpp \
              vtkpost/featureedge.cpp \
              vtkpost/vtkpost.cpp \
              vtkpost/isosurface.cpp \
              vtkpost/isocontour.cpp \
              vtkpost/epmesh.cpp \
              vtkpost/colorbar.cpp \
              vtkpost/meshpoint.cpp \
              vtkpost/meshedge.cpp \
              vtkpost/surface.cpp \
              vtkpost/preferences.cpp \
              vtkpost/vector.cpp \
              vtkpost/readepfile.cpp \
              vtkpost/streamline.cpp \
              vtkpost/timestep.cpp \
              vtkpost/ecmaconsole.cpp \
              vtkpost/text.cpp

   contains(DEFINES, EG_MATC) {
      HEADERS += vtkpost/matc.h \
                 vtkpost/mc.h

      FORMS += vtkpost/matc.ui

      SOURCES += vtkpost/matc.cpp
   }
}

contains(DEFINES, EG_OCC) {
   HEADERS += cad/cadview.h \
              cad/cadpreferences.h

   FORMS += cad/cadpreferences.ui

   SOURCES += cad/cadview.cpp \
              cad/cadpreferences.cpp
}

#------------------------------------------------------------------------------
# Resource files:
#------------------------------------------------------------------------------
RESOURCES += ElmerGUI.qrc
win32: RC_FILE += ElmerGUI.rc
macx: RC_FILE = M3Dicon.icns

#------------------------------------------------------------------------------
# END OF FILE
#------------------------------------------------------------------------------
</code>```

but nothing happen when I compile the project, No error appears but I think app could not call static lib.so what should I do?

答:
Your main in main.cpp should be:

```<code>int main(int argc, char *argv[])
{
  return main2(argc, argv);
}
</code>```

your line

```<code>main2;
</code>```

do compiles fine, but does nothing.

Body:
Qt Creator Nothing happen when call a static library from an application.
I have these line of codes as my main.cpp main app file:

#include "mainwindow.h"
#include <QApplication>
#include<src/main.cpp>
#include <src/john.cpp>

int main(int argc, char *argv[])
{
//John ll;
main2;

//    QApplication a2(argc, argv);
//    MainWindow w2;
//    w2.show();

//    MainWindow mainWindow;
//  //mainWindow.parseCmdLine();   //modified
//   // mainWindow.show();

   // return a2.exec();
//return 1;

}

and that's .Pro file:

#-------------------------------------------------
#
# Project created by QtCreator 2017-12-08T05:51:54
#
#-------------------------------------------------

QT       += core gui

greaterThan(QT_MAJOR_VERSION, 4): QT += widgets

TARGET = untitled
TEMPLATE = app

SOURCES += main.cpp\
        mainwindow.cpp

HEADERS  += mainwindow.h

FORMS    += mainwindow.ui

INCLUDEPATH += ../application
LIBS += -L../application/release/ -lApplication
#TARGET = ../app17-exe # move executable one dire up

and my main2.cpp static library file is as below:

/*****************************************************************************
 *                                                                           *
 *  Elmer, A Finite Element Software for Multiphysical Problems              *
 *                                                                           *
 *  Copyright 1st April 1995 - , CSC - IT Center for Science Ltd., Finland    *
 *                                                                           *
 *  This program is free software; you can redistribute it and/or            *
 *  modify it under the terms of the GNU General Public License              *
 *  as published by the Free Software Foundation; either version 2           *
 *  of the License, or (at your option) any later version.                   *
 *                                                                           *
 *  This program is distributed in the hope that it will be useful,          *
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of           *
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the            *
 *  GNU General Public License for more details.                             *
 *                                                                           *
 *  You should have received a copy of the GNU General Public License        *
 *  along with this program (in file fem/GPL-2); if not, write to the        *
 *  Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,         *
 *  Boston, MA 02110-1301, USA.                                              *
 *                                                                           *
 *****************************************************************************/

/*****************************************************************************
 *                                                                           *
 *  ElmerGUI main                                                            *
 *                                                                           *
 *****************************************************************************
 *                                                                           *
 *  Authors: Mikko Lyly, Juha Ruokolainen and Peter Råback                   *
 *  Email:   Juha.Ruokolainen@csc.fi                                         *
 *  Web:     http://www.csc.fi/elmer                                         *
 *  Address: CSC - IT Center for Science Ltd.                                 *
 *           Keilaranta 14                                                   *
 *           02101 Espoo, Finland                                            *
 *                                                                           *
 *  Original Date: 15 Mar 2008                                               *
 *                                                                           *
 *****************************************************************************/

//#include "mainwindow.h"
//#include <QApplication>
//#include<src/main.cpp>

//int main(int argc, char *argv[])
//{

//main2;
//    return a.exec();
//}

#include <QApplication>
//#include <iostream>
#include "mainwindow.h"

using namespace std;
/*
#ifdef __APPLE__
#include <mach-o/dyld.h>
#include <stdlib.h>
#endif

int main2(int argc, char *argv[])
{
    MainWindow mainWindow2;
  //mainWindow.parseCmdLine();   //modified
    mainWindow2.showFullScreen();

#ifdef __APPLE__
// we'll change ENVIRONMENT so that the Elmer binaries and libraries
// hidden wihtin the application bundle will be correctly found

  char executablePath[MAXPATHLENGTH] = {0};
  uint32_t len = MAXPATHLENGTH;
  if(! _NSGetExecutablePath( (char*) executablePath, &len)){
    // remove executable name from path:
    *(strrchr(executablePath,'/'))='\0';
    char *oldValue = 0, *newValue = 0;

    oldValue = getenv("PATH");
    asprintf(&newValue, "%s/../bin:%s",executablePath,oldValue);
    setenv("PATH",newValue,1);
    free(newValue);

    oldValue = getenv("DYLD_LIBRARY_PATH");
    asprintf(&newValue,"%s/../lib:%s",executablePath,oldValue);
    setenv("DYLD_LIBRARY_PATH",newValue,0);
    free(newValue);

    asprintf(&newValue,"%s/..",executablePath);
    setenv("ELMER_HOME",newValue,0);
    free(newValue);

    asprintf(&newValue,"%s/../share/elmerpost",executablePath);
    setenv("ELMER_POST_HOME",newValue,0);
    free(newValue);

#ifdef DEBUG
    printf("PATH = %s\nDYLD_LIBRARY_PATH=%s\nELMER_HOME=%s\n",
       getenv("PATH"),
       getenv("DYLD_LIBRARY_PATH"),
       getenv("ELMER_HOME"));
#endif
  }
#endif

  //========================================================================

  QApplication app(argc, argv);

  QStringList argList = QCoreApplication::arguments();

  cout << "Usage:" << endl;

  if(argList.contains("-h") || argList.contains("--help")) {
    cout << "Usage:" << endl;
    cout << "  ElmerGUI [OPTION [FILE|DIR]]..." << endl;
    cout << endl;
    cout << "Graphical user interface and mesh generator for Elmer" << endl;
    cout << endl;
    cout << "Application options:" << endl;
    cout << " -h, --help       Show help options" << endl;
    cout << " -i <string>      Select input file" << endl;
    cout << " -o <string>      Select output dir" << endl;
    cout << " -nogui           Disable GUI" << endl;
    cout << " -e               Exit after saving" << endl;
    cout << endl;
    return 0;
  }

  MainWindow mainWindow;
//mainWindow.parseCmdLine();   //modified
  mainWindow.showFullScreen();

  QApplication a(argc, argv);
  MainWindow w;
  w.show();

  printf("sss");
  char o;
  scanf("%c",o);

 //  return a.exec();

 // return app.exec();
  return 900;
}
*/
int main2(int argc, char *argv[])
{
//John ll;
//main2;

    QApplication a2(argc, argv);
    MainWindow w2;
    w2.show();

   // MainWindow mainWindow;
  //mainWindow.parseCmdLine();   //modified
   // mainWindow.show();

    return a2.exec();
//return 1;

}

and it's .pro file:

#==============================================================================
#
#      ElmerGUI: qmake project file for Unix, Win32, and MacX
#
#==============================================================================

include(../ElmerGUI.pri)

#------------------------------------------------------------------------------
# Target:
#------------------------------------------------------------------------------
TARGET = Application
TEMPLATE = app
CONFIG += release

#------------------------------------------------------------------------------
# Installation directory and files:
#------------------------------------------------------------------------------
target.path = $${ELMERGUI_HOME}
INSTALLS += target
edf.path = $${ELMERGUI_HOME}/edf
edf.files = edf/*
INSTALLS += edf
edf-extra.path = $${ELMERGUI_HOME}/edf-extra
edf-extra.files = edf-extra/*
INSTALLS += edf-extra

#------------------------------------------------------------------------------
# Compiler flags:
#------------------------------------------------------------------------------
#CONFIG += warn_off

 #QMAKE_LFLAGS += -Wl,-rpath,$$(VTKHOME)/lib/vtk-5.2

#win32 {
 # QMAKE_LFLAGS += /NODEFAULTLIB:library
#}

TEMPLATE = lib
CONFIG += staticlib
#CONFIG += warn_off

 QMAKE_LFLAGS += -Wl,-rpath,$$(VTKHOME)/lib/vtk-5.2

win32 {
 QMAKE_LFLAGS += /NODEFAULTLIB:library
}

#win32 {
 #       TARGET = test
  #      LIBS += -lliba.lib \
   #             libb.lib
#
 #       CONFIG(release, debug|release){
  #              QMAKE_LFLAGS += /NODEFAULTLIB:libcmt
   #     }
    #    CONFIG(debug, debug|release){
     #           QMAKE_LFLAGS += /NODEFAULTLIB:libcmtd
      #  }
#}

QMAKE_CXXFLAGS_DEBUG += -g
QMAKE_CXXFLAGS += -g

#------------------------------------------------------------------------------
# Directories:
#------------------------------------------------------------------------------
DEPENDPATH += . src forms plugins vtkpost cad twod
INCLUDEPATH += .
MOC_DIR = tmp
OBJECTS_DIR = tmp
RCC_DIR = tmp
UI_DIR = tmp
DESTDIR = .

#------------------------------------------------------------------------------
# QT:
#------------------------------------------------------------------------------
QT += opengl xml script
CONFIG += uitools
QT+=uitools
#------------------------------------------------------------------------------
# MATC (see ../matc/README for more details):
#------------------------------------------------------------------------------
contains(DEFINES, EG_MATC) {
   LIBPATH += ../matc/lib
   LIBS += -lmatc
}

#------------------------------------------------------------------------------
# NETGEN (see ../netgen/README for more details):
#------------------------------------------------------------------------------
INCLUDEPATH += ../netgen/libsrc/interface
LIBPATH += ../netgen/ngcore
LIBS += -lng

#------------------------------------------------------------------------------
# QWT:
#------------------------------------------------------------------------------
contains(DEFINES, EG_QWT) {
   INCLUDEPATH += $${QWT_INCLUDEPATH}
   LIBPATH += $${QWT_LIBPATH}
   LIBS += $${QWT_LIBS}
}

#------------------------------------------------------------------------------
# VTK:
#------------------------------------------------------------------------------
contains(DEFINES, EG_VTK) {
   INCLUDEPATH += $${VTK_INCLUDEPATH}
   LIBPATH += $${VTK_LIBPATH}
   LIBS += $${VTK_LIBS}
}

#------------------------------------------------------------------------------
# OpenCASCADE:
#------------------------------------------------------------------------------
contains(DEFINES, EG_OCC) {
   contains(BITS, 64):  DEFINES += _OCC64

   unix: DEFINES += HAVE_CONFIG_H HAVE_IOSTREAM HAVE_FSTREAM HAVE_LIMITS_H
   win32: DEFINES += WNT CSFDB
   macx: DEFINED -= EG_OCC         # not supported at the moment

   INCLUDEPATH += $${OCC_INCLUDEPATH}
   LIBPATH += $${OCC_LIBPATH}
   LIBS += $${OCC_LIBS}
}

#------------------------------------------------------------------------------
# PYTHONQT (see ../PythonQt/README for more details):
#------------------------------------------------------------------------------
contains(DEFINES, EG_PYTHONQT) {
   INCLUDEPATH += $${PY_INCLUDEPATH} ../PythonQt/src
   LIBPATH += $${PY_LIBPATH} ../PythonQt/lib
   LIBS += $${PY_LIBS} -lPythonQt
}

#------------------------------------------------------------------------------
# Process info query on win32:
#------------------------------------------------------------------------------
win32: LIBS += -lpsapi

#------------------------------------------------------------------------------
# OpenGL GLU
#------------------------------------------------------------------------------
unix:  LIBS += -lGLU
#------------------------------------------------------------------------------
# Input files:
#------------------------------------------------------------------------------
HEADERS += src/bodypropertyeditor.h \
           src/boundarydivision.h \
           src/boundarypropertyeditor.h \
           src/checkmpi.h \
           src/dynamiceditor.h \
           src/edfeditor.h \
           src/egini.h \
           src/generalsetup.h \
           src/glcontrol.h \
           src/glwidget.h \
           src/helpers.h \
           src/mainwindow.h \
           src/materiallibrary.h \
           src/maxlimits.h \
           src/meshcontrol.h \
           src/meshingthread.h \
           src/meshtype.h \
           src/meshutils.h \
           src/operation.h \
           src/parallel.h \
           src/projectio.h \
           src/sifgenerator.h \
           src/sifwindow.h \
           src/solverparameters.h \
           src/summaryeditor.h \
           plugins/egconvert.h \
           plugins/egdef.h \
           plugins/egmain.h \
           plugins/egmesh.h \
           plugins/egnative.h \
           plugins/egtypes.h \
           plugins/egutils.h \
           plugins/elmergrid_api.h \
           plugins/nglib_api.h \
           plugins/tetgen.h \
           plugins/tetlib_api.h \
           twod/renderarea.h \
           twod/twodview.h \
           twod/curveeditor.h \
    src/john.h

FORMS += forms/bodypropertyeditor.ui \
         forms/boundarydivision.ui \
         forms/boundarypropertyeditor.ui \
         forms/generalsetup.ui \
         forms/glcontrol.ui \
         forms/materiallibrary.ui \
         forms/meshcontrol.ui \
         forms/parallel.ui \
         forms/solverparameters.ui \
         forms/summaryeditor.ui

SOURCES += src/bodypropertyeditor.cpp \
           src/boundarydivision.cpp \
           src/boundarypropertyeditor.cpp \
           src/checkmpi.cpp \
           src/dynamiceditor.cpp \
           src/edfeditor.cpp \
           src/egini.cpp \
           src/generalsetup.cpp \
           src/glcontrol.cpp \
           src/glwidget.cpp \
           src/helpers.cpp \
           src/main.cpp \
           src/mainwindow.cpp \
           src/materiallibrary.cpp \
           src/maxlimits.cpp \
           src/meshcontrol.cpp \
           src/meshingthread.cpp \
           src/meshtype.cpp \
           src/meshutils.cpp \
           src/operation.cpp \
           src/parallel.cpp \
           src/projectio.cpp \
           src/sifgenerator.cpp \
           src/sifwindow.cpp \
           src/solverparameters.cpp \
           src/summaryeditor.cpp \
           plugins/egconvert.cpp \
           plugins/egmain.cpp \
           plugins/egmesh.cpp \
           plugins/egnative.cpp \
           plugins/egutils.cpp \
           plugins/elmergrid_api.cpp \
           plugins/nglib_api.cpp \
           plugins/tetlib_api.cpp \
           twod/renderarea.cpp \
           twod/twodview.cpp \
           twod/curveeditor.cpp \
    src/john.cpp

#------------------------------------------------------------------------------
# Optional input files:
#------------------------------------------------------------------------------
contains(DEFINES, EG_QWT) {
   HEADERS += src/convergenceview.h
   SOURCES += src/convergenceview.cpp
}

contains(DEFINES, EG_VTK) {
   HEADERS += vtkpost/axes.h \
              vtkpost/featureedge.h \
              vtkpost/vtkpost.h \
              vtkpost/isosurface.h \
              vtkpost/isocontour.h \
              vtkpost/epmesh.h \
              vtkpost/colorbar.h \
              vtkpost/meshpoint.h \
              vtkpost/meshedge.h \
              vtkpost/surface.h \
              vtkpost/preferences.h \
              vtkpost/vector.h \
              vtkpost/readepfile.h \
              vtkpost/streamline.h \
              vtkpost/timestep.h \
              vtkpost/ecmaconsole.h \
              vtkpost/text.h

   FORMS += vtkpost/axes.ui \
            vtkpost/featureedge.ui \
            vtkpost/isosurface.ui \
            vtkpost/isocontour.ui \
            vtkpost/colorbar.ui \
            vtkpost/surface.ui \
            vtkpost/meshpoint.ui \
            vtkpost/meshedge.ui \
            vtkpost/preferences.ui \
            vtkpost/vector.ui \
            vtkpost/readepfile.ui \
            vtkpost/streamline.ui \
            vtkpost/timestep.ui \
            vtkpost/text.ui

   SOURCES += vtkpost/axes.cpp \
              vtkpost/featureedge.cpp \
              vtkpost/vtkpost.cpp \
              vtkpost/isosurface.cpp \
              vtkpost/isocontour.cpp \
              vtkpost/epmesh.cpp \
              vtkpost/colorbar.cpp \
              vtkpost/meshpoint.cpp \
              vtkpost/meshedge.cpp \
              vtkpost/surface.cpp \
              vtkpost/preferences.cpp \
              vtkpost/vector.cpp \
              vtkpost/readepfile.cpp \
              vtkpost/streamline.cpp \
              vtkpost/timestep.cpp \
              vtkpost/ecmaconsole.cpp \
              vtkpost/text.cpp

   contains(DEFINES, EG_MATC) {
      HEADERS += vtkpost/matc.h \
                 vtkpost/mc.h

      FORMS += vtkpost/matc.ui

      SOURCES += vtkpost/matc.cpp
   }
}

contains(DEFINES, EG_OCC) {
   HEADERS += cad/cadview.h \
              cad/cadpreferences.h

   FORMS += cad/cadpreferences.ui

   SOURCES += cad/cadview.cpp \
              cad/cadpreferences.cpp
}

#------------------------------------------------------------------------------
# Resource files:
#------------------------------------------------------------------------------
RESOURCES += ElmerGUI.qrc
win32: RC_FILE += ElmerGUI.rc
macx: RC_FILE = M3Dicon.icns

#------------------------------------------------------------------------------
# END OF FILE
#------------------------------------------------------------------------------

but nothing happen when I compile the project, No error appears but I think app could not call static lib.so what should I do?

Body:
Your main in main.cpp should be:

int main(int argc, char *argv[])
{
  return main2(argc, argv);
}

your line

main2;

do compiles fine, but does nothing.


答: Camera matrix (mts) is incorrect. Fx and Fy are very different (Fx=6.4154558230601404e+04 Fy=9.8908265814965678e+04) and very big. According to comment in OpenCV calibrateCamera() function this problem usually occurs because you have probably used patternSize=cvSize(rows,cols) instead of using patternSize=cvSize(cols,rows) in findChessboardCorners.</p>

Title: output from solvePnP doesn't match projectPoints

Body:
I get strange data from solvePnP, so I tried to check it with projectPoints:

retval, rvec, tvec=cv2.solvePnP(opts, ipts, mtx, dist, flags=cv2.SOLVEPNP_ITERATIVE)
print(retval,rvec,tvec)
proj, jac = cv2.projectPoints(opts, rvec, tvec, mtx, dist)
print(proj,ipts)

here opts are 3d points with z=0, detected on this picture:

And ipts are taken from this pic (only part of picture here):

I've checked points themselves (detected with SIFT, points are detected correctly and pairing in a right way).

Now I want to test if rvec and tvec, found by SolvePnP is correct, so I invoke cv2.projectPoint to test if 3d points are projected to the image points. And here is what I have:

So I see that projected points lie outside of image, having y<0.

(retval from solvePnP is true)

This is distortion matrix dist:

1.6324642475694839e+02 -2.1480843988631259e+04 -3.4969507980045117e-01 7.9693609309756430e-01 -4.0684056606034986e+01

This is mtx:

6.4154558230601404e+04 0. 1.2973531562160772e+03
0. 9.8908265814965678e+04 9.5760834379036123e+02
0. 0. 1.

This is opts:

[[ 1708.74987793  1138.92041016     0.        ]
 [ 1708.74987793  1138.92041016     0.        ]
 [ 1708.74987793  1138.92041016     0.        ]
 [ 1708.74987793  1138.92041016     0.        ]
 [ 1708.74987793  1138.92041016     0.        ]
 [ 1708.74987793  1138.92041016     0.        ]
 [ 1708.74987793  1138.92041016     0.        ]
 [ 1984.09973145  1069.31677246     0.        ]
 [ 1984.09973145  1069.31677246     0.        ]
 [ 1908.19396973  1200.05529785     0.        ]
 [ 1994.56677246  1286.16516113     0.        ]
 [ 1994.56677246  1286.16516113     0.        ]
 [ 1806.82177734  1058.06872559     0.        ]
 [ 1925.55639648  1077.33703613     0.        ]
 [ 1998.30627441  1115.51647949     0.        ]
 [ 1998.30627441  1115.51647949     0.        ]
 [ 1998.30627441  1115.51647949     0.        ]
 [ 2013.79003906  1168.08728027     0.        ]
 [ 1972.93457031  1234.92614746     0.        ]
 [ 2029.11364746  1220.234375       0.        ]]

This is ipts:

[[  71.6125946    11.61344719]
 [ 116.60684967   71.6068573 ]
 [ 116.60684967   71.6068573 ]
 [ 101.60684967   86.60684967]
 [ 101.60684967   86.60684967]
 [ 116.60684967  101.6068573 ]
 [ 116.60684967  101.6068573 ]
 [ 112.37421417   53.40462112]
 [ 112.37421417   53.40462112]
 [  83.76233673   84.36077118]
 [  98.45358276  112.38414764]
 [  98.45358276  112.38414764]
 [  67.2594223    38.04878998]
 [  96.85155487   51.85028076]
 [ 112.26165009   67.25630188]
 [ 112.26165009   67.25630188]
 [ 112.26165009   67.25630188]
 [ 112.24694061   82.24401855]
 [  96.82528687   97.66513824]
 [ 112.2511673    97.25905609]]

rvec = [[-0.21890167] [-0.86241377] [ 0.96051463]]
tvec = [[  239.04461181] [-2165.99539286] [-1700.61539107]]

Also I tried to follow one of the comments and multiply each y from opts by -1, but this gave me even more crazy coordinates outside picture like 10^13.


问:
Is PackageMaker considered the standard for Mac OS X software installation? Or is there something else out there?
I've put together my very first package with PackageMaker (for a system service), but I am not happy about several faults:

Frequent crashes while applying target permissions to my source files

Package source files are not automatically or easily refreshed

File filter does not work

Is there something else out there more capable of this task?  Free is not a requirement.

答:
I had the same problem until I added #!/bin/sh at the top of the script. Apparently PackageMaker needs it; I wish the log was a bit more clear about it.

IHIH, Oren

ContentLicense: CC BY-SA 2.5


问:
Picking a picture either from photos or multimedia, but not by recent images
I would like to pick picture similar to whatsapp:

Code:

```<code>   public void pickImage()
    {
        if (Build.VERSION.SDK_INT <19)
        {
            Intent pickPhoto = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);

            Intent intent = new Intent();
            intent.setType("image/*");
            intent.setAction(Intent.ACTION_GET_CONTENT);
            startActivityForResult(Intent.createChooser(intent, "Select Picture"), SELECT_PICTURE);
        } else {
            Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
            intent.addCategory(Intent.CATEGORY_OPENABLE);
            intent.setType("image/*");
            startActivityForResult(intent, KITKAT_SELECT_PICTURE);

        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (resultCode != Activity.RESULT_OK) return;
        if (null == data) return;
        Uri originalUri = null;
        if (requestCode == SELECT_PICTURE)
        {
            originalUri = data.getData();
        }
        else if (requestCode == KITKAT_SELECT_PICTURE)
        {
            originalUri = data.getData();
            final int takeFlags = data.getFlags() & (Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
            // Check for the freshest data.
            getContentResolver().takePersistableUriPermission(originalUri, takeFlags);
        }
    }
</code>```

Question:

The above can pick pictures and then showing pic properly in an imageview. However, during the picking process, it messes up the pictures photoed by camera (called album) and pictures in other media, and is sorted by most recent images.

How could i make it similar to whatsapp, picking image from a folder containing only but all images taken from camera, or a folder containing all other multimedia, INSTEAD OF messing up camera photos and mutimedia pictures by most recently added?

Thank you.

答:
Try this hope so it will be helpful my problem was fix out with help of this code..

```<code>Uri selectedImageURI = data.getData();
imageFile = new File(getRealPathFromURI(selectedImageURI));
</code>```

and:

```<code>private String getRealPathFromURI(Uri contentURI) {
    String result;
    Cursor cursor = getContentResolver().query(contentURI, null, null, null, null);
    if (cursor == null) { // Source is Dropbox or other similar local file path
        result = contentURI.getPath();
    } else {
        cursor.moveToFirst();
        int idx = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
        result = cursor.getString(idx);
        cursor.close();
    }
    return result;
}
</code>```

Body:
I would like to pick picture similar to whatsapp:

Code:

   public void pickImage()
    {
        if (Build.VERSION.SDK_INT <19)
        {
            Intent pickPhoto = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);

            Intent intent = new Intent();
            intent.setType("image/*");
            intent.setAction(Intent.ACTION_GET_CONTENT);
            startActivityForResult(Intent.createChooser(intent, "Select Picture"), SELECT_PICTURE);
        } else {
            Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
            intent.addCategory(Intent.CATEGORY_OPENABLE);
            intent.setType("image/*");
            startActivityForResult(intent, KITKAT_SELECT_PICTURE);

        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (resultCode != Activity.RESULT_OK) return;
        if (null == data) return;
        Uri originalUri = null;
        if (requestCode == SELECT_PICTURE)
        {
            originalUri = data.getData();
        }
        else if (requestCode == KITKAT_SELECT_PICTURE)
        {
            originalUri = data.getData();
            final int takeFlags = data.getFlags() & (Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
            // Check for the freshest data.
            getContentResolver().takePersistableUriPermission(originalUri, takeFlags);
        }
    }

Question:

The above can pick pictures and then showing pic properly in an imageview. However, during the picking process, it messes up the pictures photoed by camera (called album) and pictures in other media, and is sorted by most recent images.

How could i make it similar to whatsapp, picking image from a folder containing only but all images taken from camera, or a folder containing all other multimedia, INSTEAD OF messing up camera photos and mutimedia pictures by most recently added?

Thank you.

Body:
Try this hope so it will be helpful my problem was fix out with help of this code..

Uri selectedImageURI = data.getData();
imageFile = new File(getRealPathFromURI(selectedImageURI));

and:

private String getRealPathFromURI(Uri contentURI) {
    String result;
    Cursor cursor = getContentResolver().query(contentURI, null, null, null, null);
    if (cursor == null) { // Source is Dropbox or other similar local file path
        result = contentURI.getPath();
    } else {
        cursor.moveToFirst();
        int idx = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
        result = cursor.getString(idx);
        cursor.close();
    }
    return result;
}


问:
Unable to access one custom domain in Azure Wordpress Multisite
I have moved my WordPress multisite installation successfully to Azure. My main blog and another that I have moved work fine:
cedarrivermusic.com and
timpurdum.com.

However, my third site, cedarrivertech.com, does not resolve.
ERR_NAME_RESOLUTION_FAILED or Can't Reach errors when using this address.
I can access the dashboard, because this resolves to tech.cedarrivermusic.com, but not the actual site.

I have checked all DNS records, and they are identical for all three.
The web app on Azure verifies all three addresses, as well as *.cedarrivermusic.com.

Not sure whether this is a WP issue or an Azure issue.

EDIT
I "solved" this by going into the WHM panel on the old server, and seeing that I had deleted the DNS zone for cedarrivertech.com. So I recreated the entry on the old server. Which makes absolutely no sense to me, as every ping/dns service I can find shows the new server. I'd still love suggestions on how this is happening from the old DNS zone server.

答:
As mentioned in the edit, deleting a DNS zone in your old (yet active) WHM panel will cause this failure. However, I have also discovered that I can turn off the old server completely, and the new server functions correctly.

EDIT

Actually, turning off the WHM server does eventually cause failure again, so I am in contact with my old host/domain registrar to try to fix this.


问:
Cannot read value of property after ajax request
My code looks like this:

```<code>constructor(props: any) {
    super(props);
    this.state = {
        list: [],
    };
}

public componentWillMount() {
    this.getData();
}

public getData = () => {
        axios.get(someURL)
        .then( (response) => {
            this.setState({list: response.data.arrivals});
        })
        .catch( (error) => {
            console.log("FAILED", error);
        });
}

public render(): JSX.Element {
    const {list}: any = this.state;
    const data: IScheduler = list;

    console.log("TEST");

    console.log(data); //cannot get data here

    console.log("TEST");

    return (
        <div className="main-page-container">
            <ArrivalsTable data={data}/>
        </div>
    );
}
</code>```

My problem is that I am unable to read my data.

```<code> console.log(data);
</code>```

gives me back an array:

```<code>length: 0
__proto__: Array(0)
</code>```

and

```<code> console.log(data.generatedDate);
</code>```

gives:

```<code> undefined
</code>```

A sample of my data (modified):

```<code>{
   "arrivals": [
       {
          "generatedDate": "03.12.2017"
       }
        ...
    ]
}
</code>```

I was wondering how to fix that. Can anyone help?

(Tried to fix that, but still I cannot get data in render() )

Is there any other way to fetch data from URL and put them into property?

答:
getData should be as as below

```<code>axios.get(someURL)
    .then((response) => {
        this.setState({list: response.data.arrivals});
    })
    .catch( (error) => {
        console.log("FAILED", error);
    });
}
</code>```

Note the this.setState({list: response.data.arrivals}); section.

Body:
My code looks like this:

constructor(props: any) {
    super(props);
    this.state = {
        list: [],
    };
}

public componentWillMount() {
    this.getData();
}

public getData = () => {
        axios.get(someURL)
        .then( (response) => {
            this.setState({list: response.data.arrivals});
        })
        .catch( (error) => {
            console.log("FAILED", error);
        });
}

public render(): JSX.Element {
    const {list}: any = this.state;
    const data: IScheduler = list;

    console.log("TEST");

    console.log(data); //cannot get data here

    console.log("TEST");

    return (

            <ArrivalsTable data={data}/>

    );
}

My problem is that I am unable to read my data.

 console.log(data);

gives me back an array:

length: 0
__proto__: Array(0)

and

 console.log(data.generatedDate);

gives:

 undefined

A sample of my data (modified):

{
   "arrivals": [
       {
          "generatedDate": "03.12.2017"
       }
        ...
    ]
}

I was wondering how to fix that. Can anyone help?

(Tried to fix that, but still I cannot get data in render() )

Is there any other way to fetch data from URL and put them into property?

Body:
getData should be as as below

axios.get(someURL)
    .then((response) => {
        this.setState({list: response.data.arrivals});
    })
    .catch( (error) => {
        console.log("FAILED", error);
    });
}

Note the this.setState({list: response.data.arrivals}); section.


问:
What is the result of adding an Object and an Array in javascript?
I tried this code in the address bar:

javascript: alert({} + [])

The result is: [object Object].

javascript: alert(typeof ({} + []))

The result is: string.

Can somebody explain to me what's going on?

答:
It looks like because the + operator is not defined to accept arguments as one [] and one {}, it basically converts both to strings (makes more sense than trying to cast them into numbers) and then applies + as the concatenation operator.

Edit:
In response to the changed question, I think they are still being converted into a string first. Here's a session in spidermonkey where I tried it out:

```<code>js> x=[]+{}
[object Object]
js> z=x[0]
[
js> x.length
15
js> x=[]+{}
[object Object]
js> x.length
15
js> x[0]
[
js> x[1]
o
js> for (var i=0;i<x.length;i++) {print(x[i]);}
[
o
b
j
e
c
t

O
b
j
e
c
t
]
js> typeof(x)
string
js> print(x)
[object Object]
</code>```

What is happening is that the result of {}+[] is a string, but not en empty string. Rather it is the string "[object Object]".

Body:
It looks like because the + operator is not defined to accept arguments as one [] and one {}, it basically converts both to strings (makes more sense than trying to cast them into numbers) and then applies + as the concatenation operator.

Edit:
In response to the changed question, I think they are still being converted into a string first. Here's a session in spidermonkey where I tried it out:

js> x=[]+{}
[object Object]
js> z=x[0]
[
js> x.length
15
js> x=[]+{}
[object Object]
js> x.length
15
js> x[0]
[
js> x[1]
o
js> for (var i=0;i<x.length;i++) {print(x[i]);}
[
o
b
j
e
c
t

O
b
j
e
c
t
]
js> typeof(x)
string
js> print(x)
[object Object]

What is happening is that the result of {}+[] is a string, but not en empty string. Rather it is the string "[object Object]".


问:
Install app via usb: The device is temporarily restricted
When I toggle on the install via USB in developer mode:

it will pop the toast message said that the device is temporarily restricted

then toggle off the settings.

Is there any solution for this?

I searched through all the way like turning off MIUI optimization but still does not work. I cannot debug my application by Android Studio in this way......

答:
If turning your Wi-Fi off is not working for you, then you might have not yet registered your MIUI account as a developer account.

To do so go to  MIUI Dev center and register your already created account. After the review process this should not be bugging you anymore.

But remember as other have noted to:

Turn off Wi-Fi connection

Turn on mobile connection


问:
How to edit font size in code section on Ghost
I'm using Ghost as blogging platform.
I put my code between ``` just like it's one on stackoverlfow.
This works well but the text size of my code is to big.

I know some css but I don't know how or where I can change this size somewhere?

答:
Those code blocks are wrapped in an element (most-likely code or pre wrapped in <>) but you can check what element to apply the CSS to by right clicking on it in your browser and selecting 'inspect'. Inspect will let you look at the code and see what kind of html element it is wrapped in.

Ex:
This is inside code element

```This is inside pre element```

Once you know what element you need to alter you can target it with CSS and add it to your css style files.

pre{
font-size:18px;
color:red;
}

code{
font-size:16px;
color:blue;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code>```Sample code using pre```

<code>Sample Code using code</code></code>```

Body:
Those code blocks are wrapped in an element (most-likely code or pre wrapped in <>) but you can check what element to apply the CSS to by right clicking on it in your browser and selecting 'inspect'. Inspect will let you look at the code and see what kind of html element it is wrapped in.

Ex:
This is inside code element

This is inside pre element

Once you know what element you need to alter you can target it with CSS and add it to your css style files.

pre{
font-size:18px;
color:red;
}

code{
font-size:16px;
color:blue;
}

<pre>Sample code using pre</pre>

<code>Sample Code using code</code>


问:
Quickly scrape the content of a page using capybara despite some useless assets on the page taking too long to load

I am using Capybara to scrape websites to check if they use cookies and if they have banners that explain why they use cookies (that may be generated using javascript).

Here is the code to initialize Capybara :

```<code>def init_capybara
  require 'capybara/poltergeist'

  Capybara.register_driver :poltergeist do |app|
    Capybara::Poltergeist::Driver.new(app, phantomjs: Phantomjs.path, js_errors: false)
  end

Capybara.default_driver = :poltergeist
end
</code>```

Here is my code for the scraper :

```<code>def presence(url)
  init_capybara

  @browser = Capybara.current_session
  @browser.visit(url)

  cookies = @browser.evaluate_script("document.cookie")

  return cookies
end
</code>```

The scraper for the banner works the same way.

I expect to get a string of all the cookies used in the website.

But I get a timeout error if I try to scrape a webpage that needs content that takes a long time to load (e.g. an analytics tool that takes a minute to load) although I do not need this content to proceed.

I do not want to just put a longer "default_max_wait_time" because the analysis needs to take only a few second and for most of the websites it's the case.

答:
The answer by @mdesantis is on the right track, however the article linked to is for capybara-webkit not Poltergeist.  With Poltergeist it should really just be configured in the driver setup (rather than a before block) and you probably also want to tell PhantomJS not to load images - https://github.com/teampoltergeist/poltergeist#customization

```<code>Capybara.register_driver :poltergeist do |app|
  Capybara::Poltergeist::Driver.new(app,
    phantomjs: Phantomjs.path,
    js_errors: false,
    phantomjs_options: ['--load-images=no'],
    url_blacklist: ['*/analytics_tool.js'] # can use * and ? wildcards in these
  )
end
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am using Capybara to scrape websites to check if they use cookies and if they have banners that explain why they use cookies (that may be generated using javascript).

Here is the code to initialize Capybara :

def init_capybara
  require 'capybara/poltergeist'

  Capybara.register_driver :poltergeist do |app|
    Capybara::Poltergeist::Driver.new(app, phantomjs: Phantomjs.path, js_errors: false)
  end

Capybara.default_driver = :poltergeist
end

Here is my code for the scraper :

def presence(url)
  init_capybara

  @browser = Capybara.current_session
  @browser.visit(url)

  cookies = @browser.evaluate_script("document.cookie")

  return cookies
end

The scraper for the banner works the same way.

I expect to get a string of all the cookies used in the website.

But I get a timeout error if I try to scrape a webpage that needs content that takes a long time to load (e.g. an analytics tool that takes a minute to load) although I do not need this content to proceed.

I do not want to just put a longer "default_max_wait_time" because the analysis needs to take only a few second and for most of the websites it's the case.

Body:
The answer by @mdesantis is on the right track, however the article linked to is for capybara-webkit not Poltergeist.  With Poltergeist it should really just be configured in the driver setup (rather than a before block) and you probably also want to tell PhantomJS not to load images - https://github.com/teampoltergeist/poltergeist#customization

Capybara.register_driver :poltergeist do |app|
  Capybara::Poltergeist::Driver.new(app,
    phantomjs: Phantomjs.path,
    js_errors: false,
    phantomjs_options: ['--load-images=no'],
    url_blacklist: ['*/analytics_tool.js'] # can use * and ? wildcards in these
  )
end


问:
How to try/catch all exceptions
I'm completing a UWP app started by someone else. The app crashes frequently and I always end up in App.g.i.cs at

```<code>if (global::System.Diagnostics.Debugger.IsAttached)
    global::System.Diagnostics.Debugger.Break();
</code>```

where I then have to say "no, don't start the debugger" and close 2 windows.

Is there somewhere I could put a big try/catch so that I don't have to restart the app each time this happen? I can't find anything in AppShell or App.

Or do I have to put a try/catch in every single event handler?

答:
You can try/catch in your main app to catch all exceptions.  Shown is an example using Xamarin Forms DisplayAlert:

```<code>            try
            {
                //throw new Exception("gone and done it");
                MyMainProgram();
                                }
            catch (Exception ex)
            {
                await DisplayAlert("Whoops!", ex.Message, "ok");
                throw ex;
            }
</code>```

You can test this by uncommenting the "throw new Exception".  Execution stops with an alert you must answer, then continues by throwing the exception to prevent executing corrupted code.

Title: How to try/catch all exceptions

Body:
I'm completing a UWP app started by someone else. The app crashes frequently and I always end up in App.g.i.cs at

if (global::System.Diagnostics.Debugger.IsAttached)
    global::System.Diagnostics.Debugger.Break();

where I then have to say "no, don't start the debugger" and close 2 windows.

Is there somewhere I could put a big try/catch so that I don't have to restart the app each time this happen? I can't find anything in AppShell or App.

Or do I have to put a try/catch in every single event handler?

Body:
You can try/catch in your main app to catch all exceptions.  Shown is an example using Xamarin Forms DisplayAlert:

            try
            {
                //throw new Exception("gone and done it");
                MyMainProgram();
                                }
            catch (Exception ex)
            {
                await DisplayAlert("Whoops!", ex.Message, "ok");
                throw ex;
            }

You can test this by uncommenting the "throw new Exception".  Execution stops with an alert you must answer, then continues by throwing the exception to prevent executing corrupted code.


问:
Center a string using sprintf
I have a code that would like to display the message in the center between the bars. I looked at the C functions and found nothing that would allow me this.

```<code>sprintf(message,"============================================================");
send_message(RED, message);
sprintf(message, "[ Welcome %s ]", p->client_name);
send_message(RED, message);
sprintf(message,"============================================================");
send_message(RED, message);
</code>```

I am looking for a way to show the Welcome message by counting the size of the user name always show centralized. Example:

example 1:

```<code>=============================================
                Welcome Carol
=============================================
</code>```

example 2:

```<code>=============================================
               Welcome Giovanna
=============================================
</code>```

答:
There is no special function for it, so you should do the math.

Count the number of bars, and the length of the message.

Subtract them and divide by 2.

If the length of the message is even, then add 1 to the quotient.

Add to the quotient the length of the message.

Sample code:

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

int main(void) {
    char* message = "Welcome Giovanna";
    int len = (int)strlen(message);
    printf("===============================================\n"); // 45 chars
    printf("%*s\n", (45-len)/2 + ((len % 2 == 0) ? 1 : 0) + len, message);
    printf("===============================================\n");

    return 0;
}
</code>```

Output:

```<code>=============================================
               Welcome Giovanna
=============================================
</code>```

PS: You could replace (45-len)/2 + ((len % 2 == 0) ? 1 : 0) with (46-len)/2, in order to get the same result, since the latter is shorter.

Title: Center a string using sprintf

Body:
I have a code that would like to display the message in the center between the bars. I looked at the C functions and found nothing that would allow me this.

sprintf(message,"============================================================");
send_message(RED, message);
sprintf(message, "[ Welcome %s ]", p->client_name);
send_message(RED, message);
sprintf(message,"============================================================");
send_message(RED, message);

I am looking for a way to show the Welcome message by counting the size of the user name always show centralized. Example:

example 1:

=============================================
                Welcome Carol
=============================================

example 2:

=============================================
               Welcome Giovanna
=============================================

Body:
There is no special function for it, so you should do the math.

Count the number of bars, and the length of the message.

Subtract them and divide by 2.

If the length of the message is even, then add 1 to the quotient.

Add to the quotient the length of the message.

Sample code:

#include <stdio.h>
#include <string.h>

int main(void) {
    char* message = "Welcome Giovanna";
    int len = (int)strlen(message);
    printf("===============================================\n"); // 45 chars
    printf("%*s\n", (45-len)/2 + ((len % 2 == 0) ? 1 : 0) + len, message);
    printf("===============================================\n");

    return 0;
}

Output:

=============================================
               Welcome Giovanna
=============================================

PS: You could replace (45-len)/2 + ((len % 2 == 0) ? 1 : 0) with (46-len)/2, in order to get the same result, since the latter is shorter.


问:
What is a possible alternative to these static variables?
I have created a simple GUI engine which I plan to use in a game.
The issue I am having is understanding how to instance a class that will be accessed in multiple stack frames without being static (people have made it quite clear that static variables are just evil).

I have a code example below:

```<code>class MyGame
{
    class InputEngine
    {
        internal void DoInput()
        {
            if (Keys["F1"].IsPressed)
            {
                // Create a window using the gui engine
            }
        }
    }
    class GuiEngine
    {
        internal void Update() { }
        internal void Draw() { }
    }
    private GuiEngine engine;
    private InputEngine input;

    internal MyGame()
    {
        this.input = new InputEngine();
        this.engine = new GuiEngine();
    }

    internal void Update()
    {
        this.engine.Update();
        this.input.DoInput();
    }
    internal void Draw()
    {
        this.engine.Draw();
    }
}
</code>```

How can I access the gui engine instance not only from the input example, but from tens of other places without making it static. (I would really rather not pass it as a parameter).

答:
You've only got three real passing options -

Statics

Parameterization (cctor, method, etc.)

Delegates/Closures/Lambda

Techniques like inversion of control containers can help here too in terms of creating, managing-lifetime-of, and discovering instances.  Add in dependency injection and the whole lifecycle can be automatic with minimal attribution/coding.

Of the three techniques, statics and parameterization pass the software maintenance "test" best in terms of obviousness and simplicity.  IoC is fairly readable.  However DI codebases tend to feel a lot more like black-magic with implicit behaviour for lifetime, location, and binding.

Delegates, closures, etc. can work very well, with context preserved when created however debugging can be a bit of nightmare, and often maintaining/reading closure code feels jumbled since it is rarely executed in context of where it is written.

Statics are as you point out probably most gnarly, being harder to mock, replace etc..

Body:
I have created a simple GUI engine which I plan to use in a game.
The issue I am having is understanding how to instance a class that will be accessed in multiple stack frames without being static (people have made it quite clear that static variables are just evil).

I have a code example below:

class MyGame
{
    class InputEngine
    {
        internal void DoInput()
        {
            if (Keys["F1"].IsPressed)
            {
                // Create a window using the gui engine
            }
        }
    }
    class GuiEngine
    {
        internal void Update() { }
        internal void Draw() { }
    }
    private GuiEngine engine;
    private InputEngine input;

    internal MyGame()
    {
        this.input = new InputEngine();
        this.engine = new GuiEngine();
    }

    internal void Update()
    {
        this.engine.Update();
        this.input.DoInput();
    }
    internal void Draw()
    {
        this.engine.Draw();
    }
}

How can I access the gui engine instance not only from the input example, but from tens of other places without making it static. (I would really rather not pass it as a parameter).


问:
type mismatch found at 'EMPTYPE' between FETCH cursor and INTO variables
```<code>create or replace type emp_obj as object(empno varchar2(500));

create or replace type  emp_table as table of emp_obj ;
</code>```

Procedure

```<code>create or replace procedure getempid(emptype out emp_table)
is
cursor c1 is select empno from emp ;
begin
open c1;
fetch c1 bulk collect into  emptype;

close c1;
end;
</code>```

I am unable to understand why i am getting below error :

Error(6,17): PLS-00386: type mismatch found at 'EMPTYPE' between FETCH cursor and INTO variables

答:
Apparently you cannot directly assign a collection object using a bulk collect into fetch from a cursor, notwithstanding the fact that the two would contain compatible datatype elements.

From oracle documentation,

PLS-00386: type mismatch found at 'string' between FETCH cursor and
  INTO variables

Cause: An assignment target in the INTO list of a FETCH statement does
  not match in datatype with the corresponding column in the select list
  of the cursor declaration, and it is unclear which implicit conversion
  is required to correct the mismatch.

Use element-wise assignment instead, using an intermediate collection.

```<code>CREATE OR replace PROCEDURE Getempid(emptype OUT EMP_TABLE)
IS
  CURSOR c1 IS
    SELECT empno
    FROM   emp;
  TYPE c_rowtype
    IS TABLE OF c1%ROWTYPE;
  crow C_ROWTYPE;
BEGIN
    OPEN c1;

    FETCH c1 bulk collect INTO crow;

    CLOSE c1;

    FOR i IN 1..crow.count LOOP
        emptype(i).empno := crow(i).empno;
    END LOOP;
END;
</code>```

Body:
create or replace type emp_obj as object(empno varchar2(500));

create or replace type  emp_table as table of emp_obj ;

Procedure

create or replace procedure getempid(emptype out emp_table)
is
cursor c1 is select empno from emp ;
begin
open c1;
fetch c1 bulk collect into  emptype;

close c1;
end;

I am unable to understand why i am getting below error :

Error(6,17): PLS-00386: type mismatch found at 'EMPTYPE' between FETCH cursor and INTO variables

Body:
Apparently you cannot directly assign a collection object using a bulk collect into fetch from a cursor, notwithstanding the fact that the two would contain compatible datatype elements.

From oracle documentation,

PLS-00386: type mismatch found at 'string' between FETCH cursor and
  INTO variables

Cause: An assignment target in the INTO list of a FETCH statement does
  not match in datatype with the corresponding column in the select list
  of the cursor declaration, and it is unclear which implicit conversion
  is required to correct the mismatch.

Use element-wise assignment instead, using an intermediate collection.

CREATE OR replace PROCEDURE Getempid(emptype OUT EMP_TABLE)
IS
  CURSOR c1 IS
    SELECT empno
    FROM   emp;
  TYPE c_rowtype
    IS TABLE OF c1%ROWTYPE;
  crow C_ROWTYPE;
BEGIN
    OPEN c1;

    FETCH c1 bulk collect INTO crow;

    CLOSE c1;

    FOR i IN 1..crow.count LOOP
        emptype(i).empno := crow(i).empno;
    END LOOP;
END;


问:
undefined method empty? for nil:NilClass - when it's not nil
Can anyone explain why this code:

```<code>    <%= form.select(:language_id) do
            Language.all.each do |lang|
                content_tag(:option, lang.name, value: lang.id,
                    onchange: "setThemeAndMode('#{lang.theme}','#{lang.mode}')")
            end
        end
    %>
</code>```

Errors with this:

```<code>undefined method `empty?' for nil:NilClass
Extracted source (around line #22):
20
21
22
23
24
25

        </p>
    </div>
    <%= form.select(:language_id) do
            Language.all.each do |lang|
                content_tag(:option, lang.name, value: lang.id,
                    onchange: "setThemeAndMode('#{lang.theme}','#{lang.mode}')")
</code>```

I'm very new to Ruby, and believe it to mean that it isn't finding any languages - But the database is full of them. Removing the content_tag and just having an
lang.name
 displays correctly. Any help is very much appreciated.

答:
It is an issue with how you are passing your block. Do this instead</p>

```<code><%= f.select(:language_id) do %>
  <% Language.all.each do |lang| %>
    <%= content_tag(:option, lang.name, value: lang.id,
                     onchange: "setThemeAndMode('#{lang.name}','#{lang.id}')") %>
  <% end %>
<% end %>
</code>```

Body:
Can anyone explain why this code:

    <%= form.select(:language_id) do
            Language.all.each do |lang|
                content_tag(:option, lang.name, value: lang.id,
                    onchange: "setThemeAndMode('#{lang.theme}','#{lang.mode}')")
            end
        end
    %>

Errors with this:

undefined method `empty?' for nil:NilClass
Extracted source (around line #22):
20
21
22
23
24
25

    <%= form.select(:language_id) do
            Language.all.each do |lang|
                content_tag(:option, lang.name, value: lang.id,
                    onchange: "setThemeAndMode('#{lang.theme}','#{lang.mode}')")

I'm very new to Ruby, and believe it to mean that it isn't finding any languages - But the database is full of them. Removing the content_tag and just having an
lang.name
 displays correctly. Any help is very much appreciated.

Body:
It is an issue with how you are passing your block. Do this instead

<%= f.select(:language_id) do %>
  <% Language.all.each do |lang| %>
    <%= content_tag(:option, lang.name, value: lang.id,
                     onchange: "setThemeAndMode('#{lang.name}','#{lang.id}')") %>
  <% end %>
<% end %>


问:
Carbon subtracting Datetime from Carbon::now()
I want to use this Carbon function:
Carbon::now()->subDays(5)->diffForHumans()

And I need to create the correct integer.

I am loading a string with a Datetime, which I want to subtract in Laravel like this:

```<code> $datetime = $score->created_at;
</code>```

Then I save the current Time into a variable

```<code> $now = Carbon::now()->toDateTimeString();
</code>```

This is what I get:

```<code> echo $now . '<br>'; // 2014-07-13 22:53:03
 echo $datetime;     // 2014-07-12 14:32:17
</code>```

But when I want to subtract one from another I get the following error:

```<code> echo $now - $datetime;
</code>```

Object of class Carbon\Carbon could not be converted to int

Any help here would be greatly apreciated.

答:
If you want to change the date format just use the format function</p>

```<code>$now = Carbon::now();

$score->created_at->diffForHumans($now)->format('Y-m-d');
</code>```

Body:
I want to use this Carbon function:
Carbon::now()->subDays(5)->diffForHumans()

And I need to create the correct integer.

I am loading a string with a Datetime, which I want to subtract in Laravel like this:

 $datetime = $score->created_at;

Then I save the current Time into a variable

 $now = Carbon::now()->toDateTimeString();

This is what I get:

 echo $now . '
'; // 2014-07-13 22:53:03
 echo $datetime;     // 2014-07-12 14:32:17

But when I want to subtract one from another I get the following error:

 echo $now - $datetime;

Object of class Carbon\Carbon could not be converted to int

Any help here would be greatly apreciated.

Body:
If you want to change the date format just use the format function

$now = Carbon::now();

$score->created_at->diffForHumans($now)->format('Y-m-d');


问:
Angular4 view not updating with data set in a setTimeout
I'm trying to update a progress bar with the importing of some data. I have the import delayed a second for each record (might not be the best way but this function isn't going to be used that often and this works.)

I have the import working, and applying the updated % to a variable but the view is not updating properly.

```<code>export class AddQuestionComponent {
    public completionPercent = 0;

    public readThis(inputValue: any): void {
        var file: File = inputValue.files[0];
        var myReader: FileReader = new FileReader();

        myReader.onloadend = function (e) {
           // console.log(myReader.result);

           let time = 1000;
           let count = 1;
           let data = JSON.parse(myReader.result);

           for (let i = 0; i < data.length; i++) {

             setTimeout(function () {
               // do something here
               count++;
               this.completionPercent = Math.round(100 * i / data.length);
               console.log(this.completionPercent);
           }, time);
           time += 1000;
       }

    };

myReader.readAsText(file);
}
</code>```

The console outputs the updated % of this.completionPercent but the view never updates.

```<code><div class="progress progress-sm mb-3">
     <div class="progress-bar bg-info" role="progressbar" [ngStyle]="{ 'width': completionPercent + '%' }" aria-valuemin="0" aria-valuemax="100"></div>
</div>
</code>```

What am I missing/doing wrong?

答:
```<code>setTimeout(function () {
</code>```

"breaks" this

Use instead

```<code>setTimeout(() => {
</code>```

See also https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions

and instead of

```<code>myReader.onloadend = function (e) {
</code>```

use

```<code>myReader.onloadend = (e) => {
</code>```

Body:
I'm trying to update a progress bar with the importing of some data. I have the import delayed a second for each record (might not be the best way but this function isn't going to be used that often and this works.)

I have the import working, and applying the updated % to a variable but the view is not updating properly.

export class AddQuestionComponent {
    public completionPercent = 0;

    public readThis(inputValue: any): void {
        var file: File = inputValue.files[0];
        var myReader: FileReader = new FileReader();

        myReader.onloadend = function (e) {
           // console.log(myReader.result);

           let time = 1000;
           let count = 1;
           let data = JSON.parse(myReader.result);

           for (let i = 0; i < data.length; i++) {

             setTimeout(function () {
               // do something here
               count++;
               this.completionPercent = Math.round(100 * i / data.length);
               console.log(this.completionPercent);
           }, time);
           time += 1000;
       }

    };

myReader.readAsText(file);
}

The console outputs the updated % of this.completionPercent but the view never updates.

What am I missing/doing wrong?

Body:
setTimeout(function () {

"breaks" this

Use instead

setTimeout(() => {

See also https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions

and instead of

myReader.onloadend = function (e) {

use

myReader.onloadend = (e) => {