问:
Pandas: Improving corrupted matrix via transformation stuck
```<code>import pandas as pd
import numpy as np

df_flat = pd.DataFrame({
    'dim1': ['b', 'b', 'b', 'b', 'c', 'c', 'c', 'c', 'd', 'd', 'd', 'd', 'e', 'e', 'e', 'e', 'f', 'f', 'f', 'f', 'g', 'g', 'g', 'g'],
    'dim2': ['H0', 'H1', 'H2', 'H3', 'H0', 'H1', 'H2', 'H3', 'H0', 'H1', 'H2', 'H3', 'H0', 'H1', 'H2', 'H3', 'H0', 'H1', 'H2', 'H3', 'H0', 'H1', 'H2', 'H3'],
    'val': [2, 4, 3, 3.1, 3.2, 3.3, 6, 2.1, 2.2, 4.1, 3.4, 3.5, np.nan, 6.1, 2.3, 1.2, np.nan, np.nan, 2.4, 2.5, np.nan, np.nan, np.nan, 2.5]})

new_df = df_flat.set_index(['dim1', 'dim2']).unstack()
new_df.columns = new_df.columns.droplevel(0)
</code>```

I am dealing with corrupted matrix (diagonal matrix), want to process the matrix. Matrix is to be read from right to lift for this case (as corruption is on left):

Check the value prior to corruption. For ex for row = 4,
value prior to corruption is 6.1 (in H1).
Find two closest value (in H1 column) in rows with no corruption (i.e. row 0, 1, 2).
Take average of these two rows at H0 and H1 (Add this as extra col H0_miss, H_max_miss). Similarly, for row 5, value prior to corruption is 2.4, Find two closest value (in H2 column) in rows with no corruption (i.e. row 0, 1, 2).
Take average of these two rows at H0 and H2 (Add this as extra col H0_miss, H_max_miss)

Expected Output:

```<code>df_flat = pd.DataFrame({
'dim1': ['b', 'b', 'b', 'b', 'b', 'b', 'c', 'c', 'c', 'c', 'c', 'c', 'd', 'd', 'd', 'd', 'd', 'd', 'e', 'e', 'e', 'e', 'e', 'e', 'f', 'f', 'f', 'f', 'f', 'f','g', 'g', 'g', 'g', 'g', 'g'],
'dim2': ['H0', 'H1', 'H2', 'H3', 'H0_miss', 'H_max_miss', 'H0', 'H1', 'H2', 'H3', 'H0_miss', 'H_max_miss', 'H0', 'H1', 'H2', 'H3', 'H0_miss', 'H_max_miss', 'H0', 'H1', 'H2', 'H3', 'H0_miss', 'H_max_miss', 'H0', 'H1', 'H2', 'H3', 'H0_miss', 'H_max_miss', 'H0', 'H1', 'H2', 'H3', 'H0_miss', 'H_max_miss'],
'val': [2, 4, 3, 3.1, np.nan, np.nan, 3.2, 3.3, 6, 2.1, np.nan, np.nan, 2.2, 4.1, 3.4, 3.5, np.nan, np.nan, np.nan, 6.1, 2.3, 1.2, 4.05, 2.1, np.nan, np.nan, 2.4, 2.5, 3.2, 2.1, np.nan, np.nan, np.nan, 2.5, 2.6, 2.6]})

new_df = df_flat.set_index(['dim1', 'dim2']).unstack()
new_df.columns = new_df.columns.droplevel(0)
</code>```

Approach (Stuck actually):

```<code>a = new_df.to_numpy()
m = np.isnan(a)
col = m.argmin(axis=1)
</code>```

Any way forward?

Body:
import pandas as pd
import numpy as np

df_flat = pd.DataFrame({
    'dim1': ['b', 'b', 'b', 'b', 'c', 'c', 'c', 'c', 'd', 'd', 'd', 'd', 'e', 'e', 'e', 'e', 'f', 'f', 'f', 'f', 'g', 'g', 'g', 'g'],
    'dim2': ['H0', 'H1', 'H2', 'H3', 'H0', 'H1', 'H2', 'H3', 'H0', 'H1', 'H2', 'H3', 'H0', 'H1', 'H2', 'H3', 'H0', 'H1', 'H2', 'H3', 'H0', 'H1', 'H2', 'H3'],
    'val': [2, 4, 3, 3.1, 3.2, 3.3, 6, 2.1, 2.2, 4.1, 3.4, 3.5, np.nan, 6.1, 2.3, 1.2, np.nan, np.nan, 2.4, 2.5, np.nan, np.nan, np.nan, 2.5]})

new_df = df_flat.set_index(['dim1', 'dim2']).unstack()
new_df.columns = new_df.columns.droplevel(0)

I am dealing with corrupted matrix (diagonal matrix), want to process the matrix. Matrix is to be read from right to lift for this case (as corruption is on left):

Check the value prior to corruption. For ex for row = 4,
value prior to corruption is 6.1 (in H1).
Find two closest value (in H1 column) in rows with no corruption (i.e. row 0, 1, 2).
Take average of these two rows at H0 and H1 (Add this as extra col H0_miss, H_max_miss). Similarly, for row 5, value prior to corruption is 2.4, Find two closest value (in H2 column) in rows with no corruption (i.e. row 0, 1, 2).
Take average of these two rows at H0 and H2 (Add this as extra col H0_miss, H_max_miss)

Expected Output:

df_flat = pd.DataFrame({
'dim1': ['b', 'b', 'b', 'b', 'b', 'b', 'c', 'c', 'c', 'c', 'c', 'c', 'd', 'd', 'd', 'd', 'd', 'd', 'e', 'e', 'e', 'e', 'e', 'e', 'f', 'f', 'f', 'f', 'f', 'f','g', 'g', 'g', 'g', 'g', 'g'],
'dim2': ['H0', 'H1', 'H2', 'H3', 'H0_miss', 'H_max_miss', 'H0', 'H1', 'H2', 'H3', 'H0_miss', 'H_max_miss', 'H0', 'H1', 'H2', 'H3', 'H0_miss', 'H_max_miss', 'H0', 'H1', 'H2', 'H3', 'H0_miss', 'H_max_miss', 'H0', 'H1', 'H2', 'H3', 'H0_miss', 'H_max_miss', 'H0', 'H1', 'H2', 'H3', 'H0_miss', 'H_max_miss'],
'val': [2, 4, 3, 3.1, np.nan, np.nan, 3.2, 3.3, 6, 2.1, np.nan, np.nan, 2.2, 4.1, 3.4, 3.5, np.nan, np.nan, np.nan, 6.1, 2.3, 1.2, 4.05, 2.1, np.nan, np.nan, 2.4, 2.5, 3.2, 2.1, np.nan, np.nan, np.nan, 2.5, 2.6, 2.6]})

new_df = df_flat.set_index(['dim1', 'dim2']).unstack()
new_df.columns = new_df.columns.droplevel(0)

Approach (Stuck actually):

a = new_df.to_numpy()
m = np.isnan(a)
col = m.argmin(axis=1)

Any way forward?


来源: stackexchange

问:
The LINQ expression node type 'Invoke' is not supported in LINQ to Entities
I have written a query that works fine when I use ToList() at the end of query before calling the predicate, but it throws an exception when I don't use ToList().

I don't want to use ToList() until the complete query is executed on the DB server otherwise, it will fetch thousands of records to memory, so I need to call the predicate once the complete query is executed.

Here is My Query without ToList() :

```<code>var myquery = (from p in se.CompanyRepresentatives
                             join qr in questionnaires on p.ID equals qr.RespondentID

                             join ra in se.Responses on qr.ID equals ra.QuestionnaireResponseID into raGroup
                             from res in raGroup.Where(r=> r.QuestionID == 1 || r.QuestionID == 2 || r.QuestionID == 3).DefaultIfEmpty(null)

                             where
                            qr.QuestionnaireID == SurveyEntities.PROJECT_QUESTIONNAIRE_ID
                             select new ResultViewModel
                             {
                                 CompRep = p,
                                 QuestionnaireRes = qr,
                                 Res = raGroup.FirstOrDefault(x =>   x.QuestionID == 1),
                                 ProjectDeliverable = raGroup.FirstOrDefault(x =>   x.QuestionID == 2).Answer,
                                 ProjectDescription = raGroup.FirstOrDefault(x =>  x.QuestionID == 3).Answer,

                             });

    query= myquery.Where(ContainsAny(projectNamelist));
</code>```

Here at the following line it throws the exception mentioned in title:

```<code>var nquery = query.ToList();
</code>```

Here is my predicate builder :

```<code>static Expression<Func<ResultViewModel, bool>> ContainsAny(List<string> filters)
        {

            var predicate = PredicateBuilder.True<ResultViewModel>();
            foreach (var filter in filters)
            {
                string newfilter = filter.ToLower();
                predicate = predicate.And(cprep=> cprep.CompRep.CompanyName != null && cprep.CompRep.CompanyName.ToLower().Contains(newfilter)
                                            || ( cprep.CompRep.Email != null && cprep.CompRep.Email.ToLower().Contains(newfilter.ToLower()))
                                            || (  cprep.CompRep.FirstName != null && cprep.CompRep.FirstName.ToLower().Contains(newfilter.ToLower()))
                                            || (cprep.Res.Answer != null && cprep.Res.Answer.ToLower().Contains(newfilter.ToLower()))
                                            || (cprep.CompRep.CompanyDescription != null && cprep.CompRep.CompanyDescription.ToLower().Contains(newfilter.ToLower())));
            }
            return predicate;
        }
</code>```

Here is PredicateBuilder:

```<code>public static class PredicateBuilder
    {
        public static Expression<Func<T, bool>> True<T>() { return f => true; }
        public static Expression<Func<T, bool>> False<T>() { return f => false; }

        public static Expression<Func<T, bool>> Or<T>(this Expression<Func<T, bool>> expr1,
                                                            Expression<Func<T, bool>> expr2)
        {
            var invokedExpr = Expression.Invoke(expr2, expr1.Parameters.Cast<Expression>());
            return Expression.Lambda<Func<T, bool>>
                  (Expression.OrElse(expr1.Body, invokedExpr), expr1.Parameters);
        }

        public static Expression<Func<T, bool>> And<T>(this Expression<Func<T, bool>> expr1,
                                                             Expression<Func<T, bool>> expr2)
        {
            var invokedExpr = Expression.Invoke(expr2, expr1.Parameters.Cast<Expression>());
            return Expression.Lambda<Func<T, bool>>
                  (Expression.AndAlso(expr1.Body, invokedExpr), expr1.Parameters);
        }
    }
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have written a query that works fine when I use ToList() at the end of query before calling the predicate, but it throws an exception when I don't use ToList().

I don't want to use ToList() until the complete query is executed on the DB server otherwise, it will fetch thousands of records to memory, so I need to call the predicate once the complete query is executed.

Here is My Query without ToList() :

var myquery = (from p in se.CompanyRepresentatives
                             join qr in questionnaires on p.ID equals qr.RespondentID

                             join ra in se.Responses on qr.ID equals ra.QuestionnaireResponseID into raGroup
                             from res in raGroup.Where(r=> r.QuestionID == 1 || r.QuestionID == 2 || r.QuestionID == 3).DefaultIfEmpty(null)

                             where
                            qr.QuestionnaireID == SurveyEntities.PROJECT_QUESTIONNAIRE_ID
                             select new ResultViewModel
                             {
                                 CompRep = p,
                                 QuestionnaireRes = qr,
                                 Res = raGroup.FirstOrDefault(x =>   x.QuestionID == 1),
                                 ProjectDeliverable = raGroup.FirstOrDefault(x =>   x.QuestionID == 2).Answer,
                                 ProjectDescription = raGroup.FirstOrDefault(x =>  x.QuestionID == 3).Answer,

                             });

    query= myquery.Where(ContainsAny(projectNamelist));

Here at the following line it throws the exception mentioned in title:

var nquery = query.ToList();

Here is my predicate builder :

static Expression<Func<ResultViewModel, bool>> ContainsAny(List<string> filters)
        {

            var predicate = PredicateBuilder.True<ResultViewModel>();
            foreach (var filter in filters)
            {
                string newfilter = filter.ToLower();
                predicate = predicate.And(cprep=> cprep.CompRep.CompanyName != null && cprep.CompRep.CompanyName.ToLower().Contains(newfilter)
                                            || ( cprep.CompRep.Email != null && cprep.CompRep.Email.ToLower().Contains(newfilter.ToLower()))
                                            || (  cprep.CompRep.FirstName != null && cprep.CompRep.FirstName.ToLower().Contains(newfilter.ToLower()))
                                            || (cprep.Res.Answer != null && cprep.Res.Answer.ToLower().Contains(newfilter.ToLower()))
                                            || (cprep.CompRep.CompanyDescription != null && cprep.CompRep.CompanyDescription.ToLower().Contains(newfilter.ToLower())));
            }
            return predicate;
        }

Here is PredicateBuilder:

public static class PredicateBuilder
    {
        public static Expression<Func<T, bool>> True<T>() { return f => true; }
        public static Expression<Func<T, bool>> False<T>() { return f => false; }

        public static Expression<Func<T, bool>> Or<T>(this Expression<Func<T, bool>> expr1,
                                                            Expression<Func<T, bool>> expr2)
        {
            var invokedExpr = Expression.Invoke(expr2, expr1.Parameters.Cast<Expression>());
            return Expression.Lambda<Func<T, bool>>
                  (Expression.OrElse(expr1.Body, invokedExpr), expr1.Parameters);
        }

        public static Expression<Func<T, bool>> And<T>(this Expression<Func<T, bool>> expr1,
                                                             Expression<Func<T, bool>> expr2)
        {
            var invokedExpr = Expression.Invoke(expr2, expr1.Parameters.Cast<Expression>());
            return Expression.Lambda<Func<T, bool>>
                  (Expression.AndAlso(expr1.Body, invokedExpr), expr1.Parameters);
        }
    }


问:
Proxy error: Could not proxy request /auth/register from localhost:3003 to http://127.0.0.1:8800/api/ (ECONNREFUSED)
I watched video tutorials on youtube. https://youtu.be/0aPLk2e2Z3g and I got problems and http://localhost:3003/auth/register 500 (Internal Server Error) problem I don't know if this is the same problem or not.

I'm trying to change the proxy localhost to 127.0.0.1

I think my problem is with registering past

I stuck with this problem for 5 hours.

this is my controller auth.js

```<code>import { db } from "../db.js";
import bcrypt from "bcryptjs";
import jwt from "jsonwebtoken";

export const register = (req, res) => {
  //CHECK EXISTING USER
  const q = "SELECT * FROM users WHERE email = ? OR username = ?";

  db.query(q, [req.body.email, req.body.username], (err, data) => {
    if (err) return res.status(500).json(err);
    if (data.length) return res.status(409).json("User already exists!");

    //Hash the password and create a user
    const salt = bcrypt.genSaltSync(10);
    const hash = bcrypt.hashSync(req.body.password, salt);

    const q = "INSERT INTO users(`username`,`email`,`password`) VALUES (?)";
    const values = [req.body.username, req.body.email, hash];

    db.query(q, [values], (err, data) => {
      if (err) return res.status(500).json(err);
      return res.status(200).json("User has been created.");
    });
  });
};

export const login = (req, res) => {
  //CHECK USER

  const q = "SELECT * FROM users WHERE username = ?";

  db.query(q, [req.body.username], (err, data) => {
    if (err) return res.status(550).json(err);
    if (data.length === 0) return res.status(404).json("User not found!");

    //Check password
    const isPasswordCorrect = bcrypt.compareSync(
      req.body.password,
      data[0].password
    );

    if (!isPasswordCorrect)
      return res.status(400).json("Wrong username or password!");

    const token = jwt.sign({ id: data[0].id }, "jwtkey");
    const { password, ...other } = data[0];

    res
      .cookie("access_token", token, {
        httpOnly: true,
      })
      .status(200)
      .json(other);
  });
};

export const logout = (req, res) => {
  res.clearCookie("access_token",{
    sameSite:"none",
    secure:true
  }).status(200).json("User has been logged out.")
};
</code>```

and register.jsx

```<code>import React from "react";
import { useState } from "react";
import { Link, useNavigate } from "react-router-dom";
import axios from "axios";

const Register = () => {
  const [inputs, setInputs] = useState({
    username: "",
    email: "",
    password: "",
  });
  const [err, setError] = useState(null);

  const navigate = useNavigate();

  const handleChange = (e) => {
    setInputs((prev) => ({ ...prev, [e.target.name]: e.target.value }));
  };

  const handleSubmit = async (e) => {
    e.preventDefault();
    try {
      await axios.post(`/auth/register`, inputs);
      navigate("/login");
    } catch (err) {
      setError(err.response.data);
    }
  };

  return (
    <div className="auth">
      <h1>Register</h1>
      <form>
        <input
          required
          type="text"
          placeholder="username"
          name="username"
          onChange={handleChange}
        />
        <input
          required
          type="email"
          placeholder="email"
          name="email"
          onChange={handleChange}
        />
        <input
          required
          type="password"
          placeholder="password"
          name="password"
          onChange={handleChange}
        />
        <button onClick={handleSubmit}>Register</button>
        {err && <p>{err}</p>}
        <span>
          Do you have an account? <Link to="/login">Login</Link>
        </span>
      </form>
    </div>
  );
};

export default Register;
</code>```

my localhost

```<code>    "proxy": "http://localhost:8800/api/"
</code>```

I'm making a face Sign up and see if your data is saved. But it has this problem. I've tried checking both video clips and looking for solutions from other sources but still can't help.

Body:
I watched video tutorials on youtube. https://youtu.be/0aPLk2e2Z3g and I got problems and http://localhost:3003/auth/register 500 (Internal Server Error) problem I don't know if this is the same problem or not.

I'm trying to change the proxy localhost to 127.0.0.1

I think my problem is with registering past

I stuck with this problem for 5 hours.

this is my controller auth.js

import { db } from "../db.js";
import bcrypt from "bcryptjs";
import jwt from "jsonwebtoken";

export const register = (req, res) => {
  //CHECK EXISTING USER
  const q = "SELECT * FROM users WHERE email = ? OR username = ?";

  db.query(q, [req.body.email, req.body.username], (err, data) => {
    if (err) return res.status(500).json(err);
    if (data.length) return res.status(409).json("User already exists!");

    //Hash the password and create a user
    const salt = bcrypt.genSaltSync(10);
    const hash = bcrypt.hashSync(req.body.password, salt);

    const q = "INSERT INTO users(`username`,`email`,`password`) VALUES (?)";
    const values = [req.body.username, req.body.email, hash];

    db.query(q, [values], (err, data) => {
      if (err) return res.status(500).json(err);
      return res.status(200).json("User has been created.");
    });
  });
};

export const login = (req, res) => {
  //CHECK USER

  const q = "SELECT * FROM users WHERE username = ?";

  db.query(q, [req.body.username], (err, data) => {
    if (err) return res.status(550).json(err);
    if (data.length === 0) return res.status(404).json("User not found!");

    //Check password
    const isPasswordCorrect = bcrypt.compareSync(
      req.body.password,
      data[0].password
    );

    if (!isPasswordCorrect)
      return res.status(400).json("Wrong username or password!");

    const token = jwt.sign({ id: data[0].id }, "jwtkey");
    const { password, ...other } = data[0];

    res
      .cookie("access_token", token, {
        httpOnly: true,
      })
      .status(200)
      .json(other);
  });
};

export const logout = (req, res) => {
  res.clearCookie("access_token",{
    sameSite:"none",
    secure:true
  }).status(200).json("User has been logged out.")
};

and register.jsx

import React from "react";
import { useState } from "react";
import { Link, useNavigate } from "react-router-dom";
import axios from "axios";

const Register = () => {
  const [inputs, setInputs] = useState({
    username: "",
    email: "",
    password: "",
  });
  const [err, setError] = useState(null);

  const navigate = useNavigate();

  const handleChange = (e) => {
    setInputs((prev) => ({ ...prev, [e.target.name]: e.target.value }));
  };

  const handleSubmit = async (e) => {
    e.preventDefault();
    try {
      await axios.post(`/auth/register`, inputs);
      navigate("/login");
    } catch (err) {
      setError(err.response.data);
    }
  };

  return (

Register

      <form>
        <input
          required
          type="text"
          placeholder="username"
          name="username"
          onChange={handleChange}
        />
        <input
          required
          type="email"
          placeholder="email"
          name="email"
          onChange={handleChange}
        />
        <input
          required
          type="password"
          placeholder="password"
          name="password"
          onChange={handleChange}
        />
        <button onClick={handleSubmit}>Register</button>
        {err &&
{err}
}

          Do you have an account? <Link to="/login">Login</Link>

      </form>

  );
};

export default Register;

my localhost

    "proxy": "http://localhost:8800/api/"

I'm making a face Sign up and see if your data is saved. But it has this problem. I've tried checking both video clips and looking for solutions from other sources but still can't help.


Title: lexical analyser recognise numbers

Body:
i'm trying to make a small lexical analyser that recognizes numbers as it is in the following regular expression:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>

char C[500];
bool temp;

bool Q0(char k[]);
bool Q1(char k[]);
bool Q2(char k[]);
bool Q3(char k[]);

void substr (char C[]);
char nextchar(char C[]);

int main()
{
    printf("enter a string: ");
    scanf("%s",C);

    temp=Q0(C);

    if (temp==true)
    {
        printf("it's number");
    }
    else
    {
        printf("false");
    }
    return 0;
}

bool Q0(char k[])
{
    printf("%s\n",k);
    printf("%c\n",k[0]);
    if (k[0]=='+'||k[0]=='-')
    {
        return Q1(nextchar(k));
    }
    else if (k[0]=='0'||k[0]=='1'||k[0]=='2'||k[0]=='3'||k[0]=='4'||k[0]=='5'||k[0]=='6'||k[0]=='7'||k[0]=='8'||k[0]=='9')
        {
            return Q1(nextchar(k));
        }
    else
        {
            return false;
        }

}

bool Q1(char k[])

{
    if (k[0]=='0'||k[0]=='1'||k[0]=='2'||k[0]=='3'||k[0]=='4'||k[0]=='5'||k[0]=='6'||k[0]=='7'||k[0]=='8'||k[0]=='9')
    {
        return Q1(nextchar(k));
    }
    else if (k[0]=='.')
        {
            return Q2(nextchar(k));
        }
    else if (k[0]=='\0')
            {
                return true;
            }
    else
            {
                return false;
            }

        }

bool Q2(char k[])
{
    if (k[0]=='0'||k[0]=='1'||k[0]=='2'||k[0]=='3'||k[0]=='4'||k[0]=='5'||k[0]=='6'||k[0]=='7'||k[0]=='8'||k[0]=='9')
    {
        return Q2(nextchar(k));
    }
    else if (k[0]=='e'||k[0]=='E')
        {
            return Q3(nextchar(k));
        }
    else
        {
            return false;
        }
    }

bool Q3(char k[])
{
    if (k[0]=='+'||k[0]=='-')
    {
        return Q3(nextchar(k));
    }
    else if (k[0]=='0'||k[0]=='1'||k[0]=='2'||k[0]=='3'||k[0]=='4'||k[0]=='5'||k[0]=='6'||k[0]=='7'||k[0]=='8'||k[0]=='9')
        {
            return Q3(nextchar(k));
        }
    else if (k[0]=='\0')
            {
                return true;
            }
    else
            {
                return false;
            }

        }
void substr (char *C)
{
    (C)++;
}
char nextchar(char *C){
    substr(C);
    return  C[0];
}

why the code execute else section in the Q0 function ?
in the result k[0] equals 5 and it should execute the else if(k[0] == ...'5'...)
and go to the next state Q1
also i got lot of warnings about type casting and passing parameters but i can't understand why
PS: i printed the whole string and the first letter of it in order to make sure that there isn't a problem with the array


问:
Minimum requested sequence is X but orderer is at sequence x ERROR
We started to experience the following error, seemingly out of the blue, everything was working fine (or appear to be) until one the orderers appear to get out of sync and isn't able to connect with other components:

```<code>DEBU [common.deliver] deliverBlocks - [channel: mychannel] Delivering block [35151] for (0xc00bcf2b40) for 10.0.1.37:60946","stream":"stderr","time":"2022-12-14T21:02:21.383441052Z"
DEBU [blkstorage] waitForBlock - Going to wait for newer blocks. maxAvailaBlockNumber=[35151], waitForBlockNum=[35152]","stream":"stderr","time":"2022-12-14T21:02:21.383483616Z"
INFO [orderer.common.cluster.puller] fetchLastBlockSeq - Skipping pulling from orderer.example.com:7050: minimum requested sequence is 35152 but orderer.example.com:7050 is at sequence 35151 channel=mychannel","stream":"stderr","time":"2022-12-14T21:02:21.383715084Z"
[grpc] InfoDepth - DEBU 1627e [core]Channel Connectivity change to SHUTDOWN","stream":"stderr","time":"2022-12-14T21:02:21.383722749Z"
[grpc] InfoDepth - DEBU 1627f [core]Subchannel Connectivity change to SHUTDOWN","stream":"stderr","time":"2022-12-14T21:02:21.383744556Z"
WARN [orderer.common.cluster.puller] func1 - Received error of type 'minimum requested sequence is 35152 but orderer.example.com:7050 is at sequence 35151' from orderer.example.com:7050 channel=mychannel","stream":"stderr","time":"2022-12-14T21:02:21.383757632Z"
[grpc] InfoDepth - DEBU 16280 [transport]transport: loopyWriter.run returning. connection error: desc = \"transport is closing\"","stream":"stderr","time":"2022-12-14T21:02:21.383792554Z"
</code>```

We've tried to recreate the world state a couple of times and it works OK until a certain point, usually at block 35152.

The HL Fabric network is composed of three orgs running on docker-swarm, each ORG on a different VM.

Any ideas?

Body:
We started to experience the following error, seemingly out of the blue, everything was working fine (or appear to be) until one the orderers appear to get out of sync and isn't able to connect with other components:

DEBU [common.deliver] deliverBlocks - [channel: mychannel] Delivering block [35151] for (0xc00bcf2b40) for 10.0.1.37:60946","stream":"stderr","time":"2022-12-14T21:02:21.383441052Z"
DEBU [blkstorage] waitForBlock - Going to wait for newer blocks. maxAvailaBlockNumber=[35151], waitForBlockNum=[35152]","stream":"stderr","time":"2022-12-14T21:02:21.383483616Z"
INFO [orderer.common.cluster.puller] fetchLastBlockSeq - Skipping pulling from orderer.example.com:7050: minimum requested sequence is 35152 but orderer.example.com:7050 is at sequence 35151 channel=mychannel","stream":"stderr","time":"2022-12-14T21:02:21.383715084Z"
[grpc] InfoDepth - DEBU 1627e [core]Channel Connectivity change to SHUTDOWN","stream":"stderr","time":"2022-12-14T21:02:21.383722749Z"
[grpc] InfoDepth - DEBU 1627f [core]Subchannel Connectivity change to SHUTDOWN","stream":"stderr","time":"2022-12-14T21:02:21.383744556Z"
WARN [orderer.common.cluster.puller] func1 - Received error of type 'minimum requested sequence is 35152 but orderer.example.com:7050 is at sequence 35151' from orderer.example.com:7050 channel=mychannel","stream":"stderr","time":"2022-12-14T21:02:21.383757632Z"
[grpc] InfoDepth - DEBU 16280 [transport]transport: loopyWriter.run returning. connection error: desc = \"transport is closing\"","stream":"stderr","time":"2022-12-14T21:02:21.383792554Z"

We've tried to recreate the world state a couple of times and it works OK until a certain point, usually at block 35152.

The HL Fabric network is composed of three orgs running on docker-swarm, each ORG on a different VM.

Any ideas?


问:
Show integer numbers on textbox in Flash AS2
I'm making a game and I need a text box to show only whole numbers, such as "999" and not "999.58". This is messing up the image because it's too big and it's outside the text box and there's also no need for the player to see the decimals. I'm using the simple call (this.text1:Number=_root.text2) but '_root.text2' has decimal and that's what I want to remove. Thanks in advance.</p>


问:
Exclude classes from JaCoCo coverage report on multiple levels
I have a multi-module gradle project configured with convention plugins. I'd like to be able to exclude classes from the code coverage report both in the convention plugin and in the module level build script.

Here are the relevant files from the project:

buildSrc/src/main/kotlin/mapstruct-conventions.gradle.kts

```<code>// ...other configurations here

