问:
Android Wifi-direct groups and services
I have two Android devices I would like to connect to each other via wifi-direct.

One of them is display only (device A) and therefore has no input devices like touchscreens or mouse. The other would be a mobile phone (device B). Therefore I would like device A to be the device to initiate the connection to device B, so that the pop-up accept dialog would be displayed on device B.
I've done some research and testing on wifi-direct groups, and have managed to connect the two devices together. Unfortunately, as device A is display only, I would like to give device A some level of smarts so that it only connects to wifi-direct groups that are running a compatible app. I'm trying to do this via wifi-direct local services.

The plan is for device B to broadcast a service, and device A to listen to that service. Once device A finds the service, it will connect to device B. Then, device A would advertise its own service, so that device B, the mobile phone, will know that it can proceed with the application communication.

So far, I've noticed that you're able to see a service before the wifi-direct group is created. I would like to ask some questions about how the wifi-direct should work:

If one device sees a service, but not connected to a group that contains the device that's broadcasting the service, then I assume you cannot connect to the service/device directly? It's always i) connect to group, then ii) connect to the device.

If so, since I can see a service without being in the same group as the service broadcaster, then how would I know that the device broadcasting the service is in my device's current wifi-direct group, and that I'm connecting to the same device?
I know that you can get a "peers list" of currently connected peers in a group, but is there a good way to make the association that "service broadcaster" == "this specific peer?"

Thank you.

答:
I believe you are on the right track.

Regarding the first question: A device can connect to any peer thats advertising a local service. Even if they are not in the same group, when a device connects to another one, they form another / new group automatically, see the next question answer explaining how to get the service peer.

For the second question: it's possible to associate discovered services with specific peers, without even calling get peers list. You can follow this way:

Implement the local service listeners before initiating service discovery:

```<code>WifiP2pManager.DnsSdServiceResponseListener dnsListener = new WifiP2pManager.DnsSdServiceResponseListener() {
            @Override
            public void onDnsSdServiceAvailable(String instanceName, String registrationType, WifiP2pDevice device) {
           // instanceName is service name and device is the print information
}};

WifiP2pManager.DnsSdTxtRecordListener txtListener = new WifiP2pManager.DnsSdTxtRecordListener() {
            @Override
            public void onDnsSdTxtRecordAvailable(String fullDomain, Map record, WifiP2pDevice device) {
            // here we get the service published information in the record map object
}};
</code>```

Notice that each of them returns a WifiP2pDevice device object, you can use this object to connect to the device using the manager connect method and cache the list of services mapping them to their devices.

Hope this helps, goodluck.

Title: Android Wifi-direct groups and services

Body:
I believe you are on the right track.

Regarding the first question: A device can connect to any peer thats advertising a local service. Even if they are not in the same group, when a device connects to another one, they form another / new group automatically, see the next question answer explaining how to get the service peer.

For the second question: it's possible to associate discovered services with specific peers, without even calling get peers list. You can follow this way:

Implement the local service listeners before initiating service discovery:

WifiP2pManager.DnsSdServiceResponseListener dnsListener = new WifiP2pManager.DnsSdServiceResponseListener() {
            @Override
            public void onDnsSdServiceAvailable(String instanceName, String registrationType, WifiP2pDevice device) {
           // instanceName is service name and device is the print information
}};

WifiP2pManager.DnsSdTxtRecordListener txtListener = new WifiP2pManager.DnsSdTxtRecordListener() {
            @Override
            public void onDnsSdTxtRecordAvailable(String fullDomain, Map record, WifiP2pDevice device) {
            // here we get the service published information in the record map object
}};

Notice that each of them returns a WifiP2pDevice device object, you can use this object to connect to the device using the manager connect method and cache the list of services mapping them to their devices.

Hope this helps, goodluck.


来源: stackexchange

问:
JGit checkout previous commit
How to tell JGit to checkout its parent? For example, if I have a situation like the one below on the master branch:

```<code>c815b27 newestCommit (HEAD -> master, origin/master, master)
e46dcaf previousCommit
b2d6867 previousPreviousCommit
</code>```

I would like to call a command from JGit that would look something like:

git.checkout().setName("c815b27~").call();
```

<p>and would result in the state where HEAD would be moved to commit <code>e46dcaf</code>:</p>

```c815b27 newestCommit (origin/master, master)
e46dcaf previousCommit (HEAD)
b2d6867 previousPreviousCommit
```

<p>However, when I call the above checkout statement nothing happens. I have also come across the following statement, which also does not move HEAD:</p>

<pre class="lang-java prettyprint-override"><code>git.checkout().setStartPoint("c815b27~").call();
</code>```

Any ideas how to achieve moving to the previous commit based on tilde (~) or caret (^) symbols, and whether is even possible with the JGit API?

答:
First, you need to resolve the expression that points to the previous commit. Then you can checkout the resulting commit id.

For example:

ObjectId previousCommitId = git.getRepository().resolve( "HEAD^" );
git.checkout().setName( previousCommitId ).call();
```

Note that checking out a commit detaches HEAD.

ContentLicense: CC BY-SA 3.0

Title: JGit checkout previous commit

Body:
How to tell JGit to checkout its parent? For example, if I have a situation like the one below on the master branch:

c815b27 newestCommit (HEAD -> master, origin/master, master)
e46dcaf previousCommit
b2d6867 previousPreviousCommit

I would like to call a command from JGit that would look something like:

git.checkout().setName("c815b27~").call();

and would result in the state where HEAD would be moved to commit e46dcaf:

c815b27 newestCommit (origin/master, master)
e46dcaf previousCommit (HEAD)
b2d6867 previousPreviousCommit

However, when I call the above checkout statement nothing happens. I have also come across the following statement, which also does not move HEAD:

git.checkout().setStartPoint("c815b27~").call();

Any ideas how to achieve moving to the previous commit based on tilde (~) or caret (^) symbols, and whether is even possible with the JGit API?

Body:
First, you need to resolve the expression that points to the previous commit. Then you can checkout the resulting commit id.

For example:

ObjectId previousCommitId = git.getRepository().resolve( "HEAD^" );
git.checkout().setName( previousCommitId ).call();

Note that checking out a commit detaches HEAD.


问:
How to return first element of a group excluding NA's when non-NA values exist
I have a data frame named df which looks like.

```<code>x   y
A   NA
B   d1
L   d2
F   c1
L   s2
A   c4
B   NA
B   NA
A   c1
F   a5
G   NA
H   NA
</code>```

I want to group by x and fill in NA values with the first non-NA element in that group if possible. Note that some groups will not have a non-NA element so returning NA is fine for that case.

```<code>df %>% group_by(x) %>% mutate(new_y = first(y))
</code>```

returns the first value including NA's even when non-NA values exist for that group.

答:
We can use replace

```<code>df %>%
   group_by(x) %>%
   mutate(y = replace(y, is.na(y), y[!is.na(y)][1]))
