问:
SQL Server statement with bulk insert
I am working on a project where I have used the bulk insert statement to import a batch .csv file into a table.

The problem I have is that some of the records are duplicates to what is currently in the table I am looking to import data into. Is there a way to run a statement with the bulk insert to check for specific rows that match the file rows based off of certain criteria?

I am sure there is a way to make this work, just nothing I have in mind.

答:
No, the BULK INSERT statement is optimized for raw speed - it just inserts that data as quickly as possible - but it does not allow for inspection or decisions to be made while importing.

The usual approach in such a case is to bulk insert your data into a staging table, and then after that's done, copy only those rows that are not duplicates into the actual data table and discard everything else.

But that's a separate step - cannot be done while bulk inserting ....

Title: SQL Server statement with bulk insert


来源: stackexchange

问:
Is EmailComposeTask Class already working?
For example here:

http://msdn.microsoft.com/en-us/library/ff769550(VS.92).asp

```
<code>EmailComposeTask emailComposeTask = new EmailComposeTask();
emailComposeTask.To = "user@example.com";
emailComposeTask.Body = "Email message body";
emailComposeTask.Cc = "user2@example.com";
emailComposeTask.Subject = "Email subject";
emailComposeTask.Show();
</code>
```

I read it doesnt work yet.

答:
I have a real device, and an application in the marketplace - it is definitely working. The reason it doesn't work on an emulator is that you can't set up an email account on the emulator, and the first step of the email compose task when it is run is to prompt the user to select which email account to send the email with (if you've got more than one)

Since you can't set one up on the emulator, it kicks back and you can't send an email.

The only way to test this (for now) is to debug on an actual WP7 device, but I can 100% guarantee this is working.

One thing to note about the email tasker is that you can't programmatically add attachments...yet.

ContentLicense: CC BY-SA 2.5

Body:
For example here:

http://msdn.microsoft.com/en-us/library/ff769550(VS.92).asp

EmailComposeTask emailComposeTask = new EmailComposeTask();
emailComposeTask.To = "user@example.com";
emailComposeTask.Body = "Email message body";
emailComposeTask.Cc = "user2@example.com";
emailComposeTask.Subject = "Email subject";
emailComposeTask.Show();

I read it doesnt work yet.


问:
I want to display the output with full string
```<code>Connect-VIServer XXXX

[System.Collections.ArrayList]$Result=@()
$vms = Get-VM | Where-Object {$_.Name -like 'XXX*'}
try{
 ForEach ($v in $vms)
  {
   foreach ($d in $v.ExtensionData.Guest.Disk)
    {
    $usedSpace = $d.Capacity - $d.FreeSpace
    $percentUsed =  [math]::Round(($usedSpace / $d.Capacity) * 100)

    $List = New-Object -TypeName PSObject -Property @{
        SERVER_NAME = $v.Name | Out-String
            "Total_Capacity(GB)" = [math]::round([int]($d.Capacity/1GB), 1)
            "Free_Space(GB)" = [math]::round([int]($d.FreeSpace/1GB), 1)
            PercentFull = "$percentUsed%"
                        }
                #Write-Host "$ErrorList"
            $Result+=$List
    }
  }
}
catch [Exception]
{
write-host "OD-VM-Monitor: $v : FATAL SCRIPT ERROR" $_.Exception.Message
}
</code>```

I have executed the above script. but while trying to display the result, it is showing with dot like below . I tried the below two.

```<code>$Result | Select-Object SERVER_NAME, 'Total_Capacity(GB)', 'Free_Space(GB)', PercentFull | Out-String -Width 4096 | ft -auto
$Result | Select-Object SERVER_NAME, 'Total_Capacity(GB)', 'Free_Space(GB)', PercentFull | Format-Table -AutoSize

SERVER_NAME     Total_Capacity(GB) Free_Space(GB) PercentFull
-----------     ------------------ -------------- -----------
XXXXXXX...                200            113 43%
XXXXXXX...                150             50 67%
XXXXXXX...                150             31 79%
XXXXXXX...                100             32 68%
XXXXXXX...                500             87 83%
XXXXXXX...                100             43 57%
XXXXXXX...                100             36 64%
XXXXXXX...                150             37 75%
</code>```

Any idea how to get rid out of the dots.
Thanks in advance.

答:
It's because the strings are too wide for your screen (console windows).
Try a format-list instead of format-table to confirm that data is not ruined.

This is a guide to Change the size both programmatically and through the GUI: https://blogs.technet.microsoft.com/heyscriptingguy/2006/12/04/how-can-i-expand-the-width-of-the-windows-powershell-console/

ContentLicense: CC BY-SA 3.0

Body:
Connect-VIServer XXXX

[System.Collections.ArrayList]$Result=@()
$vms = Get-VM | Where-Object {$_.Name -like 'XXX*'}
try{
 ForEach ($v in $vms)
  {
   foreach ($d in $v.ExtensionData.Guest.Disk)
    {
    $usedSpace = $d.Capacity - $d.FreeSpace
    $percentUsed =  [math]::Round(($usedSpace / $d.Capacity) * 100)

    $List = New-Object -TypeName PSObject -Property @{
        SERVER_NAME = $v.Name | Out-String
            "Total_Capacity(GB)" = [math]::round([int]($d.Capacity/1GB), 1)
            "Free_Space(GB)" = [math]::round([int]($d.FreeSpace/1GB), 1)
            PercentFull = "$percentUsed%"
                        }
                #Write-Host "$ErrorList"
            $Result+=$List
    }
  }
}
catch [Exception]
{
write-host "OD-VM-Monitor: $v : FATAL SCRIPT ERROR" $_.Exception.Message
}

I have executed the above script. but while trying to display the result, it is showing with dot like below . I tried the below two.

$Result | Select-Object SERVER_NAME, 'Total_Capacity(GB)', 'Free_Space(GB)', PercentFull | Out-String -Width 4096 | ft -auto
$Result | Select-Object SERVER_NAME, 'Total_Capacity(GB)', 'Free_Space(GB)', PercentFull | Format-Table -AutoSize

SERVER_NAME     Total_Capacity(GB) Free_Space(GB) PercentFull
-----------     ------------------ -------------- -----------
XXXXXXX...                200            113 43%
XXXXXXX...                150             50 67%
XXXXXXX...                150             31 79%
XXXXXXX...                100             32 68%
XXXXXXX...                500             87 83%
XXXXXXX...                100             43 57%
XXXXXXX...                100             36 64%
XXXXXXX...                150             37 75%

Any idea how to get rid out of the dots.
Thanks in advance.


问:
PHP: Find last occurence of string in array
I need to find the last found element of a specific value from an array. I giving an example in php of what I'm actually seeking for.

```<code>$Data = array(
    '0' => 'car',
    '1' => 'bike',
    '2' => 'bus',
    '3' => 'bike',
    '4' => 'boat'
 );

$key = array_search('bike', $Data) // it returns $key = 1 as result which the first element matched inside the array.
</code>```

I want $key = 3 which is the last matched element.

Any suggestion appreciated.

答:
For this I am created one function it is very easy to use. You can pass only array and parameters.

```<code>function text_to_id($value, $arr_master) {
    $id_selected = 0;
    $search_array = $arr_master;
    if (in_array($value, $search_array)) {
        $id_selected = array_search($value, $search_array);
        // pr($id_selected);exit;
    }

    if (!$id_selected) {
        foreach ($search_array as $f_key => $f_value) {
            if (is_array($f_value)) {
                if (in_array($value, $f_value)) {
                    $id_selected = $f_key;
                    break;
                }
            } else if ($value == $f_value) {
                $id_selected = $f_key;
                break;
            }
                else;
        }
    }
    return $id_selected;
}
</code>```

this function use like this
  $variable = text_to_id('bike', $your_array);

Body:
I need to find the last found element of a specific value from an array. I giving an example in php of what I'm actually seeking for.

$Data = array(
    '0' => 'car',
    '1' => 'bike',
    '2' => 'bus',
    '3' => 'bike',
    '4' => 'boat'
 );

$key = array_search('bike', $Data) // it returns $key = 1 as result which the first element matched inside the array.

I want $key = 3 which is the last matched element.

Any suggestion appreciated.

Body:
For this I am created one function it is very easy to use. You can pass only array and parameters.

function text_to_id($value, $arr_master) {
    $id_selected = 0;
    $search_array = $arr_master;
    if (in_array($value, $search_array)) {
        $id_selected = array_search($value, $search_array);
        // pr($id_selected);exit;
    }

    if (!$id_selected) {
        foreach ($search_array as $f_key => $f_value) {
            if (is_array($f_value)) {
                if (in_array($value, $f_value)) {
                    $id_selected = $f_key;
                    break;
                }
            } else if ($value == $f_value) {
                $id_selected = $f_key;
                break;
            }
                else;
        }
    }
    return $id_selected;
}

this function use like this
  $variable = text_to_id('bike', $your_array);


问:
Immutable js how to get specific value in complex structure
I have a Immutable Map in structure as below.

Immutable Map

In this map there is specific array with value "filterOptions". Under it, there is maps with arrays. Inside this array, first index is value and second index with specific value like "CMS". Reference from the picture structure, I would like to gather this value such as CMS, MOBILE and etc as return of Immutable map.
How can I do this?

I tried as below and I get error undefined map. Please help

```<code>const filterLevel1AvailableLots= filterLevel1.get('filterOptions').map(option => {
    return Immutable.Map({option: option})});
</code>```

答:
I believe you just want filterLevel1.get('filterOptions').map( not .filter.map(:

var filterLevel1 = Immutable.Map({
  filterOptions: Immutable.List([
    Immutable.Map({value: 'CMS'}),
    Immutable.Map({value: 'Mobile'}),
  ])
});

var filterLevel1AvailableLots = filterLevel1
       .get('filterOptions')
       .map(option => Immutable.Map({option: option}));

console.log(filterLevel1AvailableLots);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/immutable/4.0.0-rc.2/immutable.js"></script></code>```

Body:
I have a Immutable Map in structure as below.

Immutable Map

In this map there is specific array with value "filterOptions". Under it, there is maps with arrays. Inside this array, first index is value and second index with specific value like "CMS". Reference from the picture structure, I would like to gather this value such as CMS, MOBILE and etc as return of Immutable map.
How can I do this?

I tried as below and I get error undefined map. Please help

const filterLevel1AvailableLots= filterLevel1.get('filterOptions').map(option => {
    return Immutable.Map({option: option})});

Body:
I believe you just want filterLevel1.get('filterOptions').map( not .filter.map(:

var filterLevel1 = Immutable.Map({
  filterOptions: Immutable.List([
    Immutable.Map({value: 'CMS'}),
    Immutable.Map({value: 'Mobile'}),
  ])
});

var filterLevel1AvailableLots = filterLevel1
       .get('filterOptions')
       .map(option => Immutable.Map({option: option}));

console.log(filterLevel1AvailableLots);

<script src="https://cdnjs.cloudflare.com/ajax/libs/immutable/4.0.0-rc.2/immutable.js"></script>


问:
How to solve laravel notification with broadcast ? Laravel 5.3
My controller is like this :

```<code>public function add($param)
{
    ...
    $message = Message::create([
        ...
        'created_at'            => Carbon::now(),
        'updated_at'            => Carbon::now()
    ]);
    Notification::send($notify_to, new MessageInsert($message));
    dd($message);
    return $message;
}
</code>```

My MessageInsert is like this :

```<code><?php
namespace App\Notifications;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Notifications\Messages\MailMessage;
use Illuminate\Notifications\Notification;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
class MessageInsert extends Notification implements ShouldBroadcast, ShouldQueue
{
    use Queueable;
    private $data;
    public function __construct($data)
    {
        $this->data = $data;
    }
    public function via($notifiable)
    {
        return ['broadcast','database','mail'];
    }
    public function toArray($notifiable)
    {
        return [
            'id'        => $this->data->id,
            ...
        ];
    }
    public function toMail($notifiable)
    {
        return (new MailMessage)
            ->greeting('Hello!')
            ->line('...')
            ->action('...')
            ->line('Thank you!');
    }
}
</code>```

If like this :

return ['broadcast','database','mail'];

The result of dd($message); is error

But if like this :

return ['database','mail'];

The result of dd($message); is array of $message

Why there is error when I use broadcast?

答:
Did you try adding the toBroadcast function?</p>

```<code>public function toBroadcast($notifiable) {
return new BroadcastMessage([ 'invoice_id' => $this->invoice->id, 'amount' => $this->invoice->amount, ]);
}
</code>```

Body:
My controller is like this :

public function add($param)
{
    ...
    $message = Message::create([
        ...
        'created_at'            => Carbon::now(),
        'updated_at'            => Carbon::now()
    ]);
    Notification::send($notify_to, new MessageInsert($message));
    dd($message);
    return $message;
}

My MessageInsert is like this :

<?php
namespace App\Notifications;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Notifications\Messages\MailMessage;
use Illuminate\Notifications\Notification;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
class MessageInsert extends Notification implements ShouldBroadcast, ShouldQueue
{
    use Queueable;
    private $data;
    public function __construct($data)
    {
        $this->data = $data;
    }
    public function via($notifiable)
    {
        return ['broadcast','database','mail'];
    }
    public function toArray($notifiable)
    {
        return [
            'id'        => $this->data->id,
            ...
        ];
    }
    public function toMail($notifiable)
    {
        return (new MailMessage)
            ->greeting('Hello!')
            ->line('...')
            ->action('...')
            ->line('Thank you!');
    }
}

If like this :

return ['broadcast','database','mail'];

The result of dd($message); is error

But if like this :

return ['database','mail'];

The result of dd($message); is array of $message

Why there is error when I use broadcast?

Body:
Did you try adding the toBroadcast function?

public function toBroadcast($notifiable) {
return new BroadcastMessage([ 'invoice_id' => $this->invoice->id, 'amount' => $this->invoice->amount, ]);
}


问:
Plotting a location into an irregular rectangle
I have 4 Point values: TopLeft, TopRight, BottomLeft, BottomRight. These define a 4 sided shape (like a distorted rectangle) on my monitor. These are the point a Tobii gaze device thinks I am looking at when in fact I am looking at the four corners of my monitor.

This picture shows a bitmap on the left representing my monitor, and the points the Tobii device tells me I am looking at when I am in fact looking at the corners of the screen. (It's a representation, not real).

I want to use those four calibration points to take a screen X,Y position that is from an inaccurate gaze position and correct it so that it is positioned as per the image on the right.

答:
You can define a unique Linear Transform using 6 equations. The 3 points which have to align provide those 6 equations, as each pair of matching points provides two equations in x and y.

If you want to pursue this, I can provide the matrix equation which defines the Linear Transform based on how it maps three points. You invert this matrix and it will provide the linear transform.

But having done that, the transform is completely specified. You have no control over where the corner points of the original quadrilateral will go. In general, you can't even define a linear transform to map one quadrilateral onto another; this gives 8 equations (2 for each corner) with only 6 unknowns. Its over-specified. In fact a Linear Transform must always map a rectangle to a parallelogram, so in general you can't define a Linear Transform which maps one quadrilateral to another.

So if it can't be a Linear Transform, can it be a non-Linear Transform? Well, yes, but non-Linear Transforms don't necessarily map straight lines to straight lines, so the mapped edges of the quadrilateral won't be straight. Or any other lines. And you still have 14 equations (2 for each point and corner) for which you have to invent some non-Linear transform with 14 unknowns.

So the problem as stated cannot be solved with a Linear Transform; its over specified. Using a non-Linear transform will require you to devise a non-Linear transform which has 14 free variables (vs the 6 in a Linear Transform), this will map the 7 points correctly but straight lines will no longer be straight. Adding this requirement in adds an infinite number of constraints (one for every point in the line) and you won't even be able to use continuous functions.

There may be some solution to what you are doing in terms of what you are really trying to do (ie the underlying application need), but as a mathematical problem it is unsolvable.

Let me know if you want the matrix equation to produce a Linear Transform based on how it transforms 3 points.


问:
Inserting a value into all possible locations in a list
I am trying to do print all the possible outcomes of a given list and I was wondering how to put a value into various locations in the list. For example, if my list was [A, B], I want to insert X into all possible index of the list such that it would return this [X, A, B], [A, X, B], [A, B, X].

I was thinking about using range(len()) and a for loop but not sure how to start.

答:
Coming from JavaScript, this was something I was used to having "built-in" via Array.prototype.splice(), so I made a Python function that does the same:</p>

```<code>def list_splice(target, start, delete_count=None, *items):
    """Remove existing elements and/or add new elements to a list.

    target        the target list (will be changed)
    start         index of starting position
    delete_count  number of items to remove (default: len(target) - start)
    *items        items to insert at start index

    Returns a new list of removed items (or an empty list)
    """
    if delete_count == None:
        delete_count = len(target) - start

    # store removed range in a separate list and replace with *items
    total = start + delete_count
    removed = target[start:total]
    target[start:total] = items

    return removed
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Coming from JavaScript, this was something I was used to having "built-in" via Array.prototype.splice(), so I made a Python function that does the same:

def list_splice(target, start, delete_count=None, *items):
    """Remove existing elements and/or add new elements to a list.

    target        the target list (will be changed)
    start         index of starting position
    delete_count  number of items to remove (default: len(target) - start)
    *items        items to insert at start index

    Returns a new list of removed items (or an empty list)
    """
    if delete_count == None:
        delete_count = len(target) - start

    # store removed range in a separate list and replace with *items
    total = start + delete_count
    removed = target[start:total]
    target[start:total] = items

    return removed


问:
error javax.net.ssl.SSLPeerUnverifiedException: No peer certificate and SSLNullSession.java:104
I'm facing this error javax.net.ssl.SSLPeerUnverifiedException: No peer certificate on android version lower than Marshmallow when I use https to connect the server and I'm getting this exception:

```<code>   03-27 16:15:04.481 23391-23469/com.intellinects.app W/System.err: javax.net.ssl.SSLPeerUnverifiedException: No peer certificate
   03-27 16:15:04.495 23391-23469/com.intellinects.app W/System.err:     at com.android.org.conscrypt.SSLNullSession.getPeerCertificates(SSLNullSession.java:104)
   03-27 16:15:04.495 23391-23469/com.intellinects.app W/System.err:     at org.apache.http.conn.ssl.AbstractVerifier.verify(AbstractVerifier.java:93)
   03-27 16:15:04.495 23391-23469/com.intellinects.app W/System.err:     at org.apache.http.conn.ssl.SSLSocketFactory.createSocket(SSLSocketFactory.java:388)
   03-27 16:15:04.495 23391-23469/com.intellinects.app W/System.err:     at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:165)
   03-27 16:15:04.495 23391-23469/com.intellinects.app W/System.err:     at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164)
   03-27 16:15:04.495 23391-23469/com.intellinects.app W/System.err:     at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119)
   03-27 16:15:04.495 23391-23469/com.intellinects.app W/System.err:     at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:360)
   03-27 16:15:04.495 23391-23469/com.intellinects.app W/System.err:     at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555)
   03-27 16:15:04.496 23391-23469/com.intellinects.app W/System.err:     at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
   03-27 16:15:04.496 23391-23469/com.intellinects.app W/System.err:     at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465)
   03-27 16:15:04.496 23391-23469/com.intellinects.app W/System.err:     at com.intellinects.app.Network.executeService(Network.java:77)
   03-27 16:15:04.496 23391-23469/com.intellinects.app W/System.err:     at com.intellinects.app.Network.checkSecureConnection(Network.java:180)
   03-27 16:15:04.496 23391-23469/com.intellinects.app W/System.err:     at com.intellinects.app.Network.get(Network.java:124)
   03-27 16:15:04.496 23391-23469/com.intellinects.app W/System.err:     at com.intellinects.app.SplashActivity$CheckURL.doInBackground(SplashActivity.java:144)
   03-27 16:15:04.496 23391-23469/com.intellinects.app W/System.err:     at com.intellinects.app.SplashActivity$CheckURL.doInBackground(SplashActivity.java:127)
   03-27 16:15:04.496 23391-23469/com.intellinects.app W/System.err:     at android.os.AsyncTask$2.call(AsyncTask.java:288)
   03-27 16:15:04.496 23391-23469/com.intellinects.app W/System.err:     at java.util.concurrent.FutureTask.run(FutureTask.java:237)
   03-27 16:15:04.496 23391-23469/com.intellinects.app W/System.err:     at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
   03-27 16:15:04.496 23391-23469/com.intellinects.app W/System.err:     at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
   03-27 16:15:04.497 23391-23469/com.intellinects.app W/System.err:     at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
   03-27 16:15:04.497 23391-23469/com.intellinects.app W/System.err:     at java.lang.Thread.run(Thread.java:818)
