问:
application can't find a .js file
I have a Play application. The UI of the application is in  Angular. I have created a folder ui which is the top level Angular directory.

```<code>build.sbt
`ui-dev-build` := {
    implicit val UIroot = baseDirectory.value / "ui"
      if (runDevBuild != Success) throw new Exception("Oops! UI Build crashed.")
}

def runDevBuild(implicit dir: File): Int = ifUiInstalled(runScript("npm run build"))

package.json
"build": "ng build --output-path ../public/ui",
</code>```

When the Angular application is build, I transfer the output to the public folder of the Play framework. From there, Play transfers the contacts of the public folder to target folder for deployment. In the index.html (homepage html file), I access angular by including the scripts created in Angular build.

```<code><script src="@routes.Assets.versioned("ui/runtime.js")" type="text/javascript"></script>
    <script src="@routes.Assets.versioned("ui/vendor.js")" type="text/javascript"></script>
    <script src="@routes.Assets.versioned("ui/styles.js")" type="text/javascript"></script>
    <script src="@routes.Assets.versioned("ui/main.js")" type="text/javascript"></script>
<script src="@routes.Assets.versioned("ui/scripts.js")" type="text/javascript"></script>
</code>```

This works fine.

I want to use ng-ace2-editor in my application - https://github.com/fxmontigny/ng2-ace-editor. I have added it in package.json - "ng2-ace-editor": "0.3.9" and I can see that ng2-ace-editor directory is present in node_modules.

When I run the application, I get error

```<code>GET http://localhost:9000/mode-html.js net::ERR_ABORTED 404 (Not Found)
exports.loadScript  @   index.js:3802
exports.loadModule  @   index.js:4174
setMode @   index.js:10152
push../node_modules/ng2-ace-editor/src/component.js.AceEditorComponent.setMode
</code>```

I can't understand how to make my application find mode-html.js. The file is present at location "./node_modules/ace-builds/src-min/mode-html.js. I have added this path in "script":[] of package.json but I still get the error.

```<code>"scripts":[
              "./node_modules/ace-builds/src-min/ace.js",
              "./node_modules/ace-builds/src-min/theme-eclipse.js",
              "./node_modules/ace-builds/src-min/mode-html.js"
]
</code>```

Interestingly, things work if I include ace.js in the homepage file

```<code><script src="@routes.Assets.versioned("ui/runtime.js")" type="text/javascript"></script>
    <script src="@routes.Assets.versioned("ui/vendor.js")" type="text/javascript"></script>
    <script src="@routes.Assets.versioned("ui/styles.js")" type="text/javascript"></script>
    <script src="@routes.Assets.versioned("ui/main.js")" type="text/javascript"></script>
<script src="@routes.Assets.versioned("ui/scripts.js")" type="text/javascript"></script>
    <script src="@routes.Assets.versioned("javascripts/common/vendor/ace/src-min/ace.js")" type="text/javascript"></script> <!-- this makes things work-->
</code>```

So I know that issue  is that my mode-html.js file is not getting served and most likely it is the path resolution issue but I can't figure out what is it.

Further analysis shows that the following code in ace.js causes the error.

```<code>exports.loadModule = function(moduleName, onLoad) {
    var module, moduleType;
    if (Array.isArray(moduleName)) {
        moduleType = moduleName[0];
        moduleName = moduleName[1];
    }

    try {
        module = require(moduleName);
    } catch (e) {}
    if (module && !exports.$loading[moduleName])
        return onLoad && onLoad(module);

    if (!exports.$loading[moduleName])
        exports.$loading[moduleName] = [];

    exports.$loading[moduleName].push(onLoad);

    if (exports.$loading[moduleName].length > 1)
        return;

    var afterLoad = function() {
        require([moduleName], function(module) {
            exports._emit("load.module", {name: moduleName, module: module});
            var listeners = exports.$loading[moduleName];
            exports.$loading[moduleName] = null;
            listeners.forEach(function(onLoad) {
                onLoad && onLoad(module);
            });
        });
    };

    if (!exports.get("packaged"))
        return afterLoad();

    net.loadScript(exports.moduleUrl(moduleName, moduleType), afterLoad);
    reportErrorIfPathIsNotConfigured();
};

var reportErrorIfPathIsNotConfigured = function() {
    if (
        !options.basePath && !options.workerPath
        && !options.modePath && !options.themePath
        && !Object.keys(options.$moduleUrls).length
    ) {
        console.error(
            "Unable to infer path to ace from script src,",
            "use ace.config.set('basePath', 'path') to enable dynamic loading of modes and themes",
            "or with webpack use ace/webpack-resolver"
        );
        reportErrorIfPathIsNotConfigured = function() {};
    }
};
</code>```

Why does explicitly calling  make the code work. Should this script be already available in ui/scripts.js as per Angular packaging method https://upgradetoangular.com/angular-news/the-angular-cli-is-a-great-way-to-build-your-angular-app-but-what-it-does-can-be-a-mystery-what-are-those-files-it-generates/?

答:
I finally was able to make my code work.  My setup is different. I build my Angular application and the it is served from my Play server. The angular build is stored in Play's /public/ui folder. The requests should be in format /assets/ui/.. which gets mapped to /public/ui/... due to a rule in Play routes file

```<code>GET     /assets/*file               controllers.Assets.versioned(path="/public", file: Asset)
</code>```

When I ran the code, I got error.

```<code>Uncaught DOMException: Failed to execute 'importScripts' on 'WorkerGlobalScope': The script at 'http://localhost:9000/worker-javascript.js' failed to load.
    at blob:http://localhost:9000/3df21e42-fecb-4026-8bd6-f2b0d1d0540a:1:1
</code>```

Earlier, I also got error Unable to infer path to ace from script src, use ace.config.set('basePath', 'path') to enable dynamic loading of modes and themes or with webpack use ace/webpack-resolver

It seems ng-ace-editor imports .js scripts (theme, mode, worker) based on the theme and mode of the editor. The theme and mode js files can be included in scripts.js but some worker-.js files can't be (I don't know why, maybe because worker ones are loaded dynamically using importScript.

The scripts section in Angular.json is (this will all get bundled in scripts.js in Angular's final bundle)

```<code>"scripts": [
              "./node_modules/ace-builds/src/ace.js",
              "./node_modules/ace-builds/src/theme-eclipse.js",
              "./node_modules/ace-builds/src/theme-monokai.js",
              "./node_modules/ace-builds/src/mode-html.js"
            ]]
</code>```

To include worker-.js files, I added this rule because it seems angular-cli can't load from node_modules. So I had to copy the files from node modules to root of my ui build - How to include assets from node_modules in angular cli project

```<code>"assets": [
              "src/assets",
              "src/favicon.ico",
              {
                "glob": "**/*",
                "input": "./node_modules/ace-builds/src/",
                "output": "/"
              }
            ],
</code>```

When I executed the code, I found error that http://localhost:9000/worker-javascript.js can't be loaded. I realised that my files are loaded in /assets/ui/ path and not in the server's root directory.  So I set the basepath to /assets/ui in the component's .ts file

```<code>import * as ace from 'ace-builds/src-noconflict/ace';
    ace.config.set('basePath', '/assets/ui/');
    ace.config.set('modePath', '');
    ace.config.set('themePath', '');
</code>```

In summary
basePath seem to be what is used to load scripts dynamically (eg worker scripts)
modePath and themePath are / as the mode and theme scripts are bundled in scripts.js and are available at root level
need to copy worker-.js files outside node_modules as angular_cli can't copy assets from node_modules

Title: application can't find a .js file

Body:
I have a Play application. The UI of the application is in  Angular. I have created a folder ui which is the top level Angular directory.

build.sbt
`ui-dev-build` := {
    implicit val UIroot = baseDirectory.value / "ui"
      if (runDevBuild != Success) throw new Exception("Oops! UI Build crashed.")
}

def runDevBuild(implicit dir: File): Int = ifUiInstalled(runScript("npm run build"))

package.json
"build": "ng build --output-path ../public/ui",

When the Angular application is build, I transfer the output to the public folder of the Play framework. From there, Play transfers the contacts of the public folder to target folder for deployment. In the index.html (homepage html file), I access angular by including the scripts created in Angular build.

This works fine.

I want to use ng-ace2-editor in my application - https://github.com/fxmontigny/ng2-ace-editor. I have added it in package.json - "ng2-ace-editor": "0.3.9" and I can see that ng2-ace-editor directory is present in node_modules.

When I run the application, I get error

GET http://localhost:9000/mode-html.js net::ERR_ABORTED 404 (Not Found)
exports.loadScript  @   index.js:3802
exports.loadModule  @   index.js:4174
setMode @   index.js:10152
push../node_modules/ng2-ace-editor/src/component.js.AceEditorComponent.setMode

I can't understand how to make my application find mode-html.js. The file is present at location "./node_modules/ace-builds/src-min/mode-html.js. I have added this path in "script":[] of package.json but I still get the error.

"scripts":[
              "./node_modules/ace-builds/src-min/ace.js",
              "./node_modules/ace-builds/src-min/theme-eclipse.js",
              "./node_modules/ace-builds/src-min/mode-html.js"
]

Interestingly, things work if I include ace.js in the homepage file

So I know that issue  is that my mode-html.js file is not getting served and most likely it is the path resolution issue but I can't figure out what is it.

Further analysis shows that the following code in ace.js causes the error.

exports.loadModule = function(moduleName, onLoad) {
    var module, moduleType;
    if (Array.isArray(moduleName)) {
        moduleType = moduleName[0];
        moduleName = moduleName[1];
    }

    try {
        module = require(moduleName);
    } catch (e) {}
    if (module && !exports.$loading[moduleName])
        return onLoad && onLoad(module);

    if (!exports.$loading[moduleName])
        exports.$loading[moduleName] = [];

    exports.$loading[moduleName].push(onLoad);

    if (exports.$loading[moduleName].length > 1)
        return;

    var afterLoad = function() {
        require([moduleName], function(module) {
            exports._emit("load.module", {name: moduleName, module: module});
            var listeners = exports.$loading[moduleName];
            exports.$loading[moduleName] = null;
            listeners.forEach(function(onLoad) {
                onLoad && onLoad(module);
            });
        });
    };

    if (!exports.get("packaged"))
        return afterLoad();

    net.loadScript(exports.moduleUrl(moduleName, moduleType), afterLoad);
    reportErrorIfPathIsNotConfigured();
};

var reportErrorIfPathIsNotConfigured = function() {
    if (
        !options.basePath && !options.workerPath
        && !options.modePath && !options.themePath
        && !Object.keys(options.$moduleUrls).length
    ) {
        console.error(
            "Unable to infer path to ace from script src,",
            "use ace.config.set('basePath', 'path') to enable dynamic loading of modes and themes",
            "or with webpack use ace/webpack-resolver"
        );
        reportErrorIfPathIsNotConfigured = function() {};
    }
};

Why does explicitly calling  make the code work. Should this script be already available in ui/scripts.js as per Angular packaging method https://upgradetoangular.com/angular-news/the-angular-cli-is-a-great-way-to-build-your-angular-app-but-what-it-does-can-be-a-mystery-what-are-those-files-it-generates/?

Body:
I finally was able to make my code work.  My setup is different. I build my Angular application and the it is served from my Play server. The angular build is stored in Play's /public/ui folder. The requests should be in format /assets/ui/.. which gets mapped to /public/ui/... due to a rule in Play routes file

GET     /assets/*file               controllers.Assets.versioned(path="/public", file: Asset)

When I ran the code, I got error.

Uncaught DOMException: Failed to execute 'importScripts' on 'WorkerGlobalScope': The script at 'http://localhost:9000/worker-javascript.js' failed to load.
    at blob:http://localhost:9000/3df21e42-fecb-4026-8bd6-f2b0d1d0540a:1:1

Earlier, I also got error Unable to infer path to ace from script src, use ace.config.set('basePath', 'path') to enable dynamic loading of modes and themes or with webpack use ace/webpack-resolver

It seems ng-ace-editor imports .js scripts (theme, mode, worker) based on the theme and mode of the editor. The theme and mode js files can be included in scripts.js but some worker-.js files can't be (I don't know why, maybe because worker ones are loaded dynamically using importScript.

The scripts section in Angular.json is (this will all get bundled in scripts.js in Angular's final bundle)

"scripts": [
              "./node_modules/ace-builds/src/ace.js",
              "./node_modules/ace-builds/src/theme-eclipse.js",
              "./node_modules/ace-builds/src/theme-monokai.js",
              "./node_modules/ace-builds/src/mode-html.js"
            ]]

To include worker-.js files, I added this rule because it seems angular-cli can't load from node_modules. So I had to copy the files from node modules to root of my ui build - How to include assets from node_modules in angular cli project

"assets": [
              "src/assets",
              "src/favicon.ico",
              {
                "glob": "**/*",
                "input": "./node_modules/ace-builds/src/",
                "output": "/"
              }
            ],