#      x     y
#   <chr> <chr>
#1      A    c4
#2      B    d1
#3      L    d2
#4      F    c1
#5      L    s2
#6      A    c4
#7      B    d1
#8      B    d1
#9      A    c1
#10     F    a5
#11     G  <NA>
#12     H  <NA>
</code>```

Or we can do a join in data.table

```<code>library(data.table)
library(tidyr)
setDT(df)[df[order(x, is.na(y)), .SD[1L], x], y := coalesce(y, i.y),on = .(x)]
df
#    x  y
# 1: A c4
# 2: B d1
# 3: L d2
# 4: F c1
# 5: L s2
# 6: A c4
# 7: B d1
# 8: B d1
# 9: A c1
#10: F a5
#11: G NA
#12: H NA
</code>```

Or using base R

```<code>df$y <- with(df, ave(y, x, FUN = function(x) replace(x, is.na(x), x[!is.na(x)][1])))
</code>```

data

```<code>df <- structure(list(x = c("A", "B", "L", "F", "L", "A", "B", "B",
 "A", "F", "G", "H"), y = c(NA, "d1", "d2", "c1", "s2", "c4",
NA, NA, "c1", "a5", NA, NA)), .Names = c("x", "y"), class = "data.frame",
row.names = c(NA, -12L))
</code>```

Body:
I have a data frame named df which looks like.

x   y
A   NA
B   d1
L   d2
F   c1
L   s2
A   c4
B   NA
B   NA
A   c1
F   a5
G   NA
H   NA

I want to group by x and fill in NA values with the first non-NA element in that group if possible. Note that some groups will not have a non-NA element so returning NA is fine for that case.

df %>% group_by(x) %>% mutate(new_y = first(y))

returns the first value including NA's even when non-NA values exist for that group.

Body:
We can use replace

df %>%
   group_by(x) %>%
   mutate(y = replace(y, is.na(y), y[!is.na(y)][1]))
#      x     y
#   <chr> <chr>
#1      A    c4
#2      B    d1
#3      L    d2
#4      F    c1
#5      L    s2
#6      A    c4
#7      B    d1
#8      B    d1
#9      A    c1
#10     F    a5
#11     G  <NA>
#12     H  <NA>

Or we can do a join in data.table

library(data.table)
library(tidyr)
setDT(df)[df[order(x, is.na(y)), .SD[1L], x], y := coalesce(y, i.y),on = .(x)]
df
#    x  y
# 1: A c4
# 2: B d1
# 3: L d2
# 4: F c1
# 5: L s2
# 6: A c4
# 7: B d1
# 8: B d1
# 9: A c1
#10: F a5
#11: G NA
#12: H NA

Or using base R

df$y <- with(df, ave(y, x, FUN = function(x) replace(x, is.na(x), x[!is.na(x)][1])))

data

df <- structure(list(x = c("A", "B", "L", "F", "L", "A", "B", "B",
 "A", "F", "G", "H"), y = c(NA, "d1", "d2", "c1", "s2", "c4",
NA, NA, "c1", "a5", NA, NA)), .Names = c("x", "y"), class = "data.frame",
row.names = c(NA, -12L))


问:
VBA copy data from one workbook sheet to another workbook sheet

The data above is given to my company every month.

the data here is just me copy and pasting each and every data to this workbook every month manually.

Notice that they do tally. For example, Available for sales security tallies with each other in terms of value. My question is how do I write a macro to solve this in a automated manner? Can someone point me in a direction to get started. My manager just asked me to try to automate this process to save time. Im thinking of storing the values in variables for the first image and inserting the value in certain cells if the variable names are the same for the next workbook. is that possible? Please help thank you

答:
This can be done by VBA however I think it would be using sledgehammer to crack a walnut.

Instead you can use vlookup or Index(Match()) combo which is comparative easier to use.

you are looking at creating a "master" file one sheet your version and second sheet you can copy data when you receive it.

In you sheet you will need to apply one of the above mention formula linking to second worksheet.

By the way this what I think is best approach. if you still want to use VBA please post you code or research so far to get more specific help.


问:
Angular 2 Reactive Forms trigger validation on submit
is there a way that all validators of a reactive forms can be triggered upon submit and not only by the "dirty" and "touch" events?

The reason for this is we have a very large forms which doesn't indicate if a field is required or not, and user might miss some of the required control, so upon submit, it is expected that all of the invalid fields which are missed by the end user will be shown.

I have tried marking the form as "touched" by using the

```<code>FormGroup.markAsTouched(true);
</code>```

it worked, and so I also tried marking it as "dirty"

```<code>FormGroup.markAsDirty(true);
</code>```

but the css of the class is still "ng-pristine",

Is there a way to trigger it manually from the component, I tried googling it to no avail, thanks you in advance!

UPDATE

I already got it working by iterating the FormGroup.controls and marking it as "dirty", but is there a "standard" way to do this.

答:
Coming back after some months, I share here the improved version based on all the comments, just for the record:

```<code>markAsTouched(group: FormGroup | FormArray) {
  group.markAsTouched({ onlySelf: true });

  Object.keys(group.controls).map((field) => {
    const control = group.get(field);
    if (control instanceof FormControl) {
      control.markAsTouched({ onlySelf: true });
    } else if (control instanceof FormGroup) {
      this.markAsTouched(control);
    }
  });
}
</code>```

Hope it will be useful!

UPDATE: Angular 8 introduced FormGroup.markAllAsTouched() and it does this! :D

Body:
is there a way that all validators of a reactive forms can be triggered upon submit and not only by the "dirty" and "touch" events?

The reason for this is we have a very large forms which doesn't indicate if a field is required or not, and user might miss some of the required control, so upon submit, it is expected that all of the invalid fields which are missed by the end user will be shown.

I have tried marking the form as "touched" by using the

FormGroup.markAsTouched(true);

it worked, and so I also tried marking it as "dirty"

FormGroup.markAsDirty(true);

but the css of the class is still "ng-pristine",

Is there a way to trigger it manually from the component, I tried googling it to no avail, thanks you in advance!

UPDATE

I already got it working by iterating the FormGroup.controls and marking it as "dirty", but is there a "standard" way to do this.

Body:
Coming back after some months, I share here the improved version based on all the comments, just for the record:

markAsTouched(group: FormGroup | FormArray) {
  group.markAsTouched({ onlySelf: true });

  Object.keys(group.controls).map((field) => {
    const control = group.get(field);
    if (control instanceof FormControl) {
      control.markAsTouched({ onlySelf: true });
    } else if (control instanceof FormGroup) {
      this.markAsTouched(control);
    }
  });
}

Hope it will be useful!

UPDATE: Angular 8 introduced FormGroup.markAllAsTouched() and it does this! :D

ContentLicense: CC BY-SA 4.0


问:
What is the best/simplest way to read in an XML file in Java application?
Currently our Java application uses the values held within a tab delimited *.cfg file. We need to change this application so that it now uses an XML file.

What is the best/simplest library to use in order to read in values from this file?

答: JAXB is simple to use and is included in Java 6 SE. With JAXB, or other XML data binding such as Simple, you don't have to handle the XML yourself, most of the work is done by the library. The basic usage is to add annotation to your existing POJO. These annotation are then used to generate an XML Schema for you data and also when reading/writing your data from/to a file.</p>

OwnerDisplayName: ryanmcc

ContentLicense: CC BY-SA 2.5


问:
UIButton Not Working After Updated to Xcode 8.3
After I updated to Xcode 8.3 the following code is not working in Xcode Playgrounds. Before on Xcode 8.2.1, I was able to click on the button and the action would follow, but now nothing is happening when I click the button.

```<code>import UIKit
import SpriteKit
import PlaygroundSupport

let view = SKView(frame: CGRect(x: 0, y: 0, width: 550, height: 575))
let scene = SKScene(size: CGSize(width: 550, height: 575))
scene.backgroundColor = UIColor.white
scene.scaleMode = SKSceneScaleMode.aspectFit
view.presentScene(scene)

class Responder: NSObject {
    @objc func nextScene() {
        print("Next button pressed!")
    }
}
let responder = Responder()

let nextButton = UIButton(type: .system)
nextButton.frame = CGRect(x: 250, y: 557.5, width: 40, height: 15)
nextButton.setTitle("Next", for: .normal)
nextButton.titleLabel?.font = UIFont(name: "Marker Felt", size: 17)
nextButton.tintColor = .black
nextButton.addTarget(responder, action: #selector(Responder.nextScene), for: .touchUpInside)
view.addSubview(nextButton)

PlaygroundPage.current.liveView = view
</code>```

EDIT: I updated my code so that it includes PlaygroundPage.current.liveView = view and the code for setting up the view and scene.

答:
You do not set a live view for the playground in your code. Normally, a playground will execute the code and stop - it does not wait for input or events etc, unless you explicitly specify it should.

You should add the following line at the end of the playground to specify that canvas is a live view - provided it is, I can't know since you have not provided the implementation for canvas.

```<code>PlaygroundPage.current.liveView = canvas
</code>```

Body:
After I updated to Xcode 8.3 the following code is not working in Xcode Playgrounds. Before on Xcode 8.2.1, I was able to click on the button and the action would follow, but now nothing is happening when I click the button.

import UIKit
import SpriteKit
import PlaygroundSupport

let view = SKView(frame: CGRect(x: 0, y: 0, width: 550, height: 575))
let scene = SKScene(size: CGSize(width: 550, height: 575))
scene.backgroundColor = UIColor.white
scene.scaleMode = SKSceneScaleMode.aspectFit
view.presentScene(scene)

class Responder: NSObject {
    @objc func nextScene() {
        print("Next button pressed!")
    }
}
let responder = Responder()

let nextButton = UIButton(type: .system)
nextButton.frame = CGRect(x: 250, y: 557.5, width: 40, height: 15)
nextButton.setTitle("Next", for: .normal)
nextButton.titleLabel?.font = UIFont(name: "Marker Felt", size: 17)
nextButton.tintColor = .black
nextButton.addTarget(responder, action: #selector(Responder.nextScene), for: .touchUpInside)
view.addSubview(nextButton)

PlaygroundPage.current.liveView = view

EDIT: I updated my code so that it includes PlaygroundPage.current.liveView = view and the code for setting up the view and scene.

Body:
You do not set a live view for the playground in your code. Normally, a playground will execute the code and stop - it does not wait for input or events etc, unless you explicitly specify it should.

You should add the following line at the end of the playground to specify that canvas is a live view - provided it is, I can't know since you have not provided the implementation for canvas.

PlaygroundPage.current.liveView = canvas


问:
Buffer overflow works in gdb but not without it
I am on CentOS 6.4 32 bit and am trying to cause a buffer overflow in a program. Within GDB it works. Here is the output:

```<code>[root@localhost bufferoverflow]# gdb stack
GNU gdb (GDB) Red Hat Enterprise Linux (7.2-60.el6_4.1)
Copyright (C) 2010 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>
This is free software: you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.  Type "show copying"
and "show warranty" for details.
This GDB was configured as "i686-redhat-linux-gnu".
For bug reporting instructions, please see:
<http://www.gnu.org/software/gdb/bugs/>...
Reading symbols from /root/bufferoverflow/stack...done.
(gdb) r
Starting program: /root/bufferoverflow/stack
process 6003 is executing new program: /bin/bash
Missing separate debuginfos, use: debuginfo-install glibc-2.12-1.107.el6_4.2.i686
sh-4.1#
</code>```

However when I run the program stack just on its own it seg faults. Why might this be?

答:
Here is a straightforward way of running your program with identical stacks in the terminal and in gdb:

First, make sure your program is compiled without stack protection,

gcc -m32 -fno-stack-protector -z execstack -o shelltest shelltest.c -g

and and ASLR is disabled:

echo 0 > /proc/sys/kernel/randomize_va_space

NOTE: default value on my machine was 2, note yours before changing this.

Then run your program like so (terminal and gdb respectively):

```<code>env -i PWD="/root/Documents/MSec" SHELL="/bin/bash" SHLVL=0 /root/Documents/MSec/shelltest
env -i PWD="/root/Documents/MSec" SHELL="/bin/bash" SHLVL=0 gdb /root/Documents/MSec/shelltest
</code>```

Within gdb, make sure to unset LINES and COLUMNS.

Note: I got those environment variables by playing around with a test program.

Those two runs will give you identical pointers to the top of the stack, so no need for remote script shenanigans if you're trying to exploit a binary hosted remotely.

Body:
I am on CentOS 6.4 32 bit and am trying to cause a buffer overflow in a program. Within GDB it works. Here is the output:

[root@localhost bufferoverflow]# gdb stack
GNU gdb (GDB) Red Hat Enterprise Linux (7.2-60.el6_4.1)
Copyright (C) 2010 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>
This is free software: you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.  Type "show copying"
and "show warranty" for details.
This GDB was configured as "i686-redhat-linux-gnu".
For bug reporting instructions, please see:
<http://www.gnu.org/software/gdb/bugs/>...
Reading symbols from /root/bufferoverflow/stack...done.
(gdb) r
Starting program: /root/bufferoverflow/stack
process 6003 is executing new program: /bin/bash
Missing separate debuginfos, use: debuginfo-install glibc-2.12-1.107.el6_4.2.i686
sh-4.1#

However when I run the program stack just on its own it seg faults. Why might this be?

Body:
Here is a straightforward way of running your program with identical stacks in the terminal and in gdb:

First, make sure your program is compiled without stack protection,

gcc -m32 -fno-stack-protector -z execstack -o shelltest shelltest.c -g

and and ASLR is disabled:

echo 0 > /proc/sys/kernel/randomize_va_space

NOTE: default value on my machine was 2, note yours before changing this.

Then run your program like so (terminal and gdb respectively):

env -i PWD="/root/Documents/MSec" SHELL="/bin/bash" SHLVL=0 /root/Documents/MSec/shelltest
env -i PWD="/root/Documents/MSec" SHELL="/bin/bash" SHLVL=0 gdb /root/Documents/MSec/shelltest

Within gdb, make sure to unset LINES and COLUMNS.

Note: I got those environment variables by playing around with a test program.

Those two runs will give you identical pointers to the top of the stack, so no need for remote script shenanigans if you're trying to exploit a binary hosted remotely.


问:
How to use CTE recursion to get a running total of a column
I have been researching CTE recursion, but I still seem to be confused.

I have table: utb(date, b_id, v_id, b_vol)

I need to get the running total of the column: b_vol.

The catch is that I need to divide if the row_number is even, and multiply if it is odd, so essentially:

P1= b_vol1, P2 = b_vol1/b_vol2, P3= b_vol1/b_vol2*b_vol3,
  P4= b_vol1/b_vol2*b_vol3/b_vol4

So, it is basically P(n)= (P(n-1)(*OR/(b_vol(n))

I can't seem to figure out how to put that into a query.

Thanks for taking the time to read this. I hope you can help.

答:
My sample table only has 1 column B_VOL. Try this</p>

```<code>DECLARE @SampleData AS TABLE ( B_VOL int)
INSERT INTO @SampleData VALUES (50), (50), ( 50), (50) ,(155), (255)

;WITH temp AS
(
   SELECT sd.*, row_number() OVER(ORDER BY (SELECT null)) - 1 AS RowIndex FROM @SampleData sd
)
,cte AS
(
   SELECT TOP 1  t.RowIndex, CAST( t.B_VOL  AS decimal(18,7)) AS sv FROM temp t ORDER BY t.RowIndex ASC
   UNION ALL
   SELECT t.RowIndex, CAST(cte.sv * (CASE WHEN t.RowIndex % 2 = 1 THEN CAST(1 AS decimal(18,7))/t.B_VOL ELSE t.B_VOL  END) AS  decimal(18,7)) AS sv
   FROM  cte
   INNER JOIN temp t ON cte.RowIndex + 1 = t.RowIndex
)
SELECT  t.*, c.sv
FROM temp t
INNER JOIN cte c ON t.RowIndex = c.RowIndex
OPTION(MAXRECURSION 0)
</code>```

Body:
My sample table only has 1 column B_VOL. Try this

DECLARE @SampleData AS TABLE ( B_VOL int)
INSERT INTO @SampleData VALUES (50), (50), ( 50), (50) ,(155), (255)

;WITH temp AS
(
   SELECT sd.*, row_number() OVER(ORDER BY (SELECT null)) - 1 AS RowIndex FROM @SampleData sd
)
,cte AS
(
   SELECT TOP 1  t.RowIndex, CAST( t.B_VOL  AS decimal(18,7)) AS sv FROM temp t ORDER BY t.RowIndex ASC
   UNION ALL
   SELECT t.RowIndex, CAST(cte.sv * (CASE WHEN t.RowIndex % 2 = 1 THEN CAST(1 AS decimal(18,7))/t.B_VOL ELSE t.B_VOL  END) AS  decimal(18,7)) AS sv
   FROM  cte
   INNER JOIN temp t ON cte.RowIndex + 1 = t.RowIndex
)
SELECT  t.*, c.sv
FROM temp t
INNER JOIN cte c ON t.RowIndex = c.RowIndex
OPTION(MAXRECURSION 0)


问:
Automatically passing focus betwen EditText
Since my question asking about separating characters that are typed in an EditText into groups or blocks didn't receive much attention, I've come here with another question on an alternative way to accomplish what I need.

So, my idea is to have four EditText that have 4 char length. Now what I want is to change the focus as the user type, from an EdutText to another when the limit is reached.
Example: Let's say we have EditText A, B, C, D; the first to gain focus is EditText A, then when the chars length at A reach 4, the focus passes to EditText B and so on and stops At D.

I'm trying something like the code bellow, but the focus is not requested when the length reaches 4 chars.

```<code>inputFieldA.requestFocus();

    inputFieldA.addTextChangedListener(new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            if(s.toString().trim().length() == 4){
                inputFieldB.requestFocus();
            }
        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {

        }

        @Override
        public void afterTextChanged(Editable s) {

        }
    });
    inputFieldB.addTextChangedListener(new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            if(s.toString().trim().length() == 4){
                inputFieldC.requestFocus();
            }
        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {

        }

        @Override
        public void afterTextChanged(Editable s) {

        }
    });
    inputFieldC.addTextChangedListener(new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            if(s.toString().trim().length() == 4){
                inputFieldD.requestFocus();
            }
        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {

        }

        @Override
        public void afterTextChanged(Editable s) {

        }
    });
    inputFieldD.addTextChangedListener(new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            if(s.toString().trim().length() == 4){
                //send all to Main EditText (A + B + C + D)
            }
        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {

        }

        @Override
        public void afterTextChanged(Editable s) {

        }
    });
