问:
Change style of material component doesn't work

Hello,
I use Angular 5 and material for my project, i'm trying to change the width of the autocomplete panel, with the exemple, i can now display the options corretly, but i cannot see all the informations for the options, then i modified the css file of the new component, but it doesn't work for the material component, can someone tell me how to do it, please?

This is the html of the component:

```<code><mat-expansion-panel [expanded]="panelOpenState === true">
      <mat-expansion-panel-header>
        <mat-panel-title>
          Critère de recherche
        </mat-panel-title>
        <mat-panel-description>
          Saisir un numéro de procédure
        </mat-panel-description>
      </mat-expansion-panel-header>

      <mat-form-field>
        <input id="autocomplete" type="text" matInput placeholder="number" [ngControl]="inputControl"
                [(ngModel)]="searchValue" [matAutocomplete]="auto" (keyup)="onChange()">
        <mat-autocomplete #auto="matAutocomplete" class="class1">
          <mat-option *ngFor="let procedure of filteredProcedures | async" [value]="procedure.procedureId">
            <span>{{procedure.procedureId}} | </span>
            <small>{{procedure.firstName}} </small>
            <small>{{procedure.lastName}}</small>
            <small>{{procedure.userId}}</small>
          </mat-option>
        </mat-autocomplete>
      </mat-form-field>
      <button class="pull-right btn btn-info" (click)="search()">
        <span matTooltip="Chercher une procédure">
          <i class="fa fa-search"></i> Chercher </span>
      </button>
    </mat-expansion-panel>
</code>```

And the css file:

```<code>.mat-button {
    color: white
}

#autocomplete {
    width: 400px, !important;
}
.class1 {
    width: 400px, !important;
}

.cdk-overlay-pane {
    width: 400px;
}
</code>```

I have tried also to use :host, but it doesn't work.

```<code>:host ::ng-deep mat-autocomplete-panel(class1) {
   width : 400px;
}
</code>```

Can you tell me where is the error, please?

I want to display all/more informations of the options.

In fact, with the css file, the button style is applied correctly. but it doesn't work for the autocomplete panel, why?

Thank you.

答:
Remove the commas from your css (then the width works) and you can't use :host as a pseudo since it's not a pseudo element. Pseudos list here: https://developer.mozilla.org/en-US/docs/Web/CSS/Pseudo-classes</p>

```<code>#autocomplete {
        width: 400px !important;
    }
    .class1 {
        width: 400px !important;
    }
</code>```

Body:
Hello,
I use Angular 5 and material for my project, i'm trying to change the width of the autocomplete panel, with the exemple, i can now display the options corretly, but i cannot see all the informations for the options, then i modified the css file of the new component, but it doesn't work for the material component, can someone tell me how to do it, please?

This is the html of the component:

<mat-expansion-panel [expanded]="panelOpenState === true">
      <mat-expansion-panel-header>
        <mat-panel-title>
          Critère de recherche
        </mat-panel-title>
        <mat-panel-description>
          Saisir un numéro de procédure
        </mat-panel-description>
      </mat-expansion-panel-header>

      <mat-form-field>
        <input id="autocomplete" type="text" matInput placeholder="number" [ngControl]="inputControl"
                [(ngModel)]="searchValue" [matAutocomplete]="auto" (keyup)="onChange()">
        <mat-autocomplete #auto="matAutocomplete" class="class1">
          <mat-option *ngFor="let procedure of filteredProcedures | async" [value]="procedure.procedureId">
            {{procedure.procedureId}} |
            {{procedure.firstName}}
            {{procedure.lastName}}
            {{procedure.userId}}
          </mat-option>
        </mat-autocomplete>
      </mat-form-field>
      <button class="pull-right btn btn-info" (click)="search()">

           Chercher
      </button>
    </mat-expansion-panel>

And the css file:

.mat-button {
    color: white
}

#autocomplete {
    width: 400px, !important;
}
.class1 {
    width: 400px, !important;
}

.cdk-overlay-pane {
    width: 400px;
}

I have tried also to use :host, but it doesn't work.

:host ::ng-deep mat-autocomplete-panel(class1) {
   width : 400px;
}

Can you tell me where is the error, please?

I want to display all/more informations of the options.

In fact, with the css file, the button style is applied correctly. but it doesn't work for the autocomplete panel, why?

Thank you.

Body:
Remove the commas from your css (then the width works) and you can't use :host as a pseudo since it's not a pseudo element. Pseudos list here: https://developer.mozilla.org/en-US/docs/Web/CSS/Pseudo-classes

#autocomplete {
        width: 400px !important;
    }
    .class1 {
        width: 400px !important;
    }


来源: stackexchange

问:
Python GUI quit doesn't work
I am learning how to create a GUI with Pyqt5 and QT-Designer and I have a problem with the Cancel button which should just close the GUI Window.
I used this function QtCore.QCoreApplication.instance() to quit but it does not work.

The whole code:

```<code>from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtGui import QIcon, QFont
from PyQt5.QtWidgets import QToolTip

class Ui_MainWindow(object):
    def setupUi(self, MainWindow):
        MainWindow.setObjectName("MainWindow")
        MainWindow.resize(524, 201)
        self.centralwidget = QtWidgets.QWidget(MainWindow)
        self.centralwidget.setObjectName("centralwidget")
        self.pushButton = QtWidgets.QPushButton(self.centralwidget)
        self.pushButton.setGeometry(QtCore.QRect(320, 50, 151, 51))
        font = QtGui.QFont()
        font.setFamily("Algerian")
        font.setPointSize(12)
        font.setBold(True)
        font.setItalic(True)
        font.setWeight(75)
        self.pushButton.setFont(font)
        self.pushButton.setMouseTracking(False)
        self.pushButton.setAutoFillBackground(False)
        self.pushButton.setObjectName("pushButton")
        self.pushButton_2 = QtWidgets.QPushButton(self.centralwidget)
        self.pushButton_2.setGeometry(QtCore.QRect(30, 50, 161, 51))
        self.pushButton_2.setObjectName("pushButton_2")
        MainWindow.setCentralWidget(self.centralwidget)
        self.menubar = QtWidgets.QMenuBar(MainWindow)
        self.menubar.setGeometry(QtCore.QRect(0, 0, 524, 31))
        self.menubar.setObjectName("menubar")
        MainWindow.setMenuBar(self.menubar)
        self.statusbar = QtWidgets.QStatusBar(MainWindow)
        self.statusbar.setObjectName("statusbar")
        MainWindow.setStatusBar(self.statusbar)
         #####
        self.pushButton.setToolTip('this is just a <u> Button </u>')
        self.pushButton.clicked.connect(self.press)
        QToolTip.setFont(QFont('Times New Roman',14))
        MainWindow.setToolTip('my window!')
        self.pushButton_2.clicked.connect(QtCore.QCoreApplication.instance().quit)

        ###

        self.retranslateUi(MainWindow)
        QtCore.QMetaObject.connectSlotsByName(MainWindow)

    def retranslateUi(self, MainWindow):
        _translate = QtCore.QCoreApplication.translate
        MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))
        self.pushButton.setText(_translate("MainWindow", "Press Here"))
        self.pushButton_2.setText(_translate("MainWindow", "Cancel!"))

    def press(self): #1
        print('Hallo World!')

if __name__ == "__main__":
    import sys
    app = QtWidgets.QApplication(sys.argv)
    MainWindow = QtWidgets.QMainWindow()
    ui = Ui_MainWindow()
    ui.setupUi(MainWindow)
    MainWindow.setWindowTitle('Mein QT Windwow')
    MainWindow.setWindowIcon(QIcon('MeinBild.png'))
    MainWindow.show()
    sys.exit(app.exec_())
</code>```

答:
Your code work fine with me, try to replace:

```<code>self.pushButton_2.clicked.connect(QtCore.QCoreApplication.instance().quit)
</code>```

with:

```<code>self.pushButton_2.clicked.connect(MainWindow.close)
</code>```

Hope that's help, don't forget to close topic if your problem solved.

ContentLicense: CC BY-SA 3.0

Title: Python GUI quit doesn't work

Body:
I am learning how to create a GUI with Pyqt5 and QT-Designer and I have a problem with the Cancel button which should just close the GUI Window.
I used this function QtCore.QCoreApplication.instance() to quit but it does not work.

The whole code:

from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtGui import QIcon, QFont
from PyQt5.QtWidgets import QToolTip

class Ui_MainWindow(object):
    def setupUi(self, MainWindow):
        MainWindow.setObjectName("MainWindow")
        MainWindow.resize(524, 201)
        self.centralwidget = QtWidgets.QWidget(MainWindow)
        self.centralwidget.setObjectName("centralwidget")
        self.pushButton = QtWidgets.QPushButton(self.centralwidget)
        self.pushButton.setGeometry(QtCore.QRect(320, 50, 151, 51))
        font = QtGui.QFont()
        font.setFamily("Algerian")
        font.setPointSize(12)
        font.setBold(True)
        font.setItalic(True)
        font.setWeight(75)
        self.pushButton.setFont(font)
        self.pushButton.setMouseTracking(False)
        self.pushButton.setAutoFillBackground(False)
        self.pushButton.setObjectName("pushButton")
        self.pushButton_2 = QtWidgets.QPushButton(self.centralwidget)
        self.pushButton_2.setGeometry(QtCore.QRect(30, 50, 161, 51))
        self.pushButton_2.setObjectName("pushButton_2")
        MainWindow.setCentralWidget(self.centralwidget)
        self.menubar = QtWidgets.QMenuBar(MainWindow)
        self.menubar.setGeometry(QtCore.QRect(0, 0, 524, 31))
        self.menubar.setObjectName("menubar")
        MainWindow.setMenuBar(self.menubar)
        self.statusbar = QtWidgets.QStatusBar(MainWindow)
        self.statusbar.setObjectName("statusbar")
        MainWindow.setStatusBar(self.statusbar)
         #####
        self.pushButton.setToolTip('this is just a  Button ')
        self.pushButton.clicked.connect(self.press)
        QToolTip.setFont(QFont('Times New Roman',14))
        MainWindow.setToolTip('my window!')
        self.pushButton_2.clicked.connect(QtCore.QCoreApplication.instance().quit)

        ###

        self.retranslateUi(MainWindow)
        QtCore.QMetaObject.connectSlotsByName(MainWindow)

    def retranslateUi(self, MainWindow):
        _translate = QtCore.QCoreApplication.translate
        MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))
        self.pushButton.setText(_translate("MainWindow", "Press Here"))
        self.pushButton_2.setText(_translate("MainWindow", "Cancel!"))

    def press(self): #1
        print('Hallo World!')

if __name__ == "__main__":
    import sys
    app = QtWidgets.QApplication(sys.argv)
    MainWindow = QtWidgets.QMainWindow()
    ui = Ui_MainWindow()
    ui.setupUi(MainWindow)
    MainWindow.setWindowTitle('Mein QT Windwow')
    MainWindow.setWindowIcon(QIcon('MeinBild.png'))
    MainWindow.show()
    sys.exit(app.exec_())

Body:
Your code work fine with me, try to replace:

self.pushButton_2.clicked.connect(QtCore.QCoreApplication.instance().quit)

