问:
Error unwrapping UITableView cell
I know I am force unwrapping a nil but I dont know how to fix it.

I am just trying to follow a tutorial and can't get help from the author. I am getting this error:

"Thread 1: Fatal error: Unexpectedly found nil while unwrapping an Optional value"

```<code>override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "firstcell")
    cell?.textLabel?.text = firstTableArrary[indexPath.row]
    return cell!
</code>```

答: Are you sure you registered the cell's identifier in the storyboard or programmatically? If you did, check the spelling (case sensitive) of the reuse identifier. </p>

Title: Error unwrapping UITableView cell

Body:
I know I am force unwrapping a nil but I dont know how to fix it.

I am just trying to follow a tutorial and can't get help from the author. I am getting this error:

"Thread 1: Fatal error: Unexpectedly found nil while unwrapping an Optional value"

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "firstcell")
    cell?.textLabel?.text = firstTableArrary[indexPath.row]
    return cell!


来源: stackexchange

问:
Xamarin Forms error while writing anim R$anim.class
Hello i am update to visual studio community 2017 15.5 on debug i have this error</p>

```<code>obj\Debug\android\src\android\support\compat\R.java:11: error: error while writing anim: obj\Debug\android\bin\classes\android\support\compat\R$anim.class (El proceso no tiene acceso al archivo porque est├í siendo utilizado por otro proceso)
3>      public static final class anim {
3>                          ^
3>  Note: Some input files use or override a deprecated API.
3>  Note: Recompile with -Xlint:deprecation for details.
3>  Note: Some input files use unchecked or unsafe operations.
3>  Note: Recompile with -Xlint:unchecked for details.
3>  1 error
</code>```

