问:
Node can't find module but it exists in node_modules?
I've been playing with node for the past day and I've run into an issue I would really appreciate help on.

I created a new project and am trying to use a module I installed using npm, the module exists in the node_modules directory as expected and the command ran without error but node is unable to find it and throws an error (I have tried multiple packages with the same result). Below explains what I have done:

I created a new project using npm init and completed the guided package.json creation. I then created a javascript file containing this line of code.

const k = require('korbit-node');

and installed the module using npm install korbit-node then tried to run it locally using node index.js (what i called the js file) and was given this error.

```<code>$ node index.js

module.js:472
    throw err;
    ^

Error: Cannot find module 'korbit-node'
    at Function.Module._resolveFilename (module.js:470:15)
    at Function.Module._load (module.js:418:25)
    at Module.require (module.js:498:17)
    at require (internal/module.js:20:19)
    at Object.<anonymous> (/Users/gabe/Desktop/js_sandbox/index.js:1:73)
    at Module._compile (module.js:571:32)
    at Object.Module._extensions..js (module.js:580:10)
    at Module.load (module.js:488:32)
    at tryModuleLoad (module.js:447:12)
    at Function.Module._load (module.js:439:3)
</code>```

To me this seems to be a fairly straight-forward error message telling me that the package isn't installed. However my project structure looks like this:

```<code>├── index.js
├── node_modules
│   ├── debug
│   │   ├── CHANGELOG.md
│   │   ├── LICENSE
│   │   ├── Makefile
│   │   ├── README.md
│   │   ├── component.json
│   │   ├── karma.conf.js
│   │   ├── node.js
│   │   ├── package.json
│   │   └── src
│   │       ├── browser.js
│   │       ├── debug.js
│   │       ├── index.js
│   │       └── node.js
│   ├── iconv-lite
│   │   ├── Changelog.md
│   │   ├── LICENSE
│   │   ├── README.md
│   │   ├── encodings
│   │   │   ├── dbcs-codec.js
│   │   │   ├── dbcs-data.js
│   │   │   ├── index.js
│   │   │   ├── internal.js
│   │   │   ├── sbcs-codec.js
│   │   │   ├── sbcs-data-generated.js
│   │   │   ├── sbcs-data.js
│   │   │   ├── tables
│   │   │   │   ├── big5-added.json
│   │   │   │   ├── cp936.json
│   │   │   │   ├── cp949.json
│   │   │   │   ├── cp950.json
│   │   │   │   ├── eucjp.json
│   │   │   │   ├── gb18030-ranges.json
│   │   │   │   ├── gbk-added.json
│   │   │   │   └── shiftjis.json
│   │   │   ├── utf16.js
│   │   │   └── utf7.js
│   │   ├── lib
│   │   │   ├── bom-handling.js
│   │   │   ├── extend-node.js
│   │   │   ├── index.d.ts
│   │   │   ├── index.js
│   │   │   └── streams.js
│   │   └── package.json
│   ├── korbit-node
│   │   ├── README.md
│   │   ├── korbit.js
│   │   └── package.json
│   ├── lodash
│   │   ├── README.md
│   │   ├── dist
│   │   │   ├── lodash.compat.js
│   │   │   ├── lodash.compat.min.js
│   │   │   ├── lodash.js
│   │   │   ├── lodash.legacy.js
│   │   │   ├── lodash.legacy.min.js
│   │   │   ├── lodash.min.js
│   │   │   ├── lodash.mobile.js
│   │   │   ├── lodash.mobile.min.js
│   │   │   ├── lodash.underscore.js
│   │   │   └── lodash.underscore.min.js
│   │   ├── lodash.js
│   │   └── package.json
│   ├── ms
│   │   ├── index.js
│   │   ├── license.md
│   │   ├── package.json
│   │   └── readme.md
│   └── needle
│       ├── README.md
│       ├── bin
│       │   └── needle
│       ├── examples
│       │   ├── deflated-stream.js
│       │   ├── digest-auth.js
│       │   ├── download-to-file.js
│       │   ├── multipart-stream.js
│       │   ├── parsed-stream.js
│       │   ├── parsed-stream2.js
│       │   ├── stream-events.js
│       │   ├── stream-to-file.js
│       │   └── upload-image.js
│       ├── lib
│       │   ├── auth.js
│       │   ├── cookies.js
│       │   ├── decoder.js
│       │   ├── multipart.js
│       │   ├── needle.js
│       │   ├── parsers.js
│       │   └── querystring.js
│       ├── package.json
│       └── test
│           ├── basic_auth_spec.js
│           ├── compression_spec.js
│           ├── cookies_spec.js
│           ├── decoder_spec.js
│           ├── errors_spec.js
│           ├── helpers.js
│           ├── keys
│           │   ├── ssl.cert
│           │   └── ssl.key
│           ├── parsing_spec.js
│           ├── proxy_spec.js
│           ├── querystring_spec.js
│           ├── redirect_spec.js
│           ├── stream_spec.js
│           ├── url_spec.js
│           └── utils
│               ├── formidable.js
│               ├── proxy.js
│               └── test.js
└── package.json
</code>```

and I can clearly see the module in the node_modules file so I am unsure why it isn't being found.

I've seen these questions Node.js NODE_PATH environment variable
about making sure the NODE_PATH is set properly but I found that even after I explicitly pointed the path to the file it still did not work. I also of course found questions about the package not being installed but that is not the case in this situation.

Could someone please tell me why this isn't being found by node or point me to some resources about this issue/how node handles packages? I'm sure its a simple issue but everything I have found online/in the documentation has been unhelpful so far.

答:
The main file of your module must be index.js.
(node_modules/korbit-node/index.js). Here it is nonexistent.

replace node_modules/korbit-node/korbit-node.js with node_modules/korbit-node/index.js

Body:
I've been playing with node for the past day and I've run into an issue I would really appreciate help on.

I created a new project and am trying to use a module I installed using npm, the module exists in the node_modules directory as expected and the command ran without error but node is unable to find it and throws an error (I have tried multiple packages with the same result). Below explains what I have done:

I created a new project using npm init and completed the guided package.json creation. I then created a javascript file containing this line of code.

const k = require('korbit-node');

and installed the module using npm install korbit-node then tried to run it locally using node index.js (what i called the js file) and was given this error.

$ node index.js

module.js:472
    throw err;
    ^

Error: Cannot find module 'korbit-node'
    at Function.Module._resolveFilename (module.js:470:15)
    at Function.Module._load (module.js:418:25)
    at Module.require (module.js:498:17)
    at require (internal/module.js:20:19)
    at Object.<anonymous> (/Users/gabe/Desktop/js_sandbox/index.js:1:73)
    at Module._compile (module.js:571:32)
    at Object.Module._extensions..js (module.js:580:10)
    at Module.load (module.js:488:32)
    at tryModuleLoad (module.js:447:12)
    at Function.Module._load (module.js:439:3)

To me this seems to be a fairly straight-forward error message telling me that the package isn't installed. However my project structure looks like this:

├── index.js
├── node_modules
│   ├── debug
│   │   ├── CHANGELOG.md
│   │   ├── LICENSE
│   │   ├── Makefile
│   │   ├── README.md
│   │   ├── component.json
│   │   ├── karma.conf.js
│   │   ├── node.js
│   │   ├── package.json
│   │   └── src
│   │       ├── browser.js
│   │       ├── debug.js
│   │       ├── index.js
│   │       └── node.js
│   ├── iconv-lite
│   │   ├── Changelog.md
│   │   ├── LICENSE
│   │   ├── README.md
│   │   ├── encodings
│   │   │   ├── dbcs-codec.js
│   │   │   ├── dbcs-data.js
│   │   │   ├── index.js
│   │   │   ├── internal.js
│   │   │   ├── sbcs-codec.js
│   │   │   ├── sbcs-data-generated.js
│   │   │   ├── sbcs-data.js
│   │   │   ├── tables
│   │   │   │   ├── big5-added.json
│   │   │   │   ├── cp936.json
│   │   │   │   ├── cp949.json
│   │   │   │   ├── cp950.json
│   │   │   │   ├── eucjp.json
│   │   │   │   ├── gb18030-ranges.json
│   │   │   │   ├── gbk-added.json
│   │   │   │   └── shiftjis.json
│   │   │   ├── utf16.js
│   │   │   └── utf7.js
│   │   ├── lib
│   │   │   ├── bom-handling.js
│   │   │   ├── extend-node.js
│   │   │   ├── index.d.ts
│   │   │   ├── index.js
│   │   │   └── streams.js
│   │   └── package.json
│   ├── korbit-node
│   │   ├── README.md
│   │   ├── korbit.js
│   │   └── package.json
│   ├── lodash
│   │   ├── README.md
│   │   ├── dist
│   │   │   ├── lodash.compat.js
│   │   │   ├── lodash.compat.min.js
│   │   │   ├── lodash.js
│   │   │   ├── lodash.legacy.js
│   │   │   ├── lodash.legacy.min.js
│   │   │   ├── lodash.min.js
│   │   │   ├── lodash.mobile.js
│   │   │   ├── lodash.mobile.min.js
│   │   │   ├── lodash.underscore.js
│   │   │   └── lodash.underscore.min.js
│   │   ├── lodash.js
│   │   └── package.json
│   ├── ms
│   │   ├── index.js
│   │   ├── license.md
│   │   ├── package.json
│   │   └── readme.md
│   └── needle
│       ├── README.md
│       ├── bin
│       │   └── needle
│       ├── examples
│       │   ├── deflated-stream.js
│       │   ├── digest-auth.js
│       │   ├── download-to-file.js
│       │   ├── multipart-stream.js
│       │   ├── parsed-stream.js
│       │   ├── parsed-stream2.js
│       │   ├── stream-events.js
│       │   ├── stream-to-file.js
│       │   └── upload-image.js
│       ├── lib
│       │   ├── auth.js
│       │   ├── cookies.js
│       │   ├── decoder.js
│       │   ├── multipart.js
│       │   ├── needle.js
│       │   ├── parsers.js
│       │   └── querystring.js
│       ├── package.json
│       └── test
│           ├── basic_auth_spec.js
│           ├── compression_spec.js
│           ├── cookies_spec.js
│           ├── decoder_spec.js
│           ├── errors_spec.js
│           ├── helpers.js
│           ├── keys
│           │   ├── ssl.cert
│           │   └── ssl.key
│           ├── parsing_spec.js
│           ├── proxy_spec.js
│           ├── querystring_spec.js
│           ├── redirect_spec.js
│           ├── stream_spec.js
│           ├── url_spec.js
│           └── utils
│               ├── formidable.js
│               ├── proxy.js
│               └── test.js
└── package.json

