问:
Getting generated view with MVC on Docker
I have a dotnet core application with authorization. Because company policy does not allow to store Bearer tokens on the front-end, I want to run it through an MVC Controller. However, I am running a SPA with Vue.js which is generated. So I have to return the generated index.cshtml from the Controller. This works locally in Kestrel, but once I deploy it to a Docker container it doesn't work anymore -- I suppose it has something to do with the way MVC expects files to be somewhere and this doesn't match how Docker handles it.

I've tried various ways to find the file on the pod. The app runs standard in /app; and the SPA was initially deployed to /app/wwwroot. I couldn't find a way to make the MVC Controller read from that folder. I changed the vue.js webpack to create an Index.cshtml and all required assets under /app/View/[ControllerName] but that didn't work either.

Dockerfile:

```<code>FROM microsoft/dotnet:2.2-aspnetcore-runtime

EXPOSE 80

# Create app directory
WORKDIR /app

# Copy files from the artifact staging folder on agent
COPY <ProjectName>/out .

RUN apt-get update -y && apt-get install ca-certificates -y && rm -rf /var/lib/apt/lists/*
ADD certificate.crt
ADD certificate2.crt
ADD certificate3.crt
RUN update-ca-certificates

ENTRYPOINT ["dotnet", "<ProjectName>.dll"]
</code>```

Expected result: the SPA loads.
Actual results: often MVC errors that it couldn't find the index.cshtml file in various locations. And it's always looking at the wrong locations, even though I'm trying to point it in the right direction. That was with trying to point at the vue.js under /app/wwwroot; with the SPA being generated under /Views/[ControllerName] it appears the buildserver isn't building it correctly to place it there and other strange things happen. At one time, apparently, it generated a HomeController; which the project doesn't have.

答:
I've been fidgeting around and I've ended up simply grabbing the generated file and return that as a response.

public ActionResult Index()
{
    try
    {
        var fileStream = new FileStream("/app/wwwroot/index.html", FileMode.Open);
        return File(fileStream, "text/html; charset=utf-8");
    }
    catch (Exception ex)
    {
        _logger.LogError($"Kon /app/wwwroot/index.html niet openen", ex);
    }

    return StatusCode(500);
 }
```

Body:
I have a dotnet core application with authorization. Because company policy does not allow to store Bearer tokens on the front-end, I want to run it through an MVC Controller. However, I am running a SPA with Vue.js which is generated. So I have to return the generated index.cshtml from the Controller. This works locally in Kestrel, but once I deploy it to a Docker container it doesn't work anymore -- I suppose it has something to do with the way MVC expects files to be somewhere and this doesn't match how Docker handles it.

I've tried various ways to find the file on the pod. The app runs standard in /app; and the SPA was initially deployed to /app/wwwroot. I couldn't find a way to make the MVC Controller read from that folder. I changed the vue.js webpack to create an Index.cshtml and all required assets under /app/View/[ControllerName] but that didn't work either.

Dockerfile:

FROM microsoft/dotnet:2.2-aspnetcore-runtime

EXPOSE 80

# Create app directory
WORKDIR /app

# Copy files from the artifact staging folder on agent
COPY <ProjectName>/out .

RUN apt-get update -y && apt-get install ca-certificates -y && rm -rf /var/lib/apt/lists/*
ADD certificate.crt
ADD certificate2.crt
ADD certificate3.crt
RUN update-ca-certificates

ENTRYPOINT ["dotnet", "<ProjectName>.dll"]

Expected result: the SPA loads.
Actual results: often MVC errors that it couldn't find the index.cshtml file in various locations. And it's always looking at the wrong locations, even though I'm trying to point it in the right direction. That was with trying to point at the vue.js under /app/wwwroot; with the SPA being generated under /Views/[ControllerName] it appears the buildserver isn't building it correctly to place it there and other strange things happen. At one time, apparently, it generated a HomeController; which the project doesn't have.


来源: stackexchange

问:
Use Sqlite & Knex with Node Module
im building a desktop app with electron and use for that JS and jQuery. All of them are installed as modules and used with "require" . it works perfect.

Now i want my database with sqlite and knex and try to start the node server with the knex and sqlite db together with the app.

but the problem is, that knex cant find the sqlite module.

can someone help me?

```<code>HERE is the start

console.log('SQL - Datenbank-Server gestartet');

let express = require('express');
let app = express();

let knex = require('knex');

let server = app.listen(8286, function () {
console.log('DB Server running on port 8286');
});

let connection = knex({
client: 'sqlite3',
connection: {
    filename: './finanzverwaltung.db'
}
});

HERE is the Failure
 Server gestartet.
SQL - Datenbank-Server gestartet
Knex: run
$ npm install sqlite3 --save
Cannot find module 'F:\Projekte\finanzverwaltung\node_modules\sqlite3\lib\binding\node-v70-win32-x64\node_sqlite3.node'
Require stack:
- F:\Projekte\finanzverwaltung\node_modules\sqlite3\lib\sqlite3.js
- F:\Projekte\finanzverwaltung\node_modules\knex\lib\dialects\sqlite3\index.js
- F:\Projekte\finanzverwaltung\node_modules\knex\lib\knex.js
- F:\Projekte\finanzverwaltung\node_modules\knex\lib\index.js
- F:\Projekte\finanzverwaltung\node_modules\knex\knex.js
- F:\Projekte\finanzverwaltung\app\server\sql_server.js
Error: Cannot find module 'F:\Projekte\finanzverwaltung\node_modules\sqlite3\lib\binding\node-v70-win32-x64\node_sqlite3.node'
Require stack:
- F:\Projekte\finanzverwaltung\node_modules\sqlite3\lib\sqlite3.js
- F:\Projekte\finanzverwaltung\node_modules\knex\lib\dialects\sqlite3\index.js
- F:\Projekte\finanzverwaltung\node_modules\knex\lib\knex.js
- F:\Projekte\finanzverwaltung\node_modules\knex\lib\index.js
- F:\Projekte\finanzverwaltung\node_modules\knex\knex.js
- F:\Projekte\finanzverwaltung\app\server\sql_server.js
    at Function.Module._resolveFilename (internal/modules/cjs/loader.js:659:15)
    at Function.Module._load (internal/modules/cjs/loader.js:577:27)
    at Module.require (internal/modules/cjs/loader.js:715:19)
    at require (internal/modules/cjs/helpers.js:14:16)
    at Object.<anonymous> (F:\Projekte\finanzverwaltung\node_modules\sqlite3\lib\sqlite3.js:4:15)
    at Module._compile (internal/modules/cjs/loader.js:808:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:820:10)
    at Module.load (internal/modules/cjs/loader.js:677:32)
    at tryModuleLoad (internal/modules/cjs/loader.js:609:12)
    at Function.Module._load (internal/modules/cjs/loader.js:601:3)
    at Module.require (internal/modules/cjs/loader.js:715:19)
    at require (internal/modules/cjs/helpers.js:14:16)
    at Client_SQLite3._driver (F:\Projekte\finanzverwaltung\node_modules\knex\lib\dialects\sqlite3\index.js:44:12)
    at Client_SQLite3.initializeDriver (F:\Projekte\finanzverwaltung\node_modules\knex\lib\client.js:253:26)
    at Client_SQLite3.Client (F:\Projekte\finanzverwaltung\node_modules\knex\lib\client.js:84:10)
    at new Client_SQLite3 (F:\Projekte\finanzverwaltung\node_modules\knex\lib\dialects\sqlite3\index.js:31:19)
F:\Projekte\finanzverwaltung\node_modules\knex\lib\client.js:257
      throw new Error(`${message}\n${e.message}`);
      ^

Error: Knex: run
$ npm install sqlite3 --save
Cannot find module 'F:\Projekte\finanzverwaltung\node_modules\sqlite3\lib\binding\node-v70-win32-x64\node_sqlite3.node'
Require stack:
- F:\Projekte\finanzverwaltung\node_modules\sqlite3\lib\sqlite3.js
- F:\Projekte\finanzverwaltung\node_modules\knex\lib\dialects\sqlite3\index.js
- F:\Projekte\finanzverwaltung\node_modules\knex\lib\knex.js
- F:\Projekte\finanzverwaltung\node_modules\knex\lib\index.js
- F:\Projekte\finanzverwaltung\node_modules\knex\knex.js
- F:\Projekte\finanzverwaltung\app\server\sql_server.js
    at Client_SQLite3.initializeDriver (F:\Projekte\finanzverwaltung\node_modules\knex\lib\client.js:257:13)
    at Client_SQLite3.Client (F:\Projekte\finanzverwaltung\node_modules\knex\lib\client.js:84:10)
    at new Client_SQLite3 (F:\Projekte\finanzverwaltung\node_modules\knex\lib\dialects\sqlite3\index.js:31:19)
    at Knex (F:\Projekte\finanzverwaltung\node_modules\knex\lib\knex.js:57:42)
    at Object.<anonymous> (F:\Projekte\finanzverwaltung\app\server\sql_server.js:12:18)
    at Module._compile (internal/modules/cjs/loader.js:808:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:820:10)
    at Module.load (internal/modules/cjs/loader.js:677:32)
    at tryModuleLoad (internal/modules/cjs/loader.js:609:12)
    at Function.Module._load (internal/modules/cjs/loader.js:601:3)
    at Function.Module.runMain (internal/modules/cjs/loader.js:873:10)
    at internal/main/run_main_module.js:21:11
