问:
Looping a component in another component Vue.js
The question here is how can I get this Task.vue file to loop in my tasklist.vue file knowing I'm willing to pass a json file so I can get the list of all the task to do.

Task.vue

```<code><template>
    <table :id="id" class="task_box">
        <tr>
            <td class="task_user">{{name}}</td>
            <td class="task_date">{{date}}</td>
            <td class="task_time">{{time}}</td>
        </tr>
        <tr>
            <td colspan="3" class="task_description">
                <div class="toto">{{description}}</div>
            </td>
        </tr>
    </table>
</template>

<script>
export default {
  name: "task",
  data() {
    return {
      id: 1,
      name: "Test",
      date: new Date(),
      time: "9:30 ",
      description: "whatever"
    };
  }
};
</script>
</code>```

So this task.vue is meant to be a container that I can use in the tasklist.vue.

tasklist.vue

```<code><template>
    <div>
        <task v-for="task in tasks" :key="task.id"></task>
    </div>
</template>

<script>
import Task from "./Task.vue";

export default {
  name: "tasklist",
  data() {
    return {
      tasks: []
    };
  },
  components: {
    Task
  }
};
</script>
</code>```

答:
You need to use Properties to pass your task from your task list to your task.  Code is untested.

#Task

```<code><template>
    <table :id="task.id" class="task_box">
        <tr>
            <td class="task_user">{{task.name}}</td>
            <td class="task_date">{{task.date}}</td>
            <td class="task_time">{{task.time}}</td>
        </tr>
        <tr>
            <td colspan="3" class="task_description">
                <div class="toto">{{description}}</div>
            </td>
        </tr>
    </table>
</template>

<script>
export default {
  name: "task",
  props: ["task"],
};
</script>
</code>```

#TaskList

```<code><template>
    <div>
        <task v-for="task in tasks" :task="task" :key="task.id"></task>
    </div>
</template>

<script>
import Task from "./Task.vue";

export default {
  name: "tasklist",
  data() {
    return {
      tasks: [{
                 id: 1,
                 name: "Test",
                 date: new Date(),
                 time: "9:30 ",
                 description: "whatever"
      }]
    };
  },
  components: {
    Task
  }
};
</script>
</code>```

Body:
The question here is how can I get this Task.vue file to loop in my tasklist.vue file knowing I'm willing to pass a json file so I can get the list of all the task to do.

Task.vue

<template>

            {{name}}
            {{date}}
            {{time}}

{{description}}

</template>

So this task.vue is meant to be a container that I can use in the tasklist.vue.

tasklist.vue

<template>

        <task v-for="task in tasks" :key="task.id"></task>

</template>

Body:
You need to use Properties to pass your task from your task list to your task.  Code is untested.

#Task

<template>
    <table :id="task.id" class="task_box">
        <tr>
            <td class="task_user">{{task.name}}</td>
            <td class="task_date">{{task.date}}</td>
            <td class="task_time">{{task.time}}</td>
        </tr>
        <tr>
            <td colspan="3" class="task_description">
                <div class="toto">{{description}}</div>
            </td>
        </tr>
    </table>
</template>

<script>
export default {
  name: "task",
  props: ["task"],
};
</script>

#TaskList

<template>
    <div>
        <task v-for="task in tasks" :task="task" :key="task.id"></task>
    </div>
</template>

<script>
import Task from "./Task.vue";

export default {
  name: "tasklist",
  data() {
    return {
      tasks: [{
                 id: 1,
                 name: "Test",
                 date: new Date(),
                 time: "9:30 ",
                 description: "whatever"
      }]
    };
  },
  components: {
    Task
  }
};
</script>

ContentLicense: CC BY-SA 4.0


来源: stackexchange

问:
I need some help here with SQL Sum function group by dates and group
I have a table called Table1

```
CaseNumber | Year  | Month | Group    | HoursAttended
1          | 2010  |   1   |   16-20  |  8
2          | 2010  |   1   |   16-20  |  1
3          | 2010  |   2   |    0-5   |  2
4          | 2009  |   4   |    0-5   |  2
4          | 2009  |   4   |  16-20   |  5
```

If I wanted to have a result like this

```
Year | Month |GroupHours| GroupHourTotal
2010 | 1     |16-20     | 9
2010 | 3     |2         | 2
2009 | 4     |0-5       | 2
2009 | 4     |16-20     | 5
```

I tried this but I am getting incorrect results when the dates are not in the same month.
Any ideas?

```select Year,Month,group,hourattended,sum(hourattended)
from Table1
groupby Year,Month,hourattended,sum(hourattended)
order by year desc
```

答:
Don't group by hourattended

```<code>select Year,Month,group,sum(hourattended) grouphourtotal
from Table1
group by Year,Month,group
order by year desc, month desc
</code>```

This must be pseudo, otherwise quote the "group" column name as required

ContentLicense: CC BY-SA 2.5

Body:
I have a table called Table1

CaseNumber | Year  | Month | Group    | HoursAttended
1          | 2010  |   1   |   16-20  |  8
2          | 2010  |   1   |   16-20  |  1
3          | 2010  |   2   |    0-5   |  2
4          | 2009  |   4   |    0-5   |  2
4          | 2009  |   4   |  16-20   |  5

If I wanted to have a result like this

Year | Month |GroupHours| GroupHourTotal
2010 | 1     |16-20     | 9
2010 | 3     |2         | 2
2009 | 4     |0-5       | 2
2009 | 4     |16-20     | 5

I tried this but I am getting incorrect results when the dates are not in the same month.
Any ideas?

select Year,Month,group,hourattended,sum(hourattended)
from Table1
groupby Year,Month,hourattended,sum(hourattended)
order by year desc

Body:
Don't group by hourattended

select Year,Month,group,sum(hourattended) grouphourtotal
from Table1
group by Year,Month,group
order by year desc, month desc

This must be pseudo, otherwise quote the "group" column name as required


问:
dplyr() grouping and getting counts - error message Evaluation error: no applicable method for 'summarise_' applied to an object of class "logical"
I've got a data frame (df) with two variables, location and weather.

I'd like a  wide data frame (dfgoal), in which the data is grouped by location and in which there are three new variables (weather_1 to weather_3) with counts for the observations in the original weather variable.

The problem's that when I try to use dplyr()::mutate() I only get TRUE/FALSE output rather than counts, alternatively an error message: Evaluation error: no applicable method for 'summarise_' applied to an object of class "logical".

Any help would be much appreciated.

Starting point (df):

```<code>df <- data.frame(location=c("az","az","az","az","bi","bi","bi","ca","ca","ca","ca","ca"),weather=c(1,1,2,3,2,3,2,1,2,3,1,2))
</code>```

Desired outcome (df):

```<code>dfgoal <- data.frame(location=c("az","bi","ca"),weather_1=c(2,0,2),weather_2=c(1,2,2),weather_3=c(1,1,1))
</code>```

Current code:

```<code>library(dplyr)
df %>% group_by(location)  %>% mutate(weather_1 = (weather == 1)) %>% mutate(weather_2 = (weather == 2)) %>% mutate(weather_3 = (weather == 3))
df %>% group_by(location)  %>% mutate(weather_1 = summarise(weather == 1)) %>% mutate(weather_2 = summarise(weather == 2)) %>% mutate(weather_3 = summarise(weather == 3))
</code>```

答:
It is super simple with function called table:

```<code>df %>% table

        weather
location 1 2 3
      az 2 1 1
      bi 0 2 1
      ca 2 2 1
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I've got a data frame (df) with two variables, location and weather.

I'd like a  wide data frame (dfgoal), in which the data is grouped by location and in which there are three new variables (weather_1 to weather_3) with counts for the observations in the original weather variable.

The problem's that when I try to use dplyr()::mutate() I only get TRUE/FALSE output rather than counts, alternatively an error message: Evaluation error: no applicable method for 'summarise_' applied to an object of class "logical".

Any help would be much appreciated.

Starting point (df):

df <- data.frame(location=c("az","az","az","az","bi","bi","bi","ca","ca","ca","ca","ca"),weather=c(1,1,2,3,2,3,2,1,2,3,1,2))

Desired outcome (df):

dfgoal <- data.frame(location=c("az","bi","ca"),weather_1=c(2,0,2),weather_2=c(1,2,2),weather_3=c(1,1,1))

Current code:

library(dplyr)
df %>% group_by(location)  %>% mutate(weather_1 = (weather == 1)) %>% mutate(weather_2 = (weather == 2)) %>% mutate(weather_3 = (weather == 3))
df %>% group_by(location)  %>% mutate(weather_1 = summarise(weather == 1)) %>% mutate(weather_2 = summarise(weather == 2)) %>% mutate(weather_3 = summarise(weather == 3))

Body:
It is super simple with function called table:

df %>% table

        weather
location 1 2 3
      az 2 1 1
      bi 0 2 1
      ca 2 2 1


问:
Remove status bar and keep resize icon in tinymce 4
I am trying to remove the status bar and keep the resize icon in tinymce just like a normal text area resizer. Any idea ?</p>

答:
Unfortunately, there is no way to do it via component settings. But you can try and change css:

```<code>your-tiny-mce-textarea .mce-path.mce-flow-layout-item {
    display: none !important;
}
</code>```

UPD: This one seems more pretty:

```<code>your-tiny-mce-textarea.mce-statusbar {
    border: 0 !important;
}
your-tiny-mce-textarea.mce-path {
    display: none !important;
}
</code>```

Body:
Unfortunately, there is no way to do it via component settings. But you can try and change css:

your-tiny-mce-textarea .mce-path.mce-flow-layout-item {
    display: none !important;
}

UPD: This one seems more pretty:

your-tiny-mce-textarea.mce-statusbar {
    border: 0 !important;
}
your-tiny-mce-textarea.mce-path {
    display: none !important;
}


问:
How to check any missing number from a series of numbers?
I am doing a project creating an admission system for a college; the technologies are Java and Oracle.

In one of the tables, pre-generated serial numbers are stored. Later, against those serial numbers, the applicant's form data will be entered. My requirement is that when the entry process is completed I will have to generate a Lot wise report. If during feeding pre-generated serial numbers any sequence numbers went missing.

For example, say in a table, the sequence numbers are 7001, 7002, 7004, 7005, 7006, 7010.
From the above series it is clear that from 7001 to 7010 the numbers missing are 7003, 7007, 7008 and 7009

Is there any DBMS function available in Oracle to find out these numbers or if any stored procedure may fulfill my purpose then please suggest an algorithm.

I can find some techniques in Java but for speed I want to find the solution in Oracle.

答:
Here's a solution that:

Relies on Oracle's LAG function

Does not require knowledge of the complete sequence (but thus doesn't detect if very first or last numbers in sequence were missed)

Lists the values surrounding the missing lists of numbers

Lists the missing lists of numbers as contiguous groups (perhaps convenient for reporting)

Tragically fails for very large lists of missing numbers, due to listagg limitations

SQL:

```<code>WITH MentionedValues /*this would just be your actual table, only defined here to provide data for this example */
        AS (SELECT *
              FROM (    SELECT LEVEL + 7000 seqnum
                          FROM DUAL
                    CONNECT BY LEVEL <= 10000)
             WHERE seqnum NOT IN (7003,7007,7008,7009)--omit those four per example
                                       ),
     Ranges /*identifies all ranges between adjacent rows*/
        AS (SELECT seqnum AS seqnum_curr,
                   LAG (seqnum, 1) OVER (ORDER BY seqnum) AS seqnum_prev,
                   seqnum - (LAG (seqnum, 1) OVER (ORDER BY seqnum)) AS diff
              FROM MentionedValues)
SELECT Ranges.*,
       (    SELECT LISTAGG (Ranges.seqnum_prev + LEVEL, ',') WITHIN GROUP (ORDER BY 1)
              FROM DUAL
        CONNECT BY LEVEL < Ranges.diff) "MissingValues" /*count from lower seqnum+1 up to lower_seqnum+(diff-1)*/
  FROM Ranges
 WHERE diff != 1 /*ignore when diff=1 because that means the numers are sequential without skipping any*/
