问:
What is the recommended way to package perl scripts for CPAN (and CorporatePAN)?
Recently I looked at a module on CPAN that comes with a script to be installed
which made me wonder. What is the recommended way to include a script in a package
that should end up on the public CPAN and if there is any different recommendation for
packages that would be released on an in-house CPAN server?

The script starts like this:

```<code>#!/usr/bin/perl

eval 'exec /usr/bin/perl  -S $0 ${1+"$@"}'
  if 0; # not running under some shell
</code>```

Two questions

Do I understand correctly the eval part is unnecessary?
That will be embedded by the CPAN client during installation and it
will be very different when installing on Windows.

What is the recommended sh-bang line?
Would that be

```<code>#!/usr/bin/env perl
</code>```

instead of the above?

答:
When the distribution is being installed, it is being installed for some particular perl, and should explicitly set the #! to use that perl (as given in $Config{startperl}).  As far as I know all the module installers do this for you.  (Update: as noted by cjm, only if the #! as distributed runs perl, not env.)

The eval stuff is traditionally included to automatically use perl even if a script is invoked with sh scriptname.  It's harmless.

Body:
Recently I looked at a module on CPAN that comes with a script to be installed
which made me wonder. What is the recommended way to include a script in a package
that should end up on the public CPAN and if there is any different recommendation for
packages that would be released on an in-house CPAN server?

The script starts like this:

#!/usr/bin/perl

eval 'exec /usr/bin/perl  -S $0 ${1+"$@"}'
  if 0; # not running under some shell

Two questions

Do I understand correctly the eval part is unnecessary?
That will be embedded by the CPAN client during installation and it
will be very different when installing on Windows.

What is the recommended sh-bang line?
Would that be

#!/usr/bin/env perl

instead of the above?


来源: stackexchange

问:
Vision Framework with ARkit and CoreML
While I have been researching best practices and experimenting multiple options for an ongoing project(i.e. Unity3D iOS project in Vuforia with native integration, extracting frames with AVFoundation then passing the image through cloud-based image recognition), I have come to the conclusion that I would like to use ARkit, Vision Framework, and CoreML; let me explain.

I am wondering how I would be able to capture ARFrames, use the Vision Framework to detect and track a given object using a CoreML model.

Additionally, it would be nice to have a bounding box once the object is recognized with the ability to add an AR object upon a gesture touch but this is something that could be implemented after getting the solid project down.

This is undoubtedly possible, but I am unsure of how to pass the ARFrames to CoreML via Vision for processing.

Any ideas?

答:
Update: Apple now has a sample code project that does some of these steps. Read on for those you still need to figure out yourself...

Just about all of the pieces are there for what you want to do... you mostly just need to put them together.

