问:
Change varchar column to datetime?
I have column in mysql table called "dtm"

Data in it is like this "20200525/0704Z"

It has date and time in Zulu format.

Currently column type is varchar 255.

How do I convert this to more useful column type like datetime?

Im getting "too big precision error max is 6" when trying to just change column type.

Thanks

答:
An addendum to @Calvin-Tan's answer since it would be a poor fit in the comment section.

You can populate the new column from the old directly in MySQL using a query like:

UPDATE table SET new_date = CONCAT(
  SUBSTR(old_date, 1, 4),
  '-',
  SUBSTR(old_date, 5, 2),
  '-',
  SUBSTR(old_date, 7, 2),
  ' ',
  SUBSTR(old_date, 10, 2),
  ':',
  SUBSTR(old_date, 12, 2),
  ':00'
);
```

Which will reformat the string as 2020-05-25 07:04:00.

Also bear in mind that MySQL date/time types have no concept of timezone.

Title: Change varchar column to datetime?

Body:
An addendum to @Calvin-Tan's answer since it would be a poor fit in the comment section.

You can populate the new column from the old directly in MySQL using a query like:

UPDATE table SET new_date = CONCAT(
  SUBSTR(old_date, 1, 4),
  '-',
  SUBSTR(old_date, 5, 2),
  '-',
  SUBSTR(old_date, 7, 2),
  ' ',
  SUBSTR(old_date, 10, 2),
  ':',
  SUBSTR(old_date, 12, 2),
  ':00'
);

Which will reformat the string as 2020-05-25 07:04:00.

Also bear in mind that MySQL date/time types have no concept of timezone.


来源: stackexchange

问:
Process vs Worker vs Thread vs Task vs Pool in Node.js
What is Process, Worker, Thread, Task, Pool in Node.js from a programmer point of view?

I went through a lot of material, but difficult to understand quickly for a beginner programmer. Here is a quick summary

答:
A Node.js process is created when run a Node.js program like node app.js (or the child process created through child_process or cluster modules). Each process will have its own memory and resources

Worker is a Node.js built-in module which takes your module (.js) as an input and creates worker object, inside a process, that executes asynchronously.

```<code>//app.js
//TODO add modules
const { Worker } = require('worker_threads');

//TODO wrap the below code into your code

const worker = new Worker('./task_processor.js');
const workerMaxLifetime = 10000;

//Send message to worker
worker.postMessage('Message to thread');
//Receive message from worker
worker.on('message', (message) => { console.log(' App:', message); });
//Terminate worker
setTimeout(() => { worker.terminate(); }, workerMaxLifetime);
</code>```

Task is your module (.js) where you write the code to run as a Thread. Actually, we should call it 'Task Processor'

```<code>//task_processor.js
//TODO add modules
const { parentPort } = require('worker_threads');
//TODO wrap the below code into your code

//Receive message from App
parentPort.on('message', (task_input) => {
  //Send message to App
  parentPort.postMessage(task_input.a + task_input.b);
});
</code>```

Thread is nothing but the worker in execution.

Pool is a wrapper .js file which create/terminate worker objects and facilitates communication between App and worker. Worker pool is not mandatory though most real world scenarios implements pools where worker thread concept is implemented. Example

Node.js module is a .js file

App: The main(or default) thread in a process is also referred as App

Process vs Worker: Each process will have its own memory and resources, whereas worker uses the same memory and resources of the process from which it is created.

ContentLicense: CC BY-SA 4.0

Body:
A Node.js process is created when run a Node.js program like node app.js (or the child process created through child_process or cluster modules). Each process will have its own memory and resources

Worker is a Node.js built-in module which takes your module (.js) as an input and creates worker object, inside a process, that executes asynchronously.

//app.js
//TODO add modules
const { Worker } = require('worker_threads');

//TODO wrap the below code into your code

const worker = new Worker('./task_processor.js');
const workerMaxLifetime = 10000;

//Send message to worker
worker.postMessage('Message to thread');
//Receive message from worker
worker.on('message', (message) => { console.log(' App:', message); });
//Terminate worker
setTimeout(() => { worker.terminate(); }, workerMaxLifetime);

Task is your module (.js) where you write the code to run as a Thread. Actually, we should call it 'Task Processor'

//task_processor.js
//TODO add modules
const { parentPort } = require('worker_threads');
//TODO wrap the below code into your code

//Receive message from App
parentPort.on('message', (task_input) => {
  //Send message to App
  parentPort.postMessage(task_input.a + task_input.b);
});

Thread is nothing but the worker in execution.

Pool is a wrapper .js file which create/terminate worker objects and facilitates communication between App and worker. Worker pool is not mandatory though most real world scenarios implements pools where worker thread concept is implemented. Example

Node.js module is a .js file

App: The main(or default) thread in a process is also referred as App

Process vs Worker: Each process will have its own memory and resources, whereas worker uses the same memory and resources of the process from which it is created.


问:
How would I set an alert for multiple crosses?
Is this how I would set an alert for multiple crosses keeping them separate but running in one alert?</p>

```<code>//==ALERTS==
Cond1 = cross(macd1, macd2 )
    or  cross(macd3, macd4 )
    or  cross(macd9, macd10)
    or  cross(macd11,macd12)
    or  cross(macd13,macd14)
    or  cross(macd15,macd16)
    or  cross(macd17,macd18)
    or  cross(macd19,macd20)
    or  cross(macd21,macd22)
    or  cross(macd23,macd24)
    or  cross(macd25,macd26)
    or  cross(macd27,macd28)
    or  cross(macd29,macd30)

Cond2 = cross(macd31,macd32)
    or  cross(macd33,macd34)
    or  cross(macd35,macd36)
    or  cross(macd37,macd38)
    or  cross(macd39,macd40)
    or  cross(macd41,macd42)
    or  cross(macd43,macd44)
    or  cross(macd45,macd46)