</code>```

答: The server you are trying to connect is not authorized. You will have to do SSL pinning, download the SSL Certificate signed by any CA. </p>

Body:
I'm facing this error javax.net.ssl.SSLPeerUnverifiedException: No peer certificate on android version lower than Marshmallow when I use https to connect the server and I'm getting this exception:

   03-27 16:15:04.481 23391-23469/com.intellinects.app W/System.err: javax.net.ssl.SSLPeerUnverifiedException: No peer certificate
   03-27 16:15:04.495 23391-23469/com.intellinects.app W/System.err:     at com.android.org.conscrypt.SSLNullSession.getPeerCertificates(SSLNullSession.java:104)
   03-27 16:15:04.495 23391-23469/com.intellinects.app W/System.err:     at org.apache.http.conn.ssl.AbstractVerifier.verify(AbstractVerifier.java:93)
   03-27 16:15:04.495 23391-23469/com.intellinects.app W/System.err:     at org.apache.http.conn.ssl.SSLSocketFactory.createSocket(SSLSocketFactory.java:388)
   03-27 16:15:04.495 23391-23469/com.intellinects.app W/System.err:     at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:165)
   03-27 16:15:04.495 23391-23469/com.intellinects.app W/System.err:     at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164)
   03-27 16:15:04.495 23391-23469/com.intellinects.app W/System.err:     at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119)
   03-27 16:15:04.495 23391-23469/com.intellinects.app W/System.err:     at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:360)
   03-27 16:15:04.495 23391-23469/com.intellinects.app W/System.err:     at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555)
   03-27 16:15:04.496 23391-23469/com.intellinects.app W/System.err:     at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
   03-27 16:15:04.496 23391-23469/com.intellinects.app W/System.err:     at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465)
   03-27 16:15:04.496 23391-23469/com.intellinects.app W/System.err:     at com.intellinects.app.Network.executeService(Network.java:77)
   03-27 16:15:04.496 23391-23469/com.intellinects.app W/System.err:     at com.intellinects.app.Network.checkSecureConnection(Network.java:180)
   03-27 16:15:04.496 23391-23469/com.intellinects.app W/System.err:     at com.intellinects.app.Network.get(Network.java:124)
   03-27 16:15:04.496 23391-23469/com.intellinects.app W/System.err:     at com.intellinects.app.SplashActivity$CheckURL.doInBackground(SplashActivity.java:144)
   03-27 16:15:04.496 23391-23469/com.intellinects.app W/System.err:     at com.intellinects.app.SplashActivity$CheckURL.doInBackground(SplashActivity.java:127)
   03-27 16:15:04.496 23391-23469/com.intellinects.app W/System.err:     at android.os.AsyncTask$2.call(AsyncTask.java:288)
   03-27 16:15:04.496 23391-23469/com.intellinects.app W/System.err:     at java.util.concurrent.FutureTask.run(FutureTask.java:237)
   03-27 16:15:04.496 23391-23469/com.intellinects.app W/System.err:     at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
   03-27 16:15:04.496 23391-23469/com.intellinects.app W/System.err:     at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
   03-27 16:15:04.497 23391-23469/com.intellinects.app W/System.err:     at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
   03-27 16:15:04.497 23391-23469/com.intellinects.app W/System.err:     at java.lang.Thread.run(Thread.java:818)


问:
How can I make all the Text children of a View element have the same style?
I want to have something similar to CSS, where you can give the 'color' style to a div and any text within it will have it.

I have multiple Text components within a View component and I would like them to all have the same text color.

If I pass a 'color' style to the view it would throw a warning.

I would like to avoid having to pass the same style to all these children when their parent can have the style for all of them.

I would like to go from this:

```<code><View>
  <Text style={styles.Warning}>
  </Text>
  <Text style={styles.Warning}>
  </Text>
  <Text style={styles.Warning}>
  </Text>
  <Text style={styles.Warning}>
  </Text>
  <Text style={styles.Warning}>
  </Text>
