问:
Difference between Spring provided starter projects
I am learning Spring boot.

There are many starter projects provided. From a developer point of view, what is the difference amongst all of them, when should one go one specifically?

For instances, what is difference in - spring-boot-starter-parent,spring-boot-starter-web,spring-boot-starter-freemarker,spring-boot-starter-data-jpa etc.

Thanks

答:
As per Spring starter's documentation.

Spring Boot Starters are a set of convenient dependency descriptors
  that you can include in your application. You get a one-stop-shop for
  all the Spring and related technology that you need without having to
  hunt through sample code and copy paste loads of dependency
  descriptors. For example, if you want to get started using Spring and
  JPA for database access just include the spring-boot-starter-data-jpa
  dependency in your project, and you are good to go.

Refer this for all starter-poms supported by spring.

spring-boot-starter-web  - Starter for building web, including RESTful, applications using Spring MVC. Uses Tomcat as the default embedded container

spring-boot-starter-freemarker - Starter for building MVC web applications using FreeMarker views

spring-boot-starter-data-jpa - Starter for using Spring Data JPA with Hibernate

Refer spring's official documentation for more starter-projects.

Starters provide you OOTB integration of different applications shunning the need of boilerplate configuration.

Hope this helps!


来源: stackexchange

问:
Colour of progress bar in fileInput -- Shiny
I am trying to change the colour of the upload progress bar in the fileInput widget in Shiny. I am a bit of a shiny novice and have scoured the internet with no results. Any ideas?</p>

答:
Here is a sample app where I have made the color of progress bar green using css.

```<code>ui <- fluidPage(

    tags$head(tags$style(".progress-bar{background-color:#3c763d;}")),

    fileInput(inputId = "fileInp", label = "Input file:",multiple = FALSE,
               accept = c(
                 "text/csv",
                 "text/comma-separated-values,text/plain",
                 ".csv"))

  )

  server <- function(input, output){

  }

  shinyApp(ui=ui, server=server)
</code>```

Using the above code you get something like this:

Hope it helps!

ContentLicense: CC BY-SA 3.0

Body:
Here is a sample app where I have made the color of progress bar green using css.

ui <- fluidPage(

    tags$head(tags$style(".progress-bar{background-color:#3c763d;}")),

    fileInput(inputId = "fileInp", label = "Input file:",multiple = FALSE,
               accept = c(
                 "text/csv",
                 "text/comma-separated-values,text/plain",
                 ".csv"))

  )

  server <- function(input, output){

  }

  shinyApp(ui=ui, server=server)

Using the above code you get something like this:

Hope it helps!


问:
How to create programatic autolayout in objective c?
I want to Displays the content (including image, title and description) in a table.
I am trying to set autolayout for same. but my image is getting shrink according to cell height.
But I want to show image as original (all images are of diff. height width)

```<code> UIImageView *customImageView;
        UILabel *customLabel;

        customImageView = [[UIImageView alloc] init];
        customImageView.translatesAutoresizingMaskIntoConstraints = NO;
        customImageView.tag = indexPath.row + 100;
        customImageView.translatesAutoresizingMaskIntoConstraints = NO;
        [cell.contentView addSubview:customImageView];

        customLabel = [[UILabel alloc] init];
        customLabel.translatesAutoresizingMaskIntoConstraints = NO;
        customLabel.tag =  indexPath.row + 500;
        customLabel.numberOfLines = 0;
        customLabel.lineBreakMode = NSLineBreakByWordWrapping;

        [cell.contentView addSubview:customLabel];

        NSDictionary *views = NSDictionaryOfVariableBindings(customImageView, customLabel);
        [cell.contentView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|-5-[customImageView(160)]-[customLabel]|" options:0 metrics:nil views:views]];
        [cell.contentView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|-3-[customImageView]-3-|"                 options:0 metrics:nil views:views]];
        [cell.contentView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|-3-[customLabel]-3-|"                     options:0 metrics:nil views:views]];
</code>```

1.HOw can i show image as it is
2.how can I add another label for description below title label using constraints?
Can you please suggest some solution or guide me on this?

答:
All that you need is UITableViewAutomaticDimension. ImageView's has implicit size. ImageViews take size based on the image set to them. When your cell contains the components with implicit sizes you can make use of UITableViewAutomaticDimension to tell the tableView to size the cell based on the size of imageView.

make sure you set the imageView's content mode set to center

Code :

```<code>self.tableView.rowHeight = UITableViewAutomaticDimension
self.tableView.estimatedRowHeight = 140
</code>```

Don't write height for row at indexPath :)

O/P:

Look at cell sizes. Changing their size automatically based on image.

EDIT :

Forgot to mention the only auto layout constraint added to imageView and cell are trailing, leading, top and bottom constraints with constant 0 to cell.