with:

self.pushButton_2.clicked.connect(MainWindow.close)

Hope that's help, don't forget to close topic if your problem solved.


问:
What is the rationale for limitations on pointer arithmetic or comparison?
In C/C++, addition or subtraction on pointer is defined only if the resulting pointer lies within the original pointed complete object. Moreover, comparison of two pointers can only be performed if the two pointed objects are subobjects of a unique complete object.

What are the reasons of such limitations?

I supposed that segmented memory model (see here §1.2.1) could be one of the reasons but since compilers can actually define a total order on all pointers as demonstrated by this answer, I am doubting this.

答:
The reason is to keep the possibility to generate reasonable code. This applies to systems with a flat memory model as well as to systems with more complex memory models. If you forbid the (not very useful) corner cases like adding or subtracting out of arrays and demanding a total order on pointers between objects you can skip a lot of overhead in the generated code.

The limitations imposed by the standard allows the compiler to make assumptions on pointer arithmetic and use this to improve quality of the code. It covers both computing things statically in the compiler instead of at runtime and choosing which instrutions and addressing modes to use. As an example, consider a program with two pointers p1 and p2. If the compiler can derive that they point to different data objects it can safely assume that any no operation based on following p1 will ever affect the object pointed to by p2. This allows the compiler to reorder loads and stores based on p1 without consider loads and stores based on p2 and the other way around.


问:
Why does the default persist() will store the data in the JVM heap as unserialized objects?
I am learning Apache Spark and trying to clear out the concepts related to caching and persistence of RDDs in Spark.

So according to the documentation of persistence in book "Learning Spark":

To avoid computing an RDD multiple times, we can ask Spark to persist the data.
  When we ask Spark to persist an RDD, the nodes that compute the RDD store their partitions.
  Spark has many levels of persistence to choose from based on what our goals are.

In Scala and Java, the default persist() will
  store the data in the JVM heap as unserialized objects. In Python, we always serialize
  the data that persist stores, so the default is instead stored in the JVM heap as pickled
  objects. When we write data out to disk or off-heap storage, that data is also always
  serialized.

But why is-- the default persist() will
store the data in the JVM heap as unserialized objects.

答: Because there is no serialization and deserialization overhead making it low cost operation and cached data can be load without additional memory. SerDe is expensive and significantly increase overall cost. And keeping serialized and deserialized objects (particularly with standard Java serialization) can double memory usage in the worst case scenario.</p>


问:
Retrieve subString from string in java?
I  am receiving exception message in java, I need exception code of exception message.

Example in below string i need to extract only 535-5.7.8 as output

```<code>535-5.7.8 Username and Password not accepted. Learn more at
535 5.7.8  https://support.google.com/mail/?p=BadCredentials q74sm13073133pfd.134 - gsmtp
</code>```

below is code

```<code>  public class mailDemo {
public static void main(String[] args) {
    Properties props = new Properties();
    props.put("mail.smtp.auth", "true");
    props.put("mail.smtp.starttls.enable", "true");
    props.put("mail.smtp.host","smtp.gmail.com");
    props.put("mail.smtp.port","587");
    //get Session

    Session session = Session.getDefaultInstance(props);
    Transport transport;
    while (true) {
        Scanner scanner=new Scanner(System.in);
        System.out.println("Enter Email Address ");
        String userName=scanner.nextLine();
        System.out.println("Enter password ");
        String passwd=scanner.nextLine();
        try {
            transport = session.getTransport("smtp");
            transport.connect("smtp.gmail.com", userName,
                    passwd);
            transport.close();
            System.out.println("SuccessFull");
            //Authentication success
        } catch (Exception e) {
            System.out.println("Session Failed ");
      //  e.printStackTrace();
        }
    }
}
</code>```

答: Simply use String.split(" ")[0] to recieve the error code.

ContentLicense: CC BY-SA 4.0

Title: Retrieve subString from string in java?

Body:
I  am receiving exception message in java, I need exception code of exception message.

Example in below string i need to extract only 535-5.7.8 as output

535-5.7.8 Username and Password not accepted. Learn more at
535 5.7.8  https://support.google.com/mail/?p=BadCredentials q74sm13073133pfd.134 - gsmtp

