问:
SQL - char field with date - how to search between two dates
I have simple problem with SQL query.. I would like to search fields, where dates begin and ends in specific date and time.

Field is defined as CHAR and have structure: DD.MM.YYYY hh:mm:ss and I cannot change it.

I tried to declare some variables and search by this, also tried by Converting.

This is what I tried and didn't work:

```<code>SELECT date FROM table WHERE date BETWEEN '1.01.2017 00:00:00' AND '1.02.2017 23:59:59'

SELECT date FROM table WHERE date >= '1.01.2017 00:00:00' AND date <= '1.02.2017 00:00:00'

SELECT date FROM table WHERE date >= Convert(DATETIME, '1.01.2017', 104) AND date <= Convert(DATETIME, '1.02.2017', 104)
</code>```

Always after this query I get all dates, not this what I asked.

答:
I solved my problem. Problem was with that HOW this fields are storage in DB.
I thought that they are storage like: DD.MM.YYYY hh:mm:ss, but it was only structure. In DB they are storage like: YYYYMMDDhhmmss and after changes in WHERE query line it works.</p>

```<code>SELECT date FROM table WHERE date >= '20170101000000' AND date <= '20170101235959'
</code>```

Body:
I have simple problem with SQL query.. I would like to search fields, where dates begin and ends in specific date and time.

Field is defined as CHAR and have structure: DD.MM.YYYY hh:mm:ss and I cannot change it.

I tried to declare some variables and search by this, also tried by Converting.

This is what I tried and didn't work:

SELECT date FROM table WHERE date BETWEEN '1.01.2017 00:00:00' AND '1.02.2017 23:59:59'

SELECT date FROM table WHERE date >= '1.01.2017 00:00:00' AND date <= '1.02.2017 00:00:00'

SELECT date FROM table WHERE date >= Convert(DATETIME, '1.01.2017', 104) AND date <= Convert(DATETIME, '1.02.2017', 104)

Always after this query I get all dates, not this what I asked.

Body:
I solved my problem. Problem was with that HOW this fields are storage in DB.
I thought that they are storage like: DD.MM.YYYY hh:mm:ss, but it was only structure. In DB they are storage like: YYYYMMDDhhmmss and after changes in WHERE query line it works.

SELECT date FROM table WHERE date >= '20170101000000' AND date <= '20170101235959'


来源: stackexchange

问:
Validate checkbox using JavaScript.
I would like some help with checkbox validation.

If you look in below picture, when user click the image, the checkbox becomes selected.

What I would want is if all checkbox are selected alert an simple message.

This is a code to select checkbox by clicking on an image.

```<code>        $( document ).ready(function() {

    $("#roll-<?php echo $row['id_vnr']; ?><?php echo $cut_counter; ?>").click (function(){
         var $$ = $(this)

          if( !$$.is('.checked')){
              $$.addClass('checked');

              $('#imgCheck-<?php echo $row['id_vnr']; ?><?php echo $cut_counter; ?>').prop('checked', true);

                }
            });
    });
</code>```

So I can select check box by clicking on an image. How I can alert message if all check box are selected. Soon user click last picture, the picture will disappear, the red tick box will appear and user should see alert message.

Thank you in advance.

答:
You can use the following javascript code:</p>

```<code>$(function(){
   $('input[type="checkbox"]').click(function() {
     totalCheckboxCount = $('input[type="checkbox"]').length;
     selectedBoxesCount = $('input[type="checkbox"]:checked').length;
     if(totalCheckboxCount == selectedBoxesCount) {
       alert("All checkboxes selected!");
     }
   });
});
</code>```

ContentLicense: CC BY-SA 3.0

Title: Validate checkbox using JavaScript.

Body:
I would like some help with checkbox validation.

If you look in below picture, when user click the image, the checkbox becomes selected.

What I would want is if all checkbox are selected alert an simple message.

This is a code to select checkbox by clicking on an image.

        $( document ).ready(function() {

    $("#roll-<?php echo $row['id_vnr']; ?><?php echo $cut_counter; ?>").click (function(){
         var $$ = $(this)

          if( !$$.is('.checked')){
              $$.addClass('checked');

              $('#imgCheck-<?php echo $row['id_vnr']; ?><?php echo $cut_counter; ?>').prop('checked', true);

                }
            });
    });

So I can select check box by clicking on an image. How I can alert message if all check box are selected. Soon user click last picture, the picture will disappear, the red tick box will appear and user should see alert message.

Thank you in advance.

Body:
You can use the following javascript code:

$(function(){
   $('input[type="checkbox"]').click(function() {
     totalCheckboxCount = $('input[type="checkbox"]').length;
     selectedBoxesCount = $('input[type="checkbox"]:checked').length;
     if(totalCheckboxCount == selectedBoxesCount) {
       alert("All checkboxes selected!");
     }
   });
});


问:
Barcode Height missing from Custom Barcode Entry
I am integrating FedEx shipping API to generate labels using Java. Everything is working fine, but except for this issue. I am receiving the following error when setting LabelFormatType to COMMON2D or LABEL_DATA_ONLY for FedEx Freight i.e FEDEX_FREIGHT_ECONOMY and FEDEX_FREIGHT_PRIORITY.

```<code>        <Code>6022</Code>
        <Message>Barcode Height missing from Custom Barcode Entry</Message>
</code>```

I did try to add Barcode height in fields below, but its not working

```<code>RequestedShipment -> ShippingDocumentSpecification -> CustomShipmentDocumentDetail -> CustomContent -> BarcodeEntries -> BarHeight

RequestedShipment -> ShippingDocumentSpecification -> CustomPackageDocumentDetail -> CustomContent -> BarcodeEntries -> BarHeight

RequestedShipment -> ShippingDocumentSpecification -> FreightAddressLabelDetail -> CustomContent -> BarcodeEntries -> BarHeight

RequestedShipment -> LabelSpecification -> CustomerSpecifiedDetail -> CustomContent -> BarcodeEntries -> BarHeight
</code>```

Note: The code is working for other two LabelFormatTypei.e FEDEX_FREIGHT_STRAIGHT_BILL_OF_LADING and VICS_BILL_OF_LADING and other ServiceTypes.

I am unable to find any solution yet.

Please let me know what am I missing ?

答:
You were right, you need to use those 2 label format types. When it comes to LTL Freight shipment request, the "Barcode Height missing from Custom Barcode Entry" can be returned when using COMMON2D or LABEL_DATA_ONLY. As per FedEx support, the FedEx LTL shipments require a Bill-Of-Lading (BOL) and the only LabelFormatTypes available for this are either the FEDEX_FREIGHT_STRAIGHT_BILL_OF_LADING or VICS_BILL_OF_LADING where VICS = Voluntary Inter-Industry Commerce Standards.
This label is returned in PDF format, besides that you can request a FedEx Address Label in ZPL format.

Body:
I am integrating FedEx shipping API to generate labels using Java. Everything is working fine, but except for this issue. I am receiving the following error when setting LabelFormatType to COMMON2D or LABEL_DATA_ONLY for FedEx Freight i.e FEDEX_FREIGHT_ECONOMY and FEDEX_FREIGHT_PRIORITY.

        6022
        <Message>Barcode Height missing from Custom Barcode Entry</Message>

I did try to add Barcode height in fields below, but its not working

RequestedShipment -> ShippingDocumentSpecification -> CustomShipmentDocumentDetail -> CustomContent -> BarcodeEntries -> BarHeight

RequestedShipment -> ShippingDocumentSpecification -> CustomPackageDocumentDetail -> CustomContent -> BarcodeEntries -> BarHeight

RequestedShipment -> ShippingDocumentSpecification -> FreightAddressLabelDetail -> CustomContent -> BarcodeEntries -> BarHeight

RequestedShipment -> LabelSpecification -> CustomerSpecifiedDetail -> CustomContent -> BarcodeEntries -> BarHeight

Note: The code is working for other two LabelFormatTypei.e FEDEX_FREIGHT_STRAIGHT_BILL_OF_LADING and VICS_BILL_OF_LADING and other ServiceTypes.

I am unable to find any solution yet.

Please let me know what am I missing ?


问:
Laravel Dusk, how to destroy session data between tests
I am getting started using Laravel Dusk for browser testing, and have created a couple of tests to test my login form. I have the following code:

```<code>class LoginTest extends DuskTestCase
{

public function testLogin()
{
    $this->browse(function (Browser $browser) {
        $browser->visit('/admin')
            ->type('email', 'inigo@mydomain.co.uk')
            ->type('password', 'MyPass')
            ->press('Login')
            ->assertSee('Loading...');
    });
}

public function testLoginFailure(){
    $this->browse(function (Browser $browser){

        $browser->visit('/admin/logout'); // I have to add this to logout first, otherwise it's already logged in for this test!

        $browser->visit('/admin')
            ->type('email', 'someemail@afakedomain.com')
            ->type('password', 'somefakepasswordthatdoesntwork')
            ->press('Login')
            ->assertSee('These credentials do not match our records.');
    });
}
</code>```

See the comment. The first function runs fine, but when it comes to the second function, I have to logout first, since the user is already logged in as a result of running the first function. This came as a surprise to me as I thought unit tests were completely independent, with session data being destroyed automatically.

Is there a better way of doing this- some Dusk method that I'm missing perhaps- than having to call $browser->visit('/admin/logout'); ?

Thanks

EDIT Thanks for the 2 answers so far, which both seem valid solutions. I've updated the second function to the following:

```<code>public function testLoginFailure(){
    $this->createBrowsersFor(function(Browser $browser){
        $browser->visit('/admin')
            ->type('email', 'someshit@afakedomain.com')
            ->type('password', 'somefakepasswordthatdoesntwork')
            ->press('Login')
            ->assertSee('These credentials do not match our records.');
    });
}
</code>```

Which does the job. So

I can safely assume that this second browser only exists for the duration of this single function, correct?

What are the obvious advantages/disadvantages of creating a second browser instance rather than using the teardown method?

答:
You can call

```<code>$this->logout();
</code>```

InteractsWithAuthentication - Github

Edit:

This is the behaviour of the Dusk Test case, the primary browser instance remains for the other tests.

A second solution, create a second browser instance, which will be destroyed after the single test

See Dusk/TestCase #L103

Body:
I am getting started using Laravel Dusk for browser testing, and have created a couple of tests to test my login form. I have the following code:

class LoginTest extends DuskTestCase
{

public function testLogin()
{
    $this->browse(function (Browser $browser) {
        $browser->visit('/admin')
            ->type('email', 'inigo@mydomain.co.uk')
            ->type('password', 'MyPass')
            ->press('Login')
            ->assertSee('Loading...');
    });
}

public function testLoginFailure(){
    $this->browse(function (Browser $browser){

        $browser->visit('/admin/logout'); // I have to add this to logout first, otherwise it's already logged in for this test!

        $browser->visit('/admin')
            ->type('email', 'someemail@afakedomain.com')
            ->type('password', 'somefakepasswordthatdoesntwork')
            ->press('Login')
            ->assertSee('These credentials do not match our records.');
    });
}

See the comment. The first function runs fine, but when it comes to the second function, I have to logout first, since the user is already logged in as a result of running the first function. This came as a surprise to me as I thought unit tests were completely independent, with session data being destroyed automatically.

Is there a better way of doing this- some Dusk method that I'm missing perhaps- than having to call $browser->visit('/admin/logout'); ?

Thanks

EDIT Thanks for the 2 answers so far, which both seem valid solutions. I've updated the second function to the following:

public function testLoginFailure(){
    $this->createBrowsersFor(function(Browser $browser){
        $browser->visit('/admin')
            ->type('email', 'someshit@afakedomain.com')
            ->type('password', 'somefakepasswordthatdoesntwork')
            ->press('Login')
            ->assertSee('These credentials do not match our records.');
    });
}

Which does the job. So

I can safely assume that this second browser only exists for the duration of this single function, correct?

What are the obvious advantages/disadvantages of creating a second browser instance rather than using the teardown method?

Body:
You can call

$this->logout();

InteractsWithAuthentication - Github

Edit:

This is the behaviour of the Dusk Test case, the primary browser instance remains for the other tests.

A second solution, create a second browser instance, which will be destroyed after the single test

See Dusk/TestCase #L103


问:
How to set bits?
I have a remote service that receives a number of parameters and an integer to flag which ones are null:

```<code>byte<(param_count + 7)/8> null bitmap
</code>```

I've tried a naive implementation but since I've no experience in bit shifting I'd rather not show it.

So, given a vector of booleans, how can I create my bit map?

答:
If param_count is known at compile time you can use std::bitset. Here is an example:

```<code>// Define a bitmap with 'param_count + 7' elements
std::bitset<param_count + 7> b;

// Set the fifth bit, zero is the first bit
b[4] = 1;

// Convert to 'unsigned long', and the casting it to an int.
int a = int(b.to_ulong());
</code>```

If param_count is not known at compile time, you can use std::vector<bool>. Here is another example:

```<code>// Define a bitmap with 'param_count + 7' elements
std::vector<bool> b(param_count + 7);

// Set the fifth bit, zero is the first bit
b[4] = 1;

// Convert to 'int'
int a = std::accumulate(b.rbegin(), b.rend(), 0, [](int x, int y) { return (x << 1) + y; });
</code>```

The conversion from std::vector<bool> to int is taken from this answer.

Title: How to set bits?

Body:
I have a remote service that receives a number of parameters and an integer to flag which ones are null:

byte<(param_count + 7)/8> null bitmap

I've tried a naive implementation but since I've no experience in bit shifting I'd rather not show it.

So, given a vector of booleans, how can I create my bit map?

Body:
If param_count is known at compile time you can use std::bitset. Here is an example:

// Define a bitmap with 'param_count + 7' elements
std::bitset<param_count + 7> b;

// Set the fifth bit, zero is the first bit
b[4] = 1;

// Convert to 'unsigned long', and the casting it to an int.
int a = int(b.to_ulong());

If param_count is not known at compile time, you can use std::vector<bool>. Here is another example:

// Define a bitmap with 'param_count + 7' elements
std::vector<bool> b(param_count + 7);

// Set the fifth bit, zero is the first bit
b[4] = 1;

// Convert to 'int'
int a = std::accumulate(b.rbegin(), b.rend(), 0, [](int x, int y) { return (x << 1) + y; });

The conversion from std::vector<bool> to int is taken from this answer.


问:
Recursive delete
I have this code to recursive delete files and directories. It works fine but has a little problem. If $path = /var/www/foo/ it will delete everything inside of foo, but not foo. I want to delete foo directory too. Any idea? </p>

```<code>public function delete($path) {
    if(!file_exists($path)) {
        throw new RecursiveDirectoryException('Directory doesn\'t exist.');
    }

    $directoryIterator = new DirectoryIterator($path);

    foreach($directoryIterator as $fileInfo) {
        $filePath = $fileInfo->getPathname();

        if(!$fileInfo->isDot()) {
            if($fileInfo->isFile()) {
                unlink($filePath);
            }
            else if($fileInfo->isDir()) {
                if($this->emptyDirectory($filePath)) {
                    rmdir($filePath);
                }
                else {
                    $this->delete($filePath);
                    rmdir($filePath);
                }
            }
        }
    }
}
</code>```

答:
Why even recurse in your function?

```<code>public function delete($path) {
    $it = new RecursiveIteratorIterator(
        new RecursiveDirectoryIterator($path),
        RecursiveIteratorIterator::CHILD_FIRST
    );
    foreach ($it as $file) {
        if (in_array($file->getBasename(), array('.', '..'))) {
            continue;
        } elseif ($file->isDir()) {
            rmdir($file->getPathname());
        } elseif ($file->isFile() || $file->isLink()) {
            unlink($file->getPathname());
        }
    }
    rmdir($path);
}
</code>```

It works, because RII::CHILD_FIRST iterates over the children before the parent element.  So by the time it reaches the directory, it should be empty.

But the actual error is due to where you delete your directories.  In inner directories you do it in the parent iteration.  That means that your root directory will never be deleted.  I'd suggest doing it in the local delete iteration:

```<code>public function delete($path) {
    if(!file_exists($path)) {
        throw new RecursiveDirectoryException('Directory doesn\'t exist.');
    }

    $directoryIterator = new DirectoryIterator($path);

    foreach($directoryIterator as $fileInfo) {
        $filePath = $fileInfo->getPathname();
        if(!$fileInfo->isDot()) {
            if($fileInfo->isFile()) {
                unlink($filePath);
            } elseif($fileInfo->isDir()) {
                if($this->emptyDirectory($filePath)) {
                    rmdir($filePath);
                } else {
                    $this->delete($filePath);
                }
            }
        }
    }
    rmdir($path);
}
</code>```

Note the two changes.  We're only deleting the empty directories inside of the iteration.  Calling $this->delete() on it will handle the deletion for you.  The second change is the addition of the final rmdir at the end of the method...

Title: Recursive delete

Body:
I have this code to recursive delete files and directories. It works fine but has a little problem. If $path = /var/www/foo/ it will delete everything inside of foo, but not foo. I want to delete foo directory too. Any idea?

public function delete($path) {
    if(!file_exists($path)) {
        throw new RecursiveDirectoryException('Directory doesn\'t exist.');
    }

    $directoryIterator = new DirectoryIterator($path);

    foreach($directoryIterator as $fileInfo) {
        $filePath = $fileInfo->getPathname();

        if(!$fileInfo->isDot()) {
            if($fileInfo->isFile()) {
                unlink($filePath);
            }
            else if($fileInfo->isDir()) {
                if($this->emptyDirectory($filePath)) {
                    rmdir($filePath);
                }
                else {
                    $this->delete($filePath);
                    rmdir($filePath);
                }
            }
        }
    }
}

Body:
Why even recurse in your function?

public function delete($path) {
    $it = new RecursiveIteratorIterator(
        new RecursiveDirectoryIterator($path),
        RecursiveIteratorIterator::CHILD_FIRST
    );
    foreach ($it as $file) {
        if (in_array($file->getBasename(), array('.', '..'))) {
            continue;
        } elseif ($file->isDir()) {
            rmdir($file->getPathname());
        } elseif ($file->isFile() || $file->isLink()) {
            unlink($file->getPathname());
        }
    }
    rmdir($path);
}

It works, because RII::CHILD_FIRST iterates over the children before the parent element.  So by the time it reaches the directory, it should be empty.

But the actual error is due to where you delete your directories.  In inner directories you do it in the parent iteration.  That means that your root directory will never be deleted.  I'd suggest doing it in the local delete iteration:

public function delete($path) {
    if(!file_exists($path)) {
        throw new RecursiveDirectoryException('Directory doesn\'t exist.');
    }

    $directoryIterator = new DirectoryIterator($path);

    foreach($directoryIterator as $fileInfo) {
        $filePath = $fileInfo->getPathname();
        if(!$fileInfo->isDot()) {
            if($fileInfo->isFile()) {
                unlink($filePath);
            } elseif($fileInfo->isDir()) {
                if($this->emptyDirectory($filePath)) {
                    rmdir($filePath);
                } else {
                    $this->delete($filePath);
                }
            }
        }
    }
    rmdir($path);
}

Note the two changes.  We're only deleting the empty directories inside of the iteration.  Calling $this->delete() on it will handle the deletion for you.  The second change is the addition of the final rmdir at the end of the method...

ContentLicense: CC BY-SA 2.5


问:
iBatis resultClass result variable is null
Sorry, poor English level,
Forgive me stackoverflow.

The company is using the "ANT" script generation tool generated SQL MAPPER, the use of 'resultClass', the return of the object data is empty. Sql in the database is no problem. And other people use the same wording, can not get the correct results.

PS: If I do not use resultClass, just return a count to get the result

ANT script：

```<code><operation name="queryAgentLoanCount" multiplicity="many" resultClass="com.bench.common.dal.result.AgentLoanCountResult">
    <extraparams>
        <param name="agentNo" javatype="java.lang.String"/>
    </extraparams>
    <sql>
        SELECT COUNT(ID) FROM bops_agent_loan_record
    </sql>
    <sqlmap>
        <![CDATA[
        SELECT COALESCE(SUM(tt.LOAN_AMT),0) TT_AMT ,COALESCE(COUNT(t.ID),0) TT_SUM
        FROM bops_agent_loan_record t LEFT JOIN bops_loan_request tt
                ON t.REQ_NO = tt.REQ_NO
        WHERE tt.LOAN_TYPE IN ('P1024', 'P1002', 'P5060')
                AND tt.STATE IN ('SELLING', 'BACKING', 'BACKED', 'OVERDUE')
                AND t.AGENT_NO = #agentNo#
        ]]>
    </sqlmap>
</operation>
</code>```

Generated SQLMAPPER:

```<code><select id="MS-AGENT-LOAN-RECORD-QUERY-AGENT-LOAN-COUNT" resultClass="com.bench.common.dal.result.AgentLoanCountResult">
    SELECT COALESCE(SUM(tt.LOAN_AMT),0) TT_AMT ,COALESCE(COUNT(t.ID),0) TT_SUM
        FROM bops_agent_loan_record t LEFT JOIN bops_loan_request tt
                ON t.REQ_NO = tt.REQ_NO
        WHERE tt.LOAN_TYPE IN ('P1024', 'P1002', 'P5060')
                AND tt.STATE IN ('SELLING', 'BACKING', 'BACKED', 'OVERDUE')
                AND t.AGENT_NO = #agentNo#
</select>
</code>```

resultClass:

```<code>public class AgentLoanCountResult extends BaseDO {

private Long ttSum;

private Double ttAmt;

public AgentLoanCountResult() {
}

public AgentLoanCountResult(Long ttSum, Double ttAmt) {
    this.ttSum = ttSum;
    this.ttAmt = ttAmt;
}

public void setTtSum(Long ttSum) {
    this.ttSum = ttSum;
}

public Long getTtSum() {
    return ttSum;
}

public Double getTtAmt() {
    return ttAmt;
}

public void setTtAmt(Double ttAmt) {
    this.ttAmt = ttAmt;
}
</code>```

}