</View>
</code>```

to this:

```<code><View style={styles.Warning}>
  <Text>
  </Text>
  <Text>
  </Text>
  <Text>
  </Text>
  <Text>
  </Text>
  <Text>
  </Text>
</View>
</code>```

With the styles being:

```<code>const styles = StyleSheet.create({
  Warning:{
    color:'#a94442'
  }
});
</code>```

(It would be better if I don't have to install anything)
Thank you.

答:
Yes, you can definitely do the same you want. The only part you are missing is having the Text container inside he View container.

Example:

```<code><View>
 <Text style={{color:'red'}}>
   <Text>
     text1 // will inherit red color
   </Text>
   <Text>
     text2 // will inherit red color
   </Text>
 </Text>
</View>
</code>```

For further information you can also check out the link
https://facebook.github.io/react-native/docs/text.html#containers

Body:
I want to have something similar to CSS, where you can give the 'color' style to a div and any text within it will have it.

I have multiple Text components within a View component and I would like them to all have the same text color.

If I pass a 'color' style to the view it would throw a warning.

I would like to avoid having to pass the same style to all these children when their parent can have the style for all of them.

I would like to go from this:

<View>
  <Text style={styles.Warning}>
  </Text>
  <Text style={styles.Warning}>
  </Text>
  <Text style={styles.Warning}>
  </Text>
  <Text style={styles.Warning}>
  </Text>
  <Text style={styles.Warning}>
  </Text>
</View>

to this:

<View style={styles.Warning}>
  <Text>
  </Text>
  <Text>
  </Text>
  <Text>
  </Text>
  <Text>
  </Text>
  <Text>
  </Text>
</View>

With the styles being:

const styles = StyleSheet.create({
  Warning:{
    color:'#a94442'
  }
});

(It would be better if I don't have to install anything)
Thank you.

Body:
Yes, you can definitely do the same you want. The only part you are missing is having the Text container inside he View container.

Example:

<View>
 <Text style={{color:'red'}}>
   <Text>
     text1 // will inherit red color
   </Text>
   <Text>
     text2 // will inherit red color
   </Text>
 </Text>
</View>

For further information you can also check out the link
https://facebook.github.io/react-native/docs/text.html#containers


问:
Spark Accumulator confusion
I'm writing a Spark job that takes in data from multiple sources, filters bad input rows, and outputs a slightly modified version of the input.  The job has two additional requirements:

I must keep track of the number of bad inputs rows per source to notify those upstream providers.

I must support an output limit per source.

The job seemed straightforward and I approached the problem using accumulators to keep track of the number of filtered rows per source.  However, when I implemented the final .limit(N), my accumulator behavior changed.  Here's some striped down sample code that triggers the behavior on a single source:

```<code>from pyspark.sql import Row, SparkSession
from pyspark.sql.types import *
from random import randint

def filter_and_transform_parts(rows, filter_int, accum):
    for r in rows:
        if r[0] == filter_int:
            accum.add(1)
            continue

        yield r[0], r[1] + 1, r[2] + 1

def main():
    spark= SparkSession \
           .builder \
           .appName("Test") \
           .getOrCreate()

    sc = spark.sparkContext
    accum = sc.accumulator(0)

    # 20 inputs w/ tuple having 4 as first element
    inputs = [(4, randint(1, 10), randint(1, 10)) if x % 5 == 0 else (randint(6, 10), randint(6, 10), randint(6, 10)) for x in xrange(100)]

    rdd = sc.parallelize(inputs)
    # filter out tuples where 4 is first element
    rdd = rdd.mapPartitions(lambda r: filter_and_transform_parts(r, 4, accum))

    # if not limit, accumulator value is 20
    # if limit and limit_count <= 63, accumulator value is 0
    # if limit and limit_count >= 64, accumulator value is 20
    limit = True
    limit_count = 63

    if limit:
        rdd = rdd.map(lambda r: Row(r[0], r[1], r[2]))
        df_schema = StructType([StructField("val1", IntegerType(), False),
                                StructField("val2", IntegerType(), False),
                                StructField("val3", IntegerType(), False)])
        df = spark.createDataFrame(rdd, schema=df_schema)
        df = df.limit(limit_count)
        df.write.mode("overwrite").csv('foo/')
    else:
        rdd.saveAsTextFile('foo/')

    print "Accum value: {}".format(accum.value)

if __name__ == "__main__":
    main()
</code>```

The problem is that my accumulator sometimes reports the number of filtered rows and sometimes doesn't, depending on the limit specified and number of inputs for a source.  However, in all situations the filtered rows don't make it into the output meaning the filter occurred and the accumulator should have a value.

If you can shed some light on this that'd be very helpful, thanks!

Update:

Adding a rdd.persist() call after mapPartitions made the accumulator behavior consistent.

答:
Actually, it doesnt't matter what the limit_count's value is.

The reason why sometime Accum value is 0 is because you performe accumulator       in transformations(e.g.: rdd.map,rdd.mapPartitions).

Spark only guaranty that accumulator works as well inside actions(e.g.: rdd.foreach)

Lets make a little bit of change on your code:

```<code>from pyspark.sql import *
from random import randint

