问:
webpack-dev-server get blank screen
Greetings I'm building a MERN stack for the first time and using Webpack  as my build tool. The goal is to have the API's of the app served by Express and the static content(my static dir) and bundles served by webpack-dev-server.

```<code>Here is my build:
Project is running at http://localhost:8000/
webpack output is served from /
Content not from webpack is served from static
Hash: 0f82642b68722fddb0c7
Version: webpack 3.1.0
Time: 3941ms
           Asset     Size  Chunks                    Chunk Names
   app.bundle.js  15.4 kB       0  [emitted]         app
vendor.bundle.js  1.35 MB       1  [emitted]  [big]  vendor
  [10] (webpack)/buildin/global.js 509 bytes {1} [built]
  [80] ./node_modules/react/react.js 56 bytes {1} [built]
 [153] (webpack)-dev-server/client?http://localhost:8000 5.59 kB {1} [built]
 [171] (webpack)/hot/dev-server.js 1.61 kB {1} [built]
 [173] ./node_modules/babel-polyfill/lib/index.js 833 bytes {1} [built]
 [209] ./node_modules/react-dom/index.js 59 bytes {1} [built]
 [235] ./node_modules/whatwg-fetch/fetch.js 12.7 kB {1} [built]
 [236] multi (webpack)-dev-server/client?http://localhost:8000 webpack/hot/dev-server ./src/App.jsx 52 bytes {0} [built]
 [237] ./node_modules/url/url.js 23.3 kB {1} [built]
 [243] ./node_modules/strip-ansi/index.js 161 bytes {1} [built]
 [245] (webpack)-dev-server/client/socket.js 856 bytes {1} [built]
 [284] ./src/App.jsx 655 bytes {0} [built]
 [482] ./node_modules/react-dom/lib/ReactDOM.js 5.17 kB {1} [built]
 [567] ./src/IssueList.jsx 8.32 kB {0} [built]
 [570] multi (webpack)-dev-server/client?http://localhost:8000 webpack/hot/dev-server react react-dom whatwg-fetch babel-polyfill 88 bytes {1} [built]
    + 556 hidden modules
webpack: Compiled successfully.

My dependencies:
"dependencies": {
    "body-parser": "^1.17.2",
    "express": "^4.15.3",
    "mongodb": "^2.2.29"
  },
"devDependencies": {
    "babel-cli": "^6.24.1",
    "babel-core": "^6.25.0",
    "babel-loader": "^7.1.1",
    "babel-polyfill": "^6.23.0",
    "babel-preset-es2015": "^6.24.1",
    "babel-preset-react": "^6.24.1",
    "nodemon": "^1.11.0",
    "react": "^15.6.1",
    "react-dom": "^15.6.1",
    "webpack": "^3.0.0",
    "webpack-dev-server": "^2.5.1",
    "whatwg-fetch": "^2.0.3"
  }

My webpack.config.js file:

    const webpack = require('webpack');
    const path = require('path');

    module.exports = {
        entry: {
            app: './src/App.jsx',
            vendor:['react', 'react-dom', 'whatwg-fetch'],
        },
        output: {
            path: path.resolve(__dirname, './static'),
            filename: "app.bundle.js"
        },
        plugins: [
          new webpack.optimize.CommonsChunkPlugin({name: 'vendor',filename: 'vendor.bundle.js'})
        ],
        module: {
            rules:[
                {
                    test:/\.jsx$/,
                    use: {
                        loader: 'babel-loader',
                        options: {
                            presets: ['react','es2015']
                        }
                    }
                },
            ]
        },

        devServer:{
            port: 8000,
                contentBase: '/Users/Angel/WebstormProjects/myMern/static',
                proxy: {
                '/api/*':{
                    target: 'http://localhost:3000',
                }
            }
        }

    };
</code>```

When I open port: 8000 I get a blank screen but all the network traffic is good.... I'm I missing something?

Thank you.

答: Check if your bundles are build correctly, either by inspecting them manually running $ webpack or maybe there are errors/warnings in the console, it's likely to get a blank page in case there are build errors and the JS fails to load/parse/execute. Otherwise check the proxy settings or remove them if possible, check them by adding some HTML to your index.html manually.

Title: webpack-dev-server get blank screen

Body:
Greetings I'm building a MERN stack for the first time and using Webpack  as my build tool. The goal is to have the API's of the app served by Express and the static content(my static dir) and bundles served by webpack-dev-server.

Here is my build:
Project is running at http://localhost:8000/
webpack output is served from /
Content not from webpack is served from static
Hash: 0f82642b68722fddb0c7
Version: webpack 3.1.0
Time: 3941ms
           Asset     Size  Chunks                    Chunk Names
   app.bundle.js  15.4 kB       0  [emitted]         app
vendor.bundle.js  1.35 MB       1  [emitted]  [big]  vendor
  [10] (webpack)/buildin/global.js 509 bytes {1} [built]
  [80] ./node_modules/react/react.js 56 bytes {1} [built]
 [153] (webpack)-dev-server/client?http://localhost:8000 5.59 kB {1} [built]
 [171] (webpack)/hot/dev-server.js 1.61 kB {1} [built]
 [173] ./node_modules/babel-polyfill/lib/index.js 833 bytes {1} [built]
 [209] ./node_modules/react-dom/index.js 59 bytes {1} [built]
 [235] ./node_modules/whatwg-fetch/fetch.js 12.7 kB {1} [built]
 [236] multi (webpack)-dev-server/client?http://localhost:8000 webpack/hot/dev-server ./src/App.jsx 52 bytes {0} [built]
 [237] ./node_modules/url/url.js 23.3 kB {1} [built]
 [243] ./node_modules/strip-ansi/index.js 161 bytes {1} [built]
 [245] (webpack)-dev-server/client/socket.js 856 bytes {1} [built]
 [284] ./src/App.jsx 655 bytes {0} [built]
 [482] ./node_modules/react-dom/lib/ReactDOM.js 5.17 kB {1} [built]
 [567] ./src/IssueList.jsx 8.32 kB {0} [built]
 [570] multi (webpack)-dev-server/client?http://localhost:8000 webpack/hot/dev-server react react-dom whatwg-fetch babel-polyfill 88 bytes {1} [built]
    + 556 hidden modules
webpack: Compiled successfully.

My dependencies:
"dependencies": {
    "body-parser": "^1.17.2",
    "express": "^4.15.3",
    "mongodb": "^2.2.29"
  },
"devDependencies": {
    "babel-cli": "^6.24.1",
    "babel-core": "^6.25.0",
    "babel-loader": "^7.1.1",
    "babel-polyfill": "^6.23.0",
    "babel-preset-es2015": "^6.24.1",
    "babel-preset-react": "^6.24.1",
    "nodemon": "^1.11.0",
    "react": "^15.6.1",
    "react-dom": "^15.6.1",
    "webpack": "^3.0.0",
    "webpack-dev-server": "^2.5.1",
    "whatwg-fetch": "^2.0.3"
  }

My webpack.config.js file:

    const webpack = require('webpack');
    const path = require('path');

    module.exports = {
        entry: {
            app: './src/App.jsx',
            vendor:['react', 'react-dom', 'whatwg-fetch'],
        },
        output: {
            path: path.resolve(__dirname, './static'),
            filename: "app.bundle.js"
        },
        plugins: [
          new webpack.optimize.CommonsChunkPlugin({name: 'vendor',filename: 'vendor.bundle.js'})
        ],
        module: {
            rules:[
                {
                    test:/\.jsx$/,
                    use: {
                        loader: 'babel-loader',
                        options: {
                            presets: ['react','es2015']
                        }
                    }
                },
            ]
        },

        devServer:{
            port: 8000,
                contentBase: '/Users/Angel/WebstormProjects/myMern/static',
                proxy: {
                '/api/*':{
                    target: 'http://localhost:3000',
                }
            }
        }

    };

When I open port: 8000 I get a blank screen but all the network traffic is good.... I'm I missing something?

Thank you.


来源: stackexchange

问:
How quickly dealocate map which contains dynamically allocated memory as a value?
Map consists of string as a key and objects of A as a value. Function clear() from std::map/std::unordered_map won`t call destructor. I have to take care of dealocating memory by my self when I want to clear the map. Is it only one way to dealocate memory using for loop?
Code:

```<code>#include <iostream>
#include <unordered_map>
class A
{
public:
    A() { std::cout << "A()" << std::endl; }
    ~A() { std::cout << "~A()" << std::endl; }
};
int main ()
{
  std::unordered_map<std::string, const A*> mymap = { {"house",new A()}, {"car", new A()}, {"grapefruit", new A()} };
  //mymap.clear();//won`t call destructor
  for(const auto &i : mymap)
      delete i.second;      //dealocate value
  mymap.clear();            //clear whole object from tha map
}
</code>```

Is it possible to do this faster, e.g. without using for loop?

答:
Yep!  Use unique_ptr and automate this.

(Note how I have converted const A* to std::unique_ptr<const A>)

```<code>#include <iostream>
#include <memory>
#include <unordered_map>

class A {
public:
    A() { std::cout << "A()" << std::endl; }
    ~A() { std::cout << "~A()" << std::endl; }
};

int main() {
  std::unordered_map<std::string, std::unique_ptr<const A>> mymap;
  mymap["house"] = std::make_unique<A>();
  mymap["car"] = std::make_unique<A>();
  mymap["grapefruit"] = std::make_unique<A>();

  mymap.clear(); // Will call destructor!
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Map consists of string as a key and objects of A as a value. Function clear() from std::map/std::unordered_map won`t call destructor. I have to take care of dealocating memory by my self when I want to clear the map. Is it only one way to dealocate memory using for loop?
Code:

#include <iostream>
#include <unordered_map>
class A
{
public:
    A() { std::cout << "A()" << std::endl; }
    ~A() { std::cout << "~A()" << std::endl; }
};
int main ()
{
  std::unordered_map<std::string, const A*> mymap = { {"house",new A()}, {"car", new A()}, {"grapefruit", new A()} };
  //mymap.clear();//won`t call destructor
  for(const auto &i : mymap)
      delete i.second;      //dealocate value
  mymap.clear();            //clear whole object from tha map
}

