问:
How to get setting value from VolumePreference
For the application I am working on, I need to have a preference screen, which has a EditTextPreference, SwitchPreference and a VolumePreference. I am using the VolumePreference as I need a preference that is set with a slider, and VolumePreference was the only one I could find that fit the bill. Here is my Preference XML:

```<code><PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">

<EditTextPreference
    android:capitalize="words"
    android:defaultValue="@string/pref_default_channel"
    android:inputType="number"
    android:key="pref_channel"
    android:selectAllOnFocus="true"
    android:singleLine="true"
    android:title="@string/pref_title_channel"
    android:summary="@string/pref_summary_channel"/>

<SwitchPreference
    android:key="pref_customVol"
    android:title="@string/pref_title_custom_vol"
    android:summary="@string/pref_summary_custom_vol"
    android:defaultValue="false" />

<VolumePreference
    android:name="Volume Preference"
    android:title="Notification Volume"
    android:summary="Set your notification volume, so you will be notified when your Seahorse is almost finished running"
    android:key="pref_notifVolPref"
    android:dependency="pref_customVol"/>
</code>```

I am able to get the value set by the SwitchPreference easily from shared preferences, using the code:

```<code>    SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(this);
    boolean customVol = sharedPref.getBoolean("pref_customVol", false);
</code>```

However, when I try to do the same to get the value from my VolumePreference, it always returns the default value of -1. Here is the code I use to retrieve the volume preference:

```<code>    SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(this);
    int vol = sharedPref.getBoolean("pref_notifVolPref", -1);
</code>```

Am I using the VolumePreference incorrectly? Do I need to create my own custom preference to display a slider preference? Has anyone had this issue before? Thanks

答:
first extends PreferenceActivity

second add this to onCreate()

addPreferencesFromResource(R.xml.account_preferences);

```<code>Preference checkPreference = getPreferenceScreen().findPreference("checkbox_contacts_sync");
Preference.OnPreferenceChangeListener lis1 = new Preference.OnPreferenceChangeListener()
{
    @Override
    public boolean onPreferenceChange(Preference preference, Object o)
    {
        Toast.makeText(SystemManager.getAppContext(), "yess", Toast.LENGTH_LONG).show();
        return true;
    }
};
checkPreference.setOnPreferenceChangeListener(lis1);
</code>```

and add this to layout

```<code><ListView
              android:layout_width="match_parent"
              android:layout_height="match_parent"
              android:visibility="visible"
              android:id="@android:id/list">
    </ListView>
</code>```

Or in main activity use this.

```<code>SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
        SharedPreferences.OnSharedPreferenceChangeListener shListener = new SharedPreferences.OnSharedPreferenceChangeListener()
        {
            @Override
            public void onSharedPreferenceChanged(SharedPreferences sharedPref, String key)
            {
                Assistance.print("change");
                Toast.makeText(SystemManager.getAppContext(),"ohh",Toast.LENGTH_LONG).show();
            }
        };
        sharedPreferences.registerOnSharedPreferenceChangeListener(shListener);
</code>```

Body:
For the application I am working on, I need to have a preference screen, which has a EditTextPreference, SwitchPreference and a VolumePreference. I am using the VolumePreference as I need a preference that is set with a slider, and VolumePreference was the only one I could find that fit the bill. Here is my Preference XML:

<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">

<EditTextPreference
    android:capitalize="words"
    android:defaultValue="@string/pref_default_channel"
    android:inputType="number"
    android:key="pref_channel"
    android:selectAllOnFocus="true"
    android:singleLine="true"
    android:title="@string/pref_title_channel"
    android:summary="@string/pref_summary_channel"/>

<SwitchPreference
    android:key="pref_customVol"
    android:title="@string/pref_title_custom_vol"
    android:summary="@string/pref_summary_custom_vol"
    android:defaultValue="false" />

<VolumePreference
    android:name="Volume Preference"
    android:title="Notification Volume"
    android:summary="Set your notification volume, so you will be notified when your Seahorse is almost finished running"
    android:key="pref_notifVolPref"
    android:dependency="pref_customVol"/>

I am able to get the value set by the SwitchPreference easily from shared preferences, using the code:

    SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(this);
    boolean customVol = sharedPref.getBoolean("pref_customVol", false);

However, when I try to do the same to get the value from my VolumePreference, it always returns the default value of -1. Here is the code I use to retrieve the volume preference:

    SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(this);
    int vol = sharedPref.getBoolean("pref_notifVolPref", -1);

Am I using the VolumePreference incorrectly? Do I need to create my own custom preference to display a slider preference? Has anyone had this issue before? Thanks

Body:
first extends PreferenceActivity

second add this to onCreate()

addPreferencesFromResource(R.xml.account_preferences);

Preference checkPreference = getPreferenceScreen().findPreference("checkbox_contacts_sync");
Preference.OnPreferenceChangeListener lis1 = new Preference.OnPreferenceChangeListener()
{
    @Override
    public boolean onPreferenceChange(Preference preference, Object o)
    {
        Toast.makeText(SystemManager.getAppContext(), "yess", Toast.LENGTH_LONG).show();
        return true;
    }
};
checkPreference.setOnPreferenceChangeListener(lis1);

and add this to layout

<ListView
              android:layout_width="match_parent"
              android:layout_height="match_parent"
              android:visibility="visible"
              android:id="@android:id/list">
    </ListView>

Or in main activity use this.

SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
        SharedPreferences.OnSharedPreferenceChangeListener shListener = new SharedPreferences.OnSharedPreferenceChangeListener()
        {
            @Override
            public void onSharedPreferenceChanged(SharedPreferences sharedPref, String key)
            {
                Assistance.print("change");
                Toast.makeText(SystemManager.getAppContext(),"ohh",Toast.LENGTH_LONG).show();
            }
        };
        sharedPreferences.registerOnSharedPreferenceChangeListener(shListener);


来源: stackexchange

问:
Strip file and write the chunks concurrently to server through TCP shows broken pipe error
My client divides a file into multiple amount of chunks (128mb each), then it will upload the chunks to multiple servers concurrently using goroutines.

However, when I use more than 1 goroutine, I got an error from the my client program.

```<code>write tcp [::1]:49324->[::1]:2001: write: broken pipe
</code>```

And in my server, the error is

```<code>EOF
</code>```

Note that the broken pipe error and EOF error occurs in different chunks. For example, broken pipe error might happen when writing chunk 1 while EOF error might happen when server is receiving chunk 2.

Below is the client code:

```<code>//set maximum no. of goroutine running in the back
maxGoroutines := 3
guard := make(chan struct{}, maxGoroutines)

var sentByte int64

for i:= 0; i < chunkCount; i += 1{
    guard <- struct{}{}

    go func(i int){
        index := i%len(serverList)
        vsConnection, _ := net.Dial("tcp", serverList[index])

        sentByte=0
        file, _ := os.Open(fileName)
        file.Seek(int64(i)*CHUNKSIZE,0) //CHUNKSIZE is 134217728
        for {
            n, _ := file.Read(sendBuffer)

            n2, err2 := vsConnection.Write(sendBuffer[:n])
            if err2 != nil {
                fmt.Println("err2",err2,chunkName)
            }
            if(n2!=65536){ //65536 is size of sendBuffer
                fmt.Println("n2",n2)
            }
            sentByte = sentByte+int64(n)
            if(sentByte == CHUNKSIZE){
                break;
            }
        }
        vsConnection.Close()
        file.Close()
        <-guard
    }(i)
}
</code>```

Below is the server code:

```<code>func main() {
    mapping := cmap.New()
    server, error := net.Listen("tcp", ":2001")
    if error != nil {
        fmt.Println("There was an error starting the server" +    error.Error())
        return
    }

    for {
        connection, error := server.Accept()
        if error != nil {
            fmt.Println("There was am error with the connection" + error.Error())
            return
        }
        //one goroutine per connection
        go ConnectionHandler(connection,mapping)
    }
}

func ConnectionHandler(connection net.Conn, mapping cmap.ConcurrentMap) {
    fmt.Println("Connected")
    //make a buffer to hold data
    var bufferFile bytes.Buffer
    writer := bufio.NewWriter(&bufferFile)

    var receivedBytes int64
    receivedBytes=0
    for {

        if(CHUNKSIZE<=receivedBytes){
            break
        }
        n,err := io.CopyN(writer, connection, BUFFERSIZE)
        receivedBytes += n
        if err != nil {
            fmt.Println("err", err.Error(), fileName)
            break
        }
    }
    mapping.Set(fileName,bufferFile.Bytes())
    connection.Close()

}
</code>```

Big thanks in advance.

答:
In your client sentByte should be a local variable to the sender goroutine. Since you have declared it as a global, there is a race condition in your code. Try the below fix:

```<code>go func(i int){
    index := i%len(serverList)
    vsConnection, _ := net.Dial("tcp", serverList[index])

    sentByte := 0 // make sentByte a local variable, so each goroutine
                  // has its own copy
    file, _ := os.Open(fileName)
    file.Seek(int64(i)*CHUNKSIZE,0) //CHUNKSIZE is 134217728
    for {
        n, _ := file.Read(sendBuffer)
        // ...
</code>```

ContentLicense: CC BY-SA 3.0

Body:
My client divides a file into multiple amount of chunks (128mb each), then it will upload the chunks to multiple servers concurrently using goroutines.

However, when I use more than 1 goroutine, I got an error from the my client program.

write tcp [::1]:49324->[::1]:2001: write: broken pipe

And in my server, the error is

EOF

Note that the broken pipe error and EOF error occurs in different chunks. For example, broken pipe error might happen when writing chunk 1 while EOF error might happen when server is receiving chunk 2.

Below is the client code:

//set maximum no. of goroutine running in the back
maxGoroutines := 3
guard := make(chan struct{}, maxGoroutines)

var sentByte int64