When I executed the code, I found error that http://localhost:9000/worker-javascript.js can't be loaded. I realised that my files are loaded in /assets/ui/ path and not in the server's root directory.  So I set the basepath to /assets/ui in the component's .ts file

import * as ace from 'ace-builds/src-noconflict/ace';
    ace.config.set('basePath', '/assets/ui/');
    ace.config.set('modePath', '');
    ace.config.set('themePath', '');

In summary
basePath seem to be what is used to load scripts dynamically (eg worker scripts)
modePath and themePath are / as the mode and theme scripts are bundled in scripts.js and are available at root level
need to copy worker-.js files outside node_modules as angular_cli can't copy assets from node_modules


来源: stackexchange

问:
Why am i getting a unknown value in console while running a for loop with setTimeout?
Running the following code in the console:

for (var i = 0; i < 5; i++) {
    let j = i;
    setTimeout(function(){
        console.log(j);
    }, 0)
}```
</div>
</div>
</p>

<p>results in some strange behavior. When I run it once, I see something like:</p>

<p><img src="https://i.stack.imgur.com/kzEHl.png" alt="enter image description here"></p>

<p>What is that number at the top?</p>

```9 // what is this????
0
1
2
3
4
```

<p>The next time I run it, it's different:</p>

```13 // what is this????
0
1
2
3
4
```

答:
The console will log the result of the final expression that was evaluated. This is why, for example, typing in

```<code>'foo' + 'bar'
</code>```

results in 'foobar' being logged.

Here, the final expression evaluated (synchronously) is the setTimeout, and setTimeout returns an integer indicating the ID of the timeout (which can be used with clearTimeout later). setInterval works the same way. So the number you're seeing is that timeout ID. (it sounds like setTimeout was called 12 times previously on that load of the page)

ContentLicense: CC BY-SA 4.0

Body:
Running the following code in the console:

for (var i = 0; i < 5; i++) {
    let j = i;
    setTimeout(function(){
        console.log(j);
    }, 0)
}

results in some strange behavior. When I run it once, I see something like:

What is that number at the top?

9 // what is this????
0
1
2
3
4

The next time I run it, it's different:

13 // what is this????
0
1
2
3
4

Body:
The console will log the result of the final expression that was evaluated. This is why, for example, typing in

'foo' + 'bar'

results in 'foobar' being logged.

Here, the final expression evaluated (synchronously) is the setTimeout, and setTimeout returns an integer indicating the ID of the timeout (which can be used with clearTimeout later). setInterval works the same way. So the number you're seeing is that timeout ID. (it sounds like setTimeout was called 12 times previously on that load of the page)


问:
Select two different Items if they meet different condition
I have a select problem with mssql which is;

```<code>Invoice 1
ItemUniqueNo    ItemName    InvoceNo
1               A           123
3               C           123

Table A (All Invoices)
ItemUniqueNo   ItemName   InvoceNo
1               A           123
2               B           235
3               C           123

Table B (Item List)
ItemUniqueNo    ItemName    ItemGroup
1               A           XXX
2               B           YYY
3               C           ZZZ
</code>```

I want to select every items (from Table A) If an invoice has both type of product which is; ItemUniqueNo=3 and ItemGroup = XXX, in same invoice. Here is my code:

```<code>SELECT
*
FROM
TABLE_A
WHERE
(ItemUniqueNo IN (SELECT ItemUniqueNo FROM TABLE_B WHERE ItemGroup='XXX') OR ItemUniqueNo = 3)
</code>```

with this code, I've listed all items which has either ItemGroup = XXX and ItemUniqueNo=3 BUT
I want to meet both condition in same invoice, like:

```<code>Invoice 1
ItemUniqueNo    ItemName    InvoceNo
1               A           123  --->  This meets 'XXX' ItemGroup condition
3               C           123  --->  This meets '3' ItemUniqueNo condition
</code>```

This invoice meet both 2 condition, so i want to list this two item with InvoceNo.
AND all other items which meet this condition.

答:
You can use a case statement in your where clause instead of 'OR' then your output will be match what you did want before. You can check my answer.

```<code>Create table TableA (ItemUniqueNo int, ItemName Char(1),  InvoceNo int)
insert into TableA Values
(1, 'A', 123),
(2, 'B', 235),
(3, 'C', 123),
(4, 'A', 999),
(3, 'B', 999)

Create table TableB (ItemUniqueNo int, ItemName Char(1),  ItemGroup Varchar(10))
insert into TableB Values
(1, 'A', 'XXX'),
(2, 'B', 'YYY'),
(3, 'C', 'ZZZ'),
(4, 'A', 'XXX')

SELECT TABLEA.*
  FROM TABLEA INNER JOIN (SELECT DISTINCT TABLEA.INVOCENO
           FROM (SELECT TABLEA.INVOCENO,
                        (CASE
                            WHEN ITEMGROUP = 'XXX' THEN 1
                            WHEN TABLEA.ITEMUNIQUENO = 3 THEN 1
                            ELSE 0
                         END)
                           AS FLAG
                   FROM TABLEA
                        INNER JOIN TABLEB
                           ON CONCAT(TABLEA.ITEMUNIQUENO,TABLEA.ITEMNAME) = CONCAT(TABLEB.ITEMUNIQUENO,TABLEB.ITEMNAME))
                TABLEA
          WHERE FLAG = 1) COND ON TABLEA.INVOCENO = COND.INVOCENO
</code>```

Here is a dbfiddle link

Body:
I have a select problem with mssql which is;

Invoice 1
ItemUniqueNo    ItemName    InvoceNo
1               A           123
3               C           123

Table A (All Invoices)
ItemUniqueNo   ItemName   InvoceNo
1               A           123
2               B           235
3               C           123

Table B (Item List)
ItemUniqueNo    ItemName    ItemGroup
1               A           XXX
2               B           YYY
3               C           ZZZ

I want to select every items (from Table A) If an invoice has both type of product which is; ItemUniqueNo=3 and ItemGroup = XXX, in same invoice. Here is my code:

SELECT
*
FROM
TABLE_A
WHERE
(ItemUniqueNo IN (SELECT ItemUniqueNo FROM TABLE_B WHERE ItemGroup='XXX') OR ItemUniqueNo = 3)

with this code, I've listed all items which has either ItemGroup = XXX and ItemUniqueNo=3 BUT
I want to meet both condition in same invoice, like:

Invoice 1
ItemUniqueNo    ItemName    InvoceNo
1               A           123  --->  This meets 'XXX' ItemGroup condition
3               C           123  --->  This meets '3' ItemUniqueNo condition

This invoice meet both 2 condition, so i want to list this two item with InvoceNo.
AND all other items which meet this condition.

Body:
You can use a case statement in your where clause instead of 'OR' then your output will be match what you did want before. You can check my answer.

Create table TableA (ItemUniqueNo int, ItemName Char(1),  InvoceNo int)
insert into TableA Values
(1, 'A', 123),
(2, 'B', 235),
(3, 'C', 123),
(4, 'A', 999),
(3, 'B', 999)

Create table TableB (ItemUniqueNo int, ItemName Char(1),  ItemGroup Varchar(10))
insert into TableB Values
(1, 'A', 'XXX'),
(2, 'B', 'YYY'),
(3, 'C', 'ZZZ'),
(4, 'A', 'XXX')

SELECT TABLEA.*
  FROM TABLEA INNER JOIN (SELECT DISTINCT TABLEA.INVOCENO
           FROM (SELECT TABLEA.INVOCENO,
                        (CASE
                            WHEN ITEMGROUP = 'XXX' THEN 1
                            WHEN TABLEA.ITEMUNIQUENO = 3 THEN 1
                            ELSE 0
                         END)
                           AS FLAG
                   FROM TABLEA
                        INNER JOIN TABLEB
                           ON CONCAT(TABLEA.ITEMUNIQUENO,TABLEA.ITEMNAME) = CONCAT(TABLEB.ITEMUNIQUENO,TABLEB.ITEMNAME))
                TABLEA
          WHERE FLAG = 1) COND ON TABLEA.INVOCENO = COND.INVOCENO

Here is a dbfiddle link


问:
How to get the checked value of radio button when container is visible using jquery
I have 3 div like below each with 2 radio buttons in each div. I am trying to get the value of the checked radio button in the div that is showing ie. has display: block.

```<code><div class="details" style="display: none;">
<input id="r1" name="room" type="radio" value="1">
<input id="r2" name="room" checked type="radio" value="2">
</div>

