答:
You will always see that flash until you move your gapi.load method into a higher component. The function it calls is a promise, so that means your component will continue to render while that function is being requested. I would move just that piece into it's own component one level higher, and have your login page be a child of that component.

EDIT:

Here's an example:

```<code>class AuthUser extends React.Component {
    constructor(props){
        super(props);
        this.state = {
            redirect: false
            loaded: false
        }
        this.onSignIn = this.onSignIn.bind(this)
        this.updateRedirect = this.updateRedirect.bind(this)
        // this.test = this.test.bind(this)
    }

    onSignIn(googleUser) {
        console.log('this ran')
        var profile = googleUser.getBasicProfile();
        console.log('ID: ' + profile.getId()); // Do not send to your backend! Use an ID token instead.
        console.log('Name: ' + profile.getName());
        console.log('Image URL: ' + profile.getImageUrl());
        console.log('Email: ' + profile.getEmail()); // This is null if the 'email' scope is not present.
        this.updateRedirect()
    }
    componentWillMount() {
        console.log('componentWillMount ran')
        gapi.load('auth2', () => {
            gapi.auth2.init({
                client_id: '817677528939-dss5sreclldv1inb26tb3tueac98d24r'
            }).then((auth2) => {
                console.log( "signed in: " + auth2.isSignedIn.get())
                this.setState({
                    redirect: auth2.isSignedIn.get(),
                    loaded: true
                })
            })
        })
    }
    componentDidMount() {
        gapi.signin2.render('my-signin2', {
            'scope': 'profile email',
            'width': 300,
            'height': 50,
            'longtitle': true,
            'theme': 'dark',
            'onsuccess': this.onSignIn,
        });
    }
    updateRedirect() {
        this.setState({
            redirect: true
        });
    }
    render() {
        if(!this.state.loaded) {
            return null
        }
        return this.state.redirect ? <Redirect to='/options' /> : <SignIn />;
    }
}

class SignIn extends React.Component{
    render() {
        return (
            <div>
                <AppBar title="Pliny" showMenuIconButton={false} zDepth={2} />
                <div id="my-signin2"></div>
            </div>
        )
    }
}
</code>```

So now, the <SignIn /> component won't be rendered until AFTER the auth requests have finished AND the user isn't being redirected.

Body:
This is the full error:

index.js:2177 Warning: Can only update a mounted or mounting component. This usually means you called setState, replaceState, or forceUpdate on an unmounted component. This is a no-op.

What does it mean? What am I doing that is generating the error?

This is my login page:

/* global gapi */

class SignIn extends React.Component{

    constructor(props){
        super(props);
        this.state = {
            redirect: false

        }
        this.onSignIn = this.onSignIn.bind(this)
        this.updateRedirect = this.updateRedirect.bind(this)
        // this.test = this.test.bind(this)
    }

     componentWillMount() {
        console.log('componentWillMount ran')
        gapi.load('auth2', () => {
            gapi.auth2.init({
                client_id: '817677528939-dss5sreclldv1inb26tb3tueac98d24r'
            }).then((auth2) => {
                console.log( "signed in: " + auth2.isSignedIn.get())
                this.setState({
                    redirect: auth2.isSignedIn.get()
                })
            })
        })
    }

    updateRedirect() {
        this.setState({
            redirect: true
        })
    }

    componentDidMount() {
        gapi.signin2.render('my-signin2', {
            'scope': 'profile email',
            'width': 300,
            'height': 50,
            'longtitle': true,
            'theme': 'dark',
            'onsuccess': this.onSignIn,
        });
    }

    onSignIn(googleUser) {
        console.log('this ran')
        var profile = googleUser.getBasicProfile();
        console.log('ID: ' + profile.getId()); // Do not send to your backend! Use an ID token instead.
        console.log('Name: ' + profile.getName());
        console.log('Image URL: ' + profile.getImageUrl());
        console.log('Email: ' + profile.getEmail()); // This is null if the 'email' scope is not present.
        this.updateRedirect()
    }

    render() {
        return (
            this.state.redirect ?
            <Redirect to='/options' />
            :

                <AppBar title="Pliny" showMenuIconButton={false} zDepth={2} />

        )
    }
}

export default SignIn

For some reason when the page loads, it is loading the

 for a split second before re-routing. So the user sees the login page flash on the screen and then routed to the correct page.

Is there a way to have it re-route before anything else on the page loads?

Ideally, I'd like to check to see if a user is logged in, and if so, immediately route him to a specific page. If the user isn't logged in, then show them the login page (the
)

Body:
You will always see that flash until you move your gapi.load method into a higher component. The function it calls is a promise, so that means your component will continue to render while that function is being requested. I would move just that piece into it's own component one level higher, and have your login page be a child of that component.

EDIT:

Here's an example:

class AuthUser extends React.Component {
    constructor(props){
        super(props);
        this.state = {
            redirect: false
            loaded: false
        }
        this.onSignIn = this.onSignIn.bind(this)
        this.updateRedirect = this.updateRedirect.bind(this)
        // this.test = this.test.bind(this)
    }

    onSignIn(googleUser) {
        console.log('this ran')
        var profile = googleUser.getBasicProfile();
        console.log('ID: ' + profile.getId()); // Do not send to your backend! Use an ID token instead.
        console.log('Name: ' + profile.getName());
        console.log('Image URL: ' + profile.getImageUrl());
        console.log('Email: ' + profile.getEmail()); // This is null if the 'email' scope is not present.
        this.updateRedirect()
    }
    componentWillMount() {
        console.log('componentWillMount ran')
        gapi.load('auth2', () => {
            gapi.auth2.init({
                client_id: '817677528939-dss5sreclldv1inb26tb3tueac98d24r'
            }).then((auth2) => {
                console.log( "signed in: " + auth2.isSignedIn.get())
                this.setState({
                    redirect: auth2.isSignedIn.get(),
                    loaded: true
                })
            })
        })
    }
    componentDidMount() {
        gapi.signin2.render('my-signin2', {
            'scope': 'profile email',
            'width': 300,
            'height': 50,
            'longtitle': true,
            'theme': 'dark',
            'onsuccess': this.onSignIn,
        });
    }
    updateRedirect() {
        this.setState({
            redirect: true
        });
    }
    render() {
        if(!this.state.loaded) {
            return null
        }
        return this.state.redirect ? <Redirect to='/options' /> : <SignIn />;
    }
}

class SignIn extends React.Component{
    render() {
        return (
            <div>
                <AppBar title="Pliny" showMenuIconButton={false} zDepth={2} />
                <div id="my-signin2"></div>
            </div>
        )
    }
}

So now, the <SignIn /> component won't be rendered until AFTER the auth requests have finished AND the user isn't being redirected.


来源: stackexchange

问:
Is it good practice in Android to implement our own back button rather than using device's backbutton

Is it good practice in Android to implement our own back button rather than using device's backbutton. May I know what are the disadvantages of using our own back button in Application rather than device provided one.

Thanks in Advance,

答: As a user myself, I find it intuitive to use the back button because it is in use in all major applications. Futhermore, I find that adding another back button to serve the same function is a waste of screen real estate (and this is usually something you like to spare).</p>

ContentLicense: CC BY-SA 2.5


问:
SQL - alternative to UNION - JOIN possible?
This query does not perform well.  I want to know if this can be done in fewer CTEs and / or without a UNION.</p>

```<code>WITH SourceOutputNodes
              AS (
              SELECT t.p.value('@OutputNodeID', 'uniqueidentifier') AS OutputNodeID,
                     t.p.value('@OutputNodeTypeID', 'int') AS OutputNodeTypeID,
                     t.p.value('@OutputTemplateID', 'uniqueidentifier') AS OutputTemplateID,
                     t.p.value('@OutputTemplateBookmarkID', 'uniqueidentifier') AS OutputTemplateBookmarkID,
                     t.p.value('@PublicNodeID', 'uniqueidentifier') AS PublicNodeID,
                     t.p.value('@Name', 'nvarchar(100)') AS Name,
                     t.p.value('@Description', 'nvarchar(300)') AS [Description],
                     t.p.value('@CreatedDate', 'datetime') AS CreatedDate,
                     coalesce(t.p.value('@CreatedByUserID', 'uniqueidentifier'), '00000000-0000-0000-0000-000000000000') AS CreatedByUserID,
                     t.p.value('@DeletedDate', 'datetime') AS DeletedDate,
                     t.p.value('@DeletedByUserID', 'uniqueidentifier') AS DeletedByUserID,
                     t.p.value('@ModifiedByUserID', 'uniqueidentifier') AS ModifiedByUserID,
                     t.p.value('@ModifiedDate', 'datetime') AS ModifiedDate,
                     t.p.value('@IsPublic', 'bit') AS IsPublic,
                     t.p.value('@DisplayOrder', 'int') AS DisplayOrder,
                     t.p.value('@RuleID', 'uniqueidentifier') AS RuleID,
                     t.p.value('@RuleDescription', 'nvarchar(max)') AS RuleDescription,
                     t.p.value('@DataItemID', 'uniqueidentifier') AS DataItemID,
                     t.p.value('@DataItemName', 'nvarchar(100)') AS DataItemName,
                     t.p.value('@DataItemOtherOptions', 'nvarchar(max)') AS DataItemOtherOptions,
                     t.p.value('@OutputDocRepeaterOptionID', 'int') AS OutputDocRepeaterOptionID,
                     t.p.value('@FormOptions', 'nvarchar(max)') AS FormOptions,
                     t.p.value('@FormID', 'uniqueidentifier') AS FormID,
                     t.p.value('@DefaultValue', 'nvarchar(max)') AS DefaultValue,
                     t.p.value('@GenericFieldDefinitionInspectionTypeID', 'uniqueidentifier') AS GenericFieldDefinitionInspectionTypeID,
                     t.p.value('@GenericFieldDefinitionRoleID', 'uniqueidentifier') AS GenericFieldDefinitionRoleID,
                     t.p.value('@PhotoGrid_ImagesToShow', 'nvarchar(50)') AS PhotoGrid_ImagesToShow,
                     t.p.value('@PhotoGrid_NumberColumns', 'int') AS PhotoGrid_NumberColumns,
                     t.p.value('@PhotoGrid_NumberRows', 'int') AS PhotoGrid_NumberRows,
                     t.p.value('@Photo_PublicOnly', 'bit') AS Photo_PublicOnly,
                     t.p.value('@Photo_LabelPosition', 'nvarchar(50)') AS Photo_LabelPosition,
                     t.p.value('@Photo_Number', 'int') AS Photo_Number,
                     t.p.value('@LinkedToNodeID', 'uniqueidentifier') AS LinkedToNodeID,
                     t.p.value('@UseNoPhotoPlaceholder', 'bit') AS UseNoPhotoPlaceholder,
                     t.p.value('@NoPhotoPlaceholderURL', 'nvarchar(max)') AS NoPhotoPlaceholderURL,
                     t.p.value('@Photo_HighlightHazards', 'bit') AS Photo_HighlightHazards,
                     t.p.value('@Photo_Level', 'int') AS Photo_Level,
                     t.p.value('@CommCov_Level', 'int') AS CommCov_Level
              FROM [Promotion].Promotions AS p
                   CROSS APPLY p.OutputsXml.nodes('/Data/Outputs.OutputNodes/Outputs.OutputNodes') t(p)
              WHERE p.PromotionID = 'xxxxx'),--@promotionID),

  OutputNodesNullBookmarks AS (
   SELECT * FROM SourceOutputNodes WHERE OutputTemplateBookmarkID IS NULL
  ),

  OutputNodesMatchingBookmarks AS (
SELECT o.*
FROM SourceOutputNodes o
INNER JOIN [Outputs].[OutputDocTemplateBookmarks] b
ON o.OutputTemplateBookmarkID = b.[OutputDocTemplateBookmarkID]
  ),

  OutputNodes AS (
   SELECT *
   FROM
   OutputNodesNullBookmarks
   UNION
   SELECT *
   FROM
   OutputNodesMatchingBookmarks
  )
  SELECT * FROM OutputNodes
</code>```

