问:
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?

答:
If you are getting manifest merge conflicts you have two options.

1) find all the manifest files included in your project including the ones in libraries that you have as dependencies, and ensure there are no conflicting configurations.

or 2) add some merge resolution rules to your Manifests to dictate how each conflict should be resolved.

There is a great page on that here with many details.

https://developer.android.com/studio/build/manifest-merge.html

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?


来源: stackexchange

问:
Only geometry.elementsNeedUpdate results in memory allocation - why?
If I have a simple animate function

```<code>function animate() {
geometry.elementsNeedUpdate = true;  // allocates memory without geometry.faces[ 0 ].color = ...
requestAnimationFrame( animate );
renderer.render( scene, camera ); }
</code>```

I get a memory allocation, even if no element is changed.
Then I add the manipulation of the color of the face.

```<code>function animate() {

geometry.elementsNeedUpdate = true;
// geometry.colorsNeedUpdate = true; // not necessary
// material.needsUpdate = true;      // not necessary
time = clock.getElapsedTime();
if ( time * 16 % 10 < 5 ) {
    geometry.faces[ 0 ].color = colorBlue;
} else {
    geometry.faces[ 0 ].color = colorRed;
}
requestAnimationFrame( animate );
renderer.render( scene, camera ); }
</code>```

and it remains in the memory allocation.

geometry.elementsNeedUpdate = true; is necessary to change the face colors.

How to avoid memory allocation?

The full example is available at http://sandbox.threejs.hofk.de/memory/

答:
You want to change the face colors of your object.

You can do so using copy() or setHex() like so:

```<code>mesh.geometry.faces[ 0 ].color.copy( myColor ); // or .setHex( 0xff0000 )

mesh.geometry.colorsNeedUpdate = true; // required if geometry previously rendered
</code>```

Do not set other needsUpdate flags unnecessarily.

Do not assign a new THREE.Color object, as you are currently doing.

three.js r.84

ContentLicense: CC BY-SA 3.0

Body:
If I have a simple animate function

function animate() {
geometry.elementsNeedUpdate = true;  // allocates memory without geometry.faces[ 0 ].color = ...
requestAnimationFrame( animate );
renderer.render( scene, camera ); }

I get a memory allocation, even if no element is changed.
Then I add the manipulation of the color of the face.

function animate() {

geometry.elementsNeedUpdate = true;
// geometry.colorsNeedUpdate = true; // not necessary
// material.needsUpdate = true;      // not necessary
time = clock.getElapsedTime();
if ( time * 16 % 10 < 5 ) {
    geometry.faces[ 0 ].color = colorBlue;
} else {
    geometry.faces[ 0 ].color = colorRed;
}
requestAnimationFrame( animate );
renderer.render( scene, camera ); }

and it remains in the memory allocation.

geometry.elementsNeedUpdate = true; is necessary to change the face colors.

How to avoid memory allocation?

The full example is available at http://sandbox.threejs.hofk.de/memory/

Body:
You want to change the face colors of your object.

You can do so using copy() or setHex() like so:

mesh.geometry.faces[ 0 ].color.copy( myColor ); // or .setHex( 0xff0000 )

mesh.geometry.colorsNeedUpdate = true; // required if geometry previously rendered

Do not set other needsUpdate flags unnecessarily.

Do not assign a new THREE.Color object, as you are currently doing.

three.js r.84


问:
Pop multiple values from Redis data structure atomically?
Is there a Redis data structure, which would allow atomic operation of popping (get+remove) multiple elements, which it contains?

There are well known SPOP or RPOP, but they always return a single value. Therefore, when I need first N values from set/list, I need to call the command N-times, which is expensive. Let's say the set/list contains millions of items. Is there anything like SPOPM "setName" 1000, which would return and remove 1000 random items from set or RPOPM "listName" 1000, which would return 1000 right-most items from list?

I know there are commands like SRANDMEMBER and LRANGE, but they do not remove the items from the data structure. They can be deleted separately. However, if there are more clients reading from the same data structure, some items can be read more than once and some can be deleted without reading! Therefore, atomicity is what my question is about.

Also, I am fine if the time complexity for such operation is more expensive. I doubt it will be more expensive than issuing N (let's say 1000, N from the previous example) separate requests to Redis server.

I also know about separate transaction support. However, this sentence from Redis docs discourages me from using it for parallel processes modifying the set (destructively reading from it):

When using WATCH, EXEC will execute commands only if the watched keys were not modified, allowing for a check-and-set mechanism.

答:
To expand on Eli's response with a complete example for list collections, using lrange and ltrim builtins instead of Lua:

```<code>127.0.0.1:6379> lpush a 0 1 2 3 4 5 6 7 8 9
(integer) 10
127.0.0.1:6379> lrange a 0 3        # read 4 items off the top of the stack
1) "9"
2) "8"
3) "7"
4) "6"
127.0.0.1:6379> ltrim a 4 -1        # remove those 4 items
OK
127.0.0.1:6379> lrange a 0 999      # remaining items
1) "5"
2) "4"
3) "3"
4) "2"
5) "1"
6) "0"
</code>```

If you wanted to make the operation atomic, you would wrap the lrange and ltrim in multi and exec commands.

Also as noted elsewhere, you should probably ltrim the number of returned items not the number of items you asked for.  e.g. if you did lrange a 0 99 but got 50 items you would ltrim a 50 -1 not ltrim a 100 -1.

To implement queue semantics instead of a stack, replace lpush with rpush.

Body:
To expand on Eli's response with a complete example for list collections, using lrange and ltrim builtins instead of Lua:

127.0.0.1:6379> lpush a 0 1 2 3 4 5 6 7 8 9
(integer) 10
127.0.0.1:6379> lrange a 0 3        # read 4 items off the top of the stack
1) "9"
2) "8"
3) "7"
4) "6"
127.0.0.1:6379> ltrim a 4 -1        # remove those 4 items
OK
127.0.0.1:6379> lrange a 0 999      # remaining items
1) "5"
2) "4"
3) "3"
4) "2"
5) "1"
6) "0"

If you wanted to make the operation atomic, you would wrap the lrange and ltrim in multi and exec commands.

Also as noted elsewhere, you should probably ltrim the number of returned items not the number of items you asked for.  e.g. if you did lrange a 0 99 but got 50 items you would ltrim a 50 -1 not ltrim a 100 -1.

To implement queue semantics instead of a stack, replace lpush with rpush.


问:
iOS app crashes on calendar.dateComponents
I'm having a crash on this line of code and I'm not entirely sure why.

```<code>let difference = calendar.dateComponents([.day, .hour, .minute], from: start, to: end!)
</code>```

This only happens on some devices and does not happen all of the time.

Full code:

```<code>    let start = Date()
    let formatter = DateFormatter()
    formatter.dateFormat = "MM/dd/yy hh:mm a"
    let end = formatter.date(from: dateString)

    let calendar = Calendar.current
    let difference = calendar.dateComponents([.day, .hour, .minute], from: start, to: end!)
</code>```

dateString is 5/3/17 7:00 PM

What could be causing the issue?

答:
The issue is with the following two lines of code, when the device you are running on is in 24-hour clock mode.

```<code>formatter.dateFormat = "MM/dd/yy hh:mm a"
let end = formatter.date(from: dateString)
</code>```

When in 24-hour mode, the second line returns nil for the date, and as @rmaddy warns above in the comments, forcing optionals is not a good idea since that can result in runtime crashes :)

Update:
I wanted to check the code to make sure that the crash goes away before I added this but as @LeoDabus states, adding the following line should fix the crash:

```<code>formatter.locale = Locale(identifier: "en_US_POSIX")
</code>```

Body:
I'm having a crash on this line of code and I'm not entirely sure why.

let difference = calendar.dateComponents([.day, .hour, .minute], from: start, to: end!)

This only happens on some devices and does not happen all of the time.

Full code:

    let start = Date()
    let formatter = DateFormatter()
    formatter.dateFormat = "MM/dd/yy hh:mm a"
    let end = formatter.date(from: dateString)

    let calendar = Calendar.current
    let difference = calendar.dateComponents([.day, .hour, .minute], from: start, to: end!)

dateString is 5/3/17 7:00 PM

What could be causing the issue?

Body:
The issue is with the following two lines of code, when the device you are running on is in 24-hour clock mode.

formatter.dateFormat = "MM/dd/yy hh:mm a"
let end = formatter.date(from: dateString)

When in 24-hour mode, the second line returns nil for the date, and as @rmaddy warns above in the comments, forcing optionals is not a good idea since that can result in runtime crashes :)

Update:
I wanted to check the code to make sure that the crash goes away before I added this but as @LeoDabus states, adding the following line should fix the crash:

formatter.locale = Locale(identifier: "en_US_POSIX")


问:
How to configure log4j for a Spark program running inside of Intellij?
I've tried all possible suggestion on google but I still get spark log with INFO level which is too verbose. </p>

```<code>import org.apache.log4j.{Level, LogManager, Logger}
import org.apache.spark.sql.SparkSession

object  tmp {

  def main(args: Array[String]): Unit = {
    val spark =  SparkSession.builder()
      .master("local[*]")
      .getOrCreate()

    spark.sparkContext.setLogLevel("ERROR")

    LogManager.getRootLogger.setLevel(Level.ERROR)
    val rootLogger = Logger.getRootLogger()
    rootLogger.setLevel(Level.ERROR)

    Logger.getLogger("org").setLevel(Level.OFF)
    Logger.getLogger("akka").setLevel(Level.OFF)

    spark.read.json("/home/white/wk/tmp/people.json").show
  }
}
</code>```

答: Add a log4j.properties file to the classpath with the rootLogger level set to FATAL or OFF.

Body:
I've tried all possible suggestion on google but I still get spark log with INFO level which is too verbose.

import org.apache.log4j.{Level, LogManager, Logger}
import org.apache.spark.sql.SparkSession

object  tmp {