;
</code>```

Output:

```<code>SEQNUM_CURR SEQNUM_PREV DIFF MissingValues
7004        7002        2    "7003"
7010        7006        4    "7007,7008,7009"
</code>```

Body:
Here's a solution that:

Relies on Oracle's LAG function

Does not require knowledge of the complete sequence (but thus doesn't detect if very first or last numbers in sequence were missed)

Lists the values surrounding the missing lists of numbers

Lists the missing lists of numbers as contiguous groups (perhaps convenient for reporting)

Tragically fails for very large lists of missing numbers, due to listagg limitations

SQL:

WITH MentionedValues /*this would just be your actual table, only defined here to provide data for this example */
        AS (SELECT *
              FROM (    SELECT LEVEL + 7000 seqnum
                          FROM DUAL
                    CONNECT BY LEVEL <= 10000)
             WHERE seqnum NOT IN (7003,7007,7008,7009)--omit those four per example
                                       ),
     Ranges /*identifies all ranges between adjacent rows*/
        AS (SELECT seqnum AS seqnum_curr,
                   LAG (seqnum, 1) OVER (ORDER BY seqnum) AS seqnum_prev,
                   seqnum - (LAG (seqnum, 1) OVER (ORDER BY seqnum)) AS diff
              FROM MentionedValues)
SELECT Ranges.*,
       (    SELECT LISTAGG (Ranges.seqnum_prev + LEVEL, ',') WITHIN GROUP (ORDER BY 1)
              FROM DUAL
        CONNECT BY LEVEL < Ranges.diff) "MissingValues" /*count from lower seqnum+1 up to lower_seqnum+(diff-1)*/
  FROM Ranges
 WHERE diff != 1 /*ignore when diff=1 because that means the numers are sequential without skipping any*/
;

Output:

SEQNUM_CURR SEQNUM_PREV DIFF MissingValues
7004        7002        2    "7003"
7010        7006        4    "7007,7008,7009"


问:
ag-grid hide checkbox in some rows depend on the cell value
Currently I am using ag-grid to implement my table but I faced a problem.
I just want to display the checkbox in same rows only instead of all rows. May I know how to do it?</p>

答:
From the docs on the column properties:

checkboxSelection - Boolean or Function. Set to true (or return true from function) to render a selection checkbox in the column.

Here is a plunker with an example that puts a checkbox for people whose names start with a letter that is greater than 'M'

The relevant code that can be found in the app/rich-grid.component.ts:

```<code>headerName: "Name",
field: "name",
checkboxSelection: params=>params.data.name[0] >'M'
</code>```

Body:
From the docs on the column properties:

checkboxSelection - Boolean or Function. Set to true (or return true from function) to render a selection checkbox in the column.

Here is a plunker with an example that puts a checkbox for people whose names start with a letter that is greater than 'M'

The relevant code that can be found in the app/rich-grid.component.ts:

headerName: "Name",
field: "name",
checkboxSelection: params=>params.data.name[0] >'M'


问:
awk to convert unix time without strftime or date command(-d & -r option isn't supported in AIX)
I have current output as

```<code>file | awk '$1=="IMAGE" {print $2","$7","$14","$17","$19/1000}'