and I can clearly see the module in the node_modules file so I am unsure why it isn't being found.

I've seen these questions Node.js NODE_PATH environment variable
about making sure the NODE_PATH is set properly but I found that even after I explicitly pointed the path to the file it still did not work. I also of course found questions about the package not being installed but that is not the case in this situation.

Could someone please tell me why this isn't being found by node or point me to some resources about this issue/how node handles packages? I'm sure its a simple issue but everything I have found online/in the documentation has been unhelpful so far.


来源: stackexchange

问:
Set up path on prompt on pycharm terminal windon
I just upgrade pycharm into 2016.3.1. Before upgrade, I do not have problem to see the current directory path under the prompt on terminal window. After upgrade into pycharm 2016
3.1. All directory path on prompt on terminal window seems like messed up with 133;C;133;D;01337;RemoteHost=hawkins@pc_name.home1337;CurrentDir=/Users/hawkins/path133;MAC:path hawkins$ 133;B for some reason. Anyone have expereience on how to resolve this?

```<code>MAC:path$
133;C;133;D;01337;RemoteHost=hawkins@pc_name.home1337;CurrentDir=/Users/hawkins/path133;MAC:path hawkins$ 133;B
133;C;133;D;01337;RemoteHost=hawkins@pc_name.home1337;CurrentDir=/Users/hawkins/path133;MAC:path hawkins$ 133;B
133;C;133;D;01337;RemoteHost=hawkins@pc_name.home1337;CurrentDir=/Users/hawkins/path133;MAC:path hawkins$ 133;B
</code>```

答:
Found this question while trying to resolve similar issue for 'Geany' on mac osx. I had an install of iterm2 on my machine and was getting garbage in front of the terminal prompt.

similar solution as KPLauritzen offered also works for 'Geany' terminal as such.

Hope this helps someone:

Create shell script in home directory using desired PS1 & CLICOLOR settings:

~/geany_terminal.sh

export PROMT_COMMAND=
export PS1='[\e[1;32m][\u@\h \W] \D{%F %T}\n\$[\e[0m]'
export CLICOLOR=1
export LSCOLORS=gxBxhxDxfxhxhxhxhxcxcx
bash -i

Then I went to 'Edit -> Preferences --> Terminal' and set my 'Shell' to:
/bin/bash /Users/myusername/geany_terminal.sh

Upon reloading Geany, the Terminal now displays with PS1 and CLICOLOR settings exactly as I have set in my .bash_profile without garbage in front.

ContentLicense: CC BY-SA 3.0

Body:
I just upgrade pycharm into 2016.3.1. Before upgrade, I do not have problem to see the current directory path under the prompt on terminal window. After upgrade into pycharm 2016
3.1. All directory path on prompt on terminal window seems like messed up with 133;C;133;D;01337;RemoteHost=hawkins@pc_name.home1337;CurrentDir=/Users/hawkins/path133;MAC:path hawkins$ 133;B for some reason. Anyone have expereience on how to resolve this?

MAC:path$
133;C;133;D;01337;RemoteHost=hawkins@pc_name.home1337;CurrentDir=/Users/hawkins/path133;MAC:path hawkins$ 133;B
133;C;133;D;01337;RemoteHost=hawkins@pc_name.home1337;CurrentDir=/Users/hawkins/path133;MAC:path hawkins$ 133;B
133;C;133;D;01337;RemoteHost=hawkins@pc_name.home1337;CurrentDir=/Users/hawkins/path133;MAC:path hawkins$ 133;B


问:
User Impersonation with Service Account using Application Default Credentials
I'm trying to use a service account with domain-wide delegation (DwD) on an App Engine deployment with Go.

I've followed the steps for using Google Application Default Credentials to use a service account with App Engine.

I got the code running locally on my dev machine but I'm stuck at retrieving the actual data from my domain.

I'm using the Admin SDK. Under the section Delegate domain-wide authority to your service account, it says that my "service account needs to impersonate one of those users to access the Admin SDK Directory API".

I've looked through the documentation for Go on using service account and user impersonation, AND I've also pored through the source code. Nowhere does it indicate where I can enter the user's email address/identity to impersonate.

Here is the error that I got:

```<code>googleapi: Error 404: Domain not found., notFound
</code>```

The source code does show some clue but I faced other obstacles when trying to use something other than the Application Default Credentials.

Does anyone have any idea? Thanks in advance.

答:
It seems that for the Admin SDK I need to ask for the user (the administrator) permissions to access the Directory API. This is quite different from the other APIs where I simply just set the user email address to access the specified user's data.

It's understandable I guess since the Admin SDK is a far more powerful API affecting the domain and not just the individual user.

Body:
I'm trying to use a service account with domain-wide delegation (DwD) on an App Engine deployment with Go.

I've followed the steps for using Google Application Default Credentials to use a service account with App Engine.

I got the code running locally on my dev machine but I'm stuck at retrieving the actual data from my domain.

I'm using the Admin SDK. Under the section Delegate domain-wide authority to your service account, it says that my "service account needs to impersonate one of those users to access the Admin SDK Directory API".

I've looked through the documentation for Go on using service account and user impersonation, AND I've also pored through the source code. Nowhere does it indicate where I can enter the user's email address/identity to impersonate.

Here is the error that I got:

googleapi: Error 404: Domain not found., notFound

The source code does show some clue but I faced other obstacles when trying to use something other than the Application Default Credentials.

Does anyone have any idea? Thanks in advance.


问:
How to convert UIColor to HEX and display in NSLog
I have checked several links on how to convert UIColor codes to HEX however I am not sure on how to  call to the method to display them in NSLog. I haven't got the reputation to comment so posting as a question is my last resort. I want it to display when I run my app in the log.

Second, where do I input the RGB color number ( R = 30, G = 171, B = 13)? I see that all examples use Array [0], [1], [2] which normally refers to index position, so where do I add the color values?

I have this code:

```<code>- (NSString *) hexFromUIColor:(UIColor *)color {

    if (CGColorGetNumberOfComponents(color.CGColor) < 4) {
        const CGFloat *components = CGColorGetComponents(color.CGColor);
        color = [UIColor colorWithRed:components[30] green:components[141] blue:components[13] alpha:components[1]];
    }
    if (CGColorSpaceGetModel(CGColorGetColorSpace(color.CGColor)) != kCGColorSpaceModelRGB) {
        return [NSString stringWithFormat:@"#FFFFFF"];
    }
    return [NSString stringWithFormat:@"#%02X%02X%02X", (int)((CGColorGetComponents(color.CGColor))[0]*255.0), (int)((CGColorGetComponents(color.CGColor))[1]*255.0), (int)((CGColorGetComponents(color.CGColor))[2]*255.0)];

}
</code>```

Links I have checked:

hex color from uicolor

How to convert HEX RGB color codes to UIColor?

I have tried to call the method in viewDidLoad however it wont work without UIColor. I am sure it's something simple.

Thanks to anyone who answers.

What is the code I use in my viewDidLoad to call to this method in order to display in NSLog?

答:
The swift 2 answer converted to swift 3</p>

```<code>var hexString: String {
    let components = self.cgColor.components

    let red = Float((components?[0])!)
    let green = Float((components?[1])!)
    let blue = Float((components?[2])!)
    return String(format: "#%02lX%02lX%02lX", lroundf(red * 255), lroundf(green * 255), lroundf(blue * 255))
}
</code>```

Body:
I have checked several links on how to convert UIColor codes to HEX however I am not sure on how to  call to the method to display them in NSLog. I haven't got the reputation to comment so posting as a question is my last resort. I want it to display when I run my app in the log.

Second, where do I input the RGB color number ( R = 30, G = 171, B = 13)? I see that all examples use Array [0], [1], [2] which normally refers to index position, so where do I add the color values?

I have this code:

- (NSString *) hexFromUIColor:(UIColor *)color {

    if (CGColorGetNumberOfComponents(color.CGColor) < 4) {
        const CGFloat *components = CGColorGetComponents(color.CGColor);
        color = [UIColor colorWithRed:components[30] green:components[141] blue:components[13] alpha:components[1]];
    }
    if (CGColorSpaceGetModel(CGColorGetColorSpace(color.CGColor)) != kCGColorSpaceModelRGB) {
        return [NSString stringWithFormat:@"#FFFFFF"];
    }
    return [NSString stringWithFormat:@"#%02X%02X%02X", (int)((CGColorGetComponents(color.CGColor))[0]*255.0), (int)((CGColorGetComponents(color.CGColor))[1]*255.0), (int)((CGColorGetComponents(color.CGColor))[2]*255.0)];

}

Links I have checked:

hex color from uicolor

How to convert HEX RGB color codes to UIColor?

I have tried to call the method in viewDidLoad however it wont work without UIColor. I am sure it's something simple.

Thanks to anyone who answers.

What is the code I use in my viewDidLoad to call to this method in order to display in NSLog?

Body:
The swift 2 answer converted to swift 3

var hexString: String {
    let components = self.cgColor.components

    let red = Float((components?[0])!)
    let green = Float((components?[1])!)
    let blue = Float((components?[2])!)
    return String(format: "#%02lX%02lX%02lX", lroundf(red * 255), lroundf(green * 255), lroundf(blue * 255))
}


问:
Cannot read property 'style' of undefined React Native
I removed some of unused dependencies from package.json file and then I did rm -rf node_modules and then npm install.

If I now build my project in Xcode I do not get any errors, but If I try yo run it in a simulator I get red screen as follows:

In the simulator I get :