答:
I'm not sure about that first CTE, but the second, third and fourth could be combined with an OR in your WHERE clause with a correlated subquery.

```<code>WITH SourceOutputNodes
AS (
    SELECT t.p.value('@OutputNodeID', 'uniqueidentifier') AS OutputNodeID,
        t.p.value('@OutputNodeTypeID', 'int') AS OutputNodeTypeID,
        t.p.value('@OutputTemplateID', 'uniqueidentifier') AS OutputTemplateID,
        t.p.value('@OutputTemplateBookmarkID', 'uniqueidentifier') AS OutputTemplateBookmarkID,
        t.p.value('@PublicNodeID', 'uniqueidentifier') AS PublicNodeID,
        t.p.value('@Name', 'nvarchar(100)') AS NAME,
        t.p.value('@Description', 'nvarchar(300)') AS [Description],
        t.p.value('@CreatedDate', 'datetime') AS CreatedDate,
        coalesce(t.p.value('@CreatedByUserID', 'uniqueidentifier'), '00000000-0000-0000-0000-000000000000') AS CreatedByUserID,
        t.p.value('@DeletedDate', 'datetime') AS DeletedDate,
        t.p.value('@DeletedByUserID', 'uniqueidentifier') AS DeletedByUserID,
        t.p.value('@ModifiedByUserID', 'uniqueidentifier') AS ModifiedByUserID,
        t.p.value('@ModifiedDate', 'datetime') AS ModifiedDate,
        t.p.value('@IsPublic', 'bit') AS IsPublic,
        t.p.value('@DisplayOrder', 'int') AS DisplayOrder,
        t.p.value('@RuleID', 'uniqueidentifier') AS RuleID,
        t.p.value('@RuleDescription', 'nvarchar(max)') AS RuleDescription,
        t.p.value('@DataItemID', 'uniqueidentifier') AS DataItemID,
        t.p.value('@DataItemName', 'nvarchar(100)') AS DataItemName,
        t.p.value('@DataItemOtherOptions', 'nvarchar(max)') AS DataItemOtherOptions,
        t.p.value('@OutputDocRepeaterOptionID', 'int') AS OutputDocRepeaterOptionID,
        t.p.value('@FormOptions', 'nvarchar(max)') AS FormOptions,
        t.p.value('@FormID', 'uniqueidentifier') AS FormID,
        t.p.value('@DefaultValue', 'nvarchar(max)') AS DefaultValue,
        t.p.value('@GenericFieldDefinitionInspectionTypeID', 'uniqueidentifier') AS GenericFieldDefinitionInspectionTypeID,
        t.p.value('@GenericFieldDefinitionRoleID', 'uniqueidentifier') AS GenericFieldDefinitionRoleID,
        t.p.value('@PhotoGrid_ImagesToShow', 'nvarchar(50)') AS PhotoGrid_ImagesToShow,
        t.p.value('@PhotoGrid_NumberColumns', 'int') AS PhotoGrid_NumberColumns,
        t.p.value('@PhotoGrid_NumberRows', 'int') AS PhotoGrid_NumberRows,
        t.p.value('@Photo_PublicOnly', 'bit') AS Photo_PublicOnly,
        t.p.value('@Photo_LabelPosition', 'nvarchar(50)') AS Photo_LabelPosition,
        t.p.value('@Photo_Number', 'int') AS Photo_Number,
        t.p.value('@LinkedToNodeID', 'uniqueidentifier') AS LinkedToNodeID,
        t.p.value('@UseNoPhotoPlaceholder', 'bit') AS UseNoPhotoPlaceholder,
        t.p.value('@NoPhotoPlaceholderURL', 'nvarchar(max)') AS NoPhotoPlaceholderURL,
        t.p.value('@Photo_HighlightHazards', 'bit') AS Photo_HighlightHazards,
        t.p.value('@Photo_Level', 'int') AS Photo_Level,
        t.p.value('@CommCov_Level', 'int') AS CommCov_Level
    FROM [Promotion].Promotions AS p
    CROSS APPLY p.OutputsXml.nodes('/Data/Outputs.OutputNodes/Outputs.OutputNodes') t(p)
    WHERE p.PromotionID = 'xxxxx'
    ), --@promotionID)
SELECT *
FROM SourceOutputNodes o
WHERE OutputTemplateBookmarkID IS NULL
    OR EXISTS (SELECT [OutputDocTemplateBookmarkID] FROM [Outputs].[OutputDocTemplateBookmarks] WHERE o.OutputTemplateBookmarkID = OutputDocTemplateBookmarkID)
</code>```

ContentLicense: CC BY-SA 3.0

Body:
This query does not perform well.  I want to know if this can be done in fewer CTEs and / or without a UNION.

WITH SourceOutputNodes
              AS (
              SELECT t.p.value('@OutputNodeID', 'uniqueidentifier') AS OutputNodeID,
                     t.p.value('@OutputNodeTypeID', 'int') AS OutputNodeTypeID,
                     t.p.value('@OutputTemplateID', 'uniqueidentifier') AS OutputTemplateID,
                     t.p.value('@OutputTemplateBookmarkID', 'uniqueidentifier') AS OutputTemplateBookmarkID,
                     t.p.value('@PublicNodeID', 'uniqueidentifier') AS PublicNodeID,
                     t.p.value('@Name', 'nvarchar(100)') AS Name,
                     t.p.value('@Description', 'nvarchar(300)') AS [Description],
                     t.p.value('@CreatedDate', 'datetime') AS CreatedDate,
                     coalesce(t.p.value('@CreatedByUserID', 'uniqueidentifier'), '00000000-0000-0000-0000-000000000000') AS CreatedByUserID,
                     t.p.value('@DeletedDate', 'datetime') AS DeletedDate,
                     t.p.value('@DeletedByUserID', 'uniqueidentifier') AS DeletedByUserID,
                     t.p.value('@ModifiedByUserID', 'uniqueidentifier') AS ModifiedByUserID,
                     t.p.value('@ModifiedDate', 'datetime') AS ModifiedDate,
                     t.p.value('@IsPublic', 'bit') AS IsPublic,
                     t.p.value('@DisplayOrder', 'int') AS DisplayOrder,
                     t.p.value('@RuleID', 'uniqueidentifier') AS RuleID,
                     t.p.value('@RuleDescription', 'nvarchar(max)') AS RuleDescription,
                     t.p.value('@DataItemID', 'uniqueidentifier') AS DataItemID,
                     t.p.value('@DataItemName', 'nvarchar(100)') AS DataItemName,
                     t.p.value('@DataItemOtherOptions', 'nvarchar(max)') AS DataItemOtherOptions,
                     t.p.value('@OutputDocRepeaterOptionID', 'int') AS OutputDocRepeaterOptionID,
                     t.p.value('@FormOptions', 'nvarchar(max)') AS FormOptions,
                     t.p.value('@FormID', 'uniqueidentifier') AS FormID,
                     t.p.value('@DefaultValue', 'nvarchar(max)') AS DefaultValue,
                     t.p.value('@GenericFieldDefinitionInspectionTypeID', 'uniqueidentifier') AS GenericFieldDefinitionInspectionTypeID,
                     t.p.value('@GenericFieldDefinitionRoleID', 'uniqueidentifier') AS GenericFieldDefinitionRoleID,
                     t.p.value('@PhotoGrid_ImagesToShow', 'nvarchar(50)') AS PhotoGrid_ImagesToShow,
                     t.p.value('@PhotoGrid_NumberColumns', 'int') AS PhotoGrid_NumberColumns,
                     t.p.value('@PhotoGrid_NumberRows', 'int') AS PhotoGrid_NumberRows,
                     t.p.value('@Photo_PublicOnly', 'bit') AS Photo_PublicOnly,
                     t.p.value('@Photo_LabelPosition', 'nvarchar(50)') AS Photo_LabelPosition,
                     t.p.value('@Photo_Number', 'int') AS Photo_Number,
                     t.p.value('@LinkedToNodeID', 'uniqueidentifier') AS LinkedToNodeID,
                     t.p.value('@UseNoPhotoPlaceholder', 'bit') AS UseNoPhotoPlaceholder,
                     t.p.value('@NoPhotoPlaceholderURL', 'nvarchar(max)') AS NoPhotoPlaceholderURL,
                     t.p.value('@Photo_HighlightHazards', 'bit') AS Photo_HighlightHazards,
                     t.p.value('@Photo_Level', 'int') AS Photo_Level,
                     t.p.value('@CommCov_Level', 'int') AS CommCov_Level
              FROM [Promotion].Promotions AS p
                   CROSS APPLY p.OutputsXml.nodes('/Data/Outputs.OutputNodes/Outputs.OutputNodes') t(p)
              WHERE p.PromotionID = 'xxxxx'),--@promotionID),

  OutputNodesNullBookmarks AS (
   SELECT * FROM SourceOutputNodes WHERE OutputTemplateBookmarkID IS NULL
  ),

  OutputNodesMatchingBookmarks AS (
SELECT o.*
FROM SourceOutputNodes o
INNER JOIN [Outputs].[OutputDocTemplateBookmarks] b
ON o.OutputTemplateBookmarkID = b.[OutputDocTemplateBookmarkID]
  ),

  OutputNodes AS (
   SELECT *
   FROM
   OutputNodesNullBookmarks
   UNION
   SELECT *
   FROM
   OutputNodesMatchingBookmarks
  )
  SELECT * FROM OutputNodes

Body:
I'm not sure about that first CTE, but the second, third and fourth could be combined with an OR in your WHERE clause with a correlated subquery.