Body:
I want to Displays the content (including image, title and description) in a table.
I am trying to set autolayout for same. but my image is getting shrink according to cell height.
But I want to show image as original (all images are of diff. height width)

 UIImageView *customImageView;
        UILabel *customLabel;

        customImageView = [[UIImageView alloc] init];
        customImageView.translatesAutoresizingMaskIntoConstraints = NO;
        customImageView.tag = indexPath.row + 100;
        customImageView.translatesAutoresizingMaskIntoConstraints = NO;
        [cell.contentView addSubview:customImageView];

        customLabel = [[UILabel alloc] init];
        customLabel.translatesAutoresizingMaskIntoConstraints = NO;
        customLabel.tag =  indexPath.row + 500;
        customLabel.numberOfLines = 0;
        customLabel.lineBreakMode = NSLineBreakByWordWrapping;

        [cell.contentView addSubview:customLabel];

        NSDictionary *views = NSDictionaryOfVariableBindings(customImageView, customLabel);
        [cell.contentView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|-5-[customImageView(160)]-[customLabel]|" options:0 metrics:nil views:views]];
        [cell.contentView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|-3-[customImageView]-3-|"                 options:0 metrics:nil views:views]];
        [cell.contentView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|-3-[customLabel]-3-|"                     options:0 metrics:nil views:views]];

1.HOw can i show image as it is
2.how can I add another label for description below title label using constraints?
Can you please suggest some solution or guide me on this?

Body:
All that you need is UITableViewAutomaticDimension. ImageView's has implicit size. ImageViews take size based on the image set to them. When your cell contains the components with implicit sizes you can make use of UITableViewAutomaticDimension to tell the tableView to size the cell based on the size of imageView.

make sure you set the imageView's content mode set to center

Code :

self.tableView.rowHeight = UITableViewAutomaticDimension
self.tableView.estimatedRowHeight = 140

Don't write height for row at indexPath :)

O/P:

Look at cell sizes. Changing their size automatically based on image.

EDIT :

Forgot to mention the only auto layout constraint added to imageView and cell are trailing, leading, top and bottom constraints with constant 0 to cell.


问:
Powershell Remote Commands
I'm trying to run the get-service command on a remote machine in powershell. After doing some research, it appears this is only possilbe n powershell 2 CTP, which I cannot use as I need to use the version of powershell installed with exchange, which is usualy 1. It seems the -computerName switch is only availible in  get-service in ps 2.
So i've pretty much decided its a no-go, but wanted to see if anyone here had an clever solutions before I give up on it.</p>

答:
Well, you can go directly to WMI the get the service information.</p>

```<code>gwmi Win32_Service -computername FOO
</code>```

ContentLicense: CC BY-SA 2.5

Title: Powershell Remote Commands

Body:
Well, you can go directly to WMI the get the service information.

gwmi Win32_Service -computername FOO

OwnerDisplayName: EBGreen


问:
How to plot surface plot

Is there an inbuilt / m file in Matlab
  to obtain the highly fluctuatiing and
  multiple peaks of the plot of an
  alpine function? I want to obtain a
  similar figure in 3D which is !alt
  text and

The formula (probably) is

z=sin(x1)sin(x2)\sqrt{x1x2}

How does one plot a surface plot for the major functions like alpine,rosenbrock, egg crate function etc in a colorful illustrative way. Kindly help with a sample code.

答:
Well, you must create a meshgrid choosing the right sampling (in this example from -5 to 5 with a step of 0.1). In Z put the formula of your function Z = f(X,Y) </p>

```<code>X=[-5:0.1:5]; %% The X-axis goes from the value of -5 to +5 with a step of 0.1 (100 points)
Y=[-5:0.1:5]; %% like the X-axis
[wx,wy]=meshgrid(X,Y); %% see [MATLAB documentation][1]
Z=sinc(sqrt((wx-5).^2+wy.^2)); %% this is an example formula, substitute it with YOUR formula
fig=surfl(wx,wy,Z); %% make a surface plot with lighting
shading interp; %% optional, try to remove it.
colormap hot; %% here you decide the colormap: hot is the one going from white to red
view(45,40) %% optional, select the angle of view
</code>```

<p>If you want a meaningful color just study the colormap function, it's very simple. </p>

Title: How to plot surface plot

Body:
Well, you must create a meshgrid choosing the right sampling (in this example from -5 to 5 with a step of 0.1). In Z put the formula of your function Z = f(X,Y)

X=[-5:0.1:5]; %% The X-axis goes from the value of -5 to +5 with a step of 0.1 (100 points)
Y=[-5:0.1:5]; %% like the X-axis
[wx,wy]=meshgrid(X,Y); %% see [MATLAB documentation][1]
Z=sinc(sqrt((wx-5).^2+wy.^2)); %% this is an example formula, substitute it with YOUR formula
fig=surfl(wx,wy,Z); %% make a surface plot with lighting
shading interp; %% optional, try to remove it.
colormap hot; %% here you decide the colormap: hot is the one going from white to red
view(45,40) %% optional, select the angle of view

If you want a meaningful color just study the colormap function, it's very simple.


问:
I am not able to find the .exe file in Visual Studio 2013
I am trying to create a c++ blank project
I am not able to find the .exe file in the debug folder.
Where can I find it or should I search in a new directory or should I do something else?
Pls help.
Thanks </p>

答:
you dont have any exe nor debug or release folder until you build the project you are working on...

after that you will find folders Debug or Release depending on what you did

and inside is the exe generated by VS


问:
What are Promotional Text and Subtitle in iTunesConnection?
Promotional Text and Subtitle are the new feature in iTuneconnection which is available in iOS 11.0 or above. Subtitle is optional. But Promotional Text is not mentioned as optional. Which text we need to write as Promotional Text. Is it for only current app or any other apps using same developer account?</p>

答:
Promotional Text (or Description)

it is optional we can update the description on any time.

Your app’s promotional text appears at the top of the description and is limited to 170 characters. You can update it at any time without having to submit a new version of your app. Consider using promotional text to share the latest news about your app, which can include new promotions for your app or in-app purchases, upcoming features or content, limited- time sales, or other events within your app.

for more information you can get appstore product page and here also


问:
Why does the numpy.zeros() matrix get false in scipy.sparse.issparse()?
I created matrix by np.zeros(), and tested it with sp.issparse(). Why I get false even the matrix is zero (or in case of mostly zero matrix as well)?

答:
A sparse matrix has a different memory representation: it is not the cells being zero that matters but the fact that the cells are allocated in memory.

np.zeros() allocates all fields of the array in memory, even those being zero, while a sparse matrix does not.

See here for how to convert from a numpy matrix/array to a sparse matrix.


问:
Laravel Update not working
I have table called admins and model called Admin.

When i try to update the records it fails every time with one field.

```<code>$admindetail = Admin::find($id);
$admindetail->fill(['is_delete'=>1])->save();
</code>```

Above code is not updating record in DB. datatype for is_delete is tinyint.

If i update name field it works with the same code like

```<code>$admindetail = Admin::find($id);
$admindetail->fill(['name'=>'abc'])->save();
</code>```

Can you help me why first code is not working.

答:
Instead of passing value as array, you could try the code below:</p>
```<code>$admindetail = Admin::find($id);
if(!$admindetail)
{
  $admindetail->is_delete=1;
   $admindetail->save();
}
</code>```

Title: Laravel Update not working

Body:
I have table called admins and model called Admin.

When i try to update the records it fails every time with one field.

$admindetail = Admin::find($id);
$admindetail->fill(['is_delete'=>1])->save();

Above code is not updating record in DB. datatype for is_delete is tinyint.

If i update name field it works with the same code like

$admindetail = Admin::find($id);
$admindetail->fill(['name'=>'abc'])->save();

Can you help me why first code is not working.

Body:
Instead of passing value as array, you could try the code below:

$admindetail = Admin::find($id);
if(!$admindetail)
{
  $admindetail->is_delete=1;
   $admindetail->save();
}

ContentLicense: CC BY-SA 4.0


问:
Line paragraphing - Xamarin.Android
I have been trying to paragraph my lines(text) and get the right font on my app. My question seems crazy but please help me out. This is what I have tried so far.

Line.axml

```<code>  <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:textAppearance="?android:attr/textAppearanceMedium"
                android:textSize="17sp"
                android:textColor="#333333"
                android:text="Caption"
                android:layout_weight="1"
                android:ellipsize="none"
                android:maxLines="50"
                android:scrollHorizontally="false"
                android:id="@+id/textView"
                android:fontFamily="Times New Roman"
                android:layout_marginLeft="4dp"
                android:layout_marginTop="15dp"
                android:layout_gravity="center_vertical|right"

            />
</code>```

Current Display

Expected Display

答:
The expected font you want looks like the Roboto Regular to me. Then you can simply change your android:fontFamily="Times New Roman" to android:fontFamily="sans-serif".

Roboto is the standard typeface on Android. And you can check Roboto & Noto fonts to find the latest version of Roboto:

So the font family are as following:

```<code>android:fontFamily="sans-serif"           // roboto regular
android:fontFamily="sans-serif-light"     // roboto light
android:fontFamily="sans-serif-condensed" // roboto condensed
android:fontFamily="sans-serif-black"     // roboto black
android:fontFamily="sans-serif-thin"      // roboto thin (android 4.2)
android:fontFamily="sans-serif-medium"    // roboto medium (android 5.0)
</code>```

together we can define the font also with  android:textStyle="normal|bold|italic".

In addition, if you want to use your custom font, you can refer to this official doc: Working With Fonts.

Title: Line paragraphing - Xamarin.Android

Body:
I have been trying to paragraph my lines(text) and get the right font on my app. My question seems crazy but please help me out. This is what I have tried so far.

Line.axml

  <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:textAppearance="?android:attr/textAppearanceMedium"
                android:textSize="17sp"
                android:textColor="#333333"
                android:text="Caption"
                android:layout_weight="1"
                android:ellipsize="none"
                android:maxLines="50"
                android:scrollHorizontally="false"
                android:id="@+id/textView"
                android:fontFamily="Times New Roman"
                android:layout_marginLeft="4dp"
                android:layout_marginTop="15dp"
                android:layout_gravity="center_vertical|right"

            />

Current Display

Expected Display

Body:
The expected font you want looks like the Roboto Regular to me. Then you can simply change your android:fontFamily="Times New Roman" to android:fontFamily="sans-serif".

Roboto is the standard typeface on Android. And you can check Roboto & Noto fonts to find the latest version of Roboto:

So the font family are as following:

android:fontFamily="sans-serif"           // roboto regular
android:fontFamily="sans-serif-light"     // roboto light
android:fontFamily="sans-serif-condensed" // roboto condensed
android:fontFamily="sans-serif-black"     // roboto black
android:fontFamily="sans-serif-thin"      // roboto thin (android 4.2)
android:fontFamily="sans-serif-medium"    // roboto medium (android 5.0)

together we can define the font also with  android:textStyle="normal|bold|italic".

In addition, if you want to use your custom font, you can refer to this official doc: Working With Fonts.


问:
supportsLollipop in Kotlin
I am learning Kotlin syntac and extensions of it. I came across that if you want to run code on Lollipop and above you can do

```<code>supportsLollipop {
    window.setStatusBarColor(Color.BLACK)
}
</code>```

This seems well, I am trying to use it in my code but getting an error "Expecting member declaration" .

```<code>class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        submitButton.setOnClickListener({ view ->
            longToast("Clicked")
        })
    }

    inline fun supportsLollipop(code: () -> Unit) {
        if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            code()
        }
    }

    supportsLollipop {
        Log.d("Test", "Test")
    }
}
</code>```

Do I need to install any extension for it ? Do you have an idea ?

答:
You could go through https://android.jlelse.eu/keddit-part-7-infinite-scroll-higher-order-functions-lambdas-3a11fbd5090e</p>

```<code>class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        submitButton.setOnClickListener({ view ->
            longToast("Clicked")
        })

        supportsLollipop {
            Log.d("Test", "Test")
        }
    }

    inline fun supportsLollipop(code: () -> Unit) {
        if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            code()
        }
    }

}
</code>```

Title: supportsLollipop in Kotlin

Body:
I am learning Kotlin syntac and extensions of it. I came across that if you want to run code on Lollipop and above you can do

supportsLollipop {
    window.setStatusBarColor(Color.BLACK)
}

This seems well, I am trying to use it in my code but getting an error "Expecting member declaration" .

class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        submitButton.setOnClickListener({ view ->
            longToast("Clicked")
        })
    }

    inline fun supportsLollipop(code: () -> Unit) {
        if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            code()
        }
    }

    supportsLollipop {
        Log.d("Test", "Test")
    }
}

Do I need to install any extension for it ? Do you have an idea ?

Body:
You could go through https://android.jlelse.eu/keddit-part-7-infinite-scroll-higher-order-functions-lambdas-3a11fbd5090e

class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        submitButton.setOnClickListener({ view ->
            longToast("Clicked")
        })

        supportsLollipop {
            Log.d("Test", "Test")
        }
    }

    inline fun supportsLollipop(code: () -> Unit) {
        if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            code()
        }
    }

}


问:
How to print on the screen data from SQLite db?
I have tried to follow this:
How do I dump the data of some SQLite3 tables?
but was not helpfull too much.

```<code>sqlite3 Database.pich1.db .dump
PRAGMA foreign_keys=OFF;
BEGIN TRANSACTION;
COMMIT;
</code>```

Also with

```<code>sqlite3 database.pich1.db .dump | grep '^INSERT INTO "tablename"'
</code>```

I got nothing.
This works better,although writes to file:

```<code>echo '.dump' | sqlite3 pich1.db > pich1.txt
</code>```

After that I can cat the text file:

```<code>PRAGMA foreign_keys=OFF;
BEGIN TRANSACTION;
CREATE TABLE pcod (
    id INTEGER PRIMARY KEY,
    name TEXT,
    age INTEGER,
    address TEXT,
    salary FLOAT
);
INSERT INTO "pcod" VALUES(1,'Silivio',37,'Futoshka',250.0);
INSERT INTO "pcod" VALUES(2,'Jean',17,'Bulevar',800.0);
INSERT INTO "pcod" VALUES(3,'Phil',22,'Dunavska',770.0);
INSERT INTO "pcod" VALUES(4,'Ed',24,'Lipov Gaj',1300.0);
INSERT INTO "pcod" VALUES(5,'Oskar',57,'Partizanska',99.0);
INSERT INTO "pcod" VALUES(6,'John',37,'Veternik',250.0);
INSERT INTO "pcod" VALUES(7,'JIm',17,'Suboticks',800.0);
INSERT INTO "pcod" VALUES(8,'Doug',22,'Vrsacka',770.0);
INSERT INTO "pcod" VALUES(9,'Lev',24,'Beogradska',1300.0);
INSERT INTO "pcod" VALUES(10,'Chris',57,'Bihacka',99.0);
COMMIT;
</code>```

Is there any other way to dump the contents on the screen?I am on Ubuntu 14.04.

答:
Use this code

```<code>SELECT * FROM <FileName>
</code>```

* is a special character which prints all the columns.
you can also refer here : https://dba.stackexchange.com/questions/40656/how-to-properly-format-sqlite-shell-output