below is code

  public class mailDemo {
public static void main(String[] args) {
    Properties props = new Properties();
    props.put("mail.smtp.auth", "true");
    props.put("mail.smtp.starttls.enable", "true");
    props.put("mail.smtp.host","smtp.gmail.com");
    props.put("mail.smtp.port","587");
    //get Session

    Session session = Session.getDefaultInstance(props);
    Transport transport;
    while (true) {
        Scanner scanner=new Scanner(System.in);
        System.out.println("Enter Email Address ");
        String userName=scanner.nextLine();
        System.out.println("Enter password ");
        String passwd=scanner.nextLine();
        try {
            transport = session.getTransport("smtp");
            transport.connect("smtp.gmail.com", userName,
                    passwd);
            transport.close();
            System.out.println("SuccessFull");
            //Authentication success
        } catch (Exception e) {
            System.out.println("Session Failed ");
      //  e.printStackTrace();
        }
    }
}


问:
Unique on Compound Columns
I am trying to ensure that the values in RESTAURANTID and TABLENUMBER, together, are Unique using PowerDesigner (12.5). I've tried creating an alternate key which resulted in the following in my .sql file:

```<code>create table TABLES
(
   TABLEID             int not null,
   RESTAURANTID         int not null,
   TABLENUMBER         int not null,
   primary key (TABLESID),
   key AK_mykey (RESTAURANTID, TABLENUMBER)
);
</code>```

However with this, I can still enter identical values for RESTAURANTID and TABLENUMBER more than once.

I used this http://www.tek-tips.com/viewthread.cfm?qid=403554 to create the alternate key in PowerDesigner.

Would anyone know the proper way to achieve this in PowerDesigner?

Note: This isn't a duplicate of the question posted above as I'm looking for a way to achieve this in PowerDesigner without having to edit the generated sql file afterwards.

答:
In Power Designer:

Open the "TABLES" table properties (right click -> properties)

Keys tab

Insert row (name it to "AK_mykey")

Apply (previously inserted row saved)

On the "AK_mykey" row: right click -> properties

Columns tab

Add columns button

Select the required columns (RESTAURANTID, TABLENUMBER)

OK, OK, OK buttons

+1 You can check the result in table properties preview tab.

```<code>alter table TABLES
   add unique AK_mykey (RESTAURANTID, TABLENUMBER);
</code>```

Title: Unique on Compound Columns

Body:
I am trying to ensure that the values in RESTAURANTID and TABLENUMBER, together, are Unique using PowerDesigner (12.5). I've tried creating an alternate key which resulted in the following in my .sql file:

create table TABLES
(
   TABLEID             int not null,
   RESTAURANTID         int not null,
   TABLENUMBER         int not null,
   primary key (TABLESID),
   key AK_mykey (RESTAURANTID, TABLENUMBER)
);

However with this, I can still enter identical values for RESTAURANTID and TABLENUMBER more than once.

I used this http://www.tek-tips.com/viewthread.cfm?qid=403554 to create the alternate key in PowerDesigner.

Would anyone know the proper way to achieve this in PowerDesigner?

Note: This isn't a duplicate of the question posted above as I'm looking for a way to achieve this in PowerDesigner without having to edit the generated sql file afterwards.

Body:
In Power Designer:

Open the "TABLES" table properties (right click -> properties)

Keys tab

Insert row (name it to "AK_mykey")

Apply (previously inserted row saved)

On the "AK_mykey" row: right click -> properties

Columns tab

Add columns button

Select the required columns (RESTAURANTID, TABLENUMBER)

OK, OK, OK buttons

+1 You can check the result in table properties preview tab.

alter table TABLES
   add unique AK_mykey (RESTAURANTID, TABLENUMBER);


问:
Is it possible using String as PrimaryKey in Android Room
I use uuid in my java backend server. So I need to use that uuid in room android to make sure entities are sync'd properly.
I am aware of Is it possible to apply primary key on the text fields in android database and  text as primarykey in android. I want to create something like this

```<code>@Entity(tableName = CrewColumns.TABLE_NAME)
@TypeConverters(BigDecimalConverter::class)
@JsonIgnoreProperties(ignoreUnknown = true)
class Crew() {
    constructor (uuid: String) : this() {
        this.uuid = uuid;
    }

    /**
     * The unique ID of the item.
     */
    @PrimaryKey
    @ColumnInfo(name = CrewColumns.UUID)
    var uuid: String = ""
    @ColumnInfo(name = CrewColumns.NAME)
    var name: String = ""
}
</code>```

Will it be a problem with Room (DAO etc)? Thank you.

答:
Yes, you can use a String as a @PrimaryKey.

Additionally, I also recommend making use of Kotlin's data class to simplify your entities. For example:

```<code>@Entity
data class Crew(@PrimaryKey val uuid: String, val name: String) {
    // Put any functions or other members not initialized by the constructor here
}
</code>```

Body:
I use uuid in my java backend server. So I need to use that uuid in room android to make sure entities are sync'd properly.
I am aware of Is it possible to apply primary key on the text fields in android database and  text as primarykey in android. I want to create something like this

@Entity(tableName = CrewColumns.TABLE_NAME)
@TypeConverters(BigDecimalConverter::class)
@JsonIgnoreProperties(ignoreUnknown = true)
class Crew() {
    constructor (uuid: String) : this() {
        this.uuid = uuid;
    }

    /**
     * The unique ID of the item.
     */
    @PrimaryKey
    @ColumnInfo(name = CrewColumns.UUID)
    var uuid: String = ""
    @ColumnInfo(name = CrewColumns.NAME)
    var name: String = ""
}

Will it be a problem with Room (DAO etc)? Thank you.

Body:
Yes, you can use a String as a @PrimaryKey.

Additionally, I also recommend making use of Kotlin's data class to simplify your entities. For example:

@Entity
data class Crew(@PrimaryKey val uuid: String, val name: String) {
    // Put any functions or other members not initialized by the constructor here
}


问:
Does JSON 'officially' Support Conversion of Native Types?
In PHP, you can use json_encode to encode an object as a json string.

```<code>$string = json_encode($some_object);
</code>```

However, PHP has the standard slew of datatypes which are not considered objects (ints, strings, etc.)  If you pass in a string to json_encode, this returns a string that contains a javascript statement that could be used to define the string.

In less awkward phrasing, this

```<code>echo json_encode("Hello
world, please don't " . '"' . "misuse quote's for emphasis " .  "or possessive apostrophes' ");
</code>```

will output this (a javascript ready string)

```<code>"Hello \n\tworld, please don't \"misuse quote'sor possessive apostrophes' "
</code>```

Is this behavior part of the JSON specification?  That is, does JSON define or recommend how an implementation should handle conversion of native, non-object, datatypes?  Or even have an opinion on conversion at all?  My reading of the RFC left this as ambiguous, but I'm crap at interpreting these things.

I ask because I'm interested in the likelihood of this behavior disappearing from a future version of the function.  i.e. If it's codified in a specification somewhere, it's less likely to disappear than if it was a one off someone thought to add on during development.

答: JSON doesn't care about native types at all. It is up to the developer of the JSON library or functionality as to how the JSON is translated to and from types that the programming language can use/understand.</p>

ContentLicense: CC BY-SA 2.5

Body:
In PHP, you can use json_encode to encode an object as a json string.

$string = json_encode($some_object);

However, PHP has the standard slew of datatypes which are not considered objects (ints, strings, etc.)  If you pass in a string to json_encode, this returns a string that contains a javascript statement that could be used to define the string.

In less awkward phrasing, this

echo json_encode("Hello
world, please don't " . '"' . "misuse quote's for emphasis " .  "or possessive apostrophes' ");

will output this (a javascript ready string)

"Hello \n\tworld, please don't \"misuse quote'sor possessive apostrophes' "

Is this behavior part of the JSON specification?  That is, does JSON define or recommend how an implementation should handle conversion of native, non-object, datatypes?  Or even have an opinion on conversion at all?  My reading of the RFC left this as ambiguous, but I'm crap at interpreting these things.

I ask because I'm interested in the likelihood of this behavior disappearing from a future version of the function.  i.e. If it's codified in a specification somewhere, it's less likely to disappear than if it was a one off someone thought to add on during development.


问:
Not able to build gradle in android studio project
My project was working fine, but suddenly from this morning it is giving me error like below,

Here in my gradle i have

```<code>compile "com.android.support:appcompat-v7:25.1.1"
compile "com.android.support:design:25.1.1"
compile "com.android.support:support-v4:25.1.1"
compile "com.android.support:recyclerview-v7:25.1.1"
</code>```

still giving me error for 27.0.1. And on click of Install repository and sync it is doing nothing. Not allowing to click that at all. I tried to follow many answers for the gradle build problems but not able to fix this.

答:
If any one might get into the similar problem then this is how i was able to fix this,

Well Some of my dependent library wanted the latest build version support(Might be updated or upgraded their code so gradle fetches the lates build if anyone have written version with 2+ or something like that avoid using that if not necessary and give fix library version).

To solve 27.0.1 this question helped me
and added

```<code>allprojects {
        repositories {
            maven {
                url 'https://maven.google.com/'
                name 'Google'
            }
            jcenter()
        }
}
</code>```

Then was getting error for attr keyboardNavigationCluster So I updated my all modules with

buildToolsVersion       : "26.0.1"

compileVersion          : 26

But after this it was working fine for debug build, but not able to generate signed apk that is bcz my play services need latest version as well to be compatible with 26 so updated it with

playServiceVersion      : "11.0.4"

And after which some of my features were broken as some of the methods are deprecated in 26 version, but now it works like charm.

Body:
My project was working fine, but suddenly from this morning it is giving me error like below,

Here in my gradle i have

compile "com.android.support:appcompat-v7:25.1.1"
compile "com.android.support:design:25.1.1"
compile "com.android.support:support-v4:25.1.1"
compile "com.android.support:recyclerview-v7:25.1.1"

still giving me error for 27.0.1. And on click of Install repository and sync it is doing nothing. Not allowing to click that at all. I tried to follow many answers for the gradle build problems but not able to fix this.

Body:
If any one might get into the similar problem then this is how i was able to fix this,

Well Some of my dependent library wanted the latest build version support(Might be updated or upgraded their code so gradle fetches the lates build if anyone have written version with 2+ or something like that avoid using that if not necessary and give fix library version).

To solve 27.0.1 this question helped me
and added

allprojects {
        repositories {
            maven {
                url 'https://maven.google.com/'
                name 'Google'
            }
            jcenter()
        }
}

Then was getting error for attr keyboardNavigationCluster So I updated my all modules with

buildToolsVersion       : "26.0.1"

compileVersion          : 26

But after this it was working fine for debug build, but not able to generate signed apk that is bcz my play services need latest version as well to be compatible with 26 so updated it with

playServiceVersion      : "11.0.4"

And after which some of my features were broken as some of the methods are deprecated in 26 version, but now it works like charm.


问:
(Oracle) SQL: Column must contain a list of values
I'm trying to figure out an efficient (Oracle) SQL statement that verifies whether a column contains a specific list of values at least once.

One option would be to filter for that list, output all distinct values and then count them. So, something like this:

```<code>SELECT count(*)
FROM (
      SELECT DISTINCT columnname
      FROM table
      WHERE columnname in ('a', 'b', 'c')
     )
;
</code>```

(And then check whether count(*) returns the number 3)

The problem with this is that the DISTINCT statement looks at the whole table, which is very bad performance-wise. All three values of my list could be at the very beginning, so i don't need to look at the millions of other rows. I only want to know that the column contains 'a', 'b' and 'c'.

Does anyone has an idea to solve this efficiently?

Thanks in advance!

答:
It might be more efficient to look for each value individually:

```<code>select (case when exists (select 1 from t where col = 'a') and
                  exists (select 1 from t where col = 'b') and
                  exists (select 1 from t where col = 'c')
             then 1 else 0
        end) as has_all_three_flag
from dual;
</code>```

This will be better particularly with an index on t(col).

Body:
I'm trying to figure out an efficient (Oracle) SQL statement that verifies whether a column contains a specific list of values at least once.

One option would be to filter for that list, output all distinct values and then count them. So, something like this:

SELECT count(*)
FROM (
      SELECT DISTINCT columnname
      FROM table
      WHERE columnname in ('a', 'b', 'c')
     )
;

(And then check whether count(*) returns the number 3)

The problem with this is that the DISTINCT statement looks at the whole table, which is very bad performance-wise. All three values of my list could be at the very beginning, so i don't need to look at the millions of other rows. I only want to know that the column contains 'a', 'b' and 'c'.

Does anyone has an idea to solve this efficiently?

Thanks in advance!

Body:
It might be more efficient to look for each value individually:

select (case when exists (select 1 from t where col = 'a') and
                  exists (select 1 from t where col = 'b') and
                  exists (select 1 from t where col = 'c')
             then 1 else 0
        end) as has_all_three_flag
from dual;

This will be better particularly with an index on t(col).


问:
segmentaion fault (core dumped)
Hi I'm kind of new to C++ and i had to fill a code. The code should read as many values as given in the first input, afterwards it should compute the triple of the sum of these values.

I tried it like this:

```<code>#include <iostream>
#include <vector>
using namespace std;

int main(int argc, char* argv[])
{
    if (argc != 2) {
        return 1;
    }
    int n = atoi(argv[1]);
    vector<double> x;
    for (int i = 0; i < n; i++)
        cin >> x[i];
    double v = 0;
    for (int i = 0; i < n; i++)
        v = 3 * x[i];
    cout << v << endl;
    return 0;
}
</code>```

Unfortunately I end up in a segmentation fault...
Here is the unfinished code

答:
```<code>vector <double> x; //here x has no space for elements
for (int i =0; i <n ; i++) cin >> x[i] ;
</code>```

You do not allocate memory to store elements in vector so x[i] is going out of bounds.Use push_back() instead.

```<code>double dummy;
for (int i =0; i <n ; i++)
{
    cin >> dummy;
    x.push_back(dummy);
}
</code>```

Title: segmentaion fault (core dumped)

Body:
Hi I'm kind of new to C++ and i had to fill a code. The code should read as many values as given in the first input, afterwards it should compute the triple of the sum of these values.

I tried it like this:

#include <iostream>
#include <vector>
using namespace std;

int main(int argc, char* argv[])
{
    if (argc != 2) {
        return 1;
    }
    int n = atoi(argv[1]);
    vector<double> x;
    for (int i = 0; i < n; i++)
        cin >> x[i];
    double v = 0;
    for (int i = 0; i < n; i++)
        v = 3 * x[i];
    cout << v << endl;
    return 0;
}

Unfortunately I end up in a segmentation fault...
Here is the unfinished code

Body:
vector <double> x; //here x has no space for elements
for (int i =0; i <n ; i++) cin >> x[i] ;

You do not allocate memory to store elements in vector so x[i] is going out of bounds.Use push_back() instead.

double dummy;
for (int i =0; i <n ; i++)
{
    cin >> dummy;
    x.push_back(dummy);
}


问:
Why CMake generate Makefile without CMAKE_CXX_FLAGS?
This is my full CMakeLists.txt file:

```<code>set(CMAKE_BUILD_TYPE Release)
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wall -Wextra -Wshadow")

set(PROJECT sample)
project(${PROJECT})

set(HEADERS
    Main.h
)
set(SOURCES
    Main.cpp
)

# Add souce file to project for compile
add_executable (${PROJECT} ${HEADERS} ${SOURCES})

target_link_libraries( ${PROJECT} )
</code>```

But, in Makefile i don't seek substring "-Wall" and other option from CMAKE_CXX_FLAGS.

Why?

答:
The CMAKE_CXX_FLAGS variable is initially set with the project() command. Move the set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} ...") after the project() command.

From CMake Toolchains -
 Languages documenation:

Languages are enabled by the project() command. Language-specific built-in variables, such as _COMPILER" rel="nofollow noreferrer">CMAKE_CXX_COMPILER, _COMPILER_ID" rel="nofollow noreferrer">CMAKE_CXX_COMPILER_ID etc are set by invoking the project() command. If no project command is in the top-level CMakeLists file, one will be implicitly generated. By default the enabled languages are C and CXX.

References

CMake and Make need to be run twice in order to build code successfully

CMake: In which Order are Files parsed (Cache, Toolchain, …)?

Body:
This is my full CMakeLists.txt file:

set(CMAKE_BUILD_TYPE Release)
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wall -Wextra -Wshadow")

set(PROJECT sample)
project(${PROJECT})

set(HEADERS
    Main.h
)
set(SOURCES
    Main.cpp
)

# Add souce file to project for compile
add_executable (${PROJECT} ${HEADERS} ${SOURCES})

target_link_libraries( ${PROJECT} )

But, in Makefile i don't seek substring "-Wall" and other option from CMAKE_CXX_FLAGS.

Why?

Body:
The CMAKE_CXX_FLAGS variable is initially set with the project() command. Move the set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} ...") after the project() command.

From CMake Toolchains -
 Languages documenation:

Languages are enabled by the project() command. Language-specific built-in variables, such as CMAKE_CXX_COMPILER, CMAKE_CXX_COMPILER_ID etc are set by invoking the project() command. If no project command is in the top-level CMakeLists file, one will be implicitly generated. By default the enabled languages are C and CXX.

References

CMake and Make need to be run twice in order to build code successfully

CMake: In which Order are Files parsed (Cache, Toolchain, …)?


问:
SFML graphics Draw Texture in Window- Black Screen
I just tried to write a chess engine, and what is important to me is that I get a nice visual representation of the game. I tried to implement the Code in a Visual Studio project - the problem is that the program only shows me a black screen instead of the texture I loaded.

My Code is the following:

```<code>#include <SFML/Graphics.hpp>
#include <time.h>
using namespace sf;

int main(){

    RenderWindow window(VideoMode(1000, 1000), "MattseChess!");

    Texture t1;
    t1.loadFromFile("images/board.png");
    Sprite s(t1);

    while (window.isOpen())
    {
        Event e;

        while (window.pollEvent(e)) {

            if (e.type == Event::Closed)
                window.close();
    //Draw
            window.clear();
            window.draw(s);
            window.display();
        }
    }

    return 0;
}
</code>```

