问:
Jenkins pipeline executing msbuild.exe (2019) build.xml - The batch file cannot be found
```<code>pipeline {
    agent { label 'Apps' }'''

   environment {
        MSBUILD_4_PATH      = "c:\\WINDOWS\\Microsoft.NET\\Framework\\v4.0.30319\\msbuild"
        MSBUILD_2019_PATH   = "c:\\Program Files (x86)\\Microsoft Visual Studio\\2019\\Enterprise\\MSBuild\\Current\\Bin\\MSBuild.exe"
        GLOBAL_SETTINGS     = "\\PATH\\TO\\msbuild_settings"
        BUILD_TYPE          = "Dev"
        // ------
    }
    stage('Build Infra - Release and Test') {
         steps {
              dir("${env.WORKSPACE}/${BRANCH_NAME}/Infra/Build"){
                 bat '''
                     set DevEnvDir="c:\\Program Files (x86)\\Microsoft Visual Studio\\2019\\Enterprise\\Common7\\IDE\\"

                        "%MSBUILD_2019_PATH%" Build.xml /p:GlobalSettings=%GLOBAL_SETTINGS%;BUILD_TYPE=%BUILD_TYPE%;SC=GIT;MSBuildCommunityTasksPath="C:\\Program Files (x86)\\MSBuild\\MSBuildCommunityTasks";ExtensionTasksPath="C:\\\\Program Files (x86)\\\\MSBuild\\\\ExtensionPack\\\\4.0\\\\" /t:ReleaseAndTest
                    '''
                }
            }
        }
</code>```

Please help, cant find root cause of the problem
Log finished with:

```<code>375 Warning(s)
0 Error(s)

Time Elapsed 00:04:54.35
The batch file cannot be found.
</code>```

Cant realize if the problem is with Jenkins pipeline or MsBuild itself
stage never finished... stack

Tried many different options and still stack