def filter_and_transform_parts(rows, filter_int, accum):
    for r in rows:
        if r[0] == filter_int:
            accum.add(1)

def main():
    spark = SparkSession.builder.appName("Test").getOrCreate()

    sc = spark.sparkContext
    print(sc.applicationId)
    accum = sc.accumulator(0)

    inputs = [(4, x * 10, x * 100) if x % 5 == 0 else (randint(6, 10), x * 10, x * 100) for x in xrange(100)]
    rdd = sc.parallelize(inputs)
    rdd.foreachPartition(lambda r: filter_and_transform_parts(r, 4, accum))

    limit = True
    limit_count = 10 or 'whatever'

    if limit:
        rdd = rdd.map(lambda r: Row(val1=r[0], val2=r[1], val3=r[2]))
        df = spark.createDataFrame(rdd)
        df = df.limit(limit_count)
        df.write.mode("overwrite").csv('file:///tmp/output')
    else:
        rdd.saveAsTextFile('file:///tmp/output')

    print "Accum value: {}".format(accum.value)

if __name__ == "__main__":
    main()
</code>```

Accum value is equle to 20 all the time

For more information:

http://spark.apache.org/docs/2.0.2/programming-guide.html#accumulators

Title: Spark Accumulator confusion

Body:
I'm writing a Spark job that takes in data from multiple sources, filters bad input rows, and outputs a slightly modified version of the input.  The job has two additional requirements:

I must keep track of the number of bad inputs rows per source to notify those upstream providers.

I must support an output limit per source.

The job seemed straightforward and I approached the problem using accumulators to keep track of the number of filtered rows per source.  However, when I implemented the final .limit(N), my accumulator behavior changed.  Here's some striped down sample code that triggers the behavior on a single source:

from pyspark.sql import Row, SparkSession
from pyspark.sql.types import *
from random import randint

def filter_and_transform_parts(rows, filter_int, accum):
    for r in rows:
        if r[0] == filter_int:
            accum.add(1)
            continue

        yield r[0], r[1] + 1, r[2] + 1

def main():
    spark= SparkSession \
           .builder \
           .appName("Test") \
           .getOrCreate()

    sc = spark.sparkContext
    accum = sc.accumulator(0)

    # 20 inputs w/ tuple having 4 as first element
    inputs = [(4, randint(1, 10), randint(1, 10)) if x % 5 == 0 else (randint(6, 10), randint(6, 10), randint(6, 10)) for x in xrange(100)]

    rdd = sc.parallelize(inputs)
    # filter out tuples where 4 is first element
    rdd = rdd.mapPartitions(lambda r: filter_and_transform_parts(r, 4, accum))

    # if not limit, accumulator value is 20
    # if limit and limit_count <= 63, accumulator value is 0
    # if limit and limit_count >= 64, accumulator value is 20
    limit = True
    limit_count = 63

    if limit:
        rdd = rdd.map(lambda r: Row(r[0], r[1], r[2]))
        df_schema = StructType([StructField("val1", IntegerType(), False),
                                StructField("val2", IntegerType(), False),
                                StructField("val3", IntegerType(), False)])
        df = spark.createDataFrame(rdd, schema=df_schema)
        df = df.limit(limit_count)
        df.write.mode("overwrite").csv('foo/')
    else:
        rdd.saveAsTextFile('foo/')

    print "Accum value: {}".format(accum.value)

if __name__ == "__main__":
    main()

The problem is that my accumulator sometimes reports the number of filtered rows and sometimes doesn't, depending on the limit specified and number of inputs for a source.  However, in all situations the filtered rows don't make it into the output meaning the filter occurred and the accumulator should have a value.

If you can shed some light on this that'd be very helpful, thanks!

Update:

Adding a rdd.persist() call after mapPartitions made the accumulator behavior consistent.

Body:
Actually, it doesnt't matter what the limit_count's value is.

The reason why sometime Accum value is 0 is because you performe accumulator       in transformations(e.g.: rdd.map,rdd.mapPartitions).

Spark only guaranty that accumulator works as well inside actions(e.g.: rdd.foreach)

Lets make a little bit of change on your code:

from pyspark.sql import *
from random import randint

def filter_and_transform_parts(rows, filter_int, accum):
    for r in rows:
        if r[0] == filter_int:
            accum.add(1)

def main():
    spark = SparkSession.builder.appName("Test").getOrCreate()

    sc = spark.sparkContext
    print(sc.applicationId)
    accum = sc.accumulator(0)

    inputs = [(4, x * 10, x * 100) if x % 5 == 0 else (randint(6, 10), x * 10, x * 100) for x in xrange(100)]
    rdd = sc.parallelize(inputs)
    rdd.foreachPartition(lambda r: filter_and_transform_parts(r, 4, accum))

    limit = True
    limit_count = 10 or 'whatever'

    if limit:
        rdd = rdd.map(lambda r: Row(val1=r[0], val2=r[1], val3=r[2]))
        df = spark.createDataFrame(rdd)
        df = df.limit(limit_count)
        df.write.mode("overwrite").csv('file:///tmp/output')
    else:
        rdd.saveAsTextFile('file:///tmp/output')

    print "Accum value: {}".format(accum.value)

if __name__ == "__main__":
    main()

Accum value is equle to 20 all the time

For more information:

http://spark.apache.org/docs/2.0.2/programming-guide.html#accumulators


问:
Dynamically Generated Text box and live Search
I tried to add text box dynamically using JQuery and make live search for each text box.. it is working, but i want to add text box in table and each table row contain five column. each column contain one text box except first column. First column contain check box. Specially text boxes should be different Ids.... I tried with below code.. but not working properly....</p>

```<code>$(document).ready(function () {
            x=0;
            $('#btn-addrow').on('click', function () {
                $('#tbl-data').append('<tr><td><input type="checkbox"></td><td><div class="search-box"><input type="text" id='txt'+x+''><div class="res"></div></div></td><td><input type="text"></td><td><input type="text"></td></tr>');
               x++;
$('.search-box input[type="text"]').on("keyup input", function () {
                    /* Get input value on change */
                    var term = $(this).val();
                    var resultDropdown = $(this).siblings(".res");
                    if (term.length) {
                        $.get("../svr/aj-live-search.php", {query: term}).done(function (data) {
                            // Display the returned data in browser
                            resultDropdown.html(data);
                        });
                    } else {
                        resultDropdown.empty();
                    }
                });

                // Set search input value on click of result item
                $(document).on("click", ".res p", function () {
                    $(this).parents(".search-box").find('input[type="text"]').val($(this).text());
                    $(this).parent(".res").empty();
                });
            })
        })