</code>```

答:
You're running into problems when bundling sqlite together with electron. Electron builder will allow you to build electron for your platform architecture however will also have to be rebuilt for other systems attempting to run it. Once you have installed electron-rebuild via npm you can add the following script to your package.json.

```<code>"rebuild": "electron-rebuild -f -w sqlite3"
</code>```

then run:

```<code>npm run rebuild
</code>```

You might run into some additional errors for dependencies as I did on Windows needing Visual Studio build tools and python 2.

Here is a video tutorial I found on this topic: https://www.youtube.com/watch?v=c76FTxLRwAw&

Depending on your needs, instead of using sqlite directly with electron, an alternative would be to use a separate nodejs server to access your database which I found to be less of a headache.

ContentLicense: CC BY-SA 4.0

Title: Use Sqlite & Knex with Node Module

Body:
im building a desktop app with electron and use for that JS and jQuery. All of them are installed as modules and used with "require" . it works perfect.

Now i want my database with sqlite and knex and try to start the node server with the knex and sqlite db together with the app.

but the problem is, that knex cant find the sqlite module.

can someone help me?

HERE is the start

console.log('SQL - Datenbank-Server gestartet');

let express = require('express');
let app = express();

let knex = require('knex');

let server = app.listen(8286, function () {
console.log('DB Server running on port 8286');
});

let connection = knex({
client: 'sqlite3',
connection: {
    filename: './finanzverwaltung.db'
}
});

HERE is the Failure
 Server gestartet.
SQL - Datenbank-Server gestartet
Knex: run
$ npm install sqlite3 --save
Cannot find module 'F:\Projekte\finanzverwaltung\node_modules\sqlite3\lib\binding\node-v70-win32-x64\node_sqlite3.node'
Require stack:
- F:\Projekte\finanzverwaltung\node_modules\sqlite3\lib\sqlite3.js
- F:\Projekte\finanzverwaltung\node_modules\knex\lib\dialects\sqlite3\index.js
- F:\Projekte\finanzverwaltung\node_modules\knex\lib\knex.js
- F:\Projekte\finanzverwaltung\node_modules\knex\lib\index.js
- F:\Projekte\finanzverwaltung\node_modules\knex\knex.js
- F:\Projekte\finanzverwaltung\app\server\sql_server.js
Error: Cannot find module 'F:\Projekte\finanzverwaltung\node_modules\sqlite3\lib\binding\node-v70-win32-x64\node_sqlite3.node'
Require stack:
- F:\Projekte\finanzverwaltung\node_modules\sqlite3\lib\sqlite3.js
- F:\Projekte\finanzverwaltung\node_modules\knex\lib\dialects\sqlite3\index.js
- F:\Projekte\finanzverwaltung\node_modules\knex\lib\knex.js
- F:\Projekte\finanzverwaltung\node_modules\knex\lib\index.js
- F:\Projekte\finanzverwaltung\node_modules\knex\knex.js
- F:\Projekte\finanzverwaltung\app\server\sql_server.js
    at Function.Module._resolveFilename (internal/modules/cjs/loader.js:659:15)
    at Function.Module._load (internal/modules/cjs/loader.js:577:27)
    at Module.require (internal/modules/cjs/loader.js:715:19)
    at require (internal/modules/cjs/helpers.js:14:16)
    at Object.<anonymous> (F:\Projekte\finanzverwaltung\node_modules\sqlite3\lib\sqlite3.js:4:15)
    at Module._compile (internal/modules/cjs/loader.js:808:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:820:10)
    at Module.load (internal/modules/cjs/loader.js:677:32)
    at tryModuleLoad (internal/modules/cjs/loader.js:609:12)
    at Function.Module._load (internal/modules/cjs/loader.js:601:3)
    at Module.require (internal/modules/cjs/loader.js:715:19)
    at require (internal/modules/cjs/helpers.js:14:16)
    at Client_SQLite3._driver (F:\Projekte\finanzverwaltung\node_modules\knex\lib\dialects\sqlite3\index.js:44:12)
    at Client_SQLite3.initializeDriver (F:\Projekte\finanzverwaltung\node_modules\knex\lib\client.js:253:26)
    at Client_SQLite3.Client (F:\Projekte\finanzverwaltung\node_modules\knex\lib\client.js:84:10)
    at new Client_SQLite3 (F:\Projekte\finanzverwaltung\node_modules\knex\lib\dialects\sqlite3\index.js:31:19)
F:\Projekte\finanzverwaltung\node_modules\knex\lib\client.js:257
      throw new Error(`${message}\n${e.message}`);
      ^

Error: Knex: run
$ npm install sqlite3 --save
Cannot find module 'F:\Projekte\finanzverwaltung\node_modules\sqlite3\lib\binding\node-v70-win32-x64\node_sqlite3.node'
Require stack:
- F:\Projekte\finanzverwaltung\node_modules\sqlite3\lib\sqlite3.js
- F:\Projekte\finanzverwaltung\node_modules\knex\lib\dialects\sqlite3\index.js
- F:\Projekte\finanzverwaltung\node_modules\knex\lib\knex.js
- F:\Projekte\finanzverwaltung\node_modules\knex\lib\index.js
- F:\Projekte\finanzverwaltung\node_modules\knex\knex.js
- F:\Projekte\finanzverwaltung\app\server\sql_server.js
    at Client_SQLite3.initializeDriver (F:\Projekte\finanzverwaltung\node_modules\knex\lib\client.js:257:13)
    at Client_SQLite3.Client (F:\Projekte\finanzverwaltung\node_modules\knex\lib\client.js:84:10)
    at new Client_SQLite3 (F:\Projekte\finanzverwaltung\node_modules\knex\lib\dialects\sqlite3\index.js:31:19)
    at Knex (F:\Projekte\finanzverwaltung\node_modules\knex\lib\knex.js:57:42)
    at Object.<anonymous> (F:\Projekte\finanzverwaltung\app\server\sql_server.js:12:18)
    at Module._compile (internal/modules/cjs/loader.js:808:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:820:10)
    at Module.load (internal/modules/cjs/loader.js:677:32)
    at tryModuleLoad (internal/modules/cjs/loader.js:609:12)
    at Function.Module._load (internal/modules/cjs/loader.js:601:3)
    at Function.Module.runMain (internal/modules/cjs/loader.js:873:10)
    at internal/main/run_main_module.js:21:11

Body:
You're running into problems when bundling sqlite together with electron. Electron builder will allow you to build electron for your platform architecture however will also have to be rebuilt for other systems attempting to run it. Once you have installed electron-rebuild via npm you can add the following script to your package.json.

"rebuild": "electron-rebuild -f -w sqlite3"

then run:

npm run rebuild

You might run into some additional errors for dependencies as I did on Windows needing Visual Studio build tools and python 2.

Here is a video tutorial I found on this topic: https://www.youtube.com/watch?v=c76FTxLRwAw&

Depending on your needs, instead of using sqlite directly with electron, an alternative would be to use a separate nodejs server to access your database which I found to be less of a headache.


问:
How to restrict the import of a Module in F# to a local scope?
Is it possible to locally restrict the import of a module, preferrably combining this with Module Abbreviations? The goal is to avoid polluting my current module with symbols from imports.

e.g. (inspired by OCaml) something like that:

```<code>let numOfEvenIntegersSquaredGreaterThan n =
    let module A = Microsoft.FSharp.Collections.Array in
        [|1..100|] |> A.filter (fun x -> x % 2 = 0)
                   |> A.map    (fun x -> x * x)
                   |> A.filter (fun x -> x > n)
                   |> A.length

let elementsGreaterThan n =
    let module A = Microsoft.FSharp.Collections.List in
        [1..100] |> A.filter (fun x -> x > n)
</code>```

Additionally is there a way to achieve something similar with namespaces?

答:
The goal is to avoid polluting my
  current module with symbols from
  imports.

Note that open Array is not allowed in F# (contrary to OCaml).
You can use abbreviations on modules, but only in the global scope:

```<code>module A = Microsoft.FSharp.Collections.Array
</code>```

Instead of Microsoft.FSharp.Collections.Array, you can use Array. So your code would be:

```<code>let numOfEvenIntegersSquaredGreaterThan n =
    [|1..100|] |> Array.filter (fun x -> x % 2 = 0)
               |> Array.map    (fun x -> x * x)
               |> Array.filter (fun x -> x > n)
               |> Array.length
</code>```

If you want to reuse the same code for Arrays and Lists, you might want to use the Seq module:

```<code>let elementsGreaterThan n =
    [1..100] |> Seq.filter (fun x -> x > n)
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Is it possible to locally restrict the import of a module, preferrably combining this with Module Abbreviations? The goal is to avoid polluting my current module with symbols from imports.

e.g. (inspired by OCaml) something like that:

let numOfEvenIntegersSquaredGreaterThan n =
    let module A = Microsoft.FSharp.Collections.Array in
        [|1..100|] |> A.filter (fun x -> x % 2 = 0)
                   |> A.map    (fun x -> x * x)
                   |> A.filter (fun x -> x > n)
                   |> A.length

let elementsGreaterThan n =
    let module A = Microsoft.FSharp.Collections.List in
        [1..100] |> A.filter (fun x -> x > n)

Additionally is there a way to achieve something similar with namespaces?

Body:
The goal is to avoid polluting my
  current module with symbols from
  imports.

Note that open Array is not allowed in F# (contrary to OCaml).
You can use abbreviations on modules, but only in the global scope:

module A = Microsoft.FSharp.Collections.Array

Instead of Microsoft.FSharp.Collections.Array, you can use Array. So your code would be:

let numOfEvenIntegersSquaredGreaterThan n =
    [|1..100|] |> Array.filter (fun x -> x % 2 = 0)
               |> Array.map    (fun x -> x * x)
               |> Array.filter (fun x -> x > n)
               |> Array.length

If you want to reuse the same code for Arrays and Lists, you might want to use the Seq module:

let elementsGreaterThan n =
    [1..100] |> Seq.filter (fun x -> x > n)


问:
Take tail of variadic template parameters
Given this type:

```<code>template<typename ...As>
struct Base {};
</code>```

I need to implement a function

```<code>template<int i, typename ...As>
constexpr auto Tail() {
   static_assert(i < sizeof...(As), "index out of range");
   return ??;
}
</code>```

which returns an instance of B using the tail of type parameter list from index i.

For example,

```<code>Tail<0, int, float, double>() -> Base<int, float, double>
Tail<1, int, float, double>() -> Base<float, double>
Tail<2, int, float, double>() -> Base<double>
Tail<3, int, float, double>() -> fails with static assert
</code>```

I know how to get the type at index i :

```<code>template <int64_t i, typename T, typename... Ts>
struct type_at
{
    static_assert(i < sizeof...(Ts) + 1, "index out of range");
    typedef typename type_at<i - 1, Ts...>::type type;
};

template <typename T, typename... Ts> struct type_at<0, T, Ts...> {
    typedef T type;
};
</code>```

but I can't get a working version for the entire problem.

答:
For Tail (why is it a function?), the approach can be almost the same as that of type_at. The only thing you have to change is the base case of the recursion:

```<code>template <typename ... Ts>
struct types_from<0, Ts...> {
    using type = Base<Ts...>; // we don't like nasty typedef syntax
};
</code>```

Body:
Given this type:

template<typename ...As>
struct Base {};

I need to implement a function

template<int i, typename ...As>
constexpr auto Tail() {
   static_assert(i < sizeof...(As), "index out of range");
   return ??;
}

which returns an instance of B using the tail of type parameter list from index i.

For example,

Tail<0, int, float, double>() -> Base<int, float, double>
Tail<1, int, float, double>() -> Base<float, double>
Tail<2, int, float, double>() -> Base<double>
Tail<3, int, float, double>() -> fails with static assert

I know how to get the type at index i :

template <int64_t i, typename T, typename... Ts>
struct type_at
{
    static_assert(i < sizeof...(Ts) + 1, "index out of range");
    typedef typename type_at::type type;
};

template <typename T, typename... Ts> struct type_at<0, T, Ts...> {
    typedef T type;
};

but I can't get a working version for the entire problem.

Body:
For Tail (why is it a function?), the approach can be almost the same as that of type_at. The only thing you have to change is the base case of the recursion:

template <typename ... Ts>
struct types_from<0, Ts...> {
    using type = Base<Ts...>; // we don't like nasty typedef syntax
};


问:
Internet Explorer 11 aborting mp4 requests
We have an online video library for corporate and institutional clients, and recently we obtained a client, using IE11 and Windows 7 with a corporate proxy, who are having trouble viewing videos. We know it's not a firewall issue because they can watch the first video on the page (each web page has multiple videos), but any subsequent request for the mp4 is aborted by IE11, and the request is never made. So far we have

added the domain to trusted sites

added the domain to the registry

changing the endpoint and domain of the video requests

The users have no issue when testing in Chrome or IE11 on Windows 10 -- it seems to be strictly an issue with Windows 7.  We would like to provide guidance to this organization but we're really out of ideas.  Just wondering whether anyone else has had a similar issue, and can point me in the right direction.

UPDATE

We were able to get this to play by  removing the https value from the reigstry key for both the domain of the website and the domain of the video endpoint on HKEY_CURRENT_MACHINE ( Preferences > Software > Microsoft > Windows > CurrentVersion > Internet Settings > ZoneMap >Domains ).  My understanding is that this changes the site from 'Trusted Zone' to 'Internet Zone'. Unfortunately, while this worked in playing the videos, it actually blocked font files from being downloaded, and now our play/pause buttons (which use font glyphs) are missing.

答:
You could use the following method to allow IE browser to download the font:

Using Internet options

Open the Internet Tools, and click the Internet Options, under the Security tab, select a zone to change security settings. Click the "Custom level…", in the popup modal, find the Fond download  option and select the Enable option.
Finally, click the OK button to apply the setting.

Using Registry key settings.

(1) Open Run window and type regedit to open registry editor.

(2) Navigate to location below.
Computer\HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Internet Settings\Zones\3

(3) Find the "1604" registry key.

(4) Double click on it and set its desired value. (To disable : 3, To enable : 0, To prompt : 1)

(5) Click on OK to close the dialog.

(6) Restart Internet Explorer to take effect of changes.


问:
Invalid redirect_uri even though they are the same
When trying to login to identityserver (using .net core 3 preview) I get Invalid redirect_uri error even though the request uri and the allowed one are identical.

What else could I be doing wrong?