  def main(args: Array[String]): Unit = {
    val spark =  SparkSession.builder()
      .master("local[*]")
      .getOrCreate()

    spark.sparkContext.setLogLevel("ERROR")

    LogManager.getRootLogger.setLevel(Level.ERROR)
    val rootLogger = Logger.getRootLogger()
    rootLogger.setLevel(Level.ERROR)

    Logger.getLogger("org").setLevel(Level.OFF)
    Logger.getLogger("akka").setLevel(Level.OFF)

    spark.read.json("/home/white/wk/tmp/people.json").show
  }
}


问:
Ruby - how to find the NEXT occurrence of a given hour?
I want to return a Ruby Time object (miliseconds) that represents the next X hour from a given DateTime.

Examples for the next 5am

if it currently is 9pm on 3/28, the NEXT 5am would be 3/29 5am

if it currently is 6am on 3/29, the NEXT 5am would be 3/30 5am

Code wise:

```<code># for the below attribute
@object.created_at
=> "2017-03-28 21:00:00"

# given the definition of the next X hour in question
next_hour_to_find = 5 # for 5am

# what's the equation to produce 3/29 5am?
</code>```

I'd like something flexible so that if next_hour_to_find = 14 then the function would be able to find the next 2pm. No worries about time zone, this is all within the scope of the time zone of the @object.created_at.

My current thinking is below, but I feel like there's a cleaner way...

```<code>if @object.created_at.hour > next_hour_to_find
  # the next X hour is always going to occur on the next date
  date = (@object.created_at + 1.days).strftime(...) # get the date out
else
  # the next X hour is always going to occur on the same date
  date = (@object.created_at).strftime(...) # get the date out
end

# now that we have a date in a string, we have to append that string with the next_hour_to_find
# not sure if below works for both single and double digit hours
string = date + next_hour_to_find + ":00:00"

# finish by returning Time object, but this seems suuuuper inefficient since we converted to string and then back again
return Time.parse(string)
</code>```

答:
There's no reason to smash around with string-formatted times. The DateTime object has everything you need:</p>

```<code>now = DateTime.now

if (now.hour >= 5)
  now = now.advance(days: 1)
end

now.change(hour: 5)
</code>```

Body:
I want to return a Ruby Time object (miliseconds) that represents the next X hour from a given DateTime.

Examples for the next 5am

if it currently is 9pm on 3/28, the NEXT 5am would be 3/29 5am

if it currently is 6am on 3/29, the NEXT 5am would be 3/30 5am

Code wise:

# for the below attribute
@object.created_at
=> "2017-03-28 21:00:00"

# given the definition of the next X hour in question
next_hour_to_find = 5 # for 5am

# what's the equation to produce 3/29 5am?

I'd like something flexible so that if next_hour_to_find = 14 then the function would be able to find the next 2pm. No worries about time zone, this is all within the scope of the time zone of the @object.created_at.

My current thinking is below, but I feel like there's a cleaner way...

if @object.created_at.hour > next_hour_to_find
  # the next X hour is always going to occur on the next date
  date = (@object.created_at + 1.days).strftime(...) # get the date out
else
  # the next X hour is always going to occur on the same date
  date = (@object.created_at).strftime(...) # get the date out
end

# now that we have a date in a string, we have to append that string with the next_hour_to_find
# not sure if below works for both single and double digit hours
string = date + next_hour_to_find + ":00:00"

# finish by returning Time object, but this seems suuuuper inefficient since we converted to string and then back again
return Time.parse(string)

Body:
There's no reason to smash around with string-formatted times. The DateTime object has everything you need:

now = DateTime.now

if (now.hour >= 5)
  now = now.advance(days: 1)
end

now.change(hour: 5)


问:
PHP/MySQL alternatives to WordPress?
I'm having a hard time believing there isn't already a good question with solid answers/discussion about this, but I didn't have any luck searching one up. Please link+close if you know of one. Certainly no hard feelings...

that being said,

I'm looking for a PHP+MySQL blog framework that's not named WordPress, and I have the following basic requirements:

relatively "light" aka easily edited/hacked/augmented (clean code, good structure, etc)

solid image support (upload, resize, etc)

solid comments system (including some sort of human verification)

Not too bad, right?

Normally I just hop over to Wikipedia for this sort of thing, but their List of CMS is uncharacteristically lacking in cross-comparison details.

Picking through that will take me awhile. Is there anyone out there who has been down the same road as I and would like to toss out some suggestions while I peruse Wikipedia's list?

Thank you!

EDIT - I finally found a similar question, by the masterly Pekka

答: There are lots of blog frameworks in that list. As i know joomla is good and also eZ Publish. But why you don't want to use Wordpress?</p>

ContentLicense: CC BY-SA 2.5

Title: PHP/MySQL alternatives to WordPress?


问:
Create a zip File From a Single file
Create a zip File From a Single file.
I have start to build a new compression tool on vb.net and its works fine, but i have to make a directory first and insert my files into it and then compress.
How can i make a compress file from a single file by press the button5.

I have try like this

```<code>ZipFileExtensions.CreateEntryFromFile(TextBox4.Text, TextBox3.Text, CompressionLevel.Optimal)
</code>```

the textbox4 is the chose file and textbox3 is name for the file
but it give me the error The value of type cannot be converted to System.IO.Compression.ZipArchive

This is my code

```<code>Imports System.IO
Imports System.IO.Compression

Public Class Form2

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    ProgressBar1.Show()
    Timer1.Start()
    TextBox2.Text = TextBox2.Text + "\" + TextBox3.Text
    ' Create ZIP from "source" directory (in program folder).
    ZipFile.CreateFromDirectory(TextBox1.Text,
                                TextBox2.Text + ".zip",
                                CompressionLevel.Optimal,
                                False)
    MessageBox.Show("The Process are complete", "MediaZip", MessageBoxButtons.OK, MessageBoxIcon.Warning)
    ProgressBar1.Hide()
End Sub

Private Sub TextBox1_TextChanged(sender As Object, e As EventArgs) Handles TextBox1.TextChanged

End Sub

Private Sub ProgressBar1_Click(sender As Object, e As EventArgs) Handles ProgressBar1.Click

End Sub

Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
    Dim dialog As New FolderBrowserDialog()
    dialog.RootFolder = Environment.SpecialFolder.Desktop
    dialog.SelectedPath = "C:\"
    dialog.Description = "Select Application Configuration Files Path"
    If dialog.ShowDialog() = Windows.Forms.DialogResult.OK Then
        TextBox1.Text = dialog.SelectedPath
    End If
    TextBox1.Text = dialog.SelectedPath

End Sub

Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
    Dim dialog As New FolderBrowserDialog()
    dialog.RootFolder = Environment.SpecialFolder.Desktop
    dialog.SelectedPath = "C:\"
    dialog.Description = "Select A Folder To Compress"
    If dialog.ShowDialog() = Windows.Forms.DialogResult.OK Then
        TextBox2.Text = dialog.SelectedPath
    End If
    TextBox2.Text = dialog.SelectedPath
End Sub

Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
    ProgressBar1.Increment(1 * 55)
End Sub

Private Sub Button4_Click(sender As Object, e As EventArgs) Handles Button4.Click
    Dim OpenFileDialog1 As New OpenFileDialog
    OpenFileDialog1.InitialDirectory = "C:\"
    OpenFileDialog1.FileName = "Select A File..."
    OpenFileDialog1.Multiselect = False
    If OpenFileDialog1.ShowDialog = Windows.Forms.DialogResult.OK Then
        Dim sName As String = OpenFileDialog1.SafeFileName
        TextBox4.Text = OpenFileDialog1.FileName

    End If
End Sub

Private Sub Button5_Click(sender As Object, e As EventArgs) Handles Button5.Click

End Sub
End Class
</code>```

答:
I have finally sort all the the errors and its working like i want.
I make a temporary directory, move the chosen file into it, then compress and send it to the Desktop , and finally delete the temporary directory.
This is the working code</p>

```<code>Imports System.IO
Imports System.IO.Compression
Imports System
Imports System.Windows.Forms
Imports System.Net
Imports System.Diagnostics
Public Class Form4
Dim tempdir As String = "C:\MediaZip"

Private Sub Form4_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    Form1.Hide()
    Me.BringToFront()
    IO.Directory.Delete(tempdir, True)
End Sub

Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
    ProgressBar1.Show()
    Timer1.Start()
    TextBox2.Text = TextBox2.Text + "\" + TextBox3.Text
    ' Create ZIP from "source" directory (in program folder).
    ZipFile.CreateFromDirectory("C:\MediaZip",
                                TextBox2.Text + ".zip",
                                CompressionLevel.Optimal,
                                False)
    MessageBox.Show("The Process are complete", "MediaZip", MessageBoxButtons.OK, MessageBoxIcon.Warning)
    ProgressBar1.Hide()
End Sub

Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
    Dim dialog As New FolderBrowserDialog()
    dialog.RootFolder = Environment.SpecialFolder.Desktop
    dialog.SelectedPath = "C:\"
    dialog.Description = "Were To Store Your File ?"
    If dialog.ShowDialog() = Windows.Forms.DialogResult.OK Then
        TextBox2.Text = dialog.SelectedPath
    End If
    TextBox2.Text = dialog.SelectedPath
    Dim logDirectoryProperties As System.IO.DirectoryInfo

    My.Computer.FileSystem.CopyFile(
       TextBox1.Text,
       "C:\MediaZip\" + TextBox4.Text)
End Sub

 Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    Dim OpenFileDialog1 As New OpenFileDialog
    OpenFileDialog1.InitialDirectory = "C:\"
    OpenFileDialog1.FileName = "File To Zip..."
    OpenFileDialog1.Multiselect = True
    If OpenFileDialog1.ShowDialog = Windows.Forms.DialogResult.OK Then
        Dim sName As String = OpenFileDialog1.SafeFileName
        TextBox1.Text = OpenFileDialog1.FileName
        TextBox4.Text = System.IO.Path.GetFileName(OpenFileDialog1.FileName)
        IO.Directory.Delete(tempdir, True)
    End If
 End Sub
End Class
</code>```

Title: Create a zip File From a Single file

