问:
Handler()postDelay is unreachable for this Kotlin code, how to fix it?
I have a function, where I just explicitly want to delay the return value

```<code>private fun loadData(): DataModel? {
    Handler(Looper.getMainLooper()).postDelayed(
    when (fetchStyle) {
        FetchStyle.FETCH_SUCCESS -> return DataModel("Data Loaded")
        FetchStyle.FETCH_EMPTY -> return DataModel("")
        FetchStyle.FETCH_ERROR -> throw IllegalStateException("Error Fetching")
    }, 3000)
}
</code>```

However there's a warning state that postDelayed is unreachable, hence the 3s delay is not triggered.

To make it reachable, I have to add the extra parenthesis around

```<code>private fun loadData(): DataModel? {
    Handler(Looper.getMainLooper()).postDelayed({
    when (fetchStyle) {
        FetchStyle.FETCH_SUCCESS -> DataModel("Data Loaded")
        FetchStyle.FETCH_EMPTY -> DataModel("")
        FetchStyle.FETCH_ERROR -> throw IllegalStateException("Error Fetching")
    }}, 3000)
}
</code>```

But then, I can't return the DataModel value anymore. How could I fix this to have the delay of 3s, while I could still return the respective DataModel or throw the exception?

答:
If you just want to block the current thread, you can use Thread.sleep:

```<code>private fun loadData(): DataModel? {
    Thread.sleep(3000);
    return when (fetchStyle) {
        FetchStyle.FETCH_SUCCESS -> DataModel("Data Loaded")
        FetchStyle.FETCH_EMPTY -> DataModel("")
        FetchStyle.FETCH_ERROR -> throw IllegalStateException("Error Fetching")
    }
}
</code>```

An example for using Handler and Runnable instead, with a separate callback function:

```<code>private fun loadData(): DataModel? {
    Handler(Looper.getMainLooper()).postDelayed({
        val result = when (fetchStyle) {
            FetchStyle.FETCH_SUCCESS -> DataModel("Data Loaded")
            FetchStyle.FETCH_EMPTY -> DataModel("")
            FetchStyle.FETCH_ERROR -> throw IllegalStateException("Error Fetching")
        }
        loadDataCallback(result)
    }, 3000)
}

fun useLoadData() {
    loadData()
}

private fun loadDataCallback(dataModel: DataModel?) {
    // use result here
}
</code>```

A more Kotlin-like approach, passing a function as the callback:

```<code>private fun loadData(callback: (DataModel?) -> Unit): DataModel? {
    Handler(Looper.getMainLooper()).postDelayed({
        val result = when (fetchStyle) {
            FetchStyle.FETCH_SUCCESS -> DataModel("Data Loaded")
            FetchStyle.FETCH_EMPTY -> DataModel("")
            FetchStyle.FETCH_ERROR -> throw IllegalStateException("Error Fetching")
        }
        callback(result)
    }, 3000)
}

fun useLoadData() {
    loadData { dataModel ->
        // use result here
    }
}
</code>```

Note that these examples don't block any threads, and the Handler(Looper.getMainLooper()) part of your original example code (that I kept for these examples) will place the execution of the when statement as well as the callbacks after that back on the main thread.

Body:
I have a function, where I just explicitly want to delay the return value

private fun loadData(): DataModel? {
    Handler(Looper.getMainLooper()).postDelayed(
    when (fetchStyle) {
        FetchStyle.FETCH_SUCCESS -> return DataModel("Data Loaded")
        FetchStyle.FETCH_EMPTY -> return DataModel("")
        FetchStyle.FETCH_ERROR -> throw IllegalStateException("Error Fetching")
    }, 3000)
}

However there's a warning state that postDelayed is unreachable, hence the 3s delay is not triggered.

To make it reachable, I have to add the extra parenthesis around

private fun loadData(): DataModel? {
    Handler(Looper.getMainLooper()).postDelayed({
    when (fetchStyle) {
        FetchStyle.FETCH_SUCCESS -> DataModel("Data Loaded")
        FetchStyle.FETCH_EMPTY -> DataModel("")
        FetchStyle.FETCH_ERROR -> throw IllegalStateException("Error Fetching")
    }}, 3000)
}

But then, I can't return the DataModel value anymore. How could I fix this to have the delay of 3s, while I could still return the respective DataModel or throw the exception?

Body:
If you just want to block the current thread, you can use Thread.sleep:

private fun loadData(): DataModel? {
    Thread.sleep(3000);
    return when (fetchStyle) {
        FetchStyle.FETCH_SUCCESS -> DataModel("Data Loaded")
        FetchStyle.FETCH_EMPTY -> DataModel("")
        FetchStyle.FETCH_ERROR -> throw IllegalStateException("Error Fetching")
    }
}

An example for using Handler and Runnable instead, with a separate callback function:

private fun loadData(): DataModel? {
    Handler(Looper.getMainLooper()).postDelayed({
        val result = when (fetchStyle) {
            FetchStyle.FETCH_SUCCESS -> DataModel("Data Loaded")
            FetchStyle.FETCH_EMPTY -> DataModel("")
            FetchStyle.FETCH_ERROR -> throw IllegalStateException("Error Fetching")
        }
        loadDataCallback(result)
    }, 3000)
}

fun useLoadData() {
    loadData()
}

private fun loadDataCallback(dataModel: DataModel?) {
    // use result here
}

A more Kotlin-like approach, passing a function as the callback:

private fun loadData(callback: (DataModel?) -> Unit): DataModel? {
    Handler(Looper.getMainLooper()).postDelayed({
        val result = when (fetchStyle) {
            FetchStyle.FETCH_SUCCESS -> DataModel("Data Loaded")
            FetchStyle.FETCH_EMPTY -> DataModel("")
            FetchStyle.FETCH_ERROR -> throw IllegalStateException("Error Fetching")
        }
        callback(result)
    }, 3000)
}

fun useLoadData() {
    loadData { dataModel ->
        // use result here
    }
}

Note that these examples don't block any threads, and the Handler(Looper.getMainLooper()) part of your original example code (that I kept for these examples) will place the execution of the when statement as well as the callbacks after that back on the main thread.


来源: stackexchange

问:
Swift and SpriteKit : I am not able to create an SKPhysicsJoint
With Swift and Sprite Kit, I want to create an SKPhysicsJoint (for example an SKPhysicsJointFixed) but the problem is that Xcode doesn't suggest me anything :

And if I try to set what should be settled (bodyA, bodyB, anchor) manually, I can do this :

```<code>myJoint.bodyA = ...
myJoint.bodyB = ...
</code>```

But I can't set the anchor point this way... It looks like it should be set with the initialization method but I simply don't get how to do that.

答:
For Swift 3 the answer would be:

```<code>let fixedJoint = SKPhysicsJointFixed.joint(withBodyA: nodeA.physicsBody!, bodyB: nodeB.physicsBody!, anchor: anchorPoint)
self.physicsWorld.add(joint)
</code>```

Assuming both physics bodies are set up.

ContentLicense: CC BY-SA 3.0

Body:
With Swift and Sprite Kit, I want to create an SKPhysicsJoint (for example an SKPhysicsJointFixed) but the problem is that Xcode doesn't suggest me anything :

And if I try to set what should be settled (bodyA, bodyB, anchor) manually, I can do this :

myJoint.bodyA = ...
myJoint.bodyB = ...

But I can't set the anchor point this way... It looks like it should be set with the initialization method but I simply don't get how to do that.

Body:
For Swift 3 the answer would be:

let fixedJoint = SKPhysicsJointFixed.joint(withBodyA: nodeA.physicsBody!, bodyB: nodeB.physicsBody!, anchor: anchorPoint)
self.physicsWorld.add(joint)

Assuming both physics bodies are set up.


问:
Save to Local File from Blob
I have a difficult question to you, which i'm struggling on for some time now.

I'm looking for a solution, where i can save a file to the users computer, without the local storage, because local storage has 5MB limit. I want the "Save to file"-dialog, but the data i want to save is only available in javascript and i would like to prevent sending the data back to the server and then send it again.

The use-case is, that the service im working on is saving compressed and encrypted chunks of the users data, so the server has no knowledge whats in those chunks and by sending the data back to the server, this would cause 4 times traffic and the server is receiving the unencrypted data, which would render the whole encryption useless.

I found a javascript function to save the data to the users computer with the "Save to file"-dialog, but the work on this has been discontinued and isnt fully supported. It's this: http://www.w3.org/TR/file-writer-api/

So since i have no window.saveAs, what is the way to save data from a Blob-object without sending everything to the server?

Would be great if i could get a hint, what to search for.

I know that this works, because MEGA is doing it, but i want my own solution :)

答:
From a file picker or input type=file file chooser, save the filename to local storage:

HTML:

```<code><audio id="player1">Your browser does not support the audio element</audio>
</code>```

JavaScript:

```<code>function picksinglefile() {
    var fop = new Windows.Storage.Pickers.FileOpenPicker();
    fop.suggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.musicLibrary;
    fop.fileTypeFilter.replaceAll([".mp3", ".wav"]);
    fop.pickSingleFileAsync().then(function (file) {
        if (file) {
            // save the file name to local storage
            localStorage.setItem("alarmname$", file.name.toString());
        } else {
            alert("Operation Cancelled");
        }
    });
}
</code>```

Then later in your code, when you want to play the file you selected, use the following, which gets the file using only it's name from the music library.  (In the UWP package manifest, set your 'Capabilites' to include 'Music Library'.)

```<code>        var l = Windows.Storage.KnownFolders.musicLibrary;
        var f = localStorage.getItem("alarmname$").toString(); // retrieve file by name
        l.getFileAsync(f).then(function (file) {
            // storagefile file is available, create URL from it
            var s = window.URL.createObjectURL(file);
            var x = document.getElementById("player1");
            x.setAttribute("src", s);
            x.play();
        });
</code>```

ContentLicense: CC BY-SA 4.0

Title: Save to Local File from Blob

Body:
From a file picker or input type=file file chooser, save the filename to local storage:

HTML:

<audio id="player1">Your browser does not support the audio element</audio>

JavaScript:

function picksinglefile() {
    var fop = new Windows.Storage.Pickers.FileOpenPicker();
    fop.suggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.musicLibrary;
    fop.fileTypeFilter.replaceAll([".mp3", ".wav"]);
    fop.pickSingleFileAsync().then(function (file) {
        if (file) {
            // save the file name to local storage
            localStorage.setItem("alarmname$", file.name.toString());
        } else {
            alert("Operation Cancelled");
        }
    });
}

Then later in your code, when you want to play the file you selected, use the following, which gets the file using only it's name from the music library.  (In the UWP package manifest, set your 'Capabilites' to include 'Music Library'.)

        var l = Windows.Storage.KnownFolders.musicLibrary;
        var f = localStorage.getItem("alarmname$").toString(); // retrieve file by name
        l.getFileAsync(f).then(function (file) {
            // storagefile file is available, create URL from it
            var s = window.URL.createObjectURL(file);
            var x = document.getElementById("player1");
            x.setAttribute("src", s);
            x.play();
        });


问:
Find the issues of SQL
I got a questions from a test, it seems an concept question or logic question, so no data at all. Please read:

Assuming there's no syntax error and the column names and table names are correct, what's wrong with the MySQL query below?

-- FOR EVERY USER WE HAVE, this is supposed to return the number of messages they sent

