问:
How to add jQuery element to the end of existing elements (instead of appending it to each)?
In order to make appendTo work, there must be a wrapper, otherwise it will add two copies (one to each div):

```<code>let $canvas = $(`<div></div>`, {html: `<div>1</div><div>2</div>`});
let $editor = $(`<div></div>`);
$editor.appendTo($canvas);
initializeEditor($editor);
</code>```

Is there a method to add to the end so that the wrap isn't necessary? I tried insertAfter like this, but it doesn't seem to do anything:

```<code>let $canvas = $(`<div>1</div><div>2</div>`);
let $editor = $(`<div></div>`);
$editor.insertAfter($canvas);
initializeEditor($editor);
</code>```

答:
Given your specific scenario, I would advise you to switch back to plain strings.

```<code>let canvas = '<div>1</div><div>2</div>';
let editor = '<div></div>';

canvas += editor;
initializeEditor($(canvas));
</code>```

Or something like that.  Now why do I suggest this?  Becase each time you do $(html) you are making jQuery parse the html into DOM nodes, in a document fragment.  Switching back to strings, you remove those two operations in favor of a simple string concatenation.

Then once you have the html down, you can pass it into your method as a jQuery object if you need it to be like that then.

Otherwise, you can either reduce the scope of the elements you are inserting after...

```<code>$editor.insertAfter($canvas.last())
</code>```

Or just add the element to the end of the jQuery object result stack...

```<code>$canvas.add(...html...)
</code>```

Body:
In order to make appendTo work, there must be a wrapper, otherwise it will add two copies (one to each div):

let $canvas = $(`<div></div>`, {html: `<div>1</div><div>2</div>`});
let $editor = $(`<div></div>`);
$editor.appendTo($canvas);
initializeEditor($editor);

Is there a method to add to the end so that the wrap isn't necessary? I tried insertAfter like this, but it doesn't seem to do anything:

let $canvas = $(`<div>1</div><div>2</div>`);
let $editor = $(`<div></div>`);
$editor.insertAfter($canvas);
initializeEditor($editor);

Body:
Given your specific scenario, I would advise you to switch back to plain strings.

let canvas = '<div>1</div><div>2</div>';
let editor = '<div></div>';

canvas += editor;
initializeEditor($(canvas));

Or something like that.  Now why do I suggest this?  Becase each time you do $(html) you are making jQuery parse the html into DOM nodes, in a document fragment.  Switching back to strings, you remove those two operations in favor of a simple string concatenation.

Then once you have the html down, you can pass it into your method as a jQuery object if you need it to be like that then.

Otherwise, you can either reduce the scope of the elements you are inserting after...

$editor.insertAfter($canvas.last())

Or just add the element to the end of the jQuery object result stack...

$canvas.add(...html...)


来源: stackexchange

问:
T-SQL - Employee Annual Average
I'm trying to make an annual average of employees, in a year.

The table 'a' is thus constructed:

```<code>CREATE TABLE [dbo]. [A]
(
    [id] [INT] NOT NULL,
    [start] [DATETIME] NOT NULL,
    [end] [DATETIME] NOT NULL,
    [employee_code] [INT] NOT NULL
)

1 - 01/01/2016 - 03/31/2019 - 56
2 - 01/01/1995 - 06/06/2017 - 13
-
-
</code>```

If I simply count the [employee_code] between 01/01/2017 and 12/31/2017 the calculation is incorrect as it does not make a monthly average.

Can you help me? (the correct calculation is to have 12 records indicating the monthly number and at the end divided by 12)

I can't do everything with a T-SQL command.

Can you help me?

hello thanks, yes, that's what I was.
Only one thing, in the query result there are the following records:

```<code>1995 1 0 NULL
1995 2 0 NULL
1995 3 0 NULL
1995 4 0 NULL
1995 5 6 NULL
1995 6 6 NULL
1995 7 10 NULL
1995 8 10 NULL
1995 9 10 NULL
1995 10 12 NULL
1995 11 12 NULL
1995 12 12 NULL
NULL 78 1995 6.500000
</code>```

The initial data from which I started are:

```<code>03/04/1995 10/20/2005 4
03/04/1995 19/06/2016 2
03/04/1995 12/15/2016 2847
03/04/1995            1
03/04/1995            5
03/04/1995            3
02/06/1995 03/07/2009 9
02/06/1995            8
02/06/1995            7
02/06/1995            6
09/15/1995 16/05/2017 34
09/15/1995            33
</code>```

why are the 6 "ecodes" in May and not April?

答:
Edited:

```<code>WITH mnths as (
  select CAST('01/15/1995' as date) as mnth UNION ALL
  select DATEADD(month,1,mnth) FROM mnths WHERE mnth<'12/15/2019'
), edata AS (
  SELECT mnth,
  (SELECT count(ecode) FROM @A A
   WHERE mnth between estart AND COALESCE(eend,getdate())) ecnt
  FROM mnths
)
SELECT year(mnth) yr, month(mnth) mn, AVG(ecnt+0.) emplcount
FROM edata
group by year(mnth), month(mnth)
WITH ROLLUP
OPTION (MAXRECURSION 1000)
</code>```

This version takes into account your latest edits and uses ROLLUP to shorten the query code, see demo here:

https://rextester.com/IQAB32422

Unfortunately, your dates were not all correct, considering you used the American syntax month/day/year. For this reason I got slightly different numbers ...

The comparison, whether an employee is employed in a particular month was originally done for the first day of each month. I changed it now to the 15th of each month. But even that is only an "arbitrary" date and will not count employees who were there from 1st to the 14th of a month.

ContentLicense: CC BY-SA 4.0

Title: T-SQL - Employee Annual Average

Body:
I'm trying to make an annual average of employees, in a year.

The table 'a' is thus constructed:

CREATE TABLE [dbo]. [A]
(
    [id] [INT] NOT NULL,
    [start] [DATETIME] NOT NULL,
    [end] [DATETIME] NOT NULL,
    [employee_code] [INT] NOT NULL
)

1 - 01/01/2016 - 03/31/2019 - 56
2 - 01/01/1995 - 06/06/2017 - 13
-
-

If I simply count the [employee_code] between 01/01/2017 and 12/31/2017 the calculation is incorrect as it does not make a monthly average.

Can you help me? (the correct calculation is to have 12 records indicating the monthly number and at the end divided by 12)

I can't do everything with a T-SQL command.

Can you help me?

hello thanks, yes, that's what I was.
Only one thing, in the query result there are the following records:

1995 1 0 NULL
1995 2 0 NULL
1995 3 0 NULL
1995 4 0 NULL
1995 5 6 NULL
1995 6 6 NULL
1995 7 10 NULL
1995 8 10 NULL
1995 9 10 NULL
1995 10 12 NULL
1995 11 12 NULL
1995 12 12 NULL
NULL 78 1995 6.500000

The initial data from which I started are:

03/04/1995 10/20/2005 4
03/04/1995 19/06/2016 2
03/04/1995 12/15/2016 2847
03/04/1995            1
03/04/1995            5
03/04/1995            3
02/06/1995 03/07/2009 9
02/06/1995            8
02/06/1995            7
02/06/1995            6
09/15/1995 16/05/2017 34
09/15/1995            33

why are the 6 "ecodes" in May and not April?

Body:
Edited:

WITH mnths as (
  select CAST('01/15/1995' as date) as mnth UNION ALL
  select DATEADD(month,1,mnth) FROM mnths WHERE mnth<'12/15/2019'
), edata AS (
  SELECT mnth,
  (SELECT count(ecode) FROM @A A
   WHERE mnth between estart AND COALESCE(eend,getdate())) ecnt
  FROM mnths
)
SELECT year(mnth) yr, month(mnth) mn, AVG(ecnt+0.) emplcount
FROM edata
group by year(mnth), month(mnth)
WITH ROLLUP
OPTION (MAXRECURSION 1000)

This version takes into account your latest edits and uses ROLLUP to shorten the query code, see demo here:

https://rextester.com/IQAB32422

Unfortunately, your dates were not all correct, considering you used the American syntax month/day/year. For this reason I got slightly different numbers ...

The comparison, whether an employee is employed in a particular month was originally done for the first day of each month. I changed it now to the 15th of each month. But even that is only an "arbitrary" date and will not count employees who were there from 1st to the 14th of a month.


问:
How to ignore DST adjustments made by java while retrieving date column from an Oracle database?
I have an Oracle table with Date column in it.

```<code>+--------+-----------------------+
|  ID    | CURR_DATE             |
+--------+-----------------------+
|   1    |2003-04-06 02:59:59    |
+--------+-----------------------+
</code>```

When I do a

```<code>select * from tablename
</code>```

in the database console, I get the correct column value for CURR_DATE.

But when I do the same from a java program using JDBC, the time shifts one hour forward due to daylight saving. Here is a link that explains it. https://www.timeanddate.com/time/change/usa/new-york?year=2003.

So I receive the value 2003-04-06 03:59:59 instead of 2003-04-06 02:59:59.

This happens because the DB and the JVM are in PST and PST follows DST.(Pls correct me if I am wrong)

Here is my code

```<code>String query="select * from tablename";
PreparedStatement psmt = con.prepareStatement(query);
ResultSet results=psmt.executeQuery();
while(results.next()) {
    System.out.println(results.getString(2));
}
</code>```

What can be done so that results.getString() returns me the same value which is in the database(without any adjustments).

I want it to return me the original value 2003-04-06 02:59:59 instead of the adjusted value 2003-04-06 03:59:59.

答:
tl;dr

```<code>java.time.LocalDateTime ldt = myResultSet.getObject( … , LocalDateTime.class ) ;
</code>```

Use smart objects, not dumb strings

You storing a date-time value in a date-time column, so use a date-time type in Java. Currently your are using strings.

The Oracle DATE type holds only a date and a time-of-day without any concept of time zone or offset-from-UTC. As such, a DATE column cannot be used to represent a moment. The equivalent in standard SQL is TIMESTAMP WITHOUT TIME ZONE.

For example, if a row stores a value in that column for the 23rd of January of this year at noon, we have know way to know if this is noon in Tokyo, noon in Kolkata, noon in Paris, or noon in Montréal. These various noons all occur in different moments, hours apart.

The appropriate type in Java to match an Oracle DATE column is LocalDateTime. This class also lacks any concept of time zone or offset-from-UTC. So it cannot be used to represent a moment. But when you have only a date and time-of-day without zone/offset, this is the class for you.

JDBC 4.2 and later requires support for directly exchanging java.time objects with the database.

```<code>LocalDateTime ldt = myResultSet.getObject( … , LocalDateTime.class ) ;
</code>```

Writing data.

```<code>myPreparedStatemen.setObject( … , ldt ) ;
</code>```

By exchanging a Java object without any zone/offset with a database column of a types without any zone/offset, you will have no issue with zone/offset. But be aware of the limitations of this kind of date-time value:

Not a moment, not a point on the timeline.

Ambiguous as it could be interpreted as any of many potential moments along a range of about 26-27 hours (the range of time zones around the globe).

Body:
I have an Oracle table with Date column in it.

+--------+-----------------------+
|  ID    | CURR_DATE             |
+--------+-----------------------+
|   1    |2003-04-06 02:59:59    |
+--------+-----------------------+

When I do a

select * from tablename

in the database console, I get the correct column value for CURR_DATE.

But when I do the same from a java program using JDBC, the time shifts one hour forward due to daylight saving. Here is a link that explains it. https://www.timeanddate.com/time/change/usa/new-york?year=2003.

So I receive the value 2003-04-06 03:59:59 instead of 2003-04-06 02:59:59.

This happens because the DB and the JVM are in PST and PST follows DST.(Pls correct me if I am wrong)