You obtain ARFrames either by periodically polling the ARSession for its currentFrame or by having them pushed to your session delegate. (If you're building your own renderer, that's ARSessionDelegate; if you're working with ARSCNView or ARSKView, their delegate callbacks refer to the view, so you can work back from there to the session to get the currentFrame that led to the callback.)

ARFrame provides the current capturedImage in the form of a CVPixelBuffer.

You pass images to Vision for processing using either the VNImageRequestHandler or VNSequenceRequestHandler class, both of which have methods that take a CVPixelBuffer as an input image to process.

You use the image request handler if you want to perform a request that uses a single image — like finding rectangles or QR codes or faces, or using a Core ML model to identify the image.

You use the sequence request handler to perform requests that involve analyzing changes between multiple images, like tracking an object's movement after you've identified it.

You can find general code for passing images to Vision + Core ML attached to the WWDC17 session on Vision, and if you watch that session the live demos also include passing CVPixelBuffers to Vision. (They get pixel buffers from AVCapture in that demo, but if you're getting buffers from ARKit the Vision part is the same.)

One sticking point you're likely to have is identifying/locating objects. Most "object recognition" models people use with Core ML + Vision (including those that Apple provides pre-converted versions of on their ML developer page) are scene classifiers. That is, they look at an image and say, "this is a picture of a (thing)," not something like "there is a (thing) in this picture, located at (bounding box)".

Vision provides easy API for dealing with classifiers — your request's results array is filled in with VNClassificationObservation objects that tell you what the scene is (or "probably is", with a confidence rating).

If you find or train a model that both identifies and locates objects — and for that part, I must stress, the ball is in your court — using Vision with it will result in VNCoreMLFeatureValueObservation objects. Those are sort of like arbitrary key-value pairs, so exactly how you identify an object from those depends on how you structure and label the outputs from your model.

If you're dealing with something that Vision already knows how to recognize, instead of using your own model — stuff like faces and QR codes — you can get the locations of those in the image frame with Vision's API.

If after locating an object in the 2D image, you want to display 3D content associated with it in AR (or display 2D content, but with said content positioned in 3D with ARKit), you'll need to hit test those 2D image points against the 3D world.

Once you get to this step, placing AR content with a hit test is something that's already pretty well covered elsewhere, both by Apple and the community.

ContentLicense: CC BY-SA 3.0

Title: Vision Framework with ARkit and CoreML


问:
I need correct example for ajax send and received data in zend framework 3
Example for send and received data between ajax function and action of controller in Zend framework 3  </p>

答:
Here is a simple example of an ajax request using ZF3. You may give a try with this one. In this example we would use ZF3's default Application module.

Lets assume we would retrieve data via a ajax call from the following url.

```<code>http://yoursite.com/title
</code>```

Lets create an action method for the title route in the IndexController.

```<code>public function titleAction()
{
    // Initialize view
    $view = new ViewModel();

    // Checks if this is a Javascript request
    $xmlHttpRequst = $this->getRequest()->isXmlHttpRequest();

    if (! $xmlHttpRequst) {
        die('Bad request');
    }

    /**
     * Here we may pull data from database but for tests
     * here we make an array of titles for the view
     */
    $titles = [];
    for ($i = 0; $i < 10; $i++) {
        $titles[] = "Lorem ipsum dolor {$i}";
    }

    // Set data to be used in the view
    $view->setVariable('titles', $titles);

    /**
     * Tell the renderer not to show the layout
     * by setting setTerminal to true
     */
    $view->setTerminal(true);

    return $view;
}
</code>```

We created a method, we need creating a view template for it.

view/application/index/title.phtml

```<code><?php
foreach ($titles as $title) {
    echo '<h2>' . $title . '</h2>';
}
</code>```

Now we would create another action method in the IndexController from where we would make the ajax call.

```<code>http://yoursite.com/text
</code>```

So lets make that action method too...

```<code>public function textAction()
{
    return new ViewModel();
}
</code>```

and view template would be like so

view/application/index/text.phtml

```<code><h1>Handling ajax request</h1>

<button onclick="showTitle()">Show Title</button>

<div id="box"></div>

<?php
    // Set url
    $url = $this->serverUrl('/title'); // http://yoursite.com/title

    // This is for the "url" catch
    echo "<script>" . PHP_EOL;
    echo "\tvar url = '{$url}';" . PHP_EOL;
    echo "</script>" . PHP_EOL;
?>

<script>
    function showTitle() {
        $.get(url, function(data){
            $('#box').html(data);
        })
        .done(function(){
            console.log('Done!');
        })
        .fail(function(){
            console.log('Failed!');
        });
    }
</script>
</code>```

This script needs jQuery Javascript library to make the ajax call. So make sure that script is added in your view/layout/layout.phtml.

The last thing we need is to set up routes for the /title and /text. Lets add those two routes to the route section of module/Application/config/module.config.php

```<code>'title' => [
    'type' => Literal::class,
    'options' => [
        'route' => '/title',
        'defaults' => [
            'controller' => Controller\IndexController::class,
            'action' => 'title',
        ],
    ],
],
'text' => [
    'type' => Literal::class,
    'options' => [
        'route' => '/text',
        'defaults' => [
            'controller' => Controller\IndexController::class,
            'action' => 'text',
        ],
    ],
],
</code>```

Let us know if it makes you happy!

Body:
Here is a simple example of an ajax request using ZF3. You may give a try with this one. In this example we would use ZF3's default Application module.

Lets assume we would retrieve data via a ajax call from the following url.

http://yoursite.com/title

Lets create an action method for the title route in the IndexController.

public function titleAction()
{
    // Initialize view
    $view = new ViewModel();

    // Checks if this is a Javascript request
    $xmlHttpRequst = $this->getRequest()->isXmlHttpRequest();

    if (! $xmlHttpRequst) {
        die('Bad request');
    }

    /**
     * Here we may pull data from database but for tests
     * here we make an array of titles for the view
     */
    $titles = [];
    for ($i = 0; $i < 10; $i++) {
        $titles[] = "Lorem ipsum dolor {$i}";
    }

    // Set data to be used in the view
    $view->setVariable('titles', $titles);

    /**
     * Tell the renderer not to show the layout
     * by setting setTerminal to true
     */
    $view->setTerminal(true);

    return $view;
}

We created a method, we need creating a view template for it.

view/application/index/title.phtml

<?php
foreach ($titles as $title) {
    echo '<h2>' . $title . '</h2>';
}

Now we would create another action method in the IndexController from where we would make the ajax call.

http://yoursite.com/text

So lets make that action method too...

public function textAction()
{
    return new ViewModel();
}

and view template would be like so

view/application/index/text.phtml

<h1>Handling ajax request</h1>

<button onclick="showTitle()">Show Title</button>

<div id="box"></div>

<?php
    // Set url
    $url = $this->serverUrl('/title'); // http://yoursite.com/title

    // This is for the "url" catch
    echo "<script>" . PHP_EOL;
    echo "\tvar url = '{$url}';" . PHP_EOL;
    echo "</script>" . PHP_EOL;
?>

<script>
    function showTitle() {
        $.get(url, function(data){
            $('#box').html(data);
        })
        .done(function(){
            console.log('Done!');
        })
        .fail(function(){
            console.log('Failed!');
        });
    }
</script>

This script needs jQuery Javascript library to make the ajax call. So make sure that script is added in your view/layout/layout.phtml.

The last thing we need is to set up routes for the /title and /text. Lets add those two routes to the route section of module/Application/config/module.config.php

'title' => [
    'type' => Literal::class,
    'options' => [
        'route' => '/title',
        'defaults' => [
            'controller' => Controller\IndexController::class,
            'action' => 'title',
        ],
    ],
],
'text' => [
    'type' => Literal::class,
    'options' => [
        'route' => '/text',
        'defaults' => [
            'controller' => Controller\IndexController::class,
            'action' => 'text',
        ],
    ],
],

Let us know if it makes you happy!


问:
Could not resolve this reference. Could not locate the assembly
Everytime I build my solution, I get this error message:

Warning

3

Could not resolve this reference. Could not locate the
  assembly "StandardClassLibrary, Version=1.0.0.0, Culture=neutral,
  processorArchitecture=MSIL". Check to make sure the assembly exists on
  disk. If this reference is required by your code, you may get
  compilation errors.

StandardClassLibrary

So my application has a number of projects of which StandardClassLibrary is one. The above message is a warning and as far as I can tell it does NOT have an impact on my solution.

But I would rather it not be there, just in case...

答: I had the same warning in VS 2017. As it turned out in my case I had added a unit test project and needed to set a dependency for the unit test on the DLL it was testing.</p>

ContentLicense: CC BY-SA 4.0


问:
C# winforms dynimcally created Labels position
I have a bunch of dynamically added controls which add row by row when the user clicks the add user button. I want there to be a label when the page loads and i want the same label to move down every time the add user button is clicked (under each row of textboxes). Right now it is there on load and it moves down when the user clicks the button the first time but after that it just stays. Here is my code:

Global variables:

```<code>Label Savelbl = new Label();
int LabelX = 15;
int LabelY = 110;
int spacelbl = 15;
</code>```

Page load:

```<code>Savelbl.Location = new Point(LabelX, LabelY);
Savelbl.Name = "Savelbl";
Savelbl.Text = "Please click 'save' to save your changes";
CaeUsersPanel.Controls.Add(Savelbl);
</code>```

Add user button:

```<code>    private void CAEAddUserbtn_Click(object sender, EventArgs e)
    {

        var i = UsernameTextBoxes.Count + 1; // this is a list of the added textboxes
        ADDUserInfo(i); //method which adds the dynamically created textboxes

      Savelbl.Location = new Point(LabelX, LabelY + spacelbl);

    }
</code>```

Remove user button (the label should move back up when this is clicked):

```<code>private void Remove_Click(object sender, EventArgs e)
{
DialogResult result = MessageBox.Show("Are you sure you want delete this user?  \n Deleting users may break workflows", "Delete", MessageBoxButtons.YesNo);
            if (result == DialogResult.Yes)
            {

                int idx = RemoveButtons.IndexOf((Button)sender);

                // Remove button
                RemoveButtons[idx].Dispose();
                RemoveButtons.RemoveAt(idx);

                // Remove textbox
                UsernameTextBoxes[idx + 1].Dispose();
                UsernameTextBoxes.RemoveAt(idx + 1);

                //Shift controls up
                for (int i = idx; i < RemoveButtons.Count; i++)
                {
                    UsernameTextBoxes[i + 1].Top -= SpaceDelta;
                }

                space -= SpaceDelta;

                Savelbl.Location = new Point(LabelX, LabelY - spacelbl);

            }
        }
</code>```

答:
You never update LabelX and LabelY.

```<code>LabelX = Savelbl.Location.X
LabelY = Savelbl.Location.Y
Savelbl.Location = new Point(LabelX, LabelY - spacelbl);
</code>```

You could also get rid of these variables probably...

Body:
I have a bunch of dynamically added controls which add row by row when the user clicks the add user button. I want there to be a label when the page loads and i want the same label to move down every time the add user button is clicked (under each row of textboxes). Right now it is there on load and it moves down when the user clicks the button the first time but after that it just stays. Here is my code:

Global variables:

Label Savelbl = new Label();
int LabelX = 15;
int LabelY = 110;
int spacelbl = 15;

Page load:

Savelbl.Location = new Point(LabelX, LabelY);
Savelbl.Name = "Savelbl";
Savelbl.Text = "Please click 'save' to save your changes";
CaeUsersPanel.Controls.Add(Savelbl);

Add user button:

    private void CAEAddUserbtn_Click(object sender, EventArgs e)
    {

        var i = UsernameTextBoxes.Count + 1; // this is a list of the added textboxes
        ADDUserInfo(i); //method which adds the dynamically created textboxes

      Savelbl.Location = new Point(LabelX, LabelY + spacelbl);

    }

Remove user button (the label should move back up when this is clicked):

private void Remove_Click(object sender, EventArgs e)
{
DialogResult result = MessageBox.Show("Are you sure you want delete this user?  \n Deleting users may break workflows", "Delete", MessageBoxButtons.YesNo);
            if (result == DialogResult.Yes)
            {

                int idx = RemoveButtons.IndexOf((Button)sender);

                // Remove button
                RemoveButtons[idx].Dispose();
                RemoveButtons.RemoveAt(idx);

                // Remove textbox
                UsernameTextBoxes[idx + 1].Dispose();
                UsernameTextBoxes.RemoveAt(idx + 1);

                //Shift controls up
                for (int i = idx; i < RemoveButtons.Count; i++)
                {
                    UsernameTextBoxes[i + 1].Top -= SpaceDelta;
                }

                space -= SpaceDelta;

                Savelbl.Location = new Point(LabelX, LabelY - spacelbl);

            }
        }

Body:
You never update LabelX and LabelY.

LabelX = Savelbl.Location.X
LabelY = Savelbl.Location.Y
Savelbl.Location = new Point(LabelX, LabelY - spacelbl);

You could also get rid of these variables probably...


问:
Postfix and prefix increment that causes an error
Why does that code does not compile due to an error:

```<code>#include <iostream>

using namespace std;

int main()
{
    int i = 0;
    cout << ++(i++) << " " << i << endl;
    return 0;
}
</code>```

While that code does compile:

```<code>#include <iostream>

using namespace std;

int main()
{
    int i = 0;
    cout << (++i)++ << " " << i << endl;
    return 0;
}
</code>```

I do not understand that. From my point of view it would be pretty reasonable for the first chunk to compile. The expression ++(i++) would just mean take i, increment it and output, then increment it again.

I am not asking about an undefined behavior in int overflow. I do not know about r and l value at all at the time of writing the question and I do not care why is ++i considered an l-value, but i++ is not.

答:
This is because the post increment and pre increment operators return values with different types. Result of post increment is a so-called 'rvalue', meaning it can not be modified. But pre-increment needs a modifiable value to increment it!

On the other hand, result of pre-increment is an lvalue, meaning that it can be safely modified by the post increment.

And the reason for above rules is the fact that post-increment needs to return a value of the object as it was before increment was applied. By the way, this is why in general case post-incrememts are considered to be more expensive than pre-increments when used on non-builtin objects.

Body:
Why does that code does not compile due to an error:

#include <iostream>

using namespace std;

int main()
{
    int i = 0;
    cout << ++(i++) << " " << i << endl;
    return 0;
}

While that code does compile:

#include <iostream>

using namespace std;

int main()
{
    int i = 0;
    cout << (++i)++ << " " << i << endl;
    return 0;
}

I do not understand that. From my point of view it would be pretty reasonable for the first chunk to compile. The expression ++(i++) would just mean take i, increment it and output, then increment it again.

I am not asking about an undefined behavior in int overflow. I do not know about r and l value at all at the time of writing the question and I do not care why is ++i considered an l-value, but i++ is not.


问:
how open .conf file with admin rights, edit and save using bat
This is the content of the conf file

use chroot = false

strict modes = false

hosts allow = *

log file = rsyncd.log

i need to add this two lines in the begin

uid=0

gid=0

and this other lines in the end

[data]

path = /cygdrive/d/My documents

read only = false

transfer logging = yes

[mail]

path = /cygdrive/d/mail

read only = false

transfer logging = yes

with the bat completed i will going to deploy it by policy on my network.

i´m really new in this, but i appreciate your help. Apologies for my english.

I tried with this code:

```<code>@echo off
Color 9A & Mode con cols=83 lines=5
Title %~n0 Adding lines to rsyncd.conf
:::::::::::::::::::::::::::::::::::::::::
:: Automatically check & get admin rights
:::::::::::::::::::::::::::::::::::::::::
REM  --> Check for permissions
Reg query "HKU\S-1-5-19\Environment" >nul 2>&1
REM --> If error flag set, we do not have admin.
if '%errorlevel%' NEQ '0' (
Echo.
ECHO                      **************************************
ECHO                       Running Admin shell... Please wait...
ECHO                      **************************************
goto UACPrompt
) else ( goto gotAdmin )
:UACPrompt
    echo Set UAC = CreateObject^("Shell.Application"^) > "%temp%\getadmin.vbs"
    set params = %*:"=""
    echo UAC.ShellExecute "cmd.exe", "/c ""%~s0"" %params%", "", "runas", 1 >> "%temp%\getadmin.vbs"

    "%temp%\getadmin.vbs"
    del "%temp%\getadmin.vbs"
    exit /B
:gotAdmin
::::::::::::::::::::::::::::
::START
::::::::::::::::::::::::::::
set "hostspath=C:\Program Files (x86)\ICW\rsyncd.conf"
FIND /C /I "uid=0" "%hostspath%" >nul
FIND /C /I "gid=0" "%hostspath%" >nul
FIND /C /I "[data]" "%hostspath%" >nul
FIND /C /I "path = /cygdrive/d/My documents" "%hostspath%" >nul
FIND /C /I "read only = false" "%hostspath%" >nul
FIND /C /I "transfer logging = yes" "%hostspath%" >nul
FIND /C /I "[mail]" "%hostspath%" >nul
FIND /C /I "path = /cygdrive/d/mail" "%hostspath%" >nul
FIND /C /I "read only = false" "%hostspath%" >nul
FIND /C /I "transfer logging = yes" "%hostspath%" >nul
)
Attrib +R "%hostspath%"
</code>```

答:
You can use this script to get admin rights. Just copy the script to the end of a batch file with this script in the beginning:</p>

```<code>@echo off

:: Run this script with elevation
call :RequestAdminElevation "%~dpfs0" %* || goto:eof

set "hostspath=C:\Program Files (x86)\ICW\rsyncd.conf"
set "new_hostspath=C:\Program Files (x86)\ICW\rsyncd.temp"

:: Add the first lines to the new file
echo uid=0> %new_hostspath%
echo gid=0>> %new_hostspath%

:: copy your original .conf file to the new one
type %hostspath% >> %new_hostspath%

:: add the last lines to the new file
echo [data] >> %new_hostspath%
echo path = /cygdrive/d/My documents >> %new_hostspath%
echo read only = false >> %new_hostspath%
echo transfer logging = yes >> %new_hostspath%
echo [mail] >> %new_hostspath%
echo path = /cygdrive/d/mail >> %new_hostspath%
echo read only = false >> %new_hostspath%
echo transfer logging = yes >> %new_hostspath%

:: copy new file over the old file
type %new_hostspath% > %hostspath

pause &goto:eof

[here you paste the RequestAdminElevation function code]
</code>```

Body:
This is the content of the conf file

use chroot = false

strict modes = false

hosts allow = *

log file = rsyncd.log

i need to add this two lines in the begin

uid=0

gid=0

and this other lines in the end

[data]

path = /cygdrive/d/My documents

read only = false

transfer logging = yes

[mail]

path = /cygdrive/d/mail

read only = false

transfer logging = yes

with the bat completed i will going to deploy it by policy on my network.

i´m really new in this, but i appreciate your help. Apologies for my english.

I tried with this code:

@echo off
Color 9A & Mode con cols=83 lines=5
Title %~n0 Adding lines to rsyncd.conf
:::::::::::::::::::::::::::::::::::::::::
:: Automatically check & get admin rights
:::::::::::::::::::::::::::::::::::::::::
REM  --> Check for permissions
Reg query "HKU\S-1-5-19\Environment" >nul 2>&1
REM --> If error flag set, we do not have admin.
if '%errorlevel%' NEQ '0' (
Echo.
ECHO                      **************************************
ECHO                       Running Admin shell... Please wait...
ECHO                      **************************************
goto UACPrompt
) else ( goto gotAdmin )
:UACPrompt
    echo Set UAC = CreateObject^("Shell.Application"^) > "%temp%\getadmin.vbs"
    set params = %*:"=""
    echo UAC.ShellExecute "cmd.exe", "/c ""%~s0"" %params%", "", "runas", 1 >> "%temp%\getadmin.vbs"

    "%temp%\getadmin.vbs"
    del "%temp%\getadmin.vbs"
    exit /B
:gotAdmin
::::::::::::::::::::::::::::
::START
::::::::::::::::::::::::::::
set "hostspath=C:\Program Files (x86)\ICW\rsyncd.conf"
FIND /C /I "uid=0" "%hostspath%" >nul
FIND /C /I "gid=0" "%hostspath%" >nul
FIND /C /I "[data]" "%hostspath%" >nul
FIND /C /I "path = /cygdrive/d/My documents" "%hostspath%" >nul
FIND /C /I "read only = false" "%hostspath%" >nul
FIND /C /I "transfer logging = yes" "%hostspath%" >nul
FIND /C /I "[mail]" "%hostspath%" >nul
FIND /C /I "path = /cygdrive/d/mail" "%hostspath%" >nul
FIND /C /I "read only = false" "%hostspath%" >nul
FIND /C /I "transfer logging = yes" "%hostspath%" >nul
)
Attrib +R "%hostspath%"

Body:
You can use this script to get admin rights. Just copy the script to the end of a batch file with this script in the beginning:

@echo off

:: Run this script with elevation
call :RequestAdminElevation "%~dpfs0" %* || goto:eof

set "hostspath=C:\Program Files (x86)\ICW\rsyncd.conf"
set "new_hostspath=C:\Program Files (x86)\ICW\rsyncd.temp"

:: Add the first lines to the new file
echo uid=0> %new_hostspath%
echo gid=0>> %new_hostspath%

:: copy your original .conf file to the new one
type %hostspath% >> %new_hostspath%

:: add the last lines to the new file
echo [data] >> %new_hostspath%
echo path = /cygdrive/d/My documents >> %new_hostspath%
echo read only = false >> %new_hostspath%
echo transfer logging = yes >> %new_hostspath%
echo [mail] >> %new_hostspath%
echo path = /cygdrive/d/mail >> %new_hostspath%
echo read only = false >> %new_hostspath%
echo transfer logging = yes >> %new_hostspath%

:: copy new file over the old file
type %new_hostspath% > %hostspath

pause &goto:eof

[here you paste the RequestAdminElevation function code]


问:
How to update date in table based on two criteria from a select
I need to update a date in one table based on if an userID and planName are returned from a select off a different table.
Something like</p>

```<code>UPDATE Table A
SET DATE = GETDATE()
WHERE userid AND planName IN (SELECT userid, planName From Table B)
</code>```

答:
This was able to get it:</p>

```<code>WITH CTE (userid, planName)
AS (SELECT userid, planName From Table B)
UPDATE A
SET DATE = GETDATE()
FROM Table A
JOIN CTE B
ON B.userid = A.userid AND B.planName = A.planName
</code>```

Body:
I need to update a date in one table based on if an userID and planName are returned from a select off a different table.
Something like

UPDATE Table A
SET DATE = GETDATE()
WHERE userid AND planName IN (SELECT userid, planName From Table B)

Body:
This was able to get it:

WITH CTE (userid, planName)
AS (SELECT userid, planName From Table B)
UPDATE A
SET DATE = GETDATE()
FROM Table A
JOIN CTE B
ON B.userid = A.userid AND B.planName = A.planName


问:
Multigraph and cheapest path
I have a problem to solve, I need to find the cheapest path between two cities, but there are several possible path between two neighboring cities so I have a Multigraph and i can have discount between two edge . Is there an algorithm to find the cheapest path in a Multigraph?

thanks!

答: Dijkstra works with Multigraphs, but you should not keep track of visited vertices, you have to examine them again because of the parallel edges. Moreover, whenever you find a self-loop you should move one without any calculations.</p>

Title: Multigraph and cheapest path


问:
C++:Boost: Does Managed Shared Memory Require a Semaphore lock?
I have two processes sharing a vector of strings.

Process A will only push strings into the vector

Process B will read the string and remove it from the vector

Does this require a semaphore in order to prevent data corruption? Does boost already handle this using managed_shared_memory ?

Thanks

答: Boost managed shared memory DOES require a semaphore lock, otherwise the processes can read and write bad data- and unexpected behaviour will occur. (segmentation faults or otherwise).</p>


问:
Ask location permissions inside service
I am getting the location data using a service, this service is started when my app runs on a activity, and i need that activity to ask for the permissions.

So basicly this is my service (it works fine)

```<code>public class GoogleLocation extends Service implements GoogleApiClient.ConnectionCallbacks,
        GoogleApiClient.OnConnectionFailedListener,
        LocationListener {

    private static final String TAG = "BOOMBOOMTESTGPS";
    private static final long FASTEST_UPDATE_INTERVAL_IN_MILLISECONDS = 0;
    private LocationManager mLocationManager = null;
    private static final int LOCATION_INTERVAL = 0;
    private static final float LOCATION_DISTANCE = 0f;
    private int updatePriority;
    private GoogleApiClient googleApiClient;
    private LocationRequest locationRequest;

    private final IBinder mBinder = new LocalBinder();
    private Intent intent;
    private String provider;
    Context context;

    Location mLastLocation;

    public class LocalBinder extends Binder {
        public GoogleLocation getServerInstance() {
            return GoogleLocation.this;
        }
    }

    public Location getLocation() {
        Log.d("IMHERE", "HELLO");
        return mLastLocation;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.e(TAG, "onStartCommand");
        context = getApplicationContext();
        super.onStartCommand(intent, flags, startId);
        return START_STICKY;
    }

    @Override
    public IBinder onBind(Intent intent) {
        return mBinder;
    }

    @Override
    public void onCreate() {
        Log.e(TAG, "onCreate");
        initializeLocationManager();

        if (mLocationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
            this.updatePriority = LocationRequest.PRIORITY_HIGH_ACCURACY;
        } else if (mLocationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {
            this.updatePriority = LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY;
        } else {
            this.updatePriority = LocationRequest.PRIORITY_HIGH_ACCURACY;
        }

        this.buildGoogleApiClient();
        this.createLocationRequest();
        this.googleApiClient.connect();

    }

    @Override
    public void onConnected(@Nullable Bundle bundle) {
        // Request location updates
        if (ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            return;
        }
        LocationServices.FusedLocationApi.requestLocationUpdates(this.googleApiClient, this.locationRequest,this);
    }

    @Override
    public void onConnectionSuspended(int i) {

    }

    @Override
    public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {

    }

    @Override
    public void onLocationChanged(Location location) {
        mLastLocation = location;
        Log.d("localizacao",mLastLocation.toString());
    }

    @Override
    public void onDestroy() {
        Log.e(TAG, "onDestroy");
        super.onDestroy();

        this.googleApiClient.unregisterConnectionCallbacks(this);
        this.googleApiClient.unregisterConnectionFailedListener(this);
        this.googleApiClient.disconnect();
        this.mLastLocation = null;
    }

    private void initializeLocationManager() {
        Log.e(TAG, "initializeLocationManager");
        mLocationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
        if (mLocationManager == null) {
            mLocationManager = (LocationManager) getApplicationContext().getSystemService(Context.LOCATION_SERVICE);
        }
    }

    private synchronized void buildGoogleApiClient() {
        this.googleApiClient = new GoogleApiClient.Builder(this)
                .addApi(LocationServices.API)
                .addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this)
                .build();
    }

    private void createLocationRequest() {
        this.locationRequest = new LocationRequest();
        this.locationRequest.setInterval(FASTEST_UPDATE_INTERVAL_IN_MILLISECONDS);
        this.locationRequest.setPriority(updatePriority);

    }
</code>```

here is where i start it

```<code>package com.example.afcosta.inesctec.pt.android;

import android.Manifest;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;

import com.example.afcosta.inesctec.pt.android.services.GoogleLocation;

public class LocationPermission extends AppCompatActivity {

    public static final int REQ_PERMISSION = 99;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        askPermission();
        Intent i = new Intent(this,Login.class);
        startActivity(i);
    }

    // PEDIDO DE PERMISSÃO
    private void askPermission() {
        checkLocationPermission();
    }

    public static final int MY_PERMISSIONS_REQUEST_LOCATION = 99;

    public boolean checkLocationPermission() {
        if (ContextCompat.checkSelfPermission(this,
                Manifest.permission. ACCESS_FINE_LOCATION)
                != PackageManager.PERMISSION_GRANTED) {

            // Should we show an explanation?
            if (ActivityCompat.shouldShowRequestPermissionRationale(this,
                    Manifest.permission. ACCESS_FINE_LOCATION)) {

                // Show an explanation to the user *asynchronously* -- don't block
                // this thread waiting for the user's response! After the user
                // sees the explanation, try again to request the permission.
                new AlertDialog.Builder(this)
                        .setTitle("Partilhar localização")
                        .setMessage("Permitir a partilha de dados sobre a sua localização?")
                        .setPositiveButton("ok", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {
                                //Prompt the user once explanation has been shown
                                ActivityCompat.requestPermissions(LocationPermission.this,
                                        new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
                                        MY_PERMISSIONS_REQUEST_LOCATION);
                            }
                        })
                        .create()
                        .show();

            } else {
                // No explanation needed, we can request the permission.
                ActivityCompat.requestPermissions(this,
                        new String[]{Manifest.permission. ACCESS_FINE_LOCATION},
                        MY_PERMISSIONS_REQUEST_LOCATION);
            }
            return false;
        } else {
            startService(new Intent(this, GoogleLocation.class));
            return true;
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode,
                                           String permissions[], int[] grantResults) {
        switch (requestCode) {
            case MY_PERMISSIONS_REQUEST_LOCATION: {
                // If request is cancelled, the result arrays are empty.
                if (grantResults.length > 0
                        && grantResults[0] == PackageManager.PERMISSION_GRANTED) {

                    // permission was granted, yay! Do the
                    // location-related task you need to do.
                    if (ContextCompat.checkSelfPermission(this,
                            Manifest.permission. ACCESS_FINE_LOCATION)
                            == PackageManager.PERMISSION_GRANTED) {

                        startService(new Intent(this, GoogleLocation.class));
                    }

                } else {

                    // permission denied, boo! Disable the
                    // functionality that depends on this permission.

                }
                return;
            }

        }
    }
}
</code>```

the thing is, i need to ask for permissions when he runs the app for the first time, or he has the location disabled. And that never happens.

I should just start the service when the user has give the permission.

Any help with this?

Thanks

答:
you can ask for any permission in runtime in this way:

```<code>if (ContextCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
    if (ActivityCompat.shouldShowRequestPermissionRationale(getActivity(), Manifest.permission.ACCESS_FINE_LOCATION)) {

    } else {
        ActivityCompat.requestPermissions(getActivity(), new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, RC_ACCESS_FINE_LOCATION);
    }
}
</code>```

and you can get it's result in:

```<code>@Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
    switch (requestCode) {
        case RC_ACCESS_FINE_LOCATION: {

        }
    }
}
</code>```

Title: Ask location permissions inside service

Body:
I am getting the location data using a service, this service is started when my app runs on a activity, and i need that activity to ask for the permissions.

So basicly this is my service (it works fine)

public class GoogleLocation extends Service implements GoogleApiClient.ConnectionCallbacks,
        GoogleApiClient.OnConnectionFailedListener,
        LocationListener {

    private static final String TAG = "BOOMBOOMTESTGPS";
    private static final long FASTEST_UPDATE_INTERVAL_IN_MILLISECONDS = 0;
    private LocationManager mLocationManager = null;
    private static final int LOCATION_INTERVAL = 0;
    private static final float LOCATION_DISTANCE = 0f;
    private int updatePriority;
    private GoogleApiClient googleApiClient;
    private LocationRequest locationRequest;

    private final IBinder mBinder = new LocalBinder();
    private Intent intent;
    private String provider;
    Context context;

    Location mLastLocation;

    public class LocalBinder extends Binder {
        public GoogleLocation getServerInstance() {
            return GoogleLocation.this;
        }
    }

    public Location getLocation() {
        Log.d("IMHERE", "HELLO");
        return mLastLocation;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.e(TAG, "onStartCommand");
        context = getApplicationContext();
        super.onStartCommand(intent, flags, startId);
        return START_STICKY;
    }

    @Override
    public IBinder onBind(Intent intent) {
        return mBinder;
    }

    @Override
    public void onCreate() {
        Log.e(TAG, "onCreate");
        initializeLocationManager();

        if (mLocationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
            this.updatePriority = LocationRequest.PRIORITY_HIGH_ACCURACY;
        } else if (mLocationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {
            this.updatePriority = LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY;
        } else {
            this.updatePriority = LocationRequest.PRIORITY_HIGH_ACCURACY;
        }

        this.buildGoogleApiClient();
        this.createLocationRequest();
        this.googleApiClient.connect();

    }

    @Override
    public void onConnected(@Nullable Bundle bundle) {
        // Request location updates
        if (ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            return;
        }
        LocationServices.FusedLocationApi.requestLocationUpdates(this.googleApiClient, this.locationRequest,this);
    }

    @Override
    public void onConnectionSuspended(int i) {

    }

    @Override
    public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {

    }

    @Override
    public void onLocationChanged(Location location) {
        mLastLocation = location;
        Log.d("localizacao",mLastLocation.toString());
    }

    @Override
    public void onDestroy() {
        Log.e(TAG, "onDestroy");
        super.onDestroy();

        this.googleApiClient.unregisterConnectionCallbacks(this);
        this.googleApiClient.unregisterConnectionFailedListener(this);
        this.googleApiClient.disconnect();
        this.mLastLocation = null;
    }

    private void initializeLocationManager() {
        Log.e(TAG, "initializeLocationManager");
        mLocationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
        if (mLocationManager == null) {
            mLocationManager = (LocationManager) getApplicationContext().getSystemService(Context.LOCATION_SERVICE);
        }
    }

    private synchronized void buildGoogleApiClient() {
        this.googleApiClient = new GoogleApiClient.Builder(this)
                .addApi(LocationServices.API)
                .addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this)
                .build();
    }

    private void createLocationRequest() {
        this.locationRequest = new LocationRequest();
        this.locationRequest.setInterval(FASTEST_UPDATE_INTERVAL_IN_MILLISECONDS);
        this.locationRequest.setPriority(updatePriority);

    }

here is where i start it

package com.example.afcosta.inesctec.pt.android;

import android.Manifest;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;

import com.example.afcosta.inesctec.pt.android.services.GoogleLocation;

public class LocationPermission extends AppCompatActivity {

    public static final int REQ_PERMISSION = 99;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        askPermission();
        Intent i = new Intent(this,Login.class);
        startActivity(i);
    }

    // PEDIDO DE PERMISSÃO
    private void askPermission() {
        checkLocationPermission();
    }

    public static final int MY_PERMISSIONS_REQUEST_LOCATION = 99;

    public boolean checkLocationPermission() {
        if (ContextCompat.checkSelfPermission(this,
                Manifest.permission. ACCESS_FINE_LOCATION)
                != PackageManager.PERMISSION_GRANTED) {

            // Should we show an explanation?
            if (ActivityCompat.shouldShowRequestPermissionRationale(this,
                    Manifest.permission. ACCESS_FINE_LOCATION)) {

                // Show an explanation to the user *asynchronously* -- don't block
                // this thread waiting for the user's response! After the user
                // sees the explanation, try again to request the permission.
                new AlertDialog.Builder(this)
                        .setTitle("Partilhar localização")
                        .setMessage("Permitir a partilha de dados sobre a sua localização?")
                        .setPositiveButton("ok", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {
                                //Prompt the user once explanation has been shown
                                ActivityCompat.requestPermissions(LocationPermission.this,
                                        new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
                                        MY_PERMISSIONS_REQUEST_LOCATION);
                            }
                        })
                        .create()
                        .show();

            } else {
                // No explanation needed, we can request the permission.
                ActivityCompat.requestPermissions(this,
                        new String[]{Manifest.permission. ACCESS_FINE_LOCATION},
                        MY_PERMISSIONS_REQUEST_LOCATION);
            }
            return false;
        } else {
            startService(new Intent(this, GoogleLocation.class));
            return true;
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode,
                                           String permissions[], int[] grantResults) {
        switch (requestCode) {
            case MY_PERMISSIONS_REQUEST_LOCATION: {
                // If request is cancelled, the result arrays are empty.
                if (grantResults.length > 0
                        && grantResults[0] == PackageManager.PERMISSION_GRANTED) {

                    // permission was granted, yay! Do the
                    // location-related task you need to do.
                    if (ContextCompat.checkSelfPermission(this,
                            Manifest.permission. ACCESS_FINE_LOCATION)
                            == PackageManager.PERMISSION_GRANTED) {

                        startService(new Intent(this, GoogleLocation.class));
                    }

                } else {

                    // permission denied, boo! Disable the
                    // functionality that depends on this permission.

                }
                return;
            }

        }
    }
}

the thing is, i need to ask for permissions when he runs the app for the first time, or he has the location disabled. And that never happens.

I should just start the service when the user has give the permission.

Any help with this?

Thanks

Body:
you can ask for any permission in runtime in this way:

if (ContextCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
    if (ActivityCompat.shouldShowRequestPermissionRationale(getActivity(), Manifest.permission.ACCESS_FINE_LOCATION)) {

    } else {
        ActivityCompat.requestPermissions(getActivity(), new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, RC_ACCESS_FINE_LOCATION);
    }
}

and you can get it's result in:

@Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
    switch (requestCode) {
        case RC_ACCESS_FINE_LOCATION: {

        }
    }
}