</code>```

So I'm here asking if there is a way to do that.

答:
instead of adding validation on the basis of CharSeq length add validation on the basis of edittext text like this:

replace

```<code>    if(s.toString().trim().length() == 4)
</code>```

with

```<code>    if (currEdittext.getText().toString().length() >= 4)
</code>```

Note: update your condition as well.

currEdittext will be either inputFieldA, inputFieldB, inputFieldC depending on your requirement

Body:
Since my question asking about separating characters that are typed in an EditText into groups or blocks didn't receive much attention, I've come here with another question on an alternative way to accomplish what I need.

So, my idea is to have four EditText that have 4 char length. Now what I want is to change the focus as the user type, from an EdutText to another when the limit is reached.
Example: Let's say we have EditText A, B, C, D; the first to gain focus is EditText A, then when the chars length at A reach 4, the focus passes to EditText B and so on and stops At D.

I'm trying something like the code bellow, but the focus is not requested when the length reaches 4 chars.

inputFieldA.requestFocus();

    inputFieldA.addTextChangedListener(new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            if(s.toString().trim().length() == 4){
                inputFieldB.requestFocus();
            }
        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {

        }

        @Override
        public void afterTextChanged(Editable s) {

        }
    });
    inputFieldB.addTextChangedListener(new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            if(s.toString().trim().length() == 4){
                inputFieldC.requestFocus();
            }
        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {

        }

        @Override
        public void afterTextChanged(Editable s) {

        }
    });
    inputFieldC.addTextChangedListener(new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            if(s.toString().trim().length() == 4){
                inputFieldD.requestFocus();
            }
        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {

        }

        @Override
        public void afterTextChanged(Editable s) {

        }
    });
    inputFieldD.addTextChangedListener(new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            if(s.toString().trim().length() == 4){
                //send all to Main EditText (A + B + C + D)
            }
        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {

        }

        @Override
        public void afterTextChanged(Editable s) {

        }
    });

So I'm here asking if there is a way to do that.

Body:
instead of adding validation on the basis of CharSeq length add validation on the basis of edittext text like this:

replace

    if(s.toString().trim().length() == 4)

with

    if (currEdittext.getText().toString().length() >= 4)

Note: update your condition as well.

currEdittext will be either inputFieldA, inputFieldB, inputFieldC depending on your requirement


问:
Ant's optional tasks are not available on CentOS
When I run ant on CentOS to build java project I receive an error:

```<code>Could not create task or type of type: replaceregexp
</code>```

ant -diagnostics shows that optional tasks are not available. How I can install optional tasks for ant?

Ant is installed from CentOS package.

答:
try
yum list 'ant*'
to see available ant packages.

In my case
yum install ant-antlr.x86_64 worked.

Body:
When I run ant on CentOS to build java project I receive an error:

Could not create task or type of type: replaceregexp

ant -diagnostics shows that optional tasks are not available. How I can install optional tasks for ant?

Ant is installed from CentOS package.


问:
How to make center the hint of searchView in android?
Can anyone tell how make Search View hint in centre? Thanks in advance.

答:
To center the hint on the SearchView you need to center the gravity in the EditText contained in the SearchView.

You can find that specific view by using the Layout Inspector in Android Studio (Tools->Android->Layout Inspector). When you click on the search view in your UI, you can see it has a SearchView$SearchAutoComplete. That's an inner class in the SearchView which extends AutoCompleteTextView, which extends EditText. So, that's the view you want to change. Observe in the property-value pane of the Layout Inspector that the id is id/search_src_text so you can use that to get the view and center the gravity, like this:

```<code>int id = getResources().getIdentifier("android:id/search_src_text", null, null);
EditText searchEditText = (EditText) mSearchView.findViewById(id);
if (searchEditText != null) {
    searchEditText.setGravity(Gravity.CENTER);
}
</code>```

Since the id of the EditText isn't officially documented, there's a null check in there just in case the id changes or isn't consistent everywhere.

Body:
To center the hint on the SearchView you need to center the gravity in the EditText contained in the SearchView.

You can find that specific view by using the Layout Inspector in Android Studio (Tools->Android->Layout Inspector). When you click on the search view in your UI, you can see it has a SearchView$SearchAutoComplete. That's an inner class in the SearchView which extends AutoCompleteTextView, which extends EditText. So, that's the view you want to change. Observe in the property-value pane of the Layout Inspector that the id is id/search_src_text so you can use that to get the view and center the gravity, like this:

int id = getResources().getIdentifier("android:id/search_src_text", null, null);
EditText searchEditText = (EditText) mSearchView.findViewById(id);
if (searchEditText != null) {
    searchEditText.setGravity(Gravity.CENTER);
}

Since the id of the EditText isn't officially documented, there's a null check in there just in case the id changes or isn't consistent everywhere.


问:
Converting date and time into float in python
Below is my data set

```<code>  Date         Time
  2015-05-13   23:53:00