答:
Same here, always problems when xamarin/ms releases new ver :-(
Restart VS helps for a while...</p>

ContentLicense: CC BY-SA 3.0

Body:
Hello i am update to visual studio community 2017 15.5 on debug i have this error

obj\Debug\android\src\android\support\compat\R.java:11: error: error while writing anim: obj\Debug\android\bin\classes\android\support\compat\R$anim.class (El proceso no tiene acceso al archivo porque est├í siendo utilizado por otro proceso)
3>      public static final class anim {
3>                          ^
3>  Note: Some input files use or override a deprecated API.
3>  Note: Recompile with -Xlint:deprecation for details.
3>  Note: Some input files use unchecked or unsafe operations.
3>  Note: Recompile with -Xlint:unchecked for details.
3>  1 error


问:
Replace a string with another string within a file in Python
You will be provided a file path for input I, a file path for output O, a string S, and a string T.

Read the contents of I, replacing each occurrence of S with T and write the resulting information to file O.

You should replace O if it already exists.

```<code># Get the filepath from the command line
import sys
I= sys.argv[1]
O= sys.argv[2]
S= sys.argv[3]
T= sys.argv[4]

# Your code goes here

# open our file for writing
file1= open(I, 'r')
file2= open(O, 'w')

file2.replace(S, T)

file1.close()
file2.close()

file2= open('O', 'r')

print(file2)
</code>```

Here's the error I keep getting:

Traceback (most recent call last):
  File "write-text-file.py", line 15, in
    file2.replace(S, T)
AttributeError: '_io.TextIOWrapper' object has no attribute 'replace'

答:
file2 is a file object not a string, file object's do not have replace method

try

```<code>with open(I, 'r') as file1, open(O, 'w') as file2:
    for line in file1.readlines():
        line=line.replace(S,T)
        file2.write(line)
</code>```

Body:
You will be provided a file path for input I, a file path for output O, a string S, and a string T.

Read the contents of I, replacing each occurrence of S with T and write the resulting information to file O.

You should replace O if it already exists.

# Get the filepath from the command line
import sys
I= sys.argv[1]
O= sys.argv[2]
S= sys.argv[3]
T= sys.argv[4]

# Your code goes here

# open our file for writing
file1= open(I, 'r')
file2= open(O, 'w')

file2.replace(S, T)

file1.close()
file2.close()

file2= open('O', 'r')

print(file2)

Here's the error I keep getting:

Traceback (most recent call last):
  File "write-text-file.py", line 15, in
    file2.replace(S, T)
AttributeError: '_io.TextIOWrapper' object has no attribute 'replace'

Body:
file2 is a file object not a string, file object's do not have replace method

try

with open(I, 'r') as file1, open(O, 'w') as file2:
    for line in file1.readlines():
        line=line.replace(S,T)
        file2.write(line)


问:
Event handle on customized ListView
```<code>public class ActivityForShow extends Activity

{
     //have a ListView layout
     ListView.setAdapter(SingleRowAdapter);
}

public class SingleRowAdapter extends ArrayAdapter
{
    //every row has a CheckBox ,a TextView and a Button
}
</code>```

Now I want to handle CheckBox and Button events,do some background work and show result in a dialog.

But how to getRefences of Checkbox and Button in ActivityForShow?

findViewById() will cause Exception.

答:
It's obvious it gives error with finviewbyid method because it is used for when reference by xml ele. You can use this link for study:

http://developer.android.com/reference/android/widget/ArrayAdapter.html

ContentLicense: CC BY-SA 2.5

Title: Event handle on customized ListView

Body:
public class ActivityForShow extends Activity

{
     //have a ListView layout
     ListView.setAdapter(SingleRowAdapter);
}

public class SingleRowAdapter extends ArrayAdapter
{
    //every row has a CheckBox ,a TextView and a Button
}

Now I want to handle CheckBox and Button events,do some background work and show result in a dialog.

But how to getRefences of Checkbox and Button in ActivityForShow?

findViewById() will cause Exception.

ContentLicense: CC BY-SA 4.0


问:
Read multiple rows from Oracle table
I am trying to read a table in Oracle from PowerShell and want to save them in an ArrayList. The connection is working but reading the any rows after the first doesn't work.

Here's what I'm trying to do.

```<code>$rows = New-Object System.Collections.ArrayList
class Table {
    [String] $name
    [String] $type
}

try {
    $oraConn.Open()
    $sql = [string]::Format("select name, type from source_table where type = 'running'")

    $oraCmd = New-Object System.Data.OracleClient.OracleCommand($sql, $oraConn)
    $reader = $oraCmd.ExecuteReader()

    #add tables to arraylist
    while ($reader.Read()) {
        $table = New-Object Table
        $table.name = $reader["name"];
        $table.type = $reader["type"];
        [void]$rows.Add($table)
    }
    Write-Host "rows collected"
}
</code>```

My problem is, I only read the first row of the table, how can I tell Oracle to read them all? Would I have to countthem first and then query for each row?

I check the contents of $rows later in the code, it's not really relevant to the question since I know that this part works, so I left it out.
I know that my query returns something because I tried it in Oracle.

Do I need a foreach loop? It would make sense but how can I tell Oracle to do that? Would I have to query for each row of the table and set a counter to query only one row at a time?

I hope someone can help me and point me in the right direction, since I'm already trying a long time to get my script working. I got most of the logic for my script, but if I can't load the rows into my list, my logic doesn't help me at all.

答:
Use the following code snippet as a some base for an own solution:</p>

```<code>$cs = 'data source=oradb;user id=/;dba privilege=sysdba'
$oc = new-object oracle.dataaccess.client.oracleconnection $cs
$oc.open()
$cm = new-object oracle.dataaccess.client.oraclecommand
$cm.connection = $oc
$cm.commandtext = "select name, type from source_table where type = 'running'"
$da = new-object oracle.dataaccess.client.oracledataadapter
$da.selectcommand = $cm
$tbl = new-object data.datatable
$da.fill($tbl)
$tbl | %{"$($_.name = $_.type)"}
</code>```

Title: Read multiple rows from Oracle table

Body:
I am trying to read a table in Oracle from PowerShell and want to save them in an ArrayList. The connection is working but reading the any rows after the first doesn't work.

Here's what I'm trying to do.

$rows = New-Object System.Collections.ArrayList
class Table {
    [String] $name
    [String] $type
}

try {
    $oraConn.Open()
    $sql = [string]::Format("select name, type from source_table where type = 'running'")

    $oraCmd = New-Object System.Data.OracleClient.OracleCommand($sql, $oraConn)
    $reader = $oraCmd.ExecuteReader()

    #add tables to arraylist
    while ($reader.Read()) {
        $table = New-Object Table
        $table.name = $reader["name"];
        $table.type = $reader["type"];
        [void]$rows.Add($table)
    }
    Write-Host "rows collected"
}

My problem is, I only read the first row of the table, how can I tell Oracle to read them all? Would I have to countthem first and then query for each row?

I check the contents of $rows later in the code, it's not really relevant to the question since I know that this part works, so I left it out.
I know that my query returns something because I tried it in Oracle.

Do I need a foreach loop? It would make sense but how can I tell Oracle to do that? Would I have to query for each row of the table and set a counter to query only one row at a time?

I hope someone can help me and point me in the right direction, since I'm already trying a long time to get my script working. I got most of the logic for my script, but if I can't load the rows into my list, my logic doesn't help me at all.

Body:
Use the following code snippet as a some base for an own solution:

$cs = 'data source=oradb;user id=/;dba privilege=sysdba'
$oc = new-object oracle.dataaccess.client.oracleconnection $cs
$oc.open()
$cm = new-object oracle.dataaccess.client.oraclecommand
$cm.connection = $oc
$cm.commandtext = "select name, type from source_table where type = 'running'"
$da = new-object oracle.dataaccess.client.oracledataadapter
$da.selectcommand = $cm
$tbl = new-object data.datatable
$da.fill($tbl)
$tbl | %{"$($_.name = $_.type)"}


问:
Using dot memory API to take multiple snapshot on same .dmv file
I am trying to profile my specific code using dot memory api. When I call the dump() method my expectation is to take snapshot and save it to dir.

I am trying to take two snapshot here one before executing my code and after executing my code by calling dump() method.

Is it possible to create the both snapshot in the same output file as we option to do it from Stand alone dot memory?

Appreciate your suggestion. following is the code snippet

```<code>SelfAttach.Attach(new SaveSnapshotProfilingConfig
{
   ProfilingControlKind = ProfilingControlKind.Api,
   SaveDir = "D:\\SelfProfiling",
   RedistDir = "D:\\Softwares\\JetBrains.Profiler.SelfSdk.2017.2.2",
   ProfilingType = ProfilingType.Memory,
   ListFile = "D:\\snapshot_list.xml"
});

while (SelfAttach.State != SelfApiState.Active)
{
     Thread.Sleep(250);  // wait until API starts
}

if (MemoryProfiler.IsActive)
{
   MemoryProfiler.Dump();
   MyMethodTobeProfiled();
   MemoryProfiler.Dump();
}

if (MemoryProfiler.CanDetach)
   MemoryProfiler.Detach();
</code>```

答:
Is it possible to create the both snapshot in the same output file as we option to do it from Stand alone dot memory?

A snapshot is normally a bunch of files. .dmw is an archive of a snapshot. This is the design now. The reason is to ability to start sending a snapshot immediately to a remote host. This is the R# requirement.

Body:
I am trying to profile my specific code using dot memory api. When I call the dump() method my expectation is to take snapshot and save it to dir.

I am trying to take two snapshot here one before executing my code and after executing my code by calling dump() method.

Is it possible to create the both snapshot in the same output file as we option to do it from Stand alone dot memory?

Appreciate your suggestion. following is the code snippet

SelfAttach.Attach(new SaveSnapshotProfilingConfig
{
   ProfilingControlKind = ProfilingControlKind.Api,
   SaveDir = "D:\\SelfProfiling",
   RedistDir = "D:\\Softwares\\JetBrains.Profiler.SelfSdk.2017.2.2",
   ProfilingType = ProfilingType.Memory,
   ListFile = "D:\\snapshot_list.xml"
});

while (SelfAttach.State != SelfApiState.Active)
{
     Thread.Sleep(250);  // wait until API starts
}

if (MemoryProfiler.IsActive)
{
   MemoryProfiler.Dump();
   MyMethodTobeProfiled();
   MemoryProfiler.Dump();
}

if (MemoryProfiler.CanDetach)
   MemoryProfiler.Detach();


问:
VSCode. Debug existing application
I have an aplication WpfApp1 that I just created via VS.

I built it via VS with DebugType == full.

Then I open solution folder with VSCode. Set breakpoint, run my app, attach to it, but it say:

no symbols have been loaded for this document

What am I doing wrong?

This is my configuration:

```<code>{
    "name": ".NET Core Attach",
    "type": "clr",
    "request": "attach",
    "processId": "${command:pickProcess}"
}
</code>```

Yes, I now that I can change DebugType to portable and it will work. But I can't do it (I have some resons for it).

答:
Use Visual Studio Community edition to debug WPF or other .NET Standard applications. VS Code is meant for cross-platform development, thus the support of the .NET Standard applications is limited to none. E.g. cross-platform development and debugging is supported as well as Mono and .NET Core projects. But WPF is neither of these so you need to use Comunity edition as a minimum.

Here is more info on the subject.

Title: VSCode. Debug existing application

Body:
I have an aplication WpfApp1 that I just created via VS.

I built it via VS with DebugType == full.

Then I open solution folder with VSCode. Set breakpoint, run my app, attach to it, but it say:

no symbols have been loaded for this document

What am I doing wrong?

This is my configuration:

{
    "name": ".NET Core Attach",
    "type": "clr",
    "request": "attach",
    "processId": "${command:pickProcess}"
}

Yes, I now that I can change DebugType to portable and it will work. But I can't do it (I have some resons for it).


问:
Confused about the depth-first-search result when using Golang
I tried to solve the 'Combination Sum' on leetcode, and the result is wrong when using test case:

[7,3,2] 18

I used C++ with the same logic and passed, but when using Golang, my result is:

[[2,2,2,2,2,2,2,2,2],[2,2,2,2,2,7,3,3],[2,2,2,2,3,7],[2,2,2,3,3,3,3],[2,2,7,7],[2,3,3,3,7],[3,3,3,3,3,3]]

and the correct one should be

[[2,2,2,2,2,2,2,2,2],[2,2,2,2,2,2,3,3],[2,2,2,2,3,7],[2,2,2,3,3,3,3],[2,2,7,7],[2,3,3,3,7],[3,3,3,3,3,3]]

the code is shown below:

```<code>import "sort"
func combinationSum(candidates []int, target int) [][]int {
    result := make([][]int, 0, 0)
    resultp := &result
    sort.Ints(candidates)
    helper(candidates, 0, target, make([]int, 0, 0), resultp, len(candidates))
    return *resultp
}

func helper(nums []int, index int, target int, list []int, resultp *[][]int, length int) {
    if target == 0 {
        *resultp = append(*resultp, list)
        return
    }
    for i := index; i < length; i++ {
        if i != index && nums[i] == nums[i - 1] {
            continue
        }
        if (nums[i] > target) {
            break
        }
        helper(nums, i, target - nums[i], append(list, nums[i]), resultp, length)
    }
}
</code>```

Can anyone tell me why the result is incorrect, I am just confused about the [2,2,2,2,2,7,3,3] in my answer, why the 7 is before the 3 since the array has been sorted? Or anyone can tell me what mistake I have made in my code

答:
So you can see the behavior a bit better by adding some print output:

https://play.golang.org/p/JPmqoAJE4S

Importantly, you can see it at this point:

```<code>0694 helper [2 3 7] 1 1 [2 2 2 2 2 2 2 3] [[2 2 2 2 2 2 2 2 2]] 3
4425 calling down 1 6 [2 2 2 2 2 2] 3
8511 helper [2 3 7] 1 3 [2 2 2 2 2 2 3] [[2 2 2 2 2 2 2 2 2]] 3
8511 calling down 1 3 [2 2 2 2 2 2 3] 3
8162 helper [2 3 7] 1 0 [2 2 2 2 2 2 3 3] [[2 2 2 2 2 2 2 2 2]] 3
8162 solution [2 2 2 2 2 2 3 3] [[2 2 2 2 2 2 2 2 2] [2 2 2 2 2 2 3 3]]
1318 calling down 1 8 [2 2 2 2 2] 3
5089 helper [2 3 7] 1 5 [2 2 2 2 2 3] [[2 2 2 2 2 2 2 2 2] [2 2 2 2 2 3 3 3]] 3
5089 calling down 1 5 [2 2 2 2 2 3] 3
4728 helper [2 3 7] 1 2 [2 2 2 2 2 3 3] [[2 2 2 2 2 2 2 2 2] [2 2 2 2 2 3 3 3]] 3
1318 calling down 2 8 [2 2 2 2 2] 7
3274 helper [2 3 7] 2 1 [2 2 2 2 2 7] [[2 2 2 2 2 2 2 2 2] [2 2 2 2 2 7 3 3]] 3
</code>```

This is the sequence of actions:

You recursively call with [2 2 2 2 2 2 3] and append 3.  You find that this is a valid solution and add [2 2 2 2 2 2 3 3] to the result slice.

You return up a few levels until you're back to [2 2 2 2 2] (before adding the 6th 2) and start trying to add 3s.  You recursively call with [2 2 2 2 2] and append 3.  Unfortunately, this overwrites your existing solution [2 2 2 2 2 2 3 3].  Since it's using the same backing array, you append 3 to the first 5 items in that slice, overwriting the 6th index in the slice you previously added to your solution set.  Your second solution becomes [2 2 2 2 2 3 3 3] (note the 3 in the 6th slot)

You find that this solution set isn't going to work after a couple iterations (at [2 2 2 2 2 3 3]) because the remaining target (2) is less than the last number added (3), so you return up.

You repeat this sequence with a 7 in the 6th slot, overwriting the underlying array index again.  Your second solution becomes [2 2 2 2 2 7 3 3], because you're still using the same underlying array.  You find this solution also won't work, and return up.

After this point, you return up to before the list slice was greater than 4 in length (which is when the slice grew, by default it grows by doubling in size), meaning you're using a different (previous) backing array, which is why further iterations do not further change the existing solutions.  By luck, none of the remaining solutions collide in a similar fashion.

This alternative print version shows you where the backing array changes (by showing where the address of the first entry changes): https://play.golang.org/p/nrgtMyqwow.  As you can see, it changes when you grow beyond lengths 2, 4, and 8, but as you return upwards, you end up reverting back to different backing arrays.

The easiest solution to fix your specific problem is to copy the list slice before adding it to the solution set:

```<code>if target == 0 {
    sol := make([]int, len(list))
    copy(sol, list)
    *resultp = append(*resultp, sol)
    return
}
</code>```

https://play.golang.org/p/3qTKoAumj0

[[2 2 2 2 2 2 2 2 2] [2 2 2 2 2 2 3 3] [2 2 2 2 3 7] [2 2 2 3 3 3 3] [2 2 7 7] [2 3 3 3 7] [3 3 3 3 3 3]]

Body:
I tried to solve the 'Combination Sum' on leetcode, and the result is wrong when using test case:

[7,3,2] 18

I used C++ with the same logic and passed, but when using Golang, my result is:

[[2,2,2,2,2,2,2,2,2],[2,2,2,2,2,7,3,3],[2,2,2,2,3,7],[2,2,2,3,3,3,3],[2,2,7,7],[2,3,3,3,7],[3,3,3,3,3,3]]

and the correct one should be

[[2,2,2,2,2,2,2,2,2],[2,2,2,2,2,2,3,3],[2,2,2,2,3,7],[2,2,2,3,3,3,3],[2,2,7,7],[2,3,3,3,7],[3,3,3,3,3,3]]

the code is shown below:

import "sort"
func combinationSum(candidates []int, target int) [][]int {
    result := make([][]int, 0, 0)
    resultp := &result
    sort.Ints(candidates)
    helper(candidates, 0, target, make([]int, 0, 0), resultp, len(candidates))
    return *resultp
}

func helper(nums []int, index int, target int, list []int, resultp *[][]int, length int) {
    if target == 0 {
        *resultp = append(*resultp, list)
        return
    }
    for i := index; i < length; i++ {
        if i != index && nums[i] == nums[i - 1] {
            continue
        }
        if (nums[i] > target) {
            break
        }
        helper(nums, i, target - nums[i], append(list, nums[i]), resultp, length)
    }
}

Can anyone tell me why the result is incorrect, I am just confused about the [2,2,2,2,2,7,3,3] in my answer, why the 7 is before the 3 since the array has been sorted? Or anyone can tell me what mistake I have made in my code

Body:
So you can see the behavior a bit better by adding some print output:

https://play.golang.org/p/JPmqoAJE4S

Importantly, you can see it at this point:

0694 helper [2 3 7] 1 1 [2 2 2 2 2 2 2 3] [[2 2 2 2 2 2 2 2 2]] 3
4425 calling down 1 6 [2 2 2 2 2 2] 3
8511 helper [2 3 7] 1 3 [2 2 2 2 2 2 3] [[2 2 2 2 2 2 2 2 2]] 3
8511 calling down 1 3 [2 2 2 2 2 2 3] 3
8162 helper [2 3 7] 1 0 [2 2 2 2 2 2 3 3] [[2 2 2 2 2 2 2 2 2]] 3
8162 solution [2 2 2 2 2 2 3 3] [[2 2 2 2 2 2 2 2 2] [2 2 2 2 2 2 3 3]]
1318 calling down 1 8 [2 2 2 2 2] 3
5089 helper [2 3 7] 1 5 [2 2 2 2 2 3] [[2 2 2 2 2 2 2 2 2] [2 2 2 2 2 3 3 3]] 3
5089 calling down 1 5 [2 2 2 2 2 3] 3
4728 helper [2 3 7] 1 2 [2 2 2 2 2 3 3] [[2 2 2 2 2 2 2 2 2] [2 2 2 2 2 3 3 3]] 3
1318 calling down 2 8 [2 2 2 2 2] 7
3274 helper [2 3 7] 2 1 [2 2 2 2 2 7] [[2 2 2 2 2 2 2 2 2] [2 2 2 2 2 7 3 3]] 3

This is the sequence of actions:

You recursively call with [2 2 2 2 2 2 3] and append 3.  You find that this is a valid solution and add [2 2 2 2 2 2 3 3] to the result slice.

You return up a few levels until you're back to [2 2 2 2 2] (before adding the 6th 2) and start trying to add 3s.  You recursively call with [2 2 2 2 2] and append 3.  Unfortunately, this overwrites your existing solution [2 2 2 2 2 2 3 3].  Since it's using the same backing array, you append 3 to the first 5 items in that slice, overwriting the 6th index in the slice you previously added to your solution set.  Your second solution becomes [2 2 2 2 2 3 3 3] (note the 3 in the 6th slot)

You find that this solution set isn't going to work after a couple iterations (at [2 2 2 2 2 3 3]) because the remaining target (2) is less than the last number added (3), so you return up.

You repeat this sequence with a 7 in the 6th slot, overwriting the underlying array index again.  Your second solution becomes [2 2 2 2 2 7 3 3], because you're still using the same underlying array.  You find this solution also won't work, and return up.

After this point, you return up to before the list slice was greater than 4 in length (which is when the slice grew, by default it grows by doubling in size), meaning you're using a different (previous) backing array, which is why further iterations do not further change the existing solutions.  By luck, none of the remaining solutions collide in a similar fashion.

This alternative print version shows you where the backing array changes (by showing where the address of the first entry changes): https://play.golang.org/p/nrgtMyqwow.  As you can see, it changes when you grow beyond lengths 2, 4, and 8, but as you return upwards, you end up reverting back to different backing arrays.

The easiest solution to fix your specific problem is to copy the list slice before adding it to the solution set:

if target == 0 {
    sol := make([]int, len(list))
    copy(sol, list)
    *resultp = append(*resultp, sol)
    return
}

https://play.golang.org/p/3qTKoAumj0

[[2 2 2 2 2 2 2 2 2] [2 2 2 2 2 2 3 3] [2 2 2 2 3 7] [2 2 2 3 3 3 3] [2 2 7 7] [2 3 3 3 7] [3 3 3 3 3 3]]


问:
Best way to send data from ArrayAdapter to MainActivity
I have an ArrayAdapter and while pressing on a button I want to:

delete some data from my Array which is being held in MainActivity

delete one line from txt file (FileManager handles deleting but i have to access a file which is private in MainActivity)

How can I send this data?

```<code>deleteDeckButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            //i've done it with DECK_NAMES being static public in
            //MainActivity and i really dont like this solution
            FileManager deckNamesManager = new FileManager(DECK_NAMES);                 deckNamesManager.deleteLine(manager.getFileName());
            // deck files is static public in MainActivity as well
            deckFiles.remove(getPosition(manager));
            manager.deleteFile();
            notifyDataSetChanged();
        }
  });
</code>```

That's how I'd like my MainActivity to look like:

```<code>public class MainActivity extends AppCompatActivity {

static final int DECK_NAME_REQUEST = 1;

private ListView mListView;
private FlashCardsAdapter deckAdapter;
// ATM deckFiles is static public
private ArrayList<FileManager> deckFiles;
// ATM DECK_NAMES is static public
private File DECK_NAMES; // ATM it's static public
</code>```

EDIT: final version of ArrayAdapter

```<code>public class FlashCardsAdapter extends ArrayAdapter<FileManager> {
interface Callback {
    void onFileDeleted(String fileName);
}

private final Callback mCallback;

public FlashCardsAdapter(Context context, ArrayList<FileManager> users, final Callback callback) {
    super(context, 0, users);
    mCallback = callback;
}
@NonNull
@Override
public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
    final FileManager manager = getItem(position);

    if (convertView == null) {
        convertView = LayoutInflater.from(getContext()).inflate(R.layout.list_view_item, parent, false);
    }

    TextView mainTextView = convertView.findViewById(R.id.deck_name_id);

    Button addCardButton = convertView.findViewById(R.id.action_add_card);

    Button deleteDeckButton = convertView.findViewById(R.id.action_delete);

    mainTextView.setText(manager.getFileName());

    mainTextView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Intent intent = new Intent(getContext(), FlashCardActivity.class);
            intent.putExtra("fileName", manager.getFileName());
            getContext().startActivity(intent);
        }
    });

    addCardButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Intent intent = new Intent(getContext(), AddCardActivity.class);
            intent.putExtra("fileName", manager.getFileName());
            getContext().startActivity(intent);
        }
    });

    deleteDeckButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            manager.deleteFile();
            mCallback.onFileDeleted(manager.getFileName());
        }
    });
    return convertView;
}

}
</code>```

答:
You can send a callback from your adapter back to your activity.

You adapter would have something like that

```<code>class Adapter {
        interface Callback {
            void onFileDeleted(String fileName);
        }

        private final Callback callback;

        Adapter(final Callback callback) {
            this.callback = callback;
        }
        ..
        ..
        ..
        deleteDeckButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                FileManager deckNamesManager = new FileManager(DECK_NAMES); //i've done it with DECK_NAMES being static public in MainActivity and i really dont like this solution
                deckNamesManager.deleteLine(manager.getFileName());
                deckFiles.remove(getPosition(manager)); // deck files is static public in MainActivity as well
                manager.deleteFile();
                notifyDataSetChanged();
                callback.onFileDeleted(manager.getFileName());
            }
        });
    }
</code>```

And when you are creating your adapter you would do something like that

```<code>new Adapter(new Adapter.Callback() {
            @Override
            public void onFileDeleted(final String fileName) {
                // Do your magic in the activity
            }
        });
</code>```

Body:
I have an ArrayAdapter and while pressing on a button I want to:

delete some data from my Array which is being held in MainActivity

delete one line from txt file (FileManager handles deleting but i have to access a file which is private in MainActivity)

How can I send this data?

deleteDeckButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            //i've done it with DECK_NAMES being static public in
            //MainActivity and i really dont like this solution
            FileManager deckNamesManager = new FileManager(DECK_NAMES);                 deckNamesManager.deleteLine(manager.getFileName());
            // deck files is static public in MainActivity as well
            deckFiles.remove(getPosition(manager));
            manager.deleteFile();
            notifyDataSetChanged();
        }
  });