问:
If Loader's sourceComponent Item references its parent, and I set "loader.active = false", I get an error
My code:

```<code>import QtQuick 2.6
import QtQuick.Window 2.2

Window {
    visible: true
    width: 640
    height: 480

    Item {
        id: loaderParent
        Loader {
            id: loader
            active: true
            sourceComponent: Item {
                parent: loaderParent
                x: parent.x
            }
        }
    }

    Item {
        focus: true
        Keys.onPressed: {
            loader.active = false;
        }
    }
}
</code>```

When I press any key, I get this error:

qrc:/main.qml:16: TypeError: Cannot read property of null

Thought I suspect this error is harmless, I'd like an explanation or any idea for a fix/workaround?

Reported here.

答: I found a workaround: instead of fetching parent.x, fetch loaderParent.x. Still want to know why the problem happens.

Body:
My code:

import QtQuick 2.6
import QtQuick.Window 2.2

Window {
    visible: true
    width: 640
    height: 480

    Item {
        id: loaderParent
        Loader {
            id: loader
            active: true
            sourceComponent: Item {
                parent: loaderParent
                x: parent.x
            }
        }
    }

    Item {
        focus: true
        Keys.onPressed: {
            loader.active = false;
        }
    }
}

When I press any key, I get this error:

qrc:/main.qml:16: TypeError: Cannot read property of null

