问:
Edit Excel VBA Module to only email the last row of the worksheet
I am trying to edit this already slightly edited code (source: Ron de Bruin). Right now it emails all individuals in the spreadsheet. I would like it to simply perform the function in the For loop once; on the last row. Being new to VBA, this has proven difficult.

```<code>Sub Send_Files()
'Working in Excel 2000-2016
'For Tips see: http://www.rondebruin.nl/win/winmail/Outlook/tips.htm
    Dim OutApp As Object
    Dim OutMail As Object
    Dim sh As Worksheet
    Dim cell As Range
    Dim FileCell As Range
    Dim rng As Range

    With Application
        .EnableEvents = False
        .ScreenUpdating = False
    End With

    Set sh = Sheets("Sheet1")

    Set OutApp = CreateObject("Outlook.Application")

    For Each cell In sh.Columns("C").Cells.SpecialCells(xlCellTypeConstants)

        'Enter the path/file names in the C:Z column in each row
        Set rng = sh.Cells(cell.Row, 1).Range("D1:Z1")

        If cell.Value Like "?*@?*.?*" And _
           Application.WorksheetFunction.CountA(rng) > 0 Then
            Set OutMail = OutApp.CreateItem(0)

            With OutMail
                .to = cell.Value
                .Subject = "Testfile"
                .Body = "Hi " & cell.Offset(0, -2).Value

                For Each FileCell In rng.SpecialCells(xlCellTypeConstants)
                     If Trim(FileCell) <> "" Then
                        If Dir(FileCell.Value) <> "" Then
                            .Attachments.Add FileCell.Value
                        End If
                    End If
                Next FileCell

                .Send  'Or use .Display
            End With

            Set OutMail = Nothing
        End If
    Next cell

    Set OutApp = Nothing
    With Application
        .EnableEvents = True
        .ScreenUpdating = True
    End With
End Sub
</code>```

To give a little bit more context, I am trying to couple this module with a UserForm to have it so an individual puts in their information and which attachments they would like emailed to them, and when it submits, it adds their info to a spreadsheet while simultaneously sending them the attachments.

In the code's current config, it would do that, but it would also email everyone every time a new entry is submitted.

Thanks!

答:
Find the last name using the loop and put your If statement outside of the loop and use mailing code only for this.</p>

```<code>If cell.Value Like "?*@?*.?*" And _
  Application.WorksheetFunction.CountA(rng) > 0 Then
    Set OutMail = OutApp.CreateItem(0)
</code>```

Body:
I am trying to edit this already slightly edited code (source: Ron de Bruin). Right now it emails all individuals in the spreadsheet. I would like it to simply perform the function in the For loop once; on the last row. Being new to VBA, this has proven difficult.

Sub Send_Files()
'Working in Excel 2000-2016
'For Tips see: http://www.rondebruin.nl/win/winmail/Outlook/tips.htm
    Dim OutApp As Object
    Dim OutMail As Object
    Dim sh As Worksheet
    Dim cell As Range
    Dim FileCell As Range
    Dim rng As Range

    With Application
        .EnableEvents = False
        .ScreenUpdating = False
    End With

    Set sh = Sheets("Sheet1")

    Set OutApp = CreateObject("Outlook.Application")

    For Each cell In sh.Columns("C").Cells.SpecialCells(xlCellTypeConstants)

        'Enter the path/file names in the C:Z column in each row
        Set rng = sh.Cells(cell.Row, 1).Range("D1:Z1")

        If cell.Value Like "?*@?*.?*" And _
           Application.WorksheetFunction.CountA(rng) > 0 Then
            Set OutMail = OutApp.CreateItem(0)

            With OutMail
                .to = cell.Value
                .Subject = "Testfile"
                .Body = "Hi " & cell.Offset(0, -2).Value

                For Each FileCell In rng.SpecialCells(xlCellTypeConstants)
                     If Trim(FileCell) <> "" Then
                        If Dir(FileCell.Value) <> "" Then
                            .Attachments.Add FileCell.Value
                        End If
                    End If
                Next FileCell

                .Send  'Or use .Display
            End With

            Set OutMail = Nothing
        End If
    Next cell

    Set OutApp = Nothing
    With Application
        .EnableEvents = True
        .ScreenUpdating = True
    End With
End Sub

To give a little bit more context, I am trying to couple this module with a UserForm to have it so an individual puts in their information and which attachments they would like emailed to them, and when it submits, it adds their info to a spreadsheet while simultaneously sending them the attachments.

In the code's current config, it would do that, but it would also email everyone every time a new entry is submitted.

Thanks!

Body:
Find the last name using the loop and put your If statement outside of the loop and use mailing code only for this.

If cell.Value Like "?*@?*.?*" And _
  Application.WorksheetFunction.CountA(rng) > 0 Then
    Set OutMail = OutApp.CreateItem(0)


来源: stackexchange

问:
How to catch IOException in javafx
I'm trying to write data into a text file by pressing a button in JavaFx. The only problem, however is when I try to use the statement, "throws IOException" in my button processing method, things don't seem to work. Here is my code.

```<code>import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.stage.Stage;
import javafx.scene.Scene;
import javafx.scene.Group;
import javafx.scene.control.Button;
import java.io.*;
import java.io.File;
import java.io.FileInputStream;

public class testingFx extends Application{
//Create controls
private Button write;
private Scene main;
private Button Exit;
private Scene sceneMain;
private File records;
private FileWriter fw;

public static void main(String[] args){
   launch(args);
 }

@Override

public void start(Stage stage) throws IOException{

  //Create new file
  records = new File("records.txt");
  records.createNewFile();
  //Create FileWriter
  fw = new FileWriter(records);

  //Create root, format controls, scene, etc...
  Group root = new Group();
  write = new Button();
  write.setText("Write");
  write.setOnAction(this::processButtonPress);
  root.getChildren().addAll(write);
  main = new Scene(root,300,300);
  stage.setScene(main);
  stage.show();
}
   public void processButtonPress(ActionEvent event) throws IOException{
   if (event.getSource() == write){
        //On button press write to file
        fw.write("Testing file writing");
        //Close filewriter
        fw.close();
     }
  }
}
</code>```

I've tried to find the answer online but the way I was taught to handle a button press differs from most others examples (the section that says (this::processButtonPress)). I'm not sure if using a try/catch statement would help me here as I don't any experience with those, forgive me. The error I specifically am getting is "error: incompatible thrown types IOException in method reference". Thank you for your help.

I've tried to make this question on topic and easy to address. Please let me know if there are any glaring issues.

答:
You absolutely need to use a try/catch statement to catch an exception.

If you update the method as I have shown, you will catch the exception.

You then need to add code to handle the exception, so the program will continue successfully.

```<code>    public void processButtonPress(ActionEvent event) {
        if (event.getSource() == write) {
            try {
                // On button press write to file
                fw.write("Testing file writing");
                // Close filewriter
                fw.close();
            } catch (IOException e) {
                e.printStackTrace();

                // Code to handle goes here...
            }
        }
    }
</code>```

ContentLicense: CC BY-SA 3.0

Title: How to catch IOException in javafx

Body:
I'm trying to write data into a text file by pressing a button in JavaFx. The only problem, however is when I try to use the statement, "throws IOException" in my button processing method, things don't seem to work. Here is my code.

import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.stage.Stage;
import javafx.scene.Scene;
import javafx.scene.Group;
import javafx.scene.control.Button;
import java.io.*;
import java.io.File;
import java.io.FileInputStream;