tasks.jacocoTestReport {
    classDirectories.setFrom(
        files(
            classDirectories.files.map {
                fileTree(it).apply {
                    exclude("**/*MapperImpl*")
                }
            }
        )
    )
}
</code>```

database-jooq/build.gradle.kts

```<code>plugins {
    id("mapstruct-conventions")
}

tasks.jacocoTestReport {
    classDirectories.setFrom(
        files(
            classDirectories.files.map {
                fileTree(it).apply {
                    exclude("**/jooq/generated/**")
                }
            }
        )
    )
}
</code>```

For some reason the two exclusions seem to override each other. If both are present, then only the one in the convention plugin will be applied. If I remove the exclusion from the convention plugin script, then the exclusion in the database-jooq module works fine.

I tried to define them in an afterEvaluate block as suggested in some answers but I get the following exception:

```<code>Caused by: org.gradle.api.internal.AbstractMutationGuard$IllegalMutationException: Project#afterEvaluate(Action) on project ':database-jooq' cannot be executed in the current context.
</code>```

Is there a way to define JaCoCo exclusions in different places and apply them together?

Body:
I have a multi-module gradle project configured with convention plugins. I'd like to be able to exclude classes from the code coverage report both in the convention plugin and in the module level build script.

Here are the relevant files from the project:

buildSrc/src/main/kotlin/mapstruct-conventions.gradle.kts

// ...other configurations here

tasks.jacocoTestReport {
    classDirectories.setFrom(
        files(
            classDirectories.files.map {
                fileTree(it).apply {
                    exclude("**/*MapperImpl*")
                }
            }
        )
    )
}

database-jooq/build.gradle.kts

plugins {
    id("mapstruct-conventions")
}

tasks.jacocoTestReport {
    classDirectories.setFrom(
        files(
            classDirectories.files.map {
                fileTree(it).apply {
                    exclude("**/jooq/generated/**")
                }
            }
        )
    )
}

For some reason the two exclusions seem to override each other. If both are present, then only the one in the convention plugin will be applied. If I remove the exclusion from the convention plugin script, then the exclusion in the database-jooq module works fine.

I tried to define them in an afterEvaluate block as suggested in some answers but I get the following exception:

Caused by: org.gradle.api.internal.AbstractMutationGuard$IllegalMutationException: Project#afterEvaluate(Action) on project ':database-jooq' cannot be executed in the current context.

Is there a way to define JaCoCo exclusions in different places and apply them together?


问:
Reassembling chunks of a binary file in Perl in a multithreaded script
I'm trying to break a binary file into chunks for a multipart upload and then have them reassembled correctly. I'm using threads to try to speed up transfers. The result hasn't validated using md5sum so I decided to try to just to reassemble it locally and see what happens. The local result comes out ok with a small text file, but not a large binary file, when multithreaded. It works either way when single threaded.

Here's a simple (admittedly inefficient) implementation of a single threaded version that works:

```<code>use strict;
use POSIX;

my $file = 'test.txt';
my $chunkSize = 3;
my $size = -s $file;
my $parts = ceil($size / $chunkSize);

my %output;
open(my $fileHandle, '<', $file) or die("Error reading file, stopped");
binmode($fileHandle);

for (my $i = 0; $i < $parts; $i++) {
    my $chunk;
    my $offset = $i * $chunkSize;

    seek ($fileHandle, $offset, 0);

    if ($chunkSize > $size) {
        $chunkSize = $size;
    }
    elsif (($chunkSize + $offset) > $size) {
        $chunkSize = $size - $offset;
    }

    my $length = read($fileHandle, $chunk, $chunkSize);
    say STDERR "Chunk size for $i: " . $chunkSize . "(" . ($chunkSize + $offset) . "/$size) starting at " . $offset .": ";# . $chunk;

    $output{ $i } = $chunk;
}

close($fileHandle);

open(my $fileHandle, '>', $file . '.comp') or die("Error reading file, stopped");
binmode($fileHandle);

for (1...$parts) {
    print $fileHandle $output{ $_ };
}

close ($fileHandle);
</code>```

Here's the multithreaded version that does not:

```<code>use strict;
use POSIX;
use threads;
use threads::shared;
use Thread::Queue;

my $file = '/backup/2022-12-13/accounts/test.tar.gz';

my $chunkSize = 500 * 1024 * 1024;
#Or my $chunkSize = 3; when using it with the smaller text test file.
my $size = -s $file;
my $parts = ceil($size / $chunkSize);

my %output :shared;

my @queueData;
for (0...$parts) { push (@queueData, $_); }

my $overallProgress :shared;
my $queue = Thread::Queue->new(@queueData);

open(my $fileHandle, '<', $file) or die("Error reading file, stopped");
binmode($fileHandle);

my @threads;
for(1..4) {
    push @threads, threads->create( sub {

        while( my $i = $queue->dequeue_nb ) {
            my $chunk;
            my $offset = ($i - 1) * $chunkSize;

            seek ($fileHandle, $offset, 0);

            if ($chunkSize > $size) {
                $chunkSize = $size;
            }
            elsif (($chunkSize + $offset) > $size) {
                $chunkSize = $size - $offset;
            }

            my $length = read($fileHandle, $chunk, $chunkSize);
            say STDERR "Chunk size for $i: " . $chunkSize . "(" . ($chunkSize + $offset) . "/$size) starting at " . $offset .": ";

            $output{ $i } = $chunk;
        }
    });
}

$_->join for @threads;
close($fileHandle);

open(my $fileHandle, '>', $file . '.comp') or die("Error reading file, stopped");
binmode($fileHandle);

for (1...$parts) {
    print "Reassembling part $_...";
    print $fileHandle $output{ $_ };
}

