问:
Angular 9 Node.js AWS - Compile errors after adding import AWS from 'aws-sdk'
I have been trying everything on the web on this topic with no luck, this is my first post to StackOverflow, sorry if I'm not doing the best job.

ERROR :

```<code> node_modules/aws-sdk/clients/dynamodbstreams.d.ts:92:38 - error TS2591: Cannot find name 'Buffer'. Do you need to install type definitions for node? Try `npm i @types/node` and then add `node` to the types field in your tsconfig.

92   export type BinaryAttributeValue = Buffer|Uint8Array|Blob|string;
                                        ~~~~~~
node_modules/aws-sdk/clients/ec2.d.ts:4439:23 - error TS2591: Cannot find name 'Buffer'. Do you need to install type definitions for node? Try `npm i @types/node` and then add `node` to the types field in your tsconfig.

4439   export type _Blob = Buffer|Uint8Array|Blob|string;
                           ~~~~~~
node_modules/aws-sdk/clients/ecr.d.ts:990:31 - error TS2591: Cannot find name 'Buffer'. Do you need to install type definitions for node? Try `npm i @types/node` and then add `node` to the types field in your tsconfig.

990   export type LayerPartBlob = Buffer|Uint8Array|Blob|string;
                                  ~~~~~~
node_modules/aws-sdk/clients/firehose.d.ts:206:22 - error TS2591: Cannot find name 'Buffer'. Do you need to install type definitions for node? Try `npm i @types/node` and then add `node` to the types field in your tsconfig.
</code>```

STEPS Taken

npm -i -d @types/node

removed types from the tsconfig files

added the polyfills.ts fix :

(window as any).global = window;
(window as any).process = {
  env: { DEBUG: undefined },
};

Files

```<code>**angular.json:**
{
  "$schema": "./node_modules/@angular/cli/lib/config/schema.json",
  "version": 1,
  "newProjectRoot": "projects",
  "projects": {
    "emsForest": {
      "projectType": "application",
      "schematics": {},
      "root": "",
      "sourceRoot": "src",
      "prefix": "app",
      "architect": {
        "build": {
          "builder": "@angular-devkit/build-angular:browser",
          "options": {
            "outputPath": "dist/emsForest",
            "index": "src/index.html",
            "main": "src/main.ts",
            "polyfills": "src/polyfills.ts",
            "tsConfig": "tsconfig.app.json",
            "aot": false,
            "assets": [
              "src/favicon.ico",
              "src/assets"
            ],
            "styles": [
              "src/styles.scss"
            ],
            "scripts": []
          },
          "configurations": {
            "production": {
              "fileReplacements": [
                {
                  "replace": "src/environments/environment.ts",
                  "with": "src/environments/environment.prod.ts"
                }
              ],
              "optimization": true,
              "outputHashing": "all",
              "sourceMap": false,
              "extractCss": true,
              "namedChunks": false,
              "extractLicenses": true,
              "vendorChunk": false,
              "buildOptimizer": true,
              "budgets": [
                {
                  "type": "initial",
                  "maximumWarning": "10mb",
                  "maximumError": "20mb"
                },
                {
                  "type": "anyComponentStyle",
                  "maximumWarning": "6kb",
                  "maximumError": "10kb"
                }
              ]
            }
          }
        },
        "serve": {
          "builder": "@angular-devkit/build-angular:dev-server",
          "options": {
            "browserTarget": "emsForest:build"
          },
          "configurations": {
            "production": {
              "browserTarget": "emsForest:build:production"
            }
          }
        },
        "extract-i18n": {
          "builder": "@angular-devkit/build-angular:extract-i18n",
          "options": {
            "browserTarget": "emsForest:build"
          }
        },
        "test": {
          "builder": "@angular-devkit/build-angular:karma",
          "options": {
            "main": "src/test.ts",
            "polyfills": "src/polyfills.ts",
            "tsConfig": "tsconfig.spec.json",
            "karmaConfig": "karma.conf.js",
            "assets": [
              "src/favicon.ico",
              "src/assets"
            ],
            "styles": [
              "src/styles.scss"
            ],
            "scripts": []
          }
        },
        "lint": {
          "builder": "@angular-devkit/build-angular:tslint",
          "options": {
            "tsConfig": [
              "tsconfig.app.json",
              "tsconfig.spec.json",
              "e2e/tsconfig.json"
            ],
            "exclude": [
              "**/node_modules/**"
            ]
          }
        },
        "e2e": {
          "builder": "@angular-devkit/build-angular:protractor",
          "options": {
            "protractorConfig": "e2e/protractor.conf.js",
            "devServerTarget": "emsForest:serve"
          },
          "configurations": {
            "production": {
              "devServerTarget": "emsForest:serve:production"
            }
          }
        }
      }
    }
  },
  "defaultProject": "emsForest",
  "cli": {
    "analytics": "4b8ead9f-656d-4d3f-8080-037f834cd184"
  },
  "schematics": {
    "@schematics/angular:component": {
      "styleext": "scss"
    }
  }
}
</code>```

package.json

```<code>{
  "name": "ems-forest",
  "version": "1.0.0",
  "scripts": {
    "ng": "ng",
    "start": "ng serve",
    "build": "ng build",
    "test": "ng test",
    "lint": "ng lint",
    "e2e": "ng e2e",
    "build:browser:prod": "ng build --prod",
    "build:browser:serverless": "ng build --prod --base-href /production/",
    "build:serverless": "npm run build:browser:serverless && npm run build:server:serverless",
    "build:prod": "npm run build:browser:prod && npm run build:server:prod",
    "server": "node local.js",
    "build:prod:deploy": "npm run build:prod && npm run deploy",
    "build:serverless:deploy": "npm run build:serverless && npm run deploy",
    "deploy": "serverless deploy",
    "build:server:prod": "webpack --config webpack.server.config.js --progress --colors",
    "build:server:serverless": "webpack --config webpack.server.config.js --progress --colors"
  },
  "private": true,
  "dependencies": {
    "@angular/animations": "~9.1.1",
    "@angular/cdk": "^9.2.0",
    "@angular/common": "^9.1.1",
    "@angular/compiler": "~9.1.1",
    "@angular/core": "~9.1.1",
    "@angular/forms": "~9.1.1",
    "@angular/localize": "^9.1.1",
    "@angular/material": "^9.2.0",
    "@angular/platform-browser": "~9.1.1",
    "@angular/platform-browser-dynamic": "~9.1.1",
    "@angular/router": "~9.1.1",
    "@ng-toolkit/serverless": "^8.1.0",
    "@types/gzip-js": "^0.3.1",
    "@types/hammerjs": "^2.0.36",
    "@types/lodash": "^4.14.149",
    "angular-bootstrap-md": "^9.0.1",
    "aws-sdk": "^2.655.0",
    "aws-serverless-express": "^3.3.8",
    "axios": "^0.19.2",
    "bootstrap": "^4.4.1",
    "buffer": "^5.5.0",
    "core-js": "^3.6.4",
    "cors": "~2.8.4",
    "cp-cli": "^1.1.0",
    "enhanced-resolve": "^4.1.1",
    "fetch": "^1.1.0",
    "file-saver": "^2.0.2",
    "fs": "0.0.1-security",
    "gzip-js": "^0.3.2",
    "hammerjs": "^2.0.8",
    "igniteui-angular": "^9.0.9",
    "igniteui-angular-core": "^9.0.1",
    "igniteui-angular-excel": "^9.0.1",
    "igniteui-angular-spreadsheet": "^9.0.1",
    "jszip": "^3.3.0",
    "lodash": "^4.17.15",
    "lzutf8": "^0.5.5",
    "minireset.css": "~0.0.4",
    "ngx-webstorage-service": "^4.1.0",
    "node-sass": "^4.13.1",
    "resize-observer-polyfill": "^1.5.1",
    "rxjs": "^6.5.5",
    "sass": "^1.26.3",
    "stream": "0.0.2",
    "tslib": "^1.11.1",
    "web-animations-js": "^2.3.2",
    "xlsx": "^0.15.6",
    "zone.js": "^0.10.3"
  },
  "devDependencies": {
    "@angular-devkit/build-angular": "^0.901.0",
    "@types/aws-sdk": "^2.7.0",
    "@angular/cli": "^9.1.0",
    "@angular/compiler-cli": "~9.1.1",
    "@angular/language-service": "~9.1.1",
    "@igniteui/angular-schematics": "~9.0.500",
    "@types/jasmine": "~3.3.8",
    "@types/jasminewd2": "~2.0.3",
    "@types/jquery": "^3.3.34",
    "@types/node": "^12.12.34",
    "codelyzer": "^5.2.2",
    "igniteui-cli": "~5.0.1",
    "jasmine-core": "^3.5.0",
    "jasmine-spec-reporter": "~4.2.1",
    "karma": "~4.1.0",
    "karma-chrome-launcher": "~2.2.0",
    "karma-coverage-istanbul-reporter": "~2.0.1",
    "karma-jasmine": "~2.0.1",
    "karma-jasmine-html-reporter": "^1.5.3",
    "opencollective": "^1.0.3",
    "protractor": "^5.4.3",
    "serverless": "1.40.0",
    "serverless-apigw-binary": "^0.4.4",
    "ts-loader": "4.2.0",
    "ts-node": "~7.0.0",
    "tslint": "~5.15.0",
    "typescript": "~3.8.3",
    "webpack-cli": "^3.3.11"
  }
}
</code>```

tsconfig.app.json

```<code>{
  "extends": "./tsconfig.json",
  "compilerOptions": {
    "outDir": "./out-tsc/app",
  },
  "files": [
    "src/main.ts",
    "src/polyfills.ts"
  ],
  "include": [
    "src/**/*.d.ts"
  ],
  "exclude": [
    "src/test.ts",
    "src/**/*.spec.ts"
  ]
}
</code>```

src\tsconfig.app.json

```<code>{
  "extends": "../tsconfig.json",
  "compilerOptions": {
    "outDir": "../out-tsc/app",
  },
  "exclude": [
    "test.ts",
    "**/*.spec.ts"
  ]
}
</code>```

The TS file if the: "import AWS from 'aws-sdk'"  is removed the code complies ok

```<code>import { Component, OnInit } from '@angular/core';

import * as AWS from 'aws-sdk';

@Component({
  selector: 'app-admin-portal',
  templateUrl: './admin-portal.component.html',
  styleUrls: ['./admin-portal.component.scss']
})
export class AdminPortalComponent implements OnInit {
  constructor() { }
  ngOnInit() {
  }
}
</code>```

答:
In the api docs, it is mentioned that you either add "types": ["node"] to the project's tsconfig.app.json file, or remove the "types" field entirely.

It is working on my side after adding the node in the array:

"compilerOptions": {
    "outDir": "./out-tsc/app",
    "types": ["node"]
  }

I hope this helps.

Body:
I have been trying everything on the web on this topic with no luck, this is my first post to StackOverflow, sorry if I'm not doing the best job.

ERROR :

 node_modules/aws-sdk/clients/dynamodbstreams.d.ts:92:38 - error TS2591: Cannot find name 'Buffer'. Do you need to install type definitions for node? Try `npm i @types/node` and then add `node` to the types field in your tsconfig.

92   export type BinaryAttributeValue = Buffer|Uint8Array|Blob|string;
                                        ~~~~~~
node_modules/aws-sdk/clients/ec2.d.ts:4439:23 - error TS2591: Cannot find name 'Buffer'. Do you need to install type definitions for node? Try `npm i @types/node` and then add `node` to the types field in your tsconfig.

4439   export type _Blob = Buffer|Uint8Array|Blob|string;
                           ~~~~~~