<div class="details" style="display: block;">
<input id="t1" name="room1"checked  type="radio" value="3">
<input id="t2" name="room1" type="radio" value="4">
</div>
</code>```

I know how to use

```<code>$('.details').css('display') == 'block')
</code>```

but having trouble combining it with

```<code>$('input[name=???]:radio:checked').attr('value')
</code>```

Does anyone know how I can get the checked value from the visible div only?

答:
Use :visible

let v = $('.details:visible').find('input:radio:checked').val()
console.log('This is visible checked radio value: ' + v)

$('.details input:radio').change(function(){
  let v = $(this).val();
  console.log('This is clicked radio value: ' + v)
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="details" style="display: none;">
  <input id="r1" name="room" type="radio" value="1">
  <input id="r2" name="room" checked type="radio" value="2">
</div>

<div class="details" style="display: block;">
  <input id="t1" name="room1" checked type="radio" value="3">
  <input id="t2" name="room1" type="radio" value="4">
</div></code>```

Body:
I have 3 div like below each with 2 radio buttons in each div. I am trying to get the value of the checked radio button in the div that is showing ie. has display: block.

<input id="r1" name="room" type="radio" value="1">
<input id="r2" name="room" checked type="radio" value="2">

<input id="t1" name="room1"checked  type="radio" value="3">
<input id="t2" name="room1" type="radio" value="4">

I know how to use

$('.details').css('display') == 'block')

but having trouble combining it with

$('input[name=???]:radio:checked').attr('value')

Does anyone know how I can get the checked value from the visible div only?

Body:
Use :visible

let v = $('.details:visible').find('input:radio:checked').val()
console.log('This is visible checked radio value: ' + v)

$('.details input:radio').change(function(){
  let v = $(this).val();
  console.log('This is clicked radio value: ' + v)
});

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="details" style="display: none;">
  <input id="r1" name="room" type="radio" value="1">
  <input id="r2" name="room" checked type="radio" value="2">
</div>

<div class="details" style="display: block;">
  <input id="t1" name="room1" checked type="radio" value="3">
  <input id="t2" name="room1" type="radio" value="4">
</div>


问:
Why am I getting an Grpc.Core.RpcException when trying to get data from gRPC service written .net core
I have a gRPC service (written in .net core 3.1) deployed in windows server as a self hosted service running in kerstel.

I added the below configuration to get the service running in https.

```<code>"Kestrel": {
"EndpointDefaults": {
  "Protocols": "Http2"
},
"Endpoints": {
  "HttpsInlineCertFile": {
    "Url": "https://hostname:8081",
    "Protocols": "Http2",
    "Certificate": {
      "Path": "path to .pfx file",
      "Password": "Super secret password"
    }
  }
}
</code>```

Using the below code

```<code>using GrpcChannel channel = GrpcChannel.ForAddress(httpsHost);
var client = new MyClient(channel);
var response = client.GetEntity(RequestCreator.GetRequest());
Console.WriteLine("Recieved: " + response.ToString());
</code>```

I get the an below exception and the inner exception is null.

Status(StatusCode=Internal, Detail="Error starting gRPC call: The SSL connection could not be established, see inner exception.")

Is there anything I should be adding to get the client to get the data from the service?

Thanks in advance

答:
Sorry for the late response to my question. The problem was the proxy. What I ended up doing is create a webproxy, add the gRPC service URL to the bypassArrayList, create httpClientHandler, assigned the created proxy then create a httpClient that uses that httpClientHandler.</p>
```<code>            var proxy = new WebProxy
            {
                Address = new Uri(proxyServer),
                UseDefaultCredentials = true,
                BypassProxyOnLocal = true,
                Credentials = CredentialCache.DefaultNetworkCredentials
            };

            proxy.BypassArrayList.Add(serviceUrl);

            var httpClientHandler = new HttpClientHandler
            {
                Proxy = proxy,
                DefaultProxyCredentials = CredentialCache.DefaultNetworkCredentials,
                UseDefaultCredentials = true,
                UseProxy = true,
            };
            var client = new HttpClient(httpClientHandler)
            {
                DefaultRequestVersion = HttpVersion.Version20
            };

            using var channel = GrpcChannel.ForAddress(serviceUrl, new GrpcChannelOptions
            {
                HttpClient = client
            });

</code>```

Body:
I have a gRPC service (written in .net core 3.1) deployed in windows server as a self hosted service running in kerstel.

I added the below configuration to get the service running in https.