```<code>TypeError: Cannot read property 'Symbol(Symbol.iterator)' of null
    at launchEditor (/Users/boris/Projects/autralis-seller/AutralisSeller/node_modules/react-native/local-cli/server/util/launchEditor.js:153:29)
    at Object.handle (/Users/boris/Projects/autralis-seller/AutralisSeller/node_modules/react-native/local-cli/server/middleware/openStackFrameInEditorMiddleware.js:17:7)
    at next (/Users/boris/Projects/autralis-seller/AutralisSeller/node_modules/connect/lib/proto.js:174:15)
    at Object.handle (/Users/boris/Projects/autralis-seller/AutralisSeller/node_modules/react-native/local-cli/server/middleware/getDevToolsMiddleware.js:74:7)
    at next (/Users/boris/Projects/autralis-seller/AutralisSeller/node_modules/connect/lib/proto.js:174:15)
    at Object.handle (/Users/boris/Projects/autralis-seller/AutralisSeller/node_modules/react-native/local-cli/server/middleware/getDevToolsMiddleware.js:74:7)
    at next (/Users/boris/Projects/autralis-seller/AutralisSeller/node_modules/connect/lib/proto.js:174:15)
    at Object.compression [as handle] (/Users/boris/Projects/autralis-seller/AutralisSeller/node_modules/compression/index.js:205:5)
    at next (/Users/boris/Projects/autralis-seller/AutralisSeller/node_modules/connect/lib/proto.js:174:15)
    at IncomingMessage.<anonymous> (/Users/boris/Projects/autralis-seller/AutralisSeller/node_modules/react-native/local-cli/server/middleware/loadRawBodyMiddleware.js:20:5)
</code>```

I do not have idea what's going on. Any idea how to solve it?

EDIT

Scene.js is from react-native router-flux navigation:

```<code>/**
 * Copyright (c) 2015-present, Pavel Aksonov
 * All rights reserved.
 *
 * This source code is licensed under the BSD-style license found in the
 * LICENSE file in the root directory of this source tree.
 *
 */
import React, { PropTypes } from 'react';
import { ViewPropTypes, Text } from 'react-native';

export default class extends React.Component {

  // @todo - should all props be documented/specified here?

  static propTypes = {
    tabBarStyle: ViewPropTypes.style,
    tabBarSelectedItemStyle: ViewPropTypes.style,
    tabBarIconContainerStyle: ViewPropTypes.style,
    tabBarShadowStyle: ViewPropTypes.style,
    tabSceneStyle: ViewPropTypes.style,
    tabStyle: ViewPropTypes.style,
    tabTitleStyle: Text.propTypes.style,
    tabSelectedTitleStyle: Text.propTypes.style,
    tabTitle: PropTypes.string,
  };

  render() {
    return null;
  }
}
</code>```

答:
So I had this issue as well and your post helped me solve it. React Native Router Flux was updated roughly 2 weeks ago, where View.propTypes was deprecated for the new ViewPropTypes. Here's the commit for it. https://github.com/aksonov/react-native-router-flux/commit/36dc20418987850677c52905beda59310a0500c3

The issue is that when this update was committed to the live branch the library version was not incremented from 3.37.0 so if you have done an npm install after that commit was implemented, your package would update with the new change, but you would most likely be none the wiser to what they had done (unless you read the commit updates for every package you use in a project)

I found that reverting react-native-router-flux to an earlier version fixed this issue. I used 3.36.0

```<code>npm install react-native-router-flux@3.36.0 --save
</code>```

Body:
I removed some of unused dependencies from package.json file and then I did rm -rf node_modules and then npm install.

If I now build my project in Xcode I do not get any errors, but If I try yo run it in a simulator I get red screen as follows:

In the simulator I get :

TypeError: Cannot read property 'Symbol(Symbol.iterator)' of null
    at launchEditor (/Users/boris/Projects/autralis-seller/AutralisSeller/node_modules/react-native/local-cli/server/util/launchEditor.js:153:29)
    at Object.handle (/Users/boris/Projects/autralis-seller/AutralisSeller/node_modules/react-native/local-cli/server/middleware/openStackFrameInEditorMiddleware.js:17:7)
    at next (/Users/boris/Projects/autralis-seller/AutralisSeller/node_modules/connect/lib/proto.js:174:15)
    at Object.handle (/Users/boris/Projects/autralis-seller/AutralisSeller/node_modules/react-native/local-cli/server/middleware/getDevToolsMiddleware.js:74:7)
    at next (/Users/boris/Projects/autralis-seller/AutralisSeller/node_modules/connect/lib/proto.js:174:15)
    at Object.handle (/Users/boris/Projects/autralis-seller/AutralisSeller/node_modules/react-native/local-cli/server/middleware/getDevToolsMiddleware.js:74:7)
    at next (/Users/boris/Projects/autralis-seller/AutralisSeller/node_modules/connect/lib/proto.js:174:15)
    at Object.compression [as handle] (/Users/boris/Projects/autralis-seller/AutralisSeller/node_modules/compression/index.js:205:5)
    at next (/Users/boris/Projects/autralis-seller/AutralisSeller/node_modules/connect/lib/proto.js:174:15)
    at IncomingMessage.<anonymous> (/Users/boris/Projects/autralis-seller/AutralisSeller/node_modules/react-native/local-cli/server/middleware/loadRawBodyMiddleware.js:20:5)

I do not have idea what's going on. Any idea how to solve it?

EDIT

Scene.js is from react-native router-flux navigation:

/**
 * Copyright (c) 2015-present, Pavel Aksonov
 * All rights reserved.
 *
 * This source code is licensed under the BSD-style license found in the
 * LICENSE file in the root directory of this source tree.
 *
 */
import React, { PropTypes } from 'react';
import { ViewPropTypes, Text } from 'react-native';

export default class extends React.Component {

  // @todo - should all props be documented/specified here?

  static propTypes = {
    tabBarStyle: ViewPropTypes.style,
    tabBarSelectedItemStyle: ViewPropTypes.style,
    tabBarIconContainerStyle: ViewPropTypes.style,
    tabBarShadowStyle: ViewPropTypes.style,
    tabSceneStyle: ViewPropTypes.style,
    tabStyle: ViewPropTypes.style,
    tabTitleStyle: Text.propTypes.style,
    tabSelectedTitleStyle: Text.propTypes.style,
    tabTitle: PropTypes.string,
  };

  render() {
    return null;
  }
}

Body:
So I had this issue as well and your post helped me solve it. React Native Router Flux was updated roughly 2 weeks ago, where View.propTypes was deprecated for the new ViewPropTypes. Here's the commit for it. https://github.com/aksonov/react-native-router-flux/commit/36dc20418987850677c52905beda59310a0500c3

The issue is that when this update was committed to the live branch the library version was not incremented from 3.37.0 so if you have done an npm install after that commit was implemented, your package would update with the new change, but you would most likely be none the wiser to what they had done (unless you read the commit updates for every package you use in a project)

I found that reverting react-native-router-flux to an earlier version fixed this issue. I used 3.36.0

npm install react-native-router-flux@3.36.0 --save

ContentLicense: CC BY-SA 4.0


问:
Execution failed for task ':app:processDebugResources'. failed to execute aapt
In Android Studio I have this error when I update Android SDK Tools to version 25:

I tried to modify SDK version in gradle build to 21 to execute my app but I have this error. Really I don't why this happens.
This is my build.gradle file:

Thanks a lot for your help!

答: Update your build tools, and the error will be fixed automatically.</p>


问:
Convert a collection of objects with a string property to an enumeration of those strings using LINQ
I have an IEnumerable object where Foo has a string property called 'Name'.  Is there an easy LINQ statement that will let me return a collection of strings from that enumeration for those names?

e.g.

```<code>IEnumerable<Foo> (which contains...)
    Foo.Name = First
    Foo.Name = Second
    Foo.Name = Third
</code>```

I want to return an IEnumerable that contains 'First', 'Second' and 'Third'

Howdoyadoozat?

答:
If your initial IEnumerable is called list, this will do it:</p>

