问:
How could you retrieve a method's POD from inside a REPL or debugger?
I would like to be able to see the documentation of a method/function when using it inside REPL or debuger.

Is there any module that allow you to see the documentation of a function when using REPL or  a debuger?.

Obviously if that module exist it would ask you to have your POD and code with a parseable structure in order to extract the docs. That is not a problem because I have all my code documented and I can adapt to whatever is needed. Currently I have all my methods with a preceding POD with a =head2 method_name and the typical lines for name, usage, example, args, return, exeptions etc

The typical example is when you are in the debuger (or REPL) and you want to use a function and you don't remember the order of arguments or their types, or the type of the return element or you want a hint for the usage.

I would like to have something like get_pod($moudle_bar, $method_foo), or even better being able to put a get_pod in a base module and being able to say $bar->get_pod('foo'). I know that this is not trivial and has a lot of corner cases. This is the reason that I am asking about a method-POD extractor module.

I want to show the output inside the REPL or debuger so any pointer to an anchored html-pod in a browser is not convenient for me.

It could be that there is something much more simple and I am obfuscated.

My first brute force and expensive approach:

```<code>> $self = new MyModule
> m $self # to see the available methods for double check the spelling
> # method wanted '_connect_db'
> $cmd = 'perldoc -t ' . ref($self)
> x qx{$cmd}=~/(_connect_db.*?)\n\n/msg
</code>```

```
0  '_connect_db
     Title   : _connect_db
     Usage   :
     Function: create a database conection and return the handler
     Example : $dbh = $self->_connect_db($user, $pass, $db_name) # host is FPrefect by default
     Returns : [0] DBI $dbh object
     Args    :
                [0] $user,
                [1] $pass,
                [2] $db_name,
                [3] $host,
                [4] $db_brand # mysql, sqlite
                [5] $mode = (ro, rw) # not used now. in the future it would use this for read the user and password'
```

Obviously this works because I know that I don't have any empty lines in my method description PODs so I use .*?)\n\n in the regex to capture the rest of the method POD.

Do someone have any good suggestion or advice for this task?

UPDATE:

Following snoopy suggestions I have taken a look at Pod::Coverage source code and I found that Pod::Coverage::Extractor (a package inside the file for Pod::Coverage) has the method command that look for Pods  Item or head elements and extract them. I will take a look how to retrieve this items.

```<code># package Pod::Coverage::Extractor
#extract subnames from a pod stream
sub command {
    my $self = shift;
    my ( $command, $text, $line_num ) = @_;
    if ( $command eq 'item' || $command =~ /^head(?:2|3|4)/ ) {

        # take a closer look
        my @pods = ( $text =~ /\s*([^\s\|,\/]+)/g );
        $self->{recent} = [];

        foreach my $pod (@pods) {
            print "Considering: '$pod'\n" if debug;

            # it's dressed up like a method cal
            $pod =~ /-E<\s*gt\s*>(.*)/ and $pod = $1;
            $pod =~ /->(.*)/           and $pod = $1;

            # it's used as a (bare) fully qualified name
            $pod =~ /\w+(?:::\w+)*::(\w+)/ and $pod = $1;

            # it's wrapped in a pod style B<>
            $pod =~ s/[A-Z]<//g;
            $pod =~ s/>//g;

            # has arguments, or a semicolon
            $pod =~ /(\w+)\s*[;\(]/ and $pod = $1;

            print "Adding: '$pod'\n" if debug;
            push @{ $self->{ $self->{nonwhitespace}
                    ? "recent"
                    : "identifiers" } }, $pod;
        }
    }
</code>```

UPDATE 2

Another place from where to take info is pdoc. This script generates html for browsing APIs and I use it in Ensembl and BioPerl. I am sure I will learn something reading the source code.

答: PDL's interactive shell (perldl) lets you read PDL's docs with the ? and ?? commands, perhaps something like that can be done for REPL.

Body:
I would like to be able to see the documentation of a method/function when using it inside REPL or debuger.

Is there any module that allow you to see the documentation of a function when using REPL or  a debuger?.

Obviously if that module exist it would ask you to have your POD and code with a parseable structure in order to extract the docs. That is not a problem because I have all my code documented and I can adapt to whatever is needed. Currently I have all my methods with a preceding POD with a =head2 method_name and the typical lines for name, usage, example, args, return, exeptions etc

The typical example is when you are in the debuger (or REPL) and you want to use a function and you don't remember the order of arguments or their types, or the type of the return element or you want a hint for the usage.

I would like to have something like get_pod($moudle_bar, $method_foo), or even better being able to put a get_pod in a base module and being able to say $bar->get_pod('foo'). I know that this is not trivial and has a lot of corner cases. This is the reason that I am asking about a method-POD extractor module.

I want to show the output inside the REPL or debuger so any pointer to an anchored html-pod in a browser is not convenient for me.

It could be that there is something much more simple and I am obfuscated.

My first brute force and expensive approach:

> $self = new MyModule
> m $self # to see the available methods for double check the spelling
> # method wanted '_connect_db'
> $cmd = 'perldoc -t ' . ref($self)
> x qx{$cmd}=~/(_connect_db.*?)\n\n/msg

0  '_connect_db
     Title   : _connect_db
     Usage   :
     Function: create a database conection and return the handler
     Example : $dbh = $self->_connect_db($user, $pass, $db_name) # host is FPrefect by default
     Returns : [0] DBI $dbh object
     Args    :
                [0] $user,
                [1] $pass,
                [2] $db_name,
                [3] $host,
                [4] $db_brand # mysql, sqlite
                [5] $mode = (ro, rw) # not used now. in the future it would use this for read the user and password'

Obviously this works because I know that I don't have any empty lines in my method description PODs so I use .*?)\n\n in the regex to capture the rest of the method POD.

Do someone have any good suggestion or advice for this task?

UPDATE:

Following snoopy suggestions I have taken a look at Pod::Coverage source code and I found that Pod::Coverage::Extractor (a package inside the file for Pod::Coverage) has the method command that look for Pods  Item or head elements and extract them. I will take a look how to retrieve this items.