for i:= 0; i < chunkCount; i += 1{
    guard <- struct{}{}

    go func(i int){
        index := i%len(serverList)
        vsConnection, _ := net.Dial("tcp", serverList[index])

        sentByte=0
        file, _ := os.Open(fileName)
        file.Seek(int64(i)*CHUNKSIZE,0) //CHUNKSIZE is 134217728
        for {
            n, _ := file.Read(sendBuffer)

            n2, err2 := vsConnection.Write(sendBuffer[:n])
            if err2 != nil {
                fmt.Println("err2",err2,chunkName)
            }
            if(n2!=65536){ //65536 is size of sendBuffer
                fmt.Println("n2",n2)
            }
            sentByte = sentByte+int64(n)
            if(sentByte == CHUNKSIZE){
                break;
            }
        }
        vsConnection.Close()
        file.Close()
        <-guard
    }(i)
}

Below is the server code:

func main() {
    mapping := cmap.New()
    server, error := net.Listen("tcp", ":2001")
    if error != nil {
        fmt.Println("There was an error starting the server" +    error.Error())
        return
    }

    for {
        connection, error := server.Accept()
        if error != nil {
            fmt.Println("There was am error with the connection" + error.Error())
            return
        }
        //one goroutine per connection
        go ConnectionHandler(connection,mapping)
    }
}

func ConnectionHandler(connection net.Conn, mapping cmap.ConcurrentMap) {
    fmt.Println("Connected")
    //make a buffer to hold data
    var bufferFile bytes.Buffer
    writer := bufio.NewWriter(&bufferFile)

    var receivedBytes int64
    receivedBytes=0
    for {

        if(CHUNKSIZE<=receivedBytes){
            break
        }
        n,err := io.CopyN(writer, connection, BUFFERSIZE)
        receivedBytes += n
        if err != nil {
            fmt.Println("err", err.Error(), fileName)
            break
        }
    }
    mapping.Set(fileName,bufferFile.Bytes())
    connection.Close()

}

Big thanks in advance.

Body:
In your client sentByte should be a local variable to the sender goroutine. Since you have declared it as a global, there is a race condition in your code. Try the below fix:

go func(i int){
    index := i%len(serverList)
    vsConnection, _ := net.Dial("tcp", serverList[index])

    sentByte := 0 // make sentByte a local variable, so each goroutine
                  // has its own copy
    file, _ := os.Open(fileName)
    file.Seek(int64(i)*CHUNKSIZE,0) //CHUNKSIZE is 134217728
    for {
        n, _ := file.Read(sendBuffer)
        // ...


问:
Set order of columns in DynamoDB table of AWS
I'm newbie on Amazon web services cloud. I'm trying to store my data to aws DynamoDB table. I have created table into DynamoDB using python script. Please show below snapshot.

In the table, order of columns doesn't showing according to my requirements. I want to order of columns something like,

```<code>Rpi_ID    RowKey    Name         Time            Date

A100       1        msc       02:07:18 PM       01-04-2017
</code>```

So, how to set columns according to my requirements?

my pythons put item code:

```<code>Table.put_item(
           Item={
            'RowKey': 1,
            'Rpi_ID': 'A100',
            'Name': 'msc',
            'Time': time.strftime("%I:%M:%S %p"),
            'Date': time.strftime("%d-%m-%Y"),
            }
        )
</code>```

Please help me. Thanks in advance.

P.S: Sorry for my poor english.

答:
Amazon DynamoDB is a NoSQL database. It does not use the concept of columns. This is because each item (row) can have different data. The management console attempts to show the data in columns to make it easier for us humans to read.

When retrieving data from DynamoDB, you can request specific keys (eg Name), or you can receive a JSON object from which you can parse the necessary information based on the Key and Value.

Body:
I'm newbie on Amazon web services cloud. I'm trying to store my data to aws DynamoDB table. I have created table into DynamoDB using python script. Please show below snapshot.

In the table, order of columns doesn't showing according to my requirements. I want to order of columns something like,

Rpi_ID    RowKey    Name         Time            Date

A100       1        msc       02:07:18 PM       01-04-2017

So, how to set columns according to my requirements?

my pythons put item code:

Table.put_item(
           Item={
            'RowKey': 1,
            'Rpi_ID': 'A100',
            'Name': 'msc',
            'Time': time.strftime("%I:%M:%S %p"),
            'Date': time.strftime("%d-%m-%Y"),
            }
        )

Please help me. Thanks in advance.

P.S: Sorry for my poor english.


问:
How to divide multiple columns with each other in Pandas
I have a dataframe with 52 columns with sales data (weekly) and 52 columns with the sold quantity. I want to create another 52 colums with the price per soldunit.

The division does not work for some reason. I get

ValueError: Wrong number of items passed 2, placement implies 1

Also, can this be achieved in a more elegant (pandas way) by removing the for loop?

This is what I have...

```<code>#calculate cost per unit
for i in range(0,52):
    cw = i + 1
    i = i + 5
    print cw
    data['Cost' + str(cw)] = data.iloc[:,i:i+1] / sap_data.iloc[:,i+52:i+1+52]
</code>```

Body:
I have a dataframe with 52 columns with sales data (weekly) and 52 columns with the sold quantity. I want to create another 52 colums with the price per soldunit.

The division does not work for some reason. I get

ValueError: Wrong number of items passed 2, placement implies 1

Also, can this be achieved in a more elegant (pandas way) by removing the for loop?

This is what I have...

#calculate cost per unit
for i in range(0,52):
    cw = i + 1
    i = i + 5
    print cw
    data['Cost' + str(cw)] = data.iloc[:,i:i+1] / sap_data.iloc[:,i+52:i+1+52]

Body:
Demo of vectorized Pandas solution:

In [23]: df = pd.DataFrame(np.random.randint(1, 8, (5, 6)),
                           columns=['amt01','amt02','amt03','qty01','qty02','qty03'])

In [24]: df
Out[24]:
   amt01  amt02  amt03  qty01  qty02  qty03
0      2      2      6      2      3      6
1      4      3      7      3      7      5
2      3      2      2      7      7      5
3      3      7      4      4      3      1
4      4      6      2      1      7      3

In [25]: cols = ['new{:02d}'.format(i) for i in np.arange(1, 3+1)]

In [26]: cols
Out[26]: ['new01', 'new02', 'new03']

In [27]: df[cols] = df.filter(regex='^amt').div(df.filter(regex='^qty').values)

In [28]: df
Out[28]:
   amt01  amt02  amt03  qty01  qty02  qty03     new01     new02     new03
0      2      2      6      2      3      6  1.000000  0.666667  1.000000
1      4      3      7      3      7      5  1.333333  0.428571  1.400000
2      3      2      2      7      7      5  0.428571  0.285714  0.400000
3      3      7      4      4      3      1  0.750000  2.333333  4.000000
4      4      6      2      1      7      3  4.000000  0.857143  0.666667


问:
Using Bootstrap 4 media queries in css
I'm importing bootstrap with postcssEasyImport from ./node_modules/bootstrap/dist/css and I was wondering how to use media query variables like @screen-md-min or if that is only available in scss.

答:
@screen-md-min is a mixin, not a variable. Variables in SASS are prefixed with $, i.e. $colorVar, whereas mixins are prefixed with @.
 Mixins do not work in CSS, you need a preprocessor (SASS, LESS etc.) for that.

However, you can still use media queries in CSS, but you have to type them out with specific px widths, meaning that

```<code>@media (min-width: @screen-md-min) {

}
</code>```

in SASS would be

```<code>@media (min-width: 992px) {

}
</code>```

in CSS.

As for variables in CSS, I suggest reading this article on CSS-Tricks: https://css-tricks.com/difference-between-types-of-css-variables/

Hope this helps.

Title: Using Bootstrap 4 media queries in css

Body:
@screen-md-min is a mixin, not a variable. Variables in SASS are prefixed with $, i.e. $colorVar, whereas mixins are prefixed with @.
 Mixins do not work in CSS, you need a preprocessor (SASS, LESS etc.) for that.

However, you can still use media queries in CSS, but you have to type them out with specific px widths, meaning that

@media (min-width: @screen-md-min) {

}

in SASS would be

@media (min-width: 992px) {

}

in CSS.

As for variables in CSS, I suggest reading this article on CSS-Tricks: https://css-tricks.com/difference-between-types-of-css-variables/

Hope this helps.


问:
Android build will not merge manifests from libraries
We have multiple projects, depending on a many Android lib modules.
To avoid duplicated xml tags in the apps manifests, we put the relevant receivers, services and activities in their respective modules.

Till today, we used:

Android Studio: 2.2.1

gradle: 2.1.3

buildToolsVersion: 23.0.3

Today we've updated to:

Android Studio: 2.3

gradle: 2.3.0

buildToolsVersion: 25.0.0

Up until this update, everything worked just fine and the manifests were merged, we had conflicts and we fixed them. As of the update we've done, the manifests will not merge, at all!!

--- Update 1 ---

We've used the Merged Manifest view, and saw that it just doesn't include the manifests in the merge, the only thing it does merge from the modules manifest is the permissions, so for example, if I add a new permission to a modules manifest it would ONLY merge it and not the rest of the elements!

I guarantee there are a lot of stuff to merge!

--- Update 2 ---

It seems that everything outside the application tag it merges into the main manifest, and everything within the application tag, it doesn't.

--- Update 3 ---

Module that doesn't merge:

Gradle:

```<code>apply plugin: 'com.android.library'

android {
    compileSdkVersion 23
    buildToolsVersion '25.0.0'

    defaultConfig {
        minSdkVersion 16
        targetSdkVersion 23
        versionCode 1
        versionName "1.0"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
        debug {
            jniDebuggable true
        }
    }
}

dependencies {
    compile project(path: ':android-infra')
    compile 'com.google.android.gms:play-services-gcm:9.0.0'
    compile project(path: ':engine-core-server')
    compile project(path: ':engine-core-aneeda')
}
</code>```

Manifest:

```<code><manifest package="com.sensiya.voip.managers.gcm"
          xmlns:android="http://schemas.android.com/apk/res/android"
          xmlns:tools="http://schemas.android.com/tools">

    <uses-permission android:name="com.google.android.c2dm.permission.KAKI"/>

    <application
        tools:node="replace">
        <service
            android:enabled="true"
          android:name="com.sensiya.voip.managers.gcm.GcmIntentService"/>

        <receiver          android:name="com.sensiya.voip.managers.gcm.GcmBroadcastReceiver"
            android:permission="com.google.android.c2dm.permission.SEND">
            <intent-filter>
                <action android:name="com.google.android.c2dm.intent.RECEIVE"/>

                <category android:name="com.iamplus.onenumber.device"/>
            </intent-filter>
        </receiver>
    </application>
</manifest>
</code>```

Module that will merge:

Gradle:

```<code>apply plugin: 'com.android.library'

android {
    compileSdkVersion 23
    buildToolsVersion '25.0.0'

    defaultConfig {
        minSdkVersion 16
        targetSdkVersion 23
        versionCode 1
        versionName "1.0"
    }

    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
        debug {
            jniDebuggable true
        }
    }
}

dependencies {
    compile project(path: ':android-infra')
    compile 'com.sensiya:sense-services-client:1.24.2@aar'
    compile project(path: ':engine-core-server')
    compile project(path: ':engine-core-aneeda')
}
</code>```

Manifest:

```<code><manifest package="com.iamplus.android.senseServices"
          xmlns:android="http://schemas.android.com/apk/res/android"
          xmlns:tools="http://schemas.android.com/tools">

    <application
        tools:node="replace">
        <service
            android:name="com.iamplus.senseServices.ContextualEventService"
            android:enabled="true"/>

        <service
            android:name="com.iamplus.senseServices.Serv"
            android:enabled="true"/>

        <service
            android:name="com.iamplus.senseServices.Serv1"
            android:enabled="true"/>
    </application>
</manifest>
</code>```

Any suggestions?

答:
It could be many things.Since  you didn't provide code, I will guess you are using default merge behavior. For more information, see: Merge conflict heuristics

You can use Merged Manifest view to preview the results of your merged manifest and find conflict errors.

In general, merge by default should work. Then just use Merged Manifest view to see how & where you lost values during merging. Using Merge rule markers would help you to manage merge by assigning rules markers.

If there is no merge at all. so it's probably a dependency issue between modules.

Note that dependency order plays a crucial role with modules which have the same priority level, such as libraries.

--- Update 5.April.2017 ---

Here are some useful tips:

Try to update and rebuild other libs as much as you can.

Remove all dependencies and then clean project, then add them again. and
check if you import them properly. that could be done by build the project without issues.

Note that since gradle 2.2.0 assets from modules won't be accessible
in app.

Check you manifest if merge process is not disabled exciplicitly by attribute:
tools:node=”remove" or tools:node="removeAll" or in gradle( see
this Disable Manifest Merger in Android Gradle Build)

Try to create a demo with a module and track merging. and then match
outputs to your projects. This will make it clear that is not
configuration issue but Android Studio 2.3 ( so then re-install fresh
version )

--- Update(2) 5.April.2017 ---

After you had added code, I could see that you are using Attribute

```<code>tools:node="replace"
</code>```

Under application element in your modules (and probably in app's manifest too). I think that is the reason why you didn't get any manifest merged from imported modules merged to your app's manifest. See tools:node="replace" under Node markers.

Replace the lower-priority element completely. That is, if there is a
  matching element in the lower-priority manifest, ignore it and use
  this element exactly as it appears in this manifest.

That means both modules above will never get any thing merged with manifest from:

android-infra

com.sensiya:sense-services-client:1.24.2

engine-core-server

engine-core-aneeda

So get rid of that attribute and clean and rebuild modules. then rebuild whole project.

Body:
We have multiple projects, depending on a many Android lib modules.
To avoid duplicated xml tags in the apps manifests, we put the relevant receivers, services and activities in their respective modules.

Till today, we used:

Android Studio: 2.2.1

gradle: 2.1.3

buildToolsVersion: 23.0.3

Today we've updated to:

Android Studio: 2.3

gradle: 2.3.0

buildToolsVersion: 25.0.0

Up until this update, everything worked just fine and the manifests were merged, we had conflicts and we fixed them. As of the update we've done, the manifests will not merge, at all!!

--- Update 1 ---

We've used the Merged Manifest view, and saw that it just doesn't include the manifests in the merge, the only thing it does merge from the modules manifest is the permissions, so for example, if I add a new permission to a modules manifest it would ONLY merge it and not the rest of the elements!

I guarantee there are a lot of stuff to merge!

--- Update 2 ---

It seems that everything outside the application tag it merges into the main manifest, and everything within the application tag, it doesn't.

--- Update 3 ---

Module that doesn't merge:

Gradle:

apply plugin: 'com.android.library'

android {
    compileSdkVersion 23
    buildToolsVersion '25.0.0'

    defaultConfig {
        minSdkVersion 16
        targetSdkVersion 23
        versionCode 1
        versionName "1.0"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
        debug {
            jniDebuggable true
        }
    }
}

dependencies {
    compile project(path: ':android-infra')
    compile 'com.google.android.gms:play-services-gcm:9.0.0'
    compile project(path: ':engine-core-server')
    compile project(path: ':engine-core-aneeda')
}

Manifest:

<manifest package="com.sensiya.voip.managers.gcm"
          xmlns:android="http://schemas.android.com/apk/res/android"
          xmlns:tools="http://schemas.android.com/tools">

    <uses-permission android:name="com.google.android.c2dm.permission.KAKI"/>

    <application
        tools:node="replace">
        <service
            android:enabled="true"
          android:name="com.sensiya.voip.managers.gcm.GcmIntentService"/>

        <receiver          android:name="com.sensiya.voip.managers.gcm.GcmBroadcastReceiver"
            android:permission="com.google.android.c2dm.permission.SEND">
            <intent-filter>
                <action android:name="com.google.android.c2dm.intent.RECEIVE"/>

                <category android:name="com.iamplus.onenumber.device"/>
            </intent-filter>
        </receiver>
    </application>
</manifest>

Module that will merge:

Gradle:

apply plugin: 'com.android.library'

android {
    compileSdkVersion 23
    buildToolsVersion '25.0.0'

    defaultConfig {
        minSdkVersion 16
        targetSdkVersion 23
        versionCode 1
        versionName "1.0"
    }

    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
        debug {
            jniDebuggable true
        }
    }
}

dependencies {
    compile project(path: ':android-infra')
    compile 'com.sensiya:sense-services-client:1.24.2@aar'
    compile project(path: ':engine-core-server')
    compile project(path: ':engine-core-aneeda')
}

Manifest:

<manifest package="com.iamplus.android.senseServices"
          xmlns:android="http://schemas.android.com/apk/res/android"
          xmlns:tools="http://schemas.android.com/tools">

    <application
        tools:node="replace">
        <service
            android:name="com.iamplus.senseServices.ContextualEventService"
            android:enabled="true"/>

        <service
            android:name="com.iamplus.senseServices.Serv"
            android:enabled="true"/>

        <service
            android:name="com.iamplus.senseServices.Serv1"
            android:enabled="true"/>
    </application>
</manifest>

Any suggestions?

Body:
It could be many things.Since  you didn't provide code, I will guess you are using default merge behavior. For more information, see: Merge conflict heuristics

You can use Merged Manifest view to preview the results of your merged manifest and find conflict errors.

In general, merge by default should work. Then just use Merged Manifest view to see how & where you lost values during merging. Using Merge rule markers would help you to manage merge by assigning rules markers.

If there is no merge at all. so it's probably a dependency issue between modules.

Note that dependency order plays a crucial role with modules which have the same priority level, such as libraries.

--- Update 5.April.2017 ---

Here are some useful tips:

Try to update and rebuild other libs as much as you can.

Remove all dependencies and then clean project, then add them again. and
check if you import them properly. that could be done by build the project without issues.

Note that since gradle 2.2.0 assets from modules won't be accessible
in app.

Check you manifest if merge process is not disabled exciplicitly by attribute:
tools:node=”remove" or tools:node="removeAll" or in gradle( see
this Disable Manifest Merger in Android Gradle Build)