```<code>select u.user_id, sum(case when um.message_id is not null then 1 else 0 end) as number_of_messages_sent
from users u left join
     users_messages um
     on um.user_id = u.user_id
where um.status = 'sent'
group by u.user_id;
</code>```

If anyone have any ideas, please help me.

答:
You are filtering all results with status="sent". Final result is not "all users and masseges". Final result is "All users who sent one or many massages".

This query is all users and the if exists their massages

```<code>SELECT u.user_id, COUNT(um.message_id)
FROM users AS u, users_messages AS um
WHERE um.user_id = u.user_id
GROUP BY u.user_id;
</code>```

This query will return Users who sent at least 1 massage. U will not see users who have not sent massage yet.

```<code>SELECT u.user_id, COUNT(um.message_id)
FROM users AS u, users_messages AS um
WHERE um.user_id = u.user_id AND status="sent"
GROUP BY u.user_id;
</code>```

Title: Find the issues of SQL

Body:
I got a questions from a test, it seems an concept question or logic question, so no data at all. Please read:

Assuming there's no syntax error and the column names and table names are correct, what's wrong with the MySQL query below?

-- FOR EVERY USER WE HAVE, this is supposed to return the number of messages they sent

select u.user_id, sum(case when um.message_id is not null then 1 else 0 end) as number_of_messages_sent
from users u left join
     users_messages um
     on um.user_id = u.user_id
where um.status = 'sent'
group by u.user_id;

If anyone have any ideas, please help me.

Body:
You are filtering all results with status="sent". Final result is not "all users and masseges". Final result is "All users who sent one or many massages".

This query is all users and the if exists their massages

SELECT u.user_id, COUNT(um.message_id)
FROM users AS u, users_messages AS um
WHERE um.user_id = u.user_id
GROUP BY u.user_id;

This query will return Users who sent at least 1 massage. U will not see users who have not sent massage yet.

SELECT u.user_id, COUNT(um.message_id)
FROM users AS u, users_messages AS um
WHERE um.user_id = u.user_id AND status="sent"
GROUP BY u.user_id;


问:
Get an outlet variable by name
Looking for a way to access an outlet programmatically in swift:

```<code>@IBOutlet var label1: UILabel?
var outletName = "label1"
view[outletName].text = "hello, world!"
</code>```

Is the only way to do this to create my own custom mapping, like so?

```<code>@IBOutlet var label1: UILabel?
let outlets = ["label1": label1]
let outletName = "label1"
outlets[outletName].text = "hello, world!"
</code>```

EDIT: Seems my original question was poorly worded, lets try again:

I'm looking to access a variable through some string identifier. In my original question I was trying to ask if a variable can be accessed by the name of the variable itself somehow. IE accessing variable label1 with a string of the variable's name "label1".

答:
There is a easier way to achieve your goal. First in your viewDidLoad, give yout outlet a unique tag number, other than 0

```<code>label1.tag = 1
</code>```

Then, whenever you want to access it

```<code>if let theLabel = self.view.viewWithTag(1) as? UILabel {
    theLabel.text = "hello, world!"
}
</code>```

Title: Get an outlet variable by name

Body:
Looking for a way to access an outlet programmatically in swift:

@IBOutlet var label1: UILabel?
var outletName = "label1"
view[outletName].text = "hello, world!"

Is the only way to do this to create my own custom mapping, like so?

@IBOutlet var label1: UILabel?
let outlets = ["label1": label1]
let outletName = "label1"
outlets[outletName].text = "hello, world!"

EDIT: Seems my original question was poorly worded, lets try again:

I'm looking to access a variable through some string identifier. In my original question I was trying to ask if a variable can be accessed by the name of the variable itself somehow. IE accessing variable label1 with a string of the variable's name "label1".

Body:
There is a easier way to achieve your goal. First in your viewDidLoad, give yout outlet a unique tag number, other than 0

label1.tag = 1

Then, whenever you want to access it

if let theLabel = self.view.viewWithTag(1) as? UILabel {
    theLabel.text = "hello, world!"
}


问:
SIGILL signal is sent to my Android app
In my application I want to be able to play streaming video (by way of RTSP protocol).
I found open RTSP stream: rtsp://red7blue.de/Primetime and tried to play it. But my application is being terminated by signal SIGILL while trying to play video. I'm using libffmpeg.so and cause ofthe SIGILL signal is located in the code of this library.
Look at what I got in logs:

```<code>D/dalvikvm(  217): Trying to load lib /data/data/my.apps.package/lib/libffmpeg.so 0x43757d68
D/dalvikvm(  217): Added shared lib /data/data/my.apps.package/lib/libffmpeg.so 0x43757d68
D/dalvikvm(  217): No JNI_OnLoad found in /data/data/my.apps.package/lib/libffmpeg.so 0x43757d68
D/dalvikvm(  217): Trying to load lib /data/data/my.apps.package/lib/libplayer-4.so 0x43757d68
D/dalvikvm(  217): Added shared lib /data/data/my.apps.package/lib/libplayer-4.so 0x43757d68
D/PlayerActivity(  217): FILE TO OPEN: rtsp://red7blue.de/Primetime
D/dalvikvm(  217): +++ not scanning '/system/lib/libwebcore.so' for 'open' (wrong CL)
D/dalvikvm(  217): +++ not scanning '/system/lib/libexif.so' for 'open' (wrong CL)
D/dalvikvm(  217): +++ not scanning '/system/lib/libFFTEm.so' for 'open' (wrong CL)
I/DEBUG   (   27): *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** ***
I/DEBUG   (   27): Build fingerprint: 'generic/sdk/generic/:1.6/Donut/20842:eng/test-keys'
I/DEBUG   (   27): pid: 217, tid: 217  >>> my.apps.package <<<
I/DEBUG   (   27): signal 4 (SIGILL), fault addr 81337fb0
I/DEBUG   (   27):  r0 00000000  r1 00000000  r2 00000001  r3 00000001
I/DEBUG   (   27):  r4 00000001  r5 00000000  r6 00000000  r7 00000000
I/DEBUG   (   27):  r8 7fffffff  r9 00000000  10 00000000  fp 20000000
I/DEBUG   (   27):  ip 00000000  sp bee438a0  lr 81337f68  pc 81337fb0  cpsr 80000010
I/DEBUG   (   27):          #00  pc 00337fb0  /data/data/my.apps.package/lib/libffmpeg.so
I/DEBUG   (   27):          #01  pc 00338564  /data/data/my.apps.package/lib/libffmpeg.so
I/DEBUG   (   27):          #02  pc 003368b8  /data/data/my.apps.package/lib/libffmpeg.so
I/DEBUG   (   27):          #03  pc 00079f74  /data/data/my.apps.package/lib/libffmpeg.so
I/DEBUG   (   27):          #04  pc 0007a040  /data/data/my.apps.package/lib/libffmpeg.so
I/DEBUG   (   27):          #05  pc 002c5780  /data/data/my.apps.package/lib/libffmpeg.so
I/DEBUG   (   27):          #06  pc 002d6bc4  /data/data/my.apps.package/lib/libffmpeg.so
I/DEBUG   (   27):          #07  pc 002c67d0  /data/data/my.apps.package/lib/libffmpeg.so
I/DEBUG   (   27):          #08  pc 003110a0  /data/data/my.apps.package/lib/libffmpeg.so
I/DEBUG   (   27):          #09  pc 00317ac4  /data/data/my.apps.package/lib/libffmpeg.so
I/DEBUG   (   27):          #10  pc 003197bc  /data/data/my.apps.package/lib/libffmpeg.so
I/DEBUG   (   27):          #11  pc 00316d04  /data/data/my.apps.package/lib/libffmpeg.so
I/DEBUG   (   27):          #12  pc 00319448  /data/data/my.apps.package/lib/libffmpeg.so
I/DEBUG   (   27):          #13  pc 002c67d0  /data/data/my.apps.package/lib/libffmpeg.so
I/DEBUG   (   27):          #14  pc 002c6fe0  /data/data/my.apps.package/lib/libffmpeg.so
I/DEBUG   (   27):          #15  pc 00004a28  /data/data/my.apps.package/lib/libplayer-4.so
I/DEBUG   (   27):          #16  pc 00007d08  /data/data/my.apps.package/lib/libplayer-4.so
I/DEBUG   (   27):          #17  pc 0000e434  /system/lib/libdvm.so
I/DEBUG   (   27):          #18  pc 00040b0e  /system/lib/libdvm.so
I/DEBUG   (   27):          #19  pc 000432b6  /system/lib/libdvm.so
I/DEBUG   (   27):          #20  pc 00013198  /system/lib/libdvm.so
I/DEBUG   (   27):          #21  pc 00017be4  /system/lib/libdvm.so
I/DEBUG   (   27):          #22  pc 0001762c  /system/lib/libdvm.so
I/DEBUG   (   27):          #23  pc 000529a8  /system/lib/libdvm.so
I/DEBUG   (   27):          #24  pc 00059eda  /system/lib/libdvm.so
I/DEBUG   (   27):          #25  pc 00013198  /system/lib/libdvm.so
I/DEBUG   (   27):          #26  pc 00017be4  /system/lib/libdvm.so
I/DEBUG   (   27):          #27  pc 0001762c  /system/lib/libdvm.so
I/DEBUG   (   27):          #28  pc 0005282c  /system/lib/libdvm.so
I/DEBUG   (   27):          #29  pc 0003f790  /system/lib/libdvm.so
I/DEBUG   (   27):          #30  pc 00031caa  /system/lib/libdvm.so
I/DEBUG   (   27):          #31  pc 0002a804  /system/lib/libandroid_runtime.so
I/DEBUG   (   27): stack:
I/DEBUG   (   27):     bee43860  00000000
I/DEBUG   (   27):     bee43864  00000000
I/DEBUG   (   27):     bee43868  20000000
I/DEBUG   (   27):     bee4386c  8135cb94  /data/data/my.apps.package/lib/libffmpeg.so
I/DEBUG   (   27):     bee43870  20000000
I/DEBUG   (   27):     bee43874  00000000
I/DEBUG   (   27):     bee43878  00000000
I/DEBUG   (   27):     bee4387c  20000000
I/DEBUG   (   27):     bee43880  00000000
I/DEBUG   (   27):     bee43884  00000000
I/DEBUG   (   27):     bee43888  00000000
I/DEBUG   (   27):     bee4388c  8135ca5c  /data/data/my.apps.package/lib/libffmpeg.so
I/DEBUG   (   27):     bee43890  bee43898  [stack]
I/DEBUG   (   27):     bee43894  81337f68  /data/data/my.apps.package/lib/libffmpeg.so
I/DEBUG   (   27):     bee43898  df002777
I/DEBUG   (   27):     bee4389c  e3a070ad
I/DEBUG   (   27): #00 bee438a0  00000000
I/DEBUG   (   27):     bee438a4  00000000
I/DEBUG   (   27):     bee438a8  00000000
I/DEBUG   (   27):     bee438ac  00000000
I/DEBUG   (   27):     bee438b0  3ff00000
I/DEBUG   (   27):     bee438b4  afc1d8f4  /system/lib/libm.so
I/DEBUG   (   27):     bee438b8  afc1d868  /system/lib/libm.so
I/DEBUG   (   27):     bee438bc  001f750c  [heap]
I/DEBUG   (   27):     bee438c0  8146ab20  /data/data/my.apps.package/lib/libffmpeg.so
I/DEBUG   (   27):     bee438c4  0000001c
I/DEBUG   (   27):     bee438c8  8b9e9309
I/DEBUG   (   27):     bee438cc  8b9e9309
I/DEBUG   (   27):     bee438d0  3fa56e5f
I/DEBUG   (   27):     bee438d4  afc0e3bc  /system/lib/libm.so
I/DEBUG   (   27):     bee438d8  2d87a4ea
I/DEBUG   (   27):     bee438dc  00000000
I/DEBUG   (   27):     bee438e0  00000000
I/DEBUG   (   27):     bee438e4  bee43928  [stack]
I/DEBUG   (   27):     bee438e8  bee4392c  [stack]
I/DEBUG   (   27):     bee438ec  ffffffbe
I/DEBUG   (   27):     bee438f0  00000000
I/DEBUG   (   27):     bee438f4  bee43928  [stack]
I/DEBUG   (   27):     bee438f8  bee4392c  [stack]
I/DEBUG   (   27):     bee438fc  bee43968  [stack]
I/DEBUG   (   27):     bee43900  00000000
I/DEBUG   (   27):     bee43904  7fffffff
I/DEBUG   (   27):     bee43908  00000000
I/DEBUG   (   27):     bee4390c  00000000
I/DEBUG   (   27):     bee43910  20000000
I/DEBUG   (   27):     bee43914  81338568  /data/data/my.apps.package/lib/libffmpeg.so
I/DEBUG   (   27): #01 bee43918  00000001
I/DEBUG   (   27):     bee4391c  00000000
I/DEBUG   (   27):     bee43920  7fffffff
I/DEBUG   (   27):     bee43924  00000000
I/DEBUG   (   27):     bee43928  8145fe10  /data/data/my.apps.package/lib/libffmpeg.so
I/DEBUG   (   27):     bee4392c  81336698  /data/data/my.apps.package/lib/libffmpeg.so
I/DEBUG   (   27):     bee43930  00000001
I/DEBUG   (   27):     bee43934  8146ab50  /data/data/my.apps.package/lib/libffmpeg.so
I/DEBUG   (   27):     bee43938  001f74f0  [heap]
I/DEBUG   (   27):     bee4393c  00000000
I/DEBUG   (   27):     bee43940  00000000
I/DEBUG   (   27):     bee43944  bee43968  [stack]
I/DEBUG   (   27):     bee43948  7fffffff
I/DEBUG   (   27):     bee4394c  8145fe34  /data/data/my.apps.package/lib/libffmpeg.so
I/DEBUG   (   27):     bee43950  8145fe10  /data/data/my.apps.package/lib/libffmpeg.so
I/DEBUG   (   27):     bee43954  813368bc  /data/data/my.apps.package/lib/libffmpeg.so
D/Zygote  (   29): Process 217 terminated by signal (4)
I/ActivityManager(   65): Process my.apps.package (pid 217) has died.
I/WindowManager(   65): WIN DEATH: Window{43846460 my.apps.package/my.apps.package.MainActivity paused=false}
</code>```