node_modules/aws-sdk/clients/ecr.d.ts:990:31 - error TS2591: Cannot find name 'Buffer'. Do you need to install type definitions for node? Try `npm i @types/node` and then add `node` to the types field in your tsconfig.

990   export type LayerPartBlob = Buffer|Uint8Array|Blob|string;
                                  ~~~~~~
node_modules/aws-sdk/clients/firehose.d.ts:206:22 - error TS2591: Cannot find name 'Buffer'. Do you need to install type definitions for node? Try `npm i @types/node` and then add `node` to the types field in your tsconfig.

STEPS Taken

npm -i -d @types/node

removed types from the tsconfig files

added the polyfills.ts fix :

(window as any).global = window;
(window as any).process = {
  env: { DEBUG: undefined },
};

Files

**angular.json:**
{
  "$schema": "./node_modules/@angular/cli/lib/config/schema.json",
  "version": 1,
  "newProjectRoot": "projects",
  "projects": {
    "emsForest": {
      "projectType": "application",
      "schematics": {},
      "root": "",
      "sourceRoot": "src",
      "prefix": "app",
      "architect": {
        "build": {
          "builder": "@angular-devkit/build-angular:browser",
          "options": {
            "outputPath": "dist/emsForest",
            "index": "src/index.html",
            "main": "src/main.ts",
            "polyfills": "src/polyfills.ts",
            "tsConfig": "tsconfig.app.json",
            "aot": false,
            "assets": [
              "src/favicon.ico",
              "src/assets"
            ],
            "styles": [
              "src/styles.scss"
            ],
            "scripts": []
          },
          "configurations": {
            "production": {
              "fileReplacements": [
                {
                  "replace": "src/environments/environment.ts",
                  "with": "src/environments/environment.prod.ts"
                }
              ],
              "optimization": true,
              "outputHashing": "all",
              "sourceMap": false,
              "extractCss": true,
              "namedChunks": false,
              "extractLicenses": true,
              "vendorChunk": false,
              "buildOptimizer": true,
              "budgets": [
                {
                  "type": "initial",
                  "maximumWarning": "10mb",
                  "maximumError": "20mb"
                },
                {
                  "type": "anyComponentStyle",
                  "maximumWarning": "6kb",
                  "maximumError": "10kb"
                }
              ]
            }
          }
        },
        "serve": {
          "builder": "@angular-devkit/build-angular:dev-server",
          "options": {
            "browserTarget": "emsForest:build"
          },
          "configurations": {
            "production": {
              "browserTarget": "emsForest:build:production"
            }
          }
        },
        "extract-i18n": {
          "builder": "@angular-devkit/build-angular:extract-i18n",
          "options": {
            "browserTarget": "emsForest:build"
          }
        },
        "test": {
          "builder": "@angular-devkit/build-angular:karma",
          "options": {
            "main": "src/test.ts",
            "polyfills": "src/polyfills.ts",
            "tsConfig": "tsconfig.spec.json",
            "karmaConfig": "karma.conf.js",
            "assets": [
              "src/favicon.ico",
              "src/assets"
            ],
            "styles": [
              "src/styles.scss"
            ],
            "scripts": []
          }
        },
        "lint": {
          "builder": "@angular-devkit/build-angular:tslint",
          "options": {
            "tsConfig": [
              "tsconfig.app.json",
              "tsconfig.spec.json",
              "e2e/tsconfig.json"
            ],
            "exclude": [
              "**/node_modules/**"
            ]
          }
        },
        "e2e": {
          "builder": "@angular-devkit/build-angular:protractor",
          "options": {
            "protractorConfig": "e2e/protractor.conf.js",
            "devServerTarget": "emsForest:serve"
          },
          "configurations": {
            "production": {
              "devServerTarget": "emsForest:serve:production"
            }
          }
        }
      }
    }
  },
  "defaultProject": "emsForest",
  "cli": {
    "analytics": "4b8ead9f-656d-4d3f-8080-037f834cd184"
  },
  "schematics": {
    "@schematics/angular:component": {
      "styleext": "scss"
    }
  }
}

package.json

{
  "name": "ems-forest",
  "version": "1.0.0",
  "scripts": {
    "ng": "ng",
    "start": "ng serve",
    "build": "ng build",
    "test": "ng test",
    "lint": "ng lint",
    "e2e": "ng e2e",
    "build:browser:prod": "ng build --prod",
    "build:browser:serverless": "ng build --prod --base-href /production/",
    "build:serverless": "npm run build:browser:serverless && npm run build:server:serverless",
    "build:prod": "npm run build:browser:prod && npm run build:server:prod",
    "server": "node local.js",
    "build:prod:deploy": "npm run build:prod && npm run deploy",
    "build:serverless:deploy": "npm run build:serverless && npm run deploy",
    "deploy": "serverless deploy",
    "build:server:prod": "webpack --config webpack.server.config.js --progress --colors",
    "build:server:serverless": "webpack --config webpack.server.config.js --progress --colors"
  },
  "private": true,
  "dependencies": {
    "@angular/animations": "~9.1.1",
    "@angular/cdk": "^9.2.0",
    "@angular/common": "^9.1.1",
    "@angular/compiler": "~9.1.1",
    "@angular/core": "~9.1.1",
    "@angular/forms": "~9.1.1",
    "@angular/localize": "^9.1.1",
    "@angular/material": "^9.2.0",
    "@angular/platform-browser": "~9.1.1",
    "@angular/platform-browser-dynamic": "~9.1.1",
    "@angular/router": "~9.1.1",
    "@ng-toolkit/serverless": "^8.1.0",
    "@types/gzip-js": "^0.3.1",
    "@types/hammerjs": "^2.0.36",
    "@types/lodash": "^4.14.149",
    "angular-bootstrap-md": "^9.0.1",
    "aws-sdk": "^2.655.0",
    "aws-serverless-express": "^3.3.8",
    "axios": "^0.19.2",
    "bootstrap": "^4.4.1",
    "buffer": "^5.5.0",
    "core-js": "^3.6.4",
    "cors": "~2.8.4",
    "cp-cli": "^1.1.0",
    "enhanced-resolve": "^4.1.1",
    "fetch": "^1.1.0",
    "file-saver": "^2.0.2",
    "fs": "0.0.1-security",
    "gzip-js": "^0.3.2",
    "hammerjs": "^2.0.8",
    "igniteui-angular": "^9.0.9",
    "igniteui-angular-core": "^9.0.1",
    "igniteui-angular-excel": "^9.0.1",
    "igniteui-angular-spreadsheet": "^9.0.1",
    "jszip": "^3.3.0",
    "lodash": "^4.17.15",
    "lzutf8": "^0.5.5",
    "minireset.css": "~0.0.4",
    "ngx-webstorage-service": "^4.1.0",
    "node-sass": "^4.13.1",
    "resize-observer-polyfill": "^1.5.1",
    "rxjs": "^6.5.5",
    "sass": "^1.26.3",
    "stream": "0.0.2",
    "tslib": "^1.11.1",
    "web-animations-js": "^2.3.2",
    "xlsx": "^0.15.6",
    "zone.js": "^0.10.3"
  },
  "devDependencies": {
    "@angular-devkit/build-angular": "^0.901.0",
    "@types/aws-sdk": "^2.7.0",
    "@angular/cli": "^9.1.0",
    "@angular/compiler-cli": "~9.1.1",
    "@angular/language-service": "~9.1.1",
    "@igniteui/angular-schematics": "~9.0.500",
    "@types/jasmine": "~3.3.8",
    "@types/jasminewd2": "~2.0.3",
    "@types/jquery": "^3.3.34",
    "@types/node": "^12.12.34",
    "codelyzer": "^5.2.2",
    "igniteui-cli": "~5.0.1",
    "jasmine-core": "^3.5.0",
    "jasmine-spec-reporter": "~4.2.1",
    "karma": "~4.1.0",
    "karma-chrome-launcher": "~2.2.0",
    "karma-coverage-istanbul-reporter": "~2.0.1",
    "karma-jasmine": "~2.0.1",
    "karma-jasmine-html-reporter": "^1.5.3",
    "opencollective": "^1.0.3",
    "protractor": "^5.4.3",
    "serverless": "1.40.0",
    "serverless-apigw-binary": "^0.4.4",
    "ts-loader": "4.2.0",
    "ts-node": "~7.0.0",
    "tslint": "~5.15.0",
    "typescript": "~3.8.3",
    "webpack-cli": "^3.3.11"
  }
}

tsconfig.app.json

{
  "extends": "./tsconfig.json",
  "compilerOptions": {
    "outDir": "./out-tsc/app",
  },
  "files": [
    "src/main.ts",
    "src/polyfills.ts"
  ],
  "include": [
    "src/**/*.d.ts"
  ],
  "exclude": [
    "src/test.ts",
    "src/**/*.spec.ts"
  ]
}

src\tsconfig.app.json

{
  "extends": "../tsconfig.json",
  "compilerOptions": {
    "outDir": "../out-tsc/app",
  },
  "exclude": [
    "test.ts",
    "**/*.spec.ts"
  ]
}

The TS file if the: "import AWS from 'aws-sdk'"  is removed the code complies ok

import { Component, OnInit } from '@angular/core';

import * as AWS from 'aws-sdk';

@Component({
  selector: 'app-admin-portal',
  templateUrl: './admin-portal.component.html',
  styleUrls: ['./admin-portal.component.scss']
})
export class AdminPortalComponent implements OnInit {
  constructor() { }
  ngOnInit() {
  }
}


来源: stackexchange

问:
Why is there no optimization for checking for empty string via "" comparison?
This google-benchmark code checked on Quick Bench, shows that string::empty() runs a lot faster than comparing with an empty-string literal. However, creating a name string of "" actually makes the compiler optimize away the check:

bool compareWithNamedConst(const std::string& target) {
    const std::string emptyString = "";
    return emptyString == target;
}

bool compareWithLiteral(const std::string& target) {
    return "" == target;
}

bool compareWithRvalue(const std::string& target) {
    return std::string{""} == target;
}

bool checkForEmpty(const std::string& target) {
    return target.empty();
}
```

<p>The performance for each of the calls is shown here:</p>

<p><img src="https://i.stack.imgur.com/Ye0MU.png" width="600" /></p>

<p>As you can see, comparing with <code>""</code> is very slow compared to all the other options. I wonder why it is the case? It must be somehow related to SSO not being applied on <code>const char*</code>, as testing this:</p>

<pre class="lang-cpp prettyprint-override"><code>bool compareWithLiteral(const std::string& target) {
    return "test with a longer string not optimized" == target;
}

bool compareWithRvalue(const std::string& target) {
    return std::string{"test with a longer string not optimized"} == target;
}
</code>```

Results comparing with a literal actually being faster:

I find that checking for string emptiness, the easiest syntax to read is "" == myVariable as it clearly indicates that myVariable is a std::string with no unneccesary clutter. Why can't we have it optimized as we have all the other cases?