Try to create a demo with a module and track merging. and then match
outputs to your projects. This will make it clear that is not
configuration issue but Android Studio 2.3 ( so then re-install fresh
version )

--- Update(2) 5.April.2017 ---

After you had added code, I could see that you are using Attribute

tools:node="replace"

Under application element in your modules (and probably in app's manifest too). I think that is the reason why you didn't get any manifest merged from imported modules merged to your app's manifest. See tools:node="replace" under Node markers.

Replace the lower-priority element completely. That is, if there is a
  matching element in the lower-priority manifest, ignore it and use
  this element exactly as it appears in this manifest.

That means both modules above will never get any thing merged with manifest from:

android-infra

com.sensiya:sense-services-client:1.24.2

engine-core-server

engine-core-aneeda

So get rid of that attribute and clean and rebuild modules. then rebuild whole project.


问:
Angular execute passed method reference in correct context
I've created a component si-button, which works as a progress button (when clicked, a loading indicator is shown).

I pass a reference to the method to be executed on click to the si-button component like this:

```<code><si-button [pb-click]="register">Register</si-button>
</code>```

The register method returns a promise, and the loading indicator is shown as long as the promise isn't resolved.
In the SIButtonComponent class, the register method is executed when the button is clicked.

SIButtonComponent:

```<code>export class SIButtonComponent{
    ...

    @Input('pb-click') pbClick : () => Promise<any> = null;

    handleClick($event){
        this.loading = true;

        this.pbClick().then(() => {
            this.showSuccess();
        }, (data) => {
            this.showError();
        });
    }

    ...
}
</code>```

RegisterComponent:

```<code>export class RegisterComponent{
    register() : Promise<any> {
        return new Promise((resolve, reject) => {
            this.auth.register(this.email, this.password).subscribe((org : Organization) => {
                resolve();
            }, (error : ErrorResponse) => {
                reject();
            });
        });
    }
}
</code>```

Problem
Since the method register is executed from an instance of SIButtonComponent, this refers to the SIButtonComponent instance rather than RegisterComponent. How should I do this correctly? It would make more sense to use @Output rather than @Input for the pb-click parameter, but I don't know how I could get the Promise-instance after emitting the click event then.

答:
Pass an arrow function instead:</p>

```<code>export class RegisterComponent {
    registerFunction = () => this.register();
    ...
}

<si-button [pb-click]="registerFunction">Register</si-button>
</code>```

Body:
I've created a component si-button, which works as a progress button (when clicked, a loading indicator is shown).

I pass a reference to the method to be executed on click to the si-button component like this:

<si-button [pb-click]="register">Register</si-button>

The register method returns a promise, and the loading indicator is shown as long as the promise isn't resolved.
In the SIButtonComponent class, the register method is executed when the button is clicked.

SIButtonComponent:

export class SIButtonComponent{
    ...

    @Input('pb-click') pbClick : () => Promise<any> = null;

    handleClick($event){
        this.loading = true;

        this.pbClick().then(() => {
            this.showSuccess();
        }, (data) => {
            this.showError();
        });
    }

    ...
}

RegisterComponent:

export class RegisterComponent{
    register() : Promise<any> {
        return new Promise((resolve, reject) => {
            this.auth.register(this.email, this.password).subscribe((org : Organization) => {
                resolve();
            }, (error : ErrorResponse) => {
                reject();
            });
        });
    }
}

Problem
Since the method register is executed from an instance of SIButtonComponent, this refers to the SIButtonComponent instance rather than RegisterComponent. How should I do this correctly? It would make more sense to use @Output rather than @Input for the pb-click parameter, but I don't know how I could get the Promise-instance after emitting the click event then.

Body:
Pass an arrow function instead:

export class RegisterComponent {
    registerFunction = () => this.register();
    ...
}

<si-button [pb-click]="registerFunction">Register</si-button>


问:
PHP version of ASP.NET's SqlCacheDependency
I find the SqlCacheDependency very useful when writing C# ASP.NET applications, and would love to use something similar in my PHP applications. Can anyone suggest something?

SqlCacheDependency caches the page page output forever, until the specified table(s) are modified in the database.

Here's the basic jist of what happens in ASP.NET:

```<code>SqlCacheDependency SqlDep = null;

// Check the Cache for the SqlSource key.
// If it isn't there, create it with a dependency
// on a SQL Server table using the SqlCacheDependency class.
if (Cache["MyCache"] == null) {
    SqlDep = new SqlCacheDependency("DatabaseName", "TableName");

    // Perform action to be cached ...
    var result = DatabaseIntensiveFunction();
    Cache.Insert("MyCache", result, SqlDep);
}

else {
    // The data was retrieved from the Cache.
}

// Output page from cache.
Output(Cache["MyCache"]);
</code>```

So does anyone know of any MySql table dependency technique? - much cleaner than time-based caching.

答:
Why not use something like Memcache or APC for this?

Edit: I also just found the MySQLnd Query Cache plugin for 5.3.3.

ContentLicense: CC BY-SA 2.5

Body:
I find the SqlCacheDependency very useful when writing C# ASP.NET applications, and would love to use something similar in my PHP applications. Can anyone suggest something?

SqlCacheDependency caches the page page output forever, until the specified table(s) are modified in the database.

Here's the basic jist of what happens in ASP.NET:

SqlCacheDependency SqlDep = null;

// Check the Cache for the SqlSource key.
// If it isn't there, create it with a dependency
// on a SQL Server table using the SqlCacheDependency class.
if (Cache["MyCache"] == null) {
    SqlDep = new SqlCacheDependency("DatabaseName", "TableName");

    // Perform action to be cached ...
    var result = DatabaseIntensiveFunction();
    Cache.Insert("MyCache", result, SqlDep);
}

else {
    // The data was retrieved from the Cache.
}

// Output page from cache.
Output(Cache["MyCache"]);

So does anyone know of any MySql table dependency technique? - much cleaner than time-based caching.


问:
What are the advantages of using Lagom over the Playframework directly?
I'm at the stage of conceiving a small JSON-based web services framework on top of Scala Play which makes really easy and suddenly stumbled upon the new Lagom framework and I'm wondering what's the added value of using it rather than the play framework directly? what would justify the extra complexity and extra footprint of Cassandra etc ...</p>

答:
Which framework is a better fit for you depends on your specific needs and requirements. When evaluating, though, you should not just consider the implementation of a single service, but of your system as a whole - e.g. how will your services communicate, how will you handle persistent storage?

Lagom has some features that Play doesn't, such as the concept of service descriptors & service clients that simplify things such as dynamic service lookup, circuit breaker integration etc.

As you have already discovered, it also simplifies setting up Cassandra persistence for Event Sourcing, and even asynchronous messaging between services by providing integration for a Kafka message bus. Please note that these only add to the footprint if you decide to use them.

Play on the other hand also has features Lagom hasn't, which you may or may not need, such as rendering HTML from templates.


问:
How to change element dynamically?
I can change element's attributes seamlessly like this:

```<code><input
  name="{{ currentField.name }}"
  type="{{ currentField.properties.type }}"
  ... />
</code>```

But, I need to change the element (input, textarea, select etc.) dynamically.

If I try to change element, AngularJS doest not rendering the element. Instead, showing HTML:

```<code><{{ currentField.element }}
  name="{{ currentField.name }}"
  type="{{ currentField.properties.type }}"
  ... />
</code>```

This is the example {{ currentField }} data:

```<code>{
    element: 'textarea',
    name: 'address',
    properties: {
        type: 'text',
    }
}
</code>```

Where is the problem?

答:
Use it like :</p>

```<code>    <textarea ng-if="currentField.element == 'textarea'"
      name="{{ currentField.name }}"
      type="{{ currentField.properties.type }}"
      ... />

<input ng-if="currentField.element == 'input'"
  name="{{ currentField.name }}"
  type="{{ currentField.properties.type }}"
  ... />
</code>```

Title: How to change element dynamically?

Body:
I can change element's attributes seamlessly like this:

<input
  name="{{ currentField.name }}"
  type="{{ currentField.properties.type }}"
  ... />

But, I need to change the element (input, textarea, select etc.) dynamically.

If I try to change element, AngularJS doest not rendering the element. Instead, showing HTML:

<{{ currentField.element }}
  name="{{ currentField.name }}"
  type="{{ currentField.properties.type }}"
  ... />

This is the example {{ currentField }} data:

{
    element: 'textarea',
    name: 'address',
    properties: {
        type: 'text',
    }
}

Where is the problem?

Body:
Use it like :

    <textarea ng-if="currentField.element == 'textarea'"
      name="{{ currentField.name }}"
      type="{{ currentField.properties.type }}"
      ... />

<input ng-if="currentField.element == 'input'"
  name="{{ currentField.name }}"
  type="{{ currentField.properties.type }}"
  ... />


问:
How to link Firebase account to Google Play Games account
I have an Android game that uses Play Games Services. Play Games Services appear to be linked to a specific Google Login. If a player starts the game, it is automatically logged into Play Games.

Now I wish to incorporate Firebase into my game as well, for example to facilitate chat.

How can I use the Play Games user account to create/login to a Firebase account?

Is there some sort of token Play Games gives me I can just pass onto Firebase?

I am trying to avoid having to use my own backend server, and avoid having the user having to sign in twice in my game, since that is a rather poor user experience.

What are my options? I'm rather stumped on how to approach this.

-- SOLVED --

First of all I needed to enable Google Signin from the Firebase auth tab.
Then I used this code in my base activity:

```<code>private FirebaseAuth mAuth;

GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_GAMES_SIGN_IN)
        .requestIdToken("<appidfromfirebase>.apps.googleusercontent.com")
        .build();

mGoogleApiClient = new GoogleApiClient.Builder(this)
    .enableAutoManage(this, this)
    .addConnectionCallbacks(this)
    .addApi(Games.API)
    .addScope(Games.SCOPE_GAMES)
    .addApi(Auth.GOOGLE_SIGN_IN_API, gso)
    .build();

@Override
    public void onConnected(Bundle connectionHint) {
        if (mGoogleApiClient.hasConnectedApi(Games.API)) {
            Auth.GoogleSignInApi.silentSignIn(mGoogleApiClient).setResultCallback(
                    new ResultCallback<GoogleSignInResult>() {
                        @Override
                        public void onResult(GoogleSignInResult googleSignInResult) {
                            GoogleSignInAccount acct = googleSignInResult.getSignInAccount();
                            if (acct == null) {
                                Logger.e("account was null: " + googleSignInResult.getStatus().getStatusMessage());
                                return;
                            }

                            AuthCredential credential = GoogleAuthProvider.getCredential(acct.getIdToken(),null);

                            mAuth.signInWithCredential(credential)
                                    .addOnCompleteListener(
                                            new OnCompleteListener<AuthResult>() {
                                                @Override
                                                public void onComplete(@NonNull Task<AuthResult> task) {
                                                    // check task.isSuccessful()
                                                }
                                            });
                        }
                    }
            );
        }
    }
</code>```

答:
Your logged-in Google account in your Android device is usually the one linked with your GPGS profile.

Now to answer your question, follow the Integrate With Your Play Games Services Project guide on how to use Firebase with GPGS.

When you add Firebase to your Play Game Services project in the Play
  Developer console, you can:

Get access to Firebase Analytics, a free app measurement solution that
  provides insight on app usage and user engagement. View your Games
  events in the Firebase Analytics by logging Play Games events to
  Firebase.

When you add Firebase to your Play Games Services project, you’re also
  linking your Google Play Account to your Firebase
  project.

Add Firebase to your Play Games Services project

In the Play Developer Console:

Click Add Firebase on the Game details page of your app Review the
  policy confirmation, then click Confirm Now Firebase is added to your
  Play Games Project and your Google Play account is linked to your
  Firebase project. Next, you will need to add the Firebase SDK to your
  app's code.

Add the Firebase SDK to your app

To get started, add Firebase Analytics to your app.

Once you have added the Firebase Analytics SDK to your app, you can
  begin logging Play Games events.

Body:
I have an Android game that uses Play Games Services. Play Games Services appear to be linked to a specific Google Login. If a player starts the game, it is automatically logged into Play Games.

Now I wish to incorporate Firebase into my game as well, for example to facilitate chat.

How can I use the Play Games user account to create/login to a Firebase account?

Is there some sort of token Play Games gives me I can just pass onto Firebase?

I am trying to avoid having to use my own backend server, and avoid having the user having to sign in twice in my game, since that is a rather poor user experience.

What are my options? I'm rather stumped on how to approach this.

-- SOLVED --

First of all I needed to enable Google Signin from the Firebase auth tab.
Then I used this code in my base activity:

private FirebaseAuth mAuth;

GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_GAMES_SIGN_IN)
        .requestIdToken("<appidfromfirebase>.apps.googleusercontent.com")
        .build();