As I guess one of the causes of SIGILL signal may be the try to perform privileged instruction. RTSP is a network protocol. It's meaning that ffmpeg.so tries to access media stream using network. Maybe some special permissions should be specified for that? In my app I have the only explicit permission - android.permission.INTERNET
Should I specify something else?

答:
use arm-eabi-objdump disassemble the libplayer-4.so and libffmpeg.so. check address around 7d08, 4a2b in libplayer-4.so and 2c6fe0 in libffmpeg.

After the address found, find out the label. It's function name.

ContentLicense: CC BY-SA 2.5

Title: SIGILL signal is sent to my Android app

Body:
In my application I want to be able to play streaming video (by way of RTSP protocol).
I found open RTSP stream: rtsp://red7blue.de/Primetime and tried to play it. But my application is being terminated by signal SIGILL while trying to play video. I'm using libffmpeg.so and cause ofthe SIGILL signal is located in the code of this library.
Look at what I got in logs:

D/dalvikvm(  217): Trying to load lib /data/data/my.apps.package/lib/libffmpeg.so 0x43757d68
D/dalvikvm(  217): Added shared lib /data/data/my.apps.package/lib/libffmpeg.so 0x43757d68
D/dalvikvm(  217): No JNI_OnLoad found in /data/data/my.apps.package/lib/libffmpeg.so 0x43757d68
D/dalvikvm(  217): Trying to load lib /data/data/my.apps.package/lib/libplayer-4.so 0x43757d68
D/dalvikvm(  217): Added shared lib /data/data/my.apps.package/lib/libplayer-4.so 0x43757d68
D/PlayerActivity(  217): FILE TO OPEN: rtsp://red7blue.de/Primetime
D/dalvikvm(  217): +++ not scanning '/system/lib/libwebcore.so' for 'open' (wrong CL)
D/dalvikvm(  217): +++ not scanning '/system/lib/libexif.so' for 'open' (wrong CL)
D/dalvikvm(  217): +++ not scanning '/system/lib/libFFTEm.so' for 'open' (wrong CL)
I/DEBUG   (   27): *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** ***
I/DEBUG   (   27): Build fingerprint: 'generic/sdk/generic/:1.6/Donut/20842:eng/test-keys'
I/DEBUG   (   27): pid: 217, tid: 217  >>> my.apps.package <<<
I/DEBUG   (   27): signal 4 (SIGILL), fault addr 81337fb0
I/DEBUG   (   27):  r0 00000000  r1 00000000  r2 00000001  r3 00000001
I/DEBUG   (   27):  r4 00000001  r5 00000000  r6 00000000  r7 00000000
I/DEBUG   (   27):  r8 7fffffff  r9 00000000  10 00000000  fp 20000000
I/DEBUG   (   27):  ip 00000000  sp bee438a0  lr 81337f68  pc 81337fb0  cpsr 80000010
I/DEBUG   (   27):          #00  pc 00337fb0  /data/data/my.apps.package/lib/libffmpeg.so
I/DEBUG   (   27):          #01  pc 00338564  /data/data/my.apps.package/lib/libffmpeg.so
I/DEBUG   (   27):          #02  pc 003368b8  /data/data/my.apps.package/lib/libffmpeg.so
I/DEBUG   (   27):          #03  pc 00079f74  /data/data/my.apps.package/lib/libffmpeg.so
I/DEBUG   (   27):          #04  pc 0007a040  /data/data/my.apps.package/lib/libffmpeg.so
I/DEBUG   (   27):          #05  pc 002c5780  /data/data/my.apps.package/lib/libffmpeg.so
I/DEBUG   (   27):          #06  pc 002d6bc4  /data/data/my.apps.package/lib/libffmpeg.so
I/DEBUG   (   27):          #07  pc 002c67d0  /data/data/my.apps.package/lib/libffmpeg.so
I/DEBUG   (   27):          #08  pc 003110a0  /data/data/my.apps.package/lib/libffmpeg.so
I/DEBUG   (   27):          #09  pc 00317ac4  /data/data/my.apps.package/lib/libffmpeg.so
I/DEBUG   (   27):          #10  pc 003197bc  /data/data/my.apps.package/lib/libffmpeg.so
I/DEBUG   (   27):          #11  pc 00316d04  /data/data/my.apps.package/lib/libffmpeg.so
I/DEBUG   (   27):          #12  pc 00319448  /data/data/my.apps.package/lib/libffmpeg.so
I/DEBUG   (   27):          #13  pc 002c67d0  /data/data/my.apps.package/lib/libffmpeg.so
I/DEBUG   (   27):          #14  pc 002c6fe0  /data/data/my.apps.package/lib/libffmpeg.so
I/DEBUG   (   27):          #15  pc 00004a28  /data/data/my.apps.package/lib/libplayer-4.so
I/DEBUG   (   27):          #16  pc 00007d08  /data/data/my.apps.package/lib/libplayer-4.so
I/DEBUG   (   27):          #17  pc 0000e434  /system/lib/libdvm.so
I/DEBUG   (   27):          #18  pc 00040b0e  /system/lib/libdvm.so
I/DEBUG   (   27):          #19  pc 000432b6  /system/lib/libdvm.so
I/DEBUG   (   27):          #20  pc 00013198  /system/lib/libdvm.so
I/DEBUG   (   27):          #21  pc 00017be4  /system/lib/libdvm.so
I/DEBUG   (   27):          #22  pc 0001762c  /system/lib/libdvm.so
I/DEBUG   (   27):          #23  pc 000529a8  /system/lib/libdvm.so
I/DEBUG   (   27):          #24  pc 00059eda  /system/lib/libdvm.so
I/DEBUG   (   27):          #25  pc 00013198  /system/lib/libdvm.so
I/DEBUG   (   27):          #26  pc 00017be4  /system/lib/libdvm.so
I/DEBUG   (   27):          #27  pc 0001762c  /system/lib/libdvm.so
I/DEBUG   (   27):          #28  pc 0005282c  /system/lib/libdvm.so
I/DEBUG   (   27):          #29  pc 0003f790  /system/lib/libdvm.so
I/DEBUG   (   27):          #30  pc 00031caa  /system/lib/libdvm.so
I/DEBUG   (   27):          #31  pc 0002a804  /system/lib/libandroid_runtime.so
I/DEBUG   (   27): stack:
I/DEBUG   (   27):     bee43860  00000000
I/DEBUG   (   27):     bee43864  00000000
I/DEBUG   (   27):     bee43868  20000000
I/DEBUG   (   27):     bee4386c  8135cb94  /data/data/my.apps.package/lib/libffmpeg.so
I/DEBUG   (   27):     bee43870  20000000
I/DEBUG   (   27):     bee43874  00000000
I/DEBUG   (   27):     bee43878  00000000
I/DEBUG   (   27):     bee4387c  20000000
I/DEBUG   (   27):     bee43880  00000000
I/DEBUG   (   27):     bee43884  00000000
I/DEBUG   (   27):     bee43888  00000000
I/DEBUG   (   27):     bee4388c  8135ca5c  /data/data/my.apps.package/lib/libffmpeg.so
I/DEBUG   (   27):     bee43890  bee43898  [stack]
I/DEBUG   (   27):     bee43894  81337f68  /data/data/my.apps.package/lib/libffmpeg.so
I/DEBUG   (   27):     bee43898  df002777
I/DEBUG   (   27):     bee4389c  e3a070ad
I/DEBUG   (   27): #00 bee438a0  00000000
I/DEBUG   (   27):     bee438a4  00000000
I/DEBUG   (   27):     bee438a8  00000000
I/DEBUG   (   27):     bee438ac  00000000
I/DEBUG   (   27):     bee438b0  3ff00000
I/DEBUG   (   27):     bee438b4  afc1d8f4  /system/lib/libm.so
I/DEBUG   (   27):     bee438b8  afc1d868  /system/lib/libm.so
I/DEBUG   (   27):     bee438bc  001f750c  [heap]
I/DEBUG   (   27):     bee438c0  8146ab20  /data/data/my.apps.package/lib/libffmpeg.so
I/DEBUG   (   27):     bee438c4  0000001c
I/DEBUG   (   27):     bee438c8  8b9e9309
I/DEBUG   (   27):     bee438cc  8b9e9309
I/DEBUG   (   27):     bee438d0  3fa56e5f
I/DEBUG   (   27):     bee438d4  afc0e3bc  /system/lib/libm.so
I/DEBUG   (   27):     bee438d8  2d87a4ea
I/DEBUG   (   27):     bee438dc  00000000
I/DEBUG   (   27):     bee438e0  00000000
I/DEBUG   (   27):     bee438e4  bee43928  [stack]
I/DEBUG   (   27):     bee438e8  bee4392c  [stack]
I/DEBUG   (   27):     bee438ec  ffffffbe
I/DEBUG   (   27):     bee438f0  00000000
I/DEBUG   (   27):     bee438f4  bee43928  [stack]
I/DEBUG   (   27):     bee438f8  bee4392c  [stack]
I/DEBUG   (   27):     bee438fc  bee43968  [stack]
I/DEBUG   (   27):     bee43900  00000000
I/DEBUG   (   27):     bee43904  7fffffff
I/DEBUG   (   27):     bee43908  00000000
I/DEBUG   (   27):     bee4390c  00000000
I/DEBUG   (   27):     bee43910  20000000
I/DEBUG   (   27):     bee43914  81338568  /data/data/my.apps.package/lib/libffmpeg.so
I/DEBUG   (   27): #01 bee43918  00000001
I/DEBUG   (   27):     bee4391c  00000000
I/DEBUG   (   27):     bee43920  7fffffff
I/DEBUG   (   27):     bee43924  00000000
I/DEBUG   (   27):     bee43928  8145fe10  /data/data/my.apps.package/lib/libffmpeg.so
I/DEBUG   (   27):     bee4392c  81336698  /data/data/my.apps.package/lib/libffmpeg.so
I/DEBUG   (   27):     bee43930  00000001
I/DEBUG   (   27):     bee43934  8146ab50  /data/data/my.apps.package/lib/libffmpeg.so
I/DEBUG   (   27):     bee43938  001f74f0  [heap]
I/DEBUG   (   27):     bee4393c  00000000
I/DEBUG   (   27):     bee43940  00000000
I/DEBUG   (   27):     bee43944  bee43968  [stack]
I/DEBUG   (   27):     bee43948  7fffffff
I/DEBUG   (   27):     bee4394c  8145fe34  /data/data/my.apps.package/lib/libffmpeg.so
I/DEBUG   (   27):     bee43950  8145fe10  /data/data/my.apps.package/lib/libffmpeg.so
I/DEBUG   (   27):     bee43954  813368bc  /data/data/my.apps.package/lib/libffmpeg.so
D/Zygote  (   29): Process 217 terminated by signal (4)
I/ActivityManager(   65): Process my.apps.package (pid 217) has died.
I/WindowManager(   65): WIN DEATH: Window{43846460 my.apps.package/my.apps.package.MainActivity paused=false}

