问:
Integration with Keycloak, isAuthenticated is always false and cookies may not have sent, localhost (ASP.NET Core MVC)
I have decided to create a simple project to test Keycloak integration to ASP.Net Core 6 MVC, so I used the following setup.

The last time I posted with ASP.NET MVC 4, I did not get any answers and luck so I decided to create a unit test with a simple project in ASP.NET Core 6 MVC and see if i can make it work, but unfortunately, same problem. I am already stuck for two weeks on this.

Please help.

```<code>      services.AddAuthentication(options =>
        {
            //Sets cookie authentication scheme
            options.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme;
            options.DefaultSignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
            options.DefaultChallengeScheme = OpenIdConnectDefaults.AuthenticationScheme;
        })

        .AddCookie(cookie =>
        {
            //Sets the cookie name and maxage, so the cookie is invalidated.
            cookie.Cookie.Name = "keycloak.cookie";
            cookie.Cookie.MaxAge = TimeSpan.FromMinutes(60);
            cookie.Cookie.SecurePolicy = CookieSecurePolicy.SameAsRequest;
            cookie.SlidingExpiration = true;
        })
        .AddOpenIdConnect(options =>
        {
            //Use default signin scheme
            options.SignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
            //Keycloak server
            options.Authority = Configuration.GetSection("Keycloak")["ServerRealm"];
            //Keycloak client ID
            options.ClientId = Configuration.GetSection("Keycloak")["ClientId"];
            //Keycloak client secret
            options.ClientSecret = Configuration.GetSection("Keycloak")["ClientSecret"];

            //Keycloak .wellknown config origin to fetch config
            // options.MetadataAddress = Configuration.GetSection("Keycloak")["Metadata"];
            //Require keycloak to use SSL
            options.RequireHttpsMetadata = false;
            options.GetClaimsFromUserInfoEndpoint = true;
            options.Scope.Add("openid");
            options.Scope.Add("profile");
            options.Scope.Add("email");

            //Save the token
            options.SaveTokens = true;
            //Token response type, will sometimes need to be changed to IdToken, depending on config.
            options.ResponseType = OpenIdConnectResponseType.Code;
            //SameSite is needed for Chrome/Firefox, as they will give http error 500 back, if not set to unspecified.
            options.NonceCookie.SameSite = SameSiteMode.None;
            options.CorrelationCookie.SameSite = SameSiteMode.None;

            options.TokenValidationParameters = new TokenValidationParameters
            {
                NameClaimType = "name",
                RoleClaimType = "https://schemas.scopic.com/roles"
            };

            Configuration.Bind("<Json Config Filter>", options);
            options.Events.OnRedirectToIdentityProvider = async context =>
            {
                context.ProtocolMessage.RedirectUri = "http://localhost:13636/home";
                await Task.FromResult(0);
            };

        });
</code>```
```<code>app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();

app.UseAuthentication();
app.UseAuthorization();
</code>```

and a simple HomeController like this

```<code>public class HomeController : Controller
{
    private readonly ILogger<HomeController> _logger;

    public HomeController(ILogger<HomeController> logger)
    {
        _logger = logger;
    }

    public IActionResult Index()
    {
        bool value = User.Identity.IsAuthenticated;
        return View();
    }

    [Authorize]
    public IActionResult Privacy()
    {
        return View();
    }
}
</code>```

As seen from above, my redirect URL is localhost:13636/home,
my keycloak is hosted somewhere remote with address like https://auth.ourcompany.com/realms/OurRealm

when i access localhost:13636/Privacy to test, the Keycloak login page is triggered as usual, but after succesful login and redirects to /home, User.Identity.IsAuthenticated is false and
when viewed in debugging console, it seems like cookies is not passed (I am not sure).

Please help understand what is happening here and how to investigate moving forward, i am really stuck on this.
the realm and app is setup without any other things like tokens, jwt, roles, etc.
other application is working properly, its just ASP.NET integration is really having problem.

How do I and what are the things I need to solve this?

I already disabled the browser cross site cookies setting (allow All in chrome) as I thought that there is a problem when recieving cookies from our remote Keycloak server, but no luck. What else am I missing here?

Update:
it doesnt seem to be related to cross site cookies as I have tested running a local keycloak (thru docker) with my localhost ASP.NET core application, the result is the same, isAuthenticated is false and there seem to be no cookies sent in redirect url.

Body:
I have decided to create a simple project to test Keycloak integration to ASP.Net Core 6 MVC, so I used the following setup.

The last time I posted with ASP.NET MVC 4, I did not get any answers and luck so I decided to create a unit test with a simple project in ASP.NET Core 6 MVC and see if i can make it work, but unfortunately, same problem. I am already stuck for two weeks on this.

Please help.

      services.AddAuthentication(options =>
        {
            //Sets cookie authentication scheme
            options.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme;
            options.DefaultSignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
            options.DefaultChallengeScheme = OpenIdConnectDefaults.AuthenticationScheme;
        })

        .AddCookie(cookie =>
        {
            //Sets the cookie name and maxage, so the cookie is invalidated.
            cookie.Cookie.Name = "keycloak.cookie";
            cookie.Cookie.MaxAge = TimeSpan.FromMinutes(60);
            cookie.Cookie.SecurePolicy = CookieSecurePolicy.SameAsRequest;
            cookie.SlidingExpiration = true;
        })
        .AddOpenIdConnect(options =>
        {
            //Use default signin scheme
            options.SignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
            //Keycloak server
            options.Authority = Configuration.GetSection("Keycloak")["ServerRealm"];
            //Keycloak client ID
            options.ClientId = Configuration.GetSection("Keycloak")["ClientId"];
            //Keycloak client secret
            options.ClientSecret = Configuration.GetSection("Keycloak")["ClientSecret"];

            //Keycloak .wellknown config origin to fetch config
            // options.MetadataAddress = Configuration.GetSection("Keycloak")["Metadata"];
            //Require keycloak to use SSL
            options.RequireHttpsMetadata = false;
            options.GetClaimsFromUserInfoEndpoint = true;
            options.Scope.Add("openid");
            options.Scope.Add("profile");
            options.Scope.Add("email");

            //Save the token
            options.SaveTokens = true;
            //Token response type, will sometimes need to be changed to IdToken, depending on config.
            options.ResponseType = OpenIdConnectResponseType.Code;
            //SameSite is needed for Chrome/Firefox, as they will give http error 500 back, if not set to unspecified.
            options.NonceCookie.SameSite = SameSiteMode.None;
            options.CorrelationCookie.SameSite = SameSiteMode.None;

            options.TokenValidationParameters = new TokenValidationParameters
            {
                NameClaimType = "name",
                RoleClaimType = "https://schemas.scopic.com/roles"
            };

            Configuration.Bind("<Json Config Filter>", options);
            options.Events.OnRedirectToIdentityProvider = async context =>
            {
                context.ProtocolMessage.RedirectUri = "http://localhost:13636/home";
                await Task.FromResult(0);
            };

        });

app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();

app.UseAuthentication();
app.UseAuthorization();

and a simple HomeController like this

public class HomeController : Controller
{
    private readonly ILogger<HomeController> _logger;

    public HomeController(ILogger<HomeController> logger)
    {
        _logger = logger;
    }

    public IActionResult Index()
    {
        bool value = User.Identity.IsAuthenticated;
        return View();
    }

    [Authorize]
    public IActionResult Privacy()
    {
        return View();
    }
}

As seen from above, my redirect URL is localhost:13636/home,
my keycloak is hosted somewhere remote with address like https://auth.ourcompany.com/realms/OurRealm

when i access localhost:13636/Privacy to test, the Keycloak login page is triggered as usual, but after succesful login and redirects to /home, User.Identity.IsAuthenticated is false and
when viewed in debugging console, it seems like cookies is not passed (I am not sure).

Please help understand what is happening here and how to investigate moving forward, i am really stuck on this.
the realm and app is setup without any other things like tokens, jwt, roles, etc.
other application is working properly, its just ASP.NET integration is really having problem.

How do I and what are the things I need to solve this?

I already disabled the browser cross site cookies setting (allow All in chrome) as I thought that there is a problem when recieving cookies from our remote Keycloak server, but no luck. What else am I missing here?

Update:
it doesnt seem to be related to cross site cookies as I have tested running a local keycloak (thru docker) with my localhost ASP.NET core application, the result is the same, isAuthenticated is false and there seem to be no cookies sent in redirect url.


来源: stackexchange

问:
How to display MYSQL Blob Image in JSP
I have inserted an image file in database using a Servlet it is inserted into database but when I tried to display on a JSP page I couldn't get the Image but all text data was retrieved.

This is servlet Code which I used for Insertion of Image

```<code>package visitor;

import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.MultipartConfig;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import jakarta.servlet.http.Part;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

import com.mysql.cj.xdevapi.Statement;

import dbConnection.ConnectionProvider;

@MultipartConfig(maxFileSize = 16177215)
public class VisitApply extends HttpServlet {
    private static final long serialVersionUID = 1L;

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        HttpSession session = request.getSession();
        String compname = (String)session.getAttribute("compname");
        String firstname = request.getParameter("firstname");
        String lastname = request.getParameter("lastname");
        String vemail = request.getParameter("vemail");
        String vphone = request.getParameter("vphone");
        String vdate = request.getParameter("vdate");
        String empname = request.getParameter("empname");
        String empmail = request.getParameter("empmail");
        String city = request.getParameter("city");
        InputStream inputStream = null;
        Part filePart = request.getPart("vimage");
        if(filePart != null){
            System.out.println(filePart.getName());
            System.out.println(filePart.getSize());
            System.out.println(filePart.getContentType());
            inputStream = filePart.getInputStream();
        }
        Connection con = ConnectionProvider.getCon();
        try {
            compname = compname.replaceAll("\\s","");
            PreparedStatement st = con.prepareStatement("use "+compname+"");
            st.executeQuery();

            PreparedStatement pst2 = con.prepareStatement("select * from "+compname+"empdetails where empmail = ?");
            pst2.setString(1, empmail);
            ResultSet rs = pst2.executeQuery();
            if(rs.next()) {
                String sql = "insert into "+compname+"avisitors(firstname, lastname, vemail, vphone, vdate, empname, empmail, city, vimage) values(?,?,?,?,?,?,?,?,?)";
                PreparedStatement statement = con.prepareStatement(sql);
                statement.setString(1, firstname);
                statement.setString(2, lastname);
                statement.setString(3, vemail);
                statement.setString(4, vphone);
                statement.setString(5, vdate);
                statement.setString(6, empname);
                statement.setString(7, empmail);
                statement.setString(8, city);
                if(inputStream != null) {
                    statement.setBlob(9, inputStream);
                }
                int row = statement.executeUpdate();
                if(row>0) {
                    response.sendRedirect("visitorform.jsp");
                }else {
                    response.sendRedirect("visitorentry.jsp");
                }
            }else{
                response.sendRedirect("visitorentry.jsp");
            }
        }catch(Exception e){
            e.printStackTrace();
        }

    }

</code>```