public class testingFx extends Application{
//Create controls
private Button write;
private Scene main;
private Button Exit;
private Scene sceneMain;
private File records;
private FileWriter fw;

public static void main(String[] args){
   launch(args);
 }

@Override

public void start(Stage stage) throws IOException{

  //Create new file
  records = new File("records.txt");
  records.createNewFile();
  //Create FileWriter
  fw = new FileWriter(records);

  //Create root, format controls, scene, etc...
  Group root = new Group();
  write = new Button();
  write.setText("Write");
  write.setOnAction(this::processButtonPress);
  root.getChildren().addAll(write);
  main = new Scene(root,300,300);
  stage.setScene(main);
  stage.show();
}
   public void processButtonPress(ActionEvent event) throws IOException{
   if (event.getSource() == write){
        //On button press write to file
        fw.write("Testing file writing");
        //Close filewriter
        fw.close();
     }
  }
}

I've tried to find the answer online but the way I was taught to handle a button press differs from most others examples (the section that says (this::processButtonPress)). I'm not sure if using a try/catch statement would help me here as I don't any experience with those, forgive me. The error I specifically am getting is "error: incompatible thrown types IOException in method reference". Thank you for your help.

I've tried to make this question on topic and easy to address. Please let me know if there are any glaring issues.

Body:
You absolutely need to use a try/catch statement to catch an exception.

If you update the method as I have shown, you will catch the exception.

You then need to add code to handle the exception, so the program will continue successfully.

    public void processButtonPress(ActionEvent event) {
        if (event.getSource() == write) {
            try {
                // On button press write to file
                fw.write("Testing file writing");
                // Close filewriter
                fw.close();
            } catch (IOException e) {
                e.printStackTrace();

                // Code to handle goes here...
            }
        }
    }


问:
Select rows from table A where string exists in a similar column in table B or table C
I have 3 different SQL tables that I am working with. Here is what the table look like:

```<code>Master Accounts
---------------
CustomerNumber PK
CompanyName
More Columns...

Bill Tos
---------------
MasterCustomerNumber FK
CompanyName

Ship Tos
---------------
MasterCustomerNumber FK
CompanyName
</code>```

I want to write a MS SQL query that returns all the columns in the Master Accounts table where a company name contains the string 'ama' in any of the three tables.

Here is my current SQL:

```<code>SELECT DISTINCT
  MA.*
FROM MasterAccounts MA
LEFT JOIN BillTos BT
  ON MA.CustNo = BT.MasterCustNo
LEFT JOIN ShipTos ST
  ON MA.CustNo = ST.MasterCustNo
WHERE MA.CompanyName LIKE '%ama%' OR BT.CompanyName LIKE '%ama%' OR ST.CompanyName LIKE '%ama%'
</code>```

My goal is to get all master accounts where a billto or a shipto companyname contains 'ama'.

答:
I read yours comments and maybe this go faster:

```<code>select MA.* from
MasterAccounts MA
join
(select CustNo  nmb from MasterAccounts where CompanyName LIKE '%ama%'
union
select MasterCustNo nmb from BillTos  where CompanyName LIKE '%ama%'
union
select MasterCustNo nmb from ShipTos where CompanyName LIKE '%ama%' ) num on (num.nmb = MA.CustNo)
</code>```

if you need more companies maybe you use company name in lower case...

*if is small error in query i'm sorry - i read this fast....

Body:
I have 3 different SQL tables that I am working with. Here is what the table look like:

Master Accounts
---------------
CustomerNumber PK
CompanyName
More Columns...

Bill Tos
---------------
MasterCustomerNumber FK
CompanyName

Ship Tos
---------------
MasterCustomerNumber FK
CompanyName

I want to write a MS SQL query that returns all the columns in the Master Accounts table where a company name contains the string 'ama' in any of the three tables.

Here is my current SQL:

SELECT DISTINCT
  MA.*
FROM MasterAccounts MA
LEFT JOIN BillTos BT
  ON MA.CustNo = BT.MasterCustNo
LEFT JOIN ShipTos ST
  ON MA.CustNo = ST.MasterCustNo
WHERE MA.CompanyName LIKE '%ama%' OR BT.CompanyName LIKE '%ama%' OR ST.CompanyName LIKE '%ama%'

My goal is to get all master accounts where a billto or a shipto companyname contains 'ama'.

Body:
I read yours comments and maybe this go faster:

select MA.* from
MasterAccounts MA
join
(select CustNo  nmb from MasterAccounts where CompanyName LIKE '%ama%'
union
select MasterCustNo nmb from BillTos  where CompanyName LIKE '%ama%'
union
select MasterCustNo nmb from ShipTos where CompanyName LIKE '%ama%' ) num on (num.nmb = MA.CustNo)

if you need more companies maybe you use company name in lower case...

*if is small error in query i'm sorry - i read this fast....


问:
How can I get a list (result set of rows) of the table name and column name in each table that references primary key ID in table Addresses?
Using SQL Server 2012, I want to mark a record inactive. Before I do, I want to check if its primary key is referenced.

I tried searching on "get a list of the table name and column name in each table that references primary key" and “get column name in each table that references primary key” but nothing relevant showed up.  This is a tricky question to search on (for me).

答:
EDIT: Adding a query to list all foreign keys, tables that reference to your table, and columns in those tables that reference to it.

```<code>SELECT  obj.name AS FK_NAME,
    sch.name AS [schema_name],
    tab1.name AS [table],
    col1.name AS [column],
    tab2.name AS [referenced_table],
    col2.name AS [referenced_column]
FROM sys.foreign_key_columns fkc
INNER JOIN sys.objects obj
    ON obj.object_id = fkc.constraint_object_id
INNER JOIN sys.tables tab1
    ON tab1.object_id = fkc.parent_object_id
INNER JOIN sys.schemas sch
    ON tab1.schema_id = sch.schema_id
INNER JOIN sys.columns col1
    ON col1.column_id = parent_column_id AND col1.object_id = tab1.object_id
INNER JOIN sys.tables tab2
    ON tab2.object_id = fkc.referenced_object_id
INNER JOIN sys.columns col2
    ON col2.column_id = referenced_column_id AND col2.object_id = tab2.object_id
WHERE tab2.name = 'TABLENAME'
</code>```

Query based on a reply in this thread;
How can I list all foreign keys referencing a given table in SQL Server?

Body:
EDIT: Adding a query to list all foreign keys, tables that reference to your table, and columns in those tables that reference to it.

SELECT  obj.name AS FK_NAME,
    sch.name AS [schema_name],
    tab1.name AS [table],
    col1.name AS [column],
    tab2.name AS [referenced_table],
    col2.name AS [referenced_column]
FROM sys.foreign_key_columns fkc
INNER JOIN sys.objects obj
    ON obj.object_id = fkc.constraint_object_id
INNER JOIN sys.tables tab1
    ON tab1.object_id = fkc.parent_object_id
INNER JOIN sys.schemas sch
    ON tab1.schema_id = sch.schema_id
INNER JOIN sys.columns col1
    ON col1.column_id = parent_column_id AND col1.object_id = tab1.object_id
INNER JOIN sys.tables tab2
    ON tab2.object_id = fkc.referenced_object_id
INNER JOIN sys.columns col2
    ON col2.column_id = referenced_column_id AND col2.object_id = tab2.object_id
WHERE tab2.name = 'TABLENAME'

Query based on a reply in this thread;
How can I list all foreign keys referencing a given table in SQL Server?


问:
Restrict or change color of specific line in Vim
I use Vim for git commits. I have created a .gitcommittemplate:

```<code>############################### <BASLIK> ###############################
#
# ...
#
# |--En fazla 50 Karakter olabilir(Max 50 Char)--|
my real title

my real body
</code>```

I want to restrict line 6 for 50 characters. Or even better, after 50 characters convert it to red and restrict writing after 72 characters.

How can I do that?

答:
For the highlighting, try this:

```<code>highlight LineSix guifg=red ctermfg=red
syntax match LineSix /\%6l\%51c.*/
</code>```