close ($fileHandle);
</code>```

If I run that code on this simple text file, it works:

```<code>1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ
</code>```

Result of md5sum on both source and destination file:

```<code>6d8d0b2c6a06f88e13167fffacb1b74e  /home/tbutler/text.txt
6d8d0b2c6a06f88e13167fffacb1b74e  /home/tbutler/text.txt.comp
</code>```

But, if I take a 9 GB tarball (and increase the chunk size to 500 MB by changing the appropriate line to my $chunkSize = 500 * 1024 * 1024) and run it likewise, the md5sum result is not matching. In fact the resultant file is approximately a gigabyte smaller than the original file and I can't figure out why.

Body:
I'm trying to break a binary file into chunks for a multipart upload and then have them reassembled correctly. I'm using threads to try to speed up transfers. The result hasn't validated using md5sum so I decided to try to just to reassemble it locally and see what happens. The local result comes out ok with a small text file, but not a large binary file, when multithreaded. It works either way when single threaded.

Here's a simple (admittedly inefficient) implementation of a single threaded version that works:

use strict;
use POSIX;

my $file = 'test.txt';
my $chunkSize = 3;
my $size = -s $file;
my $parts = ceil($size / $chunkSize);

my %output;
open(my $fileHandle, '<', $file) or die("Error reading file, stopped");
binmode($fileHandle);

for (my $i = 0; $i < $parts; $i++) {
    my $chunk;
    my $offset = $i * $chunkSize;

    seek ($fileHandle, $offset, 0);

    if ($chunkSize > $size) {
        $chunkSize = $size;
    }
    elsif (($chunkSize + $offset) > $size) {
        $chunkSize = $size - $offset;
    }

    my $length = read($fileHandle, $chunk, $chunkSize);
    say STDERR "Chunk size for $i: " . $chunkSize . "(" . ($chunkSize + $offset) . "/$size) starting at " . $offset .": ";# . $chunk;

    $output{ $i } = $chunk;
}

close($fileHandle);

open(my $fileHandle, '>', $file . '.comp') or die("Error reading file, stopped");
binmode($fileHandle);

for (1...$parts) {
    print $fileHandle $output{ $_ };
}

close ($fileHandle);

Here's the multithreaded version that does not:

use strict;
use POSIX;
use threads;
use threads::shared;
use Thread::Queue;

my $file = '/backup/2022-12-13/accounts/test.tar.gz';

my $chunkSize = 500 * 1024 * 1024;
#Or my $chunkSize = 3; when using it with the smaller text test file.
my $size = -s $file;
my $parts = ceil($size / $chunkSize);

my %output :shared;

my @queueData;
for (0...$parts) { push (@queueData, $_); }

my $overallProgress :shared;
my $queue = Thread::Queue->new(@queueData);

open(my $fileHandle, '<', $file) or die("Error reading file, stopped");
binmode($fileHandle);

my @threads;
for(1..4) {
    push @threads, threads->create( sub {

        while( my $i = $queue->dequeue_nb ) {
            my $chunk;
            my $offset = ($i - 1) * $chunkSize;

            seek ($fileHandle, $offset, 0);

            if ($chunkSize > $size) {
                $chunkSize = $size;
            }
            elsif (($chunkSize + $offset) > $size) {
                $chunkSize = $size - $offset;
            }

            my $length = read($fileHandle, $chunk, $chunkSize);
            say STDERR "Chunk size for $i: " . $chunkSize . "(" . ($chunkSize + $offset) . "/$size) starting at " . $offset .": ";

            $output{ $i } = $chunk;
        }
    });
}

$_->join for @threads;
close($fileHandle);

open(my $fileHandle, '>', $file . '.comp') or die("Error reading file, stopped");
binmode($fileHandle);

for (1...$parts) {
    print "Reassembling part $_...";
    print $fileHandle $output{ $_ };
}

close ($fileHandle);

If I run that code on this simple text file, it works:

1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ

Result of md5sum on both source and destination file:

6d8d0b2c6a06f88e13167fffacb1b74e  /home/tbutler/text.txt
6d8d0b2c6a06f88e13167fffacb1b74e  /home/tbutler/text.txt.comp

But, if I take a 9 GB tarball (and increase the chunk size to 500 MB by changing the appropriate line to my $chunkSize = 500 * 1024 * 1024) and run it likewise, the md5sum result is not matching. In fact the resultant file is approximately a gigabyte smaller than the original file and I can't figure out why.


问:
ApexChart Vuetify 2 TypeScript Support Composition API
Hello guys I have a project on Vue 2 TypeScript supported and I want to use ApexChart for showing my charts. But In documentation i see only JavaScript implementation and i tried to modify for typescript somehow i did not achieve this.

Here is the console error

My charts is not shown on the browser unfortunately.

This is what i have done in my project:

```<code><template>
  <v-card dense elevation="1">
    <v-card-title>
      <v-icon size="32" class="ml-0" color="#000000">mdi-chart-line</v-icon>
      <h4 class="pl-4">
        {{ $tc("dashboardPage.nonEarlyRetirementComponent.title", 2) }}
      </h4>
    </v-card-title>
    <v-card-subtitle>
      <p class="text-subtitle-2 pl-12">
        {{ $t("dashboardPage.shareValue") }}
      </p>
    </v-card-subtitle>
    <v-card-text>
      <LineChartNonEarly
        type="line"
        height="250"
        :options="chartOptions"
        :series="series"
      ></LineChartNonEarly>
    </v-card-text>
    <v-card-actions>
      <v-row no-gutters align="end">
        <v-row no-gutters class="ml-5 mb-8" align="center">
          <div class="pa-2 yellow darken-1 rounded-circle"></div>
          <div class="pl-4 text-subtitle-1">
            {{ $t("nonEarlyRetirement") }}
          </div>
        </v-row>
        <v-col cols="6">
          <v-list dense>
            <v-list-item>
              <v-list-item-content>
                <p class="text-subtitle-1">{{ $tc("value", 1) }} in €</p>
              </v-list-item-content>
              <v-list-item-action>
                <p class="text-subtitle-1">
                  {{ $t("dashboardPage.valueIncreased") }}
                </p>
              </v-list-item-action>
            </v-list-item>
            <v-list-item>
              <v-list-item-content>
                <p class="text-subtitle-1 font-weight-bold">
                  {{ $n(480032, "currency") }}
                </p>
              </v-list-item-content>
              <v-list-item-action>
                <v-row>
                  <p class="green--text pr-2 mt-5">
                    {{ $n(0.038, "percent") }}
                  </p>
                  <v-icon :size="25" :color="'#4BC35E'"
                    >mdi-arrow-top-right-thin-circle-outline</v-icon
                  >
                </v-row>
              </v-list-item-action>
            </v-list-item>
          </v-list>
        </v-col>
      </v-row>
    </v-card-actions>
  </v-card>
</template>
<script lang="ts" setup>
import { defineComponent, defineProps } from "vue";
import LineChartNonEarly from "vue-apexcharts";

defineComponent({
  LineChartNonEarly,
});
defineProps({
      series:[
        {
          name: "Non-early retirement",
          data: [48.5, 48, 48.9, 49.5, 50.7, 51.9],
        },
      ],
      chartOptions: {
        chart: {
          autoScaleYaxis: true,
          height: 350,
          type: "line",
          zoom: {
            enabled: false,
          },
        },

        stroke: {
          color: "#FF0000",
          width: [5, 7, 5],
          curve: "straight",
          dashArray: [0, 8, 5],
        },
        title: {
          text: "Page Statistics",
          align: "left",
        },
        colors: ["#4B77C3"],
        markers: {
          size: 7,
          hover: {
            sizeOffset: 6,
          },
        },
        xaxis: {
          categories: [
            "May 22",
            "Jun 22",
            "Jul 22",
            "Aug 22",
            "Sep 22",
            "Oct 22",
          ],
        },
        yaxis: {
          min: 47,
          max: 52,
          tickAmount: 2,
        },

        grid: {
          borderColor: "#f1f1f1",
        },
      },
})

</script>
</code>```

I also add my current chart https://codesandbox.io/s/dawn-star-h8lfri?file=/src/main.js

Body:
Hello guys I have a project on Vue 2 TypeScript supported and I want to use ApexChart for showing my charts. But In documentation i see only JavaScript implementation and i tried to modify for typescript somehow i did not achieve this.

Here is the console error

My charts is not shown on the browser unfortunately.

This is what i have done in my project:

<template>
  <v-card dense elevation="1">
    <v-card-title>
      <v-icon size="32" class="ml-0" color="#000000">mdi-chart-line</v-icon>

        {{ $tc("dashboardPage.nonEarlyRetirementComponent.title", 2) }}

    </v-card-title>
    <v-card-subtitle>

        {{ $t("dashboardPage.shareValue") }}

    </v-card-subtitle>
    <v-card-text>
      <LineChartNonEarly
        type="line"
        height="250"
        :options="chartOptions"
        :series="series"
      ></LineChartNonEarly>
    </v-card-text>
    <v-card-actions>
      <v-row no-gutters align="end">
        <v-row no-gutters class="ml-5 mb-8" align="center">

            {{ $t("nonEarlyRetirement") }}

        </v-row>
        <v-col cols="6">
          <v-list dense>
            <v-list-item>
              <v-list-item-content>

{{ $tc("value", 1) }} in €

              </v-list-item-content>
              <v-list-item-action>

                  {{ $t("dashboardPage.valueIncreased") }}

              </v-list-item-action>
            </v-list-item>
            <v-list-item>
              <v-list-item-content>

                  {{ $n(480032, "currency") }}

              </v-list-item-content>
              <v-list-item-action>
                <v-row>

                    {{ $n(0.038, "percent") }}

                  <v-icon :size="25" :color="'#4BC35E'"
                    >mdi-arrow-top-right-thin-circle-outline</v-icon
                  >
                </v-row>
              </v-list-item-action>
            </v-list-item>
          </v-list>
        </v-col>
      </v-row>
    </v-card-actions>
  </v-card>
</template>

I also add my current chart https://codesandbox.io/s/dawn-star-h8lfri?file=/src/main.js


问:
Connection to PostgreSql database with Android Kotlin
I am new to android development. I am developing an android application for my workplace. Can we connect directly to postgreSQL database without API using kotlin language on Android? If yes, how?. Also, can someone provide me a link to find similar results sourcebook?

I am waiting for your answers


问:
How to correctly display image in Kotlin from firebase storage and firestore
I'm working on a project that use Firebase Storage and Firestore. I added function that allows to upload images from phone gallery to Storage and storage url of this image is saved in Firestore with some other informations. Everything works fine, even the image url in firestore displays selected image correctly in browser. The problem is when i try to set this image to ImageView using Glide or Picasso, because it only shows a blank image/placeholder. This is how my repository functions looks to add and download data:

```<code>override fun addProject(uri: Uri, project: Project) {
    val imagesRef = storage.reference.child("images/${uri.lastPathSegment}")
    Log.d("firebase ref url", imagesRef.toString())
    imagesRef.putFile(uri).addOnCompleteListener {
        Log.d("firebase image", "Succesfully uploaded")
        imagesRef.downloadUrl.addOnSuccessListener { uri->
                project.photoUrl = uri.toString()
                db.collection("projects").add(project)
        }
    }.addOnFailureListener {
        Log.d("firebase image", "Unsuccessfully uploaded")
    }
}