Is it possible to do this faster, e.g. without using for loop?

Body:
Yep!  Use unique_ptr and automate this.

(Note how I have converted const A* to std::unique_ptr<const A>)

#include <iostream>
#include <memory>
#include <unordered_map>

class A {
public:
    A() { std::cout << "A()" << std::endl; }
    ~A() { std::cout << "~A()" << std::endl; }
};

int main() {
  std::unordered_map<std::string, std::unique_ptr<const A>> mymap;
  mymap["house"] = std::make_unique<A>();
  mymap["car"] = std::make_unique<A>();
  mymap["grapefruit"] = std::make_unique<A>();

  mymap.clear(); // Will call destructor!
}


问:
Redux Form Field Array Validation
I am using the Redux Form module for all forms in the project. I want to create a validation based on the component props. There is a table with some fields on every row.
The table
The first field is a dropdown with all the products which come from the store. Every product has an available quantity and if the field quantity is more than the available quantity the Redux Form should return an error for the specific row. I can't do it in the validate function that is passed in the reduxForm method:

```<code>reduxForm({
  validate,
  form: 'theNameOfTheForm'
})
</code>```

The reason why I can't do the table validation in the validate function is because it can't see the current props of the component (I didn't find a way how I can do that). I've decided to pass the validate function as a prop to the FieldArray component:

```<code>// some methods

validate(values) {
    // some validation code
}

render() {
    return (
        <FieldArray validate={this.validate} />
    )
}
</code>```

From the validate method I can access the component props but whatever I return from this method an error is not received by the field prop in the component passed as a component prop to the <FieldArray />.

```<code>return 'Some error message';

return ['Some error message'];

return {
    products: 'Some error message'
};

return {
    products: ['Some error message']
};

<FieldArray validate={this.validate} component={FieldArrayComponent} />

const FieldArrayComponent = ({ field, meta }) => {};
</code>```

How I can do the validation? Am I doing something wrong? Is there another way how I can do the validation?

答:
You can pass the component props to the validate function when using HOC (higher order components) and do the validation in the main validate function (no need to create a method in the component and then pass it to the FieldArray component). Just export the component like this:

```<code>export default connect(
  mapStateToProps,
  mapDispatchToProps
)(
  reduxForm({
    validate,
    form: 'ExampleForm'
  })(ExampleForm)
);
</code>```

The component props are passed in the validation function as a second parameter:

```<code>const validate = (values, props) => {
  const errors = {};

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

Title: Redux Form Field Array Validation

Body:
I am using the Redux Form module for all forms in the project. I want to create a validation based on the component props. There is a table with some fields on every row.
The table
The first field is a dropdown with all the products which come from the store. Every product has an available quantity and if the field quantity is more than the available quantity the Redux Form should return an error for the specific row. I can't do it in the validate function that is passed in the reduxForm method:

reduxForm({
  validate,
  form: 'theNameOfTheForm'
})

The reason why I can't do the table validation in the validate function is because it can't see the current props of the component (I didn't find a way how I can do that). I've decided to pass the validate function as a prop to the FieldArray component:

// some methods

validate(values) {
    // some validation code
}

render() {
    return (
        <FieldArray validate={this.validate} />
    )
}

From the validate method I can access the component props but whatever I return from this method an error is not received by the field prop in the component passed as a component prop to the <FieldArray />.

return 'Some error message';

return ['Some error message'];

return {
    products: 'Some error message'
};

return {
    products: ['Some error message']
};

<FieldArray validate={this.validate} component={FieldArrayComponent} />

const FieldArrayComponent = ({ field, meta }) => {};

How I can do the validation? Am I doing something wrong? Is there another way how I can do the validation?

Body:
You can pass the component props to the validate function when using HOC (higher order components) and do the validation in the main validate function (no need to create a method in the component and then pass it to the FieldArray component). Just export the component like this:

export default connect(
  mapStateToProps,
  mapDispatchToProps
)(
  reduxForm({
    validate,
    form: 'ExampleForm'
  })(ExampleForm)
);

The component props are passed in the validation function as a second parameter:

const validate = (values, props) => {
  const errors = {};

  return errors;
};


问:
Using fetch API with mode: 'no-cors', can’t set request headers
I am trying to hit a service end point and the service is a login service
I am using the authentication type as basic ,The code is in react and using the fetch library however even if i set the headers field in my request I am unable to see the values of corresponding headers in my request in network tab?

Following is the code  :

```<code>var obj = {
  method: 'GET' ,
  mode : 'no-cors',
  headers: {
      'Access-Control-Request-Headers': 'Authorization',
      'Authorization': 'Basic amFzcGVyYWRtaW46amFzcGVyYWRtaW4=',
      'Content-Type': 'application/json',
      'Origin': ''
  },
  credentials: 'include'
};
fetch('http://myreport:8082/jasperserver/rest/login/', obj ).then(…
</code>```

Popup where its asking me for username and password

Request and response calls from the network tabs

答:
None of your headers are CORS-safelisted, so they can not be attached to the request.

Explanation:

no-cors request mode sets guard property for a headers object to request-no-cors

To append a name/value (name/value) pair to a Headers object (headers), browser have to run these steps:

Normalize value.

If name is not a name or value is not a value, then throw a TypeError.

If guard is "immutable", then throw a TypeError.

Otherwise, if guard is "request" and name is a forbidden header name, return.

Otherwise, if guard is "request-no-cors" and name/value is not a CORS-safelisted request-header, return. ← your scenario

Otherwise, if guard is "response" and name is a forbidden response-header name, return.

Append name/value to header list.

CORS-safelisted request-header (case-insensitive):

Accept

Accept-Language

Content-Language

Content-Type, but only if the value is one of:

application/x-www-form-urlencoded

multipart/form-data

text/plain

You can learn more about fetch's Headers class specs here:
https://fetch.spec.whatwg.org/#headers-class

Body:
I am trying to hit a service end point and the service is a login service
I am using the authentication type as basic ,The code is in react and using the fetch library however even if i set the headers field in my request I am unable to see the values of corresponding headers in my request in network tab?

Following is the code  :

var obj = {
  method: 'GET' ,
  mode : 'no-cors',
  headers: {
      'Access-Control-Request-Headers': 'Authorization',
      'Authorization': 'Basic amFzcGVyYWRtaW46amFzcGVyYWRtaW4=',
      'Content-Type': 'application/json',
      'Origin': ''
  },
  credentials: 'include'
};
fetch('http://myreport:8082/jasperserver/rest/login/', obj ).then(…

Popup where its asking me for username and password

Request and response calls from the network tabs

ContentLicense: CC BY-SA 4.0


问:
How to draw a face using a method
I am drawing the face from the drawFace funtion 1 time.  I want to call that function in the paint method so it will draw the face multiple times at x/y co-ordinates i specify.</p>

```<code>public class smilingfacefunction extends Canvas
{
public void paint(Graphics g)
{
    drawFace(g, 500, 300);
    drawFace(g, 100, 100);
}

public void drawFace (Graphics g, int x, int y)
{

g.setColor(Color.YELLOW);
g.fillOval(100, 100, 100, 100);
g.setColor(Color.BLUE);
g.fillOval(125, 125, 20, 20);
g.fillOval(155, 125, 20, 20);
g.setColor(Color.red);
g.drawArc(125,150,40,40,0,-180);
}

public static void main(String[] args)
{
   JFrame win = new JFrame("Smile");
   win.setSize(700, 700);
   win.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
   win.add(new smilingfacefunction());
   win.setVisible(true);
}

}
</code>```

答:
Your drawFace method has to use the x and y parameter as a reference point from where to start drawing. Something like this:

```<code>public void drawFace (Graphics g, int x, int y)
{
   g.setColor(Color.YELLOW);
   g.fillOval(x, y, 100, 100);
   g.setColor(Color.BLUE);
   g.fillOval(x + 25, y + 25, 20, 20);
   g.fillOval(x + 55, y + 25, 20, 20);
   g.setColor(Color.red);
   g.drawArc(x + 25, y + 50, 40, 40, 0, -180);
}
</code>```

You can now fine tune the drawing so that the elements are placed where you want them for each face.

Title: How to draw a face using a method

Body:
I am drawing the face from the drawFace funtion 1 time.  I want to call that function in the paint method so it will draw the face multiple times at x/y co-ordinates i specify.

public class smilingfacefunction extends Canvas
{
public void paint(Graphics g)
{
    drawFace(g, 500, 300);
    drawFace(g, 100, 100);
}

public void drawFace (Graphics g, int x, int y)
{

g.setColor(Color.YELLOW);
g.fillOval(100, 100, 100, 100);
g.setColor(Color.BLUE);
g.fillOval(125, 125, 20, 20);
g.fillOval(155, 125, 20, 20);
g.setColor(Color.red);
g.drawArc(125,150,40,40,0,-180);
}

public static void main(String[] args)
{
   JFrame win = new JFrame("Smile");
   win.setSize(700, 700);
   win.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
   win.add(new smilingfacefunction());
   win.setVisible(true);
}

}

Body:
Your drawFace method has to use the x and y parameter as a reference point from where to start drawing. Something like this:

public void drawFace (Graphics g, int x, int y)
{
   g.setColor(Color.YELLOW);
   g.fillOval(x, y, 100, 100);
   g.setColor(Color.BLUE);
   g.fillOval(x + 25, y + 25, 20, 20);
   g.fillOval(x + 55, y + 25, 20, 20);
   g.setColor(Color.red);
   g.drawArc(x + 25, y + 50, 40, 40, 0, -180);
}

You can now fine tune the drawing so that the elements are placed where you want them for each face.


问:
Antlr V4 grammar for XQuery 3.1
I found the following Antlr 4 grammar:

https://gist.github.com/JoeyAcc/829c28fcf18091ed6ebfcf91d7519f58

I received the following error while trying to generate the code from it:

```<code>error(134): xquery31.g4:178:26: rule reference PragmaContentsInternal is not currently supported in a set
error(134): xquery31.g4:264:25: rule reference DirPIContentsInternal is not currently supported in a set
error(134): xquery31.g4:268:32: rule reference CDataSectionContentsInternal is not currently supported in a set
error(134): xquery31.g4:311:17: rule reference StringConstructorCharsInternal is not currently supported in a set
warning(156): xquery31.g4:377:59: invalid escape sequence
warning(156): xquery31.g4:378:60: invalid escape sequence
warning(156): xquery31.g4:392:30: invalid escape sequence
warning(156): xquery31.g4:394:30: invalid escape sequence
error(134): xquery31.g4:416:27: rule reference CommentContentsInternal is not currently supported in a set
warning(146): xquery31.g4:13:0: non-fragment lexer rule Prolog can match the empty string
warning(146): xquery31.g4:110:0: non-fragment lexer rule WindowVars can match the empty string
warning(146): xquery31.g4:127:0: non-fragment lexer rule OrderModifier can match the empty string
warning(146): xquery31.g4:211:0: non-fragment lexer rule PredicateList can match the empty string
warning(146): xquery31.g4:248:0: non-fragment lexer rule DirAttributeList can match the empty string
warning(146): xquery31.g4:261:0: non-fragment lexer rule DirCommentContents can match the empty string
error(99): xquery31.g4::: grammar xquery31 has no rules
</code>```

Are there any suggestions to fix this ANTLR V4 grammar?

The EBNF for XQuery v3.1 is here

答:
I think the conclusion of the work by JoeyACC is here - https://gist.github.com/JoeyAcc/375663dfc21cd7ec4d35ea8f7ff251d0#file-xquery31-g4

Another approach would be to take this Antlrv4 XQuery 1.0 grammar and add the missing parts for 3.1: https://github.com/bluezio/xquery-parser

Title: Antlr V4 grammar for XQuery 3.1

Body:
I found the following Antlr 4 grammar:

https://gist.github.com/JoeyAcc/829c28fcf18091ed6ebfcf91d7519f58

I received the following error while trying to generate the code from it:

error(134): xquery31.g4:178:26: rule reference PragmaContentsInternal is not currently supported in a set
error(134): xquery31.g4:264:25: rule reference DirPIContentsInternal is not currently supported in a set
error(134): xquery31.g4:268:32: rule reference CDataSectionContentsInternal is not currently supported in a set
error(134): xquery31.g4:311:17: rule reference StringConstructorCharsInternal is not currently supported in a set
warning(156): xquery31.g4:377:59: invalid escape sequence
warning(156): xquery31.g4:378:60: invalid escape sequence
warning(156): xquery31.g4:392:30: invalid escape sequence
warning(156): xquery31.g4:394:30: invalid escape sequence
error(134): xquery31.g4:416:27: rule reference CommentContentsInternal is not currently supported in a set
warning(146): xquery31.g4:13:0: non-fragment lexer rule Prolog can match the empty string
warning(146): xquery31.g4:110:0: non-fragment lexer rule WindowVars can match the empty string
warning(146): xquery31.g4:127:0: non-fragment lexer rule OrderModifier can match the empty string
warning(146): xquery31.g4:211:0: non-fragment lexer rule PredicateList can match the empty string
warning(146): xquery31.g4:248:0: non-fragment lexer rule DirAttributeList can match the empty string
warning(146): xquery31.g4:261:0: non-fragment lexer rule DirCommentContents can match the empty string
error(99): xquery31.g4::: grammar xquery31 has no rules

Are there any suggestions to fix this ANTLR V4 grammar?

The EBNF for XQuery v3.1 is here


问:
I'm using the CountDownLatch of JUC,but my app is blocked
I'm learning JUC,I want to calculate the total time that the program runs with five threads,but it's blocked after print "1 2 3"。please tell me what the reason is ？
   In addition, if I don't call the function "isPrime(int)",The program will execute normally.</p>

```<code>public class TestCountDownLatch {

 public static void main(String[] args) {
     CountDownLatch cwt = new CountDownLatch(5);
     Runnable runnable = new CountDownThread(cwt);
     long start = System.currentTimeMillis();
     for (int i = 0; i < 5; i++) {
         new Thread(runnable).start();
     }
     try {
         cwt.await();
     } catch (InterruptedException e) {
         e.printStackTrace();
     }
     long end = System.currentTimeMillis();
     System.out.println("total time :" + (end - start));
    }
}

class CountDownThread implements Runnable{

private CountDownLatch countdownLatch;

private int num = 1;

public CountDownThread(CountDownLatch countdownLatch) {
    this.countdownLatch = countdownLatch;
}

@Override
public void run() {
    try{
        while(true){
            synchronized (this) {
                if(num > 100){
                    break;
                }
                if(isPrime(num)){
                    System.out.println(num++);
                }
            }
        }
    }finally{
        countdownLatch.countDown();
    }

}

private boolean isPrime(int i) {
    for (int j = 2; j <= (i >> 1); j++) {
        if(i % j == 0){
            return false;
        }
    }
    return true;
}
}
</code>```

答:
Your Runnable run method, is only incrementing num when its prime and hence when it encounters 4 which is not prime its not incrementing num and your program is in that state for rest of period when its running. Fiddled with below mentioned piece which makes it go beyond that point and break at 100.

```<code> @Override
public void run() {
    try {
        while (true) {
            synchronized (this) {
                num++; // initially assigning int num = 0, and then doing this
                if (num > 100) {
                    break;
                }
                if (isPrime(num)) {
                    System.out.println(num);
                }
            }
        }
    } finally {
        countdownLatch.countDown();
    }
}
</code>```

Body:
I'm learning JUC,I want to calculate the total time that the program runs with five threads,but it's blocked after print "1 2 3"。please tell me what the reason is ？
   In addition, if I don't call the function "isPrime(int)",The program will execute normally.

public class TestCountDownLatch {

 public static void main(String[] args) {
     CountDownLatch cwt = new CountDownLatch(5);
     Runnable runnable = new CountDownThread(cwt);
     long start = System.currentTimeMillis();
     for (int i = 0; i < 5; i++) {
         new Thread(runnable).start();
     }
     try {
         cwt.await();
     } catch (InterruptedException e) {
         e.printStackTrace();
     }
     long end = System.currentTimeMillis();
     System.out.println("total time :" + (end - start));
    }
}

class CountDownThread implements Runnable{

private CountDownLatch countdownLatch;

private int num = 1;

public CountDownThread(CountDownLatch countdownLatch) {
    this.countdownLatch = countdownLatch;
}

@Override
public void run() {
    try{
        while(true){
            synchronized (this) {
                if(num > 100){
                    break;
                }
                if(isPrime(num)){
                    System.out.println(num++);
                }
            }
        }
    }finally{
        countdownLatch.countDown();
    }

}

private boolean isPrime(int i) {
    for (int j = 2; j <= (i >> 1); j++) {
        if(i % j == 0){
            return false;
        }
    }
    return true;
}
}

Body:
Your Runnable run method, is only incrementing num when its prime and hence when it encounters 4 which is not prime its not incrementing num and your program is in that state for rest of period when its running. Fiddled with below mentioned piece which makes it go beyond that point and break at 100.

 @Override
public void run() {
    try {
        while (true) {
            synchronized (this) {
                num++; // initially assigning int num = 0, and then doing this
                if (num > 100) {
                    break;
                }
                if (isPrime(num)) {
                    System.out.println(num);
                }
            }
        }
    } finally {
        countdownLatch.countDown();
    }
}


问:
When using Type abbreviations/alias, why should I use the fun keyword?
In the below example I'm using Type abbreviation. Why should I use the fun keyword as opposed to calling it without the fun keyword?</p>

```<code>type AdditionFunction = int->int->int

let f:AdditionFunction = fun a b -> a + b
</code>```

答:
Because otherwise you can't annotate it with AdditionFunction type. You need to put that on a value that has type int -> int -> int, and the way F# syntax works is that you have no way of doing it with the let-bound style.

Your options are:

```<code>let f : int -> int -> int =
   fun a b -> ...

let f a : int -> int =
   fun b -> ...

let f a b : int =
   ...
</code>```

and only the first one has the type you could replace with the alias.

But ultimately you don't need to do it. You can define it as an int -> int -> int function and you'll still be able to use it anywhere you'd use an AdditionFunction.

At the end of the day, type aliases are just that - aliases. They can be used interchangeably with the types they stand for and are erased during compilation.

Body:
In the below example I'm using Type abbreviation. Why should I use the fun keyword as opposed to calling it without the fun keyword?

type AdditionFunction = int->int->int

let f:AdditionFunction = fun a b -> a + b

Body:
Because otherwise you can't annotate it with AdditionFunction type. You need to put that on a value that has type int -> int -> int, and the way F# syntax works is that you have no way of doing it with the let-bound style.

Your options are:

let f : int -> int -> int =
   fun a b -> ...

let f a : int -> int =
   fun b -> ...

let f a b : int =
   ...

and only the first one has the type you could replace with the alias.

But ultimately you don't need to do it. You can define it as an int -> int -> int function and you'll still be able to use it anywhere you'd use an AdditionFunction.

At the end of the day, type aliases are just that - aliases. They can be used interchangeably with the types they stand for and are erased during compilation.


问:
Java mail : receiving email body as .htm file attachment along with attachment and body
Dears,

Facing an issue mail body duplicating in mobile when sending email using java mail (Microsoft Exchange server). Sending email body and pdf as attachment but when it customer receives the mail in inbox the email body content is duplicating (twice), also its sending PDF and one .htm file as attachment. Due to .htm file the email body is coming as twice. How to avoid this duplication body in mail. Below is the code used to send an email.  This issue not happening in browser based email clients, Its happening only in mobile.

Setting email body (html content) as below

```<code>import javax.mail.Message;
Message  msg = new SMTPMessage(session);
MimeMultipart mp = new MimeMultipart();
MimeBodyPart mbp = null;
mbp = new MimeBodyPart();
mbp.setContent("Hi, This is a test.", "text/html; charset=utf-8");
mp.addBodyPart(mbp);
</code>```

setting pdf as attachment

```<code> MimeBodyPart mbp = null;
 ByteArrayDataSource xfds3 = null;
 mbp = new MimeBodyPart();
 byte[] b = //PDF byte array
 xfds3 = new ByteArrayDataSource(b, "application/pdf");
 mbp.setDataHandler(new DataHandler(xfds3));
 String maskName = maskingNo(fileName, prop);
 mbp.setFileName(maskName);
 mp.addBodyPart(mbp);
 msg.setContent(mp);
 transport.sendMessage(msg, msg.getAllRecipients());
</code>```

Can anyone help how to solve this issue?

Output is coming in mail body:

Hi,
This is a test.

Hi,
This is a test

答:
This depends on the format you are sending and what the client is showing or build based on that.

There are:

plain/text(no fancy Styling)

text/html

Richtext (should normally be avoid, due to the winmail.dat issue)

multipart/mixed

So a possible email could have the source:

```<code>  multipart/mixed
    multipart/alternative (holding the two forms of the body part)
      text/plain
      text/html
    text/plain or image/gif (the attachment)
</code>```

However depending on the mail client this email might only show the plain text elements and no "structure" at all. Such stuff above if often used to have some compatibility in place, so if the email client couldn´t handle HTML emails the user can still read the plain text. If the client couldn´t understand HTML (or if the multipart section is broken) a HTML content might be changed into an attachment (might be your issue).

So your question isn´t that easy to answer as we:

Do not know which Exchange Server send out those emails

Which Format is used to send out the emails

If something is changing the format on the way to the sender

Which client the receiver is used

Further troubleshooting must be done on your side:

Is that happening when you send an email to an internal user

Is that happening when you send an email to Gmail, Outlook.com, ...

Is that happening when you send the email without HTML content (only attachment)?

Is your multipart section correct? Check some examples on the internet for example here:

package net.codejava.mail;

import java.io.IOException;
import java.util.Date;
import java.util.Properties;

import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;

public class EmailAttachmentSender {

```<code>public static void sendEmailWithAttachments(String host, String port,
        final String userName, final String password, String toAddress,
        String subject, String message, String[] attachFiles)
        throws AddressException, MessagingException {
    // sets SMTP server properties
    Properties properties = new Properties();
    properties.put("mail.smtp.host", host);
    properties.put("mail.smtp.port", port);
    properties.put("mail.smtp.auth", "true");
    properties.put("mail.smtp.starttls.enable", "true");
    properties.put("mail.user", userName);
    properties.put("mail.password", password);

    // creates a new session with an authenticator
    Authenticator auth = new Authenticator() {
        public PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(userName, password);
        }
    };
    Session session = Session.getInstance(properties, auth);

    // creates a new e-mail message
    Message msg = new MimeMessage(session);

    msg.setFrom(new InternetAddress(userName));
    InternetAddress[] toAddresses = { new InternetAddress(toAddress) };
    msg.setRecipients(Message.RecipientType.TO, toAddresses);
    msg.setSubject(subject);
    msg.setSentDate(new Date());

    // creates message part
    MimeBodyPart messageBodyPart = new MimeBodyPart();
    messageBodyPart.setContent(message, "text/html");

    // creates multi-part
    Multipart multipart = new MimeMultipart();
    multipart.addBodyPart(messageBodyPart);

    // adds attachments
    if (attachFiles != null && attachFiles.length > 0) {
        for (String filePath : attachFiles) {
            MimeBodyPart attachPart = new MimeBodyPart();

            try {
                attachPart.attachFile(filePath);
            } catch (IOException ex) {
                ex.printStackTrace();
            }

            multipart.addBodyPart(attachPart);
        }
    }

    // sets the multi-part as e-mail's content
    msg.setContent(multipart);

    // sends the e-mail
    Transport.send(msg);

}

/**
 * Test sending e-mail with attachments
 */
public static void main(String[] args) {
    // SMTP info
    String host = "smtp.gmail.com";
    String port = "587";
    String mailFrom = "your-email-address";
    String password = "your-email-password";

    // message info
    String mailTo = "your-friend-email";
    String subject = "New email with attachments";
    String message = "I have some attachments for you.";

    // attachments
    String[] attachFiles = new String[3];
    attachFiles[0] = "e:/Test/Picture.png";
    attachFiles[1] = "e:/Test/Music.mp3";
    attachFiles[2] = "e:/Test/Video.mp4";

    try {
        sendEmailWithAttachments(host, port, mailFrom, password, mailTo,
            subject, message, attachFiles);
        System.out.println("Email sent.");
    } catch (Exception ex) {
        System.out.println("Could not send email.");
        ex.printStackTrace();
    }
}
</code>```

}

Body:
Dears,

Facing an issue mail body duplicating in mobile when sending email using java mail (Microsoft Exchange server). Sending email body and pdf as attachment but when it customer receives the mail in inbox the email body content is duplicating (twice), also its sending PDF and one .htm file as attachment. Due to .htm file the email body is coming as twice. How to avoid this duplication body in mail. Below is the code used to send an email.  This issue not happening in browser based email clients, Its happening only in mobile.

Setting email body (html content) as below

import javax.mail.Message;
Message  msg = new SMTPMessage(session);
MimeMultipart mp = new MimeMultipart();
MimeBodyPart mbp = null;
mbp = new MimeBodyPart();
mbp.setContent("Hi, This is a test.", "text/html; charset=utf-8");
mp.addBodyPart(mbp);

setting pdf as attachment

 MimeBodyPart mbp = null;
 ByteArrayDataSource xfds3 = null;
 mbp = new MimeBodyPart();
 byte[] b = //PDF byte array
 xfds3 = new ByteArrayDataSource(b, "application/pdf");
 mbp.setDataHandler(new DataHandler(xfds3));
 String maskName = maskingNo(fileName, prop);
 mbp.setFileName(maskName);
 mp.addBodyPart(mbp);
 msg.setContent(mp);
 transport.sendMessage(msg, msg.getAllRecipients());

Can anyone help how to solve this issue?

Output is coming in mail body:

Hi,
This is a test.

Hi,
This is a test

Body:
This depends on the format you are sending and what the client is showing or build based on that.

There are:

plain/text(no fancy Styling)

text/html

Richtext (should normally be avoid, due to the winmail.dat issue)

multipart/mixed

So a possible email could have the source:

  multipart/mixed
    multipart/alternative (holding the two forms of the body part)
      text/plain
      text/html
    text/plain or image/gif (the attachment)

However depending on the mail client this email might only show the plain text elements and no "structure" at all. Such stuff above if often used to have some compatibility in place, so if the email client couldn´t handle HTML emails the user can still read the plain text. If the client couldn´t understand HTML (or if the multipart section is broken) a HTML content might be changed into an attachment (might be your issue).

So your question isn´t that easy to answer as we:

Do not know which Exchange Server send out those emails

Which Format is used to send out the emails

If something is changing the format on the way to the sender

Which client the receiver is used

Further troubleshooting must be done on your side:

Is that happening when you send an email to an internal user

Is that happening when you send an email to Gmail, Outlook.com, ...

Is that happening when you send the email without HTML content (only attachment)?

Is your multipart section correct? Check some examples on the internet for example here:

package net.codejava.mail;

import java.io.IOException;
import java.util.Date;
import java.util.Properties;

import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;

public class EmailAttachmentSender {

public static void sendEmailWithAttachments(String host, String port,
        final String userName, final String password, String toAddress,
        String subject, String message, String[] attachFiles)
        throws AddressException, MessagingException {
    // sets SMTP server properties
    Properties properties = new Properties();
    properties.put("mail.smtp.host", host);
    properties.put("mail.smtp.port", port);
    properties.put("mail.smtp.auth", "true");
    properties.put("mail.smtp.starttls.enable", "true");
    properties.put("mail.user", userName);
    properties.put("mail.password", password);

    // creates a new session with an authenticator
    Authenticator auth = new Authenticator() {
        public PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(userName, password);
        }
    };
    Session session = Session.getInstance(properties, auth);

    // creates a new e-mail message
    Message msg = new MimeMessage(session);

    msg.setFrom(new InternetAddress(userName));
    InternetAddress[] toAddresses = { new InternetAddress(toAddress) };
    msg.setRecipients(Message.RecipientType.TO, toAddresses);
    msg.setSubject(subject);
    msg.setSentDate(new Date());

    // creates message part
    MimeBodyPart messageBodyPart = new MimeBodyPart();
    messageBodyPart.setContent(message, "text/html");

    // creates multi-part
    Multipart multipart = new MimeMultipart();
    multipart.addBodyPart(messageBodyPart);

    // adds attachments
    if (attachFiles != null && attachFiles.length > 0) {
        for (String filePath : attachFiles) {
            MimeBodyPart attachPart = new MimeBodyPart();

            try {
                attachPart.attachFile(filePath);
            } catch (IOException ex) {
                ex.printStackTrace();
            }

            multipart.addBodyPart(attachPart);
        }
    }

    // sets the multi-part as e-mail's content
    msg.setContent(multipart);

    // sends the e-mail
    Transport.send(msg);

}

/**
 * Test sending e-mail with attachments
 */
public static void main(String[] args) {
    // SMTP info
    String host = "smtp.gmail.com";
    String port = "587";
    String mailFrom = "your-email-address";
    String password = "your-email-password";

    // message info
    String mailTo = "your-friend-email";
    String subject = "New email with attachments";
    String message = "I have some attachments for you.";

    // attachments
    String[] attachFiles = new String[3];
    attachFiles[0] = "e:/Test/Picture.png";
    attachFiles[1] = "e:/Test/Music.mp3";
    attachFiles[2] = "e:/Test/Video.mp4";

    try {
        sendEmailWithAttachments(host, port, mailFrom, password, mailTo,
            subject, message, attachFiles);
        System.out.println("Email sent.");
    } catch (Exception ex) {
        System.out.println("Could not send email.");
        ex.printStackTrace();
    }
}

}


问:
Modify a list's elements based on element index
Using Haskell:

Let's say I have list: [1,3,4,2,3]
And I want to modify all 3's in the list. I know that I can apply this to select the 3's in this case:

```<code>map (\x -> if p x then f x else x) xs
</code>```

However, the functions being applied to the threes is dependent on their index within the list.

So for example if the index was added to the desired number the output of the function I'm going for would be: [1,4,4,2,7].

答:
While zipWith is probably the right way, just for a variety you may go recursive as follows;

```<code>tpi :: [Int] -> [Int]
tpi = runner 0
      where runner _ []     = []
            runner n (x:xs) | x == 3    = (n + x) : runner (n+1) xs
                            | otherwise = x : runner (n+1) xs
</code>```

Body:
Using Haskell:

Let's say I have list: [1,3,4,2,3]
And I want to modify all 3's in the list. I know that I can apply this to select the 3's in this case:

map (\x -> if p x then f x else x) xs

However, the functions being applied to the threes is dependent on their index within the list.

So for example if the index was added to the desired number the output of the function I'm going for would be: [1,4,4,2,7].

Body:
While zipWith is probably the right way, just for a variety you may go recursive as follows;

tpi :: [Int] -> [Int]
tpi = runner 0
      where runner _ []     = []
            runner n (x:xs) | x == 3    = (n + x) : runner (n+1) xs
                            | otherwise = x : runner (n+1) xs


答: Use a map of std::unique_ptrs and just clear() it. Or just hold A objects in the map rather than pointers.

Title: How quickly dealocate map which contains dynamically allocated memory as a value?


问:
Node.js Lambda Function "response is invalid" Amazon Alexa
UPDATE: I had a mistake on my http request endpoint. I had not set the appropriate authentication options so that fixed a lot of errors possibly this specific one.

My question is similar to one here:

Node.js Lambda function returns "The response is invalid" back to Alexa Service Simulator from REST call

However the solution to that question does not solve my problem. So I make an http request call to an xsjs service in Hana cloud. I am getting the 'response is invalid' error message. I can't see why. Here is my function:

```<code> // Create a web request and handle the response.
function httpGet(query, callback) {

    console.log("/n QUERY: "+ query);

    var host = 'datacloudyd070518trial.hanatrial.ondemand.com';
    var path = '/LocationInformation/getLocationInfo.xsjs?location=';
    var hostname = 'https://' + host + path + query;

    var auth = 'user1:D1anafer';

    var req = http.request({'hostname': hostname,
                            'auth': auth
                        }, (res) => {

    var body = '';

        res.on('data', (d) => {
            body += JSON.stringify(d);
        });

        res.on('end', function () {
            callback(body);
        });

    });

    req.end();

    req.on('error', (e) => {
        console.error(e);
    });

}
</code>```

And the function that calls it:

```<code>'getNewsIntent': function () {

    //self = this;

    httpGet(location, function (response) {

        // Parse the response into a JSON object ready to be formatted.
        //var output = JSON.parse(response);
        //output = output['change'];
        var output = response;

        var cardTitle = location;
        var cardContent = output;

        alexa.emit(':tellWithCard', output, cardTitle, cardContent);

    });

},
</code>```

Thank You
-Diana

答:
This is just a guess from the top of my head. To really help some detailed error message would be required like mentioned about.

But just a guess: Your http.request() is using the http module (https://nodejs.org/api/http.html) and your are accessing the a https resource. If so there is a https (https://nodejs.org/api/https.html) module or use something like axios https://www.npmjs.com/package/axios or requestjs (https://github.com/request/request) this will handle both.

Like I said just a blind guess without detailed error message and seeing your require statements but I am happy to dive deeper if you happen to have details.

HTH

Body:
UPDATE: I had a mistake on my http request endpoint. I had not set the appropriate authentication options so that fixed a lot of errors possibly this specific one.

My question is similar to one here:

Node.js Lambda function returns "The response is invalid" back to Alexa Service Simulator from REST call

However the solution to that question does not solve my problem. So I make an http request call to an xsjs service in Hana cloud. I am getting the 'response is invalid' error message. I can't see why. Here is my function:

 // Create a web request and handle the response.
function httpGet(query, callback) {

    console.log("/n QUERY: "+ query);

    var host = 'datacloudyd070518trial.hanatrial.ondemand.com';
    var path = '/LocationInformation/getLocationInfo.xsjs?location=';
    var hostname = 'https://' + host + path + query;

    var auth = 'user1:D1anafer';

    var req = http.request({'hostname': hostname,
                            'auth': auth
                        }, (res) => {

    var body = '';

        res.on('data', (d) => {
            body += JSON.stringify(d);
        });

        res.on('end', function () {
            callback(body);
        });

    });

    req.end();

    req.on('error', (e) => {
        console.error(e);
    });

}

And the function that calls it:

'getNewsIntent': function () {

    //self = this;

    httpGet(location, function (response) {

        // Parse the response into a JSON object ready to be formatted.
        //var output = JSON.parse(response);
        //output = output['change'];
        var output = response;

        var cardTitle = location;
        var cardContent = output;

        alexa.emit(':tellWithCard', output, cardTitle, cardContent);

    });

},

Thank You
-Diana


问:
css not showing correctly asp.net mvc
hi i'm  working on a admin template. I converted the html codes into mvc structure. Now i am stuck , when i create a page using the layout in the shared folder the footer goes up to the navigation bar. for more understanding check the screenshot

here is my _layoutadmin.cshtml

```<code>   <div class="container body">

    <div class="main_container">
        <div class="col-md-3 left_col">
            <div class="left_col scroll-view">
                <div class="navbar nav_title" style="border: 0;">
                    <a href="index.html" class="site_title"><i class="fa fa-paw"></i> <span>Admin Panel</span></a>
                </div>
                <div class="clearfix"></div>
                <!-- menu prile quick info -->
                <div class="profile">
                    <div class="profile_pic">
                        <img src="~/Content/admin/AdminLogo.jpg" alt="..." class="img-circle profile_img"/>
                        @*<img src="images/img.jpg" alt="..." class="img-circle profile_img">*@
                    </div>
                    <div class="profile_info">
                        <span>Welcome,</span>
                        <h2>John Doe</h2>
                    </div>
                </div>
                <!-- /menu prile quick info -->
                <br />
                <!-- sidebar menu -->
                <div id="sidebar-menu" class="main_menu_side hidden-print main_menu">
                    <div class="menu_section">
                        <h3>General</h3>
                        <ul class="nav side-menu">
                            <li>
                                <a><i class="fa fa-home"></i> Home <span class="fa fa-chevron-down"></span></a>
                                <ul class="nav child_menu" style="display: none">
                                    <li>
                                        <a href="index.html">Dashboard</a>
                                    </li>
                                    <li>
                                        <a href="index2.html">Dashboard2</a>
                                    </li>
                                    <li>
                                        <a href="index3.html">Dashboard3</a>
                                    </li>
                                </ul>
                            </li>
                            <li>
                                <a><i class="fa fa-edit"></i> Forms <span class="fa fa-chevron-down"></span></a>
                                <ul class="nav child_menu" style="display: none">
                                    <li>
                                        <a href="form.html">General Form</a>
                                    </li>
                                    <li>
                                        <a href="form_advanced.html">Advanced Components</a>
                                    </li>
                                    <li>
                                        <a href="form_validation.html">Form Validation</a>
                                    </li>
                                    <li>
                                        <a href="form_wizards.html">Form Wizard</a>
                                    </li>
                                    <li>
                                        <a href="form_upload.html">Form Upload</a>
                                    </li>
                                    <li>
                                        <a href="form_buttons.html">Form Buttons</a>
                                    </li>
                                </ul>
                            </li>
                            <li>
                                <a><i class="fa fa-desktop"></i> UI Elements <span class="fa fa-chevron-down"></span></a>
                                <ul class="nav child_menu" style="display: none">
                                    <li>
                                        <a href="general_elements.html">General Elements</a>
                                    </li>
                                    <li>
                                        <a href="media_gallery.html">Media Gallery</a>
                                    </li>
                                    <li>
                                        <a href="typography.html">Typography</a>
                                    </li>
                                    <li>
                                        <a href="icons.html">Icons</a>
                                    </li>
                                    <li>
                                        <a href="glyphicons.html">Glyphicons</a>
                                    </li>
                                    <li>
                                        <a href="widgets.html">Widgets</a>
                                    </li>
                                    <li>
                                        <a href="invoice.html">Invoice</a>
                                    </li>
                                    <li>
                                        <a href="inbox.html">Inbox</a>
                                    </li>
                                    <li>
                                        <a href="calender.html">Calender</a>
                                    </li>
                                </ul>
                            </li>
                            <li>
                                <a><i class="fa fa-table"></i> Tables <span class="fa fa-chevron-down"></span></a>
                                <ul class="nav child_menu" style="display: none">
                                    <li>
                                        <a href="tables.html">Tables</a>
                                    </li>
                                    <li>
                                        <a href="tables_dynamic.html">Table Dynamic</a>
                                    </li>
                                </ul>
                            </li>
                            <li>
                                <a><i class="fa fa-bar-chart-o"></i> Data Presentation <span class="fa fa-chevron-down"></span></a>
                                <ul class="nav child_menu" style="display: none">
                                    <li>
                                        <a href="chartjs.html">Chart JS</a>
                                    </li>
                                    <li>
                                        <a href="chartjs2.html">Chart JS2</a>
                                    </li>
                                    <li>
                                        <a href="morisjs.html">Moris JS</a>
                                    </li>
                                    <li>
                                        <a href="echarts.html">ECharts </a>
                                    </li>
                                    <li>
                                        <a href="other_charts.html">Other Charts </a>
                                    </li>
                                </ul>
                            </li>
                        </ul>
                    </div>
                    <div class="menu_section">
                        <h3>Live On</h3>
                        <ul class="nav side-menu">
                            <li>
                                <a><i class="fa fa-bug"></i> Additional Pages <span class="fa fa-chevron-down"></span></a>
                                <ul class="nav child_menu" style="display: none">
                                    <li>
                                        <a href="e_commerce.html">E-commerce</a>
                                    </li>
                                    <li>
                                        <a href="projects.html">Projects</a>
                                    </li>
                                    <li>
                                        <a href="project_detail.html">Project Detail</a>
                                    </li>
                                    <li>
                                        <a href="contacts.html">Contacts</a>
                                    </li>
                                    <li>
                                        <a href="profile.html">Profile</a>
                                    </li>
                                </ul>
                            </li>
                            <li>
                                <a><i class="fa fa-windows"></i> Extras <span class="fa fa-chevron-down"></span></a>
                                <ul class="nav child_menu" style="display: none">
                                    <li>
                                        <a href="page_404.html">404 Error</a>
                                    </li>
                                    <li>
                                        <a href="page_500.html">500 Error</a>
                                    </li>
                                    <li>
                                        <a href="plain_page.html">Plain Page</a>
                                    </li>
                                    <li>
                                        <a href="login.html">Login Page</a>
                                    </li>
                                    <li>
                                        <a href="pricing_tables.html">Pricing Tables</a>
                                    </li>
                                </ul>
                            </li>
                            <li>
                                <a><i class="fa fa-laptop"></i> Landing Page <span class="label label-success pull-right">Coming Soon</span></a>
                            </li>
                        </ul>
                    </div>
                </div>
                <!-- /sidebar menu -->

            </div>
        </div>
        <!-- top navigation -->
        <div class="top_nav">
            <div class="nav_menu">
                <nav class="" role="navigation">
                    <div class="nav toggle">
                        <a id="menu_toggle"><i class="fa fa-bars"></i></a>
                    </div>
                    <ul class="nav navbar-nav navbar-right">
                        <li class="">
                            <a href="javascript:;" class="user-profile dropdown-toggle" data-toggle="dropdown" aria-expanded="false">
                                <img src="images/img.jpg" alt="">John Doe
                                <span class=" fa fa-angle-down"></span>
                            </a>
                            <ul class="dropdown-menu dropdown-usermenu animated fadeInDown pull-right">
                                <li>
                                    <a href="javascript:;">  Profile</a>
                                </li>
                                <li>
                                    <a href="javascript:;">
                                        <span class="badge bg-red pull-right">50%</span>
                                        <span>Settings</span>
                                    </a>
                                </li>
                                <li>
                                    <a href="javascript:;">Help</a>
                                </li>
                                <li>
                                    <a href="login.html"><i class="fa fa-sign-out pull-right"></i> Log Out</a>
                                </li>
                            </ul>
                        </li>

                    </ul>
                </nav>
            </div>
        </div>
        <!-- /top navigation -->
        <!-- page content -->
        <div class="right_col" role="main">
            <!-- top tiles -->
            @RenderBody()

            <!-- footer content -->
            <footer>
                <div class="copyright-info">
                    <p class="pull-right">
                        Gentelella - Bootstrap Admin Template by <a href="https://colorlib.com">Colorlib</a>
                    </p>
                </div>
                <div class="clearfix"></div>
            </footer>
            <!-- /footer content -->
        </div>
        <!-- /page content -->
    </div>
</div>
<div id="custom_notifications" class="custom-notifications dsp_none">
    <ul class="list-unstyled notifications clearfix" data-tabbed_notifications="notif-group"></ul>
    <div class="clearfix"></div>
    <div id="notif-group" class="tabbed_notifications"></div>
</div>
</code>```

答:
Using  tag in HTML does not create a sticky bottom footer.

Have a look to this Bootstrap example

Title: css not showing correctly asp.net mvc

Body:
hi i'm  working on a admin template. I converted the html codes into mvc structure. Now i am stuck , when i create a page using the layout in the shared folder the footer goes up to the navigation bar. for more understanding check the screenshot

here is my _layoutadmin.cshtml

                     Admin Panel

                        @**@

                        Welcome,

John Doe

General

                                 Home

                                        Dashboard

                                        Dashboard2

                                        Dashboard3

                                 Forms

                                        General Form

                                        Advanced Components

                                        Form Validation

                                        Form Wizard

                                        Form Upload

                                        Form Buttons

                                 UI Elements

                                        General Elements

                                        Media Gallery

                                        Typography

                                        Icons

                                        Glyphicons

                                        Widgets

                                        Invoice

                                        Inbox

                                        Calender

                                 Tables

                                        Tables

                                        Table Dynamic

                                 Data Presentation

                                        Chart JS

                                        Chart JS2

                                        Moris JS

                                        ECharts

                                        Other Charts

Live On

                                 Additional Pages

                                        E-commerce

                                        Projects

                                        Project Detail

                                        Contacts

                                        Profile

                                 Extras

                                        404 Error

                                        500 Error

                                        Plain Page

                                        Login Page

                                        Pricing Tables

                                 Landing Page Coming Soon

                                John Doe

                                      Profile

                                        50%
                                        Settings

                                    Help

                                     Log Out

            @RenderBody()

                        Gentelella - Bootstrap Admin Template by Colorlib

Body:
Using <footer> tag in HTML does not create a sticky bottom footer.

Have a look to this Bootstrap example


问:
Call to a member function query() on null in PHP
I am getting below error when I run my PHP code.

```<code>Call to a member function query() on null
</code>```

Below is the code,

```<code>function fetch_url($url_code) {
    $query = "SELECT * FROM `urls` WHERE `url_code` = ? ";

    $result = $this->db->query($query, array($url_code));
    if ($result) {
        return $result;
    } else {
        return false;
    }
}
</code>```

Please guide me how to remove this error.

答: Yes use this lines of code to get rid of the error Call to a member function query() on null in PHP I used it in my database class and it's working fine !</p>

Body:
I am getting below error when I run my PHP code.

Call to a member function query() on null

Below is the code,

function fetch_url($url_code) {
    $query = "SELECT * FROM `urls` WHERE `url_code` = ? ";

    $result = $this->db->query($query, array($url_code));
    if ($result) {
        return $result;
    } else {
        return false;
    }
}

Please guide me how to remove this error.


问:
WKRefreshBackgroundTask doesn't working
I'm trying to do my watch app running in the background mode. For starting doing this, I copied the example from this apple guide:

https://developer.apple.com/library/content/samplecode/WatchBackgroundRefresh/Listings/WatchBackgroundRrefresh_WatchKit_Extension_MainInterfaceController_swift.html#//apple_ref/doc/uid/TP40017295-WatchBackgroundRrefresh_WatchKit_Extension_MainInterfaceController_swift-DontLinkElementID_10

But it isn't working at all. This is my code:

```<code>import WatchKit
import Foundation

class InterfaceController: WKInterfaceController, WKExtensionDelegate, URLSessionDownloadDelegate {

@IBOutlet var unlink: WKInterfaceLabel!

@IBAction func startActivity() {
    // fire in 20 seconds
    let fireDate = Date(timeIntervalSinceNow: 20.0)
    // optional, any SecureCoding compliant data can be passed here
    let userInfo = ["reason" : "background update"] as NSDictionary

    WKExtension.shared().scheduleBackgroundRefresh(withPreferredDate: fireDate, userInfo: userInfo) { (error) in
        if (error == nil) {
            print("successfully scheduled background task, use the crown to send the app to the background and wait for handle:BackgroundTasks to fire.")
        }
    }
}

let sampleDownloadURL = URL(string: "http://devstreaming.apple.com/videos/wwdc/2015/802mpzd3nzovlygpbg/802/802_designing_for_apple_watch.pdf?dl=1")!

// MARK: WKInterfaceController

override func awake(withContext context: Any?) {
    super.awake(withContext: context)

    // Configure interface objects here.
    WKExtension.shared().delegate = self
    updateDateLabel()
}

let sampleDownloadURL = URL(string: "http://devstreaming.apple.com/videos/wwdc/2015/802mpzd3nzovlygpbg/802/802_designing_for_apple_watch.pdf?dl=1")!

// MARK: WKExtensionDelegate
func handle(_ backgroundTasks: Set<WKRefreshBackgroundTask>) {
    for task : WKRefreshBackgroundTask in backgroundTasks {
        print("received background task: ", task)
        // only handle these while running in the background
        if (WKExtension.shared().applicationState == .background) {
            if task is WKApplicationRefreshBackgroundTask {
                // this task is completed below, our app will then suspend while the download session runs
                print("application task received, start URL session")
                scheduleURLSession()
            }
        }
        else if let urlTask = task as? WKURLSessionRefreshBackgroundTask {
            let backgroundConfigObject = URLSessionConfiguration.background(withIdentifier: urlTask.sessionIdentifier)
            let backgroundSession = URLSession(configuration: backgroundConfigObject, delegate: self, delegateQueue: nil)

            print("Rejoining session ", backgroundSession)
        }
        // make sure to complete all tasks, even ones you don't handle
        task.setTaskCompleted()
    }
}

// MARK: Snapshot and UI updating

func scheduleSnapshot() {
    // fire now, we're ready
    let fireDate = Date()
    WKExtension.shared().scheduleSnapshotRefresh(withPreferredDate: fireDate, userInfo: nil) { error in
        if (error == nil) {
            print("successfully scheduled snapshot.  All background work completed.")
        }
    }
}

func updateDateLabel() {
    let currentDate = Date()
    self.unlink.setHidden(false)
    unlink.setText(dateFormatter.string(from: currentDate))
}

// MARK: URLSession handling

func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL) {
    print("NSURLSession finished to url: ", location)
    updateDateLabel()
    scheduleSnapshot()
}

func scheduleURLSession() {
    let backgroundConfigObject = URLSessionConfiguration.background(withIdentifier: NSUUID().uuidString)
    backgroundConfigObject.sessionSendsLaunchEvents = true
    let backgroundSession = URLSession(configuration: backgroundConfigObject)

    let downloadTask = backgroundSession.downloadTask(with: sampleDownloadURL)
    downloadTask.resume()
}

}
</code>```

It prints successfully scheduled background task, use the crown to send the app to the background and wait for handle:BackgroundTasks to fire, then I send the app to background but never enter on handle method.

Any help?! Thank you!!!

答:
I never got Apple's example to work either. But I did get background refresh working with the following code.  Note that unlike Apple's example you will need to make yourself the delegate on the background session. (Also you don’t really need the “self.” in Swift, I just use it here to indicate the properties/functions).

```<code>var backgroundUrlSession:URLSession?
var pendingBackgroundURLTask:WKURLSessionRefreshBackgroundTask?