fail: IdentityServer4.Validation.AuthorizeRequestValidator[0]
      Invalid redirect_uri: http://localhost:1337/authentication/login-callback
{
        "ClientId": "myapp",
        "ClientName": "myapp",
        "AllowedRedirectUris": [
          "http://localhost:1337/authentication/login-callback"
        ],
        "SubjectId": "anonymous",
        "RequestedScopes": "",
        "Raw": {
          "client_id": "myapp",
          "redirect_uri": "http://localhost:1337/authentication/login-callback",
          "response_type": "id_token token",
          "scope": "webAPI openid profile",
          "state": "5a10fc5a7006475c8d3a348c711ca58a",
          "nonce": "ae6f9f35837241e1ba3841c2ff8a4fce",
          "prompt": "none"
        }
      }
fail: IdentityServer4.Endpoints.AuthorizeEndpoint[0]
      Request validation failed
```

答:
I was using the wrong profile in the new identity server features in core 3. Was using "IdentitySpa" - should have been "SPA"

https://learn.microsoft.com/en-us/aspnet/core/security/authentication/identity-api-authorization?view=aspnetcore-3.0#other-configuration-options


问:
How do I get Reqid from Below Screen shot?
How do I get Reqid and Xdata here?

Result is coming from Odata service. I need to map Reqid and Xdata accordingly here.

How do i get this value?

答:
You will need to loop through the array and get the reqid and Xdata for each result in the array, something like this:</p>

```<code>    var i;
    for (i = 0; i < results.length; i++) {
       var reqID = results[i].Reqid;
       var xData = results[i].Xdata ;
    }
</code>```

Body:
You will need to loop through the array and get the reqid and Xdata for each result in the array, something like this:

    var i;
    for (i = 0; i < results.length; i++) {
       var reqID = results[i].Reqid;
       var xData = results[i].Xdata ;
    }


问:
How to get Time span values(Format HH:mm:ss) from the Kendo Timepicker
I am setting a time picker using the Kendo time picker, which displays in the format "HH:mm:ss" but not binding properly, shows the Date along with it.
Please Check this link.
Example usage of Kendo UI for Angular
https://www.telerik.com/kendo-angular-ui/components/dateinputs/timepicker/formats/

I tried with pipes too (with this link https://loiane.com/2017/08/angular-tips-formatting-dates-with-a-custom-date-pipe-dd-mm-yyyy/ ). But that too not working. Please help me.

```<code> <div class="example-wrapper" style="min-height: 400px;">
          <div class="col-xs-12 col-sm-6 example-col">
              <p>Select a long time: {{value}}</p> // Problem Here
              <kendo-timepicker
                  [format]="'HH:mm:ss'"
                  [value]="value"
              ></kendo-timepicker>
          </div>

          <div class="col-xs-12 col-sm-6 example-col">
              <p>Select a short time:</p>
              <kendo-timepicker
                  [format]="'hh:mm a'"
                  [value]="value"
              ></kendo-timepicker>
          </div>
      </div>
</code>```

Expected Result : 00:00:00(timestamps) to bound near {{value}}, which is to be used in the forms.

答:
Link 2 is working , by removing the ${Constants.DATE_FMT} thus

```<code>static readonly DATE_TIME_FMT = `${Constants.DATE_FMT} hh:mm:ss`;
</code>```

becomes

```<code>static readonly DATE_TIME_FMT = `hh:mm:ss`;
</code>```

Body:
I am setting a time picker using the Kendo time picker, which displays in the format "HH:mm:ss" but not binding properly, shows the Date along with it.
Please Check this link.
Example usage of Kendo UI for Angular
https://www.telerik.com/kendo-angular-ui/components/dateinputs/timepicker/formats/

I tried with pipes too (with this link https://loiane.com/2017/08/angular-tips-formatting-dates-with-a-custom-date-pipe-dd-mm-yyyy/ ). But that too not working. Please help me.

Select a long time: {{value}}
 // Problem Here
              <kendo-timepicker
                  [format]="'HH:mm:ss'"
                  [value]="value"
              ></kendo-timepicker>

Select a short time:

              <kendo-timepicker
                  [format]="'hh:mm a'"
                  [value]="value"
              ></kendo-timepicker>

Expected Result : 00:00:00(timestamps) to bound near {{value}}, which is to be used in the forms.

Body:
Link 2 is working , by removing the ${Constants.DATE_FMT} thus

static readonly DATE_TIME_FMT = `${Constants.DATE_FMT} hh:mm:ss`;

becomes

static readonly DATE_TIME_FMT = `hh:mm:ss`;


问:
What is the R script for the "isectpolyrst" from GME?
I'm trying to summarize raster cell values in overlapping polygons in ArcMap. This can be done in Geospatial Modelling Environment (GME), an extension for ArcMap. They have a command called isectpolyrst that calculates for values in overlapping polygons. My problem is, my version of ArcGIS (10.6.2), doesn't support the use of GME, so I can't use this function. I've heard that isectpolyrst can still accomplished in R Studio using R script, but I haven't found it anywhere.

I have a number of GPS points with 10 km buffers around them (these buffers overlap a lot). I'm trying to calculate proportions of different vegetation types within these buffer zones. I'm using ArcMap 10.6.2., and zonal statistics can't calculate for overlapping polygons.

答: You can use raster::extract for that. As you seem entirely new to R, you will need to study it a bit first. You can start here: https://rspatial.org/


问:
How to add data in list below previous one?
I want to add data in list. When I click the button, it takes data from different classes and adds it as a row in the list and comes back.

And again, when I insert data in form and press the button, it adds it below the previous one on another row. So an array is created of rows, and now when I click on any position of list item row, I get its content. So how to implement it?

答: First thing you need to do is whenever you add new data in the list you should call notifyDataSetChanged(). For getting its content you need to write onItemClickListener() and in listener you can get the content through its position id.


问:
Where to get the exclusion items in Spring Boot Starter Packages
I'm using Spring initializr to have the necessary package and downloading. Once I download, there are changes that I'm making in the pom.xml like excluding packages like slf4j, logging (when i plan to use log4j2) and excluding tomcat when trying to deploy into standalone server.

I don't know what are the other items that are capable to exclude. Is there any documentation like which package contains additional artifacts? Trying to avoid certain jars while packaging so that I think I can reduce the package(jar/war) size.

```<code><dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-jpa</artifactId>
    <exclusions>
        <exclusion>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-logging</artifactId>
        </exclusion>
    </exclusions>
</dependency>

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-batch</artifactId>
    <exclusions>
        <exclusion>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-tomcat</artifactId>
        </exclusion>
    </exclusions>
</dependency>

<dependency>
    <groupId>org.seleniumhq.selenium</groupId>
    <artifactId>selenium-java</artifactId>
        <exclusions>
            <exclusion>
                <artifactId>commons-logging</artifactId>
                <groupId>commons-logging</groupId>
            </exclusion>
        </exclusions>
</dependency>

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
    <exclusions>
        <exclusion>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-tomcat</artifactId>
        </exclusion>
    </exclusions>
</dependency>
</code>```

答:
All spring boot starter packages can be found here:

https://github.com/spring-projects/spring-boot/tree/master/spring-boot-project/spring-boot-starters

They are all just pom.xml files. You can exclude anything you want from any dependency you are using by analyzing the pom's dependencies in the started packages.

Body:
I'm using Spring initializr to have the necessary package and downloading. Once I download, there are changes that I'm making in the pom.xml like excluding packages like slf4j, logging (when i plan to use log4j2) and excluding tomcat when trying to deploy into standalone server.

I don't know what are the other items that are capable to exclude. Is there any documentation like which package contains additional artifacts? Trying to avoid certain jars while packaging so that I think I can reduce the package(jar/war) size.

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-jpa</artifactId>
    <exclusions>
        <exclusion>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-logging</artifactId>
        </exclusion>
    </exclusions>
</dependency>

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-batch</artifactId>
    <exclusions>
        <exclusion>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-tomcat</artifactId>
        </exclusion>
    </exclusions>
</dependency>

<dependency>
    <groupId>org.seleniumhq.selenium</groupId>
    <artifactId>selenium-java</artifactId>
        <exclusions>
            <exclusion>
                <artifactId>commons-logging</artifactId>
                <groupId>commons-logging</groupId>
            </exclusion>
        </exclusions>
</dependency>

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
    <exclusions>
        <exclusion>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-tomcat</artifactId>
        </exclusion>
    </exclusions>
</dependency>


问:
How to get parameters of a step with multiple pipelines in cucumber for the java code?
I have below steps in my feature file for a scenario.

```<code>Given my_first_step

And my_second_step
  | Themes          | one | three |

  | Service Windows | two | four  |

And my_third_step

  | Create Apps |

  | Config      |
</code>```

we can get parameters of 'my_third_step' as below in the java code as a list

public void my_third_step(List listOfItems) {}

but how can get parameters in 'my_second_step' ?
I need to get a rows as array of elements in the java code. How can I do that ?

答:
You have to pass a list of objects, your object will look like

```<code>public class MyObject {
    private Integer themes;
    private Integer service;

    public Integer getThemes() {
       return this.themes;
    }

    public void setThemes(Integer themes) {
       this.themes = themes;
    }

    public Integer getService() {
       return this.service;
    }

    public void setService(Integer service) {
       this.service = service;
    }
}
</code>```

Then you can pass a List<MyObject> to the method.

```<code>public void my_second_step(List<MyObject>) {
...
}
</code>```

In the feature file change the definition as follows:

```<code>And my_second_step
  | Themes          | Service |
  | one             | two     |
  | three           | four    |
</code>```

I hope this helps.

Body:
I have below steps in my feature file for a scenario.

Given my_first_step

And my_second_step
  | Themes          | one | three |

  | Service Windows | two | four  |

And my_third_step

  | Create Apps |

  | Config      |

we can get parameters of 'my_third_step' as below in the java code as a list

public void my_third_step(List listOfItems) {}

but how can get parameters in 'my_second_step' ?
I need to get a rows as array of elements in the java code. How can I do that ?

Body:
You have to pass a list of objects, your object will look like

public class MyObject {
    private Integer themes;
    private Integer service;

    public Integer getThemes() {
       return this.themes;
    }

    public void setThemes(Integer themes) {
       this.themes = themes;
    }

    public Integer getService() {
       return this.service;
    }

    public void setService(Integer service) {
       this.service = service;
    }
}

Then you can pass a List<MyObject> to the method.

public void my_second_step(List<MyObject>) {
...
}

In the feature file change the definition as follows:

And my_second_step
  | Themes          | Service |
  | one             | two     |
  | three           | four    |

I hope this helps.


问:
How to set count of c# without altering capacity?
I know exactly how many items I want to keep in a list, they are ordered, I only need it to finish at an specific index I know, but I don't want to alter the capacity or use TrimExcess in order to make it smaller, otherwise after adding an item again it will double the size of the list again.

How can I set the Count instead of using Remove or RemoveAt or RemoveRange?.

My priority is optimization of speed for this operation.

Important: I know I can use an array, but I am not allowed. Also, I'm adding items and removing them all the time. I just want the capacity to stay around a similar amount which I don't know exactly but it will stabilize.

答:
Use an array and (in C# 8.0 onwards) use Indices and Ranges with slicing.
https://learn.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-8#indices-and-ranges</p>


问:
URL Concatenate in report builder
In Report Builder I want to build a Action URL that requires concatenation.

This is what I've tried so far:

```<code>="https://synergy.pumpnseal.com/enterprise/docs/WflRequest.aspx?Mode=1&ID=%" + Fields!id.Value + "%7d&BCAction=1"
</code>```

答:
Try:

```<code>="https://synergy.pumpnseal.com/enterprise/docs/WflRequest.aspx?Mode=1&ID=%" & cstr(Fields!id.Value) & "%7d&BCAction=1"
</code>```

I'm not sure if there's any real difference in this instance between + and &, but I always use & to be explicit that I mean concatenate and not add.

Title: URL Concatenate in report builder

Body:
In Report Builder I want to build a Action URL that requires concatenation.

This is what I've tried so far:

="https://synergy.pumpnseal.com/enterprise/docs/WflRequest.aspx?Mode=1&ID=%" + Fields!id.Value + "%7d&BCAction=1"

Body:
Try:

="https://synergy.pumpnseal.com/enterprise/docs/WflRequest.aspx?Mode=1&ID=%" & cstr(Fields!id.Value) & "%7d&BCAction=1"

I'm not sure if there's any real difference in this instance between + and &, but I always use & to be explicit that I mean concatenate and not add.


问:
Recoding specific column values using reference list
My dataframe looks like this

```<code>data = data.frame(ID=c(1,2,3,4,5,6,7,8,9,10),
              Gender=c('Male','Female','Female','Female','Male','Female','Male','Male','Female','Female'))