</code>```

答:
Well firstly there is Some syntax error in append section, than How can you use live search with keyup event in button with click event, So i simplified your code please try this , hope it works

```<code>$(document).ready(function () {
x=0;
$('#btn-addrow').on('click', function () {
    // alert('Do what ever');
    $('#tbl-data').append('<tr><td><input type="checkbox"></td><td><div class="search-box"><input type="text" id="txt'+x+'"><div class="res"></div></div></td><td><input type="text"></td><td><input type="text"></td></tr>');
    x++;

})
   // Set search input value on click of result item
   $('.search-box input[type="text"]').on("keyup input", function () {
    /* Get input value on change */
    var term = $(this).val();
    var resultDropdown = $(this).siblings(".res");
    if (term.length) {
        $.get("../svr/aj-live-search.php", {query: term}).done(function (data) {
                        // Display the returned data in browser
                        resultDropdown.html(data);
                    });
    } else {
        resultDropdown.empty();
    }
   });

   $(document).on("click", ".res p", function () {
    $(this).parents(".search-box").find('input[type="text"]').val($(this).text());
    $(this).parent(".res").empty();
   });
</code>```

});

Body:
I tried to add text box dynamically using JQuery and make live search for each text box.. it is working, but i want to add text box in table and each table row contain five column. each column contain one text box except first column. First column contain check box. Specially text boxes should be different Ids.... I tried with below code.. but not working properly....

$(document).ready(function () {
            x=0;
            $('#btn-addrow').on('click', function () {
                $('#tbl-data').append('
<input type="checkbox">
<input type="text" id='txt'+x+''>

	<input type="text">	<input type="text">
');
               x++;
$('.search-box input[type="text"]').on("keyup input", function () {
                    /* Get input value on change */
                    var term = $(this).val();
                    var resultDropdown = $(this).siblings(".res");
                    if (term.length) {
                        $.get("../svr/aj-live-search.php", {query: term}).done(function (data) {
                            // Display the returned data in browser
                            resultDropdown.html(data);
                        });
                    } else {
                        resultDropdown.empty();
                    }
                });

                // Set search input value on click of result item
                $(document).on("click", ".res p", function () {
                    $(this).parents(".search-box").find('input[type="text"]').val($(this).text());
                    $(this).parent(".res").empty();
                });
            })
        })

Body:
Well firstly there is Some syntax error in append section, than How can you use live search with keyup event in button with click event, So i simplified your code please try this , hope it works

$(document).ready(function () {
x=0;
$('#btn-addrow').on('click', function () {
    // alert('Do what ever');
    $('#tbl-data').append('<tr><td><input type="checkbox"></td><td><div class="search-box"><input type="text" id="txt'+x+'"><div class="res"></div></div></td><td><input type="text"></td><td><input type="text"></td></tr>');
    x++;

})
   // Set search input value on click of result item
   $('.search-box input[type="text"]').on("keyup input", function () {
    /* Get input value on change */
    var term = $(this).val();
    var resultDropdown = $(this).siblings(".res");
    if (term.length) {
        $.get("../svr/aj-live-search.php", {query: term}).done(function (data) {
                        // Display the returned data in browser
                        resultDropdown.html(data);
                    });
    } else {
        resultDropdown.empty();
    }
   });

   $(document).on("click", ".res p", function () {
    $(this).parents(".search-box").find('input[type="text"]').val($(this).text());
    $(this).parent(".res").empty();
   });

});


问:
Draw outline with core-graphics
can anybody tell me how to draw an outline
on a UIButton with core-graphics?

I want the outline to look like on the link below

http://dl.dropbox.com/u/412741/test/Bildschirmfoto%202012-03-21%20um%2010.59.44.png

edit:

the image is from a wwdc 2011 Session Video
practical drawing for IOS Developers, but there is unfortunately no demo for that kind of outline

edit2:

Is there a property for the stroke of the outline?

答:
Swift 3.0

```<code> class BorderButton: UIButton {
        override func draw(_ rect: CGRect) {
            super.draw(rect)
            let context = UIGraphicsGetCurrentContext()
            context?.setStrokeColor(UIColor.red.cgColor)
            context?.setLineWidth(5.0)
            context?.stroke(bounds)
        }
    }
</code>```

Title: Draw outline with core-graphics

Body:
Swift 3.0

 class BorderButton: UIButton {
        override func draw(_ rect: CGRect) {
            super.draw(rect)
            let context = UIGraphicsGetCurrentContext()
            context?.setStrokeColor(UIColor.red.cgColor)
            context?.setLineWidth(5.0)
            context?.stroke(bounds)
        }
    }


问:
Segmentation violation detected - matlab
I get the error Segmentation violation detected in Matlab 7.12.0.635 (R2011a) (on Ubuntu 12.10) whenever I try to save a figure as jpg or png. I can save a figure as .fig, though...

What can I do to fix this problem? Have you encountered this problem?

答:
I resolved this issue by installing matlab-support package,</p>

```<code> sudo apt-get install matlab-support
</code>```

Body:
I resolved this issue by installing matlab-support package,

 sudo apt-get install matlab-support


问:
ios constraing a set of buttons to navigation item inside a uiview
I create two buttons inside a UIView and by selecting each button I intend to display a subview. I created the views in auto layout. But I cannot set constraints from the UIView containing the buttons to the navigation item. So when I run it in simulator I don't see neither buttons nor the UIview but the color of the navigation item changes to that of the button's UIView Tint (in this case blue) looks like my buttons and the UIview are hidden somewhere.

Display looks like this:

答: Give top constraint to your uiview with Top Layout Guide, make sure it is not with its superview. Then this will surely work.


问:
XSLT split single xml into multiple xmls preserving parent elements
I am trying to split a huge xml(around 300MB) into smaller files based on a repeated child element.

Example below to illustrate the scenario

input.xml

```<code><?xml version="1.0" encoding="UTF-8"?>
<a>
   <b></b>
   <bb></bb>
   <bbb>
        <c>
            <d id="1">
                <x></x>
                <y></y>
            </d>
            <d id="2">
                <x></x>
                <y></y>
            </d>
            <d id="3">
                <x></x>
                <y></y>
            </d>
        </c>
    </bbb>
    <e></e>
    <f></f>
</a>
</code>```

As mentioned above this has a repeated child element . Based on this element, separate output files are expected by keeping its parent elements and attributes intact.

Expected output out_1_a.xml

```<code><?xml version="1.0" encoding="UTF-8"?>
<a>
   <b></b>
   <bb></bb>
   <bbb>
        <c>
            <d id="1">
                <x></x>
                <y></y>
            </d>
        </c>
    </bbb>
    <e></e>
    <f></f>
</a>
</code>```

Expected output out_2_a.xml

```<code><?xml version="1.0" encoding="UTF-8"?>
<a>
   <b></b>
   <bb></bb>
   <bbb>
        <c>
            <d id="2">
                <x></x>
                <y></y>
            </d>
        </c>
    </bbb>
    <e></e>
    <f></f>
</a>
</code>```

Expected output out_3_a.xml

```<code><?xml version="1.0" encoding="UTF-8"?>
<a>
   <b></b>
   <bb></bb>
   <bbb>
        <c>
            <d id="3">
                <x></x>
                <y></y>
            </d>
        </c>
    </bbb>
    <e></e>
    <f></f>
</a>
</code>```

My xsl - sample.xsl

```<code><?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
version="2.0">

<xsl:output indent="yes"/>

<xsl:template match="/">
    <xsl:for-each select="a/bbb/c/d">
    <xsl:variable name="i" select="position()" />
    <xsl:result-document method="xml" href="out_{$i}_a.xml">
    <a>
        <b></b>
        <bb></bb>
        <bbb>
            <c>
                <xsl:copy-of select="../@* | ." />
            </c>
        </bbb>
        <e></e>
        <f></f>
    </a>
    </xsl:result-document>
    </xsl:for-each>
</xsl:template>
</xsl:stylesheet>
</code>```

This works ok and I get the output that I desire.
However, I am sure there is a better way to achieve this than hardcoding those parent elements like a, b, bb etc. Also in some cases these parent elements contains attributes and they are dynamic. So hardcoding is something I want to avoid. Any better way to solve this?

答:
The below XSLT-2.0 solution should do this job easily:

```<code><xsl:stylesheet
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    xmlns:xs="http://www.w3.org/2001/XMLSchema"
    version="2.0">
    <xsl:output method="xml" indent="yes" omit-xml-declaration="yes"/>

    <xsl:template match="@* | node()" mode="createDoc">
        <xsl:param name="id"/>
        <xsl:copy>
            <!-- apply-templates to the attributes and, the desired 'd' child element or all children elements -->
            <xsl:apply-templates select="@*, if(node()[generate-id() = $id]) then node()[generate-id() = $id] else node()" mode="createDoc">
                <xsl:with-param name="id" select="$id"/>
            </xsl:apply-templates>
        </xsl:copy>
    </xsl:template>

    <!-- template to create documents per `d` element -->
    <xsl:template match="/">
        <xsl:for-each select="a/bbb/c/d">
            <xsl:result-document href="out_{@id}_a.xml">
                <xsl:apply-templates select="root(.)" mode="createDoc">
                    <!-- pass the id of the desired element to be copied omitting its siblings-->
                    <xsl:with-param name="id" select="generate-id()"/>
                </xsl:apply-templates>
            </xsl:result-document>
        </xsl:for-each>
    </xsl:template>

</xsl:stylesheet>
</code>```

The second template creates a document per d element by passing the generate-id() of the matched element to the recursive template(the first template).

The first template, recursively copies all elements. Also, it uses an xsl:if to copy only the desired d element by its generate-id() and omitting other siblings.

Body:
I am trying to split a huge xml(around 300MB) into smaller files based on a repeated child element.

Example below to illustrate the scenario

input.xml

<?xml version="1.0" encoding="UTF-8"?>

   <bb></bb>
   <bbb>
        <c>
            <d id="1">
                <x></x>
                <y></y>
            </d>
            <d id="2">
                <x></x>
                <y></y>
            </d>
            <d id="3">
                <x></x>
                <y></y>
            </d>
        </c>
    </bbb>
    <e></e>
    <f></f>

As mentioned above this has a repeated child element . Based on this element, separate output files are expected by keeping its parent elements and attributes intact.

Expected output out_1_a.xml

<?xml version="1.0" encoding="UTF-8"?>

   <bb></bb>
   <bbb>
        <c>
            <d id="1">
                <x></x>
                <y></y>
            </d>
        </c>
    </bbb>
    <e></e>
    <f></f>

Expected output out_2_a.xml

<?xml version="1.0" encoding="UTF-8"?>

   <bb></bb>
   <bbb>
        <c>
            <d id="2">
                <x></x>
                <y></y>
            </d>
        </c>
    </bbb>
    <e></e>
    <f></f>

Expected output out_3_a.xml

<?xml version="1.0" encoding="UTF-8"?>

   <bb></bb>
   <bbb>
        <c>
            <d id="3">
                <x></x>
                <y></y>
            </d>
        </c>
    </bbb>
    <e></e>
    <f></f>

My xsl - sample.xsl

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
version="2.0">

<xsl:output indent="yes"/>

<xsl:template match="/">
    <xsl:for-each select="a/bbb/c/d">
    <xsl:variable name="i" select="position()" />
    <xsl:result-document method="xml" href="out_{$i}_a.xml">

        <bb></bb>
        <bbb>
            <c>
                <xsl:copy-of select="../@* | ." />
            </c>
        </bbb>
        <e></e>
        <f></f>

    </xsl:result-document>
    </xsl:for-each>
</xsl:template>
</xsl:stylesheet>

This works ok and I get the output that I desire.
However, I am sure there is a better way to achieve this than hardcoding those parent elements like a, b, bb etc. Also in some cases these parent elements contains attributes and they are dynamic. So hardcoding is something I want to avoid. Any better way to solve this?

Body:
The below XSLT-2.0 solution should do this job easily:

<xsl:stylesheet
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    xmlns:xs="http://www.w3.org/2001/XMLSchema"
    version="2.0">
    <xsl:output method="xml" indent="yes" omit-xml-declaration="yes"/>

    <xsl:template match="@* | node()" mode="createDoc">
        <xsl:param name="id"/>
        <xsl:copy>
            <!-- apply-templates to the attributes and, the desired 'd' child element or all children elements -->
            <xsl:apply-templates select="@*, if(node()[generate-id() = $id]) then node()[generate-id() = $id] else node()" mode="createDoc">
                <xsl:with-param name="id" select="$id"/>
            </xsl:apply-templates>
        </xsl:copy>
    </xsl:template>

    <!-- template to create documents per `d` element -->
    <xsl:template match="/">
        <xsl:for-each select="a/bbb/c/d">
            <xsl:result-document href="out_{@id}_a.xml">
                <xsl:apply-templates select="root(.)" mode="createDoc">
                    <!-- pass the id of the desired element to be copied omitting its siblings-->
                    <xsl:with-param name="id" select="generate-id()"/>
                </xsl:apply-templates>
            </xsl:result-document>
        </xsl:for-each>
    </xsl:template>

</xsl:stylesheet>

The second template creates a document per d element by passing the generate-id() of the matched element to the recursive template(the first template).

The first template, recursively copies all elements. Also, it uses an xsl:if to copy only the desired d element by its generate-id() and omitting other siblings.


问:
Prevent response body download in python async http requests
I want to "ping" a server, check the header response to see if the link is broken, and if it's not broken, actually download the response body.

Traditionally, using a sync method with the requests module, you could send a get request with the stream = True parameter, and capture the headers before the response body download, deciding, in case of error (not found, for example), to abort the connection.

My problem is, doing this with the async libraries grequests or requests-futures has become impossible for my reduced knowdlege base.

I've tried setting the stream parameter to true in request-futures but to no use, it still downloads the response body without letting me intervene as soon as it gets the response headers. And even if it did, I wouldn't be sure of how to proceed.

This is what I've tried:

test.py

```<code>from requests_futures.sessions import FuturesSession

session = FuturesSession()
session.stream = True

future = session.get('http://www.google.com')
response = future.result()
print(response.status_code) # Here I would assume the response body hasn't been loaded
</code>```

Upon debugging I find it downloads the response body either way.

I would appreciate any solution to the initial problem, whether it follows my logic or not.

答:
I believe what you want is an HTTP HEAD request:

```<code>session.head('http://www.google.com')
</code>```

Per w3.org, "the HEAD method is identical to GET except that the server MUST NOT return a message-body in the response."  If you like the status code and headers, you can follow-up with a normal GET request.

For the comments, it looks like you might also be interested in doing this in a single request.  It is possible to do so directly with sockets.  Send the normal GET request, do a recv of the first block, if you don't like the result, close the connection, otherwise loop over the remaining blocks.

Here is a proof of concept of how to download conditionally with a single request:

```<code>import socket

def fetch_on_header_condition(host, resource, condition, port=80):
    request =  'GET %s HTTP/1.1\r\n' % resource
    request += 'Host: %s\r\n' % host
    request += 'Connection: close\r\n'
    request += '\r\n'

    s = socket.socket()
    try:
        s.connect((host, port))
        s.send(request)
        first_block = s.recv(4096)
        if not condition(first_block):
            return False, ''
        blocks = [first_block]
        while True:
            block = s.recv(4096)
            if not block:
                break
            blocks.append(block)
        return True, ''.join(blocks)
    finally:
        s.close()

if __name__ == '__main__':
    print fetch_on_header_condition(
        host = 'www.jython.org',
        port = 80,
        resource = '/',
        condition = lambda s: 'Content-Type: text/xml' in s,
    )
</code>```

Body:
I want to "ping" a server, check the header response to see if the link is broken, and if it's not broken, actually download the response body.

Traditionally, using a sync method with the requests module, you could send a get request with the stream = True parameter, and capture the headers before the response body download, deciding, in case of error (not found, for example), to abort the connection.

My problem is, doing this with the async libraries grequests or requests-futures has become impossible for my reduced knowdlege base.

I've tried setting the stream parameter to true in request-futures but to no use, it still downloads the response body without letting me intervene as soon as it gets the response headers. And even if it did, I wouldn't be sure of how to proceed.

This is what I've tried:

test.py

from requests_futures.sessions import FuturesSession

session = FuturesSession()
session.stream = True

future = session.get('http://www.google.com')
response = future.result()
print(response.status_code) # Here I would assume the response body hasn't been loaded

Upon debugging I find it downloads the response body either way.

I would appreciate any solution to the initial problem, whether it follows my logic or not.

Body:
I believe what you want is an HTTP HEAD request:

session.head('http://www.google.com')

Per w3.org, "the HEAD method is identical to GET except that the server MUST NOT return a message-body in the response."  If you like the status code and headers, you can follow-up with a normal GET request.

For the comments, it looks like you might also be interested in doing this in a single request.  It is possible to do so directly with sockets.  Send the normal GET request, do a recv of the first block, if you don't like the result, close the connection, otherwise loop over the remaining blocks.

Here is a proof of concept of how to download conditionally with a single request:

import socket

def fetch_on_header_condition(host, resource, condition, port=80):
    request =  'GET %s HTTP/1.1\r\n' % resource
    request += 'Host: %s\r\n' % host
    request += 'Connection: close\r\n'
    request += '\r\n'

    s = socket.socket()
    try:
        s.connect((host, port))
        s.send(request)
        first_block = s.recv(4096)
        if not condition(first_block):
            return False, ''
        blocks = [first_block]
        while True:
            block = s.recv(4096)
            if not block:
                break
            blocks.append(block)
        return True, ''.join(blocks)
    finally:
        s.close()

if __name__ == '__main__':
    print fetch_on_header_condition(
        host = 'www.jython.org',
        port = 80,
        resource = '/',
        condition = lambda s: 'Content-Type: text/xml' in s,
    )


问:
Testing method inside method Python
Can I test a method inside a method in Python?

search.py

```<code>   def SearchWeb(query=None):
        """Search via API"""
        search = cool_api.api_request(query)
        def _HandleResponse(search):
            if search:
              return search['result']
        return _HandleResponse(search)
</code>```

I want to create a test method for _HandleResponse using unittest

search_test.py

```<code>import unittest

class MyTest(unittest.TestCase):
    def test(self):
        response = {}
        response['result'] = 'yes'
        self.assertEqual(search._HandleResponse(response), 'yes')
</code>```

But _HandleResponse is not accessible. I get:

```<code>AttributeError: 'module' object has no attribute '_HandleResponse'
</code>```

I can move _HandleResponse outside SearchWeb method and that works, but wondering if this is possible?

答:
As far as I understand it's not possible.

The nested method is actually created every time the function is called. This means you have no static reference to it and you can't write a test to a function that doesn't exist. You have to test it through the SearchWeb function.

Side note: Technically there are probably (complex) things you can do but none that I can think of are worth mentioning.

Title: Testing method inside method Python

Body:
Can I test a method inside a method in Python?

search.py

   def SearchWeb(query=None):
        """Search via API"""
        search = cool_api.api_request(query)
        def _HandleResponse(search):
            if search:
              return search['result']
        return _HandleResponse(search)

I want to create a test method for _HandleResponse using unittest

search_test.py

import unittest

class MyTest(unittest.TestCase):
    def test(self):
        response = {}
        response['result'] = 'yes'
        self.assertEqual(search._HandleResponse(response), 'yes')

But _HandleResponse is not accessible. I get:

AttributeError: 'module' object has no attribute '_HandleResponse'

I can move _HandleResponse outside SearchWeb method and that works, but wondering if this is possible?


问:
Difference between stock_move and stock_picking on Odoo(Openerp)?
can anyone please tell me what's the difference between stock_move & stock_picking? If stock_move trace all movements of products from a location to another why using stock_picking?</p>

答: Stock_picking is simply a collection of stock_move. Normally, when a stock_picking is created, it includes many items in it and each line in the picking is a stock move. A stock_picking is done only when all stock_moves in that picking are done. Same concept as sale_order and sale_order_line</p>


问:
How to zoom whole RecyclerView in android
I've created a zoom function which is working zooming for LinearLayout and FrameLayout but not working for RecyclerView.

XML file :

```<code><com.nm.esign.entities.ZoomLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/zoom_main1"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    >

    <LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/fl_zoom"
    android:orientation="vertical"

    android:layout_width="match_parent"
    android:layout_height="match_parent">

      <android.support.v7.widget.RecyclerView
            android:id="@+id/recycler_view_template_img"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_margin="30dp"

            android:scrollbars="vertical" />

    </LinearLayout>

     </com.nm.esign.entities.ZoomLayout>
</code>```

Main activity:

```<code>  protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_view_template);

        //  prevBtn=(android.support.v7.widget.AppCompatButton)findViewById(R.id.btnDocumentPrev_temp);
        // nextBtn=(android.support.v7.widget.AppCompatButton)findViewById(R.id.btnDocumentNxt_temp);
    RecyclerView    recyclerView = (RecyclerView) findViewById(R.id.recycler_view_template_img);

    LinearLayout    fl_zoom=(LinearLayout)findViewById(R.id.fl_zoom)

        ZoomLayout myZoomView = new ZoomLayout(ViewTemplate.this);

      fl_zoom.addView(myZoomView); // working fine
// recyclerView.addView(myZoomView); // not working

....................................

}
</code>```

ZoomLayout class:

```<code>/**
 * Created by Lenovo5 on 3/16/2017.
 */