Thought I suspect this error is harmless, I'd like an explanation or any idea for a fix/workaround?

Reported here.


问:
The reason to use masking
```<code>gcc 4.4.1 c89
</code>```

I am using a API that our previous programmer has produced. However, I am a bit confused as to why they do masking in this why.

What is the reason to OR the hex with a mask. And what would be the reason to have IPEV_ERROR_MASK OR'ed with IPEV_START. Why not have just the hex values?

```<code>#define IPEV_MASK               0x9000
#define IPEV_ERROR_MASK     (IPEV_MASK | 0x0800)
#define IPEV_OPEN               (IPEV_MASK | 0x01)
#define IPEV_START              (IPEV_MASK | 0x02)
#define IPEV_MEDIA_FAIL     (IPEV_ERROR_MASK | IPEV_START)
</code>```

Many thanks for any suggestions,

答:
Not really sure which part is unclear to you, so I'll explain everything.

First of all, they're obviously bit flags. Bit flags are a way of storing a lot of boolean values inside a single number. For instance, a typical 32-bit integer can store 32 boolean values. This has dual advantages of being very compact in memory, and being able to easily pass around several values at once. The drawback is, of course, that to access a single value you have to mess around with bitwise operators. Thus this approach is typically NOT used when dealing with boolean values in your code, but is often used when storing values or passing them around. Note also that while you physically could mash together every boolean value available, typically you only use this trick to group together related values (like status flags for an object or something).