alertcondition(Cond1, title="CONSIDER placing a buy", message="CONSIDER placing a buy")
alertcondition(Cond2, title="="close BTC position ",  message="close BTC position ")
</code>```

答: Yes. If any of your macd crossings occur, the associated alert will fire.</p>

Body:
Is this how I would set an alert for multiple crosses keeping them separate but running in one alert?

//==ALERTS==
Cond1 = cross(macd1, macd2 )
    or  cross(macd3, macd4 )
    or  cross(macd9, macd10)
    or  cross(macd11,macd12)
    or  cross(macd13,macd14)
    or  cross(macd15,macd16)
    or  cross(macd17,macd18)
    or  cross(macd19,macd20)
    or  cross(macd21,macd22)
    or  cross(macd23,macd24)
    or  cross(macd25,macd26)
    or  cross(macd27,macd28)
    or  cross(macd29,macd30)

Cond2 = cross(macd31,macd32)
    or  cross(macd33,macd34)
    or  cross(macd35,macd36)
    or  cross(macd37,macd38)
    or  cross(macd39,macd40)
    or  cross(macd41,macd42)
    or  cross(macd43,macd44)
    or  cross(macd45,macd46)

alertcondition(Cond1, title="CONSIDER placing a buy", message="CONSIDER placing a buy")
alertcondition(Cond2, title="="close BTC position ",  message="close BTC position ")


问:
R10 Error when deploying a Docker image to Heroku
I faced some teething issue when trying to deploy my Docker image which contains a simple streamlit app to Heroku. My issue is that I am unable to access my Docker after deployment. On closer look, I discovered the following error:

Error R10 (Boot timeout) -> Web process failed to bind to $PORT within 60 seconds of launch

I had researched and understood that this is because the port is unavailable, since Heroku will dynamically assign port number.

I had made sure that this will not happen by putting the following my Dockerfile.

Dockerfile:

```<code>FROM python:3.7
COPY . /app
WORKDIR /app
RUN pip install streamlit
ENTRYPOINT ["streamlit","run", "--server.enableCORS", "false" ,"--server.port", "$PORT"]
CMD ["app.py"]
</code>```

I am now able to see that the Network URL and External URL port number are assigned by Heroku as it is not the typical 5901 number.

What puzzled me, however, is why is the container unable to bind to the given dynamic port number? I thought the app would be using the given dynamic number?

答:
The problem is that $PORT does not get replaced with the corresponding environment variable when the Docker run is executed on the Heroku Docker Registry.

An alternative is to create a Docker file which invokes .sh script

```<code>FROM python:3.7
COPY . /app
WORKDIR /app
RUN pip install streamlit

ENTRYPOINT "/startup.sh"
</code>```

and the startup.sh

```<code>echo PORT $PORT
streamlit run --server.enableCORS false --server.port $PORT app.py
</code>```

Body:
I faced some teething issue when trying to deploy my Docker image which contains a simple streamlit app to Heroku. My issue is that I am unable to access my Docker after deployment. On closer look, I discovered the following error:

Error R10 (Boot timeout) -> Web process failed to bind to $PORT within 60 seconds of launch

I had researched and understood that this is because the port is unavailable, since Heroku will dynamically assign port number.

I had made sure that this will not happen by putting the following my Dockerfile.

Dockerfile:

FROM python:3.7
COPY . /app
WORKDIR /app
RUN pip install streamlit
ENTRYPOINT ["streamlit","run", "--server.enableCORS", "false" ,"--server.port", "$PORT"]
CMD ["app.py"]

I am now able to see that the Network URL and External URL port number are assigned by Heroku as it is not the typical 5901 number.

What puzzled me, however, is why is the container unable to bind to the given dynamic port number? I thought the app would be using the given dynamic number?

Body:
The problem is that $PORT does not get replaced with the corresponding environment variable when the Docker run is executed on the Heroku Docker Registry.

An alternative is to create a Docker file which invokes .sh script

FROM python:3.7
COPY . /app
WORKDIR /app
RUN pip install streamlit

ENTRYPOINT "/startup.sh"

and the startup.sh

echo PORT $PORT
streamlit run --server.enableCORS false --server.port $PORT app.py


问:
Data frame and text mining
```<code>library(stringr)
data<-data.frame(id=c(1,2,3),
          text=c("This is (2020) text; mining exercise (1999)","Text analysis (1975) is; bit confusing (2012)","Hint (1998) on; this text (2007) analysis?"))

a <- b <- list()
mm <- data.frame(a=NA,b=NA)
for(i in 1:length(data$text)){
   a[[i]] <- lengths(strsplit(as.character(data$text[i]),";"))
   b[[i]] <- str_count(data$text[i], "\\(19[0-9]{2}\\)|\\(20[0-9]{2}\\)")
}
</code>```

Output I'm getting:

```<code># mm
    a     b
1  NA     NA
</code>```

Why I'm not getting the corresponding values for each row of the data frame mm? The code has nor error.

Expected output:

```<code># mm
   a   b
1  2   2
2  2   2
3  2   2
</code>```

答:
An option with tidyverse

```<code>library(dplyr)
library(stringr)
library(purrr)
data %>%
   transmute(out = str_split(text, ";")) %>%
   transmute(a = lengths(out),
       b = lengths(map(out, ~ str_extract(.x, "(?<=(19|20))[0-9]{2}\\b"))))
#  a b
#1 2 2
#2 2 2
#3 2 2
</code>```

Title: Data frame and text mining

Body:
library(stringr)
data<-data.frame(id=c(1,2,3),
          text=c("This is (2020) text; mining exercise (1999)","Text analysis (1975) is; bit confusing (2012)","Hint (1998) on; this text (2007) analysis?"))

a <- b <- list()
mm <- data.frame(a=NA,b=NA)
for(i in 1:length(data$text)){
   a[[i]] <- lengths(strsplit(as.character(data$text[i]),";"))
   b[[i]] <- str_count(data$text[i], "\\(19[0-9]{2}\\)|\\(20[0-9]{2}\\)")
}

Output I'm getting:

# mm
    a     b
1  NA     NA

Why I'm not getting the corresponding values for each row of the data frame mm? The code has nor error.

Expected output:

# mm
   a   b
1  2   2
2  2   2
3  2   2

Body:
An option with tidyverse

library(dplyr)
library(stringr)
library(purrr)
data %>%
   transmute(out = str_split(text, ";")) %>%
   transmute(a = lengths(out),
       b = lengths(map(out, ~ str_extract(.x, "(?<=(19|20))[0-9]{2}\\b"))))
#  a b
#1 2 2
#2 2 2
#3 2 2


问:
ASP.NET Core, Could not find file. How Can I publish it?
I have found many questions like this, but I'm still having problems to get a "static" file.

The task should be simple. Just get a cshtml file content. A file that it's already in the project. But it's taking forever to figure it out.

This is the error that I'm getting (only when in production)

Could not find file 'D:\home\site\wwwroot\AppData\template.cshtml'.

Looking into the 'D:\home\site\wwwroot' folder, indeed the 'AppData' doesn't exist. But then how can I publish the AppData and its files?

This is how I'm getting the file

```<code>string contentRootPath = webHostEnvironment.ContentRootPath;
return $"{contentRootPath}/AppData/{filename}";
</code>```

This is inside .csproj

```<code><Folder Include="AppData\" />
</code>```

To publish the project I'm using DevOps Azure. Is there any configuration that I'm missing?

答:
I don't know if this is the right approach, but it's working (for now).

In DevOps/Pipelines/MyMypeline/Tasks, I add Copy files Task.

Source Folder: MyProject/AppData

Target Folder: $(Agent.TempDirectory)\WebAppContent\AppData

The next task (Archive files) it was already set. So in resume, the pipeline will get the files from AppData and add in the same place where the solution was build. And the other task will zip all. Than another task (Azure Web App) will sent the zip to my AppService.

I still have to test when do the swipe from dev to prod, but for now that's it.

Body:
I have found many questions like this, but I'm still having problems to get a "static" file.

The task should be simple. Just get a cshtml file content. A file that it's already in the project. But it's taking forever to figure it out.

This is the error that I'm getting (only when in production)

Could not find file 'D:\home\site\wwwroot\AppData\template.cshtml'.

Looking into the 'D:\home\site\wwwroot' folder, indeed the 'AppData' doesn't exist. But then how can I publish the AppData and its files?

This is how I'm getting the file

string contentRootPath = webHostEnvironment.ContentRootPath;
return $"{contentRootPath}/AppData/{filename}";

This is inside .csproj

<Folder Include="AppData\" />

To publish the project I'm using DevOps Azure. Is there any configuration that I'm missing?


问:
Generate One year dates using Oracle SQL
I have a table with three ID and Dates
i want generate dates of one year from current date and before and after six months
Then i want to plot three dates on this one year generated calandar
I tried</p>

```<code>SELECT (TO_DATE(SYSDATE)-180) + ROWNUM DT
  FROM (SELECT 1
          FROM DUAL
       CONNECT BY LEVEL <=180)
</code>```

答:
The concept of "month" is variable, so you may want to double check if "6 months" is really what you're looking for. It can give unexpected results if you don't know the oddities of date math.

That being said, a calendar which contains 6 months on either side of the current date can be generated with the following. Note that 184 days is the longest a 6 month span can last (July-December).

```<code>SELECT dt
  FROM (SELECT TRUNC(SYSDATE - 184) + LEVEL AS dt
          FROM dual
        CONNECT BY LEVEL <= 369)
 WHERE dt BETWEEN add_months(TRUNC(SYSDATE), -6) AND add_months(TRUNC(SYSDATE), 6);
</code>```

Body:
I have a table with three ID and Dates
i want generate dates of one year from current date and before and after six months
Then i want to plot three dates on this one year generated calandar
I tried

SELECT (TO_DATE(SYSDATE)-180) + ROWNUM DT
  FROM (SELECT 1
          FROM DUAL
       CONNECT BY LEVEL <=180)

Body:
The concept of "month" is variable, so you may want to double check if "6 months" is really what you're looking for. It can give unexpected results if you don't know the oddities of date math.

That being said, a calendar which contains 6 months on either side of the current date can be generated with the following. Note that 184 days is the longest a 6 month span can last (July-December).

SELECT dt
  FROM (SELECT TRUNC(SYSDATE - 184) + LEVEL AS dt
          FROM dual
        CONNECT BY LEVEL <= 369)
 WHERE dt BETWEEN add_months(TRUNC(SYSDATE), -6) AND add_months(TRUNC(SYSDATE), 6);


问:
How to use 2 models in 1 View
I have a Booking model and I create a list of all it's elements in the BookingController. There I managed to export the list as .json, however when I want to import a file I can't manage to use my custom validation to see if it's only .json. The problem is that in my Index for Booking I have a IEnumerable model for Booking and I use a BookingsUpload model to upload the file. So how can I access this BookingsUpload model inside the Index or how could i change it ? (could I combine what i do in BookingsUpload with my Booking model ?

Booking Model:

```<code>public class Booking
{
    [Required]
    [Display(Name = "Ladestand")]
    [Range(0, 100)]
    public double chargeState { get; set; }

    [Required]
    [Display(Name = "Benötigte Fahrstrecke")]
    [Range(1, 1000)]
    public double distance { get; set; }

    [Required]
    [Display(Name = "Beginn")]
    public DateTime startTime { get; set; }

    [Required]
    [Display(Name = "Ende")]
    public DateTime endTime { get; set; }

    [Required]
    [Display(Name = "Anschlusstyp")]
    [EnumDataType(typeof(ConnectorType))]
    [JsonConverter(typeof(StringEnumConverter))]
    public ConnectorType connectorType { get; set; }
}

public class BookingList
        {
            public List<Booking> BookingListObj { get; set; }
        }
</code>```

BookingsUpload Model:

```<code>public class BookingsUpload
{
    [Required(ErrorMessage = "Please select a file.")]
    [DataType(DataType.Upload)]
    [MaxFileSize(1024 * 1024)]
    [AllowedExtensions(new string[] { ".json" })]
    public IFormFile File { get; set; }
}
</code>```

** NEW UPDATE **:
Now Controller doesn't work as intended. Cannot add elements to List (or maybe they are added just can't display it in the View not sure):
Controller:

```<code>public class BookingController : Controller
{
    private IMemoryCache _cache;
    private string bookingsKey = "bookingsList";
    public BookingController(IMemoryCache memoryCache)
    {
        _cache = memoryCache;
    }

    public IActionResult Index()
    {
        List<Booking> bookigsList;
        _cache.TryGetValue<List<Booking>>(bookingsKey, out bookigsList);
        return View(bookigsList);
    }

    /* MVVC fucking failed :(
    public IActionResult Index()
    {
        BookingList bookingsList;
        //_cache.TryGetValue(bookingsKey, out bookingList);

        bookingsList = new BookingList();
        bookingsList.BookingListObj = new List<Booking>();

        bookingsList.BookingListObj.Add(new Booking() { chargeState = 30, distance = 150, startTime = new DateTime(2020, 8, 13, 13, 45, 0), endTime = new DateTime(2020, 8, 13, 17, 0, 0) });
        _cache.Set<List<Booking>>(bookingsKey, bookingsList.BookingListObj);

        BookingViewModel bookingViewModel = new BookingViewModel()
        {
            Bookings = bookingsList.BookingListObj
        };

        return View(bookingViewModel);
    }*/

    [HttpGet]
    public IActionResult Create()
    {
        Booking booking = new Booking();
        return View("Create", booking);
    }

    [HttpPost]
    [ValidateAntiForgeryToken]
    public IActionResult Create(Booking booking)
    {
        List<Booking> bookingsList;

        //BookingList bookingsList;
        /*_cache.TryGetValue(bookingsKey, out bookingsList);
        BookingViewModel bookingViewModel = new BookingViewModel()
        {
            BookingList = bookingsList
        };*/

        if (!ModelState.IsValid)
        {
            return View("Create", booking);
        }
        if (!_cache.TryGetValue(bookingsKey, out bookingsList))
        {
            bookingsList = new List<Booking>();
        }

        bookingsList.Add(booking);
        _cache.Set<List<Booking>>(bookingsKey, bookingsList);

        /*BookingViewModel bookingViewModel = new BookingViewModel()
        {
            BookingList = bookingsList
        };*/

        return RedirectToAction("Index", "Booking");
    }
</code>```

BookingViewModel:

```<code>public class BookingViewModel
{
    public Booking Booking { get; set; }
    public BookingList BookingList { get; set; }
    public IEnumerable<Booking> Bookings { get; set; }
    public BookingsUpload BookingsUpload { get; set; }

    public BookingViewModel()
    {
        Booking = new Booking();
        Bookings = new List<Booking>();
        BookingsUpload = new BookingsUpload();
    }
}
</code>```

Booking Index:

```<code>    @model WebApplication.ViewModels.BookingViewModel

@{
    ViewData["Title"] = "Index";
}

<br />
<div class="container row p-0 m-0">
    <div class="container col 6">
        <h1 class="text-info">Übersicht aller Buchungen</h1>
    </div>
    <div class="container col-3">
        <div class="m-1">
            <a asp-controller="Booking" asp-action="Create" class="btn btn-info form-control text-white">Erstelle Buchung</a>
        </div>
        <div class="d-flex flex-row">
            <div class="w-100 m-1">
                <a asp-controller="Booking" asp-action="Export" class="btn btn-info form-control text-white">Export</a>
            </div>
            <div class="w-100 m-1">
                <form asp-controller="Booking" asp-action="Import" method="post" enctype="multipart/form-data">
                    <div class="form-group">
                        <label class="custom-file-upload">
                            <input type="file" name="file" onchange="this.form.submit()" />
                            Import/validation_bc_fuck_MVC
                        </label>
                        <span asp-validation-for="BookingsUpload.File" class="text-danger"></span>
                    </div>
                </form>
                <a asp-controller="Booking" asp-action="Import" class="btn btn-info form-control text-white">Import + validation</a>
            </div>
        </div>
    </div>

    <div class="col-12">
        @if (Model.Booking != null)
        {
            <table class="table table-striped table-borderless table-hover">
                <thead class="thead-dark">

                    <tr>
                        <th>
                            @Html.DisplayNameFor(model => Model.Booking.chargeState) %
                        </th>
                        <th>
                            @Html.DisplayNameFor(model => Model.Booking.distance) (km)
                        </th>
                        <th>
                            @Html.DisplayNameFor(model => Model.Booking.connectorType)
                        </th>
                        <th>
                            @Html.DisplayNameFor(model => Model.Booking.startTime)
                        </th>
                        <th>
                            @Html.DisplayNameFor(model => Model.Booking.endTime)
                        </th>
                    </tr>
                </thead>
                <tbody>
                    @foreach (var item in Model.Bookings)
                    {
                        <tr>
                            <td>
                                @Html.DisplayFor(modelItem => item.chargeState)
                            </td>
                            <td>
                                @Html.DisplayFor(modelItem => item.distance)
                            </td>
                            <td>
                                @Html.DisplayFor(modelItem => item.connectorType)
                            </td>
                            <td>
                                @Html.DisplayFor(modelItem => item.startTime)
                            </td>
                            <td>
                                @Html.DisplayFor(modelItem => item.endTime)
                            </td>
                        </tr>
                    }
                </tbody>
            </table>
        }
        else
        {
            <p>Es sind keine Buchungen vorhanden</p>
        }
    </div>
</div>

<style>
    input[type="file"] {
        display: none;
    }

    .custom-file-upload {
        color: #fff !important;
        background-color: #17a2b8;
        border-color: #17a2b8;
        /*text display: inline-block;*/
        cursor: pointer;
        font-weight: 400;
        text-align: center;
        vertical-align: middle;
        user-select: none;
        border: 1px solid transparent;
        padding: 6px 12px;
        font-size: 1rem;
        line-height: 1.5;
        border-radius: .25rem;
        transition: color .15s;
        width: 100%;
        height: calc(1.5em + .75rem + 2px);
    }

    .custom-file-upload:hover {
        background-color: #138496;
        border-color: #117a8b;
    }
</style>
</code>```

So the Import label is the problem because I cant access the File from BookingsUpload to make the span asp-validation-for="File" but with the Import button I managed to go to a different View with only this code below and there the validation works because there I can use the BookingsUpload model:

```<code>    @model WebApplication.Models.BookingsUpload;

@{
    ViewData["Title"] = "Import";
}

<h1>Import</h1>

<form asp-controller="Booking" asp-action="Import" method="post" enctype="multipart/form-data">
    <div class="form-group">
        <label class="custom-file-upload">
            <input asp-for="File" type="file" name="file" onchange="this.form.submit()" />
            Import
        </label>
        <span asp-validation-for="File" class="text-danger"></span>
    </div>
</form>
</code>```

答:
You can create view model that will contain Booking and BookingsUpload, and use it in your view.

```<code>public class BookingViewModel {
    public Booking Booking {get; set;}
    public BookingsUpload BookingsUpload {get; set;}
}
</code>```

then set those data in your controller's action and in view set model to BookingViewModel

```<code>@model BookingViewModel
// access Booking object view Model.Booking
// access BookingsUpload object via Model.BookingUploads
</code>```

Title: How to use 2 models in 1 View

Body:
I have a Booking model and I create a list of all it's elements in the BookingController. There I managed to export the list as .json, however when I want to import a file I can't manage to use my custom validation to see if it's only .json. The problem is that in my Index for Booking I have a IEnumerable model for Booking and I use a BookingsUpload model to upload the file. So how can I access this BookingsUpload model inside the Index or how could i change it ? (could I combine what i do in BookingsUpload with my Booking model ?

Booking Model:

public class Booking
{
    [Required]
    [Display(Name = "Ladestand")]
    [Range(0, 100)]
    public double chargeState { get; set; }

    [Required]
    [Display(Name = "Benötigte Fahrstrecke")]
    [Range(1, 1000)]
    public double distance { get; set; }

    [Required]
    [Display(Name = "Beginn")]
    public DateTime startTime { get; set; }

    [Required]
    [Display(Name = "Ende")]
    public DateTime endTime { get; set; }

    [Required]
    [Display(Name = "Anschlusstyp")]
    [EnumDataType(typeof(ConnectorType))]
    [JsonConverter(typeof(StringEnumConverter))]
    public ConnectorType connectorType { get; set; }
}

public class BookingList
        {
            public List<Booking> BookingListObj { get; set; }
        }

BookingsUpload Model:

public class BookingsUpload
{
    [Required(ErrorMessage = "Please select a file.")]
    [DataType(DataType.Upload)]
    [MaxFileSize(1024 * 1024)]
    [AllowedExtensions(new string[] { ".json" })]
    public IFormFile File { get; set; }
}

** NEW UPDATE **:
Now Controller doesn't work as intended. Cannot add elements to List (or maybe they are added just can't display it in the View not sure):
Controller:

public class BookingController : Controller
{
    private IMemoryCache _cache;
    private string bookingsKey = "bookingsList";
    public BookingController(IMemoryCache memoryCache)
    {
        _cache = memoryCache;
    }

    public IActionResult Index()
    {
        List<Booking> bookigsList;
        _cache.TryGetValue<List<Booking>>(bookingsKey, out bookigsList);
        return View(bookigsList);
    }

    /* MVVC fucking failed :(
    public IActionResult Index()
    {
        BookingList bookingsList;
        //_cache.TryGetValue(bookingsKey, out bookingList);

        bookingsList = new BookingList();
        bookingsList.BookingListObj = new List<Booking>();

        bookingsList.BookingListObj.Add(new Booking() { chargeState = 30, distance = 150, startTime = new DateTime(2020, 8, 13, 13, 45, 0), endTime = new DateTime(2020, 8, 13, 17, 0, 0) });
        _cache.Set<List<Booking>>(bookingsKey, bookingsList.BookingListObj);

        BookingViewModel bookingViewModel = new BookingViewModel()
        {
            Bookings = bookingsList.BookingListObj
        };

        return View(bookingViewModel);
    }*/

    [HttpGet]
    public IActionResult Create()
    {
        Booking booking = new Booking();
        return View("Create", booking);
    }

    [HttpPost]
    [ValidateAntiForgeryToken]
    public IActionResult Create(Booking booking)
    {
        List<Booking> bookingsList;

        //BookingList bookingsList;
        /*_cache.TryGetValue(bookingsKey, out bookingsList);
        BookingViewModel bookingViewModel = new BookingViewModel()
        {
            BookingList = bookingsList
        };*/

        if (!ModelState.IsValid)
        {
            return View("Create", booking);
        }
        if (!_cache.TryGetValue(bookingsKey, out bookingsList))
        {
            bookingsList = new List<Booking>();
        }

        bookingsList.Add(booking);
        _cache.Set<List<Booking>>(bookingsKey, bookingsList);

        /*BookingViewModel bookingViewModel = new BookingViewModel()
        {
            BookingList = bookingsList
        };*/

        return RedirectToAction("Index", "Booking");
    }

BookingViewModel:

public class BookingViewModel
{
    public Booking Booking { get; set; }
    public BookingList BookingList { get; set; }
    public IEnumerable<Booking> Bookings { get; set; }
    public BookingsUpload BookingsUpload { get; set; }

    public BookingViewModel()
    {
        Booking = new Booking();
        Bookings = new List<Booking>();
        BookingsUpload = new BookingsUpload();
    }
}

Booking Index:

    @model WebApplication.ViewModels.BookingViewModel

@{
    ViewData["Title"] = "Index";
}

Übersicht aller Buchungen

            Erstelle Buchung

                Export

                <form asp-controller="Booking" asp-action="Import" method="post" enctype="multipart/form-data">

                            <input type="file" name="file" onchange="this.form.submit()" />
                            Import/validation_bc_fuck_MVC

                </form>
                Import + validation

        @if (Model.Booking != null)
        {

                            @Html.DisplayNameFor(model => Model.Booking.chargeState) %

                            @Html.DisplayNameFor(model => Model.Booking.distance) (km)

                            @Html.DisplayNameFor(model => Model.Booking.connectorType)

                            @Html.DisplayNameFor(model => Model.Booking.startTime)

                            @Html.DisplayNameFor(model => Model.Booking.endTime)

                    @foreach (var item in Model.Bookings)
                    {

                                @Html.DisplayFor(modelItem => item.chargeState)

                                @Html.DisplayFor(modelItem => item.distance)

                                @Html.DisplayFor(modelItem => item.connectorType)

                                @Html.DisplayFor(modelItem => item.startTime)

                                @Html.DisplayFor(modelItem => item.endTime)

                    }

        }
        else
        {

Es sind keine Buchungen vorhanden

        }

So the Import label is the problem because I cant access the File from BookingsUpload to make the span asp-validation-for="File" but with the Import button I managed to go to a different View with only this code below and there the validation works because there I can use the BookingsUpload model:

    @model WebApplication.Models.BookingsUpload;

@{
    ViewData["Title"] = "Import";
}

Import

<form asp-controller="Booking" asp-action="Import" method="post" enctype="multipart/form-data">

            <input asp-for="File" type="file" name="file" onchange="this.form.submit()" />
            Import

</form>

Body:
You can create view model that will contain Booking and BookingsUpload, and use it in your view.

public class BookingViewModel {
    public Booking Booking {get; set;}
    public BookingsUpload BookingsUpload {get; set;}
}

then set those data in your controller's action and in view set model to BookingViewModel

@model BookingViewModel
// access Booking object view Model.Booking
// access BookingsUpload object via Model.BookingUploads


问:
TypeError: 'int' object is not iterable, don't know why this is happening
```<code>def rectangleArea(l):
    lt = list(l[0])
    l = lt[:3:2]
    l.sort()
    x = l[1] - l[0]
    l = lt[1:4:2]
    l.sort()
    y = l[1] - l[0]
    area = x * y
    return area
l = [(30, 60, 60, 30), (50, 10, 10, 50)]
for i in range(2):
    print("Rectangle")
    la = l[i]
    print(la)
    area = rectangleArea(la)
    print(area)
</code>```

Sorry for my bad english.
As you can see, tuples are in list 'l' and I don't want to edit this.
When I ran it without for loop, it worked well.
And with for loop, "TypeError: 'int' object is not iterable" appears.
The error message looks like this:

```<code>Traceback (most recent call last):
  File "C:/Users/Administrator/Desktop/MP09/help.py", line 19, in <module>
    area = rectangleArea(la)
  File "C:/Users/Administrator/Desktop/MP09/help.py", line 3, in rectangleArea
    lt = list(l1[0])
</code>```

I searched about it, and my situation isn't like the other.
I guess this is related with la = l[i] but i'm not sure.
What's wrong with this code. Please help me

答:
I was just about to answer this and saw that somebody else has, the problem is that list() returns a list from a tuple, string, list, or empty list.. you are passing a number into it in the function.. so..

```<code>lt = list(l[0])
    l = lt[:3:2]
    l.sort()
</code>```

if you passed (30,60,60,30) into this rectangleArea function, you passed that tuple as l, then you asked for l[0] which is 30.. you can only pass a string, tuple, list, or empty list into the python list() function.. so this number is not iterable.. if it were a string, you would then in the next line be looking for an index 3 and 2 when '30' would only have 0 and 1 indexes.. but you aren't getting to that point.

more info on list()

I hope this was helpful!

Body:
def rectangleArea(l):
    lt = list(l[0])
    l = lt[:3:2]
    l.sort()
    x = l[1] - l[0]
    l = lt[1:4:2]
    l.sort()
    y = l[1] - l[0]
    area = x * y
    return area
l = [(30, 60, 60, 30), (50, 10, 10, 50)]
for i in range(2):
    print("Rectangle")
    la = l[i]
    print(la)
    area = rectangleArea(la)
    print(area)

Sorry for my bad english.
As you can see, tuples are in list 'l' and I don't want to edit this.
When I ran it without for loop, it worked well.
And with for loop, "TypeError: 'int' object is not iterable" appears.
The error message looks like this:

Traceback (most recent call last):
  File "C:/Users/Administrator/Desktop/MP09/help.py", line 19, in <module>
    area = rectangleArea(la)
  File "C:/Users/Administrator/Desktop/MP09/help.py", line 3, in rectangleArea
    lt = list(l1[0])

I searched about it, and my situation isn't like the other.
I guess this is related with la = l[i] but i'm not sure.
What's wrong with this code. Please help me

Body:
I was just about to answer this and saw that somebody else has, the problem is that list() returns a list from a tuple, string, list, or empty list.. you are passing a number into it in the function.. so..

lt = list(l[0])
    l = lt[:3:2]
    l.sort()

if you passed (30,60,60,30) into this rectangleArea function, you passed that tuple as l, then you asked for l[0] which is 30.. you can only pass a string, tuple, list, or empty list into the python list() function.. so this number is not iterable.. if it were a string, you would then in the next line be looking for an index 3 and 2 when '30' would only have 0 and 1 indexes.. but you aren't getting to that point.

more info on list()

I hope this was helpful!


问:
Is it possible to generate random numbers through physical process simulation?
Is it possible to generate random numbers through physical process simulation?

If I simulate the physical roll of a dice (i.e. you picking it up, shaking it in your hand, releasing it onto the table and recording which side ends up "up"...) will that produce a "random" number or would I just have a complex simulation which really accomplishes nothing.

答: It'll still be a pseudo-random number because presumably you'll be using a pseudo-random number generator to simulate all the bouncing around of the die in your hands.</p>

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Jonathan Leffler

OwnerDisplayName: Dana


问:
Binding a queue to an EJB 3.0 MDB in WebSphere 7
I'm writing, or trying to write, Baby's First MDB on WebSphere 7. I have nearly no hair left, having pulled it all out trying to get the thing to work. It appears that I've got everything set up right, but I get no response when I put a message to the associated queue.

Here's the EAR file setup:

```<code>simplemdb.ear
    META-INF
        Manifest.mf
        application.xml
    simplemdb.jar
        META-INF
            Manifest.mf
            ejb-jar.xml
        com
            [ classes go here ]
</code>```

I can't find any syntax for defining the queue's JNDI name in ejb-jar.xml, so instead I:

Define a WebSphere activation spec. Name SimpleMDBActivationSpec, JNDI name jms/SimpleActivationSpec, Destination jms/SimpleMDBQueue.

Define a WebSphere queue. Name SimpleMDBQueue, JNDI name jms/SimpleMDBQueue, Queue name SIMPLE.MDB.QUEUE.

Define an MQ queue, name SIMPLE.MDB.QUEUE.

Deploy the EAR file. During the deployment, I'm asked to enter binding information. I select Activation Specification, then point the Target Resource JNDI Name and Destination JNDI name at the activation spec and queue, respectively.

(The MDB code has no annotations.) At this point, the app points to the spec and queue, and the spec points to the queue - belt and suspenders. Naturally, I imagine that the app therefore knows about the queue. Full of hope, I put a message on the queue, and ... nothing. The onMessage event is supposed to use System.out to log a message. I see no message.

Clear documentation on this is conspicuous by its absence. Google gives LOTS of results, but none of them details how the configuration all fits together. There's lots of hand-waving about ibm-ejb-jar-bnd.xmi, but examples of the file are arcane, full of opaque numbers with no explanation about how they were generated, or how they relate to other parts of the configuration.

For goodness' sake. All I want to do is deploy an MDB, and have it write "Hello, world" when I put a message to a queue. I'm using vi and ant as my development and build tools. Can anybody out there give me an idea about what I'm missing?

Edit: "zos" tag added.

答:
have a quick look at this and see if there is anything here that helps you.

http://publib.boulder.ibm.com/infocenter/ieduasst/v1r1m0/topic/com.ibm.iea.wasfpejb/wasfpejb/6.1/DevelopmentTools/WASv61_EJB3FP_MDBLab.pdf

I haven't played with this for the last one year so i am not able to comment straight away but i thought the PDF might be of some assistance to you.

HTH

Manglu

ContentLicense: CC BY-SA 3.0

Body:
I'm writing, or trying to write, Baby's First MDB on WebSphere 7. I have nearly no hair left, having pulled it all out trying to get the thing to work. It appears that I've got everything set up right, but I get no response when I put a message to the associated queue.

Here's the EAR file setup:

simplemdb.ear
    META-INF
        Manifest.mf
        application.xml
    simplemdb.jar
        META-INF
            Manifest.mf
            ejb-jar.xml
        com
            [ classes go here ]

I can't find any syntax for defining the queue's JNDI name in ejb-jar.xml, so instead I:

Define a WebSphere activation spec. Name SimpleMDBActivationSpec, JNDI name jms/SimpleActivationSpec, Destination jms/SimpleMDBQueue.

Define a WebSphere queue. Name SimpleMDBQueue, JNDI name jms/SimpleMDBQueue, Queue name SIMPLE.MDB.QUEUE.

Define an MQ queue, name SIMPLE.MDB.QUEUE.

Deploy the EAR file. During the deployment, I'm asked to enter binding information. I select Activation Specification, then point the Target Resource JNDI Name and Destination JNDI name at the activation spec and queue, respectively.

(The MDB code has no annotations.) At this point, the app points to the spec and queue, and the spec points to the queue - belt and suspenders. Naturally, I imagine that the app therefore knows about the queue. Full of hope, I put a message on the queue, and ... nothing. The onMessage event is supposed to use System.out to log a message. I see no message.

Clear documentation on this is conspicuous by its absence. Google gives LOTS of results, but none of them details how the configuration all fits together. There's lots of hand-waving about ibm-ejb-jar-bnd.xmi, but examples of the file are arcane, full of opaque numbers with no explanation about how they were generated, or how they relate to other parts of the configuration.

For goodness' sake. All I want to do is deploy an MDB, and have it write "Hello, world" when I put a message to a queue. I'm using vi and ant as my development and build tools. Can anybody out there give me an idea about what I'm missing?

Edit: "zos" tag added.


问:
In JavaScript, what's the most performant way to determine the first character in a string: startsWith, charAt, or [0]
While writing some code that needs to be as performant as possible, I came across this question about charAt vs startsWith, but then realized it applied specifically to Java. After running some tests on jsperf.com, I found my answer. See below.

答:
tl;dr

In Chrome 102, startsWith is faster than charAt. [0] is somewhere in the middle.

perf.link Results

You can view the perf.link test here. Below are the results I got testing in Chrome Version 102.0.5005.115 (Official Build) (arm64) / macOS Monterey Version 12.4:

Setup code:

const strs = [
  '',
  '*',
  '#',
  '*short',
  '#short',
  '*'.padEnd(2500, '-'),
  '#'.padEnd(2500, '-'),
]
```
<p><strong>startsWith</strong></p>
<pre class="lang-js prettyprint-override"><code>strs.forEach(str => str.startsWith('*'))
// 1,521,590 ops/s
// fastest
</code>```

charAt

strs.forEach(str => str.charAt(0) === '*')
// 1,060,830 ops/s
```
<p><strong>[0]</strong></p>
```strs.forEach(str => str[0] === '*')
// 1,294,190 ops/s
```


问:
Loopback4 authorization user property role is always undefined
I have successfully implemented jwt auth in my lb4 app using custom service which implements userservice from @loopback/authentication-jwt. Everything is working fine for authentication.

But when I go for authorization AuthorizationMetadata contains only two fields - id and name. While issuing token I have used many fields one of which was role.

But now all other fields like role or email are undefined. Thus whenever I try to access controller protected with authorize decorator I get 501 access denied.

I can't get why other properties are undefined.

Thank you in advance

custom-service

```<code>export class CustomUserService implements UserService<User, Credentials> {

// other code

      convertToUserProfile(user: User): UserProfile {

        let address = ''
        if (user.address) {
          address = user.address
        }

        const profile = {
          [securityId]: user.id!.toString(),
          name: user.name,
          id: user.id,
          email: user.email,
          role: user.role,
          address: user.address
        }

        console.log(profile)
        return profile
      }
}
</code>```

login controller

```<code>import {authenticate, TokenService, UserService} from '@loopback/authentication';
export class UserController {

constructor(@inject(SecurityBindings.USER, {optional: true})
    public users: UserProfile,){}

//@get login
 async login(
    @requestBody(CredentialsRequestBody) credentials: Credentials,
  ): Promise<{token: string}> {
    // ensure the user exists, and the password is correct
    const user = await this.userService.verifyCredentials(credentials);

    // convert a User object into a UserProfile object (reduced set of properties)
    const userProfile = this.userService.convertToUserProfile(user);

    // create a JSON Web Token based on the user profile
    const token = await this.jwtService.generateToken(userProfile);

    return {token};

}
</code>```

authorizer.ts

```<code>import {AuthorizationContext, AuthorizationDecision, AuthorizationMetadata} from '@loopback/authorization';

export async function basicAuthorization(
  authorizationCtx: AuthorizationContext,
  metadata: AuthorizationMetadata,
): Promise<AuthorizationDecision> {
  // No access if authorization details are missing
  let currentUser: UserProfile;
  if (authorizationCtx.principals.length > 0) {
    const user = _.pick(authorizationCtx.principals[0]
      , [
        'id',
        'name',
        'role',
        'email',
        'address'
      ]);

    console.log(user) // contains only id and name
  // other code
  }
}
</code>```

答:
The actual problem was while generating the token, property role wasn't included in TokenService from @loopback/authentication.

So I created custom-token service implementing this TokenService and added a property role while token-generation.

So later loopback-authentication sends this role to loopback-authorization. You can access it in AuthorizationContext.principals[0]

Here is the code

custom-toekn.service.ts

```<code>import {TokenService} from '@loopback/authentication';
import {inject} from '@loopback/context';
import {HttpErrors} from '@loopback/rest';
import {securityId, UserProfile} from '@loopback/security';
import {promisify} from 'util';
import {TokenServiceBindings} from '../keys';

const jwt = require('jsonwebtoken');
const signAsync = promisify(jwt.sign);
const verifyAsync = promisify(jwt.verify);

export class JWTService implements TokenService {
  constructor(
    @inject(TokenServiceBindings.TOKEN_SECRET)
    private jwtSecret: string,
    @inject(TokenServiceBindings.TOKEN_EXPIRES_IN)
    private jwtExpiresIn: string,
  ) {}

  async verifyToken(token: string): Promise<UserProfile> {
    if (!token) {
      throw new HttpErrors.Unauthorized(
        `Error verifying token : 'token' is null`,
      );
    }

    let userProfile: UserProfile;

    try {
      // decode user profile from token
      const decodedToken = await verifyAsync(token, this.jwtSecret);
      // don't copy over  token field 'iat' and 'exp', nor 'email' to user profile
      userProfile = Object.assign(
        {[securityId]: '', name: ''},
        {
          [securityId]: decodedToken.id,
          name: decodedToken.name,
          id: decodedToken.id,
          role: decodedToken.role,
        },
      );
    } catch (error) {
      throw new HttpErrors.Unauthorized(
        `Error verifying token : ${error.message}`,
      );
    }
    return userProfile;
  }

  async generateToken(userProfile: UserProfile): Promise<string> {
    if (!userProfile) {
      throw new HttpErrors.Unauthorized(
        'Error generating token : userProfile is null',
      );
    }
    const userInfoForToken = {
      id: userProfile[securityId],
      name: userProfile.name,
      role: userProfile.role,
    };
    // Generate a JSON Web Token
    let token: string;
    try {
      token = await signAsync(userInfoForToken, this.jwtSecret, {
        expiresIn: Number(this.jwtExpiresIn),
      });
    } catch (error) {
      throw new HttpErrors.Unauthorized(`Error encoding token : ${error}`);
    }

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

keys.ts

```<code>import {TokenService} from '@loopback/authentication';

export namespace TokenServiceConstants {
  export const TOKEN_SECRET_VALUE = 'myjwts3cr3t';
  export const TOKEN_EXPIRES_IN_VALUE = '600';
}

export namespace TokenServiceBindings {
  export const TOKEN_SECRET = BindingKey.create<string>(
    'authentication.jwt.secret',
  );
  export const TOKEN_EXPIRES_IN = BindingKey.create<string>(
    'authentication.jwt.expires.in.seconds',
  );
  export const TOKEN_SERVICE = BindingKey.create<TokenService>(
    'services.authentication.jwt.tokenservice',
  );
}
</code>```

Then you have to bind this token-service in application.ts

application.ts

```<code>import {JWTService} from './services/token-service';
import {TokenServiceBindings, TokenServiceConstants} from './keys';

this.bind(TokenServiceBindings.TOKEN_SECRET).to(
      TokenServiceConstants.TOKEN_SECRET_VALUE,
    );

    this.bind(TokenServiceBindings.TOKEN_EXPIRES_IN).to(
      TokenServiceConstants.TOKEN_EXPIRES_IN_VALUE,
    );

    this.bind(TokenServiceBindings.TOKEN_SERVICE).toClass(JWTService);
</code>```

controller.ts

```<code>import {authenticate, TokenService, UserService} from '@loopback/authentication';
import {Credentials, OPERATION_SECURITY_SPEC, TokenServiceBindings, UserServiceBindings} from '@loopback/authentication-jwt';
import {authorize} from '@loopback/authorization';

export class UserController {
  constructor(
    @repository(UserRepository)
    public userRepository: UserRepository,

    @inject(TokenServiceBindings.TOKEN_SERVICE)
    public jwtService: TokenService,
    @inject(UserServiceBindings.USER_SERVICE)
    public userService: UserService<User, Credentials>,
    @inject(SecurityBindings.USER, {optional: true})
    public users: UserProfile,

  ) {}

@authenticate('jwt')
  @authorize({allowedRoles: ['admin'], voters: [basicAuthorization]})

aasync fund(){}

}
</code>```

Body:
I have successfully implemented jwt auth in my lb4 app using custom service which implements userservice from @loopback/authentication-jwt. Everything is working fine for authentication.

But when I go for authorization AuthorizationMetadata contains only two fields - id and name. While issuing token I have used many fields one of which was role.

But now all other fields like role or email are undefined. Thus whenever I try to access controller protected with authorize decorator I get 501 access denied.

I can't get why other properties are undefined.

Thank you in advance

custom-service

export class CustomUserService implements UserService<User, Credentials> {

// other code

      convertToUserProfile(user: User): UserProfile {

        let address = ''
        if (user.address) {
          address = user.address
        }

        const profile = {
          [securityId]: user.id!.toString(),
          name: user.name,
          id: user.id,
          email: user.email,
          role: user.role,
          address: user.address
        }

        console.log(profile)
        return profile
      }
}

login controller

import {authenticate, TokenService, UserService} from '@loopback/authentication';
export class UserController {

constructor(@inject(SecurityBindings.USER, {optional: true})
    public users: UserProfile,){}

//@get login
 async login(
    @requestBody(CredentialsRequestBody) credentials: Credentials,
  ): Promise<{token: string}> {
    // ensure the user exists, and the password is correct
    const user = await this.userService.verifyCredentials(credentials);

    // convert a User object into a UserProfile object (reduced set of properties)
    const userProfile = this.userService.convertToUserProfile(user);

    // create a JSON Web Token based on the user profile
    const token = await this.jwtService.generateToken(userProfile);

    return {token};

}

authorizer.ts

import {AuthorizationContext, AuthorizationDecision, AuthorizationMetadata} from '@loopback/authorization';

export async function basicAuthorization(
  authorizationCtx: AuthorizationContext,
  metadata: AuthorizationMetadata,
): Promise<AuthorizationDecision> {
  // No access if authorization details are missing
  let currentUser: UserProfile;
  if (authorizationCtx.principals.length > 0) {
    const user = _.pick(authorizationCtx.principals[0]
      , [
        'id',
        'name',
        'role',
        'email',
        'address'
      ]);

    console.log(user) // contains only id and name
  // other code
  }
}

Body:
The actual problem was while generating the token, property role wasn't included in TokenService from @loopback/authentication.

So I created custom-token service implementing this TokenService and added a property role while token-generation.

So later loopback-authentication sends this role to loopback-authorization. You can access it in AuthorizationContext.principals[0]

Here is the code

custom-toekn.service.ts

import {TokenService} from '@loopback/authentication';
import {inject} from '@loopback/context';
import {HttpErrors} from '@loopback/rest';
import {securityId, UserProfile} from '@loopback/security';
import {promisify} from 'util';
import {TokenServiceBindings} from '../keys';

const jwt = require('jsonwebtoken');
const signAsync = promisify(jwt.sign);
const verifyAsync = promisify(jwt.verify);

export class JWTService implements TokenService {
  constructor(
    @inject(TokenServiceBindings.TOKEN_SECRET)
    private jwtSecret: string,
    @inject(TokenServiceBindings.TOKEN_EXPIRES_IN)
    private jwtExpiresIn: string,
  ) {}

  async verifyToken(token: string): Promise<UserProfile> {
    if (!token) {
      throw new HttpErrors.Unauthorized(
        `Error verifying token : 'token' is null`,
      );
    }

    let userProfile: UserProfile;

    try {
      // decode user profile from token
      const decodedToken = await verifyAsync(token, this.jwtSecret);
      // don't copy over  token field 'iat' and 'exp', nor 'email' to user profile
      userProfile = Object.assign(
        {[securityId]: '', name: ''},
        {
          [securityId]: decodedToken.id,
          name: decodedToken.name,
          id: decodedToken.id,
          role: decodedToken.role,
        },
      );
    } catch (error) {
      throw new HttpErrors.Unauthorized(
        `Error verifying token : ${error.message}`,
      );
    }
    return userProfile;
  }

  async generateToken(userProfile: UserProfile): Promise<string> {
    if (!userProfile) {
      throw new HttpErrors.Unauthorized(
        'Error generating token : userProfile is null',
      );
    }
    const userInfoForToken = {
      id: userProfile[securityId],
      name: userProfile.name,
      role: userProfile.role,
    };
    // Generate a JSON Web Token
    let token: string;
    try {
      token = await signAsync(userInfoForToken, this.jwtSecret, {
        expiresIn: Number(this.jwtExpiresIn),
      });
    } catch (error) {
      throw new HttpErrors.Unauthorized(`Error encoding token : ${error}`);
    }

    return token;
  }
}

keys.ts

import {TokenService} from '@loopback/authentication';

export namespace TokenServiceConstants {
  export const TOKEN_SECRET_VALUE = 'myjwts3cr3t';
  export const TOKEN_EXPIRES_IN_VALUE = '600';
}

export namespace TokenServiceBindings {
  export const TOKEN_SECRET = BindingKey.create<string>(
    'authentication.jwt.secret',
  );
  export const TOKEN_EXPIRES_IN = BindingKey.create<string>(
    'authentication.jwt.expires.in.seconds',
  );
  export const TOKEN_SERVICE = BindingKey.create<TokenService>(
    'services.authentication.jwt.tokenservice',
  );
}

Then you have to bind this token-service in application.ts

application.ts

import {JWTService} from './services/token-service';
import {TokenServiceBindings, TokenServiceConstants} from './keys';

this.bind(TokenServiceBindings.TOKEN_SECRET).to(
      TokenServiceConstants.TOKEN_SECRET_VALUE,
    );

    this.bind(TokenServiceBindings.TOKEN_EXPIRES_IN).to(
      TokenServiceConstants.TOKEN_EXPIRES_IN_VALUE,
    );

    this.bind(TokenServiceBindings.TOKEN_SERVICE).toClass(JWTService);

controller.ts

import {authenticate, TokenService, UserService} from '@loopback/authentication';
import {Credentials, OPERATION_SECURITY_SPEC, TokenServiceBindings, UserServiceBindings} from '@loopback/authentication-jwt';
import {authorize} from '@loopback/authorization';

export class UserController {
  constructor(
    @repository(UserRepository)
    public userRepository: UserRepository,

    @inject(TokenServiceBindings.TOKEN_SERVICE)
    public jwtService: TokenService,
    @inject(UserServiceBindings.USER_SERVICE)
    public userService: UserService<User, Credentials>,
    @inject(SecurityBindings.USER, {optional: true})
    public users: UserProfile,

  ) {}

@authenticate('jwt')
  @authorize({allowedRoles: ['admin'], voters: [basicAuthorization]})

aasync fund(){}

}


问:
Take input from user using cmd after running Python script
I want to take input from the user after running my py script in Windows.

A new cmd should pop up displaying a particular message like "Do you wish to continue [y/n]" and store this value in a variable in the py script and cmd should close automatically after the user provides input.
(Using Python 3)
Can anyone please help.

答: You can do that with subprocess.run().</p>

Body: You can do that with subprocess.run().


问:
Spring Cloud Gateway doesn't work with @Bean DiscoveryClientRouteDefinitionLocator
I follow Spring Tips: Spring Cloud Gateway. But my gateway app doesn't create routes from the service register(Eureka). DiscoveryClientRouteDefinitionLocator constructor with 2 params. The gateway app it's not routing from Eureka server. I've been trying changing the versions in the pom.xml but I'm using the RELEASE.

The Application.java

```<code>@SpringBootApplication
public class GatewayApplication {

    @Bean
    DiscoveryClientRouteDefinitionLocator discoveryRoutes(DiscoveryClient dc, DiscoveryLocatorProperties dlp) {
        return new DiscoveryClientRouteDefinitionLocator(dc, dlp);
    }

    public static void main(String[] args) {
        SpringApplication.run(GatewayApplication.class, args);
    }
}
</code>```

The constructor of the DiscoveryClientRouteDefinitionLocator is using now 2 params instead just 1 like in the Spring Tips: Spring Clou Gateway.

The application.property:

```<code>spring.application.name=gateway
server.port=8081
eureka.client.register-with-eureka=true
</code>```

My pom.xml:

```<code><?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

<groupId>com.hcl.cnp</groupId>
<artifactId>gateway</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>

<name>gateway</name>
<description>Demo project for Spring Boot</description>

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.0.3.RELEASE</version>
    <relativePath/> <!-- lookup parent from repository -->
</parent>

<properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
    <java.version>1.8</java.version>
    <spring-cloud.version>Finchley.RELEASE</spring-cloud.version>
</properties>

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-actuator</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-redis</artifactId>
    </dependency>
    <!--<dependency>-->
        <!--<groupId>org.springframework.boot</groupId>-->
        <!--<artifactId>spring-boot-starter-security</artifactId>-->
    <!--</dependency>-->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-webflux</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-gateway</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
    </dependency>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>io.projectreactor</groupId>
        <artifactId>reactor-test</artifactId>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>org.springframework.security</groupId>
        <artifactId>spring-security-test</artifactId>
        <scope>test</scope>
    </dependency>
</dependencies>

<dependencyManagement>
    <dependencies>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-dependencies</artifactId>
            <version>${spring-cloud.version}</version>
            <type>pom</type>
            <scope>import</scope>
        </dependency>
    </dependencies>
</dependencyManagement>

<build>
    <plugins>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
        </plugin>
    </plugins>
</build>

</project>
</code>```

答:
The constructor DiscoveryClientRouteDefinitionLocator(DiscoveryClient, DiscoveryLocatorProperties) is deprecated

I suggest you to use :

ReactiveDiscoveryClient instead of DiscroveryClient

```<code>@Bean
DiscoveryClientRouteDefinitionLocator discoveryRoutes(ReactiveDiscoveryClient rdc,
        DiscoveryLocatorProperties dlp) {
    return new DiscoveryClientRouteDefinitionLocator(rdc, dlp);
}
</code>```

Other thing, you should rename your application.proporty to application.properities

Body:
I follow Spring Tips: Spring Cloud Gateway. But my gateway app doesn't create routes from the service register(Eureka). DiscoveryClientRouteDefinitionLocator constructor with 2 params. The gateway app it's not routing from Eureka server. I've been trying changing the versions in the pom.xml but I'm using the RELEASE.

The Application.java

@SpringBootApplication
public class GatewayApplication {

    @Bean
    DiscoveryClientRouteDefinitionLocator discoveryRoutes(DiscoveryClient dc, DiscoveryLocatorProperties dlp) {
        return new DiscoveryClientRouteDefinitionLocator(dc, dlp);
    }

    public static void main(String[] args) {
        SpringApplication.run(GatewayApplication.class, args);
    }
}

The constructor of the DiscoveryClientRouteDefinitionLocator is using now 2 params instead just 1 like in the Spring Tips: Spring Clou Gateway.

The application.property:

spring.application.name=gateway
server.port=8081
eureka.client.register-with-eureka=true

My pom.xml:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

<groupId>com.hcl.cnp</groupId>
<artifactId>gateway</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>

<name>gateway</name>
<description>Demo project for Spring Boot</description>

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.0.3.RELEASE</version>
    <relativePath/>
</parent>

<properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
    <java.version>1.8</java.version>
    <spring-cloud.version>Finchley.RELEASE</spring-cloud.version>
</properties>

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-actuator</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-redis</artifactId>
    </dependency>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-webflux</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-gateway</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
    </dependency>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>io.projectreactor</groupId>
        <artifactId>reactor-test</artifactId>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>org.springframework.security</groupId>
        <artifactId>spring-security-test</artifactId>
        <scope>test</scope>
    </dependency>
</dependencies>

<dependencyManagement>
    <dependencies>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-dependencies</artifactId>
            <version>${spring-cloud.version}</version>
            <type>pom</type>
            <scope>import</scope>
        </dependency>
    </dependencies>
</dependencyManagement>

<build>
    <plugins>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
        </plugin>
    </plugins>
</build>

</project>

Body:
The constructor DiscoveryClientRouteDefinitionLocator(DiscoveryClient, DiscoveryLocatorProperties) is deprecated

I suggest you to use :

ReactiveDiscoveryClient instead of DiscroveryClient

@Bean
DiscoveryClientRouteDefinitionLocator discoveryRoutes(ReactiveDiscoveryClient rdc,
        DiscoveryLocatorProperties dlp) {
    return new DiscoveryClientRouteDefinitionLocator(rdc, dlp);
}

Other thing, you should rename your application.proporty to application.properities


问:
rose diagram based on group and color it based on group in r
I have a data in degrees of three different groups. I managed to draw rose diagram using circular package but i want to color and label the rose diagram based on group. following is my data;

```<code>Value    Category
74.71    A
86.43    A
349.20   A
143.46   A
315.95   A
25.37    A
347.52   A
225.72   A
195.58   A
103.22   A
73.25    B
94.79    B
76.95    B
183.77   B
353.51   B
1.04     B
3.64     B
216.62   B
28.25    B
96.89    B
252.32   C
320.11   C
287.45   C
7.42     C
6.56     C
298.36   C
115.25   C
218.14   C
182.25   C
193.23   C
</code>```

Following is my code;

```<code>data<-data.frame(rosediag[2:3])
angl<-data$Value
group<-data$Category
rose.diag(angl,bins = 30, main = "All Categories")
</code>```

I want a rose diagram that shows A, B, C in different color and label them in a side bar. I want all 30 data points displayed on the rose diagram and color based on category.
enter image description here

答:
I don't know whether this can be easily achieved with circular, but if you would be willing to use another package, below is an example of what you could get with plotly - is that what you are after?

suppressPackageStartupMessages(library(plotly))
df <- data.frame(
    Value = c(74.71, 86.43, 349.2, 143.46, 315.95, 25.37, 347.52, 225.72,
        195.58, 103.22, 73.25, 94.79, 76.95, 183.77, 353.51, 1.04, 3.64, 216.62,
        28.25, 96.89, 252.32, 320.11, 287.45, 7.42, 6.56, 298.36, 115.25,
        218.14, 182.25, 193.23),
    Category = rep(LETTERS[1:3], each=10))

with(df, plot_ly(color=Category, theta=Value, type='barpolar', r=1))
```

Created on 2020-05-29 by the reprex package (v0.3.0)

Body:
I have a data in degrees of three different groups. I managed to draw rose diagram using circular package but i want to color and label the rose diagram based on group. following is my data;

Value    Category
74.71    A
86.43    A
349.20   A
143.46   A
315.95   A
25.37    A
347.52   A
225.72   A
195.58   A
103.22   A
73.25    B
94.79    B
76.95    B
183.77   B
353.51   B
1.04     B
3.64     B
216.62   B
28.25    B
96.89    B
252.32   C
320.11   C
287.45   C
7.42     C
6.56     C
298.36   C
115.25   C
218.14   C
182.25   C
193.23   C

Following is my code;

data<-data.frame(rosediag[2:3])
angl<-data$Value
group<-data$Category
rose.diag(angl,bins = 30, main = "All Categories")

I want a rose diagram that shows A, B, C in different color and label them in a side bar. I want all 30 data points displayed on the rose diagram and color based on category.
enter image description here

Body:
I don't know whether this can be easily achieved with circular, but if you would be willing to use another package, below is an example of what you could get with plotly - is that what you are after?

suppressPackageStartupMessages(library(plotly))
df <- data.frame(
    Value = c(74.71, 86.43, 349.2, 143.46, 315.95, 25.37, 347.52, 225.72,
        195.58, 103.22, 73.25, 94.79, 76.95, 183.77, 353.51, 1.04, 3.64, 216.62,
        28.25, 96.89, 252.32, 320.11, 287.45, 7.42, 6.56, 298.36, 115.25,
        218.14, 182.25, 193.23),
    Category = rep(LETTERS[1:3], each=10))

with(df, plot_ly(color=Category, theta=Value, type='barpolar', r=1))

Created on 2020-05-29 by the reprex package (v0.3.0)


问:
xDebug not working using docker, vscode and WSL 2
I am not sure what the issue is, it just doesn't work.

The routing seems to work, I have a server name in my nginx conf file. e.g. test.com. that works.

My project is in the root of ubuntu and not in the mount folders.

I am not sure what else to try.

xdebug.ini

```<code>[XDebug]
zend_extension=/usr/local/lib/php/extensions/no-debug-non-zts-20190902/xdebug.so

xdebug.default_enable=1
xdebug.remote_enable=1
xdebug.remote_port=9002
xdebug.remote_handler=dbgp
xdebug.remote_connect_back=0
xdebug.remote_host=soapboxtest.com
xdebug.idekey=VSCODE
xdebug.remote_autostart=1
xdebug.remote_log=/usr/local/etc/php/xdebug.log
</code>```

launch.json

```<code>{
  "name": "Listen for XDebug",
  "type": "php",
  "request": "launch",
  "port": 9002,
  "log": true,
  "externalConsole": false,
  "pathMappings": {
    "/var/www": "${workspaceRoot}"
  },
  "ignore": [
    "**/vendor/**/*.php"
    ]
  },
</code>```

Request cookies

```<code>"XDEBUG_SESSION" => "VSCODE"
</code>```

Dockerfile

```<code>FROM php:fpm-alpine3.11
...
RUN pecl install xdebug
RUN docker-php-ext-enable xdebug
...
</code>```

答:
This happened to me also and found that XDEBUG is not looking for the Docker Daemon Host. Got it fixed by adding:

```<code>"hostname": "0.0.0.0"
</code>```

As part of the general options of the launch.json on VS Code.

Full example:

{
    "version": "0.2.0",
    "configurations": [
        {
            "name": "XDebug",
            "type": "php",
            "request": "launch",
            "hostname": "0.0.0.0",
            "port": 9000,
            "pathMappings": {
                "/var/www/html/": "${workspaceFolder}"
            },
            "xdebugSettings": {
                "max_children": 999,
                "max_data": -1,
            }
        }
    ]
}
```

Body:
I am not sure what the issue is, it just doesn't work.

The routing seems to work, I have a server name in my nginx conf file. e.g. test.com. that works.

My project is in the root of ubuntu and not in the mount folders.

I am not sure what else to try.

xdebug.ini

[XDebug]
zend_extension=/usr/local/lib/php/extensions/no-debug-non-zts-20190902/xdebug.so

xdebug.default_enable=1
xdebug.remote_enable=1
xdebug.remote_port=9002
xdebug.remote_handler=dbgp
xdebug.remote_connect_back=0
xdebug.remote_host=soapboxtest.com
xdebug.idekey=VSCODE
xdebug.remote_autostart=1
xdebug.remote_log=/usr/local/etc/php/xdebug.log

launch.json

{
  "name": "Listen for XDebug",
  "type": "php",
  "request": "launch",
  "port": 9002,
  "log": true,
  "externalConsole": false,
  "pathMappings": {
    "/var/www": "${workspaceRoot}"
  },
  "ignore": [
    "**/vendor/**/*.php"
    ]
  },

Request cookies

"XDEBUG_SESSION" => "VSCODE"

Dockerfile

FROM php:fpm-alpine3.11
...
RUN pecl install xdebug
RUN docker-php-ext-enable xdebug
...

Body:
This happened to me also and found that XDEBUG is not looking for the Docker Daemon Host. Got it fixed by adding:

"hostname": "0.0.0.0"

As part of the general options of the launch.json on VS Code.

Full example:

{
    "version": "0.2.0",
    "configurations": [
        {
            "name": "XDebug",
            "type": "php",
            "request": "launch",
            "hostname": "0.0.0.0",
            "port": 9000,
            "pathMappings": {
                "/var/www/html/": "${workspaceFolder}"
            },
            "xdebugSettings": {
                "max_children": 999,
                "max_data": -1,
            }
        }
    ]
}


问:
Panda Merging Unexpected Result
I have two dataframes created with pandas. I don't know how to merge the two dataframes in a particular format using a common column.

I used

```<code>pd.merge(dataframe1,dataframe2,on='A',how='outer')
</code>```

but that doesn't yield the expected result.

Expected Result:

```<code>dataframe 1:        dataframe 2:       Result:

A B                 A                   A B
0 1                 0                   0 1
1 0                 1                   1 0
2 0                 2                   2 0
4 1                 3                   3 Nan
                    5                   4 1
                                        5 Nan

</code>```

Obtained Result:

```<code>dataframe 1:        dataframe 2:       Result:

A B                 A                   A B
0 1                 0                   0 1
1 0                 1                   1 0
2 0                 2                   2 0
4 1                 3                   3 1
                    5                   4 Nan
                                        5 Nan

</code>```

答:
Always check the data. The used showed me that there were no spaces but then sent a file with spaces (He sent the version w/o hitting save) added .str.strip() to the data element and everything started working.

Never trust any input. Always Verify.

Title: Panda Merging Unexpected Result

Body:
I have two dataframes created with pandas. I don't know how to merge the two dataframes in a particular format using a common column.

I used

pd.merge(dataframe1,dataframe2,on='A',how='outer')

but that doesn't yield the expected result.

Expected Result:

dataframe 1:        dataframe 2:       Result:

A B                 A                   A B
0 1                 0                   0 1
1 0                 1                   1 0
2 0                 2                   2 0
4 1                 3                   3 Nan
                    5                   4 1
                                        5 Nan

Obtained Result:

dataframe 1:        dataframe 2:       Result:

A B                 A                   A B
0 1                 0                   0 1
1 0                 1                   1 0
2 0                 2                   2 0
4 1                 3                   3 1
                    5                   4 Nan
                                        5 Nan


问:
How do I setup Apache and Tomcat for JSP and SEO-friendly clean URLs
I'm looking for is a "Best Practices" approach for setting up Apache httpd (2.2) with Tomcat 6 so that we can:

Allow JSP files to be served for directory listings (e.g. http:/www.example.com displays index.jsp via DirectoryIndex index.jsp).

Hide the extensions of all URLs (both *.html and *.php files served by Apache and *.jsp served by Tomcat) to make them SEO friendly. So for instance, http:/www.example.com/about-us might resolve to  about-us.jsp.

What I'm looking for is the "recommended" approach to do this (examples would be phenomenal). I'm aware of mod_rewrite, mod_jk, mod_proxy_ajp, and mod_proxy_http, but what I'm looking is pros/cons and any experience you folks may have with one or the other and how you went about setting it all up.

Any and all advice welcome.

Thanks

答:
Here are the guidelines I'm familiar with:

Try to do as much as possible in your application without the use of Apache. This will make hosting your application easier and it will help you maintain your application, because all the logic is in one spot. Additional advantage: you don't need Apache to run your application locally.

A way to do it with tomcat is to use your web.xml.
For example, to get to the homepage:

    /homepage.jsp

Here's an example of how you can map any url, in this case "/detailpage" to the /detailpage.jsp file:

```<code><servlet>
    <servlet-name>detail</servlet-name>
    <jsp-file>/detailpage.jsp</jsp-file>
</servlet>
<servlet-mapping>
    <servlet-name>detail</servlet-name>
    <url-pattern>/detailpage</url-pattern>
</servlet-mapping>
</code>```

For more information on using the web.xml file:
http://code.google.com/appengine/docs/java/config/webxml.html

Now, this can become tedious when you have a lot of documents, but I guess in that case you would start using a CMS that fixed this for you, right? Here's how it's done in Hippo CMS for example:
http://www.onehippo.org/7_7/library/concepts/request-handling/sitemapitem-matching.html.

On nice url's:
I don't think it's considered bad practice to add .jsp or .html to detailpages. Personally I like .html for detailpages and just the name for overview pages, but I guess that's a matter of taste.
Here's more background information the Dutch government gives about friendly url's:
http://versie1.webrichtlijnen.nl/english/manual/development/production/permanent-unique-urls/friendly-urls/

Disclaimer: You shouldn't see the Hippo reference as an exclusive reference. I work for Hippo, so I referenced the URL matching implementation I know of. Other (Java based) CMS's which may have similar solutions can be found here: http://en.wikipedia.org/wiki/List_of_content_management_systems#Java

Body:
Here are the guidelines I'm familiar with:

Try to do as much as possible in your application without the use of Apache. This will make hosting your application easier and it will help you maintain your application, because all the logic is in one spot. Additional advantage: you don't need Apache to run your application locally.

A way to do it with tomcat is to use your web.xml.
For example, to get to the homepage:

    /homepage.jsp

Here's an example of how you can map any url, in this case "/detailpage" to the /detailpage.jsp file:

<servlet>
    <servlet-name>detail</servlet-name>
    <jsp-file>/detailpage.jsp</jsp-file>
</servlet>
<servlet-mapping>
    <servlet-name>detail</servlet-name>
    <url-pattern>/detailpage</url-pattern>
</servlet-mapping>

For more information on using the web.xml file:
http://code.google.com/appengine/docs/java/config/webxml.html

Now, this can become tedious when you have a lot of documents, but I guess in that case you would start using a CMS that fixed this for you, right? Here's how it's done in Hippo CMS for example:
http://www.onehippo.org/7_7/library/concepts/request-handling/sitemapitem-matching.html.

On nice url's:
I don't think it's considered bad practice to add .jsp or .html to detailpages. Personally I like .html for detailpages and just the name for overview pages, but I guess that's a matter of taste.
Here's more background information the Dutch government gives about friendly url's:
http://versie1.webrichtlijnen.nl/english/manual/development/production/permanent-unique-urls/friendly-urls/

Disclaimer: You shouldn't see the Hippo reference as an exclusive reference. I work for Hippo, so I referenced the URL matching implementation I know of. Other (Java based) CMS's which may have similar solutions can be found here: http://en.wikipedia.org/wiki/List_of_content_management_systems#Java


问:
Creating a function to loop over a list of Tuples with dates
Hi guys I needed some help. I have a list of tuples wherein each tuple contains 3 elements.

Year in format 2020.

Month in integer from 1-12

Any random integer value

I wanted to create a function to loop over this list of tuples so that in each tuple I can calculate the difference between the month and the given integer and then find out the new month according to the remainder.
For example,  the tuple for May 2020 would be (2020,5,3) so then the result would be 5-3=2 which would mean Feb 2020. Also if the result is negative then the year would decrease from 2020 to 2019 and so on according to the difference. Any help would be appreciated .

Edit -  So I created this function using the logic given in one of the answers below but it's not exactly what I wanted,

```<code>def subtract_months(input_list):

output_list = []

#TODO: implement your code here

for i in input_list:

    result = i[1]-i[2]

    if 12 >= result > 0:
        output_list.append((i[0],result))
    else:
        output_list.append((i[0]-1,12-abs(result)))

return output_list
</code>```

If i use an input like [(2020,5,3)] The code works fine and gives an output of (2020,2) but if I want to give input like [(2020,5,20)] then its just looping for one year rather than 2 years.

Body:
Hi guys I needed some help. I have a list of tuples wherein each tuple contains 3 elements.

Year in format 2020.

Month in integer from 1-12

Any random integer value

I wanted to create a function to loop over this list of tuples so that in each tuple I can calculate the difference between the month and the given integer and then find out the new month according to the remainder.
For example,  the tuple for May 2020 would be (2020,5,3) so then the result would be 5-3=2 which would mean Feb 2020. Also if the result is negative then the year would decrease from 2020 to 2019 and so on according to the difference. Any help would be appreciated .

Edit -  So I created this function using the logic given in one of the answers below but it's not exactly what I wanted,

def subtract_months(input_list):

output_list = []

#TODO: implement your code here

for i in input_list:

    result = i[1]-i[2]

    if 12 >= result > 0:
        output_list.append((i[0],result))
    else:
        output_list.append((i[0]-1,12-abs(result)))

return output_list

If i use an input like [(2020,5,3)] The code works fine and gives an output of (2020,2) but if I want to give input like [(2020,5,20)] then its just looping for one year rather than 2 years.

Body:
You can try

ls = [(2020,5,3), (2020,5,14), (2020,6,1), (2020,7,18)]
[(i[0], i[1] - i[2], i[2]) if 12 >= i[1] - i[2] > 0 else (i[0] - 1, i[1], i[2])  for i in ls]

The list of tuples in the example is [(2020,5,3), (2020,5,14), (2020,6,1), (2020,7,18)]

So the output is

[(2020, 2, 3), (2019, 5, 14), (2020, 5, 1), (2019, 7, 18)]


问:
How can I use regex replace to surround each character in a matched group
I'm trying to define a regex replace that can convert a string in a matched group and surround each character with quotes.

For example, given the following:

```<code>#define TEST_1  "Test String"
#define TEST_2  "Another Test String"
</code>```

I'd like to do a regex replace to get:

```<code>char TEST_1[] = { 'T','e','s','t',' ','S','t','r','i','n','g' };
char TEST_2[] = { 'A','n','o','t','h','e','r',' ','T','e','s','t',' ','S','t','r','i','n','g' };
</code>```

Is there any way to do this in regex, specifically the regex in CMake?

答:
I'm not sure it's possible to manipulate an entire line as you requested with one CMake call, but here is one solution that requires a few calls.

Here, we split the initial string on the double-quotes:

```<code>#define TEST_1  "Test String"
</code>```

into two sections: #define TEST_1 and Test String. Next, we called string(REGEX REPLACE ...) on each section of the string to manipulate it appropriately. Then, we concatenated the two portions back together at the end:

```<code># Define an initial string, for testing.
set(MYSTRING "#define TEST_1  \"Test String\"")
message("${MYSTRING}")

# Split the string into the unquoted and quoted portions.
string(REPLACE "\"" ";" MYSTRING_LIST ${MYSTRING})
list(GET MYSTRING_LIST 0 MYSTRING_BEGIN)
list(GET MYSTRING_LIST 1 MYSTRING_QUOTED)

# Perform regex replace to match the '#define TEST_N  ' portion, and
# replace it with 'char TEST_N[] = { '.
string(REGEX REPLACE "^#define TEST_([0-9]+)([ \t\r\n]*)" "char TEST_\\1[] = { " STR_OUTPUT_BEGIN ${MYSTRING_BEGIN})
message("${STR_OUTPUT_BEGIN}")

# Perform regex replace on the quoted string portion, matching every
# character in the string, single-quoting and comma-separating each.
string(REGEX REPLACE "(.)" "'\\1'," STR_OUTPUT_QUOTED ${MYSTRING_QUOTED})
# Remove the trailing comma appended in the previous regex-replace.
string(REGEX REPLACE ",$" "" STR_OUTPUT_QUOTED2 ${STR_OUTPUT_QUOTED})
message("${STR_OUTPUT_QUOTED2}")

# Concatenate them back together, appending the ' };' to the end.
string(CONCAT FINAL_STRING ${STR_OUTPUT_BEGIN} ${STR_OUTPUT_QUOTED2} " };")
message("${FINAL_STRING}")
</code>```

So you can see what's going on, this prints:

```<code>#define TEST_1  "Test String"
char TEST_1[] = {
'T','e','s','t',' ','S','t','r','i','n','g'
char TEST_1[] = { 'T','e','s','t',' ','S','t','r','i','n','g' };
</code>```

It should be fairly easy to put this logic into a CMake function, and call the function in a loop, if you need to process multiple lines as indicated in your example.

Body:
I'm trying to define a regex replace that can convert a string in a matched group and surround each character with quotes.

For example, given the following:

#define TEST_1  "Test String"
#define TEST_2  "Another Test String"

I'd like to do a regex replace to get:

char TEST_1[] = { 'T','e','s','t',' ','S','t','r','i','n','g' };
char TEST_2[] = { 'A','n','o','t','h','e','r',' ','T','e','s','t',' ','S','t','r','i','n','g' };

Is there any way to do this in regex, specifically the regex in CMake?

Body:
I'm not sure it's possible to manipulate an entire line as you requested with one CMake call, but here is one solution that requires a few calls.

Here, we split the initial string on the double-quotes:

#define TEST_1  "Test String"

into two sections: #define TEST_1 and Test String. Next, we called string(REGEX REPLACE ...) on each section of the string to manipulate it appropriately. Then, we concatenated the two portions back together at the end:

# Define an initial string, for testing.
set(MYSTRING "#define TEST_1  \"Test String\"")
message("${MYSTRING}")

# Split the string into the unquoted and quoted portions.
string(REPLACE "\"" ";" MYSTRING_LIST ${MYSTRING})
list(GET MYSTRING_LIST 0 MYSTRING_BEGIN)
list(GET MYSTRING_LIST 1 MYSTRING_QUOTED)

# Perform regex replace to match the '#define TEST_N  ' portion, and
# replace it with 'char TEST_N[] = { '.
string(REGEX REPLACE "^#define TEST_([0-9]+)([ \t\r\n]*)" "char TEST_\\1[] = { " STR_OUTPUT_BEGIN ${MYSTRING_BEGIN})
message("${STR_OUTPUT_BEGIN}")

# Perform regex replace on the quoted string portion, matching every
# character in the string, single-quoting and comma-separating each.
string(REGEX REPLACE "(.)" "'\\1'," STR_OUTPUT_QUOTED ${MYSTRING_QUOTED})
# Remove the trailing comma appended in the previous regex-replace.
string(REGEX REPLACE ",$" "" STR_OUTPUT_QUOTED2 ${STR_OUTPUT_QUOTED})
message("${STR_OUTPUT_QUOTED2}")

# Concatenate them back together, appending the ' };' to the end.
string(CONCAT FINAL_STRING ${STR_OUTPUT_BEGIN} ${STR_OUTPUT_QUOTED2} " };")
message("${FINAL_STRING}")

So you can see what's going on, this prints:

#define TEST_1  "Test String"
char TEST_1[] = {
'T','e','s','t',' ','S','t','r','i','n','g'
char TEST_1[] = { 'T','e','s','t',' ','S','t','r','i','n','g' };

It should be fairly easy to put this logic into a CMake function, and call the function in a loop, if you need to process multiple lines as indicated in your example.


问:
Cython primes example - SyntaxError: invalid syntax
I am learning Cython in Linux and am working though the example on the Cython Tutorial pages:

https://cython.readthedocs.io/en/latest/src/tutorial/cython_tutorial.html#primes

I am studying the primes example.  Which has the code:

```<code>def primes(int nb_primes):
    cdef int n, i, len_p
    cdef int p[1000]
    if nb_primes > 1000:
        nb_primes = 1000

    len_p = 0  # The current number of elements in p.
    n = 2
    while len_p < nb_primes:
        # Is n prime?
        for i in p[:len_p]:
            if n % i == 0:
                break

        # If no break occurred in the loop, we have a prime.
        else:
            p[len_p] = n
            len_p += 1
        n += 1

    # Let's return the result in a python list:
    result_as_list  = [prime for prime in p[:len_p]]
    return result_as_list
</code>```

I have saved the code as primes.pyx and run the setup.py.

which looks like:

```<code>from setuptools import setup
from Cython.Build import cythonize

setup(
    ext_modules = cythonize("primes.pyx")
)
</code>```

However when I import primes using

```<code>>>> import primes
</code>```

I get the error:

```<code>Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/home/vagrant/merlin/scoleman/test_cython/primes.py", line 1
    def primes(int nb_primes):
</code>```

I have primes.c and primes.pyx files. Why do I get this error?

答:
You have missed a step to build it into pyd.

Create a setup.py :

from setuptools import setup
from Cython.Build import cythonize

setup(
    ext_modules=cythonize("primes.pyx"),
)
```

and run python setup.py build_ext --inplace in command line to build it.

These are at the top half of your document.

Body:
I am learning Cython in Linux and am working though the example on the Cython Tutorial pages:

https://cython.readthedocs.io/en/latest/src/tutorial/cython_tutorial.html#primes

I am studying the primes example.  Which has the code:

def primes(int nb_primes):
    cdef int n, i, len_p
    cdef int p[1000]
    if nb_primes > 1000:
        nb_primes = 1000

    len_p = 0  # The current number of elements in p.
    n = 2
    while len_p < nb_primes:
        # Is n prime?
        for i in p[:len_p]:
            if n % i == 0:
                break

        # If no break occurred in the loop, we have a prime.
        else:
            p[len_p] = n
            len_p += 1
        n += 1

    # Let's return the result in a python list:
    result_as_list  = [prime for prime in p[:len_p]]
    return result_as_list

I have saved the code as primes.pyx and run the setup.py.

which looks like:

from setuptools import setup
from Cython.Build import cythonize

setup(
    ext_modules = cythonize("primes.pyx")
)

However when I import primes using

>>> import primes

I get the error:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/home/vagrant/merlin/scoleman/test_cython/primes.py", line 1
    def primes(int nb_primes):

I have primes.c and primes.pyx files. Why do I get this error?

Body:
You have missed a step to build it into pyd.

Create a setup.py :

from setuptools import setup
from Cython.Build import cythonize

setup(
    ext_modules=cythonize("primes.pyx"),
)

and run python setup.py build_ext --inplace in command line to build it.

These are at the top half of your document.


问:
How to get ultra wide camera calibration data?
Is it possible to get calibration data AVCapturePhoto::cameraCalibrationData for ultra wide camera?

Documentation says:

Camera calibration data is present only if you specified the cameraCalibrationDataDeliveryEnabled and dualCameraDualPhotoDeliveryEnabled settings when requesting capture.

but dualCameraDualPhotoDeliveryEnabled was deprecated.

I tried to set cameraCalibrationDataDeliveryEnabled for builtInDualWideCamera and builtInUltraWideCamera without any success.

答:
The calibration data is meant to give you information about the intrinsics of multiple cameras in a virtual camera capture scenario. This used to be the dual camera (introduced with the iPhone X), but with the release of the iPhone 11 Pro, the API switched it's naming. It's now called isVirtualDeviceConstituentPhotoDeliveryEnabled and you can now specify the set of cameras that should be involved in the capture with virtualDeviceConstituentPhotoDeliveryEnabledDevices.

Note that the calibration data only seem to be available for virtual devices with at least two cameras involved (so builtInDualCamera, builtInDualWideCamera and builtInTripleCamera).