问:
bind dropdown with XML file
I have this XML file:

```<code><questions>
  <question id="title">
    <option>
      <text>Mr</text>
      <value>Mr</value>
    </option>
    <option>
      <text>Ms</text>
      <value>Ms</value>
    </option>
  </question>
  <question id="organisation">
    <option>
      <text>org1</text>
      <value>org1</value>
    </option>
    <option>
      <text>org2</text>
      <value>org2</value>
    </option>
  </question>
</questions>
</code>```

How do I bind each question to a specific drop-down in c#?

Thanks

答:
You could use a XmlDataSource. Because your XML is not conform to what this control expects you will need to adapt it by using a XSL transformation.

So Step 1:

Define a XSL transformation (~/App_Data/questions.xslt):

```<code><?xml version="1.0" encoding="utf-8" ?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:template match="questions">
    <questions>
      <xsl:apply-templates select="question"/>
    </questions>
  </xsl:template>
  <xsl:template match="option">
    <option>
      <xsl:attribute name="text">
        <xsl:value-of select="text"/>
      </xsl:attribute>
      <xsl:attribute name="value">
        <xsl:value-of select="value"/>
      </xsl:attribute>
    </option>
  </xsl:template>
</xsl:stylesheet>
</code>```

Step 2:

Use it:

```<code><%@ Page Language="C#" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head id="Head1" runat="server">
    <title></title>
</head>
<body>
    <form id="Form1" runat="server">
        <asp:DropDownList
            ID="ddl"
            runat="server"
            DataSourceID="ds"
            DataTextField="text"
            DataValueField="value"
        />

        <asp:XmlDataSource
            ID="ds"
            runat="server"
            DataFile="~/App_Data/questions.xml"
            TransformFile="~/App_Data/questions.xslt"
            XPath="//option"
        />
    </form>
</body>
</html>
</code>```

Notice how the TransformFile property on the data source is pointing to the XSL file.

Title: bind dropdown with XML file

Body:
I have this XML file:

<questions>
  <question id="title">
    <option>
      <text>Mr</text>
      <value>Mr</value>
    </option>
    <option>
      <text>Ms</text>
      <value>Ms</value>
    </option>
  </question>
  <question id="organisation">
    <option>
      <text>org1</text>
      <value>org1</value>
    </option>
    <option>
      <text>org2</text>
      <value>org2</value>
    </option>
  </question>
</questions>

How do I bind each question to a specific drop-down in c#?

Thanks

Body:
You could use a XmlDataSource. Because your XML is not conform to what this control expects you will need to adapt it by using a XSL transformation.

So Step 1:

Define a XSL transformation (~/App_Data/questions.xslt):

<?xml version="1.0" encoding="utf-8" ?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:template match="questions">
    <questions>
      <xsl:apply-templates select="question"/>
    </questions>
  </xsl:template>
  <xsl:template match="option">
    <option>
      <xsl:attribute name="text">
        <xsl:value-of select="text"/>
      </xsl:attribute>
      <xsl:attribute name="value">
        <xsl:value-of select="value"/>
      </xsl:attribute>
    </option>
  </xsl:template>
</xsl:stylesheet>

Step 2:

Use it:

<%@ Page Language="C#" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head id="Head1" runat="server">
    <title></title>
</head>
<body>
    <form id="Form1" runat="server">
        <asp:DropDownList
            ID="ddl"
            runat="server"
            DataSourceID="ds"
            DataTextField="text"
            DataValueField="value"
        />

        <asp:XmlDataSource
            ID="ds"
            runat="server"
            DataFile="~/App_Data/questions.xml"
            TransformFile="~/App_Data/questions.xslt"
            XPath="//option"
        />
    </form>
</body>
</html>

Notice how the TransformFile property on the data source is pointing to the XSL file.


来源: stackexchange

问:
Webpack Compliling failing at first sign of React object
Error occurring

```<code>ERROR in ./react/index.js
Module parse failed: /Users/jankiewicz/projects/hack-a-thon
management/react/index.js Unexpected token (16:2)
You may need an appropriate loader to handle this file type.
|
| render(
|   <App />,
|   document.getElementById('container')
| )
 @ multi (webpack)-dev-server/client?http://localhost:8080 webpack/hot/dev-
 server ./index.js
</code>```

Web Pack

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

module.exports = {
   devtool: 'inline-sourcemap',
   context: __dirname + "/react",
   entry: './index.js',
output: {
   path: __dirname + "/public",
   filename: 'bundle.js'
 },
 module: {
   loaders: [
    {
    test: /\.(js|jsx)$/,
    include: [
       path.resolve(__dirname, "/react")
     ],
    loaders: [
      'react-hot',
      'babel',
        ]
       }
      ]
    }
   };
</code>```

React entry file

```<code>import React, { Component, PropTypes } from 'react';
import ReactDOM from 'react-dom';

import App from './container/app';

//The error is occurring at "<App />"
ReactDOM.render(
   <App />,
 document.getElementById('container')
)
</code>```

I am loosing my mind. I can't figure out why this isn't working. I ran some module exports to receive strings from other files and they are all working fine. It's just my react wont render.

Package.json dev command

```<code>           {
        "name": "jwt",
        "version": "1.0.0",
        "description": "",
        "main": "index.js",
        "scripts": {
          "prestart": "npm run lint",
          "start": "node index.js",
          "dev": "nodemon & webpack-dev-server --progress --inline --hot",
          "build": "npm run lint & webpack",
          "lint": "eslint ./src/**/*.{js, jsx} --fix",
          "test": "echo \"Error: no test specified\" && exit 1"
        },
        "author": "",
        "license": "ISC",
        "dependencies": {
          "axios": "^0.15.3",
          "bcryptjs": "^2.4.3",
          "body": "^5.1.0",
          "body-parser": "^1.17.0",
          "cookie-parser": "^1.4.3",
          "ejs": "^2.5.6",
          "es6-promise": "^4.1.0",
          "express": "^4.15.0",
          "express-jwt": "^5.1.0",
          "isomorphic-fetch": "^2.2.1",
          "mongodb": "^2.2.24",
          "mongoose": "^4.8.5",
          "morgan": "^1.8.1",
          "node-fetch": "^1.6.3",
          "parser": "^0.1.4",
          "path": "^0.12.7",
          "react": "^15.4.2",
          "react-dom": "^15.4.2",
          "react-hot-loader": "^1.3.1",
          "react-redux": "^5.0.3",
          "redux": "^3.6.0",
          "redux-promise-middleware": "^4.2.0",
          "redux-thunk": "^2.2.0",
          "request": "^2.81.0"
        },
        "devDependencies": {
          "babel-core": "^6.24.0",
          "babel-eslint": "^7.2.1",
          "babel-loader": "^6.4.1",
          "babel-preset-es2015": "^6.24.0",
          "babel-preset-react": "^6.23.0",
          "babel-preset-stage-0": "^6.22.0",
          "eslint": "^3.18.0",
          "eslint-plugin-react": "^6.10.3",
          "nodemon": "^1.11.0",
          "path": "^0.12.7",
          "react-hot-loader": "^1.3.1",
          "redux-logger": "^3.0.1",
          "webpack": "^2.3.1",
          "webpack-dev-server": "^2.4.2"
        }
      }
</code>```

答:
Your loaders are not applied to ./react/index.js because in the include you use path.resolve and you give it an absolute path, which means it stops there and ignores the __dirname. What you're really including is /react/, which is the root of your file system, not the project.

You need to remove the leading /:

```<code>include: [
   path.resolve(__dirname, "react")
],
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Error occurring

ERROR in ./react/index.js
Module parse failed: /Users/jankiewicz/projects/hack-a-thon
management/react/index.js Unexpected token (16:2)
You may need an appropriate loader to handle this file type.
|
| render(
|   <App />,
|   document.getElementById('container')
| )
 @ multi (webpack)-dev-server/client?http://localhost:8080 webpack/hot/dev-
 server ./index.js

Web Pack

var path = require('path');

module.exports = {
   devtool: 'inline-sourcemap',
   context: __dirname + "/react",
   entry: './index.js',
output: {
   path: __dirname + "/public",
   filename: 'bundle.js'
 },
 module: {
   loaders: [
    {
    test: /\.(js|jsx)$/,
    include: [
       path.resolve(__dirname, "/react")
     ],
    loaders: [
      'react-hot',
      'babel',
        ]
       }
      ]
    }
   };

React entry file

import React, { Component, PropTypes } from 'react';
import ReactDOM from 'react-dom';

import App from './container/app';

//The error is occurring at "<App />"
ReactDOM.render(
   <App />,
 document.getElementById('container')
)

I am loosing my mind. I can't figure out why this isn't working. I ran some module exports to receive strings from other files and they are all working fine. It's just my react wont render.

Package.json dev command

           {
        "name": "jwt",
        "version": "1.0.0",
        "description": "",
        "main": "index.js",
        "scripts": {
          "prestart": "npm run lint",
          "start": "node index.js",
          "dev": "nodemon & webpack-dev-server --progress --inline --hot",
          "build": "npm run lint & webpack",
          "lint": "eslint ./src/**/*.{js, jsx} --fix",
          "test": "echo \"Error: no test specified\" && exit 1"
        },
        "author": "",
        "license": "ISC",
        "dependencies": {
          "axios": "^0.15.3",
          "bcryptjs": "^2.4.3",
          "body": "^5.1.0",
          "body-parser": "^1.17.0",
          "cookie-parser": "^1.4.3",
          "ejs": "^2.5.6",
          "es6-promise": "^4.1.0",
          "express": "^4.15.0",
          "express-jwt": "^5.1.0",
          "isomorphic-fetch": "^2.2.1",
          "mongodb": "^2.2.24",
          "mongoose": "^4.8.5",
          "morgan": "^1.8.1",
          "node-fetch": "^1.6.3",
          "parser": "^0.1.4",
          "path": "^0.12.7",
          "react": "^15.4.2",
          "react-dom": "^15.4.2",
          "react-hot-loader": "^1.3.1",
          "react-redux": "^5.0.3",
          "redux": "^3.6.0",
          "redux-promise-middleware": "^4.2.0",
          "redux-thunk": "^2.2.0",
          "request": "^2.81.0"
        },
        "devDependencies": {
          "babel-core": "^6.24.0",
          "babel-eslint": "^7.2.1",
          "babel-loader": "^6.4.1",
          "babel-preset-es2015": "^6.24.0",
          "babel-preset-react": "^6.23.0",
          "babel-preset-stage-0": "^6.22.0",
          "eslint": "^3.18.0",
          "eslint-plugin-react": "^6.10.3",
          "nodemon": "^1.11.0",
          "path": "^0.12.7",
          "react-hot-loader": "^1.3.1",
          "redux-logger": "^3.0.1",
          "webpack": "^2.3.1",
          "webpack-dev-server": "^2.4.2"
        }
      }

Body:
Your loaders are not applied to ./react/index.js because in the include you use path.resolve and you give it an absolute path, which means it stops there and ignores the __dirname. What you're really including is /react/, which is the root of your file system, not the project.

You need to remove the leading /:

include: [
   path.resolve(__dirname, "react")
],


问:
Dictionary is getting overriden while adding another entry
I have a function to create dictionary

```<code>def Bowler_creator (Name):

    """
    This function will create the dictionaries for the batting player

    """
    global bowler;
    bowler =    {
            Name : { "number_of_overs":0.0,
                    "number_of_runs":0,
                    "number_of_wickets":0,
                    'economy_rate':0.0,
                    'Maiden overs':0
                    },

                }
Current_Bowler = input("Enter the bowler's name\n");

Bowler_creator(Current_Bowler);
Bowler_creator('jafda');
</code>```