Now, there are several traditions for working with bit flags. For one, you always define constants with the descriptive names for each bit. Otherwise it would get really awkward really fast. (Hmm... now what did bit 17 mean...)

For another, you always use the | operator to join together several flags, even though you could theoretically use the + operator. This again has two reasons: one reason is that | is faster than +, but more importantly, if you were to accidentally include the same flag twice, the | operator would provide the correct answer, while + would mess everything up.

This is a real danger, because in the world of bit flags it is often to see not only constants for each bit, but also constants for common combinations. With the | operator you can join these and be sure that the result will contain the bits you want, without worrying if you might have set the same bit twice.

Thus we come to your example:

```<code>#define IPEV_MASK               0x9000
#define IPEV_ERROR_MASK     (IPEV_MASK | 0x0800)
#define IPEV_OPEN               (IPEV_MASK | 0x01)
#define IPEV_START              (IPEV_MASK | 0x02)
#define IPEV_MEDIA_FAIL     (IPEV_ERROR_MASK | IPEV_START)
</code>```

Apparently we have some kind of "IPEV" bit mask field somewhere, and these are the named constants for its bits. The first constant is IPEV_MASK, which sets bits number 15 and 12. Then there is the constant IPEV_ERROR_MASK, which includes the IPEV_MASK, and in addition sets the bit 11. And so on and so forth.

The reason they are using these | operations to define the constants (instead of simply writing hex literals), is for readability. The compiler will anyway optimize them to fixed values, there won't be any bit calculations at runtime. But this style of writing lets you understand at a glance which constant includes what other constants. And, of course, if you were to ever modify one of them, the changes would automatically reflect where appropriate.

Did this make it clearer? If you have any more questions, don't hesitate to ask!

ContentLicense: CC BY-SA 2.5

Title: The reason to use masking

Body:
gcc 4.4.1 c89

I am using a API that our previous programmer has produced. However, I am a bit confused as to why they do masking in this why.

What is the reason to OR the hex with a mask. And what would be the reason to have IPEV_ERROR_MASK OR'ed with IPEV_START. Why not have just the hex values?

#define IPEV_MASK               0x9000
#define IPEV_ERROR_MASK     (IPEV_MASK | 0x0800)
#define IPEV_OPEN               (IPEV_MASK | 0x01)
#define IPEV_START              (IPEV_MASK | 0x02)
#define IPEV_MEDIA_FAIL     (IPEV_ERROR_MASK | IPEV_START)

Many thanks for any suggestions,

Body:
Not really sure which part is unclear to you, so I'll explain everything.

First of all, they're obviously bit flags. Bit flags are a way of storing a lot of boolean values inside a single number. For instance, a typical 32-bit integer can store 32 boolean values. This has dual advantages of being very compact in memory, and being able to easily pass around several values at once. The drawback is, of course, that to access a single value you have to mess around with bitwise operators. Thus this approach is typically NOT used when dealing with boolean values in your code, but is often used when storing values or passing them around. Note also that while you physically could mash together every boolean value available, typically you only use this trick to group together related values (like status flags for an object or something).

Now, there are several traditions for working with bit flags. For one, you always define constants with the descriptive names for each bit. Otherwise it would get really awkward really fast. (Hmm... now what did bit 17 mean...)

For another, you always use the | operator to join together several flags, even though you could theoretically use the + operator. This again has two reasons: one reason is that | is faster than +, but more importantly, if you were to accidentally include the same flag twice, the | operator would provide the correct answer, while + would mess everything up.

This is a real danger, because in the world of bit flags it is often to see not only constants for each bit, but also constants for common combinations. With the | operator you can join these and be sure that the result will contain the bits you want, without worrying if you might have set the same bit twice.

Thus we come to your example:

#define IPEV_MASK               0x9000
#define IPEV_ERROR_MASK     (IPEV_MASK | 0x0800)
#define IPEV_OPEN               (IPEV_MASK | 0x01)
#define IPEV_START              (IPEV_MASK | 0x02)
#define IPEV_MEDIA_FAIL     (IPEV_ERROR_MASK | IPEV_START)

Apparently we have some kind of "IPEV" bit mask field somewhere, and these are the named constants for its bits. The first constant is IPEV_MASK, which sets bits number 15 and 12. Then there is the constant IPEV_ERROR_MASK, which includes the IPEV_MASK, and in addition sets the bit 11. And so on and so forth.

The reason they are using these | operations to define the constants (instead of simply writing hex literals), is for readability. The compiler will anyway optimize them to fixed values, there won't be any bit calculations at runtime. But this style of writing lets you understand at a glance which constant includes what other constants. And, of course, if you were to ever modify one of them, the changes would automatically reflect where appropriate.

Did this make it clearer? If you have any more questions, don't hesitate to ask!


问:
How to pass a result from a function that requires GUI input (python)?
I'm writing a python script that takes user input through a GUI and then passes that along to a function that basically reads through text files and checks that what the user requested is there.  This function returns an array with True or False for each check.

I want to use this array in a different function (def markup()), but if I call it without giving the function the user input, I get an error.

Is there a way for me to store the results of this function and pass it without needing the user input each time?

Pseudo code:

```<code>def clickButton():

    userInput = [A,B,C,D,E]
    textCheck(userInput)

def textCheck(userInput):

    *code for checking text creates an array named allResults*
    return allResults

def markup():

    results = textCheck()
    print(results)
</code>```

答: I ended up calling markup(allResults) at the end of textChecker(). It worked.</p>

Body:
I'm writing a python script that takes user input through a GUI and then passes that along to a function that basically reads through text files and checks that what the user requested is there.  This function returns an array with True or False for each check.

I want to use this array in a different function (def markup()), but if I call it without giving the function the user input, I get an error.

Is there a way for me to store the results of this function and pass it without needing the user input each time?

Pseudo code:

def clickButton():

    userInput = [A,B,C,D,E]
    textCheck(userInput)

def textCheck(userInput):

    *code for checking text creates an array named allResults*
    return allResults

def markup():

    results = textCheck()
    print(results)


问:
Javascript - How do i submit a canvas in a form?
Basically my problem is that i have a canvas and i want to use the canvas in a form like if it were an image submitted in a input with a type of file, so i can access the $_FILES array..

The project i have made is an image cropping script where a user chose an image file through input type file, and then the script draw the image onto a canvas, then the user can zoom/crop the image... that all works perfectly fine..

But how can i send the cropped image to a php file as form file input data and access the $_FILES super global array?

I really hope someone can help

This link here tries to do something similar to me but i dont understand how it works, or how i could do the same with my project?

Javascript

```<code>            function convertCanvasToImage() {
                var temp_ctx, temp_canvas;
                temp_canvas = document.createElement('canvas');
                temp_ctx = temp_canvas.getContext('2d');
                temp_canvas.width = windowWidth;
                temp_canvas.height = windowWidth;
                temp_ctx.drawImage(ctx.canvas, cutoutWidth, cutoutWidth, windowWidth, windowWidth, 0, 0, windowWidth, windowWidth);

                var dataurl = temp_canvas.toDataURL("image/jpeg");
                croppedImage.src = dataurl;
                contentCall(dataurl);
            }

            function contentCall(profileImage) {
                var http = new XMLHttpRequest();
                var url = "ajax.php";
                var params = "profileImage=" + profileImage;
                http.open("POST", url, true);
                http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
                http.onreadystatechange = function () {
                    if (http.readyState === 4 && http.status === 200) {
                        alert(this.responseText);
                    }
                };
                http.send(params);
            }

            document.getElementById("myfiles").addEventListener("change", pullFiles, false);
            document.getElementById("scaleSlider").addEventListener("input", updateScale, false);
            document.getElementById("convert").addEventListener("click", convertCanvasToImage, false);
</code>```

UPDATE
I managed to solve the problem myself

```<code>                var multiPart = new FormData();
                var fileName = "pernille";
                multiPart.append('retard', 'christian');
                temp_canvas.toBlob(function(blob){
                    multiPart.append('blobTest', blob, fileName);
                    contentCall(multiPart);
                }, "image/jpg");
            }

            function contentCall(profileImage) {
                var http = new XMLHttpRequest();
                var url = "ajax.php";
                http.open("POST", url, true);
                http.onreadystatechange = function () {
                    if (http.readyState === 4 && http.status === 200) {
                        alert(this.responseText);
                    }
                };
                http.send(profileImage);
            }
</code>```

答:
You'll need to store the canvas (as an image) in a hidden form field as its value and then when you submit your form, the image will be submitted.</p>

```<code>// Save canvas as dataURL image
var dataURL = canvas.toDataURL('image/png');
</code>```