答:
I believe the main difference is that comparison that involves std::string objects first only checks their sizes. If they are not equal, the comparison immediately returns. (That's also might explain why memcmp may be then used if both strings are of equal lengths, as pointed out by @KamilCuk.)

On the contrary, with literals, these are treated as C-strings/char-arrays where no information about their lengths are provided. Therefore, strcmp function is used inside which has larger overhead, even in case that one of the string is empty (at least, the overhead of a function call since strcmp seems to be not inlined in your assembly).

As for the last question, compareWithRvalue, there the string is too large for SSO, therefore, dynamic memory allocation (and deallocation) is performed (and likely not optimized away here), which represents a relatively large overhead here.

ContentLicense: CC BY-SA 4.0

Body:
This google-benchmark code checked on Quick Bench, shows that string::empty() runs a lot faster than comparing with an empty-string literal. However, creating a name string of "" actually makes the compiler optimize away the check:

bool compareWithNamedConst(const std::string& target) {
    const std::string emptyString = "";
    return emptyString == target;
}

bool compareWithLiteral(const std::string& target) {
    return "" == target;
}

bool compareWithRvalue(const std::string& target) {
    return std::string{""} == target;
}

bool checkForEmpty(const std::string& target) {
    return target.empty();
}

The performance for each of the calls is shown here:

As you can see, comparing with "" is very slow compared to all the other options. I wonder why it is the case? It must be somehow related to SSO not being applied on const char*, as testing this:

bool compareWithLiteral(const std::string& target) {
    return "test with a longer string not optimized" == target;
}

bool compareWithRvalue(const std::string& target) {
    return std::string{"test with a longer string not optimized"} == target;
}

Results comparing with a literal actually being faster:

I find that checking for string emptiness, the easiest syntax to read is "" == myVariable as it clearly indicates that myVariable is a std::string with no unneccesary clutter. Why can't we have it optimized as we have all the other cases?


问:
IBM Message Queue using PYMQI and Correlation ID
I recently inherited a testing framework using PYMQI to put a message on IBM Websphere Queue. I fixed most of the code i need by going through this link

https://dsuch.github.io/pymqi/examples.html#how-to-correlate-request-and-response-messages-using-correlationid

The only pending issue is the format of correlation ID. I tried quite a few options but MQ is converting the correlation ID Into byte array (seems IBM MQ default setting) before throwing it on the Q. All my downstream systems are looking for a HEX value and is breaking.

I am stuck on this for a few days now. Is there a way to force the correlation ID in message properties?.

Please let me know

Regards
Aravind

@JoshMc thanks a lot for the reply. It is proprietary code so little difficult to paste whole thing however here is the relevant piece. Downstream system is looking at this JMS Correlation ID to increment and put back in the queue. When i am sending this through below code it hits queue gets converted to byte array however downstream system read validation fails. I want this to hit the queue as a HEX value as in it should be the exact value i pass and not byte array.

```<code>queue = self._open_write_queue(queue_name)

put_mqmd = pymqi.md()
put_mqmd.Format = CMQC.MQFMT_STRING
CCSID = 1202

 put_opts = pymqi.pmo()
# Set the MsgType to request.
# put_mqmd["MsgType"] = CMQC.MQMT_REQUEST
put_mqmd["MsgId"] = '00002Y0001T1'
put_mqmd["CorrelId"] = '00002Y0001T1'

 put_opts = pymqi.PMO(Options=CMQC.MQPMO_NO_SYNCPOINT +
                                         CMQC.MQPMO_FAIL_IF_QUIESCING + CMQC.MQRO_PASS_CORREL_ID)
            queue.put(message, put_mqmd, put_opts)
</code>```

when I put a message through to the queue, it is getting posted successfully, but does not get processed by the downstream system:

In the screenshot above the first message in the queue was posted using app JMSToolBox- which has the correlationId as expected by the downstream systems. The second message was posted using robot framework/pymqi - which has the correlation-id displayed ID:30303..... Also please note that the JMSDestination is displayed as null for the second message.(For the first message posted manually has the as 'JMSDestination: queue:///QueueName'

Now i have two issues - CorrelationId not coming up as i expect and the JMSDestination:null. I'm not sure how I can set the destination using pymqi library(or is this set at Q-Manager level) Any help is much appreciated.

Screenshot of message sent by JMSToolBox:

Screenshot of message sent using robotframework-pymqi:

The only difference I find in the two messages now is the JMSDestination:Null in the JMSHeader for the message sent using Pymqi. I also tried changing the PROPCTL setting for the queue- but did not help.

Is there a I can send the java properties using pymqi?

答:
As the comments indicate, the correlation id needs to be a byte array padded out to 24 bytes or 48 hexadecimals. So

Python 2 & 3 compatible way

put_mqmd["CorrelId"] = 'Aravind'.ljust(24).encode('utf-8')
```

<p>Python 3 only way</p>

<pre class="lang-py prettyprint-override"><code>put_mqmd["CorrelId"] = bytes('Aravind'.ljust(24), 'utf-8')
</code>```

but the easiest way is to let the underlying client generate it for you by passing in CMQC.MQPMO_NEW_CORREL_ID. I can't tell you where in your code, because you haven't shown that bit, but there are samples in the pymqi documentation.

Body:
I recently inherited a testing framework using PYMQI to put a message on IBM Websphere Queue. I fixed most of the code i need by going through this link

https://dsuch.github.io/pymqi/examples.html#how-to-correlate-request-and-response-messages-using-correlationid

The only pending issue is the format of correlation ID. I tried quite a few options but MQ is converting the correlation ID Into byte array (seems IBM MQ default setting) before throwing it on the Q. All my downstream systems are looking for a HEX value and is breaking.

I am stuck on this for a few days now. Is there a way to force the correlation ID in message properties?.

Please let me know

Regards
Aravind

@JoshMc thanks a lot for the reply. It is proprietary code so little difficult to paste whole thing however here is the relevant piece. Downstream system is looking at this JMS Correlation ID to increment and put back in the queue. When i am sending this through below code it hits queue gets converted to byte array however downstream system read validation fails. I want this to hit the queue as a HEX value as in it should be the exact value i pass and not byte array.

queue = self._open_write_queue(queue_name)

put_mqmd = pymqi.md()
put_mqmd.Format = CMQC.MQFMT_STRING
CCSID = 1202

 put_opts = pymqi.pmo()
# Set the MsgType to request.
# put_mqmd["MsgType"] = CMQC.MQMT_REQUEST
put_mqmd["MsgId"] = '00002Y0001T1'
put_mqmd["CorrelId"] = '00002Y0001T1'

 put_opts = pymqi.PMO(Options=CMQC.MQPMO_NO_SYNCPOINT +
                                         CMQC.MQPMO_FAIL_IF_QUIESCING + CMQC.MQRO_PASS_CORREL_ID)
            queue.put(message, put_mqmd, put_opts)

when I put a message through to the queue, it is getting posted successfully, but does not get processed by the downstream system:

In the screenshot above the first message in the queue was posted using app JMSToolBox- which has the correlationId as expected by the downstream systems. The second message was posted using robot framework/pymqi - which has the correlation-id displayed ID:30303..... Also please note that the JMSDestination is displayed as null for the second message.(For the first message posted manually has the as 'JMSDestination: queue:///QueueName'

Now i have two issues - CorrelationId not coming up as i expect and the JMSDestination:null. I'm not sure how I can set the destination using pymqi library(or is this set at Q-Manager level) Any help is much appreciated.

Screenshot of message sent by JMSToolBox:

Screenshot of message sent using robotframework-pymqi:

The only difference I find in the two messages now is the JMSDestination:Null in the JMSHeader for the message sent using Pymqi. I also tried changing the PROPCTL setting for the queue- but did not help.

Is there a I can send the java properties using pymqi?

Body:
As the comments indicate, the correlation id needs to be a byte array padded out to 24 bytes or 48 hexadecimals. So

Python 2 & 3 compatible way

put_mqmd["CorrelId"] = 'Aravind'.ljust(24).encode('utf-8')

Python 3 only way

put_mqmd["CorrelId"] = bytes('Aravind'.ljust(24), 'utf-8')

but the easiest way is to let the underlying client generate it for you by passing in CMQC.MQPMO_NEW_CORREL_ID. I can't tell you where in your code, because you haven't shown that bit, but there are samples in the pymqi documentation.


问:
Locate the Keys with same values in JSON
I have below json

```<code>[{
    "workType": "NDB To Nice",
    "priority": 5
},
{
    "workType": "PDAD",
    "priority": 0
}, {
    "workType": "PPACA",
    "priority": 0
}, {
    "workType": "Retrigger",
    "priority": "5"
}, {
    "workType": "Special Intake Request Intake",
    "priority": "7"
}]
</code>```

I need to call out all the "worktype" which have same "priority" , iff the priority is NOT EQUAL TO 0.

Means for above example i should get keys = ["NDB To Nice","Retrigger"] since they both have priority 5.

I have tried below code

```<code>  function(array, k) {
  return array.reduce(function(acc, cur) {
    (acc[cur[k]] = acc[cur[k]] || []).push(cur);
    return acc;
  }, {});
};
</code>```

But i am not able to achieve the output.

答:
Try to group items by reduce method and then just filter

```<code>let hashMap = input.reduce((a, {workType, priority})=> {
    if (priority > 0) {
       a[priority] = a[priority] || [];
       a[priority].push(workType);
    }
    return a;
},{});
let result = Object.entries(hashMap)
   .filter(([k, v]) => v.length > 1)
   .map(([k, v]) => v);
</code>```

An example:

let input = [{ "workType": "NDB To Nice", "priority": 5 },
{ "workType": "PDAD", "priority": 0 },
{ "workType": "PPACA", "priority": 0 },
{ "workType": "Retrigger", "priority": "5" },
{ "workType": "Special Intake Request Intake", "priority": "7" }
];

// I need to call out all the "worktype" which have same "priority" , if the priority is NOT EQUAL TO 0.
// keys = ["NDB To Nice","Retrigger"]
let hashMap = input.reduce((a, {workType, priority})=> {
  if (priority > 0) {
  a[priority] = a[priority] || [];
  a[priority].push(workType);
  }
  return a;
},{});
let result = Object.entries(hashMap).filter(([k, v]) => v.length > 1).map(([k, v]) => v);
console.log(result);```
</div>
</div>
</p>

<p>Or of you like inline methods (in my view, it lacks readablitity)</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>let input = [{ "workType": "NDB To Nice", "priority": 5 },
{ "workType": "PDAD", "priority": 0 },
{ "workType": "PPACA", "priority": 0 },
{ "workType": "Retrigger", "priority": "5" },
{ "workType": "Special Intake Request Intake", "priority": "7" }
];

let hashMap = input.reduce((a, {workType, priority})=> ( ((priority > 0) ?
(a[priority] = a[priority] || [], a[priority].push(workType)) : null), a), {});
let result = Object.entries(hashMap).filter(([k, v]) => v.length > 1).map(([k, v]) => v)
console.log(result);</code>```

Body:
I have below json

[{
    "workType": "NDB To Nice",
    "priority": 5
},
{
    "workType": "PDAD",
    "priority": 0
}, {
    "workType": "PPACA",
    "priority": 0
}, {
    "workType": "Retrigger",
    "priority": "5"
}, {
    "workType": "Special Intake Request Intake",
    "priority": "7"
}]

I need to call out all the "worktype" which have same "priority" , iff the priority is NOT EQUAL TO 0.

Means for above example i should get keys = ["NDB To Nice","Retrigger"] since they both have priority 5.

I have tried below code

  function(array, k) {
  return array.reduce(function(acc, cur) {
    (acc[cur[k]] = acc[cur[k]] || []).push(cur);
    return acc;
  }, {});
};

But i am not able to achieve the output.

Body:
Try to group items by reduce method and then just filter

let hashMap = input.reduce((a, {workType, priority})=> {
    if (priority > 0) {
       a[priority] = a[priority] || [];
       a[priority].push(workType);
    }
    return a;
},{});
let result = Object.entries(hashMap)
   .filter(([k, v]) => v.length > 1)
   .map(([k, v]) => v);

An example:

let input = [{ "workType": "NDB To Nice", "priority": 5 },
{ "workType": "PDAD", "priority": 0 },
{ "workType": "PPACA", "priority": 0 },
{ "workType": "Retrigger", "priority": "5" },
{ "workType": "Special Intake Request Intake", "priority": "7" }
];

// I need to call out all the "worktype" which have same "priority" , if the priority is NOT EQUAL TO 0.
// keys = ["NDB To Nice","Retrigger"]
let hashMap = input.reduce((a, {workType, priority})=> {
  if (priority > 0) {
  a[priority] = a[priority] || [];
  a[priority].push(workType);
  }
  return a;
},{});
let result = Object.entries(hashMap).filter(([k, v]) => v.length > 1).map(([k, v]) => v);
console.log(result);

Or of you like inline methods (in my view, it lacks readablitity)

let input = [{ "workType": "NDB To Nice", "priority": 5 },
{ "workType": "PDAD", "priority": 0 },
{ "workType": "PPACA", "priority": 0 },
{ "workType": "Retrigger", "priority": "5" },
{ "workType": "Special Intake Request Intake", "priority": "7" }
];

let hashMap = input.reduce((a, {workType, priority})=> ( ((priority > 0) ?
(a[priority] = a[priority] || [], a[priority].push(workType)) : null), a), {});
let result = Object.entries(hashMap).filter(([k, v]) => v.length > 1).map(([k, v]) => v)
console.log(result);


问:
Lua alternative to optim()
I'm currently looking for a lua alternative to the R programming languages; optim() function, if anyone knows how to deal with this?</p>

答:
R's implementation of optim isn't actually written in R.  If you type "optim" with no parentheses at the prompt, it'll dump out the definition of the function, and you can see that after some error checking and argument shuffling it invokes an .Internal routine (coded in C and/or Fortran) to do all the real work.

So your best bet is to find a C library for mathematical optimization -- sorry, I have no recommendations -- and wrap that into Lua.  I doubt anyone has written native-Lua code for this, and I would not recommend trying to code it yourself; doing mathematical optimization efficiently is still an active domain of basic research, and the best-so-far algorithms are decidedly nontrivial to implement.

ContentLicense: CC BY-SA 3.0

Title: Lua alternative to optim()


问:
React component not working on touchscreen
I've made an knob which can be dragged to adjust the value. It is working fine when using a mouse but I can get it to work on a touchscreen. I've looked arround for some solutions like touch-action and pointer in CSS but these dont work. What else could I do to make this work because I cant really find something on SO either.

This is the knob component.

```<code>import React from 'react';

export default class Knob extends React.Component {
  constructor(props) {
    super(props);
    this.fullAngle = props.degrees;
    this.startAngle = (360 - props.degrees) / 2;
    this.endAngle = this.startAngle + props.degrees;
    this.margin = props.size * 0.15;
    this.currentDeg = Math.floor(
      this.convertRange(
        props.min,
        props.max,
        this.startAngle,
        this.endAngle,
        props.value
      )
    );
    this.state = { deg: this.currentDeg };
  }

  startDrag = e => {
    e.preventDefault();
    const knob = e.target.getBoundingClientRect();
    const pts = {
      x: knob.left + knob.width / 2,
      y: knob.top + knob.height / 2
    };
    const moveHandler = e => {
      this.currentDeg = this.getDeg(e.clientX, e.clientY, pts);
      if (this.currentDeg === this.startAngle) this.currentDeg--;
      let newValue = Math.floor(
        this.convertRange(
          this.startAngle,
          this.endAngle,
          this.props.min,
          this.props.max,
          this.currentDeg
        )
      );
      this.setState({ deg: this.currentDeg });
      this.props.onChange(newValue);
    };
    document.addEventListener("mousemove", moveHandler);
    document.addEventListener("mouseup", e => {
      document.removeEventListener("mousemove", moveHandler);
    });
  };

  getDeg = (cX, cY, pts) => {
    const x = cX - pts.x;
    const y = cY - pts.y;
    let deg = Math.atan(y / x) * 180 / Math.PI;
    if ((x < 0 && y >= 0) || (x < 0 && y < 0)) {
      deg += 90;
    } else {
      deg += 270;
    }
    let finalDeg = Math.min(Math.max(this.startAngle, deg), this.endAngle);
    return finalDeg;
  };

  convertRange = (oldMin, oldMax, newMin, newMax, oldValue) => {
    return (oldValue - oldMin) * (newMax - newMin) / (oldMax - oldMin) + newMin;
  };

  renderTicks = () => {
    let ticks = [];
    const incr = this.fullAngle / this.props.numTicks;
    const size = this.margin + this.props.size / 2;
    for (let deg = this.startAngle; deg <= this.endAngle; deg += incr) {
      const tick = {
        deg: deg,
        tickStyle: {
          height: size + 10,
          left: size - 1,
          top: size + 2,
          transform: "rotate(" + deg + "deg)",
          transformOrigin: "top"
        }
      };
      ticks.push(tick);
    }
    return ticks;
  };

  dcpy = o => {
    return JSON.parse(JSON.stringify(o));
  };

  render() {
    let kStyle = {
      width: this.props.size,
      height: this.props.size
    };
    let iStyle = this.dcpy(kStyle);
    let oStyle = this.dcpy(kStyle);
    oStyle.margin = this.margin;
    if (this.props.color) {
      oStyle.backgroundImage =
        "radial-gradient(100% 70%,hsl(210, " +
        this.currentDeg +
        "%, " +
        this.currentDeg / 5 +
        "%),hsl(" +
        Math.random() * 100 +
        ",20%," +
        this.currentDeg / 36 +
        "%))";
    }
    iStyle.transform = "rotate(" + this.state.deg + "deg)";

    return (
      <div className="knob" style={kStyle}>
        <div className="ticks">
          {this.props.numTicks
            ? this.renderTicks().map((tick, i) => (
                <div
                  key={i}
                  className={
                    "tick" + (tick.deg <= this.currentDeg ? " active" : "")
                  }
                  style={tick.tickStyle}
                />
              ))
            : null}
        </div>
        <div className="knob outer" style={oStyle} onMouseDown={this.startDrag}>
          <div className="knob inner" style={iStyle}>
            <div className="grip" />
          </div>
        </div>
      </div>
    );
  }
}
</code>```

and the stylesheet:

```<code>.knob {
  touch-action: manipulation;
  pointer-events: auto;
  display: flex;
  position: relative;
}
.knob .ticks {
  position: absolute;
}
.knob .ticks .tick {
  position: absolute;
  background: black;
  box-shadow: inset 0 0 0 0 black;
  width: 3px;
  transition: box-shadow 0.5s;
}
.knob .ticks .tick.active {
  box-shadow: inset 0 0 5px 2px #509eec, 0 0 0 1px #369;
}
.knob.outer {
  border-radius: 50%;
  border: 1px solid #222;
  border-bottom: 5px solid #222;
  background: radial-gradient(closest-side, #666 6%, #333 90%);
  box-shadow: 0 5px 15px 2px black, 0 0 5px 3px black, 0 0 0 12px #444;
}
.knob.inner {
  border-radius: 50%;
}
.knob.inner .grip {
  position: absolute;
  width: 5%;
  height: 5%;
  bottom: 2%;
  left: 50%;
  transform: translateX(-50%);
  border-radius: 50%;
  background: #509eec;
  box-shadow: 0 0 3px 1px black;
}
</code>```

答:
For touch devices, you can use onTouchStart for the same events as onMouseDown.

Also, you might be interested in onPointerDown events which will work on both touch and non touch devices. Check browser support

Body:
I've made an knob which can be dragged to adjust the value. It is working fine when using a mouse but I can get it to work on a touchscreen. I've looked arround for some solutions like touch-action and pointer in CSS but these dont work. What else could I do to make this work because I cant really find something on SO either.

This is the knob component.

import React from 'react';

export default class Knob extends React.Component {
  constructor(props) {
    super(props);
    this.fullAngle = props.degrees;
    this.startAngle = (360 - props.degrees) / 2;
    this.endAngle = this.startAngle + props.degrees;
    this.margin = props.size * 0.15;
    this.currentDeg = Math.floor(
      this.convertRange(
        props.min,
        props.max,
        this.startAngle,
        this.endAngle,
        props.value
      )
    );
    this.state = { deg: this.currentDeg };
  }

  startDrag = e => {
    e.preventDefault();
    const knob = e.target.getBoundingClientRect();
    const pts = {
      x: knob.left + knob.width / 2,
      y: knob.top + knob.height / 2
    };
    const moveHandler = e => {
      this.currentDeg = this.getDeg(e.clientX, e.clientY, pts);
      if (this.currentDeg === this.startAngle) this.currentDeg--;
      let newValue = Math.floor(
        this.convertRange(
          this.startAngle,
          this.endAngle,
          this.props.min,
          this.props.max,
          this.currentDeg
        )
      );
      this.setState({ deg: this.currentDeg });
      this.props.onChange(newValue);
    };
    document.addEventListener("mousemove", moveHandler);
    document.addEventListener("mouseup", e => {
      document.removeEventListener("mousemove", moveHandler);
    });
  };

  getDeg = (cX, cY, pts) => {
    const x = cX - pts.x;
    const y = cY - pts.y;
    let deg = Math.atan(y / x) * 180 / Math.PI;
    if ((x < 0 && y >= 0) || (x < 0 && y < 0)) {
      deg += 90;
    } else {
      deg += 270;
    }
    let finalDeg = Math.min(Math.max(this.startAngle, deg), this.endAngle);
    return finalDeg;
  };

  convertRange = (oldMin, oldMax, newMin, newMax, oldValue) => {
    return (oldValue - oldMin) * (newMax - newMin) / (oldMax - oldMin) + newMin;
  };

  renderTicks = () => {
    let ticks = [];
    const incr = this.fullAngle / this.props.numTicks;
    const size = this.margin + this.props.size / 2;
    for (let deg = this.startAngle; deg <= this.endAngle; deg += incr) {
      const tick = {
        deg: deg,
        tickStyle: {
          height: size + 10,
          left: size - 1,
          top: size + 2,
          transform: "rotate(" + deg + "deg)",
          transformOrigin: "top"
        }
      };
      ticks.push(tick);
    }
    return ticks;
  };

  dcpy = o => {
    return JSON.parse(JSON.stringify(o));
  };

  render() {
    let kStyle = {
      width: this.props.size,
      height: this.props.size
    };
    let iStyle = this.dcpy(kStyle);
    let oStyle = this.dcpy(kStyle);
    oStyle.margin = this.margin;
    if (this.props.color) {
      oStyle.backgroundImage =
        "radial-gradient(100% 70%,hsl(210, " +
        this.currentDeg +
        "%, " +
        this.currentDeg / 5 +
        "%),hsl(" +
        Math.random() * 100 +
        ",20%," +
        this.currentDeg / 36 +
        "%))";
    }
    iStyle.transform = "rotate(" + this.state.deg + "deg)";

    return (

          {this.props.numTicks
            ? this.renderTicks().map((tick, i) => (
                <div
                  key={i}
                  className={
                    "tick" + (tick.deg <= this.currentDeg ? " active" : "")
                  }
                  style={tick.tickStyle}
                />
              ))
            : null}

    );
  }
}

and the stylesheet:

.knob {
  touch-action: manipulation;
  pointer-events: auto;
  display: flex;
  position: relative;
}
.knob .ticks {
  position: absolute;
}
.knob .ticks .tick {
  position: absolute;
  background: black;
  box-shadow: inset 0 0 0 0 black;
  width: 3px;
  transition: box-shadow 0.5s;
}
.knob .ticks .tick.active {
  box-shadow: inset 0 0 5px 2px #509eec, 0 0 0 1px #369;
}
.knob.outer {
  border-radius: 50%;
  border: 1px solid #222;
  border-bottom: 5px solid #222;
  background: radial-gradient(closest-side, #666 6%, #333 90%);
  box-shadow: 0 5px 15px 2px black, 0 0 5px 3px black, 0 0 0 12px #444;
}
.knob.inner {
  border-radius: 50%;
}
.knob.inner .grip {
  position: absolute;
  width: 5%;
  height: 5%;
  bottom: 2%;
  left: 50%;
  transform: translateX(-50%);
  border-radius: 50%;
  background: #509eec;
  box-shadow: 0 0 3px 1px black;
}


问:
Browserlist config do not include Map polyfill
As I understand Browserlist tool is automatically adds needed polyfills if older browser support required. I'm trying to run ES6 js code in old Android Chrome Webview v.30 but got error:

Uncaught ReferenceError: Map is not defined", source: http://localhost/js/chunk-vendors.ed003893.js

My .browserslistrc set to:

Chrome > 20

Running npx browserslist shows that in includes chrome from 21 version and above. But after building production and running in WebView I got the same error that Map is not defined. Do I need manually add ES6 polyfill?

P.s. I'm using Vuejs 2

答:
Found solution by adding es.map polyfill to babel.config.js file:</p>

```<code>  presets: [
    ['@vue/cli-plugin-babel/preset', {
      polyfills: [
        'es.map',
      ],
    }],
  ],
}```

</code>```

Body:
Found solution by adding es.map polyfill to babel.config.js file:

  presets: [
    ['@vue/cli-plugin-babel/preset', {
      polyfills: [
        'es.map',
      ],
    }],
  ],
}```


问:
DataTables JSON Api escape content
I got some data that I'm pulling from JSON API endpoint, one of the data records has object property called requestor. Here is what I mean :

```<code>data looks like so -> [{requestor: "First Lastname <email@email.com>", some_other: 'prop'}, {requestor: "Lastname first <email2@email.com>", some_other: 'prop'}...{requestor n}]
</code>```

The problem with this is that when it renders the table column content it renders it like so :

As a result only First Lastname shows up for the column content on the screen.

Is there a way
I can 'escape' these < > or do something so this is treated like a text and not like HTML tag?

Datatables does offer render function callback, where I can return anything, but what do I return for this to be treated like a text?

Update per first edit below:

I can't want to replace < and > I need to print this into the table column First Lastname <email@email.com>

答:
A simple regex in render worked for me. Here is the code:</p>

```<code>$('#dtable').DataTable({
    data: [{requestor: "First Lastname <email@email.com>", some_other: 'prop'}, {requestor: "Lastname first <email2@email.com>", some_other: 'prop'}],
    columns: [
      {
        data: 'requestor',
        render: data => data.replace(/[<]/g, '<').replace(/[>]/g, '>')
      },
      {data: 'some_other'}
    ],
})
</code>```

Title: DataTables JSON Api escape content

Body:
I got some data that I'm pulling from JSON API endpoint, one of the data records has object property called requestor. Here is what I mean :

data looks like so -> [{requestor: "First Lastname <email@email.com>", some_other: 'prop'}, {requestor: "Lastname first <email2@email.com>", some_other: 'prop'}...{requestor n}]

The problem with this is that when it renders the table column content it renders it like so :

As a result only First Lastname shows up for the column content on the screen.

Is there a way
I can 'escape' these < > or do something so this is treated like a text and not like HTML tag?

Datatables does offer render function callback, where I can return anything, but what do I return for this to be treated like a text?

Update per first edit below:

I can't want to replace < and > I need to print this into the table column First Lastname <email@email.com>

Body:
A simple regex in render worked for me. Here is the code:

$('#dtable').DataTable({
    data: [{requestor: "First Lastname <email@email.com>", some_other: 'prop'}, {requestor: "Lastname first <email2@email.com>", some_other: 'prop'}],
    columns: [
      {
        data: 'requestor',
        render: data => data.replace(/[<]/g, '&lt;').replace(/[>]/g, '&gt;')
      },
      {data: 'some_other'}
    ],
})


问:
Debugger shows null value despite having value in Firebase Database
I was trying to send a value through intent, but my app was getting crashed. So, I try to check the value in the debugger and it is showing null. Here is the image.

As you can see that it shows userId = "null" and profilephotoURl ="null". Why is this happening?

And here is the image of the Database.

Here is the Code

ProfileInfo.class

```<code>public class ProfileInfo {

String userName, profilePhotoUrl, phoneNumber, userId;

public ProfileInfo() {}

public ProfileInfo(String userName, String profilePhotoUrl, String phoneNumber, String userId) {
    this.userName = userName;
    this.profilePhotoUrl = profilePhotoUrl;
    this.phoneNumber = phoneNumber;
    this.userId = userId;
}

public ProfileInfo(String userName, String phoneNumber) {
    this.userName = userName;
    this.phoneNumber = phoneNumber;
}

public String getUserId() {
    return userId;
}

public String getPhoneNumber() {
    return phoneNumber;
}

public String getUserName() {
    return userName;
}

public String getProfilePhotoUrl() {
    return profilePhotoUrl;
}
</code>```

UserAdapter.class

```<code>public class UsersAdapter extends RecyclerView.Adapter<UsersAdapter.ViewHolder> {

    private ArrayList<ProfileInfo> minfo;
    public static final String USER_ID = "userid";
    Context context;

    public UsersAdapter(Context context, ArrayList<ProfileInfo> minfo) {
        this.context = context;
        this.minfo = minfo;
    }

    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {

        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.user_item, parent, false);
        RecyclerView.LayoutParams lp = new RecyclerView.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.WRAP_CONTENT);
        view.setLayoutParams(lp);

        return new ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull final ViewHolder holder, int position) {
        final ProfileInfo profileInfo = minfo.get(position);
        holder.username.setText(profileInfo.getUserName());
        holder.phoneNumber.setText(profileInfo.getPhoneNumber());
        holder.id.setText(profileInfo.getUserId());
        holder.itemView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(context, MessageLayout.class);
                intent.putExtra(USER_ID, profileInfo.getUserId());
                Log.d("UserID:", profileInfo.getUserId());
                context.startActivity(intent);
            }
        });
    }

    @Override
    public int getItemCount() {
        return minfo.size();
    }

    static class ViewHolder extends RecyclerView.ViewHolder {

        TextView username;
        TextView phoneNumber, id;
        CircleImageView profileImage;
        RelativeLayout relativeLayout;

        ViewHolder(@NonNull View itemView) {
            super(itemView);
            username = itemView.findViewById(R.id.user);
            phoneNumber = itemView.findViewById(R.id.phone);
            id = itemView.findViewById(R.id.id);
            profileImage = itemView.findViewById(R.id.circleProfileImage);
            relativeLayout = itemView.findViewById(R.id.relativeLayout);

        }
    }
}
</code>```

MessageLayout.class

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

    FirebaseUser currentUser;
    DatabaseReference db, chatDb;
    EditText message;
    ImageButton sendMessage;
    TextView username;
    CircleImageView profileImage;
    String recieverId, messageText;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_message_layout);

        message = findViewById(R.id.editTextMessage);
        sendMessage = findViewById(R.id.sendMessage);
        username = findViewById(R.id.displayUsername);
        profileImage = findViewById(R.id.circledp);
        currentUser = FirebaseAuth.getInstance().getCurrentUser();

        Intent intent = getIntent();
        recieverId = intent.getStringExtra(UsersAdapter.USER_ID);

        db = FirebaseDatabase.getInstance().getReference().child("UserInfo").child(recieverId);
        chatDb = FirebaseDatabase.getInstance().getReference().child("Chats");
        db.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                ProfileInfo info = dataSnapshot.getValue(ProfileInfo.class);

                username.setText(info.getUserName());
                Glide.with(MessageLayout.this).load(info.getProfilePhotoUrl()).into(profileImage);
            }

            @Override
            public void onCancelled(@NonNull DatabaseError databaseError) {

            }
        });

    }