override suspend fun getProjects(): List<Project> {
    val projectList = mutableListOf<Project>()
    val projectRef = db.collection("projects")
    val snapshot = projectRef.get().await()
    val docs = snapshot.documents
    docs.forEach {
        val project = it.toObject(Project::class.java)
        if (project != null) {
            projectList.add(project)
            Log.d("firebase listen", projectList.toString())
        }
    }

    return projectList

}
</code>```

firebase storage

firebase firestore

After i retrieve all projects with their photoUrl and other informations i want to display them in recycler view using ListAdapter. Title and description are displayed correctly in every recycler view item but it seems like this url can't be accessed by glide/ picasso . There is also a log line which shows photoUrl and if I click on it from logcat the browser displays correct image.

```<code>fun bind(project: Project) {
    binding.apply {
        Log.d("recycler view url", project.photoUrl)
        // Picasso.get().load(project.photoUrl).into(projectIv)
        Glide.with(binding.root).load(project.photoUrl).into(projectIv)
        titleTv.text = project.name
        descriptionTv.text = project.description
    }
    binding.executePendingBindings()
}
</code>```

I have found some related topics but still haven't found working solution to that problem.

EDIT

Log result inside recyclerview bind method:

Log resylt

After clicking on link:
Link result

How it looks in my app:

app screenshot 1

app screenshot 2

It looks like it only takes the photo size parameters but can't resolve the photo content, but i'm not sure

Body:
I'm working on a project that use Firebase Storage and Firestore. I added function that allows to upload images from phone gallery to Storage and storage url of this image is saved in Firestore with some other informations. Everything works fine, even the image url in firestore displays selected image correctly in browser. The problem is when i try to set this image to ImageView using Glide or Picasso, because it only shows a blank image/placeholder. This is how my repository functions looks to add and download data:

override fun addProject(uri: Uri, project: Project) {
    val imagesRef = storage.reference.child("images/${uri.lastPathSegment}")
    Log.d("firebase ref url", imagesRef.toString())
    imagesRef.putFile(uri).addOnCompleteListener {
        Log.d("firebase image", "Succesfully uploaded")
        imagesRef.downloadUrl.addOnSuccessListener { uri->
                project.photoUrl = uri.toString()
                db.collection("projects").add(project)
        }
    }.addOnFailureListener {
        Log.d("firebase image", "Unsuccessfully uploaded")
    }
}

override suspend fun getProjects(): List<Project> {
    val projectList = mutableListOf<Project>()
    val projectRef = db.collection("projects")
    val snapshot = projectRef.get().await()
    val docs = snapshot.documents
    docs.forEach {
        val project = it.toObject(Project::class.java)
        if (project != null) {
            projectList.add(project)
            Log.d("firebase listen", projectList.toString())
        }
    }

    return projectList

}

firebase storage

firebase firestore

After i retrieve all projects with their photoUrl and other informations i want to display them in recycler view using ListAdapter. Title and description are displayed correctly in every recycler view item but it seems like this url can't be accessed by glide/ picasso . There is also a log line which shows photoUrl and if I click on it from logcat the browser displays correct image.

fun bind(project: Project) {
    binding.apply {
        Log.d("recycler view url", project.photoUrl)
        // Picasso.get().load(project.photoUrl).into(projectIv)
        Glide.with(binding.root).load(project.photoUrl).into(projectIv)
        titleTv.text = project.name
        descriptionTv.text = project.description
    }
    binding.executePendingBindings()
}

I have found some related topics but still haven't found working solution to that problem.

EDIT

Log result inside recyclerview bind method:

Log resylt

After clicking on link:
Link result

How it looks in my app:

app screenshot 1

app screenshot 2

It looks like it only takes the photo size parameters but can't resolve the photo content, but i'm not sure


问:
VPN Connect to SSMS
Working on trying to connect to SSMS while at home and am greeted with error 18425. Not by choice but wanting to use windows authenticator to log in. I am able to log in while in the office no problem. However when I am home I cannot access the database. I have tried self diagnosing this looking at the DB permissions and going through online docs with no luck.

This server I am not the only user and has to stay online if possible.

I can RDC to the server itself so I can get to the server

Just SSMS doesn't want to let me authenticate

Any help is appreciated

Company domain/username shouloud log into DBname
In office works

Same way of logging in at home
Error 18425
VPN connection

Title: VPN Connect to SSMS


问:
Is it possible to create a collapsible sidebar with Kivy and/or KivyMD?
I'm working on a project for the GUI of an app written in Python that requires a collapsible sidebar like this one:
https://www.youtube.com/watch?v=-vQIcBKdhyk&t=9s

I already created a good portion of the GUI in Kivy and KivyMD. Applied also the Navigation Drawer that works as expected. However, it is fully retracted when not active, so not exactly what was asked.

Anyone managed to create something like this?
Thank you all in advance

Using Navigation Drawer component in KivyMD, it was possible to create something almost as required. Yet, there is no partial view (with little icons that would expand when the drawer were toggled).


问:
How to receive image dragged from Safari webpage with SwiftUI `.onDrop()`
I'm not able to receive image dragged from Safari webpage in my SwiftUI app on macOS. I suppose Safari uses different mechanics, because it works properly when it comes to Chrome and Firefox. I use .onDrop() but it results empty providers no matter what kind of UTType used. Below is my code but output no provider available.

So, what UTType it is when dragging image from Safari webpage, and how can I implement it in .onDrop()

```<code>.onDrop(of: [.url, .fileURL], isTargeted: $isTarget) { providers -> Bool in
    if let provider = providers.first,
       let identifier = provider.registeredTypeIdentifiers.first {
        print(identifier)
        provider.loadItem(forTypeIdentifier: identifier) { data, error in
            // Do something here
        }
    } else {
        print("no provider available")
    }
    return true
}
</code>```

Body:
I'm not able to receive image dragged from Safari webpage in my SwiftUI app on macOS. I suppose Safari uses different mechanics, because it works properly when it comes to Chrome and Firefox. I use .onDrop() but it results empty providers no matter what kind of UTType used. Below is my code but output no provider available.

So, what UTType it is when dragging image from Safari webpage, and how can I implement it in .onDrop()

.onDrop(of: [.url, .fileURL], isTargeted: $isTarget) { providers -> Bool in
    if let provider = providers.first,
       let identifier = provider.registeredTypeIdentifiers.first {
        print(identifier)
        provider.loadItem(forTypeIdentifier: identifier) { data, error in
            // Do something here
        }
    } else {
        print("no provider available")
    }
    return true
}


问:
Switching between sender and receiver in Android Wi-Fi Direct app
I am developing an Android app to share files using Wi-Fi Direct. The app works, but I am unable to switch between being a sender and a receiver without closing the app. When I try to switch roles, the group owner is not updated and remains the same as the previous transfer. How can I update the group owner and switch roles correctly?

I do disconnect and reinitialize after every file transfer session. But it doesn't create a new group.

Here is my initialization code:

```<code>manager = getSystemService(Context.WIFI_P2P_SERVICE) as WifiP2pManager?
channel = manager?.initialize(this, mainLooper, null)?.also {
     receiver = P2pBroadcastReceiver(this)
}

</code>```

And here is the code for connecting to a peer and switching roles:

```<code>fun connectToPeer(device: WifiP2pDevice, isSender: Boolean) {
    val config = WifiP2pConfig().apply {
        deviceAddress = device.deviceAddress
        groupOwnerIntent = if (isSender) WifiP2pConfig.GROUP_OWNER_INTENT_MIN else WifiP2pConfig.GROUP_OWNER_INTENT_MAX
    }

    channel?.also { channel ->
        manager?.connect(channel, config, object : WifiP2pManager.ActionListener {
            override fun onSuccess() {
                context.apply {
                    toast("${getString(R.string.connecting_to)} ${device.deviceName}")
                }
            }

            override fun onFailure(reasonCode: Int) = onP2POperationFailed(reasonCode)
        })
    }
}

</code>```

And here is the code for disconnecting from the group:

```<code>fun disconnect() {
    manager?.apply {
        cancelConnect(channel, null)
        removeGroup(channel, null)
        stopPeerDiscovery(channel, null)
        deletePersistentGroups()
    }
    try {
        if (::serverSocket.isInitialized) serverSocket.close()
        if (::clientSocket.isInitialized) clientSocket.close()
    } catch (e: IOException) {}
}

private fun deletePersistentGroups() {
    try {
        val methods = WifiP2pManager::class.java.methods
        for (method in methods) {
            if (method.name == "deletePersistentGroup") {
                for (networkId in 0..31) {
                    method.invoke(manager, channel, networkId, null)
                }
            }
        }
    } catch (e: Exception) {}
}

</code>```

Any help would be greatly appreciated. Thank you!

I would like for devices d1 and d2 to have the ability to switch roles without closing the app. Currently, d1 is set up to receive files and d2 is set up to send them. However, if d1 needs to send files without closing the app after d2 has finished sending its files, I would like for them to be able to easily reestablish the connection and initiate the transfer.

Edit 2:

How I initiate the file transferring or sending process:

```<code>private fun onConnectionInfoChanged(info: WifiP2pInfo?) {
    if (isDeviceConnected) {
        if (info!!.isGroupOwner) { // receiver || server || group owner
            startReceiverServer()
        } else { // sender || client
            startSenderClient(info.groupOwnerAddress)
        }
    }
}

private fun startReceiverServer() {
    runOnBg {
        serverSocket = ServerSocket(P2pFileTransferHelper.PORT)
        P2pFileTransferHelper.receiveFiles(serverSocket, context.contentResolver) { fileTransferInfoLiveData.postValue(it) }
    }
}

private fun startSenderClient(serverAddress: InetAddress) {
    runOnBg {
        clientSocket = Socket()
        P2pFileTransferHelper.sendFiles(clientSocket, serverAddress, selectedFilePaths) { fileTransferInfoLiveData.postValue(it) }
    }
}
</code>```

Body:
I am developing an Android app to share files using Wi-Fi Direct. The app works, but I am unable to switch between being a sender and a receiver without closing the app. When I try to switch roles, the group owner is not updated and remains the same as the previous transfer. How can I update the group owner and switch roles correctly?

I do disconnect and reinitialize after every file transfer session. But it doesn't create a new group.

Here is my initialization code:

manager = getSystemService(Context.WIFI_P2P_SERVICE) as WifiP2pManager?
channel = manager?.initialize(this, mainLooper, null)?.also {
     receiver = P2pBroadcastReceiver(this)
}

And here is the code for connecting to a peer and switching roles:

fun connectToPeer(device: WifiP2pDevice, isSender: Boolean) {
    val config = WifiP2pConfig().apply {
        deviceAddress = device.deviceAddress
        groupOwnerIntent = if (isSender) WifiP2pConfig.GROUP_OWNER_INTENT_MIN else WifiP2pConfig.GROUP_OWNER_INTENT_MAX
    }

    channel?.also { channel ->
        manager?.connect(channel, config, object : WifiP2pManager.ActionListener {
            override fun onSuccess() {
                context.apply {
                    toast("${getString(R.string.connecting_to)} ${device.deviceName}")
                }
            }

            override fun onFailure(reasonCode: Int) = onP2POperationFailed(reasonCode)
        })
    }
}

And here is the code for disconnecting from the group:

fun disconnect() {
    manager?.apply {
        cancelConnect(channel, null)
        removeGroup(channel, null)
        stopPeerDiscovery(channel, null)
        deletePersistentGroups()
    }
    try {
        if (::serverSocket.isInitialized) serverSocket.close()
        if (::clientSocket.isInitialized) clientSocket.close()
    } catch (e: IOException) {}
}

private fun deletePersistentGroups() {
    try {
        val methods = WifiP2pManager::class.java.methods
        for (method in methods) {
            if (method.name == "deletePersistentGroup") {
                for (networkId in 0..31) {
                    method.invoke(manager, channel, networkId, null)
                }
            }
        }
    } catch (e: Exception) {}
}

Any help would be greatly appreciated. Thank you!

I would like for devices d1 and d2 to have the ability to switch roles without closing the app. Currently, d1 is set up to receive files and d2 is set up to send them. However, if d1 needs to send files without closing the app after d2 has finished sending its files, I would like for them to be able to easily reestablish the connection and initiate the transfer.

Edit 2:

How I initiate the file transferring or sending process:

private fun onConnectionInfoChanged(info: WifiP2pInfo?) {
    if (isDeviceConnected) {
        if (info!!.isGroupOwner) { // receiver || server || group owner
            startReceiverServer()
        } else { // sender || client
            startSenderClient(info.groupOwnerAddress)
        }
    }
}

private fun startReceiverServer() {
    runOnBg {
        serverSocket = ServerSocket(P2pFileTransferHelper.PORT)
        P2pFileTransferHelper.receiveFiles(serverSocket, context.contentResolver) { fileTransferInfoLiveData.postValue(it) }
    }
}

private fun startSenderClient(serverAddress: InetAddress) {
    runOnBg {
        clientSocket = Socket()
        P2pFileTransferHelper.sendFiles(clientSocket, serverAddress, selectedFilePaths) { fileTransferInfoLiveData.postValue(it) }
    }
}


问:
Is my OpenACC code compiled with GCC running on GPU?
I'm trying to write a very simple example with OpenACC using GCC as compiler, but I'm not sure if the program runs on the GPU. First of all, I have a Lenovo W540 running Debian Sid with an integrated Inted HD Graphics 4600 (which is the GPU the GUI -plasma- is using). Also, there is a NVIDIA GK106GLM [Quadro K2100M]. I have installed the xserver-xorg-video-nvidia-legacy-390xx, nvidia-legacy-390xx-driver, and nvidia-legacy-390xx-kernel-dkms packages, as they are the corresponding drivers for my GPU. Running the lspci -k | grep -A 2 -i "VGA" command I obtain

```<code>00:02.0 VGA compatible controller: Intel Corporation 4th Gen Core Processor Integrated Graphics Controller (rev 06)
        Subsystem: Lenovo 4th Gen Core Processor Integrated Graphics Controller
        Kernel driver in use: i915