```<code>list.Select(f => f.Name);
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I have an IEnumerable object where Foo has a string property called 'Name'.  Is there an easy LINQ statement that will let me return a collection of strings from that enumeration for those names?

e.g.

IEnumerable<Foo> (which contains...)
    Foo.Name = First
    Foo.Name = Second
    Foo.Name = Third

I want to return an IEnumerable that contains 'First', 'Second' and 'Third'

Howdoyadoozat?

Body:
If your initial IEnumerable is called list, this will do it:

list.Select(f => f.Name);


问:
Service Request fact and SR fact Actions - how to slice and drill thru
I have a FactServiceRequest (FctSR) table and a FactSRActions (FctSRA) table, the FctSR table is linked using Regular dimensions to

create date

completed date

dimcontact

The FctSRA has regular dimensions to

Action date

Action code

Each of the fact tables works well in isolation, however I am struggling to combine the results into one set.

So, I am looking to get:

FctSR.ID,FctSR.Details, FctSRA.Actions,FctSRA.ActionCode,FctSRA.ActionDate for each FctSR.ID

The tables have a degeneratekey in common if that helps.

Can anyone suggest how to put these on the SSAS DimensionUsage tab please?

I am using VS 2015 on a SQL Server 2016.

Thank you.

edit:

Hope this makes sense.

答: Fact Service Request Action measure group currently joins to the Fact Service Request dimension via a many-to-many relationship. I believe you need to add a new column (if it doesn't already exist) to FctSRA which is the foreign key to FctSR. Then change that relationship in the Dimension Usage tab to a regular relationship. Frankly I'm not sure how the other many-to-many relationship is working properly now with no common dimensions. </p>


问:
`docker run` on a remote host
is it possible (using the docker command or the docker-py API directly) to start a container from a remote host?

Lets assume I have two machines that have different architectures:
- A is an x86 machine
- B is an ARM machine

I would like to run a container on the B machine using my A machine. At first, I thought it was possible using this command:

```<code>[A]$> DOCKER_HOST=$MACHINE_B_IP:$MACHIN_B_PORT docker run hello-from-B
</code>```

But this command actually pulls the image hello-from-B and tries to run it on the machine A which ends up on some exec format error cause obviously you can't run images that are specific to ARM to an x86 machine.

Communication between machine A and B is working well. I can run commands like images or ps and it gives me the expected results:

```<code>[A]$> DOCKER_HOST=$MACHINE_B_IP:$MACHIN_B_PORT docker images
REPOSITORY                TAG                 IMAGE ID            CREATED             SIZE
hello-from-B              <none>              fd5059044831        13 hours ago        1.26GB
</code>```

I've heard about docker-machine and haven't tried it yet, but from my understanding, this won't solve my problem.

Is there any way to achieve that using docker directly. A workaround might be to using ssh to connect to the remote host and use the docker client directly from the remote host, but I'd like to avoid this solution as much as possible.

Thanks in advance,

TL;DR;

How can DOCKER_HOST=... docker run something runs something on the DOCKER_HOST rather than running it on my local machine.

答:
if your targeted machine B could be created on one of these platform then I guess docker-machine would serve your needs. you would create your machine using docker-machine create --driver <..driver setup..> MACHINE_B then you activate it using eval $(docker-machine env MACHINE_B).  docker-machine env MACHINE_B  will print out some export statements:

```<code>export DOCKER_TLS_VERIFY="1"
export DOCKER_HOST="tcp://...."
export DOCKER_CERT_PATH="/..."
export DOCKER_MACHINE_NAME="MACHINE_B"
</code>```

once your machine is active, you can use the docker command as you would locally to act remotely on MACHINE_B.

Title: `docker run` on a remote host

Body:
is it possible (using the docker command or the docker-py API directly) to start a container from a remote host?

Lets assume I have two machines that have different architectures:
- A is an x86 machine
- B is an ARM machine

I would like to run a container on the B machine using my A machine. At first, I thought it was possible using this command:

[A]$> DOCKER_HOST=$MACHINE_B_IP:$MACHIN_B_PORT docker run hello-from-B

But this command actually pulls the image hello-from-B and tries to run it on the machine A which ends up on some exec format error cause obviously you can't run images that are specific to ARM to an x86 machine.

Communication between machine A and B is working well. I can run commands like images or ps and it gives me the expected results:

[A]$> DOCKER_HOST=$MACHINE_B_IP:$MACHIN_B_PORT docker images
REPOSITORY                TAG                 IMAGE ID            CREATED             SIZE
hello-from-B              <none>              fd5059044831        13 hours ago        1.26GB

I've heard about docker-machine and haven't tried it yet, but from my understanding, this won't solve my problem.

Is there any way to achieve that using docker directly. A workaround might be to using ssh to connect to the remote host and use the docker client directly from the remote host, but I'd like to avoid this solution as much as possible.

Thanks in advance,

TL;DR;

How can DOCKER_HOST=... docker run something runs something on the DOCKER_HOST rather than running it on my local machine.

Body:
if your targeted machine B could be created on one of these platform then I guess docker-machine would serve your needs. you would create your machine using docker-machine create --driver <..driver setup..> MACHINE_B then you activate it using eval $(docker-machine env MACHINE_B).  docker-machine env MACHINE_B  will print out some export statements:

export DOCKER_TLS_VERIFY="1"
export DOCKER_HOST="tcp://...."
export DOCKER_CERT_PATH="/..."
export DOCKER_MACHINE_NAME="MACHINE_B"

once your machine is active, you can use the docker command as you would locally to act remotely on MACHINE_B.


问:
How to call unbound method on object of subclass in Python
I have the following classes in Python 2.7:

```<code>class Parent():
    def some_method(self):
        do_something()

class Child(Parent):
    def some_method(self):
        do_something_different()
</code>```

Suppose I have a bunch of objects that I want to run some_method on. I execute the following lines (the first two are for the sake of this example):

```<code>c = Child()
m = Parent.some_method

m(c)  # do_something() gets called
</code>```

Is there some construct such that in the last line do_something_different() gets called instead, without using any information about Child (as I potentially have many such classes inheriting from Parent)?

答:
Rather than using an unbound method object, use operator.methodcaller:

```<code>import operator

m = operator.methodcaller('some_method')

m(c)
</code>```

This will look up the object's actual some_method method and call it. It's more expensive, but the extra time is all spent doing stuff you need.

Body:
I have the following classes in Python 2.7:

class Parent():
    def some_method(self):
        do_something()

class Child(Parent):
    def some_method(self):
        do_something_different()

Suppose I have a bunch of objects that I want to run some_method on. I execute the following lines (the first two are for the sake of this example):

c = Child()
m = Parent.some_method

m(c)  # do_something() gets called

Is there some construct such that in the last line do_something_different() gets called instead, without using any information about Child (as I potentially have many such classes inheriting from Parent)?

Body:
Rather than using an unbound method object, use operator.methodcaller:

import operator

m = operator.methodcaller('some_method')

m(c)

This will look up the object's actual some_method method and call it. It's more expensive, but the extra time is all spent doing stuff you need.


问:
Having issues in moving from one activity to another using a button in Andriod Studio
I'm trying to create a sound board app with multiple actives with their own buttons and sounds. I cant seem to get the hang of moving from one activity to another using a button. The first activity moves just fine to the second, but the second doesn't move to the third and suddenly closes the app. Any help is greatly appreciated.
Here is my code for the first activity

```<code>import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.content.Intent;
import android.view.View;
import android.widget.Button;

public class MainActivity extends AppCompatActivity {
Button btnMove;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    btnMove=(Button)findViewById(R.id.btnMove);
    btnMove.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            Intent a = new Intent(MainActivity.this,Main2Activity.class);
            startActivity(a);
            finish();

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

Here is my code for the second activity

```<code>import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.content.Intent;
import android.view.View;
import android.widget.Button;

public class Main2Activity extends AppCompatActivity {
Button btnMove2;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main2);
    btnMove2=(Button)findViewById(R.id.btnMove2);
    btnMove2.setOnClickListener(new View.OnClickListener() {

          @Override
          public void onClick(View v) {
            Intent b = newIntent(Main2Activity.this,Main3Activity.class);
            startActivity(b);
            finish();

    }
});

  }

 }
</code>```

答:
What you have shown appears to work fine (albeit that using finish() is not what would normally be done). However you haven't shown the 3rd activity and that is likely where the issue is. It is also highly likely, assuming that exactly the same happened when finish() was removed from both MainActivity and Main2Activity that the App is crashing. It would be nearly impossible to determine why without the log and the code for the 3rd activity (including the layout XML, which may or may not be relevant).

One issue that would result in something similar to what you describe, is if you haven't added the 3rd activity to the manifest. This would result in an unexpected error and the App crashing with something along the lines of:

```<code>06-09 08:35:01.628 23844-23844/mjt.so44446139 E/AndroidRuntime: FATAL EXCEPTION: main
    Process: mjt.so44446139, PID: 23844
    android.content.ActivityNotFoundException: Unable to find explicit activity class {mjt.so44446139/mjt.so44446139.Activity3}; have you declared this activity in your AndroidManifest.xml?
        at android.app.Instrumentation.checkStartActivityResult(Instrumentation.java:1777)
        at android.app.Instrumentation.execStartActivity(Instrumentation.java:1501)
        at android.app.Activity.startActivityForResult(Activity.java:3745)
        at android.support.v4.app.BaseFragmentActivityJB.startActivityForResult(BaseFragmentActivityJB.java:50)
        at android.support.v4.app.FragmentActivity.startActivityForResult(FragmentActivity.java:79)
        at android.app.Activity.startActivityForResult(Activity.java:3706)
        at android.support.v4.app.FragmentActivity.startActivityForResult(FragmentActivity.java:859)
        at android.app.Activity.startActivity(Activity.java:4016)
        at android.app.Activity.startActivity(Activity.java:3984)
        at mjt.so44446139.Activity2$1.onClick(Activity2.java:23)
        at android.view.View.performClick(View.java:4780)
        at android.view.View$PerformClick.run(View.java:19866)
        at android.os.Handler.handleCallback(Handler.java:739)
        at android.os.Handler.dispatchMessage(Handler.java:95)
        at android.os.Looper.loop(Looper.java:135)
        at android.app.ActivityThread.main(ActivityThread.java:5254)
        at java.lang.reflect.Method.invoke(Native Method)
        at java.lang.reflect.Method.invoke(Method.java:372)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
</code>```

The above indicating an ActivityNotFoundException. If this is the case then you need to add Main3Activity to the manifest (you would have done this for the 2nd Activity).

Regarding finish()

If you have finish() coded after you start an activity via startActivity, then that activity will not be returned to as it has been finished. It will return to instead to that activities parent, if there is one.

Thus:

If finish() is in the first activity then that activity will not be returned to (clicking the devices back button from 2nd activity will finish the App).

If finish() is ONLY in the 2nd activity then it will not be returned to from the 3rd activity. However, returning from the 3rd (e.g. clicking the device's back button) will return to the 1st activity.

If finish() is in both the first and 2nd activity then neither will be returned to, thus clicking the device's back button will finish the App.

The normal use of finish() is to code it when you are done with an activity (not moving to another). Hence in the 3rd activity there is a line that resets the button's text to done. If finish() is un-commented then this will act to finish the activity and return to the 2nd (assuming it hasn't been finished).

Example Code

The following code may assist you in understanding or perhaps even fixing your issue (it should resemble your code quite closely):

It consists of 3 activities all with a button and currently with finish() commented out. They all use the same layout, which includes a Button and a TextView. The Textview is set to reflect the activity's name. As it is, it should reflect what you appear to want. That is clicking the button from the MainActivity takes you to the second. Clicking the button on the 2nd Activity takes you to the third (clicking on the button in the third does nothing).

MainActivity

```<code>public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        TextView msg = (TextView) this.findViewById(R.id.message);
        msg.setText(this.getClass().getSimpleName());
        Button nextbutton = (Button) this.findViewById(R.id.nextbutton);

        nextbutton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MainActivity.this,Activity2.class);
                startActivity(intent);
                //finish();
            }
        });
    }
}
</code>```

Activity2

```<code>public class Activity2 extends AppCompatActivity {
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Button nextbutton = (Button) this.findViewById(R.id.nextbutton);
        TextView msg = (TextView) this.findViewById(R.id.message);
        msg.setText(this.getClass().getSimpleName());

        nextbutton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(Activity2.this,Activity3.class);
                startActivity(intent);
                //finish();
            }
        });
    }
}
</code>```

Activity3

```<code>public class Activity3 extends AppCompatActivity {
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Button nextbutton = (Button) this.findViewById(R.id.nextbutton);
        nextbutton.setText("Done");
        TextView msg = (TextView) this.findViewById(R.id.message);
        msg.setText(this.getClass().getSimpleName());

        nextbutton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //finish();
            }
        });
    }
}
</code>```

The layout used for all 3 is (noting that tools:context="mjt.so44446139.MainActivity" would have to be changed, this is the default Blank Activity layout with the button added and with an id given to the TextView):

```<code><?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="mjt.so44446139.MainActivity">

    <TextView
        android:id="@+id/message"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello World!"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />
    <Button
        android:id="@+id/nextbutton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Next"/>

</android.support.constraint.ConstraintLayout>
</code>```

The manifest is (main thing is that both Activity2 and Activity3 have been added):

```<code><?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="mjt.so44446139">

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity android:name=".Activity2">

        </activity>
        <activity android:name=".Activity3">

        </activity>
    </application>

</manifest>
</code>```

Body:
I'm trying to create a sound board app with multiple actives with their own buttons and sounds. I cant seem to get the hang of moving from one activity to another using a button. The first activity moves just fine to the second, but the second doesn't move to the third and suddenly closes the app. Any help is greatly appreciated.
Here is my code for the first activity

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.content.Intent;
import android.view.View;
import android.widget.Button;

public class MainActivity extends AppCompatActivity {
Button btnMove;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    btnMove=(Button)findViewById(R.id.btnMove);
    btnMove.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            Intent a = new Intent(MainActivity.this,Main2Activity.class);
            startActivity(a);
            finish();

        }
    });
 }
}