This creates a new highlight group named LineSix, and then sets it to be red in the GUI or in the terminal. Then it says anything matching this regex is that highlight group.

The regex uses some fun magic. Here's a break down:

```<code>\%6l
</code>```

will match anything on line 6 (try :h /\%l)

```<code>\%51c
</code>```

will match anything on column 51 (try :h /\%c)

and then obviously .* will match anything.

As for restricting more than 75 characters, I don't think this is possible. You can try setting textwidth and colorcolumn, but these don't force you to use less than 75 characters, and they won't apply to a single line.

Body:
I use Vim for git commits. I have created a .gitcommittemplate:

############################### <BASLIK> ###############################
#
# ...
#
# |--En fazla 50 Karakter olabilir(Max 50 Char)--|
my real title

my real body

I want to restrict line 6 for 50 characters. Or even better, after 50 characters convert it to red and restrict writing after 72 characters.

How can I do that?

Body:
For the highlighting, try this:

highlight LineSix guifg=red ctermfg=red
syntax match LineSix /\%6l\%51c.*/

This creates a new highlight group named LineSix, and then sets it to be red in the GUI or in the terminal. Then it says anything matching this regex is that highlight group.

The regex uses some fun magic. Here's a break down:

\%6l

will match anything on line 6 (try :h /\%l)

\%51c

will match anything on column 51 (try :h /\%c)

and then obviously .* will match anything.

As for restricting more than 75 characters, I don't think this is possible. You can try setting textwidth and colorcolumn, but these don't force you to use less than 75 characters, and they won't apply to a single line.


问:
how to get list of supported encodings by iconv library in php?
Is it possible like in the mcrypt library with function mcrypt_list_algorithms(). Is there a iconv_list_encodings like function ?

答:
As already mentioned, in PHP the iconv extension does not have a function to list all available encodings.

The command line, however, does have such an option. This can be used to create the function you're looking for:

function iconv_list_encodings() {
   return preg_split('#//\n#', shell_exec('iconv -l'), -1, PREG_SPLIT_NO_EMPTY);
}
```

You can try it out here.

Body:
As already mentioned, in PHP the iconv extension does not have a function to list all available encodings.

The command line, however, does have such an option. This can be used to create the function you're looking for:

function iconv_list_encodings() {
   return preg_split('#//\n#', shell_exec('iconv -l'), -1, PREG_SPLIT_NO_EMPTY);
}

You can try it out here.


问:
Hotkey combinations don't work if done fast
I'm trying to make a hotkey for a web app, for example Ctrl + z performs the undo function.

It seems that when I press the keys fast (as I'm used to from using desktop apps a lot), it doesn't register. The single key press registers, but it misses the combination for some reason.

From what I understand, you have to keep track of which buttons are held down via keypress events, which is what I've done below.

Try the code below. Hitting Z outputs Z. Hitting CTRL then Z slowly outputs CTRL + Z. Hitting CTRL then Z quickly outputs Z. When I perform the action at the same speed in say Notepad for windows, it works flawlessly almost every time.

https://codepen.io/samkeddy/pen/YQjgdZ?editors=1010#0

```<code>var ctrlPressed=false, altPressed=false;

window.addEventListener("keydown", function (e) {

    hotkey = e;
    if (e.keyCode == 17) ctrlPressed = true;
    if (e.keyCode == 18) altPressed = true;
    e.preventDefault();
});

window.addEventListener("keyup", function (e) {
    hotkey = window.event;

    if (e.keyCode == 17) ctrlPressed = false;
    if (e.keyCode == 18) altPressed = false;

        if (e.keyCode == 90){
          if (altPressed && ctrlPressed && e.keyCode == 90)
            addText('ALT + CTRL + Z');
          else if (ctrlPressed && e.keyCode == 90)
            addText('CTRL + Z');
            else
              addText('Z');
    }
});

//meaningless, just adds text to doc so you can see it
function addText(text) {
  var theDiv = document.getElementById("output");
  theDiv.appendChild(document.createElement("br"));
  var content = document.createTextNode(text);
  theDiv.appendChild(content);
}
</code>```

答:
Use e.ctrlKey to check if ctrl is down instead of variables, and just check for the hotkey combination on keydown, don't do anything on key up.

https://codepen.io/samkeddy/pen/gRdBpq

```<code>function KeyPress(e) {
      var evtobj = window.event? event : e
      if (evtobj.keyCode == 90 && evtobj.ctrlKey) addText("CTRL + Z");
  else if (evtobj.keyCode == 90) addText("Z");
}

document.onkeydown = KeyPress;
</code>```

Body:
I'm trying to make a hotkey for a web app, for example Ctrl + z performs the undo function.

It seems that when I press the keys fast (as I'm used to from using desktop apps a lot), it doesn't register. The single key press registers, but it misses the combination for some reason.

From what I understand, you have to keep track of which buttons are held down via keypress events, which is what I've done below.

Try the code below. Hitting Z outputs Z. Hitting CTRL then Z slowly outputs CTRL + Z. Hitting CTRL then Z quickly outputs Z. When I perform the action at the same speed in say Notepad for windows, it works flawlessly almost every time.

https://codepen.io/samkeddy/pen/YQjgdZ?editors=1010#0

var ctrlPressed=false, altPressed=false;

window.addEventListener("keydown", function (e) {

    hotkey = e;
    if (e.keyCode == 17) ctrlPressed = true;
    if (e.keyCode == 18) altPressed = true;
    e.preventDefault();
});

window.addEventListener("keyup", function (e) {
    hotkey = window.event;

    if (e.keyCode == 17) ctrlPressed = false;
    if (e.keyCode == 18) altPressed = false;

        if (e.keyCode == 90){
          if (altPressed && ctrlPressed && e.keyCode == 90)
            addText('ALT + CTRL + Z');
          else if (ctrlPressed && e.keyCode == 90)
            addText('CTRL + Z');
            else
              addText('Z');
    }
});

//meaningless, just adds text to doc so you can see it
function addText(text) {
  var theDiv = document.getElementById("output");
  theDiv.appendChild(document.createElement("br"));
  var content = document.createTextNode(text);
  theDiv.appendChild(content);
}

Body:
Use e.ctrlKey to check if ctrl is down instead of variables, and just check for the hotkey combination on keydown, don't do anything on key up.

https://codepen.io/samkeddy/pen/gRdBpq

function KeyPress(e) {
      var evtobj = window.event? event : e
      if (evtobj.keyCode == 90 && evtobj.ctrlKey) addText("CTRL + Z");
  else if (evtobj.keyCode == 90) addText("Z");
}

document.onkeydown = KeyPress;


问:
scala: missing parameter type for expanded function: the argument types of an anonymous function must be fully known
I am new to scala and I have no idea at all what's wrong with my code:

I have some Future which may throw exception:

```<code>var clean: Future[Boolean];
</code>```

However, when I try to map

```<code>clean.map( b => {
  case true => Ok("success")
  case false => Ok("failed")
}).recover {
  case t => Ok("error: " + t)
}
</code>```

I get compile error specified in the title.. I totally have no idea where and/which part of my code exactly causes it.. I have googled but it is so difficult to find any clue because scala syntax is so flexible thus so many variations in the internet but the error I get is quite misleading...

Any help will be very appreciated...

答:
I guess you intended:</p>

```<code>clean.map( b => b match {
 case true => Ok("success")
 case false => Ok("failed")
}).recover {
 case t => Ok("error: " + t)
}
</code>```

Body:
I am new to scala and I have no idea at all what's wrong with my code:

I have some Future which may throw exception:

var clean: Future[Boolean];

However, when I try to map

clean.map( b => {
  case true => Ok("success")
  case false => Ok("failed")
}).recover {
  case t => Ok("error: " + t)
}

I get compile error specified in the title.. I totally have no idea where and/which part of my code exactly causes it.. I have googled but it is so difficult to find any clue because scala syntax is so flexible thus so many variations in the internet but the error I get is quite misleading...

Any help will be very appreciated...

Body:
I guess you intended:

clean.map( b => b match {
 case true => Ok("success")
 case false => Ok("failed")
}).recover {
 case t => Ok("error: " + t)
}


问:
Does db.session.commit change app context in Flask-SQLAlchemy?
I am configuring a fixture for pytest that creates a flask app instance. My app is created with Application Factories pattern. I am at the stage of connecting it to the database and struggle to understand the difference between 2 patterns.

```<code># project/__init__.py
import os
from flask import Flask
from flask_sqlalchemy import SQLAlchemy