Body:
I have tried to follow this:
How do I dump the data of some SQLite3 tables?
but was not helpfull too much.

sqlite3 Database.pich1.db .dump
PRAGMA foreign_keys=OFF;
BEGIN TRANSACTION;
COMMIT;

Also with

sqlite3 database.pich1.db .dump | grep '^INSERT INTO "tablename"'

I got nothing.
This works better,although writes to file:

echo '.dump' | sqlite3 pich1.db > pich1.txt

After that I can cat the text file:

PRAGMA foreign_keys=OFF;
BEGIN TRANSACTION;
CREATE TABLE pcod (
    id INTEGER PRIMARY KEY,
    name TEXT,
    age INTEGER,
    address TEXT,
    salary FLOAT
);
INSERT INTO "pcod" VALUES(1,'Silivio',37,'Futoshka',250.0);
INSERT INTO "pcod" VALUES(2,'Jean',17,'Bulevar',800.0);
INSERT INTO "pcod" VALUES(3,'Phil',22,'Dunavska',770.0);
INSERT INTO "pcod" VALUES(4,'Ed',24,'Lipov Gaj',1300.0);
INSERT INTO "pcod" VALUES(5,'Oskar',57,'Partizanska',99.0);
INSERT INTO "pcod" VALUES(6,'John',37,'Veternik',250.0);
INSERT INTO "pcod" VALUES(7,'JIm',17,'Suboticks',800.0);
INSERT INTO "pcod" VALUES(8,'Doug',22,'Vrsacka',770.0);
INSERT INTO "pcod" VALUES(9,'Lev',24,'Beogradska',1300.0);
INSERT INTO "pcod" VALUES(10,'Chris',57,'Bihacka',99.0);
COMMIT;

Is there any other way to dump the contents on the screen?I am on Ubuntu 14.04.

Body:
Use this code

SELECT * FROM <FileName>

* is a special character which prints all the columns.
you can also refer here : https://dba.stackexchange.com/questions/40656/how-to-properly-format-sqlite-shell-output


问:
PyQt showing video stream from opencv
Try to link PyQt and Opencv video feed, can't understand how to apply while loop for continuously streaming video.  It just take a still picture.Please can anyone help to solve the problem.

PtQt=5

Python=3.6.1

```<code>class App(QWidget):
    def __init__(self):
        super().__init__()
        self.title = 'PyQt5 Video'
        self.left = 100
        self.top = 100
        self.width = 640
        self.height = 480
        self.initUI()

    def initUI(self):
        self.setWindowTitle(self.title)
        self.setGeometry(self.left, self.top, self.width, self.height)
        self.resize(1800, 1200)
        #create a label
        label = QLabel(self)
        cap = cv2.VideoCapture(0)
        ret, frame = cap.read()
        rgbImage = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
        convertToQtFormat = QtGui.QImage(rgbImage.data, rgbImage.shape[1], rgbImage.shape[0],
                                         QtGui.QImage.Format_RGB888)
        convertToQtFormat = QtGui.QPixmap.fromImage(convertToQtFormat)
        pixmap = QPixmap(convertToQtFormat)
        resizeImage = pixmap.scaled(640, 480, QtCore.Qt.KeepAspectRatio)
        QApplication.processEvents()
        label.setPixmap(resizeImage)
        self.show()

if __name__ == '__main__':
    app = QApplication(sys.argv)
    ex = App()
    sys.exit(app.exec_())
</code>```

答:
The problem is that the function that obtains the image is executed only once and not updating the label.

The correct way is to place it inside a loop, but it will result in blocking the main window. This blocking of main window can be solved by using the QThread class and send through a signal QImage to update the label. For example:

import cv2
import sys
from PyQt5.QtWidgets import  QWidget, QLabel, QApplication
from PyQt5.QtCore import QThread, Qt, pyqtSignal, pyqtSlot
from PyQt5.QtGui import QImage, QPixmap

class Thread(QThread):
    changePixmap = pyqtSignal(QImage)

    def run(self):
        cap = cv2.VideoCapture(0)
        while True:
            ret, frame = cap.read()
            if ret:
                # https://stackoverflow.com/a/55468544/6622587
                rgbImage = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
                h, w, ch = rgbImage.shape
                bytesPerLine = ch * w
                convertToQtFormat = QImage(rgbImage.data, w, h, bytesPerLine, QImage.Format_RGB888)
                p = convertToQtFormat.scaled(640, 480, Qt.KeepAspectRatio)
                self.changePixmap.emit(p)

class App(QWidget):
    def __init__(self):
        super().__init__()
        [...]
        self.initUI()

    @pyqtSlot(QImage)
    def setImage(self, image):
        self.label.setPixmap(QPixmap.fromImage(image))

    def initUI(self):
        self.setWindowTitle(self.title)
        self.setGeometry(self.left, self.top, self.width, self.height)
        self.resize(1800, 1200)
        # create a label
        self.label = QLabel(self)
        self.label.move(280, 120)
        self.label.resize(640, 480)
        th = Thread(self)
        th.changePixmap.connect(self.setImage)
        th.start()
        self.show()
```

Title: PyQt showing video stream from opencv

Body:
Try to link PyQt and Opencv video feed, can't understand how to apply while loop for continuously streaming video.  It just take a still picture.Please can anyone help to solve the problem.

PtQt=5

Python=3.6.1

class App(QWidget):
    def __init__(self):
        super().__init__()
        self.title = 'PyQt5 Video'
        self.left = 100
        self.top = 100
        self.width = 640
        self.height = 480
        self.initUI()

    def initUI(self):
        self.setWindowTitle(self.title)
        self.setGeometry(self.left, self.top, self.width, self.height)
        self.resize(1800, 1200)
        #create a label
        label = QLabel(self)
        cap = cv2.VideoCapture(0)
        ret, frame = cap.read()
        rgbImage = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
        convertToQtFormat = QtGui.QImage(rgbImage.data, rgbImage.shape[1], rgbImage.shape[0],
                                         QtGui.QImage.Format_RGB888)
        convertToQtFormat = QtGui.QPixmap.fromImage(convertToQtFormat)
        pixmap = QPixmap(convertToQtFormat)
        resizeImage = pixmap.scaled(640, 480, QtCore.Qt.KeepAspectRatio)
        QApplication.processEvents()
        label.setPixmap(resizeImage)
        self.show()

if __name__ == '__main__':
    app = QApplication(sys.argv)
    ex = App()
    sys.exit(app.exec_())


问:
Android Studio - Drawable folders
I have three general questions regarding android's drawable folders.

Do i put different sized images in each of these folders, or will the images automatically scale themselves? As in, does android decrease the quality of the .bmp files automatically if placed in these folders?

When using the android design preview screen, will the appropriate image from the appropriate drawable folder be shown? If I have to make different sized images for each folder, I want to ensure that what i'm seeing in the design preview matches what is shown on other devices.

Lastly, do the drawable folders, if used, help to avoid the issue with failing to allocate memory for drawables on devices? I have had to scale my images down, and yet my college's phone still cannot allocate enough resources.

I couldn't find answers to these specific questions anywhere, so i'd really appreciate the help with these!

答:
About your first question, you should create four different drawable folders in app>res in order to provide different devices (with different screen sizes and densities) more convenient images.

/drawable-ldpi For low density screens.

/drawable-mdpi For medium density screens.

/drawable-hdpi For high resolution screens.

/drawable-xhdpi For extra high resolution screens.

Android does not decrease the quality of .bmp files when they are allocated in those folders. You have to fill each folder with the correct sized images.

About second question, I am not sure whether the android design preview screen uses the correct images or not, but in a real app running on a phone, it will.

And third question: sorry, but not.

Good luck!

Title: Android Studio - Drawable folders


答:
You need to have the function.</p>

```<code> fun supportsLollipop(code: () -> Unit) {
        supportsVersion(code, 21)
    }

private fun supportsVersion(code: () -> Unit, sdk: Int) {
    if (Build.VERSION.SDK_INT >= sdk) {
        code.invoke()
    }
}
</code>```

Title: supportsLollipop in Kotlin

Body:
You need to have the function.

 fun supportsLollipop(code: () -> Unit) {
        supportsVersion(code, 21)
    }

private fun supportsVersion(code: () -> Unit, sdk: Int) {
    if (Build.VERSION.SDK_INT >= sdk) {
        code.invoke()
    }
}


问:
Why is the following job scheduling command throwing an ambiguous redirect error?
I have 10 users(user0-user9). Each of them have a folder named delta. There are 10 folders(folder1-folder10) in each delta folder. There's a file.txt in each of the ten folders. Why does the following job scheduling command throw an ambiguous redirect?

How do I do this without a for loop provided I need to append different random strings to each of the files?

```<code>crontab -e
21 15 * * 1-6 echo $(cat /dev/urandom | tr -dc 'a-zA-Z0-9' | fold -w 10 | head -n 1) >>/home/user{0..9}/delta/folder{1..10}/file.txt
</code>```

答:
If your goal is to write the same output to all of the files, then you can use tee:

```<code>tr -dc a-zA-Z0-9 </dev/urandom |
    fold -w 10 |
    head -n 1 |
    tee -a /home/user{0..9}/delta/folder{1..10}/file.txt >/dev/null