Body:
Basically my problem is that i have a canvas and i want to use the canvas in a form like if it were an image submitted in a input with a type of file, so i can access the $_FILES array..

The project i have made is an image cropping script where a user chose an image file through input type file, and then the script draw the image onto a canvas, then the user can zoom/crop the image... that all works perfectly fine..

But how can i send the cropped image to a php file as form file input data and access the $_FILES super global array?

I really hope someone can help

This link here tries to do something similar to me but i dont understand how it works, or how i could do the same with my project?

Javascript

            function convertCanvasToImage() {
                var temp_ctx, temp_canvas;
                temp_canvas = document.createElement('canvas');
                temp_ctx = temp_canvas.getContext('2d');
                temp_canvas.width = windowWidth;
                temp_canvas.height = windowWidth;
                temp_ctx.drawImage(ctx.canvas, cutoutWidth, cutoutWidth, windowWidth, windowWidth, 0, 0, windowWidth, windowWidth);

                var dataurl = temp_canvas.toDataURL("image/jpeg");
                croppedImage.src = dataurl;
                contentCall(dataurl);
            }

            function contentCall(profileImage) {
                var http = new XMLHttpRequest();
                var url = "ajax.php";
                var params = "profileImage=" + profileImage;
                http.open("POST", url, true);
                http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
                http.onreadystatechange = function () {
                    if (http.readyState === 4 && http.status === 200) {
                        alert(this.responseText);
                    }
                };
                http.send(params);
            }

            document.getElementById("myfiles").addEventListener("change", pullFiles, false);
            document.getElementById("scaleSlider").addEventListener("input", updateScale, false);
            document.getElementById("convert").addEventListener("click", convertCanvasToImage, false);

UPDATE
I managed to solve the problem myself

                var multiPart = new FormData();
                var fileName = "pernille";
                multiPart.append('retard', 'christian');
                temp_canvas.toBlob(function(blob){
                    multiPart.append('blobTest', blob, fileName);
                    contentCall(multiPart);
                }, "image/jpg");
            }

            function contentCall(profileImage) {
                var http = new XMLHttpRequest();
                var url = "ajax.php";
                http.open("POST", url, true);
                http.onreadystatechange = function () {
                    if (http.readyState === 4 && http.status === 200) {
                        alert(this.responseText);
                    }
                };
                http.send(profileImage);
            }

Body:
You'll need to store the canvas (as an image) in a hidden form field as its value and then when you submit your form, the image will be submitted.

// Save canvas as dataURL image
var dataURL = canvas.toDataURL('image/png');


问:
How to catch IOException in javafx
I'm trying to write data into a text file by pressing a button in JavaFx. The only problem, however is when I try to use the statement, "throws IOException" in my button processing method, things don't seem to work. Here is my code.

```<code>import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.stage.Stage;
import javafx.scene.Scene;
import javafx.scene.Group;
import javafx.scene.control.Button;
import java.io.*;
import java.io.File;
import java.io.FileInputStream;

public class testingFx extends Application{
//Create controls
private Button write;
private Scene main;
private Button Exit;
private Scene sceneMain;
private File records;
private FileWriter fw;

public static void main(String[] args){
   launch(args);
 }

@Override

public void start(Stage stage) throws IOException{

  //Create new file
  records = new File("records.txt");
  records.createNewFile();
  //Create FileWriter
  fw = new FileWriter(records);

  //Create root, format controls, scene, etc...
  Group root = new Group();
  write = new Button();
  write.setText("Write");
  write.setOnAction(this::processButtonPress);
  root.getChildren().addAll(write);
  main = new Scene(root,300,300);
  stage.setScene(main);
  stage.show();
}
   public void processButtonPress(ActionEvent event) throws IOException{
   if (event.getSource() == write){
        //On button press write to file
        fw.write("Testing file writing");
        //Close filewriter
        fw.close();
     }
  }
}
</code>```

I've tried to find the answer online but the way I was taught to handle a button press differs from most others examples (the section that says (this::processButtonPress)). I'm not sure if using a try/catch statement would help me here as I don't any experience with those, forgive me. The error I specifically am getting is "error: incompatible thrown types IOException in method reference". Thank you for your help.

I've tried to make this question on topic and easy to address. Please let me know if there are any glaring issues.

答:
I would recommend to use try-with-resources statement to have automatic closing of your writer.

Also you may implement action handler like this:

```<code>write.setOnAction(event -> {
    if (event.getSource() == write) {
        try {
            try (FileWriter fw = new FileWriter(records)) {
                //On button press write to file
                fw.write("Testing file writing");
            }
        } catch (IOException e) {
            // TODO process the exception properly
            e.printStackTrace();
        }
    }
});
</code>```

Title: How to catch IOException in javafx

Body:
I'm trying to write data into a text file by pressing a button in JavaFx. The only problem, however is when I try to use the statement, "throws IOException" in my button processing method, things don't seem to work. Here is my code.

import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.stage.Stage;
import javafx.scene.Scene;
import javafx.scene.Group;
import javafx.scene.control.Button;
import java.io.*;
import java.io.File;
import java.io.FileInputStream;

public class testingFx extends Application{
//Create controls
private Button write;
private Scene main;
private Button Exit;
private Scene sceneMain;
private File records;
private FileWriter fw;

public static void main(String[] args){
   launch(args);
 }

@Override

public void start(Stage stage) throws IOException{

  //Create new file
  records = new File("records.txt");
  records.createNewFile();
  //Create FileWriter
  fw = new FileWriter(records);

  //Create root, format controls, scene, etc...
  Group root = new Group();
  write = new Button();
  write.setText("Write");
  write.setOnAction(this::processButtonPress);
  root.getChildren().addAll(write);
  main = new Scene(root,300,300);
  stage.setScene(main);
  stage.show();
}
   public void processButtonPress(ActionEvent event) throws IOException{
   if (event.getSource() == write){
        //On button press write to file
        fw.write("Testing file writing");
        //Close filewriter
        fw.close();
     }
  }
}

I've tried to find the answer online but the way I was taught to handle a button press differs from most others examples (the section that says (this::processButtonPress)). I'm not sure if using a try/catch statement would help me here as I don't any experience with those, forgive me. The error I specifically am getting is "error: incompatible thrown types IOException in method reference". Thank you for your help.

I've tried to make this question on topic and easy to address. Please let me know if there are any glaring issues.

Body:
I would recommend to use try-with-resources statement to have automatic closing of your writer.

Also you may implement action handler like this:

write.setOnAction(event -> {
    if (event.getSource() == write) {
        try {
            try (FileWriter fw = new FileWriter(records)) {
                //On button press write to file
                fw.write("Testing file writing");
            }
        } catch (IOException e) {
            // TODO process the exception properly
            e.printStackTrace();
        }
    }
});


答:
Just use

```<code>#!/usr/bin/perl
</code>```

(Or, optionally, whatever the path to perl is on your development machine.)

When Module::Build or MakeMaker installs your script, it will change the #! line to match the perl that is installing the module.  It will also add the "eval exec" lines, except under Windows, where it will create a .bat file instead.  (The CPAN client has nothing to do with this.)

If you use

```<code>#!/usr/bin/env perl
</code>```

then the installers won't realize that's a Perl script, and will not modify the #! line.

Title: What is the recommended way to package perl scripts for CPAN (and CorporatePAN)?

Body:
Recently I looked at a module on CPAN that comes with a script to be installed
which made me wonder. What is the recommended way to include a script in a package
that should end up on the public CPAN and if there is any different recommendation for
packages that would be released on an in-house CPAN server?

The script starts like this:

#!/usr/bin/perl

eval 'exec /usr/bin/perl  -S $0 ${1+"$@"}'
  if 0; # not running under some shell

Two questions

Do I understand correctly the eval part is unnecessary?
That will be embedded by the CPAN client during installation and it
will be very different when installing on Windows.

What is the recommended sh-bang line?
Would that be

#!/usr/bin/env perl

instead of the above?

Body:
Just use

#!/usr/bin/perl

(Or, optionally, whatever the path to perl is on your development machine.)

When Module::Build or MakeMaker installs your script, it will change the #! line to match the perl that is installing the module.  It will also add the "eval exec" lines, except under Windows, where it will create a .bat file instead.  (The CPAN client has nothing to do with this.)

If you use

#!/usr/bin/env perl

then the installers won't realize that's a Perl script, and will not modify the #! line.


问:
How can I make Flask work with Python 3?
I have written an API in my personal machine and I want to make it run on a remote machine.

I have used Python 3 and flask with Pycharmm without any problems in my own machine. However I connect the remote machine using ssh. So it's impossible to configure environment with an IDE.

When I type flask --version the output is as below:

```<code>Flask 0.12.2
Python 2.7.12 (default, Jul  1 2016, 15:12:24)
[GCC 5.4.0 20160609]
</code>```

Python 3 is installed. I have a choice to run the python script using python3 service.py. At that time I am given an error as ImportError: No module named 'flask'. When I use flask run I am given errors related to Python 2. I have used some features of Python 3 which are not included in Python 2.

How can I configure Flask to run using Python 3 in that environment?

答:
Try pip3 install flask. Ideally you should be doing this in a virtual environment. Also, you might want to look at dockerizing your code since it will help reduce conflict between different python versions.

As an addition I have installed the pip3 using apt-get install
  python3-pip

Body:
I have written an API in my personal machine and I want to make it run on a remote machine.

I have used Python 3 and flask with Pycharmm without any problems in my own machine. However I connect the remote machine using ssh. So it's impossible to configure environment with an IDE.

When I type flask --version the output is as below:

Flask 0.12.2
Python 2.7.12 (default, Jul  1 2016, 15:12:24)
[GCC 5.4.0 20160609]

Python 3 is installed. I have a choice to run the python script using python3 service.py. At that time I am given an error as ImportError: No module named 'flask'. When I use flask run I am given errors related to Python 2. I have used some features of Python 3 which are not included in Python 2.

How can I configure Flask to run using Python 3 in that environment?


问:
I want to save GeoJSON polygon
I want to save a polygon.

This is Geojson enter link description here