db = SQLAlchemy()

def create_app():
    app = Flask(__name__)

    app_settings = os.getenv('APP_SETTINGS')
    app.config.from_object(app_settings)

    db.init_app(app)

    [blueprint code]

    return app
</code>```

In my fixture, I think I understand the need for:

db.create_all() during setup: create my tables

db.drop_all() during teardown: clean database after tests

db.session.remove() during teardown: avoid some weird locks on postgres when hitting the database frequently in tests

The first setup (inspired by Miguel Grinberg book) makes sense to me:

```<code>import pytest
from project import create_app, db

@pytest.fixture
def app():
    app = create_app()
    with app.app_context():
        db.create_all()
        yield app
        db.session.remove()
        db.drop_all()
</code>```

It also matches the behavior I get in an interactive session, where I need to activate/push the app_context to bind the database:

```<code>Python 3.6.1 (default, Jun 21 2017, 18:45:41)
[GCC 4.9.2] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> from project import create_app, db
>>> app = create_app()
>>> db
<SQLAlchemy engine=None>
>>> app_ctx = app.app_context()
>>> app_ctx.push()
>>> db.create_all()
>>> db
<SQLAlchemy engine='postgres://postgres:postgres@users-db:5432/users_dev'>
</code>```

The second setup (inspired by testdriven.io) also work in pytest but I don't know why:

```<code>import pytest
from project import create_app, db

@pytest.fixture
def app():
    app = create_app()
    db.create_all()
    db.session.commit()  # fail when this is removed
    yield app
    db.session.remove()
    db.drop_all()
</code>```

Actually, if I try to do the same in an interactive session, I get an error:

```<code>Python 3.6.1 (default, Jun 21 2017, 18:45:41)
[GCC 4.9.2] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> from project import create_app, db
>>> app = create_app()
>>> db.create_all()
[...] timeError: application not registered on db instance and no application bound to current context
</code>```

I tried to run the fixture without db.session.commit(), thinking that maybe I was in the app context by default (similar to what I do with with app_context() in the first fixture). But it fails if I remove it.

答:
The first problem is that the second setup (by testdriven.io) is not using the Application Factory pattern, they're explicitly instantiating the db and binding the app (e.g., db = SQLAlchemy(app) versus db = SQLAlchemy() and a later db.init(app) in create_app()). If you were using the Application Factory pattern, you would get the error you're seeing in the interactive session after executing db.create_all(), keeping/removing db.session.commit() won't help either way.

I have an inkling that you're using two different from project import create_app, db for each attempt and using the Application Factory pattern for the interactive shell.

In any case, you're really asking two questions.

1) Why do I need to push an application context in order to run db.create_all() when using the Application Factory pattern?

If you look at the __init__ method in SQLAlchemy, you'll notice that you can pass through an app, in this case, that app becomes bound to the SQLAlchemy object, self.app = app. However, because you're using the Application Factory pattern, that app is never explicitly bound, even after you run db.init_app(app). Now look in create_all(), it takes an optional app, which you aren't passing through, so when we get to get_app, we skip over reference_app because it is None, we go over current_app, which looks at Flask's application context (see from flask import current_app), if you haven't pushed the context, this will also be None, and finally we check to see if there is a self.app, but this is also None because we are using the Application Factory pattern, hence the application not registered on db instance and no application bound to current context error.

2) Why do I need to explicitly run db.session.commit() after running db.create_all when binding the app during SQLAlchemy instantiation (e.g., db = SQLAlchemy(app))?**

I can't seem to reproduce this error, I've added a code block below to show you what I'm using, I got the pieces from the testdriven.io site. However, you shouldn't need to db.session.commit(), the only difference between using the Application Factory pattern and instantiating SQLAlchemy with the app (e.g., db = SQLAlchemy(app)) is that with the former you'll either need to pass in the app in create_all(app) or push an application context.

```<code>import pytest
import os
import datetime
from flask import Flask, jsonify
from flask_sqlalchemy import SQLAlchemy

app = Flask(__name__)

db = SQLAlchemy(app)

@pytest.fixture
def app():
    app = create_app()
    db.create_all()
    # db.session.commit()  # Try this with and without this line
    yield app
    db.session.remove()
    db.drop_all()