mGoogleApiClient = new GoogleApiClient.Builder(this)
    .enableAutoManage(this, this)
    .addConnectionCallbacks(this)
    .addApi(Games.API)
    .addScope(Games.SCOPE_GAMES)
    .addApi(Auth.GOOGLE_SIGN_IN_API, gso)
    .build();

@Override
    public void onConnected(Bundle connectionHint) {
        if (mGoogleApiClient.hasConnectedApi(Games.API)) {
            Auth.GoogleSignInApi.silentSignIn(mGoogleApiClient).setResultCallback(
                    new ResultCallback<GoogleSignInResult>() {
                        @Override
                        public void onResult(GoogleSignInResult googleSignInResult) {
                            GoogleSignInAccount acct = googleSignInResult.getSignInAccount();
                            if (acct == null) {
                                Logger.e("account was null: " + googleSignInResult.getStatus().getStatusMessage());
                                return;
                            }

                            AuthCredential credential = GoogleAuthProvider.getCredential(acct.getIdToken(),null);

                            mAuth.signInWithCredential(credential)
                                    .addOnCompleteListener(
                                            new OnCompleteListener<AuthResult>() {
                                                @Override
                                                public void onComplete(@NonNull Task<AuthResult> task) {
                                                    // check task.isSuccessful()
                                                }
                                            });
                        }
                    }
            );
        }
    }