--
01:00.0 VGA compatible controller: NVIDIA Corporation GK106GLM [Quadro K2100M] (rev a1)
        Subsystem: Lenovo GK106GLM [Quadro K2100M]
        Kernel modules: nvidia
</code>```

so I suppose that the NVDIA GPU is well configured and detected. Am I right?

On the other hand, I've installed GCC 12 and also the packages gcc-offload-nvptx. First question: is it neccessary such package in order to run programs on the GPU?

Well, I wrote this very simple code

```<code>#include <stdio.h>
#ifdef _OPENACC
#include <openacc.h>
#endif

#define N 10

int main()
{
    int i=0,buf[N];
    #ifdef _OPENACC
    printf("Number of devices: %d\n",acc_get_num_devices(acc_device_nvidia));
    #endif
#pragma acc parallel loop copyout(buf[0:N])
    for(i=0;i<N;i++)
    {
        buf[i] = i;
    }
    for(i=0;i<N;i++)
    {
        printf("%d ",buf[i]);
    }
    printf("\n");
    return 0;
}
</code>```

If I compile as gcc -Wall -fopenacc example.c -o example I obtain a warning:

```<code>/usr/bin/ld: /tmp/cckzNCnl.crtoffloadtable.o: warning: relocation against `__offload_vars_end' in read-only section `.rodata'
/usr/bin/ld: warning: creating DT_TEXTREL in a PIE
</code>```

but I can't interpret it. If I run the code, it works, but is very, ver slow and I obtain

```<code>Number of devices: 0
0 1 2 3 4 5 6 7 8 9
</code>```

The result is correct and I could think that it was executed on the GPU as it is extremely slow (maybe due to data copy?), but I obtain the result Number of devices: 0

Can someone gime me any hint about how to compile and run the code on the GPU?

Body:
I'm trying to write a very simple example with OpenACC using GCC as compiler, but I'm not sure if the program runs on the GPU. First of all, I have a Lenovo W540 running Debian Sid with an integrated Inted HD Graphics 4600 (which is the GPU the GUI -plasma- is using). Also, there is a NVIDIA GK106GLM [Quadro K2100M]. I have installed the xserver-xorg-video-nvidia-legacy-390xx, nvidia-legacy-390xx-driver, and nvidia-legacy-390xx-kernel-dkms packages, as they are the corresponding drivers for my GPU. Running the lspci -k | grep -A 2 -i "VGA" command I obtain

00:02.0 VGA compatible controller: Intel Corporation 4th Gen Core Processor Integrated Graphics Controller (rev 06)
        Subsystem: Lenovo 4th Gen Core Processor Integrated Graphics Controller
        Kernel driver in use: i915
--
01:00.0 VGA compatible controller: NVIDIA Corporation GK106GLM [Quadro K2100M] (rev a1)
        Subsystem: Lenovo GK106GLM [Quadro K2100M]
        Kernel modules: nvidia

so I suppose that the NVDIA GPU is well configured and detected. Am I right?

On the other hand, I've installed GCC 12 and also the packages gcc-offload-nvptx. First question: is it neccessary such package in order to run programs on the GPU?

Well, I wrote this very simple code

#include <stdio.h>
#ifdef _OPENACC
#include <openacc.h>
#endif

#define N 10

int main()
{
    int i=0,buf[N];
    #ifdef _OPENACC
    printf("Number of devices: %d\n",acc_get_num_devices(acc_device_nvidia));
    #endif
#pragma acc parallel loop copyout(buf[0:N])
    for(i=0;i<N;i++)
    {
        buf[i] = i;
    }
    for(i=0;i<N;i++)
    {
        printf("%d ",buf[i]);
    }
    printf("\n");
    return 0;
}

If I compile as gcc -Wall -fopenacc example.c -o example I obtain a warning:

/usr/bin/ld: /tmp/cckzNCnl.crtoffloadtable.o: warning: relocation against `__offload_vars_end' in read-only section `.rodata'
/usr/bin/ld: warning: creating DT_TEXTREL in a PIE

but I can't interpret it. If I run the code, it works, but is very, ver slow and I obtain

Number of devices: 0
0 1 2 3 4 5 6 7 8 9

The result is correct and I could think that it was executed on the GPU as it is extremely slow (maybe due to data copy?), but I obtain the result Number of devices: 0

Can someone gime me any hint about how to compile and run the code on the GPU?


问:
How to do a join with fields that are not keys nor have the same type in Access database?
I have a Microsoft Access table called CHECKINOUT that has a field called SENSORID of text type.

On the other hand, there is another table called Machines that has a field called MachineNumber of int type.

MachineNumber is the join I need to do with SENSORID but it does not work.

This is the query I am trying:

```<code>SELECT C.VERIFYCODE, C.CHECKTYPE, C.CHECKTIME, C.sn,
       U.USERID, U.BADGENUMBER, U.SSN, U.CardNo, U.NAME, U.STREET, U.PAGER,
       C.SENSORID, M.IP, M.MachineAlias, M.Port,M.MachineNumber
FROM (CHECKINOUT C
      INNER JOIN USERINFO U ON C.USERID = U.USERID)
INNER JOIN Machines M ON C.SENSORID = Str(M.MachineNumber)
WHERE C.CHECKTIME >= #2022-11-01 12:00:00#
</code>```

I got empty results.

I also tried with:

```<code>SELECT C.VERIFYCODE, C.CHECKTYPE, C.CHECKTIME, C.sn,
       U.USERID, U.BADGENUMBER, U.SSN, U.CardNo, U.NAME, U.STREET, U.PAGER,
       C.SENSORID, M.IP, M.MachineAlias, M.Port,M.MachineNumber
FROM (CHECKINOUT C
      INNER JOIN USERINFO U ON C.USERID = U.USERID)
INNER JOIN Machines M ON Val(C.SENSORID) = M.MachineNumber
WHERE C.CHECKTIME >= #2022-11-01 12:00:00#
</code>```

but it did not work either.

Of course, there are matching data so result should not be empty.

What should I do to execute this query successfully?

Body:
I have a Microsoft Access table called CHECKINOUT that has a field called SENSORID of text type.

On the other hand, there is another table called Machines that has a field called MachineNumber of int type.

MachineNumber is the join I need to do with SENSORID but it does not work.

This is the query I am trying:

SELECT C.VERIFYCODE, C.CHECKTYPE, C.CHECKTIME, C.sn,
       U.USERID, U.BADGENUMBER, U.SSN, U.CardNo, U.NAME, U.STREET, U.PAGER,
       C.SENSORID, M.IP, M.MachineAlias, M.Port,M.MachineNumber
FROM (CHECKINOUT C
      INNER JOIN USERINFO U ON C.USERID = U.USERID)
INNER JOIN Machines M ON C.SENSORID = Str(M.MachineNumber)
WHERE C.CHECKTIME >= #2022-11-01 12:00:00#

I got empty results.

I also tried with:

SELECT C.VERIFYCODE, C.CHECKTYPE, C.CHECKTIME, C.sn,
       U.USERID, U.BADGENUMBER, U.SSN, U.CardNo, U.NAME, U.STREET, U.PAGER,
       C.SENSORID, M.IP, M.MachineAlias, M.Port,M.MachineNumber
FROM (CHECKINOUT C
      INNER JOIN USERINFO U ON C.USERID = U.USERID)
INNER JOIN Machines M ON Val(C.SENSORID) = M.MachineNumber
WHERE C.CHECKTIME >= #2022-11-01 12:00:00#

but it did not work either.

Of course, there are matching data so result should not be empty.

What should I do to execute this query successfully?


问:
Change decimal comma to point without losing formating
I want to import a .csv file and switch the decimal comma to a point. Depending on the format I use to separate columns in the .csv file, can the program not read the file though, or if I change the decimal mark, I lose my format.

I have tried using gsub(",", ".", df):

```<code>data <- read.csv("D:\\My\\data\\pathway")

data_point <- as.data.frame(gsub(",", ".", data))
</code>```

However, here I am encountering the issue, that the file I want to read has commas to separate the columns, as well. I have tried changing these to ;, :, tab, and tabulator (all the other options I had), when exporting the .csv file from the spread sheet. But with these the programm refused to read the data altogether:

```<code>Error in read.table(file = file, header = header, sep = sep, quote = quote,  :
  more columns than column names
</code>```

To me this doesn't make sense, because if anything there should be more columns than column names when it has commas as decimal marks as well as separations. However, somehow this is the only format it accepts, but then I can not change the decimals to a point, only by losing all the columns. Because then everything is changed to a point and thus, I only have one big column.

Does anyone know a way to either

import/read the file with ;, :, or tab as column separations, so the programm will accept it?

change only the decimal commas to points but keep the column separations?

Here are the first few rows of the data (.csv) as reference:

Date & Time,Temp(C),Depth(m),Salinity(psu),Conduct(mS/cm),Sound Velocity(m/sec)
"44843,96458","19,01","-0,43","0,01",0,"1478,63"
"44843,96493","17,7","-0,54","0,01",0,"1474,38"
"44843,96528","16,65","-0,54","0,01",0,"1470,88"
"44843,96563","15,71","-0,54","0,01",0,"1467,66"
"44843,96597","14,83","-0,59","0,01",0,"1464,56"
"44843,96632","14,12","-0,59","0,01",0,"1462,03"

P.s. By now I have managed to get around the issue of the decimal comma, by first converting it into a matrix, and then using gsub:

```<code>#transforming the read data into matrix
mx <- as.matrix.data.frame(data)

#exchanging comma for point
mx_point <- gsub(",", ".", mx)
</code>```

It is probably not very elegant, but this is how far I've gotten. The next step I tried was converting this matrix now into a data frame and working with that, however I don't know if that is even necessary?

```<code>#transforming matrix into data frame
mx_df <-as.data.frame(mx_point)

mx_df[2]<-as.numeric(bpr_mx_df[2])
</code>```

Either way, as soon as I try to convert it into a numeric, it gives me another error, so I'm still missing something, or took the wrong turn along the way.

```<code>Error: 'list' object cannot be coerced to type 'double'
</code>```

Body:
I want to import a .csv file and switch the decimal comma to a point. Depending on the format I use to separate columns in the .csv file, can the program not read the file though, or if I change the decimal mark, I lose my format.

I have tried using gsub(",", ".", df):

data <- read.csv("D:\\My\\data\\pathway")

data_point <- as.data.frame(gsub(",", ".", data))

However, here I am encountering the issue, that the file I want to read has commas to separate the columns, as well. I have tried changing these to ;, :, tab, and tabulator (all the other options I had), when exporting the .csv file from the spread sheet. But with these the programm refused to read the data altogether:

Error in read.table(file = file, header = header, sep = sep, quote = quote,  :
  more columns than column names

To me this doesn't make sense, because if anything there should be more columns than column names when it has commas as decimal marks as well as separations. However, somehow this is the only format it accepts, but then I can not change the decimals to a point, only by losing all the columns. Because then everything is changed to a point and thus, I only have one big column.

Does anyone know a way to either

import/read the file with ;, :, or tab as column separations, so the programm will accept it?

change only the decimal commas to points but keep the column separations?

Here are the first few rows of the data (.csv) as reference:

Date & Time,Temp(C),Depth(m),Salinity(psu),Conduct(mS/cm),Sound Velocity(m/sec)
"44843,96458","19,01","-0,43","0,01",0,"1478,63"
"44843,96493","17,7","-0,54","0,01",0,"1474,38"
"44843,96528","16,65","-0,54","0,01",0,"1470,88"
"44843,96563","15,71","-0,54","0,01",0,"1467,66"
"44843,96597","14,83","-0,59","0,01",0,"1464,56"
"44843,96632","14,12","-0,59","0,01",0,"1462,03"

P.s. By now I have managed to get around the issue of the decimal comma, by first converting it into a matrix, and then using gsub:

#transforming the read data into matrix
mx <- as.matrix.data.frame(data)

#exchanging comma for point
mx_point <- gsub(",", ".", mx)

It is probably not very elegant, but this is how far I've gotten. The next step I tried was converting this matrix now into a data frame and working with that, however I don't know if that is even necessary?

#transforming matrix into data frame
mx_df <-as.data.frame(mx_point)

mx_df[2]<-as.numeric(bpr_mx_df[2])

Either way, as soon as I try to convert it into a numeric, it gives me another error, so I'm still missing something, or took the wrong turn along the way.

Error: 'list' object cannot be coerced to type 'double'


问:
How can I gensym when writing a compiler in Kanren?
I'm writing a compiler from an esolang to WebAssembly, using CHICKEN Scheme's miniKanren. My compiler already works somewhat, but I'd like to extend it with support for named local registers and I'm not sure how to proceed.

CHICKEN has a gensym with the following non-relational behavior:

#;1> (gensym)
g18
#;2> (gensym "asdf")
asdf19
#;3> (gensym 'asdf)
asdf20
```
<p>It would be nice if I could generate semi-readable registers in miniKanren. WebAssembly text tools usually want named registers to start with "$", as well. Given these constraints, I presumed that I could hack up a register-naming relation using <code>gensym</code>, <code>symbolo</code>, and <code>project</code>, but I'm not sure whether that is a practical solution. I also presume that I could write a custom walker against the underlying µKanren API, but that goes beyond portable miniKanren.</p>
<p>Is there a standard solution for this?</p>
<p>My compiler source is available, but likely the only relevant part is my current hack with <code>project</code> and <code>little-endian->number</code> for numbered registers:</p>
<pre class="lang-lisp prettyprint-override"><code>; The successor function.
; Nat <-> Nat
(define (succ° n m) (+o n (build-num 1) m))

; A prelude which loads the given number of local params onto the stack.
; Nat <-> WAT Insts
(define (prelude° plen prelude)
  (conde
    ((zeroo plen) (== prelude '()))
    ((fresh (len lude) (succ° len plen) (prelude° len lude)
            (project (len) (appendo lude `((local.get ,(little-endian->number len))) prelude))))))
</code>```

Body:
I'm writing a compiler from an esolang to WebAssembly, using CHICKEN Scheme's miniKanren. My compiler already works somewhat, but I'd like to extend it with support for named local registers and I'm not sure how to proceed.

CHICKEN has a gensym with the following non-relational behavior:

#;1> (gensym)
g18
#;2> (gensym "asdf")
asdf19
#;3> (gensym 'asdf)
asdf20

It would be nice if I could generate semi-readable registers in miniKanren. WebAssembly text tools usually want named registers to start with "$", as well. Given these constraints, I presumed that I could hack up a register-naming relation using gensym, symbolo, and project, but I'm not sure whether that is a practical solution. I also presume that I could write a custom walker against the underlying µKanren API, but that goes beyond portable miniKanren.

Is there a standard solution for this?

My compiler source is available, but likely the only relevant part is my current hack with project and little-endian->number for numbered registers:

; The successor function.
; Nat <-> Nat
(define (succ° n m) (+o n (build-num 1) m))

; A prelude which loads the given number of local params onto the stack.
; Nat <-> WAT Insts
(define (prelude° plen prelude)
  (conde
    ((zeroo plen) (== prelude '()))
    ((fresh (len lude) (succ° len plen) (prelude° len lude)
            (project (len) (appendo lude `((local.get ,(little-endian->number len))) prelude))))))


问:
Can we do unit testing controllers in Blazor WebAssembly using Bunit
Can we do unit testing for controllers/end point in Blazor WebAssembly using Bunit x unit?

https://bunit.dev/

like this
https://learn.microsoft.com/en-us/aspnet/web-api/overview/testing-and-debugging/unit-testing-controllers-in-web-api?

If not what is the way to do unit test for API status code checking in Blazor WebAssembly?

Please guide me.


问:
specify ssl key and ssl cert values instead of filename for MongoClient
I am currently creating a MongoClient in a node.js app as follows and the connection works fine. My issue is that I now want to pass the value of the key and the value of the cert as options into the MongoClient constructor instead of the file locations. Is this possible?

mongoClient = new MongoClient(connStr, { sslKey: sslKeyPath, sslCert: sslCertPath, serverApi: ServerApiVersion['serverApiVer'] });


问:
How to utilize dotenv package to access .env file variables in HTML + AngularJS webapp?
I have a web app that utilizes HTML and AngularJS. I use a form to ng-submit a function within the angualrJS file that communicates with a server. I want the server credentials, paths, etc... to be stored in the .env file of my project, rather than hard coded in for security reasons. Here are the files:

```<code>HTML:
<!DOCTYPE html>
<html ng-app="app.module">
  <head>
    <title>My Login Form</title>
    <link rel="stylesheet" href="../CSS/webapp_loginScreen_UIDesign.css">
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.7.9/angular.min.js"></script>

  </head>
  <body>

    <form class="login-form" ng-submit="vm.login(credentials)"  ng-controller = "loginScreenController as vm">
      <label for="username">Username:</label><br>
      <input type="text" id="username" name="username" ng-model="credentials.username"><br>
      <label for="password">Password:</label><br>
      <input type="password" id="password" name="password" ng-model="credentials.password"><br><br>
      <input type="submit" value="Login">
    </form>

    <!-- Put javascript sources at the end of body as best practice with the library first -->
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.7.9/angular-route.min.js"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.7.9/angular-cookies.min.js"></script>
    <script src="https://unpkg.com/angular-jwt/dist/angular-jwt.min.js"></script>
    <script src="../../../Web App Functions/Login Screen/webapp_loginScreen_main_functions.js"></script>

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

The angualrJS:

```<code>//import * as dotEnv from 'dotenv';
var dotenv = require('dotenv');

// Load the environment variables from the .env file
dotenv.config();

//Create main webapp module to be used in all

var webApp = angular.module('app.module', ['ngRoute','ngCookies','angular-jwt']);

//Configure it for JWT storage
webApp.config(function(jwtOptionsProvider) {
  jwtOptionsProvider.config({
    tokenGetter: ['$cookies', function($cookies) {
      return $cookies.get('jwt');
    }],
    whiteListedDomains: ['my-server.com']
  });
});

function loginScreenController($http, $cookies) {
  var vm = this;
  const serverURL = process.env.server_URL//DotenvService.get("server_URL")//"my-server.com/login/" //os.environ("server_URL");

  function login(credentials) {
    var authenticationFailed = false;
    console.log("Oi meu amor");
    $http.post(serverURL, credentials)
      .then(function(response) {
        var jwt = response.data.jwt;
        $cookies.put('jwt', jwt);
        authenticationFailed = false;
      })
      .catch(function(error) {
        authenticationFailed = true;
        console.log("It failed though");
      })
      .finally(function() {
        if (authenticationFailed) {
          document.getElementById('incorrect-credentials-label').style.display = 'block';
        }
      })
  }
  vm.login = login;
}

webApp.controller('loginScreenController',loginScreenController);

loginScreenController.$inject = ['$http','$cookies'];
</code>```

I have tried a few methods of enabling the use of process.env.server_URL but I always get an error after compiling and running in a web browser. The current set up tells me cant find variable require and if I uncomment the import * as dotenv from 'dotenv' I get the error that import is expected exactly one argument.

Also, as a side note, in some associated-with-the-app python scripts, I use import OS and os.environ["string"] to handle this privacy matter. Assuming that I can sit up the dotenv for the angular/HTML, would it be a problem to be referring to os.environ in the .py files and process.env.[insert name] in the angularJS files?

Body:
I have a web app that utilizes HTML and AngularJS. I use a form to ng-submit a function within the angualrJS file that communicates with a server. I want the server credentials, paths, etc... to be stored in the .env file of my project, rather than hard coded in for security reasons. Here are the files:

HTML:
<!DOCTYPE html>

    <title>My Login Form</title>
    <link rel="stylesheet" href="../CSS/webapp_loginScreen_UIDesign.css">

    <form class="login-form" ng-submit="vm.login(credentials)"  ng-controller = "loginScreenController as vm">
      Username:

      <input type="text" id="username" name="username" ng-model="credentials.username">

      Password:

      <input type="password" id="password" name="password" ng-model="credentials.password">

      <input type="submit" value="Login">
    </form>

The angualrJS:

//import * as dotEnv from 'dotenv';
var dotenv = require('dotenv');

// Load the environment variables from the .env file
dotenv.config();

//Create main webapp module to be used in all

var webApp = angular.module('app.module', ['ngRoute','ngCookies','angular-jwt']);

//Configure it for JWT storage
webApp.config(function(jwtOptionsProvider) {
  jwtOptionsProvider.config({
    tokenGetter: ['$cookies', function($cookies) {
      return $cookies.get('jwt');
    }],
    whiteListedDomains: ['my-server.com']
  });
});

function loginScreenController($http, $cookies) {
  var vm = this;
  const serverURL = process.env.server_URL//DotenvService.get("server_URL")//"my-server.com/login/" //os.environ("server_URL");

  function login(credentials) {
    var authenticationFailed = false;
    console.log("Oi meu amor");
    $http.post(serverURL, credentials)
      .then(function(response) {
        var jwt = response.data.jwt;
        $cookies.put('jwt', jwt);
        authenticationFailed = false;
      })
      .catch(function(error) {
        authenticationFailed = true;
        console.log("It failed though");
      })
      .finally(function() {
        if (authenticationFailed) {
          document.getElementById('incorrect-credentials-label').style.display = 'block';
        }
      })
  }
  vm.login = login;
}

webApp.controller('loginScreenController',loginScreenController);

loginScreenController.$inject = ['$http','$cookies'];

I have tried a few methods of enabling the use of process.env.server_URL but I always get an error after compiling and running in a web browser. The current set up tells me cant find variable require and if I uncomment the import * as dotenv from 'dotenv' I get the error that import is expected exactly one argument.

Also, as a side note, in some associated-with-the-app python scripts, I use import OS and os.environ["string"] to handle this privacy matter. Assuming that I can sit up the dotenv for the angular/HTML, would it be a problem to be referring to os.environ in the .py files and process.env.[insert name] in the angularJS files?


问:
How do I have selenium get oauth access tokens from a web app?
This is completely maddening... I have OAuth2.0 requests going to a web app and I want to retrieve my access token using python selenium.

I've tried using rauth, requests, and oauthlib.oath2 to get an access token after generating my api keys. Selenium is the only path where I've see any results so I may be missing the target all together.

Only the kicker is this...

I can't see the browser handle.

I don't know any of the xpath elements.

I can't see any of the HTML from the popup in Chrome Developer tools.

The Datto API Documentation says to use Postman to get your Access Token token. Which, I can do and make API calls form python, but this isn't a very repeatable process.

All of the examples from Datto are adopting this process as well.

How do I using either selenium or a python script to simply perform oauth retrieve my access token so that I can variablize it in future requests?

```<code>from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from webdriver_manager.chrome import ChromeDriverManager
from selenium.webdriver.common.by import By
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.alert import Alert
import time

#Oauth2.0 credentials.
client_id = 'public-client'
client_secret = 'public'

# URLs to retrieve tokens
authorize_url = "https://zinfandel-api.centrastage.net/auth/oauth/authorize"
access_token_url = "https://zinfandel-api.centrastage.net/auth/oauth/token"

# This is your API Public Key.
auth_user = 'YOUR_PUBLIC_KEY_HERE'

# This is your API Secret Key.
auth_pass = 'YOUR_SECRET_KEY_HERE'

# This installs the driver that selenium needs to open your browser.
browser = webdriver.Chrome(service=Service(ChromeDriverManager().install()))