import android.content.Context;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.view.ScaleGestureDetector;
import android.view.View;
import android.widget.FrameLayout;

/**
 * Layout that provides pinch-zooming of content. This view should have exactly one child
 * view containing the content.
 */
public class ZoomLayout extends FrameLayout implements ScaleGestureDetector.OnScaleGestureListener {

    private enum Mode {
        NONE,
        DRAG,
        ZOOM
    }

    private static final String TAG = "ZoomLayout";
    private static final float MIN_ZOOM = 1.0f;
    private static final float MAX_ZOOM = 4.0f;

    private Mode mode = Mode.NONE;
    private float scale = 1.0f;
    private float lastScaleFactor = 0f;

    // Where the finger first  touches the screen
    private float startX = 0f;
    private float startY = 0f;

    // How much to translate the canvas
    private float dx = 0f;
    private float dy = 0f;
    private float prevDx = 0f;
    private float prevDy = 0f;

    public ZoomLayout(Context context) {
        super(context);
        init(context);
    }

    public ZoomLayout(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(context);
    }

    public ZoomLayout(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        init(context);
    }

    private void init(Context context) {
        final ScaleGestureDetector scaleDetector = new ScaleGestureDetector(context, this);
        this.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View view, MotionEvent motionEvent) {
                switch (motionEvent.getAction() & MotionEvent.ACTION_MASK) {
                    case MotionEvent.ACTION_DOWN:
                        Log.i(TAG, "DOWN");
                        if (scale > MIN_ZOOM) {
                            mode = Mode.DRAG;
                            startX = motionEvent.getX() - prevDx;
                            startY = motionEvent.getY() - prevDy;
                        }
                        break;
                    case MotionEvent.ACTION_MOVE:
                        if (mode == Mode.DRAG) {
                            dx = motionEvent.getX() - startX;
                            dy = motionEvent.getY() - startY;
                        }
                        break;
                    case MotionEvent.ACTION_POINTER_DOWN:
                        mode = Mode.ZOOM;
                        break;
                    case MotionEvent.ACTION_POINTER_UP:
                        mode = Mode.DRAG;
                        break;
                    case MotionEvent.ACTION_UP:
                        Log.i(TAG, "UP");
                        mode = Mode.NONE;
                        prevDx = dx;
                        prevDy = dy;
                        break;
                }
                scaleDetector.onTouchEvent(motionEvent);

                if ((mode == Mode.DRAG && scale >= MIN_ZOOM) || mode == Mode.ZOOM) {
                    getParent().requestDisallowInterceptTouchEvent(true);
                    float maxDx = (child().getWidth() - (child().getWidth() / scale)) / 2 * scale;
                    float maxDy = (child().getHeight() - (child().getHeight() / scale))/ 2 * scale;
                    dx = Math.min(Math.max(dx, -maxDx), maxDx);
                    dy = Math.min(Math.max(dy, -maxDy), maxDy);
                    Log.i(TAG, "Width: " + child().getWidth() + ", scale " + scale + ", dx " + dx
                            + ", max " + maxDx);
                    applyScaleAndTranslation();
                }

                return true;
            }
        });
    }

    // ScaleGestureDetector

    @Override
    public boolean onScaleBegin(ScaleGestureDetector scaleDetector) {
        Log.i(TAG, "onScaleBegin");
        return true;
    }

    @Override
    public boolean onScale(ScaleGestureDetector scaleDetector) {
        float scaleFactor = scaleDetector.getScaleFactor();
        Log.i(TAG, "onScale" + scaleFactor);
        if (lastScaleFactor == 0 || (Math.signum(scaleFactor) == Math.signum(lastScaleFactor))) {
            scale *= scaleFactor;
            scale = Math.max(MIN_ZOOM, Math.min(scale, MAX_ZOOM));
            lastScaleFactor = scaleFactor;
        } else {
            lastScaleFactor = 0;
        }
        return true;
    }

    @Override
    public void onScaleEnd(ScaleGestureDetector scaleDetector) {
        Log.i(TAG, "onScaleEnd");
    }

    private void applyScaleAndTranslation() {
        child().setScaleX(scale);
        child().setScaleY(scale);
        child().setTranslationX(dx);
        child().setTranslationY(dy);
    }

    private View child() {
        return getChildAt(0);
    }
}
</code>```

Error  coming for:-

```<code>  recyclerView.addView(myZoomView);