Here is my code

String query="select * from tablename";
PreparedStatement psmt = con.prepareStatement(query);
ResultSet results=psmt.executeQuery();
while(results.next()) {
    System.out.println(results.getString(2));
}

What can be done so that results.getString() returns me the same value which is in the database(without any adjustments).

I want it to return me the original value 2003-04-06 02:59:59 instead of the adjusted value 2003-04-06 03:59:59.

Body:
tl;dr

java.time.LocalDateTime ldt = myResultSet.getObject( … , LocalDateTime.class ) ;

Use smart objects, not dumb strings

You storing a date-time value in a date-time column, so use a date-time type in Java. Currently your are using strings.

The Oracle DATE type holds only a date and a time-of-day without any concept of time zone or offset-from-UTC. As such, a DATE column cannot be used to represent a moment. The equivalent in standard SQL is TIMESTAMP WITHOUT TIME ZONE.

For example, if a row stores a value in that column for the 23rd of January of this year at noon, we have know way to know if this is noon in Tokyo, noon in Kolkata, noon in Paris, or noon in Montréal. These various noons all occur in different moments, hours apart.

The appropriate type in Java to match an Oracle DATE column is LocalDateTime. This class also lacks any concept of time zone or offset-from-UTC. So it cannot be used to represent a moment. But when you have only a date and time-of-day without zone/offset, this is the class for you.

JDBC 4.2 and later requires support for directly exchanging java.time objects with the database.

LocalDateTime ldt = myResultSet.getObject( … , LocalDateTime.class ) ;

Writing data.

myPreparedStatemen.setObject( … , ldt ) ;

By exchanging a Java object without any zone/offset with a database column of a types without any zone/offset, you will have no issue with zone/offset. But be aware of the limitations of this kind of date-time value:

Not a moment, not a point on the timeline.

Ambiguous as it could be interpreted as any of many potential moments along a range of about 26-27 hours (the range of time zones around the globe).


问:
T-SQL: How Can I Parse a JSON Array and Extract a Single Property Value?
Given that:

```<code>SELECT * FROM OPENJSON(JSON_QUERY('[{"JobId":"2838","Options":1}, {"JobId":"2839","Options":1}]'))
</code>```

Gives us:

```<code>key value                           type
0   {"JobId":"2838","Options":1}    5
1   {"JobId":"2839","Options":1}    5
</code>```

How can I change my query to return the job ids?

```<code>value
2838
2839
</code>```

答:
This should do it</p>

```<code>SELECT JobId
FROM OPENJSON('[{"JobId":"2838","Options":1}, {"JobId":"2839","Options":1}]')
WITH (JobId INT N'$.JobId');
</code>```

Body:
Given that:

SELECT * FROM OPENJSON(JSON_QUERY('[{"JobId":"2838","Options":1}, {"JobId":"2839","Options":1}]'))

Gives us:

key value                           type
0   {"JobId":"2838","Options":1}    5
1   {"JobId":"2839","Options":1}    5

How can I change my query to return the job ids?

value
2838
2839

Body:
This should do it

SELECT JobId
FROM OPENJSON('[{"JobId":"2838","Options":1}, {"JobId":"2839","Options":1}]')
WITH (JobId INT N'$.JobId');


问:
Can scipy.signal function be called in MATLAB?
I have a python function that I need to call in MATLAB that imports functions from scipy.signal.

However when I attempt to call the function in MATLAB I get an error

```<code>Error using arpack><module> (line 45)
Python Error: ImportError: DLL load failed: The specified procedure could not be found.

Error in __init__><module> (line 22)
from .arpack import *

Error in __init__><module> (line 11)
from .arpack import *

Error in __init__><module> (line 117)
from .eigen import *

Error in _minimize><module> (line 21)
from scipy.sparse.linalg import LinearOperator

Error in __init__><module> (line 271)
from ._minimize import *

Error in filter_design><module> (line 18)
from scipy import special, optimize, fftpack

Error in __init__><module> (line 321)
from .filter_design import *

Error in <frozen importlib>_call_with_frames_removed (line 219)

Error in <frozen importlib>exec_module (line 728)

Error in <frozen importlib>_load_unlocked (line 677)

Error in <frozen importlib>_find_and_load_unlocked (line 967)

Error in <frozen importlib>_find_and_load (line 983)

Error in <frozen importlib>_gcd_import (line 1006)

Error in __init__>import_module (line 127)
    return _bootstrap._gcd_import(name[level:], package, level)
</code>```

This occurs when both calling the python function from MATLAB or simply by typing

```<code>py.importlib.import_module('scipy.signal')
</code>```

in the MATLAB command line. Attempting to call a scipy.signal function directly

```<code>py.scipy.signal.find_peaks()
</code>```

throws the error

```<code>Undefined variable "py" or class "py.scipy.signal.find_peaks".
</code>```

Importing (or calling) numpy, scipy, or numpy submodules on the other hand are all successful.

Is the scipy.signal submodule not able to be called in MATLAB, or have I missed something?

答:
You should be able to call scipy.signal functions using this syntax e.g.
myButterFilt = py.scipy.signal.butter(1,0.25)

Body:
I have a python function that I need to call in MATLAB that imports functions from scipy.signal.

However when I attempt to call the function in MATLAB I get an error

Error using arpack><module> (line 45)
Python Error: ImportError: DLL load failed: The specified procedure could not be found.

Error in __init__><module> (line 22)
from .arpack import *

Error in __init__><module> (line 11)
from .arpack import *

Error in __init__><module> (line 117)
from .eigen import *

Error in _minimize><module> (line 21)
from scipy.sparse.linalg import LinearOperator

Error in __init__><module> (line 271)
from ._minimize import *

Error in filter_design><module> (line 18)
from scipy import special, optimize, fftpack

Error in __init__><module> (line 321)
from .filter_design import *

Error in <frozen importlib>_call_with_frames_removed (line 219)

Error in <frozen importlib>exec_module (line 728)

Error in <frozen importlib>_load_unlocked (line 677)

Error in <frozen importlib>_find_and_load_unlocked (line 967)

Error in <frozen importlib>_find_and_load (line 983)

Error in <frozen importlib>_gcd_import (line 1006)

Error in __init__>import_module (line 127)
    return _bootstrap._gcd_import(name[level:], package, level)

This occurs when both calling the python function from MATLAB or simply by typing

py.importlib.import_module('scipy.signal')

in the MATLAB command line. Attempting to call a scipy.signal function directly

py.scipy.signal.find_peaks()

throws the error

Undefined variable "py" or class "py.scipy.signal.find_peaks".

Importing (or calling) numpy, scipy, or numpy submodules on the other hand are all successful.

Is the scipy.signal submodule not able to be called in MATLAB, or have I missed something?


问:
Entity Framework - Include / Reference / Collection
I was wondering why there are separate methods for populating navigation properties.

If I work on an entire set, i can call Include on either a property or a collection.

However, if I work on a single entity, there are two separate methods to call depending on whether the item is a collection (Collection) or single reference (Reference).

Is there any way around this - this is making things more complicated than I think is necessary. And could anyone explain why this was decided during designing EF?

EDIT

Looking into it further, the problem goes deeper. What I was trying to do is create a generic way to load collection/navigation properties on a single entity. This can be done easy enough on the whole set using Include. But the method signatures for Reference and Collection are slightly different.

Never mind, will have to scatter these calls around my app.

e.g.

```<code>dbSet<T>().Include(e => e.Property).Include(e => e.Collection).Include(e => e.Collection.Property)
</code>```

all seem to work.

However the calls for the single entity are different:

```<code>context.Entry(entity).Reference(e => e.Property).Load();
context.Entry(entity).Reference(e => e.Property.Select(e => e.SubProperty)).Load();
context.Entry(entity).Collection(e => e.Collection).Load();
</code>```

答:
You can also load the referenced collection using Select.</p>

```<code>db.MyObject.Include(x => x.RefObect.Select(y => y.RefRefObject));
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I was wondering why there are separate methods for populating navigation properties.

If I work on an entire set, i can call Include on either a property or a collection.

However, if I work on a single entity, there are two separate methods to call depending on whether the item is a collection (Collection) or single reference (Reference).

Is there any way around this - this is making things more complicated than I think is necessary. And could anyone explain why this was decided during designing EF?

EDIT

Looking into it further, the problem goes deeper. What I was trying to do is create a generic way to load collection/navigation properties on a single entity. This can be done easy enough on the whole set using Include. But the method signatures for Reference and Collection are slightly different.

Never mind, will have to scatter these calls around my app.

e.g.

dbSet<T>().Include(e => e.Property).Include(e => e.Collection).Include(e => e.Collection.Property)

all seem to work.

However the calls for the single entity are different:

context.Entry(entity).Reference(e => e.Property).Load();
context.Entry(entity).Reference(e => e.Property.Select(e => e.SubProperty)).Load();
context.Entry(entity).Collection(e => e.Collection).Load();

Body:
You can also load the referenced collection using Select.

db.MyObject.Include(x => x.RefObect.Select(y => y.RefRefObject));


问:
SoapClient returning response with empty stdClass objects
I'm running into a problem with PHP SoapClient. I have the following WSDL https://api.mindbodyonline.com/0_5/DataService.asmx?WSDL and I'm calling the SelectDataXml. It returns the appropriate response, which includes an array of objects which correspond to the rows of data that the SQL query would return. I've checked the response in both Soap UI and through the __getLastResponse method (using the print_r routine and the NetBeans debugger window). I can see the complete response as a string but the array is being built with empty stdClasses. I've seen several answers here suggesting that caching be turned off to work around this. I tried that but nothing. I can't seem to find a way to make it build the objects correctly. Any help would be appreciated.

EDITED

The abstract superclass (sensitive data replaced with 'REMOVED'):

```<code>abstract class Mindbody_service {
    protected $_userCredentials = array ( "Username" => 'REMOVED', "Password" => 'REMOVED', 'SiteIDs' => array ( 'REMOVED' ) ),
        $_sourceCredentials = array ( "SourceName" => 'REMOVED', "Password" => 'REMOVED', 'SiteIDs' => array ( 'REMOVED' ) ),
        $_endPoint;

    public function __construct( $wsdl, $options = array () )
    {
        try {
            $this->_endPoint = new SoapClient( $wsdl, $options );
        } catch ( SoapFault $fault ) {
            echo $fault->getMessage();
        }
    }
}
</code>```

The concrete subclass:

```<code>include_once ('Mindbody_service.php');

class MindbodyDataServiceResponse {

    public $Status,
        $ErrorCode,
        $XMLDetail,
        $ResultCount,
        $CurrentPageIndex,
        $TotalPageCount,
        $Results;

    function __construct()
    {
        $Status = '';
        $ErrorCode = 0;
        $XMLDetail = '';
        $ResultCount = 0;
        $CurrentPageIndex = 0;
        $TotalPageCount = 0;
        $Results = new MindbodyDataServiceResults();
    }
}

class MindbodyDataServiceResults {

    public $Row;

    function __construct()
    {
        $row = array ();
    }
}

class Mindbody_data_service extends Mindbody_service {

    private $_query = "Very long SQL command that makes sense to the server";

    public function __construct()
    {
        $wsdl = 'https://api.mindbodyonline.com/0_5/DataService.asmx?wsdl';
        $options = array ();
        $classMap = array ( 'SelectDataXmlResult' => 'MindbodyDataServiceResponse' );

        $options [ 'trace' ] = TRUE;
        $options [ 'cache_wsdl' ] = WSDL_CACHE_NONE;
        $options [ 'compression' ] = SOAP_COMPRESSION_ACCEPT | SOAP   _COMPRESSION_GZIP;
        $options [ 'classmap' ] = $classMap;

        parent::__construct( $wsdl, $options );
    }