WITH SourceOutputNodes
AS (
    SELECT t.p.value('@OutputNodeID', 'uniqueidentifier') AS OutputNodeID,
        t.p.value('@OutputNodeTypeID', 'int') AS OutputNodeTypeID,
        t.p.value('@OutputTemplateID', 'uniqueidentifier') AS OutputTemplateID,
        t.p.value('@OutputTemplateBookmarkID', 'uniqueidentifier') AS OutputTemplateBookmarkID,
        t.p.value('@PublicNodeID', 'uniqueidentifier') AS PublicNodeID,
        t.p.value('@Name', 'nvarchar(100)') AS NAME,
        t.p.value('@Description', 'nvarchar(300)') AS [Description],
        t.p.value('@CreatedDate', 'datetime') AS CreatedDate,
        coalesce(t.p.value('@CreatedByUserID', 'uniqueidentifier'), '00000000-0000-0000-0000-000000000000') AS CreatedByUserID,
        t.p.value('@DeletedDate', 'datetime') AS DeletedDate,
        t.p.value('@DeletedByUserID', 'uniqueidentifier') AS DeletedByUserID,
        t.p.value('@ModifiedByUserID', 'uniqueidentifier') AS ModifiedByUserID,
        t.p.value('@ModifiedDate', 'datetime') AS ModifiedDate,
        t.p.value('@IsPublic', 'bit') AS IsPublic,
        t.p.value('@DisplayOrder', 'int') AS DisplayOrder,
        t.p.value('@RuleID', 'uniqueidentifier') AS RuleID,
        t.p.value('@RuleDescription', 'nvarchar(max)') AS RuleDescription,
        t.p.value('@DataItemID', 'uniqueidentifier') AS DataItemID,
        t.p.value('@DataItemName', 'nvarchar(100)') AS DataItemName,
        t.p.value('@DataItemOtherOptions', 'nvarchar(max)') AS DataItemOtherOptions,
        t.p.value('@OutputDocRepeaterOptionID', 'int') AS OutputDocRepeaterOptionID,
        t.p.value('@FormOptions', 'nvarchar(max)') AS FormOptions,
        t.p.value('@FormID', 'uniqueidentifier') AS FormID,
        t.p.value('@DefaultValue', 'nvarchar(max)') AS DefaultValue,
        t.p.value('@GenericFieldDefinitionInspectionTypeID', 'uniqueidentifier') AS GenericFieldDefinitionInspectionTypeID,
        t.p.value('@GenericFieldDefinitionRoleID', 'uniqueidentifier') AS GenericFieldDefinitionRoleID,
        t.p.value('@PhotoGrid_ImagesToShow', 'nvarchar(50)') AS PhotoGrid_ImagesToShow,
        t.p.value('@PhotoGrid_NumberColumns', 'int') AS PhotoGrid_NumberColumns,
        t.p.value('@PhotoGrid_NumberRows', 'int') AS PhotoGrid_NumberRows,
        t.p.value('@Photo_PublicOnly', 'bit') AS Photo_PublicOnly,
        t.p.value('@Photo_LabelPosition', 'nvarchar(50)') AS Photo_LabelPosition,
        t.p.value('@Photo_Number', 'int') AS Photo_Number,
        t.p.value('@LinkedToNodeID', 'uniqueidentifier') AS LinkedToNodeID,
        t.p.value('@UseNoPhotoPlaceholder', 'bit') AS UseNoPhotoPlaceholder,
        t.p.value('@NoPhotoPlaceholderURL', 'nvarchar(max)') AS NoPhotoPlaceholderURL,
        t.p.value('@Photo_HighlightHazards', 'bit') AS Photo_HighlightHazards,
        t.p.value('@Photo_Level', 'int') AS Photo_Level,
        t.p.value('@CommCov_Level', 'int') AS CommCov_Level
    FROM [Promotion].Promotions AS p
    CROSS APPLY p.OutputsXml.nodes('/Data/Outputs.OutputNodes/Outputs.OutputNodes') t(p)
    WHERE p.PromotionID = 'xxxxx'
    ), --@promotionID)
SELECT *
FROM SourceOutputNodes o
WHERE OutputTemplateBookmarkID IS NULL
    OR EXISTS (SELECT [OutputDocTemplateBookmarkID] FROM [Outputs].[OutputDocTemplateBookmarks] WHERE o.OutputTemplateBookmarkID = OutputDocTemplateBookmarkID)


问:
Rotation on pattern matched picture using SIFT via OpenCV python
So I've been struggling with this problem for a while so I would appreciate it if somebody helped me out with this.

I'm trying to create a physical robot that solves a puzzle. The image of the completed puzzle will be provided along with a picture of scattered pieces

Scattered piece picture

I've gotten opencv to find contours and single out each piece and rotate them so they are all parallel to the horizontal axes (all "diamond" or "diagonal" pieces are rotated so they look like squares)

I've been using SIFT to match a bunch of small square pieces to the complete picture.

Comparing an un-rotated square piece to the full picture

The problem is this is not in the correct orientation. How would I go about finding out whether I need to rotate 90, 180, 270 degrees?

Another problem I have is to determine which quadrant (non-adrant?) the piece is in. For example, this piece belongs to the bottom right corner. Is there a function that identifies the majority of similar keypoints and then classify into one of the nine regions?

答:
Since SIFT are designed to be rotation-invariant, it is a good thing that the feature matches even though you have a rotation.

To determine how much rotation you need, you generally need to have your camera calibration parameter in order to unproject the picture into a view that is top-down. For your robot, it looks like the pictures are already top-down.

If this assumption holds, you can perform a regression to figure out what angle you need to rotate your piece. If you also know that your pieces are always square, you only have 4 choices to choose from. In that case, you can try all 4 and see which one is "closest" to your extracted patch (matched via SIFT to the big picture).

Determining the quadrant the matched piece is in can be done by looking at the coordinates of the matched points. Their distance to the corners should be what you need.


问:
Docker Windows Containers CMD - Command not running
I have a docker image that ends with the following CMD:

CMD ["powershell", "c:\install\settings\install.ps1"]

or

CMD powershell c:\install\settings\install.ps1

It did not execute (or perhaps the volume is not mounted yet).

Settings are placed in a mounted volume, and it is started with:

docker run -d -p 80:80 --name openid --rm -v D:\settings\:c:\install\settings mydocker

If I run the command after starting the docker image:

docker exec openid powershell c:\install\settings\install.ps1

It runs fine.

Is there a way of doing this?

Or is there a better way of deploying an IIS website with webdeploy and custom SetParameters.xml?

答:
You can pass PS script to docker command as this:</p>

```<code>CMD ["powershell .\\myscript.ps1"]
</code>```

Body:
You can pass PS script to docker command as this:

CMD ["powershell .\\myscript.ps1"]


问:
make some django/wagtail files private
Is there a way to make some files unaccessible via direct url? For example, an image appears on a page but the image location doesn't work on it's own.</p>

答:
How Things Normally Work
By default, all static and media files are served up from the static root and media root folders. A good practice is to have NGINX or Apache route to these, or to use something like Django Whitenoise to serve up static files.

In production, you definitely don't want to have the runserver serving up these files because 1) That doesn't scale well, 2) It means you're running in DEBUG mode on production which is an absolute no-no.

Protecting Those Files
You can keep this configuration for most files that you don't need to protect. Instead, you can serve up files of your own within Django from a different filepath. Use the upload_to parameter of the filefield to specify where you want those files to live. For example,

```<code>protectedfile = models.FileField(upload_to="protected/")
publicfile = models.FileField(upload_to="public/")
</code>```

Then in NGINX make your block direct to /var/www/myproject/MEDIAROOT/public instead. That will enable you to continue serving up public files.

Meanwhile, for the protected files, those can be served up by the view with:

```<code>def view_to_serve_up_docs(request, document_id):
    my_doc = MyDocumentModel.objects.get(id=document_id)

    # Do some check against this user
    if request.user.is_authenticated():
        response = FileResponse(my_doc.privatefile)
        response["Content-Disposition"] = "attachment; filename=" + my_doc.privatefile.name
    else:
        raise Http404()
    return response
</code>```

And link to this view within your templates

```<code><a href='/downloadFileView/12345'>Download File #12345 Here!</a>
</code>```

Reference
More about the FileResponse object: https://docs.djangoproject.com/en/1.11/ref/request-response/#fileresponse-objects

Title: make some django/wagtail files private

Body:
How Things Normally Work
By default, all static and media files are served up from the static root and media root folders. A good practice is to have NGINX or Apache route to these, or to use something like Django Whitenoise to serve up static files.

In production, you definitely don't want to have the runserver serving up these files because 1) That doesn't scale well, 2) It means you're running in DEBUG mode on production which is an absolute no-no.

Protecting Those Files
You can keep this configuration for most files that you don't need to protect. Instead, you can serve up files of your own within Django from a different filepath. Use the upload_to parameter of the filefield to specify where you want those files to live. For example,

protectedfile = models.FileField(upload_to="protected/")
publicfile = models.FileField(upload_to="public/")

Then in NGINX make your block direct to /var/www/myproject/MEDIAROOT/public instead. That will enable you to continue serving up public files.

Meanwhile, for the protected files, those can be served up by the view with:

def view_to_serve_up_docs(request, document_id):
    my_doc = MyDocumentModel.objects.get(id=document_id)

    # Do some check against this user
    if request.user.is_authenticated():
        response = FileResponse(my_doc.privatefile)
        response["Content-Disposition"] = "attachment; filename=" + my_doc.privatefile.name
    else:
        raise Http404()
    return response

And link to this view within your templates

<a href='/downloadFileView/12345'>Download File #12345 Here!</a>

Reference
More about the FileResponse object: https://docs.djangoproject.com/en/1.11/ref/request-response/#fileresponse-objects


问:
Processing Checkbox Group into String
I have a form which contains a series of checkboxes, in a group. Here is the HTML -

```<code><input type="checkbox" name="p_contents[]" value="Value 1" />
<input type="checkbox" name="p_contents[]" value="Value 2" />
<input type="checkbox" name="p_contents[]" value="Value 3" />
<input type="checkbox" name="p_contents[]" value="Value 4" />
<input type="checkbox" name="p_contents[]" value="Value 5" />
</code>```

And I wish to process this with javascript -

```<code>var contents;
for(var i=0; i < document.forms['addForm'].elements['p_contents[]'].length; i++){
    if(i != (document.forms['addForm'].elements['p_contents[]'].length - 1)){
        if(document.forms['addForm'].elements['p_contents[]'].checked){
            contents += encodeURIComponent(document.forms['addForm'].elements['p_contents[]'][i].value) + ",";
        }
    }else{
        if(document.forms['addForm'].elements['p_contents[]'][i].checked){
            contents += encodeURIComponent(document.forms['addForm'].elements['p_contents[]'][i].value);
        }
    }
}
</code>```

I'm sure the problem is with the enumeration:

```<code>document.forms['addForm'].elements['p_contents[]'][i].checked
</code>```

Is this the correct way to process a grouped checkbox form?

答:
I'd do it this way:

```<code>var vals = [], p_contents =  document.forms['addForm']['p_contents[]'];
for(var i=0,elm;elm = p_contents[i];i++) {
    if(elm.checked) {
        vals.push(elm.value);
    }
}
</code>```

and if you need the result to be a string just do

```<code>vals.join(',');
</code>```

If the encodeURIComponent is needed, do that before pushing the value into the vals array like this:

```<code>vals.push(encodeURIComponent(elm.value));
</code>```

So to recap - if you are looking for the exact same result your own code is giving, do this:

```<code>var contents, vals = [], p_contents =  document.forms['addForm']['p_contents[]'];
for(var i=0,elm;elm = p_contents[i];i++) {
    if(elm.checked) {
        vals.push(encodeURIComponent(elm.value));
    }
}
contents = vals.join(',');
</code>```

You can see it in effect here: http://jsfiddle.net/3MRc7/

Title: Processing Checkbox Group into String

Body:
I have a form which contains a series of checkboxes, in a group. Here is the HTML -

<input type="checkbox" name="p_contents[]" value="Value 1" />
<input type="checkbox" name="p_contents[]" value="Value 2" />
<input type="checkbox" name="p_contents[]" value="Value 3" />
<input type="checkbox" name="p_contents[]" value="Value 4" />
<input type="checkbox" name="p_contents[]" value="Value 5" />

And I wish to process this with javascript -