Do you have any idea of what I did wrong?

答: Make sure to put your drawing code outside your event loop. Otherwise you're only drawing whenever there's some event happening (such as cursor movement).

Body:
I just tried to write a chess engine, and what is important to me is that I get a nice visual representation of the game. I tried to implement the Code in a Visual Studio project - the problem is that the program only shows me a black screen instead of the texture I loaded.

My Code is the following:

#include <SFML/Graphics.hpp>
#include <time.h>
using namespace sf;

int main(){

    RenderWindow window(VideoMode(1000, 1000), "MattseChess!");

    Texture t1;
    t1.loadFromFile("images/board.png");
    Sprite s(t1);

    while (window.isOpen())
    {
        Event e;

        while (window.pollEvent(e)) {

            if (e.type == Event::Closed)
                window.close();
    //Draw
            window.clear();
            window.draw(s);
            window.display();
        }
    }

    return 0;
}

Do you have any idea of what I did wrong?


问:
JS: functions arguments default values
In some languages you can set default values for function's arguments:

```<code>function Foo(arg1 = 50, arg2 = 'default') {
    //...
}
</code>```

How do you do it in JavaScript?

答:
You would have to do it in the function body:

```<code>function Foo(arg1 ,arg2) {
    if( typeof arg1 === 'undefined' )
        arg1 = 50;

    if( typeof arg2 === 'undefined' )
        arg2 = 'default';
    //...
}
</code>```

Another way to test them for undefined or null is like this:

```<code>function Foo(arg1 ,arg2) {
    if( arg1 == undefined )
        arg1 = 50;

    if( arg2 == undefined )
        arg2 = 'default';
    //...
}
</code>```

Some people don't like it because it is possible to override the value of undefined since it is just a global property. As long as it isn't overridden, this would work fine. If the parameters are null or undefined, they'll be set to a default.

Title: JS: functions arguments default values

Body:
In some languages you can set default values for function's arguments:

function Foo(arg1 = 50, arg2 = 'default') {
    //...
}

How do you do it in JavaScript?

Body:
You would have to do it in the function body:

function Foo(arg1 ,arg2) {
    if( typeof arg1 === 'undefined' )
        arg1 = 50;

    if( typeof arg2 === 'undefined' )
        arg2 = 'default';
    //...
}

Another way to test them for undefined or null is like this:

function Foo(arg1 ,arg2) {
    if( arg1 == undefined )
        arg1 = 50;

    if( arg2 == undefined )
        arg2 = 'default';
    //...
}

Some people don't like it because it is possible to override the value of undefined since it is just a global property. As long as it isn't overridden, this would work fine. If the parameters are null or undefined, they'll be set to a default.


问:
Animated Icon for ActionItem
I have been searching everywhere for a proper solution to my problem and I can't seem to find one yet. I have an ActionBar (ActionBarSherlock) with a menu that is inflated from an XML file and that menu contains one item and that one item is shown as an ActionItem.

menu:

```<code><menu xmlns:android="http://schemas.android.com/apk/res/android" >
    <item
        android:id="@+id/menu_refresh"
        android:icon="@drawable/ic_menu_refresh"
        android:showAsAction="ifRoom"
        android:title="Refresh"/>
</menu>
</code>```

activity:

```<code>[...]
  @Override
  public boolean onCreateOptionsMenu(Menu menu) {
    getSupportMenuInflater().inflate(R.menu.mymenu, menu);
    return true;
  }
[...]
</code>```

The ActionItem is displayed with an icon and no text however when a user clicks on the ActionItem, I want the icon to begin animating, more specifically, rotating in place. The icon in question is a refresh icon.

I realize that ActionBar has support for using custom views (Adding an Action View) however this custom view is expanded to cover the entire area of the ActionBar and actually blocks everything except the app icon, which in my case is not what I was looking for.

So my next attempt was to try to use AnimationDrawable and define my animation frame-by-frame, set the drawable as the icon for the menu item, and then in onOptionsItemSelected(MenuItem item) get the icon and begin animating using ((AnimationDrawable)item.getIcon()).start(). This however was unsuccessful. Does anyone know of any way to accomplish this effect?

答:
With support library we can animate icon without custom actionView.

```<code>private AnimationDrawableWrapper drawableWrapper;

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    //inflate menu...

    MenuItem menuItem = menu.findItem(R.id.your_icon);
    Drawable icon = menuItem.getIcon();
    drawableWrapper = new AnimationDrawableWrapper(getResources(), icon);
    menuItem.setIcon(drawableWrapper);
    return true;
}

public void startRotateIconAnimation() {
    ValueAnimator animator = ObjectAnimator.ofInt(0, 360);
    animator.addUpdateListener(animation -> {
        int rotation = (int) animation.getAnimatedValue();
        drawableWrapper.setRotation(rotation);
    });
    animator.start();
}
</code>```

We can't animate drawable directly, so use DrawableWrapper(from android.support.v7 for API<21):

```<code>public class AnimationDrawableWrapper extends DrawableWrapper {

    private float rotation;
    private Rect bounds;

    public AnimationDrawableWrapper(Resources resources, Drawable drawable) {
        super(vectorToBitmapDrawableIfNeeded(resources, drawable));
        bounds = new Rect();
    }

    @Override
    public void draw(Canvas canvas) {
        copyBounds(bounds);
        canvas.save();
        canvas.rotate(rotation, bounds.centerX(), bounds.centerY());
        super.draw(canvas);
        canvas.restore();
    }

    public void setRotation(float degrees) {
        this.rotation = degrees % 360;
        invalidateSelf();
    }

    /**
     * Workaround for issues related to vector drawables rotation and scaling:
     * https://code.google.com/p/android/issues/detail?id=192413
     * https://code.google.com/p/android/issues/detail?id=208453
     */
    private static Drawable vectorToBitmapDrawableIfNeeded(Resources resources, Drawable drawable) {
        if (drawable instanceof VectorDrawable) {
            Bitmap b = Bitmap.createBitmap(drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight(), Bitmap.Config.ARGB_8888);
            Canvas c = new Canvas(b);
            drawable.setBounds(0, 0, c.getWidth(), c.getHeight());
            drawable.draw(c);
            drawable = new BitmapDrawable(resources, b);
        }
        return drawable;
    }
}
</code>```

I took idea for DrawableWrapper from here: https://stackoverflow.com/a/39108111/5541688

Title: Animated Icon for ActionItem

Body:
I have been searching everywhere for a proper solution to my problem and I can't seem to find one yet. I have an ActionBar (ActionBarSherlock) with a menu that is inflated from an XML file and that menu contains one item and that one item is shown as an ActionItem.

menu:

<menu xmlns:android="http://schemas.android.com/apk/res/android" >
    <item
        android:id="@+id/menu_refresh"
        android:icon="@drawable/ic_menu_refresh"
        android:showAsAction="ifRoom"
        android:title="Refresh"/>
</menu>

activity:

[...]
  @Override
  public boolean onCreateOptionsMenu(Menu menu) {
    getSupportMenuInflater().inflate(R.menu.mymenu, menu);
    return true;
  }
[...]

The ActionItem is displayed with an icon and no text however when a user clicks on the ActionItem, I want the icon to begin animating, more specifically, rotating in place. The icon in question is a refresh icon.

I realize that ActionBar has support for using custom views (Adding an Action View) however this custom view is expanded to cover the entire area of the ActionBar and actually blocks everything except the app icon, which in my case is not what I was looking for.

So my next attempt was to try to use AnimationDrawable and define my animation frame-by-frame, set the drawable as the icon for the menu item, and then in onOptionsItemSelected(MenuItem item) get the icon and begin animating using ((AnimationDrawable)item.getIcon()).start(). This however was unsuccessful. Does anyone know of any way to accomplish this effect?

Body:
With support library we can animate icon without custom actionView.

private AnimationDrawableWrapper drawableWrapper;

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    //inflate menu...

    MenuItem menuItem = menu.findItem(R.id.your_icon);
    Drawable icon = menuItem.getIcon();
    drawableWrapper = new AnimationDrawableWrapper(getResources(), icon);
    menuItem.setIcon(drawableWrapper);
    return true;
}

public void startRotateIconAnimation() {
    ValueAnimator animator = ObjectAnimator.ofInt(0, 360);
    animator.addUpdateListener(animation -> {
        int rotation = (int) animation.getAnimatedValue();
        drawableWrapper.setRotation(rotation);
    });
    animator.start();
}

We can't animate drawable directly, so use DrawableWrapper(from android.support.v7 for API<21):

public class AnimationDrawableWrapper extends DrawableWrapper {

    private float rotation;
    private Rect bounds;

    public AnimationDrawableWrapper(Resources resources, Drawable drawable) {
        super(vectorToBitmapDrawableIfNeeded(resources, drawable));
        bounds = new Rect();
    }

    @Override
    public void draw(Canvas canvas) {
        copyBounds(bounds);
        canvas.save();
        canvas.rotate(rotation, bounds.centerX(), bounds.centerY());
        super.draw(canvas);
        canvas.restore();
    }

    public void setRotation(float degrees) {
        this.rotation = degrees % 360;
        invalidateSelf();
    }

    /**
     * Workaround for issues related to vector drawables rotation and scaling:
     * https://code.google.com/p/android/issues/detail?id=192413
     * https://code.google.com/p/android/issues/detail?id=208453
     */
    private static Drawable vectorToBitmapDrawableIfNeeded(Resources resources, Drawable drawable) {
        if (drawable instanceof VectorDrawable) {
            Bitmap b = Bitmap.createBitmap(drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight(), Bitmap.Config.ARGB_8888);
            Canvas c = new Canvas(b);
            drawable.setBounds(0, 0, c.getWidth(), c.getHeight());
            drawable.draw(c);
            drawable = new BitmapDrawable(resources, b);
        }
        return drawable;
    }
}

I took idea for DrawableWrapper from here: https://stackoverflow.com/a/39108111/5541688


问:
Mysql UPDATE JOIN with LOAD DATA INFILE from csv
Here are my tables :

```<code>table1
id_town  town_altitude_min  town_altitude_max
1        NULL               NULL
2        NULL               NULL
...

table2
id_town  id_zipcode
1        1100
2        1100
3        1110
...
</code>```

And my csv :

```<code>id_zipcode;town_altitude_min;town_altitude_max
1100;20;350
1110;243;440
...
</code>```

How can I update the table1 town_altitude_min and town_altitude_max with the data in the csv file ?

Thanks for all help :)

答:
You can try this Query and you can find /tmp directory inside result.csv

```<code>SELECT table2.id_zipcode, table1.town_altitude_min, table1.town_altitude_max INTO OUTFILE '/tmp/result.csv'
FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '"'
LINES TERMINATED BY '\n'
FROM table1
LEFT JOIN table2 ON table2.id_town = table1.id_town
</code>```

I hope it will Helps.

Body:
Here are my tables :

table1
id_town  town_altitude_min  town_altitude_max
1        NULL               NULL
2        NULL               NULL
...

table2
id_town  id_zipcode
1        1100
2        1100
3        1110
...

And my csv :