Body:
Create a zip File From a Single file.
I have start to build a new compression tool on vb.net and its works fine, but i have to make a directory first and insert my files into it and then compress.
How can i make a compress file from a single file by press the button5.

I have try like this

ZipFileExtensions.CreateEntryFromFile(TextBox4.Text, TextBox3.Text, CompressionLevel.Optimal)

the textbox4 is the chose file and textbox3 is name for the file
but it give me the error The value of type cannot be converted to System.IO.Compression.ZipArchive

This is my code

Imports System.IO
Imports System.IO.Compression

Public Class Form2

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    ProgressBar1.Show()
    Timer1.Start()
    TextBox2.Text = TextBox2.Text + "\" + TextBox3.Text
    ' Create ZIP from "source" directory (in program folder).
    ZipFile.CreateFromDirectory(TextBox1.Text,
                                TextBox2.Text + ".zip",
                                CompressionLevel.Optimal,
                                False)
    MessageBox.Show("The Process are complete", "MediaZip", MessageBoxButtons.OK, MessageBoxIcon.Warning)
    ProgressBar1.Hide()
End Sub

Private Sub TextBox1_TextChanged(sender As Object, e As EventArgs) Handles TextBox1.TextChanged

End Sub

Private Sub ProgressBar1_Click(sender As Object, e As EventArgs) Handles ProgressBar1.Click

End Sub

Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
    Dim dialog As New FolderBrowserDialog()
    dialog.RootFolder = Environment.SpecialFolder.Desktop
    dialog.SelectedPath = "C:\"
    dialog.Description = "Select Application Configuration Files Path"
    If dialog.ShowDialog() = Windows.Forms.DialogResult.OK Then
        TextBox1.Text = dialog.SelectedPath
    End If
    TextBox1.Text = dialog.SelectedPath

End Sub

Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
    Dim dialog As New FolderBrowserDialog()
    dialog.RootFolder = Environment.SpecialFolder.Desktop
    dialog.SelectedPath = "C:\"
    dialog.Description = "Select A Folder To Compress"
    If dialog.ShowDialog() = Windows.Forms.DialogResult.OK Then
        TextBox2.Text = dialog.SelectedPath
    End If
    TextBox2.Text = dialog.SelectedPath
End Sub

Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
    ProgressBar1.Increment(1 * 55)
End Sub

Private Sub Button4_Click(sender As Object, e As EventArgs) Handles Button4.Click
    Dim OpenFileDialog1 As New OpenFileDialog
    OpenFileDialog1.InitialDirectory = "C:\"
    OpenFileDialog1.FileName = "Select A File..."
    OpenFileDialog1.Multiselect = False
    If OpenFileDialog1.ShowDialog = Windows.Forms.DialogResult.OK Then
        Dim sName As String = OpenFileDialog1.SafeFileName
        TextBox4.Text = OpenFileDialog1.FileName

    End If
End Sub

Private Sub Button5_Click(sender As Object, e As EventArgs) Handles Button5.Click

End Sub
End Class

Body:
I have finally sort all the the errors and its working like i want.
I make a temporary directory, move the chosen file into it, then compress and send it to the Desktop , and finally delete the temporary directory.
This is the working code

Imports System.IO
Imports System.IO.Compression
Imports System
Imports System.Windows.Forms
Imports System.Net
Imports System.Diagnostics
Public Class Form4
Dim tempdir As String = "C:\MediaZip"

Private Sub Form4_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    Form1.Hide()
    Me.BringToFront()
    IO.Directory.Delete(tempdir, True)
End Sub

Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
    ProgressBar1.Show()
    Timer1.Start()
    TextBox2.Text = TextBox2.Text + "\" + TextBox3.Text
    ' Create ZIP from "source" directory (in program folder).
    ZipFile.CreateFromDirectory("C:\MediaZip",
                                TextBox2.Text + ".zip",
                                CompressionLevel.Optimal,
                                False)
    MessageBox.Show("The Process are complete", "MediaZip", MessageBoxButtons.OK, MessageBoxIcon.Warning)
    ProgressBar1.Hide()