func handle(_ backgroundTasks: Set<WKRefreshBackgroundTask>) {

    for task in backgroundTasks {
        if let refreshTask = task as? WKApplicationRefreshBackgroundTask {
            // this task is completed below, our app will then suspend while the download session runs
            print("application task received, start URL session")

            if let request = self.getRequestForRefresh() {
                let backgroundConfig = URLSessionConfiguration.background(withIdentifier: NSUUID().uuidString)
                backgroundConfig.sessionSendsLaunchEvents = true
                backgroundConfig.httpAdditionalHeaders = ["Accept":"application/json"]
                //Be sure to set self as delegate on this urlSession
                let urlSession = URLSession(configuration: backgroundConfig, delegate: self, delegateQueue: nil)
                let downloadTask = urlSession.downloadTask(with: request)

                print("Dispatching data task at \(self.getTimestamp())")
                downloadTask.resume()
            }
            self.scheduleNextBackgroundRefresh(refreshDate: self.getNextPreferredRefreshDate())
            refreshTask.setTaskCompleted()
        }
        else if let urlTask = task as? WKURLSessionRefreshBackgroundTask
        {
            //awakened because background url task has completed
            let backgroundConfigObject = URLSessionConfiguration.background(withIdentifier: urlTask.sessionIdentifier)
            //Be sure to set self as delegate on this urlSession
            self.backgroundUrlSession = URLSession(configuration: backgroundConfigObject, delegate: self, delegateQueue: nil) //set to nil in task:didCompleteWithError: delegate method

            print("Rejoining session ", self.backgroundUrlSession as Any)
            self.pendingBackgroundURLTask = urlTask //Saved for .setTaskComplete() in downloadTask:didFinishDownloadingTo location: (or if error non nil in task:didCompleteWithError:)

        } else {
            //else different task, not handling but must Complete all tasks (snapshot tasks hit this logic)
            task.setTaskCompleted()
        }
    }
}