var contents;
for(var i=0; i < document.forms['addForm'].elements['p_contents[]'].length; i++){
    if(i != (document.forms['addForm'].elements['p_contents[]'].length - 1)){
        if(document.forms['addForm'].elements['p_contents[]'].checked){
            contents += encodeURIComponent(document.forms['addForm'].elements['p_contents[]'][i].value) + ",";
        }
    }else{
        if(document.forms['addForm'].elements['p_contents[]'][i].checked){
            contents += encodeURIComponent(document.forms['addForm'].elements['p_contents[]'][i].value);
        }
    }
}

I'm sure the problem is with the enumeration:

document.forms['addForm'].elements['p_contents[]'][i].checked

Is this the correct way to process a grouped checkbox form?

Body:
I'd do it this way:

var vals = [], p_contents =  document.forms['addForm']['p_contents[]'];
for(var i=0,elm;elm = p_contents[i];i++) {
    if(elm.checked) {
        vals.push(elm.value);
    }
}

and if you need the result to be a string just do

vals.join(',');

If the encodeURIComponent is needed, do that before pushing the value into the vals array like this:

vals.push(encodeURIComponent(elm.value));

So to recap - if you are looking for the exact same result your own code is giving, do this:

var contents, vals = [], p_contents =  document.forms['addForm']['p_contents[]'];
for(var i=0,elm;elm = p_contents[i];i++) {
    if(elm.checked) {
        vals.push(encodeURIComponent(elm.value));
    }
}
contents = vals.join(',');

You can see it in effect here: http://jsfiddle.net/3MRc7/


问:
D3 Zoom Settings
I am having some trouble understanding how zoom work in D3, specifically how it is called and the settings initialized. I have the following snippet of code (only the essential bits are included), which is from a Manning Textbook on D3 V4 and works fine:

```<code>var svg = d3.select("body").append("svg")
    .attr("width",width)
    .attr("height",height)

function createMap(countries, cities) {
    var projection = d3.geoMercator()
        .scale(scale)
        .translate([width/2,height/2])

var mapZoom = d3.zoom()
    .on("zoom", zoomed)

var zoomSettings = d3.zoomIdentity
    .translate(width/2, height/2)
    .scale(scale)

svg.call(mapZoom).call(mapZoom.transform, zoomSettings) // ?!!!

function zoomed() {
        var e = d3.event
        .translate([e.transform.x, e.transform.y])
        .scale(e.transform.k)

    // I didn't include the drawing of the paths, but
       they are appended to the SVG, and this updates their data.

    d3.selectAll("path.graticule").attr("d", geoPath)
    d3.selectAll("path.countries").attr("d", geoPath)
    d3.selectAll("circle.cities")
    .attr("cx", d => projection([d.x,d.y])[0])
    .attr("cy", d => projection([d.x,d.y])[1])
}
</code>```

Why is it necessary to call the zoom function multiple times on the svg? The first time it is called, we don't pass it the "zoomSettings", and the second time we do. What is the point of this? Does it have something to do with the fact that the zoom event is working on the SVG, rather than a group holding all of my paths? I'm used to much more simple examples of zoom like this, which are called on an SVG and the elements are bound to a Group:

```<code>var zoom = d3.zoom()
    .scaleExtent([1,3])
    .on("zoom", zoomed)

function zoomed(){
    g.attr("transform", d3.event.transform)
}

var svg = d3.select("body").append("svg")
    .attr("width",width)
    .attr("height",height)
    .call(zoom)

var g = d3.select("svg").append("g")

// All elements are bound to group^
</code>```

Any clarification someone could provide on this would be greatly appreciated. I find the zoom() in D3 to be incredibly confusing, despite the API.

答:
This line:

```<code>svg.call(mapZoom).call(mapZoom.transform, zoomSettings)
</code>```

is doing two separate things.

First, svg.call(mapZoom) is applying the zoom behavior to the svg.  The second call, .call(mapZoom.transform, zoomSettings), is programmatically setting a zoom transform to the svg.  This is setting it's initial state before the user does anything to it.

So think about it like this:

Create the zoom behavior (var zoom = d3.zoom())

Apply it to svg element (svg.call(mapZoom))

Set its initial state (.call(mapZoom.transform, zoomSettings))

Title: D3 Zoom Settings

Body:
I am having some trouble understanding how zoom work in D3, specifically how it is called and the settings initialized. I have the following snippet of code (only the essential bits are included), which is from a Manning Textbook on D3 V4 and works fine:

var svg = d3.select("body").append("svg")
    .attr("width",width)
    .attr("height",height)

function createMap(countries, cities) {
    var projection = d3.geoMercator()
        .scale(scale)
        .translate([width/2,height/2])

var mapZoom = d3.zoom()
    .on("zoom", zoomed)

var zoomSettings = d3.zoomIdentity
    .translate(width/2, height/2)
    .scale(scale)

svg.call(mapZoom).call(mapZoom.transform, zoomSettings) // ?!!!

function zoomed() {
        var e = d3.event
        .translate([e.transform.x, e.transform.y])
        .scale(e.transform.k)

    // I didn't include the drawing of the paths, but
       they are appended to the SVG, and this updates their data.

    d3.selectAll("path.graticule").attr("d", geoPath)
    d3.selectAll("path.countries").attr("d", geoPath)
    d3.selectAll("circle.cities")
    .attr("cx", d => projection([d.x,d.y])[0])
    .attr("cy", d => projection([d.x,d.y])[1])
}

Why is it necessary to call the zoom function multiple times on the svg? The first time it is called, we don't pass it the "zoomSettings", and the second time we do. What is the point of this? Does it have something to do with the fact that the zoom event is working on the SVG, rather than a group holding all of my paths? I'm used to much more simple examples of zoom like this, which are called on an SVG and the elements are bound to a Group:

var zoom = d3.zoom()
    .scaleExtent([1,3])
    .on("zoom", zoomed)

function zoomed(){
    g.attr("transform", d3.event.transform)
}

var svg = d3.select("body").append("svg")
    .attr("width",width)
    .attr("height",height)
    .call(zoom)

var g = d3.select("svg").append("g")

// All elements are bound to group^

Any clarification someone could provide on this would be greatly appreciated. I find the zoom() in D3 to be incredibly confusing, despite the API.

Body:
This line:

svg.call(mapZoom).call(mapZoom.transform, zoomSettings)

is doing two separate things.

First, svg.call(mapZoom) is applying the zoom behavior to the svg.  The second call, .call(mapZoom.transform, zoomSettings), is programmatically setting a zoom transform to the svg.  This is setting it's initial state before the user does anything to it.

So think about it like this:

Create the zoom behavior (var zoom = d3.zoom())

Apply it to svg element (svg.call(mapZoom))

Set its initial state (.call(mapZoom.transform, zoomSettings))


问:
Code Folding multiple open lines in Notepad++
I'm attempting to create a user defined language based on code for motion capture syntax files (in Visual3D). I want to fold code based on the following syntax

The open argument always looks like this
!***************************************************************

! Right Knee Flexion

!***************************************************************

and the close section is always  ;. The issue is that the second line of the "Open" is never the same. Sometimes it may be ! Left Knee Flexion etc. But it will always begin with !. Does anyone have any idea on how I could enter this as a User Defined Language?

答:
This is the first time that I looked into this capability, but it appears to be possible.

Not sure how you created yours, but I put your snippet into Notepad++ (with an extra line after the one in the middle -- only to see if it would keep the fold 'range'), and then chose Language => Define your language... from the menu.

In the next User Defined Language dialog window, I set the options shown below in the red markers and the folding block appears:

I'm guessing that you could set the same for your info?


问:
How to programatically query for documents where property is null in ravendb
In ravendb studio I can do:

```<code>property: [[NULL_VALUE]]
</code>```

How to do the same using IDocumentQuery?

The try below does not work.

```<code>documentSession
 .Advanced
 .DocumentQuery<Doc, Index>()
 .WhereIn("property", new[] {"[[NULL_VALUE]]", "some value"})
 .ToList();
</code>```

答:
To query for [[NULL_VALUE]] or [[EMPTY_VALUE]]:

```<code>documentSession
 .Advanced
 .DocumentQuery<Doc, Index>()
 .WhereIn("property", new string[] {null, ""})
 .ToList();
</code>```

Body:
In ravendb studio I can do:

property: [[NULL_VALUE]]

How to do the same using IDocumentQuery?

The try below does not work.

documentSession
 .Advanced
 .DocumentQuery<Doc, Index>()
 .WhereIn("property", new[] {"[[NULL_VALUE]]", "some value"})
 .ToList();

Body:
To query for [[NULL_VALUE]] or [[EMPTY_VALUE]]:

documentSession
 .Advanced
 .DocumentQuery<Doc, Index>()
 .WhereIn("property", new string[] {null, ""})
 .ToList();


问:
Showing images into a list view
I am writing a code in C# to show the unknown number of images from a specified folder into a "listview" I don't know how to get all the files present in that specific folder.
I know I have to use a loop and array but I don't know how.
Here is the code which I use to access files with the "known name of file".
It's a windows form app.</p>

```<code>private void btnZoom_Click(object sender, EventArgs e)
{
    ImageList imgs = new ImageList();
    imgs.ImageSize = new Size(100, 100);

    string[] paths = { };
    paths = Directory.GetFiles("TestFolder");

    try
    {
        foreach (string path in paths)
        {
            imgs.Images.Add(Image.FromFile(path));
        }
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message);
    }
    listView1.SmallImageList = imgs;
    listView1.Items.Add("2",0);
}
</code>```

答:
To get all the image files you can do

```<code>IEnumerable<string> paths = Directory.GetFiles(@"Your Dir", "*.*").Where(x=>x.EndsWith(".png") || x.EndsWith(".jpg")); //add all the extensions you wish in
</code>```

then you can just iterate thru the list to add them in

Title: Showing images into a list view

Body:
I am writing a code in C# to show the unknown number of images from a specified folder into a "listview" I don't know how to get all the files present in that specific folder.
I know I have to use a loop and array but I don't know how.
Here is the code which I use to access files with the "known name of file".
It's a windows form app.

private void btnZoom_Click(object sender, EventArgs e)
{
    ImageList imgs = new ImageList();
    imgs.ImageSize = new Size(100, 100);

    string[] paths = { };
    paths = Directory.GetFiles("TestFolder");

    try
    {
        foreach (string path in paths)
        {
            imgs.Images.Add(Image.FromFile(path));
        }
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message);
    }
    listView1.SmallImageList = imgs;
    listView1.Items.Add("2",0);
}

Body:
To get all the image files you can do

IEnumerable<string> paths = Directory.GetFiles(@"Your Dir", "*.*").Where(x=>x.EndsWith(".png") || x.EndsWith(".jpg")); //add all the extensions you wish in

then you can just iterate thru the list to add them in


问:
Failed to start project The directory name is invalid
I'm new and learning SSIS, and just to get started I wanted to test funtionality by writing an excel document out to a .csv file. However, I did everything that I believe needs to be done, but when I try to run it, I get this error:

Failed to start project (Microsoft Visual Studio)
  The directory name is invalid (Microsoft.DataTransformationServices.VsIntegration)

I've run over it about as many ways as I can, and even went as far as reinstalling, but I still can't get it to work. Looking up this error doesn't return much to me, either.

Thanks for any help!

答:
There are some SSDT assemblies missing, I think that you have to reinstall or to repair the Sql Server Data Tools, you can find the latest versions on the following link:

https://learn.microsoft.com/en-us/sql/ssdt/download-sql-server-data-tools-ssdt


问:
Android firebase no data query
Im using the Android SDK for firebase database.

In the database I have a structure where I keep the messages ordered by user, that way if I need their messages I just query by user.