ABC,POL1,1510009167,1510009677,20.5
DEF,POL2,1510009667,1510009887,20.5
XYZ,POL3,1510007867,1510009887,20.5
PQR,POL4,1510009267,1510009997,20.5
</code>```

Expected output should have these unix time converted into human readable format, I can't use strftime or date -d option as they are not supported in AIX.
I do have a user defined command which i can use to convert but i can't use it in awk.I tried creating function and then use it in awk which didn't help

With Ed's Code I am getting this output as the user defined command gives output like this, However I want it to give me only day/Mon/Year. I can use awk to print this in user command, But i do i use it in this function?

```<code>ABC POL1 1510009167 = Mon Nov  6 17:59:27 EST 2017 1510009677 = Tue Nov  7 04:37:57 IST 2017 20.5
DEF POL2 1510009667 = Mon Nov  6 18:07:47 EST 2017 1510009887 = Tue Nov  7 04:41:27 IST 2017 20.5
XYZ POL3 1510007867 = Mon Nov  6 17:37:47 EST 2017 1510009887 = Tue Nov  7 04:41:27 IST 2017 20.5
PQR POL4 1510009267 = Mon Nov  6 18:01:07 EST 2017 1510009997 = Tue Nov  7 04:43:17 IST 2017 20.5
</code>```

Body:
I have current output as

file | awk '$1=="IMAGE" {print $2","$7","$14","$17","$19/1000}'

ABC,POL1,1510009167,1510009677,20.5
DEF,POL2,1510009667,1510009887,20.5
XYZ,POL3,1510007867,1510009887,20.5
PQR,POL4,1510009267,1510009997,20.5

Expected output should have these unix time converted into human readable format, I can't use strftime or date -d option as they are not supported in AIX.
I do have a user defined command which i can use to convert but i can't use it in awk.I tried creating function and then use it in awk which didn't help

With Ed's Code I am getting this output as the user defined command gives output like this, However I want it to give me only day/Mon/Year. I can use awk to print this in user command, But i do i use it in this function?

ABC POL1 1510009167 = Mon Nov  6 17:59:27 EST 2017 1510009677 = Tue Nov  7 04:37:57 IST 2017 20.5
DEF POL2 1510009667 = Mon Nov  6 18:07:47 EST 2017 1510009887 = Tue Nov  7 04:41:27 IST 2017 20.5
XYZ POL3 1510007867 = Mon Nov  6 17:37:47 EST 2017 1510009887 = Tue Nov  7 04:41:27 IST 2017 20.5
PQR POL4 1510009267 = Mon Nov  6 18:01:07 EST 2017 1510009997 = Tue Nov  7 04:43:17 IST 2017 20.5

Body:
GNU awk has a builtin strftime() function, but that most likely won't be available to you on AIX.

Try perl instead of awk:

perl -MPOSIX=strftime -F, -ane '
    $F[2] = strftime("%Y-%m-%dT%H:%M:%S", localtime($F[2]));
    $F[3] = strftime("%Y-%m-%dT%H:%M:%S", localtime($F[3]));
    print join ",", @F
' <<END
ABC,POL1,1510009167,1510009677,20.5
DEF,POL2,1510009667,1510009887,20.5
XYZ,POL3,1510007867,1510009887,20.5
PQR,POL4,1510009267,1510009997,20.5
END

ABC,POL1,2017-11-06T17:59:27,2017-11-06T18:07:57,20.5
DEF,POL2,2017-11-06T18:07:47,2017-11-06T18:11:27,20.5
XYZ,POL3,2017-11-06T17:37:47,2017-11-06T18:11:27,20.5
PQR,POL4,2017-11-06T18:01:07,2017-11-06T18:13:17,20.5


问:
SimpleSAMLPHP bind via POST
Our current SAML setup has been working just fine with the more or less default setup provided by the library SimpleSAMLPHP. However, one new IDP specifically needs to bind to the SP via a POST binding.

It seems like SimpleSAMLPHP will always redirect to the IDP using a GET request, as can be clearly seen here for example:

There also seems to be no distinct configuration setting which controls this.

We have tried to play with the NameID Policy settings with no success. The SP lists the following NameID Policy in their metadata:

```<code>urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST
</code>```

Our own NameID Policy is as follows:

```<code>urn:oasis:names:tc:SAML:1.1:nameid-format:unspecified
</code>```

Any tip here will really be highly appreciated

答:
You want the IdP's metadata to have a urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST binding for SingleSignOnService and have that binding be listed first in the list of SingleSignOnService options supported. This is often in the file metadata/saml20-idp-remote.php.  This is different from NameId and from the AssertionConsumerService SP bindings with the same binding name. Your SP will pick the first SingleSignOnService option listed for the IdP in the IdP's metadata.

```<code>$metadata['https://some.idp.co'] = array (
    'entityid' => 'https://some.idp.co',
    'metadata-set' => 'saml20-idp-remote',
    'SingleSignOnService' =>
        array (
            0 =>
                array (
                    'Binding' => 'urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST',
                    'Location' => 'https://some.idp.co/idp/profile/SAML2/POST/SSO',
                ),
            1 =>
                array (
                    'other options, etc'
                ),
        ),
</code>```

Title: SimpleSAMLPHP bind via POST

Body:
Our current SAML setup has been working just fine with the more or less default setup provided by the library SimpleSAMLPHP. However, one new IDP specifically needs to bind to the SP via a POST binding.

It seems like SimpleSAMLPHP will always redirect to the IDP using a GET request, as can be clearly seen here for example:

There also seems to be no distinct configuration setting which controls this.

We have tried to play with the NameID Policy settings with no success. The SP lists the following NameID Policy in their metadata:

urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST

Our own NameID Policy is as follows:

urn:oasis:names:tc:SAML:1.1:nameid-format:unspecified

Any tip here will really be highly appreciated

Body:
You want the IdP's metadata to have a urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST binding for SingleSignOnService and have that binding be listed first in the list of SingleSignOnService options supported. This is often in the file metadata/saml20-idp-remote.php.  This is different from NameId and from the AssertionConsumerService SP bindings with the same binding name. Your SP will pick the first SingleSignOnService option listed for the IdP in the IdP's metadata.

$metadata['https://some.idp.co'] = array (
    'entityid' => 'https://some.idp.co',
    'metadata-set' => 'saml20-idp-remote',
    'SingleSignOnService' =>
        array (
            0 =>
                array (
                    'Binding' => 'urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST',
                    'Location' => 'https://some.idp.co/idp/profile/SAML2/POST/SSO',
                ),
            1 =>
                array (
                    'other options, etc'
                ),
        ),


问:
vim ruby mismatch on Mac High Sierra
I recently upgraded my Mac to High Sierra

After the upgrade, Macvim (mvim) stopped working because (I assume) HighSierra upgraded ruby to 2.3, and mvim is using ruby 2.0.

Following is the error I am getting

dyld: Library not loaded:
  /System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/lib/libruby.2.0.0.dylib

Referenced from: /usr/local/Cellar/macvim/8.0-134/MacVim.app/Contents/bin/../MacOS/Vim

Do I need to compile vim again or is there any way to fix this problem?

Thanks in advance.

答:
This worked for me. YMMV

brew uninstall --purge macvim
brew install macvim

[amended] Regarding the upgrade alone option, that may work if you don't have the current version already. The --purge forces a removal and complete reinstall.
Also, the build from source option, while it may work, you now own your own mac-vim static snapshot and need to maintain it manually as the app evolves.
I'd avoid building from source unless you have very specific needs.

Title: vim ruby mismatch on Mac High Sierra


问:
Code Coverage not listed in VS2008 - c#
I'm trying to do unit testing in visual studio 2008 (Proffesional Edition). I've create a class library solution for this topic. Now, I want to use the feature of "Code coverage" but this is not listed in my local test config.

local config:

Does anyone knows how to listed and enable?
I'd appreciate any comments/suggestions.

Thank you.

答:
Ok Guys!
First of all thank you.

But this "issue" has been asked before :(, and yes, Code Coverage is available for Visual Studio 2008, but only for "bigger" editions, and not for Professional Edition.

Please see the next link of Microsoft. But also see the next links to stackoverflow questions, Question#1, and Question#2.

Thanks

Title: Code Coverage not listed in VS2008 - c#


问:
memcpy vs for loop - What's the proper way to copy an array from a pointer?
I have a function foo(int[] nums) which I understand is essentially equivalent to foo(int* nums).  Inside foo I need to copy the contents of the array pointed to by numsinto some int[10] declared within the scope of foo.  I understand the following is invalid:

```<code>void foo (int[] nums)
{
    myGlobalArray = *nums
}
</code>```

What is the proper way to copy the array?  Should I use memcpy like so:

```<code>void foo (int[] nums)
{
    memcpy(&myGlobalArray, nums, 10);
}
</code>```

or should I use a for loop?

```<code>void foo(int[] nums)
{
    for(int i =0; i < 10; i++)
    {
        myGlobalArray[i] = nums[i];
    }
}
</code>```

Is there a third option that I'm missing?

答:
Yes, the third option is to use a C++ construct:

```<code>std::copy(&nums[0], &nums[10], myGlobalArray);
</code>```

With any sane compiler, it:

should be optimum in the majority of cases (will compile to memcpy() where possible),

is type-safe,

gracefully copes when you decide to change the data-type to a non-primitive (i.e. it calls copy constructors, etc.),

gracefully copes when you decide to change to a container class.

Body:
I have a function foo(int[] nums) which I understand is essentially equivalent to foo(int* nums).  Inside foo I need to copy the contents of the array pointed to by numsinto some int[10] declared within the scope of foo.  I understand the following is invalid:

void foo (int[] nums)
{
    myGlobalArray = *nums
}

What is the proper way to copy the array?  Should I use memcpy like so:

void foo (int[] nums)
{
    memcpy(&myGlobalArray, nums, 10);
}

or should I use a for loop?

void foo(int[] nums)
{
    for(int i =0; i < 10; i++)
    {
        myGlobalArray[i] = nums[i];
    }
}

Is there a third option that I'm missing?

Body:
Yes, the third option is to use a C++ construct:

std::copy(&nums[0], &nums[10], myGlobalArray);

With any sane compiler, it:

should be optimum in the majority of cases (will compile to memcpy() where possible),

is type-safe,

gracefully copes when you decide to change the data-type to a non-primitive (i.e. it calls copy constructors, etc.),

gracefully copes when you decide to change to a container class.


问:
How to check if number from stdin is less than the numeric limit of a given type?
I have received a task that does not actually specify, what range of input one of my functions should expect (only, that it is always going to be a positive integer), and the input is decided runtime. Can I somehow test if the type I selected can actually hold the value it was fed to?

An illustration of what I am hoping to do:

```<code>char test;
std::cin >> test;
if(MAGIC)
{
    std::cout << "Error." << std::endl;
}
</code>```

With the magical part (or even the preceeding line) being the test I'm looking for.
It should work like this:

stdin: 100 -> no output

stdin: 1000000 -> Error.

答: I think the answer may be in https://stackoverflow.com/a/1855465/7071399 to know where to get the limits, then refer to https://stackoverflow.com/a/9574912/7071399 to get inspiration to your code (given you can use a long int or a char array to store the number and then check if it fits in the integer value). </p>

Body:
I have received a task that does not actually specify, what range of input one of my functions should expect (only, that it is always going to be a positive integer), and the input is decided runtime. Can I somehow test if the type I selected can actually hold the value it was fed to?

An illustration of what I am hoping to do:

char test;
std::cin >> test;
if(MAGIC)
{
    std::cout << "Error." << std::endl;
}

With the magical part (or even the preceeding line) being the test I'm looking for.
It should work like this:

stdin: 100 -> no output

stdin: 1000000 -> Error.


问:
I still get NaN even after converting calculations using parseInt
I Need to print the calculations gotten from options inside the Gross input box(3rd box) but instead of the calculation, I receive NaN.

The answer should return gross pay calculations based on the function below.

If the hours worked are less than equal 40, the calculation will be inside the if condition, or else, a different calculation.

function myFunction() {
  var hoursWorked;
  var hourlyRate;
  document.getElementById("hours").value = hoursWorked;
  document.getElementById("payrate").value = hourlyRate;
  if (hoursWorked <= 40) {
    var grossPay = parseInt((hoursWorked * hourlyRate)).toFixed(2);
    document.getElementById("gross").value = grossPay;
  } else {
    var grossPay = parseInt((40 * hourlyRate + 1.5 * hourlyRate * (hoursWorked - 40))).toFixed(2);
    document.getElementById("gross").value = grossPay;
  }

}```
<pre class="snippet-code-html lang-html prettyprint-override"><code># Add A H1 Heading Of "Gross Pay Calculation"

<form>
  Hourly Rate:
  <select id="payrate" align="right">
    <script>
      for(var d=10;d<=60;d++) {
        document.write("<option>"+(d)+"</option>");
        d+=9;
        document.getElementById("payrate").value;
      }
    </script>
  </select><br> Hours Worked:
  <select id="hours" align="right">
    <script>
      for(var d=10;d<=60;d++) {
        document.write("<option>"+d+"</option>");
        d+=4;
        document.getElementById("hours").value;
      }
    </script>
  </select><br>
</form>

Gross Pay: <input type="text" id="gross" align="right"><br><br>
<input type="submit" value="GrossPay" onclick="myFunction()"></code>```

答:
You are assigning your inputs to uninitialized variables change those to this

```<code>hoursWorked=document.getElementById("hours").value;
hourlyRate=document.getElementById("payrate").value;
</code>```

<!DOCTYPE html>

    <title>Page Title</title>

     # Add A H1 Heading Of "Gross Pay Calculation"

    <form>
    Hourly Rate:  <select id="payrate" align="right">

                  </select>

     Hours Worked: <select id="hours" align="right">

                  </select>

     </form>

    Gross Pay:  <input type="text" id="gross" align="right">

    <input type="submit" value="GrossPay" onclick="myFunction()">

     ```

Body:
I Need to print the calculations gotten from options inside the Gross input box(3rd box) but instead of the calculation, I receive NaN.

The answer should return gross pay calculations based on the function below.

If the hours worked are less than equal 40, the calculation will be inside the if condition, or else, a different calculation.

function myFunction() {
  var hoursWorked;
  var hourlyRate;
  document.getElementById("hours").value = hoursWorked;
  document.getElementById("payrate").value = hourlyRate;
  if (hoursWorked <= 40) {
    var grossPay = parseInt((hoursWorked * hourlyRate)).toFixed(2);
    document.getElementById("gross").value = grossPay;
  } else {
    var grossPay = parseInt((40 * hourlyRate + 1.5 * hourlyRate * (hoursWorked - 40))).toFixed(2);
    document.getElementById("gross").value = grossPay;
  }

}

# Add A H1 Heading Of "Gross Pay Calculation"

<form>
  Hourly Rate:
  <select id="payrate" align="right">

  </select>
 Hours Worked:
  <select id="hours" align="right">

  </select>

</form>

Gross Pay: <input type="text" id="gross" align="right">

<input type="submit" value="GrossPay" onclick="myFunction()">

Body:
You are assigning your inputs to uninitialized variables change those to this

hoursWorked=document.getElementById("hours").value;
hourlyRate=document.getElementById("payrate").value;

<!DOCTYPE html>
    <html>
    <head>
    <title>Page Title</title>

    <script>
     function myFunction()
     {
         var hoursWorked;
         var hourlyRate;
      //hoursWorked=
      hoursWorked=document.getElementById("hours").value;
        hourlyRate=document.getElementById("payrate").value;
        if (hoursWorked <=40)
        {
           var grossPay=parseInt((hoursWorked*hourlyRate)).toFixed(2);
           document.getElementById("gross").value = grossPay;
        }
        else
        {
           var grossPay=parseInt((40*hourlyRate+1.5*hourlyRate*(hoursWorked-40))).toFixed(2);
           document.getElementById("gross").value = grossPay;
        }

     }
     </script>
    </head>
    <body>
     # Add A H1 Heading Of "Gross Pay Calculation"

    <form>
    Hourly Rate:  <select id="payrate" align="right">
                  <script>
                  for(var d=10;d<=60;d++)
                  {
                    document.write("<option>"+(d)+"</option>");
                    d+=9;

        document.getElementById("payrate").value;
                  }
                  </script>
                  </select><br>
     Hours Worked: <select id="hours" align="right">
                  <script>
                  for(var d=10;d<=60;d++)
                  {
                    document.write("<option>"+d+"</option>");
                    d+=4;
                    document.getElementById("hours").value;
                  }
                  </script>
                  </select><br>
     </form>

    Gross Pay:  <input type="text" id="gross" align="right"><br><br>
    <input type="submit" value="GrossPay" onclick="myFunction()">

     </body>
     </html>


问:
jqueryui combobox: how do I get the value?
I borrowed the code from http://jqueryui.com/demos/autocomplete/#combobox but don't know how to get the value of the selected item.

Hoping for a simple straight answer rather than reading their docs for the next 2 hours.

答:
first set id of textbox and then get value of that textbox and match it with text of option of dropdown, if option's text match then get its value.you can see example here in jsfiddle</p>

```<code>this.input = $("<input>")
     .appendTo(this.wrapper)
     .val(value)
     .attr('placeholder', "Enter Type...")
     .attr("title", "")

     // Set Id of Input Type Text

     .attr('id', 'Mach')
     .addClass("custom-combobox-input ui-widget ui-widget-content ui-state-default ui-corner-left")
     .autocomplete({
     delay: 0,
     minLength: 0,
     source: $.proxy(this, "_source")
     })
</code>```

Body:
first set id of textbox and then get value of that textbox and match it with text of option of dropdown, if option's text match then get its value.you can see example here in jsfiddle

this.input = $("<input>")
     .appendTo(this.wrapper)
     .val(value)
     .attr('placeholder', "Enter Type...")
     .attr("title", "")

     // Set Id of Input Type Text

     .attr('id', 'Mach')
     .addClass("custom-combobox-input ui-widget ui-widget-content ui-state-default ui-corner-left")
     .autocomplete({
     delay: 0,
     minLength: 0,
     source: $.proxy(this, "_source")
     })


问:
puppeteer - how to set download location
I was able to successfully download a file with puppeteer, but it was just saving it to my /Downloads folder. I've been looking around and can't find anything in the api or forums to set this location.

My downloads are basically just go going to the link:

```<code>await page.goto(url);
</code>```

答:
Update for newer Puppeteer versions (~June 2022):

As mentioned by @Daniel here, you have to create the CDP session yourself:

```<code>const client = await page.target().createCDPSession()
await client.send('Page.setDownloadBehavior', {
  behavior: 'allow',
  downloadPath: './myAwesomeDownloadFolder',
})
</code>```

Original Answer

This is how you can set the download path in latest puppeteer v0.13.

```<code>await page._client.send('Page.setDownloadBehavior', {behavior: 'allow', downloadPath: './myAwesomeDownloadFolder'});
</code>```

The behaviour is experimental, it might be removed, modified, or changed later.

Pst, you can try more tricks listed here, on your own risk :).

Body:
I was able to successfully download a file with puppeteer, but it was just saving it to my /Downloads folder. I've been looking around and can't find anything in the api or forums to set this location.

My downloads are basically just go going to the link:

await page.goto(url);

Body:
Update for newer Puppeteer versions (~June 2022):

As mentioned by @Daniel here, you have to create the CDP session yourself:

const client = await page.target().createCDPSession()
await client.send('Page.setDownloadBehavior', {
  behavior: 'allow',
  downloadPath: './myAwesomeDownloadFolder',
})

Original Answer

This is how you can set the download path in latest puppeteer v0.13.

await page._client.send('Page.setDownloadBehavior', {behavior: 'allow', downloadPath: './myAwesomeDownloadFolder'});

The behaviour is experimental, it might be removed, modified, or changed later.

Pst, you can try more tricks listed here, on your own risk :).


问:
Adding Font To A CSS Page
I have a font I downloaded and I'm trying to apply that font to my site.

so I simply used font-family but my font isn't there(obviously) any idea on how to add it?

答:
You simply write the name of the font, such as:

```<code>font-family: Gotham;
</code>```

.. or ...

```<code>font-family: "Myriad Pro";
</code>```

It will work on your machine but not on users' machines unless they have the font installed.

Title: Adding Font To A CSS Page

Body:
You simply write the name of the font, such as:

font-family: Gotham;

.. or ...

font-family: "Myriad Pro";

It will work on your machine but not on users' machines unless they have the font installed.


问:
How to move button outside of his parent with tkinter?
I'm currently trying to move a button by using drag and drop with tkinter.
The problem is that when I'm trying to move my button, it's working but I can't move it outside his parent:
I have a LabelFrame which contains several LabelFrame with buttons. I'm trying to drag and drop a button from a LabelFrame to the other one but when the button is going outside of his parent, it "disappears".
I'm using the method "place" of the widget to move it during my drag.

I'm not sure if my problem is really understandable. I'll put some codes if it isn't to explain it better.

答:
Widgets exist in a hierarchy, and every widget will be visually clipped by its parent. Since you want a widget to appear in different frames at different times, it simply cannot be a child of either frame. Instead, make it a child of the parent of the frames. You can then use place (or pack or grid) to put the widget in either frame by using the in_ parameter.

Here's an example. It doesn't use drag and drop in order to keep the code compact, but it illustrates the principle. Click on the button to move it from one frame to the other.

```<code>import tkinter as tk

class Example:
    def __init__(self):
        self.root = tk.Tk()
        self.lf1 = tk.LabelFrame(self.root, text="Choose me!", width=200, height=200)
        self.lf2 = tk.LabelFrame(self.root, text="No! Choose me!", width=200, height=200)

        self.lf1.pack(side="left", fill="both", expand=True)
        self.lf2.pack(side="right", fill="both", expand=True)

        self.button = tk.Button(self.root, text="Click me", command=self.on_click)
        self.button.place(in_=self.lf1, x=20, y=20)

    def start(self):
        self.root.mainloop()

    def on_click(self):
        current_frame = self.button.place_info().get("in")
        new_frame = self.lf1 if current_frame == self.lf2 else self.lf2
        self.button.place(in_=new_frame, x=20, y=20)

Example().start()
</code>```

Body:
Widgets exist in a hierarchy, and every widget will be visually clipped by its parent. Since you want a widget to appear in different frames at different times, it simply cannot be a child of either frame. Instead, make it a child of the parent of the frames. You can then use place (or pack or grid) to put the widget in either frame by using the in_ parameter.

Here's an example. It doesn't use drag and drop in order to keep the code compact, but it illustrates the principle. Click on the button to move it from one frame to the other.

import tkinter as tk

class Example:
    def __init__(self):
        self.root = tk.Tk()
        self.lf1 = tk.LabelFrame(self.root, text="Choose me!", width=200, height=200)
        self.lf2 = tk.LabelFrame(self.root, text="No! Choose me!", width=200, height=200)

        self.lf1.pack(side="left", fill="both", expand=True)
        self.lf2.pack(side="right", fill="both", expand=True)

        self.button = tk.Button(self.root, text="Click me", command=self.on_click)
        self.button.place(in_=self.lf1, x=20, y=20)

    def start(self):
        self.root.mainloop()

    def on_click(self):
        current_frame = self.button.place_info().get("in")
        new_frame = self.lf1 if current_frame == self.lf2 else self.lf2
        self.button.place(in_=new_frame, x=20, y=20)

Example().start()


答:
For most data types you can check the error state of the input stream as described here. However, this would not work for some other types, such as char from your post, because std::cin >> test would read data as a single character, i.e. '1' which is not what you need to achieve.

One approach is to read the number into std::string, and compare it to the max() obtained through limits:

```<code>std::string max = std::to_string(std::numeric_limits<char>::max());
std::string s;
std::cin >> s;
bool cmp = (s.size() == max.size()) ? (s <= max) : (s.size() < max.size());
std::cout << s << " " << cmp << std::endl;
</code>```

Demo.

Note: The above code makes an assumption that the data entered is a number, which may be arbitrarily large, but must not contain characters other than digits. If you cannot make this assumption, use a solution from this Q&A to test if the input is numeric.

Title: How to check if number from stdin is less than the numeric limit of a given type?

Body:
For most data types you can check the error state of the input stream as described here. However, this would not work for some other types, such as char from your post, because std::cin >> test would read data as a single character, i.e. '1' which is not what you need to achieve.

One approach is to read the number into std::string, and compare it to the max() obtained through limits:

std::string max = std::to_string(std::numeric_limits<char>::max());
std::string s;
std::cin >> s;
bool cmp = (s.size() == max.size()) ? (s <= max) : (s.size() < max.size());
std::cout << s << " " << cmp << std::endl;

Demo.

Note: The above code makes an assumption that the data entered is a number, which may be arbitrarily large, but must not contain characters other than digits. If you cannot make this assumption, use a solution from this Q&A to test if the input is numeric.


问:
How to use non-capturing groups in this example
The following regex:

```<code>(\d+\.?\d+?)px \/\* (\d+) \*\/
</code>```

matches 5.5px /* 1440 */ in:

```<code>position: relative;
padding: 5.5px /* 1440 */ 9px /* 1440 */;
border: 0;
</code>```

but not 9px /* 1440 */.

This regex does match both 5.5px /* 1440 */ and 9px /* 1440 */ but captures groups I do not wish to capture.

```<code>(\d+(\.)?(\d+)?)px \/\* (\d+) \*\/
</code>```

How can I write (\d+(\.)?(\d+)?)px \/\* (\d+) \*\/ without capturing (\.) and (\d+)?

答:
\d+? is a lazy version of \d+, NOT an optional \d+.

Instead, the * quantifier means 0 or more.

You can also use the (?:…) non-capture syntax.

Body:
The following regex:

(\d+\.?\d+?)px \/\* (\d+) \*\/

matches 5.5px /* 1440 */ in:

position: relative;
padding: 5.5px /* 1440 */ 9px /* 1440 */;
border: 0;

but not 9px /* 1440 */.

This regex does match both 5.5px /* 1440 */ and 9px /* 1440 */ but captures groups I do not wish to capture.

(\d+(\.)?(\d+)?)px \/\* (\d+) \*\/

How can I write (\d+(\.)?(\d+)?)px \/\* (\d+) \*\/ without capturing (\.) and (\d+)?


问:
MS Access SQL - Count of Records that are Currently Open During a Workweek
I have a record set that contains

```<code> unique ID
 open date
 closed date
</code>```

I want a query to find the count of record that were active during each workweek (52 workweeks in each year).  The data spans several years so the workweeks would not be unique, repeating from 1-52 each year.

Some pseudo-Code would look like:

```<code> CountIf( ((OpenDate >= Workweek) & (ClosedDate >= WorkWeek))
         OR ((OpenDate >= Workweek) & IsNull(ClosedDate)) )
</code>```

The end result would be a table with the Years, Workweeks, and Count of Active records for that year/workweek.

I have a query that gives me Opened in a workweek:

```<code>SELECT Year([TABLE].[OpenedDate]) AS [Year], DatePart('ww',TABLE.[OpenedDate])
AS [Work Week], Count(TABLE.[ID]) AS [Count Of IDs Opened]
FROM TABLE
GROUP BY Year([TABLE].[OpenedDate]), DatePart('ww',TABLE.[OpenedDate])
ORDER BY Year([TABLE].[OpenedDate]), DatePart('ww',TABLE.[OpenedDate]);
</code>```

And a similar one for Closed but I just can't wrap my head around how to get Active during each Workweek.

Edited to add:

Example Data:

```<code>No  Opened Date Closed Date
1   20-Apr-15   23-Apr-15
2   22-Apr-15   04-May-15
3   27-Apr-15   01-May-15
4   29-Apr-15   04-May-15
5   29-Apr-15   05-Jun-15
6   04-May-15   20-May-15
7   04-May-15   07-May-15
8   05-May-15   20-May-15
9   05-May-15   20-May-15
10  06-May-15   20-May-15
11  06-May-15   20-May-15
12  06-May-15   20-May-15
13  07-May-15   20-May-15
14  11-May-15   26-May-15
15  11-May-15   26-May-15
16  13-May-15   26-May-15
17  18-May-15   26-May-15
18  20-May-15   01-Jun-15
19  21-May-15   03-Jun-15
20  12-Oct-15   07-Jul-16
21  02-Nov-15   26-Jul-17
22  06-Nov-15   30-Nov-15
23  09-Nov-15   26-Jul-17
24  08-Feb-17   05-May-17
25  13-Feb-17
26  13-Feb-17   14-Aug-17
27  07-Mar-17   17-Mar-17
</code>```

答:
Consider conditional aggregation where you count active records by same week of OpenedDate and ClosedDate. Below exaggerates indentation for readability.

```<code>SELECT Year(t.[OpenedDate]) AS [Year],
       DatePart('ww', t.[OpenedDate]) AS [Work Week],

       SUM(IIF(((
                DatePart('ww', t.[OpenedDate]) = [Work Week] AND
                DatePart('ww', t.[ClosedDate]) = [Work Week])
               ) OR
               (
                DatePart('ww', t.[OpenedDate]) = [Work Week] AND
                t.[ClosedDate] IS NULL
               ),
           1,
           0)) AS [Count Of Active IDs]

FROM myTable t
GROUP BY Year(t.[OpenedDate]), DatePart('ww', t.[OpenedDate])
ORDER BY Year(t.[OpenedDate]), DatePart('ww', t.[OpenedDate]);
</code>```

To test above, here is the unit level (non-aggregate) query:

```<code>SELECT Year(t.[OpenedDate]) AS [Year],
       DatePart('ww', t.[OpenedDate]) AS [Work Week],

       t.[OpenedDate],
       t.[ClosedDate],

       IIF(((
             DatePart('ww', t.[OpenedDate]) = [Work Week] AND
             DatePart('ww', t.[ClosedDate]) = [Work Week])
            ) OR
            (
             DatePart('ww', t.[OpenedDate]) = [Work Week] AND
             t.[ClosedDate] IS NULL
            ),
           1,
           0) AS [Active ID]

FROM myTable t
</code>```

Body:
I have a record set that contains

 unique ID
 open date
 closed date

I want a query to find the count of record that were active during each workweek (52 workweeks in each year).  The data spans several years so the workweeks would not be unique, repeating from 1-52 each year.

Some pseudo-Code would look like:

 CountIf( ((OpenDate >= Workweek) & (ClosedDate >= WorkWeek))
         OR ((OpenDate >= Workweek) & IsNull(ClosedDate)) )

The end result would be a table with the Years, Workweeks, and Count of Active records for that year/workweek.

I have a query that gives me Opened in a workweek:

SELECT Year([TABLE].[OpenedDate]) AS [Year], DatePart('ww',TABLE.[OpenedDate])
AS [Work Week], Count(TABLE.[ID]) AS [Count Of IDs Opened]
FROM TABLE
GROUP BY Year([TABLE].[OpenedDate]), DatePart('ww',TABLE.[OpenedDate])
ORDER BY Year([TABLE].[OpenedDate]), DatePart('ww',TABLE.[OpenedDate]);

And a similar one for Closed but I just can't wrap my head around how to get Active during each Workweek.

Edited to add:

Example Data:

No  Opened Date Closed Date
1   20-Apr-15   23-Apr-15
2   22-Apr-15   04-May-15
3   27-Apr-15   01-May-15
4   29-Apr-15   04-May-15
5   29-Apr-15   05-Jun-15
6   04-May-15   20-May-15
7   04-May-15   07-May-15
8   05-May-15   20-May-15
9   05-May-15   20-May-15
10  06-May-15   20-May-15
11  06-May-15   20-May-15
12  06-May-15   20-May-15
13  07-May-15   20-May-15
14  11-May-15   26-May-15
15  11-May-15   26-May-15
16  13-May-15   26-May-15
17  18-May-15   26-May-15
18  20-May-15   01-Jun-15
19  21-May-15   03-Jun-15
20  12-Oct-15   07-Jul-16
21  02-Nov-15   26-Jul-17
22  06-Nov-15   30-Nov-15
23  09-Nov-15   26-Jul-17
24  08-Feb-17   05-May-17
25  13-Feb-17
26  13-Feb-17   14-Aug-17
27  07-Mar-17   17-Mar-17