</code>```

答: In you model class, there should be a single parameterized constructor.Try commenting the second parameterized constructor and see if that helps.</p>

Body:
I was trying to send a value through intent, but my app was getting crashed. So, I try to check the value in the debugger and it is showing null. Here is the image.

As you can see that it shows userId = "null" and profilephotoURl ="null". Why is this happening?

And here is the image of the Database.

Here is the Code

ProfileInfo.class

public class ProfileInfo {

String userName, profilePhotoUrl, phoneNumber, userId;

public ProfileInfo() {}

public ProfileInfo(String userName, String profilePhotoUrl, String phoneNumber, String userId) {
    this.userName = userName;
    this.profilePhotoUrl = profilePhotoUrl;
    this.phoneNumber = phoneNumber;
    this.userId = userId;
}

public ProfileInfo(String userName, String phoneNumber) {
    this.userName = userName;
    this.phoneNumber = phoneNumber;
}

public String getUserId() {
    return userId;
}

public String getPhoneNumber() {
    return phoneNumber;
}

public String getUserName() {
    return userName;
}

public String getProfilePhotoUrl() {
    return profilePhotoUrl;
}

UserAdapter.class

public class UsersAdapter extends RecyclerView.Adapter<UsersAdapter.ViewHolder> {

    private ArrayList<ProfileInfo> minfo;
    public static final String USER_ID = "userid";
    Context context;

    public UsersAdapter(Context context, ArrayList<ProfileInfo> minfo) {
        this.context = context;
        this.minfo = minfo;
    }

    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {

        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.user_item, parent, false);
        RecyclerView.LayoutParams lp = new RecyclerView.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.WRAP_CONTENT);
        view.setLayoutParams(lp);

        return new ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull final ViewHolder holder, int position) {
        final ProfileInfo profileInfo = minfo.get(position);
        holder.username.setText(profileInfo.getUserName());
        holder.phoneNumber.setText(profileInfo.getPhoneNumber());
        holder.id.setText(profileInfo.getUserId());
        holder.itemView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(context, MessageLayout.class);
                intent.putExtra(USER_ID, profileInfo.getUserId());
                Log.d("UserID:", profileInfo.getUserId());
                context.startActivity(intent);
            }
        });
    }

    @Override
    public int getItemCount() {
        return minfo.size();
    }

    static class ViewHolder extends RecyclerView.ViewHolder {

        TextView username;
        TextView phoneNumber, id;
        CircleImageView profileImage;
        RelativeLayout relativeLayout;

        ViewHolder(@NonNull View itemView) {
            super(itemView);
            username = itemView.findViewById(R.id.user);
            phoneNumber = itemView.findViewById(R.id.phone);
            id = itemView.findViewById(R.id.id);
            profileImage = itemView.findViewById(R.id.circleProfileImage);
            relativeLayout = itemView.findViewById(R.id.relativeLayout);

        }
    }
}

MessageLayout.class

public class MessageLayout extends AppCompatActivity {

    FirebaseUser currentUser;
    DatabaseReference db, chatDb;
    EditText message;
    ImageButton sendMessage;
    TextView username;
    CircleImageView profileImage;
    String recieverId, messageText;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_message_layout);

        message = findViewById(R.id.editTextMessage);
        sendMessage = findViewById(R.id.sendMessage);
        username = findViewById(R.id.displayUsername);
        profileImage = findViewById(R.id.circledp);
        currentUser = FirebaseAuth.getInstance().getCurrentUser();

        Intent intent = getIntent();
        recieverId = intent.getStringExtra(UsersAdapter.USER_ID);

        db = FirebaseDatabase.getInstance().getReference().child("UserInfo").child(recieverId);
        chatDb = FirebaseDatabase.getInstance().getReference().child("Chats");
        db.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                ProfileInfo info = dataSnapshot.getValue(ProfileInfo.class);

                username.setText(info.getUserName());
                Glide.with(MessageLayout.this).load(info.getProfilePhotoUrl()).into(profileImage);
            }

            @Override
            public void onCancelled(@NonNull DatabaseError databaseError) {

            }
        });

    }


问:
AIR NativeProcess standardInput not connecting to app
I'm writing an AIR app that launches a C# console application and they need to communicate.  I'd like to use standard input/standard output for this, however I can't seem to get it to work.

When the C# app gets input from standard input it's supposed to send it back via standard output, and if it receives "exit" then it quits.  I can test this from the command line and it works correctly.  When I send a string from AIR, I get no response from the C# app.

I'm sending an argument when I launch the C# app, and I do get a response from that, so my AIR app is at least able to receive messages from standard output, it's just standard input that is not working.  When I send a message from AIR via standardInput I get a progress event with bytesLoaded = 3 when I send the keycode, and bytesLoaded = 5 when I send the "exit" command.

Here is the C# code:

```<code>static void Main(string[] args)
{
    if (args.Length > 0)
    {
        Console.WriteLine(args[0]);
    }
    while (true)
    {
        string incoming = Console.ReadLine();
        string outgoing = "received: " + incoming;
        Console.WriteLine(outgoing);
        if (incoming == "exit")
            return;
    }
}
</code>```

And here is the AS3 code:

```<code>private function init(e:Event=null):void {
    this.removeEventListener(Event.ADDED_TO_STAGE, init);
    NativeApplication.nativeApplication.addEventListener(Event.EXITING, onAppClose);

    var info:NativeProcessStartupInfo = new NativeProcessStartupInfo();
    var file:File = File.applicationDirectory.resolvePath("test.exe");
    info.executable = file;

    process = new NativeProcess();
    info.arguments.push("native process started");
    process.addEventListener(ProgressEvent.STANDARD_OUTPUT_DATA, onOutputData);
    process.addEventListener(ProgressEvent.STANDARD_ERROR_DATA, onErrorData);
    process.addEventListener(ProgressEvent.STANDARD_INPUT_PROGRESS, onInputProgress);
    process.addEventListener(Event.STANDARD_OUTPUT_CLOSE, onOutputClose);
    process.addEventListener(Event.STANDARD_ERROR_CLOSE, onErrorClose);
    process.addEventListener(IOErrorEvent.STANDARD_ERROR_IO_ERROR, onIOError);
    process.addEventListener(IOErrorEvent.STANDARD_INPUT_IO_ERROR, onIOError);
    process.addEventListener(IOErrorEvent.STANDARD_OUTPUT_IO_ERROR, onIOError);
    stage.addEventListener(KeyboardEvent.KEY_UP, onKeyUp);

    process.start(info);
}