</code>```

References:

https://github.com/mitsuhiko/flask-sqlalchemy/blob/d71afea650e0186348d81f02cca5181ed7c466e9/flask_sqlalchemy/init.py

http://flask-sqlalchemy.pocoo.org/2.1/contexts/

Body:
I am configuring a fixture for pytest that creates a flask app instance. My app is created with Application Factories pattern. I am at the stage of connecting it to the database and struggle to understand the difference between 2 patterns.

# project/__init__.py
import os
from flask import Flask
from flask_sqlalchemy import SQLAlchemy

db = SQLAlchemy()

def create_app():
    app = Flask(__name__)

    app_settings = os.getenv('APP_SETTINGS')
    app.config.from_object(app_settings)

    db.init_app(app)

    [blueprint code]

    return app

In my fixture, I think I understand the need for:

db.create_all() during setup: create my tables

db.drop_all() during teardown: clean database after tests

db.session.remove() during teardown: avoid some weird locks on postgres when hitting the database frequently in tests

The first setup (inspired by Miguel Grinberg book) makes sense to me:

import pytest
from project import create_app, db

@pytest.fixture
def app():
    app = create_app()
    with app.app_context():
        db.create_all()
        yield app
        db.session.remove()
        db.drop_all()

It also matches the behavior I get in an interactive session, where I need to activate/push the app_context to bind the database:

Python 3.6.1 (default, Jun 21 2017, 18:45:41)
[GCC 4.9.2] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> from project import create_app, db
>>> app = create_app()
>>> db
<SQLAlchemy engine=None>
>>> app_ctx = app.app_context()
>>> app_ctx.push()
>>> db.create_all()
>>> db
<SQLAlchemy engine='postgres://postgres:postgres@users-db:5432/users_dev'>

The second setup (inspired by testdriven.io) also work in pytest but I don't know why:

import pytest
from project import create_app, db

@pytest.fixture
def app():
    app = create_app()
    db.create_all()
    db.session.commit()  # fail when this is removed
    yield app
    db.session.remove()
    db.drop_all()

Actually, if I try to do the same in an interactive session, I get an error:

Python 3.6.1 (default, Jun 21 2017, 18:45:41)
[GCC 4.9.2] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> from project import create_app, db
>>> app = create_app()
>>> db.create_all()
[...] timeError: application not registered on db instance and no application bound to current context

I tried to run the fixture without db.session.commit(), thinking that maybe I was in the app context by default (similar to what I do with with app_context() in the first fixture). But it fails if I remove it.

Body:
The first problem is that the second setup (by testdriven.io) is not using the Application Factory pattern, they're explicitly instantiating the db and binding the app (e.g., db = SQLAlchemy(app) versus db = SQLAlchemy() and a later db.init(app) in create_app()). If you were using the Application Factory pattern, you would get the error you're seeing in the interactive session after executing db.create_all(), keeping/removing db.session.commit() won't help either way.

I have an inkling that you're using two different from project import create_app, db for each attempt and using the Application Factory pattern for the interactive shell.

In any case, you're really asking two questions.

1) Why do I need to push an application context in order to run db.create_all() when using the Application Factory pattern?

If you look at the __init__ method in SQLAlchemy, you'll notice that you can pass through an app, in this case, that app becomes bound to the SQLAlchemy object, self.app = app. However, because you're using the Application Factory pattern, that app is never explicitly bound, even after you run db.init_app(app). Now look in create_all(), it takes an optional app, which you aren't passing through, so when we get to get_app, we skip over reference_app because it is None, we go over current_app, which looks at Flask's application context (see from flask import current_app), if you haven't pushed the context, this will also be None, and finally we check to see if there is a self.app, but this is also None because we are using the Application Factory pattern, hence the application not registered on db instance and no application bound to current context error.

2) Why do I need to explicitly run db.session.commit() after running db.create_all when binding the app during SQLAlchemy instantiation (e.g., db = SQLAlchemy(app))?**

I can't seem to reproduce this error, I've added a code block below to show you what I'm using, I got the pieces from the testdriven.io site. However, you shouldn't need to db.session.commit(), the only difference between using the Application Factory pattern and instantiating SQLAlchemy with the app (e.g., db = SQLAlchemy(app)) is that with the former you'll either need to pass in the app in create_all(app) or push an application context.

import pytest
import os
import datetime
from flask import Flask, jsonify
from flask_sqlalchemy import SQLAlchemy

app = Flask(__name__)

db = SQLAlchemy(app)

@pytest.fixture
def app():
    app = create_app()
    db.create_all()
    # db.session.commit()  # Try this with and without this line
    yield app
    db.session.remove()
    db.drop_all()

References:

https://github.com/mitsuhiko/flask-sqlalchemy/blob/d71afea650e0186348d81f02cca5181ed7c466e9/flask_sqlalchemy/init.py

http://flask-sqlalchemy.pocoo.org/2.1/contexts/


问:
Exposing a web site through web services
I know what I am asking is somehow weird. There is a web application (which we don't have access to its source code), and we want to expose a few of its features as web services.

I was thinking to use something like Selenium WebDriver, so I simulate web clicks on the application according to the web service request.

I want to know whether this is a better solution or pattern to do this.

I shall mention that the application is written using Java, Spring MVC (it is not SPA) and Spring Security. And there is a CAS server providing SSO.

答: May be overkill..... But RPA? http://windowsitpro.com/scripting/review-automation-anywhere-enterprise</p>


问:
Export hive table to .avro file
I created an external hive table like this:

```<code>CREATE EXTERNAL TABLE some_hive_table
ROW FORMAT SERDE 'org.apache.hadoop.hive.serde2.avro.AvroSerDe'
STORED AS INPUTFORMAT 'org.apache.hadoop.hive.ql.io.avro.AvroContainerInputFormat'
OUTPUTFORMAT 'org.apache.hadoop.hive.ql.io.avro.AvroContainerOutputFormat'
LOCATION '/hdfs/path/some_hive_table/'
TBLPROPERTIES ('avro.schema.literal'='{json schema here}');
</code>```

I'd like to run some hive queries on it and export that data into an avro file.  I know I can export data like this:

```<code>INSERT
OVERWRITE DIRECTORY '/hdfs/path/avrofileoutput/'
SELECT * FROM some_hive_table;
</code>```

But I want my output file to be an avro file - not csv.  Can this be done and if so how?

答:
You can export any table irrespective of InputStorage as an AVRO file using below command to a Local location or HDFS location.

Starting with Hive 0.11.0

```<code>INSERT OVERWRITE LOCAL DIRECTORY '<Local directory>'
    STORED AS AVRO SELECT * FROM some_hive_table;
</code>```

https://cwiki.apache.org/confluence/display/Hive/LanguageManual+DML#LanguageManualDML-Writingdataintothefilesystemfromqueries

Title: Export hive table to .avro file

Body:
I created an external hive table like this:

CREATE EXTERNAL TABLE some_hive_table
ROW FORMAT SERDE 'org.apache.hadoop.hive.serde2.avro.AvroSerDe'
STORED AS INPUTFORMAT 'org.apache.hadoop.hive.ql.io.avro.AvroContainerInputFormat'
OUTPUTFORMAT 'org.apache.hadoop.hive.ql.io.avro.AvroContainerOutputFormat'
LOCATION '/hdfs/path/some_hive_table/'
TBLPROPERTIES ('avro.schema.literal'='{json schema here}');

I'd like to run some hive queries on it and export that data into an avro file.  I know I can export data like this:

INSERT
OVERWRITE DIRECTORY '/hdfs/path/avrofileoutput/'
SELECT * FROM some_hive_table;

But I want my output file to be an avro file - not csv.  Can this be done and if so how?

Body:
You can export any table irrespective of InputStorage as an AVRO file using below command to a Local location or HDFS location.

Starting with Hive 0.11.0

INSERT OVERWRITE LOCAL DIRECTORY '<Local directory>'
    STORED AS AVRO SELECT * FROM some_hive_table;

https://cwiki.apache.org/confluence/display/Hive/LanguageManual+DML#LanguageManualDML-Writingdataintothefilesystemfromqueries


问:
this is null in one function, not in another of the same class
In my React/JS application. this is part of the Component class I have:

```<code><p>
            <input
              onChange={ this.handleEmailChange } value={ this.props.email } type='email'
              className={ this.state.error ? 'form-control loginCredentialError shakeElement' : 'form-control' }
              name='email'
              placeholder='Email' required='True'
            />
            <input
              onChange={ this.handlePasswordChange } value={ this.props.password } type='password'
              className={ this.state.error ? 'form-control loginCredentialError shakeElement' : 'form-control' } name='password'
              placeholder='Password' required='True'
            />
          </p>
          <p>
            <Button
              onClick={ (event) => this.handleLoginClick(event) }
              className='btn btn-round-lg btn-round btn-primary btn-block center-block'
            >Sign In</Button>
          </p>
</code>```

As you can see I have handleEmailChange, handlePasswordChange, and handleLoginClick. Those three functions are of the same Component class as the render function

In this function, the this is evaluated as null, which makes this.setState fail.

```<code>handleEmailChange(event) {
    const value = event.target.value;
    console.log(value);
    this.setState({ email: value });
  }