问:
how to recover corrupted php file
Click here to see the screenshot

help me guys, I created this file 4years ago, but now I am getting an error, I think this file is corrupt.
I open this file for many software like dreamweaver, notepad++, notepad, WordPad, MSOffice, HostGator server, onedrive, google drive. but none open this file.
I attach screenshot please help me.

答:
Open the PHP file with Notepad++.

From the Encoding menu, select Convert to UTF-8 without BOM, save the file, replace the old file with this new file.

Title: how to recover corrupted php file


问:
How to send transparent choice button with telegram bot
Using a Telegram Bot, I would like to know how I can send "transparent choice buttons" like in this image.

I dug in the documentation but here, they only explain how to make custom keyboard buttons, in such a way that  the android keyboard pops up with custom buttons in order for the user to choose.

With the ones in the image I uploaded, ( the buttons named "<<", "" and ">>" ) a user could vote or navigate intuitively and not be bothered with custom keyboard.

What is the code I need to send them? Then, when an user presses them, how can I handle the choice?

I'm working with Python and Linux.

Thanks in advance.
I searched but couldn't find anything.

答:
All you need to do is implementing inline keyboards that you can find more information about them here.

And for receiving the votes from the users firstly you need a database to store them and secondly you should use callback buttons or callback queries, which are part of inline keyboard markup in telegram bot API.


问:
Change color of items in appbar
I want to change the color of my app name, search icon and overflow menu in the appbar to white. I used textColorPrimary but its not working, it is all black.

Here is my code

colors.xml

```<code><resources>
    <color name="colorPrimary">#9C27B0</color>
    <color name="colorPrimaryDark">#CE93D8</color>
    <color name="textColorPrimary">#FFFFFF</color>
    <color name="windowBackground">#FFFFFF</color>
    <color name="navigationBarColor">#FFFFFF</color>
    <color name="colorAccent">#FF80AB</color>
</resource>
</code>```

styles.xml

```<code><style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
    <!-- Customize your theme here. -->
    <item name="colorPrimary">@color/colorPrimary</item>
    <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
    <item name="textColorPrimary">@color/textColorPrimary</item>
    <item name="colorAccent">@color/colorAccent</item>
    <item name="windowActionBar">false</item>
    <item name="windowNoTitle">true</item>
</style>
</code>```

AndroidManifest.xml

```<code>     <activity
        android:name=".MainActivity"
        android:theme="@style/AppTheme"
        android:label="@string/title_activity_welcome">
    </activity>
</code>```

menumain.xml

```<code>   <menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    tools:context=".MainActivity">

    <item
        android:id="@+id/action_search"
        android:icon="@drawable/ic_search"
        android:orderInCategory="100"
        android:title="@string/action_search"
        app:showAsAction="always" />

    <item
        android:id="@+id/action_settings"
        android:title="@string/action_settings"
        android:orderInCategory="100"
        app:showAsAction="never" />

    </menu>
</code>```

This is what I want - A white text(app name), search icon(fixed,i used a white search icon so no problem) and white overflow menu

答:
Add these lines in your style:</p>

```<code> <style name="TextAppearance" parent="TextAppearance.AppCompat.Widget.ActionBar.Menu">
    <item name="android:textColor">@color/white</item>
</style>
</code>```

Title: Change color of items in appbar

Body:
I want to change the color of my app name, search icon and overflow menu in the appbar to white. I used textColorPrimary but its not working, it is all black.

Here is my code

colors.xml

<resources>
    <color name="colorPrimary">#9C27B0</color>
    <color name="colorPrimaryDark">#CE93D8</color>
    <color name="textColorPrimary">#FFFFFF</color>
    <color name="windowBackground">#FFFFFF</color>
    <color name="navigationBarColor">#FFFFFF</color>
    <color name="colorAccent">#FF80AB</color>
</resource>

styles.xml

AndroidManifest.xml

     <activity
        android:name=".MainActivity"
        android:theme="@style/AppTheme"
        android:label="@string/title_activity_welcome">
    </activity>

menumain.xml

   <menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    tools:context=".MainActivity">

    <item
        android:id="@+id/action_search"
        android:icon="@drawable/ic_search"
        android:orderInCategory="100"
        android:title="@string/action_search"
        app:showAsAction="always" />

    <item
        android:id="@+id/action_settings"
        android:title="@string/action_settings"
        android:orderInCategory="100"
        app:showAsAction="never" />

    </menu>

This is what I want - A white text(app name), search icon(fixed,i used a white search icon so no problem) and white overflow menu

Body:
Add these lines in your style:

 <style name="TextAppearance" parent="TextAppearance.AppCompat.Widget.ActionBar.Menu">
    <item name="android:textColor">@color/white</item>
</style>


问:
List View Item Click listener not working
Row layout for list view . the click on the items is not working.
the list.onItemClickListener function is not getting called even though there is no error or crash.There is some issue with it which im not able to figure out.

XML code

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

    <LinearLayout
        android:id="@+id/invoice_layout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_alignParentTop="true"
        android:layout_marginLeft="10dp"
        android:layout_marginRight="10dp"
        android:background="@drawable/button_selector"
        android:padding="5dp">

        <RelativeLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content">

            <ImageView
                android:id="@+id/invoice_image"
                android:layout_width="25dp"
                android:layout_height="25dp"
                android:layout_alignParentLeft="true"
                android:layout_marginLeft="10dp"
                android:layout_marginTop="5dp"
                android:src="@drawable/report_card_symbol"
                android:textColor="@color/black"
                android:focusable="false"/>

            <TextView
                android:id="@+id/order_id"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_centerInParent="true"
                android:layout_toRightOf="@+id/invoice_image"
                android:ellipsize="end"
                android:maxLines="1"
                android:paddingLeft="10dp"
                android:text=""
                android:textColor="@color/black"
                android:textSize="16dp"
                android:visibility="gone" />

            <TextView
                android:id="@+id/invoice_amount"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_below="@+id/order_id"
                android:layout_centerInParent="true"
                android:layout_marginTop="2dp"
                android:layout_toRightOf="@+id/invoice_image"
                android:ellipsize="end"
                android:maxLines="1"
                android:paddingLeft="10dp"
                android:text=""
                android:textColor="@color/black"
                android:textSize="15sp"
                android:visibility="visible" />

            <ImageView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_alignParentRight="true"
                android:layout_marginRight="10dp"
                android:layout_marginTop="5dp"
                android:focusable="false"
                android:src="@drawable/ic_arrow_right_new"
                android:textColor="@color/black" />
        </RelativeLayout>

    </LinearLayout>

</RelativeLayout>
</code>```

答: removed the focussable on the parent relative layout resolved the issue. The focus was on relative layout so the click on the list didnt work.</p>

Body:
Row layout for list view . the click on the items is not working.
the list.onItemClickListener function is not getting called even though there is no error or crash.There is some issue with it which im not able to figure out.

XML code

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

    <LinearLayout
        android:id="@+id/invoice_layout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_alignParentTop="true"
        android:layout_marginLeft="10dp"
        android:layout_marginRight="10dp"
        android:background="@drawable/button_selector"
        android:padding="5dp">

        <RelativeLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content">

            <ImageView
                android:id="@+id/invoice_image"
                android:layout_width="25dp"
                android:layout_height="25dp"
                android:layout_alignParentLeft="true"
                android:layout_marginLeft="10dp"
                android:layout_marginTop="5dp"
                android:src="@drawable/report_card_symbol"
                android:textColor="@color/black"
                android:focusable="false"/>

            <TextView
                android:id="@+id/order_id"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_centerInParent="true"
                android:layout_toRightOf="@+id/invoice_image"
                android:ellipsize="end"
                android:maxLines="1"
                android:paddingLeft="10dp"
                android:text=""
                android:textColor="@color/black"
                android:textSize="16dp"
                android:visibility="gone" />

            <TextView
                android:id="@+id/invoice_amount"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_below="@+id/order_id"
                android:layout_centerInParent="true"
                android:layout_marginTop="2dp"
                android:layout_toRightOf="@+id/invoice_image"
                android:ellipsize="end"
                android:maxLines="1"
                android:paddingLeft="10dp"
                android:text=""
                android:textColor="@color/black"
                android:textSize="15sp"
                android:visibility="visible" />

            <ImageView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_alignParentRight="true"
                android:layout_marginRight="10dp"
                android:layout_marginTop="5dp"
                android:focusable="false"
                android:src="@drawable/ic_arrow_right_new"
                android:textColor="@color/black" />
        </RelativeLayout>

    </LinearLayout>

</RelativeLayout>


问:
Docker workflow for automated builds on Github-Dockerhub
I already have set up a github repository with 3 branches (master, dev and docker). I already set up successfully and linked the automated build on dockerhub. Each time a push is done on Github an image is built on Dockerhub with different tag (latest for master, beta for dev and alpha for docker). This is working fine. Now the problem...

On Dockerfile, there is a git clone command to retrieve the project. The problem is this is pointing to master always. So if I push something to docker branch for example (it builds image with alpha tag) the code of project on that image is the code of master and not code of branch docker which is the desired for this case.

If I modify the Dockerfile of branch docker (which generate alpha tagged image) and I put git clone -b docker ... the build is ok, but after all the tests, when I want to merge with a pull request from docker branch to dev branch for example, another updated is needed on dev to change the git clone command inside of Dockerfile to point to the right branch. And the same with a pull request from dev to master with the additional difficult of on this project the master branch is protected and I can't push directly to master... so after a pull request from dev to master I can't fix Dockerfile changing the Dockerfile to change git clone to point again to master.

Is there a way to have different branches with different tags on automated building without changing anything after pull requests from one to other branch? Thank you.

答:
When using automated builds, this is what happens;

Docker Hub (or Docker Cloud, which has some more advanced features) checks out the git commit that triggered the build

It builds the Dockerfile that you configured to build from in your automated build

From the above; you should not git clone inside your Dockerfile at all, because you'd be doing what's already done by the automated build. Simply do;

```<code>FROM some-base-image