private function onKeyUp(e:KeyboardEvent):void {
    if (e.keyCode == Keyboard.ESCAPE)
        process.standardInput.writeUTFBytes("exit\n");
    else {
        var msg:String = e.keyCode + "\n";
        process.standardInput.writeUTFBytes(msg);
    }
}

private function onOutputData(e:ProgressEvent):void {
    var data:String = process.standardOutput.readUTFBytes(process.standardOutput.bytesAvailable);
    trace("Got: ", data);
}
</code>```

答:
In case anyone else besides me still use Adobe AIR with C# console apps, here's a solution to the problem:

Just like @tom-makin points out in the linked answer, you need to create another console app that runs on .NET 3.5, which then opens your newer .NET console app and passes input to it. Here's my take on such an app:

```<code>using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Threading;

namespace StdInPiper
{
    class Program
    {
        static void Main(string[] args)
        {
            // Remove the first arg from args, containing the newer .NET exePath.
            string exePath = args[0];
            var tempArgs = new List<string>(args);
            tempArgs.RemoveAt(0);
            string argsLine = "";
            foreach (string arg in tempArgs)
            {
                argsLine = argsLine + " " + arg;
            }
            argsLine = argsLine.Trim();

            var process = new Process();
            process.EnableRaisingEvents = true;

            process.StartInfo.UseShellExecute = false;
            process.StartInfo.RedirectStandardOutput = true;
            process.StartInfo.RedirectStandardError = true;
            process.StartInfo.RedirectStandardInput = true;
            process.StartInfo.Arguments = argsLine;
            process.StartInfo.FileName = exePath;

            process.OutputDataReceived += (sender, eventArgs) =>
            {
                Console.Write(eventArgs.Data);
            };

            process.ErrorDataReceived += (sender, eventArgs) =>
            {
                Console.Error.Write(eventArgs.Data);
            };

            process.Exited += (sender, eventArgs) =>
            {
                process.CancelOutputRead();
                process.CancelErrorRead();
                Environment.Exit(Environment.ExitCode);
            };

            process.Start();
            process.BeginOutputReadLine();
            process.BeginErrorReadLine();

            while (true)
            {
                Thread.Sleep(20);
                string line = Console.ReadLine();
                if (line != null)
                {
                    process.StandardInput.WriteLine(line);
                }
            }
        }
    }
}
</code>```

Body:
I'm writing an AIR app that launches a C# console application and they need to communicate.  I'd like to use standard input/standard output for this, however I can't seem to get it to work.

When the C# app gets input from standard input it's supposed to send it back via standard output, and if it receives "exit" then it quits.  I can test this from the command line and it works correctly.  When I send a string from AIR, I get no response from the C# app.

I'm sending an argument when I launch the C# app, and I do get a response from that, so my AIR app is at least able to receive messages from standard output, it's just standard input that is not working.  When I send a message from AIR via standardInput I get a progress event with bytesLoaded = 3 when I send the keycode, and bytesLoaded = 5 when I send the "exit" command.

Here is the C# code:

static void Main(string[] args)
{
    if (args.Length > 0)
    {
        Console.WriteLine(args[0]);
    }
    while (true)
    {
        string incoming = Console.ReadLine();
        string outgoing = "received: " + incoming;
        Console.WriteLine(outgoing);
        if (incoming == "exit")
            return;
    }
}

And here is the AS3 code:

private function init(e:Event=null):void {
    this.removeEventListener(Event.ADDED_TO_STAGE, init);
    NativeApplication.nativeApplication.addEventListener(Event.EXITING, onAppClose);

    var info:NativeProcessStartupInfo = new NativeProcessStartupInfo();
    var file:File = File.applicationDirectory.resolvePath("test.exe");
    info.executable = file;

    process = new NativeProcess();
    info.arguments.push("native process started");
    process.addEventListener(ProgressEvent.STANDARD_OUTPUT_DATA, onOutputData);
    process.addEventListener(ProgressEvent.STANDARD_ERROR_DATA, onErrorData);
    process.addEventListener(ProgressEvent.STANDARD_INPUT_PROGRESS, onInputProgress);
    process.addEventListener(Event.STANDARD_OUTPUT_CLOSE, onOutputClose);
    process.addEventListener(Event.STANDARD_ERROR_CLOSE, onErrorClose);
    process.addEventListener(IOErrorEvent.STANDARD_ERROR_IO_ERROR, onIOError);
    process.addEventListener(IOErrorEvent.STANDARD_INPUT_IO_ERROR, onIOError);
    process.addEventListener(IOErrorEvent.STANDARD_OUTPUT_IO_ERROR, onIOError);
    stage.addEventListener(KeyboardEvent.KEY_UP, onKeyUp);

    process.start(info);
}

private function onKeyUp(e:KeyboardEvent):void {
    if (e.keyCode == Keyboard.ESCAPE)
        process.standardInput.writeUTFBytes("exit\n");
    else {
        var msg:String = e.keyCode + "\n";
        process.standardInput.writeUTFBytes(msg);
    }
}

private function onOutputData(e:ProgressEvent):void {
    var data:String = process.standardOutput.readUTFBytes(process.standardOutput.bytesAvailable);
    trace("Got: ", data);
}

Body:
In case anyone else besides me still use Adobe AIR with C# console apps, here's a solution to the problem:

Just like @tom-makin points out in the linked answer, you need to create another console app that runs on .NET 3.5, which then opens your newer .NET console app and passes input to it. Here's my take on such an app:

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Threading;

namespace StdInPiper
{
    class Program
    {
        static void Main(string[] args)
        {
            // Remove the first arg from args, containing the newer .NET exePath.
            string exePath = args[0];
            var tempArgs = new List<string>(args);
            tempArgs.RemoveAt(0);
            string argsLine = "";
            foreach (string arg in tempArgs)
            {
                argsLine = argsLine + " " + arg;
            }
            argsLine = argsLine.Trim();

            var process = new Process();
            process.EnableRaisingEvents = true;

            process.StartInfo.UseShellExecute = false;
            process.StartInfo.RedirectStandardOutput = true;
            process.StartInfo.RedirectStandardError = true;
            process.StartInfo.RedirectStandardInput = true;
            process.StartInfo.Arguments = argsLine;
            process.StartInfo.FileName = exePath;

            process.OutputDataReceived += (sender, eventArgs) =>
            {
                Console.Write(eventArgs.Data);
            };

            process.ErrorDataReceived += (sender, eventArgs) =>
            {
                Console.Error.Write(eventArgs.Data);
            };

            process.Exited += (sender, eventArgs) =>
            {
                process.CancelOutputRead();
                process.CancelErrorRead();
                Environment.Exit(Environment.ExitCode);
            };

            process.Start();
            process.BeginOutputReadLine();
            process.BeginErrorReadLine();

            while (true)
            {
                Thread.Sleep(20);
                string line = Console.ReadLine();
                if (line != null)
                {
                    process.StandardInput.WriteLine(line);
                }
            }
        }
    }
}


问:
How to redirect from one domain to another in haproxy
We have setup LB using haproxy for two domain.

How to use haproxy redirect or http-request redirect to redirect one domain to another which cotain sub domain.

For example:

```<code>aaa.one.ccc.com  -> aaa.two.ccc.com
</code>```

Thanks!

答:
There is an oneline solution in haproxy.cfg.

301 redirection from aaa.one.ccc.com  -> aaa.two.ccc.com

```<code>http-request redirect prefix http://aaa.two.ccc.com code 301 if { hdr_dom(host) -i aaa.one.ccc.com }
</code>```

Note, this can't be in defaults section, only in frontend, backend or listen.

Body:
We have setup LB using haproxy for two domain.

How to use haproxy redirect or http-request redirect to redirect one domain to another which cotain sub domain.

For example:

aaa.one.ccc.com  -> aaa.two.ccc.com

Thanks!

Body:
There is an oneline solution in haproxy.cfg.

301 redirection from aaa.one.ccc.com  -> aaa.two.ccc.com

http-request redirect prefix http://aaa.two.ccc.com code 301 if { hdr_dom(host) -i aaa.one.ccc.com }

Note, this can't be in defaults section, only in frontend, backend or listen.


问:
how to convert Xcode 3.2.5 code to Xcode 4
How to convert the Xcode 3.2.5 version code to the Xcode 4?</p>

答:
You shouldn't need to convert any code. Xcode is a development environment, not a compiler.

(Of course, the word "shouldn't" has been the enemy of programmers for centuries.)

ContentLicense: CC BY-SA 2.5


问:
Use inner join with C# SQL Server (Retrieving data from multiple table using SQL query and inner join in C# ADO.NET)
Am trying to retrieve data from two different tables into a datatable and to assign into textboxes in C# WinForms. Though I succeeded with this query when I tried it in SQL Server but implementing it on WinForms is what I don't know.
This is what have tried in my code:

```<code> string supplier_id = dataGridView1.CurrentRow.Cells[1].Value.ToString();
                    SqlDataAdapter cmd = new SqlDataAdapter("select New_Supplier.Supplier_Name, New_Supplier.Address, New_Supplier.City, New_Supplier.Contact_No ,Purchase_Entry.Balance from New_Supplier,Purchase_Entry where New_Supplier.'" + supplier_id + "' = Purchase_Entry.'" + supplier_id + "' ", con);
                    DataTable dt = new DataTable(); cmd.Fill(dt);
                    Purchase_Entry.Instance.txtsuppliername.Text = dt.Rows[0][0].ToString();
                    Purchase_Entry.Instance.txtaddress.Text = dt.Rows[0][1].ToString();
                    Purchase_Entry.Instance.txtcity.Text = dt.Rows[0][2].ToString();
                    Purchase_Entry.Instance.txtcontactno.Text = dt.Rows[0][3].ToString();
                    Purchase_Entry.Instance.lblbalance.Text = dt.Rows[0][4].ToString();