Body:
Consider conditional aggregation where you count active records by same week of OpenedDate and ClosedDate. Below exaggerates indentation for readability.

SELECT Year(t.[OpenedDate]) AS [Year],
       DatePart('ww', t.[OpenedDate]) AS [Work Week],

       SUM(IIF(((
                DatePart('ww', t.[OpenedDate]) = [Work Week] AND
                DatePart('ww', t.[ClosedDate]) = [Work Week])
               ) OR
               (
                DatePart('ww', t.[OpenedDate]) = [Work Week] AND
                t.[ClosedDate] IS NULL
               ),
           1,
           0)) AS [Count Of Active IDs]

FROM myTable t
GROUP BY Year(t.[OpenedDate]), DatePart('ww', t.[OpenedDate])
ORDER BY Year(t.[OpenedDate]), DatePart('ww', t.[OpenedDate]);

To test above, here is the unit level (non-aggregate) query:

SELECT Year(t.[OpenedDate]) AS [Year],
       DatePart('ww', t.[OpenedDate]) AS [Work Week],

       t.[OpenedDate],
       t.[ClosedDate],

       IIF(((
             DatePart('ww', t.[OpenedDate]) = [Work Week] AND
             DatePart('ww', t.[ClosedDate]) = [Work Week])
            ) OR
            (
             DatePart('ww', t.[OpenedDate]) = [Work Week] AND
             t.[ClosedDate] IS NULL
            ),
           1,
           0) AS [Active ID]

FROM myTable t


问:
Javascript return value from nested function prints undefined
Here i'm trying to return value from bcrypt.compare, nested inside a function.

I want to get the result value (true or false).

Im using coffeescript. Here is the code:

```<code>comparePasswordWithHash = (pass, hash) ->
  return bcrypt.compare pass, hash, (err, result) ->
    if err
      throw err
    else
      return result

console.log comparePasswordWithHash "bacon", hashedPassword # Should print true/false
</code>```

With this code, value printed is undefined.

答:
bcrypt.compare() is asynchronous. This means that it is not returning anything, but instead calls the callback you pass to it. There is also a sync version of compare() --> bcrypt.compareSync().

My coffeescript is a little rusty, but I think you would end up with something like this using the promise:

```<code>comparePasswordWithHash = (pass, hash) -> bcrypt.compare pass, hash

comparePasswordWithHash "bacon", hashedPassword
.then (response) ->  console.log response
.catch (error) -> console.log error
</code>```

Body:
Here i'm trying to return value from bcrypt.compare, nested inside a function.

I want to get the result value (true or false).

Im using coffeescript. Here is the code:

comparePasswordWithHash = (pass, hash) ->
  return bcrypt.compare pass, hash, (err, result) ->
    if err
      throw err
    else
      return result

console.log comparePasswordWithHash "bacon", hashedPassword # Should print true/false

With this code, value printed is undefined.

Body:
bcrypt.compare() is asynchronous. This means that it is not returning anything, but instead calls the callback you pass to it. There is also a sync version of compare() --> bcrypt.compareSync().

My coffeescript is a little rusty, but I think you would end up with something like this using the promise:

comparePasswordWithHash = (pass, hash) -> bcrypt.compare pass, hash

comparePasswordWithHash "bacon", hashedPassword
.then (response) ->  console.log response
.catch (error) -> console.log error