That's how I'd like my MainActivity to look like:

public class MainActivity extends AppCompatActivity {

static final int DECK_NAME_REQUEST = 1;

private ListView mListView;
private FlashCardsAdapter deckAdapter;
// ATM deckFiles is static public
private ArrayList<FileManager> deckFiles;
// ATM DECK_NAMES is static public
private File DECK_NAMES; // ATM it's static public

EDIT: final version of ArrayAdapter

public class FlashCardsAdapter extends ArrayAdapter<FileManager> {
interface Callback {
    void onFileDeleted(String fileName);
}

private final Callback mCallback;

public FlashCardsAdapter(Context context, ArrayList<FileManager> users, final Callback callback) {
    super(context, 0, users);
    mCallback = callback;
}
@NonNull
@Override
public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
    final FileManager manager = getItem(position);

    if (convertView == null) {
        convertView = LayoutInflater.from(getContext()).inflate(R.layout.list_view_item, parent, false);
    }

    TextView mainTextView = convertView.findViewById(R.id.deck_name_id);

    Button addCardButton = convertView.findViewById(R.id.action_add_card);

    Button deleteDeckButton = convertView.findViewById(R.id.action_delete);

    mainTextView.setText(manager.getFileName());

    mainTextView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Intent intent = new Intent(getContext(), FlashCardActivity.class);
            intent.putExtra("fileName", manager.getFileName());
            getContext().startActivity(intent);
        }
    });

    addCardButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Intent intent = new Intent(getContext(), AddCardActivity.class);
            intent.putExtra("fileName", manager.getFileName());
            getContext().startActivity(intent);
        }
    });

    deleteDeckButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            manager.deleteFile();
            mCallback.onFileDeleted(manager.getFileName());
        }
    });
    return convertView;
}

}

Body:
You can send a callback from your adapter back to your activity.

You adapter would have something like that

class Adapter {
        interface Callback {
            void onFileDeleted(String fileName);
        }

        private final Callback callback;

        Adapter(final Callback callback) {
            this.callback = callback;
        }
        ..
        ..
        ..
        deleteDeckButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                FileManager deckNamesManager = new FileManager(DECK_NAMES); //i've done it with DECK_NAMES being static public in MainActivity and i really dont like this solution
                deckNamesManager.deleteLine(manager.getFileName());
                deckFiles.remove(getPosition(manager)); // deck files is static public in MainActivity as well
                manager.deleteFile();
                notifyDataSetChanged();
                callback.onFileDeleted(manager.getFileName());
            }
        });
    }

And when you are creating your adapter you would do something like that

new Adapter(new Adapter.Callback() {
            @Override
            public void onFileDeleted(final String fileName) {
                // Do your magic in the activity
            }
        });


问:
Swift - play sounds parallel with spotify
Is it possible to play a sound in swift when another one is being played, my client wants to make an app that emit sounds while spotify is playing songs too, is that possible ?</p>

答: No you cant have multiple apps playing sounds at the same time.</p>


问:
save html color table in mysql
I am making a website where users can post quilting patterns on a standard HTML table. I created a table where users can click to change the color of a cell of an HTML table, but the changes don't last. Thus, I want to save the entire HTML table to a SQL database. I looked up other posts on saving HTML tables, but they all deal with values (and changing them). I have no values. All I want to do is to save the colors. </p>

答:
Their is a javascript function to get attribute of any html tags
Here u need to use the function to get the color attribute of the respective table and store it in a variable which later can be inserted into database using php function.

ex:
var x = document.getElementsByTagName("H1")[0].getAttribute("class");

reference link:https://www.w3schools.com/jsref/met_element_getattribute.asp

Title: save html color table in mysql


问:
Page context in SignalR typescript client
In a typescript SignalR client how do I access the class scope during return from an async hub event or promise, for example:

Client.ts

```<code>class Client {
    private _elementId: string;

    constructor(elementId: string){
       this._elementId = elementId
    }

    $.connection.hub.start()
        .done(function () {
            $("#" + this._elementId).html("Connection Id" + $.connection.hub.id);
           })
        .fail((err) => {
            $("#" + this._elementId).html("Error occured");
           });

    // handlers - methods called by the SignalR Hub
    $.connection.myHub.client.notification = function (message) {
        $("#" + this._elementId).html(message);
    };

}
</code>```

In promises for both the start and notification methods above the scope of this has been lost, so I can't access the _elementId member variable.

答:
You can use an arrow function () => {} on the done handler to maintain lexical scope similar to how you do with the fail handler. This will allow this to refer the class instance inside the handler:

```<code>class Client {
    private _elementId: string;

    constructor(elementId: string){
       this._elementId = elementId
    }

    $.connection.hub.start()
        .done(() => {
            $("#" + this._elementId).html("Connection Id" + $.connection.hub.id);
        })
        .fail((err) => {
            $("#" + this._elementId).html("Error occured");
        });

    // handlers - methods called by the SignalR Hub
    $.connection.myHub.client.notification = function (message) {
        $("#" + this._elementId).html(message);
    };

}
</code>```

Here is a simple example in action. Notice the message in the console.

Hopefully that helps!

Body:
In a typescript SignalR client how do I access the class scope during return from an async hub event or promise, for example:

Client.ts

class Client {
    private _elementId: string;

    constructor(elementId: string){
       this._elementId = elementId
    }

    $.connection.hub.start()
        .done(function () {
            $("#" + this._elementId).html("Connection Id" + $.connection.hub.id);
           })
        .fail((err) => {
            $("#" + this._elementId).html("Error occured");
           });

    // handlers - methods called by the SignalR Hub
    $.connection.myHub.client.notification = function (message) {
        $("#" + this._elementId).html(message);
    };

}