func getRequestForRefresh() -> URLRequest? {

    guard let url = URL(string: "https://pokeapi.co/api/v2/pokemon") else{
        return nil
    }

    return URLRequest(url: url)
}

// MARK: URLSession handling

func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL) {
    print("NSURLSession finished to url: ", location)
    updateDateLabel()
    scheduleSnapshot()

    self.pendingBackgroundURLTask.setTaskCompleted()
    self.backgroundUrlSession = nil
}

func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) {
    if error != nil {
        self.pendingBackgroundURLTask.setTaskCompleted()
        self.backgroundUrlSession = nil
    }
}
</code>```

Also without prints/breakpoints I was sometimes hitting task:didCompleteWithError Error: like a ms before I hit downloadTask:didFinishDownloadingTo location:.

So I instead set self.pendingBackgroundURLTask completed in downloadTask:didFinishDownloadingTo location:. I only set it completed in task:didCompleteWithError Error: if error != nil.  I've updated my answer to include this logic as well.

Hope this helps you out.  It's working in production for us.

Title: WKRefreshBackgroundTask doesn't working

Body:
I'm trying to do my watch app running in the background mode. For starting doing this, I copied the example from this apple guide:

https://developer.apple.com/library/content/samplecode/WatchBackgroundRefresh/Listings/WatchBackgroundRrefresh_WatchKit_Extension_MainInterfaceController_swift.html#//apple_ref/doc/uid/TP40017295-WatchBackgroundRrefresh_WatchKit_Extension_MainInterfaceController_swift-DontLinkElementID_10

But it isn't working at all. This is my code:

import WatchKit
import Foundation

class InterfaceController: WKInterfaceController, WKExtensionDelegate, URLSessionDownloadDelegate {

@IBOutlet var unlink: WKInterfaceLabel!

@IBAction func startActivity() {
    // fire in 20 seconds
    let fireDate = Date(timeIntervalSinceNow: 20.0)
    // optional, any SecureCoding compliant data can be passed here
    let userInfo = ["reason" : "background update"] as NSDictionary

    WKExtension.shared().scheduleBackgroundRefresh(withPreferredDate: fireDate, userInfo: userInfo) { (error) in
        if (error == nil) {
            print("successfully scheduled background task, use the crown to send the app to the background and wait for handle:BackgroundTasks to fire.")
        }
    }
}

let sampleDownloadURL = URL(string: "http://devstreaming.apple.com/videos/wwdc/2015/802mpzd3nzovlygpbg/802/802_designing_for_apple_watch.pdf?dl=1")!

// MARK: WKInterfaceController

override func awake(withContext context: Any?) {
    super.awake(withContext: context)

    // Configure interface objects here.
    WKExtension.shared().delegate = self
    updateDateLabel()
}

let sampleDownloadURL = URL(string: "http://devstreaming.apple.com/videos/wwdc/2015/802mpzd3nzovlygpbg/802/802_designing_for_apple_watch.pdf?dl=1")!

// MARK: WKExtensionDelegate
func handle(_ backgroundTasks: Set<WKRefreshBackgroundTask>) {
    for task : WKRefreshBackgroundTask in backgroundTasks {
        print("received background task: ", task)
        // only handle these while running in the background
        if (WKExtension.shared().applicationState == .background) {
            if task is WKApplicationRefreshBackgroundTask {
                // this task is completed below, our app will then suspend while the download session runs
                print("application task received, start URL session")
                scheduleURLSession()
            }
        }
        else if let urlTask = task as? WKURLSessionRefreshBackgroundTask {
            let backgroundConfigObject = URLSessionConfiguration.background(withIdentifier: urlTask.sessionIdentifier)
            let backgroundSession = URLSession(configuration: backgroundConfigObject, delegate: self, delegateQueue: nil)

            print("Rejoining session ", backgroundSession)
        }
        // make sure to complete all tasks, even ones you don't handle
        task.setTaskCompleted()
    }
}

// MARK: Snapshot and UI updating

func scheduleSnapshot() {
    // fire now, we're ready
    let fireDate = Date()
    WKExtension.shared().scheduleSnapshotRefresh(withPreferredDate: fireDate, userInfo: nil) { error in
        if (error == nil) {
            print("successfully scheduled snapshot.  All background work completed.")
        }
    }
}

func updateDateLabel() {
    let currentDate = Date()
    self.unlink.setHidden(false)
    unlink.setText(dateFormatter.string(from: currentDate))
}

// MARK: URLSession handling

func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL) {
    print("NSURLSession finished to url: ", location)
    updateDateLabel()
    scheduleSnapshot()
}

func scheduleURLSession() {
    let backgroundConfigObject = URLSessionConfiguration.background(withIdentifier: NSUUID().uuidString)
    backgroundConfigObject.sessionSendsLaunchEvents = true
    let backgroundSession = URLSession(configuration: backgroundConfigObject)

    let downloadTask = backgroundSession.downloadTask(with: sampleDownloadURL)
    downloadTask.resume()
}

}

It prints successfully scheduled background task, use the crown to send the app to the background and wait for handle:BackgroundTasks to fire, then I send the app to background but never enter on handle method.

Any help?! Thank you!!!

Body:
I never got Apple's example to work either. But I did get background refresh working with the following code.  Note that unlike Apple's example you will need to make yourself the delegate on the background session. (Also you don’t really need the “self.” in Swift, I just use it here to indicate the properties/functions).

var backgroundUrlSession:URLSession?
var pendingBackgroundURLTask:WKURLSessionRefreshBackgroundTask?

func handle(_ backgroundTasks: Set<WKRefreshBackgroundTask>) {

    for task in backgroundTasks {
        if let refreshTask = task as? WKApplicationRefreshBackgroundTask {
            // this task is completed below, our app will then suspend while the download session runs
            print("application task received, start URL session")

            if let request = self.getRequestForRefresh() {
                let backgroundConfig = URLSessionConfiguration.background(withIdentifier: NSUUID().uuidString)
                backgroundConfig.sessionSendsLaunchEvents = true
                backgroundConfig.httpAdditionalHeaders = ["Accept":"application/json"]
                //Be sure to set self as delegate on this urlSession
                let urlSession = URLSession(configuration: backgroundConfig, delegate: self, delegateQueue: nil)
                let downloadTask = urlSession.downloadTask(with: request)

                print("Dispatching data task at \(self.getTimestamp())")
                downloadTask.resume()
            }
            self.scheduleNextBackgroundRefresh(refreshDate: self.getNextPreferredRefreshDate())
            refreshTask.setTaskCompleted()
        }
        else if let urlTask = task as? WKURLSessionRefreshBackgroundTask
        {
            //awakened because background url task has completed
            let backgroundConfigObject = URLSessionConfiguration.background(withIdentifier: urlTask.sessionIdentifier)
            //Be sure to set self as delegate on this urlSession
            self.backgroundUrlSession = URLSession(configuration: backgroundConfigObject, delegate: self, delegateQueue: nil) //set to nil in task:didCompleteWithError: delegate method

            print("Rejoining session ", self.backgroundUrlSession as Any)
            self.pendingBackgroundURLTask = urlTask //Saved for .setTaskComplete() in downloadTask:didFinishDownloadingTo location: (or if error non nil in task:didCompleteWithError:)

        } else {
            //else different task, not handling but must Complete all tasks (snapshot tasks hit this logic)
            task.setTaskCompleted()
        }
    }
}

func getRequestForRefresh() -> URLRequest? {

    guard let url = URL(string: "https://pokeapi.co/api/v2/pokemon") else{
        return nil
    }

    return URLRequest(url: url)
}

// MARK: URLSession handling

func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL) {
    print("NSURLSession finished to url: ", location)
    updateDateLabel()
    scheduleSnapshot()

    self.pendingBackgroundURLTask.setTaskCompleted()
    self.backgroundUrlSession = nil
}

func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) {
    if error != nil {
        self.pendingBackgroundURLTask.setTaskCompleted()
        self.backgroundUrlSession = nil
    }
}

Also without prints/breakpoints I was sometimes hitting task:didCompleteWithError Error: like a ms before I hit downloadTask:didFinishDownloadingTo location:.

So I instead set self.pendingBackgroundURLTask completed in downloadTask:didFinishDownloadingTo location:. I only set it completed in task:didCompleteWithError Error: if error != nil.  I've updated my answer to include this logic as well.

Hope this helps you out.  It's working in production for us.


问:
Updating expired administrator password remotely without windows RDP
I have remote Windows with following users:

adm (administrator)

usr (standard user)

I know adm password but it's expired. To update expired password I have to  enter old password, new password and confirmation on adm's login screen but I can't do it remotely. I can connect to usr with Teamviewer (RDP isn't enabled).

I can't do anything that requires elevated privileges because of expired adm password.
Is there any way of updating expired administrator password remotely without windows RDP?

答:
Thanks to @HarryJohnston.

With NetUserChangePassword you can change password without elevated privileges.

For java developers:
https://github.com/java-native-access/jna

```<code>Netapi32.INSTANCE.NetUserChangePassword(Kernel32Util.getComputerName(), "user-login", "old-password", "new-password");
</code>```

Body:
Thanks to @HarryJohnston.

With NetUserChangePassword you can change password without elevated privileges.

For java developers:
https://github.com/java-native-access/jna

Netapi32.INSTANCE.NetUserChangePassword(Kernel32Util.getComputerName(), "user-login", "old-password", "new-password");


问:
BadMethodCallException - Call to undefined method Illuminate\Database\Query\Builder::getAuthIdentifierName()
I have installed Laravel 5.4 and used the php artisan make:auth. Everything was all fine, I set up my database and migrate everything. I also tested the login and registration and it was working perfectly.

After that I managed to set up my other controllers and models. After I tested one of the controller (Basically, I store an image in the database and then display it). And it worked fine I stored the image and then displayed it.

However, since then I receive an error when I try to login or register.

When I try to access http://localhost:8000/login or http://localhost:8000/register I receive the following error:

Call to undefined method Illuminate\Database\Query\Builder::getAuthIdentifierName()

For this one I am not entirely sure which part of my code I should share but this is my Modal User.php:

```<code>namespace App;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;