```<code>str1 = "geojson....."
geom = RGeo::GeoJSON.decode(str1, json_parser: :json)
l = Limit.new
l.multipoligono = geom
l.save

NoMethodError: undefined methodfactory' for #RGeo::GeoJSON::FeatureCollection:0x3fc7febb7424`
</code>```

This is my rgeo.rb

```<code>RGeo::ActiveRecord::SpatialFactoryStore.instance.tap do |config|
config.default = RGeo::Geos.factory_generator
config.register(RGeo::Geographic.spherical_factory(srid: 4326), geo_type: "point")
config.register(RGeo::Geographic.spherical_factory(srid: 4326), geo_type: "multi_polygon")
config.register(RGeo::Geographic.spherical_factory(srid: 4326), geo_type: "geometry_collection")

end
</code>```

答:
With 110 stars, I think this is how they do it in ruby.

```<code>hash = RGeo::GeoJSON.encode(feature)
hash.to_json == str2      # => true
</code>```

That said, I wouldn't do that. I also wouldn't use Ruby. Check out PostGIS's ST_AsGeoJSON. It returns the feature part of geojson. That is to say, cut RGeo out of the equation.

Title: I want to save GeoJSON polygon

Body:
I want to save a polygon.

This is Geojson enter link description here

str1 = "geojson....."
geom = RGeo::GeoJSON.decode(str1, json_parser: :json)
l = Limit.new
l.multipoligono = geom
l.save

NoMethodError: undefined methodfactory' for #RGeo::GeoJSON::FeatureCollection:0x3fc7febb7424`

This is my rgeo.rb

RGeo::ActiveRecord::SpatialFactoryStore.instance.tap do |config|
config.default = RGeo::Geos.factory_generator
config.register(RGeo::Geographic.spherical_factory(srid: 4326), geo_type: "point")
config.register(RGeo::Geographic.spherical_factory(srid: 4326), geo_type: "multi_polygon")
config.register(RGeo::Geographic.spherical_factory(srid: 4326), geo_type: "geometry_collection")

end

Body:
With 110 stars, I think this is how they do it in ruby.

hash = RGeo::GeoJSON.encode(feature)
hash.to_json == str2      # => true

That said, I wouldn't do that. I also wouldn't use Ruby. Check out PostGIS's ST_AsGeoJSON. It returns the feature part of geojson. That is to say, cut RGeo out of the equation.


问:
Java GZipInputStream unexpected end of ZLib input stream
For reference, here is the complete error I am getting:

```<code>    java.io.EOFException: Unexpected end of ZLIB input stream
at java.util.zip.InflaterInputStream.fill(InflaterInputStream.java:240)
at java.util.zip.InflaterInputStream.read(InflaterInputStream.java:158)
at java.util.zip.GZIPInputStream.read(GZIPInputStream.java:117)
at java.io.FilterInputStream.read(FilterInputStream.java:107)
at com.genomedownloader.Main.FTPGet(Main.java:245)
at com.genomedownloader.Main.access$400(Main.java:28)
at com.genomedownloader.Main$1.call(Main.java:494)
at com.genomedownloader.Main$1.call(Main.java:468)
at javafx.concurrent.Task$TaskCallable.call(Task.java:1423)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at java.lang.Thread.run(Thread.java:
</code>```

I just switched my program from using FTP4J as a Java FTP client to Apache FTPClient. I tweaked my download code so that Apache would work, now I get this exception when I try to unzip the *.gz files the program downloads.
Here is the relevant code:

```<code> package com.test;

 import org.apache.commons.net.ftp.FTPClient;

 import java.io.*;
 import java.util.zip.GZIPInputStream;

 public class Main {
public static void main(String[] args) throws IOException {
    FTPClient client;
    client = new FTPClient();
    client.connect("ftp.ncbi.nlm.nih.gov");
    client.login("anonymous", "abc123");
    client.setControlKeepAliveTimeout(300 * 60000);
    client.changeWorkingDirectory("/genomes/all/GCF/000/334/875/GCF_000334875.1_ASM33487v1");
    client.retrieveFile("GCF_000334875.1_ASM33487v1_genomic.fna.gz", new BufferedOutputStream(new FileOutputStream(new File(System.getProperty("user.dir") + "\\GenomicFNA.gz"))));
    GZIPInputStream gzipInputStream = new GZIPInputStream(new FileInputStream(System.getProperty("user.dir") + "\\GenomicFNA.gz"));
    OutputStream out = new FileOutputStream(System.getProperty("user.dir") + "\\GenomicFNA.fsa");
    byte[] buf = new byte[1024];
    int len;
    while ((len = gzipInputStream.read(buf)) > 0) {
        out.write(buf, 0, len);
    }
    gzipInputStream.close();
    out.close();
    client.logout();
    client.disconnect();
}
}
</code>```

What I can't figure out for the life of me is WHY the code works with FTP4J but then fails with Apache, despite the code using nothing from Apache nor FTP4j libraries... Run the above code with Apache commons net, and it should work. (Work as in give the error at the top)

答:
Change the BufferedOutputStream to separate declaration, and change the FileOutputStream likewise, then flush and close both of them before the GZip declaration. Completed code:</p>

```<code>  package com.test;

   import org.apache.commons.net.ftp.FTPClient;

  import java.io.*;
  import java.util.zip.GZIPInputStream;

public class Main {
public static void main(String[] args) throws IOException {
    BufferedOutputStream streamy;
    FileOutputStream stream;
    FTPClient client;
    client = new FTPClient();
    client.connect("ftp.ncbi.nlm.nih.gov");
    client.login("anonymous", "abc123");
    client.setControlKeepAliveTimeout(300 * 60000);
    client.changeWorkingDirectory("/genomes/all/GCF/000/334/875/GCF_000334875.1_ASM33487v1");
    client.retrieveFile("GCF_000334875.1_ASM33487v1_genomic.fna.gz", streamy = new BufferedOutputStream(stream = new FileOutputStream(new File(System.getProperty("user.dir") + "\\GenomicFNA.gz"))));
    stream.flush();
    streamy.flush();
    stream.close();
    streamy.close();
    client.logout();
    client.disconnect();
    GZIPInputStream gzipInputStream = new GZIPInputStream(new FileInputStream(System.getProperty("user.dir") + "\\GenomicFNA.gz"));
    OutputStream out = new FileOutputStream(System.getProperty("user.dir") + "\\GenomicFNA.fsa");
    byte[] buf = new byte[1024];
    int len;
    while ((len = gzipInputStream.read(buf)) > 0) {
        out.write(buf, 0, len);
    }
    gzipInputStream.close();
    out.close();

}
}
</code>```

Body:
For reference, here is the complete error I am getting:

    java.io.EOFException: Unexpected end of ZLIB input stream