#browser.maximize_window()

time.sleep(3)

# This goes to a website.
browser.get(access_token_url)

# Used to download page source code
with open("page_source.html", "w") as f:
    f.write(browser.page_source)
    f.close()

time.sleep(5)

# A list of all window handles
main_window_handle = browser.window_handles

# Handle of the first window open.
main_window = main_window_handle[0]

# This will switch us to a new window if there is more than one.
# Right now the web app isn't being seen as a window.
for handle in browser.window_handles:
    if handle != main_window:
        popup = handle
        #print(popup)
        browser.switch_to.window(popup)

time.sleep(3)

print("Starting anonymous key send.")

actions = ActionChains(browser)

time.sleep(3)

popup_alert = Alert(browser)

print(popup_alert.page_source)

# This will error out because the page isn't an alert.
#browser.switch_to.alert

# Is this an Alert?
#with open("active_elment_alert.html", "w") as f:
#    f.write(browser.page_source)
#    f.close()

# I'm going to try to switch to a frame and write to it.
browser.switch_to.frame

# If this is a frame we'll see soething here.
with open("active_elment_frame.html", "w") as f:
    f.write(browser.page_source)
    f.close()

browser.switch_to.active_element

# Used to download active element source code.
# You can see that after I switch I don't see any html other than what was presented earlier.
with open("active_elment_source.html", "w") as f:
    f.write(browser.page_source)
    f.close()

################## I THINK THIS IS WHERE I NEED HELP ##################
#This is probably just posting nonsense in the empty html body.

# I'm trying to xpath to either a label or anything with the username field.
mystery_field = browser.find_element(By.XPATH,'//*[contains(text(),ernam)]')
#mystery_field = browser.find_element(By.XPATH,"//label[contains(text(),ernam)]")

print(mystery_field.text)

#start_a_doing_stuff = browser.switch_to.frame(mystery_field)

time.sleep(3)

actions.click(mystery_field).perform

time.sleep(3)

actions.send_keys(client_id).perform()

time.sleep(3)

actions.send_keys(Keys.TAB).perform()

time.sleep(3)

actions.send_keys(client_secret).perform()

time.sleep(3)

actions.send_keys(Keys.RETURN).perform()

time.sleep(3)

print("The anonymous key send is done.")

time.sleep(3)

################## I THINK THIS IS WHERE I NEED HELP ##################

# This portion appropriately sends content to authorize url.

#user_name_field = browser.find_element(By.NAME, "username")
#password_field = browser.find_element(By.NAME, "password")

#user_name_field.send_keys(auth_user)

#user_name_field.send_keys(Keys.TAB)

#password_field.send_keys(auth_pass)

#password_field.send_keys(Keys.RETURN)

#actions.perform()

#time.sleep(3)

#When everything is done, this closes your browser.
browser.quit()
</code>```

When the script runs you can see the cursor in the username field, and when you go to the site the html body is empty.

But, without being able to see any of the fields I'm trying to send keys to the cursor as soon as the auth alert box opens.

I know that selenium doesn't see it as an alert because when I try to send keys to an alert element my code errors out.

Body:
This is completely maddening... I have OAuth2.0 requests going to a web app and I want to retrieve my access token using python selenium.

I've tried using rauth, requests, and oauthlib.oath2 to get an access token after generating my api keys. Selenium is the only path where I've see any results so I may be missing the target all together.

Only the kicker is this...

I can't see the browser handle.

I don't know any of the xpath elements.

I can't see any of the HTML from the popup in Chrome Developer tools.

The Datto API Documentation says to use Postman to get your Access Token token. Which, I can do and make API calls form python, but this isn't a very repeatable process.

All of the examples from Datto are adopting this process as well.

How do I using either selenium or a python script to simply perform oauth retrieve my access token so that I can variablize it in future requests?

from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from webdriver_manager.chrome import ChromeDriverManager
from selenium.webdriver.common.by import By
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.alert import Alert
import time

#Oauth2.0 credentials.
client_id = 'public-client'
client_secret = 'public'

# URLs to retrieve tokens
authorize_url = "https://zinfandel-api.centrastage.net/auth/oauth/authorize"
access_token_url = "https://zinfandel-api.centrastage.net/auth/oauth/token"

# This is your API Public Key.
auth_user = 'YOUR_PUBLIC_KEY_HERE'

# This is your API Secret Key.
auth_pass = 'YOUR_SECRET_KEY_HERE'

# This installs the driver that selenium needs to open your browser.
browser = webdriver.Chrome(service=Service(ChromeDriverManager().install()))

#browser.maximize_window()

time.sleep(3)

# This goes to a website.
browser.get(access_token_url)

# Used to download page source code
with open("page_source.html", "w") as f:
    f.write(browser.page_source)
    f.close()

time.sleep(5)

# A list of all window handles
main_window_handle = browser.window_handles

# Handle of the first window open.
main_window = main_window_handle[0]

# This will switch us to a new window if there is more than one.
# Right now the web app isn't being seen as a window.
for handle in browser.window_handles:
    if handle != main_window:
        popup = handle
        #print(popup)
        browser.switch_to.window(popup)

time.sleep(3)

print("Starting anonymous key send.")

actions = ActionChains(browser)

time.sleep(3)

popup_alert = Alert(browser)

print(popup_alert.page_source)

# This will error out because the page isn't an alert.
#browser.switch_to.alert

# Is this an Alert?
#with open("active_elment_alert.html", "w") as f:
#    f.write(browser.page_source)
#    f.close()

# I'm going to try to switch to a frame and write to it.
browser.switch_to.frame

# If this is a frame we'll see soething here.
with open("active_elment_frame.html", "w") as f:
    f.write(browser.page_source)
    f.close()

browser.switch_to.active_element

# Used to download active element source code.
# You can see that after I switch I don't see any html other than what was presented earlier.
with open("active_elment_source.html", "w") as f:
    f.write(browser.page_source)
    f.close()

################## I THINK THIS IS WHERE I NEED HELP ##################
#This is probably just posting nonsense in the empty html body.

# I'm trying to xpath to either a label or anything with the username field.
mystery_field = browser.find_element(By.XPATH,'//*[contains(text(),ernam)]')
#mystery_field = browser.find_element(By.XPATH,"//label[contains(text(),ernam)]")

print(mystery_field.text)

#start_a_doing_stuff = browser.switch_to.frame(mystery_field)

time.sleep(3)

actions.click(mystery_field).perform

time.sleep(3)

actions.send_keys(client_id).perform()

time.sleep(3)

actions.send_keys(Keys.TAB).perform()

time.sleep(3)

actions.send_keys(client_secret).perform()

time.sleep(3)

actions.send_keys(Keys.RETURN).perform()

time.sleep(3)

print("The anonymous key send is done.")

time.sleep(3)

################## I THINK THIS IS WHERE I NEED HELP ##################

# This portion appropriately sends content to authorize url.

#user_name_field = browser.find_element(By.NAME, "username")
#password_field = browser.find_element(By.NAME, "password")

#user_name_field.send_keys(auth_user)

#user_name_field.send_keys(Keys.TAB)

#password_field.send_keys(auth_pass)

#password_field.send_keys(Keys.RETURN)

#actions.perform()

#time.sleep(3)

#When everything is done, this closes your browser.
browser.quit()

When the script runs you can see the cursor in the username field, and when you go to the site the html body is empty.

But, without being able to see any of the fields I'm trying to send keys to the cursor as soon as the auth alert box opens.

I know that selenium doesn't see it as an alert because when I try to send keys to an alert element my code errors out.


问:
why Saving Token in Cookies doesn't work?
Hello EveryOnes please help me i'm have a probléme in saving token Authenticated in Cookies in the browser
Everything work fine in Postman but when i use it in client side i can see the token value in Firefox Only but it hidden in others browser but also in firefox when i reload the page the token disappeare and show me the error Login to acces this resource
and this is my code :

My code from middleware auth:

```<code>  const { token } = req.cookies;

  if (!token) {
    return next(new ErrorHander("Please Login to access this resource", 401));
  }

  const decodedData = jwt.verify(token, process.env.JWT_SECRET);

  req.user = await User.findById(decodedData.id);

  next();
});
</code>```

My code from utils jwtToken :

```<code>const sendToken = (user, statusCode, res) => {
  const token = user.getJWTToken();

  // options for cookie
  const options = {
    expires: new Date(
      Date.now() + process.env.COOKIE_EXPIRE * 24 * 60 * 60 * 1000
    ),
    httpOnly: true,
  };

  res.status(statusCode).cookie("token", token, options).json({
    success: true,
    user,
    token,
  });
};

module.exports = sendToken;

</code>```

My code from userAction :

```<code>// LOGIN
export const login = (email, password) => async (dispatch) => {
  try {
    dispatch({ type: LOGIN_REQUEST });
    const config = {
      headers: {
        "Content-Type": "application/json",
        "Access-Control-Allow-Credentials": true,
      },
    };
    const { data } = await axios.post(
      "http://localhost:4000/api/v1/login",
      { email, password },
      config
    );

    dispatch({ type: LOGIN_SUCCESS, payLoad: data });
  } catch (error) {
    dispatch({ type: LOGIN_FAIL, payLoad: error.response.data.message });
  }
};

</code>```

I was trying to use Access-Control-Allow-Credentials: true in headers
and also using isCredentials : true,

but when i use this last one it show me cors error

and Thanks

Body:
Hello EveryOnes please help me i'm have a probléme in saving token Authenticated in Cookies in the browser
Everything work fine in Postman but when i use it in client side i can see the token value in Firefox Only but it hidden in others browser but also in firefox when i reload the page the token disappeare and show me the error Login to acces this resource
and this is my code :

My code from middleware auth:

  const { token } = req.cookies;

  if (!token) {
    return next(new ErrorHander("Please Login to access this resource", 401));
  }

  const decodedData = jwt.verify(token, process.env.JWT_SECRET);

  req.user = await User.findById(decodedData.id);

  next();
});

My code from utils jwtToken :

const sendToken = (user, statusCode, res) => {
  const token = user.getJWTToken();

  // options for cookie
  const options = {
    expires: new Date(
      Date.now() + process.env.COOKIE_EXPIRE * 24 * 60 * 60 * 1000
    ),
    httpOnly: true,
  };

  res.status(statusCode).cookie("token", token, options).json({
    success: true,
    user,
    token,
  });
};

module.exports = sendToken;

My code from userAction :

// LOGIN
export const login = (email, password) => async (dispatch) => {
  try {
    dispatch({ type: LOGIN_REQUEST });
    const config = {
      headers: {
        "Content-Type": "application/json",
        "Access-Control-Allow-Credentials": true,
      },
    };
    const { data } = await axios.post(
      "http://localhost:4000/api/v1/login",
      { email, password },
      config
    );

    dispatch({ type: LOGIN_SUCCESS, payLoad: data });
  } catch (error) {
    dispatch({ type: LOGIN_FAIL, payLoad: error.response.data.message });
  }
};

I was trying to use Access-Control-Allow-Credentials: true in headers
and also using isCredentials : true,

but when i use this last one it show me cors error

and Thanks


问:
IIS One Click Deployment
I am in a IOT-ish scenario where I need to deploy IIS webservices to a Windows Server instance to various physical sites. It is a background service that plugs into an existing system and supports the equipment that our teams use in the field. IIS was selected for being easy to set up on the computers we already have in the field. Containers or a more modern system could be used if it is a point and click install process.

The catch is that I need to deploy this to airgapped networks. So, it feels like going back to 2006 and emailing zip files around. This service needs to be deployed by highly skilled people who have skills other than computers and thus must be as easy as point and click.

Anybody have a good example of how to build an installer which also sets up the iis webservice?

Web Deploy has not been updated in years and is technally EOL.

MSI installer seems like it will just end up as a mess of powershell scripts to turn services on and set iss settings.

Title: IIS One Click Deployment