As I guess one of the causes of SIGILL signal may be the try to perform privileged instruction. RTSP is a network protocol. It's meaning that ffmpeg.so tries to access media stream using network. Maybe some special permissions should be specified for that? In my app I have the only explicit permission - android.permission.INTERNET
Should I specify something else?


问:
vim doesn't recognize columns beyond 72 with fortran90 code
I am editing a fortran90 code with vim.  Note that I'm working with a *.f90 file, not *.f.  vim doesn't recognize as legitimate code anything beyond column 72.  This is an annoying problem because if a quote is opened at, say, column 50 but not closed until column 80, then vim colors all the following lines as part of the same quote.  This would make sense if I was working with an old fortran77 file, but I'm clearly not.  Is there any way to convince vim to recognize code beyond column 72?</p>

答:
This could be related to the 'synmaxcol' variable. If you run

```<code>:set synmaxcol?
</code>```

In vim's command line, what do you get back? Setting this option higher might fix your issue. It's generally set low as vim can get laggy when syntax highlighting very long lines, such as those found in XML.

Body:
This could be related to the 'synmaxcol' variable. If you run

:set synmaxcol?

In vim's command line, what do you get back? Setting this option higher might fix your issue. It's generally set low as vim can get laggy when syntax highlighting very long lines, such as those found in XML.


问:
Why access specifiers can't be used for variables declared inside method in a Java Class?
Why we can't use access specifiers for variables declared inside method in a Java Class?</p>

答: As per the rules of java whatever the variables declared in the scope of method are not accessible outside, which itself means the variables are themselves private, protected and ofcourse we know its default if none specified. so there is no point in declaring a local variable with above mentioned access modifiers. However , you can still use "final" access modifier for the reason that you don't want it to be changed during the course of the method() because of some processing like unwanted reassignment of value to the variable etc.,


问:
Detecting sound in iphone
Can anyone tell me how to detect a sound on iphone....

Please help....please provide any source code or link if possible

答:
You can use AVAudioRecorder

http://mobileorchard.com/tutorial-detecting-when-a-user-blows-into-the-mic/

That tutorial works for any sound really... it goes through the steps of creating a high-pass filter to try and only detect blowing. You can change the values to make it more sensitive to sound or less sensitive.

Title: Detecting sound in iphone


问:
What is wrong with my java code for Project Euler's program 4? (finding the largest palindrome of 2 3 digit numbers)

This is my code and the answer always seems to 100001 (its not even
  performing the loop).
      I know there are much easier ways to solve this problem but what exactly is wrong with this particular code? and how do I fix it?

```<code>public class LargestPalindromes
{

 public static void main(String[] args)
{
    int largest = 100001;

    for(int i = 100; i < 1000; i++)
    {
        for(int j = 100; j < 1000; j++)
        {
            int mult = i * j;
            if(largest < mult && isPalindrome(mult))
                largest = mult;
        }
    }

    System.out.printf("\n\nThe largest palindrome is: %d\n\n", largest);
}

public static boolean isPalindrome(int mult)
{
    int n1=0, n2=0, n3=0, n4=0, n5=0, n6=0;
    int largest = 0, count = 0, p =100000;
    int x = mult;

    while(count < 6)
    {
        if(count == 1)
            n1 = x / p;
        else if(count == 2)
            n2 = x / p;
        else if(count == 3)
            n3 = x / p;
        else if(count == 4)
            n4 = x / p;
        else if(count == 5)
            n5 = x / p;
        else if(count == 6)
            n6 = x / p;

        x %= p;

        p /= 10;

        count++;
    }

    int reverse = Integer.valueOf(String.valueOf(n1) + String.valueOf(n2) + String.valueOf(n3) + String.valueOf(n4) + String.valueOf(n5) + String.valueOf(n6));

    return reverse == mult;
}
}
</code>```

答:
There were too many errors in your original public static boolean isPalindrome(int mult) method. So I replaced it with the standard version:

```<code>public static boolean isPalindrome(int mult)
{

   int temp=mult;
   int r,sum=0;
   while(mult>0){
     r=mult%10;  //getting remainder
     sum=(sum*10)+r;
     mult=mult/10;
  }
  if(temp==sum)
      return true;
  else{
      return false;
  }
}
</code>```

Body:
This is my code and the answer always seems to 100001 (its not even
  performing the loop).
      I know there are much easier ways to solve this problem but what exactly is wrong with this particular code? and how do I fix it?

public class LargestPalindromes
{

 public static void main(String[] args)
{
    int largest = 100001;

    for(int i = 100; i < 1000; i++)
    {
        for(int j = 100; j < 1000; j++)
        {
            int mult = i * j;
            if(largest < mult && isPalindrome(mult))
                largest = mult;
        }
    }

    System.out.printf("\n\nThe largest palindrome is: %d\n\n", largest);
}

public static boolean isPalindrome(int mult)
{
    int n1=0, n2=0, n3=0, n4=0, n5=0, n6=0;
    int largest = 0, count = 0, p =100000;
    int x = mult;

    while(count < 6)
    {
        if(count == 1)
            n1 = x / p;
        else if(count == 2)
            n2 = x / p;
        else if(count == 3)
            n3 = x / p;
        else if(count == 4)
            n4 = x / p;
        else if(count == 5)
            n5 = x / p;
        else if(count == 6)
            n6 = x / p;

        x %= p;

        p /= 10;

        count++;
    }

    int reverse = Integer.valueOf(String.valueOf(n1) + String.valueOf(n2) + String.valueOf(n3) + String.valueOf(n4) + String.valueOf(n5) + String.valueOf(n6));

    return reverse == mult;
}
}

Body:
There were too many errors in your original public static boolean isPalindrome(int mult) method. So I replaced it with the standard version:

public static boolean isPalindrome(int mult)
{

   int temp=mult;
   int r,sum=0;
   while(mult>0){
     r=mult%10;  //getting remainder
     sum=(sum*10)+r;
     mult=mult/10;
  }
  if(temp==sum)
      return true;
  else{
      return false;
  }
}


问:
Setting toolbar title not working in onCreate()
I am having issues setting the title of my toolbar, which only seems to work when there is a delay.

For example a simple oncreate() method for my app 'Forecast'

```<code>@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    ButterKnife.bind(this);
    setSupportActionBar(_toolbar);
    setTitle("ABCDEFG");
}
</code>```

When the app is run, the toolbar has the name of my app, not 'ABCDEFG'.

However, if I put a 200 millisecond delay before setting the title..

```<code>    Observable.just("ABCDEFG")
            .delay(200,TimeUnit.MILLISECONDS)
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(this::setTitle);
</code>```

My Toolbar title is correctly displayed as "ABCDEFG"

this is the same when it comes to doing anything with the Toolbar, does anyone know what is actually going on here? and how I can solve this without having to put a delay in?

Here is my toolbar xml..

```<code><android.support.design.widget.AppBarLayout
    android:id="@+id/appBar"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:fitsSystemWindows="true"
    android:theme="@style/AppTheme.AppBarOverlay">

    <android.support.v7.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="?android:attr/actionBarSize"
        app:layout_collapseMode="pin"
        app:layout_scrollFlags="scroll"
        app:popupTheme="@style/AppTheme.PopupOverlay" />

</android.support.design.widget.AppBarLayout>
</code>```

Thanks for your help!

EDIT forgot to mention setTitle() simply calls _toolbar.setTitle(title)

答:
If you call setSupportActionBar(Toolbar), then the Action Bar is then responsible for handling the title, therefore you need to call getSupportActionBar().setTitle("My Title"); to set a custom title.

Also check this link where toolbar.setTitle("My title"); may cause problem like below:- In android app Toolbar.setTitle method has no effect – application name is shown as title

And toolbar is the general form of action bar.

We can have multiple toolbars as layout widget but action is not.

Thus better approach is to use getSupportActionBar().setTitle("My Title");

Body:
I am having issues setting the title of my toolbar, which only seems to work when there is a delay.

For example a simple oncreate() method for my app 'Forecast'

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    ButterKnife.bind(this);
    setSupportActionBar(_toolbar);
    setTitle("ABCDEFG");
}

When the app is run, the toolbar has the name of my app, not 'ABCDEFG'.

However, if I put a 200 millisecond delay before setting the title..

    Observable.just("ABCDEFG")
            .delay(200,TimeUnit.MILLISECONDS)
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(this::setTitle);

My Toolbar title is correctly displayed as "ABCDEFG"

this is the same when it comes to doing anything with the Toolbar, does anyone know what is actually going on here? and how I can solve this without having to put a delay in?

Here is my toolbar xml..

<android.support.design.widget.AppBarLayout
    android:id="@+id/appBar"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:fitsSystemWindows="true"
    android:theme="@style/AppTheme.AppBarOverlay">

    <android.support.v7.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="?android:attr/actionBarSize"
        app:layout_collapseMode="pin"
        app:layout_scrollFlags="scroll"
        app:popupTheme="@style/AppTheme.PopupOverlay" />