</code>```

And I have a reference list that looks like this -

```<code>ref=list(Male=1,Female=2)
</code>```

I'd like to replace values in the Gender column using this reference list, without adding a new column to my dataframe.

Here's my attempt

```<code>do.call(dplyr::recode, c(list(data), ref))
</code>```

Which gives me the following error -

no applicable method for 'recode' applied to an object of class
  "data.frame"

Any inputs would be greatly appreciated

答:
You can unlist ref to give you a named vector of codes, and then index this with your data:

```<code>transform(data,Gender=unlist(ref)[as.character(Gender)])
   ID Gender
1   1      1
2   2      2
3   3      2
4   4      2
5   5      1
6   6      2
7   7      1
8   8      1
9   9      2
10 10      2
</code>```

Body:
My dataframe looks like this

data = data.frame(ID=c(1,2,3,4,5,6,7,8,9,10),
              Gender=c('Male','Female','Female','Female','Male','Female','Male','Male','Female','Female'))

And I have a reference list that looks like this -

ref=list(Male=1,Female=2)

I'd like to replace values in the Gender column using this reference list, without adding a new column to my dataframe.

Here's my attempt

do.call(dplyr::recode, c(list(data), ref))

Which gives me the following error -

no applicable method for 'recode' applied to an object of class
  "data.frame"

Any inputs would be greatly appreciated

Body:
You can unlist ref to give you a named vector of codes, and then index this with your data:

transform(data,Gender=unlist(ref)[as.character(Gender)])
   ID Gender
1   1      1
2   2      2
3   3      2
4   4      2
5   5      1
6   6      2
7   7      1
8   8      1
9   9      2
10 10      2


问:
php address request
i have this request method:

```<code>if (!$_REQUEST['0'])  {
    echo "Address missing...";
    die();
} else {
    code
    code etc.
}
</code>```

And address is: http://localhost/api.php?0=address

If I open: api.php?0=0 I should get another error which says address doesn't correct. But I get Address missing... In my opinion something wrong with:

```<code>if (!$_REQUEST['0'])
</code>```

Any ideas?

答:
You're checking if $_REQUEST['0'] is false. In PHP (and many other languages), 0 stands for false. Because 0 == false, your expression results in 'true' and the echo and die() are executed.

If you are trying to test if $_REQUEST['0'] exists, you should use isset() or empty()

Title: php address request

Body:
i have this request method:

if (!$_REQUEST['0'])  {
    echo "Address missing...";
    die();
} else {
    code
    code etc.
}

And address is: http://localhost/api.php?0=address

If I open: api.php?0=0 I should get another error which says address doesn't correct. But I get Address missing... In my opinion something wrong with:

if (!$_REQUEST['0'])

Any ideas?


问:
How to extract elements of a list in R?
I have a list with several vectors which looks like this : </p>

```<code>$`56`
[1] "OTU2998"             "UniRef90_A0A1Z9FS94" "UniRef90_A0A257ESC3"
[4] "UniRef90_A0A293NAV3" "UniRef90_A0A2E1NMU8" "UniRef90_A0A2E1NPX9"
[7] "UniRef90_A0A2E1NQL1" "UniRef90_A0A2E1NRD2" "UniRef90_X0UC66"

$`57`
[1] "OTU3820"             "UniRef90_A0A1Z9H3N2" "UniRef90_A0A2D5I161"
[4] "UniRef90_A0A2E6PRN5"

$`58`
[1] "OTU4452"                "UniRef90_A0A1Z9KBI8"    "UniRef90_A0A2E1VTI6"
[4] "UniRef90_A0A2G2KCN6"    "UniRef90_UPI000BFEC744"

$`59`
[1] "OTU0245"             "UniRef90_A0A1Z9MPM9" "UniRef90_A0A2E2ME98"
[4] "UniRef90_A0A2E8X9N7"

</code>```

<p>Is there a way to only extract the "OTUXXX" information? I mean, I would like to get something like this : </p>

```<code>$`56`
[1] "OTU2998"

$`57`
[1] "OTU3820"

$`58`
[1] "OTU4452"

$`59`
[1] "OTU0245"

</code>```

答:
We can loop through the list and extract the elements that match the substring 'OTU' at the beginning (^) of the string followed by four digits (\\d{4}) till the end ($) of the string with grepl

```<code>lapply(lst1, function(x) x[grepl("^OTU\\d{4}$", x)])
#$`56`
#[1] "OTU2998"

#$`57`
#[1] "OTU3820"

#$`58`
#[1] "OTU4452"

#$`59`
#[1] "OTU0245" "OTU1234"
</code>```

NOTE: Using only base R methods

Or if we are a tidyverse aficionado, then use keep

```<code>library(tidyverse)
map(lst1, keep, str_detect, '^OTU\\d{4}$')
</code>```

data

```<code>lst1 <-  list(
  `56` = c("OTU2998", "UniRef90_A0A1Z9FS94", "UniRef90_A0A257ESC3", "UniRef90_A0A293NAV3", "UniRef90_A0A2E1NMU8", "UniRef90_A0A2E1NPX9", "UniRef90_A0A2E1NQL1", "UniRef90_A0A2E1NRD2", "UniRef90_X0UC66"),
  `57` = c("OTU3820", "UniRef90_A0A1Z9H3N2", "UniRef90_A0A2D5I161", "UniRef90_A0A2E6PRN5"),
  `58` = c("OTU4452", "UniRef90_A0A1Z9KBI8", "UniRef90_A0A2E1VTI6", "UniRef90_A0A2G2KCN6", "UniRef90_UPI000BFEC744"),
  `59` = c("OTU0245", "UniRef90_A0A1Z9MPM9", "UniRef90_A0A2E2ME98", "UniRef90_A0A2E8X9N7", "OTU1234")
)
</code>```

Title: How to extract elements of a list in R?

Body:
I have a list with several vectors which looks like this :

$`56`
[1] "OTU2998"             "UniRef90_A0A1Z9FS94" "UniRef90_A0A257ESC3"
[4] "UniRef90_A0A293NAV3" "UniRef90_A0A2E1NMU8" "UniRef90_A0A2E1NPX9"
[7] "UniRef90_A0A2E1NQL1" "UniRef90_A0A2E1NRD2" "UniRef90_X0UC66"

$`57`
[1] "OTU3820"             "UniRef90_A0A1Z9H3N2" "UniRef90_A0A2D5I161"
[4] "UniRef90_A0A2E6PRN5"

$`58`
[1] "OTU4452"                "UniRef90_A0A1Z9KBI8"    "UniRef90_A0A2E1VTI6"
[4] "UniRef90_A0A2G2KCN6"    "UniRef90_UPI000BFEC744"

$`59`
[1] "OTU0245"             "UniRef90_A0A1Z9MPM9" "UniRef90_A0A2E2ME98"
[4] "UniRef90_A0A2E8X9N7"

Is there a way to only extract the "OTUXXX" information? I mean, I would like to get something like this :

$`56`
[1] "OTU2998"

$`57`
[1] "OTU3820"

$`58`
[1] "OTU4452"

$`59`
[1] "OTU0245"

Body:
We can loop through the list and extract the elements that match the substring 'OTU' at the beginning (^) of the string followed by four digits (\\d{4}) till the end ($) of the string with grepl

lapply(lst1, function(x) x[grepl("^OTU\\d{4}$", x)])
#$`56`
#[1] "OTU2998"

#$`57`
#[1] "OTU3820"

#$`58`
#[1] "OTU4452"

#$`59`
#[1] "OTU0245" "OTU1234"

NOTE: Using only base R methods

Or if we are a tidyverse aficionado, then use keep

library(tidyverse)
map(lst1, keep, str_detect, '^OTU\\d{4}$')

data

lst1 <-  list(
  `56` = c("OTU2998", "UniRef90_A0A1Z9FS94", "UniRef90_A0A257ESC3", "UniRef90_A0A293NAV3", "UniRef90_A0A2E1NMU8", "UniRef90_A0A2E1NPX9", "UniRef90_A0A2E1NQL1", "UniRef90_A0A2E1NRD2", "UniRef90_X0UC66"),
  `57` = c("OTU3820", "UniRef90_A0A1Z9H3N2", "UniRef90_A0A2D5I161", "UniRef90_A0A2E6PRN5"),
  `58` = c("OTU4452", "UniRef90_A0A1Z9KBI8", "UniRef90_A0A2E1VTI6", "UniRef90_A0A2G2KCN6", "UniRef90_UPI000BFEC744"),
  `59` = c("OTU0245", "UniRef90_A0A1Z9MPM9", "UniRef90_A0A2E2ME98", "UniRef90_A0A2E8X9N7", "OTU1234")
)


问:
How to get rows of a most recent day in the ascending order of time way when reading csv file?
I want to get rows of a most recent day which is in ascending order of time way.

I get dataframe as follows:

```<code>    label      uId          adId    operTime                    siteId  slotId  contentId   netType
0   0          u147333631   3887    2019-03-30 15:01:55.617     10      30      2137        1
1   0          u146930169   1462    2019-03-31 09:51:15.275     3       32      1373        1
2   0          u139816523   2084    2019-03-27 08:10:41.769     10      30      2336        1
3   0          u106546472   1460    2019-03-31 08:51:41.085     3       32      1371        4
4   0          u106642861   2295    2019-03-27 22:58:03.679     3       32      2567        4
</code>```

Cause I get about 100 million rows in this csv file, it is impossible to load all this into my PC memory.

So I want to get rows of a most recent day in ascending order of time way when reading this csv files.

For examples, if the most recent day is on 2019-04-04, it will output as follows:

```<code>#this not a real data, just for examples.
    label      uId          adId    operTime                    siteId  slotId  contentId   netType
0   0          u147336431   3887    2019-04-04 00:08:42.315     1       54      2427        2
1   0          u146933269   1462    2019-04-04 01:06:16.417     30      36      1343        6
2   0          u139536523   2084    2019-04-04 02:08:58.079     15      23      1536        7
3   0          u106663472   1460    2019-04-04 03:21:13.050     32      45      1352        2
4   0          u121642861   2295    2019-04-04 04:36:08.653     3       33      3267        4
</code>```

Could anyone help me?

Thanks in advence.

答:
Like @anky_91 mentionned, you can use the sort_values function. Here is a short example of how it works:

```<code>df = pd.DataFrame( {'Symbol':['A','A','A'] ,
    'Date':['02/20/2015','01/15/2016','08/21/2015']})
df.sort_values(by='Date')
</code>```

Out :

```<code>Date    Symbol
2   08/21/2015  A
0   02/20/2015  A
1   01/15/2016  A
</code>```

Body:
I want to get rows of a most recent day which is in ascending order of time way.

I get dataframe as follows:

    label      uId          adId    operTime                    siteId  slotId  contentId   netType
0   0          u147333631   3887    2019-03-30 15:01:55.617     10      30      2137        1
1   0          u146930169   1462    2019-03-31 09:51:15.275     3       32      1373        1
2   0          u139816523   2084    2019-03-27 08:10:41.769     10      30      2336        1
3   0          u106546472   1460    2019-03-31 08:51:41.085     3       32      1371        4
4   0          u106642861   2295    2019-03-27 22:58:03.679     3       32      2567        4

Cause I get about 100 million rows in this csv file, it is impossible to load all this into my PC memory.

So I want to get rows of a most recent day in ascending order of time way when reading this csv files.

For examples, if the most recent day is on 2019-04-04, it will output as follows:

#this not a real data, just for examples.
    label      uId          adId    operTime                    siteId  slotId  contentId   netType
0   0          u147336431   3887    2019-04-04 00:08:42.315     1       54      2427        2
1   0          u146933269   1462    2019-04-04 01:06:16.417     30      36      1343        6
2   0          u139536523   2084    2019-04-04 02:08:58.079     15      23      1536        7
3   0          u106663472   1460    2019-04-04 03:21:13.050     32      45      1352        2
4   0          u121642861   2295    2019-04-04 04:36:08.653     3       33      3267        4

Could anyone help me?

Thanks in advence.

Body:
Like @anky_91 mentionned, you can use the sort_values function. Here is a short example of how it works:

df = pd.DataFrame( {'Symbol':['A','A','A'] ,
    'Date':['02/20/2015','01/15/2016','08/21/2015']})
df.sort_values(by='Date')

Out :

Date    Symbol
2   08/21/2015  A
0   02/20/2015  A
1   01/15/2016  A


问:
Inline Horizontal Rule
How to make hr element be inline like I do it in snippet, but without absolute positioning and without hr crossing text?

div {
    position: relative;
}

hr {
  position: absolute;
  top: 0.125rem;
  left: 0;
  right: 0;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div>
  Hello, World? <hr>
</div></code>```