In promises for both the start and notification methods above the scope of this has been lost, so I can't access the _elementId member variable.

Body:
You can use an arrow function () => {} on the done handler to maintain lexical scope similar to how you do with the fail handler. This will allow this to refer the class instance inside the handler:

class Client {
    private _elementId: string;

    constructor(elementId: string){
       this._elementId = elementId
    }

    $.connection.hub.start()
        .done(() => {
            $("#" + this._elementId).html("Connection Id" + $.connection.hub.id);
        })
        .fail((err) => {
            $("#" + this._elementId).html("Error occured");
        });

    // handlers - methods called by the SignalR Hub
    $.connection.myHub.client.notification = function (message) {
        $("#" + this._elementId).html(message);
    };

}

Here is a simple <a href="https://www.typescriptlang.org/play/#src=class%20Greeter%20%7B%0D%0A%20%20%20%20greeting%3A%20string%3B%0D%0A%0D%0A%20%20%20%20constructor(message%3A%20string)%20%7B%0D%0A%20%20%20%20%20%20%20%20this.greeting%20%3D%20message%3B%0D%0A%0D%0A%20%20%20%20%20%20%20%20this.bar()%3B%0D%0A%20%20%20%20%7D%0D%0A%0D%0A%20%20%20%20foo()%3A%20Promise%3Cvoid%3E%20%7B%0D%0A%20%20%20%20%20%20%20%20return%20new%20Promise(resolve%20%3D%3E%20%7B%0D%0A%20%20%20%20%20%20%20%20%20%20%20%20return%20resolve()%3B%0D%0A%20%20%20%20%20%20%20%20%7D)%3B%0D%0A%20%20%20%20%7D%0D%0A%0D%0A%20%20%20%20bar()%3A%20void%20%7B%0D%0A%20%20%20%20%20%20%20%20this.foo().then(()%20%3D%3E%20%7B%0D%0A%20%20%20%20%20%20%20%20%20%20%20%20console.log(this)%3B%0D%0A%20%20%20%20%20%20%20%20%20%20%20%20console.log(this.greeting)%3B%0D%0A%20%20%20%20%20%20%20%20%7D)%3B%0D%0A%20%20%20%20%7D%0D%0A%7D%0D%0A%0D%0Alet%20greeter%20%3D%20new%20Greeter(%22world%22)%3B" rel="nofollow noreferrer">example in action. Notice the message in the console.

Hopefully that helps!


问:
Is there big syntax differences between Clojure and Lisp
I want to learn new language and I thought to start with Lisp. I want to know  if I learn Lisp do I also know Clojure ( with minimal effort ), is there big syntax differences between Lisp and Clojure ?</p>

答: 90% of what you learn while studying your first Lisp will carry over to your next.</p>


问:
UIViewController with ARSCNView takes significant time before presenting on screen
I have a UIViewController which uses ARSCNView and adding few elements to it via Scenekit as shown in below example. Everything is working fine except when I call present to show this view controller, it takes a significant time or delay before presenting on the screen.</p>

```<code>@IBOutlet var sceneView: ARSCNView!

override func viewDidLoad() {
    super.viewDidLoad()

    sceneView.showsStatistics =  DebugSettings.isDebugActive

    for (index, coach) in coachPositions.enumerated() {
        let coachGeometry = SCNBox(width: 0.1, height: 0.1, length: 0.1, chamferRadius: 0.005)
        let coachNode = TrainEngineNode(position:  SCNVector3Make(0, Float(index) * 0.1, -0.5), geometry: coachGeometry)
        sceneView.scene.rootNode.addChildNode(coachNode)
    }

    self.sceneView.autoenablesDefaultLighting = true
}

override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)

    // Create a session configuration
    let configuration = ARWorldTrackingConfiguration()

    // Run the view's session
    sceneView.session.run(configuration)
}
</code>```

答:
The delay, as everyone has pointed out, is the fact that you're blocking the main thread when you're setting up your scene. All UI updates happen on the main thread and the display refreshes 60 times per second, except the latest iPad Pros which can do 120Hz. This means that any unit of synchronous work you do has to complete in less than 1/60 = 0.016667 seconds.

Your initializer TrainEngineNode(position:geometry:) is likely doing work such as loading resources from a DAE or OBJ file which is probably where all that time is going. I say that because if you change this line:

```<code>let coachNode = TrainEngineNode(position:  SCNVector3Make(0, Float(index) * 0.1, -0.5), geometry: coachGeometry)
</code>```

to this, which I need to do because TrainEngineNode is not provided in your question:

```<code>let coachNode = SCNNode(geometry: coachGeometry)
</code>```

then there is no noticeable delay on an iPhone 7.

SceneKit and ARKit do not require you to make changes on any particular thread, so any time you have this situation you can simply offload the work onto a background queue, or preferably a serial queue that you manage. There are some caveats around doing work at an appropriate time, such as adding your objects to the scene after the ARSession is fully running. For some excellent ideas for patterns you might follow for creating an ARKit application, I recommend this sample provided by Apple.

A simplified example follows:

```<code>class SimpleARViewController: UIViewController {

    @IBOutlet weak var sceneView: ARSCNView!
    weak var activityIndicator: UIActivityIndicatorView?

    var coachPositions = [1, 2, 3, 4, 5]

    let updateQueue = DispatchQueue(label: "com.example.apple-samplecode.arkitexample.serialSceneKitQueue")

    override func viewDidLoad() {
        super.viewDidLoad()

        sceneView.alpha = 0
        view.backgroundColor = .black
        sceneView.isPlaying = false
        sceneView.session.delegate = self

        let activityIndicator = UIActivityIndicatorView(activityIndicatorStyle: .whiteLarge)
        activityIndicator.startAnimating()
        activityIndicator.translatesAutoresizingMaskIntoConstraints = false

        view.addSubview(activityIndicator)
        NSLayoutConstraint.activate([view.centerXAnchor.constraint(equalTo: activityIndicator.centerXAnchor, constant: 0),
                                     view.centerYAnchor.constraint(equalTo: activityIndicator.centerYAnchor, constant: 0)])
        self.activityIndicator = activityIndicator

        sceneView.autoenablesDefaultLighting = true
    }

    private func loadScene() {

        SCNTransaction.begin()
        SCNTransaction.disableActions = true

        for (index, _) in self.coachPositions.enumerated() {
            let coachGeometry = SCNBox(width: 0.1, height: 0.1, length: 0.1, chamferRadius: 0.005)

            // Simulates loading time of `TrainEngineNode(position:geometry:)`
            usleep(500000)

            let coachNode = SCNNode(geometry: coachGeometry)
            coachNode.worldPosition = SCNVector3Make(0, Float(index) * 0.1, -0.5)

            self.sceneView.scene.rootNode.addChildNode(coachNode)
        }

        SCNTransaction.commit()
        self.isLoading = false
    }

    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)

        let configuration = ARWorldTrackingConfiguration()
        sceneView.session.run(configuration)
    }

    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)

        sceneView.session.pause()
    }

    var isLoading = true
    var hasLoaded = false
}

extension SimpleARViewController: ARSessionDelegate {

    func session(_ session: ARSession, didUpdate frame: ARFrame) {

        // Waiting until after the session starts prevents objects from jumping around
        if hasLoaded == false {
            hasLoaded = true

            updateQueue.async { [weak self] in
                self?.loadScene()
            }
        } else if isLoading == false {
            guard let activityIndicator = self.activityIndicator else { return }

            DispatchQueue.main.async {
                UIView.animate(withDuration: 0.35, animations: { [weak self] in
                    self?.sceneView.alpha = 1
                    activityIndicator.alpha = 0
                }, completion: { _ in
                    activityIndicator.removeFromSuperview()
                })
            }
        }
    }
}
</code>```

This code results in the following interaction:

As you can see in the gif, there is no delay in view controller presentation because all of the loading "work" is now done on our private serial queue. Even this contrived example can be further improved by decoupling the creation of the TrainEngineNode's from the time which they are added to the scene. For the sake of brevity, I kept the logic as similar to what you already have while presenting a relatively robust initialization. For a more robust/abstracted implementation of 3D object loading, I recommend looking at VirtualObjectLoader and how it is used in the aforementioned sample project.

Body:
I have a UIViewController which uses ARSCNView and adding few elements to it via Scenekit as shown in below example. Everything is working fine except when I call present to show this view controller, it takes a significant time or delay before presenting on the screen.

@IBOutlet var sceneView: ARSCNView!

override func viewDidLoad() {
    super.viewDidLoad()

    sceneView.showsStatistics =  DebugSettings.isDebugActive

    for (index, coach) in coachPositions.enumerated() {
        let coachGeometry = SCNBox(width: 0.1, height: 0.1, length: 0.1, chamferRadius: 0.005)
        let coachNode = TrainEngineNode(position:  SCNVector3Make(0, Float(index) * 0.1, -0.5), geometry: coachGeometry)
        sceneView.scene.rootNode.addChildNode(coachNode)
    }

    self.sceneView.autoenablesDefaultLighting = true
}

override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)

    // Create a session configuration
    let configuration = ARWorldTrackingConfiguration()

    // Run the view's session
    sceneView.session.run(configuration)
}

Body:
The delay, as everyone has pointed out, is the fact that you're blocking the main thread when you're setting up your scene. All UI updates happen on the main thread and the display refreshes 60 times per second, except the latest iPad Pros which can do 120Hz. This means that any unit of synchronous work you do has to complete in less than 1/60 = 0.016667 seconds.

Your initializer TrainEngineNode(position:geometry:) is likely doing work such as loading resources from a DAE or OBJ file which is probably where all that time is going. I say that because if you change this line:

let coachNode = TrainEngineNode(position:  SCNVector3Make(0, Float(index) * 0.1, -0.5), geometry: coachGeometry)

to this, which I need to do because TrainEngineNode is not provided in your question:

let coachNode = SCNNode(geometry: coachGeometry)

then there is no noticeable delay on an iPhone 7.

SceneKit and ARKit do not require you to make changes on any particular thread, so any time you have this situation you can simply offload the work onto a background queue, or preferably a serial queue that you manage. There are some caveats around doing work at an appropriate time, such as adding your objects to the scene after the ARSession is fully running. For some excellent ideas for patterns you might follow for creating an ARKit application, I recommend this sample provided by Apple.

A simplified example follows:

class SimpleARViewController: UIViewController {

    @IBOutlet weak var sceneView: ARSCNView!
    weak var activityIndicator: UIActivityIndicatorView?

    var coachPositions = [1, 2, 3, 4, 5]

    let updateQueue = DispatchQueue(label: "com.example.apple-samplecode.arkitexample.serialSceneKitQueue")

    override func viewDidLoad() {
        super.viewDidLoad()

        sceneView.alpha = 0
        view.backgroundColor = .black
        sceneView.isPlaying = false
        sceneView.session.delegate = self

        let activityIndicator = UIActivityIndicatorView(activityIndicatorStyle: .whiteLarge)
        activityIndicator.startAnimating()
        activityIndicator.translatesAutoresizingMaskIntoConstraints = false

        view.addSubview(activityIndicator)
        NSLayoutConstraint.activate([view.centerXAnchor.constraint(equalTo: activityIndicator.centerXAnchor, constant: 0),
                                     view.centerYAnchor.constraint(equalTo: activityIndicator.centerYAnchor, constant: 0)])
        self.activityIndicator = activityIndicator

        sceneView.autoenablesDefaultLighting = true
    }