</android.support.design.widget.AppBarLayout>

Thanks for your help!

EDIT forgot to mention setTitle() simply calls _toolbar.setTitle(title)


问:
Find shortest path on three.js mesh?
I'd like to create an app using three.js where a user can paint polygons (well, actually, face loops) on a mesh.

The user would pick faces A and B using their mouse and the raycaster, and then I want to find all of the faces along the shortest path between A and B and color them.

Are there any built in utilities that will assist with this, or any examples to use?

I haven't found any so unless you can direct me to something I will implement a shortest path algorithm myself... I guess I have to start with creating an adjacency list from the threejs geometry.

答: I didn't find any three.js examples or extensions that did shortest path or tree search, so I just wrote it myself. Running here.</p>

Title: Find shortest path on three.js mesh?


问:
How to join 3 tables in sql with or condition
I have 3 tables:
table1

inner join with table2; or:

inner join with table3

The query:

```<code>select table1.x
from table1 right outer join
     table2
     on table1.x = table2.x right outer join
     table3
     on table1.x = table3.x
</code>```

but I can only see x values that are in both table2 and table3

答:
Use left join, not right join, along with an appropriate filter condition:

```<code>select table1.x
from table1 left join
     table2
     on table1.x = table2.x left join
     table3
     on table1.x = table3.x
where table2.x is not null or table3.x is not null;
</code>```

You might consider writing this using exists:

```<code>select t1.*
from table1 t1
where exists (select 1 from table2 t2 where t2.x = t1.x) or
      exists (select 1 from table3 t3 where t3.x = t1.x);
</code>```

That seems like a more natural way to implement your logic -- and you won't get duplicates when x is duplicated in table2 or table3.

Body:
I have 3 tables:
table1

inner join with table2; or:

inner join with table3

The query:

select table1.x
from table1 right outer join
     table2
     on table1.x = table2.x right outer join
     table3
     on table1.x = table3.x

but I can only see x values that are in both table2 and table3

Body:
Use left join, not right join, along with an appropriate filter condition:

select table1.x
from table1 left join
     table2
     on table1.x = table2.x left join
     table3
     on table1.x = table3.x
where table2.x is not null or table3.x is not null;

You might consider writing this using exists:

select t1.*
from table1 t1
where exists (select 1 from table2 t2 where t2.x = t1.x) or
      exists (select 1 from table3 t3 where t3.x = t1.x);

That seems like a more natural way to implement your logic -- and you won't get duplicates when x is duplicated in table2 or table3.


问:
Count and remove similar elements in a list while iterating through it
I used many references in the site to build up my program but I'm kind of stuck right now. I think using iterator will do the job. Sadly even though I went through questions which had iterator, I couldn't get the way of using it properly to implement it on my code.

I want to,
      1. remove the similar elements found in the list fname
      2. count & add the that count of each element found in fname to
          counter.

Please help me do the above using iterator or with any other method. Following is my code,

```<code>List<String> fname = new ArrayList<>(Arrays.asList(fullname.split(""))); //Assigning the string to a list//

    int count = 1;
    ArrayList<Integer> counter = new ArrayList<>();
    List<String> holder = new ArrayList<>();

    for(int element=0; element<=fname.size; element++)
    {
        for(int run=(element+1); run<=fname.size; run++)
        {
            if((fname.get(element)).equals(fname.get(run)))
            {
                count++;
                holder.add(fname.get(run));
            }

            counter.add(count);
        }

        holder.add(fname.get(element));
        fname.removeAll(holder);
    }

    System.out.println(fname);
    System.out.println(counter);
</code>```

Thanks.

答:
You can try something like this:

```<code>Set<String> mySet = new HashSet<>();
mySet.addAll( fname ); // Now you have unique values

for(String s : mySet) {
    count = 0;
    for(String x : fname) {
        if( s.equals(x) ) { count++; }
    }
    counter.add( count );
}
</code>```

This way we don't have a specific order. But I hope it helps.

In Java 8, there's a one-liner:

```<code>List<Integer> result = fname
    .stream()
    .collect(Collectors.groupingBy(s -> s))
    .entrySet()
    .stream()
    .map(e -> e.getValue().size())
    .collect(Collectors.toList());
</code>```

Body:
I used many references in the site to build up my program but I'm kind of stuck right now. I think using iterator will do the job. Sadly even though I went through questions which had iterator, I couldn't get the way of using it properly to implement it on my code.

I want to,
      1. remove the similar elements found in the list fname
      2. count & add the that count of each element found in fname to
          counter.

Please help me do the above using iterator or with any other method. Following is my code,

List<String> fname = new ArrayList<>(Arrays.asList(fullname.split(""))); //Assigning the string to a list//

    int count = 1;
    ArrayList<Integer> counter = new ArrayList<>();
    List<String> holder = new ArrayList<>();

    for(int element=0; element<=fname.size; element++)
    {
        for(int run=(element+1); run<=fname.size; run++)
        {
            if((fname.get(element)).equals(fname.get(run)))
            {
                count++;
                holder.add(fname.get(run));
            }

            counter.add(count);
        }

        holder.add(fname.get(element));
        fname.removeAll(holder);
    }

    System.out.println(fname);
    System.out.println(counter);

Thanks.

Body:
You can try something like this:

Set<String> mySet = new HashSet<>();
mySet.addAll( fname ); // Now you have unique values

for(String s : mySet) {
    count = 0;
    for(String x : fname) {
        if( s.equals(x) ) { count++; }
    }
    counter.add( count );
}

This way we don't have a specific order. But I hope it helps.

In Java 8, there's a one-liner:

List<Integer> result = fname
    .stream()
    .collect(Collectors.groupingBy(s -> s))
    .entrySet()
    .stream()
    .map(e -> e.getValue().size())
    .collect(Collectors.toList());


问:
Why is my text aligned to the left?
I'm new to Android developing, and I just couldn't fix this problem. When I build this app, my initial text is centered, but when I click the button or long click it, the response text is left aligned. And also, double tap, scrolling and flinging gestures don't work at all. What can be the reason?

MainActivity.java:

```<code>package com.revolise.gesturehandling;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.Button;
import android.widget.TextView;
import android.view.View;
import android.view.MotionEvent;
import android.view.GestureDetector;
import android.support.v4.view.GestureDetectorCompat;

public class MainActivity extends AppCompatActivity implements
GestureDetector.OnGestureListener,GestureDetector.OnDoubleTapListener
    {

        private Button button1;
        private GestureDetectorCompat gestureDetect;
        private TextView txt1;

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

            button1 = (Button)findViewById(R.id.button1);
            txt1 = (TextView)findViewById(R.id.textView1);
            this.gestureDetect = new GestureDetectorCompat(this, this);
            gestureDetect.setOnDoubleTapListener(this);

            button1.setOnClickListener(
                    new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            txt1.setText("clicked to the button whooaoaaa");
                        }
                    }
            );

            button1.setOnLongClickListener(
                    new View.OnLongClickListener() {
                        @Override
                        public boolean onLongClick(View view) {
                            txt1.setText("long clicked to the button woww");
                            return false;
                        }
                    }
            );

        }
        @Override
        public boolean onSingleTapConfirmed(MotionEvent motionEvent) {
            return true;
        }

        @Override
        public boolean onDoubleTap(MotionEvent motionEvent) {
            txt1.setText("Hey, you double tapped");
            return true;
        }

        @Override
        public boolean onDoubleTapEvent(MotionEvent motionEvent) {
            txt1.setText("Aaaand now you're swiping.");
            return true;
        }

        @Override
        public boolean onDown(MotionEvent motionEvent) {
            return true;
        }

        @Override
        public void onShowPress(MotionEvent motionEvent) {

        }

        @Override
        public boolean onSingleTapUp(MotionEvent motionEvent) {
            return true;
        }

        @Override
        public boolean onScroll(MotionEvent motionEvent, MotionEvent motionEvent1, float v, float v1) {
            txt1.setText("Scrolling weee");
            return true;
        }

        @Override
        public void onLongPress(MotionEvent motionEvent) {
            txt1.setText("Long pressed");

        }

        @Override
        public boolean onFling(MotionEvent motionEvent, MotionEvent motionEvent1, float v, float v1) {
            txt1.setText("Whoaa flinginggg");
            return true;
        }
}

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

<TextView
    android:id="@+id/textView1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginBottom="160dp"
    android:text="@string/initial_text"
    android:textSize="30sp"
    app:layout_constraintBottom_toTopOf="@+id/button1"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintRight_toRightOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    android:layout_marginTop="100dp"
    android:layout_marginLeft="50dp"
    android:layout_marginRight="50dp" />

<Button
    android:id="@+id/button1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/button_text"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintRight_toRightOf="parent"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintHorizontal_bias="0.501"
    android:layout_marginBottom="200dp" />
</android.support.constraint.ConstraintLayout>
</code>```

答:
For first problem (wrong text aligned)

You should set your TextView width as match_parent and gravity to center_horizontal. So your code should be something like this:

```<code><TextView
        android:id="@+id/textView1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginBottom="160dp"
        android:text="@string/initial_text"
        android:textSize="30sp"
        android:layout_gravity="center_horizontal"
        app:layout_constraintBottom_toTopOf="@+id/button1"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        android:layout_marginTop="100dp"
        android:layout_marginLeft="50dp"
        android:layout_marginRight="50dp" />
</code>```

Title: Why is my text aligned to the left?

Body:
I'm new to Android developing, and I just couldn't fix this problem. When I build this app, my initial text is centered, but when I click the button or long click it, the response text is left aligned. And also, double tap, scrolling and flinging gestures don't work at all. What can be the reason?

MainActivity.java:

package com.revolise.gesturehandling;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.Button;
import android.widget.TextView;
import android.view.View;
import android.view.MotionEvent;
import android.view.GestureDetector;
import android.support.v4.view.GestureDetectorCompat;

public class MainActivity extends AppCompatActivity implements
GestureDetector.OnGestureListener,GestureDetector.OnDoubleTapListener
    {

        private Button button1;
        private GestureDetectorCompat gestureDetect;
        private TextView txt1;

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

            button1 = (Button)findViewById(R.id.button1);
            txt1 = (TextView)findViewById(R.id.textView1);
            this.gestureDetect = new GestureDetectorCompat(this, this);
            gestureDetect.setOnDoubleTapListener(this);

            button1.setOnClickListener(
                    new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            txt1.setText("clicked to the button whooaoaaa");
                        }
                    }
            );

            button1.setOnLongClickListener(
                    new View.OnLongClickListener() {
                        @Override
                        public boolean onLongClick(View view) {
                            txt1.setText("long clicked to the button woww");
                            return false;
                        }
                    }
            );

        }
        @Override
        public boolean onSingleTapConfirmed(MotionEvent motionEvent) {
            return true;
        }

        @Override
        public boolean onDoubleTap(MotionEvent motionEvent) {
            txt1.setText("Hey, you double tapped");
            return true;
        }

        @Override
        public boolean onDoubleTapEvent(MotionEvent motionEvent) {
            txt1.setText("Aaaand now you're swiping.");
            return true;
        }

        @Override
        public boolean onDown(MotionEvent motionEvent) {
            return true;
        }

        @Override
        public void onShowPress(MotionEvent motionEvent) {

        }

        @Override
        public boolean onSingleTapUp(MotionEvent motionEvent) {
            return true;
        }

        @Override
        public boolean onScroll(MotionEvent motionEvent, MotionEvent motionEvent1, float v, float v1) {
            txt1.setText("Scrolling weee");
            return true;
        }

        @Override
        public void onLongPress(MotionEvent motionEvent) {
            txt1.setText("Long pressed");

        }

        @Override
        public boolean onFling(MotionEvent motionEvent, MotionEvent motionEvent1, float v, float v1) {
            txt1.setText("Whoaa flinginggg");
            return true;
        }
}

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