    public function getSomething( $since = null )
    {
        $request = array ( 'SourceCredentials' => $this->_sourceCredentials );

        $request [ 'SourceCredentials' ] = $this->_sourceCredentials;
        $request [ 'UserCredentials' ] = $this->_userCredentials;
        $request [ 'XMLDetail' ] = 'Full';
        $request [ 'PageSize' ] = 0;
        $request [ 'CurrentPageIndex' ] = 0;
        $request [ 'SelectSql' ] = $this->_conditionalQuery( $since ) . ' ORDER BY Sales.SaleDate;';

        try {
            $result = $this->_endPoint->SelectDataXml( array ( 'Request' => $request ) );
        } catch ( SoapFault $fault ) {
            echo 'ERROR: [' . $fault->faultcode . '] ' . $fault->faultstring . '.';
            exit;
        } catch ( Exception $e ) {
            echo 'ERROR: ' . $e->getMessage() . '.';
            exit;
        }

        echo '<p>';
        var_dump ($result->SelectDataXmlResult);
        echo '</p>';

        return $result->SelectDataXmlResult;
    }
}
</code>```

The method in question is getSomething. The $since variable is irrelevant, it's used in the query as a cutoff date for the data being retrieved (reason for which I have a private  _conditionalQuery( $since ) method).

The output of var_dump ($result->SelectDataXmlResult) I'm getting on my browser is:

```<code>object(MindbodyDataServiceResponse)[22]
  public 'Status' => string 'Success' (length=7)
  public 'ErrorCode' => int 200
  public 'XMLDetail' => string 'Full' (length=4)
  public 'ResultCount' => int 0
  public 'CurrentPageIndex' => int 0
  public 'TotalPageCount' => int 0
  public 'Results' =>
    object(stdClass)[23]
      public 'Row' =>
        array (size=4)
          0 =>
            object(stdClass)[24]
              ...
          1 =>
            object(stdClass)[25]
              ...
          2 =>
            object(stdClass)[26]
              ...
          3 =>
            object(stdClass)[27]
              ...
</code>```

EDITED

Here's the Server's response:

```<code><?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
    <soap:Body>
        <SelectDataXmlResponse xmlns="http://clients.mindbodyonline.com/api/0_5">
            <SelectDataXmlResult>
                <Status>Success</Status>
                <ErrorCode>200</ErrorCode>
                <XMLDetail>Bare</XMLDetail>
                <ResultCount>0</ResultCount>
                <CurrentPageIndex>0</CurrentPageIndex>
                <TotalPageCount>0</TotalPageCount>
                <Results>
                    <Row>
                        <Column1>REMOVED</Column1>...(more columns)
                    </Row>
                    <Row>
                        <Column1>REMOVED</Column1>...(more columns)
                    </Row>
                    <Row>
                        <Column1>REMOVED</Column1>...(more columns)
                    </Row>
                    <Row>
                        <Column1>REMOVED</Column1>...(more columns)
                    </Row>
                </Results>
            </SelectDataXmlResult>
        </SelectDataXmlResponse>
    </soap:Body>
</soap:Envelope>
</code>```

I've removed the actual content of each Row element due to it being customer data, but they are well formed XML elements. It's those elements that I'm getting as empty stdClass objects where I should be getting stdClass objects with members that have a 1:1 correspondence to the Row element's children.

答:
I faced similar situation, and almost pulled my hair out, but eventually I sorted it out.

From a Soap server where I can't change anything, SoapUI and Java was able to get response, but the default behaviour with PHP \SoapClient->__soapCall(...) was returning some elements as empty StdClass objects.

The solution I found is not ideal, but allows to get it done.

Basically, I wanted the raw response, so I could parse it myself, and \SoapClient->__getLastResponse() will do just that, if and only if we set options key 'trace' to 1.

So, pseudo-code:

```<code>$options = [
   // (login, password, etc...)
   'trace' => 1,
];
$client = new \SoapClient($wsdl, $options);

// (prepare the data for the call...)

$result = $client->__soapCall('save', [$callContext, $name, $inputXml]);

// Because of trace = 1 in options, this will now work.
$rawResult = $soapClient->__getLastResponse();
</code>```

Now you have full access to the response, just have to parse it.

Hope this helps someone!!

Body:
I'm running into a problem with PHP SoapClient. I have the following WSDL https://api.mindbodyonline.com/0_5/DataService.asmx?WSDL and I'm calling the SelectDataXml. It returns the appropriate response, which includes an array of objects which correspond to the rows of data that the SQL query would return. I've checked the response in both Soap UI and through the __getLastResponse method (using the print_r routine and the NetBeans debugger window). I can see the complete response as a string but the array is being built with empty stdClasses. I've seen several answers here suggesting that caching be turned off to work around this. I tried that but nothing. I can't seem to find a way to make it build the objects correctly. Any help would be appreciated.

EDITED

The abstract superclass (sensitive data replaced with 'REMOVED'):

abstract class Mindbody_service {
    protected $_userCredentials = array ( "Username" => 'REMOVED', "Password" => 'REMOVED', 'SiteIDs' => array ( 'REMOVED' ) ),
        $_sourceCredentials = array ( "SourceName" => 'REMOVED', "Password" => 'REMOVED', 'SiteIDs' => array ( 'REMOVED' ) ),
        $_endPoint;

    public function __construct( $wsdl, $options = array () )
    {
        try {
            $this->_endPoint = new SoapClient( $wsdl, $options );
        } catch ( SoapFault $fault ) {
            echo $fault->getMessage();
        }
    }
}

The concrete subclass:

include_once ('Mindbody_service.php');

class MindbodyDataServiceResponse {

    public $Status,
        $ErrorCode,
        $XMLDetail,
        $ResultCount,
        $CurrentPageIndex,
        $TotalPageCount,
        $Results;

    function __construct()
    {
        $Status = '';
        $ErrorCode = 0;
        $XMLDetail = '';
        $ResultCount = 0;
        $CurrentPageIndex = 0;
        $TotalPageCount = 0;
        $Results = new MindbodyDataServiceResults();
    }
}

class MindbodyDataServiceResults {

    public $Row;

    function __construct()
    {
        $row = array ();
    }
}

class Mindbody_data_service extends Mindbody_service {

    private $_query = "Very long SQL command that makes sense to the server";

    public function __construct()
    {
        $wsdl = 'https://api.mindbodyonline.com/0_5/DataService.asmx?wsdl';
        $options = array ();
        $classMap = array ( 'SelectDataXmlResult' => 'MindbodyDataServiceResponse' );

        $options [ 'trace' ] = TRUE;
        $options [ 'cache_wsdl' ] = WSDL_CACHE_NONE;
        $options [ 'compression' ] = SOAP_COMPRESSION_ACCEPT | SOAP   _COMPRESSION_GZIP;
        $options [ 'classmap' ] = $classMap;

        parent::__construct( $wsdl, $options );
    }

    public function getSomething( $since = null )
    {
        $request = array ( 'SourceCredentials' => $this->_sourceCredentials );

        $request [ 'SourceCredentials' ] = $this->_sourceCredentials;
        $request [ 'UserCredentials' ] = $this->_userCredentials;
        $request [ 'XMLDetail' ] = 'Full';
        $request [ 'PageSize' ] = 0;
        $request [ 'CurrentPageIndex' ] = 0;
        $request [ 'SelectSql' ] = $this->_conditionalQuery( $since ) . ' ORDER BY Sales.SaleDate;';

        try {
            $result = $this->_endPoint->SelectDataXml( array ( 'Request' => $request ) );
        } catch ( SoapFault $fault ) {
            echo 'ERROR: [' . $fault->faultcode . '] ' . $fault->faultstring . '.';
            exit;
        } catch ( Exception $e ) {
            echo 'ERROR: ' . $e->getMessage() . '.';
            exit;
        }

        echo '
';
        var_dump ($result->SelectDataXmlResult);
        echo '
';

        return $result->SelectDataXmlResult;
    }
}

The method in question is getSomething. The $since variable is irrelevant, it's used in the query as a cutoff date for the data being retrieved (reason for which I have a private  _conditionalQuery( $since ) method).

The output of var_dump ($result->SelectDataXmlResult) I'm getting on my browser is:

object(MindbodyDataServiceResponse)[22]
  public 'Status' => string 'Success' (length=7)
  public 'ErrorCode' => int 200
  public 'XMLDetail' => string 'Full' (length=4)
  public 'ResultCount' => int 0
  public 'CurrentPageIndex' => int 0
  public 'TotalPageCount' => int 0
  public 'Results' =>
    object(stdClass)[23]
      public 'Row' =>
        array (size=4)
          0 =>
            object(stdClass)[24]
              ...
          1 =>
            object(stdClass)[25]
              ...
          2 =>
            object(stdClass)[26]
              ...
          3 =>
            object(stdClass)[27]
              ...

EDITED

Here's the Server's response:

<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
    <soap:Body>
        <SelectDataXmlResponse xmlns="http://clients.mindbodyonline.com/api/0_5">
            <SelectDataXmlResult>
                <Status>Success</Status>
                <ErrorCode>200</ErrorCode>
                <XMLDetail>Bare</XMLDetail>
                <ResultCount>0</ResultCount>
                <CurrentPageIndex>0</CurrentPageIndex>
                <TotalPageCount>0</TotalPageCount>
                <Results>
                    <Row>
                        <Column1>REMOVED</Column1>...(more columns)
                    </Row>
                    <Row>
                        <Column1>REMOVED</Column1>...(more columns)
                    </Row>
                    <Row>
                        <Column1>REMOVED</Column1>...(more columns)
                    </Row>
                    <Row>
                        <Column1>REMOVED</Column1>...(more columns)
                    </Row>
                </Results>
            </SelectDataXmlResult>
        </SelectDataXmlResponse>
    </soap:Body>
</soap:Envelope>

I've removed the actual content of each Row element due to it being customer data, but they are well formed XML elements. It's those elements that I'm getting as empty stdClass objects where I should be getting stdClass objects with members that have a 1:1 correspondence to the Row element's children.

Body:
I faced similar situation, and almost pulled my hair out, but eventually I sorted it out.

From a Soap server where I can't change anything, SoapUI and Java was able to get response, but the default behaviour with PHP \SoapClient->__soapCall(...) was returning some elements as empty StdClass objects.

The solution I found is not ideal, but allows to get it done.

Basically, I wanted the raw response, so I could parse it myself, and \SoapClient->__getLastResponse() will do just that, if and only if we set options key 'trace' to 1.

So, pseudo-code:

$options = [
   // (login, password, etc...)
   'trace' => 1,
];
$client = new \SoapClient($wsdl, $options);

// (prepare the data for the call...)

$result = $client->__soapCall('save', [$callContext, $name, $inputXml]);

// Because of trace = 1 in options, this will now work.
$rawResult = $soapClient->__getLastResponse();

Now you have full access to the response, just have to parse it.

Hope this helps someone!!


问:
Gremlin: need an efficient query to check whether two vertices are connected?
Our app needs to check whether two vertices are connected via any path.

The app does not care about the segments in a path, or the shortest path.

The app only needs to know if two vertices share a common sub-graph.

My question: given two vertices with id(s) A and B, respectively, what gremlin query works well to answer the question "are A and B connected, somehow?"

答:
This one should do the trick:

```<code>g.V(A).
  repeat(both().dedup()).
    until(hasId(B)).
  hasNext()