</code>```

however, in this function the this is fine and has a value. setState works well. Can anyone please let me know why the difference in these seemingly similar functions?

```<code>handleLoginClick(event) {
    event.preventDefault();

    const payload = {
      'email': this.state.email,
      'password': this.state.password,
    };

    this.setState({ communicating: true, error: false, errorServer: false });
...
...
...
</code>```

答:
This difference here is in binding. If you look at how you set the onChange of Button and Input, in one you use an arrow function for handleLoginClick and the other you use {this.handleEmailChange}.

The arrow function automatically binds this to the function. There are two ways to fix this. Either:

```<code>onChange = {this.handleEmailChange.bind(this)}
</code>```

or

```<code>onChange = {(event) => handleEmailChange(event)}
</code>```

This will create a binding between the function and the this that you are setting the state of.

Check out : Difference of .bind() to arrow function () => usage in React for more info on binding to context using arrow functions or .bind()

Body:
In my React/JS application. this is part of the Component class I have:

            <input
              onChange={ this.handleEmailChange } value={ this.props.email } type='email'
              className={ this.state.error ? 'form-control loginCredentialError shakeElement' : 'form-control' }
              name='email'
              placeholder='Email' required='True'
            />
            <input
              onChange={ this.handlePasswordChange } value={ this.props.password } type='password'
              className={ this.state.error ? 'form-control loginCredentialError shakeElement' : 'form-control' } name='password'
              placeholder='Password' required='True'
            />

            <Button
              onClick={ (event) => this.handleLoginClick(event) }
              className='btn btn-round-lg btn-round btn-primary btn-block center-block'
            >Sign In</Button>

As you can see I have handleEmailChange, handlePasswordChange, and handleLoginClick. Those three functions are of the same Component class as the render function

In this function, the this is evaluated as null, which makes this.setState fail.

handleEmailChange(event) {
    const value = event.target.value;
    console.log(value);
    this.setState({ email: value });
  }

however, in this function the this is fine and has a value. setState works well. Can anyone please let me know why the difference in these seemingly similar functions?

handleLoginClick(event) {
    event.preventDefault();

    const payload = {
      'email': this.state.email,
      'password': this.state.password,
    };

    this.setState({ communicating: true, error: false, errorServer: false });
...
...
...

Body:
This difference here is in binding. If you look at how you set the onChange of Button and Input, in one you use an arrow function for handleLoginClick and the other you use {this.handleEmailChange}.

The arrow function automatically binds this to the function. There are two ways to fix this. Either:

onChange = {this.handleEmailChange.bind(this)}

or

onChange = {(event) => handleEmailChange(event)}

This will create a binding between the function and the this that you are setting the state of.

Check out : Difference of .bind() to arrow function () => usage in React for more info on binding to context using arrow functions or .bind()


问:
Master-child object design and generic base type for inherited objects issue in .net 4.0
I need to 2 levels of inheritance and abstraction in master-child relationship is the beginning of of the discussion.

What I want is to make sure all inherited objects from BaseMaster must have a list of children, and the type of the children must inherit from BaseChild. According to that post I have settled my design to

```<code>public abstract class BaseMaster<TChild> where TChild : BaseChild
{
    public Collection<TChild> Children { get; }
}

public abstract BaseChild
{ }

public class FirstRealMaster : BaseMaster<FirstRealChild> { /* add more properties */ }

public class FirstChild : BaseChild { /* add more properties */ }
</code>```

But with such design I lost the ability to use base object type to describe inherited objects, because BaseMaster<BaseChild> b = new FirstRealMaster(); won't be allowed, technically there are different types. Following is a sample code I hope I can make it work.

```<code>    static BaseMaster<BaseChild> ReturnBaseMaster(int i)
    {
        if (i == 1)
        {
            return new FirstRealMaster();
        }
        else if (i == 2)
        {
            return new SecondRealMaster();
        }

        return null;
    }
</code>```

Such limitation caused lots of inconvenience. Any suggestion here how to improve the design to achieve my goal that I need object model to enforce all inherited classes to have children. And meanwhile I still want the flexibility to use base type for inherited types?

答:
I am not sure what are you asking for, but maybe this will fit your expectations:

```<code>using System.Collections.Generic;

namespace ConsoleApplication
{
    class Program
    {
        static void Main (string[] args)
        {
            IMaster<IChild>           master1 = new ConcreteMaster ();
            IMaster<BaseChild>        master2 = new ConcreteMaster ();
            IMaster<ConcreteChild>    master3 = new ConcreteMaster ();
            BaseMaster<ConcreteChild> master4 = new ConcreteMaster ();
        }
    }

    public interface IChild { }

    public interface IMaster<out T> where T : IChild
    {
        IReadOnlyList<T> Children { get; }
    }

    public abstract class BaseMaster<T> : IMaster<T> where T : IChild
    {
        private readonly List<T> children = new List<T> ();

        public IReadOnlyList<T> Children => children;

        public void Add (T child)
        {
            children.Add (child);
        }
    }

    public abstract class BaseChild : IChild { }

    public class ConcreteMaster : BaseMaster<ConcreteChild> { }

    public class ConcreteChild : BaseChild {  }
}
</code>```

Notice if you want add child, you need to use base type.

Body:
I need to 2 levels of inheritance and abstraction in master-child relationship is the beginning of of the discussion.

What I want is to make sure all inherited objects from BaseMaster must have a list of children, and the type of the children must inherit from BaseChild. According to that post I have settled my design to

public abstract class BaseMaster<TChild> where TChild : BaseChild
{
    public Collection<TChild> Children { get; }
}

public abstract BaseChild
{ }

public class FirstRealMaster : BaseMaster<FirstRealChild> { /* add more properties */ }

public class FirstChild : BaseChild { /* add more properties */ }

But with such design I lost the ability to use base object type to describe inherited objects, because BaseMaster<BaseChild> b = new FirstRealMaster(); won't be allowed, technically there are different types. Following is a sample code I hope I can make it work.

    static BaseMaster<BaseChild> ReturnBaseMaster(int i)
    {
        if (i == 1)
        {
            return new FirstRealMaster();
        }
        else if (i == 2)
        {
            return new SecondRealMaster();
        }

        return null;
    }

Such limitation caused lots of inconvenience. Any suggestion here how to improve the design to achieve my goal that I need object model to enforce all inherited classes to have children. And meanwhile I still want the flexibility to use base type for inherited types?

Body:
I am not sure what are you asking for, but maybe this will fit your expectations:

using System.Collections.Generic;

namespace ConsoleApplication
{
    class Program
    {
        static void Main (string[] args)
        {
            IMaster<IChild>           master1 = new ConcreteMaster ();
            IMaster<BaseChild>        master2 = new ConcreteMaster ();
            IMaster<ConcreteChild>    master3 = new ConcreteMaster ();
            BaseMaster<ConcreteChild> master4 = new ConcreteMaster ();
        }
    }

    public interface IChild { }

    public interface IMaster<out T> where T : IChild
    {
        IReadOnlyList<T> Children { get; }
    }

    public abstract class BaseMaster<T> : IMaster<T> where T : IChild
    {
        private readonly List<T> children = new List<T> ();

        public IReadOnlyList<T> Children => children;

        public void Add (T child)
        {
            children.Add (child);
        }
    }

    public abstract class BaseChild : IChild { }

    public class ConcreteMaster : BaseMaster<ConcreteChild> { }

    public class ConcreteChild : BaseChild {  }
}

Notice if you want add child, you need to use base type.


问:
Using Classes in Python not initialise all valiables in constructor
after looking online there are several ways having a pythonic way for a class definition but not the one I was looking for. I am initialising all variables and both function need all of them. What I want is that not all variables need to be used per function, but only the ones needed, so not all don't need to be initialised:

I have the following test code:

```<code>class TestClass:

    def __init__(self,a,b,c,d):

        self.a  = a
        self.b  = b
        self.c = c
        self.d = d

    def CalcA(self):

        TestA = self.a + self.b

        return TestA

    def CalcB(self):

        TestB = self.c * self.d

        return TestB

if __name__ == '__main__':

    a=5.0
    b=10.0
    c=2.0
    d =0.01

    TestingTheClass = TestClass(a,b,c,d)
    NewCalcA = TestingTheClass.CalcA()
    NewCalcB = TestingTheClass.CalcB()

    print(NewCalcA)
    print(NewCalcB)
</code>```

答:
One possibility to get rid of extra variables(if that is what you are looking for) is to simply use a and b and redefine them so your code in the header of each class will be:

```<code>def CalcA(self, a, b):

def CalcB(self, c, d):
</code>```

and then your code at the bottom to deal with these would look something like:

```<code>a=5.0
b=10.0

TestingTheClass = TestClass()
NewCalcA = TestingTheClass.CalcA(a, b)
a = 2
b = 0.01
NewCalcB = TestingTheClass.CalcB(a, b)
</code>```

That makes it so you only have two variables at a time, and they are only defined for the next function so after the CalcA() you can get rid of the values in the variable to do CalcB()'s variables.

Body:
after looking online there are several ways having a pythonic way for a class definition but not the one I was looking for. I am initialising all variables and both function need all of them. What I want is that not all variables need to be used per function, but only the ones needed, so not all don't need to be initialised:

I have the following test code:

class TestClass:

    def __init__(self,a,b,c,d):

        self.a  = a
        self.b  = b
        self.c = c
        self.d = d

    def CalcA(self):

        TestA = self.a + self.b

        return TestA

    def CalcB(self):

        TestB = self.c * self.d

        return TestB

if __name__ == '__main__':

    a=5.0
    b=10.0
    c=2.0
    d =0.01

    TestingTheClass = TestClass(a,b,c,d)
    NewCalcA = TestingTheClass.CalcA()
    NewCalcB = TestingTheClass.CalcB()

    print(NewCalcA)
    print(NewCalcB)

Body:
One possibility to get rid of extra variables(if that is what you are looking for) is to simply use a and b and redefine them so your code in the header of each class will be:

def CalcA(self, a, b):

def CalcB(self, c, d):

and then your code at the bottom to deal with these would look something like:

a=5.0
b=10.0

TestingTheClass = TestClass()
NewCalcA = TestingTheClass.CalcA(a, b)
a = 2
b = 0.01
NewCalcB = TestingTheClass.CalcB(a, b)

That makes it so you only have two variables at a time, and they are only defined for the next function so after the CalcA() you can get rid of the values in the variable to do CalcB()'s variables.


问:
AWS: I can't link my route 53 configuration to my S3 bucket
I have 2 route53 hosted zone, let's call them myfirsturl.com and mysecondurl.com.
For both of them, I have created a bucket in S3 named after my domain names. I have verified it multiple times letter by letter.
Both of my buckets have static content, available from the S3 endpoint, with the fine policy etc: the 2 endpoints work perfectly.

The 1st hosted zone has been bought in route53 and when I connect to it, it opens my static website, all is good.
My second domain name has been transferred to Amazon last month, and in route 53 I can find the S3 bucket in the list of targets when I create the recordset, but it doesn't reach the static website

Another point: I have created a WP site a few days ago, behind a load balancer etc, and I linked wp.myfirsturl.com to it: it worked perfectly
I tried the same with wp.mysecondurl.com, to the same load balancer, it never worked.

I can't find any idea has I can't see any difference between my 2 domain name, except where I bought it.

Another difference:

The 1st is something like sometexte.info

The 2nd is something like sometext-othertext.fr

Maybe the hyphen is a problem? (it's not, pertaining to the doc)

Someone has a lead, please?

答: The bucket must have the same name as your domain or subdomain in Route53. For example, if you want to use the subdomain acme.example.com, the name of the bucket must be acme.example.com. Have a look at this documentation for more information. </p>


问:
HTML Bug, Image not aligning to the middle
I have an html file, and I am using bootstrap and Gentelella template, for some reason the only image I display in the widget is aligned to the right, and nothing that I do changes it to the middle.

Edit: For the css I am just using the regular bootstrap.min.css and the Gentella custom.css here:

```<code>.img-circle.profile_img {
width: 70%;
background: #fff;
margin-left: 15%;
z-index: 1000;
position: inherit;
margin-top: 20px;
border: 1px solid rgba(52, 73, 94, 0.44);
padding: 4px
}
</code>```

HTML:

```<code>   <div class="row">
   <div class="col-md-12 col-sm-12 col-xs-12">
<div class="x_panel">
  <div class="x_title">
    <h2>Summary</h2>
    <div class="clearfix"></div>
  </div>
  <div class="x_content">
    Users sneak peek should be inserted here...
  </div>

  <div class="col-md-3 col-xs-12 widget widget_tally_box">
    <div class="x_panel fixed_height_390">
      <div class="x_content">

        <div class="flex">
          <ul class="list-inline widget_profile_box text-center">
            <li>
              <img src="http://kenwheeler.github.io/slick/img/lazyfonz2.png" align="middle" class="img-circle profile_img">
            </li>
          </ul>
        </div>
        <h3 class="name">User Name</h3>

        <div class="flex">
          <ul class="list-inline count2">
            <li>
              <h3>123</h3>
              <span>Questions</span>
            </li>
            <li>
              <h3>1234</h3>
              <span>Answered</span>
            </li>
            <li>
              <h3>123</h3>
              <span>Unanswered</span>
            </li>
          </ul>
        </div>
        <p>
          Click here to see all the detailed information about this user.
        </p>
      </div>
    </div>
  </div>

</div>
</code>```

答:
Since .list-inline makes the li's inline-block, you can use .text-center on the ul to center the li

btw, the align attribute is obsolete on an img - https://www.w3.org/TR/html5/obsolete.html

<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>

User Name

123

            Questions

1234

            Answered

123

            Unanswered

        Click here to see all the detailed information about this user.

```

Body:
I have an html file, and I am using bootstrap and Gentelella template, for some reason the only image I display in the widget is aligned to the right, and nothing that I do changes it to the middle.

Edit: For the css I am just using the regular bootstrap.min.css and the Gentella custom.css here:

.img-circle.profile_img {
width: 70%;
background: #fff;
margin-left: 15%;
z-index: 1000;
position: inherit;
margin-top: 20px;
border: 1px solid rgba(52, 73, 94, 0.44);
padding: 4px
}

HTML:

Summary

    Users sneak peek should be inserted here...

User Name

123

              Questions

1234

              Answered

123

              Unanswered

          Click here to see all the detailed information about this user.

Body:
Since .list-inline makes the li's inline-block, you can use .text-center on the ul to center the li

btw, the align attribute is obsolete on an img - https://www.w3.org/TR/html5/obsolete.html

<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<div class="col-md-3 col-xs-12 widget widget_tally_box">
  <div class="x_panel fixed_height_390">
    <div class="x_content">

      <div class="flex">
        <ul class="list-inline widget_profile_box text-center">
          <li>
            <img src="images/user.png" class="img-circle profile_img">
          </li>
        </ul>
      </div>
      <h3 class="name">User Name</h3>

      <div class="flex">
        <ul class="list-inline count2">
          <li>
            <h3>123</h3>
            <span>Questions</span>
          </li>
          <li>
            <h3>1234</h3>
            <span>Answered</span>
          </li>
          <li>
            <h3>123</h3>
            <span>Unanswered</span>
          </li>
        </ul>
      </div>
      <p>
        Click here to see all the detailed information about this user.
      </p>
    </div>
  </div>
</div>


问:
What are my options for navigating through subroutines?
Suppose I want a program Foo.py which has some arbitrary routines Bar(), Quux(), and Fizz(). Let's say that the usual order of execution from a procedural perspective should be Bar() -> Quux() -> Fizz(). However, Fizz() should conditionally call a function Buzz() depending on some runtime action, and calling Buzz() at any time during Fizz() should return the process back to Quux().

I have a fair understanding of how concurrent processes can be implemented in assembly using system calls depending on the architecture, but what options are available to me in Python, where I can't – and frankly would prefer not to – use lots of jumps and directly move an instruction pointer around? When searching for an answer, I found loops and recursion as a suggestion for going back in a program. I don't think a loop would work without stopping the Fizz() process to wait for the condition check for Buzz(), and I'm not sure how recursion could be implemented in this scenario either. (My Buzz() would be like a "Back" button on a GUI).

答: Using coroutines (multithreading) will provide the desired concurrent functionality. Source in the comments of the question and of user2357112's answer.</p>


问:
Angular 2/4, "ngStyle". Apply different style depeding its father element active o inactive
I need to apply a style to an element when it parent element is actived. I'm using routerLinkActive to apply CSS Class and works fine, but deppending if the father element is actite apply one inline style (display: block), in other cases apply another (display: none).

If parent element is active:

```<code><li class="active">
   <ul class="sub-menu" style="display: block;">
</li>
<li>
   <ul class="sub-menu" style="display: none;">
</li>
</code>```

When I choose another element:

```<code><li>
   <ul class="sub-menu" style="display: none;">
</li>
<li class="active">
   <ul class="sub-menu" style="display: block;">
</li>
</code>```

I have an extended list of items with their respectives Links. Each "sub-menu" has its own list of elements.

答:
If you want to do this the angular way, I'd suggest making an object or array out of your menu so you can make dynamic changes to it in real time using data binding.

To make a dynamic menu with Angular, simply create a representation of your menu in your component. You can either provide it with static values if you do not plan on loading your menu from a database or making more complex modification to it. Otherwise, you can create a class for your menu and even your sub-menu to take the full advantage of object oriented programming.

Component:

```<code>menus: any [] = {
    { subMenus: any [] = { {}, {} }, active: boolean = true; },
    { subMenus: any [] = { {}, {} }, active: boolean = false; }
}
</code>```

Once you have your menu set up in your component, you can then make it fully dynamic by using angular data binding brackets in your html and using *ngFor to avoid repeating html.

Html:

```<code><li *ngFor="let menu of menus" [className]="menu.active?'active':''">
   <ul *ngFor="let subMenu of menus.subMenus class="sub-menu" [style.display]="menu.active?'block':'none'">
</li>
</code>```

You can use [ngStyle] to give more than one style at a time.

You can add

```<code>(click)="menu.active=!menu.active"
</code>```

to your 'li' tag to make it active or inactive on a click or

```<code>(click)="SetActive(menu)"
</code>```

create a function in your component that will set every menu beside the clicked menu to inactive.

Body:
I need to apply a style to an element when it parent element is actived. I'm using routerLinkActive to apply CSS Class and works fine, but deppending if the father element is actite apply one inline style (display: block), in other cases apply another (display: none).

If parent element is active:

When I choose another element:

I have an extended list of items with their respectives Links. Each "sub-menu" has its own list of elements.

Body:
If you want to do this the angular way, I'd suggest making an object or array out of your menu so you can make dynamic changes to it in real time using data binding.

To make a dynamic menu with Angular, simply create a representation of your menu in your component. You can either provide it with static values if you do not plan on loading your menu from a database or making more complex modification to it. Otherwise, you can create a class for your menu and even your sub-menu to take the full advantage of object oriented programming.

Component:

menus: any [] = {
    { subMenus: any [] = { {}, {} }, active: boolean = true; },
    { subMenus: any [] = { {}, {} }, active: boolean = false; }
}

Once you have your menu set up in your component, you can then make it fully dynamic by using angular data binding brackets in your html and using *ngFor to avoid repeating html.

Html:

<li *ngFor="let menu of menus" [className]="menu.active?'active':''">
   <ul *ngFor="let subMenu of menus.subMenus class="sub-menu" [style.display]="menu.active?'block':'none'">
</li>

You can use [ngStyle] to give more than one style at a time.

You can add

(click)="menu.active=!menu.active"

to your 'li' tag to make it active or inactive on a click or

(click)="SetActive(menu)"

create a function in your component that will set every menu beside the clicked menu to inactive.


问:
Showing UITabBar in a separate view
I'm new to Xcode/Cocoa/Objective-C, and I need a little help.

Essentially, I'm working on an app in which the first window has a couple of buttons; this is the Main Menu. When pressed, a button opens up a separate view that has a UITabBar and a Navigation Bar at the top that leads back to the Main Menu.

My two questions:

How do you make a UITabBar appear only in certain views?

How do you create a button to switch between nib files and not only views?

I've been using a RootViewController and TabBarController classes to be used by my RootView.xib (which is the main menu that holds the buttons) and a couple .xib files for the tab bar views (one nib file has each of the two views for the tab bars and nav bar).

I'd really appreciate any help with this!

答:
present your view with buttons modaly in your appDelegate. When you dismiss this view set a view controller with setSelectedViewController: as rootController in your TabBarControllers array.

Hope this helps

ContentLicense: CC BY-SA 2.5

Title: Showing UITabBar in a separate view


问:
Android onCreateOptionsMenu is never called so the menu isn't being displayed
I want to have a search bar in my menu toolbar, but when I navigate to the activity, the menu is never created because onCreateOptionsMenu is never called. I'm extending AppCompatActivity

```<code>@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.menu_search, menu);
    final SearchView searchView = (SearchView) MenuItemCompat.getActionView(menu.findItem(R.id.action_search));
    SearchManager searchManager = (SearchManager) getSystemService(SEARCH_SERVICE);
    searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));

    return true;
}
</code>```

Menu:

```<code><menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">
    <item android:id="@+id/action_search"
          android:title="@string/search"
          android:icon="@drawable/ic_search_black_36dp"
          app:showAsAction ="ifRoom|collapseActionView"
          app:actionViewClass ="android.support.v7.widget.SearchView" />

</menu>
</code>```

答:
The problem is probably on your AndroidManisfest.xml file. With the following default code I get the onCreateOptionsMenu(Menu menu) method loaded:

AndroidManisfest.xml:

```<code><application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:roundIcon="@mipmap/ic_launcher_round"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">
    <activity android:name=".MainActivity">
        <intent-filter>
        <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
</application>
</code>```

MainActivity.java:

```<code>public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        Log.d("BugFix","nothing");
        getMenuInflater().inflate(R.menu.menu_search, menu);
        final SearchView searchView = (SearchView) MenuItemCompat.getActionView(menu.findItem(R.id.action_search));
        SearchManager searchManager = (SearchManager) getSystemService(SEARCH_SERVICE);
        searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));

        return true;
    }
}
</code>```

activity_main.xml:

```<code><?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.example.el_greeko.exampleproject.MainActivity">

</android.support.constraint.ConstraintLayout>
</code>```

And the rest is your information given, with menu.search.xml in res/menu/

Btw. I suggest to read the instructions in the webpage of the
Search dialog. It may give you also a better solution for your search activity.

Body:
I want to have a search bar in my menu toolbar, but when I navigate to the activity, the menu is never created because onCreateOptionsMenu is never called. I'm extending AppCompatActivity

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.menu_search, menu);
    final SearchView searchView = (SearchView) MenuItemCompat.getActionView(menu.findItem(R.id.action_search));
    SearchManager searchManager = (SearchManager) getSystemService(SEARCH_SERVICE);
    searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));

    return true;
}