id_zipcode;town_altitude_min;town_altitude_max
1100;20;350
1110;243;440
...

How can I update the table1 town_altitude_min and town_altitude_max with the data in the csv file ?

Thanks for all help :)

Body:
You can try this Query and you can find /tmp directory inside result.csv

SELECT table2.id_zipcode, table1.town_altitude_min, table1.town_altitude_max INTO OUTFILE '/tmp/result.csv'
FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '"'
LINES TERMINATED BY '\n'
FROM table1
LEFT JOIN table2 ON table2.id_town = table1.id_town

I hope it will Helps.


问:
Join without mapping entities in spring
Am not that good yet with spring. Before now I thought its unprofessional to build an application with spring without using hibernate ORM. Until yesterday when I spent a full day trying to execute a "ManyToOne" mapping. Then I came across some threads where I got to know that u should only use hibernate with spring if only u need ORM in your application. That jdbc template will suffice should you not need ORM. Now my question is do I still need relational mapping to execute JOINS in SPRING using JDBC TEMPLATE(without using hibernate at all)</p>

答:
Spring JdbcTemplate allows you deal with native Java driver to work with databases, writing less code than using it directly. As you have guessed, it is a good option when the performance is more important than build a robust application using the "easy way" that brings you an ORM like Hibernate for example.

Answering your question, if you are talking about the Hibernate annotations like @ManyToOne or similar, the answer is no. Using JdbcTemplate you won't need them. However, you will need to specify in every query what are the required columns of every table and the columns of the related ones that you will want to get.

The following links give you some examples about how to deal with JdbcTemplate and joins:

Example 1

Example 2

More information about JdbcTemplate here

Title: Join without mapping entities in spring


问:
Why "Inline-block" doesn't work properly in this CSS?
Please check the CSS below.

```<code> /*rex is the container of ex,ex2,ex3*/
div.rex{
height:200px;
border:0px;
margin:60px auto;
padding: 0;
vertical-align:top;
}

div.ex{
width:34%;
height:200px;
background-color:#4f443a;
display:inline-block;
margin: 0;
padding: 0;
vertical-align:top;
}

div.ex2{
width:0.5%;
height:200px;
display:inline-block;
margin: 0;
padding: 0;
vertical-align:top;
}

div.ex3{
width:65.5%;
height:200px;
background-color:#7e8547;
display:inline-block;
margin: 0;
padding: 0;
vertical-align:top;
}
</code>```

The result in browser:

What I need:

答:
You can sue comments like that (this looks little better in code):</p>

```<code><div class="rex">
    <div class="ex"><!--
 --></div><div class="ex2"></div><!--
 --><div class="ex3"></div>
</div>
</code>```

Body:
Please check the CSS below.

 /*rex is the container of ex,ex2,ex3*/
div.rex{
height:200px;
border:0px;
margin:60px auto;
padding: 0;
vertical-align:top;
}

div.ex{
width:34%;
height:200px;
background-color:#4f443a;
display:inline-block;
margin: 0;
padding: 0;
vertical-align:top;
}

div.ex2{
width:0.5%;
height:200px;
display:inline-block;
margin: 0;
padding: 0;
vertical-align:top;
}

div.ex3{
width:65.5%;
height:200px;
background-color:#7e8547;
display:inline-block;
margin: 0;
padding: 0;
vertical-align:top;
}

The result in browser:

What I need:

Body:
You can sue comments like that (this looks little better in code):

<div class="rex">
    <div class="ex"><!--
 --></div><div class="ex2"></div><!--
 --><div class="ex3"></div>
</div>


问:
Angular 4 - multiple web applications in a common Web UI
Currently, I have 30 web applications (say) and I am trying to include their interfaces in a common web ui. For example, I have a menu on the left with all applications and once I click one, I can see its UI in a middle frame.

The catch here is that these applications have services that can be standardised i.e. when it comes to permissions, a common service can be built which will be called by all applications.

I am looking into doing this without decomposing each application by components. I would like to have minimal work done on the application side.

Has anyone tried to do this before? Do you have any suggestion on an approach? I was thinking of using Angular.

答:
Currently, I have 30 web applications (say) and I am trying to include
  their interfaces in a common web ui. For example, I have a menu on the
  left with all applications and once I click one, I can see its UI in a
  middle frame.

You can have one module each for each application with its own routing, these modules can be configured for lazy loading.

The catch here is that these applications have services that can be
  standardised i.e. when it comes to permissions, a common service can
  be built which will be called by all applications.

You can provide the common services at root level and provide app specific services in each module.

I am looking into doing this without decomposing each application by
  components. I would like to have minimal work done on the application
  side.

Not sure what you mean by this.


问:
Intel HAXM is required to run this AVD Your CPU does not support VT-x
I know there are a lot of similar questions out there, and I am new to Android world. I get the following errors as I try to run app (Shift + F10)

Intel HAXM is required to run this AVD.

Your CPU does not support VT-x.

Unfortunately, your computer does not support hardware accelerated virtualization.

Here are some of your options:

User a physical device for testing

Develop on a windows/osx computer with an intel processor that supports VT-x and NX

Develop on a linux computer that supports VT-x or SVM

Use an Android Virtual Device Based on an ARM system image
(This is 10x slower that hardware accelerated virtualization)

When I do dxdiag on this computer(windows 10) I get the following. Its long but the system information is as below. I am not able to determine if my PC can be used to develop android application. Can someone please help me? Is virtualization required to develop android apps?

In here it is suggested that we have to enable VT-x in bios, but I dont see anything of that sort in my bios. Is there a way out of my predicament?

System Information

```<code>  Time of this report: 12/29/2016, 15:24:38
         Machine name: DESKTOP-DTQ75J3
           Machine Id: {8D78413A-33B7-4359-BB61-8841CC747D2C}
     Operating System: Windows 10 Enterprise 64-bit (10.0, Build 14393) (14393.rs1_release_inmarket.161208-2252)
             Language: English (Regional Setting: English)
  System Manufacturer: Gigabyte Technology Co., Ltd.
         System Model: G41M-Combo
                 BIOS: Award Modular BIOS v6.00PG
            Processor: Intel(R) Core(TM)2 Duo CPU     E7400  @ 2.80GHz (2 CPUs), ~2.8GHz
               Memory: 4096MB RAM
  Available OS Memory: 4060MB RAM
            Page File: 4199MB used, 2548MB available
          Windows Dir: C:\WINDOWS
      DirectX Version: DirectX 12
  DX Setup Parameters: Not found
     User DPI Setting: Using System DPI
   System DPI Setting: 96 DPI (100 percent)
      DWM DPI Scaling: Disabled
             Miracast: Not Available
</code>```

Microsoft Graphics Hybrid: Not Supported
           DxDiag Version: 10.00.14393.0000 64bit Unicode

答:
According to Android Documentation, to run an emulator the development system's CPU should support one of the following virtualization extensions technologies:

Intel Virtualization Technology (VT, VT-x, vmx)

AMD Virtualization (AMD-V, SVM) -- only supported for Linux

Your CPU is Intel(R) Core(TM)2 Duo CPU E7400, which according to the manufacturer may or may not support Intel Virtualization Technology (VT-x). For example, SLGW3 has VT-x, while the SLB9Y and SLGQ8 do not. Looks like your particular CPU doesn't have VT-x, hence the error.

The workaround is to use an alternative Android Emulator, e.g. Genymotion.

Body:
I know there are a lot of similar questions out there, and I am new to Android world. I get the following errors as I try to run app (Shift + F10)

Intel HAXM is required to run this AVD.

Your CPU does not support VT-x.

Unfortunately, your computer does not support hardware accelerated virtualization.

Here are some of your options:

User a physical device for testing

Develop on a windows/osx computer with an intel processor that supports VT-x and NX

Develop on a linux computer that supports VT-x or SVM

Use an Android Virtual Device Based on an ARM system image
(This is 10x slower that hardware accelerated virtualization)

When I do dxdiag on this computer(windows 10) I get the following. Its long but the system information is as below. I am not able to determine if my PC can be used to develop android application. Can someone please help me? Is virtualization required to develop android apps?

In here it is suggested that we have to enable VT-x in bios, but I dont see anything of that sort in my bios. Is there a way out of my predicament?

System Information

  Time of this report: 12/29/2016, 15:24:38
         Machine name: DESKTOP-DTQ75J3
           Machine Id: {8D78413A-33B7-4359-BB61-8841CC747D2C}
     Operating System: Windows 10 Enterprise 64-bit (10.0, Build 14393) (14393.rs1_release_inmarket.161208-2252)
             Language: English (Regional Setting: English)
  System Manufacturer: Gigabyte Technology Co., Ltd.
         System Model: G41M-Combo
                 BIOS: Award Modular BIOS v6.00PG
            Processor: Intel(R) Core(TM)2 Duo CPU     E7400  @ 2.80GHz (2 CPUs), ~2.8GHz
               Memory: 4096MB RAM
  Available OS Memory: 4060MB RAM
            Page File: 4199MB used, 2548MB available
          Windows Dir: C:\WINDOWS
      DirectX Version: DirectX 12
  DX Setup Parameters: Not found
     User DPI Setting: Using System DPI
   System DPI Setting: 96 DPI (100 percent)
      DWM DPI Scaling: Disabled
             Miracast: Not Available

Microsoft Graphics Hybrid: Not Supported
           DxDiag Version: 10.00.14393.0000 64bit Unicode


问:
Check if the text file was empty
I'd like to know how to check if a text file is empty or not. It means that there is no text even some space, i.e. it was blank</p>

```<code>function keyRemain($path)
{
    $ambil = file_get_contents("data/$path/keywords.txt");
    $kw = explode(",", $ambil);
    if (count($kw) > 1) {
        return false;
    } else {
        return true;
    }
}
</code>```

答:
You have to check the empty function along with trim</p>

```<code>function keyRemain($path)
{
    $ambil = trim(file_get_contents("data/$path/keywords.txt"));
    var_dump($ambil); // check the output here
    if(!empty($ambil)) {
        return false;
    } else {
        return true;
    }
}
</code>```

Title: Check if the text file was empty

Body:
I'd like to know how to check if a text file is empty or not. It means that there is no text even some space, i.e. it was blank

function keyRemain($path)
{
    $ambil = file_get_contents("data/$path/keywords.txt");
    $kw = explode(",", $ambil);
    if (count($kw) > 1) {
        return false;
    } else {
        return true;
    }
}

Body:
You have to check the empty function along with trim

function keyRemain($path)
{
    $ambil = trim(file_get_contents("data/$path/keywords.txt"));
    var_dump($ambil); // check the output here
    if(!empty($ambil)) {
        return false;
    } else {
        return true;
    }
}


问:
Detect event success purchases Unity3D
My game is for IOS platform, I need close window with suggestion buy when user press ok from Success purchase Popup, but how detect this event? or maybe close this window when they press Buy ? How is correct ?

答:
I detected when is success event purchased in this method - </p>