use App\User;

class User extends Authenticatable
{
    use Notifiable;

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */

    protected $table = 'users';

    protected $fillable = [
        'name', 'email', 'password',
    ];

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password', 'remember_token',
    ];
}
</code>```

Thank you in advance guys, if you need other parts of my code I will be happy to share.

答:
first of all first run php artisan migrate make sure you have a tables in your database

User.php // user model add a primary key to get rid of this error

```<code> protected $primaryKey = 'yourPrimaryKey';
</code>```

Body:
I have installed Laravel 5.4 and used the php artisan make:auth. Everything was all fine, I set up my database and migrate everything. I also tested the login and registration and it was working perfectly.

After that I managed to set up my other controllers and models. After I tested one of the controller (Basically, I store an image in the database and then display it). And it worked fine I stored the image and then displayed it.

However, since then I receive an error when I try to login or register.

When I try to access http://localhost:8000/login or http://localhost:8000/register I receive the following error:

Call to undefined method Illuminate\Database\Query\Builder::getAuthIdentifierName()

For this one I am not entirely sure which part of my code I should share but this is my Modal User.php:

namespace App;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;

use App\User;

class User extends Authenticatable
{
    use Notifiable;

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */

    protected $table = 'users';

    protected $fillable = [
        'name', 'email', 'password',
    ];

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password', 'remember_token',
    ];
}

Thank you in advance guys, if you need other parts of my code I will be happy to share.

Body:
first of all first run php artisan migrate make sure you have a tables in your database

User.php // user model add a primary key to get rid of this error

 protected $primaryKey = 'yourPrimaryKey';


问:
c# cscore how to instantly play loopback capture recorded bytes
Yo guys, its me again with my noob questions. so this time I've used cscore to record windows sounds then send the recorded bytes to another pc by sockets and let them play there.

I just could not figure out how to play the gotten bytes under DataAvailable callback...

I've tried to write the bytes gotten to a file and play that file that worked but sound is not playing correctly like there's some unexpected sounds being heard with it too.

so here's my code:

```<code>WasapiCapture capture = new WasapiLoopbackCapture();
capture.Initialize();
capture.DataAvailable += (s, e) =>
{
    WaveWriter w = new WaveWriter("file.mp3", capture.WaveFormat);
    w.Write(e.Data, e.Offset, e.ByteCount);
    w.Dispose();
    MemoryStream stream = new MemoryStream(File.ReadAllBytes("file.mp3"));
    SoundPlayer player = new SoundPlayer(stream);
    player.Play();
    stream.Dispose();
};
capture.Start();
</code>```

any help would be highly appreciated ;-;.
if you wanna hear how sound comes out by that way I would record you the result.

NOTE: if I just record sounds to a file and open later it just works perfectly but if I write and play instantly it unexpected sounds being heard.....

答:
Use the SoundInSource as an adapater.

```<code>var capture = new WasapiCapture(...)
capture.Initialize(); //initialize always first!!!!