    private func loadScene() {

        SCNTransaction.begin()
        SCNTransaction.disableActions = true

        for (index, _) in self.coachPositions.enumerated() {
            let coachGeometry = SCNBox(width: 0.1, height: 0.1, length: 0.1, chamferRadius: 0.005)

            // Simulates loading time of `TrainEngineNode(position:geometry:)`
            usleep(500000)

            let coachNode = SCNNode(geometry: coachGeometry)
            coachNode.worldPosition = SCNVector3Make(0, Float(index) * 0.1, -0.5)

            self.sceneView.scene.rootNode.addChildNode(coachNode)
        }

        SCNTransaction.commit()
        self.isLoading = false
    }

    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)

        let configuration = ARWorldTrackingConfiguration()
        sceneView.session.run(configuration)
    }

    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)

        sceneView.session.pause()
    }

    var isLoading = true
    var hasLoaded = false
}

extension SimpleARViewController: ARSessionDelegate {

    func session(_ session: ARSession, didUpdate frame: ARFrame) {

        // Waiting until after the session starts prevents objects from jumping around
        if hasLoaded == false {
            hasLoaded = true

            updateQueue.async { [weak self] in
                self?.loadScene()
            }
        } else if isLoading == false {
            guard let activityIndicator = self.activityIndicator else { return }

            DispatchQueue.main.async {
                UIView.animate(withDuration: 0.35, animations: { [weak self] in
                    self?.sceneView.alpha = 1
                    activityIndicator.alpha = 0
                }, completion: { _ in
                    activityIndicator.removeFromSuperview()
                })
            }
        }
    }
}

This code results in the following interaction:

As you can see in the gif, there is no delay in view controller presentation because all of the loading "work" is now done on our private serial queue. Even this contrived example can be further improved by decoupling the creation of the TrainEngineNode's from the time which they are added to the scene. For the sake of brevity, I kept the logic as similar to what you already have while presenting a relatively robust initialization. For a more robust/abstracted implementation of 3D object loading, I recommend looking at VirtualObjectLoader and how it is used in the aforementioned sample project.


问:
leastsq() got multiple values for argument 'x0' error in the scipy.optimize.curve_fit
I am trying to input some starting guessing estimates in
the scipy.optimize.curve_fit function.
According to this link
and
 another link

I should defind them in the x0, however I tried in different ways and I get the following error. (Note: without the x0 argument, it works fine)

TypeError: leastsq() got multiple values for argument 'x0'.

I provide below a reproducible example:

```<code>import numpy as np
import pandas as pd
from sklearn.datasets import load_iris
import scipy.optimize
iris = load_iris()
data1 = pd.DataFrame(data= np.c_[ iris['target'], iris['data']],  columns=  ['target'] + iris['feature_names'] )

def formula_nls(data, pot, sp):
    return pot * np.tanh(data1.iloc[:,2] * sp / 2)

scipy.optimize.curve_fit(f = formula_nls, xdata= data1.iloc[:,1:],
                                                ydata= data1.iloc[:,0], method = 'lm',
                                             sigma = 1/data1.iloc[:,1], absolute_sigma=False,
                                                x0  = np.ndarray([ 1, 2]))
</code>```

Maybe it is something simple that I am missing.
Thanks

答:
Why use argumentx0 when docs of curve_fit say:

p0 : None, scalar, or N-length sequence, optional

Initial guess for the parameters. If None, then the initial values will all be 1 (if the number of parameters for the function can be determined using introspection, otherwise a ValueError is raised).

This differs from the API in minimize and least_squares, e.g. for the latter:

x0 : array_like with shape (n,) or float

Initial guess on independent variables. If float, it will be treated as a 1-d array with one element.

And yes, internally in curve_fit, your given p0 becomes the x0 in least_squares:

```<code>res = leastsq(func, p0, Dfun=jac, full_output=1, **kwargs)
</code>```

As x0 is not an argument for curve_fit i expect it to be treated as argument used for:

kwargs

Keyword arguments passed to leastsq for method='lm' or least_squares otherwise.

which means it will be passed to leastsq as x0, together with the x0 coming from the call from curve_fit!

Something like this:

```<code>def fun(x0, **kwargs):
    return 1

print(fun(1))
# 1
print(fun(1, x0=3))
# TypeError: fun() got multiple values for argument 'x0'
</code>```

Body:
I am trying to input some starting guessing estimates in
the scipy.optimize.curve_fit function.
According to this link
and
 another link

I should defind them in the x0, however I tried in different ways and I get the following error. (Note: without the x0 argument, it works fine)

TypeError: leastsq() got multiple values for argument 'x0'.

I provide below a reproducible example:

import numpy as np
import pandas as pd
from sklearn.datasets import load_iris
import scipy.optimize
iris = load_iris()
data1 = pd.DataFrame(data= np.c_[ iris['target'], iris['data']],  columns=  ['target'] + iris['feature_names'] )

def formula_nls(data, pot, sp):
    return pot * np.tanh(data1.iloc[:,2] * sp / 2)

scipy.optimize.curve_fit(f = formula_nls, xdata= data1.iloc[:,1:],
                                                ydata= data1.iloc[:,0], method = 'lm',
                                             sigma = 1/data1.iloc[:,1], absolute_sigma=False,
                                                x0  = np.ndarray([ 1, 2]))

Maybe it is something simple that I am missing.
Thanks

Body:
Why use argumentx0 when docs of curve_fit say:

p0 : None, scalar, or N-length sequence, optional

Initial guess for the parameters. If None, then the initial values will all be 1 (if the number of parameters for the function can be determined using introspection, otherwise a ValueError is raised).

This differs from the API in minimize and least_squares, e.g. for the latter:

x0 : array_like with shape (n,) or float

Initial guess on independent variables. If float, it will be treated as a 1-d array with one element.

And yes, internally in curve_fit, your given p0 becomes the x0 in least_squares:

res = leastsq(func, p0, Dfun=jac, full_output=1, **kwargs)

As x0 is not an argument for curve_fit i expect it to be treated as argument used for:

kwargs

Keyword arguments passed to leastsq for method='lm' or least_squares otherwise.

which means it will be passed to leastsq as x0, together with the x0 coming from the call from curve_fit!

Something like this:

def fun(x0, **kwargs):
    return 1

print(fun(1))
# 1
print(fun(1, x0=3))
# TypeError: fun() got multiple values for argument 'x0'


问:
Is there a reducing function in Clojure that performs the equivalent of `first`?
I'm often writing code of the form

```<code>(->> init
     (map ...)
     (filter ...)
     (first))
</code>```

When converting this into code that uses transducers I'll end up with something like

```<code>(transduce (comp (map ...) (filter ...)) (completing #(reduced %2)) nil init)
</code>```