答:
You could use display flex on the parent and then give the hr flex grow so it fills the rest of the line:

div { display:flex; }

hr {
  flex-grow:1;
  margin-left:10px; /* gap on left */
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div>
  <span>Hello, World?</span> <hr>
</div></code>```

Title: Inline Horizontal Rule

Body:
How to make hr element be inline like I do it in snippet, but without absolute positioning and without hr crossing text?

div {
    position: relative;
}

hr {
  position: absolute;
  top: 0.125rem;
  left: 0;
  right: 0;
}

  Hello, World?

Body:
You could use display flex on the parent and then give the hr flex grow so it fills the rest of the line:

div { display:flex; }

hr {
  flex-grow:1;
  margin-left:10px; /* gap on left */
}

<div>
  <span>Hello, World?</span> <hr>
</div>


问:
Extra items in JSON data when using Web API
I have a problem with the JSON data from the Web API service.

In a regular Web API Controller, I get the result given below.

[
  {
    "title": "başlık",
    "description": "Tanımlama",
    "creationTime": "2018-01-15T17:20:06.9801797",
    "state": 0,
    "assignedPersonId": "afd46520-521d-4945-a4ee-083893e1d14c",
    "assignedPersonName": "derya",
    "id": 2
  },
  {
    "title": "title",
    "description": "description",
    "creationTime": "2018-01-15T17:17:26.5161288",
    "state": 0,
    "assignedPersonId": null,
    "assignedPersonName": null,
    "id": 1
  }
]
```

<p>But when using ASP.NET Boilerplate infrastructure, I get the same data as:</p>

<pre class="lang-js prettyprint-override"><code>{
  "result": {
    "items": [
      {
        "title": "başlık",
        "description": "Tanımlama",
        "creationTime": "2018-01-15T17:20:06.9801797",
        "state": 0,
        "assignedPersonId": "afd46520-521d-4945-a4ee-083893e1d14c",
        "assignedPersonName": "derya",
        "id": 2
      },
      {
        "title": "title",
        "description": "description",
        "creationTime": "2018-01-15T17:17:26.5161288",
        "state": 0,
        "assignedPersonId": null,
        "assignedPersonName": null,
        "id": 1
      }
    ]
  },
  "targetUrl": null,
  "success": true,
  "error": null,
  "unAuthorizedRequest": false,
  "__abp": true
}
</code>```

It seems that the actual raw data is nested in an outer data structure. Because of this, deserialization like below doesn't work.

List<Class1> data = JsonConvert.DeserializeObject<List<Class1>>(JSONString);
```

And I have to manage some string operations on JSONString.

Am I doing something wrong? Thanks in advance.

答:
Add these two lines to the PreInitialize() method of your Web.Core project module (<ProjectName>WebCoreModuleModule.cs): docs

```<code>Configuration.Modules.AbpAspNetCore().DefaultWrapResultAttribute.WrapOnError = false;
Configuration.Modules.AbpAspNetCore().DefaultWrapResultAttribute.WrapOnSuccess = false;
</code>```

Body:
I have a problem with the JSON data from the Web API service.

In a regular Web API Controller, I get the result given below.

[
  {
    "title": "başlık",
    "description": "Tanımlama",
    "creationTime": "2018-01-15T17:20:06.9801797",
    "state": 0,
    "assignedPersonId": "afd46520-521d-4945-a4ee-083893e1d14c",
    "assignedPersonName": "derya",
    "id": 2
  },
  {
    "title": "title",
    "description": "description",
    "creationTime": "2018-01-15T17:17:26.5161288",
    "state": 0,
    "assignedPersonId": null,
    "assignedPersonName": null,
    "id": 1
  }
]

But when using ASP.NET Boilerplate infrastructure, I get the same data as:

{
  "result": {
    "items": [
      {
        "title": "başlık",
        "description": "Tanımlama",
        "creationTime": "2018-01-15T17:20:06.9801797",
        "state": 0,
        "assignedPersonId": "afd46520-521d-4945-a4ee-083893e1d14c",
        "assignedPersonName": "derya",
        "id": 2
      },
      {
        "title": "title",
        "description": "description",
        "creationTime": "2018-01-15T17:17:26.5161288",
        "state": 0,
        "assignedPersonId": null,
        "assignedPersonName": null,
        "id": 1
      }
    ]
  },
  "targetUrl": null,
  "success": true,
  "error": null,
  "unAuthorizedRequest": false,
  "__abp": true
}

It seems that the actual raw data is nested in an outer data structure. Because of this, deserialization like below doesn't work.

List<Class1> data = JsonConvert.DeserializeObject<List<Class1>>(JSONString);

And I have to manage some string operations on JSONString.

Am I doing something wrong? Thanks in advance.

Body:
Add these two lines to the PreInitialize() method of your Web.Core project module (<ProjectName>WebCoreModuleModule.cs): docs

Configuration.Modules.AbpAspNetCore().DefaultWrapResultAttribute.WrapOnError = false;
Configuration.Modules.AbpAspNetCore().DefaultWrapResultAttribute.WrapOnSuccess = false;


问:
center on resize too
This works:

```<code>$.fn.center = function () {
    this.css("position", "absolute");
    this.css("top", ($(window).height() - this.height()) / 2 + $(window).scrollTop() + "px");
    this.css("left", ($(window).width() - this.width()) / 2 + $(window).scrollLeft() + "px");
    return this
};
$('#container').center();
</code>```

.. but the element stays in the same position if the window is resized, how do I center it with the resize too?

Thanks

答:
You would need to execute that code in the window resize event. But, if the browser is resized this event fires huge! So it's in general a good idea to create a little "balancer".

```<code>$(window).bind('resize', function() {
    var that = this;

    if(!('balancer' in that) ) {
        that.balancer = setTimeout(function() {
            $('#container').center();
            delete that.balancer;
        }, 200);
    }
});
</code>```

This will absorb the many events that are fired when resizing the browser window. In fact, it only calls the .center() at a maximum of 200ms. You probably should even increase that value and cache the node reference to the #container element.

Title: center on resize too

Body:
This works:

$.fn.center = function () {
    this.css("position", "absolute");
    this.css("top", ($(window).height() - this.height()) / 2 + $(window).scrollTop() + "px");
    this.css("left", ($(window).width() - this.width()) / 2 + $(window).scrollLeft() + "px");
    return this
};
$('#container').center();

.. but the element stays in the same position if the window is resized, how do I center it with the resize too?

Thanks

Body:
You would need to execute that code in the window resize event. But, if the browser is resized this event fires huge! So it's in general a good idea to create a little "balancer".

$(window).bind('resize', function() {
    var that = this;

    if(!('balancer' in that) ) {
        that.balancer = setTimeout(function() {
            $('#container').center();
            delete that.balancer;
        }, 200);
    }
});

This will absorb the many events that are fired when resizing the browser window. In fact, it only calls the .center() at a maximum of 200ms. You probably should even increase that value and cache the node reference to the #container element.


问:
How to sort files by type in folder view of Visual Studio Code
Using Visual Studio Code, how can I sort files by type when I open folder view?

答: search "explorer" in settings page and you can change the control of sorting order there.


问:
To get the date difference between a datetime and nullable datetime
I have two dates where one field is a datetime field and the other is a nullable datetime field. I want to subtract date2 from date 1 and if date2 is null subtract it from today.

My code :

Model :

```<code>public class SampleViewModel
{
    public DateTime Date1 {get;set;}
    public DateTime? Date2 {get;set;}
    public int Diff {get;set;}
}
</code>```

Controller Action :

```<code>public ActionResult Index()
{
    var today = DateTime.Now;
    SampleViewModel model = new SampleViewModel();
    model.Date1=today;
    model.Date2 = today.AddDays(5);
    model.Diff = (model.Date1 - (model.Date2 != null ? model.Date2 : today)).Days;//Error
    return View(model);
}
</code>```

I am getting a compilation error

Error CS1061  'TimeSpan?' does not contain a definition for 'Days' and no accessible extension method 'Days' accepting a first argument of type 'TimeSpan?' could be found (are you missing a using directive or an assembly reference?)

What am I doing wrong?

答:
I would suggest to move your logic inside your model and use the null coalescing operator :

```<code>public class SampleViewModel
{
    public SampleViewModel(DateTime date1, DateTime? date2 = null){
        Date1 = date1;
        Date2 = date2;
    }

    public DateTime Date1 { get; set; }
    public DateTime? Date2 { get; set; }
    public int Diff => (Date1 - (Date2 ?? DateTime.Now)).Days;
}
</code>```

Usage:

```<code>public ActionResult Index()
{
    var today = DateTime.Now;
    var model = new SampleViewModel(today, today.AddDays(5));

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

Body:
I have two dates where one field is a datetime field and the other is a nullable datetime field. I want to subtract date2 from date 1 and if date2 is null subtract it from today.

My code :

Model :

public class SampleViewModel
{
    public DateTime Date1 {get;set;}
    public DateTime? Date2 {get;set;}
    public int Diff {get;set;}
}

Controller Action :

public ActionResult Index()
{
    var today = DateTime.Now;
    SampleViewModel model = new SampleViewModel();
    model.Date1=today;
    model.Date2 = today.AddDays(5);
    model.Diff = (model.Date1 - (model.Date2 != null ? model.Date2 : today)).Days;//Error
    return View(model);
}

I am getting a compilation error

Error CS1061  'TimeSpan?' does not contain a definition for 'Days' and no accessible extension method 'Days' accepting a first argument of type 'TimeSpan?' could be found (are you missing a using directive or an assembly reference?)

What am I doing wrong?

Body:
I would suggest to move your logic inside your model and use the null coalescing operator :

public class SampleViewModel
{
    public SampleViewModel(DateTime date1, DateTime? date2 = null){
        Date1 = date1;
        Date2 = date2;
    }

    public DateTime Date1 { get; set; }
    public DateTime? Date2 { get; set; }
    public int Diff => (Date1 - (Date2 ?? DateTime.Now)).Days;
}

Usage:

public ActionResult Index()
{
    var today = DateTime.Now;
    var model = new SampleViewModel(today, today.AddDays(5));

    return View(model);
}


问:
Delphi using TNetHTTPClient: how to give the final url after redirections?
I use, with Delphi 10.3.1, a TNetHTTPClient with GET command and I need to get the final URL after a page redirection(s).
Is there any property or function for it ?
Thx.</p>

答:
It seems there's no direct (public) access to request instance associated with response. A hacky solution relies on:

IHTTPResponse returned is implemented by THTTPResponse (implementation detail)

protected access to FRequest field of THTTPResponse

Then you can use following code to access request instance:

```<code>type
  THTTPResponseAccess = class(THTTPResponse);

procedure TForm2.Button1Click(Sender: TObject);
var
  Response: THTTPResponse;
  Request: IURLRequest;
begin
  Response := NetHTTPClient1.Get('http://google.com') as THTTPResponse;
  Request := THTTPResponseAccess(Response).FRequest;
  ShowMessage(Request.URL.ToString);
end;
</code>```

Output is:

```<code>http://www.google.com/
</code>```

Body:
It seems there's no direct (public) access to request instance associated with response. A hacky solution relies on:

IHTTPResponse returned is implemented by THTTPResponse (implementation detail)

protected access to FRequest field of THTTPResponse

Then you can use following code to access request instance:

type
  THTTPResponseAccess = class(THTTPResponse);

procedure TForm2.Button1Click(Sender: TObject);
var
  Response: THTTPResponse;
  Request: IURLRequest;
begin
  Response := NetHTTPClient1.Get('http://google.com') as THTTPResponse;
  Request := THTTPResponseAccess(Response).FRequest;
  ShowMessage(Request.URL.ToString);
end;

Output is:

http://www.google.com/


问:
Sortable UUIDs and overriding ActiveRecord::Base
I'm wanting to use UUIDs in an app I'm building and am running into a bit of a problem. Due to UUIDs (v4) not being sortable because they're randomly generated, I'm trying to override ActiveRecord::Base#first, but Rails isn't too pleased with that. It yells at me saying ArgumentError: You tried to define a scope named "first" on the model "Item", but Active Record already defined a class method with the same name. Do I have to use a different method if I want to sort and have it sort correctly?

Here's the sauce:

```<code># lib/sortable_uuid.rb
module SortableUUID
  def self.included(base)
    base.class_eval do
      scope :first, -> { order("created_at").first }
      scope :last, -> { order("created_at DESC").first }
    end
  end
end

# app/models/item.rb
class Item < ActiveRecord::Base
  include SortableUUID
end
</code>```

Rails 4.2, Ruby 2.2.2

Reference:

http://blog.nakonieczny.it/posts/rails-support-for-uuid/

http://linhmtran168.github.io/blog/2014/03/17/postgres-uuid-in-rails/ ( Drawbacks section )

答:
Rails 6 (currently in version 6.0.0rc1) comes to rescue with implicit_order_column!

To order by created_at and make .first, .last, .second etc. respect it is as simple as:

class ApplicationRecord < ActiveRecord::Base
  self.implicit_order_column = :created_at
end
```

Body:
I'm wanting to use UUIDs in an app I'm building and am running into a bit of a problem. Due to UUIDs (v4) not being sortable because they're randomly generated, I'm trying to override ActiveRecord::Base#first, but Rails isn't too pleased with that. It yells at me saying ArgumentError: You tried to define a scope named "first" on the model "Item", but Active Record already defined a class method with the same name. Do I have to use a different method if I want to sort and have it sort correctly?

Here's the sauce:

# lib/sortable_uuid.rb
module SortableUUID
  def self.included(base)
    base.class_eval do
      scope :first, -> { order("created_at").first }
      scope :last, -> { order("created_at DESC").first }
    end
  end
end

# app/models/item.rb
class Item < ActiveRecord::Base
  include SortableUUID
end

Rails 4.2, Ruby 2.2.2

Reference:

http://blog.nakonieczny.it/posts/rails-support-for-uuid/

http://linhmtran168.github.io/blog/2014/03/17/postgres-uuid-in-rails/ ( Drawbacks section )


问:
How to stop my producer container/API in spring-integration with kafka extension
I am using  spring integration with kafka producer API. I want to stop my Producer API when I got some MessageException or ProducerException.

In consumer (normal spring-kafka) I am using ConsumerAwareListenerErrorHandler to stop my Listener easily.

In a same way I am looking for some handlers in SI to stop my producer container.

Created an error channel and getting all my exceptions into that channel, but couldn't find a way to stop my container. Tried something with SmartLifeCycle, but no luck.

Here my Bean to publish messages to Kafka topic

```<code>@Bean
public IntegrationFlow hanldeKafka() {
    return IntegrationFlows.from(sendToKafkaChannel)
            .handle(
                    kafkaMessageHandler(producerFactory, topicName),
                    e -> e.id("myProducer"))
            .get();
}

public KafkaProducerMessageHandlerTemplateSpec<String, String> kafkaMessageHandler(
        ProducerFactory<String, String> producer, String topic) {
    return Kafka
            .outboundChannelAdapter(producer)
            .sync(true)
            .headerMapper(kafkaHeaderMapper())
            .messageKey(m ->  {
                try {
                Message value = jsonObjectMapper.fromJson(m.getPayload(), Message.class);
                return value.getlId();
                } catch (Exception e) {
                    log.error(e.toString());
                    throw new MessagingException(m);
                }
            })
            //.partitionId(m -> 10)
            .topicExpression("headers[kafka_topic] ?: '" + topic + "'")
            .configureKafkaTemplate(t -> t.id("kafkaTemplate:" + topic));
}
</code>```

Can anyone suggest, how to add some handlers/controllers to stop the producer container/API.

答:
It's not clear what you mean by "producer container" - there is no such thing.

To permanently close the Producer (s) call reset() on the DefaultKafkaProducerFactory.

Body:
I am using  spring integration with kafka producer API. I want to stop my Producer API when I got some MessageException or ProducerException.

In consumer (normal spring-kafka) I am using ConsumerAwareListenerErrorHandler to stop my Listener easily.

In a same way I am looking for some handlers in SI to stop my producer container.

Created an error channel and getting all my exceptions into that channel, but couldn't find a way to stop my container. Tried something with SmartLifeCycle, but no luck.

Here my Bean to publish messages to Kafka topic

@Bean
public IntegrationFlow hanldeKafka() {
    return IntegrationFlows.from(sendToKafkaChannel)
            .handle(
                    kafkaMessageHandler(producerFactory, topicName),
                    e -> e.id("myProducer"))
            .get();
}

public KafkaProducerMessageHandlerTemplateSpec<String, String> kafkaMessageHandler(
        ProducerFactory<String, String> producer, String topic) {
    return Kafka
            .outboundChannelAdapter(producer)
            .sync(true)
            .headerMapper(kafkaHeaderMapper())
            .messageKey(m ->  {
                try {
                Message value = jsonObjectMapper.fromJson(m.getPayload(), Message.class);
                return value.getlId();
                } catch (Exception e) {
                    log.error(e.toString());
                    throw new MessagingException(m);
                }
            })
            //.partitionId(m -> 10)
            .topicExpression("headers[kafka_topic] ?: '" + topic + "'")
            .configureKafkaTemplate(t -> t.id("kafkaTemplate:" + topic));
}

Can anyone suggest, how to add some handlers/controllers to stop the producer container/API.


问:
Can I define a Clojure protocol with methods starting with ":"?
I would like to provide some methods for a clojure protocol starting with the : character. Is there any way to override this in Clojure?</p>

答:
Sounds like a bad idea: colons are reserved for keywords so even if you could do this I think it would make for some confusing code.

You can of course, put a function inside a record mapped by a keyword:

```<code>(defrecord Foo [])

(def foo (Foo. nil {:method (fn [a b] (* a b))}))

((:method foo) 7 10)
=> 70
</code>```

I've found this to be a useful trick sometimes......

Body:
Sounds like a bad idea: colons are reserved for keywords so even if you could do this I think it would make for some confusing code.

You can of course, put a function inside a record mapped by a keyword:

(defrecord Foo [])

(def foo (Foo. nil {:method (fn [a b] (* a b))}))

((:method foo) 7 10)
=> 70

I've found this to be a useful trick sometimes......


问:
How do I interpolate an *ngFor variable inside of a string within a ternary expression? (Angular)
What I've tried:

```<code>  <mat-step *ngFor="let name of names" [label]="name" [completed]="name + 'IsCompleted'">
    <button mat-button (click)="redirectToNameUrl(name)" mat-raised-button color="primary">
  {{ (inProgress ? 'In progress...' : "'Sign in with ' + name + 'details!'" )}}
    </button>
  </mat-step>
</code>```

NOTE: Nested handlebars doesn't seem to work either.

Result:

A button that says 'Sign in with ' + name + 'details!'

I expect it to say:

Sign in with james details!

Thanks

答:
Just try like this

```<code>  <mat-step *ngFor="let name of names" [label]="name" [completed]="name + 'IsCompleted'">
    <button mat-button (click)="redirectToNameUrl(name)" mat-raised-button color="primary">
  {{ (inProgress ? 'In progress...' : 'Sign in with ' + name + 'details!' )}}
    </button>
  </mat-step>
</code>```

You don't need the extra double quotes around the text

Body:
What I've tried:

  <mat-step *ngFor="let name of names" [label]="name" [completed]="name + 'IsCompleted'">
    <button mat-button (click)="redirectToNameUrl(name)" mat-raised-button color="primary">
  {{ (inProgress ? 'In progress...' : "'Sign in with ' + name + 'details!'" )}}
    </button>
  </mat-step>

NOTE: Nested handlebars doesn't seem to work either.

Result:

A button that says 'Sign in with ' + name + 'details!'

I expect it to say:

Sign in with james details!

Thanks

Body:
Just try like this

  <mat-step *ngFor="let name of names" [label]="name" [completed]="name + 'IsCompleted'">
    <button mat-button (click)="redirectToNameUrl(name)" mat-raised-button color="primary">
  {{ (inProgress ? 'In progress...' : 'Sign in with ' + name + 'details!' )}}
    </button>
  </mat-step>

You don't need the extra double quotes around the text


问:
How to change key label of the custom android keyboard in java
I want to change the key label on my custom keyboard at run time, passing through java. I can't find any solution anywhere.

java file

```<code>
public class MyKeyboardService extends InputMethodService implements KeyboardView.OnKeyboardActionListener {

    public final static int keyToChange = 257;

    KeyboardView kv;
    Intent intent;

    void updateInputView() {
        if (kv == null)
            return;
        Keyboard currentKeyboard = kv.getKeyboard();
        List<Keyboard.Key> keys = currentKeyboard.getKeys();
        keys.get(keyToChange).label = "Change Label";
        kv.invalidateKey(keyToChange);
    }

    @Override
    public View onCreateInputView() {

        checkIfFirstRun();

        KeyboardView kv = (KeyboardView) getLayoutInflater().inflate(R.layout.keyboard, null);
        Keyboard keyboard = new Keyboard(this, R.xml.layout_keys);

        kv.setKeyboard(keyboard);
        kv.setPreviewEnabled(false);
        kv.setOnKeyboardActionListener(this);
        updateInputView();

        return kv;
</code>```

xml file

```<code>        <Key
            android:codes="257"
            android:keyWidth="60%p"/>
</code>```

Now, I still get blank label on the key.
I want it to display "Change Label"

答: List<>.get() returns the key with the particular index, not the key with the particular code. For example, List<>.get(0) returns the first key.</p>

Body:
I want to change the key label on my custom keyboard at run time, passing through java. I can't find any solution anywhere.

java file

public class MyKeyboardService extends InputMethodService implements KeyboardView.OnKeyboardActionListener {

    public final static int keyToChange = 257;

    KeyboardView kv;
    Intent intent;

    void updateInputView() {
        if (kv == null)
            return;
        Keyboard currentKeyboard = kv.getKeyboard();
        List<Keyboard.Key> keys = currentKeyboard.getKeys();
        keys.get(keyToChange).label = "Change Label";
        kv.invalidateKey(keyToChange);
    }

    @Override
    public View onCreateInputView() {

        checkIfFirstRun();

        KeyboardView kv = (KeyboardView) getLayoutInflater().inflate(R.layout.keyboard, null);
        Keyboard keyboard = new Keyboard(this, R.xml.layout_keys);

        kv.setKeyboard(keyboard);
        kv.setPreviewEnabled(false);
        kv.setOnKeyboardActionListener(this);
        updateInputView();

        return kv;

xml file

        <Key
            android:codes="257"
            android:keyWidth="60%p"/>

Now, I still get blank label on the key.
I want it to display "Change Label"


问:
How do I use beautify in Ace Editor?
I've found the beautify extension in Ace editor but I don't see any examples of how to use it. Here's what I have so far:

var beautiful = ace.require("ace/ext/beautify");
beautiful.beautify();
```
<p>but I get the error:</p>
```Result of expression 'e' [undefined] is not an object.
```

答:
You may need to execute the beautify.beautify after window is loaded when open the page so that editor.session is initialized.

window.addEventListener('load', () => {
  beautify.beautify(editor.session)
})
```

Title: How do I use beautify in Ace Editor?

Body:
I've found the beautify extension in Ace editor but I don't see any examples of how to use it. Here's what I have so far:

var beautiful = ace.require("ace/ext/beautify");
beautiful.beautify();

but I get the error:

Result of expression 'e' [undefined] is not an object.


问:
Google Apps Script get bounded sheet data from imported package
I am trying to figure out how to get data from a Spreadsheet bounded to a script that is referenced as a package in another script.

I have a Spreadsheet with some data and a bounded script with this function:

```<code>function getIt()
{
  return SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Sheet1").getRange("A1").getValue();
}
</code>```

The script works as expected.

Then I have a standalone script/project where I have added the above script as a library. In this standalone script, if I try library.getIt() I get an error:

```<code>TypeError: Cannot call method "getSheetByName" of null. (line 8, file "Code", project "Untitled project")
</code>```

What I want to do is create some functions in the script that is bounded to the Sheet that gets/returns data from the sheet. Then I want to be able to add the script as a library to other scripts and get said data by calling those functions.

Is this possible?

答:
You won't be able to getActiveSpreadsheet() from a standalone script, try using openById() or openByUrl() instead.

Although your getIt() script is bound to the spreadsheet, I believe it would try and run getActiveSpreadsheet() for the current script file you're running this from, which returns null because it's not bound to any spreadsheet.

Body:
I am trying to figure out how to get data from a Spreadsheet bounded to a script that is referenced as a package in another script.

I have a Spreadsheet with some data and a bounded script with this function:

function getIt()
{
  return SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Sheet1").getRange("A1").getValue();
}

The script works as expected.

Then I have a standalone script/project where I have added the above script as a library. In this standalone script, if I try library.getIt() I get an error:

TypeError: Cannot call method "getSheetByName" of null. (line 8, file "Code", project "Untitled project")

What I want to do is create some functions in the script that is bounded to the Sheet that gets/returns data from the sheet. Then I want to be able to add the script as a library to other scripts and get said data by calling those functions.

Is this possible?


问:
execute command on one host with all inventory hosts in parameter
is it possible to execute a command on on host with all inventory hosts in parameter ?

For exemple :
inventory file :

```<code>host1
host2
host3
</code>```

I want to execute this command from the host1 only :

```<code>ssh toto@host1:"touch /tmp/test"
ssh toto@host2:"touch /tmp/test"
ssh toto@host3:"touch /tmp/test"
</code>```

for this i use this code but it's not working. The code is executed only on one host

```<code>name: Execute test
  command: ssh toto@{{ inventory_hostname }}:"touch /tmp/test"
  delegate_to: host1
</code>```

答:
How about:

```<code>- hosts: host1
  tasks:
    - name: execute test
      command: ssh toto@{item} touch /tmp/test
      loop: "{{ groups.all }}"
</code>```

This will iterate over groups.all, which contains the name of every host in your inventory.

Body:
is it possible to execute a command on on host with all inventory hosts in parameter ?

For exemple :
inventory file :

host1
host2
host3

I want to execute this command from the host1 only :

ssh toto@host1:"touch /tmp/test"
ssh toto@host2:"touch /tmp/test"
ssh toto@host3:"touch /tmp/test"

for this i use this code but it's not working. The code is executed only on one host

name: Execute test
  command: ssh toto@{{ inventory_hostname }}:"touch /tmp/test"
  delegate_to: host1

Body:
How about:

- hosts: host1
  tasks:
    - name: execute test
      command: ssh toto@{item} touch /tmp/test
      loop: "{{ groups.all }}"

This will iterate over groups.all, which contains the name of every host in your inventory.


问:
JSON returning as undefined
Hello I have an ajax request that submits a form and sends and email, if the email is submitted successfully, I encode a PHP array that looks like this,

$success = array("state" => "Email Sent");

I am then checking the state of data in my ajax request to see if state matches "Email Sent" however when I alert(data) i get undefined, what am I doing wrong? Below is my javascript,

```<code>$.ajax({
                    url: "<?php echo base_url(); ?>home/callback",
                    data: $("#callback").serialize(),
                    type: "POST",
                    dataType: "JSON",
                    success: function(data){
                        $("#fancybox-content div").html(data);
                        alert(data.state);
                    }
                });
</code>```

答:
Try to get the html value of the 'fancybox-content' div.
$('#fancybox-content').html();</p>

Title: JSON returning as undefined

Body:
Hello I have an ajax request that submits a form and sends and email, if the email is submitted successfully, I encode a PHP array that looks like this,

$success = array("state" => "Email Sent");

I am then checking the state of data in my ajax request to see if state matches "Email Sent" however when I alert(data) i get undefined, what am I doing wrong? Below is my javascript,

$.ajax({
                    url: "<?php echo base_url(); ?>home/callback",
                    data: $("#callback").serialize(),
                    type: "POST",
                    dataType: "JSON",
                    success: function(data){
                        $("#fancybox-content div").html(data);
                        alert(data.state);
                    }
                });


问:
Converting TeX file to image in Python
Using this accepted answer as a reference, I've been trying to replicate the pandas DF to TeX to PDF to png recipe. However, my Python 3 (using a Jupyter Notebook thru Anaconda Navigator) is giving me some trouble.

I've installed MiKTeX at the following default location on my local disk:

```<code>C:\Users\USERNAME\AppData\Local\Programs\MiKTeX\2.9
</code>```

I also installed LaTex at the following location:

```<code>C:\Users\USERNAME\AppData\Local\Programs\Python\Python36-32\Lib\site-packages\notebook\static\components\MathJax\extensions\TeX
</code>```

However, when I run the chunk of code using my Pandas df object:

```<code>filename = 'out.tex'
pdffile = 'out.pdf'
outname = 'out.png'

template = r'''\documentclass[preview]{{standalone}}
\usepackage{{booktabs}}
\begin{{document}}
{}
\end{{document}}
'''

with open(filename, 'wb') as f:
    f.write(bytes(template.format(df.to_latex()),'UTF-8'))

subprocess.call(['pdflatex', filename], shell=True)
subprocess.call(['convert', '-density', '300', pdffile, '-quality', '90', outname])
</code>```

It's simply returning "4", and the only file created from my original df is "out.tex". I'd like the DF to be turned into a png image so I can keep the full process in my Notebook script.

Any advice would be much appreciated. Thanks.

答:
I solved this issue using the following two process calls:

```<code>subprocess.call('latex -interaction=batchmode -output-directory='+ outpath + ' ' + input_tex_file, shell=True, stdout=open(os.devnull, 'wb'))
subprocess.call('dvipng -q* -T tight -o ' + output_png_file + ' ' + input_dvi_file, shell=True, stdout=open(os.devnull, 'wb'))
</code>```

You'll have to create .tex file first from your raw latex data. Then these commands first create a .dvi file (and some additional auxiliary files) from the .tex file. You can then use dvipng (https://ctan.org/pkg/dvipng?lang=en) to create a .png file.

Title: Converting TeX file to image in Python

Body:
Using this accepted answer as a reference, I've been trying to replicate the pandas DF to TeX to PDF to png recipe. However, my Python 3 (using a Jupyter Notebook thru Anaconda Navigator) is giving me some trouble.

I've installed MiKTeX at the following default location on my local disk:

C:\Users\USERNAME\AppData\Local\Programs\MiKTeX\2.9

I also installed LaTex at the following location:

C:\Users\USERNAME\AppData\Local\Programs\Python\Python36-32\Lib\site-packages\notebook\static\components\MathJax\extensions\TeX

However, when I run the chunk of code using my Pandas df object:

filename = 'out.tex'
pdffile = 'out.pdf'
outname = 'out.png'

template = r'''\documentclass[preview]{{standalone}}
\usepackage{{booktabs}}
\begin{{document}}
{}
\end{{document}}
'''

with open(filename, 'wb') as f:
    f.write(bytes(template.format(df.to_latex()),'UTF-8'))

subprocess.call(['pdflatex', filename], shell=True)
subprocess.call(['convert', '-density', '300', pdffile, '-quality', '90', outname])

It's simply returning "4", and the only file created from my original df is "out.tex". I'd like the DF to be turned into a png image so I can keep the full process in my Notebook script.

Any advice would be much appreciated. Thanks.

Body:
I solved this issue using the following two process calls:

subprocess.call('latex -interaction=batchmode -output-directory='+ outpath + ' ' + input_tex_file, shell=True, stdout=open(os.devnull, 'wb'))
subprocess.call('dvipng -q* -T tight -o ' + output_png_file + ' ' + input_dvi_file, shell=True, stdout=open(os.devnull, 'wb'))

You'll have to create .tex file first from your raw latex data. Then these commands first create a .dvi file (and some additional auxiliary files) from the .tex file. You can then use dvipng (https://ctan.org/pkg/dvipng?lang=en) to create a .png file.


问:
Error: The name 'ConfigurationManager' does not exist in the current context
I have included the following statement in my Visual C# Console Application (Visual Studio 2005 .NET 2.0 Framework)

```<code>using System.Configuration;
</code>```

and I am using the following statement in my application:

```<code>ConfigurationManager.AppSettings["SomeStringOverHere"];
</code>```

I try to build  the application and I get the error:
The name 'ConfigurationManager' does not exist in the current context.

Any help please?

答:
at the solution explorer

select References

then click Add Reference from the right mouse button menu

in the top right corner write "Configuration:

check the System.Configuration, which would show up

press OK

ContentLicense: CC BY-SA 2.5

Body:
I have included the following statement in my Visual C# Console Application (Visual Studio 2005 .NET 2.0 Framework)

using System.Configuration;

and I am using the following statement in my application:

ConfigurationManager.AppSettings["SomeStringOverHere"];

I try to build  the application and I get the error:
The name 'ConfigurationManager' does not exist in the current context.

Any help please?


问:
Codecademy howOld syntax error at else if
As a coding noob I am always struggling with syntax in my Javascript exercises in Codecademy.  This is my first problem I havent been able to solve without some internet search help - my apologies if this is already solved here.

I am usually a semi-colon away from solving it, but not this time (?).  Im attempting to accommodate 3 outcomes:

someone inputs a year in the future and I tell them their age in that year.

someone inputs a year before they were born and I give them the # of years until they were born.

someone inputs a year after they were born and I give them their age at that time.

I've spent too much time moving curly brackets and semi colons and I guess I just cant see the error.

```<code>const howOld = (age, year) =>

 {
  if
    (year > 2019);
    let calculatedAge = ( year - 2019 + age );
  {
  return `You will be ${calculatedAge } in the year ${year}.`;

  } else if
    (year < (2019-age));
    let calculatedAge = ( 2019 - year + age );
  {
  return `The year ${year } was ${calculatedAge } years before you were
born.`;

  } else
    let calculatedAge = ( year - 2019 + age );
  {
  return `You were ${calculatedAge} in the year ${year}. `;
  }

};

console.log(howOld(47,2000))
</code>```

I am getting a syntax error at my 'else if' statement.

答:
You have small error in code that comes from unique style of yours. If we standardize the code we will see that there are excessive semicolons as well bracketing isn't correct.

```<code>const howOld = (age, year) => {
  if (year > 2019);
    let calculatedAge = ( year - 2019 + age );
  {
  return `You will be ${calculatedAge } in the year ${year}.`;

  } else if (year < (2019-age));
    let calculatedAge = ( 2019 - year + age );
  {
  return `The year ${year } was ${calculatedAge } years before you were born.`;

  } else
    let calculatedAge = ( year - 2019 + age );
  {
  return `You were ${calculatedAge} in the year ${year}. `;
  }

};
</code>```

The correct version:

```<code>const howOld = (age, year) => {
    if (year > 2019){
      let calculatedAge = ( year - 2019 + age );
      return `You will be ${calculatedAge } in the year ${year}.`;
    } else if (year < (2019-age)) {
      let calculatedAge = ( 2019 - year + age );
      return `The year ${year } was ${calculatedAge } years before you were born.`;
    } else {
      let calculatedAge = ( year - 2019 + age );
      return `You were ${calculatedAge} in the year ${year}.`;
    }
  };
console.log(howOld(47,2000))
</code>```

Body:
As a coding noob I am always struggling with syntax in my Javascript exercises in Codecademy.  This is my first problem I havent been able to solve without some internet search help - my apologies if this is already solved here.

I am usually a semi-colon away from solving it, but not this time (?).  Im attempting to accommodate 3 outcomes:

someone inputs a year in the future and I tell them their age in that year.

someone inputs a year before they were born and I give them the # of years until they were born.

someone inputs a year after they were born and I give them their age at that time.

I've spent too much time moving curly brackets and semi colons and I guess I just cant see the error.

const howOld = (age, year) =>

 {
  if
    (year > 2019);
    let calculatedAge = ( year - 2019 + age );
  {
  return `You will be ${calculatedAge } in the year ${year}.`;

  } else if
    (year < (2019-age));
    let calculatedAge = ( 2019 - year + age );
  {
  return `The year ${year } was ${calculatedAge } years before you were
born.`;

  } else
    let calculatedAge = ( year - 2019 + age );
  {
  return `You were ${calculatedAge} in the year ${year}. `;
  }

};

console.log(howOld(47,2000))

I am getting a syntax error at my 'else if' statement.

Body:
You have small error in code that comes from unique style of yours. If we standardize the code we will see that there are excessive semicolons as well bracketing isn't correct.

const howOld = (age, year) => {
  if (year > 2019);
    let calculatedAge = ( year - 2019 + age );
  {
  return `You will be ${calculatedAge } in the year ${year}.`;

  } else if (year < (2019-age));
    let calculatedAge = ( 2019 - year + age );
  {
  return `The year ${year } was ${calculatedAge } years before you were born.`;

  } else
    let calculatedAge = ( year - 2019 + age );
  {
  return `You were ${calculatedAge} in the year ${year}. `;
  }

};

The correct version:

const howOld = (age, year) => {
    if (year > 2019){
      let calculatedAge = ( year - 2019 + age );
      return `You will be ${calculatedAge } in the year ${year}.`;
    } else if (year < (2019-age)) {
      let calculatedAge = ( 2019 - year + age );
      return `The year ${year } was ${calculatedAge } years before you were born.`;
    } else {
      let calculatedAge = ( year - 2019 + age );
      return `You were ${calculatedAge} in the year ${year}.`;
    }
  };
console.log(howOld(47,2000))


问:
font awesome and images doesn't work in Laravel Voyager

Hello everyone,

i use laravel voyager as back-end.. My Admin doesn't work correctly..

font awesome, images, etc don't appear in the Admin.

https://i.imgur.com/bqFFu6J.png

when i try to Add a product a get this error:

https://i.imgur.com/LAxuhlb.png

Can anyone suggest me that what can I do to solve the problem.

答:
Please check follow:

First.

Please clear browser cache.

php artisan optimize

If it doesn't work let me know how to import font files.

Second.

Please set primary key and auto increment on "id" field of "categories" table.


问:
Assign matrix element in OpenCV
What is the most generic way of assigning an element from one source matrix to a destination matrix in OpenCV? I always find myself coding something like this, which is not exactly elegant:

```<code>cv::Mat source; // CV_32FC3
cv::Mat dest;   // CV_32FC3

// ...

switch( source.channels() )
{
case 1:
    {
        dest.at<float>( y, x ) = source.at<float>( j, i );
        break;
    }
case 2:
    {
        dest.at<cv::Vec2f>( y, x ) = source.at<cv::Vec2f>( j, i );
        break;
    }
case 3:
    {
        dest.at<cv::Vec3f>( y, x ) = source.at<cv::Vec3f>( j, i );
        break;
    }
case 4:
    {
        dest.at<cv::Vec4f>( y, x ) = source.at<cv::Vec4f>( j, i );
        break;
    }
}
</code>```

I am wondering what the recommended way for this would be, there must be some generic one-liner for this, right?

Bonus points for a solution working across different data types (e.g. assigning n-channel float elements to n-channel double or short elements)

答:
There is a templated version for cv::Vec<T, n> so you could make a template function taking source and destination types, as well as number of channels like so:

```<code>template<typename TSrc, typename TDst, int N>
void assign(const cv::Mat& src, cv::Mat& dst, int x, int y)
{
    assert(src.channels() == N);
    assert(dst.channels() == N);
    assert(src.size() == dst.size());

    const cv::Vec<TSrc, N>& srcVec = src.at<cv::Vec<TSrc, N>>(x, y);
    cv::Vec<TDst, N>& dstVec = dst.at<cv::Vec<TDst, N>>(x, y);
    for (int i = 0; i < N; ++i)
        dstVec[i] = static_cast<TDst>(srcVec[i]);
}
int main(int argc, char* argv[])
{   //sample usage:
    cv::Mat src(5, 5, CV_8UC3, cv::Scalar::all(255)), dst(5, 5, CV_32FC3, cv::Scalar::all(1));
    assign<unsigned char, float, 3>(src, dst, 3, 3);
}
</code>```

Title: Assign matrix element in OpenCV

Body:
What is the most generic way of assigning an element from one source matrix to a destination matrix in OpenCV? I always find myself coding something like this, which is not exactly elegant:

cv::Mat source; // CV_32FC3
cv::Mat dest;   // CV_32FC3

// ...

switch( source.channels() )
{
case 1:
    {
        dest.at<float>( y, x ) = source.at<float>( j, i );
        break;
    }
case 2:
    {
        dest.at<cv::Vec2f>( y, x ) = source.at<cv::Vec2f>( j, i );
        break;
    }
case 3:
    {
        dest.at<cv::Vec3f>( y, x ) = source.at<cv::Vec3f>( j, i );
        break;
    }
case 4:
    {
        dest.at<cv::Vec4f>( y, x ) = source.at<cv::Vec4f>( j, i );
        break;
    }
}

I am wondering what the recommended way for this would be, there must be some generic one-liner for this, right?

Bonus points for a solution working across different data types (e.g. assigning n-channel float elements to n-channel double or short elements)

Body:
There is a templated version for cv::Vec<T, n> so you could make a template function taking source and destination types, as well as number of channels like so:

template<typename TSrc, typename TDst, int N>
void assign(const cv::Mat& src, cv::Mat& dst, int x, int y)
{
    assert(src.channels() == N);
    assert(dst.channels() == N);
    assert(src.size() == dst.size());

    const cv::Vec<TSrc, N>& srcVec = src.at<cv::Vec<TSrc, N>>(x, y);
    cv::Vec<TDst, N>& dstVec = dst.at<cv::Vec<TDst, N>>(x, y);
    for (int i = 0; i < N; ++i)
        dstVec[i] = static_cast<TDst>(srcVec[i]);
}
int main(int argc, char* argv[])
{   //sample usage:
    cv::Mat src(5, 5, CV_8UC3, cv::Scalar::all(255)), dst(5, 5, CV_32FC3, cv::Scalar::all(1));
    assign<unsigned char, float, 3>(src, dst, 3, 3);
}


问:
Take the text of header tags one by one
What I need to do is take the text of header tags one by one when you press the key 'h'. This is my code,

```<code>var currentHeader;
currentHeader = $(":header").first();

$(window).on('keyup', function (e) {
    if (e.which === 72){ //h = 72
        alert(currentHeader.text());
        currentHeader = currentHeader.next(":header");
    }
});
</code>```

Unfortunately this code not working as expected and no error message passing :'(

What I need is alert the next header tag text each time I press the
  'h' key

答:
```<code>var headers = $(":header");
var currentHeader = headers.first();

$(window).on('keyup', function (e) {
    if (e.which === 72){ //h = 72
        alert(currentHeader.text());
        // go to the next indexed header on the page, after the current header
        currentHeader = headers.eq( headers.index(currentHeader) + 1 );
    }
});
</code>```

Title: Take the text of header tags one by one

Body:
What I need to do is take the text of header tags one by one when you press the key 'h'. This is my code,

var currentHeader;
currentHeader = $(":header").first();

$(window).on('keyup', function (e) {
    if (e.which === 72){ //h = 72
        alert(currentHeader.text());
        currentHeader = currentHeader.next(":header");
    }
});

Unfortunately this code not working as expected and no error message passing :'(

What I need is alert the next header tag text each time I press the
  'h' key


问:
How to fix a function that is not firing using server cron?
I created a server cron where a function will be triggered every 30 minutes. The problem is the data is not sending properly, but working when button is clicked or I use 'init' in the function. Also, the cron is properly triggering, added a sending mail function below the code that is needed to be triggered.

```<code>function myprefix_custom_cron_schedule( $schedules ) {
    $schedules['every_30_minutes'] = array(
        'interval' => 30 * 60, // Every 30 minutes
        'display'  => __( 'Every 30 minutes' ),
    );
    return $schedules;
}
add_filter( 'cron_schedules', 'myprefix_custom_cron_schedule' );

//Schedule an action if it's not already scheduled
if ( ! wp_next_scheduled( 'myprefix_cron_hook' ) ) {
    wp_schedule_event( time(), 'every_30_minutes', 'myprefix_cron_hook' );
}
//myprefix_cron_hook

add_action ( 'myprefix_cron_hook', function(){

//this is not being triggered
    $to_create_posts = true;
    $data = RemoteCoin::LoadRemoteCoin( $to_create_posts );

//this is the test email cron (working)
    $to = '***';
    $subject = 'Test my 30-minute cron job';
    $message = 'If you received this message, it means that your 30-minute cron job has worked!';
    mail( $to, $subject, $message, 'From: ***' . "com" );

});
</code>```

But this is working when the button I created is clicked:

```<code>
if(array_key_exists('mysubmitbtn3',$_POST)){
        $to_create_posts = true;
         $data = RemoteCoin::LoadRemoteCoin( $to_create_posts );
}

</code>```

Also, this is working too, using init:

```<code>add_action ( 'init', function(){

    $to_create_posts = true;
    $data = RemoteCoin::LoadRemoteCoin( $to_create_posts );

});

</code>```

I'm not sure where to start since it is not outputting any errors.
Anyone can help me where to start? Thank you.

答:
After days of debugging, I finally found the problem. It is the admin check function (which checks if the one that triggers it is an admin), I needed to remove it since the function will be triggered by the server, not an individual.

Thank you!

Body:
I created a server cron where a function will be triggered every 30 minutes. The problem is the data is not sending properly, but working when button is clicked or I use 'init' in the function. Also, the cron is properly triggering, added a sending mail function below the code that is needed to be triggered.

function myprefix_custom_cron_schedule( $schedules ) {
    $schedules['every_30_minutes'] = array(
        'interval' => 30 * 60, // Every 30 minutes
        'display'  => __( 'Every 30 minutes' ),
    );
    return $schedules;
}
add_filter( 'cron_schedules', 'myprefix_custom_cron_schedule' );

//Schedule an action if it's not already scheduled
if ( ! wp_next_scheduled( 'myprefix_cron_hook' ) ) {
    wp_schedule_event( time(), 'every_30_minutes', 'myprefix_cron_hook' );
}
//myprefix_cron_hook

add_action ( 'myprefix_cron_hook', function(){

//this is not being triggered
    $to_create_posts = true;
    $data = RemoteCoin::LoadRemoteCoin( $to_create_posts );

//this is the test email cron (working)
    $to = '***';
    $subject = 'Test my 30-minute cron job';
    $message = 'If you received this message, it means that your 30-minute cron job has worked!';
    mail( $to, $subject, $message, 'From: ***' . "com" );

});

But this is working when the button I created is clicked:

if(array_key_exists('mysubmitbtn3',$_POST)){
        $to_create_posts = true;
         $data = RemoteCoin::LoadRemoteCoin( $to_create_posts );
}

Also, this is working too, using init:

add_action ( 'init', function(){

    $to_create_posts = true;
    $data = RemoteCoin::LoadRemoteCoin( $to_create_posts );

});

I'm not sure where to start since it is not outputting any errors.
Anyone can help me where to start? Thank you.