<TextView
    android:id="@+id/textView1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginBottom="160dp"
    android:text="@string/initial_text"
    android:textSize="30sp"
    app:layout_constraintBottom_toTopOf="@+id/button1"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintRight_toRightOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    android:layout_marginTop="100dp"
    android:layout_marginLeft="50dp"
    android:layout_marginRight="50dp" />

<Button
    android:id="@+id/button1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/button_text"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintRight_toRightOf="parent"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintHorizontal_bias="0.501"
    android:layout_marginBottom="200dp" />
</android.support.constraint.ConstraintLayout>

Body:
For first problem (wrong text aligned)

You should set your TextView width as match_parent and gravity to center_horizontal. So your code should be something like this:

<TextView
        android:id="@+id/textView1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginBottom="160dp"
        android:text="@string/initial_text"
        android:textSize="30sp"
        android:layout_gravity="center_horizontal"
        app:layout_constraintBottom_toTopOf="@+id/button1"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        android:layout_marginTop="100dp"
        android:layout_marginLeft="50dp"
        android:layout_marginRight="50dp" />


问:
Javascript using mouse hover class to effect child ids
I am trying to make the class navButtons effect all of the ids inside it using the mouse over  effect. I read on here that you can do this with a for loop but that would require changing the names of the ids. is there a way to do this without changing the names?

document.getElementsByClassName("navButtons").addEventListener("mouseover", mouseOver);
document.getElementsByClassName("navButtons").addEventListener("mouseout", mouseOut);

function mouseOver() {
    document.getElementsByClassName("navButtons").style.color = "red";
}

function mouseOut() {
    document.getElementsByClassName("navButtons").style.color = "black";
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><nav>
  <div class="navButtons">
      <div id="about">about</div>
      <div id="portfolio">portfolio</div>
      <div id="contact">contact</div>
  </div>
</nav>

 </code>```

答:
You can just use css to add hover effect to all div inside .navButtons div.

.navButtons div{
 color: red;
}
.navButtons div:hover{
 color: green;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>Hover effect</title>
</head>
<body>
<nav>
  <div class="navButtons">
      <div id="about">about</div>
      <div id="portfolio">portfolio</div>
      <div id="contact">contact</div>
  </div>
</nav>
</body>
</html></code>```

Body:
I am trying to make the class navButtons effect all of the ids inside it using the mouse over  effect. I read on here that you can do this with a for loop but that would require changing the names of the ids. is there a way to do this without changing the names?

document.getElementsByClassName("navButtons").addEventListener("mouseover", mouseOver);
document.getElementsByClassName("navButtons").addEventListener("mouseout", mouseOut);

function mouseOver() {
    document.getElementsByClassName("navButtons").style.color = "red";
}

function mouseOut() {
    document.getElementsByClassName("navButtons").style.color = "black";
}

about

portfolio

contact

Body:
You can just use css to add hover effect to all div inside .navButtons div.

.navButtons div{
 color: red;
}
.navButtons div:hover{
 color: green;
}

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>Hover effect</title>
</head>
<body>
<nav>
  <div class="navButtons">
      <div id="about">about</div>
      <div id="portfolio">portfolio</div>
      <div id="contact">contact</div>
  </div>
</nav>
</body>
</html>


问:
Should defined numbers be stored in a table within the database?
Imagine you have a table - lets contrive an example where this is Orders - which has a field named type, which may be only one of a few fixed values (lets say 0 or 1, for Quotation and Order).

Should all the possible values of type be represented by another table in the database (with just typeID and typeName columns?), and Orders made to reference the new table?

Or is it normal to leave these numbers as-is and have them documented outside the database?

If this is a "it depends" situation: What are the important implications of both options?

I have used the first option in a recent University assignement, but without really thinking about why - and looking back at the design now I'm wondering whether this is important.

I never once queried the reference table as part of my application - because I didn't "need" to - does this indicate the reference table is unneeded, or is this a flaw in my application because it should be checking the ref table (what for?)?

Body: use enum: http://dev.mysql.com/doc/refman/5.0/en/enum.html


问:
Not ablet to pass Parcelable object as putExtra from IntentService to another Activity
Reivewed all the similar question, and yet no result.
I cannot pass one ojbect that implements parcelable from an intentService to an Activity. The Same code works fine when passing data from an activity to another activity. Even can pass ParcelableArrayListExtra also but not the parcelable Object. Its a requirment to pass the object in my project.
Code is given below(Dont have right to publish whole code,and whole code is working except these lines)
CODE:
IntentService:

```<code>    Intent action = new Intent(this, QuizActivity.class);
    intent.putParcelableArrayListExtra("userList",name);
    Random position = new Random();
    int randomPosition =position.nextInt(3);
    intent.putExtra("selectedUser",name.get(randomPosition));
    action.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
</code>```

SecondActivity:

```<code>List<User> userList= getIntent().getParcelableArrayListExtra(EXTRA_INSECTS);
Insect selected = getIntent().getExtras().getParcelable("selectedUser");
</code>```

答:
I suposse that problem can be with putting a custom Parcelable on API 25+ from service to activity.

This answer has a workaround, in the form of converting the Parcelable yourself to/from a byte[].

Begin with passing single Parcelable object, not ArrayList.

```<code>    public static void putExtra(Intent intent, String key, Parcelable parcelable) {
    byte[] bytes = marshall(parcelable);
    intent.putExtra(key, bytes);
}
</code>```

and

```<code>    public static <T> T getExtra(Intent intent, String key, Parcelable.Creator<T> creator) {
    byte[] bytes = intent.getByteArrayExtra(key);
    return ParcelableUtils.unmarshall(bytes, creator);
}
</code>```

Body:
Reivewed all the similar question, and yet no result.
I cannot pass one ojbect that implements parcelable from an intentService to an Activity. The Same code works fine when passing data from an activity to another activity. Even can pass ParcelableArrayListExtra also but not the parcelable Object. Its a requirment to pass the object in my project.
Code is given below(Dont have right to publish whole code,and whole code is working except these lines)
CODE:
IntentService:

    Intent action = new Intent(this, QuizActivity.class);
    intent.putParcelableArrayListExtra("userList",name);
    Random position = new Random();
    int randomPosition =position.nextInt(3);
    intent.putExtra("selectedUser",name.get(randomPosition));
    action.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

SecondActivity:

List<User> userList= getIntent().getParcelableArrayListExtra(EXTRA_INSECTS);
Insect selected = getIntent().getExtras().getParcelable("selectedUser");

Body:
I suposse that problem can be with putting a custom Parcelable on API 25+ from service to activity.

This answer has a workaround, in the form of converting the Parcelable yourself to/from a byte[].

Begin with passing single Parcelable object, not ArrayList.

    public static void putExtra(Intent intent, String key, Parcelable parcelable) {
    byte[] bytes = marshall(parcelable);
    intent.putExtra(key, bytes);
}

and

    public static <T> T getExtra(Intent intent, String key, Parcelable.Creator<T> creator) {
    byte[] bytes = intent.getByteArrayExtra(key);
    return ParcelableUtils.unmarshall(bytes, creator);
}


问:
select column names containing string programmatically
Given a data frame like:

```<code>df <- data.frame(z_a = 1:2,
                 z_b = 1:2,
                 y_a = 3:4,
                 y_b = 3:4)
</code>```

I can select columns names that contain a character with:

```<code>library(dplyr)
df %>% select(contains("a"), contains("b"))

  z_a y_a z_b y_b
1   1   3   1   3
2   2   4   2   4
</code>```

NOTE that the column order has changed. Columns containing a come first before columns containing b

I'd like to select column names that contain characters in a vector and that reorders the columns.

```<code>searchfor <- letters[1:2]
</code>```

Using searchfor, I'd like to make the following expression and use it in a select statement:

```<code>E <- quote(contains(searchfor[1]), contains(searchfor[2]))
df %>% select_(E)
</code>```

答:
We can do </p>

```<code>df %>%
   select_at(vars(matches(paste(searchfor, collapse="|")))) %>%
   select(order(sub(".*_", "", names(.))))
</code>```

Body:
Given a data frame like:

df <- data.frame(z_a = 1:2,
                 z_b = 1:2,
                 y_a = 3:4,
                 y_b = 3:4)

I can select columns names that contain a character with:

library(dplyr)
df %>% select(contains("a"), contains("b"))

  z_a y_a z_b y_b
1   1   3   1   3
2   2   4   2   4

NOTE that the column order has changed. Columns containing a come first before columns containing b

I'd like to select column names that contain characters in a vector and that reorders the columns.

searchfor <- letters[1:2]

Using searchfor, I'd like to make the following expression and use it in a select statement:

E <- quote(contains(searchfor[1]), contains(searchfor[2]))
df %>% select_(E)

Body:
We can do

df %>%
   select_at(vars(matches(paste(searchfor, collapse="|")))) %>%
   select(order(sub(".*_", "", names(.))))


问:
C# how to load a form with marquee progress bar?
I created a loadingForm with only a progress bar with marquee style. In my mainForm I'm trying to do this:

```<code>//before downloading
loadingForm lf = new loadingForm();
lf.Show();
//start downloading
//finishdownloading
lf.Close();
</code>```

The loadingForm was shown but the progress bar didn't appear, and the form looked like it was crash. after finishing downloading, the loadingForm was closed and my app continued to run normally. In loadingForm I only have:

```<code>void loadingForm_Load(object sender, EventArgs e)
{
     progressbar1.visible = true;
}
</code>```

I already set progressbar1 style to marquee in loadingForm.design. How do I fix this? thanks for your help in advance.

答: The UI thread might not have "resources" to redraw the ui, you should use the background worker as mentioned, or process the application messages in the queue. From the Show() method to the Close() method you should be sure to call Application.DoEvents(), so all windows messages will be processed (along with redrawing messages to your application form)</p>

Body:
I created a loadingForm with only a progress bar with marquee style. In my mainForm I'm trying to do this:

//before downloading
loadingForm lf = new loadingForm();
lf.Show();
//start downloading
//finishdownloading
lf.Close();

The loadingForm was shown but the progress bar didn't appear, and the form looked like it was crash. after finishing downloading, the loadingForm was closed and my app continued to run normally. In loadingForm I only have:

void loadingForm_Load(object sender, EventArgs e)
{
     progressbar1.visible = true;
}

I already set progressbar1 style to marquee in loadingForm.design. How do I fix this? thanks for your help in advance.


问:
There is an error in XML document C# Xamarin
I am getting the following error in my Xamarin Forms app but I don't know what the problem is:

System.InvalidOperationException: There is an error in XML document.
 items xmlns=''> was not expected

I have a basic XML file that I have added as an embedded resource:

```<code><?xml version="1.0" encoding="UTF-8"?>
  <items>
    <item>
        <id>1</id>
        <name>a name</name>
        <address>an address</address>
        <postcode>a postcode</postcode>
    </item>
    <item>
        <id>2</id>
        <name>name 2</name>
        <address>address 2</address>
        <postcode>postcode 2</postcode>
    </item>
    <item>
        <id>3</id>
        <name>name 3</name>
        <address>address 3</address>
        <postcode>postcode 3</postcode>
    </item>
</items>
</code>```

I have the following method to read the XML file:

```<code>    public static List<Item> GetItemList()
    {
        var assembly = typeof(MyNewPage).GetTypeInfo().Assembly;
        Stream stream = assembly.GetManifestResourceStream("MyNewApp.allitems.xml");

        List<Item> itemsFullList;

        using (var reader = new System.IO.StreamReader(stream))
        {
            var serializer = new XmlSerializer(typeof(List<Item>));
            itemsFullList = (List<Item>)serializer.Deserialize(reader);
        }

        return itemsFullList;
    }
</code>```

I also have a standard class to represent each item:

```<code>public class Item
{
    public Item()
    {
    }

    public string name { get; set; }
    public string address { get; set; }
    public string postcode { get; set; }

}
</code>```

I don't know why I am getting the error as from what I can see, the XML document is formatted just fine.  I am using this article as a guide but I am having no luck: https://developer.xamarin.com/guides/xamarin-forms/application-fundamentals/files/

Anyone know what I am doing wrong here?

Thanks.

答:
That class structure will not deserialize to a list of Item, it will deserialize to a single object that has a property of type Item[].

You will probably want to change class and property names to make more sense, but this is how Visual Studio generates the class structure based on your xml (Edit > Paste Special)

```<code>void Main()
{
    string xml = @"<?xml version=""1.0"" encoding=""UTF-8""?>
  <items>
    <item>
        <id>1</id>
        <name>a name</name>
        <address>an address</address>
        <postcode>a postcode</postcode>
    </item>
    <item>
        <id>2</id>
        <name>name 2</name>
        <address>address 2</address>
        <postcode>postcode 2</postcode>
    </item>
    <item>
        <id>3</id>
        <name>name 3</name>
        <address>address 3</address>
        <postcode>postcode 3</postcode>
    </item>
</items>";

    using (MemoryStream ms = new MemoryStream())
    {
        XDocument.Parse(xml).Save(ms);
        ms.Position = 0;
        using (var reader = new System.IO.StreamReader(ms))
        {
            var serializer = new XmlSerializer(typeof(items));
            var itemsFullList = (items)serializer.Deserialize(reader);
        }
    }
}

/// <remarks/>
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)]
[System.Xml.Serialization.XmlRootAttribute(ElementName = "items", Namespace = "", IsNullable = false)]
public partial class items
{

    private itemsItem[] itemField;

    /// <remarks/>
    [System.Xml.Serialization.XmlElementAttribute("item")]
    public itemsItem[] item
    {
        get
        {
            return this.itemField;
        }
        set
        {
            this.itemField = value;
        }
    }
}

/// <remarks/>
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)]
public partial class itemsItem
{

    private byte idField;

    private string nameField;

    private string addressField;

    private string postcodeField;

    /// <remarks/>
    public byte id
    {
        get
        {
            return this.idField;
        }
        set
        {
            this.idField = value;
        }
    }

    /// <remarks/>
    public string name
    {
        get
        {
            return this.nameField;
        }
        set
        {
            this.nameField = value;
        }
    }

    /// <remarks/>
    public string address
    {
        get
        {
            return this.addressField;
        }
        set
        {
            this.addressField = value;
        }
    }

    /// <remarks/>
    public string postcode
    {
        get
        {
            return this.postcodeField;
        }
        set
        {
            this.postcodeField = value;
        }
    }
}
</code>```

Body:
I am getting the following error in my Xamarin Forms app but I don't know what the problem is:

System.InvalidOperationException: There is an error in XML document.
 items xmlns=''> was not expected

I have a basic XML file that I have added as an embedded resource:

<?xml version="1.0" encoding="UTF-8"?>
  <items>
    <item>
        <id>1</id>
        <name>a name</name>
        <address>an address</address>
        <postcode>a postcode</postcode>
    </item>
    <item>
        <id>2</id>
        <name>name 2</name>
        <address>address 2</address>
        <postcode>postcode 2</postcode>
    </item>
    <item>
        <id>3</id>
        <name>name 3</name>
        <address>address 3</address>
        <postcode>postcode 3</postcode>
    </item>
</items>

I have the following method to read the XML file:

    public static List<Item> GetItemList()
    {
        var assembly = typeof(MyNewPage).GetTypeInfo().Assembly;
        Stream stream = assembly.GetManifestResourceStream("MyNewApp.allitems.xml");

        List<Item> itemsFullList;

        using (var reader = new System.IO.StreamReader(stream))
        {
            var serializer = new XmlSerializer(typeof(List<Item>));
            itemsFullList = (List<Item>)serializer.Deserialize(reader);
        }

        return itemsFullList;
    }

I also have a standard class to represent each item:

public class Item
{
    public Item()
    {
    }

    public string name { get; set; }
    public string address { get; set; }
    public string postcode { get; set; }

}

I don't know why I am getting the error as from what I can see, the XML document is formatted just fine.  I am using this article as a guide but I am having no luck: https://developer.xamarin.com/guides/xamarin-forms/application-fundamentals/files/

Anyone know what I am doing wrong here?

Thanks.

Body:
That class structure will not deserialize to a list of Item, it will deserialize to a single object that has a property of type Item[].

You will probably want to change class and property names to make more sense, but this is how Visual Studio generates the class structure based on your xml (Edit > Paste Special)

void Main()
{
    string xml = @"<?xml version=""1.0"" encoding=""UTF-8""?>
  <items>
    <item>
        <id>1</id>
        <name>a name</name>
        <address>an address</address>
        <postcode>a postcode</postcode>
    </item>
    <item>
        <id>2</id>
        <name>name 2</name>
        <address>address 2</address>
        <postcode>postcode 2</postcode>
    </item>
    <item>
        <id>3</id>
        <name>name 3</name>
        <address>address 3</address>
        <postcode>postcode 3</postcode>
    </item>
</items>";

    using (MemoryStream ms = new MemoryStream())
    {
        XDocument.Parse(xml).Save(ms);
        ms.Position = 0;
        using (var reader = new System.IO.StreamReader(ms))
        {
            var serializer = new XmlSerializer(typeof(items));
            var itemsFullList = (items)serializer.Deserialize(reader);
        }
    }
}

/// <remarks/>
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)]
[System.Xml.Serialization.XmlRootAttribute(ElementName = "items", Namespace = "", IsNullable = false)]
public partial class items
{