</code>```

I want to convert date and time into floats as separate columns in a python script.

The output should be like date as 20150513 and time as 235300

Body:
Below is my data set

  Date         Time
  2015-05-13   23:53:00

I want to convert date and time into floats as separate columns in a python script.

The output should be like date as 20150513 and time as 235300

Body:
date = "2015-05-13".replace("-", "")
time = "10:58:56".replace(":", "")


问:
How to open DICOM (.dcm) images in iOS ?
Though this is a duplicate question, it would be really great if someone can help me in integrating a DICOM image viewer in my iOS application. Basically we are building a health application, where we have a requirement to showcase .DCM images. Any solutions ?

I'd tried with this and this too. But no luck :(

答:
I am currently the primary maintainer of fo-dicom, which is a C# based cross-platform DICOM toolkit, available on .NET Framework, but also on Xamarin iOS, Xamarin Android as well as other platforms.

If you are considering developing in C#, fo-dicom might be a sufficient alternative.


问:
Redirect website to WWW apache .htaccess
I want to redirect kwikku.com to www.kwikku.com

What should I add in my .htaccess?

答:
Hope this will work.</p>

```<code>RewriteEngine on
RewriteCond %{HTTP_HOST} ^somedomain\.in
RewriteRule ^(.*)$ http://www.somedomain.com/$1 [L,R=301,NE]
</code>```

Body:
Hope this will work.

RewriteEngine on
RewriteCond %{HTTP_HOST} ^somedomain\.in
RewriteRule ^(.*)$ http://www.somedomain.com/$1 [L,R=301,NE]


问:
Handle multiple request Alamofire while Search
I'm having SearchContoller and whenever user starts searching I have to display the result. But continuous API calls over here sometimes old result remains even if there is no data received from API.
How to queue them so that there won't be any misplaced data viewed.</p>

```<code>    fileprivate func getData(searchString: String){
        getFriendList = false
        guard let currentUser = AppController.shared.currentUser else { return }
//        self.friendsList.removeAll()
        APIHandler.shared.doAPIGetCallForUrl(Constants.kcFindFriends + "?UserId=" + String(currentUser.userId) + "&seachString=" + searchString + "&PageNumber=" + String(pageNumber) , callback: { [weak self](success, jsonData, error) in
            guard let weakSelf = self else { return }
            guard success == true else {
//                weakSelf.findFriendsTableView.reloadData()
                return
            }
            guard let json = jsonData else { return }
            guard let findFriendList: [FriendList] = json.value() else { return }
            weakSelf.friendsList.append(contentsOf: findFriendList)
            weakSelf.findFriendsTableView.reloadData()
        })
    }

func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
    searchString = searchText
    pageNumber = 1
    getData(searchString: searchString)
}
</code>```

答:
Define a var for request in your viewController and in its setter cancel any old request

```<code>var searchRequest: Request?{
    didSet{
        oldValue?.cancel()
    }
}
</code>```

In your function pass the request to that var, So whenever you'll make a new search it'll cancel the old one.

```<code>searchRequest = Alamofire.request("URL", method: .post, parameters: nil)
        .responseJSON(completionHandler: { (response) in
            //Handle response
})
</code>```

Body:
I'm having SearchContoller and whenever user starts searching I have to display the result. But continuous API calls over here sometimes old result remains even if there is no data received from API.
How to queue them so that there won't be any misplaced data viewed.

    fileprivate func getData(searchString: String){
        getFriendList = false
        guard let currentUser = AppController.shared.currentUser else { return }
//        self.friendsList.removeAll()
        APIHandler.shared.doAPIGetCallForUrl(Constants.kcFindFriends + "?UserId=" + String(currentUser.userId) + "&seachString=" + searchString + "&PageNumber=" + String(pageNumber) , callback: { [weak self](success, jsonData, error) in
            guard let weakSelf = self else { return }
            guard success == true else {
//                weakSelf.findFriendsTableView.reloadData()
                return
            }
            guard let json = jsonData else { return }
            guard let findFriendList: [FriendList] = json.value() else { return }
            weakSelf.friendsList.append(contentsOf: findFriendList)
            weakSelf.findFriendsTableView.reloadData()
        })
    }

func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
    searchString = searchText
    pageNumber = 1
    getData(searchString: searchString)
}

Body:
Define a var for request in your viewController and in its setter cancel any old request

var searchRequest: Request?{
    didSet{
        oldValue?.cancel()
    }
}

In your function pass the request to that var, So whenever you'll make a new search it'll cancel the old one.

searchRequest = Alamofire.request("URL", method: .post, parameters: nil)
        .responseJSON(completionHandler: { (response) in
            //Handle response
})


问:
Qt simple error when trying to delete a word in QTextEdit
I'm trying to delete a word after pressing space on a QTextEdit.

Here's my code:

window.h:

```<code>#ifndef WINDOW_H
#define WINDOW_H
#include <QApplication>
#include <QWidget>
#include <QTextEdit>
#include <iostream>
using namespace std;

class Window: public QWidget
{
    Q_OBJECT

public:
    Window();

public slots:
    void write();

private:
    QTextEdit *textEdit;
};

#endif // WINDOW_H
</code>```

window.cpp:

```<code>#include "window.h"

Window::Window()
{
    setFixedSize(500, 500);
    textEdit = new QTextEdit(this);
    textEdit->resize(500, 500);
    QObject::connect(textEdit, SIGNAL(textChanged()), this, SLOT(write()));
}

void Window::write()
{
    QString word = textEdit->toPlainText();
    if (word[word.length()-1] == ' ')
    {
        for(int i=0;i<word.length();i++)
        {
            textEdit->textCursor().deletePreviousChar();
        }
    }
}
</code>```

main.cpp

```<code>#include <QApplication>
#include <QTextEdit>
#include <iostream>
#include <QString>
#include "window.h"
using namespace std;

int main(int argc, char *argv[])
{
    QApplication app(argc, argv);
    Window window;
    window.show();

    return app.exec();
}
</code>```

So with this code, when I'm writing "abc ", it should erase all the word, but instead it return me an error:

答:
In your write(), if word.length() equals to 0, word[word.length()-1] refers to word[-1], which is invalid.

You should check if word.length() >= 1 in your if statement:

```<code>if (word.length() >= 1 && word[word.length()-1] == ' ')
</code>```

Body:
I'm trying to delete a word after pressing space on a QTextEdit.

Here's my code:

window.h:

#ifndef WINDOW_H
#define WINDOW_H
#include <QApplication>
#include <QWidget>
#include <QTextEdit>
#include <iostream>
using namespace std;

class Window: public QWidget
{
    Q_OBJECT

public:
    Window();

public slots:
    void write();

private:
    QTextEdit *textEdit;
};

#endif // WINDOW_H

window.cpp:

#include "window.h"

Window::Window()
{
    setFixedSize(500, 500);
    textEdit = new QTextEdit(this);
    textEdit->resize(500, 500);
    QObject::connect(textEdit, SIGNAL(textChanged()), this, SLOT(write()));
}

void Window::write()
{
    QString word = textEdit->toPlainText();
    if (word[word.length()-1] == ' ')
    {
        for(int i=0;i<word.length();i++)
        {
            textEdit->textCursor().deletePreviousChar();
        }
    }
}

main.cpp

#include <QApplication>
#include <QTextEdit>
#include <iostream>
#include <QString>
#include "window.h"
using namespace std;

int main(int argc, char *argv[])
{
    QApplication app(argc, argv);
    Window window;
    window.show();

    return app.exec();
}

So with this code, when I'm writing "abc ", it should erase all the word, but instead it return me an error:

Body:
In your write(), if word.length() equals to 0, word[word.length()-1] refers to word[-1], which is invalid.

You should check if word.length() >= 1 in your if statement:

if (word.length() >= 1 && word[word.length()-1] == ' ')


问:
My server and php mail() function sends email to the spam folder
is there any way i install SMTP service on my Linux server and use php to send emails through it ?

so that emails doesn't show up as spam ?

maybe through ssl ?

my mail() function is perfect , with perfect headers , but still sending to spam :(

Thanks .

答: You can recheck your headers, maybe there might a space or something in the header from address, you can also check if the ip of your server is blacklisted (http://www.anti-abuse.org/multi-rbl-check/)</p>


问:
Application going to background, data is not loaded
I created a simple json application and working fine but when the app is going to background data is not loaded,some one please suggest me with code.  </p>

```<code>    let task = URLSession.shared.dataTask(with: URL(string: "http://tour-pedia.org/api/getReviews?location=Rome&category=poi")!) { (data, response , error) in
    if error != nil {
        print(error?.localizedDescription ?? "")
    }
    if let resultArray = (try? JSONSerialization.jsonObject(with: data!, options: [])) as? [[String:Any]] {
        for jsonreviews in resultArray {
            let review = Review()
            review.rating = jsonreviews["rating"] as? Int ?? 0
            review.text = jsonreviews["text"] as! String
            review.time = jsonreviews["time"] as! String
            reviews.append(review)
        }
        DispatchQueue.main.async {
            self.tableview.reloadData()   // if you use tableview
        }
    }
}
task.resume()
</code>```

答:
The simple solution, if you only need an extra few minutes to finish the request, is to request the OS a little time to finish this. See Background Execution: Executing Finite-Length Tasks.

So, to tell the OS that you might want a little extra time to run the request if the app happens to be suspended while the task is running, you can do:

```<code>var backgroundTask = UIBackgroundTaskInvalid

backgroundTask = UIApplication.shared.beginBackgroundTask(withName: "com.domain.app.data") {
    // do whatever clean up you want before your app exits

    UIApplication.shared.endBackgroundTask(backgroundTask)
    backgroundTask = UIBackgroundTaskInvalid
}
</code>```

And, when the task is done:

```<code>if backgroundTask != UIBackgroundTaskInvalid {
    UIApplication.shared.endBackgroundTask(backgroundTask)
    backgroundTask = UIBackgroundTaskInvalid
}
</code>```

Thus:

```<code>var backgroundTask = UIBackgroundTaskInvalid

backgroundTask = UIApplication.shared.beginBackgroundTask(withName: "com.domain.app.data") {
    // do whatever clean up you want before your app exits

    UIApplication.shared.endBackgroundTask(backgroundTask)
    backgroundTask = UIBackgroundTaskInvalid
}