```<code>myDatabase -> messages -> JonDoe
                            -> "You forgot your mail"
                            -> "Buy groceries"
                       -> JaneDoe
                            -> "Dog's birthday!"
</code>```

The problem is if the user doesnt exist the listener keeps waiting forever, and I want to show "You have no messages" in that case. (For example, if I query the user "CharlesDoe" in the example above)

Is there a way to check if a reference exists before/after/during a query?

答:
Try this on</p>

```<code>DatabaseReference root =FirebaseDatabase.getInstance().getReference();
DatabaseReference user =
root.child("myDatabase").child("messages").child("CharlesDoe");
user.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot snapshot) {
    if (snapshot.exists()) {
        // run some code
    }else{
    Toast.makeText(this,"no messages",Toast.Length_LONG).show();

    }
}

@Override
public void onCancelled(DatabaseError databaseError) {

}
});
</code>```

Title: Android firebase no data query

Body:
Im using the Android SDK for firebase database.

In the database I have a structure where I keep the messages ordered by user, that way if I need their messages I just query by user.

myDatabase -> messages -> JonDoe
                            -> "You forgot your mail"
                            -> "Buy groceries"
                       -> JaneDoe
                            -> "Dog's birthday!"

The problem is if the user doesnt exist the listener keeps waiting forever, and I want to show "You have no messages" in that case. (For example, if I query the user "CharlesDoe" in the example above)

Is there a way to check if a reference exists before/after/during a query?

Body:
Try this on

DatabaseReference root =FirebaseDatabase.getInstance().getReference();
DatabaseReference user =
root.child("myDatabase").child("messages").child("CharlesDoe");
user.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot snapshot) {
    if (snapshot.exists()) {
        // run some code
    }else{
    Toast.makeText(this,"no messages",Toast.Length_LONG).show();

    }
}

@Override
public void onCancelled(DatabaseError databaseError) {

}
});


问:
In Java, can a method/constructor declaration appear inside another method/constructor declaration?
In Java, can a method/constructor declaration appear inside another method/constructor declaration? Example:

```<code>void A() {
    int B() { }
}
</code>```

I think not, but I'd love to be reassured.

答:
No this is not possible.
For reference: http://download.oracle.com/javase/tutorial/java/javaOO/methods.html</p>

Body:
In Java, can a method/constructor declaration appear inside another method/constructor declaration? Example:

void A() {
    int B() { }
}

I think not, but I'd love to be reassured.


问:
How to save the output of a function?
I have a site that has a circle that changes color randomly when you click on it.

var letter = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '0', 'a', 'b', 'c', 'd', 'e', 'f'];

function color() {
  lineOfLetters = letter[Math.floor(Math.random() * 15)] + letter[Math.floor(Math.random() * 15)] + letter[Math.floor(Math.random() * 15)] + letter[Math.floor(Math.random() * 15)] + letter[Math.floor(Math.random() * 15)] + letter[Math.floor(Math.random() * 15)];
  var colorNumber = "#" + lineOfLetters;
  return colorNumber;
}

var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
var radius = 250

ctx.beginPath();
ctx.arc(300, 300, 250, 0, 2 * Math.PI, false)

function fillCircle() {
  ctx.fillStyle = color();
  ctx.fill()
}
document.write(color())```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.button {
  width: 500px;
  height: 500px;
  background-color: red;
  border-radius: 50%;
  display: inline-block;
  opacity: 0;
  position: absolute;
  left: 58px;
  top: 58px;
}</code>```

  <canvas id="myCanvas" width="600" height="600">nope</canvas>

```
</div>
</div>
</p>

<p>I the page to display exactly what color the circle is.</p>

<p>I tried:</p>

```document.write(color())
```

But that just generates another color value and is not related to the color of the circle at all.

How do get the page to display exactly what color the circle is?

答:
Assign the result of color() to a variable and then put it into the DOM.

var letter = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '0', 'a', 'b', 'c', 'd', 'e', 'f'];

function color() {
  lineOfLetters = letter[Math.floor(Math.random() * 15)] + letter[Math.floor(Math.random() * 15)] + letter[Math.floor(Math.random() * 15)] + letter[Math.floor(Math.random() * 15)] + letter[Math.floor(Math.random() * 15)] + letter[Math.floor(Math.random() * 15)];
  var colorNumber = "#" + lineOfLetters;
  return colorNumber;
}

var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
var radius = 250

var colorSpan = document.getElementById("colorCode");

ctx.beginPath();
ctx.arc(300, 300, 250, 0, 2 * Math.PI, false)

function fillCircle() {
  var c = color();
  ctx.fillStyle = c;
  ctx.fill();
  colorSpan.textContent = c;
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.button {
  width: 500px;
  height: 500px;
  background-color: red;
  border-radius: 50%;
  display: inline-block;
  opacity: 0;
  position: absolute;
  left: 58px;
  top: 58px;
}</code>```

  <canvas id="myCanvas" width="600" height="600">nope</canvas>
Color code is
```

Title: How to save the output of a function?

Body:
I have a site that has a circle that changes color randomly when you click on it.

var letter = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '0', 'a', 'b', 'c', 'd', 'e', 'f'];

function color() {
  lineOfLetters = letter[Math.floor(Math.random() * 15)] + letter[Math.floor(Math.random() * 15)] + letter[Math.floor(Math.random() * 15)] + letter[Math.floor(Math.random() * 15)] + letter[Math.floor(Math.random() * 15)] + letter[Math.floor(Math.random() * 15)];
  var colorNumber = "#" + lineOfLetters;
  return colorNumber;
}

var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
var radius = 250

ctx.beginPath();
ctx.arc(300, 300, 250, 0, 2 * Math.PI, false)

function fillCircle() {
  ctx.fillStyle = color();
  ctx.fill()
}
document.write(color())

.button {
  width: 500px;
  height: 500px;
  background-color: red;
  border-radius: 50%;
  display: inline-block;
  opacity: 0;
  position: absolute;
  left: 58px;
  top: 58px;
}

  <canvas id="myCanvas" width="600" height="600">nope</canvas>

I the page to display exactly what color the circle is.

I tried:

document.write(color())

But that just generates another color value and is not related to the color of the circle at all.

How do get the page to display exactly what color the circle is?

Body:
Assign the result of color() to a variable and then put it into the DOM.

var letter = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '0', 'a', 'b', 'c', 'd', 'e', 'f'];

function color() {
  lineOfLetters = letter[Math.floor(Math.random() * 15)] + letter[Math.floor(Math.random() * 15)] + letter[Math.floor(Math.random() * 15)] + letter[Math.floor(Math.random() * 15)] + letter[Math.floor(Math.random() * 15)] + letter[Math.floor(Math.random() * 15)];
  var colorNumber = "#" + lineOfLetters;
  return colorNumber;
}

var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
var radius = 250

var colorSpan = document.getElementById("colorCode");

ctx.beginPath();
ctx.arc(300, 300, 250, 0, 2 * Math.PI, false)

function fillCircle() {
  var c = color();
  ctx.fillStyle = c;
  ctx.fill();
  colorSpan.textContent = c;
}

.button {
  width: 500px;
  height: 500px;
  background-color: red;
  border-radius: 50%;
  display: inline-block;
  opacity: 0;
  position: absolute;
  left: 58px;
  top: 58px;
}

<body onload="fillCircle()">
  <div onclick="fillCircle()" class="button"></div>
  <canvas id="myCanvas" width="600" height="600">nope</canvas>
Color code is <span id="colorCode"></span>
</body>


问:
Align Multiple Views at the bottom of screen
I'm new to Android and I want to create an activity with 3 set (line) of Buttons at the bottom of screen .For my example I wrote this code for 2 set (line) of buttons:

```<code><?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_gravity="bottom"
    android:layout_alignParentBottom="true">

    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:text="1" />

    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:text="2" />

    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:text="3" />

    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:text="4" />

    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:text="5" />
</LinearLayout>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_gravity="bottom"
    android:layout_alignParentBottom="true">

    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:text="6" />

    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:text="7" />

    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:text="8" />

    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:text="9" />

    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:text="10" />
</LinearLayout>
</RelativeLayout>
</code>```

I want to buttons 6-10 put on (above) the buttons 1-5 (like Stack).

How I can do this?

Thanks

答:
You are using a RelativeLayout with two LinearLayouts.

You should give both your LinearLayout ids and after that you will position the other LinearLayout which you want to be on top by giving it the atrribute

```<code>android:layout_above="@id/the_id_of_the_one_you_want_to_be_below"
</code>```

Body:
I'm new to Android and I want to create an activity with 3 set (line) of Buttons at the bottom of screen .For my example I wrote this code for 2 set (line) of buttons:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_gravity="bottom"
    android:layout_alignParentBottom="true">

    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:text="1" />

    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:text="2" />

    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:text="3" />

    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:text="4" />

    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:text="5" />
</LinearLayout>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_gravity="bottom"
    android:layout_alignParentBottom="true">

    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:text="6" />

    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:text="7" />

    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:text="8" />

    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:text="9" />

    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:text="10" />
</LinearLayout>
</RelativeLayout>

I want to buttons 6-10 put on (above) the buttons 1-5 (like Stack).

How I can do this?

Thanks

Body:
You are using a RelativeLayout with two LinearLayouts.

You should give both your LinearLayout ids and after that you will position the other LinearLayout which you want to be on top by giving it the atrribute

android:layout_above="@id/the_id_of_the_one_you_want_to_be_below"


问:
Get n oldest rows, but no more than x that have the same value in a column
I have a simple table

```<code>CREATE TABLE `example` (
  `id` int(12) NOT NULL,
  `food` varchar(250) NOT NULL
);
</code>```

With the following data

```<code>INSERT INTO `example` (`id`, `food`) VALUES
(1, 'apple'),
(2, 'apple'),
(3, 'apple'),
(4, 'apple'),
(5, 'apple'),
(6, 'apple'),
(7, 'apple'),
(8, 'banana'),
(9, 'banana'),
(10, 'potato'),
(11, 'potato'),
(12, 'potato'),
(13, 'banana'),
(14, 'banana'),
(15, 'banana');
</code>```

I want to get the oldest 10 rows

```<code>SELECT *
FROM example
ORDER BY id ASC
LIMIT 10
</code>```

But I don't want to get more than 5 rows where food has the same value.

My current query receives 7 apple (more than I want), 2 banana, and 1 potato. In the data provided, I'd want to receive 5 apple, 2 banana, and 3 potato.

How can I accomplish this?

Update:

SQL Group BY, Top N Items for each Group is not a duplicate because it involves a different database. In particular, GROUP BY works different in sql-server than it does in MySQL

答:
I didn't create the table and test this, but it should give you what you want. Just a different approach than the one above.

```<code>Select *
From (Select ID, Food
, Count(Food) Over(Partition By Food Order by ID) as Appearances
From Your_Table) as a
Where a.Appearances <= 5
Order By ID Asc
</code>```

You can obviously put the limit if you want.

Body:
I have a simple table

CREATE TABLE `example` (
  `id` int(12) NOT NULL,
  `food` varchar(250) NOT NULL
);

With the following data

INSERT INTO `example` (`id`, `food`) VALUES
(1, 'apple'),
(2, 'apple'),
(3, 'apple'),
(4, 'apple'),
(5, 'apple'),
(6, 'apple'),
(7, 'apple'),
(8, 'banana'),
(9, 'banana'),
(10, 'potato'),
(11, 'potato'),
(12, 'potato'),
(13, 'banana'),
(14, 'banana'),
(15, 'banana');

I want to get the oldest 10 rows

SELECT *
FROM example
ORDER BY id ASC
LIMIT 10

But I don't want to get more than 5 rows where food has the same value.

My current query receives 7 apple (more than I want), 2 banana, and 1 potato. In the data provided, I'd want to receive 5 apple, 2 banana, and 3 potato.

How can I accomplish this?

Update:

SQL Group BY, Top N Items for each Group is not a duplicate because it involves a different database. In particular, GROUP BY works different in sql-server than it does in MySQL

Body:
I didn't create the table and test this, but it should give you what you want. Just a different approach than the one above.

Select *
From (Select ID, Food
, Count(Food) Over(Partition By Food Order by ID) as Appearances
From Your_Table) as a
Where a.Appearances <= 5
Order By ID Asc

You can obviously put the limit if you want.


问:
Export results from Orange3
I'd like to build a service visualizing my data.

Orange3 provides good "Scatter Plot", "Freeviz" (and so on) widgets.

Is there a way to export my results to jupiter notebook or jpeg file/files, or maybe other options would be ok.

Note: if it is requires coding in python then it is ok, but i need a clue.

Edit: as far as i've investigated for now, i'll be ok with "Report" data from Orange. but i need a way (not exactly a full solution) how to implement to build it from code.

答: If the actions you want to perform are included in the Orange3 Data Mining Library, then you can perform your calculations via python code and extract the results in .txt or a .csv file.</p>

Title: Export results from Orange3


答:
Just show that generated color like this:

```<code>function fillCircle (){
    document.write( ctx.fillStyle = color() );
    ctx.fill();
}
</code>```

But document.write should not be used here, you should rather add an html element e.g.:

```<code> <span id="color" > </span>
</code>```

So we can do this inside the code

```<code>const colorLabel = document.getElementById("color");