var soundInSource = new SoundInSource(capture)
    { FillWithZeros = true }; //set FillWithZeros to true, to prevent WasapiOut from stopping for the case WasapiCapture does not serve any data

var soundOut = new WasapiOut();
soundOut.Initialize(soundInSource);
soundOut.Play();
</code>```

Body:
Yo guys, its me again with my noob questions. so this time I've used cscore to record windows sounds then send the recorded bytes to another pc by sockets and let them play there.

I just could not figure out how to play the gotten bytes under DataAvailable callback...

I've tried to write the bytes gotten to a file and play that file that worked but sound is not playing correctly like there's some unexpected sounds being heard with it too.

so here's my code:

WasapiCapture capture = new WasapiLoopbackCapture();
capture.Initialize();
capture.DataAvailable += (s, e) =>
{
    WaveWriter w = new WaveWriter("file.mp3", capture.WaveFormat);
    w.Write(e.Data, e.Offset, e.ByteCount);
    w.Dispose();
    MemoryStream stream = new MemoryStream(File.ReadAllBytes("file.mp3"));
    SoundPlayer player = new SoundPlayer(stream);
    player.Play();
    stream.Dispose();
};
capture.Start();

any help would be highly appreciated ;-;.
if you wanna hear how sound comes out by that way I would record you the result.

NOTE: if I just record sounds to a file and open later it just works perfectly but if I write and play instantly it unexpected sounds being heard.....

Body:
Use the SoundInSource as an adapater.

var capture = new WasapiCapture(...)
capture.Initialize(); //initialize always first!!!!

var soundInSource = new SoundInSource(capture)
    { FillWithZeros = true }; //set FillWithZeros to true, to prevent WasapiOut from stopping for the case WasapiCapture does not serve any data

var soundOut = new WasapiOut();
soundOut.Initialize(soundInSource);
soundOut.Play();


问:
Atom auto tslint detection
Recently I opened Angular 2 project in my freshly installed atom editor(with https://atom.io/packages/atom-typescript and linter).
I was surprised with the fact that atom automatically detected tslint.json file in project root directory and apply those rules to highlight errors. </p>

<p>Can someone explain to me, how did this happen? </p>

答:
The linter for TypeScript is linter-tslint, which requires tslint as a dependency.

tslint looks for tslint.json files to load rules.

Title: Atom auto tslint detection

Body:
Recently I opened Angular 2 project in my freshly installed atom editor(with https://atom.io/packages/atom-typescript and linter).
I was surprised with the fact that atom automatically detected tslint.json file in project root directory and apply those rules to highlight errors.

Can someone explain to me, how did this happen?


问:
Import all modules from a directory at once [NODE]
```<code>MyApp
├── main.js
└── modules
    ├── a.js
    ├── b.js
    ├── c.js
    ├── d.js
    ├── e.js