"Kestrel": {
"EndpointDefaults": {
  "Protocols": "Http2"
},
"Endpoints": {
  "HttpsInlineCertFile": {
    "Url": "https://hostname:8081",
    "Protocols": "Http2",
    "Certificate": {
      "Path": "path to .pfx file",
      "Password": "Super secret password"
    }
  }
}

Using the below code

using GrpcChannel channel = GrpcChannel.ForAddress(httpsHost);
var client = new MyClient(channel);
var response = client.GetEntity(RequestCreator.GetRequest());
Console.WriteLine("Recieved: " + response.ToString());

I get the an below exception and the inner exception is null.

Status(StatusCode=Internal, Detail="Error starting gRPC call: The SSL connection could not be established, see inner exception.")

Is there anything I should be adding to get the client to get the data from the service?

Thanks in advance

Body:
Sorry for the late response to my question. The problem was the proxy. What I ended up doing is create a webproxy, add the gRPC service URL to the bypassArrayList, create httpClientHandler, assigned the created proxy then create a httpClient that uses that httpClientHandler.

            var proxy = new WebProxy
            {
                Address = new Uri(proxyServer),
                UseDefaultCredentials = true,
                BypassProxyOnLocal = true,
                Credentials = CredentialCache.DefaultNetworkCredentials
            };

            proxy.BypassArrayList.Add(serviceUrl);

            var httpClientHandler = new HttpClientHandler
            {
                Proxy = proxy,
                DefaultProxyCredentials = CredentialCache.DefaultNetworkCredentials,
                UseDefaultCredentials = true,
                UseProxy = true,
            };
            var client = new HttpClient(httpClientHandler)
            {
                DefaultRequestVersion = HttpVersion.Version20
            };

            using var channel = GrpcChannel.ForAddress(serviceUrl, new GrpcChannelOptions
            {
                HttpClient = client
            });


问:
How to turn numeric value into currency in BigQuery?
I am new to BigQuery and am trying to convert numeric values (from Salesforce) to currency (preferably dollar value).

Very basically, what I have currently is:

```<code>SELECT salesforce.Name,
       ROUND(salesforce.Amount,2) as Amount

FROM table.salesforce
</code>```

Which obviously only rounds the value to two decimal places.

答:
Regarding your question about how to convert a numeric value to currency value in BigQuery, I would advise you to use the FORMAT() and CONCAT() built-in functions.

I see that in your question you mentioned you want to round the numeric values to the second decimal place, you can do that using FORMAT(), you can read more about it here. In addition, to use the "$" sign, you can use CONCAT(). Below is an example where I used some dummy data to exemplify what I explained:

```<code>  WITH
  data AS (
  SELECT
    20.21 AS num
  UNION ALL
  SELECT
    99999999.12 AS num
  UNION ALL
  SELECT
    12345 AS num )
  SELECT
  CONCAT('$ ',FORMAT("%'.2f", num)) AS new_num
  FROM
  data
</code>```

And the output:

Notice that in the FORMAT() function I used "%'.2f", which rounds the number to the second decimal place. You can find more information about the meaning of each letter/number in the expression using the following guide.

As a bonus information, the currency values are formatted in a way that the dot "." is a decimal separator and the comma "," is a grouping separator. You can switch that using regex expressions with REGEX_REPLACE() and REPLACE() functions. If that is the case, just let me know so I can help.

Body:
I am new to BigQuery and am trying to convert numeric values (from Salesforce) to currency (preferably dollar value).

Very basically, what I have currently is:

SELECT salesforce.Name,
       ROUND(salesforce.Amount,2) as Amount

FROM table.salesforce

Which obviously only rounds the value to two decimal places.

Body:
Regarding your question about how to convert a numeric value to currency value in BigQuery, I would advise you to use the FORMAT() and CONCAT() built-in functions.

I see that in your question you mentioned you want to round the numeric values to the second decimal place, you can do that using FORMAT(), you can read more about it here. In addition, to use the "$" sign, you can use CONCAT(). Below is an example where I used some dummy data to exemplify what I explained:

  WITH
  data AS (
  SELECT
    20.21 AS num
  UNION ALL
  SELECT
    99999999.12 AS num
  UNION ALL
  SELECT
    12345 AS num )
  SELECT
  CONCAT('$ ',FORMAT("%'.2f", num)) AS new_num
  FROM
  data

And the output:

Notice that in the FORMAT() function I used "%'.2f", which rounds the number to the second decimal place. You can find more information about the meaning of each letter/number in the expression using the following guide.

As a bonus information, the currency values are formatted in a way that the dot "." is a decimal separator and the comma "," is a grouping separator. You can switch that using regex expressions with REGEX_REPLACE() and REPLACE() functions. If that is the case, just let me know so I can help.


问:
Citrus-Framework: Conditional validation depending on status code
I'm evaluating citrus-framework for blackbox testing of a rest service.

is there a way with the java DSL and the conditional container todo a validation depending of status code?

```<code>       http(httpActionBuilder -> httpActionBuilder
                .client(sutClient)
                .receive()
                .response()
                .messageType(MessageType.JSON)
                .extractFromPayload("$.", "operationReponse")
                .extractFromHeader(HttpMessageHeaders.HTTP_STATUS_CODE, "statusCode"));

        conditional().when("${statusCode} = 200").actions(
                // how to validate on ${operationResponse} ??
                .validate("$.field1", "${expectedUUID}")
                .validate("$.elements[0].result", "APPROVED")
        );

        conditional().when("${statusCode} = 301").actions(
                // how to extract from a variable ${operationResponse}  ??
                extractFromPayload("$.pollUrl", "idToGet");
                http(hab -> hab.client(sutClient).send().get("/v1/myendpoint"));
                http(hab -> hab.client(sutClient).receive().response(HttpStatus.OK)
                .messageType(MessageType.JSON)
                .validate("$.field1", "${expectedUUID}")
                .validate("$.elements[0].result", "APPROVED")

        );

</code>```

eventually would like to create a behavior for reuse on different test cases.

答:
What you need here is to store the received Http response into the local message store for later validation. Instead of extracting the payload to a variable you can add a name for the received message:

```<code>http(httpActionBuilder -> httpActionBuilder
                .client(sutClient)
                .receive()
                .response()
                .messageType(MessageType.JSON)
                .name("operationResponse")
                .extractFromHeader(HttpMessageHeaders.HTTP_STATUS_CODE, "statusCode"));
</code>```

You can access the named message content later in further test steps then.

```<code>echo("citrus:message(helloMessage.payload())")
</code>```

For more complex logic I would add a custom test action and access the message store to load the message by its name:

```<code>action(new AbstractTestAction() {
    @Override
    public void doExecute(TestContext context) {
        // do something with stored message
        Message message = context.getMessageStore().getMessage("operationResponse");
    }
})
</code>```

By the way I have spotted a typo in your sample code where you use "operationReponse" and "operationResponse".

Body:
I'm evaluating citrus-framework for blackbox testing of a rest service.

is there a way with the java DSL and the conditional container todo a validation depending of status code?

       http(httpActionBuilder -> httpActionBuilder
                .client(sutClient)
                .receive()
                .response()
                .messageType(MessageType.JSON)
                .extractFromPayload("$.", "operationReponse")
                .extractFromHeader(HttpMessageHeaders.HTTP_STATUS_CODE, "statusCode"));

        conditional().when("${statusCode} = 200").actions(
                // how to validate on ${operationResponse} ??
                .validate("$.field1", "${expectedUUID}")
                .validate("$.elements[0].result", "APPROVED")
        );

        conditional().when("${statusCode} = 301").actions(
                // how to extract from a variable ${operationResponse}  ??
                extractFromPayload("$.pollUrl", "idToGet");
                http(hab -> hab.client(sutClient).send().get("/v1/myendpoint"));
                http(hab -> hab.client(sutClient).receive().response(HttpStatus.OK)
                .messageType(MessageType.JSON)
                .validate("$.field1", "${expectedUUID}")
                .validate("$.elements[0].result", "APPROVED")

        );

eventually would like to create a behavior for reuse on different test cases.

Body:
What you need here is to store the received Http response into the local message store for later validation. Instead of extracting the payload to a variable you can add a name for the received message:

http(httpActionBuilder -> httpActionBuilder
                .client(sutClient)
                .receive()
                .response()
                .messageType(MessageType.JSON)
                .name("operationResponse")
                .extractFromHeader(HttpMessageHeaders.HTTP_STATUS_CODE, "statusCode"));

You can access the named message content later in further test steps then.

echo("citrus:message(helloMessage.payload())")

For more complex logic I would add a custom test action and access the message store to load the message by its name:

action(new AbstractTestAction() {
    @Override
    public void doExecute(TestContext context) {
        // do something with stored message
        Message message = context.getMessageStore().getMessage("operationResponse");
    }
})

By the way I have spotted a typo in your sample code where you use "operationReponse" and "operationResponse".


问:
convert php string to json object
I have a string in database that actualy is an json object. How can i convert it to see as object/array instead string?
this is string </p>

```<code>[{"id_piesa":"8","cantitate_piesa":"12","garantie_piesa":false},{"id_piesa":"30","cantitate_piesa":1,"garantie_piesa":true}]
</code>```

答:
```<code>$json_string = '[{"id_piesa":"8","cantitate_piesa":"12","garantie_piesa":false},{"id_piesa":"30","cantitate_piesa":1,"garantie_piesa":true}]';
$php = json_decode( $json_string );

print_r( $php );
</code>```

Have a look at this: https://www.php.net/manual/de/function.json-decode.php

Title: convert php string to json object

Body:
I have a string in database that actualy is an json object. How can i convert it to see as object/array instead string?
this is string

[{"id_piesa":"8","cantitate_piesa":"12","garantie_piesa":false},{"id_piesa":"30","cantitate_piesa":1,"garantie_piesa":true}]

Body:
$json_string = '[{"id_piesa":"8","cantitate_piesa":"12","garantie_piesa":false},{"id_piesa":"30","cantitate_piesa":1,"garantie_piesa":true}]';
$php = json_decode( $json_string );

print_r( $php );

Have a look at this: https://www.php.net/manual/de/function.json-decode.php


问:
check if an array is a palindrome or not with just index as a parameter

import java.util.Scanner;

public class Palindrome1 {

    public static boolean palindrome(int[] num, int index) {
        //write the logic here

            int length = num.length;
            int end = --length;

            if (length == 0 || length == 1)
                return true;

            if (index >= end)
               return true;

            if(num[index]!=num[end])
                return false;

            return palindrome(num, index+1);
    }

    public static void main(String args[]) {
        Scanner sc = new Scanner(System.in);
        int num[] = new int[5];
        for(int i=0; i< 5;i++)
            num[i]=sc.nextInt();
        boolean answer =palindrome(num, 0);
        System.out.println(answer);
    }
}
```

It is easy if I had an end index value where I could have auto decremented. However with just index how can we solve it? Remember I should not be changing the number of params for the isPalindrome method.

Thanks in advance.

答:
Subtract index from end too

```<code>int end = --length;

end -= index;
</code>```

to check the corresponding index from both ends

```<code>public static boolean isPalindrome(int[] num, int index) {
    int length = num.length;
    int end = --length;
    end -=index;

    print(num, index, end);

    if (length == 0 || length == 1)
        return true;

    if (index >= end)
        return true;

    if(num[index]!=num[end])
        return false;

    return isPalindrome(num, index+1);
}

private static void print(int num[], int index, int end) {
    for (int i = 0; i < num.length; i++) {
        if(i == index || i == end)
            System.out.print("["+num[i]+"]");
        else
            System.out.print("_,");
    }

    System.out.println();
}
</code>```

Output

```<code>[1]_,_,_,[1]
_,[2]_,[2]_,
_,_,[3]_,_,
true
</code>```

Body:
import java.util.Scanner;

public class Palindrome1 {

    public static boolean palindrome(int[] num, int index) {
        //write the logic here

            int length = num.length;
            int end = --length;

            if (length == 0 || length == 1)
                return true;

            if (index >= end)
               return true;

            if(num[index]!=num[end])
                return false;

            return palindrome(num, index+1);
    }

    public static void main(String args[]) {
        Scanner sc = new Scanner(System.in);
        int num[] = new int[5];
        for(int i=0; i< 5;i++)
            num[i]=sc.nextInt();
        boolean answer =palindrome(num, 0);
        System.out.println(answer);
    }
}

It is easy if I had an end index value where I could have auto decremented. However with just index how can we solve it? Remember I should not be changing the number of params for the isPalindrome method.

Thanks in advance.

Body:
Subtract index from end too

int end = --length;

end -= index;

to check the corresponding index from both ends

public static boolean isPalindrome(int[] num, int index) {
    int length = num.length;
    int end = --length;
    end -=index;

    print(num, index, end);

    if (length == 0 || length == 1)
        return true;

    if (index >= end)
        return true;

    if(num[index]!=num[end])
        return false;

    return isPalindrome(num, index+1);
}

private static void print(int num[], int index, int end) {
    for (int i = 0; i < num.length; i++) {
        if(i == index || i == end)
            System.out.print("["+num[i]+"]");
        else
            System.out.print("_,");
    }

    System.out.println();
}

Output

[1]_,_,_,[1]
_,[2]_,[2]_,
_,_,[3]_,_,
true


问:
OAuth Flow for Sender Using Apex Toolkit
I've developed an invokable Apex method that leverages the DocuSign Apex Toolkit for preparing and sending an envelope via a Salesforce flow.

The only issue I'm having is when it is invoked by a Salesforce user, that has been added as a DocuSign user, but has not yet gone through the OAuth flow to connect Salesforce to DocuSign for their user account.

A workaround is that I have that new user click a standard "Send with DocuSign" button an any record, which then shows the "Before you can use DocuSign, you must grant consent for this application to make requests on your behalf." message and a button to start and complete the OAuth flow. Once this is done I can go back to my flow and it will successfully complete as that user.

Any ideas how I can "pre-authorize" users, or check for authorization as part of the flow (is this data stored in Salesforce), or at least find a way to get to this "Authorize" screen in Salesforce without needing to begin the process of sending an envelope?

Thanks
Matt

答:
Yes, the administrator for the account can grant "blanket" consent, known as administrative consent, for the relevant integration key (client id) and scope(s) needed by your application.

To do so:

The account needs the Admin feature Access Management with SSO You can have this feature enabled for your developer sandbox account by email request to go-live@docusign.com. Contact your DocuSign account manager for adding the feature to a production account.

You need to claim the email domain for your users.

Use the Admin tool's Connected Apps tile to grant administrative consent to your users in the claimed to domain to the application.

The above assumes that you are supplying the integration key to your Apex application.

If you're using an integration key supplied by DocuSign, then you also need to use the Admin consent for external applications API.

If you're using an integration key supplied by DocuSign as part of a DocuSign for Salesforce product, then I would first ensure that the product is enabled for everyone in your account; that may take care of your app's consent issue.

Re: detecting if consent is required

DocuSign responds with a specific consent_required error if consent is needed. So check the error response of your call. See APIError


问:
How to shrink dataset using the minimum and the maximum of columns? Can I use apply family of functions?
I have a data set in this form:

```<code>  species  date         start.time           end.time              remarks
  A        2020-02-01   2020-02-01 8:00:00   2020-02-01 12:00:00   slow
  A        2020-02-01   2020-02-01 9:00:00   2020-02-02 00:00:00   NA
  A        2020-02-02   2020-02-01 8:00:00   NA                    medium
  A        2020-02-02   NA                   2020-02-01 11:30:00    NA
</code>```

I have 20 different species and 200 different dates. The data pretty much behaves the same in every species.

How can I shrink the data to get the minimum start.time, maximum end.time and every unique remark for each species and date? The output is:

```<code>  species  date         start.time   end.time   remarks
  A        2020-02-01   8:00am       12:00am    slow
  A        2020-02-02   8:00am       11:30am    medium
</code>```

I need the codes to be done in BASE R to be able to use it in a computer without the internet.

答:
Here is a data.table approach

It summarise to min-max timestampt per data, and collapses all non-NA remarks, using a ; as separator for readability.

```<code>library( data.table )

#sample data
DT <- fread("species  date         start.time           end.time              remarks
A        2020-02-01   2020-02-01T8:00:00   2020-02-01T12:00:00   slow
A        2020-02-01   2020-02-01T9:00:00   2020-02-02T00:00:00   NA
A        2020-02-02   2020-02-01T8:00:00   NA                    medium
A        2020-02-02   NA                   2020-02-01T11:30:00    NA")

#set timestamps as posix
cols = c("start.time", "end.time")
DT[, (cols) := lapply( .SD, as.POSIXct, format = "%Y-%m-%dT%H:%M:%S"), .SDcols = cols]

#summarise to desired format
DT[, .(start.time = min(start.time, na.rm = TRUE),
       end.time = max(end.time, na.rm = TRUE),
       remarks = paste0( remarks[!is.na(remarks)], collapse = ";")),
   by = .(date)]

#          date          start.time            end.time remarks
# 1: 2020-02-01 2020-02-01 08:00:00 2020-02-02 00:00:00    slow
# 2: 2020-02-02 2020-02-01 08:00:00 2020-02-01 11:30:00  medium
</code>```

Body:
I have a data set in this form:

  species  date         start.time           end.time              remarks
  A        2020-02-01   2020-02-01 8:00:00   2020-02-01 12:00:00   slow
  A        2020-02-01   2020-02-01 9:00:00   2020-02-02 00:00:00   NA
  A        2020-02-02   2020-02-01 8:00:00   NA                    medium
  A        2020-02-02   NA                   2020-02-01 11:30:00    NA

I have 20 different species and 200 different dates. The data pretty much behaves the same in every species.

How can I shrink the data to get the minimum start.time, maximum end.time and every unique remark for each species and date? The output is:

  species  date         start.time   end.time   remarks
  A        2020-02-01   8:00am       12:00am    slow
  A        2020-02-02   8:00am       11:30am    medium

I need the codes to be done in BASE R to be able to use it in a computer without the internet.

Body:
Here is a data.table approach

It summarise to min-max timestampt per data, and collapses all non-NA remarks, using a ; as separator for readability.

library( data.table )

#sample data
DT <- fread("species  date         start.time           end.time              remarks
A        2020-02-01   2020-02-01T8:00:00   2020-02-01T12:00:00   slow
A        2020-02-01   2020-02-01T9:00:00   2020-02-02T00:00:00   NA
A        2020-02-02   2020-02-01T8:00:00   NA                    medium
A        2020-02-02   NA                   2020-02-01T11:30:00    NA")

#set timestamps as posix
cols = c("start.time", "end.time")
DT[, (cols) := lapply( .SD, as.POSIXct, format = "%Y-%m-%dT%H:%M:%S"), .SDcols = cols]

#summarise to desired format
DT[, .(start.time = min(start.time, na.rm = TRUE),
       end.time = max(end.time, na.rm = TRUE),
       remarks = paste0( remarks[!is.na(remarks)], collapse = ";")),
   by = .(date)]

#          date          start.time            end.time remarks
# 1: 2020-02-01 2020-02-01 08:00:00 2020-02-02 00:00:00    slow
# 2: 2020-02-02 2020-02-01 08:00:00 2020-02-01 11:30:00  medium


问:
How to get the checkbox value in php html
I have a table showing database values as shown here:

```<code><?php
       while ($single = $output->fetch_assoc()):?>
  <tr>
    <td> <?php echo $single['Dptname']; ?></td>
    <td> <?php echo $single['firstname']; ?> </td>
    <td> <?php echo $single['lastname']; ?> </td>
    <td> <?php echo $single['email']; ?> </td>
    <td> <?php echo $single['phnumber']; ?> </td>
    <td> <?php echo $single['provider']; ?> </td>
     <td style="display: none"> <?php echo $single['id']; ?></td>
    <td><input type="checkbox" class="Dptadmin" id="Dptadmin" value="1"></td>
    <td><input type="checkbox" class="superuser" id="superuser" value="1"></td>
    <td><button type="button" class="btn b1 editbtn" data-toggle="modal" value="" data-target="#myModal"> <i class="fa fa-pencil-square-o">  </i> </button>
        <a href="process.php?delete=<?php echo $single['id'];?>" class="b2"><i class="fa fa-trash-o"></i> </a>
    </td>
  </tr>
    <?php endwhile;?>
</code>```

jQuery:

```<code><script>
 $(document).ready(function (){
    $('.editbtn').on('click', function(){
        $('#editmodal').modal('show');
        $tr = $(this).closest('tr');
        var data = $tr.children('td').map(function(){
          return $(this).text();
        }).get();
        console.log(data);
        $('#Dptname').val(data[0]);
        $('#firstname').val(data[1]);
        $('#lastname').val(data[2]);
        $('#email').val(data[3]);
        $('#phnumber').val(data[4]);
        $('#provider').val(data[5]);
        $('#userid').val(data[6]);
        $('#userid').val(data[6]);
        $('#Dptadmin').val(data[7]);
    });
 });
</code>```

Tried:-

```<code> $('.Dptadmin').on('click', function(){
     $tr = $(this).closest('tr');
        var data = $tr.children('td').map(function(){
          return $(this).text();
        }).get();
        console.log(data);
        $('#userid').val(data[6]);
        var val = $(this).find(":checkbox['<?php echo $single['Dadmin']; ?>']").val();
        console.log(val);
</code>```

As above jQuery, from console.log(data) I'm getting the value of selected TD, but not getting checkbox value. Thank you in advance.

答:
I got the solution on my own. thank you for your support your ideas are made me think beyond. here is my solution.

```<code> $('.Dadmin').on('click', function(){
         $tr = $(this).closest('tr');
        var data = $tr.children('td').map(function(){
          return $(this).text();
        }).get();
        var userid = data[6];
        var admin = $('#Dadmin').val();
        $.ajax({
        type: 'POST',
        url: 'makeadmin.php',
        data: {
            userid : userid,
            admin : admin,
        },
        success: function(data){
            console.log(data.length);
        },
        });
    })
</code>```

html

```<code> <tr>
    <td> <?php echo $single['Dptname']; ?></td>
    <td> <?php echo $single['firstname']; ?> </td>
    <td> <?php echo $single['lastname']; ?> </td>
    <td> <?php echo $single['email']; ?> </td>
    <td> <?php echo $single['phnumber']; ?> </td>
    <td> <?php echo $single['provider']; ?> </td>
     <td style="display: none"> <?php echo $single['id']; ?></td>
    <td><input type="checkbox" class="Dadmin" id="Dadmin" value="1"></td>
    <td><input type="checkbox" class="superuser" id="superuser" value="1"></td>
    <td><button type="button" class="btn b1 editbtn" data-toggle="modal" value="" data-target="#myModal"> <i class="fa fa-pencil-square-o">  </i> </button>
        <a href="process.php?delete=<?php echo $single['id'];?>" class="b2"><i class="fa fa-trash-o"></i> </a>
    </td>
  </tr>
</code>```

here only i changed $('#userid').val(data[6]); to var userid = data[6];

hope so this will help somebody. thank you all once.

Body:
I have a table showing database values as shown here:

<?php
       while ($single = $output->fetch_assoc()):?>

     <?php echo $single['Dptname']; ?>
     <?php echo $single['firstname']; ?>
     <?php echo $single['lastname']; ?>
     <?php echo $single['email']; ?>
     <?php echo $single['phnumber']; ?>
     <?php echo $single['provider']; ?>
      <?php echo $single['id']; ?>
    <input type="checkbox" class="Dptadmin" id="Dptadmin" value="1">
    <input type="checkbox" class="superuser" id="superuser" value="1">
    <button type="button" class="btn b1 editbtn" data-toggle="modal" value="" data-target="#myModal">    </button>
        <a href="process.php?delete=<?php echo $single['id'];?>" class="b2">

    <?php endwhile;?>

jQuery:

Body:
I got the solution on my own. thank you for your support your ideas are made me think beyond. here is my solution.

 $('.Dadmin').on('click', function(){
         $tr = $(this).closest('tr');
        var data = $tr.children('td').map(function(){
          return $(this).text();
        }).get();
        var userid = data[6];
        var admin = $('#Dadmin').val();
        $.ajax({
        type: 'POST',
        url: 'makeadmin.php',
        data: {
            userid : userid,
            admin : admin,
        },
        success: function(data){
            console.log(data.length);
        },
        });
    })

html

 <tr>
    <td> <?php echo $single['Dptname']; ?></td>
    <td> <?php echo $single['firstname']; ?> </td>
    <td> <?php echo $single['lastname']; ?> </td>
    <td> <?php echo $single['email']; ?> </td>
    <td> <?php echo $single['phnumber']; ?> </td>
    <td> <?php echo $single['provider']; ?> </td>
     <td style="display: none"> <?php echo $single['id']; ?></td>
    <td><input type="checkbox" class="Dadmin" id="Dadmin" value="1"></td>
    <td><input type="checkbox" class="superuser" id="superuser" value="1"></td>
    <td><button type="button" class="btn b1 editbtn" data-toggle="modal" value="" data-target="#myModal"> <i class="fa fa-pencil-square-o">  </i> </button>
        <a href="process.php?delete=<?php echo $single['id'];?>" class="b2"><i class="fa fa-trash-o"></i> </a>
    </td>
  </tr>

here only i changed $('#userid').val(data[6]); to var userid = data[6];

hope so this will help somebody. thank you all once.


问:
SwaggerUI 5.0.0 ignoring JsonProperty name
I recently upgraded a ASP.NET Core API application to Swashbuckle/Swagger 5.0.0 with ASP.NET Core 3.1.

<PackageReference Include="Swashbuckle.AspNetCore" Version="5.0.0" />
<PackageReference Include="Swashbuckle.AspNetCore.Swagger" Version="5.0.0" />
<PackageReference Include="Swashbuckle.AspNetCore.SwaggerGen" Version="5.0.0" />
<PackageReference Include="Swashbuckle.AspNetCore.SwaggerUI" Version="5.0.0" />
```

<p>However, upon doing so I have noticed that the Swagger UI is now ignoring the Newtonsoft/JSON.NET JsonProperty attribute names on DTO properties.  For example:</p>

<pre class="lang-cs prettyprint-override"><code>[HttpGet("testget", Name = "testget")]
[ProducesResponseType(StatusCodes.Status200OK)]
public ActionResult<TestGetResponse> TestGet()
{
    var response = new TestGetResponse { MyName = "John" };

    return Ok(response);
}

public class TestGetResponse
{
    [JsonProperty("name")]
    public string MyName { get; set; }
}
</code>```

Is outputting in Swagger UI as:

Code 200:
Example Value

```<code>Model
{
  "myName": "string"
}
</code>```

Instead of Model property name name.

For Swagger in Startup.cs ConfigureServices I currently have:

services.AddSwaggerGen(c =>
{
    c.SwaggerDoc("v1", new OpenApiInfo
    {
        Version = "v1",
        Title = "My API",
    });

    c.IncludeXmlComments(Path.Combine(AppContext.BaseDirectory, $"{Assembly.GetExecutingAssembly().GetName().Name}.xml"));
});
```

<p>And for Swagger in Startup.cs Configure I currently have:</p>

<pre class="lang-cs prettyprint-override"><code>app.UseSwagger();

app.UseSwaggerUI(c =>
{
    c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API");
    c.RoutePrefix = "swagger";
});
</code>```

I am aware that if I use the System.Text.Json attribute JsonPropertyName instead this will be fixed however I need to stick with the original attributes for now.

Is there a setting in Start.cs to tell SwaggerUI to use the Newtonsoft JsonProperty attribute or is there something I need to change at the ASP.NET Core level of configuration?

答:
It would appear that full support for NewtonSoft JSON.net from version 5.0.0 of Swashbuckle/Swagger is provided through a separate package.

To get this working:

1) Install the nuget package Swashbuckle.AspNetCore.Newtonsoft version 5.0.0+

2) In Startup.ConfigureServices() make a call for the support:

services.AddSwaggerGenNewtonsoftSupport();

Further info can be found here.

Body:
I recently upgraded a ASP.NET Core API application to Swashbuckle/Swagger 5.0.0 with ASP.NET Core 3.1.

<PackageReference Include="Swashbuckle.AspNetCore" Version="5.0.0" />
<PackageReference Include="Swashbuckle.AspNetCore.Swagger" Version="5.0.0" />
<PackageReference Include="Swashbuckle.AspNetCore.SwaggerGen" Version="5.0.0" />
<PackageReference Include="Swashbuckle.AspNetCore.SwaggerUI" Version="5.0.0" />

However, upon doing so I have noticed that the Swagger UI is now ignoring the Newtonsoft/JSON.NET JsonProperty attribute names on DTO properties.  For example:

[HttpGet("testget", Name = "testget")]
[ProducesResponseType(StatusCodes.Status200OK)]
public ActionResult<TestGetResponse> TestGet()
{
    var response = new TestGetResponse { MyName = "John" };

    return Ok(response);
}

public class TestGetResponse
{
    [JsonProperty("name")]
    public string MyName { get; set; }
}

Is outputting in Swagger UI as:

Code 200:
Example Value

Model
{
  "myName": "string"
}

Instead of Model property name name.

For Swagger in Startup.cs ConfigureServices I currently have:

services.AddSwaggerGen(c =>
{
    c.SwaggerDoc("v1", new OpenApiInfo
    {
        Version = "v1",
        Title = "My API",
    });

    c.IncludeXmlComments(Path.Combine(AppContext.BaseDirectory, $"{Assembly.GetExecutingAssembly().GetName().Name}.xml"));
});

And for Swagger in Startup.cs Configure I currently have:

app.UseSwagger();

app.UseSwaggerUI(c =>
{
    c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API");
    c.RoutePrefix = "swagger";
});

I am aware that if I use the System.Text.Json attribute JsonPropertyName instead this will be fixed however I need to stick with the original attributes for now.

Is there a setting in Start.cs to tell SwaggerUI to use the Newtonsoft JsonProperty attribute or is there something I need to change at the ASP.NET Core level of configuration?


问:
Error: The build restored NuGet packages. Build the project again to include these packages in the build. For more information
When I build my project for the first time the build succeeds, but when I Publish the project, the build fails and I get several errors that say:

The build restored NuGet packages. Build the project again to include these packages in the build. For more information, see the below link
  http://www.postsharp.net/links/nuget-restore.

What does this mean? And what can I do?

答:
Try run Build Solution and restart visual studio.
It did the job for me.</p>


问:
Flatten nested dictionaries, compressing keys
Suppose you have a dictionary like:

```<code>{'a': 1,
 'c': {'a': 2,
       'b': {'x': 5,
             'y' : 10}},
 'd': [1, 2, 3]}
</code>```

How would you go about flattening that into something like:

```<code>{'a': 1,
 'c_a': 2,
 'c_b_x': 5,
 'c_b_y': 10,
 'd': [1, 2, 3]}
</code>```

答:
Basically the same way you would flatten a nested list, you just have to do the extra work for iterating the dict by key/value, creating new keys for your new dictionary and creating the dictionary at final step.</p>
```<code>from collections.abc import MutableMapping

def flatten(dictionary, parent_key='', separator='_'):
    items = []
    for key, value in dictionary.items():
        new_key = parent_key + separator + key if parent_key else key
        if isinstance(value, MutableMapping):
            items.extend(flatten(value, new_key, separator=separator).items())
        else:
            items.append((new_key, value))
    return dict(items)

>>> flatten({'a': 1, 'c': {'a': 2, 'b': {'x': 5, 'y' : 10}}, 'd': [1, 2, 3]})
{'a': 1, 'c_a': 2, 'c_b_x': 5, 'd': [1, 2, 3], 'c_b_y': 10}
</code>```

Body:
Suppose you have a dictionary like:

{'a': 1,
 'c': {'a': 2,
       'b': {'x': 5,
             'y' : 10}},
 'd': [1, 2, 3]}

How would you go about flattening that into something like:

{'a': 1,
 'c_a': 2,
 'c_b_x': 5,
 'c_b_y': 10,
 'd': [1, 2, 3]}

Body:
Basically the same way you would flatten a nested list, you just have to do the extra work for iterating the dict by key/value, creating new keys for your new dictionary and creating the dictionary at final step.

from collections.abc import MutableMapping

def flatten(dictionary, parent_key='', separator='_'):
    items = []
    for key, value in dictionary.items():
        new_key = parent_key + separator + key if parent_key else key
        if isinstance(value, MutableMapping):
            items.extend(flatten(value, new_key, separator=separator).items())
        else:
            items.append((new_key, value))
    return dict(items)

>>> flatten({'a': 1, 'c': {'a': 2, 'b': {'x': 5, 'y' : 10}}, 'd': [1, 2, 3]})
{'a': 1, 'c_a': 2, 'c_b_x': 5, 'd': [1, 2, 3], 'c_b_y': 10}


问:
Live data Updating in Angular 8
Hey guys i am tyring to get data from server as soon as there add's a new in the database

i want to avoid making many get request with the timeout

is there a way to do that?

thanks

答:
One of the ways this can be done is by using changeStreams.
More info: https://docs.mongodb.com/manual/changeStreams/</p>

Title: Live data Updating in Angular 8


问:
Chaitin's Algorithm for register allocation: How many colors are used with R registers?
In the lecture I have for register allocation/Chaitin's Algorithm, it seems like we construct an interference graph and then try to find a k-coloring of that graph, where k=R if we can use R registers in the target architecture. However, if we spill a value, wouldn't that mean that we need an additional register to load values from memory prior to using them in instructions and can thus only use k=R-1 values for Chaitin's Algorithm?</p>

答: You can still use k=R. When you spill a value you add spill code that store and retrieve the value (usually on the stack, but other alternatives exists). This will replace the original virtual register with a high degree of interference with a number of new virtual registers that exists only for a short time and (hopefully) have a lower degree. You can now make another try at coloring and if it still fails you repeat the spill process until you succeed.</p>


问:
Undefined contants.ts API value
I have a constant.ts file that exports the base API. When I try to import the constants file and use the base API, I get an undefined. Here is my code</p>

```<code>Constants.ts

export class Constants {
  public static API_ENDPOINT: 'https://www.techiediaries.com/api/';
}

App.module.ts

 providers: [Constants],

Api.service.ts

import { Constants } from '../constants/constants';

getData() {
  console.log(Constants.API_ENDPOINT);
  return this.httpClient.get(Constants.API_ENDPOINT + 'data.json');
}
</code>```

答:
just another option like this instand of use a class object

constants.ts

```<code>export const ApiEndPoint = `https://www.techiediaries.com/api/`;
</code>```

Api.service.ts

```<code>import { ApiEndPoint } from '../constants/constants';

getData() {
  console.log(Constants.API_ENDPOINT);
  return this.httpClient.get(ApiEndPoint+ 'data.json');
}
</code>```

in case you want to get all contants

```<code> import * as Constants  from '../constants/constants';
</code>```

Title: Undefined contants.ts API value

Body:
I have a constant.ts file that exports the base API. When I try to import the constants file and use the base API, I get an undefined. Here is my code

Constants.ts

export class Constants {
  public static API_ENDPOINT: 'https://www.techiediaries.com/api/';
}

App.module.ts

 providers: [Constants],

Api.service.ts

import { Constants } from '../constants/constants';

getData() {
  console.log(Constants.API_ENDPOINT);
  return this.httpClient.get(Constants.API_ENDPOINT + 'data.json');
}

Body:
just another option like this instand of use a class object

constants.ts

export const ApiEndPoint = `https://www.techiediaries.com/api/`;

Api.service.ts

import { ApiEndPoint } from '../constants/constants';

getData() {
  console.log(Constants.API_ENDPOINT);
  return this.httpClient.get(ApiEndPoint+ 'data.json');
}

in case you want to get all contants

 import * as Constants  from '../constants/constants';


问:
Determine number or character in textfile C
I have a textfile with these following numbers and characters inside of it.

```<code>36@xL!?\8
28?>\4
42<pX%7
37@#5
31kL%^?>\<#%5
</code>```

Now, i want to get the first integer which is 36 and subtract it on the last integer which is 8. I want to do this line by line.

答:
You already have a good answer for the file posted as part of your question, however, the result of first - last will be incorrect if you line of text contains a '-' sign before the digits indicating a negative signed value. All of the C string to integer conversions will accept a leading +/- before the value to be converted indicating a positive or negative number. If your input can contain negative values, you need to preserve the '-' sign by including that with the digits to be converted. For example if your input file was:

```<code>36@xL!?\-8
28?>\4
-42<pX%7
37@#-5
31kL%^?>\<#%5
</code>```

The answers would be quite different with -8, -42 and -5 as the integer values from the file. Now if that isn't a possibility based on your specific assignment, then you can skip preserving the '-', but for read-world text conversion to signed values, it is critical.

One way of finding the beginning of a signed number for conversion in a string is simply scan forward in the string (similar to what strpbrk() would do) looking for either a beginning digit or '-' (whichever occurs first). If the '-' occurs first, you then check that the next character is a digit. You can do it with a simple loop, e.g.

```<code>/** scan forward in 'p' to find beginning of next valid signed integer.
 *  returns pointer to beginning of signed int on success, NULL otherwise.
 */
const char *nextdigit (const char *p)
{
    while (*p) {
        /* if digit or +/- followed by a digit */
        if (isdigit(*p) ||
            ((*p == '-' || *p == '+') && isdigit(*(p + 1))))
            return p;
        p++;
    }
    return NULL;
}
</code>```

Once you have found the beginning of a digit, then you need to use a function that provides error-checking on the conversion. atoi() provides zero diagnostics for the conversion and will silently return 0 as a valid number for the conversion of atoi("my cow"); You will have no indication whether digits were actually converted or whether the result exceeds the storage size for all integer types. atoi() issues no errors at all, even if provided with a 200 digit string as input. At minimum, use sscanf that will at least provide a yes/no, true/false as to whether a valid conversion took place, or better, use strtol which provides full error reporting on the conversion.

For example, you can write a short function that take the address of a pointer to string, use nextdigit() function above, and then use strtol to fully validate the result, setting errno for validation back in the caller on any error and returning the results of the integer conversion (or 0 on error) as follows:

```<code>/** returns next integer in string pointed to by p, or sets errno and returns
 *  zero on error.
 */
int getnextint (char **p)
{
    int nextint = 0;

    errno = 0;
    if ((*p = (char*)nextdigit(*p))) {
        char *endptr;
        long tmp = strtol (*p, &endptr, 0);

        if (*p == endptr) { /* validate digits converted */
            fputs ("error: no digits converted.\n", stderr);
            errno = EINVAL;
        }
        else if (errno)     /* validate conversion */
            fputs ("error: over/underflow occurred.\n", stderr);
        /* validate tmp is in range of integer */
        else if (INT_MIN <= tmp && tmp <= INT_MAX)
            nextint = tmp;
        else {
            fputs ("error: value exceeds range of int.\n", stderr);
            errno = ERANGE;
        }
        *p = (char*)nextdigit(endptr);
    }
    else
        errno = EINVAL;     /* if no digits found, set EINVAL */

    return nextint;
}
</code>```

(note: the address of the pointer is passed so that the pointer can be updated within the function to the beginning of the next integer to convert in the string (or NULL if no more remain)

To complete the example, you can add the needed headers and write a short main() to read from your filename provided as the first argument (or read from stdin by default if no argument is provided) that will locate the first and last integers in each line and subtract first - last outputting the result:

```<code>#include <stdio.h>
#include <stdlib.h> /* for strtol   */
#include <string.h> /* for strcspn */
#include <limits.h> /* for INT_MIN/INT_MAX */
#include <errno.h>  /* for errno    */
#include <ctype.h>  /* for isdigit */

#define ARSZ  100
#define MAXC 1024
...                                  /* insert functions here */
int main (int argc, char **argv) {

    char buf[MAXC] = "";
    /* use filename provided as 1st argument (stdin by default) */
    FILE *fp = argc > 1 ? fopen (argv[1], "r") : stdin;

    if (!fp) {  /* validate file open for reading */
        perror ("file open failed");
        return 1;
    }

    while (fgets (buf, MAXC, fp)) {     /* read each line of input */
        int arr[ARSZ] = {0};
        char *p = buf;
        size_t n = 0;
        buf[strcspn(buf, "\r\n")] = 0;
        while (n < ARSZ && p) {
            arr[n] = getnextint (&p);
            if (!errno)
                n++;
        }
        if (n > 1)
            printf ("%-19s  :  % 2d - % 2d = % 3d\n",
                    buf, *arr, arr[n-1], *arr - arr[n-1]);
        else
            fprintf (stderr, "%zu integer(s) in: '%s'\n", n, buf);
    }
    if (fp != stdin)   /* close file if not stdin */
        fclose (fp);
}
</code>```

Example Input Files

Your original input file:

```<code>$ cat dat/last-first.txt
36@xL!?\8
28?>\4
42<pX%7
37@#5
31kL%^?>\<#%5
</code>```

And another with negative values and additional extraneous lines:

```<code>$ cat dat/last-first2.txt
36@xL!?\-8
28?>\4
-42<pX%7
Nothing to see!
37@#-5
31kL%^?>\<#%5
</code>```

Example Use/Output

```<code>$ ./bin/fgets_strtol_any_last-first dat/last-first.txt
36@xL!?\8            :   36 -  8 =  28
28?>\4            :   28 -  4 =  24
42<pX%7           :   42 -  7 =  35
37@#5                :   37 -  5 =  32
31kL%^?>\<#%5  :   31 -  5 =  26
</code>```

When run on the file with negative values and the extraneous line:

```<code>$ ./bin/fgets_strtol_any_last-first dat/last-first2.txt
36@xL!?\-8           :   36 - -8 =  44
28?>\4            :   28 -  4 =  24
-42<pX%7          :  -42 -  7 = -49
0 integer(s) in: 'Nothing to see!'
37@#-5               :   37 - -5 =  42
31kL%^?>\<#%5  :   31 -  5 =  26
</code>```

As you can see from the result of the subtractions between the different files, it makes a great deal of difference whether you preserve the leading '-' when converting signed values. Something to consider going forward.

Look things over and let me know if you have additional questions.

Body:
I have a textfile with these following numbers and characters inside of it.

36@xL!?\8
28?>\4
42<pX%7
37@#5
31kL%^?>\<#%5

Now, i want to get the first integer which is 36 and subtract it on the last integer which is 8. I want to do this line by line.

Body:
You already have a good answer for the file posted as part of your question, however, the result of first - last will be incorrect if you line of text contains a '-' sign before the digits indicating a negative signed value. All of the C string to integer conversions will accept a leading +/- before the value to be converted indicating a positive or negative number. If your input can contain negative values, you need to preserve the '-' sign by including that with the digits to be converted. For example if your input file was:

36@xL!?\-8
28?&gt;\4
-42&lt;pX%7
37@#-5
31kL%^?&gt;\&lt;#%5

The answers would be quite different with -8, -42 and -5 as the integer values from the file. Now if that isn't a possibility based on your specific assignment, then you can skip preserving the '-', but for read-world text conversion to signed values, it is critical.

One way of finding the beginning of a signed number for conversion in a string is simply scan forward in the string (similar to what strpbrk() would do) looking for either a beginning digit or '-' (whichever occurs first). If the '-' occurs first, you then check that the next character is a digit. You can do it with a simple loop, e.g.

/** scan forward in 'p' to find beginning of next valid signed integer.
 *  returns pointer to beginning of signed int on success, NULL otherwise.
 */
const char *nextdigit (const char *p)
{
    while (*p) {
        /* if digit or +/- followed by a digit */
        if (isdigit(*p) ||
            ((*p == '-' || *p == '+') && isdigit(*(p + 1))))
            return p;
        p++;
    }
    return NULL;
}

Once you have found the beginning of a digit, then you need to use a function that provides error-checking on the conversion. atoi() provides zero diagnostics for the conversion and will silently return 0 as a valid number for the conversion of atoi("my cow"); You will have no indication whether digits were actually converted or whether the result exceeds the storage size for all integer types. atoi() issues no errors at all, even if provided with a 200 digit string as input. At minimum, use sscanf that will at least provide a yes/no, true/false as to whether a valid conversion took place, or better, use strtol which provides full error reporting on the conversion.

For example, you can write a short function that take the address of a pointer to string, use nextdigit() function above, and then use strtol to fully validate the result, setting errno for validation back in the caller on any error and returning the results of the integer conversion (or 0 on error) as follows:

/** returns next integer in string pointed to by p, or sets errno and returns
 *  zero on error.
 */
int getnextint (char **p)
{
    int nextint = 0;

    errno = 0;
    if ((*p = (char*)nextdigit(*p))) {
        char *endptr;
        long tmp = strtol (*p, &endptr, 0);

        if (*p == endptr) { /* validate digits converted */
            fputs ("error: no digits converted.\n", stderr);
            errno = EINVAL;
        }
        else if (errno)     /* validate conversion */
            fputs ("error: over/underflow occurred.\n", stderr);
        /* validate tmp is in range of integer */
        else if (INT_MIN <= tmp && tmp <= INT_MAX)
            nextint = tmp;
        else {
            fputs ("error: value exceeds range of int.\n", stderr);
            errno = ERANGE;
        }
        *p = (char*)nextdigit(endptr);
    }
    else
        errno = EINVAL;     /* if no digits found, set EINVAL */

    return nextint;
}

(note: the address of the pointer is passed so that the pointer can be updated within the function to the beginning of the next integer to convert in the string (or NULL if no more remain)

To complete the example, you can add the needed headers and write a short main() to read from your filename provided as the first argument (or read from stdin by default if no argument is provided) that will locate the first and last integers in each line and subtract first - last outputting the result:

#include <stdio.h>
#include <stdlib.h> /* for strtol   */
#include <string.h> /* for strcspn */
#include <limits.h> /* for INT_MIN/INT_MAX */
#include <errno.h>  /* for errno    */
#include <ctype.h>  /* for isdigit */

#define ARSZ  100
#define MAXC 1024
...                                  /* insert functions here */
int main (int argc, char **argv) {

    char buf[MAXC] = "";
    /* use filename provided as 1st argument (stdin by default) */
    FILE *fp = argc > 1 ? fopen (argv[1], "r") : stdin;

    if (!fp) {  /* validate file open for reading */
        perror ("file open failed");
        return 1;
    }

    while (fgets (buf, MAXC, fp)) {     /* read each line of input */
        int arr[ARSZ] = {0};
        char *p = buf;
        size_t n = 0;
        buf[strcspn(buf, "\r\n")] = 0;
        while (n < ARSZ && p) {
            arr[n] = getnextint (&p);
            if (!errno)
                n++;
        }
        if (n > 1)
            printf ("%-19s  :  % 2d - % 2d = % 3d\n",
                    buf, *arr, arr[n-1], *arr - arr[n-1]);
        else
            fprintf (stderr, "%zu integer(s) in: '%s'\n", n, buf);
    }
    if (fp != stdin)   /* close file if not stdin */
        fclose (fp);
}

Example Input Files

Your original input file:

$ cat dat/last-first.txt
36@xL!?\8
28?&gt;\4
42&lt;pX%7
37@#5
31kL%^?&gt;\&lt;#%5

And another with negative values and additional extraneous lines:

$ cat dat/last-first2.txt
36@xL!?\-8
28?&gt;\4
-42&lt;pX%7
Nothing to see!
37@#-5
31kL%^?&gt;\&lt;#%5

Example Use/Output

$ ./bin/fgets_strtol_any_last-first dat/last-first.txt
36@xL!?\8            :   36 -  8 =  28
28?&gt;\4            :   28 -  4 =  24
42&lt;pX%7           :   42 -  7 =  35
37@#5                :   37 -  5 =  32
31kL%^?&gt;\&lt;#%5  :   31 -  5 =  26

When run on the file with negative values and the extraneous line:

$ ./bin/fgets_strtol_any_last-first dat/last-first2.txt
36@xL!?\-8           :   36 - -8 =  44
28?&gt;\4            :   28 -  4 =  24
-42&lt;pX%7          :  -42 -  7 = -49
0 integer(s) in: 'Nothing to see!'
37@#-5               :   37 - -5 =  42
31kL%^?&gt;\&lt;#%5  :   31 -  5 =  26

As you can see from the result of the subtractions between the different files, it makes a great deal of difference whether you preserve the leading '-' when converting signed values. Something to consider going forward.

Look things over and let me know if you have additional questions.


问:
HTTP 2 request in python 2.7
Is there any difference in making request to HTTP/1 and HTTP/2 in python.

I can make HTTP/1.x calls in python like

```<code>url = 'http://someURL'
values = {'param1' : 'key',
          'param2' : 'key2'}
data = urllib.urlencode(values)
print data
req = urllib2.Request(url, data)
response = urllib2.urlopen(req)
the_page = response.read()
print the_page
</code>```

Is python supporting making HTTP/2 by default or should I add anything extra.

答:
For reference, as of 2019, another library supporting HTTP/2 is HTTPX.

HTTPX is a fully featured HTTP client for Python 3, which provides sync and async APIs, and support for both HTTP/1.1 and HTTP/2.

This requires at least Python 3.6. However, at the time of writing in 2020, Python 2 is already EOL, so Python 3.6 should be okay for any users.

ContentLicense: CC BY-SA 3.0

Title: HTTP 2 request in python 2.7

Body:
Is there any difference in making request to HTTP/1 and HTTP/2 in python.

I can make HTTP/1.x calls in python like

url = 'http://someURL'
values = {'param1' : 'key',
          'param2' : 'key2'}
data = urllib.urlencode(values)
print data
req = urllib2.Request(url, data)
response = urllib2.urlopen(req)
the_page = response.read()
print the_page

Is python supporting making HTTP/2 by default or should I add anything extra.


问:
Spring MVC with Boot: "There was an unexpected error (type=Not Found, status=404)"
So I'm new to Spring and I've so far gotten a simple web API running connected to a MongoDB database, but I'm having trouble generating just plain old views using .jsp or .html files. I've tried a variety of different approaches: InternalResourceViewResolver, XmlViewResolver, returning Strings instead of ModelAndView objects, nothing seems to be working for me. I have the following code:

Edit: here is a git repo with my project: https://github.com/jwallp/Spring-Test

As the above project is, I am getting a white label error upon going to /index which says:

```<code>There was an unexpected error (type=Internal Server Error, status=500).
Circular view path [index]: would dispatch back to the current handler URL [/index] again. Check your ViewResolver setup! (Hint: This may be the result of an unspecified view, due to default view name generation.)
</code>```

Edit: So I managed to get the view to finally load by using spring.view.prefix and spring.view.suffix instead of spring.mvc.view.prefix and such, and by moving my WEB-INF directory from my project root to inside <project root>/src/main/webapp/. I just wanted to know, if my WEB-INF directory is contained within another directory, will it still function as intended (making its contents not directly visible)?

答:
I have used mvn spring-boot:run

It's worked for me

Body:
So I'm new to Spring and I've so far gotten a simple web API running connected to a MongoDB database, but I'm having trouble generating just plain old views using .jsp or .html files. I've tried a variety of different approaches: InternalResourceViewResolver, XmlViewResolver, returning Strings instead of ModelAndView objects, nothing seems to be working for me. I have the following code:

Edit: here is a git repo with my project: https://github.com/jwallp/Spring-Test

As the above project is, I am getting a white label error upon going to /index which says:

There was an unexpected error (type=Internal Server Error, status=500).
Circular view path [index]: would dispatch back to the current handler URL [/index] again. Check your ViewResolver setup! (Hint: This may be the result of an unspecified view, due to default view name generation.)

Edit: So I managed to get the view to finally load by using spring.view.prefix and spring.view.suffix instead of spring.mvc.view.prefix and such, and by moving my WEB-INF directory from my project root to inside <project root>/src/main/webapp/. I just wanted to know, if my WEB-INF directory is contained within another directory, will it still function as intended (making its contents not directly visible)?


问:
What should we use instead of GoogleApiClient in Kotlin?
As we know, GoogleApiClient is deprecated and android studio gives error when we use its library for get data from google api. what should we use instead of GoogleApiClient?</p>

答:
What the documentation says:

Use GoogleApi based APIs instead. See Moving Past GoogleApiClient.

The reason is explained in that last link:

The code is dominated by the concept of a connection, despite using the simplified "automanage" feature. A GoogleApiClient is only connected when all APIs are available and the user has signed in (when APIs require it).

This model has a number of pitfalls:

Any connection failure prevents use of any of the requested APIs, but using multiple GoogleApiClient objects is unwieldy.

The concept of a "connection" is inappropriately overloaded. Connection failures can be result from Google Play services being missing or from authentication issues.

The developer has to track the connection state, because making some calls before onConnected is called will result in a crash.

Making a simple API call can mean waiting for two callbacks. One to wait until the GoogleApiClient is connected and another for the API call itself.

...

In general, the new GoogleApi-based APIs have the following benefits:

No connection logic, calls that require a connection are queued until a connection is available. Connections are pooled when appropriate and torn down when not in use, saving battery and preventing memory leaks.

Sign in is completely separated from APIs that consume GoogleSignInAccount which makes it easier to use authenticated APIs throughout your app.

Asynchronous API calls use the new Task API rather than PendingResult, which allows for easier management and chaining.


问:
ERROR: FATAL: password authentication failed for user "Django_test"
I am using Ubuntu 18.04 and PostgreSQL latest version. I need to do the setup for my Django Project and so I have created a new database with username and a new password with the following command in my terminal

```<code>alter user postgres with password 'test123';
</code>```

and for creating a new database :

```<code>create user Django_test with password 'test123';
</code>```

But once I check with the connection in my database I am getting the error as mentioned in the Title.
Can anyone help me with this?
Thanks in advance.

答:
Postgresql creates the user (role) in lower case.  Try to connect with user name django_test.

If you want the uppercase, do create user "Django_test" with password 'test123'.

Best regards,

Bjarni

Body:
I am using Ubuntu 18.04 and PostgreSQL latest version. I need to do the setup for my Django Project and so I have created a new database with username and a new password with the following command in my terminal

alter user postgres with password 'test123';

and for creating a new database :

create user Django_test with password 'test123';

But once I check with the connection in my database I am getting the error as mentioned in the Title.
Can anyone help me with this?
Thanks in advance.