My idea is that i will be calling this function like below so that new key with the same entry values will be created for this dictionary

So as per my idea, the dictionary should have created two elements with two keys Current_Bowler and jafda, but after I try to print the dictionary it´s returning the latest one only. Could you please let me know why my dictionary is getting overridden with a newer key?

答:
You are creating a new dictionary every time in the function Bowler_creator.
Try doing

```<code>bowler[Name] = { "number_of_overs":0.0,
                    "number_of_runs":0,
                    "number_of_wickets":0,
                    'economy_rate':0.0,
                    'Maiden overs':0
               }
</code>```

Body:
I have a function to create dictionary

def Bowler_creator (Name):

    """
    This function will create the dictionaries for the batting player

    """
    global bowler;
    bowler =    {
            Name : { "number_of_overs":0.0,
                    "number_of_runs":0,
                    "number_of_wickets":0,
                    'economy_rate':0.0,
                    'Maiden overs':0
                    },

                }
Current_Bowler = input("Enter the bowler's name\n");

Bowler_creator(Current_Bowler);
Bowler_creator('jafda');

My idea is that i will be calling this function like below so that new key with the same entry values will be created for this dictionary

So as per my idea, the dictionary should have created two elements with two keys Current_Bowler and jafda, but after I try to print the dictionary it´s returning the latest one only. Could you please let me know why my dictionary is getting overridden with a newer key?

Body:
You are creating a new dictionary every time in the function Bowler_creator.
Try doing

bowler[Name] = { "number_of_overs":0.0,
                    "number_of_runs":0,
                    "number_of_wickets":0,
                    'economy_rate':0.0,
                    'Maiden overs':0
               }


问:
Is-k-Substring function with a suffix tree
How can I do the next operation, with a suffix tree of string s, who's number of vertices is bounded by O(|s|):

Is-k-Sub-string(r) - checks if string r is a k-sub-string of s, where a k-sub-string defined as follow:

A sub-string r of s defined as k-sub-string if there is a partition of s to sub-strings for which:

r=x1x2...xk;
xi = sub-string of s.

Example: s = whitething, r = within, r is 3-sub-string of s.

I need that operation to work in complexity of O(|r|).

I don't understand how to do that on O(|r|), because each character in r can be the current delimiter, for example with 2-Sub-string, so for that I must to try all the possible characters as delimiters between x1 and x2 (for the partition r=x1x2).

Any ideas ?

答:
Lemma: If A is a suffix of B and B can be split into at most k substrings of S, so can A.

Proof: let B = x[1] x[2] x[3] ... x[k]. Let's throw away the first |B| - |A| characters of the partition. We'll get a partition with no more than k parts.

Corollary: if we have a fixed partition of some prefix of R, there's an optimal partition in which the next substring is the longest one we can take.

The solution immediately follows from the statements proven above. We can make each part as long as we can:

```<code>pos = 0
while pos < R.length:
      take the longest prefix of R[pos:] that is a substring of R
      move pos after the end of this substring
</code>```

This solution can be implemented in linear time: we can just start from the root of the tree and keep going as long their a transition for the current character of R. If there's none, we add the current part to the answer and restart from the root.

Body:
Lemma: If A is a suffix of B and B can be split into at most k substrings of S, so can A.

Proof: let B = x[1] x[2] x[3] ... x[k]. Let's throw away the first |B| - |A| characters of the partition. We'll get a partition with no more than k parts.

Corollary: if we have a fixed partition of some prefix of R, there's an optimal partition in which the next substring is the longest one we can take.

The solution immediately follows from the statements proven above. We can make each part as long as we can:

pos = 0
while pos < R.length:
      take the longest prefix of R[pos:] that is a substring of R
      move pos after the end of this substring

This solution can be implemented in linear time: we can just start from the root of the tree and keep going as long their a transition for the current character of R. If there's none, we add the current part to the answer and restart from the root.


问:
Copy conditional formatting based on cell content to other rows
I have a sheet which contains all usernames and email addresses of my database

In another sheet i have a column saying "username", in here I want to enter usernames, if a username entered here is already in the list on the other sheet the field content should change color to red.

I figured out how to do conditional formatting on the cell, so I made this formula:

```<code>=COUNTIF('Usernames and emails'!A5:A1450;$A$7)>0
</code>```

This formula works great for the cell in A7.

However when I drag A7 all the way to the bottom of my table, the conditional formatting formula is not copied. When i for example type in the same username in A8 as i did in A7, the A7 field would turn red but A8 would remain unchanged.

I need this formatting on about 1000+ fields, so making a rule for every single one of them cannot be the solution?

Example:

Worksheet : Usernames and emails:

```<code>test1
test2
test3
</code>```

Worksheet : i have to enter usernames in every row in the A column, so i enter them like this:

```<code>A1 : test
A2 : test1
A3 : test4
A4 : test3
</code>```

in this example, A2 and A4 should be colored in red since they have a value that corresponds to a value in my "usernames and emails" worksheet list

答:
According to here, you can use

```<code>=MATCH(A1,'Usernames and emails'!A:A,0)
</code>```

I tested this on some made up data and it worked (though note that some people in that thread seem to have had some issues).

Aside for that, you should probably anchor your whole range, and not the comparative cell, thus:

```<code>=COUNTIF('Usernames and emails'!$A$5:$A$1450;$A7)>0
</code>```

Body:
I have a sheet which contains all usernames and email addresses of my database

In another sheet i have a column saying "username", in here I want to enter usernames, if a username entered here is already in the list on the other sheet the field content should change color to red.

I figured out how to do conditional formatting on the cell, so I made this formula:

=COUNTIF('Usernames and emails'!A5:A1450;$A$7)>0

This formula works great for the cell in A7.

However when I drag A7 all the way to the bottom of my table, the conditional formatting formula is not copied. When i for example type in the same username in A8 as i did in A7, the A7 field would turn red but A8 would remain unchanged.

I need this formatting on about 1000+ fields, so making a rule for every single one of them cannot be the solution?

Example:

Worksheet : Usernames and emails:

test1
test2
test3

Worksheet : i have to enter usernames in every row in the A column, so i enter them like this:

A1 : test
A2 : test1
A3 : test4
A4 : test3

in this example, A2 and A4 should be colored in red since they have a value that corresponds to a value in my "usernames and emails" worksheet list

Body:
According to here, you can use

=MATCH(A1,'Usernames and emails'!A:A,0)

I tested this on some made up data and it worked (though note that some people in that thread seem to have had some issues).

Aside for that, you should probably anchor your whole range, and not the comparative cell, thus:

=COUNTIF('Usernames and emails'!$A$5:$A$1450;$A7)>0


问:
How to reduce array of numbers to an array with given length with with low information loss
I'm building an audio app for iOS and I need to capture audio from the mic and visualize it. I'm using AudioKit to receive amplitude data (from AKAmplitudeTracker) every 0.1 sec and store it to an array. This results in nice precision, but this results in 600 values/minute to be stored in array. I'm building a waveform plot from data stored in this array, and its impossible to keep needed appearance with thousands of waveforms. I'm looking for a way to reduce number of elements in array with low information loss to a given specific number, like 256 or 512. I'm unfamiliar with terminology of this field so any help is appreciated.</p>

答:
You need to resample the array by choosing evenly spaced samples.  Here is a little generic routine that does that:

```<code>func resample<T>(array: [T], toSize newSize: Int) -> [T] {
    let size = array.count
    return (0 ..< newSize).map { array[$0 * size / newSize] }
}
</code>```

Downsample example:

```<code>// Create array [0, 1, 2, ..., 98, 99, 100]
let arr = (0...100).map { $0 }

// Downsample it to 15 items
let sampled = resample(array: arr, toSize: 15)
print(sampled)
</code>```

```<code>[0, 6, 13, 20, 26, 33, 40, 47, 53, 60, 67, 74, 80, 87, 94]
</code>```

Upsample example:

```<code>// Create array [0, 1, 2, 3, 4]
let arr2 = (0...4).map { $0 }

// Upsample it to 15 items
let sampled2 = resample(array: arr2, toSize: 15)
print(sampled2)
</code>```

```<code>[0, 0, 0, 1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4]
</code>```

Body:
You need to resample the array by choosing evenly spaced samples.  Here is a little generic routine that does that:

func resample<T>(array: [T], toSize newSize: Int) -> [T] {
    let size = array.count
    return (0 ..< newSize).map { array[$0 * size / newSize] }
}

Downsample example:

// Create array [0, 1, 2, ..., 98, 99, 100]
let arr = (0...100).map { $0 }

// Downsample it to 15 items
let sampled = resample(array: arr, toSize: 15)
print(sampled)

[0, 6, 13, 20, 26, 33, 40, 47, 53, 60, 67, 74, 80, 87, 94]

Upsample example:

// Create array [0, 1, 2, 3, 4]
let arr2 = (0...4).map { $0 }

// Upsample it to 15 items
let sampled2 = resample(array: arr2, toSize: 15)
print(sampled2)

[0, 0, 0, 1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4]


问:
Logic error in Recursive method
Im trying to write a program that uses a recursive method to calculate how many months it will take to reach a goal of 10 million total invested if the same amount of money(inputted by the user) is invested with a 2 percent interest added each month. The problem is the method is returning counter too early so my "months" output is inaccurate. My guess is that my last else statement is wrong or my counter is placed incorrectly

Heres my code

```<code>   import java.util.Scanner;
    public class MoneyMakerRecursion {
        public static int counter = 0;
        public static void main(String[] args) {
            //Variables declared
            Scanner userInput = new Scanner(System.in);
            double investment;
            //User is prompted for input
            System.out.println("Enter your monthly investment: ");
            investment = userInput.nextInt();
            //Method is called
            Sum(investment);
            //Results from recursive method output
            System.out.println("It should take " + counter + " month(s) to reach your goal of $10,000,000");
        }
        //recursive Method
        public static double Sum(double investment) {
            counter++;
            double total = (investment * 0.02) + investment;
            if(total >= 10000000) {return counter;}
            else {return Sum(investment+total);}
        }
    }
</code>```

答:
Important point you missed is that your monthly investment is same throughout all months. Hence it should be static variable.

Second point you were adding investment to total which was local variable to that method. Which is not a actual investment for month. its a value passed to that function which changes for each month(Consider your code for this statement)

See below working code.

```<code>import java.util.Scanner;
    public class MoneyMakerRecursion {
        public static int counter = 0;
        public static double investment = 0;
        public static void main(String[] args) {
            //Variables declared
            Scanner userInput = new Scanner(System.in);
            //User is prompted for input
            System.out.println("Enter your monthly investment: ");
            investment = userInput.nextInt();
            //Method is called
            Sum(investment);
            //Results from recursive method output
            System.out.println("It should take " + counter + " month(s) to reach your goal of $10,000,000");
        }
        //recursive Method
        public static double Sum(double totalInvestment) {
            counter++;
            double total = (totalInvestment* 0.02) + totalInvestment;
            if(total >= 10000000) {return counter;}
            else {return Sum(total+investment);}
        }
    }
</code>```

Result

```<code>Enter your monthly investment:
100000
It should take 55 month(s) to reach your goal of $10,000,000
</code>```

Here is snapshot: here interest is considered annually hence converting 0.02 monthly interest to per year interest it becomes 0.24

Title: Logic error in Recursive method

Body:
Im trying to write a program that uses a recursive method to calculate how many months it will take to reach a goal of 10 million total invested if the same amount of money(inputted by the user) is invested with a 2 percent interest added each month. The problem is the method is returning counter too early so my "months" output is inaccurate. My guess is that my last else statement is wrong or my counter is placed incorrectly