# Copy your project's source into the image
COPY . /my-src
RUN do-something-with-the-source
</code>```

Docker Cloud has advanced features, which allow you to run custom scripts at various stages of the automated build, using build phase hooks (documentation). This allows you (for example) to make "minimal" images by building your project in a "build image", then copying the generated code to a local directory, and building the final image from that.

edit

The Automatic build options on Docker Cloud has more features than Automatic Build on Docker Hub. For example, the Dockerfile to build, and the build-context can be set separately. This allows you to have a Dockerfile in a subdirectory, but use files outside of that subdirectory to be used as the build context. To do this, set the Dockerfile location to (e.g.) /docker/Dockerfile, and the buildcontext to /

Body:
When using automated builds, this is what happens;

Docker Hub (or Docker Cloud, which has some more advanced features) checks out the git commit that triggered the build

It builds the Dockerfile that you configured to build from in your automated build

From the above; you should not git clone inside your Dockerfile at all, because you'd be doing what's already done by the automated build. Simply do;

FROM some-base-image

# Copy your project's source into the image
COPY . /my-src
RUN do-something-with-the-source

Docker Cloud has advanced features, which allow you to run custom scripts at various stages of the automated build, using build phase hooks (documentation). This allows you (for example) to make "minimal" images by building your project in a "build image", then copying the generated code to a local directory, and building the final image from that.

edit

The Automatic build options on Docker Cloud has more features than Automatic Build on Docker Hub. For example, the Dockerfile to build, and the build-context can be set separately. This allows you to have a Dockerfile in a subdirectory, but use files outside of that subdirectory to be used as the build context. To do this, set the Dockerfile location to (e.g.) /docker/Dockerfile, and the buildcontext to /


问:
Python - Pass a variable to lambda if it exists
I'm curious about how to make code more efficient in Python, I've got to execute an action, which may or may not have a payload attached depending on the length of a list.

Right now, I'm using an if statement to determine if there is a payload. Is there a better or cleaner way to find this?

```<code>                    #If payload, execute action with it
                    if(len(data) > 1):
                        action= mec.action(data[1])
                    #If no payload, then just execute action
                    else:
                        action= mec.action()
                    return action
</code>```

答:
In this case just use a ternary operator like this:

```<code>return mec.action(data[1]) if(len(data) > 1) else mec.action()
</code>```

Hope it helps!

Body:
I'm curious about how to make code more efficient in Python, I've got to execute an action, which may or may not have a payload attached depending on the length of a list.

Right now, I'm using an if statement to determine if there is a payload. Is there a better or cleaner way to find this?

                    #If payload, execute action with it
                    if(len(data) > 1):
                        action= mec.action(data[1])
                    #If no payload, then just execute action
                    else:
                        action= mec.action()
                    return action

Body:
In this case just use a ternary operator like this:

return mec.action(data[1]) if(len(data) > 1) else mec.action()

Hope it helps!


问:
How to open pdf file in external app or in webview size is greater than 25mb
hello i want to show pdf file in webview or in external app.

1) i use this url
https://docs.google.com/gview?embedded=true&url= +pdfurl , but google says "Whoops There was a problen while previewing document"

2) if i use intent to open the url in external app then they didnot load the file in external app.

3) if i use the intent to open the url in browser then its start downloading the pdf file.

```<code>Intent ii=new Intent(Intent.ACTION_VIEW);
    ii.setDataAndType(Uri.parse(pdf),"text/html");
    try {
        startActivity(ii);
    }catch (ActivityNotFoundException e)
    {
        Toast.makeText(QuranPara.this, "NO Pdf Viewer", Toast.LENGTH_SHORT).show();
    }
</code>```

here is the complete url https://docs.google.com/gview?embedded=true&url=www.elibrary.alnoorpk.com/PDF%20Books/Lafzi_aur_bamahawrah_terjma_2015/Para%201%20(Lafzi%20aur%20Bamuhawra%20Tarjma).pdf

check the image

答:
If your files are in assets first copy them to the external storage. Hope that you have handled permission flow.

Try the following code for offline

```<code>File pdfFile = new File(Environment.getExternalStorageDirectory(),"pdfName.pdf");//Pdf file path
            if (pdfFile.exists()) //Checking for the file is exist or not
            {
                Uri path = Uri.fromFile(pdfFile);
                Intent objIntent = new Intent(Intent.ACTION_VIEW);
                objIntent.setDataAndType(path, "application/pdf");
                objIntent.setFlags(Intent. FLAG_ACTIVITY_CLEAR_TOP);
                startActivity(objIntent);//Staring the pdf viewer
            } else {

                Toast.makeText(getActivity(), "The file not exists! ", Toast.LENGTH_SHORT).show();

            }
</code>```

Try the following for the webview option if you choose that

```<code>WebView webview = (WebView) findViewById(R.id.webview);
webview.getSettings().setJavaScriptEnabled(true);
String pdf = "online pdf link";
webview.loadUrl("http://drive.google.com/viewerng/viewer?embedded=true&url=" + pdf);
</code>```

But Remember if you use google docs for viewing the pdf or any other doc, google docs may throw you the error stating

You've reached the bandwidth limit for viewing or downloading files that aren't in Google Docs format..... So doesn't seem reliable

So, be cautious with google doc viewing

Body:
hello i want to show pdf file in webview or in external app.

1) i use this url
https://docs.google.com/gview?embedded=true&url= +pdfurl , but google says "Whoops There was a problen while previewing document"

2) if i use intent to open the url in external app then they didnot load the file in external app.

3) if i use the intent to open the url in browser then its start downloading the pdf file.

Intent ii=new Intent(Intent.ACTION_VIEW);
    ii.setDataAndType(Uri.parse(pdf),"text/html");
    try {
        startActivity(ii);
    }catch (ActivityNotFoundException e)
    {
        Toast.makeText(QuranPara.this, "NO Pdf Viewer", Toast.LENGTH_SHORT).show();
    }

here is the complete url https://docs.google.com/gview?embedded=true&url=www.elibrary.alnoorpk.com/PDF%20Books/Lafzi_aur_bamahawrah_terjma_2015/Para%201%20(Lafzi%20aur%20Bamuhawra%20Tarjma).pdf

check the image

Body:
If your files are in assets first copy them to the external storage. Hope that you have handled permission flow.

Try the following code for offline

File pdfFile = new File(Environment.getExternalStorageDirectory(),"pdfName.pdf");//Pdf file path
            if (pdfFile.exists()) //Checking for the file is exist or not
            {
                Uri path = Uri.fromFile(pdfFile);
                Intent objIntent = new Intent(Intent.ACTION_VIEW);
                objIntent.setDataAndType(path, "application/pdf");
                objIntent.setFlags(Intent. FLAG_ACTIVITY_CLEAR_TOP);
                startActivity(objIntent);//Staring the pdf viewer
            } else {

                Toast.makeText(getActivity(), "The file not exists! ", Toast.LENGTH_SHORT).show();

            }

Try the following for the webview option if you choose that

WebView webview = (WebView) findViewById(R.id.webview);
webview.getSettings().setJavaScriptEnabled(true);
String pdf = "online pdf link";
webview.loadUrl("http://drive.google.com/viewerng/viewer?embedded=true&url=" + pdf);

But Remember if you use google docs for viewing the pdf or any other doc, google docs may throw you the error stating

You've reached the bandwidth limit for viewing or downloading files that aren't in Google Docs format..... So doesn't seem reliable

So, be cautious with google doc viewing


问:
How to invert the entire screen in python
As you all know it is April fools today and i am working on this prank.
I already asked a question about this but that one is probably deep in the registers by now.

So, all my research is right here: Keeping the script running when closing the window and opening a text editor in Python

If you could tell me how to invert the entire screen that would be great! Thanks.

EDIT 1: Yes, i did find Python PIL, but that was only for inverting images, i need the entire screen to be inverted.

EDIT 2: Guys, i am begging you, help me, it needs to be done Today!!!

EDIT 3: I am working with Windows 10/8

答:
A possible way of doing this on windows is to use a python library that can emulate keypresses and use the windows shortcut that invert the screen (ctrl+alt+down).
If you install pyautogui it's as simple as that:</p>

```<code> Import pyautogui
 pyautogui.hotkey('ctrl', 'alt', 'down')