答:
You should map the columns in your result object. Try something like this</p>

```<code><resultMap id="resultMapName" class="com.your.object">
    <result property="ttSum" column="TT_SUM" />
    <result property="ttAmt" column="TT_AMT" />
</resultMap>
<select id="MS-AGENT-LOAN-RECORD-QUERY-AGENT-LOAN-COUNT" resultMap="resultMapName">
    SELECT COALESCE(SUM(tt.LOAN_AMT),0) TT_AMT ,COALESCE(COUNT(t.ID),0) TT_SUM
        FROM bops_agent_loan_record t LEFT JOIN bops_loan_request tt
                ON t.REQ_NO = tt.REQ_NO
        WHERE tt.LOAN_TYPE IN ('P1024', 'P1002', 'P5060')
                AND tt.STATE IN ('SELLING', 'BACKING', 'BACKED', 'OVERDUE')
                AND t.AGENT_NO = #agentNo#
</select>
</code>```

Body:
Sorry, poor English level,
Forgive me stackoverflow.

The company is using the "ANT" script generation tool generated SQL MAPPER, the use of 'resultClass', the return of the object data is empty. Sql in the database is no problem. And other people use the same wording, can not get the correct results.

PS: If I do not use resultClass, just return a count to get the result

ANT script：

<operation name="queryAgentLoanCount" multiplicity="many" resultClass="com.bench.common.dal.result.AgentLoanCountResult">
    <extraparams>
        <param name="agentNo" javatype="java.lang.String"/>
    </extraparams>
    <sql>
        SELECT COUNT(ID) FROM bops_agent_loan_record
    </sql>
    <sqlmap>
        <![CDATA[
        SELECT COALESCE(SUM(tt.LOAN_AMT),0) TT_AMT ,COALESCE(COUNT(t.ID),0) TT_SUM
        FROM bops_agent_loan_record t LEFT JOIN bops_loan_request tt
                ON t.REQ_NO = tt.REQ_NO
        WHERE tt.LOAN_TYPE IN ('P1024', 'P1002', 'P5060')
                AND tt.STATE IN ('SELLING', 'BACKING', 'BACKED', 'OVERDUE')
                AND t.AGENT_NO = #agentNo#
        ]]>
    </sqlmap>
</operation>

Generated SQLMAPPER:

<select id="MS-AGENT-LOAN-RECORD-QUERY-AGENT-LOAN-COUNT" resultClass="com.bench.common.dal.result.AgentLoanCountResult">
    SELECT COALESCE(SUM(tt.LOAN_AMT),0) TT_AMT ,COALESCE(COUNT(t.ID),0) TT_SUM
        FROM bops_agent_loan_record t LEFT JOIN bops_loan_request tt
                ON t.REQ_NO = tt.REQ_NO
        WHERE tt.LOAN_TYPE IN ('P1024', 'P1002', 'P5060')
                AND tt.STATE IN ('SELLING', 'BACKING', 'BACKED', 'OVERDUE')
                AND t.AGENT_NO = #agentNo#
</select>

resultClass:

public class AgentLoanCountResult extends BaseDO {

private Long ttSum;

private Double ttAmt;

public AgentLoanCountResult() {
}

public AgentLoanCountResult(Long ttSum, Double ttAmt) {
    this.ttSum = ttSum;
    this.ttAmt = ttAmt;
}

public void setTtSum(Long ttSum) {
    this.ttSum = ttSum;
}

public Long getTtSum() {
    return ttSum;
}

public Double getTtAmt() {
    return ttAmt;
}

public void setTtAmt(Double ttAmt) {
    this.ttAmt = ttAmt;
}

}

Body:
You should map the columns in your result object. Try something like this

<resultMap id="resultMapName" class="com.your.object">
    <result property="ttSum" column="TT_SUM" />
    <result property="ttAmt" column="TT_AMT" />
</resultMap>
<select id="MS-AGENT-LOAN-RECORD-QUERY-AGENT-LOAN-COUNT" resultMap="resultMapName">
    SELECT COALESCE(SUM(tt.LOAN_AMT),0) TT_AMT ,COALESCE(COUNT(t.ID),0) TT_SUM
        FROM bops_agent_loan_record t LEFT JOIN bops_loan_request tt
                ON t.REQ_NO = tt.REQ_NO
        WHERE tt.LOAN_TYPE IN ('P1024', 'P1002', 'P5060')
                AND tt.STATE IN ('SELLING', 'BACKING', 'BACKED', 'OVERDUE')
                AND t.AGENT_NO = #agentNo#
</select>


问:
how to run ng-repeat by hardcoding value instead of passing array
I want manually run the ng-repeat by hardcode number. I don't want to pass array parameter. I have tried below code but It's does not work!

```<code><h1 ng-repeat="x in 20">{{sumofTwendy(($index}})</h1>
</code>```