问:
Error dropping database (can't rmdir './someDB/', errno: 17)
It's insane. I have tried all the methods but it still throws the same error.

I have a database, want it to run on MySQL-Server. At the beginning of the Database:

```<code>DROP SCHEMA IF EXISTS someDB;
CREATE SCHEMA someDB;
USE someDB;
</code>```

When I tried SHOW DATABASES LIKE 'someDB'; it confirms the existence of it.

I tried:

chmod for the full path to it /var/lib/mysql/someDB/someDB.sql

Stopping MySQL-Server, Deleting the the someDB folder and starting the Server again.

I removed the entire MySQL-Server and reinstalled it again.

After hours of trying, I really need you help.

EDIT:
Answering Y. Collin Comment, when I run sudo ls -la ./someDB, it returns:

```<code>total 20
drwxrwxr-x 2 ubuntu ubuntu  4096 Nov 14 16:53 .
drwxrwxrwx 5 mysql  mysql   4096 Nov 14 16:53 ..
-rwxrwxrwx 1 ubuntu ubuntu 12243 Nov 14 16:53 someDB.sql
</code>```

答:
What do you see if who run the following command:

```<code>ls -la ./someDB/
</code>```

If there is a file in it like in this example you should delete it first.

Credit to @Beel

Body:
It's insane. I have tried all the methods but it still throws the same error.

I have a database, want it to run on MySQL-Server. At the beginning of the Database:

DROP SCHEMA IF EXISTS someDB;
CREATE SCHEMA someDB;
USE someDB;

When I tried SHOW DATABASES LIKE 'someDB'; it confirms the existence of it.

I tried:

chmod for the full path to it /var/lib/mysql/someDB/someDB.sql

Stopping MySQL-Server, Deleting the the someDB folder and starting the Server again.

I removed the entire MySQL-Server and reinstalled it again.

After hours of trying, I really need you help.

EDIT:
Answering Y. Collin Comment, when I run sudo ls -la ./someDB, it returns:

total 20
drwxrwxr-x 2 ubuntu ubuntu  4096 Nov 14 16:53 .
drwxrwxrwx 5 mysql  mysql   4096 Nov 14 16:53 ..
-rwxrwxrwx 1 ubuntu ubuntu 12243 Nov 14 16:53 someDB.sql

Body:
What do you see if who run the following command:

ls -la ./someDB/

If there is a file in it like in this example you should delete it first.

Credit to @Beel


问:
NSArrayController NSTableView Core Data Binding integers
I have an NSTableView bound to an NSArrayController, which in turn is bound to Core Data. The table displays integer values from core data nicely, but if I edit the numbers in the table I get an error:

```<code>Unacceptable type of value for attribute: property = "armorclass"; desired type = NSNumber; given type = NSTaggedPointerString; value = 10.
</code>```

Any suggestions of how I can convert this pointer string back to an Int16 before the Array Controller tries to save it back to Core Data?

I wrote the following ValueTransformer but it's not working properly. I always get the error: Cannot find value transformer with name StringIntegerValueTransformer

```<code>class StringIntegerValueTransformer: ValueTransformer {

    override class func transformedValueClass() -> AnyClass { //What do I transform
        return String.self as! AnyClass
    }

    override class func allowsReverseTransformation() -> Bool { //Can I transform back?
        return false
    }

    override func transformedValue(_ value: Any?) -> Any? {
        if let val = value {
            return String(describing: val)
        }
        return "nil"
    }

    override func reverseTransformedValue(_ value: Any?) -> Any? { //Revert transformation
        if let val = value {
            return val as? Int16
        }
        return nil
    }
}
</code>```

fff

答: Add a number formatter to the text field.</p>

Body:
I have an NSTableView bound to an NSArrayController, which in turn is bound to Core Data. The table displays integer values from core data nicely, but if I edit the numbers in the table I get an error:

Unacceptable type of value for attribute: property = "armorclass"; desired type = NSNumber; given type = NSTaggedPointerString; value = 10.

Any suggestions of how I can convert this pointer string back to an Int16 before the Array Controller tries to save it back to Core Data?

I wrote the following ValueTransformer but it's not working properly. I always get the error: Cannot find value transformer with name StringIntegerValueTransformer

class StringIntegerValueTransformer: ValueTransformer {

    override class func transformedValueClass() -> AnyClass { //What do I transform
        return String.self as! AnyClass
    }

    override class func allowsReverseTransformation() -> Bool { //Can I transform back?
        return false
    }

    override func transformedValue(_ value: Any?) -> Any? {
        if let val = value {
            return String(describing: val)
        }
        return "nil"
    }

    override func reverseTransformedValue(_ value: Any?) -> Any? { //Revert transformation
        if let val = value {
            return val as? Int16
        }
        return nil
    }
}

fff


问:
Spring-Boot | loading different messages.properties files for different clients/users dynamically
I searched a lot but I can't find any useful information on my topic. Let me explain.

I created a spring application that can change its layout based on the user that is logged in. This layout can be uploaded by an admin. Now I want to add a function that the admin can upload a specific messages.properties for this user, so the texts change based on the logged in user as well. The templates that I created with thymeleaf are always the same. So the message keys are the same, just the values are changing.

I tried to create a dynamic ReloadableResourceBundleMessageSource but that is not working because at the configuration time you don't know what the name of the messages.propertie will be.

Do I just don't get it? I don't know. Is there any way to create a dynamic messages.properties-loader that can identify the file with a name like:
messages_foo_de_DE.properties

答:
Try this approach. propsFileName, property, and value can be supplied as arguments

```<code>    @Autowired
    ReloadableResourceBundleMessageSource messageSrc;

    void updateProperty(String property, String value, String propsFileName) {
     boolean success = false;
     Properties props = new Properties();
     FileOutputStream output = null;
     FileInputStream configStream = null;
     try {
        configStream = new FileInputStream(propsFileName);
        props.load(configStream);
        props.setProperty(property, value);
        // save modified property file
        output = new FileOutputStream(propsFileName);
        props.store(output, "This description goes to the header of a file");

    } catch (IOException ex) {
        log.error(ex);
    } finally {
        if (configStream != null) {
            try {
                configStream.close();
            } catch (IOException e) {
                log.error(e);
            }
        }
        if (output != null) {
            try {
                output.close();
            } catch (IOException e) {
                log.error(e);
            }
        }
    }

     messageSrc.clearCache();
}
</code>```

Body:
Try this approach. propsFileName, property, and value can be supplied as arguments

    @Autowired
    ReloadableResourceBundleMessageSource messageSrc;

    void updateProperty(String property, String value, String propsFileName) {
     boolean success = false;
     Properties props = new Properties();
     FileOutputStream output = null;
     FileInputStream configStream = null;
     try {
        configStream = new FileInputStream(propsFileName);
        props.load(configStream);
        props.setProperty(property, value);
        // save modified property file
        output = new FileOutputStream(propsFileName);
        props.store(output, "This description goes to the header of a file");

    } catch (IOException ex) {
        log.error(ex);
    } finally {
        if (configStream != null) {
            try {
                configStream.close();
            } catch (IOException e) {
                log.error(e);
            }
        }
        if (output != null) {
            try {
                output.close();
            } catch (IOException e) {
                log.error(e);
            }
        }
    }

     messageSrc.clearCache();
}


问:
javascript function working only once
I have been trying to use java script to validate a contact form.
The idea is to add a paragraph tag above each textbox and when the submit button is clicked a javascript function should be fired.
if the textbox is empty the "hidden" class will be removed from the class list of the paragraph so it will be visible
The problem is that function is fired only once, the first time i click the button. but if I fill on textbox and click again the function is not fired.
can any body help me about this?
Note: if I use getElementById the function is not fired and the compiler goes to the server side function btnSubmit_Click but when using getElementByName the function is fired only once as described above.

```<code>        <div id="contactForm" runat="server">
            <div class="control-group form-group">
                <div class="controls">
                    <p id="errname" class="hidden">You must insert your <b>name</b></p>
                    <input type="text" runat="server" class="form-control" id="txtname" name="txtname" placeholder="*Full Name" >
                </div>
            </div>
            <div class="control-group form-group">
                <div class="controls">
                    <p id="erremail" class="hidden">You must insert your <b>email</b></p>
                    <input type="email" runat="server" class="form-control" id="txtemail" name="txtemail" placeholder="*Email" >
                </div>
            </div>
            <div class="control-group form-group">
                <div class="controls">
                    <p id="errmessage" class="hidden">You must insert a <b>message</b></p>
                    <textarea runat="server" rows="10" cols="100" class="form-control" id="txtmessage" name="txtmessage" placeholder="*Message" maxlength="999" style="resize:none"></textarea>
                </div>
            </div>
            <asp:Button ID="btnSubmit" runat="server"  OnClientClick="return myfun();" OnClick="btnSubmit_Click"  Text="Send Message" class="btn btn-primary btn-block" />
        </div>
</code>```

and the javascript function is:

```<code>    function myfun() {
        document.getElementById("errname").classList.add('hidden');
        document.getElementById("erremail").classList.add('hidden');
        document.getElementById("errmessage").classList.add('hidden');

        var flag = true;
        if (!document.getElementsById("txtname").value) {
            document.getElementById("errname").classList.remove('hidden');
            flag= false;
        }

        if (!document.getElementsById("txtemail").value) {
            document.getElementById("erremail").classList.remove('hidden');
            flag= false;
        }

        if (!document.getElementsById("txtmessage").value) {
            document.getElementById("errmessage").classList.remove('hidden');
            flag = false;
        }
        if (flag == false) { return false;}

    }
</script>
</code>```

答:
it is done by adding clientIdMode="static" to the textboxes that are called in the javascript function</p>

```<code>                    <input type="text" runat="server" class="form-control" id="txtname" name="txtname" placeholder="*Full Name" clientIdMode="static">
</code>```

Title: javascript function working only once

Body:
I have been trying to use java script to validate a contact form.
The idea is to add a paragraph tag above each textbox and when the submit button is clicked a javascript function should be fired.
if the textbox is empty the "hidden" class will be removed from the class list of the paragraph so it will be visible
The problem is that function is fired only once, the first time i click the button. but if I fill on textbox and click again the function is not fired.
can any body help me about this?
Note: if I use getElementById the function is not fired and the compiler goes to the server side function btnSubmit_Click but when using getElementByName the function is fired only once as described above.

You must insert your name

                    <input type="text" runat="server" class="form-control" id="txtname" name="txtname" placeholder="*Full Name" >

You must insert your email

                    <input type="email" runat="server" class="form-control" id="txtemail" name="txtemail" placeholder="*Email" >

You must insert a message

                    <textarea runat="server" rows="10" cols="100" class="form-control" id="txtmessage" name="txtmessage" placeholder="*Message" maxlength="999" style="resize:none"></textarea>

            <asp:Button ID="btnSubmit" runat="server"  OnClientClick="return myfun();" OnClick="btnSubmit_Click"  Text="Send Message" class="btn btn-primary btn-block" />

and the javascript function is:

    function myfun() {
        document.getElementById("errname").classList.add('hidden');
        document.getElementById("erremail").classList.add('hidden');
        document.getElementById("errmessage").classList.add('hidden');

        var flag = true;
        if (!document.getElementsById("txtname").value) {
            document.getElementById("errname").classList.remove('hidden');
            flag= false;
        }

        if (!document.getElementsById("txtemail").value) {
            document.getElementById("erremail").classList.remove('hidden');
            flag= false;
        }

        if (!document.getElementsById("txtmessage").value) {
            document.getElementById("errmessage").classList.remove('hidden');
            flag = false;
        }
        if (flag == false) { return false;}

    }
</script>

Body:
it is done by adding clientIdMode="static" to the textboxes that are called in the javascript function

                    <input type="text" runat="server" class="form-control" id="txtname" name="txtname" placeholder="*Full Name" clientIdMode="static">


问:
Can't use GSAP inside function to target MovieClip on stage (Animate CC)
I'm an HTML5 newbie and I was wondering if someone could tell me what I'm doing wrong here. I would like to be able to use GSAP to animate a vector file I'd add to the stage and would need to be able to make it animate when I call a function, however when I try to do this I keep getting cannot tween a null object, but if it's not wrapped in a function the animation plays fine.

I created a new HTML5 canvas to see if the issue persisted and it did, so this is what I did:

Added a symbol to a blank HTML5 canvas, made it a Movie Clip and drew a circle. I called the instance mcThing

In the Timeline, I selected the first frame and went into Actions

I wrote:

```<code>function playAnimation() {
    TweenMax.to(this.mcThing, 3, {y:500});
}
playAnimation();
</code>```

When testing in Chrome, I get cannot tween a null object. If I reference it as mcThing (omitting the this. I instead get mcThing is not defined.

If I then remove the function and just have this:

```<code>TweenMax.to(this.mcThing, 3, {y:500});
</code>```

It plays fine, but now I can't call it when I need to.

Some context:

Essentially what I currently have is a WebSocket listening for messages. When it receives a message, it's added to the queue. I am trying to get it to play an animation and insert the text from that message. The text itself should be okay: I used CreateJS to instantiate a text in the code and TweenMax works there, the problem is animating shapes/drawings. I suppose I could instantiate all the shapes in the code itself and TweenMax would work then but I don't think this is realistic as the animation/shapes are fairly complex, so I'm trying to target the stage. The animation would play out, stop, then the message would be removed from the queue and the next one would play (same animation, different text).

I think this is a scope issue, but I'm not sure what I need to change. Any help would be much appreciated!

答:
This issue is because of the scope. Your playAnimation is not scoped to this, so it is called in the global scope.

Try this:

```<code>this.playAnimation = function() {
    TweenMax.to(this.mcThing, 3, {y:500});
}
this.playAnimation();
</code>```

Putting your mcThing into the function scope would also work:

```<code>var thing = this.mcThing;
function playAnimation() {
    TweenMax.to(thing, 3, {y:500});
}
playAnimation();
</code>```

Or you could scope the function call itself!

```<code>function playAnimation() {
    TweenMax.to(this.mcThing, 3, {y:500});
}
playAnimation.call(this);
</code>```

There are lots of ways to get around it once you understand how the scoping works. I recommend the first approach.

Hope that helps!

Body:
I'm an HTML5 newbie and I was wondering if someone could tell me what I'm doing wrong here. I would like to be able to use GSAP to animate a vector file I'd add to the stage and would need to be able to make it animate when I call a function, however when I try to do this I keep getting cannot tween a null object, but if it's not wrapped in a function the animation plays fine.

I created a new HTML5 canvas to see if the issue persisted and it did, so this is what I did:

Added a symbol to a blank HTML5 canvas, made it a Movie Clip and drew a circle. I called the instance mcThing

In the Timeline, I selected the first frame and went into Actions

I wrote:

function playAnimation() {
    TweenMax.to(this.mcThing, 3, {y:500});
}
playAnimation();

When testing in Chrome, I get cannot tween a null object. If I reference it as mcThing (omitting the this. I instead get mcThing is not defined.

If I then remove the function and just have this:

TweenMax.to(this.mcThing, 3, {y:500});

It plays fine, but now I can't call it when I need to.

Some context:

Essentially what I currently have is a WebSocket listening for messages. When it receives a message, it's added to the queue. I am trying to get it to play an animation and insert the text from that message. The text itself should be okay: I used CreateJS to instantiate a text in the code and TweenMax works there, the problem is animating shapes/drawings. I suppose I could instantiate all the shapes in the code itself and TweenMax would work then but I don't think this is realistic as the animation/shapes are fairly complex, so I'm trying to target the stage. The animation would play out, stop, then the message would be removed from the queue and the next one would play (same animation, different text).

I think this is a scope issue, but I'm not sure what I need to change. Any help would be much appreciated!

Body:
This issue is because of the scope. Your playAnimation is not scoped to this, so it is called in the global scope.

Try this:

this.playAnimation = function() {
    TweenMax.to(this.mcThing, 3, {y:500});
}
this.playAnimation();

Putting your mcThing into the function scope would also work:

var thing = this.mcThing;
function playAnimation() {
    TweenMax.to(thing, 3, {y:500});
}
playAnimation();

Or you could scope the function call itself!

function playAnimation() {
    TweenMax.to(this.mcThing, 3, {y:500});
}
playAnimation.call(this);

There are lots of ways to get around it once you understand how the scoping works. I recommend the first approach.

Hope that helps!


问:
Navigation Controller back button is not releasing memory of dismissed viewController
Newbie question here.
Imagine a very basic storyboard with 2 vc (A and B).
A is embedded in a navController. A has a collectionView showing a grid of images. B is displaying the clicked grid item in big. So simple list->detail.

Doing all with IB, I ctrl-dragged from collectionView cell item to B and selected 'show (e.g Push)' segue.

Now when I run the app and click multiple times on image in grid and then on '< Back' button, I explore the memory graph.
I can see 10 'B' view controllers if I did the navigation 10 times.

That causes a lot of memory to be used and it grows every time.

I found a few posts speaking about unwind, and pop to root vc, but all are dealing with programmatic navigation. Here's just the case of simple storyboard done all with IB.

Expected: A->B->A. Memory: A

Reality: A->B->A. Memory: A, B

How can I avoid retaining the memory for those vc that are dismissed?

in A I have:

```<code>override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if segue.identifier == "dreamDetail" {
        let newViewController = segue.destination as! DreamDetailViewController
        newViewController.dream = allDreams?[(collectionView.indexPathsForSelectedItems?.first?.item)!]
        newViewController.dreams = allDreams
    }
}
</code>```

in B I have:

```<code>weak var dream: DreamRealm?{
    didSet {
    }
}

var dreams: [DreamRealm]?{
    didSet {
    }
}
</code>```

DreamRealm is just a Realm model.

```<code>class DreamRealm: Object {

@objc dynamic var filename: String? = nil
@objc dynamic var path = ""
</code>```

答:
All IB connections with UI elements(in view controller) must be weak!

Try to release strong objects in dealloc method;

Sometimes there are some delay before garbage collector deallocate objects,  do "show" and "back", wait ~10 seconds and see if more memory are released.

Body:
Newbie question here.
Imagine a very basic storyboard with 2 vc (A and B).
A is embedded in a navController. A has a collectionView showing a grid of images. B is displaying the clicked grid item in big. So simple list->detail.

Doing all with IB, I ctrl-dragged from collectionView cell item to B and selected 'show (e.g Push)' segue.

Now when I run the app and click multiple times on image in grid and then on '< Back' button, I explore the memory graph.
I can see 10 'B' view controllers if I did the navigation 10 times.

That causes a lot of memory to be used and it grows every time.

I found a few posts speaking about unwind, and pop to root vc, but all are dealing with programmatic navigation. Here's just the case of simple storyboard done all with IB.

Expected: A->B->A. Memory: A

Reality: A->B->A. Memory: A, B

How can I avoid retaining the memory for those vc that are dismissed?

in A I have:

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if segue.identifier == "dreamDetail" {
        let newViewController = segue.destination as! DreamDetailViewController
        newViewController.dream = allDreams?[(collectionView.indexPathsForSelectedItems?.first?.item)!]
        newViewController.dreams = allDreams
    }
}

in B I have:

weak var dream: DreamRealm?{
    didSet {
    }
}

var dreams: [DreamRealm]?{
    didSet {
    }
}

DreamRealm is just a Realm model.

class DreamRealm: Object {

@objc dynamic var filename: String? = nil
@objc dynamic var path = ""


问:
Is node.js ready for production use?
Starting a new project.  It's basically a blogging/commenting system.

We're considering node.js as the back end server. Is node.js ready for this sort of thing or is it too early and experimental?

We need HTTPS and gzip compression - perhaps a front end nginx server could provide this?

What's missing from node.js that would make developing a web app difficult?

From a production ready perspective, we're wondering if it is stable enough for building a commercial app on top of.

Thanks

答:
It's still got some rough edges, but I'd say it's ready to use (I'm about to launch a production site based on it). Here's an article describing how 3 companies are using it in production.

You may still find yourself finding/fixing the occasional bug, but that's where the community really shines.

Title: Is node.js ready for production use?


问:
CodePen issue with Bootstrap 4
Having a problem with CodePen and Bootstrap 4 , won't render a simple button, yet grid works fine:

 <button type="button" class="btn btn-primary">Primary</button>```

Any help?

https://codepen.io/klasap/pen/OOjVep

答:
This is because you're only pulling in the grid element of the Bootstrap CSS. It would seem that CodePen's existing BS4 is picking the wrong Bootstrap file.

In your pen

https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.0.0-beta.2/css/bootstrap-grid.css

Use this CDN of the full Bootstrap instead:

https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css

Title: CodePen issue with Bootstrap 4

Body:
Having a problem with CodePen and Bootstrap 4 , won't render a simple button, yet grid works fine:

 <button type="button" class="btn btn-primary">Primary</button>

Any help?

https://codepen.io/klasap/pen/OOjVep


问:
Unexpected value 'DataTablesModule' imported by the module 'AppModule'. Please add a @NgModule annotation
I am new to Angular Data tables and I am trying to implement Angular Data tables by following the instructions given in the link https://l-lin.github.io/angular-datatables/#/getting-started

after following the instructions when I try to run the application using Angular CLI  I am getting  Uncaught Error: Unexpected value 'DataTablesModule' imported by the module 'AppModule'. Please add a @NgModule annotation.

Note: I have added DataTablesModule in my app.module.ts as shown below

```<code>import { ActionComponent } from './action/action.component';
import { SearchfilterPipe } from './search/searchfilter.pipe';
import { DataTablesModule } from 'angular-datatables';

@NgModule({
declarations: [
AppComponent,
routingComponents,
LicenseComponent,
HeaderComponent,
ActionComponent,
FooterComponent,
SearchfilterPipe

],
imports: [
BrowserModule,
HttpModule,
FormsModule,
DataTablesModule,
AppRoutingModule,
NgbModule.forRoot()
],
providers: [HttpModule],
bootstrap: [AppComponent]
})
export class AppModule { }
</code>```

and in .angular-cli.json I have added the below code

```<code>{
"apps": [
{
  ...
  "styles": [
    "../node_modules/datatables.net-dt/css/jquery.dataTables.css"
  ],
  "scripts": [
    "../node_modules/jquery/dist/jquery.js",
    "../node_modules/datatables.net/js/jquery.dataTables.js"
  ],
  ...
 }
 ]
 }
</code>```

I am using the below provided versions.

@angular/cli: 1.1.0

 node: 8.0.0

  @angular/compiler: 4.2.3

 @angular/core: 4.2.6

 @angular/compiler-cli: 4.2.3

Not understanding why exactly my application is crashing.Any Inputs/Suggestions will be highly appreciated.

答:
You can run in aot

```<code>ng serve --aot
</code>```

or use the --preserve-links option

```<code>ng serve --preserve-symlinks
</code>```

Body:
I am new to Angular Data tables and I am trying to implement Angular Data tables by following the instructions given in the link https://l-lin.github.io/angular-datatables/#/getting-started

after following the instructions when I try to run the application using Angular CLI  I am getting  Uncaught Error: Unexpected value 'DataTablesModule' imported by the module 'AppModule'. Please add a @NgModule annotation.

Note: I have added DataTablesModule in my app.module.ts as shown below

import { ActionComponent } from './action/action.component';
import { SearchfilterPipe } from './search/searchfilter.pipe';
import { DataTablesModule } from 'angular-datatables';

@NgModule({
declarations: [
AppComponent,
routingComponents,
LicenseComponent,
HeaderComponent,
ActionComponent,
FooterComponent,
SearchfilterPipe

],
imports: [
BrowserModule,
HttpModule,
FormsModule,
DataTablesModule,
AppRoutingModule,
NgbModule.forRoot()
],
providers: [HttpModule],
bootstrap: [AppComponent]
})
export class AppModule { }

and in .angular-cli.json I have added the below code

{
"apps": [
{
  ...
  "styles": [
    "../node_modules/datatables.net-dt/css/jquery.dataTables.css"
  ],
  "scripts": [
    "../node_modules/jquery/dist/jquery.js",
    "../node_modules/datatables.net/js/jquery.dataTables.js"
  ],
  ...
 }
 ]
 }

I am using the below provided versions.

@angular/cli: 1.1.0

 node: 8.0.0

  @angular/compiler: 4.2.3

 @angular/core: 4.2.6

 @angular/compiler-cli: 4.2.3

Not understanding why exactly my application is crashing.Any Inputs/Suggestions will be highly appreciated.

Body:
You can run in aot

ng serve --aot

or use the --preserve-links option

ng serve --preserve-symlinks


问:
How to use enums with JPA
I have an existing database of a film rental system. Each film has a has a rating attribute. In SQL they used a constraint to limit the allowed values of this attribute.

```<code>CONSTRAINT film_rating_check CHECK
    ((((((((rating)::text = ''::text) OR
          ((rating)::text = 'G'::text)) OR
          ((rating)::text = 'PG'::text)) OR
          ((rating)::text = 'PG-13'::text)) OR
          ((rating)::text = 'R'::text)) OR
          ((rating)::text = 'NC-17'::text)))
</code>```

I think it would be nice to use a Java enum to map the constraint into the object world. But it's not possible to simply take the allowed values because of the special char in "PG-13" and "NC-17". So I implemented the following enum:

```<code>public enum Rating {

    UNRATED ( "" ),
    G ( "G" ),
    PG ( "PG" ),
    PG13 ( "PG-13" ),
    R ( "R" ),
    NC17 ( "NC-17" );

    private String rating;

    private Rating(String rating) {
        this.rating = rating;
    }

    @Override
    public String toString() {
        return rating;
    }
}

@Entity
public class Film {
    ..
    @Enumerated(EnumType.STRING)
    private Rating rating;
    ..
</code>```

With the toString() method the direction enum -> String works fine, but String -> enum does not work. I get the following exception:

[TopLink Warning]: 2008.12.09
  01:30:57.434--ServerSession(4729123)--Exception [TOPLINK-116] (Oracle
  TopLink Essentials - 2.0.1 (Build b09d-fcs (12/06/2007))):
  oracle.toplink.essentials.exceptions.DescriptorException Exception
  Description: No conversion value provided for the value [NC-17] in
  field [FILM.RATING]. Mapping:
  oracle.toplink.essentials.mappings.DirectToFieldMapping[rating-->FILM.RATING]
  Descriptor: RelationalDescriptor(de.fhw.nsdb.entities.Film -->
  [DatabaseTable(FILM)])

cheers

timo

答:
Enum
public enum ParentalControlLevelsEnum {
    U("U"), PG("PG"), _12("12"), _15("15"), _18("18");

```<code>private final String value;

ParentalControlLevelsEnum(final String value) {
    this.value = value;
}

public String getValue() {
    return value;
}

public static ParentalControlLevelsEnum fromString(final String value) {
    for (ParentalControlLevelsEnum level : ParentalControlLevelsEnum.values()) {
        if (level.getValue().equalsIgnoreCase(value)) {
            return level;
        }
    }
    return null;
}
</code>```

}

compare -> Enum

public class RatingComparator implements Comparator {

```<code>public int compare(final ParentalControlLevelsEnum o1, final ParentalControlLevelsEnum o2) {
    if (o1.ordinal() < o2.ordinal()) {
        return -1;
    } else {
        return 1;
    }
}
</code>```

}

Title: How to use enums with JPA

Body:
I have an existing database of a film rental system. Each film has a has a rating attribute. In SQL they used a constraint to limit the allowed values of this attribute.

CONSTRAINT film_rating_check CHECK
    ((((((((rating)::text = ''::text) OR
          ((rating)::text = 'G'::text)) OR
          ((rating)::text = 'PG'::text)) OR
          ((rating)::text = 'PG-13'::text)) OR
          ((rating)::text = 'R'::text)) OR
          ((rating)::text = 'NC-17'::text)))

I think it would be nice to use a Java enum to map the constraint into the object world. But it's not possible to simply take the allowed values because of the special char in "PG-13" and "NC-17". So I implemented the following enum:

public enum Rating {

    UNRATED ( "" ),
    G ( "G" ),
    PG ( "PG" ),
    PG13 ( "PG-13" ),
    R ( "R" ),
    NC17 ( "NC-17" );

    private String rating;

    private Rating(String rating) {
        this.rating = rating;
    }

    @Override
    public String toString() {
        return rating;
    }
}

@Entity
public class Film {
    ..
    @Enumerated(EnumType.STRING)
    private Rating rating;
    ..

With the toString() method the direction enum -> String works fine, but String -> enum does not work. I get the following exception:

[TopLink Warning]: 2008.12.09
  01:30:57.434--ServerSession(4729123)--Exception [TOPLINK-116] (Oracle
  TopLink Essentials - 2.0.1 (Build b09d-fcs (12/06/2007))):
  oracle.toplink.essentials.exceptions.DescriptorException Exception
  Description: No conversion value provided for the value [NC-17] in
  field [FILM.RATING]. Mapping:
  oracle.toplink.essentials.mappings.DirectToFieldMapping[rating-->FILM.RATING]
  Descriptor: RelationalDescriptor(de.fhw.nsdb.entities.Film -->
  [DatabaseTable(FILM)])

cheers

timo

Body:
Enum
public enum ParentalControlLevelsEnum {
    U("U"), PG("PG"), _12("12"), _15("15"), _18("18");

private final String value;

ParentalControlLevelsEnum(final String value) {
    this.value = value;
}

public String getValue() {
    return value;
}

public static ParentalControlLevelsEnum fromString(final String value) {
    for (ParentalControlLevelsEnum level : ParentalControlLevelsEnum.values()) {
        if (level.getValue().equalsIgnoreCase(value)) {
            return level;
        }
    }
    return null;
}

}

compare -> Enum

public class RatingComparator implements Comparator {

public int compare(final ParentalControlLevelsEnum o1, final ParentalControlLevelsEnum o2) {
    if (o1.ordinal() < o2.ordinal()) {
        return -1;
    } else {
        return 1;
    }
}

}


问:
How do I read this text file and Insert into MySQL?
sample

```<code>user id  User Name
   U456      Mathew
   U457      Leon
   U458      Cris
   U459      Yancy
   U460      Jane
</code>```

and so on up to 500k.

I need to read this text file and insert to MySQL  in two columns say User ID and User Name. How do I do this in PHP?

答:
Depends. If the two fields are separated using a TAB character, then fgetcsv($f,1000,"\t") would work to read in each line. Otherwise use substr() if it's a fixed width column text file to split up the fields (apply trim() eventually).

Loop over the rows and fields, and use your database interface of choice:

```<code>db("INSERT INTO tbl (user_id, user_name) VALUES (?,?)", $row);
</code>```

Body:
sample

user id  User Name
   U456      Mathew
   U457      Leon
   U458      Cris
   U459      Yancy
   U460      Jane

and so on up to 500k.

I need to read this text file and insert to MySQL  in two columns say User ID and User Name. How do I do this in PHP?

Body:
Depends. If the two fields are separated using a TAB character, then fgetcsv($f,1000,"\t") would work to read in each line. Otherwise use substr() if it's a fixed width column text file to split up the fields (apply trim() eventually).

Loop over the rows and fields, and use your database interface of choice:

db("INSERT INTO tbl (user_id, user_name) VALUES (?,?)", $row);


问:
OpenCV - Open an XML file from C++ to Python
I'm working on a project to improve my skill in OpenCV and since I'm new, I lack a lot of knowledge. In my project, I've detected faces on images, cropped the face area, converted it to grayscale, used LBPs and calculated the LBP image's histogram with calcHist.

I've saved all these histograms using FileStorage as .xlm files. All of the above, using C++ on Visual Studio. Now I have some code with machine learning algorithms like SVM, Neural Network, knn etc. But all this code is in Python 3.

The next step I have in mind, is to take all these .xml files and load them on a Python script, again using OpenCV to use them, but I just can't manage to do it in the last couple of days.

The most simple thing I've tried to test it (from a post made July 2017):

```<code>import cv2

fs = cv2.FileStorage("aa048t2aaunaff001.png_olbp.xml", cv2.FILE_STORAGE_READ)

fn = fs.getNode("Camera_Matrix")
print (fn.mat())
</code>```

Problems here:

1. fs doesn't have a member "getNode". Did I do something wrong with an installation here?
 2. Printing outputs "None".

XML file to load: https://drive.google.com/open?id=0B2TTkSDC13uQRk8tZlgxengzNW8

OpenCV: 3.3.0, Python: 3.6.2

Couldn't find anything else that worked, so I posted the simplest thing I've tried. Thanks for reading, any help is appreciated.

答:
Since my post was answered about 3 months ago but no official answer was provided, I will answer my own question.

I successfully opened the file I wanted but I tried to access a matrix that didn't exist. I changed fn = fs.getNode("Camera_Matrix") to fn = fs.getNode("my_histrogram") and OpenCV successfully loaded the histogram.

Body:
I'm working on a project to improve my skill in OpenCV and since I'm new, I lack a lot of knowledge. In my project, I've detected faces on images, cropped the face area, converted it to grayscale, used LBPs and calculated the LBP image's histogram with calcHist.

I've saved all these histograms using FileStorage as .xlm files. All of the above, using C++ on Visual Studio. Now I have some code with machine learning algorithms like SVM, Neural Network, knn etc. But all this code is in Python 3.

The next step I have in mind, is to take all these .xml files and load them on a Python script, again using OpenCV to use them, but I just can't manage to do it in the last couple of days.

The most simple thing I've tried to test it (from a post made July 2017):

import cv2

fs = cv2.FileStorage("aa048t2aaunaff001.png_olbp.xml", cv2.FILE_STORAGE_READ)

fn = fs.getNode("Camera_Matrix")
print (fn.mat())

Problems here:

1. fs doesn't have a member "getNode". Did I do something wrong with an installation here?
 2. Printing outputs "None".

XML file to load: https://drive.google.com/open?id=0B2TTkSDC13uQRk8tZlgxengzNW8

OpenCV: 3.3.0, Python: 3.6.2

Couldn't find anything else that worked, so I posted the simplest thing I've tried. Thanks for reading, any help is appreciated.


问:
how to remove Android Studio background line?
I've used android studio today, and I can't remove the background line:

How do I remove this line?

答:
Android Studio 3.0 on os x:

Preference -> Editor -> General -> Appearance -> Show Right Margin


问:
Is it any value of adding one script file to BundleCollection?
I am designing a very big application now and i want to make good infrastructure for the future.

In Razor (MVC) there is an option to include javascript files in a view by using the function @Scripts.Render("~/Scripts/myscript.js") by specify a specific file or bundle item from BundleCollection which defined in BundleConfig.cs.

I am wondering, is there any added value to define a bundle item in the Scripts.Render function of only single file instead of specify the script file itself?

one of added value i found is that in the long run i will be able to add more files to the bundle as needed without changing the views that using it and i will enjoy the optimization. but i couldn't find added value for that while i am still using one js file in the "bundle".

答:
There is a couple of benefits actually apart from the one you have mentioned:

Bundles are minified in release mode. When you add a file to the bundle (even a single file) and reference the bundle in the view the code will be minified. It's not the case when you reference the file directly. That's most probably what you're going for in production.

The framework generates and appends a random hash to the script with every new version of the bundle to invalidate the cache of the previous bundles. It looks something like this . Your clients will thank you for this after every new release. And again - it doesn't happen if you reference the file directly unless you generate and append the versions manually.

So what I usually do, and I consider it a good practice until I'm proven wrong, I create a bundle for every page specific needs even if it consists of a single js file with a tiny module. For example Home page:

bundles.Add(new ScriptBundle("~/bundles/home").Include("~/Scripts/home.js"));
@Scripts.Render("~/bundles/home")

Body:
There is a couple of benefits actually apart from the one you have mentioned:

Bundles are minified in release mode. When you add a file to the bundle (even a single file) and reference the bundle in the view the code will be minified. It's not the case when you reference the file directly. That's most probably what you're going for in production.

The framework generates and appends a random hash to the script with every new version of the bundle to invalidate the cache of the previous bundles. It looks something like this <script src="/bundles/myscript.js?v=CQJxkNd9QnrvutTyUG9mM-vD0FrbCc1"></script>. Your clients will thank you for this after every new release. And again - it doesn't happen if you reference the file directly unless you generate and append the versions manually.

So what I usually do, and I consider it a good practice until I'm proven wrong, I create a bundle for every page specific needs even if it consists of a single js file with a tiny module. For example Home page:

bundles.Add(new ScriptBundle("~/bundles/home").Include("~/Scripts/home.js"));
@Scripts.Render("~/bundles/home")


问:
Jenkins Content Security Policy
I'm confused about Jenkins Content Security Policy.

I know these sites:

Configuring Content Security Policy

Content Security Policy Reference

I have a html page shown via Jenkins Clover Plugin. This html page uses inline style, e.g.:

```<code><div class='greenbar' style='width:58px'>
</code>```

The div-element visualizes a progressbar.
Using the default Jenkins CSP configuration leads to the following result:
Progressbar_FAIL

The result i want to have looks like this:
Progressbar_WORKS

I tried to relax the CSP rules, adding different combinations of parameters (script-src, style-src) with different levels (self, unsafe-inline,..) but nothing works.

So my questions for now:

Where do i have to specify the CSP configuration?

Is it possible to use inline styles?

Where should the styles be located? My css-stylesheets are located local on the Jenkins Server.

What is the best way to get inline style and CSP rules "satisfied"

Update

1. Try:
-Dhudson.model.DirectoryBrowserSupport.CSP="default-src 'self'
in the jenkins.xml file. Then the following error occurs:

Refused to apply inline style because it violates the following
  Content Security Policy directive: "default-src 'self'". Either the
  'unsafe-inline' keyword, a hash ('sha256-'), or a nonce
  ('nonce-...') is required to enable inline execution. Note also that
  'style-src' was not explicitly set, so 'default-src' is used as a
  fallback.

2. Try
-Dhudson.model.DirectoryBrowserSupport.CSP="default-src 'self'; style-src 'self' in the jenkins.xml file. Then the following error occurs:

Refused to apply inline style because it violates the following
  Content Security Policy directive: "style-src 'self'". Either the
  'unsafe-inline' keyword, a hash
  ('sha256-'), or a nonce
  ('nonce-...') is required to enable inline execution

I understand that this try can not solve my problem, because default-src includes style-src

3. Try
-Dhudson.model.DirectoryBrowserSupport.CSP="default-src 'self'; style-src 'unsafe-inline' in the jenkins.xml file. Then the following error occurs:

Refused to load the stylesheet
  s://jenkins/andsomedir/stylesheet.css [its https://... not allowed to post more than two links :(]
  because it violates the following Content Security Policy directive:
  "style-src 'unsafe-inline'".

答:
To add more to the @Kirill's answer ...

If jenkins is deployed in tomcat container, set the CATALINA_OPTS environment value in setenv.sh file ( Present in ${CATALINA_BASE}/bin Folder ) as highlighted below:-

```<code>export CATALINA_OPTS="-Xmx2048m -Xms2048m -XX:MaxNewSize=768m -XX:-HeapDumpOnOutOfMemoryError -XX:HeapDumpPath=${CATALINA_BASE}/logs/java.hprof -XX:ParallelGCThreads=2 -XX:-UseConcMarkSweepGC -Dcom.sun.management.jmxremote -Dhudson.model.DirectoryBrowserSupport.CSP=\"\"
</code>```

or

```<code>export CATALINA_OPTS="-Xmx2048m -Xms2048m -XX:MaxNewSize=768m -XX:-HeapDumpOnOutOfMemoryError -XX:HeapDumpPath=/software/jenkins/tomcat_jenkins/logs/java.hprof -XX:ParallelGCThreads=2 -XX:-UseConcMarkSweepGC -Dcom.sun.management.jmxremote -Dhudson.model.DirectoryBrowserSupport.CSP=\"sandbox allow-scripts; default-src 'self'; script-src *; 'unsafe-eval'; img-src *; style-src *; 'unsafe-inline'; font-src *;\
</code>```

After Changing the above file, restart the tomcat. It worked like charm to me. Hope it helps :)

Note:- CSP is only applicable for the plugins like HTML publisher, maven plugin . It didn't work for email html file.

Title: Jenkins Content Security Policy

Body:
I'm confused about Jenkins Content Security Policy.

I know these sites:

Configuring Content Security Policy

Content Security Policy Reference

I have a html page shown via Jenkins Clover Plugin. This html page uses inline style, e.g.:

The div-element visualizes a progressbar.
Using the default Jenkins CSP configuration leads to the following result:
Progressbar_FAIL

The result i want to have looks like this:
Progressbar_WORKS

I tried to relax the CSP rules, adding different combinations of parameters (script-src, style-src) with different levels (self, unsafe-inline,..) but nothing works.

So my questions for now:

Where do i have to specify the CSP configuration?

Is it possible to use inline styles?

Where should the styles be located? My css-stylesheets are located local on the Jenkins Server.

What is the best way to get inline style and CSP rules "satisfied"

Update

1. Try:
-Dhudson.model.DirectoryBrowserSupport.CSP="default-src 'self'
in the jenkins.xml file. Then the following error occurs:

Refused to apply inline style because it violates the following
  Content Security Policy directive: "default-src 'self'". Either the
  'unsafe-inline' keyword, a hash ('sha256-'), or a nonce
  ('nonce-...') is required to enable inline execution. Note also that
  'style-src' was not explicitly set, so 'default-src' is used as a
  fallback.

2. Try
-Dhudson.model.DirectoryBrowserSupport.CSP="default-src 'self'; style-src 'self' in the jenkins.xml file. Then the following error occurs:

Refused to apply inline style because it violates the following
  Content Security Policy directive: "style-src 'self'". Either the
  'unsafe-inline' keyword, a hash
  ('sha256-'), or a nonce
  ('nonce-...') is required to enable inline execution

I understand that this try can not solve my problem, because default-src includes style-src

3. Try
-Dhudson.model.DirectoryBrowserSupport.CSP="default-src 'self'; style-src 'unsafe-inline' in the jenkins.xml file. Then the following error occurs:

Refused to load the stylesheet
  s://jenkins/andsomedir/stylesheet.css [its https://... not allowed to post more than two links :(]
  because it violates the following Content Security Policy directive:
  "style-src 'unsafe-inline'".

Body:
To add more to the @Kirill's answer ...

If jenkins is deployed in tomcat container, set the CATALINA_OPTS environment value in setenv.sh file ( Present in ${CATALINA_BASE}/bin Folder ) as highlighted below:-

export CATALINA_OPTS="-Xmx2048m -Xms2048m -XX:MaxNewSize=768m -XX:-HeapDumpOnOutOfMemoryError -XX:HeapDumpPath=${CATALINA_BASE}/logs/java.hprof -XX:ParallelGCThreads=2 -XX:-UseConcMarkSweepGC -Dcom.sun.management.jmxremote -Dhudson.model.DirectoryBrowserSupport.CSP=\"\"

or

export CATALINA_OPTS="-Xmx2048m -Xms2048m -XX:MaxNewSize=768m -XX:-HeapDumpOnOutOfMemoryError -XX:HeapDumpPath=/software/jenkins/tomcat_jenkins/logs/java.hprof -XX:ParallelGCThreads=2 -XX:-UseConcMarkSweepGC -Dcom.sun.management.jmxremote -Dhudson.model.DirectoryBrowserSupport.CSP=\"sandbox allow-scripts; default-src 'self'; script-src *; 'unsafe-eval'; img-src *; style-src *; 'unsafe-inline'; font-src *;\

After Changing the above file, restart the tomcat. It worked like charm to me. Hope it helps :)

Note:- CSP is only applicable for the plugins like HTML publisher, maven plugin . It didn't work for email html file.