type here

```<code>}
</code>```

This is JSP Code for obtaining the image I tried but nothing comes

```<code><%@page import="dbConnection.*"%>
<%@page import="java.sql.*"%>
<%
String compname = (String)session.getAttribute("compname");
Connection con = ConnectionProvider.getCon();
try{
    Statement st = con.createStatement();
    compname = compname.replaceAll("\\s", "");
    String dbuse = "use "+compname+"";
    st.executeQuery(dbuse);

    String viewdata = "select * from "+compname+"avisitors";
    PreparedStatement statement = con.prepareStatement(viewdata);
    ResultSet rs = statement.executeQuery();
    if(rs.next()){
%>
    <div class="col-xl-3 col-lg-3 col-md-3 col-sm-4 col-12">
        <figure class="user-card green">
            <figcaption>
                <img src="<%= rs.getBlob(9)%>" alt="VisitorPhoto" class="profile">
                <h5><%=rs.getString(1)%> <%= rs.getString(2)%></h5>
                <h6><%=rs.getString(5) %></h6>
                    <p>Email: <a href="mailto:<%= rs.getString(3)%>"> <%= rs.getString(3)%></a></p>
                    <p>Phone: <a href="tel:<%= rs.getString(4)%>"><%= rs.getString(4)%></a></p>
                <h6>- Employee Details -</h6>
                <p>Name: <b><%= rs.getString(6)%></b></p>
                <p>EMail: <a href="mailto:<%= rs.getString(7)%>"><%= rs.getString(7)%></a></p>
</code>```

ContentLicense: CC BY-SA 4.0

Title: How to display MYSQL Blob Image in JSP

Body:
I have inserted an image file in database using a Servlet it is inserted into database but when I tried to display on a JSP page I couldn't get the Image but all text data was retrieved.

This is servlet Code which I used for Insertion of Image

package visitor;

import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.MultipartConfig;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import jakarta.servlet.http.Part;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

import com.mysql.cj.xdevapi.Statement;

import dbConnection.ConnectionProvider;

@MultipartConfig(maxFileSize = 16177215)
public class VisitApply extends HttpServlet {
    private static final long serialVersionUID = 1L;

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        HttpSession session = request.getSession();
        String compname = (String)session.getAttribute("compname");
        String firstname = request.getParameter("firstname");
        String lastname = request.getParameter("lastname");
        String vemail = request.getParameter("vemail");
        String vphone = request.getParameter("vphone");
        String vdate = request.getParameter("vdate");
        String empname = request.getParameter("empname");
        String empmail = request.getParameter("empmail");
        String city = request.getParameter("city");
        InputStream inputStream = null;
        Part filePart = request.getPart("vimage");
        if(filePart != null){
            System.out.println(filePart.getName());
            System.out.println(filePart.getSize());
            System.out.println(filePart.getContentType());
            inputStream = filePart.getInputStream();
        }
        Connection con = ConnectionProvider.getCon();
        try {
            compname = compname.replaceAll("\\s","");
            PreparedStatement st = con.prepareStatement("use "+compname+"");
            st.executeQuery();

            PreparedStatement pst2 = con.prepareStatement("select * from "+compname+"empdetails where empmail = ?");
            pst2.setString(1, empmail);
            ResultSet rs = pst2.executeQuery();
            if(rs.next()) {
                String sql = "insert into "+compname+"avisitors(firstname, lastname, vemail, vphone, vdate, empname, empmail, city, vimage) values(?,?,?,?,?,?,?,?,?)";
                PreparedStatement statement = con.prepareStatement(sql);
                statement.setString(1, firstname);
                statement.setString(2, lastname);
                statement.setString(3, vemail);
                statement.setString(4, vphone);
                statement.setString(5, vdate);
                statement.setString(6, empname);
                statement.setString(7, empmail);
                statement.setString(8, city);
                if(inputStream != null) {
                    statement.setBlob(9, inputStream);
                }
                int row = statement.executeUpdate();
                if(row>0) {
                    response.sendRedirect("visitorform.jsp");
                }else {
                    response.sendRedirect("visitorentry.jsp");
                }
            }else{
                response.sendRedirect("visitorentry.jsp");
            }
        }catch(Exception e){
            e.printStackTrace();
        }

    }

type here

}

This is JSP Code for obtaining the image I tried but nothing comes