let task = URLSession.shared.dataTask(with: URL(string: "http://tour-pedia.org/api/getReviews?location=Rome&category=poi")!) { data, response, error in
    guard let data = data, error != nil else {
        print(error?.localizedDescription ?? "")
        return
    }

    if let resultArray = (try? JSONSerialization.jsonObject(with: data)) as? [[String: Any]] {
        for jsonreviews in resultArray {
            let review = Review()
            review.rating = jsonreviews["rating"] as? Int ?? 0
            review.text = (jsonreviews["text"] as! String)
            review.time = (jsonreviews["time"] as! String)
            reviews.append(review)
        }
        DispatchQueue.main.async {
            self.tableview.reloadData()   // if you use tableview
        }
    }

    if backgroundTask != UIBackgroundTaskInvalid {
        UIApplication.shared.endBackgroundTask(backgroundTask)
        backgroundTask = UIBackgroundTaskInvalid
    }
}
task.resume()
</code>```

If you think you'll need more than a few minutes to finish the query, you can implement background URLSession, though that might be overkill for this scenario. It requires quite a few changes including:

Use delegate-based URLSession;

Use download task rather than data task;

Make sure to implement app delegate method to respond to completion of background network request;

etc.

Body:
I created a simple json application and working fine but when the app is going to background data is not loaded,some one please suggest me with code.

    let task = URLSession.shared.dataTask(with: URL(string: "http://tour-pedia.org/api/getReviews?location=Rome&category=poi")!) { (data, response , error) in
    if error != nil {
        print(error?.localizedDescription ?? "")
    }
    if let resultArray = (try? JSONSerialization.jsonObject(with: data!, options: [])) as? [[String:Any]] {
        for jsonreviews in resultArray {
            let review = Review()
            review.rating = jsonreviews["rating"] as? Int ?? 0
            review.text = jsonreviews["text"] as! String
            review.time = jsonreviews["time"] as! String
            reviews.append(review)
        }
        DispatchQueue.main.async {
            self.tableview.reloadData()   // if you use tableview
        }
    }
}
task.resume()

Body:
The simple solution, if you only need an extra few minutes to finish the request, is to request the OS a little time to finish this. See Background Execution: Executing Finite-Length Tasks.

So, to tell the OS that you might want a little extra time to run the request if the app happens to be suspended while the task is running, you can do:

var backgroundTask = UIBackgroundTaskInvalid

backgroundTask = UIApplication.shared.beginBackgroundTask(withName: "com.domain.app.data") {
    // do whatever clean up you want before your app exits

    UIApplication.shared.endBackgroundTask(backgroundTask)
    backgroundTask = UIBackgroundTaskInvalid
}

And, when the task is done:

if backgroundTask != UIBackgroundTaskInvalid {
    UIApplication.shared.endBackgroundTask(backgroundTask)
    backgroundTask = UIBackgroundTaskInvalid
}

Thus:

var backgroundTask = UIBackgroundTaskInvalid

backgroundTask = UIApplication.shared.beginBackgroundTask(withName: "com.domain.app.data") {
    // do whatever clean up you want before your app exits

    UIApplication.shared.endBackgroundTask(backgroundTask)
    backgroundTask = UIBackgroundTaskInvalid
}

let task = URLSession.shared.dataTask(with: URL(string: "http://tour-pedia.org/api/getReviews?location=Rome&category=poi")!) { data, response, error in
    guard let data = data, error != nil else {
        print(error?.localizedDescription ?? "")
        return
    }

    if let resultArray = (try? JSONSerialization.jsonObject(with: data)) as? [[String: Any]] {
        for jsonreviews in resultArray {
            let review = Review()
            review.rating = jsonreviews["rating"] as? Int ?? 0
            review.text = (jsonreviews["text"] as! String)
            review.time = (jsonreviews["time"] as! String)
            reviews.append(review)
        }
        DispatchQueue.main.async {
            self.tableview.reloadData()   // if you use tableview
        }
    }

    if backgroundTask != UIBackgroundTaskInvalid {
        UIApplication.shared.endBackgroundTask(backgroundTask)
        backgroundTask = UIBackgroundTaskInvalid
    }
}
task.resume()

If you think you'll need more than a few minutes to finish the query, you can implement background URLSession, though that might be overkill for this scenario. It requires quite a few changes including:

Use delegate-based URLSession;

Use download task rather than data task;

Make sure to implement app delegate method to respond to completion of background network request;

etc.


问:
SQLite : insert array string into table not increased ID
try to insert string array into table but id for insert not increase and the first string has been insert. i use autoincreament for id?

Table Create

```<code>//Multi Farm Table
String CREATE_MULTI_FARM_TABLE = "CREATE TABLE " + TABLE_MULTI_FARM + "(" +
        KEY_MULTI_FARM_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
        KEY_MULTI_FARM_FARM_NAME + " TEXT" + ")";
db.execSQL(CREATE_MULTI_FARM_TABLE);
</code>```

Insert Record Function

```<code>//Add Multi Farm
public void addMultiFarm(MultiFarmModel multiFarm) {
    SQLiteDatabase db = this.getWritableDatabase();
    ContentValues values = new ContentValues();
    values.put(KEY_MULTI_FARM_ID, multiFarm.getId());
    values.put(KEY_MULTI_FARM_FARM_NAME, multiFarm.getFarmName());
    //Insert Record
    Log.e("StringInsertId", "" + db.insert(TABLE_MULTI_FARM, null, values));
    db.close();
}
</code>```

Function in Class

```<code>public MultiFarmModel(String farmName){
    this.farmName = farmName;
}
</code>```

Insert Code

```<code>String smsContent = "InsertToTable A|B|C|D|E";
DBHandler db = new DBHandler(context);
                smsContent = smsContent.substring(smsContent.indexOf(" ")+1);
                String[] string = smsContent.split("\\|");
                db.deleteAllMultiFarmRecord();
                for (String s : string) {
                    Log.e("StringToInsert", s + " ? ");
                    db.addMultiFarm(new MultiFarmModel(s));
                }
            }
</code>```

Log Console

```<code>E/String Number: A|B|C|D|E
E/StringToInsert: A ?
E/StringInsertId: 0
E/StringToInsert: B ?
E/StringInsertId: -1
E/StringToInsert: C ?
E/StringInsertId: -1
E/StringToInsert: D ?
E/StringInsertId: -1
E/StringToInsert: E ?
E/StringInsertId: -1
</code>```

答:
Remove this KEY_MULTI_FARM_ID line because it's auto increment column... you are passing same value that's why its throwing error

```<code>public void addMultiFarm(MultiFarmModel multiFarm) {
    SQLiteDatabase db = this.getWritableDatabase();
    ContentValues values = new ContentValues();
   // values.put(KEY_MULTI_FARM_ID, multiFarm.getId());
    values.put(KEY_MULTI_FARM_FARM_NAME, multiFarm.getFarmName());
    //Insert Record
    Log.e("StringInsertId", "" + db.insert(TABLE_MULTI_FARM, null, values));
    db.close();
}
</code>```

Body:
try to insert string array into table but id for insert not increase and the first string has been insert. i use autoincreament for id?

Table Create

//Multi Farm Table
String CREATE_MULTI_FARM_TABLE = "CREATE TABLE " + TABLE_MULTI_FARM + "(" +
        KEY_MULTI_FARM_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
        KEY_MULTI_FARM_FARM_NAME + " TEXT" + ")";
db.execSQL(CREATE_MULTI_FARM_TABLE);

Insert Record Function

//Add Multi Farm
public void addMultiFarm(MultiFarmModel multiFarm) {
    SQLiteDatabase db = this.getWritableDatabase();
    ContentValues values = new ContentValues();
    values.put(KEY_MULTI_FARM_ID, multiFarm.getId());
    values.put(KEY_MULTI_FARM_FARM_NAME, multiFarm.getFarmName());
    //Insert Record
    Log.e("StringInsertId", "" + db.insert(TABLE_MULTI_FARM, null, values));
    db.close();
}

Function in Class

public MultiFarmModel(String farmName){
    this.farmName = farmName;
}

Insert Code

String smsContent = "InsertToTable A|B|C|D|E";
DBHandler db = new DBHandler(context);
                smsContent = smsContent.substring(smsContent.indexOf(" ")+1);
                String[] string = smsContent.split("\\|");
                db.deleteAllMultiFarmRecord();
                for (String s : string) {
                    Log.e("StringToInsert", s + " ? ");
                    db.addMultiFarm(new MultiFarmModel(s));
                }
            }

Log Console

E/String Number: A|B|C|D|E
E/StringToInsert: A ?
E/StringInsertId: 0
E/StringToInsert: B ?
E/StringInsertId: -1
E/StringToInsert: C ?
E/StringInsertId: -1
E/StringToInsert: D ?
E/StringInsertId: -1
E/StringToInsert: E ?
E/StringInsertId: -1

Body:
Remove this KEY_MULTI_FARM_ID line because it's auto increment column... you are passing same value that's why its throwing error

public void addMultiFarm(MultiFarmModel multiFarm) {
    SQLiteDatabase db = this.getWritableDatabase();
    ContentValues values = new ContentValues();
   // values.put(KEY_MULTI_FARM_ID, multiFarm.getId());
    values.put(KEY_MULTI_FARM_FARM_NAME, multiFarm.getFarmName());
    //Insert Record
    Log.e("StringInsertId", "" + db.insert(TABLE_MULTI_FARM, null, values));
    db.close();
}


问:
How to make custom date validation attribute?
I need help to format a date like this in a EditorFor eg. 3/2017 and so on. I try to code but I see something went wrong.

example:

```<code>public class ValidDate : ValidationAttribute
{
    public override bool IsValid(object value)
    {
        DateTime dateTime;

        var isValid = DateTime.TryParseExact(Convert.ToString(value),
            "MM/yyyy",
            CultureInfo.CurrentCulture,
            DateTimeStyles.None,
            out dateTime);

        return isValid;
    }
}