```<code>public PurchaseProcessingResult ProcessPurchase (PurchaseEventArgs args)
    {

        if (String.Equals (args.purchasedProduct.definition.id, kProductIDSubscription, StringComparison.Ordinal)) {
            var builder = ConfigurationBuilder.Instance (StandardPurchasingModule.Instance ());
            var appleConfig = builder.Configure<IAppleConfiguration> ();
            DateTime? data = validate (appleConfig.appReceipt, kProductIDSubscription);
            if (data == null) {
                Debug.Log ("data then purchased");
            } else {
                Debug.Log ("Date: " + data);
            }
            if (data != null) {
                //Here is your code for success subscribed
                isPurchased = true;
            }
            #endif
        }

        else {
            Debug.Log (string.Format ("ProcessPurchase: FAIL. Unrecognized product: '{0}'", args.purchasedProduct.definition.id));
        }
        return PurchaseProcessingResult.Complete;
    }
</code>```

Title: Detect event success purchases Unity3D

Body:
I detected when is success event purchased in this method -

public PurchaseProcessingResult ProcessPurchase (PurchaseEventArgs args)
    {

        if (String.Equals (args.purchasedProduct.definition.id, kProductIDSubscription, StringComparison.Ordinal)) {
            var builder = ConfigurationBuilder.Instance (StandardPurchasingModule.Instance ());
            var appleConfig = builder.Configure<IAppleConfiguration> ();
            DateTime? data = validate (appleConfig.appReceipt, kProductIDSubscription);
            if (data == null) {
                Debug.Log ("data then purchased");
            } else {
                Debug.Log ("Date: " + data);
            }
            if (data != null) {
                //Here is your code for success subscribed
                isPurchased = true;
            }
            #endif
        }

        else {
            Debug.Log (string.Format ("ProcessPurchase: FAIL. Unrecognized product: '{0}'", args.purchasedProduct.definition.id));
        }
        return PurchaseProcessingResult.Complete;
    }


问:
Unable to process csv file through jmeter listeners

I have performed load test using J meter non-GUI mode. Result file was stored in .csv format. Usually we extract this .csv file using a macro utility.

But now when i am trying to process this report using J meter listeners in GUI mode; i am getting error

"Error loading results. see log file".

Not able to figure out reason for this. Any suggestions?

Also from where can i access this log file mentioned in error?

答:
When you are uploading the CSV file place in J Meter folder & then
upload to avoid error. Under Thread Group add CSV data config
option. Her pass the File path in File name option.Also pass the
parameters you want to change in Variables name field.


问:
WP_query no matches on multiple values in array
At the moment I’m breaking my head on a WP_query that doesn’t give me the correct results.

What I am trying to do is make a result based on values stored in an array.

Please see the code below;

```<code>// Array contents:

// $size_array = Array
// (
//   [0] => 7
//   [1] => 4
//   [2] => 2
//  )

// $color_array :
// Array
// (
//   [0] => red
//   [1] => blue
//   [2] => orange
// )

    $args = array(
    'numberposts'   => -1,
    'post_type'     => 'rondreizen',
    'meta_query'    => array(
        'relation'      => 'AND',
        array(
            'key'       => ‘size’,
            'value'     => $size_array,
            'compare'   => 'LIKE'
        ),
        array(
            'key'       => ‘color’,
            'value'     => $color_array,
            'compare'   => 'LIKE'
        )
    ),
    'orderby'           => 'date',
    'order'             => 'DESC'
);

$shoes = new WP_Query( $args );
$posts = $shoes->posts;

foreach($posts as $post) {

}
</code>```

I am trying to get a result that both matches 1 or more of the values. So for example: a shoe in size 4 and in color orange .

At the moment, I only get a result when I have only 1 item in the Arrays. I also tried to us the 'IN' compare method. But that didn't gave me any results either.

I tried to describe the issue as clear as possible. Hope anyone can help me out. :-)

Please let me know if you have any additional questions.

答:
```<code>$args = array(
    'numberposts'   => -1,
    'post_type'     => 'rondreizen',
    'meta_query'    => array(
        'relation'      => 'AND',
        array(
            'key'       => ‘size’,
            'value'     => $size_array
        ),
        array(
            'key'       => ‘color’,
            'operator'  => IN,
            'value'     => $color_array
        )
    ),
    'orderby'           => 'date',
    'order'             => 'DESC'
);

$shoes = new WP_Query( $args );
$posts = $shoes->posts;

foreach($posts as $post) {

}
</code>```

Body:
At the moment I’m breaking my head on a WP_query that doesn’t give me the correct results.

What I am trying to do is make a result based on values stored in an array.

Please see the code below;

// Array contents:

// $size_array = Array
// (
//   [0] => 7
//   [1] => 4
//   [2] => 2
//  )

// $color_array :
// Array
// (
//   [0] => red
//   [1] => blue
//   [2] => orange
// )

    $args = array(
    'numberposts'   => -1,
    'post_type'     => 'rondreizen',
    'meta_query'    => array(
        'relation'      => 'AND',
        array(
            'key'       => ‘size’,
            'value'     => $size_array,
            'compare'   => 'LIKE'
        ),
        array(
            'key'       => ‘color’,
            'value'     => $color_array,
            'compare'   => 'LIKE'
        )
    ),
    'orderby'           => 'date',
    'order'             => 'DESC'
);

$shoes = new WP_Query( $args );
$posts = $shoes->posts;

foreach($posts as $post) {

}

I am trying to get a result that both matches 1 or more of the values. So for example: a shoe in size 4 and in color orange .

At the moment, I only get a result when I have only 1 item in the Arrays. I also tried to us the 'IN' compare method. But that didn't gave me any results either.

I tried to describe the issue as clear as possible. Hope anyone can help me out. :-)

Please let me know if you have any additional questions.


问:
iPhone opengl es alpha-blending. I have black color in edge
I am developing iPhone game. I have the below Source image to draw it to the background. The Source image has alpha 0x00 and gradation around edge and the background's alpha is 0xff. When I draw the source image to the background, I have black color like you could see the Result image. I am using OpenGL ES glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA) method. I have changed every possible arguments, but every time it is not moved.

Why do I have the black color in the edge of the source image? What is the problem? Does not every games in iphone use gradation?

Do I need to make the source image with out gradation?

Does anyone know the solution?

Source image :

Result image :

答:
Does your image have pre-multiplied alpha?  Then you should be using

```<code>glBlendFunc(GL_ONE, GL_ONE_MINUS_SRC_ALPHA);
</code>```

Here is some explanations of what it is.

Note: I rewrote the answer after doing some research.  The article rotoglup mentioned has some insight on what's going on and it makes more sense then my original formula.  I also tried to see what other people are using in their code and it looks like this formula is the most used one.  It's amazing how such a basic thing in 3D graphics as alpha blending can be so controversial and everyone seems to reinvent the wheel and come up with their own solutions.

Body:
Does your image have pre-multiplied alpha?  Then you should be using

glBlendFunc(GL_ONE, GL_ONE_MINUS_SRC_ALPHA);

Here is some explanations of what it is.

Note: I rewrote the answer after doing some research.  The article rotoglup mentioned has some insight on what's going on and it makes more sense then my original formula.  I also tried to see what other people are using in their code and it looks like this formula is the most used one.  It's amazing how such a basic thing in 3D graphics as alpha blending can be so controversial and everyone seems to reinvent the wheel and come up with their own solutions.


问:
Basic program to convert integer to Roman numerals?
I'm trying to write a code that converts a user-inputted integer into its Roman numeral equivalent. What I have so far is:

The point of the generate_all_of_numeral function is so that it creates a string for each specific numeral. For example, generate_all_of_numeral(2400, 'M', 2000) would return the string 'MM'.

I'm struggling with the main program. I start off finding the Roman numeral count for M and saving that into the variable M. Then I subtract by the number of M's times the symbol value to give me the next value to work with for the next largest numeral.

Any nod to the right direction? Right now my code doesn't even print anything.

答:
A KISS version of Manhattan's algorithm, without any "advanced" notion such as OrderedDict, recursion, generators, inner function and break:

```<code>ROMAN = [
    (1000, "M"),
    ( 900, "CM"),
    ( 500, "D"),
    ( 400, "CD"),
    ( 100, "C"),
    (  90, "XC"),
    (  50, "L"),
    (  40, "XL"),
    (  10, "X"),
    (   9, "IX"),
    (   5, "V"),
    (   4, "IV"),
    (   1, "I"),
]

def int_to_roman(number):
    result = ""
    for (arabic, roman) in ROMAN:
        (factor, number) = divmod(number, arabic)
        result += roman * factor
    return result
</code>```

An early exit could be added as soon as number reaches zero, and the string accumulation could be made more pythonic, but my goal here was to produce the requested basic program.

Tested on all integers from 1 to 100000, which ought to be enough for anybody.

EDIT: the slightly more pythonic and faster version I alluded to:

```<code>def int_to_roman(number):
    result = []
    for (arabic, roman) in ROMAN:
        (factor, number) = divmod(number, arabic)
        result.append(roman * factor)
        if number == 0:
            break
    return "".join(result)
</code>```

Body:
A KISS version of Manhattan's algorithm, without any "advanced" notion such as OrderedDict, recursion, generators, inner function and break:

ROMAN = [
    (1000, "M"),
    ( 900, "CM"),
    ( 500, "D"),
    ( 400, "CD"),
    ( 100, "C"),
    (  90, "XC"),
    (  50, "L"),
    (  40, "XL"),
    (  10, "X"),
    (   9, "IX"),
    (   5, "V"),
    (   4, "IV"),
    (   1, "I"),
]

def int_to_roman(number):
    result = ""
    for (arabic, roman) in ROMAN:
        (factor, number) = divmod(number, arabic)
        result += roman * factor
    return result

An early exit could be added as soon as number reaches zero, and the string accumulation could be made more pythonic, but my goal here was to produce the requested basic program.

Tested on all integers from 1 to 100000, which ought to be enough for anybody.

EDIT: the slightly more pythonic and faster version I alluded to:

def int_to_roman(number):
    result = []
    for (arabic, roman) in ROMAN:
        (factor, number) = divmod(number, arabic)
        result.append(roman * factor)
        if number == 0:
            break
    return "".join(result)


问:
Unselect the select all checkbox when one of the other checkboxes is unselected
I iterate through an array to create some checkboxes, like below:

```<code><div class="funnels">
    <label class="checkbox-inline">
    <input type="checkbox" id="selectall"> onClick="selectAll(this)" />All funnels
    </label>
    <?php foreach ($funnels as $funnel) { ?>
        <label class="checkbox-inline">
        <input type="checkbox" name="funnel[]" id ="funnel" value="<?php echo $funnel ?>" ><?php echo $funnel ?>
        </label>
    <?php } ?>
</div>
</code>```

I use the following javascript to select all checkboxes when the All checkbox has been clicked. What I need to do is to unselect the all checkbox once one of the other checkboxes has been unchecked.
Any help would be appreciated.

```<code>  function selectAll(source) {
         checkboxes = document.getElementsByName('funnel[]');
                for(i=0;i<checkboxes.length;i++)
                checkboxes[i].checked = source.checked;
    }
</code>```

答:
You would need to bind change event handler to other checkbox element's also.

I would also recommend you to use unobtrusive event handlers see addEventListener()