function fillCircle (){
    colorLabel.textContent = ctx.fillStyle = color();
    ctx.fill();
}
</code>```

Sidenote: to get a 6 char hex string you can easily do:

```<code>const color = "#" + Math.floor( Math.random() * 16 ** 6 ).toString(16);
</code>```

Title: How to save the output of a function?

Body:
Just show that generated color like this:

function fillCircle (){
    document.write( ctx.fillStyle = color() );
    ctx.fill();
}

But document.write should not be used here, you should rather add an html element e.g.:

 <span id="color" > </span>

So we can do this inside the code

const colorLabel = document.getElementById("color");

function fillCircle (){
    colorLabel.textContent = ctx.fillStyle = color();
    ctx.fill();
}

Sidenote: to get a 6 char hex string you can easily do:

const color = "#" + Math.floor( Math.random() * 16 ** 6 ).toString(16);


问:
Utalization of classes in python
I'm trying to teach myself about OOP in python and am really struggling.

I have the following:

```<code>        def __init__(self, quantity):
            ''' '''
            self.switchboard = []
            self.state = False
            self.quantity = quantity
            for i in range(quantity):
                self.switchboard.append(i)

        def __str__(self):
            self.on_list = []
            for i in range(self.quantity):
                if i == True:
                    self.on_list.append(i)
            return("The following switches are on " + str(self.on_list))
        def which_switch(self):
            for i in range(len(self.switchboard)):
                self.on_list = []
                if self.switchboard[i] == True:
                    on_list.append(i)
                print(on_list)

        def flip(self, n):
            if self.switchboard[n] == True:
                self.switchboard[n] = False
            else:
                self.switchboard[n] = True
</code>```

When I print it, I get The following switches are on [1]. Even though I put 10 in the parameters. I want it to display all the switches that are on which in this case should be zero since their initial state is 'off'.

答: Also the reason it's printing 1 as true, is because out of all the elements in list, it's just seeing everything as false and 1 as true (as in 0 == False, 1 == True).</p>

Title: Utalization of classes in python

Body:
I'm trying to teach myself about OOP in python and am really struggling.

I have the following:

        def __init__(self, quantity):
            ''' '''
            self.switchboard = []
            self.state = False
            self.quantity = quantity
            for i in range(quantity):
                self.switchboard.append(i)

        def __str__(self):
            self.on_list = []
            for i in range(self.quantity):
                if i == True:
                    self.on_list.append(i)
            return("The following switches are on " + str(self.on_list))
        def which_switch(self):
            for i in range(len(self.switchboard)):
                self.on_list = []
                if self.switchboard[i] == True:
                    on_list.append(i)
                print(on_list)

        def flip(self, n):
            if self.switchboard[n] == True:
                self.switchboard[n] = False
            else:
                self.switchboard[n] = True

When I print it, I get The following switches are on [1]. Even though I put 10 in the parameters. I want it to display all the switches that are on which in this case should be zero since their initial state is 'off'.


问:
AngularJS Component - Function Binding
I wrote a table component:

```<code><table ng-model="$ctrl.model" class="table" md-progress="promise">
<thead class="thead">
    <tr>
        <th class="theader">ID</th>
        <th class="theader">A</th>
        <th class="theader">Actions</th>
    </tr>
</thead>
<tbody>
    <tr md-row ng-repeat="row in $ctrl.data track by $index">
        <td width="15%" class="trow">{{row.id}}</td>
        <td width="15%" class="trow">{{row.a}}</td>
        <td width="15%" class="trow">
            <md-button ng-click="$ctrl.edit({x: row.id, y: row.a})"></md-button>
        </td>
    </tr>
</tbody>
</code>```

I define the component as:

```<code>.component('tablesample', {
        require: {},
        templateUrl: 'Components/templates/tableSample.html',
        bindings: {
            data: '=',
            model: '=',
            edit: '&',
        },
        controller: function ($log) {
            var tbl = this;
            tbl.$onInit = function () {
            };
            tbl.$onChanges = function () {
            };
        }
    })
</code>```

I call the new component as:

```<code><tablesample data="tableData" model="selectedRow" edit="editFunction()"></tablesample>
</code>```

Edit Function is defined as:

```<code>$scope.editFunction = function(x,y){
    console.clear();
    $log.info(x);
    $log.info(y);
};
</code>```

The log statements always display 'undefined' and I don't know why, row.id is populated, if I dump it I can see 1,2,3, etc....  Inside editFunction I do an http get so if x is undefined the call will fail.

Can anyone see what I did wrong?

Thanks
D

答:
I had to change:

```<code><tablesample data="tableData" model="selectedRow" edit="editFunction()"></tablesample>
</code>```

to:

```<code><tablesample data="tableData" model="selectedRow" edit="editFunction(id,a)"></tablesample>
</code>```

Thanks
Docmur

Title: AngularJS Component - Function Binding

Body:
I wrote a table component:

        ID
        A
        Actions

        {{row.id}}
        {{row.a}}

            <md-button ng-click="$ctrl.edit({x: row.id, y: row.a})"></md-button>

I define the component as:

.component('tablesample', {
        require: {},
        templateUrl: 'Components/templates/tableSample.html',
        bindings: {
            data: '=',
            model: '=',
            edit: '&',
        },
        controller: function ($log) {
            var tbl = this;
            tbl.$onInit = function () {
            };
            tbl.$onChanges = function () {
            };
        }
    })

I call the new component as:

<tablesample data="tableData" model="selectedRow" edit="editFunction()"></tablesample>

Edit Function is defined as:

$scope.editFunction = function(x,y){
    console.clear();
    $log.info(x);
    $log.info(y);
};

The log statements always display 'undefined' and I don't know why, row.id is populated, if I dump it I can see 1,2,3, etc....  Inside editFunction I do an http get so if x is undefined the call will fail.

Can anyone see what I did wrong?

Thanks
D

Body:
I had to change:

<tablesample data="tableData" model="selectedRow" edit="editFunction()"></tablesample>

to:

<tablesample data="tableData" model="selectedRow" edit="editFunction(id,a)"></tablesample>

Thanks
Docmur


问:
Cycling images with javascript
Why doesn't the second (hawk) image appear when the button is clicked? It goes straight to the else statement showing the ant image. </p>

```<code><!DOCTYPE html>
<html>
    <body>
        <script>
            function changeImg() {
                if (document.getElementById("cycle").src == "fox.jpg") {
                    document.getElementById("cycle").src = "hawk.jpg";
                } else {
                    document.getElementById("cycle").src = "ant.jpg";
                }
            }
        </script>

        <button onclick = "changeImg()">change image</button>
        <img id ="cycle" src ="fox.jpg"/>
    </body>
</html>
</code>```

答:
Use getAttribute('src') if you want to access the actual contents of the attribute. Otherwise you get the resolved URL.

```<code>var cycle = document.getElementById("cycle");
if (cycle.getAttribute('src') == "fox.jpg") {
    cycle.src = "hawk.jpg";
} else {
    cycle.src = "ant.jpg";
}
</code>```

Title: Cycling images with javascript

Body:
Why doesn't the second (hawk) image appear when the button is clicked? It goes straight to the else statement showing the ant image.

<!DOCTYPE html>

        <button onclick = "changeImg()">change image</button>

Body:
Use getAttribute('src') if you want to access the actual contents of the attribute. Otherwise you get the resolved URL.

var cycle = document.getElementById("cycle");
if (cycle.getAttribute('src') == "fox.jpg") {
    cycle.src = "hawk.jpg";
} else {
    cycle.src = "ant.jpg";
}


问:
Creating new columns to table
im trying to add new columns that i need it in my moduloe, bascailly i need to create 3 columns to the "sales_flat_order" table. I already created the php script that adds the sql and configure it on my config.xml, but after loading my shop, cleaning my cache, nothing is change, sorry if im missing something, this is my first module that im building and im still new in adding new tables or columns on magento.

My module structure is like:
- local/CompanyName/Mynewmodule/sql/invoicedocs_setup/mysql4-install-010.php

```<code>$installer = $this;
$installer->startSetup();

$installer->getConnection()
    ->addColumn($installer->getTable('sales/order'),'magnifinance_invoice_id', array(
        'type'      => Varien_Db_Ddl_Table::TYPE_INTEGER,
        'nullable'  => true,
        'length'    => 10,
        'after'     => 'status', // column name to insert new column after
        'comment'   => 'Company Invoice ID'
    ))
    ->addColumn($installer->getTable('sales/order'),'magnifinance_invoice_url', array(
        'type'      => Varien_Db_Ddl_Table::TYPE_TEXT,
        'nullable'  => true,
        'length'    => 255,
        'after'     => 'status', // column name to insert new column after
        'comment'   => 'Company Invoice URL Doc'
    ))
    ->addColumn($installer->getTable('sales/order'),'magnifinance_date', array(
        'type'      => Varien_Db_Ddl_Table::TYPE_DATETIME,
        'nullable'  => true,
        'after'     => 'status', // column name to insert new column after
        'comment'   => 'Company Invoice Date'
    ));
$installer->endSetup();

- local/CompanyName/Mynewmodule/etc/config.xml:

       <config>
            <global>
                <models>
                    <magnifinance>
                        <class>CompanyName_Mynewmodule_Model</class>
                    </magnifinance>
                </models>

                <resources>
                    <invoicedocs_setup>
                        <setup>
                            <module>CompanyName_Mynewmodule</module>
                            <class>Mage_Catalog_Model_Resource_Setup</class>
                        </setup>
                        <connection>
                            <use>core_setup</use>
                        </connection>
                    </invoicedocs_setup>
                    <invoicedocs_write>
                        <connection>
                            <use>core_write</use>
                        </connection>
                    </invoicedocs_write>
                    <invoicedocs_read>
                        <connection>
                            <use>core_read</use>
                        </connection>
                    </invoicedocs_read>
                </resources>