Writing (completing #(reduced %2)) instead of first doesn't sit well with me at all. It needlessly obscures a very straightforward task. Is there a more idiomatic way of performing this task?

答:
I'd personally use your approach with a custom reducing function but here are some alternatives:

```<code>(let [[x] (into [] (comp (map inc) (filter even?) (take 1)) [0 1])]
    x)
</code>```

Using destructing :/

Or:

```<code>(first (eduction (map inc) (filter even?) [0 1])
</code>```

Here you save on calling comp which is done for you. Though it's not super lazy. It'll realize up to 32 elements so it's potentially wasteful.
Fixed with a (take 1):

```<code>(first (eduction (map inc) (filter even?) (take 1) [0 1]))
</code>```

Overall a bit shorter and not too unclear compared to:

```<code>(transduce (comp (map inc) (filter even?) (take 1)) (completing #(reduced %2)) nil [0 1])
</code>```

If you need this a bunch, then I'd probably NOT create a custom reducer function but instead a function similar to transduce that takes xform, coll as the argument and returns the first value. It's clearer what it does and you can give it a nice docstring. If you want to save on calling comp you can also make it similar to eduction:

```<code>(defn single-xf
  "Returns the first item of transducing the xforms over collection"
  {:arglists '([xform* coll])}
  [& xforms]
  (transduce (apply comp (butlast xforms)) (completing #(reduced %2)) nil (last xforms)))
</code>```

Example:

```<code>(single-xf (map inc) (filter even?) [0 1])
</code>```

Body:
I'm often writing code of the form

(->> init
     (map ...)
     (filter ...)
     (first))

When converting this into code that uses transducers I'll end up with something like

(transduce (comp (map ...) (filter ...)) (completing #(reduced %2)) nil init)

Writing (completing #(reduced %2)) instead of first doesn't sit well with me at all. It needlessly obscures a very straightforward task. Is there a more idiomatic way of performing this task?

Body:
I'd personally use your approach with a custom reducing function but here are some alternatives:

(let [[x] (into [] (comp (map inc) (filter even?) (take 1)) [0 1])]
    x)

Using destructing :/

Or:

(first (eduction (map inc) (filter even?) [0 1])

Here you save on calling comp which is done for you. Though it's not super lazy. It'll realize up to 32 elements so it's potentially wasteful.
Fixed with a (take 1):

(first (eduction (map inc) (filter even?) (take 1) [0 1]))

Overall a bit shorter and not too unclear compared to:

(transduce (comp (map inc) (filter even?) (take 1)) (completing #(reduced %2)) nil [0 1])

If you need this a bunch, then I'd probably NOT create a custom reducer function but instead a function similar to transduce that takes xform, coll as the argument and returns the first value. It's clearer what it does and you can give it a nice docstring. If you want to save on calling comp you can also make it similar to eduction:

(defn single-xf
  "Returns the first item of transducing the xforms over collection"
  {:arglists '([xform* coll])}
  [& xforms]
  (transduce (apply comp (butlast xforms)) (completing #(reduced %2)) nil (last xforms)))

Example:

(single-xf (map inc) (filter even?) [0 1])


问:
Mongodb get count of arrayitems over all collection items
I have a mongodb-collection like this:

```<code>{
    _id: 123,
    name: 'some name',
    category: 17,
    sizes: ['XS', 'S', 'XL']
},
{
    _id: 124,
    name: 'another name',
    category: 17,
    sizes: ['S', 'L', '2XL']
}
</code>```

I need two different approaches. First one: How many items per size are available in a specific category?

```<code>{
    17: {
        XS: 0,
        S:  19,
        M:  100
    },
    39: {
        XS: 5,
        ...
    }
}
</code>```

A solution, which just shows if an item in the size is available would also be possible:

```<code>{
    17: {
        XS: false,
        S:  true,
        M:  true,
        ...
    },
    39: {
        XS: true,
        ...
    }
}
</code>```

Second problem: I need the same, but after performing a full-text-search on a name.

I've tried to aggregate over the fields, but I'm a bit lost on how to perform that on the array.

Any help appreciated.

Update:

With help from this answer, I'm one step closer:

```<code>db.so.aggregate(
    [
        // First, filter by name or something else
        // this could also include the category
        {
            $match: {
                'name': {
                    $regex: /other.*/i
                }
            }
        },

        // explode the sizes-array into single documents
        { '$unwind': '$sizes' },

        // group and count
        { '$group': {
            '_id': '$sizes',
            'count': { '$sum': 1 }
        }}
    ]
)
</code>```

Still missing: do this by category

答:
Here are some example data that I inserted:

```<code>/* 1 */
{
    "_id" : 123,
    "name" : "some name",
    "category" : 17,
    "sizes" : [
        "XS",
        "S",
        "XL"
    ]
}

/* 2 */
{
    "_id" : 124,
    "name" : "another name",
    "category" : 17,
    "sizes" : [
        "S",
        "L",
        "2XL"
    ]
}

/* 3 */
{
    "_id" : 125,
    "name" : "name",
    "category" : 35,
    "sizes" : [
        "S",
        "L",
        "2XL"
    ]
}
</code>```

Use case 1

What you seem to want in your first use case, is grouping by sizes AND category. You can actually group by multiple keys and here is an example:

```<code>db.so.aggregate([
    // add your match here...
    {
        '$unwind': '$sizes' // flatten your array
    },
    // group and count
    {
        '$group': {
            '_id': {
                sizes: '$sizes',
                category: '$category'
            }, // group by both sizes and category
            'count': {
                '$sum': 1
            },

        }
    },
    {
        '$group': {
            '_id': '$category', // group by category now
            sizeCount: { // create an array that includes the size and the count for that size
                $push: {
                    size: "$sizes",
                    count: "$count"
                }
            }

        }
    }
])
</code>```

This pipeline would create this result:

```<code>{
    "_id" : 17,
    "sizeCount" : [
        {
            "size" : "2XL",
            "count" : 1.0
        },
        {
            "size" : "XS",
            "count" : 1.0
        },
        {
            "size" : "S",
            "count" : 2.0
        },
        {
            "size" : "XL",
            "count" : 1.0
        },
        {
            "size" : "L",
            "count" : 1.0
        }
    ]
}
</code>```

would that be acceptable for you?

Use case 2

Now regarding your second use case how do you want to group sizes that don't even exist for this category?
But in general you can manipulate your result by using $cond

So in the same example if you apply this pipeline:

```<code>db.so.aggregate([
    // add your match here ...
    {
        '$unwind': '$sizes' // flatten your array
    },
    // group and count
    {
        '$group': {
            '_id': {
                sizes: '$sizes',
                category: '$category'
            }, // group by both sizes and category
            'count': {
                '$sum': 1
            },

        }
    },
    {
        '$project': {
            _id: 0,
            'count': {
                $cond: [{
                    $eq: ["$count", 1.0]
                }, "Limited", "Many"]
            },
            category: "$_id.category",
            sizes: "$_id.sizes"
        }
    },
    {
        '$group': {
            '_id': '$category',
            sizeCount: {
                $push: {
                    size: "$sizes",
                    count: "$count"
                }
            }

        }
    }
])
</code>```

It would produce the following result (one example):

```<code>{
    "_id" : 17,
    "sizeCount" : [
        {
            "size" : "2XL",
            "count" : "Limited"
        },
        {
            "size" : "XS",
            "count" : "Limited"
        },
        {
            "size" : "S",
            "count" : "Many"
        },
        {
            "size" : "XL",
            "count" : "Limited"
        },
        {
            "size" : "L",
            "count" : "Limited"
        }
    ]
}
</code>```

So basically in this line $cond: [{$eq: ["$count", 1.0]}, "Limited", "Many"]}
we say that if the count field is only 1.0, then the shirts for that size are Limited, otherwise we have Many. You can apply any comparison operator, so you can also do things like: $cond: [{$lte: ["$count", 2.0]}, "Limited", "Many"]}

Body:
I have a mongodb-collection like this:

{
    _id: 123,
    name: 'some name',
    category: 17,
    sizes: ['XS', 'S', 'XL']
},
{
    _id: 124,
    name: 'another name',
    category: 17,
    sizes: ['S', 'L', '2XL']
}

I need two different approaches. First one: How many items per size are available in a specific category?

{
    17: {
        XS: 0,
        S:  19,
        M:  100
    },
    39: {
        XS: 5,
        ...
    }
}

A solution, which just shows if an item in the size is available would also be possible:

{
    17: {
        XS: false,
        S:  true,
        M:  true,
        ...
    },
    39: {
        XS: true,
        ...
    }
}

Second problem: I need the same, but after performing a full-text-search on a name.

I've tried to aggregate over the fields, but I'm a bit lost on how to perform that on the array.

Any help appreciated.

Update:

With help from this answer, I'm one step closer:

db.so.aggregate(
    [
        // First, filter by name or something else
        // this could also include the category
        {
            $match: {
                'name': {
                    $regex: /other.*/i
                }
            }
        },

        // explode the sizes-array into single documents
        { '$unwind': '$sizes' },

        // group and count
        { '$group': {
            '_id': '$sizes',
            'count': { '$sum': 1 }
        }}
    ]
)

Still missing: do this by category

Body:
Here are some example data that I inserted:

/* 1 */
{
    "_id" : 123,
    "name" : "some name",
    "category" : 17,
    "sizes" : [
        "XS",
        "S",
        "XL"
    ]
}

/* 2 */
{
    "_id" : 124,
    "name" : "another name",
    "category" : 17,
    "sizes" : [
        "S",
        "L",
        "2XL"
    ]
}

/* 3 */
{
    "_id" : 125,
    "name" : "name",
    "category" : 35,
    "sizes" : [
        "S",
        "L",
        "2XL"
    ]
}

Use case 1

What you seem to want in your first use case, is grouping by sizes AND category. You can actually group by multiple keys and here is an example:

db.so.aggregate([
    // add your match here...
    {
        '$unwind': '$sizes' // flatten your array
    },
    // group and count
    {
        '$group': {
            '_id': {
                sizes: '$sizes',
                category: '$category'
            }, // group by both sizes and category
            'count': {
                '$sum': 1
            },

        }
    },
    {
        '$group': {
            '_id': '$category', // group by category now
            sizeCount: { // create an array that includes the size and the count for that size
                $push: {
                    size: "$sizes",
                    count: "$count"
                }
            }

        }
    }
])

This pipeline would create this result:

{
    "_id" : 17,
    "sizeCount" : [
        {
            "size" : "2XL",
            "count" : 1.0
        },
        {
            "size" : "XS",
            "count" : 1.0
        },
        {
            "size" : "S",
            "count" : 2.0
        },
        {
            "size" : "XL",
            "count" : 1.0
        },
        {
            "size" : "L",
            "count" : 1.0
        }
    ]
}

would that be acceptable for you?

Use case 2

Now regarding your second use case how do you want to group sizes that don't even exist for this category?
But in general you can manipulate your result by using $cond

So in the same example if you apply this pipeline:

db.so.aggregate([
    // add your match here ...
    {
        '$unwind': '$sizes' // flatten your array
    },
    // group and count
    {
        '$group': {
            '_id': {
                sizes: '$sizes',
                category: '$category'
            }, // group by both sizes and category
            'count': {
                '$sum': 1
            },

        }
    },
    {
        '$project': {
            _id: 0,
            'count': {
                $cond: [{
                    $eq: ["$count", 1.0]
                }, "Limited", "Many"]
            },
            category: "$_id.category",
            sizes: "$_id.sizes"
        }
    },
    {
        '$group': {
            '_id': '$category',
            sizeCount: {
                $push: {
                    size: "$sizes",
                    count: "$count"
                }
            }

        }
    }
])

It would produce the following result (one example):

{
    "_id" : 17,
    "sizeCount" : [
        {
            "size" : "2XL",
            "count" : "Limited"
        },
        {
            "size" : "XS",
            "count" : "Limited"
        },
        {
            "size" : "S",
            "count" : "Many"
        },
        {
            "size" : "XL",
            "count" : "Limited"
        },
        {
            "size" : "L",
            "count" : "Limited"
        }
    ]
}

So basically in this line $cond: [{$eq: ["$count", 1.0]}, "Limited", "Many"]}
we say that if the count field is only 1.0, then the shirts for that size are Limited, otherwise we have Many. You can apply any comparison operator, so you can also do things like: $cond: [{$lte: ["$count", 2.0]}, "Limited", "Many"]}


问:
What am I screwing up trying to download particular file types with wget?
I am attempting to regularly archive a few file types hosted on a community website where our admin has been MIA for years, in case he dies or just stops paying for the hosting.

I am able to download all of the files I need using wget -r -np -nd -e robots=off -l 0 URL but this leaves me with about 60,000 extra files to waste time both downloading and deleting.

I am really only looking for files with the extensions "tbt" and "zip". When I add in -A tbt,zip to the input, wget then only downloads a single file, "index.html.tmp". It immediately deletes this file because it doesn't match the file type specified, and then the process stops entirely, with wget announcing that it is finished. It does not attempt to download any of the other files that it grabs when the -A flag is not included.

What am I doing wrong? Why does specifying file types in the way that I did cause it to finish after only looking at one file?

答:
Possibly you're hitting the same problem I've hit when trying to do something similar. When using --accept, wget determines whether a links refers to a file or directory based on whether or not it ends with a /.

For example, say I have a directory named files, and a web page that has:

```<code><a href="files">Lots o' files!</a>
</code>```

If I were to request this with wget -r, then I wget would happily GET /files, see that it was an HTML document containing a bunch of links, and continue to download those links.

However, if I add -A zip to my command line, and run wget with --debug, I see:

```<code>appending ‘http://localhost:8080/files’ to urlpos.
[...]
Deciding whether to enqueue "http://localhost:8080/files".
http://localhost:8080/files (files) does not match acc/rej rules.
Decided NOT to load it.
</code>```

In other words, wget thinks this is a file (no trailing /) and it doesn't match our acceptance criteria, so it gets rejected.

If I modify the remote file so that it looks like...

```<code><a href="files/">Lots o' files!</a>
</code>```

...then wget will follow the link and download files as desired.

I don't think there's a great solution to this problem if you need to use wget.  As I mentioned in my comment, there are other tools available that may handle this situation more gracefully.

It's also possible you're experiencing a different issue; the output of adding --debug to your command line clarify things in that case.

Body:
Possibly you're hitting the same problem I've hit when trying to do something similar. When using --accept, wget determines whether a links refers to a file or directory based on whether or not it ends with a /.

For example, say I have a directory named files, and a web page that has:

<a href="files">Lots o' files!</a>

If I were to request this with wget -r, then I wget would happily GET /files, see that it was an HTML document containing a bunch of links, and continue to download those links.

However, if I add -A zip to my command line, and run wget with --debug, I see:

appending ‘http://localhost:8080/files’ to urlpos.
[...]
Deciding whether to enqueue "http://localhost:8080/files".
http://localhost:8080/files (files) does not match acc/rej rules.
Decided NOT to load it.

In other words, wget thinks this is a file (no trailing /) and it doesn't match our acceptance criteria, so it gets rejected.

If I modify the remote file so that it looks like...

<a href="files/">Lots o' files!</a>

...then wget will follow the link and download files as desired.

I don't think there's a great solution to this problem if you need to use wget.  As I mentioned in my comment, there are other tools available that may handle this situation more gracefully.

It's also possible you're experiencing a different issue; the output of adding --debug to your command line clarify things in that case.


问:
iOS 11 UIRefreshControl with NavigationBar LargeTitle and SearchController disappearing
I have a navigationBar with largeTitle and searchcontroller and my tableView has a refreshcontrol.

When I pull to refresh the activityIndicator of refreshcontrol disappear but de refresh process continues, even when the process finish and I call .endRefreshing() of UIRefreshControll the navigationBar doesn't back to the normal size.

Someone with the same problem?

答:
Try

self.extendedLayoutIncludesOpaqueBars = YES;

If you have opaque navigation bars that is. It fixed the issue for me.


问:
PHP preg_replace shortening a string
So I've got this php code:

```<code>$text = preg_replace("/(\s)http:\/\/([\S]+?)(\s)/i" ,
"$1[url=\"http://$2\"]http://$2[/url]$3" , " $text ");
</code>```

I guess it's replacing http://xyz.xyz.xyz kind of strings into [url=http://xyz.xyz.xyz]http://xyz.xyz.xyz[/url] inside of a given text (in my case it's a postparser for my forum) right?

now what I'm trying to do is, to limit the stringlength of the http://xyz.xyz.xyz-string that comes inside the [url=http://xyz.xyz.xyz] http://xyz.xyz.xyz <-- this string [/url]
because sometimes users post very long links and those are messing up my forum design and look very ugly anyway.

is there a way I could realize that in php, while keeping the 1. http link like it is so it still links correct?

big thanks in advance! :)

Title: PHP preg_replace shortening a string

Body:
So I've got this php code:

$text = preg_replace("/(\s)http:\/\/([\S]+?)(\s)/i" ,
"$1[url=\"http://$2\"]http://$2[/url]$3" , " $text ");

I guess it's replacing http://xyz.xyz.xyz kind of strings into [url=http://xyz.xyz.xyz]http://xyz.xyz.xyz[/url] inside of a given text (in my case it's a postparser for my forum) right?

now what I'm trying to do is, to limit the stringlength of the http://xyz.xyz.xyz-string that comes inside the [url=http://xyz.xyz.xyz] http://xyz.xyz.xyz <-- this string [/url]
because sometimes users post very long links and those are messing up my forum design and look very ugly anyway.

is there a way I could realize that in php, while keeping the 1. http link like it is so it still links correct?

big thanks in advance! :)

Body:
How about:

$text = preg_replace("/(\s)http:\/\/([\S]{,40})([\S]*?)(\s)/i",
"$1[url=\"http://$2$3\"]http://$2[/url]$4" , " $text ");

to limit it to a 40 character URL?


问:
Capybara send_keys without sending click event?
It seems that using send_keys in Capybara always first fires a click element on the given input.

Is there a way to bypass this, e.g. when I know I already have set focus to the input (and for some reason don't want a click event to be fired)?

By the way, I'm using PhantomJS.

答: Poltergeist clicks the element before sending keys to it to ensure it is the element in focus - https://github.com/teampoltergeist/poltergeist/blob/master/lib/capybara/poltergeist/client/browser.coffee#L365 . As you can see from the code the click is skipped if the element already contains a selection which is defined by https://github.com/teampoltergeist/poltergeist/blob/master/lib/capybara/poltergeist/client/browser.coffee#L365 .  So the only supported way to skip the click would be to ensure the selection is already in the element you want to send keys to.</p>


问:
Fatal Exception thrown on Scheduler.Worker thread with Retrofit 2 and Rx
This is the code I use to make Http call.
I can't reproduce the error, but Bugsnag tells me that some users are getting this error : java.lang.IllegalStateException StrictMode.java

```<code>public class ApiManager {
    public interface Callback<T> {
        void onError(Throwable e);

        void onSuccess(T result);
    }

    private ApiService _apiService;

    public ApiManager() {
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(BuildConfig.BASE_URL)
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                .addConverterFactory(GsonConverterFactory.create())
                .client(ew OkHttpClient())
                .build();
        _apiService = retrofit.create(ApiService.class);
    }

    private <T> void execute(Observable<T> observable, final Callback<T> callback) {
        observable.subscribeOn(Schedulers.computation())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<T>() {
                    @Override
                    public void onCompleted() {
                    }

                    @Override
                    public void onError(Throwable e) {
                        callback.onError(e);
                    }

                    @Override
                    public void onNext(T result) {
                        callback.onSuccess(result);
                    }
                });
    }

    public void createUser(Callback<Void> callback) {
        execute(_apiService.createUser(new User()), callback);
    }

    // Retrofit Service
    public interface ApiService {
        @POST("users")
        Observable<Void> createUser(@Body User user);
    }
}
</code>```

Here is the full trace :

```<code>java.lang.IllegalStateException: Fatal Exception thrown on Scheduler.Worker thread.
        at rx.internal.schedulers.ScheduledAction.run(ScheduledAction.java:62)
        at android.os.Handler.handleCallback(Handler.java:725)
        at android.os.Handler.dispatchMessage(Handler.java:92)
        at android.os.Looper.loop(Looper.java:153)
        at android.app.ActivityThread.main(ActivityThread.java:5340)
        at java.lang.reflect.Method.invokeNative(Method.java:-2)
        at java.lang.reflect.Method.invoke(Method.java:511)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:842)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:609)
        at dalvik.system.NativeStart.main(NativeStart.java:-2)
Caused by: rx.exceptions.UnsubscribeFailedException
        at rx.observers.SafeSubscriber.onCompleted(SafeSubscriber.java:98)
        at rx.internal.operators.OperatorObserveOn$ObserveOnSubscriber.pollQueue(OperatorObserveOn.java:195)
        at rx.internal.operators.OperatorObserveOn$ObserveOnSubscriber$2.call(OperatorObserveOn.java:162)
        at rx.internal.schedulers.ScheduledAction.run(ScheduledAction.java:55)
        at android.os.Handler.handleCallback(Handler.java:725)
        at android.os.Handler.dispatchMessage(Handler.java:92)
        at android.os.Looper.loop(Looper.java:153)
        at android.app.ActivityThread.main(ActivityThread.java:5340)
        at java.lang.reflect.Method.invokeNative(Method.java:-2)
        at java.lang.reflect.Method.invoke(Method.java:511)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:842)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:609)
        at dalvik.system.NativeStart.main(NativeStart.java:-2)
Caused by: android.os.NetworkOnMainThreadException
        at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1128)
        at org.apache.harmony.xnet.provider.jsse.OpenSSLSocketImpl.close(OpenSSLSocketImpl.java:906)
        at com.squareup.okhttp.Connection.closeIfOwnedBy(Connection.java:148)
        at com.squareup.okhttp.OkHttpClient$1.closeIfOwnedBy(OkHttpClient.java:75)
        at com.squareup.okhttp.internal.http.HttpConnection.closeIfOwnedBy(HttpConnection.java:137)
        at com.squareup.okhttp.internal.http.HttpTransport.disconnect(HttpTransport.java:135)
        at com.squareup.okhttp.internal.http.HttpEngine.disconnect(HttpEngine.java:573)
        at com.squareup.okhttp.Call.cancel(Call.java:122)
        at retrofit.OkHttpCall.cancel(OkHttpCall.java:162)
        at retrofit.RxJavaCallAdapterFactory$CallOnSubscribe$1.call(RxJavaCallAdapterFactory.java:102)
        at rx.subscriptions.BooleanSubscription.unsubscribe(BooleanSubscription.java:71)
        at rx.internal.util.SubscriptionList.unsubscribeFromAll(SubscriptionList.java:124)
        at rx.internal.util.SubscriptionList.unsubscribe(SubscriptionList.java:113)
        at rx.Subscriber.unsubscribe(Subscriber.java:98)
        at rx.internal.util.SubscriptionList.unsubscribeFromAll(SubscriptionList.java:124)
        at rx.internal.util.SubscriptionList.unsubscribe(SubscriptionList.java:113)
        at rx.Subscriber.unsubscribe(Subscriber.java:98)
        at rx.internal.util.SubscriptionList.unsubscribeFromAll(SubscriptionList.java:124)
        at rx.internal.util.SubscriptionList.unsubscribe(SubscriptionList.java:113)
        at rx.Subscriber.unsubscribe(Subscriber.java:98)
        at rx.observers.SafeSubscriber.onCompleted(SafeSubscriber.java:95)
        at rx.internal.operators.OperatorObserveOn$ObserveOnSubscriber.pollQueue(OperatorObserveOn.java:195)
        at rx.internal.operators.OperatorObserveOn$ObserveOnSubscriber$2.call(OperatorObserveOn.java:162)
        at rx.internal.schedulers.ScheduledAction.run(ScheduledAction.java:55)
        at android.os.Handler.handleCallback(Handler.java:725)
        at android.os.Handler.dispatchMessage(Handler.java:92)
        at android.os.Looper.loop(Looper.java:153)
        at android.app.ActivityThread.main(ActivityThread.java:5340)
        at java.lang.reflect.Method.invokeNative(Method.java:-2)
        at java.lang.reflect.Method.invoke(Method.java:511)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:842)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:609)
        at dalvik.system.NativeStart.main(NativeStart.java:-2)
</code>```

I also tried to subscribe on Sheduler.io() and Scheduler.newThread(), but I get the same error.

答:
My experience & suggests:

Check your onError(Throwable e) and onCompleted() method implement of Subscriber, is any possible may cause any exception. For example, NullPointerException etc.

Rxjava can not catch the exception which throw from this two method. And you will get java.lang.IllegalStateException: Fatal Exception thrown on Scheduler.Worker thread. Which you even can't locate the exception source from the stack trace.

Body:
This is the code I use to make Http call.
I can't reproduce the error, but Bugsnag tells me that some users are getting this error : java.lang.IllegalStateException StrictMode.java

public class ApiManager {
    public interface Callback<T> {
        void onError(Throwable e);

        void onSuccess(T result);
    }

    private ApiService _apiService;

    public ApiManager() {
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(BuildConfig.BASE_URL)
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                .addConverterFactory(GsonConverterFactory.create())
                .client(ew OkHttpClient())
                .build();
        _apiService = retrofit.create(ApiService.class);
    }

    private <T> void execute(Observable<T> observable, final Callback<T> callback) {
        observable.subscribeOn(Schedulers.computation())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<T>() {
                    @Override
                    public void onCompleted() {
                    }

                    @Override
                    public void onError(Throwable e) {
                        callback.onError(e);
                    }

                    @Override
                    public void onNext(T result) {
                        callback.onSuccess(result);
                    }
                });
    }

    public void createUser(Callback<Void> callback) {
        execute(_apiService.createUser(new User()), callback);
    }

    // Retrofit Service
    public interface ApiService {
        @POST("users")
        Observable<Void> createUser(@Body User user);
    }
}

Here is the full trace :

java.lang.IllegalStateException: Fatal Exception thrown on Scheduler.Worker thread.
        at rx.internal.schedulers.ScheduledAction.run(ScheduledAction.java:62)
        at android.os.Handler.handleCallback(Handler.java:725)
        at android.os.Handler.dispatchMessage(Handler.java:92)
        at android.os.Looper.loop(Looper.java:153)
        at android.app.ActivityThread.main(ActivityThread.java:5340)
        at java.lang.reflect.Method.invokeNative(Method.java:-2)
        at java.lang.reflect.Method.invoke(Method.java:511)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:842)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:609)
        at dalvik.system.NativeStart.main(NativeStart.java:-2)
Caused by: rx.exceptions.UnsubscribeFailedException
        at rx.observers.SafeSubscriber.onCompleted(SafeSubscriber.java:98)
        at rx.internal.operators.OperatorObserveOn$ObserveOnSubscriber.pollQueue(OperatorObserveOn.java:195)
        at rx.internal.operators.OperatorObserveOn$ObserveOnSubscriber$2.call(OperatorObserveOn.java:162)
        at rx.internal.schedulers.ScheduledAction.run(ScheduledAction.java:55)
        at android.os.Handler.handleCallback(Handler.java:725)
        at android.os.Handler.dispatchMessage(Handler.java:92)
        at android.os.Looper.loop(Looper.java:153)
        at android.app.ActivityThread.main(ActivityThread.java:5340)
        at java.lang.reflect.Method.invokeNative(Method.java:-2)
        at java.lang.reflect.Method.invoke(Method.java:511)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:842)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:609)
        at dalvik.system.NativeStart.main(NativeStart.java:-2)