</code>```

Tried this also:

```<code> string supplier_id = dataGridView1.CurrentRow.Cells[1].Value.ToString(); MessageBox.Show(supplier_id);
                    SqlDataAdapter cmd = new SqlDataAdapter($"select New_Supplier.Supplier_Name, New_Supplier.Address, New_Supplier.City, New_Supplier.Contact_No ,Purchase_Entry.Balance from New_Supplier,Purchase_Entry where New_Supplier.{supplier_id} = Purchase_Entry.{supplier_id} ", con);
                    DataTable dt = new DataTable(); cmd.Fill(dt);
                    Purchase_Entry.Instance.txtsuppliername.Text = dt.Rows[0][0].ToString();
                    Purchase_Entry.Instance.txtaddress.Text = dt.Rows[0][1].ToString();
                    Purchase_Entry.Instance.txtcity.Text = dt.Rows[0][2].ToString();
                    Purchase_Entry.Instance.txtcontactno.Text = dt.Rows[0][3].ToString();
                    Purchase_Entry.Instance.lblbalance.Text = dt.Rows[0][4].ToString();
</code>```

But am having error concatenating the query when fetching data
Tried this in SQL Server and it works

```<code>select New_Supplier.Supplier_Name, New_Supplier.Address, New_Supplier.City, New_Supplier.Contact_No ,Purchase_Entry.Balance from New_Supplier,Purchase_Entry where New_Supplier.supplier_id = Purchase_Entry.supplier_id
</code>```

and it returned me back what I want:

答:
The query could be like

```<code>    select supplier.Supplier_Name, supplier.Address, supplier.City,
           supplier.Contact_No, purchase.Balance
    from New_Supplier supplier
    join Purchase_Entry purchase on supplier.supplier_id = purchase.supplier_id
    where purchase.supplier_id = @SupplierId