Body:
pipeline {
    agent { label 'Apps' }'''

   environment {
        MSBUILD_4_PATH      = "c:\\WINDOWS\\Microsoft.NET\\Framework\\v4.0.30319\\msbuild"
        MSBUILD_2019_PATH   = "c:\\Program Files (x86)\\Microsoft Visual Studio\\2019\\Enterprise\\MSBuild\\Current\\Bin\\MSBuild.exe"
        GLOBAL_SETTINGS     = "\\PATH\\TO\\msbuild_settings"
        BUILD_TYPE          = "Dev"
        // ------
    }
    stage('Build Infra - Release and Test') {
         steps {
              dir("${env.WORKSPACE}/${BRANCH_NAME}/Infra/Build"){
                 bat '''
                     set DevEnvDir="c:\\Program Files (x86)\\Microsoft Visual Studio\\2019\\Enterprise\\Common7\\IDE\\"

                        "%MSBUILD_2019_PATH%" Build.xml /p:GlobalSettings=%GLOBAL_SETTINGS%;BUILD_TYPE=%BUILD_TYPE%;SC=GIT;MSBuildCommunityTasksPath="C:\\Program Files (x86)\\MSBuild\\MSBuildCommunityTasks";ExtensionTasksPath="C:\\\\Program Files (x86)\\\\MSBuild\\\\ExtensionPack\\\\4.0\\\\" /t:ReleaseAndTest
                    '''
                }
            }
        }

Please help, cant find root cause of the problem
Log finished with:

375 Warning(s)
0 Error(s)

Time Elapsed 00:04:54.35
The batch file cannot be found.

Cant realize if the problem is with Jenkins pipeline or MsBuild itself
stage never finished... stack

Tried many different options and still stack


来源: stackexchange

问:
Validation errors showing before filling the model ASP.NET Core
I am still new with ASP.NET Core and I have the following problem.

I want to make a Hotel webpage and of course one of the main functionalities is Adding Reservations. And I have the following problem: I have a View Model, 2 actions in the Controller (GET and POST) for adding a reservation and a View.

VIEW MODEL:

namespace MyHotelWebsite.Web.ViewModels.Reservations
{
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;

using MyHotelWebsite.Common.CustomValidationAttributes;
using MyHotelWebsite.Data.Models;
using MyHotelWebsite.Data.Models.Enums;
using MyHotelWebsite.Services.Mapping;

public class AddReservationViewModel : IValidatableObject, IMapFrom<Reservation>
{
    [NotMapped]
    public string Email { get; set; }

    [NotMapped]
    public string PhoneNumber { get; set; }

    [Display(Name = "Check in")]
    [Required]
    [DataType(DataType.Date)]
    [AccomodationDateValidation(ErrorMessage = "Check in date must be today or later")]
    public DateTime AccommodationDate { get; set; }

    [Display(Name = "Check out")]
    [Required]
    [DataType(DataType.Date)]
    [ReleaseDateValidation(ErrorMessage = "Check out date must be tomorrow or later")]
    public DateTime ReleaseDate { get; set; }

    [Display(Name = "Adults Count")]
    [Range(1, 4)]
    public int AdultsCount { get; set; }

    [Display(Name = "Children Count")]
    [Range(0, 4)]
    public int ChildrenCount { get; set; }

    [Display(Name = "Room Type")]
    [Required]
    public RoomType RoomType { get; set; }

    [Required]
    public Catering Catering { get; set; }

    public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
    {
        List<ValidationResult> results = new List<ValidationResult>();

        if (this.ReleaseDate <= this.AccommodationDate)
        {
            results.Add(new ValidationResult("Check out date must be greater that Check In date", new[] { "ReleaseDate" }));
        }

        return results;
    }
}
}
```
<p>RESERVATIONSCONTROLLER:</p>
<pre class="lang-cs prettyprint-override"><code>using System;
using System.Threading.Tasks;

using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using MyHotelWebsite.Data.Models;
using MyHotelWebsite.Services.Data;
using MyHotelWebsite.Web.Controllers;
using MyHotelWebsite.Web.ViewModels.Administration.Rooms;
using MyHotelWebsite.Web.ViewModels.Reservations;

[Area("Guest")]
public class ReservationsController : BaseController
 {
    private readonly UserManager<ApplicationUser> userManager;
    private readonly IGuestsService guestsService;
    private readonly IRoomsService roomsService;

    public ReservationsController(UserManager<ApplicationUser> userManager, IGuestsService guestsService, IRoomsService roomsService)
    {
        this.userManager = userManager;
        this.guestsService = guestsService;
        this.roomsService = roomsService;
    }

    public async Task<IActionResult> Book()
    {
        ApplicationUser guestId = await this.userManager.GetUserAsync(this.User);
        string guestEmail = guestId.Email;
        string guestPhoneNumber = guestId.PhoneNumber;
        var model = new AddReservationViewModel()
        {
            Email = guestEmail,
            PhoneNumber = guestPhoneNumber,
            AccommodationDate = DateTime.UtcNow,
            ReleaseDate = DateTime.UtcNow.AddDays(1),
        };
        return this.View(model);
    }

    [HttpPost]
    public async Task<IActionResult> Book(AddReservationViewModel model)
    {
        if (!this.ModelState.IsValid)
        {
            return this.View(model);
        }
        var roomsByType = await     this.roomsService.GetAllRoomsByRoomTypeAsync<SingleRoomViewModel>(model.RoomType);
        return this.RedirectToAction("Index", "Home");
    }
}
</code>```

VIEW:

```<code>@using MyHotelWebsite.Data.Models.Enums
@using MyHotelWebsite.Web.ViewModels.Reservations

@model AddReservationViewModel

@{
this.ViewData["Title"] = "Book a room";
}

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="icon" href="images/icons/favicon.png" />
<title>vacayhome</title>

<!-- Bootstrap core CSS -->
<link href="~/css/bootstrap.min.css" rel="stylesheet">
<link href="~/font-awesome/css/font-awesome.min.css" rel="stylesheet" type="text/css" />
<!-- Custom styles for this template -->
<link href="~/css/style.css" rel="stylesheet">
<link href="~/fonts/antonio-exotic/stylesheet.css" rel="stylesheet">
<link rel="stylesheet" href="~/css/lightbox.min.css">
<link href="~/css/responsive.css" rel="stylesheet">

<script src="~/js/jquery.min.js" type="text/javascript"></script>
<script src="~/js/bootstrap.min.js" type="text/javascript"></script>
<script src="~/js/lightbox-plus-jquery.min.js" type="text/javascript"></script>
<script src="~/js/instafeed.min.js" type="text/javascript"></script>
<script src="~/js/custom.js" type="text/javascript"></script>
@*  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-alpha3/dist/css/bootstrap.min.css" rel="stylesheet">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.9.0/css/bootstrap-datepicker.min.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">*@

@*<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-alpha3/dist/js/bootstrap.bundle.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.9.0/js/bootstrap-datepicker.min.js"></script>*@

</head>

<body>
<form method="post" class="col-md-6 offset-md-3">
    <div class="text-center mb-3">
        <h1>@this.ViewData["Title"]</h1>
        <br />
        <h4>Dear <b>Guests</b>,</h4>
        <h4>With this form you can make a reservation for 1 room only. <i class="fa fa-smile-o" aria-hidden="true"></i> </h4>
        <h4>Number of beds (<i class="fa fa-bed" aria-hidden="true"></i>) are written next to the type of the room.</h4>
        <h4>We insist on having at least 1 adult (<i class="fa fa-male" aria-hidden="true"></i>) or (<i class="fa fa-female" aria-hidden="true"></i>) in each room with children (<i class="fa fa-child" aria-hidden="true"></i>, <i class="fa fa-child" aria-hidden="true"></i>, ...). </h4>
        <h4>If you are a group (<i class="fa fa-users" aria-hidden="true"></i>), so one room is not enough and you don't want (or don't have time <i class="fa fa-clock-o" aria-hidden="true"></i>) to make many reservations <i class="fa fa-list-alt" aria-hidden="true"></i>, do not hesitate to contact us on the phone <i class="fa fa-mobile" aria-hidden="true"></i> or via e-mail <i class="fa fa-envelope-o" aria-hidden="true"></i>.</h4>
    </div>
    <hr />
    <br />
    <div asp-validation-summary="All" class="text-danger"></div>
    <div class="text-center mb-3">
        <label asp-for="Email"></label>
        <input asp-for="Email" class="form-control" />
        <span asp-validation-for=

"Email" class="text-danger"></span>
        </div>
        <div class="text-center mb-3">
            <label asp-for="PhoneNumber"></label>
            <input asp-for="PhoneNumber" class="form-control" />
            <span asp-validation-for="PhoneNumber" class="text-danger"></span>
        </div>
        <div class="text-center mb-3">
            <label asp-for="AccommodationDate"></label>
            <input asp-for="AccommodationDate" class="date form-control" type="date" />
            <span asp-validation-for="AccommodationDate" class="text-danger"></span>
        </div>
        <div class="text-center mb-3">
            <label asp-for="ReleaseDate"></label>
            <input asp-for="ReleaseDate" class="date form-control" type="date" />
            <span asp-validation-for="ReleaseDate" class="text-danger"></span>
        </div>
        <div class="text-center mb-3">
            <label asp-for="AdultsCount"></label>
            <input asp-for="AdultsCount" type="number" class="form-control" />
            <span asp-validation-for="AdultsCount" class="text-danger"></span>
        </div>
        <div class="text-center mb-3">
            <label asp-for="ChildrenCount"></label>
            <input asp-for="ChildrenCount" type="number" class="form-control" />
            <span asp-validation-for="ChildrenCount" class="text-danger"></span>
        </div>
        <div class="text-center mb-3">
            <label asp-for="RoomType"></label>
            <select class="form-select" asp-for="RoomType" asp-items="@Html.GetEnumSelectList<RoomType>()" style="font-size:medium">
                <option>Select Room Type</option>
            </select>
        </div>
        <div class="text-center mb-3">
            <label asp-for="Catering"></label>
            <select class="form-select" asp-for="Catering" asp-items="@Html.GetEnumSelectList<Catering>()" style="font-size:medium">
                <option>Select Catering</option>
            </select>
        </div>
        <div class="text-center mb-3">
            <input type="submit" class="btn btn-danger" />
        </div>
    </form>
</body>
</html>
</code>```

I tried to write the code in many different ways, but the problem remains.
If I comment the POST method everything is fine - it loads User e-mail and Phone number, as well as Check in and Check out date correctly. But when uncomment it I receive the following with the initial loading of the model before writing anything:

The errors

Please, tell me what can be the problem and how to solve it? I am struggling with this issue for a few days. I use a ready template for the webpage if this can have something in common. The strangest thing is that I do not have this problem when creating a blog or a dish for the hotel restaurant. Thank you in advance.

ContentLicense: CC BY-SA 4.0

Body:
I am still new with ASP.NET Core and I have the following problem.

I want to make a Hotel webpage and of course one of the main functionalities is Adding Reservations. And I have the following problem: I have a View Model, 2 actions in the Controller (GET and POST) for adding a reservation and a View.

VIEW MODEL:

namespace MyHotelWebsite.Web.ViewModels.Reservations
{
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;

using MyHotelWebsite.Common.CustomValidationAttributes;
using MyHotelWebsite.Data.Models;
using MyHotelWebsite.Data.Models.Enums;
using MyHotelWebsite.Services.Mapping;

public class AddReservationViewModel : IValidatableObject, IMapFrom<Reservation>
{
    [NotMapped]
    public string Email { get; set; }

    [NotMapped]
    public string PhoneNumber { get; set; }

    [Display(Name = "Check in")]
    [Required]
    [DataType(DataType.Date)]
    [AccomodationDateValidation(ErrorMessage = "Check in date must be today or later")]
    public DateTime AccommodationDate { get; set; }

    [Display(Name = "Check out")]
    [Required]
    [DataType(DataType.Date)]
    [ReleaseDateValidation(ErrorMessage = "Check out date must be tomorrow or later")]
    public DateTime ReleaseDate { get; set; }

    [Display(Name = "Adults Count")]
    [Range(1, 4)]
    public int AdultsCount { get; set; }

    [Display(Name = "Children Count")]
    [Range(0, 4)]
    public int ChildrenCount { get; set; }

    [Display(Name = "Room Type")]
    [Required]
    public RoomType RoomType { get; set; }

    [Required]
    public Catering Catering { get; set; }

    public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
    {
        List<ValidationResult> results = new List<ValidationResult>();

        if (this.ReleaseDate <= this.AccommodationDate)
        {
            results.Add(new ValidationResult("Check out date must be greater that Check In date", new[] { "ReleaseDate" }));
        }

        return results;
    }
}
}

RESERVATIONSCONTROLLER:

using System;
using System.Threading.Tasks;

using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using MyHotelWebsite.Data.Models;
using MyHotelWebsite.Services.Data;
using MyHotelWebsite.Web.Controllers;
using MyHotelWebsite.Web.ViewModels.Administration.Rooms;
using MyHotelWebsite.Web.ViewModels.Reservations;

[Area("Guest")]
public class ReservationsController : BaseController
 {
    private readonly UserManager<ApplicationUser> userManager;
    private readonly IGuestsService guestsService;
    private readonly IRoomsService roomsService;

    public ReservationsController(UserManager<ApplicationUser> userManager, IGuestsService guestsService, IRoomsService roomsService)
    {
        this.userManager = userManager;
        this.guestsService = guestsService;
        this.roomsService = roomsService;
    }

    public async Task<IActionResult> Book()
    {
        ApplicationUser guestId = await this.userManager.GetUserAsync(this.User);
        string guestEmail = guestId.Email;
        string guestPhoneNumber = guestId.PhoneNumber;
        var model = new AddReservationViewModel()
        {
            Email = guestEmail,
            PhoneNumber = guestPhoneNumber,
            AccommodationDate = DateTime.UtcNow,
            ReleaseDate = DateTime.UtcNow.AddDays(1),
        };
        return this.View(model);
    }

    [HttpPost]
    public async Task<IActionResult> Book(AddReservationViewModel model)
    {
        if (!this.ModelState.IsValid)
        {
            return this.View(model);
        }
        var roomsByType = await     this.roomsService.GetAllRoomsByRoomTypeAsync<SingleRoomViewModel>(model.RoomType);
        return this.RedirectToAction("Index", "Home");
    }
}

VIEW:

@using MyHotelWebsite.Data.Models.Enums
@using MyHotelWebsite.Web.ViewModels.Reservations

@model AddReservationViewModel

@{
this.ViewData["Title"] = "Book a room";
}

<!DOCTYPE html>

<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="icon" href="images/icons/favicon.png" />
<title>vacayhome</title>

<link href="~/css/bootstrap.min.css" rel="stylesheet">
<link href="~/font-awesome/css/font-awesome.min.css" rel="stylesheet" type="text/css" />

<link href="~/css/style.css" rel="stylesheet">
<link href="~/fonts/antonio-exotic/stylesheet.css" rel="stylesheet">
<link rel="stylesheet" href="~/css/lightbox.min.css">
<link href="~/css/responsive.css" rel="stylesheet">

@*  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-alpha3/dist/css/bootstrap.min.css" rel="stylesheet">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.9.0/css/bootstrap-datepicker.min.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">*@

@*

*@

<form method="post" class="col-md-6 offset-md-3">

@this.ViewData["Title"]

Dear Guests,

With this form you can make a reservation for 1 room only.

Number of beds () are written next to the type of the room.

We insist on having at least 1 adult () or () in each room with children (, , ...).

If you are a group (), so one room is not enough and you don't want (or don't have time ) to make many reservations , do not hesitate to contact us on the phone  or via e-mail .

        <input asp-for="Email" class="form-control" />

            <input asp-for="PhoneNumber" class="form-control" />

            <input asp-for="AccommodationDate" class="date form-control" type="date" />

            <input asp-for="ReleaseDate" class="date form-control" type="date" />

            <input asp-for="AdultsCount" type="number" class="form-control" />

            <input asp-for="ChildrenCount" type="number" class="form-control" />

            <select class="form-select" asp-for="RoomType" asp-items="@Html.GetEnumSelectList<RoomType>()" style="font-size:medium">
                <option>Select Room Type</option>
            </select>

            <select class="form-select" asp-for="Catering" asp-items="@Html.GetEnumSelectList<Catering>()" style="font-size:medium">
                <option>Select Catering</option>
            </select>

            <input type="submit" class="btn btn-danger" />

    </form>

I tried to write the code in many different ways, but the problem remains.
If I comment the POST method everything is fine - it loads User e-mail and Phone number, as well as Check in and Check out date correctly. But when uncomment it I receive the following with the initial loading of the model before writing anything:

The errors

Please, tell me what can be the problem and how to solve it? I am struggling with this issue for a few days. I use a ready template for the webpage if this can have something in common. The strangest thing is that I do not have this problem when creating a blog or a dish for the hotel restaurant. Thank you in advance.


问:
Method for recoding all user-defined missing values from SPSS to NA during import in R?
I am using the haven package to import a large SPSS dataset into R. The dataset contains many variables with unique user-defined missing values--sometimes several for a single variable.

The date/time variables share 8888-08-08 and 9999-09-09 as user-defined missing values (signifying "Not Applicable" and "Unknown", respectively). Another set of variables related to ICD-10 codes contains 77777, 88888, and 99999 as missing values, indicating "Injured but Unknown Code", "Not Applicable", and "Unknown". Yet another set of variables contains the codes 66, 77, 88, and 99 (for "Not Applicable", "Refused to Answer", "Variable Did Not Exist at Time of Collection", and "Unknown")... etc.

My question is whether there is an argument in haven (or another data loading package in R) that will automatically convert these various user-defined missing values to NA during the import process of the original SPSS file.

I have tried the following without success:

```<code>df <- read_sav("/path/to/file.sav", user_na = FALSE)
</code>```

Body:
I am using the haven package to import a large SPSS dataset into R. The dataset contains many variables with unique user-defined missing values--sometimes several for a single variable.

The date/time variables share 8888-08-08 and 9999-09-09 as user-defined missing values (signifying "Not Applicable" and "Unknown", respectively). Another set of variables related to ICD-10 codes contains 77777, 88888, and 99999 as missing values, indicating "Injured but Unknown Code", "Not Applicable", and "Unknown". Yet another set of variables contains the codes 66, 77, 88, and 99 (for "Not Applicable", "Refused to Answer", "Variable Did Not Exist at Time of Collection", and "Unknown")... etc.

My question is whether there is an argument in haven (or another data loading package in R) that will automatically convert these various user-defined missing values to NA during the import process of the original SPSS file.

I have tried the following without success:

df <- read_sav("/path/to/file.sav", user_na = FALSE)


问:
Resnet for Text data
Hi I want to use ResNet for Text data. I tried to look some code example lot of other data at the end I wrote the following code. But I'm not sure it's the correct way for ResNet or not.

NOTE::: this part is optional if i recieve an opinion on it. it will be great but I'm going to try it once the above one is corrected. if it is correct way then I want it to implement it in this way ----> ResNet should contain 18 layers in total whereas these layers should be divided into four stages and each stage should consist of two convolutional blocks. Each convolutional block should contain two convolutional layers with batch normalization and ReLU non_linearity in-between. Then, ResNet should pass the output from the convolutional layers to two fully-connected layers that will use the reduced data to classify the initial data to a given website class. Last but not least, you should use Adam optimizer and categorical cross-entropy (typically used for multi-class classification problems). Make sure that you identify and use the optimal hyper-parameters for your ResNet.

```<code>import pandas as pd
import os
import numpy as np
from sklearn import metrics
from scipy.stats import zscore
from sklearn.model_selection import KFold
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense, Activation

class ResNet_class():

    def __init__(self):
        # Cross-Validate
        self.no_of_folds = int(input('enter no of K_fold: '))
        self.kf = KFold(self.no_of_folds, shuffle=True, random_state=42)  # Use for KFold classification
        self.EPOCHS = int(input('enter no of epochs: '))

    def check_test(self):
        df = pd.read_csv(
            "https://data.heatonresearch.com/data/t81-558/jh-simple-dataset.csv",
            na_values=['NA','?'])
        df = pd.concat([df,pd.get_dummies(df['job'],prefix="job")],axis=1)
        df.drop('job', axis=1, inplace=True)
        df = pd.concat([df,pd.get_dummies(df['area'],prefix="area")],axis=1)
        df.drop('area', axis=1, inplace=True)
        df = pd.concat([df,pd.get_dummies(df['product'],prefix="product")],axis=1)
        df.drop('product', axis=1, inplace=True)
        med = df['income'].median()
        df['income'] = df['income'].fillna(med)
        df['income'] = zscore(df['income'])
        df['aspect'] = zscore(df['aspect'])
        df['save_rate'] = zscore(df['save_rate'])
        df['subscriptions'] = zscore(df['subscriptions'])
        x_columns = df.columns.drop('age').drop('id')
        x = df[x_columns].values
        y = df['age'].values
        oos_y = []
        oos_pred = []
        fold = 0
        for train, test in self.kf.split(x):
            fold += 1
            print(f"Fold #{fold}")
            x_train = x[train]
            y_train = y[train]
            x_test = x[test]
            y_test = y[test]
            model = Sequential()
            model.add(Dense(20, input_dim=x.shape[1], activation='relu'))
            model.add(Dense(10, activation='relu'))
            model.add(Dense(1))
            model.compile(loss='mean_squared_error', optimizer='adam')
            model.fit(x_train, y_train, validation_data=(x_test, y_test), verbose=0,
                      epochs=self.EPOCHS)
            pred = model.predict(x_test)
            oos_y.append(y_test)
            oos_pred.append(pred)
            score = np.sqrt(metrics.mean_squared_error(pred, y_test))
            print(f"Fold score (RMSE): {score}")
        oos_y = np.concatenate(oos_y)
        oos_pred = np.concatenate(oos_pred)
        score = np.sqrt(metrics.mean_squared_error(oos_pred, oos_y))
        print(f"Final, out of sample score (RMSE): {score}")
        oos_y = pd.DataFrame(oos_y)
        oos_pred = pd.DataFrame(oos_pred)
        oosDF = pd.concat([df, oos_y, oos_pred], axis=1)
resnet = ResNet_class()
resnet.check_test()
</code>```

Title: Resnet for Text data

Body:
Hi I want to use ResNet for Text data. I tried to look some code example lot of other data at the end I wrote the following code. But I'm not sure it's the correct way for ResNet or not.

NOTE::: this part is optional if i recieve an opinion on it. it will be great but I'm going to try it once the above one is corrected. if it is correct way then I want it to implement it in this way ----> ResNet should contain 18 layers in total whereas these layers should be divided into four stages and each stage should consist of two convolutional blocks. Each convolutional block should contain two convolutional layers with batch normalization and ReLU non_linearity in-between. Then, ResNet should pass the output from the convolutional layers to two fully-connected layers that will use the reduced data to classify the initial data to a given website class. Last but not least, you should use Adam optimizer and categorical cross-entropy (typically used for multi-class classification problems). Make sure that you identify and use the optimal hyper-parameters for your ResNet.

import pandas as pd
import os
import numpy as np
from sklearn import metrics
from scipy.stats import zscore
from sklearn.model_selection import KFold
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense, Activation

class ResNet_class():

    def __init__(self):
        # Cross-Validate
        self.no_of_folds = int(input('enter no of K_fold: '))
        self.kf = KFold(self.no_of_folds, shuffle=True, random_state=42)  # Use for KFold classification
        self.EPOCHS = int(input('enter no of epochs: '))

    def check_test(self):
        df = pd.read_csv(
            "https://data.heatonresearch.com/data/t81-558/jh-simple-dataset.csv",
            na_values=['NA','?'])
        df = pd.concat([df,pd.get_dummies(df['job'],prefix="job")],axis=1)
        df.drop('job', axis=1, inplace=True)
        df = pd.concat([df,pd.get_dummies(df['area'],prefix="area")],axis=1)
        df.drop('area', axis=1, inplace=True)
        df = pd.concat([df,pd.get_dummies(df['product'],prefix="product")],axis=1)
        df.drop('product', axis=1, inplace=True)
        med = df['income'].median()
        df['income'] = df['income'].fillna(med)
        df['income'] = zscore(df['income'])
        df['aspect'] = zscore(df['aspect'])
        df['save_rate'] = zscore(df['save_rate'])
        df['subscriptions'] = zscore(df['subscriptions'])
        x_columns = df.columns.drop('age').drop('id')
        x = df[x_columns].values
        y = df['age'].values
        oos_y = []
        oos_pred = []
        fold = 0
        for train, test in self.kf.split(x):
            fold += 1
            print(f"Fold #{fold}")
            x_train = x[train]
            y_train = y[train]
            x_test = x[test]
            y_test = y[test]
            model = Sequential()
            model.add(Dense(20, input_dim=x.shape[1], activation='relu'))
            model.add(Dense(10, activation='relu'))
            model.add(Dense(1))
            model.compile(loss='mean_squared_error', optimizer='adam')
            model.fit(x_train, y_train, validation_data=(x_test, y_test), verbose=0,
                      epochs=self.EPOCHS)
            pred = model.predict(x_test)
            oos_y.append(y_test)
            oos_pred.append(pred)
            score = np.sqrt(metrics.mean_squared_error(pred, y_test))
            print(f"Fold score (RMSE): {score}")
        oos_y = np.concatenate(oos_y)
        oos_pred = np.concatenate(oos_pred)
        score = np.sqrt(metrics.mean_squared_error(oos_pred, oos_y))
        print(f"Final, out of sample score (RMSE): {score}")
        oos_y = pd.DataFrame(oos_y)
        oos_pred = pd.DataFrame(oos_pred)
        oosDF = pd.concat([df, oos_y, oos_pred], axis=1)
resnet = ResNet_class()
resnet.check_test()


问:
Question about grid and data type conversion
I am making a 12* 12 grid with numbers leading the columns and rows, leftover place placed by '.'.

```<code>void creatGrid(){
    char theGrid[SizeX][SizeY];
    for(int b = 0; b<SizeY;b++){
            theGrid[0][b] = b + 0;
            for(int i =0;i<SizeX;i++){
                if(b==0){
                    char t = i+0;
                    theGrid[i][b] = t;
                }else if(i==0){
                    char e = b+0;
                    theGrid[i][b] = e;
                }else{
                    theGrid[i][b] = '.';
                }
            }
        }
    for(int i = 0;i<SizeY;i++){
        for(int a =0; a<SizeX;a++){
            printf("%c ",theGrid[a][i]);
        }
        printf("\n");
    }
}
</code>```

I am using a char-type two-dimensional array to create the grid, I convert the int to char by adding 0 behind them, but it is not working as the output is gibberish at the position of int.

Body:
I am making a 12* 12 grid with numbers leading the columns and rows, leftover place placed by '.'.

void creatGrid(){
    char theGrid[SizeX][SizeY];
    for(int b = 0; b<SizeY;b++){
            theGrid[0][b] = b + 0;
            for(int i =0;i<SizeX;i++){
                if(b==0){
                    char t = i+0;
                    theGrid[i][b] = t;
                }else if(i==0){
                    char e = b+0;
                    theGrid[i][b] = e;
                }else{
                    theGrid[i][b] = '.';
                }
            }
        }
    for(int i = 0;i<SizeY;i++){
        for(int a =0; a<SizeX;a++){
            printf("%c ",theGrid[a][i]);
        }
        printf("\n");
    }
}

I am using a char-type two-dimensional array to create the grid, I convert the int to char by adding 0 behind them, but it is not working as the output is gibberish at the position of int.


问:
Why do I need to use conditional rendering on when fetching single data and not on array of data?
EDIT: I got that! it is because the state of both of them different, the once with the array has an initial state of array, so obviously nothing wrong there! got it! no need to answer

In the attached image, I use twice useEffect in order to bring data from a server.

One fucntion (white draw), bring array of prodcuts from the server and the second function bring a single product.

When I tried to display the one products React show me an error, and I check about it,and understood I have to use conditional rendring first, why?

Cause in the first time the component render, their is still no product so it display Error, So, First I have to "check" if there is one and then give it an order to display it, I got that, that makes sense, but, why all the mentioned above dont apply to the time Im trying to bring array of products (red draw)?

 Also here, in the first render, there are still no products and I should get an Error!


问:
Arrange break lines html text code in Visual Studio Code
I wan't to arrange breaklines in vscode, I wan't all lines to be the same size more or less.

I always use extensions for formatting the code like prettier, but they make it worse as they insert break lines to long lines. But they don't fix shorter lines, ending up with a lot of small lines. Something like this:


问:
PostgreSQL simple SELECT query didn't work with WHERE (newbie)
I try to start work with Pgadmin4, and when i use query like this:

```<code>select *
from users
</code>```

I get normal results like this:
enter image description here

and when i use query like this:

```<code>select *
from users
where login='admin'
</code>```

i get nothing:
enter image description here

i've tried to use 'like' and no changes
i've tried to use 'admin' w\o quotes and no changes
what's my problem here?

Body:
I try to start work with Pgadmin4, and when i use query like this:

select *
from users

I get normal results like this:
enter image description here

and when i use query like this:

select *
from users
where login='admin'

i get nothing:
enter image description here

i've tried to use 'like' and no changes
i've tried to use 'admin' w\o quotes and no changes
what's my problem here?


问:
Call a callback during animation
Is there an event emitted on every frame, or every time an SVG object object moves according to the <animate> or <animateMotion> element? If so, how's it's called?

I have a moving circle and I'd like to display the current coordinate of the circle in <tspan>. My intuition is that there must be an event emitted on every frame, or every time the position of a circle changes. But I'm failing to find an event I should subscribe to.

Maybe this can be done somehow via SMIL itself?

Otherwise, is this typically done via calling an requestAnimationFrame function? If yes, how'd I use requestAnimationFrame to update the value of a <tspan>?

<svg width=400 height=200 style="margin-left: 15px">
  <text x=10 y=30 style="font-family: Courier New; font-size: 8pt">(35, 50)</text>
  <text x=90 y=30 style="font-family: Courier New; font-size: 8pt">(115, 50)</text>
  <path id="mPath" d="M115,40 L35,40" stroke-width="1" stroke-dasharray="3" stroke="red"></path>
  <circle r="4">
    <animateMotion
      repeatCount="indefinite"
      rotate="auto"
      dur="3s"
      fill="freeze"
    >
      <mpath xlink:href="#mPath" />
    </animateMotion>
  </circle>
  <circle cx="115" cy="40" r="2" fill=blue></circle>
  <circle cx="35" cy="40" r="2" fill=red></circle>
  <text x=0 y=70 style="font-family: Courier New; font-size: 8pt">Current (x, y): <tspan style="font-weight: bold" id="curPos">(115, 50)</tspan></text>
</svg>```

Title: Call a callback during animation


问:
javascript array for function var document.getelementsbyclassname ("classname" + 1)
So essentially i have this javascript code:

```<code>var coll = document.getElementsByClassName("btn1");
          var i;

          for (let i = 0; i < coll.length; i++) {
            coll[i].addEventListener("click", function() {
              this.classList.toggle("active");
              var content = this.nextElementSibling;
              if (content.style.display === "block") {
                content.style.display = "none";
              } else {
                content.style.display = "block";
              }
            });
          }

          var coll = document.getElementsByClassName("btn2");
          var i;

          for (i = 0; i < coll.length; i++) {
            coll[i].addEventListener("click", function() {
              this.classList.toggle("active");
              var content = this.nextElementSibling;
              if (content.style.display === "block") {
                content.style.display = "none";
              } else {
                content.style.display = "block";
              }
            });
          }

          var coll = document.getElementsByClassName("btn3");
          var i;

          for (i = 0; i < coll.length; i++) {
            coll[i].addEventListener("click", function() {
              this.classList.toggle("active");
              var content = this.nextElementSibling;
              if (content.style.display === "block") {
                content.style.display = "none";
              } else {
                content.style.display = "block";
              }
            });
          }
}
</code>```

And I want to be able to make an array that links the classes of "btn", essentially a way of condensing the code into a smaller segment and utilizing array to list the buttons. The buttons link to this HTML:

```<code><button class="btn1">

<img src="dylan.png" alt="Dylan Conaway" style="width:100px"><br><br>Dylan Conaway

</button>

<button class="btn2">

<img src="shania.jpeg" alt="Shania Ammons" style="width:100px"><br><br>Shania Ammons

</button>

<button class="btn3">

<img src="shelia.png" alt="Shelia Eddy" style="width:100px"/><br><br>Shelia Eddy

</button>

</code>```

Anyone know if this is possible?

Thanks in advance for any help!!

Body:
So essentially i have this javascript code:

var coll = document.getElementsByClassName("btn1");
          var i;

          for (let i = 0; i < coll.length; i++) {
            coll[i].addEventListener("click", function() {
              this.classList.toggle("active");
              var content = this.nextElementSibling;
              if (content.style.display === "block") {
                content.style.display = "none";
              } else {
                content.style.display = "block";
              }
            });
          }

          var coll = document.getElementsByClassName("btn2");
          var i;

          for (i = 0; i < coll.length; i++) {
            coll[i].addEventListener("click", function() {
              this.classList.toggle("active");
              var content = this.nextElementSibling;
              if (content.style.display === "block") {
                content.style.display = "none";
              } else {
                content.style.display = "block";
              }
            });
          }

          var coll = document.getElementsByClassName("btn3");
          var i;

          for (i = 0; i < coll.length; i++) {
            coll[i].addEventListener("click", function() {
              this.classList.toggle("active");
              var content = this.nextElementSibling;
              if (content.style.display === "block") {
                content.style.display = "none";
              } else {
                content.style.display = "block";
              }
            });
          }
}

And I want to be able to make an array that links the classes of "btn", essentially a way of condensing the code into a smaller segment and utilizing array to list the buttons. The buttons link to this HTML:

<button class="btn1">

Dylan Conaway

</button>

<button class="btn2">

Shania Ammons

</button>

<button class="btn3">

Shelia Eddy

</button>

Anyone know if this is possible?

Thanks in advance for any help!!


问:
r.requestBody/r.requestText/r.requestBuffer is undefined (NJS - JavaScript Modules on NGINX)
I'm building a NGINX module with JavaScript, that read incoming requests and design whether to pass them to the proxy server, or to ignore them and return a "block.html" page as a response [kinda WAF].

The problem is when I try to access r.requestBody/r.requestText/r.requestBuffer (all three ways should give me the whole request), the variable was undefined.

Here are the JavaScript file (that for now has only "reading incoming messages" ability) and NGINX's configuration file:

waf.js

function main(r)
{
    return "Request: " + r.requestText;
}

export default { main };
```
<p><strong>/etc/nginx/conf.d/default.conf</strong></p>
```js_path "/etc/nginx/njs";
js_import waf.js;

js_set $return_value_of_main_func_in_waf waf.main;
log_format ret_val $return_value_of_main_func_in_waf;

server {
    listen       80;
    server_name  localhost;

    access_log  /var/log/nginx/njs_output.log ret_val;

    location / {
        js_content waf.main;
    }

    location /block.html {
        root   /usr/share/nginx/html;
    }

    location @app-backend {
        proxy_pass http://127.0.0.1:7777;
    }

    #error_page  404              /404.html;

    # redirect server error pages to the static page /50x.html
    #
    error_page   500 502 503 504  /50x.html;
    location = /50x.html {
        root   /usr/share/nginx/html;
    }
}
```
<p><strong>njs_output.log</strong></p>
```Request: undefined
Request: undefined
Request: undefined
Request: undefined
```
<p>I tried to access other things in the <code>r</code> variable, like <code>r.rawHeadersIn</code>, and the output was fine:</p>
```Host,localhost,Connection,keep-alive,Cache-Control,max-age=0,sec-ch-ua,\x22Not?A_Brand\x22;v=\x228\x22, \x22Chromium\x22;v=\x22108\x22, \x22Google Chrome\x22;v=\x22108\x22,sec-ch-ua-mobile,?0,sec-ch-ua-platform,\x22Windows\x22,Upgrade-Insecure-Requests,1,User-Agent,Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/108.0.0.0 Safari/537.36,Accept,text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9,Sec-Fetch-Site,none,Sec-Fetch-Mode,navigate,Sec-Fetch-User,?1,Sec-Fetch-Dest,document,Accept-Encoding,gzip, deflate, br,Accept-Language,he-IL,he;q=0.9,en-US;q=0.8,en;q=0.7,Cookie,security_level=0; security=low; PHPSESSID=ruioabebdprspfihjst4vu66he; session=9603a1c6-1fe4-4f93-be1a-68ad6a5738ed.vsLXilN0X5P1XWLCWBveUL1PkW8
```

Body:
I'm building a NGINX module with JavaScript, that read incoming requests and design whether to pass them to the proxy server, or to ignore them and return a "block.html" page as a response [kinda WAF].

The problem is when I try to access r.requestBody/r.requestText/r.requestBuffer (all three ways should give me the whole request), the variable was undefined.

Here are the JavaScript file (that for now has only "reading incoming messages" ability) and NGINX's configuration file:

waf.js

function main(r)
{
    return "Request: " + r.requestText;
}

export default { main };

/etc/nginx/conf.d/default.conf

js_path "/etc/nginx/njs";
js_import waf.js;

js_set $return_value_of_main_func_in_waf waf.main;
log_format ret_val $return_value_of_main_func_in_waf;

server {
    listen       80;
    server_name  localhost;

    access_log  /var/log/nginx/njs_output.log ret_val;

    location / {
        js_content waf.main;
    }

    location /block.html {
        root   /usr/share/nginx/html;
    }

    location @app-backend {
        proxy_pass http://127.0.0.1:7777;
    }

    #error_page  404              /404.html;

    # redirect server error pages to the static page /50x.html
    #
    error_page   500 502 503 504  /50x.html;
    location = /50x.html {
        root   /usr/share/nginx/html;
    }
}

njs_output.log

Request: undefined
Request: undefined
Request: undefined
Request: undefined

I tried to access other things in the r variable, like r.rawHeadersIn, and the output was fine:

Host,localhost,Connection,keep-alive,Cache-Control,max-age=0,sec-ch-ua,\x22Not?A_Brand\x22;v=\x228\x22, \x22Chromium\x22;v=\x22108\x22, \x22Google Chrome\x22;v=\x22108\x22,sec-ch-ua-mobile,?0,sec-ch-ua-platform,\x22Windows\x22,Upgrade-Insecure-Requests,1,User-Agent,Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/108.0.0.0 Safari/537.36,Accept,text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9,Sec-Fetch-Site,none,Sec-Fetch-Mode,navigate,Sec-Fetch-User,?1,Sec-Fetch-Dest,document,Accept-Encoding,gzip, deflate, br,Accept-Language,he-IL,he;q=0.9,en-US;q=0.8,en;q=0.7,Cookie,security_level=0; security=low; PHPSESSID=ruioabebdprspfihjst4vu66he; session=9603a1c6-1fe4-4f93-be1a-68ad6a5738ed.vsLXilN0X5P1XWLCWBveUL1PkW8


问:
MPI Spawn method gives not enough slots error
I am trying to run a script (in parallel execution) within another python script (which is MPI singleton) using following command:

MPI.COMM_WORLD.Spawn(sys.executable, args=["hello.py"], maxprocs=10)

It gives following error:

There are not enough slots available in the system to satisfy the 10
slots that were requested by the application.

I know that my laptop has 10 processors (Processor). When I run the script as mpirun -n 10 python hello.py, it creates 10 processes. But, when I use spawn method, it gives above error only when the maxprocs argument exceeds 5. Below 5, it works fine. I also tried to use MPI.COMM_SELF.Spawn() method, but it shows same behavior.

I am not sure what is causing this error. I am suspecting that the number of performance cores in my processor is 6 which might be limiting the maxprocs to 5, but I am not sure. Any help on this will be appreciated!

System Specs:

Ubuntu: 22.04

OpenMPI: 4.0.7

mpi4py: 3.1.3


问:
Python syntax GFOO or MPOO (Generic Function or Message Passing Object Oriented)?
I am an R user who is increasing my knowledge of Python, and I wondered if Python is best understood as using Message Passing Object Oriented (MPOO) syntax, or like R, Generic Functional Object Oriented (GFOO) syntax?

I encouraged the MPOO and GFOO concepts in Hadley Wickham's 2010 Mutable Objects in R. The red font is my text.

The first question might be how to change the first lines of text in an opened file, in one line like the above, in Python. Examples I have found use multiple lines, such as what constructs the function found in this SO answer.

```<code>def replace_line(file_name, line_num, text):
    lines = open(file_name, 'r').readlines()
    lines[line_num] = text
    out = open(file_name, 'w')
    out.writelines(lines)
    out. Close()

replace_line('stats.txt', 0, 'Mage')
</code>```

Body:
I am an R user who is increasing my knowledge of Python, and I wondered if Python is best understood as using Message Passing Object Oriented (MPOO) syntax, or like R, Generic Functional Object Oriented (GFOO) syntax?

I encouraged the MPOO and GFOO concepts in Hadley Wickham's 2010 Mutable Objects in R. The red font is my text.

The first question might be how to change the first lines of text in an opened file, in one line like the above, in Python. Examples I have found use multiple lines, such as what constructs the function found in this SO answer.

def replace_line(file_name, line_num, text):
    lines = open(file_name, 'r').readlines()
    lines[line_num] = text
    out = open(file_name, 'w')
    out.writelines(lines)
    out. Close()

replace_line('stats.txt', 0, 'Mage')


问:
Add neww tool to Yocto build environment
I'm wondering it is possibile to add new tool to Yocto env. My recipe calls mkimage tool provided by U-Boot but this tool need to call bison which is not available on Yocto env (error message says: /bin/sh: bison: not going,). How to add this tool?
Thanks.</p>


问:
Is there a way to keep a single url, domain, or ip, for communication between docker containters, and between localhost and containers?
I am working on a web app where a single environmental variable is used for specifying a certain server (a rest api), like this:

.env:

```<code>...
URL_SERVER_API="http://localhost:8080"
...
</code>```

the application is running inside a container, and it uses the server api variable for two things related to my problem:

It could generate and serve dynamic html where it append URL_SERVER_API to complete full api urls, for example {{URL_SERVER_API}}/someendpoint

It calls the api directly from a (php) script using CURL, defining the endpoint in the same fashion as 1

so I end up with a situation where if I set URL_SERVER_API to localhost:8080 the main application forms valid urls to call because the api app (which is also running in a docker container) was exposed in the correspondingly port, but the CURL calls don't work because localhost:8080 is not a known server inside the container.

Also I configured a bridge network and attached both apps to it, and I was capable to ping from the main app to the api succesfuly (e.g. ping api_docker), then when I set URL_SERVER_API=api_docker the CURL calls to the api are successfull, but the html files returned from the main app are constructed with unreachable urls like http://api_docker/someendpoint

Hope you can see my issue

I am able to solve the issue by having two variables URL_SERVER_API and URL_SERVER_API_INTERNAL and using the first for html serving and the second for the CURL calls, but I think it is not the best solution to add new variables to remember because I am not in charge to do so.
Thanks for the time taken to read

Body:
I am working on a web app where a single environmental variable is used for specifying a certain server (a rest api), like this:

.env:

...
URL_SERVER_API="http://localhost:8080"
...

the application is running inside a container, and it uses the server api variable for two things related to my problem:

It could generate and serve dynamic html where it append URL_SERVER_API to complete full api urls, for example {{URL_SERVER_API}}/someendpoint

It calls the api directly from a (php) script using CURL, defining the endpoint in the same fashion as 1

so I end up with a situation where if I set URL_SERVER_API to localhost:8080 the main application forms valid urls to call because the api app (which is also running in a docker container) was exposed in the correspondingly port, but the CURL calls don't work because localhost:8080 is not a known server inside the container.

Also I configured a bridge network and attached both apps to it, and I was capable to ping from the main app to the api succesfuly (e.g. ping api_docker), then when I set URL_SERVER_API=api_docker the CURL calls to the api are successfull, but the html files returned from the main app are constructed with unreachable urls like http://api_docker/someendpoint

Hope you can see my issue

I am able to solve the issue by having two variables URL_SERVER_API and URL_SERVER_API_INTERNAL and using the first for html serving and the second for the CURL calls, but I think it is not the best solution to add new variables to remember because I am not in charge to do so.
Thanks for the time taken to read


问:
Numerical Analysiz find are of a circle with use midpoint
[the question i couldnt find the solution (https://i.stack.imgur.com/vr6IN.png)</p>
```<code>I don't know how to solve the question by finding the middle point
</code>```

Body:
[the question i couldnt find the solution (https://i.stack.imgur.com/vr6IN.png)

I don't know how to solve the question by finding the middle point


问:
socketIO - override setInterval for movement on player entitity
Im building an online multiplayer game where you can click on tiles to move to them. The tiles have an x and z position.

I dont know how to reset the clearInterval if a player clicks another tile in socket.io. Right now it doubles the speed because it duplicates the setInterval I guess and if I try to clearInterval at the beginning it seems not to target the old setInterval. I tried to bind the setInterval to the player[socket.id] object but got a Maximum call stack size exceeded error then.

How do I clear this specific setInterval for the player so it hasnt 2 setIntervals when I click a second tile while moving?

index.js (server)

```<code>
players[socket.id] = {
    x: 0,
    z: 0,
    xTo:0,
    zTo:0,
    isMoving: false,
    playerId: socket.id,
    name: name,
    room: 'lobby'
};

//when client clicks on a tile
socket.on('moveRequest', function(pos) {
  //set clicked tile x/z to player entity
  players[socket.id].xTo = pos[0];
  players[socket.id].zTo = pos[2];
  //only continiue if clicked tile is different from current tile
  if (players[socket.id].x !== players[socket.id].xTo) {
    //get direction left/right
    var xDiff = players[socket.id].xTo - players[socket.id].x;
    var xDirection = 'none';
    if (xDiff > 0) {
      console.log('player wants to move right');
      xDirection = 'right';
    } else {
      console.log('player wants to move left');
      xDirection = 'left';
    }
    //if there is wanted movement
    if (xDirection !== 'none') {
      //setInterval 60fps
      const moveInterval = setInterval(function() {
        //if direction is right and players current position is smaller then clicked position
        if (xDirection == 'right' && players[socket.id].x < players[socket.id].xTo) {
          //move player
          players[socket.id].x = players[socket.id].x + 0.03;
        } else {
          //if reached destination clear the interval
          xDirection = 'none';
          clearInterval(moveInterval);
        }
        //now send move to all players in room
        io.to('game').emit('playerMove', players[socket.id]);
      }, 1000 / 60);
    }
  }
});
</code>```

Body:
Im building an online multiplayer game where you can click on tiles to move to them. The tiles have an x and z position.

I dont know how to reset the clearInterval if a player clicks another tile in socket.io. Right now it doubles the speed because it duplicates the setInterval I guess and if I try to clearInterval at the beginning it seems not to target the old setInterval. I tried to bind the setInterval to the player[socket.id] object but got a Maximum call stack size exceeded error then.

How do I clear this specific setInterval for the player so it hasnt 2 setIntervals when I click a second tile while moving?

index.js (server)

players[socket.id] = {
    x: 0,
    z: 0,
    xTo:0,
    zTo:0,
    isMoving: false,
    playerId: socket.id,
    name: name,
    room: 'lobby'
};

//when client clicks on a tile
socket.on('moveRequest', function(pos) {
  //set clicked tile x/z to player entity
  players[socket.id].xTo = pos[0];
  players[socket.id].zTo = pos[2];
  //only continiue if clicked tile is different from current tile
  if (players[socket.id].x !== players[socket.id].xTo) {
    //get direction left/right
    var xDiff = players[socket.id].xTo - players[socket.id].x;
    var xDirection = 'none';
    if (xDiff > 0) {
      console.log('player wants to move right');
      xDirection = 'right';
    } else {
      console.log('player wants to move left');
      xDirection = 'left';
    }
    //if there is wanted movement
    if (xDirection !== 'none') {
      //setInterval 60fps
      const moveInterval = setInterval(function() {
        //if direction is right and players current position is smaller then clicked position
        if (xDirection == 'right' && players[socket.id].x < players[socket.id].xTo) {
          //move player
          players[socket.id].x = players[socket.id].x + 0.03;
        } else {
          //if reached destination clear the interval
          xDirection = 'none';
          clearInterval(moveInterval);
        }
        //now send move to all players in room
        io.to('game').emit('playerMove', players[socket.id]);
      }, 1000 / 60);
    }
  }
});


问:
Discord Server WHitelist
I'm trying to make it where, if the server id isn't whitelisted then the bot will leave the server immediately after joining, but if the owner of the bot whitelists the servers id then it will stay in the server. But the whitelist would be through a slash command. /whitelist (guildid)

I didnt try anything, I don't know where to start from

Title: Discord Server WHitelist


问:
How can i read and write an array of structures to a binary file in C
I have a static array of structs and through a void new_cinema() function i want to get an info about a film and so on and write this info to the file and then using another function i want to read this info through the file. I've tried to do this:

```<code>FILE* file;
fpos_t current_position = 0;

struct cinema
{
    char name[256];
    char session[256];
    double price;
    int audience;
};

struct cinema october[25];
int counter = 0;
int cntr[N] = { 0 };

void new_cinema()
{

    if (counter < N)
    {
        if (counter == 0)
        {
            fopen_s(&file, "file.bin", "wb");
            if (file == NULL)
            {
                printf("An error occured1\n");
                fclose(file);
                return;
            }
        }
        if (counter != 0)
        {
            fopen_s(&file, "file.bin", "ab");
            if (file == NULL)
            {
                printf("An error occured2\n");
                fclose(file);
                return;
            }
        }
        fsetpos(file, &current_position);
        printf("\nWrite the name of the movie:\n");
        gets_s(october[counter].name, 255);
        printf("\nEnter the session time:\n");
        scanf_s("%s", october[counter].session, 255);
        printf("\nEnter ticket price:\n");
        scanf_s("%lf", &october[counter].price);
        printf("\nEnter the number of viewers:\n");
        scanf_s("%d", &october[counter].audience);
        fwrite(&october[counter], sizeof(struct cinema), 1, file);
        fgetpos(file, &current_position);
        counter++;
    }

    else
        printf("\nThe limit has gone!\n");
    fclose(file);
}
</code>```

In this part of the code i create a struct cinema and then an array october of the struct cinema type. In the new_cinema() function if counter is zero, which means the user didn't actually create anything before i fopen_s(&file, "file.bin", "wb"); and set the the position to zero fsetpos(file, &current_position);,  after that i get some info and write it to the file  fwrite(&october[counter], sizeof(struct cinema), 1, file); and then i get the current position and increment the counter.

I think that i'm doing all this wrong, firsty i'm not sure abot the
fwrite(&october[counter], sizeof(struct cinema), 1, file);, i don't know about the & because it is the array. Do i need & in here? Secondly, the fgetpos() and fsetpos() when i get the current position and when the user enters new_cinema() again and fsetpos sets the position of indicator of stream i guess that after completeing receiving information about the movie and writing this info to the file, the last character of the previous structure can be rewritten to reflect the new information. Is it ?

And after doing all this, I try to read this information from the file, i wrote this code, but it is incorrect:

```<code>void read_struct()
{
    fopen_s(&file, "file.bin", "rb");
    if (file == NULL)
    {
        printf("couldn't read the file\n");
        return;
    }
    struct cinema *testing;
    testing = (struct cinema*)malloc(sizeof(struct cinema) * 25);
    int i = 0;
    while(!feof(file))
    {
        fread(&testing[i], sizeof(struct cinema), 1, file);
        ++i;
    }
    for (i = 0; i < 25; i++)
    {
        printf("%s\n", testing[i].name);
        printf("%s\n", testing[i].session);
        printf("%lf", testing[i].price);
        printf("%d\n", testing[i].audience);
    }
}
</code>```

Assistance is really appreciated!

Body:
I have a static array of structs and through a void new_cinema() function i want to get an info about a film and so on and write this info to the file and then using another function i want to read this info through the file. I've tried to do this:

FILE* file;
fpos_t current_position = 0;

struct cinema
{
    char name[256];
    char session[256];
    double price;
    int audience;
};

struct cinema october[25];
int counter = 0;
int cntr[N] = { 0 };

void new_cinema()
{

    if (counter < N)
    {
        if (counter == 0)
        {
            fopen_s(&file, "file.bin", "wb");
            if (file == NULL)
            {
                printf("An error occured1\n");
                fclose(file);
                return;
            }
        }
        if (counter != 0)
        {
            fopen_s(&file, "file.bin", "ab");
            if (file == NULL)
            {
                printf("An error occured2\n");
                fclose(file);
                return;
            }
        }
        fsetpos(file, &current_position);
        printf("\nWrite the name of the movie:\n");
        gets_s(october[counter].name, 255);
        printf("\nEnter the session time:\n");
        scanf_s("%s", october[counter].session, 255);
        printf("\nEnter ticket price:\n");
        scanf_s("%lf", &october[counter].price);
        printf("\nEnter the number of viewers:\n");
        scanf_s("%d", &october[counter].audience);
        fwrite(&october[counter], sizeof(struct cinema), 1, file);
        fgetpos(file, &current_position);
        counter++;
    }

    else
        printf("\nThe limit has gone!\n");
    fclose(file);
}

In this part of the code i create a struct cinema and then an array october of the struct cinema type. In the new_cinema() function if counter is zero, which means the user didn't actually create anything before i fopen_s(&file, "file.bin", "wb"); and set the the position to zero fsetpos(file, &current_position);,  after that i get some info and write it to the file  fwrite(&october[counter], sizeof(struct cinema), 1, file); and then i get the current position and increment the counter.

I think that i'm doing all this wrong, firsty i'm not sure abot the
fwrite(&october[counter], sizeof(struct cinema), 1, file);, i don't know about the & because it is the array. Do i need & in here? Secondly, the fgetpos() and fsetpos() when i get the current position and when the user enters new_cinema() again and fsetpos sets the position of indicator of stream i guess that after completeing receiving information about the movie and writing this info to the file, the last character of the previous structure can be rewritten to reflect the new information. Is it ?

And after doing all this, I try to read this information from the file, i wrote this code, but it is incorrect:

void read_struct()
{
    fopen_s(&file, "file.bin", "rb");
    if (file == NULL)
    {
        printf("couldn't read the file\n");
        return;
    }
    struct cinema *testing;
    testing = (struct cinema*)malloc(sizeof(struct cinema) * 25);
    int i = 0;
    while(!feof(file))
    {
        fread(&testing[i], sizeof(struct cinema), 1, file);
        ++i;
    }
    for (i = 0; i < 25; i++)
    {
        printf("%s\n", testing[i].name);
        printf("%s\n", testing[i].session);
        printf("%lf", testing[i].price);
        printf("%d\n", testing[i].audience);
    }
}

Assistance is really appreciated!


问:
Python tool to get an outline map of counties/states given the bounding coordinates?
I am looking for a python tool that gives me the county and/or state boundaries in an image format if I provide the 4 corners in lat/lon coordinates. I plan to overlay some satellite images on these.

I briefly dabbled with geopandas and I could get a map of North America, but having something more zoomed in would be better.

Thanks.


问:
Flutter animate letters typed in TextFormField?
I'm adding letters to a TextFormField from code with this function in the initState hook:

```<code>Future.delayed(
  const Duration(seconds: 1),
  (() async {
    for (var i = 0; i < sampleEmail.length; i++) {
      await Future.delayed(const Duration(milliseconds: 100));
      setState(() {
        _textEditingController.text += sampleEmail[i];
      });
    }
  }),
);
</code>```

I was wondering if there is a way to animate how the letters appear in the field, instead of the normal way for example they "drop" from a litte above, or they enter from one side.
If you can just give me some direction it would be great.
Do i need to make a custom TextFormField inheriting from it? Or use an animation controller?

Body:
I'm adding letters to a TextFormField from code with this function in the initState hook:

Future.delayed(
  const Duration(seconds: 1),
  (() async {
    for (var i = 0; i < sampleEmail.length; i++) {
      await Future.delayed(const Duration(milliseconds: 100));
      setState(() {
        _textEditingController.text += sampleEmail[i];
      });
    }
  }),
);

I was wondering if there is a way to animate how the letters appear in the field, instead of the normal way for example they "drop" from a litte above, or they enter from one side.
If you can just give me some direction it would be great.
Do i need to make a custom TextFormField inheriting from it? Or use an animation controller?


问:
How do you embed variables in Gitbook content?
I'm migrating documentation to Gitbook, but I'm unable to get the variables feature to render variable content in my pages.

The variables docs page indicates that variables are set in /book.json and that they are accessible through book.[CONFIGURATION_DATA]

The templatting docs page indicates this is done through a {{ varname }} construction.

However in my published Gitbook docs, I'm just getting literal {{ varname }} content in my output. This happens even when I update via the linked Git repo to ensure there is no escaping of the variable constructions.

I'm happy to use other approaches, e.g. liquid-style constructs with .yaml configs, but I'm unable to find any docs on other options either. As long as I can update those setting centrally, it will work for me.


问:
OpenMP on fortran 90 lasts almost the same(if not more) as non parallelized program
I'm trying to parallelize a simulation of an Ising 2D model to get some expected values as a function of the temperature of the system. For L=48, the one-threaded version takes about 240 seconds to run 20 temperatures and 1 seed each, but the parallelized version takes about 268 seconds, which is similar.

If you take the time per seed per temperature, it results in 12 seconds for the one-threaded version and 13.4 seconds for the parallelized version. I'm looking for help with my code because I don't understand these durations. I thought that the parallelized version would split one temperature among all threads and therefore should take about 30 seconds to complete.

I need to run the simulation for 50 temperatures and 200 seeds each, for 5 values of L. It would be helpful to reduce the compute time, because otherwise it could take 20 hours for L=48 and some days for L=72.

I'm using an i7-10700KF (8 cores, 16 logical threads).

```<code>program Ising
    use omp_lib
    implicit none
    integer L, seed, i, j, seed0, nseed,k
    parameter (L=48)
    integer s(1:L, 1:L)
    integer*4 pbc(0:L+1), mctot, N, mcd, mcini, difE
    real*8 genrand_real2, magne, energ, energia, temp, temp1, DE
    real*8 mag, w(-8:8)
    real*8 start, finish
    real*8 sum, sume, sume2, summ, summ2, sumam, vare, varm, maxcv, maxx
    real*8 cv, x, Tmaxcv, Tmaxx
    integer irand, jrand

11  format(10(f20.6))

! Initialize variables

    mctot = 80000
    mcd = 20
    mcini = 8000
    N = L*L
    seed0 = 20347880
    nseed = 20
    maxcv=0.d0
    maxx=0.d0

! Initialize vector pbc

    pbc(0) = L
    pbc(L+1) = 1
    do i = 1, L
        pbc(i) = i
    end do

! Initialize matrix s with random values

    do i = 1, L
        do j = 1, L
            if (genrand_real2() < 0.5) then
                s(i,j) = 1
            else
                s(i,j) = -1
            endif
        end do
    end do

! Metropolis algorithm

    open(1, file='Expectation values.dat')
    start = omp_get_wtime()
    write(1,*) '#Temp,       ','E,       ','E2,       ','M,       ','M2,       ','|M|,       ','VarE,       ','VarM,       ',&
    'Cv,       ','X,       '

!Start loop to calculate for different temperatures
!$OMP PARALLEL PRIVATE(s,seed,w,energia,difE,irand,jrand,temp,mag,sum,sume,sume2,summ,summ2,sumam,vare,varm,cv,x)
        temp1 = 1.59d0
!$OMP DO ordered schedule(dynamic)
    do k = 1, 10
        temp = temp1 + (0.01d0*k)
!Define the matrix w, which contains the values of the Boltzmann function for each temperature, so as not to have to calculate them each iteration

        do i = -8, 8
            w(i) = dexp(-i/temp)
        end do
        write(*,*) "Temperature: ", temp, "Thread", omp_get_thread_num()
        sum = 0.d0
        sume = 0.d0
        sume2 = 0.d0
        summ = 0.d0
        summ2 = 0.d0
        sumam = 0.d0

        do seed = seed0, seed0 + nseed-1, 1
            call init_genrand(seed)
            call reinicia(s,l)
            energia = energ(s,l,pbc)

            do i = 1, mctot
                do j = 1, N
                    irand = int(genrand_real2()*L) + 1
                    jrand = int(genrand_real2()*L) + 1
                    difE = int(DE(s,l,irand,jrand,pbc))
                    if (difE < 0) then
                        s(irand,jrand) = -s(irand,jrand)
                        energia = energia + difE
                    else if (genrand_real2() < w(int(difE))) then
                        s(irand,jrand) = -s(irand,jrand)
                        energia = energia + difE
                    endif
                end do

                if ((i > mcini).and.(mcd*(i/mcd)==i)) then
                    mag= magne(s,l)
                    sum = sum + 1.d0
                    sume = sume + energia
                    sume2 = sume2 + energia**2
                    summ = summ + mag
                    summ2 = summ2 + mag**2
                    sumam = sumam + abs(mag)
                endif
            end do
        end  do

!Energy
        sume=sume/(sum*N)
        sume2=sume2/(sum*N*N)
!Magnetitzation
        summ = summ/(sum*N)
        sumam=sumam/(sum*N)
        summ2=summ2/(sum*N*N)
!Variances
        vare = dsqrt(sume2-sume*sume)/dsqrt(sum)
        varm = dsqrt(summ2-summ*summ)/dsqrt(sum)
!Cv
        cv = (N*(sume2-sume*sume))/temp**2
        if (cv.gt.maxcv) then
            maxcv=cv
            Tmaxcv=temp
        endif
!X
        x = (N*(summ2-summ*summ))/temp
        if (x.gt.maxx) then
            maxx=x
            Tmaxx=temp
        endif

        write(1,11) temp,sume,sume2,summ,summ2,sumam,vare,varm,cv,x
    end do
!$OMP END DO
!$OMP END PARALLEL

    finish = omp_get_wtime()
    close(1)

    print*, "Time: ",(finish-start),"Seconds"

end program Ising

! Functions

!Function that calculates the energy of the matrix s

real*8 function energ(S,L, pbc)
    implicit none
    integer s(1:L, 1:L), i, j, L
    integer*4 pbc(0:L+1)
    real*8 ene
    ene = 0.0d0
    do i = 1, L
        do j = 1, L
            ene = ene - s(i,j) * s(pbc(i+1),j) - s(i,j) * s(i,pbc(j+1))
        end do
    end do
    energ = ene
    return
end function energ

!Function that calculates the difference in energy that occurs when the spin of position (i, j) is changed

real*8 function DE(S,L,i,j,pbc)
    implicit none
    integer s(1:L, 1:L), i, j, L, difE
    integer*4 pbc(0:L+1)
    real*8 suma
    difE = 0
    suma = 0.0d0
        suma = suma + s(pbc(i-1),j) + s(pbc(i+1),j) + s(i,pbc(j-1)) + s(i,pbc(j+1))
        difE = difE + int(2 * s(i,j) * suma)
    DE = difE
    return
end function DE

!Function that calculates the magnetization of the matrix s

real*8 function magne(S,L)
    implicit none
    integer s(1:L, 1:L),L
    magne = sum(s)
    return
end function magne

! SUBRUTINES

!Subroutine that resets the matrix s with random values
subroutine reinicia(S,L)
    implicit none
    integer s(1:L, 1:L), i,j,L
    real*8 genrand_real2
    do i = 1, L
        do j = 1, L
            if (genrand_real2() < 0.5) then
                s(i,j) = 1
            else
                s(i,j) = -1
            endif
        end do
    end do
    return
end subroutine
</code>```

I have tried parallelizing the seeds loop instead of the temperatures, but it lasts almost the same, so i think i'm not parallelizing it correctly, because it looks a nice code to parallelize.

The other option I thought of is to manually parallelize the simulation. I could do this by compiling 16 programs, each of which handles a different range of temperatures. Then I could run all of the programs concurrently, so each program would get its own thread. However, this approach would require a lot of extra RAM.

Body:
I'm trying to parallelize a simulation of an Ising 2D model to get some expected values as a function of the temperature of the system. For L=48, the one-threaded version takes about 240 seconds to run 20 temperatures and 1 seed each, but the parallelized version takes about 268 seconds, which is similar.

If you take the time per seed per temperature, it results in 12 seconds for the one-threaded version and 13.4 seconds for the parallelized version. I'm looking for help with my code because I don't understand these durations. I thought that the parallelized version would split one temperature among all threads and therefore should take about 30 seconds to complete.

I need to run the simulation for 50 temperatures and 200 seeds each, for 5 values of L. It would be helpful to reduce the compute time, because otherwise it could take 20 hours for L=48 and some days for L=72.

I'm using an i7-10700KF (8 cores, 16 logical threads).

program Ising
    use omp_lib
    implicit none
    integer L, seed, i, j, seed0, nseed,k
    parameter (L=48)
    integer s(1:L, 1:L)
    integer*4 pbc(0:L+1), mctot, N, mcd, mcini, difE
    real*8 genrand_real2, magne, energ, energia, temp, temp1, DE
    real*8 mag, w(-8:8)
    real*8 start, finish
    real*8 sum, sume, sume2, summ, summ2, sumam, vare, varm, maxcv, maxx
    real*8 cv, x, Tmaxcv, Tmaxx
    integer irand, jrand

11  format(10(f20.6))

! Initialize variables

    mctot = 80000
    mcd = 20
    mcini = 8000
    N = L*L
    seed0 = 20347880
    nseed = 20
    maxcv=0.d0
    maxx=0.d0

! Initialize vector pbc

    pbc(0) = L
    pbc(L+1) = 1
    do i = 1, L
        pbc(i) = i
    end do

! Initialize matrix s with random values

    do i = 1, L
        do j = 1, L
            if (genrand_real2() < 0.5) then
                s(i,j) = 1
            else
                s(i,j) = -1
            endif
        end do
    end do

! Metropolis algorithm

    open(1, file='Expectation values.dat')
    start = omp_get_wtime()
    write(1,*) '#Temp,       ','E,       ','E2,       ','M,       ','M2,       ','|M|,       ','VarE,       ','VarM,       ',&
    'Cv,       ','X,       '

!Start loop to calculate for different temperatures
!$OMP PARALLEL PRIVATE(s,seed,w,energia,difE,irand,jrand,temp,mag,sum,sume,sume2,summ,summ2,sumam,vare,varm,cv,x)
        temp1 = 1.59d0
!$OMP DO ordered schedule(dynamic)
    do k = 1, 10
        temp = temp1 + (0.01d0*k)
!Define the matrix w, which contains the values of the Boltzmann function for each temperature, so as not to have to calculate them each iteration

        do i = -8, 8
            w(i) = dexp(-i/temp)
        end do
        write(*,*) "Temperature: ", temp, "Thread", omp_get_thread_num()
        sum = 0.d0
        sume = 0.d0
        sume2 = 0.d0
        summ = 0.d0
        summ2 = 0.d0
        sumam = 0.d0

        do seed = seed0, seed0 + nseed-1, 1
            call init_genrand(seed)
            call reinicia(s,l)
            energia = energ(s,l,pbc)

            do i = 1, mctot
                do j = 1, N
                    irand = int(genrand_real2()*L) + 1
                    jrand = int(genrand_real2()*L) + 1
                    difE = int(DE(s,l,irand,jrand,pbc))
                    if (difE < 0) then
                        s(irand,jrand) = -s(irand,jrand)
                        energia = energia + difE
                    else if (genrand_real2() < w(int(difE))) then
                        s(irand,jrand) = -s(irand,jrand)
                        energia = energia + difE
                    endif
                end do

                if ((i > mcini).and.(mcd*(i/mcd)==i)) then
                    mag= magne(s,l)
                    sum = sum + 1.d0
                    sume = sume + energia
                    sume2 = sume2 + energia**2
                    summ = summ + mag
                    summ2 = summ2 + mag**2
                    sumam = sumam + abs(mag)
                endif
            end do
        end  do

!Energy
        sume=sume/(sum*N)
        sume2=sume2/(sum*N*N)
!Magnetitzation
        summ = summ/(sum*N)
        sumam=sumam/(sum*N)
        summ2=summ2/(sum*N*N)
!Variances
        vare = dsqrt(sume2-sume*sume)/dsqrt(sum)
        varm = dsqrt(summ2-summ*summ)/dsqrt(sum)
!Cv
        cv = (N*(sume2-sume*sume))/temp**2
        if (cv.gt.maxcv) then
            maxcv=cv
            Tmaxcv=temp
        endif
!X
        x = (N*(summ2-summ*summ))/temp
        if (x.gt.maxx) then
            maxx=x
            Tmaxx=temp
        endif

        write(1,11) temp,sume,sume2,summ,summ2,sumam,vare,varm,cv,x
    end do
!$OMP END DO
!$OMP END PARALLEL

    finish = omp_get_wtime()
    close(1)

    print*, "Time: ",(finish-start),"Seconds"

end program Ising

! Functions

!Function that calculates the energy of the matrix s

real*8 function energ(S,L, pbc)
    implicit none
    integer s(1:L, 1:L), i, j, L
    integer*4 pbc(0:L+1)
    real*8 ene
    ene = 0.0d0
    do i = 1, L
        do j = 1, L
            ene = ene - s(i,j) * s(pbc(i+1),j) - s(i,j) * s(i,pbc(j+1))
        end do
    end do
    energ = ene
    return
end function energ

!Function that calculates the difference in energy that occurs when the spin of position (i, j) is changed

real*8 function DE(S,L,i,j,pbc)
    implicit none
    integer s(1:L, 1:L), i, j, L, difE
    integer*4 pbc(0:L+1)
    real*8 suma
    difE = 0
    suma = 0.0d0
        suma = suma + s(pbc(i-1),j) + s(pbc(i+1),j) + s(i,pbc(j-1)) + s(i,pbc(j+1))
        difE = difE + int(2 * s(i,j) * suma)
    DE = difE
    return
end function DE

!Function that calculates the magnetization of the matrix s

real*8 function magne(S,L)
    implicit none
    integer s(1:L, 1:L),L
    magne = sum(s)
    return
end function magne

! SUBRUTINES

!Subroutine that resets the matrix s with random values
subroutine reinicia(S,L)
    implicit none
    integer s(1:L, 1:L), i,j,L
    real*8 genrand_real2
    do i = 1, L
        do j = 1, L
            if (genrand_real2() < 0.5) then
                s(i,j) = 1
            else
                s(i,j) = -1
            endif
        end do
    end do
    return
end subroutine

I have tried parallelizing the seeds loop instead of the temperatures, but it lasts almost the same, so i think i'm not parallelizing it correctly, because it looks a nice code to parallelize.

The other option I thought of is to manually parallelize the simulation. I could do this by compiling 16 programs, each of which handles a different range of temperatures. Then I could run all of the programs concurrently, so each program would get its own thread. However, this approach would require a lot of extra RAM.


问:
Nginx URL rewrite exlude static php file
I recently moved from apache to nginx my url rewrites were working fine on apache but on nginx I am facing a problem i.e. my single download url is not working and treated as slug as other url rewrites I want to exlucde that download.php URL from rewriting.

Current structure of URLs

```<code>https://example.com/en
https://example.com/en/contact
https://example.com/downloads.php
</code>```

Old .htaccess code

```<code>RewriteEngine on

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([^/]+)$ index.php?lang=$1 [L]

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([^/]+)/([^/]+)$ index.php?lang=$1&page=$2 [L]
</code>```

New Nginx URL rewrite code which is making trouble

```<code>location / {
    rewrite ^/([^/]+)$ /index.php?lang=$1 last;
    rewrite ^/([^/]+)/([^/]+)$ /index.php?lang=$1&page=$2 last;
}
</code>```

everything works fine on nginx except https://example.com/downloads.php

Body:
I recently moved from apache to nginx my url rewrites were working fine on apache but on nginx I am facing a problem i.e. my single download url is not working and treated as slug as other url rewrites I want to exlucde that download.php URL from rewriting.

Current structure of URLs

https://example.com/en
https://example.com/en/contact
https://example.com/downloads.php

Old .htaccess code

RewriteEngine on

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([^/]+)$ index.php?lang=$1 [L]

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([^/]+)/([^/]+)$ index.php?lang=$1&page=$2 [L]

New Nginx URL rewrite code which is making trouble

location / {
    rewrite ^/([^/]+)$ /index.php?lang=$1 last;
    rewrite ^/([^/]+)/([^/]+)$ /index.php?lang=$1&page=$2 last;
}

everything works fine on nginx except https://example.com/downloads.php


问:
How to find a specific View?
I want to know how to declare and get ID in View.

I tried using both ref and nativeID, but I can't read them on android.

How can I get View's ID in Android?

Please let me know if there is a way to specify a View even if it is not an ID.

What I'm trying to do with this is like event delegation in JS.

```<code>...
<Pressable
     ...
     onPress={(e) => ...I want to get the Views' ID}
    >
      <View
       ...
        nativeID={"view2"}
        pointerEvents={"box-only"}
      ></View>
      <View
        style={styles.container3}
        nativeID={"view3"}
        pointerEvents={"box-only"}
      ></View>
</Pressable>
...
</code>```

please help me..

Title: How to find a specific View?

Body:
I want to know how to declare and get ID in View.

I tried using both ref and nativeID, but I can't read them on android.

How can I get View's ID in Android?

Please let me know if there is a way to specify a View even if it is not an ID.

What I'm trying to do with this is like event delegation in JS.

...
<Pressable
     ...
     onPress={(e) => ...I want to get the Views' ID}
    >
      <View
       ...
        nativeID={"view2"}
        pointerEvents={"box-only"}
      ></View>
      <View
        style={styles.container3}
        nativeID={"view3"}
        pointerEvents={"box-only"}
      ></View>
</Pressable>
...

please help me..


问:
android studio How to display a camera capture image on another screen/activity
I am making a truth or dare app and let players before they start the game take a photo of the group they're playing it with. It's a simple take picture functionality and imageview above displaying the taken image by the user's camera.

I would like this picture to be displayed on another screen/activity. I was looking for ways to save the file locally so I could retrieve it in different activities but this didn't work. I'm not sure how to proceed with this as I've been looking all day for approaches to get it to work. Help is appreciated.

CameraActivity.KT

```<code>package com.example.test

import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.os.Environment
import android.provider.MediaStore
import android.widget.Button
import android.widget.ImageView
import androidx.activity.result.contract.ActivityResultContracts
import androidx.appcompat.app.AppCompatActivity
import androidx.core.content.FileProvider
import kotlinx.android.synthetic.main.activity_camera.*
import java.io.File

class CameraActivity : AppCompatActivity() {

    lateinit var imgView: ImageView
    lateinit var btnChange: Button
    lateinit var imageUri: Uri
    private val contract = registerForActivityResult(ActivityResultContracts.TakePicture()){
        /*imgView.setImageURI(null)*/
        imgView.setImageURI(imageUri)
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_camera)

        val actionBar = supportActionBar

        actionBar!!.title = "Take a picture of your group!"

        actionBar.setDisplayHomeAsUpEnabled(true)

        imgView = findViewById(R.id.imageViewId)
        btnChange = findViewById(R.id.captureBtn)
        imageUri = createImageUri()!!
        captureBtn.setOnClickListener {
            contract.launch(imageUri)

        }

            val PlayTruthOrDareGame = findViewById<Button>(R.id.playTruthOrDareGameBtn);
            PlayTruthOrDareGame.setOnClickListener {
                val intent = Intent(this, TruthOrDareActivity::class.java)
                startActivity(intent)
            }
    }

    private fun createImageUri():Uri?{
        val image= File(applicationContext.filesDir, "camera_photo.png")

        return FileProvider.getUriForFile(applicationContext,
            "com.example.test.fileProvider",
            image)
    }

}
</code>```

/layout/activity_camera.xml

It's able to convert android:src="@drawable/ic_baseline_image_24" to the image taken and I don't quite understand that. But trying this on DareActivity.xml doesn't work

```<code>
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".CameraActivity"
    android:orientation="horizontal">

    <ImageView
        android:id="@+id/imageViewId"
        android:layout_width="400dp"
        android:layout_height="300dp"
        android:src="@drawable/ic_baseline_image_24"
        tools:ignore="MissingConstraints"
        tools:layout_editor_absoluteX="5dp"
        tools:layout_editor_absoluteY="66dp" />

    <com.google.android.material.button.MaterialButton
        android:id="@+id/captureBtn"
        style="@style/Widget.MaterialComponents.Button.OutlinedButton"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Take picture"
        app:layout_constraintTop_toBottomOf="@+id/imageViewId"
        tools:ignore="MissingConstraints" />

    <Button
        android:id="@+id/playTruthOrDareGameBtn"
        android:layout_width="410dp"
        android:layout_height="wrap_content"
        android:text="Play Game"
        android:textSize="16dp"
        android:textStyle="bold"
        app:layout_constraintTop_toBottomOf="@+id/captureBtn"
        tools:ignore="MissingConstraints" />

    <TextView
        android:id="@+id/errorMessage"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Error: Take a picture first!"
        android:textSize="16dp"
        android:textStyle="bold"
        android:paddingTop="70dp"
        android:layout_marginLeft="110dp"
        android:visibility="invisible"
        tools:ignore="MissingConstraints" />

</androidx.constraintlayout.widget.ConstraintLayout>
</code>```

Manifest.xml

```<code><uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

<provider android:name="androidx.core.content.FileProvider"
            android:authorities="com.example.test.fileProvider"
            android:exported="false"
            android:grantUriPermissions="true">
            <meta-data android:name="android.support.FILE_PROVIDER_PATHS"
                android:resource="@xml/file_paths"/>

        </provider>
</code>```

/xml/file_paths

```<code><?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
<files-path
    name="camera_photos"
    path="." />
</paths>
</code>```

I would like to display the image here and continiously throughout the players returning on this page

activity_daregame.xml

```<code><ImageView
        android:id="@+id/imageViewId"
        android:layout_width="400dp"
        android:layout_height="300dp"
        android:src="@drawable/ic_baseline_image_24"
        tools:ignore="MissingConstraints"
        tools:layout_editor_absoluteX="5dp"
        tools:layout_editor_absoluteY="66dp" />
</code>```

DareActivity.KT

```<code>package com.example.test

import android.content.Context
import android.content.Intent
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.os.VibrationEffect
import android.os.Vibrator
import android.view.View
import android.widget.ImageView
import androidx.activity.result.contract.ActivityResultContracts
import androidx.appcompat.app.AppCompatActivity
import androidx.core.content.FileProvider
import kotlinx.android.synthetic.main.activity_camera.*
import kotlinx.android.synthetic.main.activity_daregame.*
import java.io.File

class DareActivity : AppCompatActivity() {

    private var currentPosition:Int=1
    private var questionList:ArrayList<DareQuestionData> ? = null

    override fun onCreate(savedInstanceState: Bundle?) {

        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_daregame)

        val actionBar = supportActionBar

        actionBar!!.title = "You chose Dare!"

        actionBar.setDisplayHomeAsUpEnabled(true)

        questionList=DareData.getDareQuestion()
        setQuestion()

        acceptDare.setOnClickListener {
            resultAcceptView.setVisibility(View.VISIBLE);
            nextDare.setVisibility(View.VISIBLE)
            acceptDare.setClickable(false)
            rejectDare.setClickable(false)
            val v = getSystemService(VIBRATOR_SERVICE) as Vibrator
            // Vibrate for 500 milliseconds
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                v.vibrate(VibrationEffect.createOneShot(500, VibrationEffect.DEFAULT_AMPLITUDE))
            } else {
                //deprecated in API 26
                v.vibrate(500)
            }
        }

        rejectDare.setOnClickListener {
            resultRejectView.setVisibility(View.VISIBLE);
            nextDare.setVisibility(View.VISIBLE)
            acceptDare.setClickable(false)
            rejectDare.setClickable(false)
        }

        nextDare.setOnClickListener {
                val intent = Intent(this, TruthOrDareActivity::class.java)
                startActivity(intent)
        }
    }

    fun setQuestion(){

        val question = questionList!![currentPosition-1]
        question_text.text=question.dareQuestion
    }
}
</code>```

Body:
I am making a truth or dare app and let players before they start the game take a photo of the group they're playing it with. It's a simple take picture functionality and imageview above displaying the taken image by the user's camera.

I would like this picture to be displayed on another screen/activity. I was looking for ways to save the file locally so I could retrieve it in different activities but this didn't work. I'm not sure how to proceed with this as I've been looking all day for approaches to get it to work. Help is appreciated.

CameraActivity.KT

package com.example.test

import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.os.Environment
import android.provider.MediaStore
import android.widget.Button
import android.widget.ImageView
import androidx.activity.result.contract.ActivityResultContracts
import androidx.appcompat.app.AppCompatActivity
import androidx.core.content.FileProvider
import kotlinx.android.synthetic.main.activity_camera.*
import java.io.File

class CameraActivity : AppCompatActivity() {

    lateinit var imgView: ImageView
    lateinit var btnChange: Button
    lateinit var imageUri: Uri
    private val contract = registerForActivityResult(ActivityResultContracts.TakePicture()){
        /*imgView.setImageURI(null)*/
        imgView.setImageURI(imageUri)
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_camera)

        val actionBar = supportActionBar

        actionBar!!.title = "Take a picture of your group!"

        actionBar.setDisplayHomeAsUpEnabled(true)

        imgView = findViewById(R.id.imageViewId)
        btnChange = findViewById(R.id.captureBtn)
        imageUri = createImageUri()!!
        captureBtn.setOnClickListener {
            contract.launch(imageUri)

        }

            val PlayTruthOrDareGame = findViewById<Button>(R.id.playTruthOrDareGameBtn);
            PlayTruthOrDareGame.setOnClickListener {
                val intent = Intent(this, TruthOrDareActivity::class.java)
                startActivity(intent)
            }
    }

    private fun createImageUri():Uri?{
        val image= File(applicationContext.filesDir, "camera_photo.png")

        return FileProvider.getUriForFile(applicationContext,
            "com.example.test.fileProvider",
            image)
    }

}

/layout/activity_camera.xml

It's able to convert android:src="@drawable/ic_baseline_image_24" to the image taken and I don't quite understand that. But trying this on DareActivity.xml doesn't work

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".CameraActivity"
    android:orientation="horizontal">

    <ImageView
        android:id="@+id/imageViewId"
        android:layout_width="400dp"
        android:layout_height="300dp"
        android:src="@drawable/ic_baseline_image_24"
        tools:ignore="MissingConstraints"
        tools:layout_editor_absoluteX="5dp"
        tools:layout_editor_absoluteY="66dp" />

    <com.google.android.material.button.MaterialButton
        android:id="@+id/captureBtn"
        style="@style/Widget.MaterialComponents.Button.OutlinedButton"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Take picture"
        app:layout_constraintTop_toBottomOf="@+id/imageViewId"
        tools:ignore="MissingConstraints" />

    <Button
        android:id="@+id/playTruthOrDareGameBtn"
        android:layout_width="410dp"
        android:layout_height="wrap_content"
        android:text="Play Game"
        android:textSize="16dp"
        android:textStyle="bold"
        app:layout_constraintTop_toBottomOf="@+id/captureBtn"
        tools:ignore="MissingConstraints" />

    <TextView
        android:id="@+id/errorMessage"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Error: Take a picture first!"
        android:textSize="16dp"
        android:textStyle="bold"
        android:paddingTop="70dp"
        android:layout_marginLeft="110dp"
        android:visibility="invisible"
        tools:ignore="MissingConstraints" />

</androidx.constraintlayout.widget.ConstraintLayout>

Manifest.xml

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

<provider android:name="androidx.core.content.FileProvider"
            android:authorities="com.example.test.fileProvider"
            android:exported="false"
            android:grantUriPermissions="true">
            <meta-data android:name="android.support.FILE_PROVIDER_PATHS"
                android:resource="@xml/file_paths"/>

        </provider>

/xml/file_paths

<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
<files-path
    name="camera_photos"
    path="." />
</paths>

I would like to display the image here and continiously throughout the players returning on this page

activity_daregame.xml

<ImageView
        android:id="@+id/imageViewId"
        android:layout_width="400dp"
        android:layout_height="300dp"
        android:src="@drawable/ic_baseline_image_24"
        tools:ignore="MissingConstraints"
        tools:layout_editor_absoluteX="5dp"
        tools:layout_editor_absoluteY="66dp" />

DareActivity.KT

package com.example.test

import android.content.Context
import android.content.Intent
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.os.VibrationEffect
import android.os.Vibrator
import android.view.View
import android.widget.ImageView
import androidx.activity.result.contract.ActivityResultContracts
import androidx.appcompat.app.AppCompatActivity
import androidx.core.content.FileProvider
import kotlinx.android.synthetic.main.activity_camera.*
import kotlinx.android.synthetic.main.activity_daregame.*
import java.io.File

class DareActivity : AppCompatActivity() {

    private var currentPosition:Int=1
    private var questionList:ArrayList<DareQuestionData> ? = null

    override fun onCreate(savedInstanceState: Bundle?) {

        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_daregame)

        val actionBar = supportActionBar

        actionBar!!.title = "You chose Dare!"

        actionBar.setDisplayHomeAsUpEnabled(true)

        questionList=DareData.getDareQuestion()
        setQuestion()

        acceptDare.setOnClickListener {
            resultAcceptView.setVisibility(View.VISIBLE);
            nextDare.setVisibility(View.VISIBLE)
            acceptDare.setClickable(false)
            rejectDare.setClickable(false)
            val v = getSystemService(VIBRATOR_SERVICE) as Vibrator
            // Vibrate for 500 milliseconds
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                v.vibrate(VibrationEffect.createOneShot(500, VibrationEffect.DEFAULT_AMPLITUDE))
            } else {
                //deprecated in API 26
                v.vibrate(500)
            }
        }

        rejectDare.setOnClickListener {
            resultRejectView.setVisibility(View.VISIBLE);
            nextDare.setVisibility(View.VISIBLE)
            acceptDare.setClickable(false)
            rejectDare.setClickable(false)
        }

        nextDare.setOnClickListener {
                val intent = Intent(this, TruthOrDareActivity::class.java)
                startActivity(intent)
        }
    }

    fun setQuestion(){

        val question = questionList!![currentPosition-1]
        question_text.text=question.dareQuestion
    }
}