</code>```

Body:
A possible way of doing this on windows is to use a python library that can emulate keypresses and use the windows shortcut that invert the screen (ctrl+alt+down).
If you install pyautogui it's as simple as that:

 Import pyautogui
 pyautogui.hotkey('ctrl', 'alt', 'down')


问:
What is HTTP "Host" header?
Given that the TCP connection is already established when the HTTP request is sent, the IP address and port are implicitly known -- a TCP connection is an IP + Port.

So, why do we need the Host header?  Is this only needed for the case where there are multiple hosts mapped to the IP address implied in the TCP connection?

答:
The Host Header tells the webserver which virtual host to use (if set up). You can even have the same virtual host using several aliases (= domains and wildcard-domains). In this case, you still have the possibility to read that header manually in your web app if you want to provide different behavior based on different domains addressed. This is possible because in your webserver you can (and if I'm not mistaken you must) set up one vhost to be the default host. This default vhost is used whenever the host header does not match any of the configured virtual hosts.

That means: You get it right, although saying "multiple hosts" may be somewhat misleading: The host (the addressed machine) is the same, what really gets resolved to the IP address are different domain names (including subdomains) that are also referred to as hostnames (but not hosts!).

Although not part of the question, a fun fact: This specification led to problems with SSL in the early days because the web server has to deliver the certificate that corresponds to the domain the client has addressed. However, in order to know what certificate to use, the webserver should have known the addressed hostname in advance. But because the client sends that information only over the encrypted channel (which means: after the certificate has already been sent), the server had to assume you browsed the default host. That meant one SSL-secured domain per IP address / port-combination.

This has been overcome with Server Name Indication; however, that again breaks some privacy, as the server name is now transferred in plain text again, so every man-in-the-middle would see which hostname you are trying to connect to.

Although the webserver would know the hostname from Server Name Indication, the Host header is not obsolete, because the Server Name Indication information is only used within the TLS handshake. With an unsecured connection, there is no Server Name Indication at all, so the Host header is still valid (and necessary).

Another fun fact: Most webservers (if not all) reject your HTTP request if it does not contain exactly one Host header, even if it could be omitted because there is only the default vhost configured. That means the minimum required information in an HTTP-(GET-)request is the first line containing METHOD RESOURCE and PROTOCOL VERSION and at least the Host header, like this:

```<code>GET /someresource.html HTTP/1.1
Host: www.example.com
</code>```

In the MDN Documentation on the "Host" header they actually phrase it like this:

A Host header field must be sent in all HTTP/1.1 request messages. A
400 (Bad Request) status code will be sent to any HTTP/1.1 request
message that lacks a Host header field or contains more than one.

As mentioned by Darrel Miller, the complete specs can be found in RFC7230.

ContentLicense: CC BY-SA 4.0

Title: What is HTTP "Host" header?

Body:
The Host Header tells the webserver which virtual host to use (if set up). You can even have the same virtual host using several aliases (= domains and wildcard-domains). In this case, you still have the possibility to read that header manually in your web app if you want to provide different behavior based on different domains addressed. This is possible because in your webserver you can (and if I'm not mistaken you must) set up one vhost to be the default host. This default vhost is used whenever the host header does not match any of the configured virtual hosts.

That means: You get it right, although saying "multiple hosts" may be somewhat misleading: The host (the addressed machine) is the same, what really gets resolved to the IP address are different domain names (including subdomains) that are also referred to as hostnames (but not hosts!).

Although not part of the question, a fun fact: This specification led to problems with SSL in the early days because the web server has to deliver the certificate that corresponds to the domain the client has addressed. However, in order to know what certificate to use, the webserver should have known the addressed hostname in advance. But because the client sends that information only over the encrypted channel (which means: after the certificate has already been sent), the server had to assume you browsed the default host. That meant one SSL-secured domain per IP address / port-combination.

This has been overcome with Server Name Indication; however, that again breaks some privacy, as the server name is now transferred in plain text again, so every man-in-the-middle would see which hostname you are trying to connect to.

Although the webserver would know the hostname from Server Name Indication, the Host header is not obsolete, because the Server Name Indication information is only used within the TLS handshake. With an unsecured connection, there is no Server Name Indication at all, so the Host header is still valid (and necessary).

Another fun fact: Most webservers (if not all) reject your HTTP request if it does not contain exactly one Host header, even if it could be omitted because there is only the default vhost configured. That means the minimum required information in an HTTP-(GET-)request is the first line containing METHOD RESOURCE and PROTOCOL VERSION and at least the Host header, like this:

GET /someresource.html HTTP/1.1
Host: www.example.com

In the MDN Documentation on the "Host" header they actually phrase it like this:

A Host header field must be sent in all HTTP/1.1 request messages. A
400 (Bad Request) status code will be sent to any HTTP/1.1 request
message that lacks a Host header field or contains more than one.

As mentioned by Darrel Miller, the complete specs can be found in RFC7230.


问:
Simple cold to extends SwingWorker to help to count value in the background
This is a simple code that extends SwingWorker to help counting value in the background.
But when I run the code, it just skip to finished. For example, if I enter a number 5, it should display 5 4 3 2 1 finished!.
I guess maybe my declaration has problems.

```<code>import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.concurrent.ExecutionException;

import javax.swing.Icon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
import javax.swing.SwingWorker;
import static javax.swing.WindowConstants.DISPOSE_ON_CLOSE;

public class LabResponsiveGUI extends JFrame implements ActionListener {

    private final String TEXT_COUNT_DOWN = "Count down!";
    private final String TEXT_CANCEL = "Cancel!";

    private JTextField txt = new JTextField("3");
    private JButton button = new JButton(TEXT_COUNT_DOWN);
    //private JButton button1 = new JButton(TEXT_CANCEL);

    private JTextArea txtOutput = new JTextArea(10, 20);

    public LabResponsiveGUI() {
        super("Simple GUI example");
        setSize(400, 400);
        button.addActionListener(this);
        //button1.addActionListener(this);
        setDefaultCloseOperation(DISPOSE_ON_CLOSE);
        add(txt, BorderLayout.NORTH);
        button.setPreferredSize(new Dimension(200, 50));
        add(button, BorderLayout.SOUTH);
        JScrollPane scroll = new JScrollPane(txtOutput);
        add(scroll, BorderLayout.CENTER);
    }

    public void actionPerformed(ActionEvent e) {
        int value ;

        BackgroundTask bgt = new BackgroundTask();

        bgt.execute();

        try {
            value = Integer.parseInt(txt.getText());
            if (value <= 0) {
                JOptionPane.showMessageDialog(this, "Please enter a number greater than zero");
                return;
            }

        } catch (NumberFormatException ex) {
            JOptionPane.showMessageDialog(this, "Please enter a valid integer");
            return;
        }
    }

    public class BackgroundTask extends SwingWorker<Void,String> {
        private int value;

        public  void BackgroudTask(int value){
            this.value = value;
        }

        @Override
        protected Void doInBackground() throws Exception {

            try {
                int count =  value;
                String line = null;
                while (count > 0) {
                    line = String.valueOf(count);
                    txtOutput.append(line + System.getProperty("line.separator"));
                    count--;
                    Thread.sleep(1000);
                }
                txtOutput.append("Finished! ");
            } catch(Exception ex) {
                ex.printStackTrace();
            }
            return null;
        }
    }