</code>```

If your goal is to append different things, then I think a loop is unavoidable. For your cron-job case, that means you'll need to wrap your command in bash -c '...'.

Body:
I have 10 users(user0-user9). Each of them have a folder named delta. There are 10 folders(folder1-folder10) in each delta folder. There's a file.txt in each of the ten folders. Why does the following job scheduling command throw an ambiguous redirect?

How do I do this without a for loop provided I need to append different random strings to each of the files?

crontab -e
21 15 * * 1-6 echo $(cat /dev/urandom | tr -dc 'a-zA-Z0-9' | fold -w 10 | head -n 1) >>/home/user{0..9}/delta/folder{1..10}/file.txt

Body:
If your goal is to write the same output to all of the files, then you can use tee:

tr -dc a-zA-Z0-9 </dev/urandom |
    fold -w 10 |
    head -n 1 |
    tee -a /home/user{0..9}/delta/folder{1..10}/file.txt >/dev/null

If your goal is to append different things, then I think a loop is unavoidable. For your cron-job case, that means you'll need to wrap your command in bash -c '...'.


问:
Why can we supply a Comparator to TreeSet but not something like Hasher to HashSet?
In Java 6, my understanding is that you can supply a Comparator to a TreeSet when creating it to override the "natural ordering" of the objects in the set.

Do you have any thoughts why Java doesn't support supplying a "Hasher" that overrides the "natural hashing" of objects in the set as well?

EDIT:
Getting input from you might help me when designing APIs in the future.

Thanks.

答:
A Hasher object would be redundant to the hashCode() method in the Object class.

If you want to effect the nature of the hashing, you should override the hashCode() method defined on Object.  Just be sure to override equals(Object) as well, since these two should always go together.

A HashSet or other similar data structure will use the objects hashCode() method to get a hash value to determine bin storage.  It will then use equals() to compare that object to other objects in the same bin to determine equality.

The hash code generated needs to be unique to that specific class of object.  This can be ensured simply by overriding the hashCode() method and doesn't need to change from implementation to implementation.  A Hasher object would just obfuscate and serve no additional purpose.  I couldn't think of a single use case where multiple hash codes would be needed for storage in different data structures.


问:
Dropdown list in Table view
i want to add a drop down list For e.g:
I need two menus like chats and soups.

In chat i have to display some chat items
 similarly in soup items i need to display some soup items.

While selecting the chat menu, the soup menu items should hidden and soup menu bar to be pushed down displayed with an right arrow similarly when i select soup menu chat menu items should hidden and chat menu bar to be pushed up with a right arrow. How can i add this in using  UITableView  ..

答:
I have used the subtable master which acts as drop down in table view itself.attached link below

https://github.com/ajkoshy7/SubTable

Title: Dropdown list in Table view


问:
jQuery Hide / Show not working on iOS
I'm trying to make hide and show loading bar on my website
I tested on Android and PC it working well
but it not working for ios please take a look.

Jquery

```<code>  echo' <script> ';
    echo' $(document).ready(function(){ ';
    echo'     $("#btn").click(function(){ ';
    echo"        $('#btn').hide(); ";
     echo'    }); ';
     echo'    $("#btn").click(function(){ ';
      echo'       $("#loading").show(); ';
     echo'    }); ';
    echo' });';
    echo'</script>';
</code>```

HTML

```<code>echo"       <a class='btn btn-success margin btn-block btn-lg' id='btn' href='" . $loginUrl . "'>Click to Play</a>";
echo'           <img style="display:none;" class="img-responsive img center-block" id="loading" src="loading.gif"/> ';
</code>```

答:
What if You add timeout to show/hide?</p>

```<code>  $('#btn').hide(250);
  $("#loading").show(250);
</code>```

Title: jQuery Hide / Show not working on iOS

Body:
I'm trying to make hide and show loading bar on my website
I tested on Android and PC it working well
but it not working for ios please take a look.

Jquery

  echo' ';

HTML

echo"       Click to Play";
echo'            ';

Body:
What if You add timeout to show/hide?

  $('#btn').hide(250);
  $("#loading").show(250);


问:
javascript - Age calculation
Having 2 javascript Dates,

first is birthdate
and second is a date to calculate age from that date.

What should be the best way to do this.

答:
Get age calculating by current year</p>

```<code>calculateExp(birthDate) {
    birthDate = new Date(birthDate);
    var now = new Date();
    otherDate = new Date(now.getFullYear(),now.getMonth(),now.getDate());
    var years = (otherDate.getFullYear() - birthDate.getFullYear() );

    if (otherDate.getMonth() < birthDate.getMonth() || otherDate.getMonth() == birthDate.getMonth() && otherDate.getDate() < birthDate.getDate()) {
        years--;
    }

    return years;
}
</code>```

Title: javascript - Age calculation

Body:
Get age calculating by current year

calculateExp(birthDate) {
    birthDate = new Date(birthDate);
    var now = new Date();
    otherDate = new Date(now.getFullYear(),now.getMonth(),now.getDate());
    var years = (otherDate.getFullYear() - birthDate.getFullYear() );

    if (otherDate.getMonth() < birthDate.getMonth() || otherDate.getMonth() == birthDate.getMonth() && otherDate.getDate() < birthDate.getDate()) {
        years--;
    }

    return years;
}


问:
Mounting SSHFS for local folder on Mac OS X to edit files on Ubuntu AWS instance
I want to be able to edit files locally using a nice IDE and have the files
on my local machine (~/Code/myproject) get immediately pushed to the Ubuntu machine in the cloud (/home/ubuntu/myproject).

I installed FUSE and SSHFS for my Mac OS X laptop (local) machine.

I have an Ubuntu 16.04 AWS instance on EC2:

```<code>ubuntu@ip-xxxxxx:~$ uname -a
Linux ip-xxxxxx 4.4.0-1017-aws #26-Ubuntu SMP Fri Apr 28 19:48:19 UTC 2017 x86_64 x86_64 x86_64 GNU/Linux
ubuntu@ip-xxxxxxx:~$ lsb_release -a
No LSB modules are available.
Distributor ID: Ubuntu
Description:    Ubuntu 16.04.2 LTS
Release:    16.04
Codename:   xenial
</code>```

I use a .pem file to SSH into that box with the -i flag (haven't set up authorized_keys).

So here's what I do on local machine:

```<code>$ mount  # check for mounted
/dev/disk1 on / (hfs, local, journaled)
devfs on /dev (devfs, local, nobrowse)
map -hosts on /net (autofs, nosuid, automounted, nobrowse)
map auto_home on /home (autofs, automounted, nobrowse)

$ sudo sshfs -o allow_other,defer_permissions,IdentityFile=~/.ssh/aws.pem,loglevel=debug \
    ubuntu@ec2-xxxxxxxx.compute-1.amazonaws.com:/home/ubuntu/myproject \
    /Users/me/Code/myproject
</code>```

It prompts me for local machine password and then I see the following:

```<code>Password:
remote host has disconnected
</code>```

Clearly, something has mounted though:

```<code>$ mount
/dev/disk1 on / (hfs, local, journaled)
devfs on /dev (devfs, local, nobrowse)
map -hosts on /net (autofs, nosuid, automounted, nobrowse)
map auto_home on /home (autofs, automounted, nobrowse)
ubuntu@ec2-xxxxxxx.compute-1.amazonaws.com:/home/ubuntu/myproject on /Users/me/Code/myproject (osxfuse, synchronous)
</code>```

and if I try the same sshfs command as above again (without unmoun-ting) I get a different error:

```<code>mount_osxfuse: mount point /Users/me/Code/myproject is itself on a OSXFUSE volume
</code>```

I can unmount and try again with sudo diskutil umount force /Users/me/Code/myproject/ but I get the same original error when I try again.

I thought perhaps it was a problem with my remote server's SFTP so I located all the sftp-server location on the remote box:

```<code>$ sudo find / | grep sftp-server
...
/usr/lib/sftp-server
/usr/lib/openssh/sftp-server
</code>```

And then I tried with both in my /etc/ssh/sshd_config file with the line:

```<code>#Subsystem sftp /usr/lib/openssh/sftp-server
Subsystem sftp /usr/lib/sftp-server
</code>```

but neither configuration after a reboot seems to work.

I can SFTP in with the following command:

```<code>$ sftp -i ~/.ssh/aws.pem ubuntu@ec2-xxx.compute-1.amazonaws.com
Connected to ec2-xxx.compute-1.amazonaws.com.
sftp>
</code>```

EDIT: running the debug3 loglevel gives relatively the same results:

```<code>$ sudo sshfs -o allow_other,defer_permissions,IdentityFile=~/.ssh/aws.pem,loglevel=debug3 ubuntu@ec2-xxxx.compute-1.amazonaws.com:/home/ubuntu/myproject /Users/me/Code/myproject
sudo: cannot get working directory
The authenticity of host 'ec2-xxx.compute-1.amazonaws.com (xx.xx.xx.xx)' can't be established.
ECDSA key fingerprint is SHA256:xxxxxxxxxxxxxxx.
Are you sure you want to continue connecting (yes/no)? yes
remote host has disconnected
</code>```

Any ideas on what to fix / where the issue could be?

答:
You are running the sshfs under sudo, which makes the difference from running the sftp as your user, becuause the root can not find your authentication keys:

```<code>IdentityFile=~/.ssh/aws.pem
</code>```

expands to your home directory for your user (/home/your-user/.ssh/aws.pem), but to root home for sudo user (/root/.ssh/aws.pem), where the file obviously is not.

Use the full path to the PEM file, such as

```<code>IdentityFile=/home/your-user/.ssh/aws.pem`
</code>```

Body:
I want to be able to edit files locally using a nice IDE and have the files
on my local machine (~/Code/myproject) get immediately pushed to the Ubuntu machine in the cloud (/home/ubuntu/myproject).

I installed FUSE and SSHFS for my Mac OS X laptop (local) machine.

I have an Ubuntu 16.04 AWS instance on EC2:

ubuntu@ip-xxxxxx:~$ uname -a
Linux ip-xxxxxx 4.4.0-1017-aws #26-Ubuntu SMP Fri Apr 28 19:48:19 UTC 2017 x86_64 x86_64 x86_64 GNU/Linux
ubuntu@ip-xxxxxxx:~$ lsb_release -a
No LSB modules are available.
Distributor ID: Ubuntu
Description:    Ubuntu 16.04.2 LTS
Release:    16.04
Codename:   xenial