</code>```

Start at A, then start visiting neighbors, don't visit any vertex twice, and stop if B is reached. Obviously, this can run into timeouts (or memory issues) if you are dealing with huge subgraphs.

Body:
This one should do the trick:

g.V(A).
  repeat(both().dedup()).
    until(hasId(B)).
  hasNext()

Start at A, then start visiting neighbors, don't visit any vertex twice, and stop if B is reached. Obviously, this can run into timeouts (or memory issues) if you are dealing with huge subgraphs.


问:
How to call function separately for each tab?
I want to call function for each tabs separately.
Like function openCity(event, 'London') and function openCity(event, 'Paris')

I am new in JavaScript and trying find a solution.
Here is my code and it works fine this way.How can I do it separately?

function openCity(evt, cityName) {
  // Declare all variables
  var i, tabcontent, tablinks;

  // Get all elements with class="tabcontent" and hide them
  tabcontent = document.getElementsByClassName("tabcontent");
  for (i = 0; i < tabcontent.length; i++) {
    tabcontent[i].style.display = "none";
  }

  // Get all elements with class="tablinks" and remove the class "active"
  tablinks = document.getElementsByClassName("tablinks");
  for (i = 0; i < tablinks.length; i++) {
    tablinks[i].className = tablinks[i].className.replace(" active", "");
  }

  // Show the current tab, and add an "active" class to the button that    opened the tab
  document.getElementById(cityName).style.display = "block";
  evt.currentTarget.className += " active";
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!-- Tab links -->
<div class="tab">
  <button class="tablinks" onclick="openCity(event, 'London')">London</button>
  <button class="tablinks" onclick="openCity(event, 'Paris')">Paris</button>
</div>

<!-- Tab content -->
<div id="London" class="tabcontent">
  <h3>London</h3>
  <p>London is the capital city of England.</p>
</div>

<div id="Paris" class="tabcontent">
  <h3>Paris</h3>
  <p>Paris is the capital of France.</p>
</div></code>```

答:
Take the event out of the DOM and run it in the script : its better because it more efficient that way

```<code>  //execute scripts when DOM ready !
      document.addEventListener("DOMContentLoaded", function (event) {
     var city;//define your city var

    //find all tab classes with queryselector
    const buttons = document.querySelectorAll(".tablinks")

//loop though them and add click event
    for (const button of buttons) {
    button.addEventListener('click', function(event) {
     city = this.innerHTML;//find city name better to use data-attribute

      openCity(event,city);

      })
    }

            });
</code>```

keep your original open city function

remove onclick from all tabs .. add as many tabs as you like now

Body:
I want to call function for each tabs separately.
Like function openCity(event, 'London') and function openCity(event, 'Paris')

I am new in JavaScript and trying find a solution.
Here is my code and it works fine this way.How can I do it separately?

function openCity(evt, cityName) {
  // Declare all variables
  var i, tabcontent, tablinks;

  // Get all elements with class="tabcontent" and hide them
  tabcontent = document.getElementsByClassName("tabcontent");
  for (i = 0; i < tabcontent.length; i++) {
    tabcontent[i].style.display = "none";
  }

  // Get all elements with class="tablinks" and remove the class "active"
  tablinks = document.getElementsByClassName("tablinks");
  for (i = 0; i < tablinks.length; i++) {
    tablinks[i].className = tablinks[i].className.replace(" active", "");
  }

  // Show the current tab, and add an "active" class to the button that    opened the tab
  document.getElementById(cityName).style.display = "block";
  evt.currentTarget.className += " active";
}

  <button class="tablinks" onclick="openCity(event, 'London')">London</button>
  <button class="tablinks" onclick="openCity(event, 'Paris')">Paris</button>

London

London is the capital city of England.

Paris

Paris is the capital of France.

Body:
Take the event out of the DOM and run it in the script : its better because it more efficient that way

  //execute scripts when DOM ready !
      document.addEventListener("DOMContentLoaded", function (event) {
     var city;//define your city var

    //find all tab classes with queryselector
    const buttons = document.querySelectorAll(".tablinks")

//loop though them and add click event
    for (const button of buttons) {
    button.addEventListener('click', function(event) {
     city = this.innerHTML;//find city name better to use data-attribute

      openCity(event,city);

      })
    }

            });

keep your original open city function

remove onclick from all tabs .. add as many tabs as you like now


问:
Why escaped dot Regex in Java doesn't match a entry string
I'm trying to check if a string matches a regex of a double type value in Java.

I want to understand why the following instruction prints "false".

```<code>System.out.println("1.".matches("1\\."));
</code>```

And why this prints "false"

```<code>System.out.println("1.2".matches("[1-9][0-9]*(\\.[0-9]*)?"));
</code>```

And why this prints "true"

```<code>System.out.println("1.2a".matches("-?\\d+(\\.\\d+)?"));
</code>```

答:
Double \ escapes a dot character for the matches method regex argument

```<code>System.out.println("1.".matches("1\\."));
</code>```

Body:
I'm trying to check if a string matches a regex of a double type value in Java.

I want to understand why the following instruction prints "false".

System.out.println("1.".matches("1\\."));

And why this prints "false"

System.out.println("1.2".matches("[1-9][0-9]*(\\.[0-9]*)?"));

And why this prints "true"

System.out.println("1.2a".matches("-?\\d+(\\.\\d+)?"));

Body:
Double \ escapes a dot character for the matches method regex argument

System.out.println("1.".matches("1\\."));


问:
How to sort strings by number of occurrences with bash in linux?
I have a file that contains lines like this:

```<code>May 25 05:34:16 192.0.2.2
May 25 05:34:16 192.0.2.1
May 25 05:34:16 192.0.1.5
May 25 05:38:16 192.0.2.2
</code>```

Now i want to get the number of occurrences of the IPs and list them by most occurred and also how often they appeared, like this:

```<code>2 May 25 05:34:16 192.0.2.2
1 May 25 05:34:16 192.0.2.1
1 May 25 05:34:16 192.0.1.5
</code>```

Preferably a one liner in bash with awk.

Body:
I have a file that contains lines like this:

May 25 05:34:16 192.0.2.2
May 25 05:34:16 192.0.2.1
May 25 05:34:16 192.0.1.5
May 25 05:38:16 192.0.2.2

Now i want to get the number of occurrences of the IPs and list them by most occurred and also how often they appeared, like this:

2 May 25 05:34:16 192.0.2.2
1 May 25 05:34:16 192.0.2.1
1 May 25 05:34:16 192.0.1.5

Preferably a one liner in bash with awk.

Body:
With GNU sort and GNU uniq:

sort -k4 file | uniq --count --skip-fields=3

Output:

      1 May 25 05:34:16 192.0.1.5
      1 May 25 05:34:16 192.0.2.1
      2 May 25 05:34:16 192.0.2.2

See: man uniq


问:
TSql query for a customer/order summary across a date range
I have two tables: a Customer table and an Order table.  The Customer table has many columns but the two that are needed are Customer.Id, and Customer.Name.  Similarly the Order table also has many columns and again only three are needed: Order.Id and Order.OrderDate, Order.CustomerId.  I need to build a query that will give an order report by date for a given date range: DateStart through DateEnd.  Some of the days may have no orders and other days that do have orders, not all customers will have an order, and some customers may have more than one order.

Here's the data and the report that would be expected.

```
Customer Table
Customer.Id     Customer.Name
1               One
2               Two
3               Three

Order Table
Order.Id        Order.CustomerId        Order.OrderDate
1               1                       2019-01-01
2               1                       2019-01-01
3               1                       2019-01-02
4               3                       2019-01-02
5               3                       2019-01-04

Results
Customer.Id     Customer.Name           Order.OrderDate Count
1               One                     2019-01-01      2
2               Two                     2019-01-01      0
3               Three                   2019-01-01      0
1               One                     2019-01-02      1
2               Two                     2019-01-02      0
3               Three                   2019-01-02      1
1               One                     2019-01-03      0
2               Two                     2019-01-03      0
3               Three                   2019-01-03      0
1               One                     2019-01-04      0
2               Two                     2019-01-04      0
3               Three                   2019-01-04      1
```

答:
Firstly you need to somehow create a table that will contain all dates (for '2019-01-03' there is no orders). Then you can cross join to customer to create all combinations and count customer orders.

```<code>declare @minDate date = (select min(OrderDate) from [Order])
declare @maxDate date = (select max(OrderDate) from [Order])
declare @Date date = @minDate
create table #rangeOfDates (dat date)

while @Date <= @maxDate
begin
    insert into #rangeOfDates values (@Date)
    set @Date = dateadd(day , 1, @Date)
end

select
     c.Id
    ,c.Name
    ,r.dat as OrderDate
    ,count(o.Id) as [Count]
from Customer as c
cross join #rangeOfDates as r
left join [Order] as o
 on c.Id = o.CustomerId
 and r.dat = o.OrderDate
group by  c.Id, c.Name, r.dat
order by  OrderDate, Id

Id  Name    OrderDate   Count
1   One   2019-01-01    2
2   Two   2019-01-01    0
3   Three 2019-01-01    0
1   One   2019-01-02    1
2   Two   2019-01-02    0
3   Three 2019-01-02    1
1   One   2019-01-03    0
2   Two   2019-01-03    0
3   Three 2019-01-03    0
1   One   2019-01-04    0
2   Two   2019-01-04    0
3   Three 2019-01-04    1
</code>```

Ideally, it would be to have a table that contains all dates instead of do it on the fly and restrict it based on @minDate and @maxDate.

Body:
I have two tables: a Customer table and an Order table.  The Customer table has many columns but the two that are needed are Customer.Id, and Customer.Name.  Similarly the Order table also has many columns and again only three are needed: Order.Id and Order.OrderDate, Order.CustomerId.  I need to build a query that will give an order report by date for a given date range: DateStart through DateEnd.  Some of the days may have no orders and other days that do have orders, not all customers will have an order, and some customers may have more than one order.

Here's the data and the report that would be expected.

Customer Table
Customer.Id     Customer.Name
1               One
2               Two
3               Three

Order Table
Order.Id        Order.CustomerId        Order.OrderDate
1               1                       2019-01-01
2               1                       2019-01-01
3               1                       2019-01-02
4               3                       2019-01-02
5               3                       2019-01-04

Results
Customer.Id     Customer.Name           Order.OrderDate Count
1               One                     2019-01-01      2
2               Two                     2019-01-01      0
3               Three                   2019-01-01      0
1               One                     2019-01-02      1
2               Two                     2019-01-02      0
3               Three                   2019-01-02      1
1               One                     2019-01-03      0
2               Two                     2019-01-03      0
3               Three                   2019-01-03      0
1               One                     2019-01-04      0
2               Two                     2019-01-04      0
3               Three                   2019-01-04      1

Body:
Firstly you need to somehow create a table that will contain all dates (for '2019-01-03' there is no orders). Then you can cross join to customer to create all combinations and count customer orders.

declare @minDate date = (select min(OrderDate) from [Order])
declare @maxDate date = (select max(OrderDate) from [Order])
declare @Date date = @minDate
create table #rangeOfDates (dat date)

while @Date <= @maxDate
begin
    insert into #rangeOfDates values (@Date)
    set @Date = dateadd(day , 1, @Date)
end

select
     c.Id
    ,c.Name
    ,r.dat as OrderDate
    ,count(o.Id) as [Count]
from Customer as c
cross join #rangeOfDates as r
left join [Order] as o
 on c.Id = o.CustomerId
 and r.dat = o.OrderDate
group by  c.Id, c.Name, r.dat
order by  OrderDate, Id

Id  Name    OrderDate   Count
1   One   2019-01-01    2
2   Two   2019-01-01    0
3   Three 2019-01-01    0
1   One   2019-01-02    1
2   Two   2019-01-02    0
3   Three 2019-01-02    1
1   One   2019-01-03    0
2   Two   2019-01-03    0
3   Three 2019-01-03    0
1   One   2019-01-04    0
2   Two   2019-01-04    0
3   Three 2019-01-04    1