</code>```

I suggest to use parameters in order to avoid Sql Injection

```<code>cmd.SelectCommand.Parameters.Add("@SupplierId", SqlDbType.Int).Value = supplier_id ;
</code>```

You can use also ORM to map the query to an object, like dapper

because mapping with datatable with array is a little huge. If you change the query and the order of your select, could display the wrong data

Body:
Am trying to retrieve data from two different tables into a datatable and to assign into textboxes in C# WinForms. Though I succeeded with this query when I tried it in SQL Server but implementing it on WinForms is what I don't know.
This is what have tried in my code:

 string supplier_id = dataGridView1.CurrentRow.Cells[1].Value.ToString();
                    SqlDataAdapter cmd = new SqlDataAdapter("select New_Supplier.Supplier_Name, New_Supplier.Address, New_Supplier.City, New_Supplier.Contact_No ,Purchase_Entry.Balance from New_Supplier,Purchase_Entry where New_Supplier.'" + supplier_id + "' = Purchase_Entry.'" + supplier_id + "' ", con);
                    DataTable dt = new DataTable(); cmd.Fill(dt);
                    Purchase_Entry.Instance.txtsuppliername.Text = dt.Rows[0][0].ToString();
                    Purchase_Entry.Instance.txtaddress.Text = dt.Rows[0][1].ToString();
                    Purchase_Entry.Instance.txtcity.Text = dt.Rows[0][2].ToString();
                    Purchase_Entry.Instance.txtcontactno.Text = dt.Rows[0][3].ToString();
                    Purchase_Entry.Instance.lblbalance.Text = dt.Rows[0][4].ToString();

Tried this also:

 string supplier_id = dataGridView1.CurrentRow.Cells[1].Value.ToString(); MessageBox.Show(supplier_id);
                    SqlDataAdapter cmd = new SqlDataAdapter($"select New_Supplier.Supplier_Name, New_Supplier.Address, New_Supplier.City, New_Supplier.Contact_No ,Purchase_Entry.Balance from New_Supplier,Purchase_Entry where New_Supplier.{supplier_id} = Purchase_Entry.{supplier_id} ", con);
                    DataTable dt = new DataTable(); cmd.Fill(dt);
                    Purchase_Entry.Instance.txtsuppliername.Text = dt.Rows[0][0].ToString();
                    Purchase_Entry.Instance.txtaddress.Text = dt.Rows[0][1].ToString();
                    Purchase_Entry.Instance.txtcity.Text = dt.Rows[0][2].ToString();
                    Purchase_Entry.Instance.txtcontactno.Text = dt.Rows[0][3].ToString();
                    Purchase_Entry.Instance.lblbalance.Text = dt.Rows[0][4].ToString();

But am having error concatenating the query when fetching data
Tried this in SQL Server and it works

select New_Supplier.Supplier_Name, New_Supplier.Address, New_Supplier.City, New_Supplier.Contact_No ,Purchase_Entry.Balance from New_Supplier,Purchase_Entry where New_Supplier.supplier_id = Purchase_Entry.supplier_id

and it returned me back what I want:

Body:
The query could be like

    select supplier.Supplier_Name, supplier.Address, supplier.City,
           supplier.Contact_No, purchase.Balance
    from New_Supplier supplier
    join Purchase_Entry purchase on supplier.supplier_id = purchase.supplier_id
    where purchase.supplier_id = @SupplierId

I suggest to use parameters in order to avoid Sql Injection

cmd.SelectCommand.Parameters.Add("@SupplierId", SqlDbType.Int).Value = supplier_id ;

You can use also ORM to map the query to an object, like dapper

because mapping with datatable with array is a little huge. If you change the query and the order of your select, could display the wrong data


问:
how to actually hide Tab from TabPane with JavaFX
previously I was working on Java Swing and now I'm trying to work with JavaFX. My Java Swing code last time:

```<code>//These line of code is to call method that declared in ContentPage.java
contentPage.adminFeatureEnabled(adminEnabled);
contentPage.managerFeatureEnabled(managerEnabled);
</code>```

and in my ContentPage.java

```<code>//By default, all feature (or tab) are enabled.
//This method is to remove register account if the user login into the system is manager and staff
public void adminFeatureEnabled(boolean a) {
    if (!a) {
        tabPane.removeTabAt(tabPane.indexOfComponent(registerAccount));
    }
}
//This method is to remove register account and purchase order if the user who log into the system is staff
public void managerFeatureEnabled(boolean a) {
    if(!a) {
        tabPane.removeTabAt(tabPane.indexOfComponent(purchaseOrder));
    }
}
</code>```

and in my code:

```<code>if (role.equals("admin")){
     contentPage.contentFrame.setTitle("Menu - Admin!");
     contentPage.disUser.setEditable(true);
     contentPage.chgRoles.setEnabled(true);
} else if(role.equals("manager")){
     contentPage.contentFrame.setTitle("Menu - Manager!");
     contentPage.chgRoles.setSelectedItem("manager");
     adminEnabled = false;
}else if (role.equals("staff")){
     contentPage.contentFrame.setTitle("Menu - Staff!");
     contentPage.chgRoles.setSelectedItem("staff");
     adminEnabled = false;
     managerEnabled = false;
}
</code>```

The code above will perform like this:

when the user login with admin account, all the feature (Tab) enabled

when the user login as manager, some feature (tab) will be hide

My current problem now:

I wanted the same feature as above in JavaFX but I don't know how as none of the method works as I wanted.

anyone can help me with this?

答:
It's been so long since the question asked, but this maybe helpful for someone.

You can try something like this.

you have a tabPane with three tabs tabOne, tabTwo and tabThree.

position index of tabs

```<code>tabOne - 0
tabTwo - 1
tabThree - 2
</code>```

to hide tabTwo, you can use remove function and again reappear you can use set function.

to remove tab

```<code>tabPane.getTabs().remove(tabTwo);
</code>```

set again with the relevant index to display at the correct location.

```<code>tabPane.getTabs().set(1, tabTwo);
</code>```

Body:
previously I was working on Java Swing and now I'm trying to work with JavaFX. My Java Swing code last time:

//These line of code is to call method that declared in ContentPage.java
contentPage.adminFeatureEnabled(adminEnabled);
contentPage.managerFeatureEnabled(managerEnabled);

and in my ContentPage.java

//By default, all feature (or tab) are enabled.
//This method is to remove register account if the user login into the system is manager and staff
public void adminFeatureEnabled(boolean a) {
    if (!a) {
        tabPane.removeTabAt(tabPane.indexOfComponent(registerAccount));
    }
}
//This method is to remove register account and purchase order if the user who log into the system is staff
public void managerFeatureEnabled(boolean a) {
    if(!a) {
        tabPane.removeTabAt(tabPane.indexOfComponent(purchaseOrder));
    }
}

and in my code:

if (role.equals("admin")){
     contentPage.contentFrame.setTitle("Menu - Admin!");
     contentPage.disUser.setEditable(true);
     contentPage.chgRoles.setEnabled(true);
} else if(role.equals("manager")){
     contentPage.contentFrame.setTitle("Menu - Manager!");
     contentPage.chgRoles.setSelectedItem("manager");
     adminEnabled = false;
}else if (role.equals("staff")){
     contentPage.contentFrame.setTitle("Menu - Staff!");
     contentPage.chgRoles.setSelectedItem("staff");
     adminEnabled = false;
     managerEnabled = false;
}

The code above will perform like this:

when the user login with admin account, all the feature (Tab) enabled

when the user login as manager, some feature (tab) will be hide

My current problem now:

I wanted the same feature as above in JavaFX but I don't know how as none of the method works as I wanted.

anyone can help me with this?

Body:
It's been so long since the question asked, but this maybe helpful for someone.

You can try something like this.

you have a tabPane with three tabs tabOne, tabTwo and tabThree.

position index of tabs

tabOne - 0
tabTwo - 1
tabThree - 2

to hide tabTwo, you can use remove function and again reappear you can use set function.

to remove tab

tabPane.getTabs().remove(tabTwo);

set again with the relevant index to display at the correct location.

tabPane.getTabs().set(1, tabTwo);


问:
IoT Device Streaming is not connecting
I am exploring the Azure IoT Hub Device Streams functionality.

I have a C# client connected to the IoT Hub (located in Central US) and active.

The client is using the following algorithm to wait to an incoming connection (using SDK version 1.29.0-preview-004):

var buffer = new byte[1024];

using var cancellationTokenSource = new CancellationTokenSource(TimeSpan.FromMinutes(5));

DeviceStreamRequest streamRequest = await deviceClient.WaitForDeviceStreamRequestAsync(cancellationTokenSource.Token);

if (streamRequest is null)
    return;

```

<p>On the server-side, I have a Azure App Service that is called on a specific endpoint. It retrieves the IoT Hub's connection string </p>

<pre class="lang-cs prettyprint-override"><code>ServiceClient serviceClient = ServiceClient.CreateFromConnectionString(Constants.IoTHub.ConnectionString, TransportType.Amqp);

DeviceStreamRequest deviceStreamRequest = new DeviceStreamRequest("portal");