End Sub

Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
    Dim dialog As New FolderBrowserDialog()
    dialog.RootFolder = Environment.SpecialFolder.Desktop
    dialog.SelectedPath = "C:\"
    dialog.Description = "Were To Store Your File ?"
    If dialog.ShowDialog() = Windows.Forms.DialogResult.OK Then
        TextBox2.Text = dialog.SelectedPath
    End If
    TextBox2.Text = dialog.SelectedPath
    Dim logDirectoryProperties As System.IO.DirectoryInfo

    My.Computer.FileSystem.CopyFile(
       TextBox1.Text,
       "C:\MediaZip\" + TextBox4.Text)
End Sub

 Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    Dim OpenFileDialog1 As New OpenFileDialog
    OpenFileDialog1.InitialDirectory = "C:\"
    OpenFileDialog1.FileName = "File To Zip..."
    OpenFileDialog1.Multiselect = True
    If OpenFileDialog1.ShowDialog = Windows.Forms.DialogResult.OK Then
        Dim sName As String = OpenFileDialog1.SafeFileName
        TextBox1.Text = OpenFileDialog1.FileName
        TextBox4.Text = System.IO.Path.GetFileName(OpenFileDialog1.FileName)
        IO.Directory.Delete(tempdir, True)
    End If
 End Sub
End Class


问:
Laravel logging out on user deleting
I am using Laravel 5.3.

I have an User model extending Authenticatable.

I also have an users panel where the super user can update and delete other users.

However, every time the super user deletes another user, he gets disconnected (logged out) from the system. How can I workaround this?

I am deleting on a custom controller "UserController":

```<code>public function delete (User $user)
    {
        $deleted = $user->delete();
        return compact('deleted');
    }
</code>```

答:
Found the problem:

When creating a new User using the built-in make:auth register method, the logged user inevitably gets re-logged as the recently created user. So, the logged user was no more the "super user" but the recently created user that, when deleted, gets logged out. Solved by registering in another method.

Title: Laravel logging out on user deleting

Body:
I am using Laravel 5.3.

I have an User model extending Authenticatable.

I also have an users panel where the super user can update and delete other users.

However, every time the super user deletes another user, he gets disconnected (logged out) from the system. How can I workaround this?

I am deleting on a custom controller "UserController":

public function delete (User $user)
    {
        $deleted = $user->delete();
        return compact('deleted');
    }


问:
"could not extract ResultSet" in JPQL GROUP BY query
In my Spring Boot 1.5 application with Spring Data JPA, I have a TDR table like:

```<code>     Table TDR
-----------------------
id | c_id | m_id | p_id
 1 |   1  |    1 |    1
 2 |   1  |    1 |    2
 3 |   2  |    1 |    1
 4 |   2  |    1 |    2
 5 |   3  |    1 |    1
</code>```

where I need to find the last records grouped by m_id and p_id. With PostgreSQL SQL, I do this with the MAX aggregate function:

```<code>SELECT t.id, t.c_id, t.m_id, t.p_id
FROM (
  SELECT MAX(id) AS id, m_id, p_id
  FROM tdr
  WHERE m_id = 1                      -- <<< parameterized below
  GROUP BY m_id, p_id
  ) m JOIN tdr t ON t.id = m.id
</code>```

which returns the correct records:

```<code>     Table TDR
-----------------------
id | c_id | m_id | p_id
 4 |   2  |    1 |    2
 5 |   3  |    1 |    1
</code>```

Since the GROUP BY does not include c_id, the SQL is structured as correlated sub-query and matched with a join (see this question for details).

I'd like to convert this SQL to JPQL with this Lombok @Data entity:

```<code>@Data
@Entity
@Table(name = "TDR")
public class TDR implements Serializable {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(nullable = false)
    private Long id;

    @ManyToOne(optional=false, cascade = { CascadeType.ALL })
    @JoinColumn(name="m_id")
    private M m;

    @ManyToOne(optional=false, cascade = { CascadeType.ALL })
    @JoinColumn(name="p_id")
    private P p;

    @ManyToOne(optional=false, cascade = { CascadeType.ALL })
    @JoinColumn(name="c_id")
    private C c;
}
</code>```

but my JPQL for the correlated sub-query with parameterized m ID (:m_id):

```<code>SELECT t FROM TDR t WHERE t.id in (
  SELECT MAX(t.id) AS id, t.m, t.p FROM TDR t WHERE t.m = :m GROUP BY t.m, t.p
  )
</code>```

results in this error:

```<code>org.springframework.dao.InvalidDataAccessResourceUsageException: could not extract ResultSet; SQL [n/a]; nested exception is org.hibernate.exception.SQLGrammarException: could not extract ResultSet
   // at ...
Caused by: org.hibernate.exception.SQLGrammarException: could not extract ResultSet
   // at ...
Caused by: org.postgresql.util.PSQLException: ERROR: subquery has too many columns
</code>```

答:
The thing that jumps out to me is that your first SELECT:

SELECT FROM

...doesn't state which columns you're selecting

Body:
In my Spring Boot 1.5 application with Spring Data JPA, I have a TDR table like:

     Table TDR
-----------------------
id | c_id | m_id | p_id
 1 |   1  |    1 |    1
 2 |   1  |    1 |    2
 3 |   2  |    1 |    1
 4 |   2  |    1 |    2
 5 |   3  |    1 |    1

where I need to find the last records grouped by m_id and p_id. With PostgreSQL SQL, I do this with the MAX aggregate function:

SELECT t.id, t.c_id, t.m_id, t.p_id
FROM (
  SELECT MAX(id) AS id, m_id, p_id
  FROM tdr
  WHERE m_id = 1                      -- <<< parameterized below
  GROUP BY m_id, p_id
  ) m JOIN tdr t ON t.id = m.id

which returns the correct records:

     Table TDR
-----------------------
id | c_id | m_id | p_id
 4 |   2  |    1 |    2
 5 |   3  |    1 |    1

Since the GROUP BY does not include c_id, the SQL is structured as correlated sub-query and matched with a join (see this question for details).

I'd like to convert this SQL to JPQL with this Lombok @Data entity:

@Data
@Entity
@Table(name = "TDR")
public class TDR implements Serializable {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(nullable = false)
    private Long id;

    @ManyToOne(optional=false, cascade = { CascadeType.ALL })
    @JoinColumn(name="m_id")
    private M m;

    @ManyToOne(optional=false, cascade = { CascadeType.ALL })
    @JoinColumn(name="p_id")
    private P p;

    @ManyToOne(optional=false, cascade = { CascadeType.ALL })
    @JoinColumn(name="c_id")
    private C c;
}

but my JPQL for the correlated sub-query with parameterized m ID (:m_id):

SELECT t FROM TDR t WHERE t.id in (
  SELECT MAX(t.id) AS id, t.m, t.p FROM TDR t WHERE t.m = :m GROUP BY t.m, t.p
  )

results in this error:

org.springframework.dao.InvalidDataAccessResourceUsageException: could not extract ResultSet; SQL [n/a]; nested exception is org.hibernate.exception.SQLGrammarException: could not extract ResultSet
   // at ...
Caused by: org.hibernate.exception.SQLGrammarException: could not extract ResultSet
   // at ...
Caused by: org.postgresql.util.PSQLException: ERROR: subquery has too many columns


问:
Capitalization standards in importing in python
There are a lot of standard abbreviations used for importing modules in python.  I frequently see

```<code>import matplotlib.pyplot as plt
import numpy as np
import networkx as nx
</code>```

I notice that all of these are lower case.  I can't think of any exceptions.  However, it is case sensitive, so we certainly can use capital letters.  Is there any PEP standard about this?  In particular, would there be any problem with creating modules with capitalized names and importing them with capitalizations?

For example:

```<code>import MyClass as MC
import TomAndJerry as TaJ
</code>```

(please note - I'm not really interested in personal opinions - but rather whether there are official standards)

答:
There is a standard.

It also gets violated not infrequently. The most common example of off the top of my head is cPickle.

Body:
There are a lot of standard abbreviations used for importing modules in python.  I frequently see

import matplotlib.pyplot as plt
import numpy as np
import networkx as nx

I notice that all of these are lower case.  I can't think of any exceptions.  However, it is case sensitive, so we certainly can use capital letters.  Is there any PEP standard about this?  In particular, would there be any problem with creating modules with capitalized names and importing them with capitalizations?

For example:

import MyClass as MC
import TomAndJerry as TaJ

(please note - I'm not really interested in personal opinions - but rather whether there are official standards)


问:
Google Bar Chart from Mysql Database
I have a mysql db with 3 fields region(vachar), new_customers(int) and old_customers(int).

I am trying to create a bar chart with google charts and php but it doesn't work. I think i am doing sth wrong on echo.
Here is my code:

```<code><script type="text/javascript" src="https://www.google.com/jsapi"></script>

 <script type="text/javascript">
 google.load('visualization', '1', {packages: ['corechart', 'bar']});
 google.setOnLoadCallback(drawMaterial);

 function drawMaterial() {
 var data = google.visualization.arrayToDataTable([
 ['Region', 'New Customers', 'Old Customers'],
 <?php
 $query = "SELECT sum(new_customers) AS new, sum(old_customers) AS old, region FROM daily GROUP BY region";

 $exec = mysqli_query($con,$query);

 while($row = mysqli_fetch_array($exec)){

 echo "['".$row['region']."',";

 echo "['".$row['new']."',";

 echo "['".$row['old']."',";

 }
 ?>
 ]);

 var options = {

 title: 'Country wise new and returned visitors',

 bars: 'horizontal'
 };
 var material = new google.charts.Bar(document.getElementById('barchart'));
 material.draw(data, options);
 }
 </script>
</code>```

答:
The problem you are having is that the chart is not taking the three parameters in the data variable.
At the moment you have it like: ['Region', 'New Customers', 'Old Customers'],.

Change it to:  ['Region', 'New Customers'],.

In the while loop, PHP is not recognising any column with the name $row['new'] or $row['old']. Instead use indexes and change your echo to:
echo "['".$row[2]." [".$row[0]."]', ".$row[1]."],";

I would also recommend you to have the sql query outside the function and have only the iteration through the sql results (the while loop with the echo).

Also, you were not loading the charts properly. You forgot to add the word 'charts':

```<code>  google.charts.load('visualization', '1', {packages: ['corechart', 'bar']});
  google.charts.setOnLoadCallback(drawMaterial);
</code>```

This is the final solution:

```<code><?php
include("YOUR PHP CONNECT FILE");

$query = "SELECT sum(new_customers) AS new, sum(old_customers) AS old, region FROM daily GROUP BY region";
$exec = mysqli_query($YOURCONNECTIONVARIABLE ,$query);

?>

<!DOCTYPE html>
  <head>
    <script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
    <script type="text/javascript">
      google.charts.load('visualization', '1', {packages: ['corechart', 'bar']});
      google.charts.setOnLoadCallback(drawMaterial);

       function drawMaterial() {
       var data = google.visualization.arrayToDataTable([
       ['Region', 'New Customers'],
        <?php
          while($row = mysqli_fetch_array($exec)){
            echo "['".$row[2]." [".$row[0]."]', ".$row[1]."],";
          }
        ?>
        ]);

        var options = {
          title: 'Country wise new and returned visitors',
          bars: 'horizontal'
        };

        var material = new google.charts.Bar(document.getElementById('barchart'));
          material.draw(data, options);
        }
    </script>
</head>
<body>
    <div id="barchart" style="width: 100%; height: 40em;"></div>
</body>
</html>
</code>```

Let me know if you have any questions.

Title: Google Bar Chart from Mysql Database

Body:
The problem you are having is that the chart is not taking the three parameters in the data variable.
At the moment you have it like: ['Region', 'New Customers', 'Old Customers'],.

Change it to:  ['Region', 'New Customers'],.

In the while loop, PHP is not recognising any column with the name $row['new'] or $row['old']. Instead use indexes and change your echo to:
echo "['".$row[2]." [".$row[0]."]', ".$row[1]."],";

I would also recommend you to have the sql query outside the function and have only the iteration through the sql results (the while loop with the echo).

Also, you were not loading the charts properly. You forgot to add the word 'charts':

  google.charts.load('visualization', '1', {packages: ['corechart', 'bar']});
  google.charts.setOnLoadCallback(drawMaterial);

This is the final solution:

<?php
include("YOUR PHP CONNECT FILE");

$query = "SELECT sum(new_customers) AS new, sum(old_customers) AS old, region FROM daily GROUP BY region";
$exec = mysqli_query($YOURCONNECTIONVARIABLE ,$query);

?>

<!DOCTYPE html>
  <head>
    <script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
    <script type="text/javascript">
      google.charts.load('visualization', '1', {packages: ['corechart', 'bar']});
      google.charts.setOnLoadCallback(drawMaterial);

       function drawMaterial() {
       var data = google.visualization.arrayToDataTable([
       ['Region', 'New Customers'],
        <?php
          while($row = mysqli_fetch_array($exec)){
            echo "['".$row[2]." [".$row[0]."]', ".$row[1]."],";
          }
        ?>
        ]);

        var options = {
          title: 'Country wise new and returned visitors',
          bars: 'horizontal'
        };

        var material = new google.charts.Bar(document.getElementById('barchart'));
          material.draw(data, options);
        }
    </script>
</head>
<body>
    <div id="barchart" style="width: 100%; height: 40em;"></div>
</body>
</html>

Let me know if you have any questions.


问:
Linking against multiple shared libraries that all linked against a common static library
Say you have 2 share libraries, lib1.so and lib2.so, that both have libcommon.a statically linked into them. Would the compiler complain about ambiguous symbol reference if you were to dynamically link both lib1.so and lib2.so? Or would be the compiler be smart enough to know libcommon symbols are shared between lib1 and lib2 and allow you to dynamically link against both?</p>

答:
Suppose the two shared libraries linked with the different static libraries. But the static libraries both contain a function with the same name. There would be conflict.

I'm sure of that because I have a tcl/tk application, it load two tcl libraries(.so). Both of the libraries are static linked with the openssl library. but with different version.
A segmentation fault occurred when I run the tcl application. I trace it into the openssl. There is a function implementation changed in the new version.


问:
r as.Date switching my year and month
I have a character string that is a date (month, day, year).

```<code>char <- "12/1/2014"
</code>```

When I try to turn this character string into a date, and I specify month,day, year

```<code>date <- as.Date(char, origin = "%m/%d/%Y")
</code>```

it formats it like I put in year, day, month:

```<code>> date
[1] "0012-01-20"
</code>```

What am I missing?

答:
You need to specify the format using the format argument, not the origin argument.

```<code>(date <- as.Date("12/1/2014", format = "%m/%d/%Y"))
[1] "2014-12-01"
</code>```

Title: r as.Date switching my year and month

Body:
I have a character string that is a date (month, day, year).

char <- "12/1/2014"

When I try to turn this character string into a date, and I specify month,day, year

date <- as.Date(char, origin = "%m/%d/%Y")

it formats it like I put in year, day, month:

> date
[1] "0012-01-20"

What am I missing?

Body:
You need to specify the format using the format argument, not the origin argument.

(date <- as.Date("12/1/2014", format = "%m/%d/%Y"))
[1] "2014-12-01"


问:
Cannot get Google Map to display on MEAN app
I am trying to simply get a Google Map to display in a MEAN stack app. If I just run the index.html file, it works; however, when I run the app, the map does not display at all. Is there an error in my code or have I not installed the right packages in order to display the map?

https://github.com/tayrembos/Nav/blob/master/index.html

UPDATE: full code
https://github.com/sammymhowe/NavSpot/blob/master/packages/custom/NavSpot/public/views/system/index.html

答: Check if the google map is rendered in the elements panel. If map related dom(that google renders to div) is there then it might be css issue. Also check console for any other errors.</p>


问:
Add elements to sub-array recursively
I'm trying to add elements to a sub array of the sub array where they were added in the previous iteration, i.e. transforming this:

```<code>$a = array('a', 'b', 'c');
</code>```

Into this:

```<code>$new_array = array(
    'a' => array(
        'b' => array(
            'c' => array()
        )
    )
);
</code>```

答:
Similar to @aibs solution.

```<code><?php

function splitIntoSubArray($array) {
  return $array ? array(array_shift($array) => splitIntoSubArray($array)) : array();
}

$a = array('a', 'b', 'c');

print_r(splitIntoSubArray($a));
</code>```

Output:

```<code>Array
(
    [a] => Array
        (
            [b] => Array
                (
                    [c] => Array
                        (
                        )

                )

        )

)
</code>```

Title: Add elements to sub-array recursively

Body:
I'm trying to add elements to a sub array of the sub array where they were added in the previous iteration, i.e. transforming this:

$a = array('a', 'b', 'c');

Into this:

$new_array = array(
    'a' => array(
        'b' => array(
            'c' => array()
        )
    )
);

Body:
Similar to @aibs solution.

<?php

function splitIntoSubArray($array) {
  return $array ? array(array_shift($array) => splitIntoSubArray($array)) : array();
}

$a = array('a', 'b', 'c');

print_r(splitIntoSubArray($a));

Output:

Array
(
    [a] => Array
        (
            [b] => Array
                (
                    [c] => Array
                        (
                        )

                )

        )

)


问:
Parsing a JSON date into a C# DateTime
i have an API that get information from targetProcess and put that information in sql tables.

the issue comes when a targetProcess field is date because i recieved it as json date "/Date(1409202000000-0500 )/".

How can i convert this json date to Datetime in c#?

i have been trying add extra quotes like the asnwer in this StackOverflow Post but it doesnt work.

i tried replace the the word Date for only use 1409202000000-0500 in

```<code>DateTime dotNetDate = new DateTime(1970, 1, 1);
dotNetDate = dotNetDate.AddMilliseconds(Convert.ToInt64(1409202000000-0500)
</code>```

i use too JSON.NET as bellow

```<code>string sa = "/Date(1409202000000-0500 )/"
DateTime dt = new DateTime();
dt = JsonConvert.DeserializeObject<DateTime>(sa);
</code>```

but it doesnt work too,

so the question is....How can i convert this json date to Datetime in c#?

答:
The issue is with your date string.
instead of

```<code>string sa = "/Date(1409202000000-0500 )/"
</code>```

try

```<code>string sa = @"""/Date(1409202000000-0500)/""";
</code>```

Change your code :

```<code> string sa = @"""/Date(1409202000000-0500)/""";
            DateTime dt = new DateTime();
            dt = JsonConvert.DeserializeObject<DateTime>(sa);
            // dt = "2014-08-28 3.00.00 PM"
</code>```

Title: Parsing a JSON date into a C# DateTime

Body:
i have an API that get information from targetProcess and put that information in sql tables.

the issue comes when a targetProcess field is date because i recieved it as json date "/Date(1409202000000-0500 )/".

How can i convert this json date to Datetime in c#?

i have been trying add extra quotes like the asnwer in this StackOverflow Post but it doesnt work.

i tried replace the the word Date for only use 1409202000000-0500 in

DateTime dotNetDate = new DateTime(1970, 1, 1);
dotNetDate = dotNetDate.AddMilliseconds(Convert.ToInt64(1409202000000-0500)

i use too JSON.NET as bellow

string sa = "/Date(1409202000000-0500 )/"
DateTime dt = new DateTime();
dt = JsonConvert.DeserializeObject<DateTime>(sa);

but it doesnt work too,

so the question is....How can i convert this json date to Datetime in c#?

Body:
The issue is with your date string.
instead of

string sa = "/Date(1409202000000-0500 )/"

try

string sa = @"""/Date(1409202000000-0500)/""";

Change your code :

 string sa = @"""/Date(1409202000000-0500)/""";
            DateTime dt = new DateTime();
            dt = JsonConvert.DeserializeObject<DateTime>(sa);
            // dt = "2014-08-28 3.00.00 PM"


问:
Deploying a node.js application with Bluemix
I am trying to deploy a simple node.js application with the new Kubernetes support in Bluemix. When I run the container I made, I get a ImagePullBackOff error, which means it can't pull down the image.

NAME                                  READY     STATUS             RESTARTS   AGE
hello-node-2399519400-6m8dz           0/1       ImagePullBackOff   0          13m```
</div>
</div>
</p>

<p>My Docker image uses the node.js base image.</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code>FROM node:6.9.2
EXPOSE 8080
COPY server.js .
CMD node server.js</code>```

I deployed using:

docker build -t hello-node:v1 .
kubectl run hello-node --image=hello-node:v1 --port=8080```

I am thinking that Bluemix can't pull down the node.js image, but I am not certain.

答:
I see the docker build of the image, and I'm presuming that you're using the kubectl with the exported cluster config (bx cs cluster-config ...), so that it's targetting your cluster.

Did you tag and push that image from your local docker into the bluemix registry, or to another remote registry that would be accessible from the container service?  (My apologies if this is obvious - just didn't see the step there to tag and push it to a registry that would be available).

Body:
I am trying to deploy a simple node.js application with the new Kubernetes support in Bluemix. When I run the container I made, I get a ImagePullBackOff error, which means it can't pull down the image.

NAME                                  READY     STATUS             RESTARTS   AGE
hello-node-2399519400-6m8dz           0/1       ImagePullBackOff   0          13m

My Docker image uses the node.js base image.

FROM node:6.9.2
EXPOSE 8080
COPY server.js .
CMD node server.js

I deployed using:

docker build -t hello-node:v1 .
kubectl run hello-node --image=hello-node:v1 --port=8080

I am thinking that Bluemix can't pull down the node.js image, but I am not certain.


问:
Parse json file in U-SQL
I'm trying to parse below Json file using USQL but keep getting error.

```<code>Json file@

{"dimBetType_SKey":1,"BetType_BKey":1,"BetTypeName":"Test1"}
{"dimBetType_SKey":2,"BetType_BKey":2,"BetTypeName":"Test2"}
{"dimBetType_SKey":3,"BetType_BKey":3,"BetTypeName":"Test3"}
</code>```

Below is the USQL script, I'm trying to extract the data from above file.

```<code>    REFERENCE ASSEMBLY [Newtonsoft.Json];
    REFERENCE ASSEMBLY [Microsoft.Analytics.Samples.Formats];

DECLARE @Full_Path string =
"adl://xxxx.azuredatalakestore.net/2017/03/28/00_0_66ffdd26541742fab57139e95080e704.json";

DECLARE @Output_Path = "adl://xxxx.azuredatalakestore.net/Output/Output.csv";

@logSchema =
EXTRACT dimBetType_SKey int
FROM @Full_Path
USING new Microsoft.Analytics.Samples.Formats.Json.JsonExtractor();

OUTPUT @logSchema
TO @Output_Path
USING Outputters.Csv();
</code>```

But the USQL is keep failing with Vertex error

Any help?

答:
For you information, ADF can help you easily copy from JSON(JSON Format) to be CSV(Text Format). Instructions can be referred from:
https://learn.microsoft.com/en-us/azure/data-factory/data-factory-faq#specifying-formats

Copy wizard can help you preview the data and set up the pipeline via UI.
https://learn.microsoft.com/en-us/azure/data-factory/data-factory-copy-data-wizard-tutorial

Title: Parse json file in U-SQL

Body:
I'm trying to parse below Json file using USQL but keep getting error.

Json file@

{"dimBetType_SKey":1,"BetType_BKey":1,"BetTypeName":"Test1"}
{"dimBetType_SKey":2,"BetType_BKey":2,"BetTypeName":"Test2"}
{"dimBetType_SKey":3,"BetType_BKey":3,"BetTypeName":"Test3"}

Below is the USQL script, I'm trying to extract the data from above file.

    REFERENCE ASSEMBLY [Newtonsoft.Json];
    REFERENCE ASSEMBLY [Microsoft.Analytics.Samples.Formats];

DECLARE @Full_Path string =
"adl://xxxx.azuredatalakestore.net/2017/03/28/00_0_66ffdd26541742fab57139e95080e704.json";

DECLARE @Output_Path = "adl://xxxx.azuredatalakestore.net/Output/Output.csv";

@logSchema =
EXTRACT dimBetType_SKey int
FROM @Full_Path
USING new Microsoft.Analytics.Samples.Formats.Json.JsonExtractor();

OUTPUT @logSchema
TO @Output_Path
USING Outputters.Csv();

But the USQL is keep failing with Vertex error

Any help?


问:
Join year and julian day as a date column in R and plot it
I have some data with a column for the day of the year and another for year. As example, let's think in this dummy data:

```<code>temp <- rep(runif(730,15,40))
doy <- rep(c(1:365),2)
year <- c(rep(2015,365), rep(2016,365))
</code>```

I would like to join doy and year as a date column (2015-365 format). Is it possible to deal with this date format? How ggplot or the basic function plot deal with it?

答:
To convert a Julian date to a Date object use the %j format.  For example:</p>

```<code>temp <- rep(runif(730,15,40))
doy <- rep(c(1:365),2)
year <- c("2015","2016")

jdate<-as.Date(paste(year, doy, sep="-"),"%Y-%j")
df<- data.frame(jdate, temp)

library(ggplot2)
f<-ggplot(df, aes(x=jdate, y=temp))
f+ geom_point() + scale_x_date(date_breaks="6 week", date_labels="%Y-%j")
</code>```

Body:
I have some data with a column for the day of the year and another for year. As example, let's think in this dummy data:

temp <- rep(runif(730,15,40))
doy <- rep(c(1:365),2)
year <- c(rep(2015,365), rep(2016,365))

I would like to join doy and year as a date column (2015-365 format). Is it possible to deal with this date format? How ggplot or the basic function plot deal with it?

Body:
To convert a Julian date to a Date object use the %j format.  For example:

temp <- rep(runif(730,15,40))
doy <- rep(c(1:365),2)
year <- c("2015","2016")

jdate<-as.Date(paste(year, doy, sep="-"),"%Y-%j")
df<- data.frame(jdate, temp)

library(ggplot2)
f<-ggplot(df, aes(x=jdate, y=temp))
f+ geom_point() + scale_x_date(date_breaks="6 week", date_labels="%Y-%j")


问:
Need help to post multipart form data using the post method in VBA
I am trying to use an API to update an online database.

The API is hosted by a french site and the usage details are slim with no examples.

This is the information they have provided

```<code>The query must be sent as a "multipart / form-data" html form using the "POST" method.
Input parameters:
ssid : (type "text") user's ScreenScraper identifier
sspassword : (type "text") ScreenScraper password of the user
gameid : (type "text") numerical identifier of the game on ScreenScraper
or
romid ( "text") numeric ID of the Roma on ScreenScraper

to propose a textual info:
modiftypeinfo ( "text") type of information sent (see list "modiftypeinfo")
modifregion ( "text"

<html>
  <head>
  <META http-equiv="Content-Type" content="text/html; charset=UTF-8">
  <META http-equiv="content-language" content="fr">
  <title></title>
  </head>
  <body>
    <form name="myform" id="myform" method="post" enctype="multipart/form-data" action="https://www.screenscraper.fr/api/botProposition.php?ssid=xxx&sspassword=yyy">
      <input type="text" name="gameid" value="3">
      <input type="text" name="modiftypeinfo" value="description">
      <input type="text" name="modifregion" value="">
      <input type="text" name="modiflangue" value="fr">
      <input type="text" name="modifversion" value="">
      <input type="text" name="modiftexte" value="ici, le synopsis du jeu ! ne pas valider, c'est un test ;)">
      <input type="text" name="modifsource" value="botProposition / source de l'info">
      <input type="submit" value="envoyer">
    </form>

  <script>
    document.getElementById("myform").submit();
    </script>

  </body>
</html>
</code>```

This is the code I have put together:

```<code>Sub Post_Detail()

    Dim xmlhttp As Object, response As String, SendString As String

    Set xmlhttp = CreateObject("MSXML2.XMLHTTP.6.0")

    '~~> Indicates that page that will receive the request and the type of request being submitted
    xmlhttp.Open "POST", "https://www.screenscraper.fr/api/botProposition.php?ssid=xxx&sspassword=yyy", False

    '~~> Indicate that the body of the request contains form data
    xmlhttp.setRequestHeader "Content-Type", "text/html; charset=UTF-8"
    xmlhttp.setRequestHeader "enctype", "multipart/form-data"

    '~~> Send the data as name/value pairs
    SendString = "&type=text&name=gameid&value=185882"
    SendString = SendString & "&type=text&name=modiftypeinfo&value=genres"
    SendString = SendString & "&type=text&name=modiftexte&value=Sports"
    SendString = SendString & "&type=submit&value=envoyer"
    Debug.Print SendString
    xmlhttp.send SendString

    response = xmlhttp.responseText
    MsgBox response

    Set xmlhttp = Nothing

End Sub
</code>```

I am not sure what to do with this part: form name="myform" id="myform" in the instructions and I am not sure if my request via building a string is even anywhere near correct.

You won't be able to run without a login, it will return a password invalid error.

答:
Untested:

```<code>Sub Post_Detail()

    Dim xmlhttp As Object, response As String, SendString As String

    Set xmlhttp = CreateObject("MSXML2.XMLHTTP.6.0")

    '~~> Indicates that page that will receive the request and the type of request being submitted
    xmlhttp.Open "POST", "https://www.screenscraper.fr/api/botProposition.php?ssid=xxx&sspassword=yyy", False

    '~~> Indicate that the body of the request contains form data
    xmlhttp.setRequestHeader "enctype", "multipart/form-data"

    '~~> Send the data as name/value pairs
    SendString = "gameid=185882" & _
                "&modiftypeinfo=genres" & _
                "&modiftexte=Sports"

    Debug.Print SendString
    xmlhttp.send SendString

    response = xmlhttp.responseText
    MsgBox response

    Set xmlhttp = Nothing

End Sub
</code>```

I don't think the submit button is included in the POST if it has no name attribute.

Body:
I am trying to use an API to update an online database.

The API is hosted by a french site and the usage details are slim with no examples.

This is the information they have provided

The query must be sent as a "multipart / form-data" html form using the "POST" method.
Input parameters:
ssid : (type "text") user's ScreenScraper identifier
sspassword : (type "text") ScreenScraper password of the user
gameid : (type "text") numerical identifier of the game on ScreenScraper
or
romid ( "text") numeric ID of the Roma on ScreenScraper

to propose a textual info:
modiftypeinfo ( "text") type of information sent (see list "modiftypeinfo")
modifregion ( "text"

  <META http-equiv="Content-Type" content="text/html; charset=UTF-8">
  <META http-equiv="content-language" content="fr">
  <title></title>

    <form name="myform" id="myform" method="post" enctype="multipart/form-data" action="https://www.screenscraper.fr/api/botProposition.php?ssid=xxx&sspassword=yyy">
      <input type="text" name="gameid" value="3">
      <input type="text" name="modiftypeinfo" value="description">
      <input type="text" name="modifregion" value="">
      <input type="text" name="modiflangue" value="fr">
      <input type="text" name="modifversion" value="">
      <input type="text" name="modiftexte" value="ici, le synopsis du jeu ! ne pas valider, c'est un test ;)">
      <input type="text" name="modifsource" value="botProposition / source de l'info">
      <input type="submit" value="envoyer">
    </form>

This is the code I have put together:

Sub Post_Detail()

    Dim xmlhttp As Object, response As String, SendString As String

    Set xmlhttp = CreateObject("MSXML2.XMLHTTP.6.0")

    '~~> Indicates that page that will receive the request and the type of request being submitted
    xmlhttp.Open "POST", "https://www.screenscraper.fr/api/botProposition.php?ssid=xxx&sspassword=yyy", False

    '~~> Indicate that the body of the request contains form data
    xmlhttp.setRequestHeader "Content-Type", "text/html; charset=UTF-8"
    xmlhttp.setRequestHeader "enctype", "multipart/form-data"

    '~~> Send the data as name/value pairs
    SendString = "&type=text&name=gameid&value=185882"
    SendString = SendString & "&type=text&name=modiftypeinfo&value=genres"
    SendString = SendString & "&type=text&name=modiftexte&value=Sports"
    SendString = SendString & "&type=submit&value=envoyer"
    Debug.Print SendString
    xmlhttp.send SendString

    response = xmlhttp.responseText
    MsgBox response

    Set xmlhttp = Nothing

End Sub

I am not sure what to do with this part: form name="myform" id="myform" in the instructions and I am not sure if my request via building a string is even anywhere near correct.

You won't be able to run without a login, it will return a password invalid error.

Body:
Untested:

Sub Post_Detail()

    Dim xmlhttp As Object, response As String, SendString As String

    Set xmlhttp = CreateObject("MSXML2.XMLHTTP.6.0")

    '~~> Indicates that page that will receive the request and the type of request being submitted
    xmlhttp.Open "POST", "https://www.screenscraper.fr/api/botProposition.php?ssid=xxx&sspassword=yyy", False

    '~~> Indicate that the body of the request contains form data
    xmlhttp.setRequestHeader "enctype", "multipart/form-data"

    '~~> Send the data as name/value pairs
    SendString = "gameid=185882" & _
                "&modiftypeinfo=genres" & _
                "&modiftexte=Sports"

    Debug.Print SendString
    xmlhttp.send SendString

    response = xmlhttp.responseText
    MsgBox response

    Set xmlhttp = Nothing

End Sub

I don't think the submit button is included in the POST if it has no name attribute.


问:
Django: translate in a different language than current language
I would like to notify the user in case he's viewing the site in a language that doesn't correspond to his first preference in the ACCEPT_LANGUAGE header.

For this reason I would like to present the message to the user in his first prefered language rather than the one he's currently viewing the web-site.

Is it possible with django (views and templates) to translate a string in a specific language indipendently than the current language?

Thanks

Example:

Italian user visits for the first time the site, but the english version.
I want him to see a message in italian like: "Preferiresti vedere il sito in Italiano?"

答: You might find some use in the functions activate(language) and deactivate(language) located in django.utils.translation. I'm not sure about the efficiency of this, I imagine it is slow, but it might do the job :)


问:
flexbox overflowing container in firefox
I'm working on a flexbox layout and I have an issue where the flex items will overflow the container in firefox only. Here's as stripped down an example as I could come up with (sorry it's not super minimal, I'm unsure what's causing the issue, so it's hard to know what I can remove):

```<code><div class="css-190tu11">
  <h1 class="css-1qqir8k">Blah</h1>
  <div class="css-131b9cy">
    <div class="css-1suni8j">
      <a class="css-yq2t95" href="some-url">
        <span class="icon icon-register css-nwymqb" aria-hidden="true"></span>
        <h2 class="css-1892n22">Title</h2>
        <div class="css-kgza95">Description</div>
      </a>
      <div class="css-kujdaf">
        Some special thing
      </div>
    </div>
    <div class="css-1suni8j">
      <a class="css-yq2t95" href="some-url">
        <span class="icon icon-register css-nwymqb" aria-hidden="true"></span>
        <h2 class="css-1892n22">Title</h2>
        <div class="css-kgza95">Description</div>
      </a>
      <div class="css-dkez8"></div>
    </div>
    <div class="css-1suni8j">
      <a class="css-yq2t95" href="some-url">
        <span class="icon icon-register css-nwymqb" aria-hidden="true"></span>
        <h2 class="css-1892n22">Title</h2>
        <div class="css-kgza95">Description</div>
      </a>
      <div class="css-dkez8"></div>
    </div>
    <div class="css-1suni8j">
      <a class="css-yq2t95" href="some-url">
        <span class="icon icon-register css-nwymqb" aria-hidden="true"></span>
        <h2 class="css-1892n22">Title</h2>
        <div class="css-kgza95">Description</div>
      </a>
      <div class="css-dkez8"></div
    </div>
  </div>
</div>
</code>```

And the CSS:

```<code>.css-190tu11,
[data-css-190tu11] {
  padding: 12px 48px 24px 48px;
  border: solid 1px #e0e0e0;
}
.css-1qqir8k,
[data-css-1qqir8k] {
  font-size: 24px;
  font-weight: 300;
  margin-bottom: 18px;
  margin-top: 0;
}
.css-131b9cy,
[data-css-131b9cy] {
  display: flex;
  justify-content: space-around;
  flex-wrap: wrap;
}
.css-131b9cy > *,
[data-css-131b9cy] > * {
  flex: 0 1 auto;
  margin-left: 0;
  margin-right: 0;
}
.css-131b9cy > *:not(:first-child),
[data-css-131b9cy] > *:not(:first-child) {
  margin-left: 10px;
}
.css-131b9cy > *:not(:last-child),
[data-css-131b9cy] > *:not(:last-child) {
  margin-right: 10px;
}

.css-1suni8j,
[data-css-1suni8j] {
  display: flex;
  background-color: white;
  flex-direction: column;
  justify-content: space-between;
  text-align: center;
  max-width: 186px;
  min-width: 120px;
  height: 240px;
}
.css-1suni8j > *,
[data-css-1suni8j] > * {
  margin-top: 0;
  margin-bottom: 0;
}
.css-1suni8j > *:not(:first-child),
[data-css-1suni8j] > *:not(:first-child) {
  margin-top: 10px;
}
.css-1suni8j > *:not(:last-child),
[data-css-1suni8j] > *:not(:last-child) {
  margin-bottom: 10px;
}

.css-yq2t95,
[data-css-yq2t95] {
  flex: 1;
  justify-content: space-between;
  flex-direction: column;
  display: flex;
}
.css-yq2t95 > *:last-child,
[data-css-yq2t95] > *:last-child {
  flex: 0 1 auto;
}
.css-yq2t95 > *,
[data-css-yq2t95] > * {
  margin-top: 0;
  margin-bottom: 0;
}
.css-yq2t95 > *:not(:first-child),
[data-css-yq2t95] > *:not(:first-child) {
  margin-top: 5px;
}
.css-yq2t95 > *:not(:last-child),
[data-css-yq2t95] > *:not(:last-child) {
  margin-bottom: 5px;
}

.css-nwymqb,
[data-css-nwymqb] {
  transition: all 0.5s ease;
  border-radius: 50%;
  display: block;
  margin-left: auto;
  border: 1px solid #0070ba;
  height: 60px;
  width: 60px;
  font-size: 30px;
  line-height: 54px;
  margin-right: auto;
}

.css-1892n22,
[data-css-1892n22] {
  font-weight: normal;
  flex: 0 1 auto;
  color: inherit;
  padding: 0;
  font-size: 16px;
  height: 80px;
}
.css-kgza95,
[data-css-kgza95] {
  font-weight: normal;
  font-size: 11px;
  color: #333333;
  height: 76px;
}
.css-kujdaf,
[data-css-kujdaf] {
  min-height: 36px;
  background-image: linear-gradient(93deg, #1446a0, #0070ba);
  width: 100%;
  color: white;
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 10px;
}
.css-dkez8,
[data-css-dkez8] {
  min-height: 36px;
}
</code>```

Here's what it looks like in Chrome and Safari (this is what I want it to look like):

And here's what it looks like in Firefox:

Even Internet Explorer 10 shows it the way I want! (Can't verify in the codepen because I removed vendor prefixes, but it works in my app).

Here's a codepen for this.

Thanks for any help!

答: Turns out that the element that is overflowing needs to have a min-height: 0 on it. I'm not sure why, but by putting that on .css-yq2t95 everything's working nicely. Thanks everyone for pitching in!

Body:
I'm working on a flexbox layout and I have an issue where the flex items will overflow the container in firefox only. Here's as stripped down an example as I could come up with (sorry it's not super minimal, I'm unsure what's causing the issue, so it's hard to know what I can remove):

Blah

Title

Description

        Some special thing

Title

Description

Title

Description

Title

Description

</div

And the CSS:

.css-190tu11,
[data-css-190tu11] {
  padding: 12px 48px 24px 48px;
  border: solid 1px #e0e0e0;
}
.css-1qqir8k,
[data-css-1qqir8k] {
  font-size: 24px;
  font-weight: 300;
  margin-bottom: 18px;
  margin-top: 0;
}
.css-131b9cy,
[data-css-131b9cy] {
  display: flex;
  justify-content: space-around;
  flex-wrap: wrap;
}
.css-131b9cy > *,
[data-css-131b9cy] > * {
  flex: 0 1 auto;
  margin-left: 0;
  margin-right: 0;
}
.css-131b9cy > *:not(:first-child),
[data-css-131b9cy] > *:not(:first-child) {
  margin-left: 10px;
}
.css-131b9cy > *:not(:last-child),
[data-css-131b9cy] > *:not(:last-child) {
  margin-right: 10px;
}

.css-1suni8j,
[data-css-1suni8j] {
  display: flex;
  background-color: white;
  flex-direction: column;
  justify-content: space-between;
  text-align: center;
  max-width: 186px;
  min-width: 120px;
  height: 240px;
}
.css-1suni8j > *,
[data-css-1suni8j] > * {
  margin-top: 0;
  margin-bottom: 0;
}
.css-1suni8j > *:not(:first-child),
[data-css-1suni8j] > *:not(:first-child) {
  margin-top: 10px;
}
.css-1suni8j > *:not(:last-child),
[data-css-1suni8j] > *:not(:last-child) {
  margin-bottom: 10px;
}

.css-yq2t95,
[data-css-yq2t95] {
  flex: 1;
  justify-content: space-between;
  flex-direction: column;
  display: flex;
}
.css-yq2t95 > *:last-child,
[data-css-yq2t95] > *:last-child {
  flex: 0 1 auto;
}
.css-yq2t95 > *,
[data-css-yq2t95] > * {
  margin-top: 0;
  margin-bottom: 0;
}
.css-yq2t95 > *:not(:first-child),
[data-css-yq2t95] > *:not(:first-child) {
  margin-top: 5px;
}
.css-yq2t95 > *:not(:last-child),
[data-css-yq2t95] > *:not(:last-child) {
  margin-bottom: 5px;
}

.css-nwymqb,
[data-css-nwymqb] {
  transition: all 0.5s ease;
  border-radius: 50%;
  display: block;
  margin-left: auto;
  border: 1px solid #0070ba;
  height: 60px;
  width: 60px;
  font-size: 30px;
  line-height: 54px;
  margin-right: auto;
}

.css-1892n22,
[data-css-1892n22] {
  font-weight: normal;
  flex: 0 1 auto;
  color: inherit;
  padding: 0;
  font-size: 16px;
  height: 80px;
}
.css-kgza95,
[data-css-kgza95] {
  font-weight: normal;
  font-size: 11px;
  color: #333333;
  height: 76px;
}
.css-kujdaf,
[data-css-kujdaf] {
  min-height: 36px;
  background-image: linear-gradient(93deg, #1446a0, #0070ba);
  width: 100%;
  color: white;
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 10px;
}
.css-dkez8,
[data-css-dkez8] {
  min-height: 36px;
}

Here's what it looks like in Chrome and Safari (this is what I want it to look like):

And here's what it looks like in Firefox:

Even Internet Explorer 10 shows it the way I want! (Can't verify in the codepen because I removed vendor prefixes, but it works in my app).

Here's a codepen for this.

Thanks for any help!


问:
Why is a string function in sql useful?
I can't for the life of me figure out what good a string function in SQL can possibly do. I realize that the queries that I'm working from in the book are purely for exercise so the questions are arbitrary, but for example:

```<code>select substring('San Antonio, TX', 5,3);
</code>```

Why couldn't you get the same results to this query with a regular Select statement and a Wildcard,  and what possible good could it do to find three letters starting at the fifth letter of a string? In short: what are string functions actually GOOD for in a practical sense? Can anyone give me some examples? Thank you.

答:
I think there are two parts to your question: what use are functions at all, and, in particular, the substring.

In general, it is important that in a database you store things in their simplest form, and never store duplicated or dependent data. The latter principal means that if one column is any way related to another, then the design is wrong.

For example, you should store, say the given name and the family name, but you should not store the full name as well — that can be derived. Similarly, you might store the date of birth, but not the age, since that again can be derived.

String functions are useful for deriving data from simpler strings.

In particular, the substring function is used toe extract part of a string. If you have a string which is complex, it may be necessary to break it up into smaller components. This is especially useful for things like product codes or some types of serial codes which are really made up of sections.

substring is not directly useful for strings which contain varying parts. If they do, then you will need to combine them with something more complex.

Having said that, in a well-designed database there is little real need for the substring function. If the data is really a combination of parts, then it should already have been broken into separate columns. This the principle of atomicity, ensuring that each item of data is the smallest unit.

In your example, the string should have been in 2 separate columns, for town and state, so there is no further need to extract anything from it.

Title: Why is a string function in sql useful?

Body:
I can't for the life of me figure out what good a string function in SQL can possibly do. I realize that the queries that I'm working from in the book are purely for exercise so the questions are arbitrary, but for example:

select substring('San Antonio, TX', 5,3);

Why couldn't you get the same results to this query with a regular Select statement and a Wildcard,  and what possible good could it do to find three letters starting at the fifth letter of a string? In short: what are string functions actually GOOD for in a practical sense? Can anyone give me some examples? Thank you.


问:
CNTK python API: Dynamic Axis construction for CNN+LSTM-Network
I'm working on a Regression problem on video/image sequence input with CNTK Python API.
Input data is a (minibatch_size x sequence_length x channel x height x width)-tensor with (at this time) fixed minibatch_size = 1, sequence_length = 3 and only 1 channel. Output data is a (minibatch_size x sequence_length x num_landmarks) tensor with exactly the same sequence length. A CNN+LSTM network then analyzes one video frame and outputs 26 landmarks.
My network is defined as follows:

```<code>def create_network_definition(model_func):

    # define dynamic axes
    batch_axis = Axis.default_batch_axis()
    input_seq_axis = Axis('inputAxis')
    label_seq_axis = Axis('labelAxis')

    # construct input variables
    input_dynamic_axes = [batch_axis, input_seq_axis]
    input_var = input_variable(shape=(video_channel_count, video_height, video_width), dynamic_axes=input_dynamic_axes, dtype=np.float32)

    label_dynamic_axes = [batch_axis, label_seq_axis]
    label_var = input_variable(shape=(num_landmarks), dynamic_axes=label_dynamic_axes, dtype=np.float32)

    # instantiate 2D Convolution network
    z = model_func(input_var, out_dims = num_landmarks)

    # loss and metric
    loss = squared_error(z, label_var)
    error = sqrt(constant(1/num_landmarks) * loss)

    return {
        'input'  : input_var,
        'label'  : label_var,
        'loss'   : loss,
        'error'  : error,
        'output' : z
    }
</code>```

This envokes following error:

```<code>Training so far unspecified number of parameters in 7 parameter tensors.
Traceback (most recent call last):
  File "Conv2D_300VW_v1.py", line 490, in <module>
    gen_heartbeat      = False)
  File "Conv2D_300VW_v1.py", line 457, in do_training_and_validation
    trainer = create_trainer(network, epoch_size, max_epochs, minibatch_size, progress_printer)
  File "Conv2D_300VW_v1.py", line 357, in create_trainer
    learner  = momentum_sgd(network['output'].parameters, lr_schedule, mm_schedule) #, l2_regularization_weight=l2_reg_weight)
  File "C:\local\Anaconda3-4.1.1-Windows-x86_64\envs\cntk-py35\lib\site-packages\cntk\internal\swig_helper.py", line 63, in wrapper
    result = f(*args, **kwds)
  File "C:\local\Anaconda3-4.1.1-Windows-x86_64\envs\cntk-py35\lib\site-packages\cntk\learners\__init__.py", line 499, in momentum_sgd
    additional_options)
ValueError: Cannot create an NDArrayView using a view shape '[? x 26]' that has unknown dimensions for any of its axes.

[CALL STACK]
    > CNTK::NDArrayView::  DeepClone
    - CNTK::NDArrayView::NDArrayView<double>
    - CNTK::NDArrayView::  NDArrayView
    - CNTK::Value::  GetSequenceStartsAndLengths
    - CNTK::Value::  GetSequenceStartsAndLengths
    - CNTK::Variable::operator std::shared_ptr<CNTK::Function>
    - CNTK::Value::  GetSequenceStartsAndLengths
    - RtlRunOnceExecuteOnce
    - InitOnceExecuteOnce
    - _crtInitOnceExecuteOnce
    - CNTK::Value::  GetSequenceStartsAndLengths
    - CNTK::Variable::  Value
    - CNTK::Internal::  SaveAsLegacyModel
    - CNTK::  AdamLearner
    - CNTK::Internal::  ZeroesWithDynamicAxesLike
    - CNTK::Internal::  ZeroesWithDynamicAxesLike
</code>```

I suspect that the learner fails to get the batch size and the sequence size from the data. But why? How do I have to implement the dynamic axes correctly? I cannot find any hint in CNTK documentation.

I also tried setting both dynamic_axes=input_dynamic_axes as well as input_seq_axis = Axis.default_dynamic_axis() but nothing changed.

答:
input and label dynamic axis need to be the same. As follow:</p>

```<code>input_dynamic_axes = [batch_axis, input_seq_axis]
label_dynamic_axes = [batch_axis, input_seq_axis]
</code>```

Body:
I'm working on a Regression problem on video/image sequence input with CNTK Python API.
Input data is a (minibatch_size x sequence_length x channel x height x width)-tensor with (at this time) fixed minibatch_size = 1, sequence_length = 3 and only 1 channel. Output data is a (minibatch_size x sequence_length x num_landmarks) tensor with exactly the same sequence length. A CNN+LSTM network then analyzes one video frame and outputs 26 landmarks.
My network is defined as follows:

def create_network_definition(model_func):

    # define dynamic axes
    batch_axis = Axis.default_batch_axis()
    input_seq_axis = Axis('inputAxis')
    label_seq_axis = Axis('labelAxis')

    # construct input variables
    input_dynamic_axes = [batch_axis, input_seq_axis]
    input_var = input_variable(shape=(video_channel_count, video_height, video_width), dynamic_axes=input_dynamic_axes, dtype=np.float32)

    label_dynamic_axes = [batch_axis, label_seq_axis]
    label_var = input_variable(shape=(num_landmarks), dynamic_axes=label_dynamic_axes, dtype=np.float32)

    # instantiate 2D Convolution network
    z = model_func(input_var, out_dims = num_landmarks)

    # loss and metric
    loss = squared_error(z, label_var)
    error = sqrt(constant(1/num_landmarks) * loss)

    return {
        'input'  : input_var,
        'label'  : label_var,
        'loss'   : loss,
        'error'  : error,
        'output' : z
    }

This envokes following error:

Training so far unspecified number of parameters in 7 parameter tensors.
Traceback (most recent call last):
  File "Conv2D_300VW_v1.py", line 490, in <module>
    gen_heartbeat      = False)
  File "Conv2D_300VW_v1.py", line 457, in do_training_and_validation
    trainer = create_trainer(network, epoch_size, max_epochs, minibatch_size, progress_printer)
  File "Conv2D_300VW_v1.py", line 357, in create_trainer
    learner  = momentum_sgd(network['output'].parameters, lr_schedule, mm_schedule) #, l2_regularization_weight=l2_reg_weight)
  File "C:\local\Anaconda3-4.1.1-Windows-x86_64\envs\cntk-py35\lib\site-packages\cntk\internal\swig_helper.py", line 63, in wrapper
    result = f(*args, **kwds)
  File "C:\local\Anaconda3-4.1.1-Windows-x86_64\envs\cntk-py35\lib\site-packages\cntk\learners\__init__.py", line 499, in momentum_sgd
    additional_options)
ValueError: Cannot create an NDArrayView using a view shape '[? x 26]' that has unknown dimensions for any of its axes.

[CALL STACK]
    > CNTK::NDArrayView::  DeepClone
    - CNTK::NDArrayView::NDArrayView<double>
    - CNTK::NDArrayView::  NDArrayView
    - CNTK::Value::  GetSequenceStartsAndLengths
    - CNTK::Value::  GetSequenceStartsAndLengths
    - CNTK::Variable::operator std::shared_ptr<CNTK::Function>
    - CNTK::Value::  GetSequenceStartsAndLengths
    - RtlRunOnceExecuteOnce
    - InitOnceExecuteOnce
    - _crtInitOnceExecuteOnce
    - CNTK::Value::  GetSequenceStartsAndLengths
    - CNTK::Variable::  Value
    - CNTK::Internal::  SaveAsLegacyModel
    - CNTK::  AdamLearner
    - CNTK::Internal::  ZeroesWithDynamicAxesLike
    - CNTK::Internal::  ZeroesWithDynamicAxesLike

I suspect that the learner fails to get the batch size and the sequence size from the data. But why? How do I have to implement the dynamic axes correctly? I cannot find any hint in CNTK documentation.

I also tried setting both dynamic_axes=input_dynamic_axes as well as input_seq_axis = Axis.default_dynamic_axis() but nothing changed.

Body:
input and label dynamic axis need to be the same. As follow:

input_dynamic_axes = [batch_axis, input_seq_axis]
label_dynamic_axes = [batch_axis, input_seq_axis]

ContentLicense: CC BY-SA 4.0


问:
CheckedTextView doesn't respond to click
I have a listview that is dynamically populated with CheckedTextViews. The listview is set to multiple choice mode. I'm using OnItemClickListener to respond to clicks on my listview. Also I made an XML file with CheckedTextView's layout (actually it is just a copy of standard android.R.layout.simple_list_item_multiple_choice). So in this case all works fine: when I'm clicking an item in the listview, the appropriate checkedtextview becomes checked. But when I'm trying to use the following layout, the checkedtextview doesn't respond to the click and still unchecked.

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/ll"
    android:layout_height="wrap_content"
    android:layout_width="wrap_content"
    android:orientation="vertical"
    android:padding="5px">
    <CheckedTextView xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@android:id/text1"
        android:layout_width="fill_parent"
        android:layout_height="?android:attr/listPreferredItemHeight"
        android:gravity="center_vertical"
        android:drawableLeft="@drawable/checkbox_selector"
        android:paddingLeft="6dip"
        android:paddingRight="6dip"
        android:background="#00ffffff"
        android:textSize="15sp"
        android:singleLine="true"/>
</LinearLayout>
</code>```

I guess that it because CheckedTextViews are put into LinearLayout and they don't receive the click event from list items of the Listview.

答: This issue is caused by the attr singleLine = true. If you delete this or replace with maxLines = 1, it will work fine. Actually, the status is checked when you click on the item — I think it's an Android bug.

Body:
I have a listview that is dynamically populated with CheckedTextViews. The listview is set to multiple choice mode. I'm using OnItemClickListener to respond to clicks on my listview. Also I made an XML file with CheckedTextView's layout (actually it is just a copy of standard android.R.layout.simple_list_item_multiple_choice). So in this case all works fine: when I'm clicking an item in the listview, the appropriate checkedtextview becomes checked. But when I'm trying to use the following layout, the checkedtextview doesn't respond to the click and still unchecked.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/ll"
    android:layout_height="wrap_content"
    android:layout_width="wrap_content"
    android:orientation="vertical"
    android:padding="5px">
    <CheckedTextView xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@android:id/text1"
        android:layout_width="fill_parent"
        android:layout_height="?android:attr/listPreferredItemHeight"
        android:gravity="center_vertical"
        android:drawableLeft="@drawable/checkbox_selector"
        android:paddingLeft="6dip"
        android:paddingRight="6dip"
        android:background="#00ffffff"
        android:textSize="15sp"
        android:singleLine="true"/>
</LinearLayout>

I guess that it because CheckedTextViews are put into LinearLayout and they don't receive the click event from list items of the Listview.