Ideally, it would be to have a table that contains all dates instead of do it on the fly and restrict it based on @minDate and @maxDate.


问:
android canvas concatinate
I am trying to construct a SurfaceView by reading in an array and using case switches to build the canvas.

so the question is: can I construct a canvas looping Y, by tracking X. loading bitmaps using BitmapFactory() into the canvas and then using 1 .show() to render the canvas to the screen? or will I need to call the canvas render for each of these (or will that through away the screen every time I do that)?

答: Not sure what you're getting at, but for one thing avoid using BitmapFactory in onDraw. You don't want to be doing bitmap decoding at the same time as rendering. You should load your bitmaps ahead of time and keep them around in memory for faster drawing later on.

Title: android canvas concatinate


问:
UnhandledPromiseRejectionWarning: Error: error:0906D06C:PEM routines:PEM_read_bio:no start line
I have an app with a node/express server, a React client, and firebase firestore as database. When I do an operation on the firebase database, my code seems to work, but the data does not show up in the firestore console and I get the error below.

I implemented the solution below but it does not work:
https://stackoverflow.com/a/40321130/1438277

I am running npm 6.9.0 and node v11.8.0

Thank you

```<code>Unhandled Rejection at: Promise Promise {
[0]   <rejected> Error: error:0906D06C:PEM routines:PEM_read_bio:no start line
[0]       at Sign.sign (internal/crypto/sig.js:84:29)
[0]       at Object.sign (/Users/antoine/Desktop/jf_express_with_react/server/node_modules/jwa/index.js:152:45)
[0]       at Object.jwsSign [as sign] (/Users/antoine/Desktop/jf_express_with_react/server/node_modules/jws/lib/sign-stream.js:32:24)
[0]       at GoogleToken.requestToken (/Users/antoine/Desktop/jf_express_with_react/server/node_modules/gtoken/build/src/index.js:180:31)
[0]       at GoogleToken.getTokenAsync (/Users/antoine/Desktop/jf_express_with_react/server/node_modules/gtoken/build/src/index.js:119:21)
[0]       at GoogleToken.getToken (/Users/antoine/Desktop/jf_express_with_react/server/node_modules/gtoken/build/src/index.js:61:21)
[0]       at JWT.refreshTokenNoCache (/Users/antoine/Desktop/jf_express_with_react/server/node_modules/google-auth-library/build/src/auth/jwtclient.js:129:36)
[0]       at JWT.refreshToken (/Users/antoine/Desktop/jf_express_with_react/server/node_modules/google-auth-library/build/src/auth/oauth2client.js:148:24)
[0]       at JWT.getRequestMetadataAsync (/Users/antoine/Desktop/jf_express_with_react/server/node_modules/google-auth-library/build/src/auth/oauth2client.js:265:28)
[0]       at JWT.getRequestMetadataAsync (/Users/antoine/Desktop/jf_express_with_react/server/node_modules/google-auth-library/build/src/auth/jwtclient.js:76:26)
[0]       at JWT.getRequestHeaders (/Users/antoine/Desktop/jf_express_with_react/server/node_modules/google-auth-library/build/src/auth/oauth2client.js:244:32)
[0]       at SingleCallCredentials.call_credentials_1.CallCredentials.createFromMetadataGenerator [as metadataGenerator] (/Users/antoine/Desktop/jf_express_with_react/server/node_modules/@grpc/grpc-js/build/src/index.js:74:39)
[0]       at Promise (/Users/antoine/Desktop/jf_express_with_react/server/node_modules/@grpc/grpc-js/build/src/call-credentials.js:64:18)
[0]       at new Promise (<anonymous>)
[0]       at SingleCallCredentials.generateMetadata (/Users/antoine/Desktop/jf_express_with_react/server/node_modules/@grpc/grpc-js/build/src/call-credentials.js:63:16)
[0]       at Promise.all.creds.map (/Users/antoine/Desktop/jf_express_with_react/server/node_modules/@grpc/grpc-js/build/src/call-credentials.js:47:75) } reason: Error: error:0906D06C:PEM routines:PEM_read_bio:no start line
[0]     at Sign.sign (internal/crypto/sig.js:84:29)
[0]     at Object.sign (/Users/antoine/Desktop/jf_express_with_react/server/node_modules/jwa/index.js:152:45)
[0]     at Object.jwsSign [as sign] (/Users/antoine/Desktop/jf_express_with_react/server/node_modules/jws/lib/sign-stream.js:32:24)
[0]     at GoogleToken.requestToken (/Users/antoine/Desktop/jf_express_with_react/server/node_modules/gtoken/build/src/index.js:180:31)
[0]     at GoogleToken.getTokenAsync (/Users/antoine/Desktop/jf_express_with_react/server/node_modules/gtoken/build/src/index.js:119:21)
[0]     at GoogleToken.getToken (/Users/antoine/Desktop/jf_express_with_react/server/node_modules/gtoken/build/src/index.js:61:21)
[0]     at JWT.refreshTokenNoCache (/Users/antoine/Desktop/jf_express_with_react/server/node_modules/google-auth-library/build/src/auth/jwtclient.js:129:36)
[0]     at JWT.refreshToken (/Users/antoine/Desktop/jf_express_with_react/server/node_modules/google-auth-library/build/src/auth/oauth2client.js:148:24)
[0]     at JWT.getRequestMetadataAsync (/Users/antoine/Desktop/jf_express_with_react/server/node_modules/google-auth-library/build/src/auth/oauth2client.js:265:28)
[0]     at JWT.getRequestMetadataAsync (/Users/antoine/Desktop/jf_express_with_react/server/node_modules/google-auth-library/build/src/auth/jwtclient.js:76:26)
[0]     at JWT.getRequestHeaders (/Users/antoine/Desktop/jf_express_with_react/server/node_modules/google-auth-library/build/src/auth/oauth2client.js:244:32)
[0]     at SingleCallCredentials.call_credentials_1.CallCredentials.createFromMetadataGenerator [as metadataGenerator] (/Users/antoine/Desktop/jf_express_with_react/server/node_modules/@grpc/grpc-js/build/src/index.js:74:39)
[0]     at Promise (/Users/antoine/Desktop/jf_express_with_react/server/node_modules/@grpc/grpc-js/build/src/call-credentials.js:64:18)
[0]     at new Promise (<anonymous>)
[0]     at SingleCallCredentials.generateMetadata (/Users/antoine/Desktop/jf_express_with_react/server/node_modules/@grpc/grpc-js/build/src/call-credentials.js:63:16)
[0]     at Promise.all.creds.map (/Users/antoine/Desktop/jf_express_with_react/server/node_modules/@grpc/grpc-js/build/src/call-credentials.js:47:75)
[0] (node:3612) PromiseRejectionHandledWarning: Promise rejection was handled asynchronously (rejection id: 2)
[0] Unhandled Rejection at: Promise Promise {
[0]   <rejected> { Error: Getting metadata from plugin failed with error: error:0906D06C:PEM routines:PEM_read_bio:no start line
[0]       at Http2CallStream.call.on (/Users/antoine/Desktop/jf_express_with_react/server/node_modules/@grpc/grpc-js/build/src/client.js:102:45)
[0]       at Http2CallStream.emit (events.js:202:15)
[0]       at Http2CallStream.EventEmitter.emit (domain.js:439:20)
[0]       at Http2CallStream.endCall (/Users/antoine/Desktop/jf_express_with_react/server/node_modules/@grpc/grpc-js/build/src/call-stream.js:74:18)
[0]       at /Users/antoine/Desktop/jf_express_with_react/server/node_modules/@grpc/grpc-js/build/src/call-stream.js:355:18
[0]       at processTicksAndRejections (internal/process/next_tick.js:81:5)
[0]     code: 2,
[0]     details:
[0]      'Getting metadata from plugin failed with error: error:0906D06C:PEM routines:PEM_read_bio:no start line',
[0]     metadata: Metadata { internalRepr: Map {} } } } reason: { Error: Getting metadata from plugin failed with error: error:0906D06C:PEM routines:PEM_read_bio:no start line
[0]     at Http2CallStream.call.on (/Users/antoine/Desktop/jf_express_with_react/server/node_modules/@grpc/grpc-js/build/src/client.js:102:45)
[0]     at Http2CallStream.emit (events.js:202:15)
[0]     at Http2CallStream.EventEmitter.emit (domain.js:439:20)
[0]     at Http2CallStream.endCall (/Users/antoine/Desktop/jf_express_with_react/server/node_modules/@grpc/grpc-js/build/src/call-stream.js:74:18)
[0]     at /Users/antoine/Desktop/jf_express_with_react/server/node_modules/@grpc/grpc-js/build/src/call-stream.js:355:18
[0]     at processTicksAndRejections (internal/process/next_tick.js:81:5)
[0]   code: 2,
[0]   details:
[0]    'Getting metadata from plugin failed with error: error:0906D06C:PEM routines:PEM_read_bio:no start line',
[0]   metadata: Metadata { internalRepr: Map {} } }
</code>```

This is the database call I am making from my express server:

```<code>const admin = require('firebase-admin')
const config = require('./config.js')

exports.createAsin = p => {
  try {
    let addDoc = config.db.collection('asins').add({
      uid: p.uid,
      asin: p.asin,
      mapPrice: p.mapPrice,
      data: []
    })
    console.log('db: ASIN created')
    return p
  } catch (e) {
    console.log('db: error creating ASIN /', e)
    return null
  }
}
</code>```

答:
Firebase (or any database) calls are asynchronous events, so you need to use promises or callback functions to avoid promise rejection errors. Here is the docs for Javascript promises:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise

And here is a pretty helpful article on how to use them with Firebase:
https://howtofirebase.com/promises-for-firebase-bbb9d0d595ed

For your example, you could do something like

```<code>exports.createAsin = async p => {
  try {
    let addDoc = await config.db.collection('asins').add({
      ...
    })
    console.log('db: ASIN created')
    return p
  } catch (e) {
    ...
  }
}
</code>```

Body:
I have an app with a node/express server, a React client, and firebase firestore as database. When I do an operation on the firebase database, my code seems to work, but the data does not show up in the firestore console and I get the error below.

I implemented the solution below but it does not work:
https://stackoverflow.com/a/40321130/1438277

I am running npm 6.9.0 and node v11.8.0

Thank you