DeviceStreamResponse result = await serviceClient.CreateStreamAsync(serialNumber, deviceStreamRequest);
</code>```

I am not able to establish the connection. The CreateStreamAsync call times out after 1 minute and the client side never seems to get out of the WaitForDeviceStreamRequestAsync call.

I have followed the troubleshooting guide to find out what was is going on but I do not get anything:

Question

Why am I missing that would prevent the IoT Device Streaming from connecting?

答:
Note, that the Azure IoT Hub Device Streams feature is still in the public preview (over one year).
You are using the SDKs 1.29.0-preview-004 on device side and 1.27.0-preview-004 on the service side and sample DeviceStreamingSample from the azure-iot-samples-csharp-master package.

The device streams feature using for handshaking process between the service and device, the same communication concept like for invoking a device method. This handshaking phase can be easy tested with a REST POST request.

For demonstration purpose, I will use my IoT Hub Tester, where the Device Streams feature has been implemented, see more detail in the section Appendix A2.

Step 1. Run the DeviceClientStreamingSample program for your device. You should used the Transport.Amqp. Note, that the others failed in my test.

Step 2. Use the REST client tool for generating a POST request. The following url is for my test:

```<code>https://xxxxxxxxxxx.azure-devices.net/twins/device1/streams/teststream?api-version=2018-08-30-preview
</code>```

headers:

```<code>accept: application/json
iothub-streaming-response-timeout-in-seconds: 15
iothub-streaming-connect-timeout-in-seconds: 5
Authorization: sas-token
</code>```

payload:
   any or empty

The following screen snippet demonstrated when the POST has been sent to the device1:

and the following snippet shows stopping a program at the breakpoint after the WaitForDeviceStreamRequestAsync method:

The full handshake and streaming between the device and service (in this case my tester) is shown in the following screen snippet:

As I mentioned, the Azure IoT Hub Tester has implemented the Device Streams feature, the following screen snippet shows a stream buffer:

Note, that running the simulated device for TransportType.Mqtt doesn't working, the symptom is the same like yours, timeout. It looks like (based on the REST POST response), there is a bug for subscribing a device for the topic such as $iothub/streams/POST/#

However, when your device is using a direct MQTT protocol to the IoT Hub, everything is working well, see screen snippet from my tester, where the device1 is connected to the IoT Hub:

Once you have the Azure IoT Hub Tester on the screen, you can use it for testing a service SDK for streaming such as the following line from the SDK sample:

```<code>DeviceStreamResponse result = await _serviceClient.CreateStreamAsync(_deviceId, deviceStreamRequest).ConfigureAwait(false);
</code>```

and the tester will show a device1 streaming:

In conclusion, based on my above testing, you should have a successful streaming with the SDKs when the simulated device is configured for TransportType.Amqp protocol.

UPDATE:

In the case of using a REST client tool, you can see the response from the device handshaking in the headers:

This response is generated by the following line:

```<code>await _deviceClient.AcceptDeviceStreamRequestAsync(streamRequest, cancellationTokenSource.Token).ConfigureAwait(false);
</code>```

Based on the response headers such as

```<code>iothub-streaming-is-accepted
iothub-streaming-url
iothub-streaming-auth-token
</code>```

can be established a webSocket streaming communication between the device and service via the IoT Hub.
Note, that after this point, the simulated device will be failed in the case of using a REST client tool.

Title: IoT Device Streaming is not connecting

Body:
I am exploring the Azure IoT Hub Device Streams functionality.

I have a C# client connected to the IoT Hub (located in Central US) and active.

The client is using the following algorithm to wait to an incoming connection (using SDK version 1.29.0-preview-004):

var buffer = new byte[1024];

using var cancellationTokenSource = new CancellationTokenSource(TimeSpan.FromMinutes(5));

DeviceStreamRequest streamRequest = await deviceClient.WaitForDeviceStreamRequestAsync(cancellationTokenSource.Token);

if (streamRequest is null)
    return;

On the server-side, I have a Azure App Service that is called on a specific endpoint. It retrieves the IoT Hub's connection string

ServiceClient serviceClient = ServiceClient.CreateFromConnectionString(Constants.IoTHub.ConnectionString, TransportType.Amqp);

DeviceStreamRequest deviceStreamRequest = new DeviceStreamRequest("portal");

DeviceStreamResponse result = await serviceClient.CreateStreamAsync(serialNumber, deviceStreamRequest);

I am not able to establish the connection. The CreateStreamAsync call times out after 1 minute and the client side never seems to get out of the WaitForDeviceStreamRequestAsync call.

I have followed the troubleshooting guide to find out what was is going on but I do not get anything:

Question

Why am I missing that would prevent the IoT Device Streaming from connecting?

Body:
Note, that the Azure IoT Hub Device Streams feature is still in the public preview (over one year).
You are using the SDKs 1.29.0-preview-004 on device side and 1.27.0-preview-004 on the service side and sample DeviceStreamingSample from the azure-iot-samples-csharp-master package.

The device streams feature using for handshaking process between the service and device, the same communication concept like for invoking a device method. This handshaking phase can be easy tested with a REST POST request.

For demonstration purpose, I will use my IoT Hub Tester, where the Device Streams feature has been implemented, see more detail in the section Appendix A2.

Step 1. Run the DeviceClientStreamingSample program for your device. You should used the Transport.Amqp. Note, that the others failed in my test.

Step 2. Use the REST client tool for generating a POST request. The following url is for my test:

https://xxxxxxxxxxx.azure-devices.net/twins/device1/streams/teststream?api-version=2018-08-30-preview

headers:

accept: application/json
iothub-streaming-response-timeout-in-seconds: 15
iothub-streaming-connect-timeout-in-seconds: 5
Authorization: sas-token

payload:
   any or empty

The following screen snippet demonstrated when the POST has been sent to the device1:

and the following snippet shows stopping a program at the breakpoint after the WaitForDeviceStreamRequestAsync method:

The full handshake and streaming between the device and service (in this case my tester) is shown in the following screen snippet:

As I mentioned, the Azure IoT Hub Tester has implemented the Device Streams feature, the following screen snippet shows a stream buffer:

Note, that running the simulated device for TransportType.Mqtt doesn't working, the symptom is the same like yours, timeout. It looks like (based on the REST POST response), there is a bug for subscribing a device for the topic such as $iothub/streams/POST/#

However, when your device is using a direct MQTT protocol to the IoT Hub, everything is working well, see screen snippet from my tester, where the device1 is connected to the IoT Hub:

Once you have the Azure IoT Hub Tester on the screen, you can use it for testing a service SDK for streaming such as the following line from the SDK sample:

DeviceStreamResponse result = await _serviceClient.CreateStreamAsync(_deviceId, deviceStreamRequest).ConfigureAwait(false);

and the tester will show a device1 streaming:

In conclusion, based on my above testing, you should have a successful streaming with the SDKs when the simulated device is configured for TransportType.Amqp protocol.

UPDATE:

In the case of using a REST client tool, you can see the response from the device handshaking in the headers:

This response is generated by the following line:

await _deviceClient.AcceptDeviceStreamRequestAsync(streamRequest, cancellationTokenSource.Token).ConfigureAwait(false);

Based on the response headers such as

iothub-streaming-is-accepted
iothub-streaming-url
iothub-streaming-auth-token

can be established a webSocket streaming communication between the device and service via the IoT Hub.
Note, that after this point, the simulated device will be failed in the case of using a REST client tool.


问:
Make a ping function with QTcpSocket
I want to make a ping function with Qt (and don't like the QProcess execution system ping way).

Here's the demo code,

```<code>void SimmplePing(const QString& sAddress, int port=80)
{
    QTcpSocket messenger;
    messenger.connectToHost(sAddress, port);
    if (!messenger.waitForConnected(3000))
    {
        qDebug() << messenger.error();
    }
    else
    {
        qDebug() << "OK";
    }
}
void test()
{
    SimmplePing("182.34.19.222", 80);
}
</code>```

I test it with "192.168.0.1" (my router IP) and "www.baidu.com" both can work.

But I test it "182.34.19.222" failed with QAbstractSocket::SocketTimeoutError error message.

However, pinging it within system cmd can work properly. Couldn't figure out why.

答:
The main difference here is that the ping command as it's normally used, uses the ICMP protocol which doesn't use TCP for communication. Trying to connect to a host via websockets using TCP is handled in a different way. If the TCP socket of the host you're trying to connect to doesn't listen on the specified port, in this case port 80, you won't recieve an answer, which can lead to the behaviour you encountered.

(https://en.wikipedia.org/wiki/Internet_Control_Message_Protocol)

Title: Make a ping function with QTcpSocket

Body:
I want to make a ping function with Qt (and don't like the QProcess execution system ping way).

Here's the demo code,

void SimmplePing(const QString& sAddress, int port=80)
{
    QTcpSocket messenger;
    messenger.connectToHost(sAddress, port);
    if (!messenger.waitForConnected(3000))
    {
        qDebug() << messenger.error();
    }
    else
    {
        qDebug() << "OK";
    }
}
void test()
{
    SimmplePing("182.34.19.222", 80);
}

I test it with "192.168.0.1" (my router IP) and "www.baidu.com" both can work.

But I test it "182.34.19.222" failed with QAbstractSocket::SocketTimeoutError error message.

However, pinging it within system cmd can work properly. Couldn't figure out why.


问:
How to identify touch on a specific imageView from multiple imageViews in a UIScrollView?
I have multiple ImageViews in a UIScrollView and I want to identify the specific imageView on which I touched. So that I could do some actions. (for example, showing Alert with the image name).

I have seen some similar posts, but they did not have proper answer. And some answers were complex to me as I am pretty new to iPhone programming.

It would be great, If anybody helps with a simple example. :-)

my code is like this

```<code>- (void)viewDidLoad {

imgScrollView.userInteractionEnabled =YES;

// load all the images from our bundle and add them to the scroll view
NSUInteger i;
for (i = 1; i <= 5; i++)
{
    NSString *imageName = [NSString stringWithFormat:@"image%d.jpg", i];
    UIImage *image = [UIImage imageNamed:imageName];
    UIImageView *imageView = [[UIImageView alloc] initWithImage:image];

    // setup each frame to a default height and width
    CGRect rect = imageView.frame;
    rect.size.height = kHeight;
    rect.size.width = kWidth;
    imageView.frame = rect;
    imageView.tag = i;

    [imgScrollView addSubview:imageView];

    [imageView release];
}

[self layoutImages];

[super viewDidLoad];
}

     -(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
// WHAT CODE SHOULD I GIVE HERE ?????????? :-)

}
</code>```

答: You can use UIButton instead of image view. Assign tags for each button and then identify them using switch(...).</p>

Body:
I have multiple ImageViews in a UIScrollView and I want to identify the specific imageView on which I touched. So that I could do some actions. (for example, showing Alert with the image name).

I have seen some similar posts, but they did not have proper answer. And some answers were complex to me as I am pretty new to iPhone programming.

It would be great, If anybody helps with a simple example. :-)

my code is like this

- (void)viewDidLoad {

imgScrollView.userInteractionEnabled =YES;

// load all the images from our bundle and add them to the scroll view
NSUInteger i;
for (i = 1; i <= 5; i++)
{
    NSString *imageName = [NSString stringWithFormat:@"image%d.jpg", i];
    UIImage *image = [UIImage imageNamed:imageName];
    UIImageView *imageView = [[UIImageView alloc] initWithImage:image];

    // setup each frame to a default height and width
    CGRect rect = imageView.frame;
    rect.size.height = kHeight;
    rect.size.width = kWidth;
    imageView.frame = rect;
    imageView.tag = i;

    [imgScrollView addSubview:imageView];

    [imageView release];
}

[self layoutImages];

[super viewDidLoad];
}

     -(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
// WHAT CODE SHOULD I GIVE HERE ?????????? :-)

}