Menu:

<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">
    <item android:id="@+id/action_search"
          android:title="@string/search"
          android:icon="@drawable/ic_search_black_36dp"
          app:showAsAction ="ifRoom|collapseActionView"
          app:actionViewClass ="android.support.v7.widget.SearchView" />

</menu>

Body:
The problem is probably on your AndroidManisfest.xml file. With the following default code I get the onCreateOptionsMenu(Menu menu) method loaded:

AndroidManisfest.xml:

<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:roundIcon="@mipmap/ic_launcher_round"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">
    <activity android:name=".MainActivity">
        <intent-filter>
        <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
</application>

MainActivity.java:

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        Log.d("BugFix","nothing");
        getMenuInflater().inflate(R.menu.menu_search, menu);
        final SearchView searchView = (SearchView) MenuItemCompat.getActionView(menu.findItem(R.id.action_search));
        SearchManager searchManager = (SearchManager) getSystemService(SEARCH_SERVICE);
        searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));

        return true;
    }
}

activity_main.xml:

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.example.el_greeko.exampleproject.MainActivity">

</android.support.constraint.ConstraintLayout>

And the rest is your information given, with menu.search.xml in res/menu/

Btw. I suggest to read the instructions in the webpage of the
Search dialog. It may give you also a better solution for your search activity.