E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.nm.esign, PID: 6028
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.nm.esign/com.nm.esign.activity.ViewTemplate}: java.lang.IllegalStateException: RecyclerView has no LayoutManager
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3319)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3415)
    at android.app.ActivityThread.access$1100(ActivityThread.java:229)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1821)
    at android.os.Handler.dispatchMessage(Handler.java:102)
    at android.os.Looper.loop(Looper.java:148)
    at android.app.ActivityThread.main(ActivityThread.java:7331)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)
 Caused by: java.lang.IllegalStateException: RecyclerView has no LayoutManager
    at android.support.v7.widget.RecyclerView.generateDefaultLayoutParams(RecyclerView.java:3869)
    at android.view.ViewGroup.addView(ViewGroup.java:4431)
    at android.view.ViewGroup.addView(ViewGroup.java:4409)
    at com.nm.esign.activity.ViewTemplate.onCreate(ViewTemplate.java:112)
    at android.app.Activity.performCreate(Activity.java:6904)
    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1136)
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3266)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3415)
    at android.app.ActivityThread.access$1100(ActivityThread.java:229)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1821)
    at android.os.Handler.dispatchMessage(Handler.java:102)
    at android.os.Looper.loop(Looper.java:148)
    at android.app.ActivityThread.main(ActivityThread.java:7331)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)
</code>```

答:
The solution was simple, you can create the layout manager manager manually.

Code snippet from https://github.com/kanytu/example-parallaxrecycler/blob/master/app/src/main/java/com/poliveira/apps/exampleparallaxrecycler/MainActivity.java#L24

Add this

```<code>LinearLayoutManager manager = new LinearLayoutManager(this);
manager.setOrientation(LinearLayoutManager.VERTICAL);
myRecycler.setLayoutManager(manager);
</code>```

Body:
I've created a zoom function which is working zooming for LinearLayout and FrameLayout but not working for RecyclerView.

XML file :

<com.nm.esign.entities.ZoomLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/zoom_main1"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    >

    <LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/fl_zoom"
    android:orientation="vertical"

    android:layout_width="match_parent"
    android:layout_height="match_parent">

      <android.support.v7.widget.RecyclerView
            android:id="@+id/recycler_view_template_img"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_margin="30dp"

            android:scrollbars="vertical" />

    </LinearLayout>

     </com.nm.esign.entities.ZoomLayout>

Main activity:

  protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_view_template);

        //  prevBtn=(android.support.v7.widget.AppCompatButton)findViewById(R.id.btnDocumentPrev_temp);
        // nextBtn=(android.support.v7.widget.AppCompatButton)findViewById(R.id.btnDocumentNxt_temp);
    RecyclerView    recyclerView = (RecyclerView) findViewById(R.id.recycler_view_template_img);

    LinearLayout    fl_zoom=(LinearLayout)findViewById(R.id.fl_zoom)

        ZoomLayout myZoomView = new ZoomLayout(ViewTemplate.this);

      fl_zoom.addView(myZoomView); // working fine
// recyclerView.addView(myZoomView); // not working

....................................

}

ZoomLayout class:

/**
 * Created by Lenovo5 on 3/16/2017.
 */

import android.content.Context;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.view.ScaleGestureDetector;
import android.view.View;
import android.widget.FrameLayout;

/**
 * Layout that provides pinch-zooming of content. This view should have exactly one child
 * view containing the content.
 */
public class ZoomLayout extends FrameLayout implements ScaleGestureDetector.OnScaleGestureListener {

    private enum Mode {
        NONE,
        DRAG,
        ZOOM
    }

    private static final String TAG = "ZoomLayout";
    private static final float MIN_ZOOM = 1.0f;
    private static final float MAX_ZOOM = 4.0f;

    private Mode mode = Mode.NONE;
    private float scale = 1.0f;
    private float lastScaleFactor = 0f;

    // Where the finger first  touches the screen
    private float startX = 0f;
    private float startY = 0f;

    // How much to translate the canvas
    private float dx = 0f;
    private float dy = 0f;
    private float prevDx = 0f;
    private float prevDy = 0f;

    public ZoomLayout(Context context) {
        super(context);
        init(context);
    }

    public ZoomLayout(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(context);
    }

    public ZoomLayout(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        init(context);
    }

    private void init(Context context) {
        final ScaleGestureDetector scaleDetector = new ScaleGestureDetector(context, this);
        this.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View view, MotionEvent motionEvent) {
                switch (motionEvent.getAction() & MotionEvent.ACTION_MASK) {
                    case MotionEvent.ACTION_DOWN:
                        Log.i(TAG, "DOWN");
                        if (scale > MIN_ZOOM) {
                            mode = Mode.DRAG;
                            startX = motionEvent.getX() - prevDx;
                            startY = motionEvent.getY() - prevDy;
                        }
                        break;
                    case MotionEvent.ACTION_MOVE:
                        if (mode == Mode.DRAG) {
                            dx = motionEvent.getX() - startX;
                            dy = motionEvent.getY() - startY;
                        }
                        break;
                    case MotionEvent.ACTION_POINTER_DOWN:
                        mode = Mode.ZOOM;
                        break;
                    case MotionEvent.ACTION_POINTER_UP:
                        mode = Mode.DRAG;
                        break;
                    case MotionEvent.ACTION_UP:
                        Log.i(TAG, "UP");
                        mode = Mode.NONE;
                        prevDx = dx;
                        prevDy = dy;
                        break;
                }
                scaleDetector.onTouchEvent(motionEvent);

                if ((mode == Mode.DRAG && scale >= MIN_ZOOM) || mode == Mode.ZOOM) {
                    getParent().requestDisallowInterceptTouchEvent(true);
                    float maxDx = (child().getWidth() - (child().getWidth() / scale)) / 2 * scale;
                    float maxDy = (child().getHeight() - (child().getHeight() / scale))/ 2 * scale;
                    dx = Math.min(Math.max(dx, -maxDx), maxDx);
                    dy = Math.min(Math.max(dy, -maxDy), maxDy);
                    Log.i(TAG, "Width: " + child().getWidth() + ", scale " + scale + ", dx " + dx
                            + ", max " + maxDx);
                    applyScaleAndTranslation();
                }

                return true;
            }
        });
    }

    // ScaleGestureDetector

    @Override
    public boolean onScaleBegin(ScaleGestureDetector scaleDetector) {
        Log.i(TAG, "onScaleBegin");
        return true;
    }

    @Override
    public boolean onScale(ScaleGestureDetector scaleDetector) {
        float scaleFactor = scaleDetector.getScaleFactor();
        Log.i(TAG, "onScale" + scaleFactor);
        if (lastScaleFactor == 0 || (Math.signum(scaleFactor) == Math.signum(lastScaleFactor))) {
            scale *= scaleFactor;
            scale = Math.max(MIN_ZOOM, Math.min(scale, MAX_ZOOM));
            lastScaleFactor = scaleFactor;
        } else {
            lastScaleFactor = 0;
        }
        return true;
    }

    @Override
    public void onScaleEnd(ScaleGestureDetector scaleDetector) {
        Log.i(TAG, "onScaleEnd");
    }

    private void applyScaleAndTranslation() {
        child().setScaleX(scale);
        child().setScaleY(scale);
        child().setTranslationX(dx);
        child().setTranslationY(dy);
    }

    private View child() {
        return getChildAt(0);
    }
}

Error  coming for:-

  recyclerView.addView(myZoomView);

E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.nm.esign, PID: 6028
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.nm.esign/com.nm.esign.activity.ViewTemplate}: java.lang.IllegalStateException: RecyclerView has no LayoutManager
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3319)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3415)
    at android.app.ActivityThread.access$1100(ActivityThread.java:229)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1821)
    at android.os.Handler.dispatchMessage(Handler.java:102)
    at android.os.Looper.loop(Looper.java:148)
    at android.app.ActivityThread.main(ActivityThread.java:7331)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)
 Caused by: java.lang.IllegalStateException: RecyclerView has no LayoutManager
    at android.support.v7.widget.RecyclerView.generateDefaultLayoutParams(RecyclerView.java:3869)
    at android.view.ViewGroup.addView(ViewGroup.java:4431)
    at android.view.ViewGroup.addView(ViewGroup.java:4409)
    at com.nm.esign.activity.ViewTemplate.onCreate(ViewTemplate.java:112)
    at android.app.Activity.performCreate(Activity.java:6904)
    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1136)
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3266)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3415)
    at android.app.ActivityThread.access$1100(ActivityThread.java:229)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1821)
    at android.os.Handler.dispatchMessage(Handler.java:102)
    at android.os.Looper.loop(Looper.java:148)
    at android.app.ActivityThread.main(ActivityThread.java:7331)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)

Body:
The solution was simple, you can create the layout manager manager manually.

Code snippet from https://github.com/kanytu/example-parallaxrecycler/blob/master/app/src/main/java/com/poliveira/apps/exampleparallaxrecycler/MainActivity.java#L24

Add this

LinearLayoutManager manager = new LinearLayoutManager(this);
manager.setOrientation(LinearLayoutManager.VERTICAL);
myRecycler.setLayoutManager(manager);


问:
C++ operator's optimization via templates
So, I have a C++ Matrix class, and there are some overloaded operators(like +, *, %, - atc...), they look like this:

```<code>Matrix operator*(const Matrix& b) const;
</code>```

They are returning the TMP object of type Matrix, and then it's being copied, whinch decreaces the performance.

If I do something like

```<code>Matrix some = a*b + c*d - (i+j)*m*b; //[1]
</code>```

There are something about 6 copy constructors being called.

So, I saw ppl doing some template metaprogramming, to expand the [1] to something like:

```<code>Matrix some = ((a*b)+=(c*d))-=(((i+j)*=m)*=b); //[2]
</code>```

The code at [2] gonna call somewhere around 3 copy constructors.(*=, += writing the results to left operand and returns the link for it)

Can you guys pls explain me, how do I do that via templates, or what should I read to understand how to do that.

答:
They keyword to search on is "expression templates".

A lot of things can be achieved simply by using rvalue references, though.

Incidentally, if you're really serious about it you'll want even more rewriting than your example suggests; e.g. multiply and addition steps often want to be combined into a single operation rather than two separate ones.

Body:
So, I have a C++ Matrix class, and there are some overloaded operators(like +, *, %, - atc...), they look like this:

Matrix operator*(const Matrix& b) const;

They are returning the TMP object of type Matrix, and then it's being copied, whinch decreaces the performance.

If I do something like

Matrix some = a*b + c*d - (i+j)*m*b; //[1]

There are something about 6 copy constructors being called.

So, I saw ppl doing some template metaprogramming, to expand the [1] to something like:

Matrix some = ((a*b)+=(c*d))-=(((i+j)*=m)*=b); //[2]

The code at [2] gonna call somewhere around 3 copy constructors.(*=, += writing the results to left operand and returns the link for it)

Can you guys pls explain me, how do I do that via templates, or what should I read to understand how to do that.


问:
Enter numeric value only into textbox in visual basic
I am trying to set up a form to accept a telephone number, but i am unsure of how to validate it so it will only take numeric values with 11 digits.

So far i have it working to ensure that there is something in the textbox

```<code> 'Validate data for Telephone Number
 If txtTelephoneNumber.Text = "" Then
 txtTelephoneNumber.Focus()
 MessageBox.Show("You must enter a Telephone Number.", "Data Entry Error", MessageBoxButtons.OK, MessageBoxIcon.Information)