    private itemsItem[] itemField;

    /// <remarks/>
    [System.Xml.Serialization.XmlElementAttribute("item")]
    public itemsItem[] item
    {
        get
        {
            return this.itemField;
        }
        set
        {
            this.itemField = value;
        }
    }
}

/// <remarks/>
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)]
public partial class itemsItem
{

    private byte idField;

    private string nameField;

    private string addressField;

    private string postcodeField;

    /// <remarks/>
    public byte id
    {
        get
        {
            return this.idField;
        }
        set
        {
            this.idField = value;
        }
    }

    /// <remarks/>
    public string name
    {
        get
        {
            return this.nameField;
        }
        set
        {
            this.nameField = value;
        }
    }

    /// <remarks/>
    public string address
    {
        get
        {
            return this.addressField;
        }
        set
        {
            this.addressField = value;
        }
    }

    /// <remarks/>
    public string postcode
    {
        get
        {
            return this.postcodeField;
        }
        set
        {
            this.postcodeField = value;
        }
    }
}


问:
InputStream.read() unexpectedly returns number of bytes instead of -1
When I run read() in Eclipse and enter chars at the console followed by ENTER, the returned value is the number of bytes entered, not -1, though the string I enter into the console is terminated by ENTER, which as I understand generates end-of-stream condition..

The only explanation I can think of is that ENTER signals end-of-stream for the console itself, without being interpreted by read() as EOF

答:
the string I enter into the console is terminated by ENTER, which as I understand generates end-of-stream condition

No, pressing Enter does not generate end-of-stream condition. Depending on your operating system, it is usually either a Ctrl+d or Ctrl+z.

Moreover, read will return a number of bytes it reads on first call, even if you end console's stream. The second call, when the stream is already closed, will produce -1. This behavior is correct, otherwise your program would not receive the "tail end" of the data entered on the console just prior to stream termination.


问:
Ziggurat matrix doesn't work with "for" and "repeat" loops in R - Why?
I'm a beginner in R. I cannot understand why "for" loops doesn't work in my matrix. I need to build ziggurat in which I enter "n" in function that will have to return a matrix like in the picture.
screenshot
This code works with n is equal to 5, or less than 5. But when it's bigger than 5, "for" loop doens't run through all (1:hunt) number. For example, see the picture below
screenshot 2
I tried to use "repeat" loop but it doesn't work too. Where is a mistake in my code?</p>

```<code>build_ziggurat <- function(n){
h<-1
hunt <- n-4
if(n==1){
 m<- matrix(1, nrow = 1, ncol = 1)
  } else {
  if(n<5){
  d <- matrix(h, ncol = 2*n-h, nrow=2*n-h)
  d[2:(n+n-2),2:(n+n-2)]<-h+1;d
  d[(n-h):(n+h), (n-h):(n+h)]<-n-h;d
  d[n,n]<-n;d
  print(d)
} else {

  for(i in hunt:1){
    h<-1
      t <- matrix(h, ncol = 2*n-h, nrow=2*n-h)
      t[2:(n+n-2),2:(n+n-2)]<-h+1
      t[(n-h-i):(n+h+i), (n-h-i):(n+h+i)]<-(n-h-i)
      t[(n-h):(n+h),(n-h):(n+h)]<-n-h
      t[n,n]<-n
      return(t)

  }

}
}
if(n==1) m
}
</code>```

答:
Are you looking for something like that?</p>

```<code>zigguratCreator <- function(n){
  out <- mat.or.vec(nr = (n - 1)*2 + 1, nc = (n - 1)*2 + 1) + 1
  for(i in seq(n - 1)){
    out[seq(i + 1, nrow(out) - i), seq(i + 1, ncol(out) - i)] <- i + 1
  }

  return(out)
}

zigguratCreator(n = 6)
</code>```

Body:
I'm a beginner in R. I cannot understand why "for" loops doesn't work in my matrix. I need to build ziggurat in which I enter "n" in function that will have to return a matrix like in the picture.
screenshot
This code works with n is equal to 5, or less than 5. But when it's bigger than 5, "for" loop doens't run through all (1:hunt) number. For example, see the picture below
screenshot 2
I tried to use "repeat" loop but it doesn't work too. Where is a mistake in my code?

build_ziggurat <- function(n){
h<-1
hunt <- n-4
if(n==1){
 m<- matrix(1, nrow = 1, ncol = 1)
  } else {
  if(n<5){
  d <- matrix(h, ncol = 2*n-h, nrow=2*n-h)
  d[2:(n+n-2),2:(n+n-2)]<-h+1;d
  d[(n-h):(n+h), (n-h):(n+h)]<-n-h;d
  d[n,n]<-n;d
  print(d)
} else {

  for(i in hunt:1){
    h<-1
      t <- matrix(h, ncol = 2*n-h, nrow=2*n-h)
      t[2:(n+n-2),2:(n+n-2)]<-h+1
      t[(n-h-i):(n+h+i), (n-h-i):(n+h+i)]<-(n-h-i)
      t[(n-h):(n+h),(n-h):(n+h)]<-n-h
      t[n,n]<-n
      return(t)

  }

}
}
if(n==1) m
}