Caused by: android.os.NetworkOnMainThreadException
        at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1128)
        at org.apache.harmony.xnet.provider.jsse.OpenSSLSocketImpl.close(OpenSSLSocketImpl.java:906)
        at com.squareup.okhttp.Connection.closeIfOwnedBy(Connection.java:148)
        at com.squareup.okhttp.OkHttpClient$1.closeIfOwnedBy(OkHttpClient.java:75)
        at com.squareup.okhttp.internal.http.HttpConnection.closeIfOwnedBy(HttpConnection.java:137)
        at com.squareup.okhttp.internal.http.HttpTransport.disconnect(HttpTransport.java:135)
        at com.squareup.okhttp.internal.http.HttpEngine.disconnect(HttpEngine.java:573)
        at com.squareup.okhttp.Call.cancel(Call.java:122)
        at retrofit.OkHttpCall.cancel(OkHttpCall.java:162)
        at retrofit.RxJavaCallAdapterFactory$CallOnSubscribe$1.call(RxJavaCallAdapterFactory.java:102)
        at rx.subscriptions.BooleanSubscription.unsubscribe(BooleanSubscription.java:71)
        at rx.internal.util.SubscriptionList.unsubscribeFromAll(SubscriptionList.java:124)
        at rx.internal.util.SubscriptionList.unsubscribe(SubscriptionList.java:113)
        at rx.Subscriber.unsubscribe(Subscriber.java:98)
        at rx.internal.util.SubscriptionList.unsubscribeFromAll(SubscriptionList.java:124)
        at rx.internal.util.SubscriptionList.unsubscribe(SubscriptionList.java:113)
        at rx.Subscriber.unsubscribe(Subscriber.java:98)
        at rx.internal.util.SubscriptionList.unsubscribeFromAll(SubscriptionList.java:124)
        at rx.internal.util.SubscriptionList.unsubscribe(SubscriptionList.java:113)
        at rx.Subscriber.unsubscribe(Subscriber.java:98)
        at rx.observers.SafeSubscriber.onCompleted(SafeSubscriber.java:95)
        at rx.internal.operators.OperatorObserveOn$ObserveOnSubscriber.pollQueue(OperatorObserveOn.java:195)
        at rx.internal.operators.OperatorObserveOn$ObserveOnSubscriber$2.call(OperatorObserveOn.java:162)
        at rx.internal.schedulers.ScheduledAction.run(ScheduledAction.java:55)
        at android.os.Handler.handleCallback(Handler.java:725)
        at android.os.Handler.dispatchMessage(Handler.java:92)
        at android.os.Looper.loop(Looper.java:153)
        at android.app.ActivityThread.main(ActivityThread.java:5340)
        at java.lang.reflect.Method.invokeNative(Method.java:-2)
        at java.lang.reflect.Method.invoke(Method.java:511)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:842)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:609)
        at dalvik.system.NativeStart.main(NativeStart.java:-2)