# package Pod::Coverage::Extractor
#extract subnames from a pod stream
sub command {
    my $self = shift;
    my ( $command, $text, $line_num ) = @_;
    if ( $command eq 'item' || $command =~ /^head(?:2|3|4)/ ) {

        # take a closer look
        my @pods = ( $text =~ /\s*([^\s\|,\/]+)/g );
        $self->{recent} = [];

        foreach my $pod (@pods) {
            print "Considering: '$pod'\n" if debug;

            # it's dressed up like a method cal
            $pod =~ /-E<\s*gt\s*>(.*)/ and $pod = $1;
            $pod =~ /->(.*)/           and $pod = $1;

            # it's used as a (bare) fully qualified name
            $pod =~ /\w+(?:::\w+)*::(\w+)/ and $pod = $1;

            # it's wrapped in a pod style B<>
            $pod =~ s/[A-Z]<//g;
            $pod =~ s/>//g;

            # has arguments, or a semicolon
            $pod =~ /(\w+)\s*[;\(]/ and $pod = $1;

            print "Adding: '$pod'\n" if debug;
            push @{ $self->{ $self->{nonwhitespace}
                    ? "recent"
                    : "identifiers" } }, $pod;
        }
    }

UPDATE 2

Another place from where to take info is pdoc. This script generates html for browsing APIs and I use it in Ensembl and BioPerl. I am sure I will learn something reading the source code.


来源: stackexchange

问:
What does it mean that something is transitive in programming?
What does it mean that something is transitive with regard to programming? An example is the following (from here):

Using-directives are transitive for the purposes of unqualified
  lookup:

I am aware of the elaboration of this particular statement, however, I am striving for a more general programming related explanation.

答:
A binary relationship ~ is transitive if and only if a ~ b and b ~ c implies a ~ c.

(For instance, "is taller than" is transitive; "lives next door to" isn't.)

In this special case, A is using B, and B is using C, and it has the same effect as A using C directly.

ContentLicense: CC BY-SA 3.0


问:
$.parseJSON(data).shift is not a function
i have to parsing json data get from $post method

```<code>$.post( "vehicle_route_qry.php",function(data) {

    siteshistory = $.parseJSON(data);
    siteshistory.shift();
    draw_route(siteshistory);
    $("#dev_det_spin").hide();

});
</code>```

my php file

```<code>$myJSON = '{ "name":"John", "age":31, "city":"New York" }';
echo json_encode($myJSON);
</code>```

i am getting json properly in my response
but getting this issue

```<code>siteshistory.shift is not a function
</code>```

i have loaded following js files

```<code><script src="js/function.js"></script>
<script src="js/jquery.min.js"></script>
<script src="https://developers.google.com/maps/documentation/javascript/examples/markerclusterer/markerclusterer.js">
</script>
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyDaL0ieAkLhzy1rDoLifajeowdXPwTvzmI"></script>
<!-- <script type="text/javascript" src="js/date.js"></script> -->
<script type="text/javascript" src="js/loader.js"></script>
<script type="text/javascript" src="js/header_function.js"></script>
</code>```

but shift function for  $.parseJSON(data).shift() is not working
i am not able to find any reference regarding shift function

suggestion would be helpful

答:
Use </p>

```<code>`"delete siteshistory.name"`;
</code>```

<p>instead of </p>

```<code>"siteshistory.shift()";
</code>```

Body:
i have to parsing json data get from $post method

$.post( "vehicle_route_qry.php",function(data) {

    siteshistory = $.parseJSON(data);
    siteshistory.shift();
    draw_route(siteshistory);
    $("#dev_det_spin").hide();

});

my php file

$myJSON = '{ "name":"John", "age":31, "city":"New York" }';
echo json_encode($myJSON);

i am getting json properly in my response
but getting this issue

siteshistory.shift is not a function

i have loaded following js files

but shift function for  $.parseJSON(data).shift() is not working
i am not able to find any reference regarding shift function

suggestion would be helpful

Body:
Use

`"delete siteshistory.name"`;

instead of

"siteshistory.shift()";


问:
JS button event with redirect (Sonata Admin)
I'm using Sonata Admin for my project and I have a SweetAlert 2 on $('button[type="submit"]') event.

The problem is that initially I'm using preventDefault() to keep form alive, then I'm trying to submit form with $(form).submit() but I'm redirected to the same EDIT page even if I click on "Update & Close" page.

FYI: Sonata has 2 possibilities:'Update' & 'Update and close'. First one is updating entity and redirect you to the same page, the other one, is updating entity and redirecting you to listing page.

```<code>$('button[type="submit"]').click(function (e) {
    var currentStatus = $('#' + adminUniqueId + '_status option:selected').val();
    var exitDate = $('#' + adminUniqueId + '_exitDate').val().trim();
    var form = $(this).parents('form');
    var nextPage = $(this).attr('name');

    loanId = parseInt(loanId);

    // Modal operations
    if((currentStatus === closedStatus || exitDate !== '') && loanId !== 0) {
        if (outstandingBalance > 0) {
            e.preventDefault(); // Stop action until we find a response.

            swal({
                title: 'Current outstanding principal balance is $' + numberFormatter.format(outstandingBalance) + '. How much do you want to write off ?',
                input: 'text',
                width: '600px',
                inputClass: 'money-mask',
                showCancelButton: true,
                confirmButtonText: 'Close this loan',
                showLoaderOnConfirm: true,
                preConfirm: function (amount) {
                    return new Promise(function (resolve, reject) {
                        var convertedAmount = getValueFromFormattedNumber(amount);

                        if (isNaN(convertedAmount)) {
                            reject('Please write an amount.')
                        } else if (convertedAmount < 0 || convertedAmount > outstandingBalance) {
                            reject('The write-off amount is greater than the outstanding principal balance.')
                        } else {
                            $.ajax({
                                type: "POST",
                                url: setLoanTransactionRoute,
                                data: {
                                    loanId: loanId,
                                    outstandingBalance: outstandingBalance,
                                    amountToWriteOff: convertedAmount
                                },
                                success: function (data) {
                                    if (true === data.success) {
                                        $('#' + adminUniqueId + '_status').val(closedStatus).change();
                                        setTimeout($(form).submit(), 500);

                                        resolve();

                                    } else {
                                        reject('We found an error: ' + data.message + '.')
                                    }
                                },
                                error: function (response, textStatus, jqXHR) {
                                    reject("Something went wrong and we couldn't add this transaction. Please check if you have a write-off and/or repayment loan category.")
                                }
                            });
                        }
                    })
                }
            });
        }
    }
});
</code>```

答:
When user click the [Update] button, It will redirect to the same edit page and when user click the [Update and close button] will redirect to the listing page instead

As documented by swal plugin, You can call the deferred callback then by the time swal preConfirm function callback:

https://limonte.github.io/sweetalert2/

Here's a given reference code:

Note: I've place a [id] attribute for this given form and some additional conditions as well

$('#frm-submit input[type="submit"]').click(function(event) {
    event.preventDefault();

    var aValidSubmitValues = ['Update', 'Update and Close'];
    var sButtonValue = $(this).val();
    if ($.inArray(sButtonValue, aValidSubmitValues) < 0) {
        return false;
    }

    var convertedAmount = '123.00';
    var outstandingBalance = '200.00';

    swal({
        title: 'Current outstanding principal balance is $100.00 How much do you want to write off ?',
        input: 'text',
        width: '600px',
        inputClass: 'money-mask',
        showCancelButton: true,
        confirmButtonText: 'Close this loan',
        showLoaderOnConfirm: true,
        preConfirm: function(amount) {
            return new Promise(function(resolve, reject) {
                if (isNaN(convertedAmount)) {
                    reject('Please write an amount.')
                } else if (convertedAmount < 0 || convertedAmount > outstandingBalance) {
                    reject('The write-off amount is greater than the outstanding principal balance.')
                } else {
                     // Your given ajax code up until the resolve callback parameter
                     // Your $.ajax() here until resolve
                     resolve();
                }

            });
        }

    }).then(function(response) {
        console.log('You have click the ' + sButtonValue + ' button');
        if (sButtonValue === 'Update') {
             console.log('Reload the page');
             // location.reload()
        } else {
             console.log('Go to a certain listing page');
             // location.href = '/list-of-transaction-page';
        }
    });

});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/limonte-sweetalert2/6.11.5/sweetalert2.all.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div class="container">
    <form id="frm-submit">
        <input type="submit" value="Update" />
        <input type="submit" value="Update and Close" />
    </form>
</div></code>```

Hope this will guide you well

Body:
I'm using Sonata Admin for my project and I have a SweetAlert 2 on $('button[type="submit"]') event.

The problem is that initially I'm using preventDefault() to keep form alive, then I'm trying to submit form with $(form).submit() but I'm redirected to the same EDIT page even if I click on "Update & Close" page.

FYI: Sonata has 2 possibilities:'Update' & 'Update and close'. First one is updating entity and redirect you to the same page, the other one, is updating entity and redirecting you to listing page.

$('button[type="submit"]').click(function (e) {
    var currentStatus = $('#' + adminUniqueId + '_status option:selected').val();
    var exitDate = $('#' + adminUniqueId + '_exitDate').val().trim();
    var form = $(this).parents('form');
    var nextPage = $(this).attr('name');

    loanId = parseInt(loanId);

    // Modal operations
    if((currentStatus === closedStatus || exitDate !== '') && loanId !== 0) {
        if (outstandingBalance > 0) {
            e.preventDefault(); // Stop action until we find a response.

            swal({
                title: 'Current outstanding principal balance is $' + numberFormatter.format(outstandingBalance) + '. How much do you want to write off ?',
                input: 'text',
                width: '600px',
                inputClass: 'money-mask',
                showCancelButton: true,
                confirmButtonText: 'Close this loan',
                showLoaderOnConfirm: true,
                preConfirm: function (amount) {
                    return new Promise(function (resolve, reject) {
                        var convertedAmount = getValueFromFormattedNumber(amount);

                        if (isNaN(convertedAmount)) {
                            reject('Please write an amount.')
                        } else if (convertedAmount < 0 || convertedAmount > outstandingBalance) {
                            reject('The write-off amount is greater than the outstanding principal balance.')
                        } else {
                            $.ajax({
                                type: "POST",
                                url: setLoanTransactionRoute,
                                data: {
                                    loanId: loanId,
                                    outstandingBalance: outstandingBalance,
                                    amountToWriteOff: convertedAmount
                                },
                                success: function (data) {
                                    if (true === data.success) {
                                        $('#' + adminUniqueId + '_status').val(closedStatus).change();
                                        setTimeout($(form).submit(), 500);

                                        resolve();

                                    } else {
                                        reject('We found an error: ' + data.message + '.')
                                    }
                                },
                                error: function (response, textStatus, jqXHR) {
                                    reject("Something went wrong and we couldn't add this transaction. Please check if you have a write-off and/or repayment loan category.")
                                }
                            });
                        }
                    })
                }
            });
        }
    }
});

Body:
When user click the [Update] button, It will redirect to the same edit page and when user click the [Update and close button] will redirect to the listing page instead

As documented by swal plugin, You can call the deferred callback then by the time swal preConfirm function callback:

https://limonte.github.io/sweetalert2/

Here's a given reference code:

Note: I've place a [id] attribute for this given form and some additional conditions as well

$('#frm-submit input[type="submit"]').click(function(event) {
    event.preventDefault();

    var aValidSubmitValues = ['Update', 'Update and Close'];
    var sButtonValue = $(this).val();
    if ($.inArray(sButtonValue, aValidSubmitValues) < 0) {
        return false;
    }

    var convertedAmount = '123.00';
    var outstandingBalance = '200.00';

    swal({
        title: 'Current outstanding principal balance is $100.00 How much do you want to write off ?',
        input: 'text',
        width: '600px',
        inputClass: 'money-mask',
        showCancelButton: true,
        confirmButtonText: 'Close this loan',
        showLoaderOnConfirm: true,
        preConfirm: function(amount) {
            return new Promise(function(resolve, reject) {
                if (isNaN(convertedAmount)) {
                    reject('Please write an amount.')
                } else if (convertedAmount < 0 || convertedAmount > outstandingBalance) {
                    reject('The write-off amount is greater than the outstanding principal balance.')
                } else {
                     // Your given ajax code up until the resolve callback parameter
                     // Your $.ajax() here until resolve
                     resolve();
                }

            });
        }

    }).then(function(response) {
        console.log('You have click the ' + sButtonValue + ' button');
        if (sButtonValue === 'Update') {
             console.log('Reload the page');
             // location.reload()
        } else {
             console.log('Go to a certain listing page');
             // location.href = '/list-of-transaction-page';
        }
    });

});

<script src="https://cdnjs.cloudflare.com/ajax/libs/limonte-sweetalert2/6.11.5/sweetalert2.all.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div class="container">
    <form id="frm-submit">
        <input type="submit" value="Update" />
        <input type="submit" value="Update and Close" />
    </form>
</div>

Hope this will guide you well


问:
Extracting values from (multiple) brackets in one string
Here's what I would like to do with MySQL (MariaDB). I want to retrieve a substring of the contents between curly brackets (let's call them tags) in the column 'Case_Title'. My table looks like this.

Table: cases

```<code>| Case_ID | Case_Title                       | Department  |
|---------|----------------------------------|-------------|
| 7032389 | {RJ1} Not able to connect        | Consumer    |
| 7243040 | {RJ2}{ZO}{WAD} Connection issues | Business    |
| 7249910 | {O2A} No incoming mgs {WAD}      | Consumer    |
|---------|----------------------------------|-------------|
</code>```

By searching Stack Overflow I came up with two options to retrieve these substrings.

1 - Using regular expressions. Since I'm on MariaDB so I can use REGEXP_SUBSTR, REGEXP_INSTR, REGEXP_REPLACE.

```<code>SELECT Case_ID, REGEXP_SUBSTR(Case_title,'{(.*?)}') as 'Tag'
FROM cases
</code>```

2 - combinations of SUBSTR() and INSTR().

```<code>SELECT Case_ID, SUBSTR(Case_Title,INSTR(Case_Title,"{"), INSTR(Case_Title,"}") - INSTR(Case_Title,"{") + 1) as 'Tag'
FROM cases
</code>```

Both options will output:

```<code>| Case_ID | Tag   |
|---------|-------|
| 7032389 | {RJ1} |
| 7243040 | {RJ2} |
| 7249910 | {O2A} |
|---------|-------|
</code>```

However, the other 'tags' in the Case_Title are ignored. I just cannot seem to find a way to get the output like this:

```<code>| Case_ID | Tag   |
|---------|-------|
| 7032389 | {RJ1} |
| 7243040 | {RJ2} |
| 7243040 | {ZO}  |
| 7243040 | {WAD} |
| 7249910 | {O2A} |
| 7249910 | {WAD} |
|---------|-------|
</code>```

Please note that I'd like to have new records/rows for each tag, rather than concatenating them like: {RJ1},{ZO},{WAD}. Also, I don't know in advance:

how many tags a title will contain.

where the tags are located in the Case_Title.

if all tags are grouped together or if they're scattered across the Case_Title.

the actual contents of the tag themselves.

答:
Using a combination of functions this works by first pivoting the data, separating them by }{, this then gets each value on its own line. From there I removed all values after the first }. Some concatenation was needed to restore lost brackets removed in the pivoting.

```<code>SELECT Case_ID,
CONCAT(substring_index(CASE WHEN RIGHT(CASE WHEN LEFT(tag,1) = '{'
                                            THEN tag
                                            ELSE CONCAT('{',tag) END,1) = '}'
                            THEN CASE WHEN LEFT(tag,1) = '{'
                                      THEN tag
                                      ELSE CONCAT('{',tag)
                                 END
                            ELSE CONCAT(CASE WHEN LEFT(tag,1) = '{'
                                             THEN tag
                                             ELSE CONCAT('{',tag)
                                        END,'}')
                       END,'}',1),'}') AS tag
FROM (
SELECT DISTINCT Case_ID, SUBSTRING_INDEX(SUBSTRING_INDEX(Case_Title, '}{', n), '}{', -1) tag
FROM (SELECT 1 n
      UNION ALL
      SELECT 2
      UNION ALL
      SELECT 3
      UNION ALL
      SELECT 4
      UNION ALL
      SELECT 5) n
INNER JOIN cases ON CHAR_LENGTH(Case_Title)-CHAR_LENGTH(REPLACE(Case_Title, '}{', ''))>=n-1) a
</code>```

Input

```<code>Case_ID Case_Title                       Department
7032389 {RJ1} Not able to connect        Consumer
7243040 {RJ2}{ZO}{WAD} Connection issues Business
7249910 {O2A} No incoming mgs {WAD}      Consumer
</code>```

Output

```<code>Case_ID tag
7032389 {RJ1}
7243040 {RJ2}
7249910 {O2A}
7243040 {ZO}
7243040 {WAD}
</code>```

SQL Fiddle: http://sqlfiddle.com/#!9/0fa9c13/94/0

Body:
Here's what I would like to do with MySQL (MariaDB). I want to retrieve a substring of the contents between curly brackets (let's call them tags) in the column 'Case_Title'. My table looks like this.

Table: cases

| Case_ID | Case_Title                       | Department  |
|---------|----------------------------------|-------------|
| 7032389 | {RJ1} Not able to connect        | Consumer    |
| 7243040 | {RJ2}{ZO}{WAD} Connection issues | Business    |
| 7249910 | {O2A} No incoming mgs {WAD}      | Consumer    |
|---------|----------------------------------|-------------|

By searching Stack Overflow I came up with two options to retrieve these substrings.

1 - Using regular expressions. Since I'm on MariaDB so I can use REGEXP_SUBSTR, REGEXP_INSTR, REGEXP_REPLACE.

SELECT Case_ID, REGEXP_SUBSTR(Case_title,'{(.*?)}') as 'Tag'
FROM cases

2 - combinations of SUBSTR() and INSTR().

SELECT Case_ID, SUBSTR(Case_Title,INSTR(Case_Title,"{"), INSTR(Case_Title,"}") - INSTR(Case_Title,"{") + 1) as 'Tag'
FROM cases

Both options will output:

| Case_ID | Tag   |
|---------|-------|
| 7032389 | {RJ1} |
| 7243040 | {RJ2} |
| 7249910 | {O2A} |
|---------|-------|

However, the other 'tags' in the Case_Title are ignored. I just cannot seem to find a way to get the output like this:

| Case_ID | Tag   |
|---------|-------|
| 7032389 | {RJ1} |
| 7243040 | {RJ2} |
| 7243040 | {ZO}  |
| 7243040 | {WAD} |
| 7249910 | {O2A} |
| 7249910 | {WAD} |
|---------|-------|

Please note that I'd like to have new records/rows for each tag, rather than concatenating them like: {RJ1},{ZO},{WAD}. Also, I don't know in advance:

how many tags a title will contain.

where the tags are located in the Case_Title.

if all tags are grouped together or if they're scattered across the Case_Title.

the actual contents of the tag themselves.

Body:
Using a combination of functions this works by first pivoting the data, separating them by }{, this then gets each value on its own line. From there I removed all values after the first }. Some concatenation was needed to restore lost brackets removed in the pivoting.

SELECT Case_ID,
CONCAT(substring_index(CASE WHEN RIGHT(CASE WHEN LEFT(tag,1) = '{'
                                            THEN tag
                                            ELSE CONCAT('{',tag) END,1) = '}'
                            THEN CASE WHEN LEFT(tag,1) = '{'
                                      THEN tag
                                      ELSE CONCAT('{',tag)
                                 END
                            ELSE CONCAT(CASE WHEN LEFT(tag,1) = '{'
                                             THEN tag
                                             ELSE CONCAT('{',tag)
                                        END,'}')
                       END,'}',1),'}') AS tag
FROM (
SELECT DISTINCT Case_ID, SUBSTRING_INDEX(SUBSTRING_INDEX(Case_Title, '}{', n), '}{', -1) tag
FROM (SELECT 1 n
      UNION ALL
      SELECT 2
      UNION ALL
      SELECT 3
      UNION ALL
      SELECT 4
      UNION ALL
      SELECT 5) n
INNER JOIN cases ON CHAR_LENGTH(Case_Title)-CHAR_LENGTH(REPLACE(Case_Title, '}{', ''))>=n-1) a

Input

Case_ID Case_Title                       Department
7032389 {RJ1} Not able to connect        Consumer
7243040 {RJ2}{ZO}{WAD} Connection issues Business
7249910 {O2A} No incoming mgs {WAD}      Consumer

Output

Case_ID tag
7032389 {RJ1}
7243040 {RJ2}
7249910 {O2A}
7243040 {ZO}
7243040 {WAD}

SQL Fiddle: http://sqlfiddle.com/#!9/0fa9c13/94/0


问:
VB Script to write Output of script to a different worksheet Ask
I have written a Script which generates a CSV file list of AD users for a different vendor Org for our Company. Now I want to add the Output of the Script below into the 2nd Tab (Worksheet) of another Excel File which I have saved in C:.

I have appended the following code in the beginning of the script so that the output is printed to the 2nd Tab (Worksheet) of another Excel File but I am getting multiple errors for the same. The code snippet is as follows :-

```<code>Option Explicit
Dim xL
Dim Targetbook
Set Targetbook = xl.workbooks.open("C:\Users\achowdhury\Desktop\Projects\Project automation\IM controls\Iuc.xlsx")
Dim Targetsheet
Set Targetsheet = targetbook.worksheets("IM AD users")
Dim t
Set t = targetsheet.range("a1")
</code>```

But I am getting multiple VBScript compilation errors when I append the snippet above and run the code. What is the mistake that I am doing here ? Or also can I add after count = count +1 statement to append the output to the Other Workbook's 2nd Worksheet? I am kind of new and confused on this.

```<code>Option Explicit
Dim xL
Dim Targetbook
Set Targetbook = xl.workbooks.open("C:\Users\achowdhury\Desktop\Projects\Project automation\IM controls\Iuc.xlsx")
Dim Targetsheet
Set Targetsheet = targetbook.worksheets("IM AD users")
Dim t
Set t = targetsheet.range("a1")

Dim objConnection,objCommand,objRecordSet,objUser,ObjFSO, InitFSO,objdialog,thisday,intreturn,OutputFile,myprompt
Dim intCounter,strfname,strDN,arrPath,stroutput,objoutput,Account_locked,Objclass,ObjMail
Dim StrEmpType,IntUAC,UserStatus,slogin,Last_Logon_timestamp,Last_Login,Last_pwd_changed,PWD_Never_Expire,objLastLogon,intLastLogonTime,intLastLogon,User_must_change_pwd

Dim objShell
Dim strFileName
Dim strFilePath
Dim objFile
Dim manager,manager1,manager2,IMSite,IMSite1,IMSite2,count

Const ADS_SCOPE_SUBTREE = 2
Const ForWriting = 2
Const ADS_UF_ACCOUNTDISABLE = 2
Const ADS_UF_DONT_EXPIRE_PASSWD = &H10000
Const ADS_UF_PASSWD_NOTREQD = &H0020
Const ADS_UF_PASSWORD_EXPIRED = 8388608
Const ADS_UF_LOCKOUT= 16

' Declare Option Constants
'------------------------
Const BIF_EDITBOX = &H10
Const BIF_NONEWFOLDER = &H0200
Const BIF_RETURNONLYFSDIRS = &H1

Dim strprompt, intoptions,strroot,strfolderpath

' Setup connection to AD
'------------------------
Set objConnection = CreateObject("ADODB.Connection")
Set objCommand = CreateObject("ADODB.Command")
objConnection.Provider = "ADsDSOObject"
objConnection.Open "Active Directory Provider"
Set objCommand.ActiveConnection = objConnection

' Specify the output file.
'-----------------------------

Msgbox " This script will generate a list of all IM AD users that are into the IM OU in the imaje.intra domain and that are enabled." & vbnewline & vbnewline  _
    & "You will be prompted to enter the location where to store the output file." _
    & vbnewline & vbnewline & " Just browse the folder where you want to save it " _
    & vbnewline & vbnewline & " You will be notified when the script will be completed . Press OK to continue"

' Generate the output filename with the date
'-------------------------------------------
thisday=Year(Date) & Right("0" & Month(Date),2) & Right("0" & Day(Date),2)

strPrompt = "Please select the folder where to store the final output file."
intOptions = BIF_RETURNONLYFSDIRS + BIF_EDITBOX + BIF_NONEWFOLDER

' Return the path, e.g. C:\
strFolderPath = Browse4Folder(strPrompt, intOptions, "")

OutputFile = strFolderPath & "\List_IM_AD_users_" & thisday & ".csv"

Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objoutput = objFSO.CreateTextFile(OutputFile)

Msgbox " Press OK to start extracting Active Directory information for IM Users into " & OutputFile & vbnewline & vbnewline  _
    & " You'll be notified when the script will be completed !"

' Set paging file higher to accommodate lots of AD records
'-------------------------------------------------------------

objCommand.Properties("Page Size") = 40000
objCommand.Properties("Searchscope") = ADS_SCOPE_SUBTREE

'Prepare the LDAP command
'--------------------------

objCommand.CommandText = "SELECT AdsPath FROM 'LDAP://OU=IM,OU=MIUsers,OU=MI,DC=Imaje,DC=intra' WHERE objectCategory='user'"
Set objRecordSet = objCommand.Execute
objRecordSet.MoveFirst

' Read the Entire AD domain for objectCategory=user and write the various fields into the output file
'-----------------------------------------------------------------------------------------------------
objOutput.Write "SamAccountName;GivenName;sn;DisplayName;E-mail @;IM Site;Exists in IM list;IM location;Title;Country;Manager;employeeID;Account locked;Last Logon;LastLogon timestamp;Pwd Never Expires;Last PWD Change;User_must_change_pwd;User creation date;User Change Date;Description;DN" & vbcrlf

count=1

Do Until objRecordSet.EOF
    Userstatus="Enabled"
    Set objUser = GetObject(objRecordSet.Fields("AdsPath").Value)

' Get status of the User ( disabled or not , pwd required or Not , User must change pwd)
'-------------------------------------------------------------------------------------------
    intUAC=ObjUser.userAccountControl
    If intUAC AND ADS_UF_ACCOUNTDISABLE Then
        Userstatus="Disabled"
    End If

    If intUAC AND ADS_UF_DONT_EXPIRE_PASSWD Then
      PWD_Never_Expire="Yes"
    Else
      pwd_never_expire="No"
    End If

    If intUAC AND ADS_UF_PASSWORD_EXPIRED Then
      User_must_change_pwd="Yes"
    Else
      User_must_change_pwd="No"
    End If

    If intUAC AND ADS_UF_LOCKOUT Then
      Account_locked="Yes"
    Else
      Account_locked="No"
    End If

' Get LastLogonTimestamp , LastLogon, LastPwdChange of the User
'------------------------------------------------------------------

    On Error Resume Next

    Set objLastLogon = objUser.Get("lastLogonTimestamp")

    intLastLogonTime = objLastLogon.HighPart * (2^32) + objLastLogon.LowPart
    intLastLogonTime = intLastLogonTime / (60 * 10000000)
    intLastLogonTime = intLastLogonTime / 1440

    Last_Logon_timestamp=intLastLogonTime + #1/1/1601#

    Set objLastLogon = objUser.Get("lastLogon")

    intLastLogon = objLastLogon.HighPart * (2^32) + objLastLogon.LowPart
    intLastLogon = intLastLogon / (60 * 10000000)
    intLastLogon = intLastLogon / 1440

    Last_Login=intLastLogon + #1/1/1601#

    On Error Goto 0

    On Error Resume Next

    sLogin = objUser.passwordLastChanged
    If Err = 0 Then
            Last_pwd_changed=sLogin
        Else
            Last_pwd_changed="Never"
        End If

    On Error Goto 0

    ObjClass = objUser.Class

    ObjMail = objUser.Mail
    manager = ""
    IMSite=""

    If ObjClass = "user" and userstatus = "Enabled" then
        On Error Resume Next
        manager1= split(objUser.Manager,",")
        manager = manager1(0)
        manager2=split(manager,"=")
        manager = manager2(1)

        IMSite1 = InStr(ObjUser.distinguishedName,",OU=IM")
        IMSite2 = Mid (ObjUser.distinguishedName,IMSite1-12,12)
        IMSite1 = split(IMSite2,"=")
        IMSite = IMSite1(1)

        count=count + 1

        objOutput.Write objUser.samaccountname &";" & objUser.GivenName &";" & objUser.sn &";" & objUser.DisplayName &";" & ObjMail & ";" & IMSite & _
        ";=IFERROR(IF(VLOOKUP(E" & count & ",'IM employees'!C:C,1,FALSE)=E" & count & ",""Yes""),""No"")" & ";=IF(G" & count & "=""Yes"",VLOOKUP(E" & _
        count & ",'IM employees'!C:D,2,FALSE),""Missing"")" & ";" &ObjUser.Title & ";" & ObjUser.Co & ";" & Manager &";" & objUser.employeeID & ";" & _
        Account_locked & ";" & last_Login & ";" & last_Logon_timestamp & ";"& pwd_never_expire & ";"& Last_pwd_Changed & ";" _
        & User_must_change_pwd & ";" & objUser.whenCreated & ";" & objUser.whenChanged & ";" & objUser.description &";" & objUser.distinguishedName &";" & vbcrlf

    End If

' Next record in recordset
'------------------------------
    objRecordSet.MoveNext

Loop

Msgbox " Script is completed ! The file " & OutputFile & " is now ready !! "

'End Script

Function Browse4Folder(strPrompt, intOptions, strRoot)
    Dim objFolder, objFolderItem, objShell
    Set objShell = CreateObject("Shell.Application")
    Set objFolder = objShell.BrowseForFolder(0, strPrompt, intOptions, strRoot)
    If (objFolder Is Nothing) Then
        Browse4Folder = ""
    Else
        Set objFolderItem = objFolder.Self
        Browse4Folder = objFolderItem.Path
        Set objFolderItem = Nothing
        Set objFolder = Nothing
    End If
    Set objShell = Nothing
End Function
</code>```

答:
One potential issue I can see is that you are not getting a hold of excel first:

the first few lines of code should maybe be:

```<code>Option Explicit
Dim xL
Set xl = CreateObject("Excel.Application")
Dim Targetbook
Set Targetbook = xl.Workbooks.Open("C:\Users\achowdhury\Desktop\Projects\Project automation\IM controls\Iuc.xlsx")
Dim targetsheet
targetbook.Sheets("IM AD users").Select
Set targetsheet = targetbook.ActiveSheet    '<<<i added SET here
</code>```

Apart from that entering data is pretty straight forward:

```<code>Dim currentRow : currentRow = 1

Function RecordData (username,companyCode)
    targetsheet.Cells(currentRow,1).Value = companyCode
    targetsheet.Cells(currentRow,2).Value = username
    currentRow = currentRow + 1
End Function
</code>```

You can then call that function with data whenever you want:

```<code>RecordData ("2000","bobbyj")
</code>```

You will also need to save and close the file:

```<code>'alerts need to be disabled so that you don't get warnings about saving over the file etc. (excel pop ups)
'ALERTS MUST BE TURNED ON AGAIN IMMEDIATELY AS THIS IS A GLOBAL SETTING FOR EXCEL
'    - i.e. users will not get warnings about unsaved files etc. when quitting excel normally'
xl.DisplayAlerts = false
targetbook.SaveAs("C:\Users\achowdhury\Desktop\Projects\Project automation\IM controls\Iuc.xlsx")
xl.DisplayAlerts = true

'close workbook now it has been saved - there should be no pop ups'
targetbook.Close()

'release references and close excel'
set targetbook = nothing
set targetsheet = nothing

xl.Quit()

set xl = Nothing
</code>```

Body:
I have written a Script which generates a CSV file list of AD users for a different vendor Org for our Company. Now I want to add the Output of the Script below into the 2nd Tab (Worksheet) of another Excel File which I have saved in C:.

I have appended the following code in the beginning of the script so that the output is printed to the 2nd Tab (Worksheet) of another Excel File but I am getting multiple errors for the same. The code snippet is as follows :-

Option Explicit
Dim xL
Dim Targetbook
Set Targetbook = xl.workbooks.open("C:\Users\achowdhury\Desktop\Projects\Project automation\IM controls\Iuc.xlsx")
Dim Targetsheet
Set Targetsheet = targetbook.worksheets("IM AD users")
Dim t
Set t = targetsheet.range("a1")

But I am getting multiple VBScript compilation errors when I append the snippet above and run the code. What is the mistake that I am doing here ? Or also can I add after count = count +1 statement to append the output to the Other Workbook's 2nd Worksheet? I am kind of new and confused on this.

Option Explicit
Dim xL
Dim Targetbook
Set Targetbook = xl.workbooks.open("C:\Users\achowdhury\Desktop\Projects\Project automation\IM controls\Iuc.xlsx")
Dim Targetsheet
Set Targetsheet = targetbook.worksheets("IM AD users")
Dim t
Set t = targetsheet.range("a1")

Dim objConnection,objCommand,objRecordSet,objUser,ObjFSO, InitFSO,objdialog,thisday,intreturn,OutputFile,myprompt
Dim intCounter,strfname,strDN,arrPath,stroutput,objoutput,Account_locked,Objclass,ObjMail
Dim StrEmpType,IntUAC,UserStatus,slogin,Last_Logon_timestamp,Last_Login,Last_pwd_changed,PWD_Never_Expire,objLastLogon,intLastLogonTime,intLastLogon,User_must_change_pwd

Dim objShell
Dim strFileName
Dim strFilePath
Dim objFile
Dim manager,manager1,manager2,IMSite,IMSite1,IMSite2,count

Const ADS_SCOPE_SUBTREE = 2
Const ForWriting = 2
Const ADS_UF_ACCOUNTDISABLE = 2
Const ADS_UF_DONT_EXPIRE_PASSWD = &H10000
Const ADS_UF_PASSWD_NOTREQD = &H0020
Const ADS_UF_PASSWORD_EXPIRED = 8388608
Const ADS_UF_LOCKOUT= 16

' Declare Option Constants
'------------------------
Const BIF_EDITBOX = &H10
Const BIF_NONEWFOLDER = &H0200
Const BIF_RETURNONLYFSDIRS = &H1

Dim strprompt, intoptions,strroot,strfolderpath

' Setup connection to AD
'------------------------
Set objConnection = CreateObject("ADODB.Connection")
Set objCommand = CreateObject("ADODB.Command")
objConnection.Provider = "ADsDSOObject"
objConnection.Open "Active Directory Provider"
Set objCommand.ActiveConnection = objConnection

' Specify the output file.
'-----------------------------

Msgbox " This script will generate a list of all IM AD users that are into the IM OU in the imaje.intra domain and that are enabled." & vbnewline & vbnewline  _
    & "You will be prompted to enter the location where to store the output file." _
    & vbnewline & vbnewline & " Just browse the folder where you want to save it " _
    & vbnewline & vbnewline & " You will be notified when the script will be completed . Press OK to continue"

' Generate the output filename with the date
'-------------------------------------------
thisday=Year(Date) & Right("0" & Month(Date),2) & Right("0" & Day(Date),2)

strPrompt = "Please select the folder where to store the final output file."
intOptions = BIF_RETURNONLYFSDIRS + BIF_EDITBOX + BIF_NONEWFOLDER

' Return the path, e.g. C:\
strFolderPath = Browse4Folder(strPrompt, intOptions, "")

OutputFile = strFolderPath & "\List_IM_AD_users_" & thisday & ".csv"

Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objoutput = objFSO.CreateTextFile(OutputFile)

Msgbox " Press OK to start extracting Active Directory information for IM Users into " & OutputFile & vbnewline & vbnewline  _
    & " You'll be notified when the script will be completed !"

' Set paging file higher to accommodate lots of AD records
'-------------------------------------------------------------

objCommand.Properties("Page Size") = 40000
objCommand.Properties("Searchscope") = ADS_SCOPE_SUBTREE

'Prepare the LDAP command
'--------------------------

objCommand.CommandText = "SELECT AdsPath FROM 'LDAP://OU=IM,OU=MIUsers,OU=MI,DC=Imaje,DC=intra' WHERE objectCategory='user'"
Set objRecordSet = objCommand.Execute
objRecordSet.MoveFirst

' Read the Entire AD domain for objectCategory=user and write the various fields into the output file
'-----------------------------------------------------------------------------------------------------
objOutput.Write "SamAccountName;GivenName;sn;DisplayName;E-mail @;IM Site;Exists in IM list;IM location;Title;Country;Manager;employeeID;Account locked;Last Logon;LastLogon timestamp;Pwd Never Expires;Last PWD Change;User_must_change_pwd;User creation date;User Change Date;Description;DN" & vbcrlf

count=1

Do Until objRecordSet.EOF
    Userstatus="Enabled"
    Set objUser = GetObject(objRecordSet.Fields("AdsPath").Value)

' Get status of the User ( disabled or not , pwd required or Not , User must change pwd)
'-------------------------------------------------------------------------------------------
    intUAC=ObjUser.userAccountControl
    If intUAC AND ADS_UF_ACCOUNTDISABLE Then
        Userstatus="Disabled"
    End If

    If intUAC AND ADS_UF_DONT_EXPIRE_PASSWD Then
      PWD_Never_Expire="Yes"
    Else
      pwd_never_expire="No"
    End If

    If intUAC AND ADS_UF_PASSWORD_EXPIRED Then
      User_must_change_pwd="Yes"
    Else
      User_must_change_pwd="No"
    End If

    If intUAC AND ADS_UF_LOCKOUT Then
      Account_locked="Yes"
    Else
      Account_locked="No"
    End If

' Get LastLogonTimestamp , LastLogon, LastPwdChange of the User
'------------------------------------------------------------------

    On Error Resume Next

    Set objLastLogon = objUser.Get("lastLogonTimestamp")

    intLastLogonTime = objLastLogon.HighPart * (2^32) + objLastLogon.LowPart
    intLastLogonTime = intLastLogonTime / (60 * 10000000)
    intLastLogonTime = intLastLogonTime / 1440

    Last_Logon_timestamp=intLastLogonTime + #1/1/1601#

    Set objLastLogon = objUser.Get("lastLogon")

    intLastLogon = objLastLogon.HighPart * (2^32) + objLastLogon.LowPart
    intLastLogon = intLastLogon / (60 * 10000000)
    intLastLogon = intLastLogon / 1440

    Last_Login=intLastLogon + #1/1/1601#

    On Error Goto 0

    On Error Resume Next

    sLogin = objUser.passwordLastChanged
    If Err = 0 Then
            Last_pwd_changed=sLogin
        Else
            Last_pwd_changed="Never"
        End If

    On Error Goto 0

    ObjClass = objUser.Class

    ObjMail = objUser.Mail
    manager = ""
    IMSite=""

    If ObjClass = "user" and userstatus = "Enabled" then
        On Error Resume Next
        manager1= split(objUser.Manager,",")
        manager = manager1(0)
        manager2=split(manager,"=")
        manager = manager2(1)

        IMSite1 = InStr(ObjUser.distinguishedName,",OU=IM")
        IMSite2 = Mid (ObjUser.distinguishedName,IMSite1-12,12)
        IMSite1 = split(IMSite2,"=")
        IMSite = IMSite1(1)

        count=count + 1

        objOutput.Write objUser.samaccountname &";" & objUser.GivenName &";" & objUser.sn &";" & objUser.DisplayName &";" & ObjMail & ";" & IMSite & _
        ";=IFERROR(IF(VLOOKUP(E" & count & ",'IM employees'!C:C,1,FALSE)=E" & count & ",""Yes""),""No"")" & ";=IF(G" & count & "=""Yes"",VLOOKUP(E" & _
        count & ",'IM employees'!C:D,2,FALSE),""Missing"")" & ";" &ObjUser.Title & ";" & ObjUser.Co & ";" & Manager &";" & objUser.employeeID & ";" & _
        Account_locked & ";" & last_Login & ";" & last_Logon_timestamp & ";"& pwd_never_expire & ";"& Last_pwd_Changed & ";" _
        & User_must_change_pwd & ";" & objUser.whenCreated & ";" & objUser.whenChanged & ";" & objUser.description &";" & objUser.distinguishedName &";" & vbcrlf

    End If

' Next record in recordset
'------------------------------
    objRecordSet.MoveNext

Loop

Msgbox " Script is completed ! The file " & OutputFile & " is now ready !! "

'End Script

Function Browse4Folder(strPrompt, intOptions, strRoot)
    Dim objFolder, objFolderItem, objShell
    Set objShell = CreateObject("Shell.Application")
    Set objFolder = objShell.BrowseForFolder(0, strPrompt, intOptions, strRoot)
    If (objFolder Is Nothing) Then
        Browse4Folder = ""
    Else
        Set objFolderItem = objFolder.Self
        Browse4Folder = objFolderItem.Path
        Set objFolderItem = Nothing
        Set objFolder = Nothing
    End If
    Set objShell = Nothing
End Function

Body:
One potential issue I can see is that you are not getting a hold of excel first:

the first few lines of code should maybe be:

Option Explicit
Dim xL
Set xl = CreateObject("Excel.Application")
Dim Targetbook
Set Targetbook = xl.Workbooks.Open("C:\Users\achowdhury\Desktop\Projects\Project automation\IM controls\Iuc.xlsx")
Dim targetsheet
targetbook.Sheets("IM AD users").Select
Set targetsheet = targetbook.ActiveSheet    '<<<i added SET here

Apart from that entering data is pretty straight forward:

Dim currentRow : currentRow = 1

Function RecordData (username,companyCode)
    targetsheet.Cells(currentRow,1).Value = companyCode
    targetsheet.Cells(currentRow,2).Value = username
    currentRow = currentRow + 1
End Function

You can then call that function with data whenever you want:

RecordData ("2000","bobbyj")

You will also need to save and close the file:

'alerts need to be disabled so that you don't get warnings about saving over the file etc. (excel pop ups)
'ALERTS MUST BE TURNED ON AGAIN IMMEDIATELY AS THIS IS A GLOBAL SETTING FOR EXCEL
'    - i.e. users will not get warnings about unsaved files etc. when quitting excel normally'
xl.DisplayAlerts = false
targetbook.SaveAs("C:\Users\achowdhury\Desktop\Projects\Project automation\IM controls\Iuc.xlsx")
xl.DisplayAlerts = true

'close workbook now it has been saved - there should be no pop ups'
targetbook.Close()

'release references and close excel'
set targetbook = nothing
set targetsheet = nothing

xl.Quit()

set xl = Nothing


问:
importing js file in Vue project throws error
I am trying to use this plugin https://www.npmjs.com/package/mobius1-selectr

I did a npm install mobius1-selectr

and imported it in my main.js

```<code>import 'mobius1-selectr/dist/selectr.min.css';
import 'mobius1-selectr/dist/selectr.min.js';
</code>```

but as soon I import I get this exception:

```<code>You must supply either a HTMLSelectElement or a CSS3 selector string.
</code>```

which comes from the source of selectr.

Is the import not to be done this way in webpack / main.js?

What am I doing wrong? Any help is appreciated.

答:
Yes your imports are incorrect. This library uses UMD to export Selectr constructor. You are using Webpack so default import in your case should work:

```<code>import Selectr from 'mobius1-selectr'
</code>```

Body:
I am trying to use this plugin https://www.npmjs.com/package/mobius1-selectr

I did a npm install mobius1-selectr

and imported it in my main.js

import 'mobius1-selectr/dist/selectr.min.css';
import 'mobius1-selectr/dist/selectr.min.js';

but as soon I import I get this exception:

You must supply either a HTMLSelectElement or a CSS3 selector string.

which comes from the source of selectr.

Is the import not to be done this way in webpack / main.js?

What am I doing wrong? Any help is appreciated.

Body:
Yes your imports are incorrect. This library uses UMD to export Selectr constructor. You are using Webpack so default import in your case should work:

import Selectr from 'mobius1-selectr'


问:
S#arp Architecture 1.9 + Multi Tenant Custom View Engine
What is the easiest way to create a Custom AreaViewEngine that S#arp uses?

I want to add another directory to search for view for the current tenant, the tenant directory would be part of the domain name (e.g. hm.com), so i would like my view engine to check:

/Tenants/hm.com/Views/Home/Index.aspx

I tried to create a new TenantViewEngine.cs inherited from the AreaViewEngine to add my new paths but I can't get access to the HttpContext to get the host name.

Any ideas?

Thanks.
Paul

答:
HttpContext.Current should be available. Also, ControllerContext passed as a parameter to Find* and Create* methods has a HttpContext property.

You might also want to look at the VirtualPathProviderViewEngine class.

ContentLicense: CC BY-SA 2.5


问:
Increase index of a form's input field's name attribute in a dynamic form
Suppose I have this form with indexed input fields username and level:

```<code><form>
 <table>
  <tr class="trToClone">
    <td>
      <label>Username:</label>
      <input type="text" name="username[0]" />
    </td>
    <td>
      <label>Level:</label>
      <select name="level[0]">
        <option value="">---</option>
        <option value="a">A</option>
        <option value="b">B</option>
        <option value="c">C</option>
      </select>
    </td>
    <td><input type="button" class="addField" value="Add" /></td>
  </tr>
 </table>
</form>
</code>```

The row can be repeated using this jQuery:

```<code>$("input.addField").on('click', function() {
  var $tr = $(this).closest('.trToClone');
  var $clone = $tr.clone();
  $clone.find(':text').val('');
  $tr.after($clone);
});
</code>```

Now for every subsequent row I add, I want to increase the indices of the name attribute (i.e. username[1],level[1]; username[2],level[2]; and so on...). How can I do this? I've looked for possible solutions, but to no avail.

答:
$('.addField').click(function(){
  var count = $('#btnIncrease').val();
  var $tr = $(this).closest('.trToClone');
  var $clone = $tr.clone();
  count++;
  $('#btnIncrease').val(count);
  $clone.find(':text').val('');
  $clone.find(':text').attr('name', 'username[' + count + ']');
  $tr.after($clone);
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
  <tr class="trToClone">
    <td>
      <label>Username:</label>
      <input type="text" name="username[0]" />
    </td>
    <td>
      <label>Level:</label>
      <select name="level[0]">
        <option value="">---</option>
        <option value="a">A</option>
        <option value="b">B</option>
        <option value="c">C</option>
      </select>
    </td>
    <td><input type="button" class="addField" value="Add" /></td>
  </tr>
 </table>

 <input type="hidden" id="btnIncrease" value="0" /></code>```

This would work for you.

Body:
Suppose I have this form with indexed input fields username and level:

<form>

      Username:
      <input type="text" name="username[0]" />

      Level:
      <select name="level[0]">
        <option value="">---</option>
        <option value="a">A</option>
        <option value="b">B</option>
        <option value="c">C</option>
      </select>

    <input type="button" class="addField" value="Add" />

</form>

The row can be repeated using this jQuery:

$("input.addField").on('click', function() {
  var $tr = $(this).closest('.trToClone');
  var $clone = $tr.clone();
  $clone.find(':text').val('');
  $tr.after($clone);
});

Now for every subsequent row I add, I want to increase the indices of the name attribute (i.e. username[1],level[1]; username[2],level[2]; and so on...). How can I do this? I've looked for possible solutions, but to no avail.

Body:
$('.addField').click(function(){
  var count = $('#btnIncrease').val();
  var $tr = $(this).closest('.trToClone');
  var $clone = $tr.clone();
  count++;
  $('#btnIncrease').val(count);
  $clone.find(':text').val('');
  $clone.find(':text').attr('name', 'username[' + count + ']');
  $tr.after($clone);
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
  <tr class="trToClone">
    <td>
      <label>Username:</label>
      <input type="text" name="username[0]" />
    </td>
    <td>
      <label>Level:</label>
      <select name="level[0]">
        <option value="">---</option>
        <option value="a">A</option>
        <option value="b">B</option>
        <option value="c">C</option>
      </select>
    </td>
    <td><input type="button" class="addField" value="Add" /></td>
  </tr>
 </table>

 <input type="hidden" id="btnIncrease" value="0" />

This would work for you.


问:
Telerik Kendo UI How to Clone an element already initialized
In our project, I need to multiply table row. The row which would be copied contains several initialized Kendo UI elements.(AutoComplete, DropDownList,DatePicker.)
When I clone row and change ids of its children, but these copied Kendo UI elements don't work.
Is there any solution to solve this problem?</p>

答:
I had the same query and what I found is that you can make deep copy of the returned JSON object and to assign it where you want after that.

```<code>var grid = $("#grid").data('kendoGrid');
// Deep copy
var newGrid = jQuery.extend(true, {}, grid);
</code>```

I took the idea from - What is the most efficient way to deep clone an object in JavaScript?

Body:
I had the same query and what I found is that you can make deep copy of the returned JSON object and to assign it where you want after that.

var grid = $("#grid").data('kendoGrid');
// Deep copy
var newGrid = jQuery.extend(true, {}, grid);

I took the idea from - What is the most efficient way to deep clone an object in JavaScript?


问:
JSoup parsing badly structured HTML
I have HTML structure that looks like this:

```<code><h1>Title</h1>
<h2>Subtitle</h2>
<p>Some text</p>
<p>Some other text</p>

<h1>Some other title</h1>
<h2>Another sub-title</h2>
<p>Some other text</p>
</code>```

Basically they're articles but each article is not inside a single div. So what draws them apart is the  tag. I am interested in parsing the paragraph texts only, where each article should be a separate entity.

What I was thinking about: get the container where the articles are stored in, find the first h1 tag. Start parsing all elements until we reach another h1 tag. When a new h1 tag is reached, process the previously parsed data and start anew.

But I was wondering if a simpler solution is possible?

答:
I can only refine your solution a tiny bit:

Select all h1 elements within the container (rather than just searching through the container's elements one by one)

For each matching h1

Gather up its following siblings until the first h1

Process them

select lets you find the h1s (e.g., .select("selector-for-container > h1"), then nextElementSibling lets you easily traverse forward from each h1 (or nextSibling, but then you have to weed out the non-elements yourself — of course, if there's article content that isn't in a p, you'd want this for the text nodes).

Title: JSoup parsing badly structured HTML

Body:
I have HTML structure that looks like this:

Title

Subtitle

Some text

Some other text

Some other title

Another sub-title

Some other text

Basically they're articles but each article is not inside a single div. So what draws them apart is the  tag. I am interested in parsing the paragraph texts only, where each article should be a separate entity.

What I was thinking about: get the container where the articles are stored in, find the first h1 tag. Start parsing all elements until we reach another h1 tag. When a new h1 tag is reached, process the previously parsed data and start anew.

But I was wondering if a simpler solution is possible?


问:
Flask Limiter - Using more than one key_func for a single endpoint
I'm working on building up an API endpoint w/ flask and flask_limiter, and I'm running into an issue.  My goal is to rate limit on BOTH the client IP address, as well as an API key that the client provides (accessible through flask's "request" module), on a single endpoint.

The IP address limiter is important because I'd like to protect against brute force attacks, whereas the API key limiter is simply for business reasons.  I've built up both rate limiters, and independently they work (i.e. I can limit on the IP address OR the provided API key), but I haven't been able to get both running on the endpoint at the same time.  An example of what I've tried out so far:

```<code>from flask import Flask, request
from flask_limiter import Limiter
from flask_limiter.util import get_remote_address

app = Flask(__name__)
ip_limiter = Limiter(app, key_func=get_remote_address)
get_api_key = lambda : request.args.get('apikey')
api_key_limiter = Limiter(app, key_func=get_api_key)

@app.route('/theEndpoint')
@ip_limiter.limit('some_limit_here')
@api_key_limiter.limit('other_limit_here')
def theEndpointFunction(...):
    .......
</code>```

It would be nice to implement all rate limits in a single package (i.e. flask_limiter), but thus far the only way I can think to implement rate limits on multiple keys is to switch over to something like redis.

Any clues on a way to implement multi-key rate-limits with flask_limiter?

答:
In case anyone is interested, I've decided to switch over to Redis to implement my dual-key rate limit.  The solution goes something like this:

```<code>class RateLimit(object):
    def __init__(self, key, max_requests, seconds):
        self.reset = int(time.time()) + seconds
        self.key = key
        self.max_requests = max_requests
        self.seconds = seconds
        p = redis.pipeline()
        p.incr(self.key)
        p.expireat(self.key, self.reset)
        self.current = min(p.execute()[0], max_requests)
    remaining = property(lambda x: x.max_requests - x.current)
    over_limit = property(lambda x: x.current >= x.max_requests)

def get_view_rate_limit():
    return getattr(g, '_view_rate_limit', None)

def over_limit(limit):
    #formatting a JSON response
    response = {"result": "Max number of requests exceeded",
                "status": False}
    response = jsonify(response)
    response.status_code = 400
    return response

def ratelimit(max_requests, seconds, key_func, over_limit=over_limit):
    def decorator(f):
        def rate_limited(*args, **kwargs):
            key = key_func()
            rlimit = RateLimit(key, max_requests, seconds)
            g._view_rate_limit = rlimit
            if over_limit is not None and rlimit.over_limit:
                return over_limit(rlimit)
            return f(*args, **kwargs)
        return update_wrapper(rate_limited, f)
    return decorator

RATE_LIMIT_FUNCS = {'apikey': lambda: request.args.get('apikey'),
                    'ip': lambda: get_remote_address}
</code>```

and then decorating the flask endpoint:

```<code>@app.route('/theEndpoint')
@ratelimit(max_requests=5, seconds=300, key_func=RATE_LIMIT_FUNCS['apikey'])
@ratelimit(max_requests=15, seconds=300, key_func=RATE_LIMIT_FUNCS['ip'])
def theEndpointFunction():
    ....
</code>```

Body:
I'm working on building up an API endpoint w/ flask and flask_limiter, and I'm running into an issue.  My goal is to rate limit on BOTH the client IP address, as well as an API key that the client provides (accessible through flask's "request" module), on a single endpoint.

The IP address limiter is important because I'd like to protect against brute force attacks, whereas the API key limiter is simply for business reasons.  I've built up both rate limiters, and independently they work (i.e. I can limit on the IP address OR the provided API key), but I haven't been able to get both running on the endpoint at the same time.  An example of what I've tried out so far:

from flask import Flask, request
from flask_limiter import Limiter
from flask_limiter.util import get_remote_address

app = Flask(__name__)
ip_limiter = Limiter(app, key_func=get_remote_address)
get_api_key = lambda : request.args.get('apikey')
api_key_limiter = Limiter(app, key_func=get_api_key)

@app.route('/theEndpoint')
@ip_limiter.limit('some_limit_here')
@api_key_limiter.limit('other_limit_here')
def theEndpointFunction(...):
    .......

It would be nice to implement all rate limits in a single package (i.e. flask_limiter), but thus far the only way I can think to implement rate limits on multiple keys is to switch over to something like redis.

Any clues on a way to implement multi-key rate-limits with flask_limiter?

Body:
In case anyone is interested, I've decided to switch over to Redis to implement my dual-key rate limit.  The solution goes something like this:

class RateLimit(object):
    def __init__(self, key, max_requests, seconds):
        self.reset = int(time.time()) + seconds
        self.key = key
        self.max_requests = max_requests
        self.seconds = seconds
        p = redis.pipeline()
        p.incr(self.key)
        p.expireat(self.key, self.reset)
        self.current = min(p.execute()[0], max_requests)
    remaining = property(lambda x: x.max_requests - x.current)
    over_limit = property(lambda x: x.current >= x.max_requests)

def get_view_rate_limit():
    return getattr(g, '_view_rate_limit', None)

def over_limit(limit):
    #formatting a JSON response
    response = {"result": "Max number of requests exceeded",
                "status": False}
    response = jsonify(response)
    response.status_code = 400
    return response

def ratelimit(max_requests, seconds, key_func, over_limit=over_limit):
    def decorator(f):
        def rate_limited(*args, **kwargs):
            key = key_func()
            rlimit = RateLimit(key, max_requests, seconds)
            g._view_rate_limit = rlimit
            if over_limit is not None and rlimit.over_limit:
                return over_limit(rlimit)
            return f(*args, **kwargs)
        return update_wrapper(rate_limited, f)
    return decorator

RATE_LIMIT_FUNCS = {'apikey': lambda: request.args.get('apikey'),
                    'ip': lambda: get_remote_address}

and then decorating the flask endpoint:

@app.route('/theEndpoint')
@ratelimit(max_requests=5, seconds=300, key_func=RATE_LIMIT_FUNCS['apikey'])
@ratelimit(max_requests=15, seconds=300, key_func=RATE_LIMIT_FUNCS['ip'])
def theEndpointFunction():
    ....


问:
Image Conversion library: Word, PDF, Excel to Images
We have a requirement to convert any incoming documents which are either in Excel, PDF and Word to images. Any recommendation?

I am NOT sure whether ImageMagik would do this but my understanding it is ONLY for format conversion of images and I guess handles PDF as well. What about Excel and Word?

Thanks in advance

答:
You're correct -- imagemagick won't handle the MS Office formats because it only handles image format conversion.

For PDFs, can just use imagemagick directly:

```<code>convert -density 400 filename.pdf filename.jpeg
</code>```

It will give you files:

filename[0].jpg

filename[2].jpg

...

filename[N-1].jpg

Where N was the number of pages in your document.  pdf2ps will achieve the same thing, but you'll need to play around with the command-line parameters to get the same output quality.

For the MS Office products, I remember that there is some sort of API that allows you access to the suite's features (this was MS Office 2007, from memory), like opening a file and exporting it to PDF.  If you can get things out to PDF, then you can use the method above to convert it to images.  Some negative points:

This was many years ago at my previous job, and I can't remember what exactly it was called or how to use it.

I remember the output PDF formatting wasn't great (not 100% like it appears on the screen) but it readable.  This may have improved since I last used it.

I have a vague recollection of it firing up an Excel window in the background, so it's not entirely a command-line solution (may be unsuitable for servers)

Body:
You're correct -- imagemagick won't handle the MS Office formats because it only handles image format conversion.

For PDFs, can just use imagemagick directly:

convert -density 400 filename.pdf filename.jpeg

It will give you files:

filename[0].jpg

filename[2].jpg

...

filename[N-1].jpg

Where N was the number of pages in your document.  pdf2ps will achieve the same thing, but you'll need to play around with the command-line parameters to get the same output quality.

For the MS Office products, I remember that there is some sort of API that allows you access to the suite's features (this was MS Office 2007, from memory), like opening a file and exporting it to PDF.  If you can get things out to PDF, then you can use the method above to convert it to images.  Some negative points:

This was many years ago at my previous job, and I can't remember what exactly it was called or how to use it.

I remember the output PDF formatting wasn't great (not 100% like it appears on the screen) but it readable.  This may have improved since I last used it.

I have a vague recollection of it firing up an Excel window in the background, so it's not entirely a command-line solution (may be unsuitable for servers)


问:
Gradient overlay on element on the right side
I have created a container with elements that is scrollable. I want the element on the right side to have a gradient overlay. How can I create that with CSS?

.container {
  display: flex;
  flex-wrap: nowrap;
  overflow-x: scroll;
  width: 1000px;
}

.element {
  min-width: 200px;
  height: 100px;
  background-color: red;
  margin-right: 10px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
  <div class="element">
  </div>
  <div class="element">
  </div>
  <div class="element">
  </div>
  <div class="element">
  </div>
  <div class="element">
  </div>
  <div class="element">
  </div>
  <div class="element">
  </div>
</div></code>```

https://codepen.io/naomilea/pen/RjZGaM

答:
If you are just looking for the last element to have a gradient color, you can code your css like this:

   .container {

  display: flex;
  flex-wrap: nowrap;
  overflow-x: scroll;
  width: 1000px;
}
.element {
    min-width: 200px;
    height: 100px;
    background-color: grey;
    margin-right: 10px;

  }
.element:last-child
{
  background: -webkit-linear-gradient(to right, grey, white);
  background: -o-linear-gradient(to right, grey, white);
  background: -moz-linear-gradient(to right, grey, white);
  background: linear-gradient(to right, grey, white);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
  <div class="element">
  </div>
   <div class="element">
  </div>
   <div class="element">
  </div>
   <div class="element">
  </div>
   <div class="element">
  </div>
   <div class="element">
  </div>
 <div class="element">
  </div>

</div></code>```

Check updated codepen

Body:
I have created a container with elements that is scrollable. I want the element on the right side to have a gradient overlay. How can I create that with CSS?

.container {
  display: flex;
  flex-wrap: nowrap;
  overflow-x: scroll;
  width: 1000px;
}

.element {
  min-width: 200px;
  height: 100px;
  background-color: red;
  margin-right: 10px;
}

https://codepen.io/naomilea/pen/RjZGaM

Body:
If you are just looking for the last element to have a gradient color, you can code your css like this:

   .container {

  display: flex;
  flex-wrap: nowrap;
  overflow-x: scroll;
  width: 1000px;
}
.element {
    min-width: 200px;
    height: 100px;
    background-color: grey;
    margin-right: 10px;

  }
.element:last-child
{
  background: -webkit-linear-gradient(to right, grey, white);
  background: -o-linear-gradient(to right, grey, white);
  background: -moz-linear-gradient(to right, grey, white);
  background: linear-gradient(to right, grey, white);
}

<div class="container">
  <div class="element">
  </div>
   <div class="element">
  </div>
   <div class="element">
  </div>
   <div class="element">
  </div>
   <div class="element">
  </div>
   <div class="element">
  </div>
 <div class="element">
  </div>

</div>

Check updated codepen


问:
Need to reduce try and except statements
I have this piece of code (below). I have data in json file and I fetch the data (code below). I zip these values and write them to csv file.
My issue is that if any of the value doesn't exist in try I want to put a 'None' over there for that value. What I tried (I think is lame) -> I added try and except for each values that I am fetching below. I need help in writing this better.

The Exception tells me what value is missing. For example, code is missing. So how to I deal with this in except and put None for code?

```<code> for i in range(len(res_1)):
        try:
            gp_code.append(res_1[i]['metadata']['annotations']['code'])
            ticket.append(res_1[i]['metadata']['annotations']['ticket'])
            node.append(res_1[i]['metadata']['annotations']['node-selector'])
            display_name.append(res_1[i]['metadata']['name'])
            status.append(res_1[i]['status']['phase'])
            timer.append(res_1[i]['metadata']['creationTimestamp'])
            lifetime.append(res_1[i]['metadata']['annotations']['lifetime'])
        except Exception as e:
            print(e)
</code>```

答:
You can use get with appropriate default values and avoid exception handling alltogether:

```<code>for x in res_1:
    gp_code.append(x.get('metadata', {}).get('annotations', {}).get('code', None)
    # ...
</code>```

Or you can put the exception/default value handling in a function:

```<code>def _append(lst, obj, *items):
    try:
        for item in items:
            obj = obj[item]
        lst.append(obj)
    except KeyError:
        lst.append(None)

for x in res_1:
    _append(gp_code, x, 'metadata', 'annotations', 'code')
    # ...
</code>```

Body:
I have this piece of code (below). I have data in json file and I fetch the data (code below). I zip these values and write them to csv file.
My issue is that if any of the value doesn't exist in try I want to put a 'None' over there for that value. What I tried (I think is lame) -> I added try and except for each values that I am fetching below. I need help in writing this better.

The Exception tells me what value is missing. For example, code is missing. So how to I deal with this in except and put None for code?

 for i in range(len(res_1)):
        try:
            gp_code.append(res_1[i]['metadata']['annotations']['code'])
            ticket.append(res_1[i]['metadata']['annotations']['ticket'])
            node.append(res_1[i]['metadata']['annotations']['node-selector'])
            display_name.append(res_1[i]['metadata']['name'])
            status.append(res_1[i]['status']['phase'])
            timer.append(res_1[i]['metadata']['creationTimestamp'])
            lifetime.append(res_1[i]['metadata']['annotations']['lifetime'])
        except Exception as e:
            print(e)

Body:
You can use get with appropriate default values and avoid exception handling alltogether:

for x in res_1:
    gp_code.append(x.get('metadata', {}).get('annotations', {}).get('code', None)
    # ...

Or you can put the exception/default value handling in a function:

def _append(lst, obj, *items):
    try:
        for item in items:
            obj = obj[item]
        lst.append(obj)
    except KeyError:
        lst.append(None)

for x in res_1:
    _append(gp_code, x, 'metadata', 'annotations', 'code')
    # ...


问:
Using VARRAYs to overlap time series data
I have some data want to overlap, I do it like below. and there may be some more smarter methods, since the data is very big, please advise.

Here is my VArray:

```<code>CREATE OR REPLACE TYPE NUMBER_VARRAY_5 AS VARRAY (5) OF NUMBER NOT NULL
</code>```

Here is the original data (table TEST_1)

```<code>"DATE_A","TOTO3_A"
"01/01/2005","281.25"
"02/01/2005","-9999.00"
"03/01/2005","291.50"
"04/01/2005","310.50"
"05/01/2005","298.75"
"06/01/2005","300.75"
</code>```

The table TEST_2 is the result of overlapping by date lag 1 day and fixed days (5 days)

```<code>"DATE_START","DATE_END","O3"
"01/01/2005","05/01/2005","<Collection>"
1      281.25
2      -9999
3      291.5
4      310.5
5      298.75
"02/01/2005","06/01/2005","<Collection>"
1      -9999
2      291.5
3      310.5
4      298.75
5      300.75
</code>```

Here is my code to do this

```<code>CREATE OR REPLACE PROCEDURE TEST
IS
   NUMBER_VARRAY   NUMBER_VARRAY_5 := NUMBER_VARRAY_5 ();
   L_VALUE         NUMBER;
   MIN_DATE        DATE;
   MAX_DATE        DATE;

BEGIN
   SELECT MIN (DATE_A), MAX (DATE_A)
     INTO MIN_DATE, MAX_DATE
     FROM TEST_1;

   FOR CUR_R IN 0 .. (MAX_DATE - MIN_DATE - 4)
   LOOP
      L_VALUE := 0;

      FOR I IN CUR_R .. (CUR_R + 4)
      LOOP
         L_VALUE := L_VALUE + 1;
         NUMBER_VARRAY.EXTEND;

         SELECT TOTO3_A
           INTO NUMBER_VARRAY (L_VALUE)
           FROM TEST_1
          WHERE DATE_A = MIN_DATE + I;
      END LOOP;

      INSERT INTO TEST_2 (DATE_START, DATE_END, O3)
           VALUES (MIN_DATE + CUR_R, (MIN_DATE + CUR_R + 4), NUMBER_VARRAY);

      COMMIT;

      NUMBER_VARRAY.DELETE ();
   END LOOP;
END TEST;
</code>```

答:
I think you can do this in pure SQL using the COLLECT function:

```<code>with dt as ( select max(date_a)-4 as mx from TEST_1 )
   , dr as ( select date_a as date_start
                    , date_a + 4 as date_end
            from TEST_1
                 cross join dt
             where date_a <= dt.mx )
select dr.*
       , cast(collect(TEST_1.toto3_a) as NUMBER_VARRAY_5) as coll03
from TEST_1
      cross join dr
where TEST_1.date_a between dr.date_start and dr.date_end
group by dr.date_start, dr.date_end
order by dr.date_start
/
</code>```

" there are some errors:ORA-22814: attribute or element value is larger than specified in type"

Hmmmm, try this piece of voodoo:

```<code> cast(collect(cast(TEST_1.toto3_a as number)) as NUMBER_VARRAY_5)
</code>```

Body:
I have some data want to overlap, I do it like below. and there may be some more smarter methods, since the data is very big, please advise.

Here is my VArray:

CREATE OR REPLACE TYPE NUMBER_VARRAY_5 AS VARRAY (5) OF NUMBER NOT NULL

Here is the original data (table TEST_1)

"DATE_A","TOTO3_A"
"01/01/2005","281.25"
"02/01/2005","-9999.00"
"03/01/2005","291.50"
"04/01/2005","310.50"
"05/01/2005","298.75"
"06/01/2005","300.75"

The table TEST_2 is the result of overlapping by date lag 1 day and fixed days (5 days)

"DATE_START","DATE_END","O3"
"01/01/2005","05/01/2005","<Collection>"
1      281.25
2      -9999
3      291.5
4      310.5
5      298.75
"02/01/2005","06/01/2005","<Collection>"
1      -9999
2      291.5
3      310.5
4      298.75
5      300.75

Here is my code to do this

CREATE OR REPLACE PROCEDURE TEST
IS
   NUMBER_VARRAY   NUMBER_VARRAY_5 := NUMBER_VARRAY_5 ();
   L_VALUE         NUMBER;
   MIN_DATE        DATE;
   MAX_DATE        DATE;

BEGIN
   SELECT MIN (DATE_A), MAX (DATE_A)
     INTO MIN_DATE, MAX_DATE
     FROM TEST_1;

   FOR CUR_R IN 0 .. (MAX_DATE - MIN_DATE - 4)
   LOOP
      L_VALUE := 0;

      FOR I IN CUR_R .. (CUR_R + 4)
      LOOP
         L_VALUE := L_VALUE + 1;
         NUMBER_VARRAY.EXTEND;

         SELECT TOTO3_A
           INTO NUMBER_VARRAY (L_VALUE)
           FROM TEST_1
          WHERE DATE_A = MIN_DATE + I;
      END LOOP;

      INSERT INTO TEST_2 (DATE_START, DATE_END, O3)
           VALUES (MIN_DATE + CUR_R, (MIN_DATE + CUR_R + 4), NUMBER_VARRAY);

      COMMIT;

      NUMBER_VARRAY.DELETE ();
   END LOOP;
END TEST;

Body:
I think you can do this in pure SQL using the COLLECT function:

with dt as ( select max(date_a)-4 as mx from TEST_1 )
   , dr as ( select date_a as date_start
                    , date_a + 4 as date_end
            from TEST_1
                 cross join dt
             where date_a <= dt.mx )
select dr.*
       , cast(collect(TEST_1.toto3_a) as NUMBER_VARRAY_5) as coll03
from TEST_1
      cross join dr
where TEST_1.date_a between dr.date_start and dr.date_end
group by dr.date_start, dr.date_end
order by dr.date_start
/

" there are some errors:ORA-22814: attribute or element value is larger than specified in type"

Hmmmm, try this piece of voodoo:

 cast(collect(cast(TEST_1.toto3_a as number)) as NUMBER_VARRAY_5)


问:
Why textbox is not appearing on Clicking the CREDIT/DEBIT radiobutton in C# .net?
And this is my aspx.cs file

```<code>protected void RadioButton1_CheckedChanged(object sender, EventArgs e)
{
    TextBox2.Visible = true;
}

protected void Button1_Click(object sender, EventArgs e)
{
    TextBox1.ReadOnly = false;
}

protected void RadioButton2_CheckedChanged(object sender, EventArgs e)
{
    TextBox2.Visible = false;
}
</code>```

Why does the textbox not appear when the CREDIT/DEBIT radioButton is checked?

答:
You have to use  AutoPostBack="true" and you can use the below code. Its working

Aspx

```<code><%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="Stack_Overflow.WebForm1" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" />
        <asp:RadioButton ID="RadioButton1" AutoPostBack="true" runat="server" Text="Credit" OnCheckedChanged="RadioButton1_CheckedChanged" GroupName="a">

        </asp:RadioButton>
        <asp:RadioButton ID="RadioButton2" AutoPostBack="true" runat="server" Text="Debit" OnCheckedChanged="RadioButton2_CheckedChanged" GroupName="a" />
        <br />
        <asp:Label ID="Label6" runat="server" Text="Label"></asp:Label>
        <br />
        <asp:Label ID="Label7" runat="server" Text="Label"></asp:Label>
        <br />
        <asp:Label ID="Label8" runat="server" Text="Label"></asp:Label>

        <asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
        <asp:TextBox ID="TextBox3" runat="server"></asp:TextBox>
        <asp:TextBox ID="TextBox4" runat="server"></asp:TextBox>

        <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
    </div>
    </form>

</body>
</html>
</code>```

code behind file

```<code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace Stack_Overflow
{
    public partial class WebForm1 : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

        }

        protected void RadioButton1_CheckedChanged(object sender, EventArgs e)
        {
            Label6.Visible = true;
            Label7.Visible = true;
            Label8.Visible = true;
            TextBox2.Visible = true;
            TextBox3.Visible = true;
            TextBox4.Visible = true;
        }

        protected void Button1_Click(object sender, EventArgs e)
        {
            TextBox1.ReadOnly = false;
        }

        protected void RadioButton2_CheckedChanged(object sender, EventArgs e)
        {
            Label6.Visible = false;
            Label7.Visible = false;
            Label8.Visible = false;
            TextBox2.Visible = false;
            TextBox3.Visible = false;
            TextBox4.Visible = false;
        }
    }
}
</code>```

do let me know in case you face any issue

Body:
And this is my aspx.cs file

protected void RadioButton1_CheckedChanged(object sender, EventArgs e)
{
    TextBox2.Visible = true;
}

protected void Button1_Click(object sender, EventArgs e)
{
    TextBox1.ReadOnly = false;
}

protected void RadioButton2_CheckedChanged(object sender, EventArgs e)
{
    TextBox2.Visible = false;
}

Why does the textbox not appear when the CREDIT/DEBIT radioButton is checked?

Body:
You have to use  AutoPostBack="true" and you can use the below code. Its working

Aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="Stack_Overflow.WebForm1" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" />
        <asp:RadioButton ID="RadioButton1" AutoPostBack="true" runat="server" Text="Credit" OnCheckedChanged="RadioButton1_CheckedChanged" GroupName="a">

        </asp:RadioButton>
        <asp:RadioButton ID="RadioButton2" AutoPostBack="true" runat="server" Text="Debit" OnCheckedChanged="RadioButton2_CheckedChanged" GroupName="a" />
        <br />
        <asp:Label ID="Label6" runat="server" Text="Label"></asp:Label>
        <br />
        <asp:Label ID="Label7" runat="server" Text="Label"></asp:Label>
        <br />
        <asp:Label ID="Label8" runat="server" Text="Label"></asp:Label>

        <asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
        <asp:TextBox ID="TextBox3" runat="server"></asp:TextBox>
        <asp:TextBox ID="TextBox4" runat="server"></asp:TextBox>

        <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
    </div>
    </form>

</body>
</html>

code behind file

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace Stack_Overflow
{
    public partial class WebForm1 : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

        }

        protected void RadioButton1_CheckedChanged(object sender, EventArgs e)
        {
            Label6.Visible = true;
            Label7.Visible = true;
            Label8.Visible = true;
            TextBox2.Visible = true;
            TextBox3.Visible = true;
            TextBox4.Visible = true;
        }

        protected void Button1_Click(object sender, EventArgs e)
        {
            TextBox1.ReadOnly = false;
        }

        protected void RadioButton2_CheckedChanged(object sender, EventArgs e)
        {
            Label6.Visible = false;
            Label7.Visible = false;
            Label8.Visible = false;
            TextBox2.Visible = false;
            TextBox3.Visible = false;
            TextBox4.Visible = false;
        }
    }
}

do let me know in case you face any issue


问:
How to get the value of the href attribute?
With the help of XPath, how to get the value of the href attribute in the following case (only grabbing the url that is the right one)?:

```<code><a href="http://foo.com">a wrong one</a>
<a href="http://example.com">the right one</a>
<a href="http://boo.com">a wrong one</a>
</code>```

That is, to get the value of the href attribute if the link has a particular text.

答:
Here's a full example using SimpleXML:</p>

```<code>$xml = '<html><a href="http://foo.com">a wrong one</a>'
        . '<a href="http://example.com">the right one</a>'
        . '<a href="http://boo.com">a wrong one</a></html>';
$tree = simplexml_load_string($xml);
$nodes = $tree->xpath('//a[text()="the right one"]');
$href = (string) $nodes[0]['href'];
</code>```

Body:
With the help of XPath, how to get the value of the href attribute in the following case (only grabbing the url that is the right one)?:

a wrong one
the right one
a wrong one

That is, to get the value of the href attribute if the link has a particular text.

Body:
Here's a full example using SimpleXML:

$xml = '<html><a href="http://foo.com">a wrong one</a>'
        . '<a href="http://example.com">the right one</a>'
        . '<a href="http://boo.com">a wrong one</a></html>';
$tree = simplexml_load_string($xml);
$nodes = $tree->xpath('//a[text()="the right one"]');
$href = (string) $nodes[0]['href'];


答:
Specify new index with $('.trToClone').length, modify it on each element with name attribute with jQuery .attr() method:

$("input.addField").on('click', function() {
  var $tr = $(this).closest('.trToClone');
  var $clone = $tr.clone(true, true);

  var $names = $clone.find('[name]');
  var trIndex = $('.trToClone').length;

  $names.each(function(index, element) {

    var newName = $(element).attr('name').replace(/[0-9]/g, trIndex);

    $(element).attr('name', newName);

    console.log($(element).attr('name'));

  });

  $clone.find(':text').val('');
  $tr.after($clone);
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
 <table>
  <tr class="trToClone">
    <td>
      <label>Username:</label>
      <input type="text" name="username[0]" />
    </td>
    <td>
      <label>Level:</label>
      <select name="level[0]">
        <option value="">---</option>
        <option value="a">A</option>
        <option value="b">B</option>
        <option value="c">C</option>
      </select>
    </td>
    <td><input type="button" class="addField" value="Add" /></td>
  </tr>
 </table>
</form></code>```

Title: Increase index of a form's input field's name attribute in a dynamic form

Body:
Suppose I have this form with indexed input fields username and level:

<form>

      Username:
      <input type="text" name="username[0]" />

      Level:
      <select name="level[0]">
        <option value="">---</option>
        <option value="a">A</option>
        <option value="b">B</option>
        <option value="c">C</option>
      </select>

    <input type="button" class="addField" value="Add" />

</form>

The row can be repeated using this jQuery:

$("input.addField").on('click', function() {
  var $tr = $(this).closest('.trToClone');
  var $clone = $tr.clone();
  $clone.find(':text').val('');
  $tr.after($clone);
});

Now for every subsequent row I add, I want to increase the indices of the name attribute (i.e. username[1],level[1]; username[2],level[2]; and so on...). How can I do this? I've looked for possible solutions, but to no avail.

Body:
Specify new index with $('.trToClone').length, modify it on each element with name attribute with jQuery .attr() method:

$("input.addField").on('click', function() {
  var $tr = $(this).closest('.trToClone');
  var $clone = $tr.clone(true, true);

  var $names = $clone.find('[name]');
  var trIndex = $('.trToClone').length;

  $names.each(function(index, element) {

    var newName = $(element).attr('name').replace(/[0-9]/g, trIndex);

    $(element).attr('name', newName);

    console.log($(element).attr('name'));

  });

  $clone.find(':text').val('');
  $tr.after($clone);
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
 <table>
  <tr class="trToClone">
    <td>
      <label>Username:</label>
      <input type="text" name="username[0]" />
    </td>
    <td>
      <label>Level:</label>
      <select name="level[0]">
        <option value="">---</option>
        <option value="a">A</option>
        <option value="b">B</option>
        <option value="c">C</option>
      </select>
    </td>
    <td><input type="button" class="addField" value="Add" /></td>
  </tr>
 </table>
</form>


问:
how to check the a bunch of users is in online/offline and it is online show green dots or else red dot using typescript in angular4
this is my component.ts code.Really I don't know about that one just I am trying .whether it is correct or wrong however I want to show the if users are in online besides username shows green button or else red dot button</p>

```<code> onlineCheck()
      {
        let xhr = new XMLHttpRequest();
        return new Promise((resolve, reject)=>{
            xhr.onload = () => {
                // Set online status
                this.isOnline = true;
                resolve(true);
                console.log("user is in online "+this.isOnline);
            };
            xhr.onerror = () => {
                // Set online status
                this.isOnline = false;
                reject(false);
                console.log("user is in offline "+this.isOnline);

            };
            xhr.open('GET',this.onlineURL(this.appl_name,this.s_name), true);
            console.log("live Url "+this.onlineURL(this.appl_name,this.s_name));
            xhr.send();
        });
</code>```

答:
This is sample code you can simpleify or customize based on your requirement.
Many useful features are available in Socketio refer here for further change here.

Server code:

```<code>var app = require('http').createServer(handler)
var io = require('socket.io')(app);
var fs = require('fs');

app.listen(80);

function handler (req, res) {
   fs.readFile(__dirname + '/index.html',
      function (err, data) {
         if (err) {
             res.writeHead(500);
             return res.end('Error loading index.html');
         }
   res.writeHead(200);
   res.end(data);
   });
 }

 io.on('connection', function (socket) {
   socket.on('myOnlineStatus', function (data) {
     console.log(data);
   });
 });
</code>```

Client code:

```<code> var socket = io('http://localhost');
 socket.on('myOnlineStatus', function (data) {
   console.log(data);
   // Write logic to identify each user and update network status
   // You will get status of each user every 10 seconds
 });
 setInterval(() => {
           socket.emit('my other event', { myId: 'Raja', status : navigator.onLine });
     }, 10000);
</code>```

Body:
this is my component.ts code.Really I don't know about that one just I am trying .whether it is correct or wrong however I want to show the if users are in online besides username shows green button or else red dot button

 onlineCheck()
      {
        let xhr = new XMLHttpRequest();
        return new Promise((resolve, reject)=>{
            xhr.onload = () => {
                // Set online status
                this.isOnline = true;
                resolve(true);
                console.log("user is in online "+this.isOnline);
            };
            xhr.onerror = () => {
                // Set online status
                this.isOnline = false;
                reject(false);
                console.log("user is in offline "+this.isOnline);

            };
            xhr.open('GET',this.onlineURL(this.appl_name,this.s_name), true);
            console.log("live Url "+this.onlineURL(this.appl_name,this.s_name));
            xhr.send();
        });

Body:
This is sample code you can simpleify or customize based on your requirement.
Many useful features are available in Socketio refer here for further change here.

Server code:

var app = require('http').createServer(handler)
var io = require('socket.io')(app);
var fs = require('fs');

app.listen(80);

function handler (req, res) {
   fs.readFile(__dirname + '/index.html',
      function (err, data) {
         if (err) {
             res.writeHead(500);
             return res.end('Error loading index.html');
         }
   res.writeHead(200);
   res.end(data);
   });
 }

 io.on('connection', function (socket) {
   socket.on('myOnlineStatus', function (data) {
     console.log(data);
   });
 });

Client code:

 var socket = io('http://localhost');
 socket.on('myOnlineStatus', function (data) {
   console.log(data);
   // Write logic to identify each user and update network status
   // You will get status of each user every 10 seconds
 });
 setInterval(() => {
           socket.emit('my other event', { myId: 'Raja', status : navigator.onLine });
     }, 10000);


问:
Prolog how to delete from a list of lists
I'm trying to delete an element form a list of lists. This is an example of what I'm trying to do:

```<code>List=[[1,2],[1,3],[4,2]]
Max=2
delete(List,[_|Max],List2)
List2=[[1,3]]
</code>```

Explanation: so given List I'm trying to use delete/3 to remove every element that has Max as its second element in its sub list. I'm not sure if this is possible with the standard delete/3 predicate. Thanks for the help!

This is what I have tried so far for my own predicate. I realize this isn't working and won't do what I want it.

```<code>second_element(E, []).
second_element(E,L):-
   member(X,L),
   X==[_,E],
   delete(L,X,L2),
   second_element(E,L2).
</code>```

答:
I'm not going to just give you the answer to your assignment. But I can give you a pattern commonly used in Prolog that it follows. This plus the hint I provided in comments are all the tools you need to solve the problem.

If you have a list, L, and you want another list, RL, that omits those elements of L that meet a certain criteria, then this is handled with a common recursive pattern:

```<code>filtered_list([], []).     % The empty list is a filtered version of the empty list

filtered_list([H|T], R) :-
    (   meets_criteria_for_omission(H)
    ->  R = RT                 % R will not have H if it meets criteria for omission
    ;   R = [H|RT]             % R will have H if it does not meet criteria for omission
    ),
    filtered_list(T, RT).
</code>```

In the case of the original problem, the criteria for omission is that the element being checked is a list whose second element is given. That means that element being checked against must be provided as an argument. And the criteria to check is whether it is the second element of the given list.

This is as much information as I can give without simply handing over the complete answer, but it's 85% of the way there. Time to use the noodle.

Body:
I'm trying to delete an element form a list of lists. This is an example of what I'm trying to do:

List=[[1,2],[1,3],[4,2]]
Max=2
delete(List,[_|Max],List2)
List2=[[1,3]]

Explanation: so given List I'm trying to use delete/3 to remove every element that has Max as its second element in its sub list. I'm not sure if this is possible with the standard delete/3 predicate. Thanks for the help!

This is what I have tried so far for my own predicate. I realize this isn't working and won't do what I want it.

second_element(E, []).
second_element(E,L):-
   member(X,L),
   X==[_,E],
   delete(L,X,L2),
   second_element(E,L2).

Body:
I'm not going to just give you the answer to your assignment. But I can give you a pattern commonly used in Prolog that it follows. This plus the hint I provided in comments are all the tools you need to solve the problem.

If you have a list, L, and you want another list, RL, that omits those elements of L that meet a certain criteria, then this is handled with a common recursive pattern:

filtered_list([], []).     % The empty list is a filtered version of the empty list

filtered_list([H|T], R) :-
    (   meets_criteria_for_omission(H)
    ->  R = RT                 % R will not have H if it meets criteria for omission
    ;   R = [H|RT]             % R will have H if it does not meet criteria for omission
    ),
    filtered_list(T, RT).

In the case of the original problem, the criteria for omission is that the element being checked is a list whose second element is given. That means that element being checked against must be provided as an argument. And the criteria to check is whether it is the second element of the given list.

This is as much information as I can give without simply handing over the complete answer, but it's 85% of the way there. Time to use the noodle.