Heres my code

   import java.util.Scanner;
    public class MoneyMakerRecursion {
        public static int counter = 0;
        public static void main(String[] args) {
            //Variables declared
            Scanner userInput = new Scanner(System.in);
            double investment;
            //User is prompted for input
            System.out.println("Enter your monthly investment: ");
            investment = userInput.nextInt();
            //Method is called
            Sum(investment);
            //Results from recursive method output
            System.out.println("It should take " + counter + " month(s) to reach your goal of $10,000,000");
        }
        //recursive Method
        public static double Sum(double investment) {
            counter++;
            double total = (investment * 0.02) + investment;
            if(total >= 10000000) {return counter;}
            else {return Sum(investment+total);}
        }
    }

Body:
Important point you missed is that your monthly investment is same throughout all months. Hence it should be static variable.

Second point you were adding investment to total which was local variable to that method. Which is not a actual investment for month. its a value passed to that function which changes for each month(Consider your code for this statement)

See below working code.

import java.util.Scanner;
    public class MoneyMakerRecursion {
        public static int counter = 0;
        public static double investment = 0;
        public static void main(String[] args) {
            //Variables declared
            Scanner userInput = new Scanner(System.in);
            //User is prompted for input
            System.out.println("Enter your monthly investment: ");
            investment = userInput.nextInt();
            //Method is called
            Sum(investment);
            //Results from recursive method output
            System.out.println("It should take " + counter + " month(s) to reach your goal of $10,000,000");
        }
        //recursive Method
        public static double Sum(double totalInvestment) {
            counter++;
            double total = (totalInvestment* 0.02) + totalInvestment;
            if(total >= 10000000) {return counter;}
            else {return Sum(total+investment);}
        }
    }

Result

Enter your monthly investment:
100000
It should take 55 month(s) to reach your goal of $10,000,000

Here is snapshot: here interest is considered annually hence converting 0.02 monthly interest to per year interest it becomes 0.24


问:
Setting Local Notifications on a new thread?
I need to know if it is possible to create a new thread to handle setting local notifications.

My app depends heavily on these notifications, so I want to make the app work while the phone sets the notifications.

Example:

(now)

you launch the app, the app hangs at the splash screen to set the local notifications, then it launches.

(I want)

The app launches and is usable while the Local notifications are set.

I need some sample code, too, please :)

(for the record, i am setting 60 local notifications each time the app enters foreground for my own reasons...)

Thanks!!

答:
One way to do threads is with is with performSelectorInBackground.

For example:

```<code>[myObj performSelectorInBackground:@selector(doSomething) withObject:nil];
</code>```

You should note, however, that Apple is pretty strongly recommending that you use higher-level concepts like NSOperations and Dispatch Queues instead of explicitly spawning threads. See the Concurrency Programming Guide

ContentLicense: CC BY-SA 2.5

Body:
One way to do threads is with is with performSelectorInBackground.

For example:

[myObj performSelectorInBackground:@selector(doSomething) withObject:nil];

You should note, however, that Apple is pretty strongly recommending that you use higher-level concepts like NSOperations and Dispatch Queues instead of explicitly spawning threads. See the Concurrency Programming Guide


问:
While loop with try-catch blocks doesn't wait for input in the try block after looping once
So I've got a method getInput, that is meant to, well, ask user for input, use a try-catch to make sure it's a correct data type(int in this case) and validate whether it's in a predefined range. Problem is, when I enter, say, a string, it repeats the message about incorrect input, prints the message I have asking for input in try {} and goes straight to catch without waiting for input.
Here's the code:

```<code>public static int getInput(String message, int lowerLimit, int upperLimit) {
    while (true) {
        int input;
        try {
            System.out.println(message);
            input = scanner.nextInt();
            if (lowerLimit > input && input > upperLimit) {
                return input;
            } else {
                System.out.println("Incorrect input value, try again");
            }
        } catch (Exception e) {
            System.out.println("Incorrect input, try again");
        }
    }
}
</code>```

I know there are other, working ways of accomplishing this, but I'd like to know why this one doesn't work - I think it should. Any ideas?

答:
```<code>if (lowerLimit > input && input > upperLimit)
</code>```

This is ALWAYS false.  You meant

```<code>if (input >= lowerlimit && input <= upperLimit)
    return input;
</code>```

Body:
So I've got a method getInput, that is meant to, well, ask user for input, use a try-catch to make sure it's a correct data type(int in this case) and validate whether it's in a predefined range. Problem is, when I enter, say, a string, it repeats the message about incorrect input, prints the message I have asking for input in try {} and goes straight to catch without waiting for input.
Here's the code:

public static int getInput(String message, int lowerLimit, int upperLimit) {
    while (true) {
        int input;
        try {
            System.out.println(message);
            input = scanner.nextInt();
            if (lowerLimit > input && input > upperLimit) {
                return input;
            } else {
                System.out.println("Incorrect input value, try again");
            }
        } catch (Exception e) {
            System.out.println("Incorrect input, try again");
        }
    }
}

I know there are other, working ways of accomplishing this, but I'd like to know why this one doesn't work - I think it should. Any ideas?

Body:
if (lowerLimit > input && input > upperLimit)

This is ALWAYS false.  You meant

if (input >= lowerlimit && input <= upperLimit)
    return input;


答:
Assuming you are using Scanner class, you could check, whether token has int or not

```<code> if(scanner.hasNextInt()){
  int input = scanner.nextInt();
     if (lowerLimit > input && input < upperLimit) {
     return input;
      }
   }
  else
   {
      System.out.println("Incorrect input value, try again");
    }
</code>```

Title: While loop with try-catch blocks doesn't wait for input in the try block after looping once

Body:
Assuming you are using Scanner class, you could check, whether token has int or not

 if(scanner.hasNextInt()){
  int input = scanner.nextInt();
     if (lowerLimit > input && input < upperLimit) {
     return input;
      }
   }
  else
   {
      System.out.println("Incorrect input value, try again");
    }


问:
SoapUI error on request - NoClassDefFoundError
I am new to web services and I have deployed a web service locally ( I am able to see the wsdl)
I tried to query the web service by creating a request in SOAPUI.
The response I got back was

```<code>     <env:Fault>
     <faultcode>env:Server</faultcode>
     <faultstring>java.lang.NoClassDefFoundError: org/apache/commons/lang/StringEscapeUtils
     </faultstring>
  </env:Fault>
</code>```

I see a bunch of errors in the jboss console in eclipse...

```<code>11:53:06,226 ERROR [SOAPFaultHelperJAXWS]
SOAP requestexceptionjava.lang.RuntimeException:
java.lang.NoClassDefFoundError:org/apache/commons/lang/StringEscapeUtils
</code>```

Can someone help me in figuring out what the problem could be?

Is something wrong with the way I setup my SOAPUI or is it I missed something in my project(web service server)

答: You need commons-lang.jar in your classpath

Body:
I am new to web services and I have deployed a web service locally ( I am able to see the wsdl)
I tried to query the web service by creating a request in SOAPUI.
The response I got back was

     <env:Fault>
     <faultcode>env:Server</faultcode>
     <faultstring>java.lang.NoClassDefFoundError: org/apache/commons/lang/StringEscapeUtils
     </faultstring>
  </env:Fault>

I see a bunch of errors in the jboss console in eclipse...

11:53:06,226 ERROR [SOAPFaultHelperJAXWS]
SOAP requestexceptionjava.lang.RuntimeException:
java.lang.NoClassDefFoundError:org/apache/commons/lang/StringEscapeUtils

Can someone help me in figuring out what the problem could be?

Is something wrong with the way I setup my SOAPUI or is it I missed something in my project(web service server)


问:
how to rename a folder in Google-storage programmatically?
I have a google-storage java client.

I want to rename a folder on the cloud.

It there a way to do it?

I saw the update post but i'm not sure how to change the name meta data.

here is my try but i don't know what to fill in "entity" and there is no oac.setName()

```<code>public void renameDirectory(String oldPath, String newName) throws IOException {

    final Storage gsClient = GCSlientFactory.get(PromptoConfig.s.GCP_PROJECT_ID).getGSClient();
    final URI uri = URI.create(oldPath);

    ObjectAccessControl oac = new ObjectAccessControl();
    oac.setId("newName");

    final Storage.ObjectAccessControls.Update update = gsClient.objectAccessControls().update(BUCKET_NAME, uri.toString().replace("gs://"+BUCKET_NAME+"/", ""), "", oac);
    update.execute();
}
</code>```

and also:

```<code>final Storage gsClient = GCSlientFactory.get(PromptoConfig.s.GCP_PROJECT_ID).getGSClient();
final URI uri = URI.create(oldPath);

ObjectAccessControl oac = new ObjectAccessControl();
oac.set("name", newName);

final Storage.ObjectAccessControls.Update update = gsClient.objectAccessControls().update(BUCKET_NAME, uri.toString().replace("gs://"+BUCKET_NAME+"/", ""), "allUsers", oac);
update.execute();
</code>```

答:
GCS doesn't support true folders -- the namespace is flat, and the meaning of "/" is really imposed by clients (and client libraries). As such, folders can't be renamed atomically - you would need to rename each of the contained files, like what the gsutil mv command does. You can see this by running a command like:

```<code>gsutil -d mv gs://my-bucket/folder1 gs://my-bucket/folder2
</code>```

The -d option will cause it to output the sequence of requests gsutil generates to do the rename.

Body:
I have a google-storage java client.

I want to rename a folder on the cloud.

It there a way to do it?

I saw the update post but i'm not sure how to change the name meta data.

here is my try but i don't know what to fill in "entity" and there is no oac.setName()

public void renameDirectory(String oldPath, String newName) throws IOException {

    final Storage gsClient = GCSlientFactory.get(PromptoConfig.s.GCP_PROJECT_ID).getGSClient();
    final URI uri = URI.create(oldPath);

    ObjectAccessControl oac = new ObjectAccessControl();
    oac.setId("newName");

    final Storage.ObjectAccessControls.Update update = gsClient.objectAccessControls().update(BUCKET_NAME, uri.toString().replace("gs://"+BUCKET_NAME+"/", ""), "", oac);
    update.execute();
}

and also:

final Storage gsClient = GCSlientFactory.get(PromptoConfig.s.GCP_PROJECT_ID).getGSClient();
final URI uri = URI.create(oldPath);

ObjectAccessControl oac = new ObjectAccessControl();
oac.set("name", newName);

final Storage.ObjectAccessControls.Update update = gsClient.objectAccessControls().update(BUCKET_NAME, uri.toString().replace("gs://"+BUCKET_NAME+"/", ""), "allUsers", oac);
update.execute();

Body:
GCS doesn't support true folders -- the namespace is flat, and the meaning of "/" is really imposed by clients (and client libraries). As such, folders can't be renamed atomically - you would need to rename each of the contained files, like what the gsutil mv command does. You can see this by running a command like:

gsutil -d mv gs://my-bucket/folder1 gs://my-bucket/folder2

The -d option will cause it to output the sequence of requests gsutil generates to do the rename.


问:
Polymerfire firebase-query not working and no error log
I want to fetch data from Firebase using polymerfire  and somehow it doesn't work.

Firebase data

```<code>lol-project (a name with 5 randomized letters)
+- events
    +- (some random event id, which is auto-generated)
        +- name: "haha"
        +- desc: "hihi"
    +- (some random event id, which is auto-generated)
        +- name: "huhu"
        +- desc: "hehe"
</code>```

Code (Polymer v1.6, Polymerfire v0.10.2)