...
</code>```

Am i missing something?

答:
Please, verify if you have the section in the config.xml

```<code><modules>
   <CompanyName_Mynewmodule>
      <version>0.1.0</version>
   </CompanyName_Mynewmodule>
</modules>
</code>```

Try to rename the file mysql4-install-010.php to mysql4-install-0.1.0.php
(The numbers in the name of the file should be the same as the version in the config.xml)

Please, make sure the table core_resource doesn't have the row: invoicedocs_setup 0.1.0 0.1.0 before running the sql script. (If the row exists you will not be able to run the script. The row should appear after a successful installation)

Title: Creating new columns to table

Body:
im trying to add new columns that i need it in my moduloe, bascailly i need to create 3 columns to the "sales_flat_order" table. I already created the php script that adds the sql and configure it on my config.xml, but after loading my shop, cleaning my cache, nothing is change, sorry if im missing something, this is my first module that im building and im still new in adding new tables or columns on magento.

My module structure is like:
- local/CompanyName/Mynewmodule/sql/invoicedocs_setup/mysql4-install-010.php

$installer = $this;
$installer->startSetup();

$installer->getConnection()
    ->addColumn($installer->getTable('sales/order'),'magnifinance_invoice_id', array(
        'type'      => Varien_Db_Ddl_Table::TYPE_INTEGER,
        'nullable'  => true,
        'length'    => 10,
        'after'     => 'status', // column name to insert new column after
        'comment'   => 'Company Invoice ID'
    ))
    ->addColumn($installer->getTable('sales/order'),'magnifinance_invoice_url', array(
        'type'      => Varien_Db_Ddl_Table::TYPE_TEXT,
        'nullable'  => true,
        'length'    => 255,
        'after'     => 'status', // column name to insert new column after
        'comment'   => 'Company Invoice URL Doc'
    ))
    ->addColumn($installer->getTable('sales/order'),'magnifinance_date', array(
        'type'      => Varien_Db_Ddl_Table::TYPE_DATETIME,
        'nullable'  => true,
        'after'     => 'status', // column name to insert new column after
        'comment'   => 'Company Invoice Date'
    ));
$installer->endSetup();

- local/CompanyName/Mynewmodule/etc/config.xml:

       <config>
            <global>
                <models>
                    <magnifinance>
                        <class>CompanyName_Mynewmodule_Model</class>
                    </magnifinance>
                </models>

                <resources>
                    <invoicedocs_setup>
                        <setup>
                            <module>CompanyName_Mynewmodule</module>
                            <class>Mage_Catalog_Model_Resource_Setup</class>
                        </setup>
                        <connection>
                            <use>core_setup</use>
                        </connection>
                    </invoicedocs_setup>
                    <invoicedocs_write>
                        <connection>
                            <use>core_write</use>
                        </connection>
                    </invoicedocs_write>
                    <invoicedocs_read>
                        <connection>
                            <use>core_read</use>
                        </connection>
                    </invoicedocs_read>
                </resources>
...

Am i missing something?

Body:
Please, verify if you have the section in the config.xml

<modules>
   <CompanyName_Mynewmodule>
      <version>0.1.0</version>
   </CompanyName_Mynewmodule>
</modules>

Try to rename the file mysql4-install-010.php to mysql4-install-0.1.0.php
(The numbers in the name of the file should be the same as the version in the config.xml)

Please, make sure the table core_resource doesn't have the row: invoicedocs_setup 0.1.0 0.1.0 before running the sql script. (If the row exists you will not be able to run the script. The row should appear after a successful installation)


问:
Form Controls difference in using .shapes and using .buttons in code?
I have put several buttons in this macro and everything works great and looks great but I had a question about the code. As you can see down below, in this snippet of code, while using With Activesheet, the code then uses .Shapes AND .BUTTONS. It looks like .Shapes has more to do with sizing the button after it has been placed? and .BUTTONS has more to do with what it looks like and what it does?

I am just wondering what the difference in these are because at one point I use .BUTTONS to add the buttons, and then I use .shapes to change the size of the buttons. But then I use .Shapes to tell it what to do OnAction when clicked instead of .BUTTONS. What exactly is the difference in these properties? (or whatever it is called I am not sure) It just seems like they kind of intertwine and I am not too sure which to use and when.

```<code>With Activesheet
    .BUTTONS.Add(53.25, 36.75, 190.5, 41.25).Select
    .Shapes("Button 6").IncrementLeft 222.75
    .Shapes("Button 6").IncrementTop 147
    .BUTTONS("Button 6").Text = "Mexmo MFG"

    .BUTTONS("Button 10").Text = "10"
    .BUTTONS("Button 10").name = "Button 10"
    .BUTTONS("Button 11").Text = "11"
    .BUTTONS("Button 11").name = "Button 11"
    .BUTTONS("Button 12").Text = "12"
    .BUTTONS("Button 12").name = "Button 12"

    .Shapes("Atlanta MFG").OnAction = "Atlanta"
    .Shapes("Denver MFG").OnAction = "Denver"
    .Shapes("Jackson MFG").OnAction = "Jackson"
    .Shapes("Louisville MFG").OnAction = "Louisville"
End With
</code>```

答:
Extending @cyoashu's answer, it's worth noting that the .Buttons.Add() method returns the added button, so you can use that directly in your With block:

```<code>Sub test()
    With ActiveSheet.Buttons.Add(53.25, 36.75, 190.5, 41.25)
        .Name = "Blah"
        .Text = "Blah"
        .OnAction = "DoSomething"
        With .ShapeRange
            .IncrementLeft 222.75
            .IncrementTop 147
            .IncrementTop 147
        End With
    End With
End Sub
</code>```

... which spares you from having to know anything about the name of the just-added button.

Body:
I have put several buttons in this macro and everything works great and looks great but I had a question about the code. As you can see down below, in this snippet of code, while using With Activesheet, the code then uses .Shapes AND .BUTTONS. It looks like .Shapes has more to do with sizing the button after it has been placed? and .BUTTONS has more to do with what it looks like and what it does?

I am just wondering what the difference in these are because at one point I use .BUTTONS to add the buttons, and then I use .shapes to change the size of the buttons. But then I use .Shapes to tell it what to do OnAction when clicked instead of .BUTTONS. What exactly is the difference in these properties? (or whatever it is called I am not sure) It just seems like they kind of intertwine and I am not too sure which to use and when.

With Activesheet
    .BUTTONS.Add(53.25, 36.75, 190.5, 41.25).Select
    .Shapes("Button 6").IncrementLeft 222.75
    .Shapes("Button 6").IncrementTop 147
    .BUTTONS("Button 6").Text = "Mexmo MFG"

    .BUTTONS("Button 10").Text = "10"
    .BUTTONS("Button 10").name = "Button 10"
    .BUTTONS("Button 11").Text = "11"
    .BUTTONS("Button 11").name = "Button 11"
    .BUTTONS("Button 12").Text = "12"
    .BUTTONS("Button 12").name = "Button 12"

    .Shapes("Atlanta MFG").OnAction = "Atlanta"
    .Shapes("Denver MFG").OnAction = "Denver"
    .Shapes("Jackson MFG").OnAction = "Jackson"
    .Shapes("Louisville MFG").OnAction = "Louisville"
End With

Body:
Extending @cyoashu's answer, it's worth noting that the .Buttons.Add() method returns the added button, so you can use that directly in your With block:

Sub test()
    With ActiveSheet.Buttons.Add(53.25, 36.75, 190.5, 41.25)
        .Name = "Blah"
        .Text = "Blah"
        .OnAction = "DoSomething"
        With .ShapeRange
            .IncrementLeft 222.75
            .IncrementTop 147
            .IncrementTop 147
        End With
    End With
End Sub

... which spares you from having to know anything about the name of the just-added button.


问:
Partitioning an arraylist into Map buckets
I have two ArrayLists of type String ArrayList<String> xList and ArrayList<String> yList and I want to partition one list into buckets, according to someAttribute (for the below example lets say it uses .contains().

```<code>   Map<String, List<String>> yBuckets = new HashMap<>();
             yList.forEach(y -> yBuckets.compute(y.contains("I'm here"), (k,v) ->
                     (v == null ? new ArrayList<>() : v).add(y)));
</code>```

However I'm getting an incompatible types error (String can't be converted to Boolean). I've never really used Java 8 to date but it seems to be useful for what I want so I'm wondering if anyone would be able to tell me how i'd go about fixing this code.
Thanks

答:
There are 2 mistakes in your code. The first one is that if you want to partition based on .contains which returns a boolean your map needs to be Map<Boolean, List<String>>.

The second mistake is with parenthesis. The (k,v) ->... lambda needs to return List<String> because you put .add(y) inside the lambda it return a boolean you need to add to the list returned by compute like so:

```<code>yList.forEach(y -> yBuckets.compute(y.contains("I'm here"), (k,v) ->
(v == null ? new ArrayList<>() : v)).add(y));
</code>```

Body:
I have two ArrayLists of type String ArrayList<String> xList and ArrayList<String> yList and I want to partition one list into buckets, according to someAttribute (for the below example lets say it uses .contains().

   Map<String, List<String>> yBuckets = new HashMap<>();
             yList.forEach(y -> yBuckets.compute(y.contains("I'm here"), (k,v) ->
                     (v == null ? new ArrayList<>() : v).add(y)));

However I'm getting an incompatible types error (String can't be converted to Boolean). I've never really used Java 8 to date but it seems to be useful for what I want so I'm wondering if anyone would be able to tell me how i'd go about fixing this code.
Thanks

Body:
There are 2 mistakes in your code. The first one is that if you want to partition based on .contains which returns a boolean your map needs to be Map<Boolean, List<String>>.

The second mistake is with parenthesis. The (k,v) ->... lambda needs to return List<String> because you put .add(y) inside the lambda it return a boolean you need to add to the list returned by compute like so:

yList.forEach(y -> yBuckets.compute(y.contains("I'm here"), (k,v) ->
(v == null ? new ArrayList<>() : v)).add(y));


问:
Database design for high sample rate data, graphing at multiple zoom levels
I've got multiple sensors feeding data to my web app. Each channel is 5 samples per second and the data gets uploaded bundled together in 1 minute json messages (containing 300 samples).
The data will be graphed using flot at multiple zoom levels from 1 day to 1 minute.

I'm using Amazon SimpleDB and I'm currently storing the data in the 1 minute chunks that I receive it in. This works well for high zoom levels, but for full days there will be simply be too many rows to retrieve.

The idea I've currently got is that every hour I can crawl through the data and collect together 300 samples for the last hour and store them in another table, essentially down-sampling the data.

Does this sound like a reasonable solution? How have others implemented the same sort of systems?

答:
Storing downsampled data is perfectly fine approach.
Check out how munin stores it's graphs - dayly, mounthly, early and intraday graphs are stored separately there.

You may store data for each minute, each 5 minutes, each hour, each 4 hours, each day in different tables. Overhead is very little in comparison to just storing every minute with lots of benefit as you don't transmit what you don't need to.


问:
Queryset in Django if empty field returns all elements
I want to do a filter in Django that uses form method.
If the user type de var it should query in the dataset that var, if it is left in blank to should bring all the elements.

How can I do that?

I am new in Django

```<code>if request.GET.get('Var'):
    Var = request.GET.get('Var')