I use a .pem file to SSH into that box with the -i flag (haven't set up authorized_keys).

So here's what I do on local machine:

$ mount  # check for mounted
/dev/disk1 on / (hfs, local, journaled)
devfs on /dev (devfs, local, nobrowse)
map -hosts on /net (autofs, nosuid, automounted, nobrowse)
map auto_home on /home (autofs, automounted, nobrowse)

$ sudo sshfs -o allow_other,defer_permissions,IdentityFile=~/.ssh/aws.pem,loglevel=debug \
    ubuntu@ec2-xxxxxxxx.compute-1.amazonaws.com:/home/ubuntu/myproject \
    /Users/me/Code/myproject

It prompts me for local machine password and then I see the following:

Password:
remote host has disconnected

Clearly, something has mounted though:

$ mount
/dev/disk1 on / (hfs, local, journaled)
devfs on /dev (devfs, local, nobrowse)
map -hosts on /net (autofs, nosuid, automounted, nobrowse)
map auto_home on /home (autofs, automounted, nobrowse)
ubuntu@ec2-xxxxxxx.compute-1.amazonaws.com:/home/ubuntu/myproject on /Users/me/Code/myproject (osxfuse, synchronous)

and if I try the same sshfs command as above again (without unmoun-ting) I get a different error:

mount_osxfuse: mount point /Users/me/Code/myproject is itself on a OSXFUSE volume

I can unmount and try again with sudo diskutil umount force /Users/me/Code/myproject/ but I get the same original error when I try again.

I thought perhaps it was a problem with my remote server's SFTP so I located all the sftp-server location on the remote box:

$ sudo find / | grep sftp-server
...
/usr/lib/sftp-server
/usr/lib/openssh/sftp-server

And then I tried with both in my /etc/ssh/sshd_config file with the line:

#Subsystem sftp /usr/lib/openssh/sftp-server
Subsystem sftp /usr/lib/sftp-server

but neither configuration after a reboot seems to work.

I can SFTP in with the following command:

$ sftp -i ~/.ssh/aws.pem ubuntu@ec2-xxx.compute-1.amazonaws.com
Connected to ec2-xxx.compute-1.amazonaws.com.
sftp>

EDIT: running the debug3 loglevel gives relatively the same results:

$ sudo sshfs -o allow_other,defer_permissions,IdentityFile=~/.ssh/aws.pem,loglevel=debug3 ubuntu@ec2-xxxx.compute-1.amazonaws.com:/home/ubuntu/myproject /Users/me/Code/myproject
sudo: cannot get working directory
The authenticity of host 'ec2-xxx.compute-1.amazonaws.com (xx.xx.xx.xx)' can't be established.
ECDSA key fingerprint is SHA256:xxxxxxxxxxxxxxx.
Are you sure you want to continue connecting (yes/no)? yes
remote host has disconnected

Any ideas on what to fix / where the issue could be?

Body:
You are running the sshfs under sudo, which makes the difference from running the sftp as your user, becuause the root can not find your authentication keys:

IdentityFile=~/.ssh/aws.pem

expands to your home directory for your user (/home/your-user/.ssh/aws.pem), but to root home for sudo user (/root/.ssh/aws.pem), where the file obviously is not.

Use the full path to the PEM file, such as

IdentityFile=/home/your-user/.ssh/aws.pem`


问:
How can I get revert the changes of git pull?
I had taken VCS pull from Git but aborted the process. There after I messed up with my codes as the stash saved unncessary comments. To skip with the stash comments, I reverted the version. Now I lost some of the codes that I had changed.

Is there a way I can restore my local changes before taking that pull from VCS?

I'm new to Git and really don't have time to go through all the documents and stuff to read the whole process.

答:
your check your local history, there also a copy of changes present
right click on Project -> local history ->Show History -> then a panel will appear then your can figure out what changes your have made. just copy and pasted it then.


问:
Which version of Jenkins 2.x is stable for upgrading from 1.x
Am currently using jenkins 1.642.3 and planning to upgrade to 2.x version. Could anyone please suggest what version of 2.x is stable with all features and where I can get more details.

Thanks
Ashif

答: There are the LTS (Long Term Support) releases, which are considered more stable and receive bug fixes.</p>


问:
android custom layout doesn't align correctly in gridView
I am having an layout issue where i have a custom layout I use in a gridView in which a checkbox is suppose to align at the bottom right corner of an imageView. The preview of the layout shows it looks correct but when it loads into the gridView it moves the check box to the top left of the imageView. I have tried making the image smaller in the gridView and also removing the spacing in in between objects in the gridview, but to no avail.

here is my custom layout for each item of the gridView

```<code><?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">

<ImageView
    android:id="@+id/imgThumb"
    android:layout_width="100dp"
    android:layout_height="100dp"/>

<CheckBox
    android:id="@+id/chkImage"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignEnd="@+id/imgThumb"
    android:layout_alignRight="@+id/imgThumb"
    android:layout_alignBottom="@+id/imgThumb"/>

</RelativeLayout>
</code>```

and here is the gridView layout

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:orientation="vertical">
<GridView
    android:id="@+id/grdImages"
    android:layout_width="match_parent"
    android:layout_height="0dp"
    android:layout_weight="1"
    android:numColumns="3"
    android:verticalSpacing="5dp"
    android:horizontalSpacing="5dp"
    android:columnWidth="90dp"
    android:stretchMode="columnWidth"
    android:gravity="center"/>

<Button
    android:id="@+id/btnSelect"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Select"
    android:layout_marginTop="5dp"/>

</LinearLayout>
</code>```

here is an image of what i would like the item in the gridview to look like, and this is also what the preview shows it will look like Preview

and this is what happens in the actual gridView GridView

答:
Try this Custom Layout.This may help you.</p>

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >

<LinearLayout
    android:id="@+id/lin"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/icons"
    android:orientation="vertical" >

    <ImageView
        android:id="@+id/gridImg"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:layout_marginBottom="@dimen/_5sdp"
        android:layout_marginTop="@dimen/_5sdp"
        android:src="@mipmap/ic_launcher" />

    <CheckBox
    android:id="@+id/chkImage"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="right"/>
</LinearLayout>

</LinearLayout>
</code>```

Body:
I am having an layout issue where i have a custom layout I use in a gridView in which a checkbox is suppose to align at the bottom right corner of an imageView. The preview of the layout shows it looks correct but when it loads into the gridView it moves the check box to the top left of the imageView. I have tried making the image smaller in the gridView and also removing the spacing in in between objects in the gridview, but to no avail.

here is my custom layout for each item of the gridView

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">

<ImageView
    android:id="@+id/imgThumb"
    android:layout_width="100dp"
    android:layout_height="100dp"/>

<CheckBox
    android:id="@+id/chkImage"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignEnd="@+id/imgThumb"
    android:layout_alignRight="@+id/imgThumb"
    android:layout_alignBottom="@+id/imgThumb"/>

</RelativeLayout>

and here is the gridView layout

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:orientation="vertical">
<GridView
    android:id="@+id/grdImages"
    android:layout_width="match_parent"
    android:layout_height="0dp"
    android:layout_weight="1"
    android:numColumns="3"
    android:verticalSpacing="5dp"
    android:horizontalSpacing="5dp"
    android:columnWidth="90dp"
    android:stretchMode="columnWidth"
    android:gravity="center"/>

<Button
    android:id="@+id/btnSelect"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Select"
    android:layout_marginTop="5dp"/>

</LinearLayout>

here is an image of what i would like the item in the gridview to look like, and this is also what the preview shows it will look like Preview

and this is what happens in the actual gridView GridView

Body:
Try this Custom Layout.This may help you.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >

<LinearLayout
    android:id="@+id/lin"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/icons"
    android:orientation="vertical" >

    <ImageView
        android:id="@+id/gridImg"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:layout_marginBottom="@dimen/_5sdp"
        android:layout_marginTop="@dimen/_5sdp"
        android:src="@mipmap/ic_launcher" />

    <CheckBox
    android:id="@+id/chkImage"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="right"/>
</LinearLayout>

</LinearLayout>


问:
Node JS, run same function after it is finished
My applications need to poll every 2 seconds if there are changes. For now i use setInterval, but sometimes myFunction takes longer then 2 seconds to execute and records in the mysql database will be inserted twice. I make use of the async lib in myFunction..

So i need this...

When myFunction is finished

method.myFunction() =>

It needs to run again (but only when it is finished). setInterval with x seconds is not an option. This is because they can run at the same time if the scripts takes longer then  x seconds.

How can i run myFunction again after x seconds, but only when myFunction is done with processing
So in psuedo code it would be this

if method.myFunction == finished
wait 2 seconds
 run method.myFunction again

答: Use callback or, even better, Promises to let next poll execute only when the previous process is completed.</p>


问:
Camel download files
I have maybe a stupid question but how I can to download files from ftp server.
I use the route

.from("ftp:/test@localhost:21/?password=test") .to("file:/d:\\test")

I have the error : can not store null body. Why ? I read several examples Where is my error? Thanks

EDIT

I use the route :

.from("direct:xx")
  .from("ftp://test@localhost:21/?password=test")
  .to("file://d:\inbox");

And I have the error :

org.apache.camel.component.file.GenericFileOperationFailedException: Cannot write null body to file: d:\inbox\xxxxxxx
    at org.apache.camel.component.file.FileOperations.storeFile(FileOperations.java:237)
    at org.apache.camel.component.file.GenericFileProducer.writeFile(GenericFileProducer.java:277)
    at org.apache.camel.component.file.GenericFileProducer.processExchange(GenericFileProducer.java:165)
    at org.apache.camel.component.file.GenericFileProducer.process(GenericFileProducer.java:79)

答:
Add parameter 'allowNullBody=true' to your TO file endpoint

to("file://d:\test?allowNullBody=true")

If you go deep into source code as state in org.apache.camel.component.file.FileOperations.storeFile(FileOperations.java:237), you will see the related GenericFileOperationFailedException happens when

In Body of exchange is null

allowNullBody is set to false

By default, allowNullBody in File producer is 'false' as state in Camel File Component. You need to change it to 'true' to allow storage of empty files.

Title: Camel download files


问:
Update the column with Specific Comma Separated Value
I have created a table which stores the value in comma separated form.
Is there any mechanism which achieve the following result?

I have the column named qty in table and it stores the value in following format:

```<code>Initially Column Contain:-  1,5,8,9,7,10,5
</code>```

Now i want to update the third value which is 8 by 2

```<code>So Final Answer that Column contain is:-  1,5,2,9,7,10,5
</code>```

答:
Let's suppose there is column SampleID in Student table:

value of Name in table is : '1,5,8,9,7,10,5', and you want to replace '8' with '2'

You can use the following query:

```<code>UPDATE dbo.Student
SET [SampleID] = REPLACE([SampleID], '8', '2')
</code>```

You can modify this further to get more accuracy.

Body:
I have created a table which stores the value in comma separated form.
Is there any mechanism which achieve the following result?

I have the column named qty in table and it stores the value in following format:

Initially Column Contain:-  1,5,8,9,7,10,5

Now i want to update the third value which is 8 by 2

So Final Answer that Column contain is:-  1,5,2,9,7,10,5

Body:
Let's suppose there is column SampleID in Student table:

value of Name in table is : '1,5,8,9,7,10,5', and you want to replace '8' with '2'

You can use the following query:

UPDATE dbo.Student
SET [SampleID] = REPLACE([SampleID], '8', '2')

You can modify this further to get more accuracy.


问:
str.maketrans or re.sub for unicode in Python3
The desired task is to get v to be replaced with their u umlaut counterpart.

I could do it as such:

```<code>>>> replacements = {'v':'u', u'v̄':u'ǖ', u'v́':u'ǘ', u'v̌':u'ǚ', u'v̀':u'ǜ'}
>>> s = u'lv́'
>>> for v, u in replacements.items():
...     s = s.replace(v, u)
...
>>> s
'lǘ'
</code>```

But when I tried it with str.maketrans, it throws a ValueError:

```<code>>>> str.maketrans({'v':'u', u'v̄':u'ǖ', u'v́':u'ǘ', u'v̌':u'ǚ', u'v̀':u'ǜ'})
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: string keys in translate table must be of length 1
</code>```

Is it possible to use str.maketrans and str.tranlsate for the unicode?

If not, what would be the an appropriate single regex substitution to achieved the desired output? Or is it not possible too?

答:
I hope this helps, though I'm not sure it's more efficient than your original code. (I assume you're after a performance gain?)

```<code>import re

replacements = {'v': 'u', 'v̀': 'ǜ', 'v̌': 'ǚ', 'v́': 'ǘ', 'v̄': 'ǖ'}
def replace(match):
    return replacements[match.group(0)]

# alternative 1
assert re.sub(r'v̄|v́|v̌|v̀|v', replace, 'lv́vv̌') == 'lǘuǚ'

# alternative 2
assert re.sub(r'v[́̄̌̀]?', replace, 'lv́vv̌') == 'lǘuǚ'
</code>```

Note that in the first alternative, it's important to put the v last in the regular expression. Otherwise it will get matched first (rather than the longer sequences).

Body:
The desired task is to get v to be replaced with their u umlaut counterpart.

I could do it as such:

>>> replacements = {'v':'u', u'v̄':u'ǖ', u'v́':u'ǘ', u'v̌':u'ǚ', u'v̀':u'ǜ'}
>>> s = u'lv́'
>>> for v, u in replacements.items():
...     s = s.replace(v, u)
...
>>> s
'lǘ'

But when I tried it with str.maketrans, it throws a ValueError:

>>> str.maketrans({'v':'u', u'v̄':u'ǖ', u'v́':u'ǘ', u'v̌':u'ǚ', u'v̀':u'ǜ'})
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: string keys in translate table must be of length 1

Is it possible to use str.maketrans and str.tranlsate for the unicode?

If not, what would be the an appropriate single regex substitution to achieved the desired output? Or is it not possible too?

Body:
I hope this helps, though I'm not sure it's more efficient than your original code. (I assume you're after a performance gain?)

import re

replacements = {'v': 'u', 'v̀': 'ǜ', 'v̌': 'ǚ', 'v́': 'ǘ', 'v̄': 'ǖ'}
def replace(match):
    return replacements[match.group(0)]

# alternative 1
assert re.sub(r'v̄|v́|v̌|v̀|v', replace, 'lv́vv̌') == 'lǘuǚ'

# alternative 2
assert re.sub(r'v[́̄̌̀]?', replace, 'lv́vv̌') == 'lǘuǚ'

Note that in the first alternative, it's important to put the v last in the regular expression. Otherwise it will get matched first (rather than the longer sequences).


答:
Actually you should not store the values with comma because this will cause SQL injection attacks and no of reasons behind that.But now to handle use below query:</p>

```<code>     update table_name set coulmn_name=REPLACE('1,5,8,9,7,10,5', '8', '2') where 1
 and conditions;
</code>```

Title: Update the column with Specific Comma Separated Value

Body:
Actually you should not store the values with comma because this will cause SQL injection attacks and no of reasons behind that.But now to handle use below query:

     update table_name set coulmn_name=REPLACE('1,5,8,9,7,10,5', '8', '2') where 1
 and conditions;


答:
Use several string functions can do that:

```<code>update yourtabel
set yourcol =
    concat(
        substring_index(yourcol, ',', 2), -- this will get string without trailing comma before third value
        ',',
        '2', -- the value you want to update to third value
        ',',
        substring_index(
            yourcol,
            ',',
            2 - (length(yourcol) - length(replace(yourcol, ',', '')))
        ) -- this will get string without heading comma after third value
     )
</code>```

Here is a demo in SQLFiddle.

substring_index:https://dev.mysql.com/doc/refman/5.7/en/string-functions.html#function_substring-index

length:https://dev.mysql.com/doc/refman/5.7/en/string-functions.html#function_length

replace:https://dev.mysql.com/doc/refman/5.7/en/string-functions.html#function_replace

Body:
Use several string functions can do that:

update yourtabel
set yourcol =
    concat(
        substring_index(yourcol, ',', 2), -- this will get string without trailing comma before third value
        ',',
        '2', -- the value you want to update to third value
        ',',
        substring_index(
            yourcol,
            ',',
            2 - (length(yourcol) - length(replace(yourcol, ',', '')))
        ) -- this will get string without heading comma after third value
     )

Here is a demo in SQLFiddle.

substring_index:https://dev.mysql.com/doc/refman/5.7/en/string-functions.html#function_substring-index

length:https://dev.mysql.com/doc/refman/5.7/en/string-functions.html#function_length

replace:https://dev.mysql.com/doc/refman/5.7/en/string-functions.html#function_replace


答:
You can use string replace, knowing that this is  not a well formed normalized database.

Your database shall follow the standard normalization patterns in order to obtain a solid relationship between tables where performance, usability and maintenance will be much better. Your table is not even 1NF.

Though this query for now helps, but consider changing your structure.

```<code>   update TBL
       set column = replace(column , '8', '2')
     where your_condition
</code>```

Check this link to get to know more about normalization and their forms : Normalization

Body:
You can use string replace, knowing that this is  not a well formed normalized database.

Your database shall follow the standard normalization patterns in order to obtain a solid relationship between tables where performance, usability and maintenance will be much better. Your table is not even 1NF.

Though this query for now helps, but consider changing your structure.

   update TBL
       set column = replace(column , '8', '2')
     where your_condition

Check this link to get to know more about normalization and their forms : Normalization


问:
Hyperlink Visibility in MVVM and Prism
I have a hyperlink for Logout and it should be hidden on the main page as user has not yet logged in. As soon as user is in, it should be visible.
I have replaced the text in Hyperlink with a textbox and set its content after checking the authentication.

Is there a way, by which we can set Visibilty of Hyperlink instead of using TextBox for its content?

XAML Code :

```<code><TextBlock DockPanel.Dock="Right" TextAlignment="Center" Margin="0,0,0,10" Width="60">
        <Hyperlink Name="lnkLogOut" Focusable="True" FontSize="16" FontStyle="Normal" Command="{Binding LogOutCommand}" Foreground="#AC0000">
            <TextBlock Text="{Binding LogOutText}" />
            <!--Log Out--> // this was the static text before
        </Hyperlink>
        </TextBlock>
</code>```

Model :

```<code>private string _showlogOut = string.Empty;
public string ShowlogOut
{
   get { return _showlogOut; }
   set
   {
       SetProperty(ref _showlogOut, value);
   }
}
</code>```

ViewModel:

```<code>if (_isLoginSuccessful)
{
   ShowlogOut = "Log Out";
//.............other code...............
}
</code>```

答: Either another (bool) property in the view model that you bind to the visibility of your log out hyperlink using BoolToVisibilityConverter or you create an StringEmptyToVisibilityConverter and use the existing property.

Title: Hyperlink Visibility in MVVM and Prism

Body:
I have a hyperlink for Logout and it should be hidden on the main page as user has not yet logged in. As soon as user is in, it should be visible.
I have replaced the text in Hyperlink with a textbox and set its content after checking the authentication.

Is there a way, by which we can set Visibilty of Hyperlink instead of using TextBox for its content?

XAML Code :

<TextBlock DockPanel.Dock="Right" TextAlignment="Center" Margin="0,0,0,10" Width="60">
        <Hyperlink Name="lnkLogOut" Focusable="True" FontSize="16" FontStyle="Normal" Command="{Binding LogOutCommand}" Foreground="#AC0000">
            <TextBlock Text="{Binding LogOutText}" />
             // this was the static text before
        </Hyperlink>
        </TextBlock>

Model :

private string _showlogOut = string.Empty;
public string ShowlogOut
{
   get { return _showlogOut; }
   set
   {
       SetProperty(ref _showlogOut, value);
   }
}

ViewModel:

if (_isLoginSuccessful)
{
   ShowlogOut = "Log Out";
//.............other code...............
}


问:
Running jobs sequentially in Jenkins
Maybe someone could help me. I’d like to run one build at a time in Jenkins for some projects even if there are more builds in the queue. I know that I could limit number of executors but it would affect all projects and this solution doesn’t suit me. I try to use Throttle Concurrent Builds plugin as it’s recommended in this situation but it doesn’t work and I have no idea why.

Before I installed this plugin all builds run correctly. When I have it installed (just installed, I don’t make any changes in configuration) builds go to the queue and never starts (I use 2 executors, both are in idle status all the time). I verified that everything is OK with my node, it’s online, number of executors equals to 2, and it’s set to be utilize as much as possible. There’s no problem with the free space. Increasing number of executors also doesn’t help.

Then I tried to configure Throttle Concurrent Builds (just as an experiment). I went to ‘Configure System’ and add ‘Multi-Project Throttle Category’ with ‘Maximum Total Concurrent Builds’ and ‘Maximum Concurrent Builds Per Node’ set to 1. I went to one of my projects and select ‘Throttle Concurrent Builds’ option. Next, I chose ‘Throttle this project as part of one or more categories’ and checked the check box of the 'Multi-Project Throttle Category' I had just created. As a result when I clicked ‘Build now’ for my project nothing happened. It even didn’t go to the build queue.

Disabling Throttle Concurrent Builds plugin made my projects building again.

I have 2 questions:

Why I couldn’t build any project when I have Throttle Concurrent Builds plugin enabled (builds go to the queue and never start or don’t appear at all)?

Is there any other way to force some jobs running sequentially (also other than changing number of executors)? I have some projects which execute Windows batch command. They must always run separately no matter how many projects I will schedule to build (number of projects and their combination is variable).

Thank you in advance,
Anna

PS. I’ve just started my adventure with Jenkins, so please be understanding:)

答:
The following plugin is for Jenkins and will do what you're looking for:

https://wiki.jenkins-ci.org/display/JENKINS/Multijob+Plugin

Create a 'MultiJob' project, which allows you to define 'phases' for its build.

Many 'phases' can be set up as part of the MultiJob project and each phase "contains" one or more "other" Jenkins jobs. When the MultiJob project is run, the phases will be run sequentially.

Therefore, in order to run N jobs sequentially, add N phases to your MultiJob project, and then add one job to each phase.

Note: There is a setting for each phase that indicates 'Run in parallel' or 'Run sequentially', which I took to mean that it would run the jobs contained in the phase either sequentially or in parallel. However, when I set 'Run sequentially' those jobs still seemed to run in parallel. (I need to investigate this setting further).

Title: Running jobs sequentially in Jenkins


答:
You can change the hash code of an object by wrapping in an Object which inplements hash code your way.  The assumption is that you may want to have a objects sorted a numebr of ways, but not have multiple hashing strategies.

c.f. Trove4j supports hashing strategies for its HashMap and while I use this library often I have only used a custom hashing strategy once I can remember.

Title: Why can we supply a Comparator to TreeSet but not something like Hasher to HashSet?

Body:
In Java 6, my understanding is that you can supply a Comparator to a TreeSet when creating it to override the "natural ordering" of the objects in the set.

Do you have any thoughts why Java doesn't support supplying a "Hasher" that overrides the "natural hashing" of objects in the set as well?

EDIT:
Getting input from you might help me when designing APIs in the future.

Thanks.


答:
You have to put images in different folders as per the image size. it will not generate automatically.

You can not select image for that screen. you can just select different screen sizes android studio will automatically use proper images for that.

For memory issue you can add this line in manifest :

android:hardwareAccelerated="true"

Title: Android Studio - Drawable folders

Body:
I have three general questions regarding android's drawable folders.

Do i put different sized images in each of these folders, or will the images automatically scale themselves? As in, does android decrease the quality of the .bmp files automatically if placed in these folders?

When using the android design preview screen, will the appropriate image from the appropriate drawable folder be shown? If I have to make different sized images for each folder, I want to ensure that what i'm seeing in the design preview matches what is shown on other devices.

Lastly, do the drawable folders, if used, help to avoid the issue with failing to allocate memory for drawables on devices? I have had to scale my images down, and yet my college's phone still cannot allocate enough resources.

I couldn't find answers to these specific questions anywhere, so i'd really appreciate the help with these!


问:
Json mapping to Java object
I have got really weird Json object from a third party service provider and I have issue implementing the same. Below is the json object.

```<code>{
  "signers": [
    "xyz@abc.com"
  ],
  "will_self_sign": true,
  "signatory": "nbc@hgj.com",
  "callback": "79474939202836",
  "comment": "Please sign the document",
  "expire_in_days": 10,
  "display_on_page": "all",
  "sign_coordinates": {
    "xyz@abc.com": {
      "1": [
        {
          "llx": 315,
          "lly": 20,
          "urx": 455,
          "ury": 60
        }
      ]
    },
    "xyz1@abc.com": {
      "1": [
        {
          "llx": 315,
          "lly": 20,
          "urx": 455,
          "ury": 60
        }
      ],
      "2": [
        {
          "llx": 315,
          "lly": 20,
          "urx": 455,
          "ury": 60
        }
      ],

    }
  }
}
</code>```

My Java objects look like below

```<code>@JsonIgnoreProperties(ignoreUnknown = true)
@JsonInclude(JsonInclude.Include.NON_NULL)
public class DigioUpload {

    @JsonProperty(value = "signers", required = true)
    public List<String> signers;

    @JsonProperty(value = "will_self_sign")
    public Boolean willSelfSign;

    @JsonProperty("signatory")
    public String signatory;

    @JsonProperty("callback")
    public String callback;

    @JsonProperty("comment")
    public String comment;

    @JsonProperty(value = "expire_in_days")
    public Integer expireInDays;

    @JsonProperty("display_on_page")
    public String displayOnPage;

    @JsonProperty("sign_coordinates")

    public Map<String, SignDetails> signCoordinates;

}

public class SignDetails {

    public HashMap<String, SignCoordinates> details;

}

public class SignCoordinates {

    public Map<String, List<Coordinates>> coordinates;

}

class Coordinates {

    public Integer llx;
    public Integer lly;
    public Integer urx;
    public Integer ury;
}
</code>```

Unable to map the objects inside dynamic keys like "xyz@abc.com" Any help is appreciated.

Result is as below:

```<code>{"signers":["xyz@abc.com"],"will_self_sign":true,"signatory":"nbc@hgj.com","callback":"79474939202836","comment":"Please sign the document","expire_in_days":10,"display_on_page":"all","sign_coordinates":{"xyz@abc.com":{},"xyz1@abc.com":{}}}
</code>```

答: Nevermind, I got it working by converting this public Map<String, SignDetails> signCoordinates; to public Map<String, Object> signCoordinates;

Title: Json mapping to Java object

Body:
I have got really weird Json object from a third party service provider and I have issue implementing the same. Below is the json object.

{
  "signers": [
    "xyz@abc.com"
  ],
  "will_self_sign": true,
  "signatory": "nbc@hgj.com",
  "callback": "79474939202836",
  "comment": "Please sign the document",
  "expire_in_days": 10,
  "display_on_page": "all",
  "sign_coordinates": {
    "xyz@abc.com": {
      "1": [
        {
          "llx": 315,
          "lly": 20,
          "urx": 455,
          "ury": 60
        }
      ]
    },
    "xyz1@abc.com": {
      "1": [
        {
          "llx": 315,
          "lly": 20,
          "urx": 455,
          "ury": 60
        }
      ],
      "2": [
        {
          "llx": 315,
          "lly": 20,
          "urx": 455,
          "ury": 60
        }
      ],

    }
  }
}

My Java objects look like below

@JsonIgnoreProperties(ignoreUnknown = true)
@JsonInclude(JsonInclude.Include.NON_NULL)
public class DigioUpload {

    @JsonProperty(value = "signers", required = true)
    public List<String> signers;

    @JsonProperty(value = "will_self_sign")
    public Boolean willSelfSign;

    @JsonProperty("signatory")
    public String signatory;

    @JsonProperty("callback")
    public String callback;

    @JsonProperty("comment")
    public String comment;

    @JsonProperty(value = "expire_in_days")
    public Integer expireInDays;

    @JsonProperty("display_on_page")
    public String displayOnPage;

    @JsonProperty("sign_coordinates")

    public Map<String, SignDetails> signCoordinates;

}

public class SignDetails {

    public HashMap<String, SignCoordinates> details;

}

public class SignCoordinates {

    public Map<String, List<Coordinates>> coordinates;

}

class Coordinates {

    public Integer llx;
    public Integer lly;
    public Integer urx;
    public Integer ury;
}

Unable to map the objects inside dynamic keys like "xyz@abc.com" Any help is appreciated.

Result is as below:

{"signers":["xyz@abc.com"],"will_self_sign":true,"signatory":"nbc@hgj.com","callback":"79474939202836","comment":"Please sign the document","expire_in_days":10,"display_on_page":"all","sign_coordinates":{"xyz@abc.com":{},"xyz1@abc.com":{}}}


问:
GA event not getting fired for broken images loaded from css file
I have below GA code in my javascript. window.addEventListener method captures any broken link or images which result in 404 and fires _gaq.push method.
Below code is working fine for all broken links / images but its not firing _gaq call if broken image is from css file.
I have checked in browser my js file is getting loaded before my css file.
below is the sequence of files getting loaded-

-common.js

-common.css

-xyz

-xyz

-ga.js : initiator is common.js but its loaded after common.css

broken_image.gif: causing 404 - not getting detected.

Below is my GA code-

```<code>var _gaq = _gaq || [];
_gaq.push([ '_setAccount', 'UA-34xxxxx-1' ]);
_gaq.push([ '_trackPageview' ]);

(function() {
    var ga = document.createElement('script');
    ga.type = 'text/javascript';
    ga.async = true;
    ga.src = 'https://ssl.google-analytics.com/ga.js';
    var s = document.getElementsByTagName('script')[0];
    s.parentNode.insertBefore(ga, s);
})();

window.addEventListener('error', function(e) {
    _gaq.push([ '_trackEvent', '404 myapp', 'Missing Element',
            e.target && e.target.src ? e.target.src : '', 1 ]);

}, true);
</code>```

url call which is failing-

```<code>.myTool {
    background: url("../images/common/my-tool.jpg") no-repeat 0 0;
}
</code>```

答:
The onerror event requires/supports only certain html tags: https://www.w3schools.com/jsref/event_onerror.asp
https://www.w3schools.com/jsref/event_onerror_media.asp

and occurs from HTML5 Server-Sent Events.

So since the "in CSS" dowloadables don't contain any of the above mentioned the onerror event is never fired

Body:
I have below GA code in my javascript. window.addEventListener method captures any broken link or images which result in 404 and fires _gaq.push method.
Below code is working fine for all broken links / images but its not firing _gaq call if broken image is from css file.
I have checked in browser my js file is getting loaded before my css file.
below is the sequence of files getting loaded-

-common.js

-common.css

-xyz

-xyz

-ga.js : initiator is common.js but its loaded after common.css

broken_image.gif: causing 404 - not getting detected.

Below is my GA code-

var _gaq = _gaq || [];
_gaq.push([ '_setAccount', 'UA-34xxxxx-1' ]);
_gaq.push([ '_trackPageview' ]);

(function() {
    var ga = document.createElement('script');
    ga.type = 'text/javascript';
    ga.async = true;
    ga.src = 'https://ssl.google-analytics.com/ga.js';
    var s = document.getElementsByTagName('script')[0];
    s.parentNode.insertBefore(ga, s);
})();

window.addEventListener('error', function(e) {
    _gaq.push([ '_trackEvent', '404 myapp', 'Missing Element',
            e.target && e.target.src ? e.target.src : '', 1 ]);

}, true);

url call which is failing-

.myTool {
    background: url("../images/common/my-tool.jpg") no-repeat 0 0;
}


问:
Hero animation with an AlertDialog
I'd like to implement a hero animation for an image on my main screen while presenting an AlertDialog widget with the same image in the dialog's content.

I'd like the presentation to appear as in the screenshot below. When I tap the image in the bottom left, I'd like the hero animation and an inset preview of the image along with a transparent overlay that can be tapped to dismiss.

The below code doesn't perform the hero animation.

```<code>class AlertDialogTest extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return new Material(
      child: new InkWell(
        child: new Hero(
          tag: "preview",
          child: new Container(
            alignment: FractionalOffset.bottomLeft,
            child: new Image(
              image: new AssetImage('assets/images/theater.png'),
            ),
          ),
        ),
        onTap: () {
          showDialog(
            context: context,
            child: new AlertDialog(
              content: new Hero(
                tag: "preview",
                child: new Image(
                  image: new AssetImage('assets/images/theater.png'),
                ),
              ),
            ),
          );
        },
      ),
    );
  }
}
</code>```

答:
Hero transitions are only enabled for transitions between two instances of PageRoute. So if you want to make use of the existing Hero system, you should probably use a PageRoute.

Instead of pushing an AlertDialog, you could try a full-screen dialog:

```<code>Navigator.push(context, new MaterialPageRoute(
  fullscreenDialog: true,
  builder: (BuildContext context) {
    return new Scaffold(
      appBar: new AppBar(
        title: new Text('Dialog'),
      ),
      body: new Hero(
        tag: "preview",
        child: new Image(
          image: new AssetImage('assets/images/theater.png'),
        ),
      ),
    );
  }
));
</code>```

If you want a semi-transparent barrier, you can extend PageRoute and make it a more dialog-like.

Here is some code that implements the animation above.

```<code>import 'package:flutter/material.dart';