Here is my code for the second activity

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.content.Intent;
import android.view.View;
import android.widget.Button;

public class Main2Activity extends AppCompatActivity {
Button btnMove2;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main2);
    btnMove2=(Button)findViewById(R.id.btnMove2);
    btnMove2.setOnClickListener(new View.OnClickListener() {

          @Override
          public void onClick(View v) {
            Intent b = newIntent(Main2Activity.this,Main3Activity.class);
            startActivity(b);
            finish();

    }
});

  }

 }

Body:
What you have shown appears to work fine (albeit that using finish() is not what would normally be done). However you haven't shown the 3rd activity and that is likely where the issue is. It is also highly likely, assuming that exactly the same happened when finish() was removed from both MainActivity and Main2Activity that the App is crashing. It would be nearly impossible to determine why without the log and the code for the 3rd activity (including the layout XML, which may or may not be relevant).

One issue that would result in something similar to what you describe, is if you haven't added the 3rd activity to the manifest. This would result in an unexpected error and the App crashing with something along the lines of:

06-09 08:35:01.628 23844-23844/mjt.so44446139 E/AndroidRuntime: FATAL EXCEPTION: main
    Process: mjt.so44446139, PID: 23844
    android.content.ActivityNotFoundException: Unable to find explicit activity class {mjt.so44446139/mjt.so44446139.Activity3}; have you declared this activity in your AndroidManifest.xml?
        at android.app.Instrumentation.checkStartActivityResult(Instrumentation.java:1777)
        at android.app.Instrumentation.execStartActivity(Instrumentation.java:1501)
        at android.app.Activity.startActivityForResult(Activity.java:3745)
        at android.support.v4.app.BaseFragmentActivityJB.startActivityForResult(BaseFragmentActivityJB.java:50)
        at android.support.v4.app.FragmentActivity.startActivityForResult(FragmentActivity.java:79)
        at android.app.Activity.startActivityForResult(Activity.java:3706)
        at android.support.v4.app.FragmentActivity.startActivityForResult(FragmentActivity.java:859)
        at android.app.Activity.startActivity(Activity.java:4016)
        at android.app.Activity.startActivity(Activity.java:3984)
        at mjt.so44446139.Activity2$1.onClick(Activity2.java:23)
        at android.view.View.performClick(View.java:4780)
        at android.view.View$PerformClick.run(View.java:19866)
        at android.os.Handler.handleCallback(Handler.java:739)
        at android.os.Handler.dispatchMessage(Handler.java:95)
        at android.os.Looper.loop(Looper.java:135)
        at android.app.ActivityThread.main(ActivityThread.java:5254)
        at java.lang.reflect.Method.invoke(Native Method)
        at java.lang.reflect.Method.invoke(Method.java:372)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)

The above indicating an ActivityNotFoundException. If this is the case then you need to add Main3Activity to the manifest (you would have done this for the 2nd Activity).

Regarding finish()

If you have finish() coded after you start an activity via startActivity, then that activity will not be returned to as it has been finished. It will return to instead to that activities parent, if there is one.

Thus:

If finish() is in the first activity then that activity will not be returned to (clicking the devices back button from 2nd activity will finish the App).

If finish() is ONLY in the 2nd activity then it will not be returned to from the 3rd activity. However, returning from the 3rd (e.g. clicking the device's back button) will return to the 1st activity.

If finish() is in both the first and 2nd activity then neither will be returned to, thus clicking the device's back button will finish the App.

The normal use of finish() is to code it when you are done with an activity (not moving to another). Hence in the 3rd activity there is a line that resets the button's text to done. If finish() is un-commented then this will act to finish the activity and return to the 2nd (assuming it hasn't been finished).

Example Code

The following code may assist you in understanding or perhaps even fixing your issue (it should resemble your code quite closely):

It consists of 3 activities all with a button and currently with finish() commented out. They all use the same layout, which includes a Button and a TextView. The Textview is set to reflect the activity's name. As it is, it should reflect what you appear to want. That is clicking the button from the MainActivity takes you to the second. Clicking the button on the 2nd Activity takes you to the third (clicking on the button in the third does nothing).

MainActivity

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        TextView msg = (TextView) this.findViewById(R.id.message);
        msg.setText(this.getClass().getSimpleName());
        Button nextbutton = (Button) this.findViewById(R.id.nextbutton);

        nextbutton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MainActivity.this,Activity2.class);
                startActivity(intent);
                //finish();
            }
        });
    }
}

Activity2

public class Activity2 extends AppCompatActivity {
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Button nextbutton = (Button) this.findViewById(R.id.nextbutton);
        TextView msg = (TextView) this.findViewById(R.id.message);
        msg.setText(this.getClass().getSimpleName());

        nextbutton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(Activity2.this,Activity3.class);
                startActivity(intent);
                //finish();
            }
        });
    }
}

Activity3

public class Activity3 extends AppCompatActivity {
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Button nextbutton = (Button) this.findViewById(R.id.nextbutton);
        nextbutton.setText("Done");
        TextView msg = (TextView) this.findViewById(R.id.message);
        msg.setText(this.getClass().getSimpleName());

        nextbutton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //finish();
            }
        });
    }
}

The layout used for all 3 is (noting that tools:context="mjt.so44446139.MainActivity" would have to be changed, this is the default Blank Activity layout with the button added and with an id given to the TextView):

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="mjt.so44446139.MainActivity">

    <TextView
        android:id="@+id/message"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello World!"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />
    <Button
        android:id="@+id/nextbutton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Next"/>

</android.support.constraint.ConstraintLayout>

The manifest is (main thing is that both Activity2 and Activity3 have been added):

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="mjt.so44446139">

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity android:name=".Activity2">

        </activity>
        <activity android:name=".Activity3">

        </activity>
    </application>

</manifest>


问:
Subcategory inside category in the Codeigniter framework
I want to show subcategory inside the main category. My table looks like this. but when i print_r($cat_id) it returns only the last id of the category. How can I fix this? Here is my controller:

```<code>$data['categories'] = $this->courses_model->get_all_categories_for_courses();

            foreach($data['categories'] as $ct){

                        $cat_id = $ct['id'];
                }

            $data['subcategories'] = $this->courses_model->get_all_subcategories_for_courses($cat_id);

            $this->load->view('templates/header');
            $this->load->view('courses/courses-grid-fullwidth', $data);
            $this->load->view('templates/footer');
        }
</code>```

and here is my model:

```<code>public function get_all_categories_for_courses() {
        $query = $this->db->get_where('categories', array('parent_id' => NULL));
        return $query->result_array();
    }

    function get_all_subcategories_for_courses($cat_id) {
        $query = $this->db->get_where('categories', array('parent_id' => $cat_id));
        return $query->result_array();
    }
</code>```

and here is my view page:

```<code><?php foreach($categories as $cat): ?>
          <div class="col-md-3 col-sm-6 incat">

             <h4>
               <a href="#" class="catname"><i class="fa <?= $cat['icon']; ?>" aria-hidden="true"></i>
               <?= $cat['name_rus']; ?></a>
             </h4>

            <ul>
              <?php foreach($subcategories as $subcat): ?>
              <li><a href="#"><?= $subcat['name_rus']; ?></a></li>
              <?php endforeach; ?>
            </ul>
          </div>
        <?php endforeach; ?>
</code>```

Thanks in advance!

答:
Or you can do this</p>

```<code><?php foreach($categories as $cat): ?>
          <div class="col-md-3 col-sm-6 incat">

             <h4>
               <a href="<?= site_url('/courses/category/'.$cat['category_slug']); ?>" class="catname"><i class="fa <?= $cat['icon']; ?>" aria-hidden="true"></i>
               <?= $cat['name_rus']; ?></a>
             </h4>

            <ul>
            <?php
            $query = $this->db->get_where('categories', array('parent_id' => $cat['id']));
            ?>

              <?php foreach($query->result() as $subcat): ?>
              <li><a href="<?= site_url('/courses/category/'.$subcat->category_slug); ?>"><?= $subcat->name_rus; ?></a></li>
              <?php endforeach; ?>
            </ul>
          </div>
        <?php endforeach; ?>
</code>```