```<code><link rel="import" href="../../../bower_components/polymerfire/polymerfire.html">
<link rel="import" href="../../../bower_components/polymerfire/firebase-auth.html">
<link rel="import" href="../../../bower_components/polymerfire/firebase-query.html">
...
<firebase-auth user="{{user}}"></firebase-auth>

<firebase-query id="eventquery" path="/events" data="{{events}}"></firebase-query>

<div class="Page-container" id="section1">
    <template is="dom-repeat" items="[[events]]" as="item">
        <p>[[item.name]]</p>
    </template>
</div>
...
properties: {
    events: {
        type: Object,
        observer: '_eventsChanged'
    }
},

_eventsChanged: function(newData, oldData) {
    console.log("it changed?!");
    console.info(newData);
}
</code>```

Firebase rules

```<code>{
  "rules": {
    ".read": "auth != null",
    ".write": "auth != null"
  }
}
</code>```

No error, no data. The console.info(newData); gives empty array. After hours of googling, I stumbled upon similar case, which apparently left unanswered in here (yes, this problem is pretty much similar to that one).

Anyone knows what I'm missing? Please help.

答:
Few Things:

events is an Array.
See firebase-query: "If the child nodes of the query are objects (most cases), data will be an array of those objects with an extra $key field added to represent the key."

No need to import polymerfire.html

Are you sure you are logged in?
You can propagate signed-in property in firebase-auth <firebase-auth user="{{user}}" signed-in="{{signedIn}}"></firebase-auth>
and place User signedIn is {{signedIn}} just above your
.

You could also temporarily change your database security rules.

Body:
I want to fetch data from Firebase using polymerfire  and somehow it doesn't work.

Firebase data

lol-project (a name with 5 randomized letters)
+- events
    +- (some random event id, which is auto-generated)
        +- name: "haha"
        +- desc: "hihi"
    +- (some random event id, which is auto-generated)
        +- name: "huhu"
        +- desc: "hehe"

Code (Polymer v1.6, Polymerfire v0.10.2)

<link rel="import" href="../../../bower_components/polymerfire/polymerfire.html">
<link rel="import" href="../../../bower_components/polymerfire/firebase-auth.html">
<link rel="import" href="../../../bower_components/polymerfire/firebase-query.html">
...
<firebase-auth user="{{user}}"></firebase-auth>

<firebase-query id="eventquery" path="/events" data="{{events}}"></firebase-query>

    <template is="dom-repeat" items="[[events]]" as="item">

[[item.name]]

    </template>

...
properties: {
    events: {
        type: Object,
        observer: '_eventsChanged'
    }
},

_eventsChanged: function(newData, oldData) {
    console.log("it changed?!");
    console.info(newData);
}

Firebase rules

{
  "rules": {
    ".read": "auth != null",
    ".write": "auth != null"
  }
}

No error, no data. The console.info(newData); gives empty array. After hours of googling, I stumbled upon similar case, which apparently left unanswered in here (yes, this problem is pretty much similar to that one).

Anyone knows what I'm missing? Please help.

Body:
Few Things:

events is an Array.
See firebase-query: "If the child nodes of the query are objects (most cases), data will be an array of those objects with an extra $key field added to represent the key."

No need to import polymerfire.html

Are you sure you are logged in?
You can propagate signed-in property in firebase-auth <firebase-auth user="{{user}}" signed-in="{{signedIn}}"></firebase-auth>
and place User signedIn is {{signedIn}} just above your <div>.

You could also temporarily change your database security rules.


问:
C++ class inclusion issue "not type named xxx in namespace"
Here is the code -- a component class first:

```<code>// LoSComponent.h

namespace LoS {
    class Component: public Ref {

    public:
        Component();
        ~Component();
    };
}
</code>```

and another class need a pointer of LoS::Component as parameter:

```<code>LoSStrategyPreProcessBase.h

#include "LoSComponent.h"

namespace LoS {

    namespace Strategy {

        namespace PreProcess {

            class Base {
            public:
                Base(LoS::Component* losComponent)
                {
                    this->_losComponent = losComponent;
                };
                ~Base()
                {
                };
            public:
                LoS::Component* _losComponent;
            };
        }
    }
}
</code>```

And the code above will give me the error:

```<code>LoSStrategyPreProcessBase.h No type named 'Component' in namespace 'LoS'
</code>```

Any ideas that how I can get this code to complier?

Thanks in advance .

Update 1:

I tried to replace LoS::Component to ::LoSComponent  but is still getting the same error:

Update 2:

I created a simple project with 2 simple class and I found that the problem seem to be caused in header file inclusion.

The code complier && link OK:

```<code>LoSComponent.h

#ifndef LoSComponent_h
#define LoSComponent_h

namespace LoS {

    class Component {

    public:
        Component();
        ~Component();
    };
}

#endif /* LoSComponent_h */
</code>```

And :

```<code>#ifndef LoSBase_h
#define LoSBase_h

#include "LoSComponent.h"

namespace LoS {

    namespace Stragergy {
        class Base {

        public:
            Base(LoS::Component* los){
                this->_los = los;
            };
            ~Base();
        private:
            LoS::Component* _los;
        };

    }
}

#endif /* LoSBase_h */
</code>```

As you can see I can use LoS::Component in LoSBase.h with no error.

Then I tried to change the LoSComponent.h :

```<code>#ifndef LoSComponent_h
#define LoSComponent_h

#include "LoSBase.h"

namespace LoS {

    class Component {

    public:
        Component();
        ~Component();

    private:
        LoS::Stragergy::Base* _base;
    };
}

#endif /* LoSComponent_h */
</code>```

As you can see I added a
#include "LoSBase.h"

and

```<code>LoS::Stragergy::Base* _base;
</code>```

and this time it fails with an error:

```<code>LoSComponent.h:23:14: error: no member named 'Stragergy' in namespace 'LoS'
        LoS::Stragergy::Base* _base;
        ~~~~~^

LoSBase.h:20:23: error: no type named 'Component' in namespace 'LoS'
            Base(LoS::Component* los){
                 ~~~~~^
</code>```

答:
Change Base(LoS::Component* losComponent) to Base(::LoS::Component* losComponent).

:: before namespace, class or function tells compiler to look for namespace/class/function in global namespace

Body:
Here is the code -- a component class first:

// LoSComponent.h

namespace LoS {
    class Component: public Ref {

    public:
        Component();
        ~Component();
    };
}

and another class need a pointer of LoS::Component as parameter:

LoSStrategyPreProcessBase.h

#include "LoSComponent.h"

namespace LoS {

    namespace Strategy {

        namespace PreProcess {

            class Base {
            public:
                Base(LoS::Component* losComponent)
                {
                    this->_losComponent = losComponent;
                };
                ~Base()
                {
                };
            public:
                LoS::Component* _losComponent;
            };
        }
    }
}

And the code above will give me the error:

LoSStrategyPreProcessBase.h No type named 'Component' in namespace 'LoS'

Any ideas that how I can get this code to complier?

Thanks in advance .

Update 1:

I tried to replace LoS::Component to ::LoSComponent  but is still getting the same error:

Update 2:

I created a simple project with 2 simple class and I found that the problem seem to be caused in header file inclusion.

The code complier && link OK:

LoSComponent.h

#ifndef LoSComponent_h
#define LoSComponent_h

namespace LoS {

    class Component {

    public:
        Component();
        ~Component();
    };
}

#endif /* LoSComponent_h */

And :

#ifndef LoSBase_h
#define LoSBase_h

#include "LoSComponent.h"

namespace LoS {

    namespace Stragergy {
        class Base {

        public:
            Base(LoS::Component* los){
                this->_los = los;
            };
            ~Base();
        private:
            LoS::Component* _los;
        };

    }
}

#endif /* LoSBase_h */

As you can see I can use LoS::Component in LoSBase.h with no error.

Then I tried to change the LoSComponent.h :

#ifndef LoSComponent_h
#define LoSComponent_h

#include "LoSBase.h"

namespace LoS {

    class Component {

    public:
        Component();
        ~Component();

    private:
        LoS::Stragergy::Base* _base;
    };
}

#endif /* LoSComponent_h */

As you can see I added a
#include "LoSBase.h"

and

LoS::Stragergy::Base* _base;

and this time it fails with an error:

LoSComponent.h:23:14: error: no member named 'Stragergy' in namespace 'LoS'
        LoS::Stragergy::Base* _base;
        ~~~~~^