[ValidDate]
public DateTime Date { get; set; }
</code>```

Valid Result Examples:

```<code>1/2017
2/2017
3/2017
4/2017
5/2017
6/2017
7/2017
8/2017
9/2017
10/2017
11/2017
12/2017
</code>```

答:
I've checked you attribute and found out that  you passed date as M/yyyy format.
That's why you need change attribute as below:</p>

```<code>public class ValidDate : ValidationAttribute
{
    public override bool IsValid(object value)
    {
        DateTime dateTime;

        var isValid = DateTime.TryParseExact(Convert.ToString(value),
            "M/yyyy",
            CultureInfo.CurrentCulture,
            DateTimeStyles.None,
            out dateTime);

        return isValid;
    }
}
</code>```

Body:
I need help to format a date like this in a EditorFor eg. 3/2017 and so on. I try to code but I see something went wrong.

example:

public class ValidDate : ValidationAttribute
{
    public override bool IsValid(object value)
    {
        DateTime dateTime;

        var isValid = DateTime.TryParseExact(Convert.ToString(value),
            "MM/yyyy",
            CultureInfo.CurrentCulture,
            DateTimeStyles.None,
            out dateTime);

        return isValid;
    }
}

[ValidDate]
public DateTime Date { get; set; }

Valid Result Examples:

1/2017
2/2017
3/2017
4/2017
5/2017
6/2017
7/2017
8/2017
9/2017
10/2017
11/2017
12/2017

Body:
I've checked you attribute and found out that  you passed date as M/yyyy format.
That's why you need change attribute as below:

public class ValidDate : ValidationAttribute
{
    public override bool IsValid(object value)
    {
        DateTime dateTime;

        var isValid = DateTime.TryParseExact(Convert.ToString(value),
            "M/yyyy",
            CultureInfo.CurrentCulture,
            DateTimeStyles.None,
            out dateTime);

        return isValid;
    }
}


问:
Remove empty elements from an array in Javascript
How do I remove empty elements from an array in JavaScript?

Is there a straightforward way, or do I need to loop through it and remove them manually?

答:
This might help you : https://lodash.com/docs/4.17.4#remove

```<code>var details = [
            {
                reference: 'ref-1',
                description: 'desc-1',
                price: 1
            }, {
                reference: '',
                description: '',
                price: ''
            }, {
                reference: 'ref-2',
                description: 'desc-2',
                price: 200
            }, {
                reference: 'ref-3',
                description: 'desc-3',
                price: 3
            }, {
                reference: '',
                description: '',
                price: ''
            }
        ];

        scope.removeEmptyDetails(details);
        expect(details.length).toEqual(3);
</code>```

```<code>scope.removeEmptyDetails = function(details){
            _.remove(details, function(detail){
                return (_.isEmpty(detail.reference) && _.isEmpty(detail.description) && _.isEmpty(detail.price));
            });
        };
</code>```

OwnerDisplayName: DrJokepu

Body:
This might help you : https://lodash.com/docs/4.17.4#remove

var details = [
            {
                reference: 'ref-1',
                description: 'desc-1',
                price: 1
            }, {
                reference: '',
                description: '',
                price: ''
            }, {
                reference: 'ref-2',
                description: 'desc-2',
                price: 200
            }, {
                reference: 'ref-3',
                description: 'desc-3',
                price: 3
            }, {
                reference: '',
                description: '',
                price: ''
            }
        ];

        scope.removeEmptyDetails(details);
        expect(details.length).toEqual(3);

scope.removeEmptyDetails = function(details){
            _.remove(details, function(detail){
                return (_.isEmpty(detail.reference) && _.isEmpty(detail.description) && _.isEmpty(detail.price));
            });
        };


问:
Can I remote install a free iPhone app using WiFi to iPhones connected to it?
I am trying to install an iPhone app to all users connected to my WiFi. Is there a way by which I can achieve that?</p>

答: No, that's not possible.You can only install the app through iTunes or through Xcode if you have its source code.</p>


问:
How to deserialize multiple objects sequentially using jackson-databind
I am using msgpack to serialize data. I have some code works fine with serializing data.

```<code>public void testJackson() throws Exception {
    ByteArrayOutputStream out = new ByteArrayOutputStream();

    String data1 = "test data";
    int data2 = 10;
    List<String> data3 = new ArrayList<String>();
    data3.add("list data1");
    data3.add("list data1");

    ObjectMapper mapper = new ObjectMapper();
    mapper.writeValue(out, data1);
    mapper.writeValue(out, data2);
    mapper.writeValue(out, data3);

    // TODO: How to deserialize?

}
</code>```

But now I don't know how to deserialize data.
I am not finding any solution anywhere. It will be good if anyone can help how to proceed.

答:
The problem

I have tried many of the readValue methods, but I only can get the first String, about the second and third value I have no idea

The thing is, Jackson always reads the first data, since the data is neither deleted from the nor did you explicitly tell Jackson that the next data is from position A to position B

Solutions

this example works and is similar to your code, but is not very elegant. Here I explicitly tell Jackson where my data is, but I have to know how it got written, which is a way too specific solution

```<code>File dataFile = new File("jackson.txt");
if(!dataFile.exists())
  dataFile.createNewFile();
FileOutputStream fileOut = new FileOutputStream(dataFile);
ByteArrayOutputStream out = new ByteArrayOutputStream();
FileInputStream fileIn = new FileInputStream(dataFile);

String writeData1 = "test data";
int writeData2 = 10;
List<String> writeData3 = new ArrayList<String>();
writeData3.add("list data1");
writeData3.add("list data1");

ObjectMapper mapper = new ObjectMapper();
byte[] writeData1Bytes = mapper.writeValueAsBytes(writeData1);
out.write(writeData1Bytes);
byte[] writeData2Bytes = mapper.writeValueAsBytes(writeData2);
out.write(writeData2Bytes);
byte[] writeData3Bytes = mapper.writeValueAsBytes(writeData3);
out.write(writeData3Bytes);
out.writeTo(fileOut);

// TODO: How to deserialize?
int pos = 0;
byte[] readData = new byte[1000];
fileIn.read(readData);
String readData1 = mapper.readValue(readData, pos, writeData1Bytes.length, String.class);
pos += writeData1Bytes.length;
Integer readData2 = mapper.readValue(readData, pos, writeData2Bytes.length, Integer.class);
pos += writeData2Bytes.length;
ArrayList readData3 = mapper.readValue(readData, pos, writeData3Bytes.length, ArrayList.class);
pos += writeData3Bytes.length;

System.out.printf("readData1 = %s%n", readData1);
System.out.printf("readData2 = %s%n", readData2);
System.out.printf("readData3 = %s%n", readData3);
</code>```

the file looks then like this

```<code>"test data"10["list data1","list data1"]
</code>```

How to do it correctly

a way more elegant way is to encapsulate your data in an object which can be turned into a valid JSON string and from that Jackson won't need any more information

```<code>public class JacksonTest {
  public static class DataNode {
    @JsonProperty("data1")
    private String data1;
    @JsonProperty("data2")
    private int data2;
    @JsonProperty("data3")
    private List<String> data3;

    //needed for Jackson
    public DataNode() {
    }

    public DataNode(String data1, int data2, List<String> data3) {
      this.data1 = data1;
      this.data2 = data2;
      this.data3 = data3;
    }
  }

  public static void main(String[] args) throws Exception {
    File dataFile = new File("jackson.txt");
    if(!dataFile.exists())
      dataFile.createNewFile();
    FileOutputStream fileOut = new FileOutputStream(dataFile);
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    FileInputStream fileIn = new FileInputStream(dataFile);

    String writeData1 = "test data";
    int writeData2 = 10;
    List<String> writeData3 = new ArrayList<String>();
    writeData3.add("list data1");
    writeData3.add("list data1");

    DataNode writeData = new DataNode(writeData1, writeData2, writeData3);

    ObjectMapper mapper = new ObjectMapper();
    mapper.writeValue(out, writeData);
    out.writeTo(fileOut);

    // TODO: How to deserialize?
    DataNode readData = mapper.readValue(fileIn, DataNode.class);

    System.out.printf("readData1 = %s%n", readData.data1);
    System.out.printf("readData2 = %s%n", readData.data2);
    System.out.printf("readData3 = %s%n", readData.data3);
  }
}
</code>```

the content of the file looks like this

```<code>{"data1":"test data","data2":10,"data3":["list data1","list data1"]}
</code>```

Body:
I am using msgpack to serialize data. I have some code works fine with serializing data.

public void testJackson() throws Exception {
    ByteArrayOutputStream out = new ByteArrayOutputStream();

    String data1 = "test data";
    int data2 = 10;
    List<String> data3 = new ArrayList<String>();
    data3.add("list data1");
    data3.add("list data1");

    ObjectMapper mapper = new ObjectMapper();
    mapper.writeValue(out, data1);
    mapper.writeValue(out, data2);
    mapper.writeValue(out, data3);

    // TODO: How to deserialize?

}

But now I don't know how to deserialize data.
I am not finding any solution anywhere. It will be good if anyone can help how to proceed.

Body:
The problem

I have tried many of the readValue methods, but I only can get the first String, about the second and third value I have no idea

The thing is, Jackson always reads the first data, since the data is neither deleted from the nor did you explicitly tell Jackson that the next data is from position A to position B

Solutions

this example works and is similar to your code, but is not very elegant. Here I explicitly tell Jackson where my data is, but I have to know how it got written, which is a way too specific solution

File dataFile = new File("jackson.txt");
if(!dataFile.exists())
  dataFile.createNewFile();
FileOutputStream fileOut = new FileOutputStream(dataFile);
ByteArrayOutputStream out = new ByteArrayOutputStream();
FileInputStream fileIn = new FileInputStream(dataFile);

String writeData1 = "test data";
int writeData2 = 10;
List<String> writeData3 = new ArrayList<String>();
writeData3.add("list data1");
writeData3.add("list data1");

ObjectMapper mapper = new ObjectMapper();
byte[] writeData1Bytes = mapper.writeValueAsBytes(writeData1);
out.write(writeData1Bytes);
byte[] writeData2Bytes = mapper.writeValueAsBytes(writeData2);
out.write(writeData2Bytes);
byte[] writeData3Bytes = mapper.writeValueAsBytes(writeData3);
out.write(writeData3Bytes);
out.writeTo(fileOut);

// TODO: How to deserialize?
int pos = 0;
byte[] readData = new byte[1000];
fileIn.read(readData);
String readData1 = mapper.readValue(readData, pos, writeData1Bytes.length, String.class);
pos += writeData1Bytes.length;
Integer readData2 = mapper.readValue(readData, pos, writeData2Bytes.length, Integer.class);
pos += writeData2Bytes.length;
ArrayList readData3 = mapper.readValue(readData, pos, writeData3Bytes.length, ArrayList.class);
pos += writeData3Bytes.length;

System.out.printf("readData1 = %s%n", readData1);
System.out.printf("readData2 = %s%n", readData2);
System.out.printf("readData3 = %s%n", readData3);

the file looks then like this

"test data"10["list data1","list data1"]

How to do it correctly

a way more elegant way is to encapsulate your data in an object which can be turned into a valid JSON string and from that Jackson won't need any more information

public class JacksonTest {
  public static class DataNode {
    @JsonProperty("data1")
    private String data1;
    @JsonProperty("data2")
    private int data2;
    @JsonProperty("data3")
    private List<String> data3;

    //needed for Jackson
    public DataNode() {
    }

    public DataNode(String data1, int data2, List<String> data3) {
      this.data1 = data1;
      this.data2 = data2;
      this.data3 = data3;
    }
  }

  public static void main(String[] args) throws Exception {
    File dataFile = new File("jackson.txt");
    if(!dataFile.exists())
      dataFile.createNewFile();
    FileOutputStream fileOut = new FileOutputStream(dataFile);
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    FileInputStream fileIn = new FileInputStream(dataFile);

    String writeData1 = "test data";
    int writeData2 = 10;
    List<String> writeData3 = new ArrayList<String>();
    writeData3.add("list data1");
    writeData3.add("list data1");

    DataNode writeData = new DataNode(writeData1, writeData2, writeData3);

    ObjectMapper mapper = new ObjectMapper();
    mapper.writeValue(out, writeData);
    out.writeTo(fileOut);

    // TODO: How to deserialize?
    DataNode readData = mapper.readValue(fileIn, DataNode.class);

    System.out.printf("readData1 = %s%n", readData.data1);
    System.out.printf("readData2 = %s%n", readData.data2);
    System.out.printf("readData3 = %s%n", readData.data3);
  }
}

the content of the file looks like this

{"data1":"test data","data2":10,"data3":["list data1","list data1"]}


问:
Swift + AVAudioRecorder records very quietly
I have built an iOS App in Swift that records audio clips, these clips are then sent up to the server. Every recording I make is very quiet.

Initially I thought my problems were similar to this question on Stack Overflow - but after trying this solution, my recordings are still very quiet.

Routing the audio through the speaker does not make the recordings any louder, as is suggested here:

https://stackoverflow.com/a/5662478/1037617

Note that its not playback on the device that is an issue. The issue is that the recordings are too quiet. I have tested the Microphone itself, and it is fine.

This is the best waveform I can produce, and this is almost shouting into the Microphone. As you can see, the waveform recorded is very quiet:

Is there any way of getting my iOS App to record at a louder volume?

This is the code I am using to record the audio clips:

```<code>let recorderSettings=[
    AVFormatIDKey            : kAudioFormatLinearPCM,
    AVEncoderAudioQualityKey : AVAudioQuality.Max.rawValue,
    AVEncoderBitRateKey      : 128000,
    AVNumberOfChannelsKey    : 1,
    AVSampleRateKey          : 44100.0
]