Body:
I want to show subcategory inside the main category. My table looks like this. but when i print_r($cat_id) it returns only the last id of the category. How can I fix this? Here is my controller:

$data['categories'] = $this->courses_model->get_all_categories_for_courses();

            foreach($data['categories'] as $ct){

                        $cat_id = $ct['id'];
                }

            $data['subcategories'] = $this->courses_model->get_all_subcategories_for_courses($cat_id);

            $this->load->view('templates/header');
            $this->load->view('courses/courses-grid-fullwidth', $data);
            $this->load->view('templates/footer');
        }

and here is my model:

public function get_all_categories_for_courses() {
        $query = $this->db->get_where('categories', array('parent_id' => NULL));
        return $query->result_array();
    }

    function get_all_subcategories_for_courses($cat_id) {
        $query = $this->db->get_where('categories', array('parent_id' => $cat_id));
        return $query->result_array();
    }

and here is my view page:

<?php foreach($categories as $cat): ?>

               <i class="fa <?= $cat['icon']; ?>" aria-hidden="true">
               <?= $cat['name_rus']; ?>

              <?php foreach($subcategories as $subcat): ?>

<?= $subcat['name_rus']; ?>

              <?php endforeach; ?>

        <?php endforeach; ?>

Thanks in advance!

Body:
Or you can do this

<?php foreach($categories as $cat): ?>
          <div class="col-md-3 col-sm-6 incat">

             <h4>
               <a href="<?= site_url('/courses/category/'.$cat['category_slug']); ?>" class="catname"><i class="fa <?= $cat['icon']; ?>" aria-hidden="true"></i>
               <?= $cat['name_rus']; ?></a>
             </h4>

            <ul>
            <?php
            $query = $this->db->get_where('categories', array('parent_id' => $cat['id']));
            ?>

              <?php foreach($query->result() as $subcat): ?>
              <li><a href="<?= site_url('/courses/category/'.$subcat->category_slug); ?>"><?= $subcat->name_rus; ?></a></li>
              <?php endforeach; ?>
            </ul>
          </div>
        <?php endforeach; ?>


问:
Watch the object and compare in angularjs to trigger css class change if the value is changed
Im using AngularJS 1.5x

I have a Web Form to submit Car information  1)model, 2)make to Backend(Api: SaveCarDetails).to save this form information in the Backend DB.

On success, I have to make a API call(GetCarsInfo) to get the array list of cars information(so far saved in the BE).

I need to display car information Cards showing the make  & model and with EDIT button so that user can update exactly that particular car information and we use (SaveCarDetails same API as used for adding new details).

On the succesfull update, I need to again make to call to (GetBanks) to get the updated list of bank account information.

Now I need to show Tickmark Icon ONLY on the Car info card that has been updated or newly added.

What is the best way to do this? (show the icon only on the card that got updated or newly added).

How to find out exactly which card is updated by comparing or watching an Object? there is no unique identifier that is being passed for any updates to the response object.

I tried to do an $watch on the object but I couldn't get it to work.

Here is the code: http://plnkr.co/edit/RztTjy?p=preview

// Code goes here

angular.module('app', [])
 .controller('MyCtrl', function($scope) {
    var vm = this;
    vm.carobj = [{
         'make': 'acura',
             'model': "TL",
             'name':'joe'
            },
            {
              'make': "bmw",
             'model': '5series',
             'name':'doe'

        }];

console.log(vm.carobj);
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>/* Styles go here */

.card{
  border: 10px solid #cccccc;
  width: 200px;
  height:160px;
  margin:20px;
  position:relative;

}

.tickWhenUpdated{
  float:right;
  position:absolute;
  right:0;
  bottom:0;

}

.editbtn{
  width:100px;
}</code>```

<!DOCTYPE html>

    <link data-require="font-awesome@4.3.0" data-semver="4.3.0" rel="stylesheet" href="//maxcdn.bootstrapcdn.com/font-awesome/4.3.0/css/font-awesome.min.css" />
    <link data-require="bootstrap@4.0.5" data-semver="4.0.5" rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" />

    <link rel="stylesheet" href="style.css" />

Hello Plunker!

Car Info Box

        Account num:{{car.make}}

        Routung num: {{car.model}}

        <input value="edit" class="btn btn-primary editbtn" type="button" />

```

答:
First of all, instead of dynamically updating the class using ng-class or something, you could just set a variable on the car objects called updated that is truthy when the car was updated. Then place ng-show="car.updated" on the  tag.

Regarding how to set that updated variable on the object, you can either try to manipulate it directly when you click the edit button. Just pass the element to a function which will modify the updated field. Something like;

```<code>Html:
<div ng-repeat="car in cars">
  <input type="button" ng-click"update(cars, car.id)">
</div>

Js:

$scope.update = function(cars, id) {
  cars = cars.map(function(car) {
    if (car.id == id) {
      car.updated = true
    } else {
      car.updated = false
    }
  })
}
</code>```

If you absolutely don't have an ID, the only thing I can think of is to put something that increments on the object (unix timestamp, incrementor). Something like

```<code>Js:
$scope.itr = 0;
$scope.update = function(car) {
 $scope.itr++
  car.itr = $scope.itr
}
</code>```

Then have an ngChange on the array that calls a function and sets car.updated to false on all objects except the one with the largest itr value, which it sets to true.

This is a hardcore hack, and I would really try to just have some sort of unique ID.

Body:
Im using AngularJS 1.5x

I have a Web Form to submit Car information  1)model, 2)make to Backend(Api: SaveCarDetails).to save this form information in the Backend DB.

On success, I have to make a API call(GetCarsInfo) to get the array list of cars information(so far saved in the BE).

I need to display car information Cards showing the make  & model and with EDIT button so that user can update exactly that particular car information and we use (SaveCarDetails same API as used for adding new details).

On the succesfull update, I need to again make to call to (GetBanks) to get the updated list of bank account information.

Now I need to show Tickmark Icon ONLY on the Car info card that has been updated or newly added.

What is the best way to do this? (show the icon only on the card that got updated or newly added).

How to find out exactly which card is updated by comparing or watching an Object? there is no unique identifier that is being passed for any updates to the response object.

I tried to do an $watch on the object but I couldn't get it to work.

Here is the code: http://plnkr.co/edit/RztTjy?p=preview

// Code goes here

angular.module('app', [])
 .controller('MyCtrl', function($scope) {
    var vm = this;
    vm.carobj = [{
         'make': 'acura',
             'model': "TL",
             'name':'joe'
            },
            {
              'make': "bmw",
             'model': '5series',
             'name':'doe'

        }];

console.log(vm.carobj);
});

/* Styles go here */

.card{
  border: 10px solid #cccccc;
  width: 200px;
  height:160px;
  margin:20px;
  position:relative;

}

.tickWhenUpdated{
  float:right;
  position:absolute;
  right:0;
  bottom:0;

}

.editbtn{
  width:100px;
}

<!DOCTYPE html>

    <link data-require="font-awesome@4.3.0" data-semver="4.3.0" rel="stylesheet" href="//maxcdn.bootstrapcdn.com/font-awesome/4.3.0/css/font-awesome.min.css" />
    <link data-require="bootstrap@4.0.5" data-semver="4.0.5" rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" />

    <link rel="stylesheet" href="style.css" />

Hello Plunker!

Car Info Box

        Account num:{{car.make}}

        Routung num: {{car.model}}

        <input value="edit" class="btn btn-primary editbtn" type="button" />

Body:
First of all, instead of dynamically updating the class using ng-class or something, you could just set a variable on the car objects called updated that is truthy when the car was updated. Then place ng-show="car.updated" on the  tag.

Regarding how to set that updated variable on the object, you can either try to manipulate it directly when you click the edit button. Just pass the element to a function which will modify the updated field. Something like;

Html:
<div ng-repeat="car in cars">
  <input type="button" ng-click"update(cars, car.id)">
</div>

Js:

$scope.update = function(cars, id) {
  cars = cars.map(function(car) {
    if (car.id == id) {
      car.updated = true
    } else {
      car.updated = false
    }
  })
}

If you absolutely don't have an ID, the only thing I can think of is to put something that increments on the object (unix timestamp, incrementor). Something like

Js:
$scope.itr = 0;
$scope.update = function(car) {
 $scope.itr++
  car.itr = $scope.itr
}

Then have an ngChange on the array that calls a function and sets car.updated to false on all objects except the one with the largest itr value, which it sets to true.

This is a hardcore hack, and I would really try to just have some sort of unique ID.


问:
Converting a working SQL NOT IN
I have some SQL to tell me the superheroes who don't ever wield a sword.

Creating the table

First, here is the (MySQL) script to create and populate the table.

```<code>CREATE TABLE IF NOT EXISTS `mydb`.`weaponry` (
  `hero` VARCHAR(20) NULL,
  `weapon` VARCHAR(20) NULL)
ENGINE = InnoDB

insert into weaponry (hero, weapon) values ('Wonder Woman', 'Lasso of truth');
insert into weaponry (hero, weapon) values ('Wonder Woman', 'Sword');
insert into weaponry (hero, weapon) values ('Wonder Woman', 'Shield');
insert into weaponry (hero, weapon) values ('Spider Man', 'Web');
insert into weaponry (hero, weapon) values ('Gamora', 'Sword');
insert into weaponry (hero, weapon) values ('Gamora', 'Daggar');
insert into weaponry (hero, weapon) values ('Batman', 'Batarang');
insert into weaponry (hero, weapon) values ('Batman', 'Batgrapple');
insert into weaponry (hero, weapon) values ('Batman', 'Tranquilizer gun');
</code>```

Working code using a NOT IN and a subselect

```<code>select distinct hero from weaponry
  where hero not in
  (select hero from weaponry where weapon = 'Sword')
</code>```

This correctly returns Spider Man and Batman, who don't wield a sword.

Alternative 1: Using NOT EXISTS

I would like to implement the same query using NOT EXISTS.
I looked at https://stackoverflow.com/a/5231731/509840.
I tried this:

```<code>select distinct hero from weaponry
  where not exists
  (select * from weaponry where weapon = 'Sword')
</code>```

Unfortunately, this returns no rows.

Alternative 2: Using LEFT JOIN