Unhandled Rejection at: Promise Promise {
[0]   <rejected> Error: error:0906D06C:PEM routines:PEM_read_bio:no start line
[0]       at Sign.sign (internal/crypto/sig.js:84:29)
[0]       at Object.sign (/Users/antoine/Desktop/jf_express_with_react/server/node_modules/jwa/index.js:152:45)
[0]       at Object.jwsSign [as sign] (/Users/antoine/Desktop/jf_express_with_react/server/node_modules/jws/lib/sign-stream.js:32:24)
[0]       at GoogleToken.requestToken (/Users/antoine/Desktop/jf_express_with_react/server/node_modules/gtoken/build/src/index.js:180:31)
[0]       at GoogleToken.getTokenAsync (/Users/antoine/Desktop/jf_express_with_react/server/node_modules/gtoken/build/src/index.js:119:21)
[0]       at GoogleToken.getToken (/Users/antoine/Desktop/jf_express_with_react/server/node_modules/gtoken/build/src/index.js:61:21)
[0]       at JWT.refreshTokenNoCache (/Users/antoine/Desktop/jf_express_with_react/server/node_modules/google-auth-library/build/src/auth/jwtclient.js:129:36)
[0]       at JWT.refreshToken (/Users/antoine/Desktop/jf_express_with_react/server/node_modules/google-auth-library/build/src/auth/oauth2client.js:148:24)
[0]       at JWT.getRequestMetadataAsync (/Users/antoine/Desktop/jf_express_with_react/server/node_modules/google-auth-library/build/src/auth/oauth2client.js:265:28)
[0]       at JWT.getRequestMetadataAsync (/Users/antoine/Desktop/jf_express_with_react/server/node_modules/google-auth-library/build/src/auth/jwtclient.js:76:26)
[0]       at JWT.getRequestHeaders (/Users/antoine/Desktop/jf_express_with_react/server/node_modules/google-auth-library/build/src/auth/oauth2client.js:244:32)
[0]       at SingleCallCredentials.call_credentials_1.CallCredentials.createFromMetadataGenerator [as metadataGenerator] (/Users/antoine/Desktop/jf_express_with_react/server/node_modules/@grpc/grpc-js/build/src/index.js:74:39)
[0]       at Promise (/Users/antoine/Desktop/jf_express_with_react/server/node_modules/@grpc/grpc-js/build/src/call-credentials.js:64:18)
[0]       at new Promise (<anonymous>)
[0]       at SingleCallCredentials.generateMetadata (/Users/antoine/Desktop/jf_express_with_react/server/node_modules/@grpc/grpc-js/build/src/call-credentials.js:63:16)
[0]       at Promise.all.creds.map (/Users/antoine/Desktop/jf_express_with_react/server/node_modules/@grpc/grpc-js/build/src/call-credentials.js:47:75) } reason: Error: error:0906D06C:PEM routines:PEM_read_bio:no start line
[0]     at Sign.sign (internal/crypto/sig.js:84:29)
[0]     at Object.sign (/Users/antoine/Desktop/jf_express_with_react/server/node_modules/jwa/index.js:152:45)
[0]     at Object.jwsSign [as sign] (/Users/antoine/Desktop/jf_express_with_react/server/node_modules/jws/lib/sign-stream.js:32:24)
[0]     at GoogleToken.requestToken (/Users/antoine/Desktop/jf_express_with_react/server/node_modules/gtoken/build/src/index.js:180:31)
[0]     at GoogleToken.getTokenAsync (/Users/antoine/Desktop/jf_express_with_react/server/node_modules/gtoken/build/src/index.js:119:21)
[0]     at GoogleToken.getToken (/Users/antoine/Desktop/jf_express_with_react/server/node_modules/gtoken/build/src/index.js:61:21)
[0]     at JWT.refreshTokenNoCache (/Users/antoine/Desktop/jf_express_with_react/server/node_modules/google-auth-library/build/src/auth/jwtclient.js:129:36)
[0]     at JWT.refreshToken (/Users/antoine/Desktop/jf_express_with_react/server/node_modules/google-auth-library/build/src/auth/oauth2client.js:148:24)
[0]     at JWT.getRequestMetadataAsync (/Users/antoine/Desktop/jf_express_with_react/server/node_modules/google-auth-library/build/src/auth/oauth2client.js:265:28)
[0]     at JWT.getRequestMetadataAsync (/Users/antoine/Desktop/jf_express_with_react/server/node_modules/google-auth-library/build/src/auth/jwtclient.js:76:26)
[0]     at JWT.getRequestHeaders (/Users/antoine/Desktop/jf_express_with_react/server/node_modules/google-auth-library/build/src/auth/oauth2client.js:244:32)
[0]     at SingleCallCredentials.call_credentials_1.CallCredentials.createFromMetadataGenerator [as metadataGenerator] (/Users/antoine/Desktop/jf_express_with_react/server/node_modules/@grpc/grpc-js/build/src/index.js:74:39)
[0]     at Promise (/Users/antoine/Desktop/jf_express_with_react/server/node_modules/@grpc/grpc-js/build/src/call-credentials.js:64:18)
[0]     at new Promise (<anonymous>)
[0]     at SingleCallCredentials.generateMetadata (/Users/antoine/Desktop/jf_express_with_react/server/node_modules/@grpc/grpc-js/build/src/call-credentials.js:63:16)
[0]     at Promise.all.creds.map (/Users/antoine/Desktop/jf_express_with_react/server/node_modules/@grpc/grpc-js/build/src/call-credentials.js:47:75)
[0] (node:3612) PromiseRejectionHandledWarning: Promise rejection was handled asynchronously (rejection id: 2)
[0] Unhandled Rejection at: Promise Promise {
[0]   <rejected> { Error: Getting metadata from plugin failed with error: error:0906D06C:PEM routines:PEM_read_bio:no start line
[0]       at Http2CallStream.call.on (/Users/antoine/Desktop/jf_express_with_react/server/node_modules/@grpc/grpc-js/build/src/client.js:102:45)
[0]       at Http2CallStream.emit (events.js:202:15)
[0]       at Http2CallStream.EventEmitter.emit (domain.js:439:20)
[0]       at Http2CallStream.endCall (/Users/antoine/Desktop/jf_express_with_react/server/node_modules/@grpc/grpc-js/build/src/call-stream.js:74:18)
[0]       at /Users/antoine/Desktop/jf_express_with_react/server/node_modules/@grpc/grpc-js/build/src/call-stream.js:355:18
[0]       at processTicksAndRejections (internal/process/next_tick.js:81:5)
[0]     code: 2,
[0]     details:
[0]      'Getting metadata from plugin failed with error: error:0906D06C:PEM routines:PEM_read_bio:no start line',
[0]     metadata: Metadata { internalRepr: Map {} } } } reason: { Error: Getting metadata from plugin failed with error: error:0906D06C:PEM routines:PEM_read_bio:no start line
[0]     at Http2CallStream.call.on (/Users/antoine/Desktop/jf_express_with_react/server/node_modules/@grpc/grpc-js/build/src/client.js:102:45)
[0]     at Http2CallStream.emit (events.js:202:15)
[0]     at Http2CallStream.EventEmitter.emit (domain.js:439:20)
[0]     at Http2CallStream.endCall (/Users/antoine/Desktop/jf_express_with_react/server/node_modules/@grpc/grpc-js/build/src/call-stream.js:74:18)
[0]     at /Users/antoine/Desktop/jf_express_with_react/server/node_modules/@grpc/grpc-js/build/src/call-stream.js:355:18
[0]     at processTicksAndRejections (internal/process/next_tick.js:81:5)
[0]   code: 2,
[0]   details:
[0]    'Getting metadata from plugin failed with error: error:0906D06C:PEM routines:PEM_read_bio:no start line',
[0]   metadata: Metadata { internalRepr: Map {} } }

This is the database call I am making from my express server:

const admin = require('firebase-admin')
const config = require('./config.js')

exports.createAsin = p => {
  try {
    let addDoc = config.db.collection('asins').add({
      uid: p.uid,
      asin: p.asin,
      mapPrice: p.mapPrice,
      data: []
    })
    console.log('db: ASIN created')
    return p
  } catch (e) {
    console.log('db: error creating ASIN /', e)
    return null
  }
}

Body:
Firebase (or any database) calls are asynchronous events, so you need to use promises or callback functions to avoid promise rejection errors. Here is the docs for Javascript promises:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise

And here is a pretty helpful article on how to use them with Firebase:
https://howtofirebase.com/promises-for-firebase-bbb9d0d595ed

For your example, you could do something like

exports.createAsin = async p => {
  try {
    let addDoc = await config.db.collection('asins').add({
      ...
    })
    console.log('db: ASIN created')
    return p
  } catch (e) {
    ...
  }
}


问:
Why does my function push one value too much?
I'm trying to write my own fibonacci function. It should return all fibonacci numbers that are smaller than num in an array. I tried checking currentPush against num with a while loop, but it pushes one value too much to the returned array.

Whats wrong with my code? It should stop before the last iteration because currentPush is definitely bigger than num.

```<code>function fib(num) {

  if(num < 2){return 1};

  let fib = [1, 1];
  let currentPush = 2;

  while (currentPush < num){
    // get last two elements from array and add them together
    currentPush = fib.slice(fib.length-2, fib.length).reduce((a, b) => a + b);
    fib.push(currentPush);
  }

  return fib;
}
 console.log(fib(10)); // [ 1, 1, 2, 3, 5, 8, 13 ]
 console.log(fib(100)); // [ 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144 ]
</code>```

答:
As the comments mention, you'll have to check for currentPush < num before pushing to the array but after computing currentPush

function fib(num) {

  if(num < 2) {return 1};

  let fib = [1, 1];

  while (true) {
    let currentPush = fib.slice(fib.length-2, fib.length).reduce((a, b) => a + b);
    if (currentPush > num)
      return fib;
    fib.push(currentPush);
  }
}

console.log(fib(10)); // [ 1, 1, 2, 3, 5, 8, 13 ]
console.log(fib(100)); // [ 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144 ]```

Body:
I'm trying to write my own fibonacci function. It should return all fibonacci numbers that are smaller than num in an array. I tried checking currentPush against num with a while loop, but it pushes one value too much to the returned array.

Whats wrong with my code? It should stop before the last iteration because currentPush is definitely bigger than num.

function fib(num) {

  if(num < 2){return 1};

  let fib = [1, 1];
  let currentPush = 2;

  while (currentPush < num){
    // get last two elements from array and add them together
    currentPush = fib.slice(fib.length-2, fib.length).reduce((a, b) => a + b);
    fib.push(currentPush);
  }

  return fib;
}
 console.log(fib(10)); // [ 1, 1, 2, 3, 5, 8, 13 ]
 console.log(fib(100)); // [ 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144 ]


问:
Nest.Js Redirect from a controller to another
So I have this module:

```<code>@Module({
  imports: [],
  controllers: [AppController, AnotherController],
  providers: [],
})
</code>```

And in AppController on some route I want to do res.redirect('/books') where /books is a route found in AnotherController.

For some reason this doesn't work and I can't figure out if it's not supported or I'm doing it wrong.

答:
Redirecting from one controller to another works with res.redirect(target). As target, you have to combine the paths from the controller and the route annotation:

@Controller('books') + @Get('greet') = /books/greet

```<code>@Controller()
export class AppController {
  @Get()
  redirect(@Res() res) {
    return res.redirect('/books/greet');
  }
}

@Controller('books')
export class AnotherController {
  @Get('greet')
  greet() {
    return 'hello';
  }
}
</code>```

See this running example here:

Body:
So I have this module:

@Module({
  imports: [],
  controllers: [AppController, AnotherController],
  providers: [],
})

And in AppController on some route I want to do res.redirect('/books') where /books is a route found in AnotherController.

For some reason this doesn't work and I can't figure out if it's not supported or I'm doing it wrong.

Body:
Redirecting from one controller to another works with res.redirect(target). As target, you have to combine the paths from the controller and the route annotation:

@Controller('books') + @Get('greet') = /books/greet

@Controller()
export class AppController {
  @Get()
  redirect(@Res() res) {
    return res.redirect('/books/greet');
  }
}

@Controller('books')
export class AnotherController {
  @Get('greet')
  greet() {
    return 'hello';
  }
}

See this running example here:


问:
TensorFlow Serving RAM Usage
I'm having trouble finding specific information in the documentation regarding how models are saved and loaded in TensorFlow Serving and possible differences when running on CPU vs GPU.

For serving multiple models (and one or more versions of each), one general workflow is:

Train models

Save frozen models (tf.saved_model.simple_save)

Creates directory structure containing

saved_model.pb

variables/variables.data

variables/variables.index

Point to models and versions in config.conf

I am currently running inference on CPU and loading many models at once which is eating up RAM much more quickly than expected. The saved model is relatively small on disk, but when TF Serving loads the model into memory it is nearly an order of magnitude larger. A single 200MB saved_model on disk turns into 1.5GB in RAM, greatly limiting the number of models that can be loaded.

Questions:

Is this behavior (larger memory footprint in RAM) expected?

Is there a difference in how TF Serving uses Memory on CPU vs GPU?

Would we be able to load more models by doing inference on GPU?

Loosely related search results:

Eager load the entire model to estimate memory consumption of Tensorflow Serving

https://github.com/tensorflow/serving/issues/1215

答:
Yes that's expected.

No it won't matter CPU/GPU

You're probably going to fit fewer in GPU memory, due to having less GPU memory than system memory.

Title: TensorFlow Serving RAM Usage


问:
Export ASPX to HTML
We're building a CMS. The site will be built and managed by the users in aspx pages, but we would like to create a static site of HTML's.
The way we're doing it now is with code I found here that overloads the Render method in the Aspx Page and writes the HTML string to a file. This works fine for a single page, but the thing with our CMS is that we want to automatically create a few HTML pages for a site right from the start, even before the creator has edited anything in the system.
Does anyone know of any way to do this?</p>

答:
@ckarras: I would rather not use an external tool, because I want the HTML pages to be created programmatically and not manually.

@jttraino: I don't have a time interval in which the site needs to be outputted- the uotput has to occur when a user creates a new site.

@Frank Krueger: I don't really understand how to create an instance of my page using WebContext and WebRequest.

I searched for "wget" in searchdotnet, and got to a post about a .net class called WebClient. It seems to do what I want if I use the DownloadString() method - gets a string from a specific url. The problem is that because our CMS needs to be logged in to, when the method tries to reach the page it's thrown to the login page, and therefore returns the login.aspx HTML...

Any thoughts as to how I can continue from here?

OwnerDisplayName: Leac

ContentLicense: CC BY-SA 2.5

Title: Export ASPX to HTML

LastEditorDisplayName: Leac


问:
What should my JSON string look like in my Action?
in .NET MVC my action looks like:

```<code>public ActionResult TestAjax(string testID)
{

    return Content(@"{first: ""1"", second : ""2""}");
}
</code>```

In my JavaScript I am doing:

```<code>function(data)
{
      alert(data.first);
}
</code>```

I am getting [object Object] as the output, why is that?

Is my JSON string wrong?

答:
How about letting the system deal with it:</p>

```<code>    public ActionResult TestAjax(string testID)
    {
        return Json(new {first = 1, second = 2});
    }
</code>```

Body:
in .NET MVC my action looks like:

public ActionResult TestAjax(string testID)
{

    return Content(@"{first: ""1"", second : ""2""}");
}

In my JavaScript I am doing:

function(data)
{
      alert(data.first);
}

I am getting [object Object] as the output, why is that?

Is my JSON string wrong?

Body:
How about letting the system deal with it:

    public ActionResult TestAjax(string testID)
    {
        return Json(new {first = 1, second = 2});
    }

OwnerDisplayName: Marc Gravell


问:
Android: How to create my own cursor class?
I'm using Sqlite in Android and to get a value from the database I use something like this:

```<code>Cursor cursor = sqliteDatabase.rawQuery("select title,category from table", null);

int columnIndexTitle = cursor.getColumnIndex("title");
iny columnIndexCategory = cursor.getColumnIndex("category");

cursor.moveToFirst();
while (cursor.moveToNext()) {
    String title = cursor.getString(columnIndexTitle);
    String category = cursor.getString(columnIndexCategory);
}
cursor.close();
</code>```

I want to create my own Cursor so that I can do getColumnIndex() and getString() with one method. Something like this:

```<code>String title = cursor.getString("title");
</code>```

I want to create my own class that extends the cursor that I get from sqliteDatabase.rawQuery, but I'm not sure how to accomplish this. Should I extend SQLiteCursor or how should I do this? Is it even a possible and is it a good idea?

答:
You should make use of the DatabaseUtils.stringForQuery() static method that is already in Android SDK to easily retrieve a value, this example is for String bot there is also method for Long

```<code>stringForQuery(SQLiteDatabase db, String query, String[] selectionArgs)
</code>```

Utility method to run the query on the db and return the value in the first column of the first row.

Something like

```<code>String myString=DatabaseUtils.stringForQuery(getDB(),query,selectionArgs);
</code>```

Body:
I'm using Sqlite in Android and to get a value from the database I use something like this:

Cursor cursor = sqliteDatabase.rawQuery("select title,category from table", null);

int columnIndexTitle = cursor.getColumnIndex("title");
iny columnIndexCategory = cursor.getColumnIndex("category");

cursor.moveToFirst();
while (cursor.moveToNext()) {
    String title = cursor.getString(columnIndexTitle);
    String category = cursor.getString(columnIndexCategory);
}
cursor.close();

I want to create my own Cursor so that I can do getColumnIndex() and getString() with one method. Something like this:

String title = cursor.getString("title");

I want to create my own class that extends the cursor that I get from sqliteDatabase.rawQuery, but I'm not sure how to accomplish this. Should I extend SQLiteCursor or how should I do this? Is it even a possible and is it a good idea?

Body:
You should make use of the DatabaseUtils.stringForQuery() static method that is already in Android SDK to easily retrieve a value, this example is for String bot there is also method for Long

stringForQuery(SQLiteDatabase db, String query, String[] selectionArgs)

Utility method to run the query on the db and return the value in the first column of the first row.

Something like

String myString=DatabaseUtils.stringForQuery(getDB(),query,selectionArgs);


问:
Error 500 (Internal Server Error) in API Laravel 5.8 and Angular 7
I am running a project on Angular 7 and Laravel 5.8. When i post login form angular form to API Laravel I get error 500 (Internal Server Error) in console .... why?

I tried running the Application on local system, it works perfectly. But when I took it to online serve, the problem started.
Note: Backend API is working perfectly with POSTMAN.

My CORS.php in Laravel is:

```<code>    public function handle($request, Closure $next)
    {
        header('Access-Control-Allow-Origin : *');
        header('Access-Control-Allow-Headers : Content-type, X-Auth-Token, Authorization, Origin');
        return $next($request);
    }

</code>```

kernel

```<code>    protected $middleware = [

        \App\Http\Middleware\CORS::class,
    ];

    protected $routeMiddleware = [

        'CORS' => \App\Http\Middleware\CORS::class,
    ];
</code>```

route

```<code>Route::post('login', 'UserController@login');
</code>```

login.service

```<code>export class SandboxUserService {

  private API_URL= environment.apiUrl;

  login(data) {
    return this.http.post(this.API_URL + '/login', data)
  }
</code>```

login.component.ts

```<code> onSubmit() {
    this.SandboxUser.login(this.form).subscribe(
      data => this.handleResponse(data),
       error => this.handleError(error)
    );
  }
  handleResponse(data) {
     this.notify.success('Done, you have successfully logged in.', {timeout:2000, position: "rightTop"})

    this.Token.handle(data.access_token);
    this.Auth.changeAuthStatus(true);
    // this.router.navigateByUrl('/admindashboard');
    if(this.form.id == 1){
      this.router.navigateByUrl('/admindashboard');
   }
   else
   {
      this.router.navigateByUrl('/userdashboard');
   }

</code>```

After login, I expect it to redirect me to the dashboard. But it did not respond. So when I inspect, I found this:

Error 500 (Internal Server Error)

答:
The issue is with your URL, your API is running on HTTPS connection but you are trying to access it wihout HTTPS. That's why your request is being blocked and treated as insecure.

Try to change your URL from:

```<code>example.com/api/login
</code>```

to

```<code>https://example.com/api/login
</code>```

Body:
I am running a project on Angular 7 and Laravel 5.8. When i post login form angular form to API Laravel I get error 500 (Internal Server Error) in console .... why?

I tried running the Application on local system, it works perfectly. But when I took it to online serve, the problem started.
Note: Backend API is working perfectly with POSTMAN.

My CORS.php in Laravel is:

    public function handle($request, Closure $next)
    {
        header('Access-Control-Allow-Origin : *');
        header('Access-Control-Allow-Headers : Content-type, X-Auth-Token, Authorization, Origin');
        return $next($request);
    }

kernel

    protected $middleware = [

        \App\Http\Middleware\CORS::class,
    ];

    protected $routeMiddleware = [

        'CORS' => \App\Http\Middleware\CORS::class,
    ];

route

Route::post('login', 'UserController@login');

login.service

export class SandboxUserService {

  private API_URL= environment.apiUrl;

  login(data) {
    return this.http.post(this.API_URL + '/login', data)
  }

login.component.ts