document.addEventListener("DOMContentLoaded", function(event) {
  var checkboxes = document.getElementsByName('funnel[]'),
    selectall = document.getElementById('selectall');

  for (var i = 0; i < checkboxes.length; i++) {
    checkboxes[i].addEventListener('change', function() {
      //Conver to array
      var inputList = Array.prototype.slice.call(checkboxes);

      //Set checked  property of selectall input
      selectall.checked = inputList.every(function(c) {
        return c.checked;
      });
    });
  }

  selectall.addEventListener('change', function() {
    for (var i = 0; i < checkboxes.length; i++) {
      checkboxes[i].checked = selectall.checked;
    }
  });

});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><label> <input type="checkbox" id="selectall"  />All funnels</label>
<br><label> <input type="checkbox" name="funnel[]" value="1">1</label>
<br><label> <input type="checkbox" name="funnel[]" value="2">2</label>
<br><label> <input type="checkbox" name="funnel[]" value="2">3</label></code>```

Refrences

DOMContentLoaded

Array.every()

Body:
I iterate through an array to create some checkboxes, like below:

    <input type="checkbox" id="selectall"> onClick="selectAll(this)" />All funnels

    <?php foreach ($funnels as $funnel) { ?>

        <input type="checkbox" name="funnel[]" id ="funnel" value="<?php echo $funnel ?>" ><?php echo $funnel ?>

    <?php } ?>

I use the following javascript to select all checkboxes when the All checkbox has been clicked. What I need to do is to unselect the all checkbox once one of the other checkboxes has been unchecked.
Any help would be appreciated.

  function selectAll(source) {
         checkboxes = document.getElementsByName('funnel[]');
                for(i=0;i<checkboxes.length;i++)
                checkboxes[i].checked = source.checked;
    }

Body:
You would need to bind change event handler to other checkbox element's also.

I would also recommend you to use unobtrusive event handlers see addEventListener()

document.addEventListener("DOMContentLoaded", function(event) {
  var checkboxes = document.getElementsByName('funnel[]'),
    selectall = document.getElementById('selectall');

  for (var i = 0; i < checkboxes.length; i++) {
    checkboxes[i].addEventListener('change', function() {
      //Conver to array
      var inputList = Array.prototype.slice.call(checkboxes);

      //Set checked  property of selectall input
      selectall.checked = inputList.every(function(c) {
        return c.checked;
      });
    });
  }

  selectall.addEventListener('change', function() {
    for (var i = 0; i < checkboxes.length; i++) {
      checkboxes[i].checked = selectall.checked;
    }
  });

});

<label> <input type="checkbox" id="selectall"  />All funnels</label>
<br><label> <input type="checkbox" name="funnel[]" value="1">1</label>
<br><label> <input type="checkbox" name="funnel[]" value="2">2</label>
<br><label> <input type="checkbox" name="funnel[]" value="2">3</label>

Refrences

DOMContentLoaded

Array.every()


问:
Function which edit other functions in PostgreSQL
For example, I want to rename some function and all it's calls from other functions. I would write the function rename_func(schema_name text, old_func_name text, new_func_name text), which must edit other functions.

Where does PostgreSQL store the body of functions (using plpgsql)? I cann't find such column in system tables.

I just can get all functions with

```<code>SELECT f.proname, f.prosrc, f.probin   -- trouble: f.prosrc and f.probin are empty
FROM pg_proc f;
</code>```

but I cann't access to their code.

答:
I just couldn't see content of pg_proc.prosrc, but it was present. May be, cause is that it contains multiple strings (I used pgAdmin III). I used it in queries and it worked.

Moreover, I found that pg_get_functiondef(func.oid) returns DDL script which I can modify and execute later to save changes to function.

Thanks to this answer to other question.

Body:
For example, I want to rename some function and all it's calls from other functions. I would write the function rename_func(schema_name text, old_func_name text, new_func_name text), which must edit other functions.

Where does PostgreSQL store the body of functions (using plpgsql)? I cann't find such column in system tables.

I just can get all functions with

SELECT f.proname, f.prosrc, f.probin   -- trouble: f.prosrc and f.probin are empty
FROM pg_proc f;

but I cann't access to their code.


答:
file_get_contents() will read the whole file while filesize() uses stat() to detirmine the file size. Use filesize(), it should consume less disk I/O.

That's the answer found here, on stack...

You can also (on same link there's this answer):

```<code>clearstatcache();
if(filesize($path_to_your_file)) {
    // your file is not empty
}
</code>```

Title: Check if the text file was empty

Body:
file_get_contents() will read the whole file while filesize() uses stat() to detirmine the file size. Use filesize(), it should consume less disk I/O.

That's the answer found here, on stack...

You can also (on same link there's this answer):

clearstatcache();
if(filesize($path_to_your_file)) {
    // your file is not empty
}


问:
Can I get ido-mode-style completion for searching tags in Emacs?
Is it possible to use ido-mode completion to find definitions in a TAGS file?  I suspect that ido-completing-read is part of the answer.  Here's my non-working code, which shows an unpopulated ido-mode minibuffer:</p>

```<code>(defun ido-choose-from-tags ()
  "Use ido to select tags "
  (interactive)
    (etags-tags-apropos
     (ido-completing-read "Tags: "  nil t)))
</code>```

答:
Kind of inefficient, but how about:</p>

```<code>(defun my-ido-find-tag ()
  "Find a tag using ido"
  (interactive)
  (tags-completion-table)
  (let (tag-names)
    (mapc (lambda (x)
            (unless (integerp x)
              (push (prin1-to-string x t) tag-names)))
          tags-completion-table)
    (find-tag (ido-completing-read "Tag: " tag-names))))