</code>```

答:
In your textbox keydown event. Use the following:

```<code>If Not IsNumeric(Chr(e.KeyCode)) Then
    e.SuppressKeyPress = True
End If
</code>```

If you want allow other characters you would do it like so:

```<code>If Not IsNumeric(Chr(e.KeyCode)) And Not e.KeyCode = 8 And Not e.KeyCode = 46 Then
    e.SuppressKeyPress = True
End If

'(8 = backspace key and 46 = Delete key)
</code>```

Body:
I am trying to set up a form to accept a telephone number, but i am unsure of how to validate it so it will only take numeric values with 11 digits.

So far i have it working to ensure that there is something in the textbox

 'Validate data for Telephone Number
 If txtTelephoneNumber.Text = "" Then
 txtTelephoneNumber.Focus()
 MessageBox.Show("You must enter a Telephone Number.", "Data Entry Error", MessageBoxButtons.OK, MessageBoxIcon.Information)

Body:
In your textbox keydown event. Use the following:

If Not IsNumeric(Chr(e.KeyCode)) Then
    e.SuppressKeyPress = True
End If

If you want allow other characters you would do it like so:

If Not IsNumeric(Chr(e.KeyCode)) And Not e.KeyCode = 8 And Not e.KeyCode = 46 Then
    e.SuppressKeyPress = True
End If

'(8 = backspace key and 46 = Delete key)


问:
Slow loading rails environment
Is it OK that loading my rails environment takes 25 seconds?

```<code>alhafoudh@xxx:~/Projects/xxx$ time ruby -r./config/environment.rb -e ""
real    0m25.320s
user    0m22.093s
sys     0m1.988s

alhafoudh@xxx:~/Projects/xxx$ ruby -v
ruby 1.9.2p0 (2010-08-18 revision 29036) [i686-linux]

alhafoudh@xxx:~/Projects/xxx$ gem list | grep rails
using rails 3.0.3
</code>```

I am using also rvm

答:
Do you use sqlite or other client-server database engine?

Please run rails console and check whether calling reload! method is also slow...

Title: Slow loading rails environment

Body:
Is it OK that loading my rails environment takes 25 seconds?

alhafoudh@xxx:~/Projects/xxx$ time ruby -r./config/environment.rb -e ""
real    0m25.320s
user    0m22.093s
sys     0m1.988s

alhafoudh@xxx:~/Projects/xxx$ ruby -v
ruby 1.9.2p0 (2010-08-18 revision 29036) [i686-linux]

alhafoudh@xxx:~/Projects/xxx$ gem list | grep rails
using rails 3.0.3

I am using also rvm


问:
Deleberate Malware Insertion
This question made me sit and think for a while. I was wondering why deliberately inserting malware into code you are developing is not an example of negligence. It's a test process isn't it? I'm sure when developing anti-malware software, they need some sort of testing process to see how well his/her/their software copes with the real malware. And when developing a software, don't developers or testers attempt to break and exploit software to see its weakness, and how well it performs, to evaluate its capability, attribution, and etc?</p>

答: The answer to this question is it depends on how you define malware. If you define it by the attacker's (malicious) intention then you would never be inserting malware into your code if it is for testing reasons. You would be making it more secure instead.</p>

Title: Deleberate Malware Insertion


问:
searching controller in a web application
I am new to Spring-mvc. In my first tutorial I am having a doubt, we create a servelet of DispatcherServlet in web.xml and mark our controller using @contorller annotation.
Then using @Requestmapping annotation we filter url for function to be invoked.

How Spring searches for controller in the webapp?
Which function actually invoked in  DispatcherServelet to create a instance of controller class?
Can i have multiple controller in my application?

答:
Can I have multiple controller in my application?

Yes.You can create multiple controller in your application.You can get more idea following this post.


问:
Using findViewById inside a Fragment
I am creating a new Tab interface and for every tab I have functionality like:

```<code>public class ClassViewFragment extends Fragment {
    ListView classListView = null;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {

        View rootView = inflater.inflate(R.layout.class_view, container, false);

        classListView = (ListView) findViewById(R.id.classList);

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

But I am getting cannot resolve method findViewById also at another place I am also unable to use runOnUiThread and getting Error:(88, 29) error: cannot find symbol method runOnUiThread(<anonymous Runnable>)

I understand these will work fine if my class was extended from Activity but it’s a tab fragment so how can I use this funcitons?

答:
Use rootView.findViewById(R.id.classList) instead of findViewById(R.id.classList).

Try this:

```<code>public class ClassViewFragment extends Fragment {
    ListView classListView = null;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {

        View rootView = inflater.inflate(R.layout.class_view, container, false);
        classListView = (ListView) rootView.findViewById(R.id.classList);

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

Title: Using findViewById inside a Fragment

Body:
I am creating a new Tab interface and for every tab I have functionality like:

public class ClassViewFragment extends Fragment {
    ListView classListView = null;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {

        View rootView = inflater.inflate(R.layout.class_view, container, false);

        classListView = (ListView) findViewById(R.id.classList);

        return rootView;
    }
}

But I am getting cannot resolve method findViewById also at another place I am also unable to use runOnUiThread and getting Error:(88, 29) error: cannot find symbol method runOnUiThread(<anonymous Runnable>)

I understand these will work fine if my class was extended from Activity but it’s a tab fragment so how can I use this funcitons?

Body:
Use rootView.findViewById(R.id.classList) instead of findViewById(R.id.classList).

Try this:

public class ClassViewFragment extends Fragment {
    ListView classListView = null;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {

        View rootView = inflater.inflate(R.layout.class_view, container, false);
        classListView = (ListView) rootView.findViewById(R.id.classList);

        return rootView;
    }
}