So I have planed to create a dummy array in controller and assign value 20 to length of that array. then I pass the array on `ng-repeat.

```<code>   $scope.data=[];
   $scope.data.length=20;
   <h1 ng-repeat="x in data">{{sumofTwendy(($index}})</h1>
</code>```

this is also does not working :( .

How can we run  ng-repeat only by 20 times without passing array values?

let me know the solution if it angular 1 or angular 2?

答:
Just create array with length 20:</p>

```<code>new Array(20);
</code>```

Body:
I want manually run the ng-repeat by hardcode number. I don't want to pass array parameter. I have tried below code but It's does not work!

{{sumofTwendy(($index}})

So I have planed to create a dummy array in controller and assign value 20 to length of that array. then I pass the array on `ng-repeat.

   $scope.data=[];
   $scope.data.length=20;

{{sumofTwendy(($index}})

this is also does not working :( .

How can we run  ng-repeat only by 20 times without passing array values?

let me know the solution if it angular 1 or angular 2?

Body:
Just create array with length 20:

new Array(20);


问:
How to call an api from another api in expressjs?
I have an api like this:

```<code>app.get('/test', (req, res) => {
   console.log("this is test");
});
</code>```

and another api:

```<code>app.get('/check', (req, res) => {
   //I want to call "test" api without redirect to it.
});
</code>```

I want to call "test" api in "check" api without redirect to "test" api, just do the function in the "test" api.
Above is the example code. 'Cause I dont' want to rewrite function from "test" api to "check"

答:
To "call an API from another API", a quick and easy way is sending HTTP request inside Express server, browser would never know an internal HTTP invocation happens, not mention page-redirect. The benefit of this design includes:

There's no need to change the current API design.

The API invocation can be made exact like sent from browser.

Here is an example:

```<code>var http = require('http');

router.get('/test', function(req, res) {
  res.end('data_from_test');
});

router.get('/check', function(req, res) {
  var request = http.request({
    host: 'localhost',
    port: 3000,
    path: '/test',
    method: 'GET',
    headers: {
      // headers such as "Cookie" can be extracted from req object and sent to /test
    }
  }, function(response) {
    var data = '';
    response.setEncoding('utf8');
    response.on('data', (chunk) => {
      data += chunk;
    });
    response.on('end', () => {
      res.end('check result: ' + data);
    });
  });
  request.end();
});
</code>```

The result of GET /check would be:

```<code>check result: data_from_test
</code>```

Body:
I have an api like this:

app.get('/test', (req, res) => {
   console.log("this is test");
});

and another api:

app.get('/check', (req, res) => {
   //I want to call "test" api without redirect to it.
});

I want to call "test" api in "check" api without redirect to "test" api, just do the function in the "test" api.
Above is the example code. 'Cause I dont' want to rewrite function from "test" api to "check"

Body:
To "call an API from another API", a quick and easy way is sending HTTP request inside Express server, browser would never know an internal HTTP invocation happens, not mention page-redirect. The benefit of this design includes:

There's no need to change the current API design.

The API invocation can be made exact like sent from browser.

Here is an example:

var http = require('http');

router.get('/test', function(req, res) {
  res.end('data_from_test');
});

router.get('/check', function(req, res) {
  var request = http.request({
    host: 'localhost',
    port: 3000,
    path: '/test',
    method: 'GET',
    headers: {
      // headers such as "Cookie" can be extracted from req object and sent to /test
    }
  }, function(response) {
    var data = '';
    response.setEncoding('utf8');
    response.on('data', (chunk) => {
      data += chunk;
    });
    response.on('end', () => {
      res.end('check result: ' + data);
    });
  });
  request.end();
});

The result of GET /check would be:

check result: data_from_test


问:
How can I plot more than 50,000 values in a scatter chart, saving computer resource?
I'm using Visual Studio 2017 and am trying to make a program that shows real-time values in a scatter chart, using C# and winform.

With the source code below, I was able to make it show real-time values, whenever an event occurs and it gets a new value(3~5 times a second).

valueArray continuously gets new values through GetRealTimeData function and the chart shows all the elements in the array.

```<code>        valueArray[valueArray.Length - 1] = Convert.ToDouble(GetRealTimeData().Trim());

        Array.Copy(valueArray, 1, valueArray, 0, valueArray.Length - 1);

        this.chart1.Series["Series1"].Points.Clear();
        this.chart1.Series["Series1"].Points.DataBindY(valueArray);
</code>```

However, I have a problem using this program, which is it consumes much computer resource even when it shows 3,000 values in the chart.

I plan to make the chart represent 50,000 to 100,000 values, but I think it uses up too much resource copying and showing old values everytime it gets a new value.

I'd like to know if there are any functions or methods to do this kind of job. I would appreciate it if I could get some advices or ideas.

答:
There's hardly any reason that I know of, to ever load any chart with 100,000+ points. You can present your data using a fraction of your original points, without any loss of visual information. Here's a sample filtering 100,000 points down to 250 points (0.25%):

```<code>public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    private void Form1_Load(object sender, EventArgs e)
    {
        double percent = 0.0025;

        List<DataPoint> original = GetData();
        List<DataPoint> filtered = Filter(original, percent);

        foreach (DataPoint dp in original)
            chart1.Series[0].Points.Add(dp);

        foreach (DataPoint dp in filtered)
            chart1.Series[1].Points.Add(dp);

        chart1.ChartAreas[0].AxisY.Maximum = original.Max(dp => dp.YValues[0]);
        chart1.ChartAreas[0].AxisY.Minimum = original.Min(dp => dp.YValues[0]);
        chart1.ChartAreas[0].AxisX.Minimum = 0;

        Text = string.Format("original = {0:0,0} points, filtered = {1:0,0} points, percent = {2:P2}", original.Count, filtered.Count, percent);
    }

    private List<DataPoint> Filter(List<DataPoint> orig, double percent)
    {
        Random r = new Random(DateTime.Now.Millisecond);

        List<DataPoint> filt = new List<DataPoint>(orig.ToArray());
        double total = filt.Count;

        while (filt.Count / total > percent)
            filt.RemoveAt(r.Next(1, filt.Count - 1));

        return filt;
    }

    private void button1_Click(object sender, EventArgs e)
    {
        if (chart1.Series[0].Enabled)
        {
            chart1.Series[0].Enabled = false;
            chart1.Series[1].Enabled = true;
        }
        else
        {
            chart1.Series[0].Enabled = true;
            chart1.Series[1].Enabled = false;
        }
    }
}
</code>```

I understand you're adding points dynamically, so you'll have to add some logic to it. But my point still stands: you must filter your data. Also, you can use a more sophisticated filter, if you can come up with one.

Body:
I'm using Visual Studio 2017 and am trying to make a program that shows real-time values in a scatter chart, using C# and winform.

With the source code below, I was able to make it show real-time values, whenever an event occurs and it gets a new value(3~5 times a second).

valueArray continuously gets new values through GetRealTimeData function and the chart shows all the elements in the array.

        valueArray[valueArray.Length - 1] = Convert.ToDouble(GetRealTimeData().Trim());

        Array.Copy(valueArray, 1, valueArray, 0, valueArray.Length - 1);

        this.chart1.Series["Series1"].Points.Clear();
        this.chart1.Series["Series1"].Points.DataBindY(valueArray);

However, I have a problem using this program, which is it consumes much computer resource even when it shows 3,000 values in the chart.

I plan to make the chart represent 50,000 to 100,000 values, but I think it uses up too much resource copying and showing old values everytime it gets a new value.

I'd like to know if there are any functions or methods to do this kind of job. I would appreciate it if I could get some advices or ideas.

Body:
There's hardly any reason that I know of, to ever load any chart with 100,000+ points. You can present your data using a fraction of your original points, without any loss of visual information. Here's a sample filtering 100,000 points down to 250 points (0.25%):

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    private void Form1_Load(object sender, EventArgs e)
    {
        double percent = 0.0025;

        List<DataPoint> original = GetData();
        List<DataPoint> filtered = Filter(original, percent);

        foreach (DataPoint dp in original)
            chart1.Series[0].Points.Add(dp);

        foreach (DataPoint dp in filtered)
            chart1.Series[1].Points.Add(dp);

        chart1.ChartAreas[0].AxisY.Maximum = original.Max(dp => dp.YValues[0]);
        chart1.ChartAreas[0].AxisY.Minimum = original.Min(dp => dp.YValues[0]);
        chart1.ChartAreas[0].AxisX.Minimum = 0;

        Text = string.Format("original = {0:0,0} points, filtered = {1:0,0} points, percent = {2:P2}", original.Count, filtered.Count, percent);
    }

    private List<DataPoint> Filter(List<DataPoint> orig, double percent)
    {
        Random r = new Random(DateTime.Now.Millisecond);

        List<DataPoint> filt = new List<DataPoint>(orig.ToArray());
        double total = filt.Count;

        while (filt.Count / total > percent)
            filt.RemoveAt(r.Next(1, filt.Count - 1));

        return filt;
    }

    private void button1_Click(object sender, EventArgs e)
    {
        if (chart1.Series[0].Enabled)
        {
            chart1.Series[0].Enabled = false;
            chart1.Series[1].Enabled = true;
        }
        else
        {
            chart1.Series[0].Enabled = true;
            chart1.Series[1].Enabled = false;
        }
    }
}

I understand you're adding points dynamically, so you'll have to add some logic to it. But my point still stands: you must filter your data. Also, you can use a more sophisticated filter, if you can come up with one.


问:
Class constant in CreateJS undefined
I am trying to create a constant named "SPEED" for a "Main" class in Adobe Animate. Below is my code.

```<code>function Main(){
    this.update.bind(this));
}

Main.SPEED = 3.0;

Main.prototype.update = function(evt){
    console.log("SPEED"+SPEED);
    console.log(5+SPEED);
}
</code>```

The problem is that it displays as undefined.
If I try to do some calculations with it the result is NaN.
The sample of the console feed can be viewed here.

What would be the cause of this?

答:
You have defined correctly your constant:

```<code>Main.SPEED = 3.0;
</code>```

But you are not using it. In your code, you defined Main.SPEED, but in your update function you're using SPEED, a variable you haven't defined:

```<code>Main.prototype.update = function(evt){
    console.log("SPEED"+SPEED); // SPEED is not defined
    console.log(5+SPEED);
}
</code>```

Try the following code. In this one, I defined your constant, and a speed property of the Main function, setted to 0. In each tick, the value of the constant is added to the speed property.

```<code>function Main(){
    this.speed = 0;
    createjs.Ticker.addEventListener("tick", this.update.bind(this));
}

Main.SPEED = 3.0;

Main.prototype.update = function(evt){
    this.speed += Main.SPEED;
    console.log("SPEED: " + this.speed);
}

var main = new Main();
</code>```

Title: Class constant in CreateJS undefined

Body:
I am trying to create a constant named "SPEED" for a "Main" class in Adobe Animate. Below is my code.

function Main(){
    this.update.bind(this));
}

Main.SPEED = 3.0;

Main.prototype.update = function(evt){
    console.log("SPEED"+SPEED);
    console.log(5+SPEED);
}

The problem is that it displays as undefined.
If I try to do some calculations with it the result is NaN.
The sample of the console feed can be viewed here.

What would be the cause of this?

Body:
You have defined correctly your constant:

Main.SPEED = 3.0;

But you are not using it. In your code, you defined Main.SPEED, but in your update function you're using SPEED, a variable you haven't defined:

Main.prototype.update = function(evt){
    console.log("SPEED"+SPEED); // SPEED is not defined
    console.log(5+SPEED);
}

Try the following code. In this one, I defined your constant, and a speed property of the Main function, setted to 0. In each tick, the value of the constant is added to the speed property.

function Main(){
    this.speed = 0;
    createjs.Ticker.addEventListener("tick", this.update.bind(this));
}

Main.SPEED = 3.0;

Main.prototype.update = function(evt){
    this.speed += Main.SPEED;
    console.log("SPEED: " + this.speed);
}

var main = new Main();


问:
trigger travis CI build only with specific commit message
I want travis to start only if I have a certian commit message.
how can i do this. My travis.yml file is here

I know there is an on condition from this question but I dont know where to put it.

答:
The question you mentioned regards deploying travis build. So on: condition only determines if build is deployed or not. Regardless this setting other build steps are executed on each commit/pull request.

What you could use instead is adding [ci skip] or [skip ci] in commit messages to force build skipping.

You can also use TRAVIS_COMMIT_MESSAGE default env variable in all your build steps to determine if step should be executed or skipped, e.g.

```<code> script: if [[ $TRAVIS_COMMIT_MESSAGE == *"trigger build"* ]]; then mvn install ; fi ;
</code>```

Body:
The question you mentioned regards deploying travis build. So on: condition only determines if build is deployed or not. Regardless this setting other build steps are executed on each commit/pull request.

What you could use instead is adding [ci skip] or [skip ci] in commit messages to force build skipping.

You can also use TRAVIS_COMMIT_MESSAGE default env variable in all your build steps to determine if step should be executed or skipped, e.g.

 script: if [[ $TRAVIS_COMMIT_MESSAGE == *"trigger build"* ]]; then mvn install ; fi ;

ContentLicense: CC BY-SA 4.0


问:
pip install --find-links html file format
I need to include a few python packages into my product, but the jenkins server that does the build does not have access to the Internet. I've downloaded one of the packages using pip download, which downloaded the package and all its dependencies. However, I need to make sure pip knows where to find those dependencies. I'm trying to use the options --no-index and --find-links with a path to an html file with links to those packages. The full command looks like this:

```<code>pip install http://SERVER/python-packages/impyla/0.14.0/impyla-0.14.0.tar.gz --no-index --trusted-host SERVER --find-links http://SERVER/python-packages/impyla/0.14.0/packages.html
</code>```

...and the packages.html file looks like this:

bitarray-0.8.1.tar.gz
ply-3.10.tar.gz
six-1.10.0-py2.py3-none-any.whl
thriftpy-0.3.9.tar.gz```

However, when jenkins tries to run these commands, I get:

Could not find a version that satisfies the requirement
  thriftpy>=0.3.5 (from impyla==0.14.0) (from versions: )

No matching distribution found for thriftpy>=0.3.5 (from
  impyla==0.14.0)

I'm wondering if my packages.html isn't in a correct format, but I can't find any examples of using an html file for dependency resolution. Has anyone used --find-links successfully?

答: I never saw a requirements file in html format but maybe is possible, the examples in official doc are .txt files but I think your trouble is another thing for example you must check the following the architectural of the operative system where you did the download of the package because this package are bind to that architectural I mean 64bit or 32bit, the other thing is to check you have same python interpreter or another one compatible with the one where you did the packages download, all that things are important, even if it is not important for you to keep the version of thriftpy do not specify a version for this package and delete it from the requirement file and let the pip find the mayor version who works for you that is what happen if you do not specify a version for a package.

Body:
I need to include a few python packages into my product, but the jenkins server that does the build does not have access to the Internet. I've downloaded one of the packages using pip download, which downloaded the package and all its dependencies. However, I need to make sure pip knows where to find those dependencies. I'm trying to use the options --no-index and --find-links with a path to an html file with links to those packages. The full command looks like this:

pip install http://SERVER/python-packages/impyla/0.14.0/impyla-0.14.0.tar.gz --no-index --trusted-host SERVER --find-links http://SERVER/python-packages/impyla/0.14.0/packages.html

...and the packages.html file looks like this:

bitarray-0.8.1.tar.gz
ply-3.10.tar.gz
six-1.10.0-py2.py3-none-any.whl
thriftpy-0.3.9.tar.gz

However, when jenkins tries to run these commands, I get:

Could not find a version that satisfies the requirement
  thriftpy>=0.3.5 (from impyla==0.14.0) (from versions: )

No matching distribution found for thriftpy>=0.3.5 (from
  impyla==0.14.0)

I'm wondering if my packages.html isn't in a correct format, but I can't find any examples of using an html file for dependency resolution. Has anyone used --find-links successfully?


问:
How to retrieve a generic list from session?
I have a list that I put in session:

```<code>Session.Add("SessionList", mylist);
</code>```

How to retrieve it back from the session?

答:
Try this:</p>

```<code>Var sessionlist = (List<Type of list>) Session["CustomerSessionList"];
</code>```

Body:
I have a list that I put in session:

Session.Add("SessionList", mylist);

How to retrieve it back from the session?

Body:
Try this:

Var sessionlist = (List<Type of list>) Session["CustomerSessionList"];


问:
Running Angular Web App and NodeJS server together on same port?
I used Yeoman to set up a basic angularjs web app which I build and run using Grunt, and I've made a basic nodejs server with a few endpoints that the angular app uses to fetch data.

However I want to run the angular app and the node server on the same port, is there some way that I serve the angular app from my node server without using grunt serve or grunt serve:dist? Will I still be able to minify my angular app before serving it from a node server?

Clarification:
e.g. if I go to http://localhost/ it should serve the angular app, however, if I go to http://localhost/api/xyz it should serve the node endpoint.

答:
You can do as follows.
folder Structure

```<code>/
 /public
  /dist
   index.html
 /models
 /controllers
 server.js
</code>```

server.js is the normal nodejs server starting file.

public/dist folder is the built output form the angular (by ng build)

In server.js file, define all api routers first and after that add * route to send the index.html file

```<code>// Set our api routes
app.use('/api', api);     // <- define api end point

// Catch all other routes and return the index file
app.get('*', function(req, res) {
   res.sendFile(path.join(__dirname, 'dist/index.html'));
});
</code>```

Here what I do is, if url is something like http://localhost/api/xyz then it will hit in the api router. if url is some something other than /api it will send the index.html file to the client.

Note: in the browser you should navigate to something like http://localhost/ but not to http://locahlost/api. By the angular app you should handle(redirect) the miss order router inputs.

I think you got my point. If you want more example contact me, I will give you my code samples.

Body:
You can do as follows.
folder Structure

/
 /public
  /dist
   index.html
 /models
 /controllers
 server.js

server.js is the normal nodejs server starting file.

public/dist folder is the built output form the angular (by ng build)

In server.js file, define all api routers first and after that add * route to send the index.html file

// Set our api routes
app.use('/api', api);     // <- define api end point

// Catch all other routes and return the index file
app.get('*', function(req, res) {
   res.sendFile(path.join(__dirname, 'dist/index.html'));
});

Here what I do is, if url is something like http://localhost/api/xyz then it will hit in the api router. if url is some something other than /api it will send the index.html file to the client.

Note: in the browser you should navigate to something like http://localhost/ but not to http://locahlost/api. By the angular app you should handle(redirect) the miss order router inputs.

I think you got my point. If you want more example contact me, I will give you my code samples.


问:
Keystone JS CORS
Ok so I am pretty new to Keystone JS and I have decided to use it as an API backend for a project.

I have gotten all my API endpoints/routes are all done and they work perfectly in my browser however when trying to fetch the data remotely I keep getting the same error: XMLHttpRequest cannot load http://localhost:3000/keystone/api/. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost' is therefore not allowed access.

I am not unfamiliar with CORS and have tried to enable it by adding the following to my keystone.js and routes/index.js

keystone.js:

```<code>keystone.set('cors allow origin', true);
keystone.set('cors allow methods', true);
keystone.set('cors allow headers', true);
</code>```

routes/index.js:

```<code>// Setup Route Bindings
exports = module.exports = function (app) {
    app.all('/api/*', keystone.middleware.cors);
    app.options('/api*', function(req, res) { res.send(200); });

    // Views
    app.get('/', routes.views.index);

    // API
    // Lists
    ...
</code>```

Now I have tried finding solutions to this by looking through alot of documentation but according to my findings this should be more than enough to make CORS work with Keystone.

In addition to this I will present also my Keystone Service in my Angular JS 1.x frontend for you to see what I am trying to pull off..

keystone.service.js:

```<code>(function() {
    'use strict';

    angular.module('zApp')
        .service('KeystoneService', ['$log', '$http', function($log, $http) {
            var $keystoneApi = {};

            var _handleRequest = function(requestObj) {
                var data = {};

                if(requestObj.withCredentials === undefined) {
                    requestObj.withCredentials = true;
                }

                if(requestObj.method === undefined) {
                    requestObj.method = 'GET';
                }

                $http(requestObj, {headers: $keystoneApi.headers})
                    .then(
                        function success(response) {
                            data = response.data;
                        },
                        function error(response) {
                            // todo; handle error
                            $log.info(response);
                        }
                    );
                return data;
            };

            var _isIdValid = function(id) {
                if(/^[a-zA-Z0-9]*$/.test(id)) {
                    return true;
                }
                return false;
            };

            // Should be changed to oauth when there is better support in Keystone!
            this.init = function(settings) {
                if(settings.url !== undefined && settings.usr !== undefined && settings.pass !== undefined) {
                    $keystoneApi = settings;
                    $keystoneApi.auth = window.btoa($keystoneApi.usr + ':' + $keystoneApi.pass);
                    $keystoneApi.headers = {"Authorization": "Basic " + $keystoneApi.auth};
                    return this;
                }
                return false;
            }

            /**
             * User
             */
            this.getCmsAllUsers = function() {
                var requestObj = {
                    url: $keystoneApi.url + 'User/'
                };
                var response = _handleRequest(requestObj);
                // todo; handle response
                $log.info(response);
            };

            this.getCmsUser = function(id) {
                if(_isIdValid(id)) {
                    var requestObj = {
                        url: $keystoneApi.url + 'User/' + id
                    };

                    var response = _handleRequest(requestObj);
                    // todo; handle response
                    $log.info(response);
                }
            };

            this.updateCmsUser = function(userObject) {
                if(_isIdValid(userObject.id)) {
                    var requestObj = {
                        url: $keystoneApi.url + 'User/' + id + '/update/',
                        data: userObject
                    };

                    var response = _handleRequest(requestObj);
                    // todo; handle response
                    $log.info(response);
                }
            };

            /**
             * Profile
             */
            this.getCmsAllProfiles = function() {
                var requestObj = {
                    url: $keystoneApi.url + 'Profile/'
                };
                var response = _handleRequest(requestObj);
                // todo; handle response
                $log.info(response);
            };

            this.getCmsProfile = function(id) {
                if(_isIdValid(id)) {
                    var requestObj = {
                        url: $keystoneApi.url + 'Profile/' + id
                    };
                    var response = _handleRequest(requestObj);
                    // todo; handle response
                    $log.info(response);
                }
            };

            this.createCmsProfile = function(profileObject) {
                var requestObj = {
                    url: $keystoneApi.url + 'Profile/create',
                    data: profileObject
                };
                var response = _handleRequest(requestObj);
                // todo; handle response
                $log.info(response);
            };

            this.updateCmsProfile = function(profileObject) {
                if(_isIdValid(profileObject.id)) {
                    var requestObj = {
                        url: $keystoneApi.url + 'Profile/' + profileObject.id + '/update',
                        data: profileObject
                    };
                    var response = _handleRequest(requestObj);
                    // todo; handle response
                    $log.info(response);
                }
            };

            this.deleteCmsProfile = function(id) {
                if(_isIdValid(id)) {
                    var requestObj = {
                        url: $keystoneApi.url + 'Profile/' + id + '/remove'
                    };
                    var response = _handleRequest(requestObj);
                    // todo; handle response
                    $log.info(response);
                }
            };

            /**
             * Favourite Template
             */
            this.getCmsAllFavouriteTemplates = function() {
                var requestObj = {
                    url: $keystoneApi.url + 'FavouriteTemplate/'
                };
                var response = _handleRequest(requestObj);
                // todo; handle response
                $log.info(response);
            };

            this.getCmsFavouriteTemplate = function(id) {
                if(_isIdValid(id)) {
                    var requestObj = {
                        url: $keystoneApi.url + 'FavouriteTemplate/' + id
                    };
                    var response = _handleRequest(requestObj);
                    // todo; handle response
                    $log.info(response);
                }
            };

            this.createCmsFavouriteTemplate = function(favouriteTemplateObject) {
                var requestObj = {
                    url: $keystoneApi.url + 'FavouriteTemplate/create',
                    data: favouriteTemplateObject
                };
                var response = _handleRequest(requestObj);
                // todo; handle response
                $log.info(response);
            };

            this.updateCmsFavouriteTemplate = function(favouriteTemplateObject) {
                if(_isIdValid(favouriteTemplateObject.id)) {
                    var requestObj = {
                        url: $keystoneApi.url + 'FavouriteTemplate/' + favouriteTemplateObject.id + '/update',
                        data: favouriteTemplateObject
                    };
                    var response = _handleRequest(requestObj);
                    // todo; handle response
                    $log.info(response);
                }
            };

            this.deleteCmsFavouriteTemplate = function(id) {
                if(_isIdValid(id)) {
                    var requestObj = {
                        url: $keystoneApi.url + 'FavouriteTemplate/' + id + '/remove'
                    };
                    var response = _handleRequest(requestObj);
                    // todo; handle response
                    $log.info(response);
                }
            };

            /**
             * Customer Content
             */
            this.getCmsAllCustomerContent = function() {
                var requestObj = {
                    url: $keystoneApi.url + 'CustomerContent/'
                };
                var response = _handleRequest(requestObj);
                // todo; handle response
                $log.info(response);
            };

            this.getCmsCustomerContent = function(id) {
                if(_isIdValid(id)) {
                    var requestObj = {
                        url: $keystoneApi.url + 'CustomerContent/' + id
                    };
                    var response = _handleRequest(requestObj);
                    // todo; handle response
                    $log.info(response);
                }
            };

            /**
             * Frontpage Content
             */
            this.getCmsAllFrontpageContent = function() {
                var requestObj = {
                    url: $keystoneApi.url + 'FrontpageContent/'
                };
                var response = _handleRequest(requestObj);
                // todo; handle response
                $log.info(response);
            };

            this.getCmsFrontpageContent = function(id) {
                if(_isIdValid(id)) {
                    var requestObj = {
                        url: $keystoneApi.url + 'FrontpageContent/' + id
                    };
                    var response = _handleRequest(requestObj);
                    // todo; handle response
                    $log.info(response);
                }
            };

            /**
             * Faq
             */
            this.getCmsAllFaq = function() {
                var requestObj = {
                    url: $keystoneApi.url + 'Faq/'
                };
                var response = _handleRequest(requestObj);
                // todo; handle response
                $log.info(response);
            };

            /**
             * General Settings
             */
            this.getCmsAllGeneralSettings = function() {
                var requestObj = {
                    url: $keystoneApi.url + 'GeneralSettings/'
                };
                var response = _handleRequest(requestObj);
                // todo; handle response
                $log.info(response);
            };

            this.getCmsGeneralSettings = function(id) {
                if(_isIdValid(id)) {
                    var requestObj = {
                        url: $keystoneApi.url + 'GeneralSettings/' + id
                    };
                    var response = _handleRequest(requestObj);
                    // todo; handle response
                    $log.info(response);
                }
            };

            this.updateCmsGeneralSettings = function(favouriteTemplateObject) {
                if(_isIdValid(favouriteTemplateObject.id)) {
                    var requestObj = {
                        url: $keystoneApi.url + 'GeneralSettings/' + favouriteTemplateObject.id + '/update',
                        data: favouriteTemplateObject
                    };
                    var response = _handleRequest(requestObj);
                    // todo; handle response
                    $log.info(response);
                }
            };

            /**
             * Org Units
             */
            this.getCmsAllOrgUnits = function() {
                var requestObj = {
                    url: $keystoneApi.url + 'OrgUnit/'
                };
                var response = _handleRequest(requestObj);
                // todo; handle response
                $log.info(response);
            };

            this.getCmsOrgUnit = function(id) {
                if(_isIdValid(id)) {
                    var requestObj = {
                        url: $keystoneApi.url + 'OrgUnit/' + id
                    };
                    var response = _handleRequest(requestObj);
                    // todo; handle response
                    $log.info(response);
                }
            };
        }]);
})();
</code>```

Yes I know there is currently logic missing in my end-point methods but it is besides the point at the moment since none of these return anything but the same CORS error. I am also just using Basic Authorisation during the test phase this will be replaced by proper OAuth middleware so please refrain from commenting on that, it is also besides the point.

Any helpful insight is much appreciated.

答:
Well, that's the point of CORS, i.e. to make it possible to keep frontend and backend on separate servers.

In keystone.js:

```<code>keystone.set('cors allow origin', true);
keystone.set('cors allow methods', true);
keystone.set('cors allow headers', true);
</code>```

In routes\index.js: either:

```<code>app.get('/api/stuff', [keystone.middleware.api, keystone.middleware.cors], routes.api.workshop.getStuff);
</code>```

or:

```<code>app.get('/api/stuff', keystone.middleware.cors, routes.api.workshop.getStuff);
</code>```

and all the other routes accordingly. That's all that is necessary to enable CORS headers.

Title: Keystone JS CORS

Body:
Ok so I am pretty new to Keystone JS and I have decided to use it as an API backend for a project.

I have gotten all my API endpoints/routes are all done and they work perfectly in my browser however when trying to fetch the data remotely I keep getting the same error: XMLHttpRequest cannot load http://localhost:3000/keystone/api/. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost' is therefore not allowed access.

I am not unfamiliar with CORS and have tried to enable it by adding the following to my keystone.js and routes/index.js

keystone.js:

keystone.set('cors allow origin', true);
keystone.set('cors allow methods', true);
keystone.set('cors allow headers', true);

routes/index.js:

// Setup Route Bindings
exports = module.exports = function (app) {
    app.all('/api/*', keystone.middleware.cors);
    app.options('/api*', function(req, res) { res.send(200); });

    // Views
    app.get('/', routes.views.index);

    // API
    // Lists
    ...

Now I have tried finding solutions to this by looking through alot of documentation but according to my findings this should be more than enough to make CORS work with Keystone.

In addition to this I will present also my Keystone Service in my Angular JS 1.x frontend for you to see what I am trying to pull off..

keystone.service.js:

(function() {
    'use strict';

    angular.module('zApp')
        .service('KeystoneService', ['$log', '$http', function($log, $http) {
            var $keystoneApi = {};

            var _handleRequest = function(requestObj) {
                var data = {};

                if(requestObj.withCredentials === undefined) {
                    requestObj.withCredentials = true;
                }

                if(requestObj.method === undefined) {
                    requestObj.method = 'GET';
                }

                $http(requestObj, {headers: $keystoneApi.headers})
                    .then(
                        function success(response) {
                            data = response.data;
                        },
                        function error(response) {
                            // todo; handle error
                            $log.info(response);
                        }
                    );
                return data;
            };

            var _isIdValid = function(id) {
                if(/^[a-zA-Z0-9]*$/.test(id)) {
                    return true;
                }
                return false;
            };

            // Should be changed to oauth when there is better support in Keystone!
            this.init = function(settings) {
                if(settings.url !== undefined && settings.usr !== undefined && settings.pass !== undefined) {
                    $keystoneApi = settings;
                    $keystoneApi.auth = window.btoa($keystoneApi.usr + ':' + $keystoneApi.pass);
                    $keystoneApi.headers = {"Authorization": "Basic " + $keystoneApi.auth};
                    return this;
                }
                return false;
            }

            /**
             * User
             */
            this.getCmsAllUsers = function() {
                var requestObj = {
                    url: $keystoneApi.url + 'User/'
                };
                var response = _handleRequest(requestObj);
                // todo; handle response
                $log.info(response);
            };

            this.getCmsUser = function(id) {
                if(_isIdValid(id)) {
                    var requestObj = {
                        url: $keystoneApi.url + 'User/' + id
                    };

                    var response = _handleRequest(requestObj);
                    // todo; handle response
                    $log.info(response);
                }
            };

            this.updateCmsUser = function(userObject) {
                if(_isIdValid(userObject.id)) {
                    var requestObj = {
                        url: $keystoneApi.url + 'User/' + id + '/update/',
                        data: userObject
                    };

                    var response = _handleRequest(requestObj);
                    // todo; handle response
                    $log.info(response);
                }
            };

            /**
             * Profile
             */
            this.getCmsAllProfiles = function() {
                var requestObj = {
                    url: $keystoneApi.url + 'Profile/'
                };
                var response = _handleRequest(requestObj);
                // todo; handle response
                $log.info(response);
            };

            this.getCmsProfile = function(id) {
                if(_isIdValid(id)) {
                    var requestObj = {
                        url: $keystoneApi.url + 'Profile/' + id
                    };
                    var response = _handleRequest(requestObj);
                    // todo; handle response
                    $log.info(response);
                }
            };

            this.createCmsProfile = function(profileObject) {
                var requestObj = {
                    url: $keystoneApi.url + 'Profile/create',
                    data: profileObject
                };
                var response = _handleRequest(requestObj);
                // todo; handle response
                $log.info(response);
            };

            this.updateCmsProfile = function(profileObject) {
                if(_isIdValid(profileObject.id)) {
                    var requestObj = {
                        url: $keystoneApi.url + 'Profile/' + profileObject.id + '/update',
                        data: profileObject
                    };
                    var response = _handleRequest(requestObj);
                    // todo; handle response
                    $log.info(response);
                }
            };

            this.deleteCmsProfile = function(id) {
                if(_isIdValid(id)) {
                    var requestObj = {
                        url: $keystoneApi.url + 'Profile/' + id + '/remove'
                    };
                    var response = _handleRequest(requestObj);
                    // todo; handle response
                    $log.info(response);
                }
            };

            /**
             * Favourite Template
             */
            this.getCmsAllFavouriteTemplates = function() {
                var requestObj = {
                    url: $keystoneApi.url + 'FavouriteTemplate/'
                };
                var response = _handleRequest(requestObj);
                // todo; handle response
                $log.info(response);
            };

            this.getCmsFavouriteTemplate = function(id) {
                if(_isIdValid(id)) {
                    var requestObj = {
                        url: $keystoneApi.url + 'FavouriteTemplate/' + id
                    };
                    var response = _handleRequest(requestObj);
                    // todo; handle response
                    $log.info(response);
                }
            };

            this.createCmsFavouriteTemplate = function(favouriteTemplateObject) {
                var requestObj = {
                    url: $keystoneApi.url + 'FavouriteTemplate/create',
                    data: favouriteTemplateObject
                };
                var response = _handleRequest(requestObj);
                // todo; handle response
                $log.info(response);
            };

            this.updateCmsFavouriteTemplate = function(favouriteTemplateObject) {
                if(_isIdValid(favouriteTemplateObject.id)) {
                    var requestObj = {
                        url: $keystoneApi.url + 'FavouriteTemplate/' + favouriteTemplateObject.id + '/update',
                        data: favouriteTemplateObject
                    };
                    var response = _handleRequest(requestObj);
                    // todo; handle response
                    $log.info(response);
                }
            };

            this.deleteCmsFavouriteTemplate = function(id) {
                if(_isIdValid(id)) {
                    var requestObj = {
                        url: $keystoneApi.url + 'FavouriteTemplate/' + id + '/remove'
                    };
                    var response = _handleRequest(requestObj);
                    // todo; handle response
                    $log.info(response);
                }
            };

            /**
             * Customer Content
             */
            this.getCmsAllCustomerContent = function() {
                var requestObj = {
                    url: $keystoneApi.url + 'CustomerContent/'
                };
                var response = _handleRequest(requestObj);
                // todo; handle response
                $log.info(response);
            };

            this.getCmsCustomerContent = function(id) {
                if(_isIdValid(id)) {
                    var requestObj = {
                        url: $keystoneApi.url + 'CustomerContent/' + id
                    };
                    var response = _handleRequest(requestObj);
                    // todo; handle response
                    $log.info(response);
                }
            };

            /**
             * Frontpage Content
             */
            this.getCmsAllFrontpageContent = function() {
                var requestObj = {
                    url: $keystoneApi.url + 'FrontpageContent/'
                };
                var response = _handleRequest(requestObj);
                // todo; handle response
                $log.info(response);
            };

            this.getCmsFrontpageContent = function(id) {
                if(_isIdValid(id)) {
                    var requestObj = {
                        url: $keystoneApi.url + 'FrontpageContent/' + id
                    };
                    var response = _handleRequest(requestObj);
                    // todo; handle response
                    $log.info(response);
                }
            };

            /**
             * Faq
             */
            this.getCmsAllFaq = function() {
                var requestObj = {
                    url: $keystoneApi.url + 'Faq/'
                };
                var response = _handleRequest(requestObj);
                // todo; handle response
                $log.info(response);
            };

            /**
             * General Settings
             */
            this.getCmsAllGeneralSettings = function() {
                var requestObj = {
                    url: $keystoneApi.url + 'GeneralSettings/'
                };
                var response = _handleRequest(requestObj);
                // todo; handle response
                $log.info(response);
            };

            this.getCmsGeneralSettings = function(id) {
                if(_isIdValid(id)) {
                    var requestObj = {
                        url: $keystoneApi.url + 'GeneralSettings/' + id
                    };
                    var response = _handleRequest(requestObj);
                    // todo; handle response
                    $log.info(response);
                }
            };

            this.updateCmsGeneralSettings = function(favouriteTemplateObject) {
                if(_isIdValid(favouriteTemplateObject.id)) {
                    var requestObj = {
                        url: $keystoneApi.url + 'GeneralSettings/' + favouriteTemplateObject.id + '/update',
                        data: favouriteTemplateObject
                    };
                    var response = _handleRequest(requestObj);
                    // todo; handle response
                    $log.info(response);
                }
            };

            /**
             * Org Units
             */
            this.getCmsAllOrgUnits = function() {
                var requestObj = {
                    url: $keystoneApi.url + 'OrgUnit/'
                };
                var response = _handleRequest(requestObj);
                // todo; handle response
                $log.info(response);
            };

            this.getCmsOrgUnit = function(id) {
                if(_isIdValid(id)) {
                    var requestObj = {
                        url: $keystoneApi.url + 'OrgUnit/' + id
                    };
                    var response = _handleRequest(requestObj);
                    // todo; handle response
                    $log.info(response);
                }
            };
        }]);
})();

Yes I know there is currently logic missing in my end-point methods but it is besides the point at the moment since none of these return anything but the same CORS error. I am also just using Basic Authorisation during the test phase this will be replaced by proper OAuth middleware so please refrain from commenting on that, it is also besides the point.

Any helpful insight is much appreciated.

Body:
Well, that's the point of CORS, i.e. to make it possible to keep frontend and backend on separate servers.

In keystone.js:

keystone.set('cors allow origin', true);
keystone.set('cors allow methods', true);
keystone.set('cors allow headers', true);

In routes\index.js: either:

app.get('/api/stuff', [keystone.middleware.api, keystone.middleware.cors], routes.api.workshop.getStuff);

or:

app.get('/api/stuff', keystone.middleware.cors, routes.api.workshop.getStuff);

and all the other routes accordingly. That's all that is necessary to enable CORS headers.


问:
Add css to 1 page using scss and ReactJS and redux
I am using ReactJS with redux.
I using scss.
lets say my path is:
http://localhost:3000/login
I need to add to this page:
html:{ overflow:hidden}

and on other pages i want to remove this attribute.

Anyone have a clue?

答:
You could just import a className, let's say loginStyle, and make it so:

html: {
    overflow: hidden;
}

Then, you just put it as a condition let's say on your header (has to be an element present in every page).

Something like

const isLogin = window.location.pathname === login ? true : false ( <= this is not the real condition, but make it so isLogin equals true is you are on your login page).

<Header className={${className1} ${className2} ${isLogin ? loginStyle : ' '}}/>

And your style will only be applied on your login page. Maybe not the simpliest, but at least this would work :)


答:
Yes you can do by passing variable to a function and generate a new array,

var myApp=angular.module('myApp',[]);

myApp.controller('thecontroller',function($scope){
$scope.getNumber = function(num) {
    return new Array(num);
}
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html>
    <head>
        <title>ng-Messages Service</title>
        <script src='https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js'></script>
        <script src='https://code.angularjs.org/1.5.0-rc.0/angular.min.js'></script>
    </head>
    <body ng-app="myApp">

        <div ng-controller='thecontroller'>
    <ul>
    <li ng-repeat="i in getNumber(20) track by $index"><span>{{$index+1}}</span></li>
</ul>
        </div>
    </body>
</html></code>```

Title: how to run ng-repeat by hardcoding value instead of passing array

Body:
Yes you can do by passing variable to a function and generate a new array,

var myApp=angular.module('myApp',[]);

myApp.controller('thecontroller',function($scope){
$scope.getNumber = function(num) {
    return new Array(num);
}
});

<!DOCTYPE html>
<html>
    <head>
        <title>ng-Messages Service</title>
        <script src='https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js'></script>
        <script src='https://code.angularjs.org/1.5.0-rc.0/angular.min.js'></script>
    </head>
    <body ng-app="myApp">

        <div ng-controller='thecontroller'>
    <ul>
    <li ng-repeat="i in getNumber(20) track by $index"><span>{{$index+1}}</span></li>
</ul>
        </div>
    </body>
</html>


问:
Odoo - Sales Order - Tranfer is not generating accouting entries
I have a problem: After doing a transfer(screenshot: click on Apply) there is no accounting entries generated (in Journal entry) despite the configuration made for auto-generate accounting entries and configuring product category as well:

Settings -> Warehouse -> Accounting

Product categories-> Account properties

Question: where is the function that triggers the generation of accounting lines? or any other suggestions

10x

答:
The problem was in my configuration of the transfer (stock.move object), when the source location is a type view => no accounting entries are generated, otherwise if the source location type is "internal location" then the accounting entries are created successfully.

How to see the source location type of the transfer:

Sales orders->go to your order->click on "view delivery order"-> under "Stock Moves" -> click on a specific line

Locations -> Source Location -> Location Type:

source location type "View" --> won't generate accounting entries

source location type "Internal Location" --> generate normally accounting entries


问:
Jqgrid Pagination
Pagination is not working. Here is my code for the grid</p>

```<code>$('#tblGridId').jqGrid({
        url: 'JHandler/PakedOpening.ashx',
        datatype: 'json',
        mtype:'Get',
    colNames: ['Item Send', 'Use Lot No.', 'Packing Type', 'Design No.', 'Bundle', 'Thaan', 'Quantity', 'Action'],
    colModel: [
        { name: 'ITEMSEND', width: 150, sortable: true },
        { name: 'LOTNO.', width: 70, sortable: true },
        { name: 'PACKINGTYPE', width: 70, sortable: true },
        { name: 'DESIGNNO.', width: 70, sortable: true },
        { name: 'BUNDLE', width: 70, sortable: true },
        { name: 'THAAN', width: 70, sortable: true },
        { name: 'QUANTITY', width: 70, sortable: true },
    //    { name: 'WAREHOUSE', width: 100, sortable: true },
        { name: 'ACTION', width: 50, sortable: false },
    ],
    height: 'auto',
    autowidth: 'auto',
    rownum: 20,
    LoadOnce: true,
    rowList: [50, 100, 200, 400],
    pager: 'tblGridPager',
    sortName: 'ItemSend',
    viewrecords: true,
    sortorder: 'asc',
    caption: 'Opening',
    emptyrecords: 'No Records To Display',
    jsonreader: {
        repeatitems: false,
        Id:'0',
    },
    multiselect: false
});

$('#tblGridId').jqGrid('navGrid', '#tblGridPager', { edit: false, add: false, del: false, paging:true, search: false });
</code>```

<p>`  </p>

答:
Here you go with the solution http://jsfiddle.net/QEzhr/1435/</p>

```<code>    <table id="tblGridId" > </table> <div id="tblGridPager" style="text-align:center" > </div>
</code>```

Title: Jqgrid Pagination

Body:
Pagination is not working. Here is my code for the grid

$('#tblGridId').jqGrid({
        url: 'JHandler/PakedOpening.ashx',
        datatype: 'json',
        mtype:'Get',
    colNames: ['Item Send', 'Use Lot No.', 'Packing Type', 'Design No.', 'Bundle', 'Thaan', 'Quantity', 'Action'],
    colModel: [
        { name: 'ITEMSEND', width: 150, sortable: true },
        { name: 'LOTNO.', width: 70, sortable: true },
        { name: 'PACKINGTYPE', width: 70, sortable: true },
        { name: 'DESIGNNO.', width: 70, sortable: true },
        { name: 'BUNDLE', width: 70, sortable: true },
        { name: 'THAAN', width: 70, sortable: true },
        { name: 'QUANTITY', width: 70, sortable: true },
    //    { name: 'WAREHOUSE', width: 100, sortable: true },
        { name: 'ACTION', width: 50, sortable: false },
    ],
    height: 'auto',
    autowidth: 'auto',
    rownum: 20,
    LoadOnce: true,
    rowList: [50, 100, 200, 400],
    pager: 'tblGridPager',
    sortName: 'ItemSend',
    viewrecords: true,
    sortorder: 'asc',
    caption: 'Opening',
    emptyrecords: 'No Records To Display',
    jsonreader: {
        repeatitems: false,
        Id:'0',
    },
    multiselect: false
});

$('#tblGridId').jqGrid('navGrid', '#tblGridPager', { edit: false, add: false, del: false, paging:true, search: false });

`

Body:
Here you go with the solution http://jsfiddle.net/QEzhr/1435/

    <table id="tblGridId" > </table> <div id="tblGridPager" style="text-align:center" > </div>


问:
How to update an observable array inside a component from the main ViewModel?
I need to set from the main viewmodel a property inside an observable array.

I'm using the classic pre to debug and display the content of my observable array.
By using types.valueHasMutated() I can see the applied changes - just only to vm.types (which wouldn't be the case otherwise).

However, I need to see this changes reflected inside my component.

In my example, when I ckick "Apples", the corresponding input shall be disabled like the one below. Sadly, this is actually not the case.

What I'm doing wrong?

ko.components.register("available-items", {
  viewModel: function(params) {
    function AvailableItems(params) {
      var self = this;
      self.params = params;
      self.location = "A";
      self.types = ko.computed(function() {
        var types = self.params.types();
        return ko.utils.arrayFilter(types, function(item) {
          return item.location == self.location;
        });
      });
      self.addItem = function(data, event) {
        self.params.items.addItem(self.location, data.type);
      };
    }
    return new AvailableItems(params);
  },
  template: '
' +
    '
Add item
' +
    '
' +
    '
' +
    '<input type="text" data-bind="value: type, enable:available, event: {click: $parent.addItem}" readonly/>' +
    '
' +
    '
' +
    '
',
  synchronous: true
});

var types = [{
  type: "Apples",
  location: "A",
  available: true
}, {
  type: "Bananas",
  location: "A",
  available: false
}];

function Vm(data) {
  var self = this;
  self.items = ko.observableArray();
  self.types = ko.observableArray(ko.utils.arrayMap(data, function(item) {
    return item;
  }));
  self.items.addItem = function(location, type) {
    self.items.push({
      location: location,
      type: type
    });
    if (location == "A" && type == "Apples") {
      self.types()[0].available = false;
      self.types.valueHasMutated();
    }
  };
}

ko.options.deferUpdates = true;
var vm = new Vm(types);
ko.applyBindings(vm);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>pre {
  position: absolute;
  width: 300px;
  right: 0;
  top: 0;
}</code>```

<!DOCTYPE html>

 -

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

答:
I have run this on jfiddle and even when I added a new type, I wasn't getting any update.

It seems like there was an issue with the

```<code>'<ul data-bind="foreach: types">' +
</code>```

I changed it to

'
' +

https://jsfiddle.net/fabwoofer/9szbqhj7/1/

Now the type gets added but it seems like the re-rendering of the first item is not handled. People with similar problems have suggested using template rendering as described here

Knockout.js Templates Foreach - force complete re-render

Hope this helps

Body:
I need to set from the main viewmodel a property inside an observable array.

I'm using the classic pre to debug and display the content of my observable array.
By using types.valueHasMutated() I can see the applied changes - just only to vm.types (which wouldn't be the case otherwise).

However, I need to see this changes reflected inside my component.

In my example, when I ckick "Apples", the corresponding input shall be disabled like the one below. Sadly, this is actually not the case.

What I'm doing wrong?

ko.components.register("available-items", {
  viewModel: function(params) {
    function AvailableItems(params) {
      var self = this;
      self.params = params;
      self.location = "A";
      self.types = ko.computed(function() {
        var types = self.params.types();
        return ko.utils.arrayFilter(types, function(item) {
          return item.location == self.location;
        });
      });
      self.addItem = function(data, event) {
        self.params.items.addItem(self.location, data.type);
      };
    }
    return new AvailableItems(params);
  },
  template: '
' +
    '
Add item
' +
    '
' +
    '
' +
    '<input type="text" data-bind="value: type, enable:available, event: {click: $parent.addItem}" readonly/>' +
    '
' +
    '
' +
    '
',
  synchronous: true
});

var types = [{
  type: "Apples",
  location: "A",
  available: true
}, {
  type: "Bananas",
  location: "A",
  available: false
}];

function Vm(data) {
  var self = this;
  self.items = ko.observableArray();
  self.types = ko.observableArray(ko.utils.arrayMap(data, function(item) {
    return item;
  }));
  self.items.addItem = function(location, type) {
    self.items.push({
      location: location,
      type: type
    });
    if (location == "A" && type == "Apples") {
      self.types()[0].available = false;
      self.types.valueHasMutated();
    }
  };
}

ko.options.deferUpdates = true;
var vm = new Vm(types);
ko.applyBindings(vm);

pre {
  position: absolute;
  width: 300px;
  right: 0;
  top: 0;
}

<!DOCTYPE html>

 -

Body:
I have run this on jfiddle and even when I added a new type, I wasn't getting any update.

It seems like there was an issue with the

'<ul data-bind="foreach: types">' +

I changed it to

'<ul data-bind="foreach: $root.types">' +

https://jsfiddle.net/fabwoofer/9szbqhj7/1/

Now the type gets added but it seems like the re-rendering of the first item is not handled. People with similar problems have suggested using template rendering as described here

Knockout.js Templates Foreach - force complete re-render

Hope this helps


问:
Seam component init method after request parameters are set
I'm using an event-scope component as a view controller. I need to have an "init" method on that controller, where I can do authorization checks, load some entities from JPA, etc.

Problem is, if I choose to do that in a @Create method, parameters defined in page.xml are not yet set (via GET). @RequestParameter fields get set, but they are less flexible - can't use them in inner classes of the component, or just somewhere deeper down in a bean path. For example, I can direct name=abc to #{controller.user.name}, but can only use a component-level setter with @RequestParameter.

Is there another way to do an "init" method, where all request parameters are set, then?

答:
maybe u can try this in u page.xml</p>

```<code><param name="xxx" value="#{component.xxx}"/>
<action execute="#{component.init}"/>
</code>```

Body:
maybe u can try this in u page.xml

<param name="xxx" value="#{component.xxx}"/>
<action execute="#{component.init}"/>


问:
Output redirect of nested script not working with cron
So, I have this shell script, that dynamically builds another script and calls it (i.e. a nested script).

Something like this, let's say it is called the_script.sh:

```<code>#!/bin/sh

# do some stuff here, and create another script
./nested_script.sh

# do some other stuff, end
</code>```

If I just call ./the_script.sh it outputs everything to STDOUT, including the nested script's output.

But if it runs from a cronjob, like so:

```<code>0 8,12 * * 1-5 /home/myuser/the_script.sh >> /home/myuser/thescript.log
</code>```

Then it does not output the nested script's result, which is very important for me. The result of both script is correct however it is run (from the prompt or cron), and it runs as expected.

Any clues on why this happens and how to prevent it?

答:
To display error in log adding 2>&1

```<code>0 8,12 * * 1-5 /home/myuser/the_script.sh >> /home/myuser/thescript.log 2>&1
</code>```

Then it will display something like : No such file or directory, this is because current working directory is not the shell's directory. The cleanest is to use absolute path, otherwise cd -- "$(dirname "${0:-.}")"

Body:
So, I have this shell script, that dynamically builds another script and calls it (i.e. a nested script).

Something like this, let's say it is called the_script.sh:

#!/bin/sh

# do some stuff here, and create another script
./nested_script.sh

# do some other stuff, end

If I just call ./the_script.sh it outputs everything to STDOUT, including the nested script's output.

But if it runs from a cronjob, like so:

0 8,12 * * 1-5 /home/myuser/the_script.sh >> /home/myuser/thescript.log

Then it does not output the nested script's result, which is very important for me. The result of both script is correct however it is run (from the prompt or cron), and it runs as expected.

Any clues on why this happens and how to prevent it?

Body:
To display error in log adding 2>&1

0 8,12 * * 1-5 /home/myuser/the_script.sh >> /home/myuser/thescript.log 2>&1

Then it will display something like : No such file or directory, this is because current working directory is not the shell's directory. The cleanest is to use absolute path, otherwise cd -- "$(dirname "${0:-.}")"


问:
get the file path with Python on Windows error
I want to load the file path with Python,on my Windows.
but now there is a problem:
the code:

```<code>def Test2(rootDir):
    f = []
    for lists in os.listdir(rootDir):
        path = os.path.join(rootDir, lists)
        #print (path)
        #img = cv2.imread(path,0)
        #cv2.imshow("image",img)
        if os.path.isdir(path):
            Test2(path)
        if os.path.isfile(path):
            print (path)
</code>```

Test2("D:/111test/picpic")

and the consequence is :

```<code>D:/111test/picpic\haha1\111.png
</code>```

the consequence is not I want,because it contains '/'&'\'.
How to resolve this problem?

Anothor problem:
I got the file path successfully by using Test2("D:\111test\picpic");

```<code>D:\111test\picpic\haha1\111.png
</code>```

and now I want to replace these filepath into a list,the code I use:

```<code>if os.path.isfile(path):
        print (path)
        f.append(path)
        print(f)
</code>```

and the consequence is what I don't want:

```<code>['D:\\111test\\picpic\\haha1\\111.png',
 'D:\\111test\\picpic\\haha1\\222.png']
</code>```

because the filepath of the list contains double"\".What should I do?

My wish:get the filepaths,and place them in a list correctly.
I am appraiciate for your method!!!

I'm glad for your answer!

答:
You should switch to using pathlib when you're dealing with Windows paths. If you're on Python 2, it's available as a package too.

To give you an example how to use the pathlib library:

```<code>def Test2(rootDir):
    f = []
    rootDir = pathlib.Path(rootDir)
    for iter_file in rootDir.iterdir():
        if iter_file.is_dir():
            Test2(iter_file)
        if iter_file.is_file():
            print(iter_file)
</code>```

Body:
I want to load the file path with Python,on my Windows.
but now there is a problem:
the code:

def Test2(rootDir):
    f = []
    for lists in os.listdir(rootDir):
        path = os.path.join(rootDir, lists)
        #print (path)
        #img = cv2.imread(path,0)
        #cv2.imshow("image",img)
        if os.path.isdir(path):
            Test2(path)
        if os.path.isfile(path):
            print (path)

Test2("D:/111test/picpic")

and the consequence is :

D:/111test/picpic\haha1\111.png

the consequence is not I want,because it contains '/'&'\'.
How to resolve this problem?

Anothor problem:
I got the file path successfully by using Test2("D:\111test\picpic");

D:\111test\picpic\haha1\111.png

and now I want to replace these filepath into a list,the code I use:

if os.path.isfile(path):
        print (path)
        f.append(path)
        print(f)

and the consequence is what I don't want:

['D:\\111test\\picpic\\haha1\\111.png',
 'D:\\111test\\picpic\\haha1\\222.png']

because the filepath of the list contains double"\".What should I do?

My wish:get the filepaths,and place them in a list correctly.
I am appraiciate for your method!!!

I'm glad for your answer!

Body:
You should switch to using pathlib when you're dealing with Windows paths. If you're on Python 2, it's available as a package too.

To give you an example how to use the pathlib library:

def Test2(rootDir):
    f = []
    rootDir = pathlib.Path(rootDir)
    for iter_file in rootDir.iterdir():
        if iter_file.is_dir():
            Test2(iter_file)
        if iter_file.is_file():
            print(iter_file)


问:
Liquid shorthands?
Are there any liquid shorthands? For example I'm trying to express this in a more concise way:</p>

```<code>{% if job.offsite %}}
  {{job.offsite}}
{{% else %}}
  {{ job.url }}
{% endif %}
</code>```

答:
For this particular example, you could write:

```<code>{{ job.offsite | default: job.url }}
</code>```

The value provided to the default filter will be used if the left side of the expression is false or nil.

Title: Liquid shorthands?

Body:
Are there any liquid shorthands? For example I'm trying to express this in a more concise way:

{% if job.offsite %}}
  {{job.offsite}}
{{% else %}}
  {{ job.url }}
{% endif %}

Body:
For this particular example, you could write:

{{ job.offsite | default: job.url }}

The value provided to the default filter will be used if the left side of the expression is false or nil.


问:
Sort by month in linq and EF
I have a linq query and inside of it is the month name. I want the results sorted by the month (Jan, Feb, Mar, ...).

Currently I have the below but it's giving me and error:

LINQ to Entities does not recognize the method 'System.DateTime
  Parse(System.String)' method, and this method cannot be translated
  into a store expression.

```<code>var shockValues = (from s in ctx.Shocks
                               where s.ID == id
                               orderby DateTime.Parse(s.MonthName)
                               select new
                               {
                                   val = s.MonthName + "=" + s.ShockValue
                               });
</code>```

答:
The best way and easiest way is create a stored procedure </p>

```<code>Create procedure sortevents
   as
 SELECT *
        FROM [SAGMJ].[dbo].[Events]
        ORDER BY CASE
                 WHEN MONTH([StartAt]) = MONTH(GETDATE())
                    AND YEAR([StartAt])  = YEAR(GETDATE()) THEN 0
                   ELSE 1
                 END, [StartAt];
</code>```

<p>//Next call your sp</p>

```<code>var v = (dc.sortevents()).ToList();
</code>```

Title: Sort by month in linq and EF

Body:
I have a linq query and inside of it is the month name. I want the results sorted by the month (Jan, Feb, Mar, ...).

Currently I have the below but it's giving me and error:

LINQ to Entities does not recognize the method 'System.DateTime
  Parse(System.String)' method, and this method cannot be translated
  into a store expression.

var shockValues = (from s in ctx.Shocks
                               where s.ID == id
                               orderby DateTime.Parse(s.MonthName)
                               select new
                               {
                                   val = s.MonthName + "=" + s.ShockValue
                               });

Body:
The best way and easiest way is create a stored procedure

Create procedure sortevents
   as
 SELECT *
        FROM [SAGMJ].[dbo].[Events]
        ORDER BY CASE
                 WHEN MONTH([StartAt]) = MONTH(GETDATE())
                    AND YEAR([StartAt])  = YEAR(GETDATE()) THEN 0
                   ELSE 1
                 END, [StartAt];

//Next call your sp

var v = (dc.sortevents()).ToList();