I also took a look at this answer: https://stackoverflow.com/a/17413996/509840 .
I was curious to try replacing the NOT IN with a LEFT JOIN.

```<code>  select * from weaponry a
    left join weaponry b on a.hero=b.hero and a.weapon=b.weapon
    where a.weapon <> 'Sword'
</code>```

But this just returns all non-sword heroes (including Wonder Woman and Gamora), since all wield weapons other than swords.

Would you please help me rewrite the NOT IN query with either the NOT EXISTS or the LEFT JOIN?

EDIT: Left Join and the correlated subquery

@JeffUK suggested in his comments that one could understand the correlated subquery better by removing the WHERE clause. Here's a small modification to the select with the where removed.

```<code>select distinct a.hero, weaponryInner.hero from weaponry a
    left join
        (Select * from weaponry b where weapon = 'Sword') as weaponryInner
    on a.hero=weaponryInner.hero
</code>```

The results are two columns of heroes, some of which are NULL.

```<code>-------------------------------
Hero          |  Hero
-------------------------------
Wonder Woman  |  Wonder Woman
Gamora        |  Gamora
Spider Man    |  <null>
Batman        |  <null>
-------------------------------
</code>```

So adding the final where weaponryInner.Weapon is null will return just Spider Man and Batman.

答:
```<code>SELECT h.hero
  FROM weaponry h
    LEFT JOIN weaponry w
      ON    w.hero = h.hero
        AND w.weapon = 'Sword'
  WHERE w.weapon is null
  GROUP BY h.hero
</code>```

OR

```<code>SELECT distinct h.hero
  FROM weaponry h
  WHERE not exists( SELECT 1
                      FROM weaponry w
                      WHERE w.hero = h.hero
                        AND w.weapon = 'Sword'
                  )
</code>```

Title: Converting a working SQL NOT IN

Body:
I have some SQL to tell me the superheroes who don't ever wield a sword.

Creating the table

First, here is the (MySQL) script to create and populate the table.

CREATE TABLE IF NOT EXISTS `mydb`.`weaponry` (
  `hero` VARCHAR(20) NULL,
  `weapon` VARCHAR(20) NULL)
ENGINE = InnoDB

insert into weaponry (hero, weapon) values ('Wonder Woman', 'Lasso of truth');
insert into weaponry (hero, weapon) values ('Wonder Woman', 'Sword');
insert into weaponry (hero, weapon) values ('Wonder Woman', 'Shield');
insert into weaponry (hero, weapon) values ('Spider Man', 'Web');
insert into weaponry (hero, weapon) values ('Gamora', 'Sword');
insert into weaponry (hero, weapon) values ('Gamora', 'Daggar');
insert into weaponry (hero, weapon) values ('Batman', 'Batarang');
insert into weaponry (hero, weapon) values ('Batman', 'Batgrapple');
insert into weaponry (hero, weapon) values ('Batman', 'Tranquilizer gun');

Working code using a NOT IN and a subselect

select distinct hero from weaponry
  where hero not in
  (select hero from weaponry where weapon = 'Sword')

This correctly returns Spider Man and Batman, who don't wield a sword.

Alternative 1: Using NOT EXISTS

I would like to implement the same query using NOT EXISTS.
I looked at https://stackoverflow.com/a/5231731/509840.
I tried this:

select distinct hero from weaponry
  where not exists
  (select * from weaponry where weapon = 'Sword')

Unfortunately, this returns no rows.

Alternative 2: Using LEFT JOIN

I also took a look at this answer: https://stackoverflow.com/a/17413996/509840 .
I was curious to try replacing the NOT IN with a LEFT JOIN.

  select * from weaponry a
    left join weaponry b on a.hero=b.hero and a.weapon=b.weapon
    where a.weapon <> 'Sword'

But this just returns all non-sword heroes (including Wonder Woman and Gamora), since all wield weapons other than swords.

Would you please help me rewrite the NOT IN query with either the NOT EXISTS or the LEFT JOIN?

EDIT: Left Join and the correlated subquery

@JeffUK suggested in his comments that one could understand the correlated subquery better by removing the WHERE clause. Here's a small modification to the select with the where removed.

select distinct a.hero, weaponryInner.hero from weaponry a
    left join
        (Select * from weaponry b where weapon = 'Sword') as weaponryInner
    on a.hero=weaponryInner.hero

The results are two columns of heroes, some of which are NULL.

-------------------------------
Hero          |  Hero
-------------------------------
Wonder Woman  |  Wonder Woman
Gamora        |  Gamora
Spider Man    |  <null>
Batman        |  <null>
-------------------------------

So adding the final where weaponryInner.Weapon is null will return just Spider Man and Batman.

Body:
SELECT h.hero
  FROM weaponry h
    LEFT JOIN weaponry w
      ON    w.hero = h.hero
        AND w.weapon = 'Sword'
  WHERE w.weapon is null
  GROUP BY h.hero

OR

SELECT distinct h.hero
  FROM weaponry h
  WHERE not exists( SELECT 1
                      FROM weaponry w
                      WHERE w.hero = h.hero
                        AND w.weapon = 'Sword'
                  )


问:
Spring MVC passing model as dto to form?
I have question about passing my entity models to controllers and after that to form on view, where user can populate necessary data.

So right now it is like that :

Controller

```<code>User user = new UserModel();
model.add("user", user);
</code>```

View

```<code>Form thing to populate values
</code>```

And the question is:
I want to not pass entity itself but DTO for safety purposes.
Because DTO must be Immutable without setters, How then I will set those mandatory fields on view ?
I need to make something like POJO to just passing data? Then After population of data, convert POJO to entity with assembler and save it in my database?
Or there are other ways to do that ?

Edit. I use Thymeleaf on view side.

答: You need to create a Form object, which is a simple pojo with setters and getters to capture your Form data. To enforce validation rules such as @NotNull have a look at javax.validation.constraints. You should have a @Service component that has to be @Autowired in your @Controllerto populate form data into one or more @Entityand call a @Repository component, that has to be @Autowired in your @Service, for database operations.

Body:
I have question about passing my entity models to controllers and after that to form on view, where user can populate necessary data.

So right now it is like that :

Controller

User user = new UserModel();
model.add("user", user);

View

Form thing to populate values

And the question is:
I want to not pass entity itself but DTO for safety purposes.
Because DTO must be Immutable without setters, How then I will set those mandatory fields on view ?
I need to make something like POJO to just passing data? Then After population of data, convert POJO to entity with assembler and save it in my database?
Or there are other ways to do that ?

Edit. I use Thymeleaf on view side.


问:
Serial port listener in background C#
I have a question , i build a form application in C# but i am not so good in it.
I want to add a new feature to the form that listen to the serial port in the background and that then show the received data in a textbox and this has to be done so long that the appication is running.

I found some code from how to do this for a console application but now i want to change the code so that i can use it in a form , could anyone help me?

```<code>using System;
using System.IO.Ports;

class PortDataReceived
{
    public static void Main()
    {
        SerialPort mySerialPort = new SerialPort("COM8");

        mySerialPort.BaudRate = 57600;
        mySerialPort.Parity = Parity.None;
        mySerialPort.StopBits = StopBits.One;
        mySerialPort.DataBits = 8;
        mySerialPort.Handshake = Handshake.None;

        mySerialPort.DataReceived += new SerialDataReceivedEventHandler(DataReceivedHandler);

        mySerialPort.Open();

        Console.WriteLine("Press any key to continue...");
        Console.WriteLine();
        Console.ReadKey();
        mySerialPort.Close();
    }

    private static void DataReceivedHandler(
                        object sender,
                        SerialDataReceivedEventArgs e)
    {
        SerialPort sp = (SerialPort)sender;
        string indata = sp.ReadExisting();
        Console.WriteLine("Data Received:");
        Console.Write(indata);
    }
}
</code>```

答:
You can use the method invoker delegate and set the text in your DataRecieved event.

Example:

```<code>private static void DataReceivedHandler(object sender, SerialDataReceivedEventArgs e)
{
    SerialPort sp = (SerialPort)sender;
    string indata = sp.ReadExisting();

    this.Invoke((MethodInvoker)delegate
    {
        textBox.Text += indata;
    });
}
</code>```

Title: Serial port listener in background C#

Body:
I have a question , i build a form application in C# but i am not so good in it.
I want to add a new feature to the form that listen to the serial port in the background and that then show the received data in a textbox and this has to be done so long that the appication is running.

I found some code from how to do this for a console application but now i want to change the code so that i can use it in a form , could anyone help me?

using System;
using System.IO.Ports;

class PortDataReceived
{
    public static void Main()
    {
        SerialPort mySerialPort = new SerialPort("COM8");

        mySerialPort.BaudRate = 57600;
        mySerialPort.Parity = Parity.None;
        mySerialPort.StopBits = StopBits.One;
        mySerialPort.DataBits = 8;
        mySerialPort.Handshake = Handshake.None;

        mySerialPort.DataReceived += new SerialDataReceivedEventHandler(DataReceivedHandler);

        mySerialPort.Open();

        Console.WriteLine("Press any key to continue...");
        Console.WriteLine();
        Console.ReadKey();
        mySerialPort.Close();
    }

    private static void DataReceivedHandler(
                        object sender,
                        SerialDataReceivedEventArgs e)
    {
        SerialPort sp = (SerialPort)sender;
        string indata = sp.ReadExisting();
        Console.WriteLine("Data Received:");
        Console.Write(indata);
    }
}

Body:
You can use the method invoker delegate and set the text in your DataRecieved event.

Example:

private static void DataReceivedHandler(object sender, SerialDataReceivedEventArgs e)
{
    SerialPort sp = (SerialPort)sender;
    string indata = sp.ReadExisting();

    this.Invoke((MethodInvoker)delegate
    {
        textBox.Text += indata;
    });
}