else:
    Var = WHAT SHOULD I PUT HERE TO FILTER ALL THE ELEMNTS IN THE CODE BELLOW

models.objects.filter(Var=Var)
</code>```

答:
A simpler and more explicit way of doing this would be:</p>

```<code>if request.GET.get('Var'):
    data = models.objects.filter(Var=request.GET.get('Var'))
else:
    data = models.objects.all()
</code>```

Body:
I want to do a filter in Django that uses form method.
If the user type de var it should query in the dataset that var, if it is left in blank to should bring all the elements.

How can I do that?

I am new in Django

if request.GET.get('Var'):
    Var = request.GET.get('Var')
else:
    Var = WHAT SHOULD I PUT HERE TO FILTER ALL THE ELEMNTS IN THE CODE BELLOW

models.objects.filter(Var=Var)

Body:
A simpler and more explicit way of doing this would be:

if request.GET.get('Var'):
    data = models.objects.filter(Var=request.GET.get('Var'))
else:
    data = models.objects.all()


问:
C language-> Read a file to a dynamic array
So I have a file that as some text and I want my function to read that file and store it on an array. I did some code and when I print my dynamic array it prints crap values :< help.</p>

```<code>char* read_message(char *filename)
{   //gets the PATH of the txt file
    char *file_contents;
    long input_file_size;
    FILE *input_file = fopen(filename, "r");
    if(input_file == NULL)
    {
         return NULL;
    }
    fseek(input_file, 0, SEEK_END);
    input_file_size = ftell(input_file);
    rewind(input_file);
    file_contents = (char*)malloc(input_file_size+1 * (sizeof(char)));
    fread(file_contents, input_file_size, 1, input_file);
    printf("%s",file_contents);//----Prints crap--------
    fclose(input_file);
                                                  // returns the address to the array of strings
    return file_contents;
}
</code>```

答:
You read in the contents of the file into a char array.  At that point you do not yet have a string but an array of characters because there is no terminating null byte at the end.

When you then use printf to print this array, it reads the uninitialized byte at the end of the allocated memory segment (and possibly several bytes after it that are not part of allocated memory).  Reading uninitialized bytes invokes undefined behavior.

Because calling fread does not add a terminating null byte after what was read, you need to do that yourself:

```<code>fread(file_contents, input_file_size, 1, input_file);
file_contents[input_file_size] = 0;
</code>```

Body:
So I have a file that as some text and I want my function to read that file and store it on an array. I did some code and when I print my dynamic array it prints crap values :< help.

char* read_message(char *filename)
{   //gets the PATH of the txt file
    char *file_contents;
    long input_file_size;
    FILE *input_file = fopen(filename, "r");
    if(input_file == NULL)
    {
         return NULL;
    }
    fseek(input_file, 0, SEEK_END);
    input_file_size = ftell(input_file);
    rewind(input_file);
    file_contents = (char*)malloc(input_file_size+1 * (sizeof(char)));
    fread(file_contents, input_file_size, 1, input_file);
    printf("%s",file_contents);//----Prints crap--------
    fclose(input_file);
                                                  // returns the address to the array of strings
    return file_contents;
}

Body:
You read in the contents of the file into a char array.  At that point you do not yet have a string but an array of characters because there is no terminating null byte at the end.

When you then use printf to print this array, it reads the uninitialized byte at the end of the allocated memory segment (and possibly several bytes after it that are not part of allocated memory).  Reading uninitialized bytes invokes undefined behavior.

Because calling fread does not add a terminating null byte after what was read, you need to do that yourself:

fread(file_contents, input_file_size, 1, input_file);
file_contents[input_file_size] = 0;


问:
Excel macro to compare two ranges for perfect match
When  I run a macro, I'd like a message to pop up if the values for L6:L29 match, row to row, the values in M6:M29.

The long and inefficient way to write this might be:

```<code>Public Sub MyMacro()
    If Range("L6").Value = Range("M6).Value
AND Range("L7").Value = Range("M7).Value
AND Range("L8").Value = Range("M8).Value
etc.
    Then
        MsgBox "Both columns match!.", vbInformation, "Match!"
    Exit Sub
End If

...

End Sub
</code>```

But I'm looking for more efficient code that can evaluate each row in the two columns/ranges without having to specify each pair.

I did see the below answer to a similar question, but it evaluates only one row (in this case, #5). I need to evaluate every row in the range: Fastest way to check if two ranges are equal in excel vba

```<code>Sub RowCompare()
    Dim ary1() As Variant
    Dim Range1 As Range, Range2 As Range, rr1 As Range, rr2 As Range
    Set Range1 = Range("B9:F20")
    Set Range2 = Range("I16:M27")
    Set rr1 = Range1.Rows(5)
    Set rr2 = Range2.Rows(5)
    ary1 = Application.Transpose(Application.Transpose(rr1))
    ary2 = Application.Transpose(Application.Transpose(rr2))
    st1 = Join(ary1, ",")
    st2 = Join(ary2, ",")
    If st1 = st2 Then
        MsgBox "the same"
    Else
        MsgBox "different"
    End If
End Sub
</code>```

答:
Try this:

```<code>Option Explicit
</code>```

```<code>Sub RowCompare()

    Dim i As Long
    Dim ComparisionResult As Boolean

    For i = 6 To 29
        If IIf(Cells(i, 12).Value = "", "", Cells(i, 12).Value) = IIf(Cells(i, 13).Value = "", "", Cells(i, 13).Value) Then
            ComparisionResult = True
        Else
            ComparisionResult = False
            Exit For
        End If
    Next i

   If ComparisionResult Then MsgBox "Both columns match!", vbInformation, "Match!" Else _
        MsgBox "different", vbInformation, "Match!"

End Sub
</code>```

Body:
When  I run a macro, I'd like a message to pop up if the values for L6:L29 match, row to row, the values in M6:M29.

The long and inefficient way to write this might be:

Public Sub MyMacro()
    If Range("L6").Value = Range("M6).Value
AND Range("L7").Value = Range("M7).Value
AND Range("L8").Value = Range("M8).Value
etc.
    Then
        MsgBox "Both columns match!.", vbInformation, "Match!"
    Exit Sub
End If

...

End Sub

But I'm looking for more efficient code that can evaluate each row in the two columns/ranges without having to specify each pair.

I did see the below answer to a similar question, but it evaluates only one row (in this case, #5). I need to evaluate every row in the range: Fastest way to check if two ranges are equal in excel vba

Sub RowCompare()
    Dim ary1() As Variant
    Dim Range1 As Range, Range2 As Range, rr1 As Range, rr2 As Range
    Set Range1 = Range("B9:F20")
    Set Range2 = Range("I16:M27")
    Set rr1 = Range1.Rows(5)
    Set rr2 = Range2.Rows(5)
    ary1 = Application.Transpose(Application.Transpose(rr1))
    ary2 = Application.Transpose(Application.Transpose(rr2))
    st1 = Join(ary1, ",")
    st2 = Join(ary2, ",")
    If st1 = st2 Then
        MsgBox "the same"
    Else
        MsgBox "different"
    End If
End Sub

Body:
Try this:

Option Explicit

Sub RowCompare()

    Dim i As Long
    Dim ComparisionResult As Boolean

    For i = 6 To 29
        If IIf(Cells(i, 12).Value = "", "", Cells(i, 12).Value) = IIf(Cells(i, 13).Value = "", "", Cells(i, 13).Value) Then
            ComparisionResult = True
        Else
            ComparisionResult = False
            Exit For
        End If
    Next i

   If ComparisionResult Then MsgBox "Both columns match!", vbInformation, "Match!" Else _
        MsgBox "different", vbInformation, "Match!"

End Sub


问:
Nodejs Read very large file(~10GB), Process line by line then write to other file
I have a 10 GB log file in a particular format, I want to process this file line by line and then write the output to other file after applying some transformations. I am using node for this operation.

Though this method is fine but it takes a hell lot of time to do this. I was able to do this within 30-45 mins in JAVA, but in node it is taking more than 160 minutes to do the same job. Following is the code:

Following is the initiation code which reads each line from the input.

```<code>var path = '../10GB_input_file.txt';
var output_file = '../output.txt';

function fileopsmain(){

    fs.exists(output_file, function(exists){
        if(exists) {
            fs.unlink(output_file, function (err) {
                if (err) throw err;
                console.log('successfully deleted ' + output_file);
            });
        }
    });

    new lazy(fs.createReadStream(path, {bufferSize: 128 * 4096}))
        .lines
        .forEach(function(line){
            var line_arr = line.toString().split(';');
            perform_line_ops(line_arr, line_arr[6], line_arr[7], line_arr[10]);
        }
    );

}
</code>```

This is the method that performs some operation over that line and
  passes the input to write method to write it into the output file.

```<code>function perform_line_ops(line_arr, range_start, range_end, daynums){

    var _new_lines = '';
    for(var i=0; i<days; i++){
        //perform some operation to modify line pass it to print
    }

    write_line_ops(_new_lines);
}
</code>```

Following method is used to write data into a new file.

```<code>function write_line_ops(line) {
    if(line != null && line != ''){
        fs.appendFileSync(output_file, line);
    }
}
</code>```

I want to bring this time down to 15-20 mins. Is it possible to do so.

Also for the record I'm trying this on a intel i7 processor with 8 GB of RAM.

答:
I know this is old but...

At a guess  appendFileSync()  _write()_s to the file system and waits for the response. Lots of small writes are generally expensive, presuming you use a BufferedWriter in Java you might get faster results by skipping some write()s.

Use one of the async writes and see if node buffers sensibly, or write the lines to large node Buffer until it is full and always write a full (or nearly full) Buffer. By tuning the buffer size you could validate if the number of writes affects perf.  I suspect it would.

Body:
I have a 10 GB log file in a particular format, I want to process this file line by line and then write the output to other file after applying some transformations. I am using node for this operation.

Though this method is fine but it takes a hell lot of time to do this. I was able to do this within 30-45 mins in JAVA, but in node it is taking more than 160 minutes to do the same job. Following is the code:

Following is the initiation code which reads each line from the input.

var path = '../10GB_input_file.txt';
var output_file = '../output.txt';

function fileopsmain(){

    fs.exists(output_file, function(exists){
        if(exists) {
            fs.unlink(output_file, function (err) {
                if (err) throw err;
                console.log('successfully deleted ' + output_file);
            });
        }
    });

    new lazy(fs.createReadStream(path, {bufferSize: 128 * 4096}))
        .lines
        .forEach(function(line){
            var line_arr = line.toString().split(';');
            perform_line_ops(line_arr, line_arr[6], line_arr[7], line_arr[10]);
        }
    );

}

This is the method that performs some operation over that line and
  passes the input to write method to write it into the output file.

function perform_line_ops(line_arr, range_start, range_end, daynums){

    var _new_lines = '';
    for(var i=0; i<days; i++){
        //perform some operation to modify line pass it to print
    }

    write_line_ops(_new_lines);
}

Following method is used to write data into a new file.

function write_line_ops(line) {
    if(line != null && line != ''){
        fs.appendFileSync(output_file, line);
    }
}

I want to bring this time down to 15-20 mins. Is it possible to do so.

Also for the record I'm trying this on a intel i7 processor with 8 GB of RAM.