</code>```

In my NodeJS app, how can I import all my custom modules (a,b,c,d,e) in my main.js file at once?

I have long list of modules and I dont want to import them all separately.

答:
```<code>const path = require('path');
const fs = require('fs');

const modulesPath = './modules';
const modulesList = fs.readdirSync(modulesPath);
modulesList.forEach(modulePath => require(path.resolve(modulesPath, modulePath)));
</code>```

Body:
MyApp
├── main.js
└── modules
    ├── a.js
    ├── b.js
    ├── c.js
    ├── d.js
    ├── e.js

In my NodeJS app, how can I import all my custom modules (a,b,c,d,e) in my main.js file at once?

I have long list of modules and I dont want to import them all separately.


问:
How can one use regex to capture the text occurring between lines beginning with a single semicolon?
I want to capture the text between lines which begin with single semicolons:

sample input:

```<code>s = '''
;

the color blue

;

the color green

;

the color red

;
'''
</code>```

this is the desired output:

```<code>['the color blue', 'the color green', 'the color red']
</code>```

this attempted solution doesn't work:

```<code>import re
pat = r'^;(.*)^;'
r = re.findall(pat, s, re.S|re.M)
print(r)
</code>```

this is the wrong output:

```<code>['\n\nthe color blue\n\n;\n\nthe color green\n\n;\n\nthe color red\n\n']
</code>```

答:
Non-regex solution,I split on ; and remove null strings

```<code>s = '''
    ;

    the color blue

;

the color green

;

the color red

;
'''

f = s.split(';')

x = [a.strip('\n') for a in f]

print(x) #prints ['', 'the color blue', 'the color green', 'the color red', '']

a = [elem for elem in x if len(elem)]

print(a) #prints ['the color blue', 'the color green', 'the color red']
</code>```

Body:
I want to capture the text between lines which begin with single semicolons:

sample input:

s = '''
;

the color blue

;

the color green

;

the color red

;
'''

this is the desired output:

['the color blue', 'the color green', 'the color red']

this attempted solution doesn't work:

import re
pat = r'^;(.*)^;'
r = re.findall(pat, s, re.S|re.M)
print(r)

this is the wrong output:

['\n\nthe color blue\n\n;\n\nthe color green\n\n;\n\nthe color red\n\n']

Body:
Non-regex solution,I split on ; and remove null strings

s = '''
    ;

    the color blue

;

the color green

;

the color red

;
'''

f = s.split(';')

x = [a.strip('\n') for a in f]

print(x) #prints ['', 'the color blue', 'the color green', 'the color red', '']

a = [elem for elem in x if len(elem)]

print(a) #prints ['the color blue', 'the color green', 'the color red']