<%@page import="dbConnection.*"%>
<%@page import="java.sql.*"%>
<%
String compname = (String)session.getAttribute("compname");
Connection con = ConnectionProvider.getCon();
try{
    Statement st = con.createStatement();
    compname = compname.replaceAll("\\s", "");
    String dbuse = "use "+compname+"";
    st.executeQuery(dbuse);

    String viewdata = "select * from "+compname+"avisitors";
    PreparedStatement statement = con.prepareStatement(viewdata);
    ResultSet rs = statement.executeQuery();
    if(rs.next()){
%>

                <img src="<%= rs.getBlob(9)%>" alt="VisitorPhoto" class="profile">

<%=rs.getString(1)%> <%= rs.getString(2)%>

<%=rs.getString(5) %>

Email: <a href="mailto:<%= rs.getString(3)%>"> <%= rs.getString(3)%>

Phone: <a href="tel:<%= rs.getString(4)%>"><%= rs.getString(4)%>

- Employee Details -

Name: <%= rs.getString(6)%>

EMail: <a href="mailto:<%= rs.getString(7)%>"><%= rs.getString(7)%>


问:
Restore Timetracking in GitLab
I am looking for the time tracking report data in Gitlab. Is there any way to restore this data if someone accidently has removed a whole report?

The reason is, we can't customize the removal behaviour:
https://docs.gitlab.com/ee/user/project/time_tracking.html#delete-all-the-time-spent

Title: Restore Timetracking in GitLab


问:
Creating deep copy of a pre-trained model for finetuning in pytorch
I am trying to make a deep copy of a VGG-19 model. I want to use the original pre-trained model for feature extraction of images and also fine tune another version of the model by creating a deep copy of it. But for some reason, when I set requires.grad = False for the original model, it gets reflected in the copied model as well. I am assuming the deep copy is not working as expected here.

Here is a snippet of my code:

```<code>import copy
vgg = model.vgg
vgg.load_state_dict(torch.load(args.vgg))
Encoder = copy.deepcopy(vgg)
Encoder.train()
Encoder.to(device)
optimizer_E = torch.optim.Adam(Encoder.parameters(), lr=args.e_lr)
</code>```

Any idea on why it isn't working?

I want to extract content and style features separately. So for the fixed model I have set:

```<code>vgg = nn.Sequential(*list(vgg.children())[:31])
#Inside the class
 feature_extractor  = list(vgg.children())
 self.layer_1 = nn.Sequential(*feature_extractor[:4])
 self.layer_2 = nn.Sequential(*feature_extractor[4:11])
 self.layer_3 = nn.Sequential(*feature_extractor[11:18])
 self.layer_4 = nn.Sequential(*feature_extractor[18:31])
 # fix the encoder
 for name in ['layer_1', 'layer_2', 'layer_3', 'layer_4']:
     for param in getattr(self, name).parameters():
         param.requires_grad = False
</code>```

For the Encoder, I have done the same except for setting param.requires_grad = True

Body:
I am trying to make a deep copy of a VGG-19 model. I want to use the original pre-trained model for feature extraction of images and also fine tune another version of the model by creating a deep copy of it. But for some reason, when I set requires.grad = False for the original model, it gets reflected in the copied model as well. I am assuming the deep copy is not working as expected here.

Here is a snippet of my code:

import copy
vgg = model.vgg
vgg.load_state_dict(torch.load(args.vgg))
Encoder = copy.deepcopy(vgg)
Encoder.train()
Encoder.to(device)
optimizer_E = torch.optim.Adam(Encoder.parameters(), lr=args.e_lr)

Any idea on why it isn't working?

I want to extract content and style features separately. So for the fixed model I have set:

vgg = nn.Sequential(*list(vgg.children())[:31])
#Inside the class
 feature_extractor  = list(vgg.children())
 self.layer_1 = nn.Sequential(*feature_extractor[:4])
 self.layer_2 = nn.Sequential(*feature_extractor[4:11])
 self.layer_3 = nn.Sequential(*feature_extractor[11:18])
 self.layer_4 = nn.Sequential(*feature_extractor[18:31])
 # fix the encoder
 for name in ['layer_1', 'layer_2', 'layer_3', 'layer_4']:
     for param in getattr(self, name).parameters():
         param.requires_grad = False

For the Encoder, I have done the same except for setting param.requires_grad = True


问:
Sampling in pyspark with two columns
I am working with a big data frame on pyspark and I am new to it. I want to be able to get 10% of the entire population stratified on two columns: one Is a categorical column, and another columns is a continuous column.
Example:

```<code>     user_ID      score    other information
</code>```

I want to be able to pull 10% of the entire population, but the amount of data for each user and their score should be proportionate to the values they have in the entire dataset,
How would I stratify using sampleBy in pyspark , and is there a better way to think about this?

Title: Sampling in pyspark with two columns

Body:
I am working with a big data frame on pyspark and I am new to it. I want to be able to get 10% of the entire population stratified on two columns: one Is a categorical column, and another columns is a continuous column.
Example:

     user_ID      score    other information

I want to be able to pull 10% of the entire population, but the amount of data for each user and their score should be proportionate to the values they have in the entire dataset,
How would I stratify using sampleBy in pyspark , and is there a better way to think about this?


问:
How to enable public access on a local posgreSQL database to allow database continuous migration
Im building a .NET Web API project with a posgreSQL database and I'm trying to deploy it on DigitalOcean and set up a continuous migration. In their docs it is explained how this should be done but in order to start I need to create my database publicly accessible and Im struggling to do so, I tried looking up at tutorials and web sources but that did not help. I also dont understand if there are any dangers in making my database public and how to set up the migration to be secure. Any advice is going to greatly help me, thank you!</p>


问:
Using Regex in Swift to remove parenthesis while keeping the character in between
I am currently working on an expression simplification program. This is how I planned my steps to simplify:

```<code>Original: x*(9/3)
Simplified: x*(3)
Next Simplification: x*3
...
</code>```

Right now I am having trouble removing the parenthesis if there's only 1 digit number/variable inside.

This is my current code:

```<code>let removeParen = try! NSRegularExpression(pattern: "\\(\\S\\)", options: NSRegularExpression.Options.caseInsensitive)
expr = removeParen.stringByReplacingMatches(in: expr, options: [], range: NSMakeRange(0, expr.count), withTemplate: "")
</code>```

I am not sure how to use withTemplate here.

The only thing I know for sure is that $0 copies the matched string back. Group doesn't seem to work in this situation.

Body:
I am currently working on an expression simplification program. This is how I planned my steps to simplify:

Original: x*(9/3)
Simplified: x*(3)
Next Simplification: x*3
...

Right now I am having trouble removing the parenthesis if there's only 1 digit number/variable inside.

This is my current code:

let removeParen = try! NSRegularExpression(pattern: "\\(\\S\\)", options: NSRegularExpression.Options.caseInsensitive)
expr = removeParen.stringByReplacingMatches(in: expr, options: [], range: NSMakeRange(0, expr.count), withTemplate: "")

I am not sure how to use withTemplate here.

The only thing I know for sure is that $0 copies the matched string back. Group doesn't seem to work in this situation.


问:
Doctrine query return Object instead of array
I am finishing the migration of my symfony application from version 2 to version 5.4.
I have a problem with my unit tests.

When I make a request to get the MedicalVists, I get a result where the $files field is is object Type instead of array.

In my test schema, the files field must be returned as arrays. Should I specify a configuration to get the files field as an array as expected?
I use doctrine 2.7

My postman tests error :

```<code>Invalid Schema (item 0) :0 - Invalid type: object (expected array) at /files (/properties/files/type) | AssertionError: expected false to be truthy
</code>```

My Postman expecting schema :

```<code>{"$schema":"http://json-schema.org/draft-04/schema#","additionalProperties":false,"type":"object","properties":{"id":{"type":"integer","minimum":1},"type":{"type":"integer"},"other_type":{"type":"string","maxLength":45},"conclusion":{"type":"string"},"date":{"type":"string","pattern":"^[0-9]{4}-[0-9]{2}-[0-9]{2} [0-9]{2}:[0-9]{2}:[0-9]{2}$"},"description":{"type":"string"},"roles":{"type":"string"},"status":{"type":"integer"},"files":{"type":"array","items":{"type":"object","additionalProperties":false,"properties":{"id":{"type":"integer","minimum":1}},"required":["id"]}},"employee":{"type":"object","additionalProperties":true,"properties":{"id":{"type":"integer","minimum":1},"roles":{"type":"string"}},"required":["id","roles"]},"comment_creator":{"type":"object","additionalProperties":true,"properties":{"id":{"type":"integer","minimum":1},"roles":{"type":"string"}}}},"required":["id","type","date","description","roles","employee"]}
</code>```

My postman request result :

```<code>[
    {
        "id": 3,
        "type": 1,
        "status": 1,
        "files": {
            "Doctrine\\ORM\\PersistentCollectionsnapshot": [],
            "Doctrine\\ORM\\PersistentCollectionassociation": {
                "fieldName": "files",
                "joinTable": {
                    "name": "w2d_em_medical_visit_files",
                    "joinColumns": [
                        {
                            "name": "interview_id",
                            "unique": false,
                            "nullable": true,
                            "referencedColumnName": "id"
                        }
                    ],
                    "inverseJoinColumns": [
                        {
                            "name": "file_id",
                            "unique": false,
                            "nullable": true,
                            "referencedColumnName": "id"
                        }
                    ]
                },
                "targetEntity": "W2D\\FileBundle\\Entity\\File",
                "cascade": [],
                "orphanRemoval": false,
                "fetch": 2,
                "type": 8,
                "isOwningSide": true,
                "sourceEntity": "W2D\\EmployeeBundle\\Entity\\MedicalVisit",
                "isCascadeRemove": false,
                "isCascadePersist": false,
                "isCascadeRefresh": false,
                "isCascadeMerge": false,
                "isCascadeDetach": false,
                "joinTableColumns": [
                    "interview_id",
                    "file_id"
                ],
                "relationToSourceKeyColumns": {
                    "interview_id": "id"
                },
                "relationToTargetKeyColumns": {
                    "file_id": "id"
                }
            },
            "Doctrine\\ORM\\PersistentCollectionem": {},
            "Doctrine\\ORM\\PersistentCollectiontypeClass": {},
            "Doctrine\\ORM\\PersistentCollectionisDirty": false,
            "*collection": [],
            "*initialized": false
        },
        "date": "2018-01-01 00:00:00",
        "description": "PUT medical visit description",
        "employee": {
            "id": 6,
            "firstname": "Robin",
            "lastname": "Monteil",
            "gender": 0,
            "entry_at": "2014-09-01 00:00:00",
            "birthday": "1987-02-24 00:00:00",
            "city_birth": "Marseille",
            "department_birth": "Bouches-du-Rhône",
            "country_birth": {},
            "photo": {},
            "roles": "roles"
        },
        "roles": "roles"
    },
</code>```

I tried to add fetch=EAGER in my entity MedicalVisit but this is not the expected result...

Body:
I am finishing the migration of my symfony application from version 2 to version 5.4.
I have a problem with my unit tests.

When I make a request to get the MedicalVists, I get a result where the $files field is is object Type instead of array.

In my test schema, the files field must be returned as arrays. Should I specify a configuration to get the files field as an array as expected?
I use doctrine 2.7

My postman tests error :

Invalid Schema (item 0) :0 - Invalid type: object (expected array) at /files (/properties/files/type) | AssertionError: expected false to be truthy

My Postman expecting schema :

{"$schema":"http://json-schema.org/draft-04/schema#","additionalProperties":false,"type":"object","properties":{"id":{"type":"integer","minimum":1},"type":{"type":"integer"},"other_type":{"type":"string","maxLength":45},"conclusion":{"type":"string"},"date":{"type":"string","pattern":"^[0-9]{4}-[0-9]{2}-[0-9]{2} [0-9]{2}:[0-9]{2}:[0-9]{2}$"},"description":{"type":"string"},"roles":{"type":"string"},"status":{"type":"integer"},"files":{"type":"array","items":{"type":"object","additionalProperties":false,"properties":{"id":{"type":"integer","minimum":1}},"required":["id"]}},"employee":{"type":"object","additionalProperties":true,"properties":{"id":{"type":"integer","minimum":1},"roles":{"type":"string"}},"required":["id","roles"]},"comment_creator":{"type":"object","additionalProperties":true,"properties":{"id":{"type":"integer","minimum":1},"roles":{"type":"string"}}}},"required":["id","type","date","description","roles","employee"]}

My postman request result :

[
    {
        "id": 3,
        "type": 1,
        "status": 1,
        "files": {
            "Doctrine\\ORM\\PersistentCollectionsnapshot": [],
            "Doctrine\\ORM\\PersistentCollectionassociation": {
                "fieldName": "files",
                "joinTable": {
                    "name": "w2d_em_medical_visit_files",
                    "joinColumns": [
                        {
                            "name": "interview_id",
                            "unique": false,
                            "nullable": true,
                            "referencedColumnName": "id"
                        }
                    ],
                    "inverseJoinColumns": [
                        {
                            "name": "file_id",
                            "unique": false,
                            "nullable": true,
                            "referencedColumnName": "id"
                        }
                    ]
                },
                "targetEntity": "W2D\\FileBundle\\Entity\\File",
                "cascade": [],
                "orphanRemoval": false,
                "fetch": 2,
                "type": 8,
                "isOwningSide": true,
                "sourceEntity": "W2D\\EmployeeBundle\\Entity\\MedicalVisit",
                "isCascadeRemove": false,
                "isCascadePersist": false,
                "isCascadeRefresh": false,
                "isCascadeMerge": false,
                "isCascadeDetach": false,
                "joinTableColumns": [
                    "interview_id",
                    "file_id"
                ],
                "relationToSourceKeyColumns": {
                    "interview_id": "id"
                },
                "relationToTargetKeyColumns": {
                    "file_id": "id"
                }
            },
            "Doctrine\\ORM\\PersistentCollectionem": {},
            "Doctrine\\ORM\\PersistentCollectiontypeClass": {},
            "Doctrine\\ORM\\PersistentCollectionisDirty": false,
            "*collection": [],
            "*initialized": false
        },
        "date": "2018-01-01 00:00:00",
        "description": "PUT medical visit description",
        "employee": {
            "id": 6,
            "firstname": "Robin",
            "lastname": "Monteil",
            "gender": 0,
            "entry_at": "2014-09-01 00:00:00",
            "birthday": "1987-02-24 00:00:00",
            "city_birth": "Marseille",
            "department_birth": "Bouches-du-Rhône",
            "country_birth": {},
            "photo": {},
            "roles": "roles"
        },
        "roles": "roles"
    },

I tried to add fetch=EAGER in my entity MedicalVisit but this is not the expected result...


问:
How to join two Map -Key and Value while looping through a Array List in PySpark
I have 3 dataframes as below:
**Dataframe_1 **  This needs to loop for each set/array list

```<code>| Some_id                                   |
|-------------------------------------------|
|["23815", "23824", "36978", "23824", "81"] |
|["37551", "36091", "81"]                   |
</code>```

Dataframe_2  This is a lookup

```<code>|Some_id|Cor_name |PropertiesMap                            |
|------ |---------|-----------------------------------------|
|37551  |Mango    |{cor_name  -> Mango, _value -> 18912}    |
|36091  |Orange   |{cor_name  -> Orange, _value -> 1234}   |
|23824  |Mango    |{cor_name  -> Mango, _value -> 29014}    |
|81     |Apple    |{cor_name  -> Apple, _value -> E7063}    |
</code>```

Dataframe_3  From this table, I need to get the matching Ids

```<code>|Need_id|PropertiesMap                                     |
|------ |--------------------------------------------------|
|1      |[Mango :18912 ]                                   |
|2      |[Mango :18912, Apple: E7063 , Orange: 1234]       |
|3      |[Apple : E7063 ]                                  |
|4      |[Mango :18912, Apple: E7063 , Orange: 1234]       |
</code>```

Expected Output:

Need_id
Some_id
PropertiesMap

2
["37551", "36091", "81"]
[Mango :18912, Apple: E7063 , Orange: 1234]

4
["37551", "36091", "81"]
[Mango :18912, Apple: E7063 , Orange: 1234]

I am trying like this, but, it is not at all efficient

```<code>for row in dataframe_1.collect():
    lis_1 = list(row)
    dataframe_2= (dataframe_2.alias("A").join(dataframe_1.alias("B"),
    on = (F.array_contains("B.some_id", "A.some_id"))))
#What to do after
</code>```

Anyother efficient way to achive this. First join itself taking long time.

Body:
I have 3 dataframes as below:
**Dataframe_1 **  This needs to loop for each set/array list

| Some_id                                   |
|-------------------------------------------|
|["23815", "23824", "36978", "23824", "81"] |
|["37551", "36091", "81"]                   |

Dataframe_2  This is a lookup

|Some_id|Cor_name |PropertiesMap                            |
|------ |---------|-----------------------------------------|
|37551  |Mango    |{cor_name  -> Mango, _value -> 18912}    |
|36091  |Orange   |{cor_name  -> Orange, _value -> 1234}   |
|23824  |Mango    |{cor_name  -> Mango, _value -> 29014}    |
|81     |Apple    |{cor_name  -> Apple, _value -> E7063}    |

Dataframe_3  From this table, I need to get the matching Ids

|Need_id|PropertiesMap                                     |
|------ |--------------------------------------------------|
|1      |[Mango :18912 ]                                   |
|2      |[Mango :18912, Apple: E7063 , Orange: 1234]       |
|3      |[Apple : E7063 ]                                  |
|4      |[Mango :18912, Apple: E7063 , Orange: 1234]       |

Expected Output:

Need_id
Some_id
PropertiesMap

2
["37551", "36091", "81"]
[Mango :18912, Apple: E7063 , Orange: 1234]

4
["37551", "36091", "81"]
[Mango :18912, Apple: E7063 , Orange: 1234]

I am trying like this, but, it is not at all efficient

for row in dataframe_1.collect():
    lis_1 = list(row)
    dataframe_2= (dataframe_2.alias("A").join(dataframe_1.alias("B"),
    on = (F.array_contains("B.some_id", "A.some_id"))))
#What to do after

Anyother efficient way to achive this. First join itself taking long time.


问:
How to download attachment from gmail using gmail API (PYTHON)
facing problem how to download attachment from email using gmail API in python.

help me with how to download email attachment .

below code will print subject, body, sender but not attachment details.

how to get mail attechmentID in below code

```<code># import the required libraries
from googleapiclient.discovery import build
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request
import pickle
import os.path
import base64
import email
from bs4 import BeautifulSoup
import bs4

SCOPES = ['https://www.googleapis.com/auth/gmail.readonly']

def getEmails():
  creds = None
  if os.path.exists('token.pickle'):
      with open('token.pickle', 'rb') as token:
          creds = pickle.load(token)
  if not creds or not creds.valid:
      if creds and creds.expired and creds.refresh_token:
          creds.refresh(Request())
      else:
          flow = InstalledAppFlow.from_client_secrets_file('red.json', SCOPES)
          creds = flow.run_local_server(port=0)
      with open('token.pickle', 'wb') as token:
          pickle.dump(creds, token)
  service = build('gmail', 'v1', credentials=creds)
  # request a list of all the messages
  # result = service.users().messages().list(userId='me').execute()
  result = service.users().messages().list(maxResults=2, userId='me').execute()
  messages = result.get('messages')
  for msg in messages:
      txt = service.users().messages().get(userId='me', id=msg['id']).execute()
      try:
          payload = txt['payload']
          headers = payload['headers']
          for d in headers:
              if d['name'] == 'Subject':
                  subject = d['value']
              if d['name'] == 'From':
                  sender = d['value']
          parts = payload.get('parts')[0]
          data = parts['body']['data']
          data = data.replace("-","+").replace("_","/")
          decoded_data = base64.b64decode(data)
          soup = BeautifulSoup(decoded_data , "lxml")
          body = soup.body()

          print("From:::::: ", sender)
          print("Subject::: ", subject)
          print("body:::::: ", body)
          print('\n')
      except:
          pass

getEmails()

</code>```

Body:
facing problem how to download attachment from email using gmail API in python.

help me with how to download email attachment .

below code will print subject, body, sender but not attachment details.

how to get mail attechmentID in below code

# import the required libraries
from googleapiclient.discovery import build
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request
import pickle
import os.path
import base64
import email
from bs4 import BeautifulSoup
import bs4

SCOPES = ['https://www.googleapis.com/auth/gmail.readonly']

def getEmails():
  creds = None
  if os.path.exists('token.pickle'):
      with open('token.pickle', 'rb') as token:
          creds = pickle.load(token)
  if not creds or not creds.valid:
      if creds and creds.expired and creds.refresh_token:
          creds.refresh(Request())
      else:
          flow = InstalledAppFlow.from_client_secrets_file('red.json', SCOPES)
          creds = flow.run_local_server(port=0)
      with open('token.pickle', 'wb') as token:
          pickle.dump(creds, token)
  service = build('gmail', 'v1', credentials=creds)
  # request a list of all the messages
  # result = service.users().messages().list(userId='me').execute()
  result = service.users().messages().list(maxResults=2, userId='me').execute()
  messages = result.get('messages')
  for msg in messages:
      txt = service.users().messages().get(userId='me', id=msg['id']).execute()
      try:
          payload = txt['payload']
          headers = payload['headers']
          for d in headers:
              if d['name'] == 'Subject':
                  subject = d['value']
              if d['name'] == 'From':
                  sender = d['value']
          parts = payload.get('parts')[0]
          data = parts['body']['data']
          data = data.replace("-","+").replace("_","/")
          decoded_data = base64.b64decode(data)
          soup = BeautifulSoup(decoded_data , "lxml")
          body = soup.body()

          print("From:::::: ", sender)
          print("Subject::: ", subject)
          print("body:::::: ", body)
          print('\n')
      except:
          pass

getEmails()


问:
How to let Angular recieve post data from external URL direction?
I am using .Net Core + Angular to develop a Login Page.
This single Login Page will be used by a few diffrent Applications.

So, The external Applications will have to tell my Application about who they are.
However, I don't want them to let me know by the URL Parameters.

Yet, I cannot find the way to let Angular to recieve a Post Data from the external URL direction.
Can Someone Help me, Please?

I already try the http.get in Angular, but as I said, I don't have a certain URL or Backend to get Data from…


问:
Cannot see tooltip in iPhone in portrait mode
I have used a span element to display my tooltip content by setting its visibility on hover and active. Here's my JSX and CSS:-

```<code><text className={classNames(styles.iconInfo)}>ⓘ<span className={classNames(styles.tooltip)}>{t('order_id_tooltip')}</span></text>

.iconInfo .tooltip {
  visibility: hidden;
  width: auto;
  background-color: white;
  color: black;
  text-align: left;
  line-height: 20px;
  border-radius: 8px;
  padding: 8px;
  @include theme-aware('font-family', 'font-family');
  font-size: 16px;
  font-weight: normal;
  filter: drop-shadow(rgba(0, 0, 0, 0.3) 0 2px 10px);
  position: absolute;
  z-index: 1;
  margin-left: 12px;
  margin-top: -6px;
}

.iconInfo .tooltip::after {
  content: "";
  position: absolute;
  top: 50%;
  right: 100%;
  margin-top: -8px;
  border-width: 8px;
  border-style: solid;
  border-color: transparent white transparent transparent;
}

.iconInfo:hover .tooltip, .iconInfo:active .tooltip {
  visibility: visible;
}
</code>```

Now this implementation works for all web browsers on Mac and PC (Safari, Chrome etc.). It works on all tablets (you touch the tooltip icon to show the tooltip). It even works on iPhones but there's a catch: it works only in landscape mode, not portrait mode. I've tried on quite a few iPhones in both Safari and Chrome browsers, but it doesn't work.

I've gone through the solutions in Fix CSS hover on iPhone/iPad/iPod and https://dev.webonomic.nl/fixing-the-iphone-css-hover-problem-on-ios but they didn't work for me.

Any idea why this happens? I guess I should probably mention that I'm treating my page as a mobile screen with a media query: @media only screen and (max-width: 576px). When I rotate the iPhone to landscape, it shows the page in my tablet design, which is what I want. So, could this media query have an effect as well?

I'm using BrowserStack to emulate the devices.

Body:
I have used a span element to display my tooltip content by setting its visibility on hover and active. Here's my JSX and CSS:-

<text className={classNames(styles.iconInfo)}>ⓘ{t('order_id_tooltip')}</text>

.iconInfo .tooltip {
  visibility: hidden;
  width: auto;
  background-color: white;
  color: black;
  text-align: left;
  line-height: 20px;
  border-radius: 8px;
  padding: 8px;
  @include theme-aware('font-family', 'font-family');
  font-size: 16px;
  font-weight: normal;
  filter: drop-shadow(rgba(0, 0, 0, 0.3) 0 2px 10px);
  position: absolute;
  z-index: 1;
  margin-left: 12px;
  margin-top: -6px;
}

.iconInfo .tooltip::after {
  content: "";
  position: absolute;
  top: 50%;
  right: 100%;
  margin-top: -8px;
  border-width: 8px;
  border-style: solid;
  border-color: transparent white transparent transparent;
}

.iconInfo:hover .tooltip, .iconInfo:active .tooltip {
  visibility: visible;
}

Now this implementation works for all web browsers on Mac and PC (Safari, Chrome etc.). It works on all tablets (you touch the tooltip icon to show the tooltip). It even works on iPhones but there's a catch: it works only in landscape mode, not portrait mode. I've tried on quite a few iPhones in both Safari and Chrome browsers, but it doesn't work.

I've gone through the solutions in Fix CSS hover on iPhone/iPad/iPod and https://dev.webonomic.nl/fixing-the-iphone-css-hover-problem-on-ios but they didn't work for me.

Any idea why this happens? I guess I should probably mention that I'm treating my page as a mobile screen with a media query: @media only screen and (max-width: 576px). When I rotate the iPhone to landscape, it shows the page in my tablet design, which is what I want. So, could this media query have an effect as well?

I'm using BrowserStack to emulate the devices.


问:
Python readline delete the printed content line on double clicking backspace
I have a simple python code where i printed a question and i expect input from the user.
I imported readline so that user can access to history of his inputs and use arrow keys.
This is the code :

```<code>import readline

print("Welcome to Numgame, please enter a number \nuser $", end=" ")
m = input()
</code>```

After running the script, if i add one character and press backspace to remove the character all of the second line is deleted.

Example: This is the output of running the script and typing for example 'e' :

Welcome to Numgame, please enter a number

user $ e

If i press backspace, the output looks like this:

Welcome to Numgame, please enter a number

As you can see, the second line is gone. I want a solution so that i can use backspace without "user $" being removed.

Body:
I have a simple python code where i printed a question and i expect input from the user.
I imported readline so that user can access to history of his inputs and use arrow keys.
This is the code :

import readline

print("Welcome to Numgame, please enter a number \nuser $", end=" ")
m = input()

After running the script, if i add one character and press backspace to remove the character all of the second line is deleted.

Example: This is the output of running the script and typing for example 'e' :

Welcome to Numgame, please enter a number

user $ e

If i press backspace, the output looks like this:

Welcome to Numgame, please enter a number

As you can see, the second line is gone. I want a solution so that i can use backspace without "user $" being removed.


问:
Switch a flux conditionally testing the first n elements (switchOnFirstN)
What would be the best way to achieve the following:

```<code>If the first n elements of a flux pass a certain test -> reproduce the whole flux
else -> empty
</code>```

The operation would behave like Flux.switchOnFirst(), but with the first n elements in scope.
The empty flux can be picked up by switchOnEmpty if necessary.

Examples:

"If the first 5 elements contain 'foo' then proceed, else abort / return empty."

"If the flux has at least 5 elements then proceed else abort"

I tried to solve this problem without forking by cache(). The solution is only a proof of concept yet and might lack proper signal handling.

The code essentialy splits the original flux into two windows, uses switchOnFirst() to collect the (finite) first window into a Mono<List<T>> and applies the test on that list. The test either yields the whole list (true) or empty (false). It then puts everything back together, avoiding double subscribe to the windows, which is forbidden.

I wonder if there is a more elegant solution to this.

 fun demo() {
     val flux = Flux.just("foo", "bar", "baz", "etc")
                .transform(filterByFirstElements(numElementsToTest = 3) { it.contains("bar") })
                .subscribe { println(it) } //will return "foo", "bar", "baz", "etc"

     val flux2 = Flux.just("foo", "bar", "baz", "etc")
                .transform(filterByFirstElements(numElementsToTest = 3) { it.contains("bar2") })
                .subscribe { println(it) } //will return empty
 }

/** Applies a test to the first n elements. Produces the whole flux if the test passes. Returns empty if not. **/
fun <T> filterByFirstElements(numElementsToTest: Int, test: (List<T>) -> Boolean): (Flux<T>) -> Flux<T> =
    { flux ->
        flux
           .index()
           .windowUntil({ tuple ->
                         val index = tuple.t1
                         index + 1 > numElementsToTest
                        }, true
           ).switchOnFirst { firstFluxSignal, everyFlux ->
                        val monoPrefix = firstFluxSignal.get()!! //TODO: Error handling
                        .map { it.t2 }.collectList().mapNotNull { list ->
                            if (test(list)) list else null
                        }
                        monoPrefix
                            .flatMapMany { list ->
                                Flux.fromIterable(list).concatWith(everyFlux.skip(1)
                                    .concatMap { it.map { it.t2 } })//may not subscribe twice
                            }
                    }
            }
    }
```

Body:
What would be the best way to achieve the following:

If the first n elements of a flux pass a certain test -> reproduce the whole flux
else -> empty

The operation would behave like Flux.switchOnFirst(), but with the first n elements in scope.
The empty flux can be picked up by switchOnEmpty if necessary.

Examples:

"If the first 5 elements contain 'foo' then proceed, else abort / return empty."

"If the flux has at least 5 elements then proceed else abort"

I tried to solve this problem without forking by cache(). The solution is only a proof of concept yet and might lack proper signal handling.

The code essentialy splits the original flux into two windows, uses switchOnFirst() to collect the (finite) first window into a Mono<List<T>> and applies the test on that list. The test either yields the whole list (true) or empty (false). It then puts everything back together, avoiding double subscribe to the windows, which is forbidden.

I wonder if there is a more elegant solution to this.

 fun demo() {
     val flux = Flux.just("foo", "bar", "baz", "etc")
                .transform(filterByFirstElements(numElementsToTest = 3) { it.contains("bar") })
                .subscribe { println(it) } //will return "foo", "bar", "baz", "etc"

     val flux2 = Flux.just("foo", "bar", "baz", "etc")
                .transform(filterByFirstElements(numElementsToTest = 3) { it.contains("bar2") })
                .subscribe { println(it) } //will return empty
 }

/** Applies a test to the first n elements. Produces the whole flux if the test passes. Returns empty if not. **/
fun <T> filterByFirstElements(numElementsToTest: Int, test: (List<T>) -> Boolean): (Flux<T>) -> Flux<T> =
    { flux ->
        flux
           .index()
           .windowUntil({ tuple ->
                         val index = tuple.t1
                         index + 1 > numElementsToTest
                        }, true
           ).switchOnFirst { firstFluxSignal, everyFlux ->
                        val monoPrefix = firstFluxSignal.get()!! //TODO: Error handling
                        .map { it.t2 }.collectList().mapNotNull { list ->
                            if (test(list)) list else null
                        }
                        monoPrefix
                            .flatMapMany { list ->
                                Flux.fromIterable(list).concatWith(everyFlux.skip(1)
                                    .concatMap { it.map { it.t2 } })//may not subscribe twice
                            }
                    }
            }
    }


问:
Make forumla in two seperate columns in the same column in excel
I have a formula that exists in two columns because I can't seem to figure out how to make it in simply one column.
The two formulas are in colomn: "Fragttype Paller" & "Fragttype koli"
However these two seperate formulas should be made as one formula in column "Fragttype simplified"

Conditions for formula
The excel spreadsheet I've uploaded here https://easyupload.io/kpvqcv

Can someone help me?

BR
Luca

I tried simple copying both two formulas in excel on top of each summed in one column, but did not work


问:
simpl-schema to validate multiple types of data
Is it possible to use the simple schema package to validate data that can potentially be multiple types.

For example, if we have an object, and are checking to see if it's an admin by both checking a unique name is apart of the admins, and if there

```<code>const user1 = {
                name: 'Mr Is Admin',
                isAdmin: true }
</code>```

below is some pseudo code of what I hope it could do

```<code>const isAdmin = new SimpleSchema({
  isAdmin: array, boolean
  code: {
    type: [] || boolean
  }
};
</code>```

The reason I'm asking about it specifically supporting multiple types is that the application I'm working on has users cast votes in a meeting, and they can respond in multiple ways depending on the type of question

```<code>interface MeetingQuestionVoteUpdate {

    vote?: boolean | [] | null;

}
</code>```

Essentially. Would I be able to use simpl-schema to validate votes, given it could be different types?

Body:
Is it possible to use the simple schema package to validate data that can potentially be multiple types.

For example, if we have an object, and are checking to see if it's an admin by both checking a unique name is apart of the admins, and if there

const user1 = {
                name: 'Mr Is Admin',
                isAdmin: true }

below is some pseudo code of what I hope it could do

const isAdmin = new SimpleSchema({
  isAdmin: array, boolean
  code: {
    type: [] || boolean
  }
};

The reason I'm asking about it specifically supporting multiple types is that the application I'm working on has users cast votes in a meeting, and they can respond in multiple ways depending on the type of question

interface MeetingQuestionVoteUpdate {

    vote?: boolean | [] | null;

}

Essentially. Would I be able to use simpl-schema to validate votes, given it could be different types?


问:
How to prune inactive / bad APNs tokens in Django-push-notifications
I'm using django-push-notifications (DPN) to send notification to an iOS app. When I send a notification, DPN gives me the response from APNs as a dict with the device tokens and their status.

```<code>r = devices.send_message(message="Fancy pansy message.", sound="default")
</code>```

Where the response looks something like:

```<code>r = [
        {
            '<devicetoken1>': 'Success',
            '<devicetoken2>': 'BadDeviceToken',
            '<devicetoken3>': 'Success',
        }
    ]
</code>```

I have a view in Django which takes POST requests. I use this endpoint to post the message I send to APNs with send_message() as well as save the message to my DB.

So my plan was to add the following simple logic to the same view to prune the DB each time I get feedback on expired / bad device tokens from APNs (or something like it, I may of course need to add more statuses than "BadDeviceToken").

```<code>for token_str, token_status in r[0].items():
    if token_status == 'BadDeviceToken':
        APNSDevice.objects.filter(registration_id=token_str).delete()

</code>```

My question is if there is a better way of doing this? Should pruning be done with some periodic task instead? Are there any issues with doing this kind of logic in the views in Django? Or am I missing any existing solutions to this problem (pruning tokens) in either Django or DPN?

Cheers!

Body:
I'm using django-push-notifications (DPN) to send notification to an iOS app. When I send a notification, DPN gives me the response from APNs as a dict with the device tokens and their status.

r = devices.send_message(message="Fancy pansy message.", sound="default")

Where the response looks something like:

r = [
        {
            '<devicetoken1>': 'Success',
            '<devicetoken2>': 'BadDeviceToken',
            '<devicetoken3>': 'Success',
        }
    ]

I have a view in Django which takes POST requests. I use this endpoint to post the message I send to APNs with send_message() as well as save the message to my DB.

So my plan was to add the following simple logic to the same view to prune the DB each time I get feedback on expired / bad device tokens from APNs (or something like it, I may of course need to add more statuses than "BadDeviceToken").

for token_str, token_status in r[0].items():
    if token_status == 'BadDeviceToken':
        APNSDevice.objects.filter(registration_id=token_str).delete()

My question is if there is a better way of doing this? Should pruning be done with some periodic task instead? Are there any issues with doing this kind of logic in the views in Django? Or am I missing any existing solutions to this problem (pruning tokens) in either Django or DPN?

Cheers!


问:
mockStatic of Mockito vs mockStatic of PowerMock
In order to mock static methods for unit testing in Java we can either use PowerMock or we Can use mockStatic of Mockito. I already know that need to mock static method means code smell and I should refactor the original code but that is not possible as of now.

Sample Class to be Tested

```<code>public class classToBeTested{

//Some Code

public static String methodToBeTested() {
// Some Code
}

}
</code>```

Testing Using Mockito-Inline (Mockito MockStatic)

```<code>public class TestClassToBeTested{
private MockedStatic<classToBeTested> mockedClassToBeTested;

@Test
public void testmethodToBeTested() {

mockedClassToBeTested =
Mockito.mockStatic(classToBeTested.class);
mockedClassToBeTested.when(classToBeTested::methodToBeTested)
.thenReturn("Some Value");

// extra code for testing
}
}
</code>```

Testing Using PowerMock

```<code>public class TestClassToBeTested{

@Test
public void testmethodToBeTested() {

PowerMockito.mockStatic(classToBeTested.class);
when(classToBeTested.methodToBeTested())
.thenReturn("Some Value");

// extra code for testing
}
}
</code>```

So which mocking technique is better mockito-inline one or power mockito. what is the difference between them? what do they do behind the scene to achieve this?

Body:
In order to mock static methods for unit testing in Java we can either use PowerMock or we Can use mockStatic of Mockito. I already know that need to mock static method means code smell and I should refactor the original code but that is not possible as of now.

Sample Class to be Tested

public class classToBeTested{

//Some Code

public static String methodToBeTested() {
// Some Code
}

}

Testing Using Mockito-Inline (Mockito MockStatic)

public class TestClassToBeTested{
private MockedStatic<classToBeTested> mockedClassToBeTested;

@Test
public void testmethodToBeTested() {

mockedClassToBeTested =
Mockito.mockStatic(classToBeTested.class);
mockedClassToBeTested.when(classToBeTested::methodToBeTested)
.thenReturn("Some Value");

// extra code for testing
}
}

Testing Using PowerMock

public class TestClassToBeTested{

@Test
public void testmethodToBeTested() {

PowerMockito.mockStatic(classToBeTested.class);
when(classToBeTested.methodToBeTested())
.thenReturn("Some Value");

// extra code for testing
}
}

So which mocking technique is better mockito-inline one or power mockito. what is the difference between them? what do they do behind the scene to achieve this?


问:
FIFTPATH tonstarter contract
Problem when exporting Fift.fif file to the tonstarter contract

I tried export FIFTPATH=/Users\engue\Downloads\ton-master\ton-master\crypto\fift\lib
but it didnot give
It was expected to be exported to the contract and then execute npm run build command to compile main.fc

Title: FIFTPATH tonstarter contract


问:
MobiScroll's Agenda Synchronized Views free Alternative
I want to have an npm or free version of the above listed mobiscroll's Agenda Synchronized view.

I would like to show the Upcoming events of the current month or by clicking on the Date in the Calendar.

Something Like this.

Any help would be appreciated.


问:
Update React State with Django
I want to open a Dialog-window in React whenever the User clicks on the corresponding button in Navbar. The Problem is that the Navbar is part of a Django Frontend.

I have tried updating the state via localstorage, but I wasn't successful. I have tried using the
window.addEventlistener() , but it wont update if changes where made on the same page, as it only updates if changes where made from another site/tab

I just want to know if
there is any way to make Django communicate with React to trigger such an state update?

Title: Update React State with Django


问:
Docker/Prisma - Error: P1001: Can't reach database server at `localhost`:`3310`

.dev.env

DATABASE_URL=mysql://root:root@localhost:3310/masterapp_mysql_db_dev?schema=public

docker-compose.yaml

```<code>version: "3.9"
services:
  masterapp-dev-db:
    image: mysql:latest
    container_name: masterapp_db
    ports:
    - 3310:3310
    expose:
      - 3310
    volumes:
      - /var/lib/mysql:/var/lib/mysql
    environment:
      MYSQL_ROOT_PASSWORD: root
      MYSQL_DATABASE: masterapp_mysql_db_dev
      MYSQL_USER: test_user
      MYSQL_PASSWORD: test_pass
      MYSQL_ROOT_HOST: '%'
      MYSQL_TCP_PORT: 3310
  server-dev:
    build: ./server
    volumes:
      - /server/home/node/server
    env_file:
      - ./server/src/config/envConfig/.dev.env
    ports:
      - "8080:8080"
    links:
      - masterapp-dev-db
    depends_on:
      - masterapp-dev-db
</code>```

Dockerfile

```<code>
FROM node:19-alpine3.15

WORKDIR /server

COPY package*.json ./

RUN npm i

COPY . ./

EXPOSE 8080

RUN npm run migrate:mysql:dev

RUN npx prisma generate

CMD ["npm", "run", "dev"]
</code>```

package.json

```<code>"migrate:mysql:dev": "dotenv -e ./src/config/envConfig/.dev.env -- npx prisma migrate dev --name migrate-msql",
    "db:dev:rm": "docker compose rm masterapp-dev-db -s -f -v",
    "db:dev:up": "docker compose up masterapp-dev-db -d",
    "db:dev:restart": "npm run db:dev:rm && npm run db:dev:up && sleep 1 && npm run migrate:mysql:dev",
    "dev": "ts-node-dev --files --respawn --transpile-only src/app.ts"
</code>```

First i run docker compose up masterapp-dev-db -d which spins up the container for my mysql database. At this point the database i working properly and can be reached on localhost with the environment credentials listed in docker-compose file.

Then I ran docker compose up server-dev -d  which gets me the above mentioned error.

I've tried changing localhost to the name of the service (masterapp-dev-db) , to the name of the container (masterapp_db), to the IP of the container (172.19.0.2) and stil got the same error.

Body:
.dev.env

DATABASE_URL=mysql://root:root@localhost:3310/masterapp_mysql_db_dev?schema=public

docker-compose.yaml

version: "3.9"
services:
  masterapp-dev-db:
    image: mysql:latest
    container_name: masterapp_db
    ports:
    - 3310:3310
    expose:
      - 3310
    volumes:
      - /var/lib/mysql:/var/lib/mysql
    environment:
      MYSQL_ROOT_PASSWORD: root
      MYSQL_DATABASE: masterapp_mysql_db_dev
      MYSQL_USER: test_user
      MYSQL_PASSWORD: test_pass
      MYSQL_ROOT_HOST: '%'
      MYSQL_TCP_PORT: 3310
  server-dev:
    build: ./server
    volumes:
      - /server/home/node/server
    env_file:
      - ./server/src/config/envConfig/.dev.env
    ports:
      - "8080:8080"
    links:
      - masterapp-dev-db
    depends_on:
      - masterapp-dev-db

Dockerfile

FROM node:19-alpine3.15

WORKDIR /server

COPY package*.json ./

RUN npm i

COPY . ./

EXPOSE 8080

RUN npm run migrate:mysql:dev

RUN npx prisma generate

CMD ["npm", "run", "dev"]

package.json

"migrate:mysql:dev": "dotenv -e ./src/config/envConfig/.dev.env -- npx prisma migrate dev --name migrate-msql",
    "db:dev:rm": "docker compose rm masterapp-dev-db -s -f -v",
    "db:dev:up": "docker compose up masterapp-dev-db -d",
    "db:dev:restart": "npm run db:dev:rm && npm run db:dev:up && sleep 1 && npm run migrate:mysql:dev",
    "dev": "ts-node-dev --files --respawn --transpile-only src/app.ts"

First i run docker compose up masterapp-dev-db -d which spins up the container for my mysql database. At this point the database i working properly and can be reached on localhost with the environment credentials listed in docker-compose file.

Then I ran docker compose up server-dev -d  which gets me the above mentioned error.

I've tried changing localhost to the name of the service (masterapp-dev-db) , to the name of the container (masterapp_db), to the IP of the container (172.19.0.2) and stil got the same error.


问:
Specify scenario(s) not to run in parallel with Junit-5 using Cucumber
I am trying to execute some scenarios in which there are some specific scenarios should not run in parallel.
This is the documentation for Cucumber JUnit Platform Engine

Note: I've tried @isolated, happened to face the same issue here:
https://github.com/cucumber/cucumber-jvm/issues/2589


问:
Why deadlock exception in single transaction in SQL Server
I have a table Table_1 in SQL Server 2014. It has two columns name, id.

I want to run the following script in two separate connections simultaneously:

```<code>while 1 = 1
begin
begin try
    SET TRANSACTION ISOLATION LEVEL Serializable;
        begin tran

        declare @maxId int = 0
        select @maxId = MAX(Id) + 1 from [dbo].[Table_1]
        print(@maxId)

        set identity_insert [dbo].[Table_1] on
            INSERT INTO [dbo].[Table_1] (Id,[Name])
            VALUES (@maxId,'11')
        set identity_insert [dbo].[Table_1] off

commit tran
end try
begin catch

IF(@@TRANCOUNT > 0)
rollback tran

    print ( ERROR_MESSAGE())
    print ( ERROR_SEVERITY())
    print ( ERROR_STATE())

end catch

end
</code>```

In this script, I inserted rows in my table inside the while loop. When two instances of this script run, I got the following error:

Transaction (Process ID 62) was deadlocked on lock resources with another process and has been chosen as the deadlock victim. Rerun the transaction.

Why different transactions in different connections do not wait for each other and we got a deadlock error?

In reality, I don't use while.

I just simulate high request to database (in different process) to check consistency and also check concurrency problem.

The ambiguous part of the query is why deadlock?.

One process has two action:

```<code>select from Table_1
</code>```

and

```<code>insert into Table_1
</code>```

Both of them placed in single transaction and single process.
I'm anticipate timeout, but why deadlock.

What I know about deadlock is when we have two resource and two transaction, If Transaction1 locks resource1 and in the same time Transaction2 locks resource2 and they need to lock other resource(Transaction1 locks resource2 and Transaction2 locks resource1). But both of them, can't lock second resource.

In this scenario, database engine terminates one of the transaction with deadlock exception.

Body:
I have a table Table_1 in SQL Server 2014. It has two columns name, id.

I want to run the following script in two separate connections simultaneously:

while 1 = 1
begin
begin try
    SET TRANSACTION ISOLATION LEVEL Serializable;
        begin tran

        declare @maxId int = 0
        select @maxId = MAX(Id) + 1 from [dbo].[Table_1]
        print(@maxId)

        set identity_insert [dbo].[Table_1] on
            INSERT INTO [dbo].[Table_1] (Id,[Name])
            VALUES (@maxId,'11')
        set identity_insert [dbo].[Table_1] off

commit tran
end try
begin catch

IF(@@TRANCOUNT > 0)
rollback tran

    print ( ERROR_MESSAGE())
    print ( ERROR_SEVERITY())
    print ( ERROR_STATE())

end catch

end

In this script, I inserted rows in my table inside the while loop. When two instances of this script run, I got the following error:

Transaction (Process ID 62) was deadlocked on lock resources with another process and has been chosen as the deadlock victim. Rerun the transaction.

Why different transactions in different connections do not wait for each other and we got a deadlock error?

In reality, I don't use while.

I just simulate high request to database (in different process) to check consistency and also check concurrency problem.

The ambiguous part of the query is why deadlock?.

One process has two action:

select from Table_1

and

insert into Table_1

Both of them placed in single transaction and single process.
I'm anticipate timeout, but why deadlock.

What I know about deadlock is when we have two resource and two transaction, If Transaction1 locks resource1 and in the same time Transaction2 locks resource2 and they need to lock other resource(Transaction1 locks resource2 and Transaction2 locks resource1). But both of them, can't lock second resource.

In this scenario, database engine terminates one of the transaction with deadlock exception.


问:
Can github-copilot create new classes for suggestions with the Intellij Plugin
If I create an Entity class in Intellij, and then, in that file,  "ask" co-pilot for a repostiory
Like this:

//create Repository for Book entity class
It comes up with this perfectly valid solution for a name and location(but not more)

// Path: src\main\java\dat3.library.repository\BookRepository.java

If I now open the Copilot window and press the Refresh button it comes up with a completely acceptable suggestion, extending the JpaRepository.
But when I press the "accept the  solution" button, it inserts the repository inside the Entity class file, even if the suggestion includes the correct repository package.

Am I missing something, or can Github Copilot/the Intellij-plugin really only create hints inside a single file?
If it can, any suggestion to how, will be much appreciated.


问:
How to make plotly Bar-Chart with dynamic Sqlachemy query data in Flask
I need help to make Bar-Chart which data save in Sqlachemy database.  I typed all codes and after running python or html does not give any error but Bar-Chart is not visible.  I could not find where making mistake.

python codes are as below

```<code>app.route("/mainmenu")
def mainmenu():
    if request.method == 'GET':
        knitdaily = db.session.execute("SELECT knit_date,sum([knit_XS]+[knit_S]+[knit_M]+[knit_L]+[knit_XL]+[knit_XXL])as TotalKnit FROM knitting GROUP By knit_date ORDER BY id DESC LIMIT 10")
        knitdailychart = db.session.execute("SELECT knit_date,sum([knit_XS]+[knit_S]+[knit_M]+[knit_L]+[knit_XL]+[knit_XXL])as TotalKnit FROM knitting GROUP By knit_date ORDER BY id DESC LIMIT 10")
        knitchartdata = knitdailychart.fetchall()
        df = pd.DataFrame(knitchartdata,
                            columns=["knit_date","TotalKnit"],
                            index=["a","b","c","d","e","f","g","h","j","k"])
        fig = px.bar(df, x="knit_date", y="TotalKnit", color="TotalKnit", barmode="relative")
        graphJson = json.dumps(fig, cls=plotly.utils.PlotlyJSONEncoder)

    return render_template("main.html",knitdaily=knitdaily, graphJson=graphJson)
</code>```

knitdaily query using for Table show. It is working.
Graph Jason is for Bar-Chart but shown any thing. I have 10 limit 10 record on query and I set chart index data as it.

Html Side :

```<code><div class="knitchart">
            <h6> Knit chart Viewers</h6>
            <div id='chart' class='chart'></div>
        </div>
<script src="https://cdn.plot.ly/plotly-latest.min.js"></script>
<script type='text/javascript'>
      var graphs = {{graphJSON | safe}};
          Plotly.plot("chart",graphs,{});
    </script>
</code>```

Body:
I need help to make Bar-Chart which data save in Sqlachemy database.  I typed all codes and after running python or html does not give any error but Bar-Chart is not visible.  I could not find where making mistake.

python codes are as below

app.route("/mainmenu")
def mainmenu():
    if request.method == 'GET':
        knitdaily = db.session.execute("SELECT knit_date,sum([knit_XS]+[knit_S]+[knit_M]+[knit_L]+[knit_XL]+[knit_XXL])as TotalKnit FROM knitting GROUP By knit_date ORDER BY id DESC LIMIT 10")
        knitdailychart = db.session.execute("SELECT knit_date,sum([knit_XS]+[knit_S]+[knit_M]+[knit_L]+[knit_XL]+[knit_XXL])as TotalKnit FROM knitting GROUP By knit_date ORDER BY id DESC LIMIT 10")
        knitchartdata = knitdailychart.fetchall()
        df = pd.DataFrame(knitchartdata,
                            columns=["knit_date","TotalKnit"],
                            index=["a","b","c","d","e","f","g","h","j","k"])
        fig = px.bar(df, x="knit_date", y="TotalKnit", color="TotalKnit", barmode="relative")
        graphJson = json.dumps(fig, cls=plotly.utils.PlotlyJSONEncoder)

    return render_template("main.html",knitdaily=knitdaily, graphJson=graphJson)

knitdaily query using for Table show. It is working.
Graph Jason is for Bar-Chart but shown any thing. I have 10 limit 10 record on query and I set chart index data as it.

Html Side :

 Knit chart Viewers


问:
Pyrogram multi account compose
How can I make several accounts do the same thing in pyrogram through compose with one command?</p>
```<code>import asyncio
from pyrogram import Client, compose

async def main():
    apps = [
        Client("account1"),
        Client("account2"),
        Client("account3")
    ]

    ...

    await compose(apps)

asyncio.run(main())
</code>```

Title: Pyrogram multi account compose

Body:
How can I make several accounts do the same thing in pyrogram through compose with one command?

import asyncio
from pyrogram import Client, compose

async def main():
    apps = [
        Client("account1"),
        Client("account2"),
        Client("account3")
    ]

    ...

    await compose(apps)

asyncio.run(main())


问:
Google API: Using requestAccessToken() without a popup? (Ionic/Capacitor)
I am using the following code to get a client token from Google in order to access the user's calendar. This works absolutely fine on Desktop.

However, on my Capacitor mobile app, a popup can not be opened out of the box.

So my question is: Is there possibility to authenticate my client without a popup?

```<code>    const client = google.accounts.oauth2.initTokenClient({
        client_id: '{id}',
        scope: 'https://www.googleapis.com/auth/calendar.readonly',
        redirect_uri: 'http://localhost:3000/calendar',
        callback: (tokenResponse) => {
            googleGetEvents(tokenResponse.access_token);
            return tokenResponse.access_token;
        }
    });

    client.requestAccessToken({ prompt: '' }); // prompt '' is required to avoid the consent screen
</code>```

Body:
I am using the following code to get a client token from Google in order to access the user's calendar. This works absolutely fine on Desktop.

However, on my Capacitor mobile app, a popup can not be opened out of the box.

So my question is: Is there possibility to authenticate my client without a popup?

    const client = google.accounts.oauth2.initTokenClient({
        client_id: '{id}',
        scope: 'https://www.googleapis.com/auth/calendar.readonly',
        redirect_uri: 'http://localhost:3000/calendar',
        callback: (tokenResponse) => {
            googleGetEvents(tokenResponse.access_token);
            return tokenResponse.access_token;
        }
    });

    client.requestAccessToken({ prompt: '' }); // prompt '' is required to avoid the consent screen


问:
How to limit the number of parallel plugin execution in rollup
When putting multiple plugins with a hook that is parallel, rolllup will execute all of them in parallel at the same time. No metter the number of plugins. This could lead to an heavy load on the machine.

Therefore, I wonder if there is a way to configure rollup to limit the number of parallel plugins executed during the processing of a given hook ?

All plugins will be executed in the end, and the order still does not matter, but no more than the configured amount would be executed in parallel, others would be queued to be executed when a previous one has eneded.

I'm using rollup through vite to build a project. I have several plugins that run using the writeBundle (async, parallel) hook. Those plugins use quite a lot of ressources and my CI workers can't handle running all of them in parallel.

The list of plugins is generated by a function I have no control over. This makes workarounds like using another hook or distributing them in several hook quite tricky to do. An this is not the kind of solution i'm looking after.

Here is what my vite config looks like:

```<code>import { defineConfig } from "vite";
import { getOptimizers, getScripts } from "optimizer-vite";

export default defineConfig({
    base: "./",
    build: {
        rollupOptions: {
            input: {
                index: "./index.html",
                ...getScripts(),
            },
        },
    },
    plugins: [...getOptimizers()],
    server: {
        host: "localhost",
        headers: {
            "Access-Control-Allow-Origin": "*",
            "Access-Control-Allow-Methods": "GET, POST, PUT, DELETE, PATCH, OPTIONS",
            "Access-Control-Allow-Headers": "X-Requested-With, content-type, Authorization",
            "Cache-Control": "no-cache, no-store, must-revalidate",
        },
        open: "/",
    },
});
</code>```

I scouted the rollup and vite documentation and issues, but all I could find is a way to limit the number of file descriptors opened. I feel like this more of a rollup than a vite configuration problem but i may be wrong.

Any advice or help appreciated !

Body:
When putting multiple plugins with a hook that is parallel, rolllup will execute all of them in parallel at the same time. No metter the number of plugins. This could lead to an heavy load on the machine.

Therefore, I wonder if there is a way to configure rollup to limit the number of parallel plugins executed during the processing of a given hook ?

All plugins will be executed in the end, and the order still does not matter, but no more than the configured amount would be executed in parallel, others would be queued to be executed when a previous one has eneded.

I'm using rollup through vite to build a project. I have several plugins that run using the writeBundle (async, parallel) hook. Those plugins use quite a lot of ressources and my CI workers can't handle running all of them in parallel.

The list of plugins is generated by a function I have no control over. This makes workarounds like using another hook or distributing them in several hook quite tricky to do. An this is not the kind of solution i'm looking after.

Here is what my vite config looks like:

import { defineConfig } from "vite";
import { getOptimizers, getScripts } from "optimizer-vite";

export default defineConfig({
    base: "./",
    build: {
        rollupOptions: {
            input: {
                index: "./index.html",
                ...getScripts(),
            },
        },
    },
    plugins: [...getOptimizers()],
    server: {
        host: "localhost",
        headers: {
            "Access-Control-Allow-Origin": "*",
            "Access-Control-Allow-Methods": "GET, POST, PUT, DELETE, PATCH, OPTIONS",
            "Access-Control-Allow-Headers": "X-Requested-With, content-type, Authorization",
            "Cache-Control": "no-cache, no-store, must-revalidate",
        },
        open: "/",
    },
});

I scouted the rollup and vite documentation and issues, but all I could find is a way to limit the number of file descriptors opened. I feel like this more of a rollup than a vite configuration problem but i may be wrong.

Any advice or help appreciated !


问:
Make the number of line of an overflowing text dynamic depend on available vertical space
This my screenshot

Let's say I have a card. The card has three parts: header, body and footer (like in the picture). In the body I want to show only some amount of text from the full content and add an ellipsis at the end.

I know we can do this by using webkit-line-clamp and overflow: hidden. However, the problem with this approach is we can set the number of lines with a specific number only. When the card header's height is small, it will make the card's height shorter than other cards in the same row. I want the number of lines to dynamically fit the card's height evenly. Can I get this effect by using only CSS? If not, what is the best approach to do it?

This is my code:

```<code><!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">
    <title>Document</title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.0.0/dist/css/bootstrap.min.css">
</head>
<body>
    <style>
        /* .body-content {
            display: -webkit-box;
            overflow: hidden;
            text-overflow: ellipsis;
            -webkit-box-orient: vertical;
            -webkit-line-clamp: 4;
        } */
    </style>

    <div class="container">
        <div class="row">

            <div class="col-md-4">
                <div class="card">
                    <div class="card-body">
                        <div class="header-content mb-3">
                            <h4>This is Header Text 1 This is Header Text 1 This is Header Text 1 This is Header Text 1</h4>
                        </div>
                        <div class="body-content mb-3">
                            <p>Lorem ipsum, dolor sit amet consectetur adipisicing elit. Ducimus ex laborum repellendus esse itaque velit quam, quisquam et! Similique officiis dignissimos eligendi? Nihil quidem inventore ad minus! Aliquid, dolore laudantium.
                            </p>
                        </div>
                        <div class="footer-content">
                            <h6>This is Footer</h6>
                        </div>
                    </div>
                </div>
            </div>

            <div class="col-md-4">
                <div class="card">
                    <div class="card-body">
                        <div class="header-content mb-3">
                            <h4>This is Header Text 2 This is Header Text 2</h4>
                        </div>
                        <div class="body-content mb-3">
                            <p>Lorem ipsum, dolor sit amet consectetur adipisicing elit. Ducimus ex laborum repellendus esse itaque velit quam, quisquam et! Similique officiis dignissimos eligendi? Nihil quidem inventore ad minus! Aliquid, dolore laudantium.
                            </p>
                        </div>
                        <div class="footer-content">
                            <h6>This is Footer</h6>
                        </div>
                    </div>
                </div>
            </div>

        </div>
    </div>
</body>
</html>
</code>```

Body:
This my screenshot

Let's say I have a card. The card has three parts: header, body and footer (like in the picture). In the body I want to show only some amount of text from the full content and add an ellipsis at the end.

I know we can do this by using webkit-line-clamp and overflow: hidden. However, the problem with this approach is we can set the number of lines with a specific number only. When the card header's height is small, it will make the card's height shorter than other cards in the same row. I want the number of lines to dynamically fit the card's height evenly. Can I get this effect by using only CSS? If not, what is the best approach to do it?

This is my code:

<!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">
    <title>Document</title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.0.0/dist/css/bootstrap.min.css">

This is Header Text 1 This is Header Text 1 This is Header Text 1 This is Header Text 1

Lorem ipsum, dolor sit amet consectetur adipisicing elit. Ducimus ex laborum repellendus esse itaque velit quam, quisquam et! Similique officiis dignissimos eligendi? Nihil quidem inventore ad minus! Aliquid, dolore laudantium.

This is Footer

This is Header Text 2 This is Header Text 2

Lorem ipsum, dolor sit amet consectetur adipisicing elit. Ducimus ex laborum repellendus esse itaque velit quam, quisquam et! Similique officiis dignissimos eligendi? Nihil quidem inventore ad minus! Aliquid, dolore laudantium.

This is Footer


问:
Connecting two slider components to act as one
I'm new to React Native and I'm currently trying to make a Split functionality where the user can adjust the percentage of each person. If both the percentages add up to 100%, the slider cannot move further for any person, but can be lowered in order to increase the other persons percentage.

I'm using the react-native-slider library to achieve this.

So far I've tried the following to achieve this:

Snack Link: https://snack.expo.dev/@jay_m/delicious-chip?platform=android

Code:

```<code>import React, {useState} from 'react';
import {StyleSheet, View, Text, TouchableOpacity} from 'react-native';
import Slider from '@react-native-community/slider';

const SplitBillPage = () => {
  const [range, setRange] = useState('50%');
  const [secondRange, setSecondRange] = useState('50%');
  const [maxValue, setMaxValue] = useState('1');
  const [disable, setDisable] = useState(false);
  const [maxSecondValue, setMaxSecondValue] = useState('1');

  function rangeSetter(value) {
    setRange(parseInt(value * 100) + '%');
    let x = range;
    let y = secondRange;
    let withoutPercentage = x.replace('%', '');
    let withoutPercentageSecond = y.replace('%', '');
    if (
      parseInt(withoutPercentage) + parseInt(withoutPercentageSecond) ==
      100
    ) {
      setDisable(true);
    }
  }

  function rangeSetterSecond(value) {
    setSecondRange(parseInt(value * 100) + '%');
    let x = range;
    let y = secondRange;
    let withoutPercentage = x.replace('%', '');
    let withoutPercentageSecond = y.replace('%', '');
    if (parseInt(withoutPercentage) + parseInt(withoutPercentageSecond) < 100) {
      setDisable(false);
    } else if (
      parseInt(withoutPercentage) + parseInt(withoutPercentageSecond) ==
      100
    ) {
      setDisable(true);
    }
  }

  return (
    <View>
      <Text>{range}</Text>
      <Slider
        style={{width: 200, height: 40}}
        minimumValue={0}
        value={0.5}
        disabled={disable}
        maximumValue={1}
        minimumTrackTintColor="darkblue"
        maximumTrackTintColor="#000000"
        onValueChange={value => rangeSetter(value)}
      />
      <Text>{secondRange}</Text>
      <Slider
        style={{width: 200, height: 40}}
        minimumValue={0}
        value={0.5}
        maximumValue={1}
        minimumTrackTintColor="darkblue"
        maximumTrackTintColor="#000000"
        onValueChange={value => rangeSetterSecond(value)}
      />
    </View>
  );
};

export default SplitBillPage;

</code>```

Now there are a few problems that come with this:

Here for some reason the sliders dont work sometimes, they sometimes stop when the 2 equal to 100% but sometimes they keep going.

Here I only found a way to stop the user from adjusting the slider is by disabling it, but then that means that the user wont even be able to lower it as the slider is now disabled. Hence I only put the disable feature in the first slider so that it can be adjusted again when the second one is lowered which is not what I want.

P.S: The expo snack emulator isn't disabling the slider when it runs, but when I tried it with my systems emulator, it disables...

Body:
I'm new to React Native and I'm currently trying to make a Split functionality where the user can adjust the percentage of each person. If both the percentages add up to 100%, the slider cannot move further for any person, but can be lowered in order to increase the other persons percentage.

I'm using the react-native-slider library to achieve this.

So far I've tried the following to achieve this:

Snack Link: https://snack.expo.dev/@jay_m/delicious-chip?platform=android

Code:

import React, {useState} from 'react';
import {StyleSheet, View, Text, TouchableOpacity} from 'react-native';
import Slider from '@react-native-community/slider';

const SplitBillPage = () => {
  const [range, setRange] = useState('50%');
  const [secondRange, setSecondRange] = useState('50%');
  const [maxValue, setMaxValue] = useState('1');
  const [disable, setDisable] = useState(false);
  const [maxSecondValue, setMaxSecondValue] = useState('1');

  function rangeSetter(value) {
    setRange(parseInt(value * 100) + '%');
    let x = range;
    let y = secondRange;
    let withoutPercentage = x.replace('%', '');
    let withoutPercentageSecond = y.replace('%', '');
    if (
      parseInt(withoutPercentage) + parseInt(withoutPercentageSecond) ==
      100
    ) {
      setDisable(true);
    }
  }

  function rangeSetterSecond(value) {
    setSecondRange(parseInt(value * 100) + '%');
    let x = range;
    let y = secondRange;
    let withoutPercentage = x.replace('%', '');
    let withoutPercentageSecond = y.replace('%', '');
    if (parseInt(withoutPercentage) + parseInt(withoutPercentageSecond) < 100) {
      setDisable(false);
    } else if (
      parseInt(withoutPercentage) + parseInt(withoutPercentageSecond) ==
      100
    ) {
      setDisable(true);
    }
  }

  return (
    <View>
      <Text>{range}</Text>
      <Slider
        style={{width: 200, height: 40}}
        minimumValue={0}
        value={0.5}
        disabled={disable}
        maximumValue={1}
        minimumTrackTintColor="darkblue"
        maximumTrackTintColor="#000000"
        onValueChange={value => rangeSetter(value)}
      />
      <Text>{secondRange}</Text>
      <Slider
        style={{width: 200, height: 40}}
        minimumValue={0}
        value={0.5}
        maximumValue={1}
        minimumTrackTintColor="darkblue"
        maximumTrackTintColor="#000000"
        onValueChange={value => rangeSetterSecond(value)}
      />
    </View>
  );
};

export default SplitBillPage;

Now there are a few problems that come with this:

Here for some reason the sliders dont work sometimes, they sometimes stop when the 2 equal to 100% but sometimes they keep going.

Here I only found a way to stop the user from adjusting the slider is by disabling it, but then that means that the user wont even be able to lower it as the slider is now disabled. Hence I only put the disable feature in the first slider so that it can be adjusted again when the second one is lowered which is not what I want.

P.S: The expo snack emulator isn't disabling the slider when it runs, but when I tried it with my systems emulator, it disables...


问:
I got error message when i'm trying train my data : The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
I'm a beginner in python. I'm not able to understand what the problem is?

I tried this syntax

```<code>Malware_model.fit(X_train, y_train, validation_data = (X_test, y_test), epochs=10,  class_weight=class_weights)
</code>```

The error I'm getting is:

```<code>ValueError                                Traceback (most recent call last)
<ipython-input-114-d1528325f5ea> in <module>
----> 1 Malware_model.fit(X_train, y_train, validation_data = (X_test, y_test), epochs=10,  class_weight=class_weights)

1 frames
/usr/local/lib/python3.8/dist-packages/keras/engine/data_adapter.py in _configure_dataset_and_inferred_steps(***failed resolving arguments***)
   1177     del x
   1178     dataset = self._adapter.get_dataset()
-> 1179     if class_weight:
   1180       dataset = dataset.map(_make_class_weight_map_fn(class_weight))
   1181     self._inferred_steps = self._infer_steps(steps_per_epoch, dataset)

ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
</code>```
```<code></code>```

Body:
I'm a beginner in python. I'm not able to understand what the problem is?

I tried this syntax

Malware_model.fit(X_train, y_train, validation_data = (X_test, y_test), epochs=10,  class_weight=class_weights)

The error I'm getting is:

ValueError                                Traceback (most recent call last)
<ipython-input-114-d1528325f5ea> in <module>
----> 1 Malware_model.fit(X_train, y_train, validation_data = (X_test, y_test), epochs=10,  class_weight=class_weights)

1 frames
/usr/local/lib/python3.8/dist-packages/keras/engine/data_adapter.py in _configure_dataset_and_inferred_steps(***failed resolving arguments***)
   1177     del x
   1178     dataset = self._adapter.get_dataset()
-> 1179     if class_weight:
   1180       dataset = dataset.map(_make_class_weight_map_fn(class_weight))
   1181     self._inferred_steps = self._infer_steps(steps_per_epoch, dataset)

ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()


问:
Deployer (deployer.org) not deploying the git repository
I am using deployer (from deployer.org) to deploy Laravel and Magento 2 sites. From what I understand, it should deploy the .git folder also to a server. But for my configuration it does not do it somehow.

How can I make sure the git repository is also deployed and is available on the server after a deploy?

To make clear what the issue is, steps to reproduce (for me).

Deploy to server with deployer (dep deploy)

Login to server with SSH

Go to project directory

Typ in git status

Expected result:

```<code>app@e1a372088c46 ~/application (master)$ git status
On branch master
Your branch is up to date with 'origin/master'.

nothing to commit, working tree clean`
</code>```

Actual result

```<code>app@app:~/public_html/application$ git status
fatal: not a git repository (or any parent up to mount point /)
</code>```

Body:
I am using deployer (from deployer.org) to deploy Laravel and Magento 2 sites. From what I understand, it should deploy the .git folder also to a server. But for my configuration it does not do it somehow.

How can I make sure the git repository is also deployed and is available on the server after a deploy?

To make clear what the issue is, steps to reproduce (for me).

Deploy to server with deployer (dep deploy)

Login to server with SSH

Go to project directory

Typ in git status

Expected result:

app@e1a372088c46 ~/application (master)$ git status
On branch master
Your branch is up to date with 'origin/master'.

nothing to commit, working tree clean`

Actual result

app@app:~/public_html/application$ git status
fatal: not a git repository (or any parent up to mount point /)


问:
How to deploy django application with celery and celery beat in digitalocean droplet?
Hello developers i nedd to deploy django application with celery and celery beat in digitalocean droplet.
where celery worker and celery beat will execute simulteneoulsy.

for celery worker:

```<code>celery -A <project_name>.celery worker --pool=solo -l INFO
</code>```

for celery beat:

```<code>celery -A <project_name> beatb -l INFO
</code>```

afterward it will run.

Body:
Hello developers i nedd to deploy django application with celery and celery beat in digitalocean droplet.
where celery worker and celery beat will execute simulteneoulsy.

for celery worker:

celery -A <project_name>.celery worker --pool=solo -l INFO

for celery beat:

celery -A <project_name> beatb -l INFO

afterward it will run.


问:
How can I include the end date in np.busday_count?
By default, the function excludes the last date while calculating business days. Adding 1 is not a good idea. If the last day is a Sunday and adding 1 will give incorrect business days. Is there a parameter that handles this or a way to get business days with the last date included?</p>


问:
Gradle: Build getting failed with exception: org/gradle/ api/internal/ExternalProcessStartedListener
I am new to gradle and not able to debug the following issue whenever I am trying to build any project.
I am using the command  (gradle clean build)

FAILURE: Build failed with an exception.

What went wrong:
org/gradle/api/internal/ExternalProcessStartedListener

I am using gradle version 7.4.2

Any help is greatly appreciated.