at java.util.zip.InflaterInputStream.fill(InflaterInputStream.java:240)
at java.util.zip.InflaterInputStream.read(InflaterInputStream.java:158)
at java.util.zip.GZIPInputStream.read(GZIPInputStream.java:117)
at java.io.FilterInputStream.read(FilterInputStream.java:107)
at com.genomedownloader.Main.FTPGet(Main.java:245)
at com.genomedownloader.Main.access$400(Main.java:28)
at com.genomedownloader.Main$1.call(Main.java:494)
at com.genomedownloader.Main$1.call(Main.java:468)
at javafx.concurrent.Task$TaskCallable.call(Task.java:1423)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at java.lang.Thread.run(Thread.java:

I just switched my program from using FTP4J as a Java FTP client to Apache FTPClient. I tweaked my download code so that Apache would work, now I get this exception when I try to unzip the *.gz files the program downloads.
Here is the relevant code:

 package com.test;

 import org.apache.commons.net.ftp.FTPClient;

 import java.io.*;
 import java.util.zip.GZIPInputStream;

 public class Main {
public static void main(String[] args) throws IOException {
    FTPClient client;
    client = new FTPClient();
    client.connect("ftp.ncbi.nlm.nih.gov");
    client.login("anonymous", "abc123");
    client.setControlKeepAliveTimeout(300 * 60000);
    client.changeWorkingDirectory("/genomes/all/GCF/000/334/875/GCF_000334875.1_ASM33487v1");
    client.retrieveFile("GCF_000334875.1_ASM33487v1_genomic.fna.gz", new BufferedOutputStream(new FileOutputStream(new File(System.getProperty("user.dir") + "\\GenomicFNA.gz"))));
    GZIPInputStream gzipInputStream = new GZIPInputStream(new FileInputStream(System.getProperty("user.dir") + "\\GenomicFNA.gz"));
    OutputStream out = new FileOutputStream(System.getProperty("user.dir") + "\\GenomicFNA.fsa");
    byte[] buf = new byte[1024];
    int len;
    while ((len = gzipInputStream.read(buf)) > 0) {
        out.write(buf, 0, len);
    }
    gzipInputStream.close();
    out.close();
    client.logout();
    client.disconnect();
}
}

What I can't figure out for the life of me is WHY the code works with FTP4J but then fails with Apache, despite the code using nothing from Apache nor FTP4j libraries... Run the above code with Apache commons net, and it should work. (Work as in give the error at the top)

Body:
Change the BufferedOutputStream to separate declaration, and change the FileOutputStream likewise, then flush and close both of them before the GZip declaration. Completed code:

  package com.test;

   import org.apache.commons.net.ftp.FTPClient;

  import java.io.*;
  import java.util.zip.GZIPInputStream;

public class Main {
public static void main(String[] args) throws IOException {
    BufferedOutputStream streamy;
    FileOutputStream stream;
    FTPClient client;
    client = new FTPClient();
    client.connect("ftp.ncbi.nlm.nih.gov");
    client.login("anonymous", "abc123");
    client.setControlKeepAliveTimeout(300 * 60000);
    client.changeWorkingDirectory("/genomes/all/GCF/000/334/875/GCF_000334875.1_ASM33487v1");
    client.retrieveFile("GCF_000334875.1_ASM33487v1_genomic.fna.gz", streamy = new BufferedOutputStream(stream = new FileOutputStream(new File(System.getProperty("user.dir") + "\\GenomicFNA.gz"))));
    stream.flush();
    streamy.flush();
    stream.close();
    streamy.close();
    client.logout();
    client.disconnect();
    GZIPInputStream gzipInputStream = new GZIPInputStream(new FileInputStream(System.getProperty("user.dir") + "\\GenomicFNA.gz"));
    OutputStream out = new FileOutputStream(System.getProperty("user.dir") + "\\GenomicFNA.fsa");
    byte[] buf = new byte[1024];
    int len;
    while ((len = gzipInputStream.read(buf)) > 0) {
        out.write(buf, 0, len);
    }
    gzipInputStream.close();
    out.close();

}
}


问:
Jetty 7 hightide distribution, JSP and JSTL support
I've been struggling with Jetty 7 and its support for JSP and JSTL.

My JSP file:

```<code><%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

<head>
  <title>blah</title>
</head>
<body>
  <table id="data">
    <tr class="columns">
      <td>Hour</td>
      <c:forEach var="campaign" items="${campaigns}">
        <td>${campaign}</td>
      </c:forEach>
    </tr>

    <c:forEach var="hour" items="${results}">
      <tr>
        <td class="hour">${hour.key}</td>
        <c:forEach var="campaign" items="${campaigns}">
          <td>${hour[campaign]}</td>
        </c:forEach>
      </tr>
     </c:forEach>
  </table>
</body>
</html>
</code>```

The JSP portions above work as expected. JSTL, however, does not. The campaigns and results variables are request attributes set by a servlet.

I get the following errors:

```<code>WARN: ... compiler.TagLibraryInfoImpl: Unknown element (deferred-value) in attribute
WARN: ... compiler.TagLibraryInfoImpl: Unknown element (deferred-value) in attribute
WARN: ... compiler.TagLibraryInfoImpl: Unknown element (deferred-value) in attribute
ERROR: ... javax.servlet.ServletException: java.lang.AbstractMethodError: javax.servlet.jsp.PageContext.getELContext()Ljavax/el/ELContext;
</code>```

I am not bundling any jar files into my .war file deployed to jetty.

The version of jetty I'm using is: jetty-hightide-7.0.1.v20091125

The classpath:

```<code>/usr/local/jetty/lib/jetty-xml-7.0.1.v20091125.jar:/usr/local/jetty/lib/servlet-api-2.5.jar:/usr/local/jetty/lib/jetty-http-7.0.1.v20091125.jar:/usr/local/jetty/lib/jetty-continuation-7.0.1.v20091125.jar:/usr/local/jetty/lib/jetty-server-7.0.1.v20091125.jar:/usr/local/jetty/lib/jetty-security-7.0.1.v20091125.jar:/usr/local/jetty/lib/jetty-servlet-7.0.1.v20091125.jar:/usr/local/jetty/lib/jetty-webapp-7.0.1.v20091125.jar:/usr/local/jetty/lib/jetty-deploy-7.0.1.v20091125.jar:/usr/local/jetty/lib/jetty-servlets-7.0.1.v20091125.jar:/usr/local/jetty/lib/jsp/ant-1.6.5.jar:/usr/local/jetty/lib/jsp/core-3.1.1.jar:/usr/local/jetty/lib/jsp/jetty-jsp-2.1-7.0.1.v20091125.jar:/usr/local/jetty/lib/jsp/jsp-2.1-glassfish-9.1.1.B60.25.p2.jar:/usr/local/jetty/lib/jsp/jsp-api-2.1-glassfish-9.1.1.B60.25.p2.jar:/usr/local/jetty/resources:/usr/local/jetty/lib/jetty-util-7.0.1.v20091125.jar:/usr/local/jetty/lib/jetty-io-7.0.1.v20091125.jar
</code>```

Any help would be greatly appreciated.

Thanks in advance,

Lior.

答:
tsk... I don;t have privilege to comment. I am using Jetty 7.1.6 and answer provided by bmargulies works.

Basically, changing URI from

```<code><%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
</code>```

to

```<code><%@ taglib uri="http://java.sun.com/jstl/core" prefix="c" %>
</code>```

makes taglibs to work in Jetty 7.

-Nishant

Body:
I've been struggling with Jetty 7 and its support for JSP and JSTL.

My JSP file:

<%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

  <title>blah</title>

      Hour
      <c:forEach var="campaign" items="${campaigns}">
        ${campaign}
      </c:forEach>

    <c:forEach var="hour" items="${results}">

        ${hour.key}
        <c:forEach var="campaign" items="${campaigns}">
          ${hour[campaign]}
        </c:forEach>

     </c:forEach>

The JSP portions above work as expected. JSTL, however, does not. The campaigns and results variables are request attributes set by a servlet.

I get the following errors:

WARN: ... compiler.TagLibraryInfoImpl: Unknown element (deferred-value) in attribute
WARN: ... compiler.TagLibraryInfoImpl: Unknown element (deferred-value) in attribute
WARN: ... compiler.TagLibraryInfoImpl: Unknown element (deferred-value) in attribute
ERROR: ... javax.servlet.ServletException: java.lang.AbstractMethodError: javax.servlet.jsp.PageContext.getELContext()Ljavax/el/ELContext;

I am not bundling any jar files into my .war file deployed to jetty.

The version of jetty I'm using is: jetty-hightide-7.0.1.v20091125

The classpath:

/usr/local/jetty/lib/jetty-xml-7.0.1.v20091125.jar:/usr/local/jetty/lib/servlet-api-2.5.jar:/usr/local/jetty/lib/jetty-http-7.0.1.v20091125.jar:/usr/local/jetty/lib/jetty-continuation-7.0.1.v20091125.jar:/usr/local/jetty/lib/jetty-server-7.0.1.v20091125.jar:/usr/local/jetty/lib/jetty-security-7.0.1.v20091125.jar:/usr/local/jetty/lib/jetty-servlet-7.0.1.v20091125.jar:/usr/local/jetty/lib/jetty-webapp-7.0.1.v20091125.jar:/usr/local/jetty/lib/jetty-deploy-7.0.1.v20091125.jar:/usr/local/jetty/lib/jetty-servlets-7.0.1.v20091125.jar:/usr/local/jetty/lib/jsp/ant-1.6.5.jar:/usr/local/jetty/lib/jsp/core-3.1.1.jar:/usr/local/jetty/lib/jsp/jetty-jsp-2.1-7.0.1.v20091125.jar:/usr/local/jetty/lib/jsp/jsp-2.1-glassfish-9.1.1.B60.25.p2.jar:/usr/local/jetty/lib/jsp/jsp-api-2.1-glassfish-9.1.1.B60.25.p2.jar:/usr/local/jetty/resources:/usr/local/jetty/lib/jetty-util-7.0.1.v20091125.jar:/usr/local/jetty/lib/jetty-io-7.0.1.v20091125.jar

Any help would be greatly appreciated.

Thanks in advance,

Lior.

Body:
tsk... I don;t have privilege to comment. I am using Jetty 7.1.6 and answer provided by bmargulies works.

Basically, changing URI from

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>

to

<%@ taglib uri="http://java.sun.com/jstl/core" prefix="c" %>

makes taglibs to work in Jetty 7.

-Nishant


问:
Matching a result in c#
I have the following string

```<code>background-image: url('https://s3-eu-west-1.amazonaws.com/files.domain.com/uploads/image/file/168726/carousel_IMG_6455.jpg')
</code>```

and I just want to get the image URL.

My code is:

```<code>image = image.Replace(@"'", "\"");
Match match = Regex.Match(image, @"'([^']*)");
</code>```

Match.Success returns nothing, so I can not get the image URL.

Is there something missing? This used to work but not now.

答:
The regex of: (\".*\")

Will match the URL given the input string:
background-image: url("https://s3-eu-west-1.amazonaws.com/files.domain.com/uploads/image/file/168726/carousel_IMG_6455.jpg")

```<code>image = image.Replace(@"'", "\"");
Match match = Regex.Match(image, "(\\\".*\\\")");
</code>```

Edit:
If you are looking for something that will match pairs of single quotes or double quotes you could use:

```<code>(\".*\"|'.*')

Match match = Regex.Match(image, "(\\\".*\\\"|'.*')");
</code>```

Title: Matching a result in c#

Body:
I have the following string

background-image: url('https://s3-eu-west-1.amazonaws.com/files.domain.com/uploads/image/file/168726/carousel_IMG_6455.jpg')

and I just want to get the image URL.

My code is:

image = image.Replace(@"'", "\"");
Match match = Regex.Match(image, @"'([^']*)");

Match.Success returns nothing, so I can not get the image URL.

Is there something missing? This used to work but not now.

Body:
The regex of: (\".*\")

Will match the URL given the input string:
background-image: url("https://s3-eu-west-1.amazonaws.com/files.domain.com/uploads/image/file/168726/carousel_IMG_6455.jpg")

image = image.Replace(@"&#39;", "\"");
Match match = Regex.Match(image, "(\\\".*\\\")");

Edit:
If you are looking for something that will match pairs of single quotes or double quotes you could use:

(\".*\"|'.*')

Match match = Regex.Match(image, "(\\\".*\\\"|'.*')");


问:
how I extract field from xml string in java / scala
I have following as a string and I want to get values from it like response code and response message how I can get that</p>

```<code><soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:tns="https://exa.org/UpdateOrder/">
<soapenv:Body>
<tns:UpdateResponse xmlns="https://exa.org/UpdateOrder/">
<tns:responseCode>0</tns:responseCode>
<tns:responseMessage/>
</tns:UpdateResponse>
</soapenv:Body>
</soapenv:Envelope>
</code>```

答:
The standard scala xml library could make short work of it: The standard Scala XML library

Check out scala String to scala.xml.Elem to convert the string to an scala xml element.

Then you can navigate and parse the xml tree using xpath like sequences in the scala xml library.  Something like this:

```<code>val xmlNode = scala.xml.XML.loadString(string)
val responseCode = (xmlNode \ "Body" \ "UpdateResponse" \ "responseCode").text
</code>```

Body:
I have following as a string and I want to get values from it like response code and response message how I can get that

<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:tns="https://exa.org/UpdateOrder/">
<soapenv:Body>
<tns:UpdateResponse xmlns="https://exa.org/UpdateOrder/">
<tns:responseCode>0</tns:responseCode>
<tns:responseMessage/>
</tns:UpdateResponse>
</soapenv:Body>
</soapenv:Envelope>

Body:
The standard scala xml library could make short work of it: The standard Scala XML library

Check out scala String to scala.xml.Elem to convert the string to an scala xml element.

Then you can navigate and parse the xml tree using xpath like sequences in the scala xml library.  Something like this:

val xmlNode = scala.xml.XML.loadString(string)
val responseCode = (xmlNode \ "Body" \ "UpdateResponse" \ "responseCode").text