Body:
Are you looking for something like that?

zigguratCreator <- function(n){
  out <- mat.or.vec(nr = (n - 1)*2 + 1, nc = (n - 1)*2 + 1) + 1
  for(i in seq(n - 1)){
    out[seq(i + 1, nrow(out) - i), seq(i + 1, ncol(out) - i)] <- i + 1
  }

  return(out)
}

zigguratCreator(n = 6)


问:
how can i access vuejs data in method
I have saved a collection of data from database to an array in vue.js using ajax request in laravel. I want to get some data from that collection inside a method so that i can make more data for the body but somehow I can not access it. for example, by using the code below.

```<code>var vm = this;
$.get('url', function (response) {
      vm.time_slots = response;
      for( i=0; i < vm.time_slots.length; i++){  //also tried with var/let i
         if(i=0){
            console.log(vm.time_slots[i].start_time);
         }else if(vm.time_slots[i].start_time > vm.time_slots[i-1].start_time){
           console.log(vm.time_slots[i].start_time);
         }
      }
     }, 'json');
</code>```

i get undifined. but if i access it through the console i get what i need. below is the data.

```<code>data: {
  time_slots: [],
  current_timeslots: []
},
</code>```

now each time_slot in time_slots has a start_date end_date etc. i want to access them but i get undefined. even this.time_slots.length is returned as 0, while if i check in console i get 12.
how can i access data with in the method.

答:
I think it seems more about asynchronous problem than Vuejs problem. You just need to remember how asynchronous call behave in javascript. Asynchronous call will execute it's task without blocking the next line of code. In other words, asynchronous call will executed almost at the same time the next line of code executed. For your case:

```<code>$.get('url', function (response) {
  // if you want to do operations (formatting data, do some calculation, or set your vue instance data) immediately after $.get returns data, put your operations inside this callback

}, 'json');
// this is the next line of code, and will be executed almost at the same time $.get executed
// if you put those operations here (outset $.get method), $.get method hasn't finished yet because asynchronous call need more time to finish, so you don't have any data to be processed at that time, that's why it show 'undefined'
</code>```

Why accessing from console returns data? It's because the $.get has already finished before you access your console. If you're unlucky or $.get need more time to finish than the time you access the console, you wouldn't get the data anyway

Hope this can help

Title: how can i access vuejs data in method

Body:
I have saved a collection of data from database to an array in vue.js using ajax request in laravel. I want to get some data from that collection inside a method so that i can make more data for the body but somehow I can not access it. for example, by using the code below.

var vm = this;
$.get('url', function (response) {
      vm.time_slots = response;
      for( i=0; i < vm.time_slots.length; i++){  //also tried with var/let i
         if(i=0){
            console.log(vm.time_slots[i].start_time);
         }else if(vm.time_slots[i].start_time > vm.time_slots[i-1].start_time){
           console.log(vm.time_slots[i].start_time);
         }
      }
     }, 'json');

i get undifined. but if i access it through the console i get what i need. below is the data.

data: {
  time_slots: [],
  current_timeslots: []
},

now each time_slot in time_slots has a start_date end_date etc. i want to access them but i get undefined. even this.time_slots.length is returned as 0, while if i check in console i get 12.
how can i access data with in the method.

Body:
I think it seems more about asynchronous problem than Vuejs problem. You just need to remember how asynchronous call behave in javascript. Asynchronous call will execute it's task without blocking the next line of code. In other words, asynchronous call will executed almost at the same time the next line of code executed. For your case:

$.get('url', function (response) {
  // if you want to do operations (formatting data, do some calculation, or set your vue instance data) immediately after $.get returns data, put your operations inside this callback

}, 'json');
// this is the next line of code, and will be executed almost at the same time $.get executed
// if you put those operations here (outset $.get method), $.get method hasn't finished yet because asynchronous call need more time to finish, so you don't have any data to be processed at that time, that's why it show 'undefined'

Why accessing from console returns data? It's because the $.get has already finished before you access your console. If you're unlucky or $.get need more time to finish than the time you access the console, you wouldn't get the data anyway

Hope this can help


答:
I do not think that you need iterators here. However, there are many other possible solutions you could use, like recursion. Nevertheless, I have just modified your code as the following:

```<code>    final List<String> fname = new ArrayList<String>(Arrays.asList(fullname.split("")));
    // defining a list that will hold the unique elements.
    final List<String> resultList = new ArrayList<>();
    // defining a list that will hold the number of replication for every item in the fname list; the order here is same to the order in resultList
    final ArrayList<Integer> counter = new ArrayList<>();

    for (int element = 0; element < fname.size(); element++) {
        int count = 1;
        for (int run = (element + 1); run < fname.size(); run++) {
            if ((fname.get(element)).equals(fname.get(run))) {
                count++;
                // we remove the element that has been already counted and return the index one step back to start counting over.
                fname.remove(run--);
            }
        }
        // we add the element to the resulted list and counter of that element
        counter.add(count);
        resultList.add(fname.get(element));
    }
    // here we print out both lists.
    System.out.println(resultList);
    System.out.println(counter);
</code>```

Assuming String fullname = "StringOfSomeStaff"; the output will be as the following:

```<code>[S, t, r, i, n, g, O, f, o, m, e, a]
[3, 2, 1, 1, 1, 1, 1, 3, 1, 1, 1, 1]
</code>```

Title: Count and remove similar elements in a list while iterating through it

Body:
I used many references in the site to build up my program but I'm kind of stuck right now. I think using iterator will do the job. Sadly even though I went through questions which had iterator, I couldn't get the way of using it properly to implement it on my code.

I want to,
      1. remove the similar elements found in the list fname
      2. count & add the that count of each element found in fname to
          counter.

Please help me do the above using iterator or with any other method. Following is my code,

List<String> fname = new ArrayList<>(Arrays.asList(fullname.split(""))); //Assigning the string to a list//

    int count = 1;
    ArrayList<Integer> counter = new ArrayList<>();
    List<String> holder = new ArrayList<>();

    for(int element=0; element<=fname.size; element++)
    {
        for(int run=(element+1); run<=fname.size; run++)
        {
            if((fname.get(element)).equals(fname.get(run)))
            {
                count++;
                holder.add(fname.get(run));
            }

            counter.add(count);
        }

        holder.add(fname.get(element));
        fname.removeAll(holder);
    }

    System.out.println(fname);
    System.out.println(counter);

Thanks.

Body:
I do not think that you need iterators here. However, there are many other possible solutions you could use, like recursion. Nevertheless, I have just modified your code as the following:

    final List<String> fname = new ArrayList<String>(Arrays.asList(fullname.split("")));
    // defining a list that will hold the unique elements.
    final List<String> resultList = new ArrayList<>();
    // defining a list that will hold the number of replication for every item in the fname list; the order here is same to the order in resultList
    final ArrayList<Integer> counter = new ArrayList<>();

    for (int element = 0; element < fname.size(); element++) {
        int count = 1;
        for (int run = (element + 1); run < fname.size(); run++) {
            if ((fname.get(element)).equals(fname.get(run))) {
                count++;
                // we remove the element that has been already counted and return the index one step back to start counting over.
                fname.remove(run--);
            }
        }
        // we add the element to the resulted list and counter of that element
        counter.add(count);
        resultList.add(fname.get(element));
    }
    // here we print out both lists.
    System.out.println(resultList);
    System.out.println(counter);

Assuming String fullname = "StringOfSomeStaff"; the output will be as the following:

[S, t, r, i, n, g, O, f, o, m, e, a]
[3, 2, 1, 1, 1, 1, 1, 3, 1, 1, 1, 1]


问:
Confused on Error Handling in Swift 3
I got confused error handling in swift3. I try to do like  "if XX function got error then try YY function"
Let me show you what I try:

```<code>    class MyClass {
      enum error: Error
      {
        case nilString
      }
      func findURL() {
            do {
                let opt = try HTTP.GET(url_adr!)
                opt.start { response in
                    if let err = response.error {
                        print("error: \(err.localizedDescription)")
                        return //also notify app of failure as needed
                    }
                    do
                    {
/* This is func1. and got error. I want to if this function has error then go next function. */
                            try self.stringOperation(data: response.description)
                        }
                        catch{
                            print("doesn't work on func1. trying 2nd func")
                          self.stringOperation2(data:response.descritption)
                        }

                    }
                } catch let error {
                    print("got an error creating the request: \(error)")
                }
         }
         func stringOperation(data:String)throws -> Bool{
                do{
/** 1 **/
                        if let _:String = try! data.substring(from: data.index(of: "var sources2")!){
                            print("its done")
                        }else{
                        throw error.nilString
             }
</code>```

IN 1: I got this fatal error on this line:
"fatal error: unexpectedly found nil while unwrapping an Optional value" and program crashed.
I googled error handling try to understand and apply to in my code. However not succeed yet. Can someone explain where did I wrong?

Additional info: I got String extension for .substring(from:...) , and .index(of:"str"). So these lines doesn't got you confused.

答:
As a general rule, try avoiding using force unwrapping (!), where you have

```<code>if let _: String= try! data.substring...
</code>```

Instead use

```<code>if let index = data.index(of: "var sources2"),
    let _: String = try? data.substring(from: index) { ... } else { ... }
</code>```

That way you remove the two force unwraps that may be causing your crash. You already have the if let protection for catching the nil value, so you can make the most of it by using the conditional unwrapping.

Title: Confused on Error Handling in Swift 3

Body:
I got confused error handling in swift3. I try to do like  "if XX function got error then try YY function"
Let me show you what I try:

    class MyClass {
      enum error: Error
      {
        case nilString
      }
      func findURL() {
            do {
                let opt = try HTTP.GET(url_adr!)
                opt.start { response in
                    if let err = response.error {
                        print("error: \(err.localizedDescription)")
                        return //also notify app of failure as needed
                    }
                    do
                    {
/* This is func1. and got error. I want to if this function has error then go next function. */
                            try self.stringOperation(data: response.description)
                        }
                        catch{
                            print("doesn't work on func1. trying 2nd func")
                          self.stringOperation2(data:response.descritption)
                        }

                    }
                } catch let error {
                    print("got an error creating the request: \(error)")
                }
         }
         func stringOperation(data:String)throws -> Bool{
                do{
/** 1 **/
                        if let _:String = try! data.substring(from: data.index(of: "var sources2")!){
                            print("its done")
                        }else{
                        throw error.nilString
             }

IN 1: I got this fatal error on this line:
"fatal error: unexpectedly found nil while unwrapping an Optional value" and program crashed.
I googled error handling try to understand and apply to in my code. However not succeed yet. Can someone explain where did I wrong?

Additional info: I got String extension for .substring(from:...) , and .index(of:"str"). So these lines doesn't got you confused.

Body:
As a general rule, try avoiding using force unwrapping (!), where you have

if let _: String= try! data.substring...

Instead use

if let index = data.index(of: "var sources2"),
    let _: String = try? data.substring(from: index) { ... } else { ... }

That way you remove the two force unwraps that may be causing your crash. You already have the if let protection for catching the nil value, so you can make the most of it by using the conditional unwrapping.