LoSBase.h:20:23: error: no type named 'Component' in namespace 'LoS'
            Base(LoS::Component* los){
                 ~~~~~^


问:
Is there a way of copying a JPanel's Graphic2D instance to make a Graphic2D for a BufferedImage?
I have a JPanel which displays a graph using the Graphic2D. This works fine. I now want to be able to save the graph to a file. So far the only way I can get this to work is create a BufferedImage and everything I write to the JPanels Graphic2D object I write to the Graphic2D object belonging to the BufferedImage and then doing a PrintAll from the BufferedImage.
So I have code like the following:

```<code>    g.setFont(g.getFont().deriveFont(fontSize));
    g.drawString(text, xPos, yPos);
    g.setFont(saveFont);
    bG.setFont(g.getFont().deriveFont(fontSize));
    bG.drawString(text, xPos, yPos);
    bG.setFont(saveFont);
</code>```

where g is the Graphic2D object of the JPanel
and bG is the Graphic2D object of the BufferedImage

Surely this can't be the best way of doing this. Is there a way of using the Graphic2D object belonging to the JPanel to produce the Graphic2D object for the BufferedImage?

答:
I'd extract a method, say paintGraph(Graphics2D g) that paints the graph. Then you invoke it from two locations. Once from your JPanel's paintComponent(..) method, and once in your "saveToFile" method, using your BufferedImage's Graphics2D instance.

You might need a Dimension as a second parameter to your method, which is either the size of your panel or your image, if your graph drawing code is resizeable.

In code:

```<code>void paintGraph(Graphics2D g, Dimension size) {
    g.setFont(g.getFont().deriveFont(fontSize));
    g.drawString(text, xPos, yPos);
    g.setFont(saveFont);
    // ...etc
}

@Override
public void paintComponent(Graphics g) {
    super.paintComponent(g);
    paintGraph((Graphics2D) g, getSize());
}

void saveToFile(File f) {
    BufferedImage image = new BufferedImage(512, 512, BufferedImage.TYPE_INT_ARGB);

    Graphics2D g = image.createGaphics();
    paintGraph(g, new Dimension(image.getWidth(), image.getHeight());
    g.dispose();

    ImageIO.write(image, "PNG", f);
}
</code>```

Body:
I have a JPanel which displays a graph using the Graphic2D. This works fine. I now want to be able to save the graph to a file. So far the only way I can get this to work is create a BufferedImage and everything I write to the JPanels Graphic2D object I write to the Graphic2D object belonging to the BufferedImage and then doing a PrintAll from the BufferedImage.
So I have code like the following:

    g.setFont(g.getFont().deriveFont(fontSize));
    g.drawString(text, xPos, yPos);
    g.setFont(saveFont);
    bG.setFont(g.getFont().deriveFont(fontSize));
    bG.drawString(text, xPos, yPos);
    bG.setFont(saveFont);

where g is the Graphic2D object of the JPanel
and bG is the Graphic2D object of the BufferedImage

Surely this can't be the best way of doing this. Is there a way of using the Graphic2D object belonging to the JPanel to produce the Graphic2D object for the BufferedImage?

Body:
I'd extract a method, say paintGraph(Graphics2D g) that paints the graph. Then you invoke it from two locations. Once from your JPanel's paintComponent(..) method, and once in your "saveToFile" method, using your BufferedImage's Graphics2D instance.

You might need a Dimension as a second parameter to your method, which is either the size of your panel or your image, if your graph drawing code is resizeable.

In code:

void paintGraph(Graphics2D g, Dimension size) {
    g.setFont(g.getFont().deriveFont(fontSize));
    g.drawString(text, xPos, yPos);
    g.setFont(saveFont);
    // ...etc
}

@Override
public void paintComponent(Graphics g) {
    super.paintComponent(g);
    paintGraph((Graphics2D) g, getSize());
}

void saveToFile(File f) {
    BufferedImage image = new BufferedImage(512, 512, BufferedImage.TYPE_INT_ARGB);

    Graphics2D g = image.createGaphics();
    paintGraph(g, new Dimension(image.getWidth(), image.getHeight());
    g.dispose();

    ImageIO.write(image, "PNG", f);
}


问:
grouping and simplifying multiple if conditions / bash
I have multiple If conditions to to run at the beginning of the script

```<code>if blah; then
echo "hop"
fi
if [ ! -f blah-blah ]; then
echo "hop-hop"
else
echo "hip-hop-hap"
fi
if [ $? -eq 0 ]; then
echo "hip-hop"
fi
</code>```

each of this conditions
are separate from each other, and I have them 7-8
so I'm thinking if there is some way to group them...
I was thinking to use
elif , but elif will stop checking conditions if one of them is truth,
any suggestion would be ppreciated

答:
It is hard to give a definitive answer to a question that asks for some way.

Here is an alternative idea. We create an array of boolean values that contains the results of evaluation of logical conditions. And for each
condition i define a pair of functions func${i}0 and func${i}1 that will be called when condition i evaluates to true or false respectively. Finally we loop through our boolean array.

The code below implements this idea. It is rather awkward. Feel free to suggest improvements or downvote.

Here we assume that blah evaluates to either 0 or 1.

```<code># populate array b by evaluating boolean conditions
foo=$( blah );                b[1]=$?
foo=$( [ ! -f blah-blah ] );  b[2]=$?
foo=$( [ $? -eq 0 ] );        b[3]=$?

# For each condition 1 through 3 define the actions when
# the condition is True or False
func10(){
echo "hop"
}
func11(){ :;}

func20(){
    echo "hop-hop"
}
func21(){
    echo "hip-hop-hap"
}

func30(){
    echo "hip-hop"
}
func31(){ :;}

#loop through the array and execute the functions
for i in $(seq 1 ${#b[*]}) ; do
func${i}${b[i]}
done
</code>```

Edits:

Replaced {(:)} by { :;} per Charles Duffy suggestion

The use of $(seq) in the loop is inefficient, yet explicitly
incrementing the loop counter seems a bit too much to type.

Body:
I have multiple If conditions to to run at the beginning of the script

if blah; then
echo "hop"
fi
if [ ! -f blah-blah ]; then
echo "hop-hop"
else
echo "hip-hop-hap"
fi
if [ $? -eq 0 ]; then
echo "hip-hop"
fi

each of this conditions
are separate from each other, and I have them 7-8
so I'm thinking if there is some way to group them...
I was thinking to use
elif , but elif will stop checking conditions if one of them is truth,
any suggestion would be ppreciated

Body:
It is hard to give a definitive answer to a question that asks for some way.

Here is an alternative idea. We create an array of boolean values that contains the results of evaluation of logical conditions. And for each
condition i define a pair of functions func${i}0 and func${i}1 that will be called when condition i evaluates to true or false respectively. Finally we loop through our boolean array.

The code below implements this idea. It is rather awkward. Feel free to suggest improvements or downvote.

Here we assume that blah evaluates to either 0 or 1.

# populate array b by evaluating boolean conditions
foo=$( blah );                b[1]=$?
foo=$( [ ! -f blah-blah ] );  b[2]=$?
foo=$( [ $? -eq 0 ] );        b[3]=$?

# For each condition 1 through 3 define the actions when
# the condition is True or False
func10(){
echo "hop"
}
func11(){ :;}

func20(){
    echo "hop-hop"
}
func21(){
    echo "hip-hop-hap"
}

func30(){
    echo "hip-hop"
}
func31(){ :;}

#loop through the array and execute the functions
for i in $(seq 1 ${#b[*]}) ; do
func${i}${b[i]}
done

Edits:

Replaced {(:)} by { :;} per Charles Duffy suggestion

The use of $(seq) in the loop is inefficient, yet explicitly
incrementing the loop counter seems a bit too much to type.


问:
Try catch does not work in Azure server
In the config of my application I deleted the customErrors to make a test of an error that is difficult to replicate.

And where the error should be happening I put a try:

```<code>if (ModelState.IsValid)
        {
            db.TarefaHoras.Add(tarefaHora);

            try
            {
                db.SaveChanges();
            }
            catch (DbUpdateException ex)
            {
                ErroDetalhe erro = new ErroDetalhe();
                erro.Data = tarefaHora.Data;
                erro.UsuarioId = tarefaHora.ApplicationUserId;
                erro.JSON = JsonConvert.SerializeObject(tarefaHora);
                erro.Tipo = "TarefaHora";
                erro.Controller = "TarefaHoras";
                erro.Action = "Create Post";
                erro.Exception = ex.GetType().FullName;

                db.ErroDetalhes.Add(erro);
                db.SaveChanges();

                return RedirectToAction("ErroNaAtualizacaoDaBase", "Erros", new { id = erro.ID });
            }

            return RedirectToAction("Index", "Home");
        }

        return View(tarefaHora);
    }
</code>```

This error only happens at runtime and only on Azure server, so my attempt was to get a better description of the error and for this I created a table where the information is deposited.

But....

The problem is that the View error that I'm getting is not the View "ErrorInputUpdate" that I created and that is redirected in Catch.

I am getting the default AspNET error view.

So I went into Shared Views and deleted the default page and removed customErrors from web.config.

And even then Azure still brings the default error view.

Anyone have any idea what might be happening?

答:
So calling db.SaveChanges(); generates an exception. That means that the context db is invalid and it should be resolved or discarded.

However, what you are doing is creating an error entry and add using the same db context which is still in a faulty state. So the call to db.SaveChanges(); in your catch block will still generate an exception, but this time it won't be catched.

The solution is either to write the error to something else than the database, like a file or whatever or to use another EF context instance. Other options are to removed or correct the invalid entries before calling db.SaveChanges(); again or do not store the error in the database but include all the details in the redirect view.

Title: Try catch does not work in Azure server

Body:
In the config of my application I deleted the customErrors to make a test of an error that is difficult to replicate.

And where the error should be happening I put a try:

if (ModelState.IsValid)
        {
            db.TarefaHoras.Add(tarefaHora);

            try
            {
                db.SaveChanges();
            }
            catch (DbUpdateException ex)
            {
                ErroDetalhe erro = new ErroDetalhe();
                erro.Data = tarefaHora.Data;
                erro.UsuarioId = tarefaHora.ApplicationUserId;
                erro.JSON = JsonConvert.SerializeObject(tarefaHora);
                erro.Tipo = "TarefaHora";
                erro.Controller = "TarefaHoras";
                erro.Action = "Create Post";
                erro.Exception = ex.GetType().FullName;

                db.ErroDetalhes.Add(erro);
                db.SaveChanges();

                return RedirectToAction("ErroNaAtualizacaoDaBase", "Erros", new { id = erro.ID });
            }

            return RedirectToAction("Index", "Home");
        }

        return View(tarefaHora);
    }

This error only happens at runtime and only on Azure server, so my attempt was to get a better description of the error and for this I created a table where the information is deposited.

But....

The problem is that the View error that I'm getting is not the View "ErrorInputUpdate" that I created and that is redirected in Catch.

I am getting the default AspNET error view.

So I went into Shared Views and deleted the default page and removed customErrors from web.config.

And even then Azure still brings the default error view.

Anyone have any idea what might be happening?


问:
Add an array into Bootstrap DateTimePicker options
I'm attempting to disable certain dates in the Bootstrap Date Time Picker by eonasdan found here.

I'm able to manually add an array of dates that then become disabled but I can't figure out how to add an array created dynamically into this option.

Here is my code:

noDates = ['31/03/2017', '19/04/2017', '20/04/2017', '25/04/2017'];

// Just for testing
console.log(noDates);

// Studio 1 datepicker
$('#datetimepicker1').datetimepicker({
    // Date format
    format: "DD/MM/YYYY",
    // Show calendar when user clicks input field
    allowInputToggle: true,
    // Minimum date is today's date
    minDate: new Date(),
    // Disabled Dates
    disabledDates: noDates
});
```

<p>Where it says <code>disabledDates: noDates</code> I am able to manually write out the dates like so:</p>

<pre class="lang-js prettyprint-override"><code>disabledDates: [
    "03/31/2017",
    "04/19/2017",
    moment("04/20/2017"),
    moment("04/25/2017")
]
</code>```

I have also attempted the following:

$('#datetimepicker1').data('DateTimePicker').disabledDates(noDates);
```

<p>However, that gives me the error: </p>

```Uncaught TypeError: Cannot read property 'disabledDates' of undefined
```

Is there a way to add variables/arrays into objects like this?

Body:
I'm attempting to disable certain dates in the Bootstrap Date Time Picker by eonasdan found here.

I'm able to manually add an array of dates that then become disabled but I can't figure out how to add an array created dynamically into this option.

Here is my code:

noDates = ['31/03/2017', '19/04/2017', '20/04/2017', '25/04/2017'];

// Just for testing
console.log(noDates);

// Studio 1 datepicker
$('#datetimepicker1').datetimepicker({
    // Date format
    format: "DD/MM/YYYY",
    // Show calendar when user clicks input field
    allowInputToggle: true,
    // Minimum date is today's date
    minDate: new Date(),
    // Disabled Dates
    disabledDates: noDates
});

Where it says disabledDates: noDates I am able to manually write out the dates like so:

disabledDates: [
    "03/31/2017",
    "04/19/2017",
    moment("04/20/2017"),
    moment("04/25/2017")
]

I have also attempted the following:

$('#datetimepicker1').data('DateTimePicker').disabledDates(noDates);

However, that gives me the error:

Uncaught TypeError: Cannot read property 'disabledDates' of undefined

Is there a way to add variables/arrays into objects like this?

Body:
The problem is with your dates, more specific the format:

Wrong:

var noDates = ['31/03/2017', '19/04/2017', '20/04/2017', '25/04/2017'];

OK:

var noDates = ['2017-03-31', '2017-04-19', '2017-04-20', '2017-04-25'];


问:
nullPointerException on FXML object while manually adding controllers
I'm making a application where PuzzleBlocks are being constructed in a grid of 5x5 rectangles. I've moved away from declaring fx:controller in the .fxml file and instead did this in main:

```<code>@Override
    public void start(Stage primaryStage) throws Exception {
        FXMLLoader baseViewLoader = new FXMLLoader(getClass().getResource("Views/BaseView.fxml"));
        baseViewLoader.setLocation(getClass().getResource("Views/BaseView.fxml"));
        baseViewLoader.setController(new DockViewController());
        Parent root = baseViewLoader.load();

        FXMLLoader dockLoader = new FXMLLoader(getClass().getResource("Views/DockView.fxml"));
        dockLoader.setLocation(getClass().getResource("Views/DockView.fxml"));
        dockLoader.setController(new DockViewController());
        Parent dockView = dockLoader.load();

        primaryStage.setResizable(false);
        primaryStage.sizeToScene();

        primaryStage.setTitle("Tiles 2059275");

        Scene gameScene = new Scene(root);

        primaryStage.setScene(gameScene);

        primaryStage.show();

        new GameController();
    }
</code>```

Now previously when it was done via having the Controller declared via the .fxml file this piece of code in the Initialize of my DockViewController would work properly:

```<code>@FXML
    StackPane dockStackPane;

    @Override
    public void initialize(URL location, ResourceBundle resources) {
        for (int i = 0; i < 5; i++) {
            for (int j = 0; j < 5; j++) {
                tile1 = createSquare(Color.GREY);
                tile2 = createSquare(Color.GREY);
                tile3 = createSquare(Color.GREY);

                tile1.setTranslateX(32 * (i) - 176);
                tile1.setTranslateY(32 * (j) - 48);

                tile2.setTranslateX(32 * (i) - 16);
                tile2.setTranslateY(32 * (j) - 48);

                tile3.setTranslateX(32 * (i) + 144);
                tile3.setTranslateY(32 * (j) - 48);

                dockStackPane.getChildren().add(tile1);
                dockStackPane.getChildren().add(tile2);
                dockStackPane.getChildren().add(tile3);

                puzzleBlock1.add(tile1);
                puzzleBlock2.add(tile2);
                puzzleBlock3.add(tile3);
            }
        }
        System.out.println("Ini test");
    }
</code>```

The error occurs at dockStackPane.getChildren().add(tile1); because dockStackPane is null. If I remove manually adding the controllers in my Main and return to adding the controllers with fx:controller in the FXML file it works properly. But then I do not have a reference to my controller.

DockView.fxml

```<code><?xml version="1.0" encoding="UTF-8"?>

<?import javafx.scene.layout.Pane?>
<?import javafx.scene.layout.StackPane?>

<Pane maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" prefHeight="128.0" prefWidth="384.0" xmlns="http://javafx.com/javafx/8.0.111" xmlns:fx="http://javafx.com/fxml/1">
   <children>
      <StackPane fx:id="dockStackPane" prefHeight="128.0" prefWidth="384.0" />
   </children>
</Pane>
</code>```

And the DockView is included in the BaseView

答:
Thanks to the comments to my question I was able to work it out the solution is to add a fx:id to the include in my BaseView.fxml:

```<code> <fx:include fx:id="includedDockView" source="DockView.fxml" />
</code>```

Make sure the include element then has a fx:controller set as so:

```<code><Pane fx:id="dockPane" fx:controller="tiles.Controllers.DockViewController" maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" prefHeight="128.0" prefWidth="384.0" xmlns="http://javafx.com/javafx/8.0.111" xmlns:fx="http://javafx.com/fxml/1">
</code>```

Then in the BaseViewController you can do:

```<code>@FXML
    private DockViewController includedDockViewController;

    public DockViewController getDockViewController() {
        return includedDockViewController;
    }
</code>```

And in the main you can pass the BaseView as such:

```<code>public void start(Stage primaryStage) throws Exception {
    FXMLLoader baseViewLoader = new FXMLLoader(getClass().getResource("Views/BaseView.fxml"));
    baseViewLoader.setLocation(getClass().getResource("Views/BaseView.fxml"));
    baseViewLoader.setController(new BaseViewController());
    Parent root = baseViewLoader.load();

    primaryStage.setResizable(false);
    primaryStage.sizeToScene();

    primaryStage.setTitle("Tiles 2059275");

    Scene gameScene = new Scene(root);

    primaryStage.setScene(gameScene);

    primaryStage.show();

    new GameController(baseViewLoader);
}
</code>```

Body:
I'm making a application where PuzzleBlocks are being constructed in a grid of 5x5 rectangles. I've moved away from declaring fx:controller in the .fxml file and instead did this in main:

@Override
    public void start(Stage primaryStage) throws Exception {
        FXMLLoader baseViewLoader = new FXMLLoader(getClass().getResource("Views/BaseView.fxml"));
        baseViewLoader.setLocation(getClass().getResource("Views/BaseView.fxml"));
        baseViewLoader.setController(new DockViewController());
        Parent root = baseViewLoader.load();

        FXMLLoader dockLoader = new FXMLLoader(getClass().getResource("Views/DockView.fxml"));
        dockLoader.setLocation(getClass().getResource("Views/DockView.fxml"));
        dockLoader.setController(new DockViewController());
        Parent dockView = dockLoader.load();

        primaryStage.setResizable(false);
        primaryStage.sizeToScene();

        primaryStage.setTitle("Tiles 2059275");

        Scene gameScene = new Scene(root);

        primaryStage.setScene(gameScene);

        primaryStage.show();

        new GameController();
    }

Now previously when it was done via having the Controller declared via the .fxml file this piece of code in the Initialize of my DockViewController would work properly:

@FXML
    StackPane dockStackPane;

    @Override
    public void initialize(URL location, ResourceBundle resources) {
        for (int i = 0; i < 5; i++) {
            for (int j = 0; j < 5; j++) {
                tile1 = createSquare(Color.GREY);
                tile2 = createSquare(Color.GREY);
                tile3 = createSquare(Color.GREY);

                tile1.setTranslateX(32 * (i) - 176);
                tile1.setTranslateY(32 * (j) - 48);

                tile2.setTranslateX(32 * (i) - 16);
                tile2.setTranslateY(32 * (j) - 48);

                tile3.setTranslateX(32 * (i) + 144);
                tile3.setTranslateY(32 * (j) - 48);

                dockStackPane.getChildren().add(tile1);
                dockStackPane.getChildren().add(tile2);
                dockStackPane.getChildren().add(tile3);

                puzzleBlock1.add(tile1);
                puzzleBlock2.add(tile2);
                puzzleBlock3.add(tile3);
            }
        }
        System.out.println("Ini test");
    }

The error occurs at dockStackPane.getChildren().add(tile1); because dockStackPane is null. If I remove manually adding the controllers in my Main and return to adding the controllers with fx:controller in the FXML file it works properly. But then I do not have a reference to my controller.

DockView.fxml

<?xml version="1.0" encoding="UTF-8"?>

<?import javafx.scene.layout.Pane?>
<?import javafx.scene.layout.StackPane?>

<Pane maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" prefHeight="128.0" prefWidth="384.0" xmlns="http://javafx.com/javafx/8.0.111" xmlns:fx="http://javafx.com/fxml/1">
   <children>
      <StackPane fx:id="dockStackPane" prefHeight="128.0" prefWidth="384.0" />
   </children>
</Pane>

And the DockView is included in the BaseView

Body:
Thanks to the comments to my question I was able to work it out the solution is to add a fx:id to the include in my BaseView.fxml:

 <fx:include fx:id="includedDockView" source="DockView.fxml" />

Make sure the include element then has a fx:controller set as so:

<Pane fx:id="dockPane" fx:controller="tiles.Controllers.DockViewController" maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" prefHeight="128.0" prefWidth="384.0" xmlns="http://javafx.com/javafx/8.0.111" xmlns:fx="http://javafx.com/fxml/1">

Then in the BaseViewController you can do:

@FXML
    private DockViewController includedDockViewController;

    public DockViewController getDockViewController() {
        return includedDockViewController;
    }

And in the main you can pass the BaseView as such:

public void start(Stage primaryStage) throws Exception {
    FXMLLoader baseViewLoader = new FXMLLoader(getClass().getResource("Views/BaseView.fxml"));
    baseViewLoader.setLocation(getClass().getResource("Views/BaseView.fxml"));
    baseViewLoader.setController(new BaseViewController());
    Parent root = baseViewLoader.load();

    primaryStage.setResizable(false);
    primaryStage.sizeToScene();

    primaryStage.setTitle("Tiles 2059275");

    Scene gameScene = new Scene(root);

    primaryStage.setScene(gameScene);

    primaryStage.show();

    new GameController(baseViewLoader);
}


答: The behaviour you're observing stems from the fact that scanner (assuming you're working with java.util.Scanner) only advances if nextInt() is successful. That means that you have to skip over the faulty input (i.e. by using next()) before proceding.

Body:
So I've got a method getInput, that is meant to, well, ask user for input, use a try-catch to make sure it's a correct data type(int in this case) and validate whether it's in a predefined range. Problem is, when I enter, say, a string, it repeats the message about incorrect input, prints the message I have asking for input in try {} and goes straight to catch without waiting for input.
Here's the code:

public static int getInput(String message, int lowerLimit, int upperLimit) {
    while (true) {
        int input;
        try {
            System.out.println(message);
            input = scanner.nextInt();
            if (lowerLimit > input && input > upperLimit) {
                return input;
            } else {
                System.out.println("Incorrect input value, try again");
            }
        } catch (Exception e) {
            System.out.println("Incorrect input, try again");
        }
    }
}

I know there are other, working ways of accomplishing this, but I'd like to know why this one doesn't work - I think it should. Any ideas?


问:
Combining dateparts to create new datetime in SQL Server
I am trying to create my own date by combining dateparts of different columns. My code is below:

```<code>CAST((datepart(yy,[FIRST_INSTALL_DATE])
     + '-'
     + datepart(mm,[INSTALL_DATE])
     + '-'
     + datepart(dd,[INSTALL_DATE])) as Datetime) AS [Install_Date],
</code>```

(Where FIRST_INSTALL_DATE's value is 2014-01-01 and INSTALL_DATE's value is 1900-08-07.)

However, I get the output below where it is supposed to be 2014-08-07 00:00:00.000

```<code>1905-08-07 00:00:00.000
</code>```

I appreciate any idea. Thanks.

答:
Basically you are trying to add numbers,

```<code>2014 +- 03 +- 02
</code>```

You must convert every DATEPART to VARCHAR before to concat it.

```<code>CAST(DATEPART(YY, FIRST_INSTALL_DATE) AS varchar(10))
</code>```

SQL-Server 2012

```<code>DECLARE @FIRST_INSTALL_DATE datetime = '2016/01/01 00:00:00';
DECLARE @INSTALL_DATE datetime = '2017/02/03 00:00:00';

SELECT DATEFROMPARTS (datepart(yyyy, @FIRST_INSTALL_DATE),
                      datepart(MM,@INSTALL_DATE),
                      datepart(dd,@INSTALL_DATE)) AS InstallDate;

GO
</code>```
```
| InstallDate         |
| :------------------ |
| 03/02/2016 00:00:00 |
```

dbfiddle here

Body:
I am trying to create my own date by combining dateparts of different columns. My code is below:

CAST((datepart(yy,[FIRST_INSTALL_DATE])
     + '-'
     + datepart(mm,[INSTALL_DATE])
     + '-'
     + datepart(dd,[INSTALL_DATE])) as Datetime) AS [Install_Date],

(Where FIRST_INSTALL_DATE's value is 2014-01-01 and INSTALL_DATE's value is 1900-08-07.)

However, I get the output below where it is supposed to be 2014-08-07 00:00:00.000

1905-08-07 00:00:00.000

I appreciate any idea. Thanks.

Body:
Basically you are trying to add numbers,

2014 +- 03 +- 02

You must convert every DATEPART to VARCHAR before to concat it.

CAST(DATEPART(YY, FIRST_INSTALL_DATE) AS varchar(10))

SQL-Server 2012

DECLARE @FIRST_INSTALL_DATE datetime = '2016/01/01 00:00:00';
DECLARE @INSTALL_DATE datetime = '2017/02/03 00:00:00';

SELECT DATEFROMPARTS (datepart(yyyy, @FIRST_INSTALL_DATE),
                      datepart(MM,@INSTALL_DATE),
                      datepart(dd,@INSTALL_DATE)) AS InstallDate;

GO

| InstallDate         |
| :------------------ |
| 03/02/2016 00:00:00 |

dbfiddle here


问:
Using babel, cannot set breakpoints in ES6 generators
In a typical react app, using babel with the presets es2015, react and stage-2 and with sourcemaps enabled, setting the breakpoint in a generator function, the breakpoint will move automatically to somewhere else.

.babelrc

```<code>{
  "presets": ["es2015", "react", "stage-2"]
}
</code>```

答:
Could be a bug with either the source maps of the transform or the source map support in the Chrome Devtools. this is a result of using babel, disabling generator-transpilation solves this.

Here's what I used,

.babelrc

```<code>{
  "plugins": ["transform-es2015-modules-commonjs"],
  "presets": ["react"]
}
</code>```

Body:
In a typical react app, using babel with the presets es2015, react and stage-2 and with sourcemaps enabled, setting the breakpoint in a generator function, the breakpoint will move automatically to somewhere else.

.babelrc

{
  "presets": ["es2015", "react", "stage-2"]
}

Body:
Could be a bug with either the source maps of the transform or the source map support in the Chrome Devtools. this is a result of using babel, disabling generator-transpilation solves this.

Here's what I used,

.babelrc

{
  "plugins": ["transform-es2015-modules-commonjs"],
  "presets": ["react"]
}


问:
Adding CheckBox to DefaultTableModel
I have a DefaultTableModel which is populated with an Object[][] array.

Now I want to add a column with checkBoxes and perform operations accordingly.

When I add the checkbox into the Object[][] array and view it, I get text displayed

'javax.swing.JCheckBox[,0,0,0x0....', how do I get it to show a checkbox and add actions to it?

答:
No you cannot provide swing component as model object[] array. That should be registered as cell editor on column.

Anyway by default DefaultTableModel supports checkbox as editor for columns under which Boolean class type values are stored.

So, in the array pass Boolean.TRUE/Boolean.FALSE object and set table as editable. Then table automatically renders checkbox for you.

Are you need to register editor for each class type

Title: Adding CheckBox to DefaultTableModel


问:
Issue getting past an html form with Scrapy
Url I am trying to scrape: https://www.uvic.ca/BAN1P/bwckschd.p_disp_dyn_sched

There are 3 pages total, first page to select the term, second page to select a subject, and the page with the actual course information.

The issue I am running into is that once subject() calls the courses() callback the html in the response.body that is written to the file is the html of the subject page instead of the courses page. How can I tell I am sending the correct form data so that I receive the correct response?

```<code># term():
#   Selects the school term to use. Clicks submit

def term(self, response):
    return scrapy.FormRequest.from_response(
    response,
    formxpath="/html/body/div[3]/form",
    formdata={
        "p_term" : "201705" },
    clickdata = { "type": "submit" },
    callback=self.subject
    )

# subject():
#   Selects the subject to query. Clicks submit

def subject(self, response):
    return scrapy.FormRequest.from_response(
    response,
    formxpath="/html/body/div[3]/form",
    formdata={
        "sel_subj" : "ART" },
    clickdata = { "type": "submit" },
    callback=self.courses
    )

# courses():
#   Currently just saves all the html on the page.

def courses(self, response):
    page = response.url.split("/")[-1]
    filename = 'uvic-%s.html' % page
    with open(filename, 'wb') as f:
        f.write(response.body)
    self.log('Saved file %s' % filename)
</code>```

Debug Output

```<code>2017-04-02 01:15:28 [scrapy.utils.log] INFO: Scrapy 1.3.3 started (bot: scrapy4uvic)
2017-04-02 01:15:28 [scrapy.utils.log] INFO: Overridden settings: {'NEWSPIDER_MODULE': 'scrapy4uvic.spiders', 'SPIDER_MODULES': ['scrapy4uvic.spiders'], 'ROBOTSTXT_OBEY': True, 'BOT_NAME': 'scrapy4uvic'}
2017-04-02 01:15:28 [scrapy.middleware] INFO: Enabled extensions:
['scrapy.extensions.logstats.LogStats',
 'scrapy.extensions.telnet.TelnetConsole',
 'scrapy.extensions.corestats.CoreStats']
2017-04-02 01:15:28 [scrapy.middleware] INFO: Enabled downloader middlewares:
['scrapy.downloadermiddlewares.robotstxt.RobotsTxtMiddleware',
 'scrapy.downloadermiddlewares.httpauth.HttpAuthMiddleware',
 'scrapy.downloadermiddlewares.downloadtimeout.DownloadTimeoutMiddleware',
 'scrapy.downloadermiddlewares.defaultheaders.DefaultHeadersMiddleware',
 'scrapy.downloadermiddlewares.useragent.UserAgentMiddleware',
 'scrapy.downloadermiddlewares.retry.RetryMiddleware',
 'scrapy.downloadermiddlewares.redirect.MetaRefreshMiddleware',
 'scrapy.downloadermiddlewares.httpcompression.HttpCompressionMiddleware',
 'scrapy.downloadermiddlewares.redirect.RedirectMiddleware',
 'scrapy.downloadermiddlewares.cookies.CookiesMiddleware',
 'scrapy.downloadermiddlewares.stats.DownloaderStats']
2017-04-02 01:15:28 [scrapy.middleware] INFO: Enabled spider middlewares:
['scrapy.spidermiddlewares.httperror.HttpErrorMiddleware',
 'scrapy.spidermiddlewares.offsite.OffsiteMiddleware',
 'scrapy.spidermiddlewares.referer.RefererMiddleware',
 'scrapy.spidermiddlewares.urllength.UrlLengthMiddleware',
 'scrapy.spidermiddlewares.depth.DepthMiddleware']
2017-04-02 01:15:28 [scrapy.middleware] INFO: Enabled item pipelines:
[]
2017-04-02 01:15:28 [scrapy.core.engine] INFO: Spider opened
2017-04-02 01:15:28 [scrapy.extensions.logstats] INFO: Crawled 0 pages (at 0 pages/min), scraped 0 items (at 0 items/min)
2017-04-02 01:15:28 [scrapy.extensions.telnet] DEBUG: Telnet console listening on 127.0.0.1:6023
2017-04-02 01:15:29 [scrapy.core.engine] DEBUG: Crawled (200) <GET https://www.uvic.ca/robots.txt> (referer: None)
2017-04-02 01:15:29 [scrapy.core.engine] DEBUG: Crawled (200) <GET https://www.uvic.ca/BAN1P/bwckschd.p_disp_dyn_sched> (referer: None)
2017-04-02 01:15:29 [scrapy.core.engine] DEBUG: Crawled (200) <POST https://www.uvic.ca/BAN1P/bwckgens.p_proc_term_date> (referer: https://www.uvic.ca/BAN1P/bwckschd.p_disp_dyn_sched)
2017-04-02 01:15:29 [scrapy.core.engine] DEBUG: Crawled (200) <POST https://www.uvic.ca/BAN1P/bwckschd.p_get_crse_unsec> (referer: https://www.uvic.ca/BAN1P/bwckgens.p_proc_term_date)
2017-04-02 01:15:30 [uvic] DEBUG: Saved file uvic-bwckschd.p_get_crse_unsec.html
2017-04-02 01:15:30 [scrapy.core.engine] INFO: Closing spider (finished)
2017-04-02 01:15:30 [scrapy.statscollectors] INFO: Dumping Scrapy stats:
{'downloader/request_bytes': 2335,
 'downloader/request_count': 4,
 'downloader/request_method_count/GET': 2,
 'downloader/request_method_count/POST': 2,
 'downloader/response_bytes': 105499,
 'downloader/response_count': 4,
 'downloader/response_status_count/200': 4,
 'finish_reason': 'finished',
 'finish_time': datetime.datetime(2017, 4, 2, 8, 15, 30, 103536),
 'log_count/DEBUG': 6,
 'log_count/INFO': 7,
 'request_depth_max': 2,
 'response_received_count': 4,
 'scheduler/dequeued': 3,
 'scheduler/dequeued/memory': 3,
 'scheduler/enqueued': 3,
 'scheduler/enqueued/memory': 3,
 'start_time': datetime.datetime(2017, 4, 2, 8, 15, 28, 987034)}
2017-04-02 01:15:30 [scrapy.core.engine] INFO: Spider closed (finished)
</code>```

答:
Seems like you are missing some form data in subject().

I managed to get it working with:

```<code>formdata={
    "sel_subj": ["dummy", "ART"],
}
</code>```

How I went about debugging it.

First you don't have to save to file, you can inspect_response during crawl:

```<code>def courses(self, response):
    from scrapy.shell import inspect_response
    inspect_response(response, self)
</code>```

This will open up a shell with response and request object, you can even call view(response) to open the html in your browser. It will also use ipython or bpython shells if those are available, in the example below I use ipython for the convenient formatting.

Second I checked my browser (firefox) what form is it sending when I click the buttons and copied it to shell under variable bar and compared it to the request body scrapy was sending:

```<code>bar = '''term_in=201705&sel_subj=dummy&sel_day=dummy&sel_schd=dummy&sel_insm=dummy&
      sel_camp=dummy&sel_levl=dummy
      &sel_sess=dummy&sel_instr=dummy&sel_ptrm=dummy&sel_attr=dummy&sel_subj=ART&sel_crse
      =&sel_title=&sel_schd
      =%25&sel_insm=%25&sel_from_cred=&sel_to_cred=&sel_camp=%25&sel_levl=%25&sel_ptrm=%2
      5&sel_instr=%25&begin_hh
      =0&begin_mi=0&begin_ap=a&end_hh=0&end_mi=0&end_ap=a'''
# split into arguments
bar = sorted(bar.split('&'))
# do the same with the request body that was sent by scrapy
foo =sorted(request.body.split('&'))
# now join these together and find the differences!
zip(foo, bar)
[('begin_ap=a', 'begin_ap=a'),
 ('begin_hh=0', 'begin_hh\n=0'),
 ('begin_mi=0', 'begin_mi=0'),
 ('end_ap=a', 'end_ap=a'),
 ('end_hh=0', 'end_hh=0'),
 ('end_mi=0', 'end_mi=0'),
 ('sel_attr=dummy', 'sel_attr=dummy'),
 ('sel_camp=%25', 'sel_camp=%25'),
 ('sel_camp=dummy', 'sel_camp=dummy'),
 ('sel_crse=', 'sel_crse='),
 ('sel_day=dummy', 'sel_day=dummy'),
 ('sel_from_cred=', 'sel_from_cred='),
 ('sel_insm=%25', 'sel_insm=%25'),
 ('sel_insm=dummy', 'sel_insm=dummy'),
 ('sel_instr=%25', 'sel_instr=%25'),
 ('sel_instr=dummy', 'sel_instr=dummy'),
 ('sel_levl=%25', 'sel_levl=%25'),
 ('sel_levl=dummy', 'sel_levl=dummy\n'),
 ('sel_ptrm=%25', 'sel_ptrm=%25'),
 ('sel_ptrm=dummy', 'sel_ptrm=dummy'),
 ('sel_schd=%25', 'sel_schd\n=%25'),
 ('sel_schd=dummy', 'sel_schd=dummy'),
 ('sel_sess=dummy', 'sel_sess=dummy'),
 ('sel_subj=ART', 'sel_subj=ART'),
 ('sel_title=', 'sel_subj=dummy'),
 ('sel_to_cred=', 'sel_title='),
 ('term_in=201705', 'sel_to_cred=')]
</code>```

As you can see you were missing "dummy" in sel_subj and 'term_in' is there when it shouldn't be but it desn't seem to have an effect :)

Body:
Url I am trying to scrape: https://www.uvic.ca/BAN1P/bwckschd.p_disp_dyn_sched

There are 3 pages total, first page to select the term, second page to select a subject, and the page with the actual course information.

The issue I am running into is that once subject() calls the courses() callback the html in the response.body that is written to the file is the html of the subject page instead of the courses page. How can I tell I am sending the correct form data so that I receive the correct response?

# term():
#   Selects the school term to use. Clicks submit

def term(self, response):
    return scrapy.FormRequest.from_response(
    response,
    formxpath="/html/body/div[3]/form",
    formdata={
        "p_term" : "201705" },
    clickdata = { "type": "submit" },
    callback=self.subject
    )

# subject():
#   Selects the subject to query. Clicks submit

def subject(self, response):
    return scrapy.FormRequest.from_response(
    response,
    formxpath="/html/body/div[3]/form",
    formdata={
        "sel_subj" : "ART" },
    clickdata = { "type": "submit" },
    callback=self.courses
    )

# courses():
#   Currently just saves all the html on the page.

def courses(self, response):
    page = response.url.split("/")[-1]
    filename = 'uvic-%s.html' % page
    with open(filename, 'wb') as f:
        f.write(response.body)
    self.log('Saved file %s' % filename)

Debug Output

2017-04-02 01:15:28 [scrapy.utils.log] INFO: Scrapy 1.3.3 started (bot: scrapy4uvic)
2017-04-02 01:15:28 [scrapy.utils.log] INFO: Overridden settings: {'NEWSPIDER_MODULE': 'scrapy4uvic.spiders', 'SPIDER_MODULES': ['scrapy4uvic.spiders'], 'ROBOTSTXT_OBEY': True, 'BOT_NAME': 'scrapy4uvic'}
2017-04-02 01:15:28 [scrapy.middleware] INFO: Enabled extensions:
['scrapy.extensions.logstats.LogStats',
 'scrapy.extensions.telnet.TelnetConsole',
 'scrapy.extensions.corestats.CoreStats']
2017-04-02 01:15:28 [scrapy.middleware] INFO: Enabled downloader middlewares:
['scrapy.downloadermiddlewares.robotstxt.RobotsTxtMiddleware',
 'scrapy.downloadermiddlewares.httpauth.HttpAuthMiddleware',
 'scrapy.downloadermiddlewares.downloadtimeout.DownloadTimeoutMiddleware',
 'scrapy.downloadermiddlewares.defaultheaders.DefaultHeadersMiddleware',
 'scrapy.downloadermiddlewares.useragent.UserAgentMiddleware',
 'scrapy.downloadermiddlewares.retry.RetryMiddleware',
 'scrapy.downloadermiddlewares.redirect.MetaRefreshMiddleware',
 'scrapy.downloadermiddlewares.httpcompression.HttpCompressionMiddleware',
 'scrapy.downloadermiddlewares.redirect.RedirectMiddleware',
 'scrapy.downloadermiddlewares.cookies.CookiesMiddleware',
 'scrapy.downloadermiddlewares.stats.DownloaderStats']
2017-04-02 01:15:28 [scrapy.middleware] INFO: Enabled spider middlewares:
['scrapy.spidermiddlewares.httperror.HttpErrorMiddleware',
 'scrapy.spidermiddlewares.offsite.OffsiteMiddleware',
 'scrapy.spidermiddlewares.referer.RefererMiddleware',
 'scrapy.spidermiddlewares.urllength.UrlLengthMiddleware',
 'scrapy.spidermiddlewares.depth.DepthMiddleware']
2017-04-02 01:15:28 [scrapy.middleware] INFO: Enabled item pipelines:
[]
2017-04-02 01:15:28 [scrapy.core.engine] INFO: Spider opened
2017-04-02 01:15:28 [scrapy.extensions.logstats] INFO: Crawled 0 pages (at 0 pages/min), scraped 0 items (at 0 items/min)
2017-04-02 01:15:28 [scrapy.extensions.telnet] DEBUG: Telnet console listening on 127.0.0.1:6023
2017-04-02 01:15:29 [scrapy.core.engine] DEBUG: Crawled (200) <GET https://www.uvic.ca/robots.txt> (referer: None)
2017-04-02 01:15:29 [scrapy.core.engine] DEBUG: Crawled (200) <GET https://www.uvic.ca/BAN1P/bwckschd.p_disp_dyn_sched> (referer: None)
2017-04-02 01:15:29 [scrapy.core.engine] DEBUG: Crawled (200) <POST https://www.uvic.ca/BAN1P/bwckgens.p_proc_term_date> (referer: https://www.uvic.ca/BAN1P/bwckschd.p_disp_dyn_sched)
2017-04-02 01:15:29 [scrapy.core.engine] DEBUG: Crawled (200) <POST https://www.uvic.ca/BAN1P/bwckschd.p_get_crse_unsec> (referer: https://www.uvic.ca/BAN1P/bwckgens.p_proc_term_date)
2017-04-02 01:15:30 [uvic] DEBUG: Saved file uvic-bwckschd.p_get_crse_unsec.html
2017-04-02 01:15:30 [scrapy.core.engine] INFO: Closing spider (finished)
2017-04-02 01:15:30 [scrapy.statscollectors] INFO: Dumping Scrapy stats:
{'downloader/request_bytes': 2335,
 'downloader/request_count': 4,
 'downloader/request_method_count/GET': 2,
 'downloader/request_method_count/POST': 2,
 'downloader/response_bytes': 105499,
 'downloader/response_count': 4,
 'downloader/response_status_count/200': 4,
 'finish_reason': 'finished',
 'finish_time': datetime.datetime(2017, 4, 2, 8, 15, 30, 103536),
 'log_count/DEBUG': 6,
 'log_count/INFO': 7,
 'request_depth_max': 2,
 'response_received_count': 4,
 'scheduler/dequeued': 3,
 'scheduler/dequeued/memory': 3,
 'scheduler/enqueued': 3,
 'scheduler/enqueued/memory': 3,
 'start_time': datetime.datetime(2017, 4, 2, 8, 15, 28, 987034)}
2017-04-02 01:15:30 [scrapy.core.engine] INFO: Spider closed (finished)

Body:
Seems like you are missing some form data in subject().

I managed to get it working with:

formdata={
    "sel_subj": ["dummy", "ART"],
}

How I went about debugging it.

First you don't have to save to file, you can inspect_response during crawl:

def courses(self, response):
    from scrapy.shell import inspect_response
    inspect_response(response, self)

This will open up a shell with response and request object, you can even call view(response) to open the html in your browser. It will also use ipython or bpython shells if those are available, in the example below I use ipython for the convenient formatting.

Second I checked my browser (firefox) what form is it sending when I click the buttons and copied it to shell under variable bar and compared it to the request body scrapy was sending:

bar = '''term_in=201705&sel_subj=dummy&sel_day=dummy&sel_schd=dummy&sel_insm=dummy&
      sel_camp=dummy&sel_levl=dummy
      &sel_sess=dummy&sel_instr=dummy&sel_ptrm=dummy&sel_attr=dummy&sel_subj=ART&sel_crse
      =&sel_title=&sel_schd
      =%25&sel_insm=%25&sel_from_cred=&sel_to_cred=&sel_camp=%25&sel_levl=%25&sel_ptrm=%2
      5&sel_instr=%25&begin_hh
      =0&begin_mi=0&begin_ap=a&end_hh=0&end_mi=0&end_ap=a'''
# split into arguments
bar = sorted(bar.split('&'))
# do the same with the request body that was sent by scrapy
foo =sorted(request.body.split('&'))
# now join these together and find the differences!
zip(foo, bar)
[('begin_ap=a', 'begin_ap=a'),
 ('begin_hh=0', 'begin_hh\n=0'),
 ('begin_mi=0', 'begin_mi=0'),
 ('end_ap=a', 'end_ap=a'),
 ('end_hh=0', 'end_hh=0'),
 ('end_mi=0', 'end_mi=0'),
 ('sel_attr=dummy', 'sel_attr=dummy'),
 ('sel_camp=%25', 'sel_camp=%25'),
 ('sel_camp=dummy', 'sel_camp=dummy'),
 ('sel_crse=', 'sel_crse='),
 ('sel_day=dummy', 'sel_day=dummy'),
 ('sel_from_cred=', 'sel_from_cred='),
 ('sel_insm=%25', 'sel_insm=%25'),
 ('sel_insm=dummy', 'sel_insm=dummy'),
 ('sel_instr=%25', 'sel_instr=%25'),
 ('sel_instr=dummy', 'sel_instr=dummy'),
 ('sel_levl=%25', 'sel_levl=%25'),
 ('sel_levl=dummy', 'sel_levl=dummy\n'),
 ('sel_ptrm=%25', 'sel_ptrm=%25'),
 ('sel_ptrm=dummy', 'sel_ptrm=dummy'),
 ('sel_schd=%25', 'sel_schd\n=%25'),
 ('sel_schd=dummy', 'sel_schd=dummy'),
 ('sel_sess=dummy', 'sel_sess=dummy'),
 ('sel_subj=ART', 'sel_subj=ART'),
 ('sel_title=', 'sel_subj=dummy'),
 ('sel_to_cred=', 'sel_title='),
 ('term_in=201705', 'sel_to_cred=')]

As you can see you were missing "dummy" in sel_subj and 'term_in' is there when it shouldn't be but it desn't seem to have an effect :)


答:
I think you should use the ISO 8601 YYYYMMDD format when convert to Datetime</p>

```<code>SELECT
CAST(
  CAST(datepart(yy,[FIRST_INSTALL_DATE]) AS VARCHAR(4)) +
  RIGHT('0' + CAST(datepart(mm,[INSTALL_DATE]) AS VARCHAR(2)), 2) +
  RIGHT('0' + CAST(datepart(dd,[INSTALL_DATE]) AS VARCHAR(2)), 2)
AS DATETIME) AS [Install_Date],
</code>```

Title: Combining dateparts to create new datetime in SQL Server

Body:
I think you should use the ISO 8601 YYYYMMDD format when convert to Datetime

SELECT
CAST(
  CAST(datepart(yy,[FIRST_INSTALL_DATE]) AS VARCHAR(4)) +
  RIGHT('0' + CAST(datepart(mm,[INSTALL_DATE]) AS VARCHAR(2)), 2) +
  RIGHT('0' + CAST(datepart(dd,[INSTALL_DATE]) AS VARCHAR(2)), 2)
AS DATETIME) AS [Install_Date],


问:
Getting out of a while loop earlier with cout using c++
```<code>#include "stdafx.h"
#include <iostream>
#include <fstream>
#include <string>
#include <iomanip>
using namespace std;

int main()
{
    string sentence = "some random sentence";
    int i = 0; //runs through the bigger string
    int j = 0; //runs through the smaller string
    int k = 0; //variable to mark the position where the string starts being equal in order to delete it using substring
    string remove = "random";
    int a = sentence.size();
    int b = remove.size();
    while (i < a)
    {
        if (sentence[i] == remove[j])
        {
            if (b == j - 1)
            {
                cout << sentence.substr(0, k) << sentence.substr(i, (a - 1));
                break;
            }
            else
            {
                i++;
                j++;
            }
        }
        else
        {
            i++;
            j = 0;
            k++;

        }

    }
        return 1;
}
</code>```

I want to remove the word random from the bigger string and print it out but when I run the code, it does not return anything. What's missing?
I already tried putting a break right below de "cout", but it does not work.

Thank you :)

答: As b == 6, j would have to be 7 in order for b == j-1 to become true. But remove[6] is the terminating \0 of the random string, so j can never grow beyond 6.

Body:
#include "stdafx.h"
#include <iostream>
#include <fstream>
#include <string>
#include <iomanip>
using namespace std;

int main()
{
    string sentence = "some random sentence";
    int i = 0; //runs through the bigger string
    int j = 0; //runs through the smaller string
    int k = 0; //variable to mark the position where the string starts being equal in order to delete it using substring
    string remove = "random";
    int a = sentence.size();
    int b = remove.size();
    while (i < a)
    {
        if (sentence[i] == remove[j])
        {
            if (b == j - 1)
            {
                cout << sentence.substr(0, k) << sentence.substr(i, (a - 1));
                break;
            }
            else
            {
                i++;
                j++;
            }
        }
        else
        {
            i++;
            j = 0;
            k++;

        }

    }
        return 1;
}

I want to remove the word random from the bigger string and print it out but when I run the code, it does not return anything. What's missing?
I already tried putting a break right below de "cout", but it does not work.

Thank you :)