let session: AVAudioSession = AVAudioSession.sharedInstance()
var error: NSError?
if session.respondsToSelector("requestRecordPermission:") {
    AVAudioSession.sharedInstance().requestRecordPermission( { (granted:Bool) -> Void in
        if !granted {
            println("permission not granted")
        }else{
            println("permission granted")

            if !session.setCategory(AVAudioSessionCategoryRecord, error: &error) { // also tried PlaybackAndRecord
                println("could not set sesssion category")
                if let e = error {
                    println(e.localizedDescription)
                }
            }

            if !session.overrideOutputAudioPort(AVAudioSessionPortOverride.Speaker, error: &error) {
                println("could not override output audio")
                if let e = error {
                    println(e.localizedDescription)
                }
            }

            if !session.setActive(true, error: &error) {
                println("could not make active")
                if let e = error {
                    println(e.localizedDescription)
                }
            }

            self.currentFilename = "xxxx.wav"
            let dirPaths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)
            let docsDir: AnyObject=dirPaths[0]
            self.recordedFilePath = docsDir.stringByAppendingPathComponent(self.currentFilename)
            self.recordedFileURL = NSURL(fileURLWithPath: self.recordedFilePath)

            self.recorder = AVAudioRecorder(URL:self.recordedFileURL, settings: self.recorderSettings, error: &error)

            if let e = error {
                println(e)
                println(e.localizedDescription)
                var err = NSError(domain: NSOSStatusErrorDomain, code: e.code, userInfo: nil)
                println(err.description)
            }else{

                self.recorder?.delegate = self
                self.recorder?.meteringEnabled = true
                self.recorder?.prepareToRecord()

                self.recorder?.record()

                self.meterTimer = NSTimer.scheduledTimerWithTimeInterval(0.1,
                    target: self,
                    selector: "updateRecordAudioMeter:",
                    userInfo: nil,
                    repeats: true)

            }
        }
    })
}
</code>```

答: When recording audio, set the audio session to AVAudioSessionCategoryPlayAndRecord or just AVAudioSessionCategoryRecord. When you're done, set it back to just AVAudioSessionCategoryPlayback.

Body:
I have built an iOS App in Swift that records audio clips, these clips are then sent up to the server. Every recording I make is very quiet.

Initially I thought my problems were similar to this question on Stack Overflow - but after trying this solution, my recordings are still very quiet.

Routing the audio through the speaker does not make the recordings any louder, as is suggested here:

https://stackoverflow.com/a/5662478/1037617

Note that its not playback on the device that is an issue. The issue is that the recordings are too quiet. I have tested the Microphone itself, and it is fine.

This is the best waveform I can produce, and this is almost shouting into the Microphone. As you can see, the waveform recorded is very quiet:

Is there any way of getting my iOS App to record at a louder volume?

This is the code I am using to record the audio clips:

let recorderSettings=[
    AVFormatIDKey            : kAudioFormatLinearPCM,
    AVEncoderAudioQualityKey : AVAudioQuality.Max.rawValue,
    AVEncoderBitRateKey      : 128000,
    AVNumberOfChannelsKey    : 1,
    AVSampleRateKey          : 44100.0
]

let session: AVAudioSession = AVAudioSession.sharedInstance()
var error: NSError?
if session.respondsToSelector("requestRecordPermission:") {
    AVAudioSession.sharedInstance().requestRecordPermission( { (granted:Bool) -> Void in
        if !granted {
            println("permission not granted")
        }else{
            println("permission granted")

            if !session.setCategory(AVAudioSessionCategoryRecord, error: &error) { // also tried PlaybackAndRecord
                println("could not set sesssion category")
                if let e = error {
                    println(e.localizedDescription)
                }
            }

            if !session.overrideOutputAudioPort(AVAudioSessionPortOverride.Speaker, error: &error) {
                println("could not override output audio")
                if let e = error {
                    println(e.localizedDescription)
                }
            }

            if !session.setActive(true, error: &error) {
                println("could not make active")
                if let e = error {
                    println(e.localizedDescription)
                }
            }

            self.currentFilename = "xxxx.wav"
            let dirPaths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)
            let docsDir: AnyObject=dirPaths[0]
            self.recordedFilePath = docsDir.stringByAppendingPathComponent(self.currentFilename)
            self.recordedFileURL = NSURL(fileURLWithPath: self.recordedFilePath)

            self.recorder = AVAudioRecorder(URL:self.recordedFileURL, settings: self.recorderSettings, error: &error)

            if let e = error {
                println(e)
                println(e.localizedDescription)
                var err = NSError(domain: NSOSStatusErrorDomain, code: e.code, userInfo: nil)
                println(err.description)
            }else{

                self.recorder?.delegate = self
                self.recorder?.meteringEnabled = true
                self.recorder?.prepareToRecord()

                self.recorder?.record()

                self.meterTimer = NSTimer.scheduledTimerWithTimeInterval(0.1,
                    target: self,
                    selector: "updateRecordAudioMeter:",
                    userInfo: nil,
                    repeats: true)

            }
        }
    })
}


问:
Can i implement Row level security in power bi Rest Api approach
I have registered Client app from power bi

Implemented RLS(row level security) in desktop for report, and publish to power bi portal.

using  power bi Rest Api approach embedded the report into my web application.

the problem is the report showing all information which is not required for user.
Is it possible to have RLS(Row level security) for the report?

It is possible in Azure power bi embedded api, has

```<code>var embedToken = PowerBIToken.CreateReportEmbedToken(this.workspaceCollection, this.workspaceId, report.Id, "Andrew Ma", ["Manager"]);'
</code>```

答:
Here, He gave answer for my query

https://www.youtube.com/watch?v=nfkVljh_9O4&list=PLv2BtOtLblH2Rm9trJPuxmN8Kr8WFv7O0&index=2

Body:
I have registered Client app from power bi

Implemented RLS(row level security) in desktop for report, and publish to power bi portal.

using  power bi Rest Api approach embedded the report into my web application.

the problem is the report showing all information which is not required for user.
Is it possible to have RLS(Row level security) for the report?

It is possible in Azure power bi embedded api, has

var embedToken = PowerBIToken.CreateReportEmbedToken(this.workspaceCollection, this.workspaceId, report.Id, "Andrew Ma", ["Manager"]);'


问:
How can I create a list of new objects in C#?
I'd like to create a list of objects for a list. I understand it possible to do this below but this isn't what I am after.

```<code>view.BindingContext =
                new ViewModel
            {
                List = new List<Section> {
                    new Section
                    {
                        Title = "Chapter 1",
                        List = new List<Reading> {
                            new Reading { Title = "Title" Text = "abc" },
                            new Reading { Title = "Title" Text = "abc" },
                            new Reading { Title = "Title" Text = "abc" },
                            new Reading { Title = "Title" Text = "abc" },
                            new Reading { Title = "Title" Text = "abc" },
                            new Reading { Title = "Title" Text = "abc" },
                            new Reading { Title = "Title" Text = "abc" },
                        }
                    },
                }
            };