    public static void main(String[] agrs){
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                LabResponsiveGUI frame = new LabResponsiveGUI();
                frame.setVisible(true);
            }
        });
    }
}
</code>```

答:
Change method

```<code>public void BackgrodTask(int value) {
</code>```

to

```<code>public BackgroundTask(int value) {
</code>```

and call the new constructor after value has been determined

Body:
This is a simple code that extends SwingWorker to help counting value in the background.
But when I run the code, it just skip to finished. For example, if I enter a number 5, it should display 5 4 3 2 1 finished!.
I guess maybe my declaration has problems.

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.concurrent.ExecutionException;

import javax.swing.Icon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
import javax.swing.SwingWorker;
import static javax.swing.WindowConstants.DISPOSE_ON_CLOSE;

public class LabResponsiveGUI extends JFrame implements ActionListener {

    private final String TEXT_COUNT_DOWN = "Count down!";
    private final String TEXT_CANCEL = "Cancel!";

    private JTextField txt = new JTextField("3");
    private JButton button = new JButton(TEXT_COUNT_DOWN);
    //private JButton button1 = new JButton(TEXT_CANCEL);

    private JTextArea txtOutput = new JTextArea(10, 20);

    public LabResponsiveGUI() {
        super("Simple GUI example");
        setSize(400, 400);
        button.addActionListener(this);
        //button1.addActionListener(this);
        setDefaultCloseOperation(DISPOSE_ON_CLOSE);
        add(txt, BorderLayout.NORTH);
        button.setPreferredSize(new Dimension(200, 50));
        add(button, BorderLayout.SOUTH);
        JScrollPane scroll = new JScrollPane(txtOutput);
        add(scroll, BorderLayout.CENTER);
    }

    public void actionPerformed(ActionEvent e) {
        int value ;

        BackgroundTask bgt = new BackgroundTask();

        bgt.execute();

        try {
            value = Integer.parseInt(txt.getText());
            if (value <= 0) {
                JOptionPane.showMessageDialog(this, "Please enter a number greater than zero");
                return;
            }

        } catch (NumberFormatException ex) {
            JOptionPane.showMessageDialog(this, "Please enter a valid integer");
            return;
        }
    }

    public class BackgroundTask extends SwingWorker<Void,String> {
        private int value;

        public  void BackgroudTask(int value){
            this.value = value;
        }

        @Override
        protected Void doInBackground() throws Exception {

            try {
                int count =  value;
                String line = null;
                while (count > 0) {
                    line = String.valueOf(count);
                    txtOutput.append(line + System.getProperty("line.separator"));
                    count--;
                    Thread.sleep(1000);
                }
                txtOutput.append("Finished! ");
            } catch(Exception ex) {
                ex.printStackTrace();
            }
            return null;
        }
    }

    public static void main(String[] agrs){
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                LabResponsiveGUI frame = new LabResponsiveGUI();
                frame.setVisible(true);
            }
        });
    }
}

Body:
Change method

public void BackgrodTask(int value) {

to

public BackgroundTask(int value) {

and call the new constructor after value has been determined


问:
Error highlighting in Visual C++
When using Eclipse or NetBeans IDE on a Java project I get to see where errors in my code are, before and after compiling. The line causing the issue is shown. I remember that back in the old days, the Visual C++ 98' edition did do underlining of errors in the code. Is there a way to enable this in Visual C++ 2005? Or is there a 3rd party plugin to do so?</p>

答:
What you need in order to do this is a static code analysis tool for C++ with a real-time plug-in for VS2005.  Unfortunately, I'm not aware of any open-source static code analyzers that plug into VS2005, but there are some commercial ones.  One such product that has been well-received is Riverblade's Visual Lint.

In general, Googling "visual c++ static code analysis" is a good place to start hunting this type of software down.

OwnerDisplayName: Matthias van der Vlies

Title: Error highlighting in Visual C++

OwnerDisplayName: MattK


问:
Iceface 2.0 commandLink partial submit doesn't work
I have a page which takes in request params for place, then generate information,
for example, http://example.com/xxx/weather.jsf?place=california.
The purpose of doing this is to let user bookmark the link.

In the weather.jsf, there are two outputtext and a commandlink:

```<code>Humidity : <ice:outputText value="#{weatherBean.humidity}"/>
Visibility : <ice:outputText value="#{weatherBean.visibility}"/>
<ice:commandLink id="likeButton"
  value="Like"
  actionListener="#{weatherBean.doLike}" />
</code>```

In the managedBean:

```<code>@ManagedBean(name="weatherBean")
@RequestScoped
public class WeatherBean
{
 String humidity;
 String visibility;
 int numLike;

 @PostConstruct
     public void init()
 {
  System.out.println("init called");
  HttpServletRequest request= (HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext().getRequest();
  String place = request.getParameter("place");
  setHumidity(WeatherDao.getHumidity(place));
  setVisibility(WeatherDao.getVisibility(place));
  setNumLike(GeneralDao.getNumLike());
 }

 public void doLike(ActionEvent event)
 {
  System.out.println("doLike called");
  GeneralDao.addNumberLike();
 }
}
</code>```

Alright, the page generated perfectly.
However, when I click the doLike commandLink,
it always triggers the init method first, then call doLike method.
Since the request param is empty, all the other values reset.
Is there any way to prevent a refresh of the page or calling of init method?
I tried partialsubmit or immediate, but no luck.

答:
Your bean is @RequestScoped, so after executing the JSF lifecycle, your bean instance is lost, until the next request comes in, at which point you get a new instance of your bean, and the PostContruct re-executes.

Try changing the scope of your bean to something longer lived, like @ViewScoped.

Body:
I have a page which takes in request params for place, then generate information,
for example, http://example.com/xxx/weather.jsf?place=california.
The purpose of doing this is to let user bookmark the link.

In the weather.jsf, there are two outputtext and a commandlink:

Humidity : <ice:outputText value="#{weatherBean.humidity}"/>
Visibility : <ice:outputText value="#{weatherBean.visibility}"/>
<ice:commandLink id="likeButton"
  value="Like"
  actionListener="#{weatherBean.doLike}" />

In the managedBean:

@ManagedBean(name="weatherBean")
@RequestScoped
public class WeatherBean
{
 String humidity;
 String visibility;
 int numLike;

 @PostConstruct
     public void init()
 {
  System.out.println("init called");
  HttpServletRequest request= (HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext().getRequest();
  String place = request.getParameter("place");
  setHumidity(WeatherDao.getHumidity(place));
  setVisibility(WeatherDao.getVisibility(place));
  setNumLike(GeneralDao.getNumLike());
 }

 public void doLike(ActionEvent event)
 {
  System.out.println("doLike called");
  GeneralDao.addNumberLike();
 }
}

Alright, the page generated perfectly.
However, when I click the doLike commandLink,
it always triggers the init method first, then call doLike method.
Since the request param is empty, all the other values reset.
Is there any way to prevent a refresh of the page or calling of init method?
I tried partialsubmit or immediate, but no luck.


问:
How to use opencv 'superres' package on Python cv2?
A simple enough question - I can't seem to find how to import or use superres from cv2 on Python, even though it is documented:
http://docs.opencv.org/2.4/modules/superres/doc/super_resolution.html

Thanks.

答: I guess there is no official Python API support for the superres module, However you may get some Open Source implementations of the same algorithm from: SeRanet Github or Python superresolution module </p>


问:
How can I get the data fields from subclass not superclass?
I have a super class named TestSuper

```<code>public class TestSuper {
  int a = 0;
}
</code>```

and I have 2 sub classes named TestSub and TestSub2 that extend TestSuper

```<code>public class TestSub extends TestSuper{
   int a=1;
}

public class TestSub2 extends TestSuper{
   int a=2;
}
</code>```

in my main class i created a method that takes in a type TestSuper and returns the a value of it and in the main i display it on the console

```<code>public class Main {
public static void main(String[] args){

    System.out.println(test(new TestSub())+" "+test(new TestSub2()));
}
public static int test(TestSuper b){
    return b.a;
}
}
</code>```

but the output is "0 0" instead of "1 2", what do I do?

答:
When you call test method like this:

```<code>test(new TestSub())+" "+test(new TestSub2())
</code>```

You use upcasting. Upcasting seperates interface and implementation for an object. But for seperating interface and implementation and achieving true implementation in polymorphism, you must use polymorphic structures. The instance variables aren't polymorphic. Because of this, actually you call a variable which is in TestSuper class.

Only instance methods are polymorphic.

Body:
I have a super class named TestSuper

public class TestSuper {
  int a = 0;
}

and I have 2 sub classes named TestSub and TestSub2 that extend TestSuper

public class TestSub extends TestSuper{
   int a=1;
}

public class TestSub2 extends TestSuper{
   int a=2;
}

in my main class i created a method that takes in a type TestSuper and returns the a value of it and in the main i display it on the console

public class Main {
public static void main(String[] args){

    System.out.println(test(new TestSub())+" "+test(new TestSub2()));
}
public static int test(TestSuper b){
    return b.a;
}
}

but the output is "0 0" instead of "1 2", what do I do?

Body:
When you call test method like this:

test(new TestSub())+" "+test(new TestSub2())

You use upcasting. Upcasting seperates interface and implementation for an object. But for seperating interface and implementation and achieving true implementation in polymorphism, you must use polymorphic structures. The instance variables aren't polymorphic. Because of this, actually you call a variable which is in TestSuper class.

Only instance methods are polymorphic.


问:
How to use Date function in hibernate query language
Hi trying to fetch the records from database based on the date wise,how can i achieve this
in database i have column like start_date with datatype datetime and in model class i have data member like

```<code>public class Records {
private Date startDate
// getters and setters
}
</code>```

am trying to write query like below

```<code>String hql = "from Records where  DATE(startDate)=? ";
Query query = session.createQuery(hql);
query.setParameter(0, getStartDate());
</code>```

答:
A number of things are not clear in your question. However, try adding TemporalType.DATE to your query, something like:

```<code>.. query.setParameter(0, getStartDate(), TemporalType.DATE);
</code>```

Basically, JPA needs to know that you're filtering records using a Date field. If I may demo using a more elaborate example: if your entity class is Record and @Id is field startDate, then:

```<code>@Entity
@NamedQuery(name="Record.findByStartDate",
    query="SELECT e FROM Record e"   // here returning the whole entity
    + " WHERE e.startDate = :startDate")
@Table(name="records")
public class Record implements Serializable {

    @Id
    @Column(name="startDate")
    @Temporal(TemporalType.DATE)
    private Date startDate;
    ...
}
</code>```

And search query method would be like:

```<code>public Record findByStartDate (Date startDate) {
    try {
      return (Record) em.createNamedQuery("Record.findByStartDate")
        .setParameter("startDate", startDate, TemporalType.DATE)
        .getSingleResult();
    } catch (NoResultException e) {
        return null;
    }
  }
</code>```

Body:
Hi trying to fetch the records from database based on the date wise,how can i achieve this
in database i have column like start_date with datatype datetime and in model class i have data member like

public class Records {
private Date startDate
// getters and setters
}

am trying to write query like below

String hql = "from Records where  DATE(startDate)=? ";
Query query = session.createQuery(hql);
query.setParameter(0, getStartDate());

Body:
A number of things are not clear in your question. However, try adding TemporalType.DATE to your query, something like:

.. query.setParameter(0, getStartDate(), TemporalType.DATE);

Basically, JPA needs to know that you're filtering records using a Date field. If I may demo using a more elaborate example: if your entity class is Record and @Id is field startDate, then:

@Entity
@NamedQuery(name="Record.findByStartDate",
    query="SELECT e FROM Record e"   // here returning the whole entity
    + " WHERE e.startDate = :startDate")
@Table(name="records")
public class Record implements Serializable {

    @Id
    @Column(name="startDate")
    @Temporal(TemporalType.DATE)
    private Date startDate;
    ...
}

And search query method would be like:

public Record findByStartDate (Date startDate) {
    try {
      return (Record) em.createNamedQuery("Record.findByStartDate")
        .setParameter("startDate", startDate, TemporalType.DATE)
        .getSingleResult();
    } catch (NoResultException e) {
        return null;
    }
  }


问:
Complexity of the python code
I am trying to find the runtime complexity of this Python program. Will the complexity be still n or will it be more than n as I am creating a new list for each recursive call</p>

```<code>def RecLinearSearch(lyst,number):
    found = False
    index = len(lyst)-1
    if lyst[index] == number:
        found = True
        return found
    elif index<len(lyst)-1:
        index +=1
        return RecLinearSearch(lyst[index:],number)
    return found
print(RecLinearSearch([1,4,5,65,44],55))
</code>```

答: Time and space complexity of your function are both O(1), since index<len(lyst)-1 is always false.

Title: Complexity of the python code

Body:
I am trying to find the runtime complexity of this Python program. Will the complexity be still n or will it be more than n as I am creating a new list for each recursive call

def RecLinearSearch(lyst,number):
    found = False
    index = len(lyst)-1
    if lyst[index] == number:
        found = True
        return found
    elif index<len(lyst)-1:
        index +=1
        return RecLinearSearch(lyst[index:],number)
    return found
print(RecLinearSearch([1,4,5,65,44],55))