I also tried to subscribe on Sheduler.io() and Scheduler.newThread(), but I get the same error.


问:
Eclipse: The project was not built since its build path is incomplete. Cannot find guava Predicate
I am using new Eclipse Oxygen. My project setup includes Maven. One of the Maven dependencies is Guava:

```<code>    <dependency>
        <groupId>com.google.guava</groupId>
        <artifactId>guava</artifactId>
        <version>20.0</version>
    </dependency>
</code>```

There are 2 problems I am facing that do not allow me to build the project:

1.
The project was not built since its build path is incomplete. Cannot find the class file for com.google.common.base.Predicate. Fix the build path then try building this project

2.
The type com.google.common.base.Predicate cannot be resolved. It is indirectly referenced from required .class files [...] Java Problem

Here is what I tried to solve it:
I have made clean & build of my project; I have closed and then reopened it; I have removed it from Eclipse and then re-imported and made clean & build.
Nothing seems to help.
Anyone has any ideas? This is super annoying.

答:
The problem was not related to Eclipse, but it was a maven issue.
In order to fix it I had to clear ~/.m2/repository folder and run Maven->Update Project in Eclipse.

Body:
I am using new Eclipse Oxygen. My project setup includes Maven. One of the Maven dependencies is Guava:

    <dependency>
        <groupId>com.google.guava</groupId>
        <artifactId>guava</artifactId>
        <version>20.0</version>
    </dependency>

There are 2 problems I am facing that do not allow me to build the project:

1.
The project was not built since its build path is incomplete. Cannot find the class file for com.google.common.base.Predicate. Fix the build path then try building this project

2.
The type com.google.common.base.Predicate cannot be resolved. It is indirectly referenced from required .class files [...] Java Problem

Here is what I tried to solve it:
I have made clean & build of my project; I have closed and then reopened it; I have removed it from Eclipse and then re-imported and made clean & build.
Nothing seems to help.
Anyone has any ideas? This is super annoying.


问:
Find closest value to determined multiplicated value
I have two values. One is static and equals 24

```<code>int A = 24;
</code>```

and I have entries list :

```<code>[0, 21, 45, 76, 98]
</code>```

All of occurences comes in loop and I want to get closest value which divides on A :

```<code>0 - 24
21 - 24
45 - 48
76 - 72
98 - 96
</code>```

How to calculate this?

答:
Using java8 you can stream the array or list and map that

```<code>public static void main(String[] args) {
    int a = 24;
    List<Integer> mL = Arrays.asList(0, 21, 45, 76, 98);
    Map<Integer, Integer> m = mL.stream().collect(Collectors.toMap(Integer::intValue, x -> {
        int r = a * (int) Math.round(x / (double) a);
        return r == 0 ? a : r;
    }));
    System.out.println(m);
}
</code>```

the output will be a map where the key is the values to analyse and the values are the closest delta to it

```<code>{0=24, 98=96, 21=24, 76=72, 45=48}
</code>```

Body:
I have two values. One is static and equals 24

int A = 24;

and I have entries list :

[0, 21, 45, 76, 98]

All of occurences comes in loop and I want to get closest value which divides on A :

0 - 24
21 - 24
45 - 48
76 - 72
98 - 96

How to calculate this?

Body:
Using java8 you can stream the array or list and map that

public static void main(String[] args) {
    int a = 24;
    List<Integer> mL = Arrays.asList(0, 21, 45, 76, 98);
    Map<Integer, Integer> m = mL.stream().collect(Collectors.toMap(Integer::intValue, x -> {
        int r = a * (int) Math.round(x / (double) a);
        return r == 0 ? a : r;
    }));
    System.out.println(m);
}

the output will be a map where the key is the values to analyse and the values are the closest delta to it

{0=24, 98=96, 21=24, 76=72, 45=48}


问:
Turn a regular Windows program into a Windows Service
NetoSoft has a simple tool to create a Windows Service from a regular application. It does work, but obviously is unmaintained now. The tool allows you to register and unregister a service and to start and stop it.

Is there a more up-to-date tool that does this?

答:
Would running it as a user defined service work?

For NT systems you can create a user defined service: http://support.microsoft.com/kb/137890

I suspect there is a slightly different method for Vista/7/2008.


问:
How to execute multiple if statements optimally in swift ios
I have defined a function which executes multiple if-statements. although it executes only if-statements but not executing else statements in a flow in which it is defined. What I have to do to execute else statements just after the respective call of related if statements.</p>

```<code>  func levelTwo() {

    if firstText.text == "A"
    {
        hintLabel.text = "\(self.hintsTwo[1])"
        self.firstValid.image = #imageLiteral(resourceName: "check")
    }
    else {
        self.firstValid.image = #imageLiteral(resourceName: "markQ")
    }

    if SecFirstText.text == "A" && secSecText.text == "C"
    {
        hintLabel.text = "\(self.hintsTwo[2])"
        self.secondValid.image = #imageLiteral(resourceName: "check")
    }
    else {
        self.secondValid.image = #imageLiteral(resourceName: "markQ")
    }

    if thiFirstText.text == "C" && thiSecText.text == "A" && thiThirdText.text == "T"
    {
        hintLabel.text = "\(self.hintsTwo[3])"
        self.thirdValid.image = #imageLiteral(resourceName: "check")
    }
    else {
        self.thirdValid.image = #imageLiteral(resourceName: "markQ")
    }

}
</code>```

答:
You may also use this construction (simplified, but the core idea is visible):</p>

```<code>class MyClass {
    var firstText = "One"
    var secondText = "Two"
    var thirdText = "Three"
    var firstImage: UIImage?
    var secondImage: UIImage?
    var thirdImage: UIImage?
}

let instance = MyClass()

let keyPaths = [\MyClass.firstText:\MyClass.firstImage,
                \MyClass.secondText:\MyClass.secondImage,
                \MyClass.thirdText:\MyClass.thirdImage]

for (text, image) in keyPaths {
    if instance[keyPath: text] == "Two" {
        instance[keyPath: image] = UIImage()
    }
}
</code>```

Body:
I have defined a function which executes multiple if-statements. although it executes only if-statements but not executing else statements in a flow in which it is defined. What I have to do to execute else statements just after the respective call of related if statements.

  func levelTwo() {

    if firstText.text == "A"
    {
        hintLabel.text = "\(self.hintsTwo[1])"
        self.firstValid.image = #imageLiteral(resourceName: "check")
    }
    else {
        self.firstValid.image = #imageLiteral(resourceName: "markQ")
    }

    if SecFirstText.text == "A" && secSecText.text == "C"
    {
        hintLabel.text = "\(self.hintsTwo[2])"
        self.secondValid.image = #imageLiteral(resourceName: "check")
    }
    else {
        self.secondValid.image = #imageLiteral(resourceName: "markQ")
    }

    if thiFirstText.text == "C" && thiSecText.text == "A" && thiThirdText.text == "T"
    {
        hintLabel.text = "\(self.hintsTwo[3])"
        self.thirdValid.image = #imageLiteral(resourceName: "check")
    }
    else {
        self.thirdValid.image = #imageLiteral(resourceName: "markQ")
    }

}

Body:
You may also use this construction (simplified, but the core idea is visible):

class MyClass {
    var firstText = "One"
    var secondText = "Two"
    var thirdText = "Three"
    var firstImage: UIImage?
    var secondImage: UIImage?
    var thirdImage: UIImage?
}

let instance = MyClass()

let keyPaths = [\MyClass.firstText:\MyClass.firstImage,
                \MyClass.secondText:\MyClass.secondImage,
                \MyClass.thirdText:\MyClass.thirdImage]

for (text, image) in keyPaths {
    if instance[keyPath: text] == "Two" {
        instance[keyPath: image] = UIImage()
    }
}