</code>```

OwnerDisplayName: James Sulak

Body:
Is it possible to use ido-mode completion to find definitions in a TAGS file?  I suspect that ido-completing-read is part of the answer.  Here's my non-working code, which shows an unpopulated ido-mode minibuffer:

(defun ido-choose-from-tags ()
  "Use ido to select tags "
  (interactive)
    (etags-tags-apropos
     (ido-completing-read "Tags: "  nil t)))

LastEditorDisplayName: James Sulak

Body:
Kind of inefficient, but how about:

(defun my-ido-find-tag ()
  "Find a tag using ido"
  (interactive)
  (tags-completion-table)
  (let (tag-names)
    (mapc (lambda (x)
            (unless (integerp x)
              (push (prin1-to-string x t) tag-names)))
          tags-completion-table)
    (find-tag (ido-completing-read "Tag: " tag-names))))


问:
Build and Version Numbering for Java Projects (ant, cvs, hudson)
What are current best-practices for systematic build numbering and version number management in Java projects?  Specifically:

How to manage build numbers systematically in a distributed development environment

How to maintain version numbers in source / available to the runtime application

How to properly integrate with source repository

How to more automatically manage version numbers vs. repository tags

How to integrate with continuous build infrastructure

There are quite a number of tools available, and ant (the build system we're using) has a task that will maintain a build number, but it's not clear how to manage this with multiple, concurrent developers using CVS, svn, or similar.

[EDIT]

Several good and helpful partial or specific answers have appeared below, so I'll summarize a few of them.  It sounds to me like there is not really a strong "best practice" on this, rather a collection of overlapping ideas.  Below, find my summaries and some resulting questions that folks might try to answer as follow-ups.  [New to stackoverflow... please provide comments if I'm doing this wrong.]

If you are using SVN, versioning of a specific checkout comes along for the ride.  Build numbering can exploit this to create a unique build number that identifies the specific checkout/revision.  [CVS, which we are using for legacy reasons, doesn't provide quite this level of insight... manual intervention with tags gets you part way there.]

If you are using maven as your build system, there is support for producing a version number from the SCM, as well as a release module for automatically producing releases.  [We can't use maven, for a variety of reasons, but this helps those who can.  [Thanks to marcelo-morales]]

If you are using ant as your build system, the following task description can help produce a Java .properties file capturing build information, which can then be folded into your build in a number of ways.  [We expanded on this idea to include hudson-derived information, thanks marty-lamb].

Ant and maven (and hudson and cruise control) provide easy means for getting build numbers into a .properties file, or into a .txt/.html file.  Is this "safe" enough to keep it from being tampered with intentionally or accidentally?  Is it better to compile it into a "versioning" class at build time?

Assertion: Build numbering should be defined/enacted in a continuous integration system like hudson.  [Thanks to marcelo-morales]  We have taken this suggestion, but it does crack open the release engineering question:  How does a release happen?  Are there multiple buildnumbers in a release?  Is there a meaningful relationship between buildnumbers from differing releases?

Question: What is the objective behind a build number?  Is it used for QA?  How?  Is it used primarily by developers to disambiguate between multiple builds during development, or more for QA to determine what build an end-user got?  If the goal is reproducibility, in theory this is what a release version number should provide -- why doesn't it?  (please answer this as a part of your answers below, it will help illuminate the choices you have made/suggested...)

Question: Is there a place for build numbers in manual builds?  Is this so problematic that EVERYONE should be using a CI solution?

Question: Should build numbers be checked in to the SCM?  If the goal is reliably and unambiguously identifying a particular build, how to cope with a variety of continuous or manual build systems that may crash/restart/etc...

Question: Should a build number be short and sweet (i.e., monotonically increasing integer) so that it's easy to stick into file names for archival, easy to refer to in communication, etc... or should it be long and full of usernames, datestamps, machine names, etc?

Question: Please provide details about how the assignment of build numbers fits into your larger automated release process.  Yes, maven lovers, we know this is done and done, but not all of us have drunk the kool-aid quite yet...

I'd really like to flesh this out into a complete answer, at least for the concrete example of our cvs/ant/hudson setup, so someone could build a complete strategy based on this question.  I'll mark as "The Answer" anyone who can give a soup-to-nuts description for this particular case (including cvs tagging scheme, relevant CI config items, and release procedure that folds the build number into the release such that it's programmatically accessible.)  If you want to ask/answer for another particular configuration (say, svn/maven/cruise control) I'll link to the question from here. --JA

[EDIT 23 Oct 09]
I accepted the top-voted answer because I think it's a reasonable solution, while several of the other answers also include good ideas.  If someone wants to take a crack at synthesizing some of these with marty-lamb's, I'll consider accepting a different one.  The only concern I have with marty-lamb's is that it doesn't produce a reliably serialized build number -- it depends on a local clock at the builder's system to provide unambiguous build numbers, which isn't great.

[Edit Jul 10]

We now include a class like the below.  This allows the version numbers to be compiled into the final executable.  Different forms of the version info are emitted in logging data, long-term archived output products, and used to trace our (sometimes years-later) analysis of output products to a specific build.

```<code>public final class AppVersion
{
   // SVN should fill this out with the latest tag when it's checked out.

   private static final String APP_SVNURL_RAW =
     "$HeadURL: svn+ssh://user@host/svnroot/app/trunk/src/AppVersion.java $";
   private static final String APP_SVN_REVISION_RAW = "$Revision: 325 $";

   private static final Pattern SVNBRANCH_PAT =
     Pattern.compile("(branches|trunk|releases)\\/([\\w\\.\\-]+)\\/.*");
   private static final String APP_SVNTAIL =
     APP_SVNURL_RAW.replaceFirst(".*\\/svnroot\\/app\\/", "");

  private static final String APP_BRANCHTAG;
  private static final String APP_BRANCHTAG_NAME;
  private static final String APP_SVNREVISION =
    APP_SVN_REVISION_RAW.replaceAll("\\$Revision:\\s*","").replaceAll("\\s*\\$", "");

  static {
    Matcher m = SVNBRANCH_PAT.matcher(APP_SVNTAIL);
    if (!m.matches()) {
      APP_BRANCHTAG = "[Broken SVN Info]";
      APP_BRANCHTAG_NAME = "[Broken SVN Info]";
    } else {
      APP_BRANCHTAG = m.group(1);
      if (APP_BRANCHTAG.equals("trunk")) {
        // this isn't necessary in this SO example, but it
        // is since we don't call it trunk in the real case
        APP_BRANCHTAG_NAME = "trunk";
      } else {
        APP_BRANCHTAG_NAME = m.group(2);
      }
    }
  }

  public static String tagOrBranchName()
  { return APP_BRANCHTAG_NAME; }

  /** Answers a formatter String descriptor for the app version.
   * @return version string */
  public static String longStringVersion()
  { return "app "+tagOrBranchName()+" ("+
    tagOrBranchName()+", svn revision="+svnRevision()+")"; }

  public static String shortStringVersion()
  { return tagOrBranchName(); }

  public static String svnVersion()
  { return APP_SVNURL_RAW; }

  public static String svnRevision()
  { return APP_SVNREVISION; }

  public static String svnBranchId()
  { return APP_BRANCHTAG + "/" + APP_BRANCHTAG_NAME; }

  public static final String banner()
  {
    StringBuilder sb = new StringBuilder();
    sb.append("\n----------------------------------------------------------------");
    sb.append("\nApplication -- ");
    sb.append(longStringVersion());
    sb.append("\n----------------------------------------------------------------\n");
    return sb.toString();
  }
}
</code>```

Leave comments if this deserves to become a wiki discussion.

答: You may also want to take a look at BuildNumber Maven plugin and Ant task in one jar found at http://code.google.com/p/codebistro/wiki/BuildNumber. I tried to make it simple and straightforward. It is a very small jar file that only depends on command line Subversion installed.</p>

OwnerDisplayName: andersoj

Body:
What are current best-practices for systematic build numbering and version number management in Java projects?  Specifically:

How to manage build numbers systematically in a distributed development environment

How to maintain version numbers in source / available to the runtime application

How to properly integrate with source repository

How to more automatically manage version numbers vs. repository tags

How to integrate with continuous build infrastructure

There are quite a number of tools available, and ant (the build system we're using) has a task that will maintain a build number, but it's not clear how to manage this with multiple, concurrent developers using CVS, svn, or similar.

[EDIT]

Several good and helpful partial or specific answers have appeared below, so I'll summarize a few of them.  It sounds to me like there is not really a strong "best practice" on this, rather a collection of overlapping ideas.  Below, find my summaries and some resulting questions that folks might try to answer as follow-ups.  [New to stackoverflow... please provide comments if I'm doing this wrong.]

If you are using SVN, versioning of a specific checkout comes along for the ride.  Build numbering can exploit this to create a unique build number that identifies the specific checkout/revision.  [CVS, which we are using for legacy reasons, doesn't provide quite this level of insight... manual intervention with tags gets you part way there.]

If you are using maven as your build system, there is support for producing a version number from the SCM, as well as a release module for automatically producing releases.  [We can't use maven, for a variety of reasons, but this helps those who can.  [Thanks to marcelo-morales]]

If you are using ant as your build system, the following task description can help produce a Java .properties file capturing build information, which can then be folded into your build in a number of ways.  [We expanded on this idea to include hudson-derived information, thanks marty-lamb].

Ant and maven (and hudson and cruise control) provide easy means for getting build numbers into a .properties file, or into a .txt/.html file.  Is this "safe" enough to keep it from being tampered with intentionally or accidentally?  Is it better to compile it into a "versioning" class at build time?

Assertion: Build numbering should be defined/enacted in a continuous integration system like hudson.  [Thanks to marcelo-morales]  We have taken this suggestion, but it does crack open the release engineering question:  How does a release happen?  Are there multiple buildnumbers in a release?  Is there a meaningful relationship between buildnumbers from differing releases?

Question: What is the objective behind a build number?  Is it used for QA?  How?  Is it used primarily by developers to disambiguate between multiple builds during development, or more for QA to determine what build an end-user got?  If the goal is reproducibility, in theory this is what a release version number should provide -- why doesn't it?  (please answer this as a part of your answers below, it will help illuminate the choices you have made/suggested...)

Question: Is there a place for build numbers in manual builds?  Is this so problematic that EVERYONE should be using a CI solution?

Question: Should build numbers be checked in to the SCM?  If the goal is reliably and unambiguously identifying a particular build, how to cope with a variety of continuous or manual build systems that may crash/restart/etc...

Question: Should a build number be short and sweet (i.e., monotonically increasing integer) so that it's easy to stick into file names for archival, easy to refer to in communication, etc... or should it be long and full of usernames, datestamps, machine names, etc?

Question: Please provide details about how the assignment of build numbers fits into your larger automated release process.  Yes, maven lovers, we know this is done and done, but not all of us have drunk the kool-aid quite yet...

I'd really like to flesh this out into a complete answer, at least for the concrete example of our cvs/ant/hudson setup, so someone could build a complete strategy based on this question.  I'll mark as "The Answer" anyone who can give a soup-to-nuts description for this particular case (including cvs tagging scheme, relevant CI config items, and release procedure that folds the build number into the release such that it's programmatically accessible.)  If you want to ask/answer for another particular configuration (say, svn/maven/cruise control) I'll link to the question from here. --JA

[EDIT 23 Oct 09]
I accepted the top-voted answer because I think it's a reasonable solution, while several of the other answers also include good ideas.  If someone wants to take a crack at synthesizing some of these with marty-lamb's, I'll consider accepting a different one.  The only concern I have with marty-lamb's is that it doesn't produce a reliably serialized build number -- it depends on a local clock at the builder's system to provide unambiguous build numbers, which isn't great.

[Edit Jul 10]

We now include a class like the below.  This allows the version numbers to be compiled into the final executable.  Different forms of the version info are emitted in logging data, long-term archived output products, and used to trace our (sometimes years-later) analysis of output products to a specific build.

public final class AppVersion
{
   // SVN should fill this out with the latest tag when it's checked out.

   private static final String APP_SVNURL_RAW =
     "$HeadURL: svn+ssh://user@host/svnroot/app/trunk/src/AppVersion.java $";
   private static final String APP_SVN_REVISION_RAW = "$Revision: 325 $";

   private static final Pattern SVNBRANCH_PAT =
     Pattern.compile("(branches|trunk|releases)\\/([\\w\\.\\-]+)\\/.*");
   private static final String APP_SVNTAIL =
     APP_SVNURL_RAW.replaceFirst(".*\\/svnroot\\/app\\/", "");

  private static final String APP_BRANCHTAG;
  private static final String APP_BRANCHTAG_NAME;
  private static final String APP_SVNREVISION =
    APP_SVN_REVISION_RAW.replaceAll("\\$Revision:\\s*","").replaceAll("\\s*\\$", "");

  static {
    Matcher m = SVNBRANCH_PAT.matcher(APP_SVNTAIL);
    if (!m.matches()) {
      APP_BRANCHTAG = "[Broken SVN Info]";
      APP_BRANCHTAG_NAME = "[Broken SVN Info]";
    } else {
      APP_BRANCHTAG = m.group(1);
      if (APP_BRANCHTAG.equals("trunk")) {
        // this isn't necessary in this SO example, but it
        // is since we don't call it trunk in the real case
        APP_BRANCHTAG_NAME = "trunk";
      } else {
        APP_BRANCHTAG_NAME = m.group(2);
      }
    }
  }

  public static String tagOrBranchName()
  { return APP_BRANCHTAG_NAME; }

  /** Answers a formatter String descriptor for the app version.
   * @return version string */
  public static String longStringVersion()
  { return "app "+tagOrBranchName()+" ("+
    tagOrBranchName()+", svn revision="+svnRevision()+")"; }

  public static String shortStringVersion()
  { return tagOrBranchName(); }

  public static String svnVersion()
  { return APP_SVNURL_RAW; }

  public static String svnRevision()
  { return APP_SVNREVISION; }

  public static String svnBranchId()
  { return APP_BRANCHTAG + "/" + APP_BRANCHTAG_NAME; }

  public static final String banner()
  {
    StringBuilder sb = new StringBuilder();
    sb.append("\n----------------------------------------------------------------");
    sb.append("\nApplication -- ");
    sb.append(longStringVersion());
    sb.append("\n----------------------------------------------------------------\n");
    return sb.toString();
  }
}

Leave comments if this deserves to become a wiki discussion.

LastEditorDisplayName: andersoj


问:
segmentaion fault (core dumped)
Hi I'm kind of new to C++ and i had to fill a code. The code should read as many values as given in the first input, afterwards it should compute the triple of the sum of these values.

I tried it like this:

```<code>#include <iostream>
#include <vector>
using namespace std;

int main(int argc, char* argv[])
{
    if (argc != 2) {
        return 1;
    }
    int n = atoi(argv[1]);
    vector<double> x;
    for (int i = 0; i < n; i++)
        cin >> x[i];
    double v = 0;
    for (int i = 0; i < n; i++)
        v = 3 * x[i];
    cout << v << endl;
    return 0;
}
</code>```

Unfortunately I end up in a segmentation fault...
Here is the unfinished code

答:
```<code>vector <double> x;
for (int i =0; i <n ; i++) cin >> x[i] ;
</code>```

x here has size zero, so you are putting elements in invalid locations of x, which luckily results in a segmentation fault (vector doesn't do any bound checking on operator[], so you are just lucky to have an error).

Either you make the vector big enough:

```<code>vector <double> x(n);
</code>```

Or let it deal with dynamic sizing:

```<code>vector <double> x;
for (int i =0; i <n ; i++) {
    double d;
    cin >> d ;
    x.push_back(d);
}
</code>```

Title: segmentaion fault (core dumped)

Body:
Hi I'm kind of new to C++ and i had to fill a code. The code should read as many values as given in the first input, afterwards it should compute the triple of the sum of these values.

I tried it like this:

#include <iostream>
#include <vector>
using namespace std;

int main(int argc, char* argv[])
{
    if (argc != 2) {
        return 1;
    }
    int n = atoi(argv[1]);
    vector<double> x;
    for (int i = 0; i < n; i++)
        cin >> x[i];
    double v = 0;
    for (int i = 0; i < n; i++)
        v = 3 * x[i];
    cout << v << endl;
    return 0;
}

Unfortunately I end up in a segmentation fault...
Here is the unfinished code

Body:
vector <double> x;
for (int i =0; i <n ; i++) cin >> x[i] ;

x here has size zero, so you are putting elements in invalid locations of x, which luckily results in a segmentation fault (vector doesn't do any bound checking on operator[], so you are just lucky to have an error).

Either you make the vector big enough:

vector <double> x(n);

Or let it deal with dynamic sizing:

vector <double> x;
for (int i =0; i <n ; i++) {
    double d;
    cin >> d ;
    x.push_back(d);
}