 onSubmit() {
    this.SandboxUser.login(this.form).subscribe(
      data => this.handleResponse(data),
       error => this.handleError(error)
    );
  }
  handleResponse(data) {
     this.notify.success('Done, you have successfully logged in.', {timeout:2000, position: "rightTop"})

    this.Token.handle(data.access_token);
    this.Auth.changeAuthStatus(true);
    // this.router.navigateByUrl('/admindashboard');
    if(this.form.id == 1){
      this.router.navigateByUrl('/admindashboard');
   }
   else
   {
      this.router.navigateByUrl('/userdashboard');
   }

After login, I expect it to redirect me to the dashboard. But it did not respond. So when I inspect, I found this:

Error 500 (Internal Server Error)

Body:
The issue is with your URL, your API is running on HTTPS connection but you are trying to access it wihout HTTPS. That's why your request is being blocked and treated as insecure.

Try to change your URL from:

example.com/api/login

to

https://example.com/api/login


问:
How to pass List from Java to JNI C++ as vector by ref?
I am fresh in C++ and JNI

Flow should be like this

From Java I pass a empty List to JNI, JNI invoke method loadData(std::vector<int>) from MyClass and this method fill my list with a data.

So, question is

I have

```<code>class MyClass {
public:
MyClass();
~MyClass();

void loadData(std::vector<int> & vector);
};

void MyClass::loadData(std::vector<int> & vector)
{
const int size = 10;

vector.resize(size);

for (int i = 0; i < size; ++i) {
    vector.push_back(4);
}
}
</code>```

This is my method that I wrote in pure C++ and now I need to use it from Java like this

```<code>public native void fillListWithData(List<Integer> list);
</code>```

So, I wrote such method in JNI to associate them

```<code>extern "C" JNIEXPORT void JNICALL
Java_com_google_ar_core_examples_java
_helloar_HelloArActivity_fillListWithData(
    JNIEnv *env,
    jobject /* this */,
    jobject input
) {
myClass->loadData("HERE I NEED TO PASS MY " input);
}
</code>```

And here how I should to invoke this method

```<code>public void TEST(){
    List<Integer> list = new ArrayList<>();
    fillListWithData(list);
    Log.e("TAG", "HERE I NEED TO HAVE A LIST WITH FILLED DATA");
}
</code>```

I can't understand how to pass this list by reference by JNI to C++...

Any ideas appreciate

答:
In this case, it's quite simple. All you have to do is to pass List to your native code and fill it inside JNI part using JNI based access methods

```<code>#include <vector>
#include "jni.h"
#include "recipeNo046_FillTheList.h"
using namespace std;

JNIEXPORT void JNICALL Java_recipeNo046_FillTheList_fillTheList
  (JNIEnv *env, jclass cls, jobject obj) {

  vector<int> vect { 1, 2, 3 };

  jclass listClass = env->FindClass("java/util/List");
  if(listClass == NULL) {
    return;                  // alternatively, throw exception (recipeNo019)
  }

  jclass integerClass = env->FindClass("java/lang/Integer");
  if(integerClass == NULL) {
    return;                  // alternatively, throw exception (recipeNo019)
  }

  jmethodID addMethodID = env->GetMethodID(listClass, "add", "(Ljava/lang/Object;)Z");
  if(addMethodID == NULL) {
    return;                  //                 - || -
  }

  jmethodID integerConstructorID = env->GetMethodID(integerClass, "<init>", "(I)V");
  if(integerConstructorID == NULL) {
    return;                  //                 - || -
  }

  for(int i : vect) {
    // Now, we have object created by Integer(i)
    jobject integerValue = env->NewObject(integerClass, integerConstructorID, i);
    if(integerValue == NULL) {
      return;
    }
    env->CallBooleanMethod(obj, addMethodID, integerValue);
  }

  env->DeleteLocalRef(listClass);
  env->DeleteLocalRef(integerClass);

}
</code>```

Note that you don't have to create List object inside JNI as you already have it there - inside C++ code. It is passed as argument of native method.

You can find full sample code here:

https://github.com/mkowsiak/jnicookbook/tree/master/recipes/recipeNo046

Once you run the code, you can see data from C++ being passed through the List object.

```<code>> make test
/Library/Java/JavaVirtualMachines/jdk-12.0.1.jdk/Contents/Home/bin/java -Djava.library.path=:./lib -cp target recipeNo046.FillTheList
library: :./lib
1
2
3
</code>```

Body:
I am fresh in C++ and JNI

Flow should be like this

From Java I pass a empty List to JNI, JNI invoke method loadData(std::vector<int>) from MyClass and this method fill my list with a data.

So, question is

I have

class MyClass {
public:
MyClass();
~MyClass();

void loadData(std::vector<int> & vector);
};

void MyClass::loadData(std::vector<int> & vector)
{
const int size = 10;

vector.resize(size);

for (int i = 0; i < size; ++i) {
    vector.push_back(4);
}
}

This is my method that I wrote in pure C++ and now I need to use it from Java like this

public native void fillListWithData(List<Integer> list);

So, I wrote such method in JNI to associate them

extern "C" JNIEXPORT void JNICALL
Java_com_google_ar_core_examples_java
_helloar_HelloArActivity_fillListWithData(
    JNIEnv *env,
    jobject /* this */,
    jobject input
) {
myClass->loadData("HERE I NEED TO PASS MY " input);
}

And here how I should to invoke this method

public void TEST(){
    List<Integer> list = new ArrayList<>();
    fillListWithData(list);
    Log.e("TAG", "HERE I NEED TO HAVE A LIST WITH FILLED DATA");
}

I can't understand how to pass this list by reference by JNI to C++...

Any ideas appreciate

Body:
In this case, it's quite simple. All you have to do is to pass List to your native code and fill it inside JNI part using JNI based access methods

#include <vector>
#include "jni.h"
#include "recipeNo046_FillTheList.h"
using namespace std;

JNIEXPORT void JNICALL Java_recipeNo046_FillTheList_fillTheList
  (JNIEnv *env, jclass cls, jobject obj) {

  vector<int> vect { 1, 2, 3 };

  jclass listClass = env->FindClass("java/util/List");
  if(listClass == NULL) {
    return;                  // alternatively, throw exception (recipeNo019)
  }

  jclass integerClass = env->FindClass("java/lang/Integer");
  if(integerClass == NULL) {
    return;                  // alternatively, throw exception (recipeNo019)
  }

  jmethodID addMethodID = env->GetMethodID(listClass, "add", "(Ljava/lang/Object;)Z");
  if(addMethodID == NULL) {
    return;                  //                 - || -
  }

  jmethodID integerConstructorID = env->GetMethodID(integerClass, "<init>", "(I)V");
  if(integerConstructorID == NULL) {
    return;                  //                 - || -
  }

  for(int i : vect) {
    // Now, we have object created by Integer(i)
    jobject integerValue = env->NewObject(integerClass, integerConstructorID, i);
    if(integerValue == NULL) {
      return;
    }
    env->CallBooleanMethod(obj, addMethodID, integerValue);
  }

  env->DeleteLocalRef(listClass);
  env->DeleteLocalRef(integerClass);

}

Note that you don't have to create List object inside JNI as you already have it there - inside C++ code. It is passed as argument of native method.

You can find full sample code here:

https://github.com/mkowsiak/jnicookbook/tree/master/recipes/recipeNo046

Once you run the code, you can see data from C++ being passed through the List object.

> make test
/Library/Java/JavaVirtualMachines/jdk-12.0.1.jdk/Contents/Home/bin/java -Djava.library.path=:./lib -cp target recipeNo046.FillTheList
library: :./lib
1
2
3


问:
XPath: Find Next Occurrence of an Element in an Ancestor
I am trying to find the next instance of  within a section of sec-type='reading'.

XML Sample:

<?xml version="1.0" encoding="US-ASCII"?>
<book>
    <sec sec-type="reading">
        <title>Section 1</title>

Sample <bold>Bold</bold>Text <fn>1</fn> Some more text

        <sec>
            <title>Section 1.1</title>

Another paragraph with a footnote <fn>2</fn>

        </sec>
        <sec>
            <title>Section 1.2</title>

Another paragraph with a footnote <fn>3</fn>

        </sec>
    </sec>

    <sec sec-type="reading">
        <title>Section 2</title>

Sample <bold>Bold</bold>Text <fn>6</fn> Some more text

        <sec>
            <title>Section 2.1</title>

Another paragraph with a footnote <fn>8</fn>

        </sec>
        <sec>
            <title>Section 2.2</title>

Another paragraph with a footnote <fn>9</fn>

        </sec>
    </sec>
</book>
```

<p>The purpose is to see if the FN labels are sequentially ordered within a section. I've numbered the second section with 6-9 to make it easier to see if it's working. </p>

<p>This is what I want:</p>

```Footnote 1 [Next: 2]
Footnote 2 [Next: 3]
Footnote 3 [Next: ]
Footnote 6 [Next: 8]
Footnote 8 [Next: 9]
Footnote 9 [Next: ]
```

<p>The eventual goal is to return a warning for <code>Footnote 6 [Next: 8]</code></p>

<p>This is the schematron I've got so far. This gives me:</p>

```Footnote 1 [Next: 2]
Footnote 2 [Next: 3]
**Footnote 3 [Next: 6]**
Footnote 6 [Next: 8]
Footnote 8 [Next: 9]
Footnote 9 [Next: ]
```

<p>It finds the next instance of the footnote. However, I don't want it to cross the sections - so <code>Footnote 3 [Next: 6]</code> is wrong.</p>

<pre class="lang-xml prettyprint-override"><code><?xml version="1.0" encoding="UTF-8"?>
<schema xmlns="http://purl.oclc.org/dsdl/schematron"
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    queryBinding="xslt2"  >

  <!--check if footnotes are sequential within a reading -->
  <pattern id="footnote-sequential">
    <rule context="fn">
        <let name="next" value="following::fn[1]/label/text()"/>

        <assert test="number(label/text()) > 40">
        Footnote <value-of select='label'/>
          [Next: <value-of select="$next"/>]
      </assert>
    </rule>
  </pattern>
</schema>
</code>```

Note: number(label/text()) > 40 in the assert is there to catch everything at the moment. It'll eventually be something along the lines of number(current)+1 != number(next)

The closest I've gotten is ancestor::sec[@sec-type='reading']//following::fn[1]/label/text() - but that looses the "next" and gives me weird results like this:

```<code>    Footnote 1 [Next: 1236]
    Footnote 2 [Next: 1236]
    Footnote 3 [Next: 1236]
    Footnote 6 [Next: 689]
    Footnote 8 [Next: 689]
    Footnote 9 [Next: 689]
</code>```

答:
You need intersect.

[EDIT]

Set $next to the fn element instead of the label text:

<let name="next" value="following::fn[1]"/>
```

<p><strong>[/EDIT]</strong></p>

<p>Go to your current section and take all footnotes of this section:</p>

<pre class="lang-xml prettyprint-override"><code><let name="sect-fns" value="ancestor::sec[@sec-type='reading']//fn" />
</code>```

Make the intersect on $next and $sect-fns:

<let name="next" value="$next intersect $sect-fns" />
```

<p>Check if <code>$next</code> is empty or its label is <code>number(./label) + 1</code>:</p>

<pre class="lang-xml prettyprint-override"><code><assert test="not($next) or number(./label) + 1 = number($next/label)">
</code>```

Body:
I am trying to find the next instance of  within a section of sec-type='reading'.

XML Sample:

<?xml version="1.0" encoding="US-ASCII"?>
<book>
    <sec sec-type="reading">
        <title>Section 1</title>

Sample <bold>Bold</bold>Text <fn>1</fn> Some more text

        <sec>
            <title>Section 1.1</title>

Another paragraph with a footnote <fn>2</fn>

        </sec>
        <sec>
            <title>Section 1.2</title>

Another paragraph with a footnote <fn>3</fn>

        </sec>
    </sec>

    <sec sec-type="reading">
        <title>Section 2</title>

Sample <bold>Bold</bold>Text <fn>6</fn> Some more text

        <sec>
            <title>Section 2.1</title>

Another paragraph with a footnote <fn>8</fn>

        </sec>
        <sec>
            <title>Section 2.2</title>

Another paragraph with a footnote <fn>9</fn>

        </sec>
    </sec>
</book>

The purpose is to see if the FN labels are sequentially ordered within a section. I've numbered the second section with 6-9 to make it easier to see if it's working.

This is what I want:

Footnote 1 [Next: 2]
Footnote 2 [Next: 3]
Footnote 3 [Next: ]
Footnote 6 [Next: 8]
Footnote 8 [Next: 9]
Footnote 9 [Next: ]

The eventual goal is to return a warning for Footnote 6 [Next: 8]

This is the schematron I've got so far. This gives me:

Footnote 1 [Next: 2]
Footnote 2 [Next: 3]
**Footnote 3 [Next: 6]**
Footnote 6 [Next: 8]
Footnote 8 [Next: 9]
Footnote 9 [Next: ]

It finds the next instance of the footnote. However, I don't want it to cross the sections - so Footnote 3 [Next: 6] is wrong.

<?xml version="1.0" encoding="UTF-8"?>
<schema xmlns="http://purl.oclc.org/dsdl/schematron"
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    queryBinding="xslt2"  >

  <pattern id="footnote-sequential">
    <rule context="fn">
        <let name="next" value="following::fn[1]/label/text()"/>

        <assert test="number(label/text()) > 40">
        Footnote <value-of select='label'/>
          [Next: <value-of select="$next"/>]
      </assert>
    </rule>
  </pattern>
</schema>

Note: number(label/text()) > 40 in the assert is there to catch everything at the moment. It'll eventually be something along the lines of number(current)+1 != number(next)

The closest I've gotten is ancestor::sec[@sec-type='reading']//following::fn[1]/label/text() - but that looses the "next" and gives me weird results like this:

    Footnote 1 [Next: 1236]
    Footnote 2 [Next: 1236]
    Footnote 3 [Next: 1236]
    Footnote 6 [Next: 689]
    Footnote 8 [Next: 689]
    Footnote 9 [Next: 689]

Body:
You need intersect.

[EDIT]

Set $next to the fn element instead of the label text:

<let name="next" value="following::fn[1]"/>

[/EDIT]

Go to your current section and take all footnotes of this section:

<let name="sect-fns" value="ancestor::sec[@sec-type='reading']//fn" />

Make the intersect on $next and $sect-fns:

<let name="next" value="$next intersect $sect-fns" />

Check if $next is empty or its label is number(./label) + 1:

<assert test="not($next) or number(./label) + 1 = number($next/label)">


问:
How can I validate a TreeView using parsley.js?
I'm using parsley for client-side validation and need to validate that a 3rd level node has been selected.

I have tried just adding the required="" attribute to the treeview tag but this doesn't appear to work.

It appears that parsley just ignores the TreeView control.

Are there any custom validators that address TreeViews?

Thanks!

答: No custom validators that I know of. You'll have to write your own.</p>