void main() {
  runApp(new MaterialApp(
    home: new HomePage(),
  ));
}

class HeroDialogRoute<T> extends PageRoute<T> {
  HeroDialogRoute({ this.builder }) : super();

  final WidgetBuilder builder;

  @override
  bool get opaque => false;

  @override
  bool get barrierDismissible => true;

  @override
  Duration get transitionDuration => const Duration(milliseconds: 300);

  @override
  bool get maintainState => true;

  @override
  Color get barrierColor => Colors.black54;

  @override
  Widget buildTransitions(BuildContext context, Animation<double> animation, Animation<double> secondaryAnimation, Widget child) {
    return new FadeTransition(
      opacity: new CurvedAnimation(
        parent: animation,
        curve: Curves.easeOut
      ),
      child: child
    );
  }

  @override
  Widget buildPage(BuildContext context, Animation<double> animation,
    Animation<double> secondaryAnimation) {
    return builder(context);
  }

}

class HomePage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      appBar: new AppBar(
        title: new Text('Hero demo'),
      ),
      body: new Align(
        alignment: FractionalOffset.center,
        child: new Card(
          child: new Hero(
            tag: 'developer-hero',
            child: new Container(
              width: 300.0,
              height: 300.0,
              child: new FlutterLogo(),
            ),
          ),
        ),
      ),
      floatingActionButton: new FloatingActionButton(
        child: new Icon(Icons.developer_mode),
        onPressed: () {
          Navigator.push(
            context,
            new HeroDialogRoute(
              builder: (BuildContext context) {
                return new Center(
                  child: new AlertDialog(
                    title: new Text('You are my hero.'),
                    content: new Container(
                      child: new Hero(
                        tag: 'developer-hero',
                        child: new Container(
                          height: 200.0,
                          width: 200.0,
                          child: new FlutterLogo(),
                        ),
                      ),
                    ),
                    actions: <Widget>[
                      new FlatButton(
                        child: new Text('RAD!'),
                        onPressed: Navigator
                          .of(context)
                          .pop,
                      ),
                    ],
                  ),
                );
              },
            ),
          );
        },
      ),
    );
  }
}
</code>```

Depending on the dialog size and where your hero is located, you might be able to see the original Hero reappear underneath the dialog once the second Hero has finished animating into position. If this bothers you, you could stack two copies the image, with only the top one being a Hero, or you could trigger an animation to hide the original Hero (perhaps using AnimatedCrossFade) until the dialog is closed.

Another option is that you could implement the animation yourself, instead of using the existing Hero system. You'd probably want to read up on the animations documentation and possibly copy bits and pieces of heroes.dart.

Title: Hero animation with an AlertDialog

Body:
I'd like to implement a hero animation for an image on my main screen while presenting an AlertDialog widget with the same image in the dialog's content.

I'd like the presentation to appear as in the screenshot below. When I tap the image in the bottom left, I'd like the hero animation and an inset preview of the image along with a transparent overlay that can be tapped to dismiss.

The below code doesn't perform the hero animation.

class AlertDialogTest extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return new Material(
      child: new InkWell(
        child: new Hero(
          tag: "preview",
          child: new Container(
            alignment: FractionalOffset.bottomLeft,
            child: new Image(
              image: new AssetImage('assets/images/theater.png'),
            ),
          ),
        ),
        onTap: () {
          showDialog(
            context: context,
            child: new AlertDialog(
              content: new Hero(
                tag: "preview",
                child: new Image(
                  image: new AssetImage('assets/images/theater.png'),
                ),
              ),
            ),
          );
        },
      ),
    );
  }
}

Body:
Hero transitions are only enabled for transitions between two instances of PageRoute. So if you want to make use of the existing Hero system, you should probably use a PageRoute.

Instead of pushing an AlertDialog, you could try a full-screen dialog:

Navigator.push(context, new MaterialPageRoute(
  fullscreenDialog: true,
  builder: (BuildContext context) {
    return new Scaffold(
      appBar: new AppBar(
        title: new Text('Dialog'),
      ),
      body: new Hero(
        tag: "preview",
        child: new Image(
          image: new AssetImage('assets/images/theater.png'),
        ),
      ),
    );
  }
));

If you want a semi-transparent barrier, you can extend PageRoute and make it a more dialog-like.

Here is some code that implements the animation above.

import 'package:flutter/material.dart';

void main() {
  runApp(new MaterialApp(
    home: new HomePage(),
  ));
}

class HeroDialogRoute<T> extends PageRoute<T> {
  HeroDialogRoute({ this.builder }) : super();

  final WidgetBuilder builder;

  @override
  bool get opaque => false;

  @override
  bool get barrierDismissible => true;

  @override
  Duration get transitionDuration => const Duration(milliseconds: 300);

  @override
  bool get maintainState => true;

  @override
  Color get barrierColor => Colors.black54;

  @override
  Widget buildTransitions(BuildContext context, Animation<double> animation, Animation<double> secondaryAnimation, Widget child) {
    return new FadeTransition(
      opacity: new CurvedAnimation(
        parent: animation,
        curve: Curves.easeOut
      ),
      child: child
    );
  }

  @override
  Widget buildPage(BuildContext context, Animation<double> animation,
    Animation<double> secondaryAnimation) {
    return builder(context);
  }

}

class HomePage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      appBar: new AppBar(
        title: new Text('Hero demo'),
      ),
      body: new Align(
        alignment: FractionalOffset.center,
        child: new Card(
          child: new Hero(
            tag: 'developer-hero',
            child: new Container(
              width: 300.0,
              height: 300.0,
              child: new FlutterLogo(),
            ),
          ),
        ),
      ),
      floatingActionButton: new FloatingActionButton(
        child: new Icon(Icons.developer_mode),
        onPressed: () {
          Navigator.push(
            context,
            new HeroDialogRoute(
              builder: (BuildContext context) {
                return new Center(
                  child: new AlertDialog(
                    title: new Text('You are my hero.'),
                    content: new Container(
                      child: new Hero(
                        tag: 'developer-hero',
                        child: new Container(
                          height: 200.0,
                          width: 200.0,
                          child: new FlutterLogo(),
                        ),
                      ),
                    ),
                    actions: <Widget>[
                      new FlatButton(
                        child: new Text('RAD!'),
                        onPressed: Navigator
                          .of(context)
                          .pop,
                      ),
                    ],
                  ),
                );
              },
            ),
          );
        },
      ),
    );
  }
}

Depending on the dialog size and where your hero is located, you might be able to see the original Hero reappear underneath the dialog once the second Hero has finished animating into position. If this bothers you, you could stack two copies the image, with only the top one being a Hero, or you could trigger an animation to hide the original Hero (perhaps using AnimatedCrossFade) until the dialog is closed.

Another option is that you could implement the animation yourself, instead of using the existing Hero system. You'd probably want to read up on the animations documentation and possibly copy bits and pieces of heroes.dart.