</code>```

Instead of the code above I'd like to create new objects from another list of objects. so something like this;

```<code>view.BindingContext =
            new ViewModel
            {
                List = new List<Section>
                {
                 foreach(Chapter chapter in ChapterList)
                    {
                    new Section { Title = chapter.Title, List = chapter.ReadingList },
                    }
                }
            };
</code>```

答:
Well, you could just loop after the initial construction. Doing everything in one statement is over-rated.

However!

```<code>new List<Foo>(oldList.Select(x => new Foo { A = x.A, B = x.B, ... }))
</code>```

should work as a simple clone of the list and list items, as would:

```<code>oldList.ConvertAll(x => new Foo { A = x.A, B = x.B, ...})
</code>```

or (as noted in the comments)

```<code>oldList.Select(x => new Foo { A = x.A, B = x.B, ... }).ToList()
</code>```

Body:
I'd like to create a list of objects for a list. I understand it possible to do this below but this isn't what I am after.

view.BindingContext =
                new ViewModel
            {
                List = new List
 {
                    new Section
                    {
                        Title = "Chapter 1",
                        List = new List<Reading> {
                            new Reading { Title = "Title" Text = "abc" },
                            new Reading { Title = "Title" Text = "abc" },
                            new Reading { Title = "Title" Text = "abc" },
                            new Reading { Title = "Title" Text = "abc" },
                            new Reading { Title = "Title" Text = "abc" },
                            new Reading { Title = "Title" Text = "abc" },
                            new Reading { Title = "Title" Text = "abc" },
                        }
                    },
                }
            };

Instead of the code above I'd like to create new objects from another list of objects. so something like this;

view.BindingContext =
            new ViewModel
            {
                List = new List

                {
                 foreach(Chapter chapter in ChapterList)
                    {
                    new Section { Title = chapter.Title, List = chapter.ReadingList },
                    }
                }
            };

Body:
Well, you could just loop after the initial construction. Doing everything in one statement is over-rated.

However!

new List<Foo>(oldList.Select(x => new Foo { A = x.A, B = x.B, ... }))

should work as a simple clone of the list and list items, as would:

oldList.ConvertAll(x => new Foo { A = x.A, B = x.B, ...})

or (as noted in the comments)

oldList.Select(x => new Foo { A = x.A, B = x.B, ... }).ToList()


问:
Laravel : Removing an element from a collection array
i use a variable called $users to "pluck" only the emails from my users table, using:

$users = user::all()->pluck('email');

when i dd($users), i get this

```<code>```
Collection {#214 ▼
  #items: array:8 [▼
    0 => "adminone@example.com"
    1 => "admintwo@example.com"
    2 => "Adobot@example.com"
    3 => "Lawly@example.com"
    4 => "Cerms@example.com"
    5 => "Charlie@example.com"
    6 => "test@example.com"
    7 => "test001@example.com"
  ]
}
```
</code>```

meaning that $users isn't purely an array, i get various types of errors when i treat it like an array.

my question is, in php (in a Laravel Framework) how do i remove a specific user's email from the variable above? or is there a better way to use "pluck" so that it returns an array instead?

thanks in advance.

答:
If you want to remove email where email id where index is 0  then you follow below query first

```<code>   $users = user::all()->pluck('email');
   unset($users['0']);
   $dd($users);
</code>```

Body:
i use a variable called $users to "pluck" only the emails from my users table, using:

$users = user::all()->pluck('email');

when i dd($users), i get this

Collection {#214 ▼
  #items: array:8 [▼
    0 => "adminone@example.com"
    1 => "admintwo@example.com"
    2 => "Adobot@example.com"
    3 => "Lawly@example.com"
    4 => "Cerms@example.com"
    5 => "Charlie@example.com"
    6 => "test@example.com"
    7 => "test001@example.com"
  ]
}

meaning that $users isn't purely an array, i get various types of errors when i treat it like an array.

my question is, in php (in a Laravel Framework) how do i remove a specific user's email from the variable above? or is there a better way to use "pluck" so that it returns an array instead?

thanks in advance.

Body:
If you want to remove email where email id where index is 0  then you follow below query first

   $users = user::all()->pluck('email');
   unset($users['0']);
   $dd($users);


问:
IE8's information bar blocking a scripted file download in response to JQuery AJAX request
I have an html/javascript frontend that is using JQuery's AJAX request to send XML containing user-entered form data to a backend application which in turn creates a PDF from that information. The frontend receives a UUID in response, which it then uses in the download url to download the generated PDF.

This works wonderfully in Firefox and Safari, but is being blocked by Internet Explorer 8's protection against scripted downloads. Telling IE8 to download the file via the spawned Information Bar forces a reload of the page, which blanks out all of the entered user content.

A single onMouseUp event on a button-esque element is triggering the generation of the XML to send, sending the XML, getting its response, then initiating the download via setting the url in the window.location object. Separating out that download into a different button (having one generate and send the xml and fetch the UUID, and the other only initiate the download using the url made from the UUID) bypasses the information bar but ruins the simplicity and intuitiveness of the interface.

Here are the relevant javascript functions:

```<code>function sendXml()
{
    var documentXml = generateDocumentXml();
    var percentEncodedDocumentXml = escape(DocumentXml);
    var url = "generate?document=" + percentEncodedDocumentXml;
    $.ajax({
        url: url,
        type: "GET",
        dataType: "xml",
        success: function (xml)
        {
            var uuid = $(xml).find('uuid').text();
            getPdf(uuid);
        },
        error: function (xhr)
        {
            alert("There was an error creating your PDF template");
        }
    });
}

function getPdf(uuid)
{
    var url = "generate?get-pdf=" + uuid;
    window.location = url;
}
</code>```

I'm fishing for suggestions about how to best handle this issue. My first preference would be to have the information bar not interfere at all, but minimizing its harm would be a dramatic improvement over the current situation. If it could not reload and wipe the frontend interface, and actually proceed to downloading the file when the user chooses to "Download File..." via the Information Bar's menu, that would help.

答:
I tested it and the reason for the bar to occur seems to be the fact, that there is no direct relation between the user-action(mouseover) and the loading of the URL(guess a PDF-file).

This workaround will solve the issue:

Create an iframe(may be hidden) inside the document and use

```<code>window.open(url,'nameAttributeOfTheIframe')
</code>```

...to load the PDF. The bar occurs too, but if the user chooses to download, the current document will reload too, but the user-content(if you mean form-data) will remain, as the bar belongs to the iframe not to the parent document.

Be sure to send a attachment-header with the PDF too, to beware of showing it inside the browser(if the browser is able to), because if you use a hidden iframe the user cannot see what's loaded there.

```<code><iframe name="nameAttributeOfTheIframe" style="display:none"></iframe>
<input type="button" value="click here"  onclick="f1()"/>
<input value="default value">
<script type="text/javascript">
<!--
function f1()
{
   //simulate delayed download
   setTimeout(f2,1000)
}

function f2()
{
  window.open('http://www.ecma-international.org/publications/files/ECMA-ST/ECMA-262.pdf','nameAttributeOfTheIframe');
}

document.getElementsByTagName('input')[1].value='this is modified value, should remain';

//-->
</script>
</code>```

Body:
I have an html/javascript frontend that is using JQuery's AJAX request to send XML containing user-entered form data to a backend application which in turn creates a PDF from that information. The frontend receives a UUID in response, which it then uses in the download url to download the generated PDF.

This works wonderfully in Firefox and Safari, but is being blocked by Internet Explorer 8's protection against scripted downloads. Telling IE8 to download the file via the spawned Information Bar forces a reload of the page, which blanks out all of the entered user content.

A single onMouseUp event on a button-esque element is triggering the generation of the XML to send, sending the XML, getting its response, then initiating the download via setting the url in the window.location object. Separating out that download into a different button (having one generate and send the xml and fetch the UUID, and the other only initiate the download using the url made from the UUID) bypasses the information bar but ruins the simplicity and intuitiveness of the interface.

Here are the relevant javascript functions:

function sendXml()
{
    var documentXml = generateDocumentXml();
    var percentEncodedDocumentXml = escape(DocumentXml);
    var url = "generate?document=" + percentEncodedDocumentXml;
    $.ajax({
        url: url,
        type: "GET",
        dataType: "xml",
        success: function (xml)
        {
            var uuid = $(xml).find('uuid').text();
            getPdf(uuid);
        },
        error: function (xhr)
        {
            alert("There was an error creating your PDF template");
        }
    });
}

function getPdf(uuid)
{
    var url = "generate?get-pdf=" + uuid;
    window.location = url;
}

I'm fishing for suggestions about how to best handle this issue. My first preference would be to have the information bar not interfere at all, but minimizing its harm would be a dramatic improvement over the current situation. If it could not reload and wipe the frontend interface, and actually proceed to downloading the file when the user chooses to "Download File..." via the Information Bar's menu, that would help.

Body:
I tested it and the reason for the bar to occur seems to be the fact, that there is no direct relation between the user-action(mouseover) and the loading of the URL(guess a PDF-file).

This workaround will solve the issue:

Create an iframe(may be hidden) inside the document and use

window.open(url,'nameAttributeOfTheIframe')

...to load the PDF. The bar occurs too, but if the user chooses to download, the current document will reload too, but the user-content(if you mean form-data) will remain, as the bar belongs to the iframe not to the parent document.

Be sure to send a attachment-header with the PDF too, to beware of showing it inside the browser(if the browser is able to), because if you use a hidden iframe the user cannot see what's loaded there.

<iframe name="nameAttributeOfTheIframe" style="display:none"></iframe>
<input type="button" value="click here"  onclick="f1()"/>
<input value="default value">
<script type="text/javascript">
<!--
function f1()
{
   //simulate delayed download
   setTimeout(f2,1000)
}

function f2()
{
  window.open('http://www.ecma-international.org/publications/files/ECMA-ST/ECMA-262.pdf','nameAttributeOfTheIframe');
}

document.getElementsByTagName('input')[1].value='this is modified value, should remain';

//-->
</script>