问:
How to validate a currency input
I am creating a form, and that includes salary, I need to check if the input value for salary is a valid currency and has two decimal places because that is what the database accepts. If the input for salary has alphabets (a-z) or symbols (!@#%^&*() except for the $ or other currency sign) it should change the border color.

example:

```<code>  10000.00
  25846.00
  213464.12
</code>```

code:

```<code>function isNumeric(){
   var numeric = document.getElementById("txtSalary").value;
   var regex  = /^\d+(?:\.\d{0,2})$/;
   if (regex.test(numeric)){
     $("#txtSalary").css("border-color","#FFFFFF");
   }else{
      $("#txtSalary").css("border-color","#FF0000");
   }
 }
</code>```

This is already working as I wanted too, but the problem is I got 6 more input boxes that needs this kind of validation. How can I make that function, when called change the border-color of the specific selector and will return false is the value is not numeric something like:

```<code>isNumeric(selector);

function isNumeric(selector){
    var regex  = /^\d+(?:\.\d{0,2})$/;
     $(selector).filter(function() {
        return (regex.test(this.value));
     }).css("border-color","#FF0000");
    }
</code>```

Thanks!

答:
I prefer:
<input type='text' pattern='^\d+(?:\.\d{1,2})$'/>

It forces you to have at least one number after the dot, so you wont get anything like:

```<code>10000.
25846
</code>```

It will only accept:

```<code>10000.1
25846.30
213464.12
</code>```

Of course you need more server side validations in the case someone wants to bypass this one by changing the tag or javascript in the browser.

Title: How to validate a currency input

Body:
I am creating a form, and that includes salary, I need to check if the input value for salary is a valid currency and has two decimal places because that is what the database accepts. If the input for salary has alphabets (a-z) or symbols (!@#%^&*() except for the $ or other currency sign) it should change the border color.

example:

  10000.00
  25846.00
  213464.12

code:

function isNumeric(){
   var numeric = document.getElementById("txtSalary").value;
   var regex  = /^\d+(?:\.\d{0,2})$/;
   if (regex.test(numeric)){
     $("#txtSalary").css("border-color","#FFFFFF");
   }else{
      $("#txtSalary").css("border-color","#FF0000");
   }
 }

This is already working as I wanted too, but the problem is I got 6 more input boxes that needs this kind of validation. How can I make that function, when called change the border-color of the specific selector and will return false is the value is not numeric something like:

isNumeric(selector);

function isNumeric(selector){
    var regex  = /^\d+(?:\.\d{0,2})$/;
     $(selector).filter(function() {
        return (regex.test(this.value));
     }).css("border-color","#FF0000");
    }

Thanks!

Body:
I prefer:
<input type='text' pattern='^\d+(?:\.\d{1,2})$'/>

It forces you to have at least one number after the dot, so you wont get anything like:

10000.
25846

It will only accept:

10000.1
25846.30
213464.12

Of course you need more server side validations in the case someone wants to bypass this one by changing the tag or javascript in the browser.


问:
Wordpress issue with Datatables/JQuery
I've tried for days and days with no luck on this. I have a wordpress site with an active theme and a working datatable. In the past, I've had to modify the typical datatable code a bit to get it to work right with scrolling and fixed search bar, etc.

The current problem is my column visibility button will not show up in any way, shape or form. If I copy the code to my test site, it works perfectly, so I know the code is technically right and the includes/css are right but I'm wondering if there's a different way to do this in a wordpress environment, maybe by appending the button or something.

The live site with the table (button not showing up) is testing.uwsinc.net/dashboardtest

Any help with this at all is much appreciated.

```<code><head>
<title>Dashboard</title>
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.15/css/jquery.dataTables.min.css" />
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/buttons/1.3.1/css/buttons.dataTables.min.css" />

<script type="text/javascript"   src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script type="text/javascript"   src="https://cdn.datatables.net/1.10.15/js/jquery.dataTables.min.js"></script>
<script type="text/javascript"   src="https://cdn.datatables.net/buttons/1.3.1/js/dataTables.buttons.min.js"></script>
<script type="text/javascript"   src="https://cdnjs.cloudflare.com/ajax/libs/jszip/3.1.3/jszip.min.js"></script>
<script type="text/javascript"   src="https://cdn.datatables.net/buttons/1.3.1/js/buttons.colVis.min.js"></script>
<script type="text/javascript"   src="https://cdn.rawgit.com/bpampuch/pdfmake/0.1.27/build/pdfmake.min.js"></script>
<script type="text/javascript"   src="https://cdn.rawgit.com/bpampuch/pdfmake/0.1.27/build/vfs_fonts.js"></script>
<script type="text/javascript"   src="https://cdn.datatables.net/buttons/1.3.1/js/buttons.html5.min.js"></script>

   <style type="text/css">

    #select-tables{
    width: 250px;

    }
    table,td,th{
        border:1px solid black;
    }
    table{
        border-collapse: collapse;
        width:100%;
    }
    td{
        border-collapse: collapse;
        /*border-right: none;
        border-left: none;*/
    }
    th{
        padding-left: 10px;
        padding-right:10px;
    }
    td{
        padding-left: 10px;
        padding-right:10px;
    }

    input[type=submit]{
        border: 1px solid grey;
        color:black;
        font-size:12px;

    }

    table.dataTable tbody th,
    table.dataTable tbody td {
    white-space: nowrap;
    }

    .dataTables_scroll
    {
       overflow:auto;
       width: 965px;
    }

    .datatable{
        width: 100% !important;
    }

    a.dt-button{
    color:red;
    }
    </style>
</head>
<body>

//this section creates a drop down to show/hide one of the 2 tables
<label style="font-weight:bold;">Select the table you would like to view:</label></br>
<select name='tables' id='select-tables'>
<option value="mytable">Survey Test Table</option>
<option value="mytableSurvey">Survey Only</option>
</select>
</br>

//this code starts the datatables
<script type="text/javascript">
(function($) {
$(document).ready(function() {
$('#mytable').DataTable({
dom: 'Blfrtip',
buttons: [
    'colvis'
]
});

$('#mytableSurvey').DataTable({
dom: 'Blfrtip',
buttons: [
    'colvis'
]
});
$('.dataTable').wrap('<div class="dataTables_scroll" />');

$(document).on('change' , '#select-tables', function(){
var table = $(this).val();
$('#' + table +'_wrapper').show();
$('[id$="_wrapper"]').not('#' + table +'_wrapper').hide();
});
$("#select-tables").trigger("change");

});
}(jQuery));
</script>
</code>```

UPDATE:

New method to hide dynamically, also not working:

```<code><script type="text/javascript">
(function($) {
$(document).ready(function() {

var table = $('#mytable').DataTable({

});

$('a.toggle-vis').on( 'click', function (e) {
    e.preventDefault();

    // Get the column API object
    var column = table.column( $(this).attr('data-column') );

    // Toggle the visibility
    column.visible( ! column.visible() );
} );

$('.dataTable').wrap('<div class="dataTables_scroll" />');

$(document).on('change' , '#select-tables', function(){
var table = $(this).val();
$('#' + table +'_wrapper').show();
$('[id$="_wrapper"]').not('#' + table +'_wrapper').hide();
});
$("#select-tables").trigger("change");

});
}(jQuery));
</script>
</code>```

答:
Your wordpress site might be using a much more up to date version of jQuery Datatables.

As per here, colvis is no longer used.

You should instead create your own button that will fit your needs

Modify this part:

```<code>buttons: [
    'colvis'
]
</code>```

To

```<code> dom: 'Bfrtip',
 buttons: ['csv',
                [
                       {
                           text: 'Hide Column',
                           className: 'classNameSoYouCanApplyMoreJSCode',
                           action: function (e, dt, node, config) {

                               //code to hide the column.

                           }
                       }
                ]
            ]
</code>```

To illustrate, default buttons (like the csv) can be declared like so, and custom buttons can be declared after the default buttons, formatted like above.

EDIT:

Now, there is likely good reason as to why they removed the colvisbutton tag, but if your datatables work in a previous project with it.. then please go on ahead.

Title: Wordpress issue with Datatables/JQuery

Body:
I've tried for days and days with no luck on this. I have a wordpress site with an active theme and a working datatable. In the past, I've had to modify the typical datatable code a bit to get it to work right with scrolling and fixed search bar, etc.

The current problem is my column visibility button will not show up in any way, shape or form. If I copy the code to my test site, it works perfectly, so I know the code is technically right and the includes/css are right but I'm wondering if there's a different way to do this in a wordpress environment, maybe by appending the button or something.

The live site with the table (button not showing up) is testing.uwsinc.net/dashboardtest

Any help with this at all is much appreciated.

<title>Dashboard</title>
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.15/css/jquery.dataTables.min.css" />
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/buttons/1.3.1/css/buttons.dataTables.min.css" />

//this section creates a drop down to show/hide one of the 2 tables
Select the table you would like to view:

<select name='tables' id='select-tables'>
<option value="mytable">Survey Test Table</option>
<option value="mytableSurvey">Survey Only</option>
</select>

//this code starts the datatables

UPDATE:

New method to hide dynamically, also not working:

Body:
Your wordpress site might be using a much more up to date version of jQuery Datatables.

As per here, colvis is no longer used.

You should instead create your own button that will fit your needs

Modify this part:

buttons: [
    'colvis'
]

To

 dom: 'Bfrtip',
 buttons: ['csv',
                [
                       {
                           text: 'Hide Column',
                           className: 'classNameSoYouCanApplyMoreJSCode',
                           action: function (e, dt, node, config) {

                               //code to hide the column.

                           }
                       }
                ]
            ]

To illustrate, default buttons (like the csv) can be declared like so, and custom buttons can be declared after the default buttons, formatted like above.

EDIT:

Now, there is likely good reason as to why they removed the colvisbutton tag, but if your datatables work in a previous project with it.. then please go on ahead.


问:
In Django, how can I automatically set "cache-control" for every template render?
I want to se the cache control to a higher number, instead of "no-store", which is the default for django.

Can I configure it in a way that's somewhat global?

答:
Eh... I'd be careful about this. The template is processed on each request. You don't want to just set it as cached willy-nilly; the data can (and probably will) change.

Thankfully, Django provides caching. I'm not sure if it sets the no-cache properly, but it definitely prevents repeated queries that aren't needed. This is what you'd want to use.

Read up on http://docs.djangoproject.com/en/dev/topics/cache/