问:
When I change my context in an element it is not updated in other elemnts that use the same context
I am making a user context that has all of my user information that I need initially it is null and I update it in the login page but after I login and try to access the context from any other page it is still null

here is the code

CurrentUserContext.js

```<code>import { createContext } from "react";
export const CurrentUserContext = createContext(null);

</code>```

UserContextLayout.jsx

```<code>
import { Outlet } from "react-router-dom";
import { useState, useMemo, useCallback } from "react";
import { CurrentUserContext } from "../hooks/CurrentUserContext";

const UserContextLayout = () => {
  const [currentUserContext, setCurrentUserContext] = useState(null);

  return (
    <CurrentUserContext.Provider
      value={[currentUserContext, setCurrentUserContext]}
    >
      <Outlet />
    </CurrentUserContext.Provider>
  );
};

export default UserContextLayout;

</code>```

MainRouter.jsx

```<code>import { Route, Routes } from "react-router-dom";
import Signin from "./pages/Signin";
import LandingPage from "./pages/LandingPage";
import { isAuthenticated } from "./apis/auth/auth-helper";
import UserContextLayout from "./utils/UserContextLayout";

const MainRouter = () => {
  return (
    <Routes>
      <Route element={<UserContextLayout />}>
        <Route path="/" element={<LandingPage />}></Route>
        <Route
          path="/signin"
          element={
            !isAuthenticated() ? <Signin /> : <Navigate to="/" replace={true} />
          }
        ></Route>
      </Route>
    </Routes>
  );
};

export default MainRouter;

</code>```

Signin.jsx

```<code>import { useState, useContext } from "react";
import { GrTechnology } from "react-icons/gr";
import { CurrentUserContext } from "../hooks/CurrentUserContext";
import { signin } from "../apis/auth/auth-api";
import { authenticate } from "../apis/auth/auth-helper";
import { useNavigate } from "react-router-dom";

const Signin = () => {
  const [currentUserContext, setCurrentUserContext] =
    useContext(CurrentUserContext);

  const navigate = useNavigate();

  const [user1, setUser1] = useState({
    email: "",
    password: "",
  });

  const [rememberMe, setrememberMe] = useState(false);

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

  const handleRememberMeClick = () => {
    setrememberMe((prev) => !prev);
  };

  const handleSubmit = async () => {
    try {
      const response = await signin(user1);

      // if (res.status == 200) {
      setCurrentUserContext(response.data.user);

      authenticate(response.data.token, rememberMe);
      navigate("/");

      // } else {
      //   throw new Error("Authentication failed");
      // }
    } catch (error) {
      console.log(error);
    }
  };

  return (
    <>
      <div >
        <div >

            <h2 >
              Sign in to your account
            </h2>

          <div >

            <div>
              <div>
                <label htmlFor="email-address">
                  Email address
                </label>
                <input
                  id="email-address"
                  name="email"
                  type="email"
                  autoComplete="email"
                  required

                  onChange={handleChange}
                />
              </div>
              <div>
                <label htmlFor="password">
                  Password
                </label>
                <input
                  id="password"
                  name="password"
                  type="password"
                  autoComplete="current-password"
                  required

                  onChange={handleChange}
                />
              </div>
            </div>

            <div >
              <div >
                <input
                  id="remember-me"
                  name="remember-me"
                  type="checkbox"

                  onClick={handleRememberMeClick}
                />
                <label
                  htmlFor="remember-me"

                >
                  Remember me
                </label>
              </div>

            </div>

            <div>
              <button
                type="submit"

                onClick={handleSubmit}
              >
                Sign in
              </button>
            </div>
          </div>
        </div>
      </div>
    </>
  );
};

export default Signin;

</code>```

response.data.user has the user data that I want to save in the context but the context is not updated when I call setCurrentUserContext

Body:
I am making a user context that has all of my user information that I need initially it is null and I update it in the login page but after I login and try to access the context from any other page it is still null

here is the code

CurrentUserContext.js

import { createContext } from "react";
export const CurrentUserContext = createContext(null);

UserContextLayout.jsx

import { Outlet } from "react-router-dom";
import { useState, useMemo, useCallback } from "react";
import { CurrentUserContext } from "../hooks/CurrentUserContext";

const UserContextLayout = () => {
  const [currentUserContext, setCurrentUserContext] = useState(null);

  return (
    <CurrentUserContext.Provider
      value={[currentUserContext, setCurrentUserContext]}
    >
      <Outlet />
    </CurrentUserContext.Provider>
  );
};

export default UserContextLayout;

MainRouter.jsx

import { Route, Routes } from "react-router-dom";
import Signin from "./pages/Signin";
import LandingPage from "./pages/LandingPage";
import { isAuthenticated } from "./apis/auth/auth-helper";
import UserContextLayout from "./utils/UserContextLayout";

const MainRouter = () => {
  return (
    <Routes>
      <Route element={<UserContextLayout />}>
        <Route path="/" element={<LandingPage />}></Route>
        <Route
          path="/signin"
          element={
            !isAuthenticated() ? <Signin /> : <Navigate to="/" replace={true} />
          }
        ></Route>
      </Route>
    </Routes>
  );
};

export default MainRouter;

Signin.jsx

import { useState, useContext } from "react";
import { GrTechnology } from "react-icons/gr";
import { CurrentUserContext } from "../hooks/CurrentUserContext";
import { signin } from "../apis/auth/auth-api";
import { authenticate } from "../apis/auth/auth-helper";
import { useNavigate } from "react-router-dom";

const Signin = () => {
  const [currentUserContext, setCurrentUserContext] =
    useContext(CurrentUserContext);

  const navigate = useNavigate();

  const [user1, setUser1] = useState({
    email: "",
    password: "",
  });

  const [rememberMe, setrememberMe] = useState(false);

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

  const handleRememberMeClick = () => {
    setrememberMe((prev) => !prev);
  };

  const handleSubmit = async () => {
    try {
      const response = await signin(user1);

      // if (res.status == 200) {
      setCurrentUserContext(response.data.user);

      authenticate(response.data.token, rememberMe);
      navigate("/");

      // } else {
      //   throw new Error("Authentication failed");
      // }
    } catch (error) {
      console.log(error);
    }
  };

  return (
    <>

              Sign in to your account

                  Email address

                <input
                  id="email-address"
                  name="email"
                  type="email"
                  autoComplete="email"
                  required

                  onChange={handleChange}
                />

                  Password

                <input
                  id="password"
                  name="password"
                  type="password"
                  autoComplete="current-password"
                  required

                  onChange={handleChange}
                />

                <input
                  id="remember-me"
                  name="remember-me"
                  type="checkbox"

                  onClick={handleRememberMeClick}
                />

                  Remember me

              <button
                type="submit"

                onClick={handleSubmit}
              >
                Sign in
              </button>

    </>
  );
};

export default Signin;

response.data.user has the user data that I want to save in the context but the context is not updated when I call setCurrentUserContext


来源: stackexchange

问:
Login issues - need to type in PW every time I open the browser page
I keep on being logged out from a a website that I am using from my mobile (Iphone with iOS). Every time I close the tab of the browser, I need to login again. On other mobile devises, iOS too, the issue doesn't seem to happen.

Could this somehow be linked with my phone's cookie policy or so, that leads to sessions being deleted after closing a tab?

Best
Nicholas

ContentLicense: CC BY-SA 4.0


问:
Load WebView with download .html file
i want to download and save an HTML file from the Internet. In another activity, I want to take this file and open it with Webview. I tried to save the file to the external storage, but the Play Store does not allow the use of this permission. Manage the external storage unless you have a very good reason to do so. Thanks for your help</p>

Title: Load WebView with download .html file


问:
Spring-boot: Join table with @OneToMany annotation return empty list
I recently started learning Spring Boot and I have a problem. I have two tables (Categories, subcategories) with a one to many relationship. I am having trouble creating this relationship. When requesting the output of all categories, the list of subcategories is empty, but in the database tables are created correctly.

Please tell me what can be wrong.

@Entity
@Table(name ="subcategory")
@Data
public class SubCategoryEntity  {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @Column(nullable=false)
    private String name;

    @ManyToOne( targetEntity = CategoryEntity.class)
    @JoinColumn(name = "category_id")
    private CategoryEntity category;

}
```
<pre class="lang-java prettyprint-override"><code>@Entity
@Table(name = "category")
@Data
public class CategoryEntity {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    @Column(nullable=false)
    private String name;
    @Column(nullable=false)
    private String img;

    @OneToMany(mappedBy = "category", fetch = FetchType.EAGER,
            cascade = CascadeType.ALL, targetEntity = SubCategoryEntity.class)
    private Set<SubCategoryEntity> subcategories;

}
</code>```

@GetMapping("/categories")
public List<CategoryEntity> getCategories() {
    return categoryRepository.findAll();
}
```

Attempt to get data:

Here I tried to get a list of categories and subcategories, but the list of subcategories is empty, although it is not.

Body:
I recently started learning Spring Boot and I have a problem. I have two tables (Categories, subcategories) with a one to many relationship. I am having trouble creating this relationship. When requesting the output of all categories, the list of subcategories is empty, but in the database tables are created correctly.

Please tell me what can be wrong.

@Entity
@Table(name ="subcategory")
@Data
public class SubCategoryEntity  {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @Column(nullable=false)
    private String name;

    @ManyToOne( targetEntity = CategoryEntity.class)
    @JoinColumn(name = "category_id")
    private CategoryEntity category;

}

@Entity
@Table(name = "category")
@Data
public class CategoryEntity {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    @Column(nullable=false)
    private String name;
    @Column(nullable=false)
    private String img;

    @OneToMany(mappedBy = "category", fetch = FetchType.EAGER,
            cascade = CascadeType.ALL, targetEntity = SubCategoryEntity.class)
    private Set<SubCategoryEntity> subcategories;

}

@GetMapping("/categories")
public List<CategoryEntity> getCategories() {
    return categoryRepository.findAll();
}

Attempt to get data:

Here I tried to get a list of categories and subcategories, but the list of subcategories is empty, although it is not.


问:
In WKWebView how do I make it so it fits the margins set within storyboard?
For the webkit I'm having problems setting its size of it. I'm using Swift with Storyboard and I've tried some other solutions but none have worked here:

class ViewController: UIViewController, UIGestureRecognizerDelegate, UIWebViewDelegate, WKNavigationDelegate  {

    let url = URL(string: "google.com")!
    var webView: WKWebView!

    override func viewDidLoad() {
        super.viewDidLoad()
        webView = WKWebView(frame: CGRect( x: 0, y: 20, width: self.view.frame.width, height: self.view.frame.height - 20 ), configuration: WKWebViewConfiguration() )
        self.view.addSubview(webView)
        webView.load(URLRequest(url: url))
        self.webView.allowsBackForwardNavigationGestures = true
    }
}
```


问:
Any way to disable "use password" button in expo LocalAuthentication?
Here is my code

```<code>        const result = await LocalAuthentication.authenticateAsync({
            promptMessage: 'Screen lock security',
        });
</code>```

I am using LocalAuthentication.authenticateAsync to get access to fingerprint or face detection but I dont want to let user to use other method like password or pattern. How can I disable the button?

Thanks!

Body:
Here is my code

        const result = await LocalAuthentication.authenticateAsync({
            promptMessage: 'Screen lock security',
        });

I am using LocalAuthentication.authenticateAsync to get access to fingerprint or face detection but I dont want to let user to use other method like password or pattern. How can I disable the button?

Thanks!


问:
import declarations may only appear at top level of a module - firefox
Hello so I keep getting this error in firefox (works in chrome, edge):

```<code>SyntaxError: import declarations may only appear at top level of a module
</code>```

here is where the issue lies:

```<code> this._workerPool = new WorkerThreadPool(
          _NUM_WORKERS, 'src/terrain-builder-threaded-worker.js');
</code>```

a little background:
I have a

Body:
Hello so I keep getting this error in firefox (works in chrome, edge):

SyntaxError: import declarations may only appear at top level of a module

here is where the issue lies:

 this._workerPool = new WorkerThreadPool(
          _NUM_WORKERS, 'src/terrain-builder-threaded-worker.js');

a little background:
I have a


问:
Function for extract-min on Young tableau succeeds on one array and not the other
For those not familiar with Young tableaus, they must increase in value from left to right and from top to bottom. We may have infinity values, but infinity values can only be at the end, as they are the largest.
I've written a function, extract_min, that removes the smallest value and replaces it with the largest value, and puts infinity at the index where the largest value once was. It then must shift the value at the first position until the rules of the Young tableau are restored (values increase from left to right and top to bottom). For example, in the following table:

12
13
15

13
18
20

15
23
25

We will remove 12, replace it with 25, and replace 25 with infinity, resulting in the following table:

25
13
15

13
18
20

15
23
inf

We then perform an operation that moves the value 25 until the rows and columns are in increasing order from left to right and from top to bottom, respectively. By the end, it should look like this:

11
13
15

18
20
25

22
23
inf

My code is as follows:

```<code>def extract_min(arr):
    min=arr[0][0]
    arr[0][0], arr[len(arr)-1][len(arr)-1]=arr[len(arr)-1][len(arr)-1], float('inf')
    young_order(arr,0,0)
    return min

def young_order(arr, x, y):
    while (arr[x][y] >= arr[x + 1][y] and arr[x][y] >= arr[x][y + 1]):
        if arr[x + 1][y] < arr[x][y + 1] or y+1==len(arr):
            arr[x][y], arr[x + 1][y] = arr[x + 1][y], arr[x][y]
            x += 1
        if arr[x][y+1] < arr[x+1][y] or x + 1 == len(arr):
            arr[x][y], arr[x][y + 1] = arr[x][y + 1], arr[x][y]
            y += 1
    for i in range(len(empty)):
        print(empty[i])
</code>```

For some reason, this function works on the example I've provided, but not on the following table:

1
2
3

4
5
6

7
8
9

My questions are:

Why, and how do I fix it?

How can I possibly make this algorithm run recursively?

TIA.

Body:
For those not familiar with Young tableaus, they must increase in value from left to right and from top to bottom. We may have infinity values, but infinity values can only be at the end, as they are the largest.
I've written a function, extract_min, that removes the smallest value and replaces it with the largest value, and puts infinity at the index where the largest value once was. It then must shift the value at the first position until the rules of the Young tableau are restored (values increase from left to right and top to bottom). For example, in the following table:

12
13
15

13
18
20

15
23
25

We will remove 12, replace it with 25, and replace 25 with infinity, resulting in the following table:

25
13
15

13
18
20

15
23
inf

We then perform an operation that moves the value 25 until the rows and columns are in increasing order from left to right and from top to bottom, respectively. By the end, it should look like this:

11
13
15

18
20
25

22
23
inf

My code is as follows:

def extract_min(arr):
    min=arr[0][0]
    arr[0][0], arr[len(arr)-1][len(arr)-1]=arr[len(arr)-1][len(arr)-1], float('inf')
    young_order(arr,0,0)
    return min

def young_order(arr, x, y):
    while (arr[x][y] >= arr[x + 1][y] and arr[x][y] >= arr[x][y + 1]):
        if arr[x + 1][y] < arr[x][y + 1] or y+1==len(arr):
            arr[x][y], arr[x + 1][y] = arr[x + 1][y], arr[x][y]
            x += 1
        if arr[x][y+1] < arr[x+1][y] or x + 1 == len(arr):
            arr[x][y], arr[x][y + 1] = arr[x][y + 1], arr[x][y]
            y += 1
    for i in range(len(empty)):
        print(empty[i])

For some reason, this function works on the example I've provided, but not on the following table:

1
2
3

4
5
6

7
8
9

My questions are:

Why, and how do I fix it?

How can I possibly make this algorithm run recursively?

TIA.


问:
OSI Selectors, what are their values? C++
I'm working with IEC61850 standard. And at first time I faced OSI Selectors: Transport selector, Session selector and Presentation selector. I'm not interested in their physical meaning.
The task is to convert their values from parsing file (from std::string) into uint8_t. I don't understand how are these values presented?

The values from file(xml schema):

```<code><P type="OSI-PSEL">00000001</P>
<P type="OSI-SSEL">0001</P>
<P type="OSI-TSEL">0001</P>
</code>```

or it can be

```<code><P type="OSI-TSEL">00000001</P>
<P type="OSI-PSEL">01</P>
<P type="OSI-SSEL">01</P>
</code>```

in xsd I got this infromation about them:

```<code><xs:complexType name="tP_OSI-TSEL">
     <xs:restriction base="tP">
     <xs:maxLength value="8"/>
     <xs:pattern value="[0-9,A-F]+"/>
     </xs:restriction>
</xs:complexType>
<xs:complexType name="tP_OSI-SSEL">
     <xs:restriction base="tP">
     <xs:maxLength value="16"/>
     <xs:pattern value="[0-9,A-F]+"/>
     </xs:restriction>
</xs:complexType>
<xs:complexType name="tP_OSI-PSEL">
     <xs:restriction base="tP">
     <xs:maxLength value="16"/>
     <xs:pattern value="[0-9,A-F]+"/>
     </xs:restriction>
</xs:complexType>
</code>```

Are 01 or 00001 or 00000001 etc represented in binary number system? Why do they have different length? I mean if 00000001 is an octet, what is 00001 and 01 then?

Body:
I'm working with IEC61850 standard. And at first time I faced OSI Selectors: Transport selector, Session selector and Presentation selector. I'm not interested in their physical meaning.
The task is to convert their values from parsing file (from std::string) into uint8_t. I don't understand how are these values presented?

The values from file(xml schema):

00000001

0001

0001

or it can be

00000001

01

01

in xsd I got this infromation about them:

<xs:complexType name="tP_OSI-TSEL">
     <xs:restriction base="tP">
     <xs:maxLength value="8"/>
     <xs:pattern value="[0-9,A-F]+"/>
     </xs:restriction>
</xs:complexType>
<xs:complexType name="tP_OSI-SSEL">
     <xs:restriction base="tP">
     <xs:maxLength value="16"/>
     <xs:pattern value="[0-9,A-F]+"/>
     </xs:restriction>
</xs:complexType>
<xs:complexType name="tP_OSI-PSEL">
     <xs:restriction base="tP">
     <xs:maxLength value="16"/>
     <xs:pattern value="[0-9,A-F]+"/>
     </xs:restriction>
</xs:complexType>

Are 01 or 00001 or 00000001 etc represented in binary number system? Why do they have different length? I mean if 00000001 is an octet, what is 00001 and 01 then?


问:
Why I dont get an exception when fluent nHibernate fails to create table?
I use fluent nHibernate to connect to a SQL Server database. So this is my domain class:

```<code>public class Option
{
    public virtual long Id { get; set; }

    public virtual string User { get; set; }

    public virtual string SvnTrunkFolder { get; set; }

}
</code>```

And this is my mapping class

```<code>public class OptionMap : ClassMap<Option>
{
    public OptionMap()
    {
        Id(x => x.Id);
        Map(x => x.User);
        Map(x => x.SvnTrunkFolder);
    }
}
</code>```

This domain class has a problem. 'User' is a keyword of SQL Server. So the create-statement nHibernate uses (as found in Visual Studios Debug Output) is:

```<code>create table mydb.[Option] (
    Id BIGINT IDENTITY NOT NULL,
   User NVARCHAR(255) null,
   SvnTrunkFolder NVARCHAR(255) null,
   primary key (Id)
)
</code>```

When I paste this to my SQL Server Manager and try it I get the following error:

```<code>Msg 156, Level 15, State 1, Line 3
Incorrect syntax near the keyword 'User'.
</code>```

My problem is, that nHibernate dont tell me about this. I get no exception, no error. Everything seems normal. But the table is not created. When I change the Property "User" to "WindowsUser" the table is created perfectly.

This is the function I use to connect to the database:

```<code>public ISessionFactory CreateSessionFactory(IDatabaseConnectionInformation connectInfo, Action<MappingConfiguration> mappings)
{
    var configure = Fluently.Configure();
    var dbConfig = MsSqlConfiguration.MsSql2012.ConnectionString(connectInfo.ConnectionString);
    var dbConfigWithSchema = dbConfig.DefaultSchema(connectInfo.Database);
    var fluentDb = configure.Database(dbConfigWithSchema);
    var fluentMap = fluentDb.Mappings(mappings);
    fluentMap = fluentMap.ExposeConfiguration(BuildSchema);
    return fluentMap.BuildSessionFactory();
}
private static void BuildSchema(Configuration config)
{
    new SchemaUpdate(config)
          .Execute(true, true);
}
</code>```

So my question is: Why did nHibernate did not tell me about the failure to create the table? Do I have to activate something? Or is this just a bug with this particular error?

Edit:
This does not answer my question because my question is !not! how I can create this column. I can just rename it. My question is: why nHibernate does not throw an exception when its not able to create the table?

Body:
I use fluent nHibernate to connect to a SQL Server database. So this is my domain class:

public class Option
{
    public virtual long Id { get; set; }

    public virtual string User { get; set; }

    public virtual string SvnTrunkFolder { get; set; }

}

And this is my mapping class

public class OptionMap : ClassMap<Option>
{
    public OptionMap()
    {
        Id(x => x.Id);
        Map(x => x.User);
        Map(x => x.SvnTrunkFolder);
    }
}

This domain class has a problem. 'User' is a keyword of SQL Server. So the create-statement nHibernate uses (as found in Visual Studios Debug Output) is:

create table mydb.[Option] (
    Id BIGINT IDENTITY NOT NULL,
   User NVARCHAR(255) null,
   SvnTrunkFolder NVARCHAR(255) null,
   primary key (Id)
)

When I paste this to my SQL Server Manager and try it I get the following error:

Msg 156, Level 15, State 1, Line 3
Incorrect syntax near the keyword 'User'.

My problem is, that nHibernate dont tell me about this. I get no exception, no error. Everything seems normal. But the table is not created. When I change the Property "User" to "WindowsUser" the table is created perfectly.

This is the function I use to connect to the database:

public ISessionFactory CreateSessionFactory(IDatabaseConnectionInformation connectInfo, Action<MappingConfiguration> mappings)
{
    var configure = Fluently.Configure();
    var dbConfig = MsSqlConfiguration.MsSql2012.ConnectionString(connectInfo.ConnectionString);
    var dbConfigWithSchema = dbConfig.DefaultSchema(connectInfo.Database);
    var fluentDb = configure.Database(dbConfigWithSchema);
    var fluentMap = fluentDb.Mappings(mappings);
    fluentMap = fluentMap.ExposeConfiguration(BuildSchema);
    return fluentMap.BuildSessionFactory();
}
private static void BuildSchema(Configuration config)
{
    new SchemaUpdate(config)
          .Execute(true, true);
}

So my question is: Why did nHibernate did not tell me about the failure to create the table? Do I have to activate something? Or is this just a bug with this particular error?

Edit:
This does not answer my question because my question is !not! how I can create this column. I can just rename it. My question is: why nHibernate does not throw an exception when its not able to create the table?


问:
Is there a way to set up a clean testing environment for Cypress each time I run tests?
We use Cypress for thorough e2e testing on our site.
The Tech stack is React + Node(koa.js).

We have a high test coverage since we tend to mock most of the user actions (most of the crud methods as well).

It happens sometimes that a test suite fails during the execution (or is interrupted by something) so we have a duplicated entry on the next run (create test fails). Then I need to manually delete testing entries from the site and re-run the pipeline.

We want to make sure that we have a clean database for testing on each run. I could use an advice. Thanks in advance!


问:
Error: "message":"PermissionDenied","type":"DomainError" after user tried to log in
Please, could you give me some clue or indication where to go?
I have checked the settings several times from our side, we are the IDP, and I am not able to detect the reason for this error.

The flow is:

User reaches the RP website => Click on Log In => A new window opens so that the user can log in to the IDP => The user enters their credentials and clicks on Log In => The window displays the following error:

"message":"PermissionDenied","type":"DomainError"

Many Thanks


问:
Android Jetpack App crawler does not run locally
I used the official jetpack android app crawler docs
Ran the following command inside of the app crawler folder where the .jar file is located.

```<code>java -jar crawl_launcher.jar --apk-file file.apk --android-sdk C:\Users\Owner\AppData\Local\Android\Sdk
</code>```

No error popped up but it just stays as is with no changes to the console and it seems it isn't running because the default timeout is 60s (I waited for almost 30 mins).

What is missing to be able to have the app crawler working

Body:
I used the official jetpack android app crawler docs
Ran the following command inside of the app crawler folder where the .jar file is located.

java -jar crawl_launcher.jar --apk-file file.apk --android-sdk C:\Users\Owner\AppData\Local\Android\Sdk

No error popped up but it just stays as is with no changes to the console and it seems it isn't running because the default timeout is 60s (I waited for almost 30 mins).

What is missing to be able to have the app crawler working


问:
How to map JSON to Java Pojo Class when consuming REST API using RestTemplate Spring Boot?
I am working on consuming or calling an external Restful API in my application. To achieve this I am using RestTemplate. As for now, I am making GET call only. So the response I am getting is in JSON format. Now I want to display that JSON data according to my Pojo class that I've created and to display result when hitting my API using postman.

So I have created RestController and Service class as below:

This is my CustomerService class to fetch list of all the clients or users available on third party platform.

```<code>public String getListOfAllClients() {
        ResponseEntity<String> responseEntity = null;
        String jsonResponse = null;
        try {
            final String uri = "https://chapi.cloudhealthtech.com/v2/customers";
            RestTemplate restTemplate = new RestTemplate();
            HttpHeaders header = new HttpHeaders();
            header.set(HttpHeaders.AUTHORIZATION, "Bearer "+apiKey);
            header.set(HttpHeaders.ACCEPT, "application/json");

            HttpEntity<String> requestEntity = new HttpEntity<String>("body",header);
            responseEntity = restTemplate.exchange(uri, HttpMethod.GET, requestEntity, String.class);
            jsonResponse =  responseEntity.getBody();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return jsonResponse;
    }
</code>```

So, in my service class, I want to use something like this

```<code>HttpEntity<Customers> requestEntity = new HttpEntity<Customers>("body",header);
ResponseEntity<Customers> responseEntity = restTemplate.exchange(uri, HttpMethod.GET, requestEntity, Customers.class);
</code>```

Is it possible?

This is my RestController to display JSON data using ResponseEntity:

```<code>@RequestMapping(value = {"/clients"}, method = {RequestMethod.GET, RequestMethod.POST}, produces = {MediaType.APPLICATION_JSON_VALUE})
    public ResponseEntity<?> getAllClients(){
        try {
            String response = cspPartnerCustomerService.getListOfAllClients();
            return new ResponseEntity<Object>(response, HttpStatus.OK);
        } catch (Exception e) {
            e.printStackTrace();
            return new ResponseEntity<Object>("Please try again later", HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }
</code>```

And this is the response I am getting from the platform using my application:

```<code>{
    "customers": [
        {
            "id": 1234,
            "name": "Company A",
            "classification": "managed_with_access",
            "billing_contact": "",
            "margin_percentage": 15.0,
            "created_at": "2020-08-05T17:35:09Z",
            "updated_at": "2022-12-06T23:04:50Z",
            "generated_external_id": "5da41675590749c41e9c9301527e4d",
            "address": {
                "street1": "123 Compugen Dr.",
                "street2": "",
                "city": "Toronto",
                "state": "08",
                "zipcode": "A2B 3B5",
                "country": "CA"
            },
        },
        {
            "id": 5678,
            "name": "Company B",
            "classification": "managed_without_access",
            "margin_percentage": 0.0,
            "created_at": "2021-01-20T15:30:31Z",
            "updated_at": "2022-12-07T02:56:40Z",
            "generated_external_id": "1d8a3f2f11265bd004562c5d8d2a0d",
            "address": {
                "street1": "100 Via Renzo Drive",
                "street2": "",
                "city": "Richmond Hill",
                "state": "08",
                "zipcode": "L4S 0B8",
                "country": "CA"
            },
        }
    ]
}
</code>```

Body:
I am working on consuming or calling an external Restful API in my application. To achieve this I am using RestTemplate. As for now, I am making GET call only. So the response I am getting is in JSON format. Now I want to display that JSON data according to my Pojo class that I've created and to display result when hitting my API using postman.

So I have created RestController and Service class as below:

This is my CustomerService class to fetch list of all the clients or users available on third party platform.

public String getListOfAllClients() {
        ResponseEntity<String> responseEntity = null;
        String jsonResponse = null;
        try {
            final String uri = "https://chapi.cloudhealthtech.com/v2/customers";
            RestTemplate restTemplate = new RestTemplate();
            HttpHeaders header = new HttpHeaders();
            header.set(HttpHeaders.AUTHORIZATION, "Bearer "+apiKey);
            header.set(HttpHeaders.ACCEPT, "application/json");

            HttpEntity<String> requestEntity = new HttpEntity<String>("body",header);
            responseEntity = restTemplate.exchange(uri, HttpMethod.GET, requestEntity, String.class);
            jsonResponse =  responseEntity.getBody();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return jsonResponse;
    }

So, in my service class, I want to use something like this

HttpEntity<Customers> requestEntity = new HttpEntity<Customers>("body",header);
ResponseEntity<Customers> responseEntity = restTemplate.exchange(uri, HttpMethod.GET, requestEntity, Customers.class);

Is it possible?

This is my RestController to display JSON data using ResponseEntity:

@RequestMapping(value = {"/clients"}, method = {RequestMethod.GET, RequestMethod.POST}, produces = {MediaType.APPLICATION_JSON_VALUE})
    public ResponseEntity<?> getAllClients(){
        try {
            String response = cspPartnerCustomerService.getListOfAllClients();
            return new ResponseEntity<Object>(response, HttpStatus.OK);
        } catch (Exception e) {
            e.printStackTrace();
            return new ResponseEntity<Object>("Please try again later", HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

And this is the response I am getting from the platform using my application:

{
    "customers": [
        {
            "id": 1234,
            "name": "Company A",
            "classification": "managed_with_access",
            "billing_contact": "",
            "margin_percentage": 15.0,
            "created_at": "2020-08-05T17:35:09Z",
            "updated_at": "2022-12-06T23:04:50Z",
            "generated_external_id": "5da41675590749c41e9c9301527e4d",
            "address": {
                "street1": "123 Compugen Dr.",
                "street2": "",
                "city": "Toronto",
                "state": "08",
                "zipcode": "A2B 3B5",
                "country": "CA"
            },
        },
        {
            "id": 5678,
            "name": "Company B",
            "classification": "managed_without_access",
            "margin_percentage": 0.0,
            "created_at": "2021-01-20T15:30:31Z",
            "updated_at": "2022-12-07T02:56:40Z",
            "generated_external_id": "1d8a3f2f11265bd004562c5d8d2a0d",
            "address": {
                "street1": "100 Via Renzo Drive",
                "street2": "",
                "city": "Richmond Hill",
                "state": "08",
                "zipcode": "L4S 0B8",
                "country": "CA"
            },
        }
    ]
}


问:
HTML Diff File is getting malformed
With difflib library I am trying to generate the diff file which is in html format. It works for most of the time but for few times, the generate html is malformed. Sometimes it also observed that formed html doesn't have all the content and sometimes the formed content doesn't have the lines at proper place.
Below is the code I am using for it:

```<code>import difflib
try:
    print("Reading file from first file")
    firstfile = open(firstFilePath, "r")
    contentsFirst = firstfile.readlines()
    print("Reading file from second file")
    secondfile = open(secondFilePath, "r")
    contentsSecond = secondfile.readlines()
    print("Creating diff file:")
    config_diff = difflib.HtmlDiff(wrapcolumn=70).make_file(contentsSecond, contentsFirst)
    if not os.path.exists(diff_file_path):
        os.makedirs(diff_file_path)
    final_path = diff_file_path + "/" + diff_file_name + '.html'
    diff_file = open(final_path, 'w')
    diff_file.write(config_diff)
    print("Diff file is genrated :")
except Exception as error:
    print("Exception occurred in create_diff_file " + str(error))
    raise Exception(str(error))
</code>```

This piece of code is called in a threaded program. Although with retry, I get the desired result but doesn't know the reason for getting malformed and inconsistent diff file. If someone can help me in finding the actual reason behind it and can propose the solution, will be helpful for me.

Title: HTML Diff File is getting malformed

Body:
With difflib library I am trying to generate the diff file which is in html format. It works for most of the time but for few times, the generate html is malformed. Sometimes it also observed that formed html doesn't have all the content and sometimes the formed content doesn't have the lines at proper place.
Below is the code I am using for it:

import difflib
try:
    print("Reading file from first file")
    firstfile = open(firstFilePath, "r")
    contentsFirst = firstfile.readlines()
    print("Reading file from second file")
    secondfile = open(secondFilePath, "r")
    contentsSecond = secondfile.readlines()
    print("Creating diff file:")
    config_diff = difflib.HtmlDiff(wrapcolumn=70).make_file(contentsSecond, contentsFirst)
    if not os.path.exists(diff_file_path):
        os.makedirs(diff_file_path)
    final_path = diff_file_path + "/" + diff_file_name + '.html'
    diff_file = open(final_path, 'w')
    diff_file.write(config_diff)
    print("Diff file is genrated :")
except Exception as error:
    print("Exception occurred in create_diff_file " + str(error))
    raise Exception(str(error))

This piece of code is called in a threaded program. Although with retry, I get the desired result but doesn't know the reason for getting malformed and inconsistent diff file. If someone can help me in finding the actual reason behind it and can propose the solution, will be helpful for me.


问:
How to use Scope Trigger in UIPath StudioX?
I’m using StudioX and I need to upload a file from my local OneDrive to a site that we are using in my enterprise, and I need to launch the Robot when the file is added to my local OneDrive! If it's possible to use trigger scope in UIPath StudioX and which package, should I install to use this trigger?</p>


问:
How to apply custom function to grouped pandas data?
fI have a dataframe with columns for IDs, measurements and uncertainties. For some IDs I have more than one value for measurement and uncertainty, so for each ID I need to take the mean of the measurements and add the uncertainties in quadrature. I can use

```<code>df["measurement"] = df.groupby("ID")["measurement"].transform("mean")
</code>```

to get the mean of the measurements, but I can't find a way to get the uncertainties added in quadrature (so a function to perform sqrt((uncertainty_1)**2 + (uncertainty_2)**2 + ...) on the uncertainties _1, _2 and so on in each ID group) to work on grouped data.

I'm looking for something like:

```<code>df["uncertainty"] = df.groupby("ID")["uncertainty"].transform("(custom function)").
</code>```

I looked into using e.g. df.groupby("ID")["uncertainty"].apply(lambda x: custom function) but couldn't get a custom function to work (I tried a few lambda functions but the output values didn't change). Many thanks for your help.

Body:
fI have a dataframe with columns for IDs, measurements and uncertainties. For some IDs I have more than one value for measurement and uncertainty, so for each ID I need to take the mean of the measurements and add the uncertainties in quadrature. I can use

df["measurement"] = df.groupby("ID")["measurement"].transform("mean")

to get the mean of the measurements, but I can't find a way to get the uncertainties added in quadrature (so a function to perform sqrt((uncertainty_1)**2 + (uncertainty_2)**2 + ...) on the uncertainties _1, _2 and so on in each ID group) to work on grouped data.

I'm looking for something like:

df["uncertainty"] = df.groupby("ID")["uncertainty"].transform("(custom function)").

I looked into using e.g. df.groupby("ID")["uncertainty"].apply(lambda x: custom function) but couldn't get a custom function to work (I tried a few lambda functions but the output values didn't change). Many thanks for your help.


问:
Getting a .app instead of .ipa as final artifact from cmake
TL;DR

My question is : How can CMake be used to build an IPA? currently we are getting a .app artifact as final product, Does CMake have the required commands or targets to do this ? Earlier we were using XCodebuild -exportArchive option for same.

I am trying to port an iOS application from Qt5 (build with Qmake) to Qt6 (build with Cmake), and I have successfully completed compilation and linking stages.
I am getting an archive as App.app instead of an expected App.ipa

commands used to build app

```<code>cmake -H. -Bbuildxcode -DCMAKE_PREFIX_PATH=/Users/cybercraft/Qt/6.2.4/ios -DCMAKE_TOOLCHAIN_FILE=../ios.toolchain.cmake -DPLATFORM=OS64  -DENABLE_BITCODE=NO -GXcode
cmake --build buildxcode
</code>```

I have a bash script that does build an ipa with Qt5.12.11, I've compared the xproj files (from both bash build and cmake build) side by side for every setting, didnt find any difference for packaging/signing.
    Building ipa directly from command line using XCodebuild -exportArchive didnt work as well, producing same .app instead of .ipa.

I'm new to cmake and iOS development, am I missing something critical?

I have added my CMakeLists.txt file here [ https://pastebin.com/VD2DxHNi ]

ios.toolchain.cmake is taken from [ https://github.com/leetal/ios-cmake ]

My info.plist file here [https://pastebin.com/qcrd6Fdy ]

My export.plist file here [ https://pastebin.com/eJiVnwFt ]

screenshot of compilation process "with build successfull" [ https://imgur.com/a/97PCXeZ ]

```<code>Build environment Details:
Qt version: 5.12.11
qmake version: 3.1
MacOs version: 12.6 (Monterey, M1 2020)
Xcode version: 14.0.1 (14A400)
xcodebuild version: 14.0.1 (14A400)
cmake version: 3.24.2
boost version: 1.80.0
</code>```

I've already followed few online suggestions and solutions mentioned in forums, but none of them worked, if you want me to add thoses, I'll add them too, just let me know if it helps.
although my question could possibly be a duplicate of Creating an .ipa from .app for iOS using CMake still hoping to find some solutions.

Xcode creates archive instead of IPA and
Get ipa from Xcode didnt help as well.

Regards.

Body:
TL;DR

My question is : How can CMake be used to build an IPA? currently we are getting a .app artifact as final product, Does CMake have the required commands or targets to do this ? Earlier we were using XCodebuild -exportArchive option for same.

I am trying to port an iOS application from Qt5 (build with Qmake) to Qt6 (build with Cmake), and I have successfully completed compilation and linking stages.
I am getting an archive as App.app instead of an expected App.ipa

commands used to build app

cmake -H. -Bbuildxcode -DCMAKE_PREFIX_PATH=/Users/cybercraft/Qt/6.2.4/ios -DCMAKE_TOOLCHAIN_FILE=../ios.toolchain.cmake -DPLATFORM=OS64  -DENABLE_BITCODE=NO -GXcode
cmake --build buildxcode

I have a bash script that does build an ipa with Qt5.12.11, I've compared the xproj files (from both bash build and cmake build) side by side for every setting, didnt find any difference for packaging/signing.
    Building ipa directly from command line using XCodebuild -exportArchive didnt work as well, producing same .app instead of .ipa.

I'm new to cmake and iOS development, am I missing something critical?

I have added my CMakeLists.txt file here [ https://pastebin.com/VD2DxHNi ]

ios.toolchain.cmake is taken from [ https://github.com/leetal/ios-cmake ]

My info.plist file here [https://pastebin.com/qcrd6Fdy ]

My export.plist file here [ https://pastebin.com/eJiVnwFt ]

screenshot of compilation process "with build successfull" [ https://imgur.com/a/97PCXeZ ]

Build environment Details:
Qt version: 5.12.11
qmake version: 3.1
MacOs version: 12.6 (Monterey, M1 2020)
Xcode version: 14.0.1 (14A400)
xcodebuild version: 14.0.1 (14A400)
cmake version: 3.24.2
boost version: 1.80.0

I've already followed few online suggestions and solutions mentioned in forums, but none of them worked, if you want me to add thoses, I'll add them too, just let me know if it helps.
although my question could possibly be a duplicate of Creating an .ipa from .app for iOS using CMake still hoping to find some solutions.

Xcode creates archive instead of IPA and
Get ipa from Xcode didnt help as well.

Regards.


问:
Identity IQ does not start
Currently, I am using a virtual machine in Oracle cloud. I have successfully installed Tomcat and IdentityIQ. The server is deployed correctly, but when I try to access through Google Chrome with the credentials, I get the following error.

I have disabled the firewall and when I try to test the connection with ping it does not respond.

Title: Identity IQ does not start


问:
Python: I have a problem with "Graph execution error"
I wrote this code which gives me this error "Graph execution error". On my friend's pc the code works without errors. what could be the problem?
I've checked the versions of the various libraries and everything seems to be the same.
I'm working in spyder environment and I don't understand what the problem is.
This is the error</p>
```<code> File "C:\Users\hp\anaconda3\envs\unet\lib\site-packages\spyder_kernels\py3compat.py", line 356, in compat_exec
    exec(code, globals, locals)

  File "c:\users\hp\desktop\universita_laurea_magistrale\tirocinio\dataset\codiceprof.py", line 147, in <module>
    storia=model.fit(train_gen, epochs=epochs, validation_data=train_gen)

  File "C:\Users\hp\anaconda3\envs\unet\lib\site-packages\keras\utils\traceback_utils.py", line 70, in error_handler
    raise e.with_traceback(filtered_tb) from None

  File "C:\Users\hp\anaconda3\envs\unet\lib\site-packages\tensorflow\python\eager\execute.py", line 54, in quick_execute
    tensors = pywrap_tfe.TFE_Py_Execute(ctx._handle, device_name, op_name,

InvalidArgumentError: Graph execution error:

Detected at node 'sparse_categorical_crossentropy/SparseSoftmaxCrossEntropyWithLogits/SparseSoftmaxCrossEntropyWithLogits' defined at (most recent call last):
    File "C:\Users\hp\anaconda3\envs\unet\lib\runpy.py", line 197, in _run_module_as_main
      return _run_code(code, main_globals, None,
    File "C:\Users\hp\anaconda3\envs\unet\lib\runpy.py", line 87, in _run_code
      exec(code, run_globals)
    File "C:\Users\hp\anaconda3\envs\unet\lib\site-packages\spyder_kernels\console\__main__.py", line 24, in <module>
      start.main()
    File "C:\Users\hp\anaconda3\envs\unet\lib\site-packages\spyder_kernels\console\start.py", line 340, in main
      kernel.start()
    File "C:\Users\hp\anaconda3\envs\unet\lib\site-packages\ipykernel\kernelapp.py", line 712, in start
      self.io_loop.start()
    File "C:\Users\hp\anaconda3\envs\unet\lib\site-packages\tornado\platform\asyncio.py", line 215, in start
      self.asyncio_loop.run_forever()
    File "C:\Users\hp\anaconda3\envs\unet\lib\asyncio\base_events.py", line 596, in run_forever
      self._run_once()
    File "C:\Users\hp\anaconda3\envs\unet\lib\asyncio\base_events.py", line 1890, in _run_once
      handle._run()
    File "C:\Users\hp\anaconda3\envs\unet\lib\asyncio\events.py", line 80, in _run
      self._context.run(self._callback, *self._args)
    File "C:\Users\hp\anaconda3\envs\unet\lib\site-packages\ipykernel\kernelbase.py", line 510, in dispatch_queue
      await self.process_one()
    File "C:\Users\hp\anaconda3\envs\unet\lib\site-packages\ipykernel\kernelbase.py", line 499, in process_one
      await dispatch(*args)
    File "C:\Users\hp\anaconda3\envs\unet\lib\site-packages\ipykernel\kernelbase.py", line 406, in dispatch_shell
      await result
    File "C:\Users\hp\anaconda3\envs\unet\lib\site-packages\ipykernel\kernelbase.py", line 730, in execute_request
      reply_content = await reply_content
    File "C:\Users\hp\anaconda3\envs\unet\lib\site-packages\ipykernel\ipkernel.py", line 390, in do_execute
      res = shell.run_cell(code, store_history=store_history, silent=silent)
    File "C:\Users\hp\anaconda3\envs\unet\lib\site-packages\ipykernel\zmqshell.py", line 528, in run_cell
      return super().run_cell(*args, **kwargs)
    File "C:\Users\hp\anaconda3\envs\unet\lib\site-packages\IPython\core\interactiveshell.py", line 2914, in run_cell
      result = self._run_cell(
    File "C:\Users\hp\anaconda3\envs\unet\lib\site-packages\IPython\core\interactiveshell.py", line 2960, in _run_cell
      return runner(coro)
    File "C:\Users\hp\anaconda3\envs\unet\lib\site-packages\IPython\core\async_helpers.py", line 78, in _pseudo_sync_runner
      coro.send(None)
    File "C:\Users\hp\anaconda3\envs\unet\lib\site-packages\IPython\core\interactiveshell.py", line 3185, in run_cell_async
      has_raised = await self.run_ast_nodes(code_ast.body, cell_name,
    File "C:\Users\hp\anaconda3\envs\unet\lib\site-packages\IPython\core\interactiveshell.py", line 3377, in run_ast_nodes
      if (await self.run_code(code, result,  async_=asy)):
    File "C:\Users\hp\anaconda3\envs\unet\lib\site-packages\IPython\core\interactiveshell.py", line 3457, in run_code
      exec(code_obj, self.user_global_ns, self.user_ns)
    File "C:\Users\hp\AppData\Local\Temp\ipykernel_9760\815882102.py", line 1, in <module>
      runfile('C:/Users/hp/Desktop/Universita_laurea_Magistrale/TIROCINIO/Dataset/codiceprof.py', wdir='C:/Users/hp/Desktop/Universita_laurea_Magistrale/TIROCINIO/Dataset')
    File "C:\Users\hp\anaconda3\envs\unet\lib\site-packages\spyder_kernels\customize\spydercustomize.py", line 524, in runfile
      return _exec_file(
    File "C:\Users\hp\anaconda3\envs\unet\lib\site-packages\spyder_kernels\customize\spydercustomize.py", line 611, in _exec_file
      exec_code(file_code, filename, ns_globals, ns_locals,
    File "C:\Users\hp\anaconda3\envs\unet\lib\site-packages\spyder_kernels\customize\spydercustomize.py", line 469, in exec_code
      exec_fun(compile(ast_code, filename, 'exec'), ns_globals, ns_locals)
    File "C:\Users\hp\anaconda3\envs\unet\lib\site-packages\spyder_kernels\py3compat.py", line 356, in compat_exec
      exec(code, globals, locals)
    File "c:\users\hp\desktop\universita_laurea_magistrale\tirocinio\dataset\codiceprof.py", line 147, in <module>
      storia=model.fit(train_gen, epochs=epochs, validation_data=train_gen)
    File "C:\Users\hp\anaconda3\envs\unet\lib\site-packages\keras\utils\traceback_utils.py", line 65, in error_handler
      return fn(*args, **kwargs)
    File "C:\Users\hp\anaconda3\envs\unet\lib\site-packages\keras\engine\training.py", line 1564, in fit
      tmp_logs = self.train_function(iterator)
    File "C:\Users\hp\anaconda3\envs\unet\lib\site-packages\keras\engine\training.py", line 1160, in train_function
      return step_function(self, iterator)
    File "C:\Users\hp\anaconda3\envs\unet\lib\site-packages\keras\engine\training.py", line 1146, in step_function
      outputs = model.distribute_strategy.run(run_step, args=(data,))
    File "C:\Users\hp\anaconda3\envs\unet\lib\site-packages\keras\engine\training.py", line 1135, in run_step
      outputs = model.train_step(data)
    File "C:\Users\hp\anaconda3\envs\unet\lib\site-packages\keras\engine\training.py", line 994, in train_step
      loss = self.compute_loss(x, y, y_pred, sample_weight)
    File "C:\Users\hp\anaconda3\envs\unet\lib\site-packages\keras\engine\training.py", line 1052, in compute_loss
      return self.compiled_loss(
    File "C:\Users\hp\anaconda3\envs\unet\lib\site-packages\keras\engine\compile_utils.py", line 265, in __call__
      loss_value = loss_obj(y_t, y_p, sample_weight=sw)
    File "C:\Users\hp\anaconda3\envs\unet\lib\site-packages\keras\losses.py", line 152, in __call__
      losses = call_fn(y_true, y_pred)
    File "C:\Users\hp\anaconda3\envs\unet\lib\site-packages\keras\losses.py", line 272, in call
      return ag_fn(y_true, y_pred, **self._fn_kwargs)
    File "C:\Users\hp\anaconda3\envs\unet\lib\site-packages\keras\losses.py", line 2084, in sparse_categorical_crossentropy
      return backend.sparse_categorical_crossentropy(
    File "C:\Users\hp\anaconda3\envs\unet\lib\site-packages\keras\backend.py", line 5630, in sparse_categorical_crossentropy
      res = tf.nn.sparse_softmax_cross_entropy_with_logits(
Node: 'sparse_categorical_crossentropy/SparseSoftmaxCrossEntropyWithLogits/SparseSoftmaxCrossEntropyWithLogits'
logits and labels must have the same first dimension, got logits shape [2048,2] and labels shape [131072]
     [[{{node sparse_categorical_crossentropy/SparseSoftmaxCrossEntropyWithLogits/SparseSoftmaxCrossEntropyWithLogits}}]] [Op:__inference_train_function_14691]
</code>```
```<code>from tensorflow import keras
import numpy as np
from tensorflow.keras.preprocessing.image import load_img
from tensorflow.keras.preprocessing.image import img_to_array
import PIL

from keras.models import Model
from keras.layers import Input, Conv2D, MaxPooling2D, UpSampling2D, concatenate, Conv2DTranspose, BatchNormalization, Dropout, Lambda
from keras.optimizers import Adam
from keras.layers import Activation, MaxPool2D, Concatenate

import glob
import matplotlib
import matplotlib.pyplot as plt
from matplotlib import pyplot as plt
from tensorflow.keras import layers

class leggi_immagini(keras.utils.Sequence):

    def __init__(self, batch_size, img_size, input_img_paths, target_img_paths):
        self.batch_size = batch_size
        self.img_size = img_size
        self.input_img_paths = input_img_paths
        self.target_img_paths = target_img_paths

    def __len__(self):
        return len(self.target_img_paths) // self.batch_size

    def __getitem__(self, idx):
        """Returns tuple (input, target) correspond to batch #idx."""
        i = idx * self.batch_size
        batch_input_img_paths = self.input_img_paths[i : i + self.batch_size]
        batch_target_img_paths = self.target_img_paths[i : i + self.batch_size]
        x = np.zeros((self.batch_size,) + self.img_size +(1,), dtype="float32")
        for j, path in enumerate(batch_input_img_paths):
            #print("eccomi")
            img = load_img(path,  color_mode='grayscale')
            x[j] = img_to_array(img) #/ 8191 # normalizza al massimo
        y = np.zeros((self.batch_size,) + self.img_size + (1,), dtype="uint8")
        for j, path2 in enumerate(batch_target_img_paths):
            img2 = load_img(path2, color_mode="grayscale")
            y[j] = img_to_array(img2) / 255
        return x, y

def get_model(img_size, num_classes):
    inputs = keras.Input(shape=img_size + (1,))

    ### [First half of the network: downsampling inputs] ###

    # Entry block
    x = layers.Conv2D(32, (3,3),strides=2,padding="same",input_shape=(256,256,1))(inputs)# strides=2, padding="same")(inputs)
    x = layers.BatchNormalization()(x)
    x = layers.Activation("relu")(x)

    previous_block_activation = x  # Set aside residual

    # Blocks 1, 2, 3 are identical apart from the feature depth.
    for filters in [64, 128, 256]:
       x = layers.Activation("relu")(x)
       x = layers.SeparableConv2D(filters, 3, padding="same")(x)
       x = layers.BatchNormalization()(x)

       x = layers.Activation("relu")(x)
       x = layers.SeparableConv2D(filters, 3, padding="same")(x)
       x = layers.BatchNormalization()(x)

       x = layers.MaxPooling2D(3, strides=2, padding="same")(x)

      # Project residual
       residual = layers.Conv2D(filters, 1, strides=2, padding="same")(
           previous_block_activation
       )
       x = layers.add([x, residual])  # Add back residual
       previous_block_activation = x  # Set aside next residual

      ### [Second half of the network: upsampling inputs] ###

    for filters in [256, 128, 64, 32]:
       x = layers.Activation("relu")(x)
       x = layers.Conv2DTranspose(filters, 3, padding="same")(x)
       x = layers.BatchNormalization()(x)

       x = layers.Activation("relu")(x)
       x = layers.Conv2DTranspose(filters, 3, padding="same")(x)
       x = layers.BatchNormalization()(x)

       x = layers.UpSampling2D(2)(x)

      # Project residual
       residual = layers.UpSampling2D(2)(previous_block_activation)
       residual = layers.Conv2D(filters, 1, padding="same")(residual)
       x = layers.add([x, residual])  # Add back residual
       previous_block_activation = x  # Set aside next residual

       # Add a per-pixel classification layer
       outputs = layers.Conv2D(num_classes, 3, activation="softmax", padding="same")(x)

       # Define the model
       model = keras.Model(inputs, outputs)
       return model

epochs=5;
batch_size=2;
img_size=(256,256)

inputdir= 'C://Users//hp//Desktop//Universita_laurea_Magistrale//TIROCINIO//Imm//immagine_uscita//'
input_path= glob.glob(inputdir+ '*.tif')

maskdir= 'C://Users//hp//Desktop//Universita_laurea_Magistrale//TIROCINIO//Imm//maschera_uscita//'
mask_path= glob.glob(maskdir+ '*.tif')

train_gen= leggi_immagini(batch_size,img_size,input_path,mask_path)

model= get_model(img_size,num_classes=2) #configuro il modello per il training
model.summary()
model.compile(optimizer="rmsprop", loss="sparse_categorical_crossentropy")
storia=model.fit(train_gen, epochs=epochs, validation_data=train_gen)

valori=model.predict(train_gen)
plt.plot(storia.history['loss'])
plt.plot(storia.history['val_loss'])
</code>```

Body:
I wrote this code which gives me this error "Graph execution error". On my friend's pc the code works without errors. what could be the problem?
I've checked the versions of the various libraries and everything seems to be the same.
I'm working in spyder environment and I don't understand what the problem is.
This is the error

 File "C:\Users\hp\anaconda3\envs\unet\lib\site-packages\spyder_kernels\py3compat.py", line 356, in compat_exec
    exec(code, globals, locals)

  File "c:\users\hp\desktop\universita_laurea_magistrale\tirocinio\dataset\codiceprof.py", line 147, in <module>
    storia=model.fit(train_gen, epochs=epochs, validation_data=train_gen)

  File "C:\Users\hp\anaconda3\envs\unet\lib\site-packages\keras\utils\traceback_utils.py", line 70, in error_handler
    raise e.with_traceback(filtered_tb) from None

  File "C:\Users\hp\anaconda3\envs\unet\lib\site-packages\tensorflow\python\eager\execute.py", line 54, in quick_execute
    tensors = pywrap_tfe.TFE_Py_Execute(ctx._handle, device_name, op_name,

InvalidArgumentError: Graph execution error:

Detected at node 'sparse_categorical_crossentropy/SparseSoftmaxCrossEntropyWithLogits/SparseSoftmaxCrossEntropyWithLogits' defined at (most recent call last):
    File "C:\Users\hp\anaconda3\envs\unet\lib\runpy.py", line 197, in _run_module_as_main
      return _run_code(code, main_globals, None,
    File "C:\Users\hp\anaconda3\envs\unet\lib\runpy.py", line 87, in _run_code
      exec(code, run_globals)
    File "C:\Users\hp\anaconda3\envs\unet\lib\site-packages\spyder_kernels\console\__main__.py", line 24, in <module>
      start.main()
    File "C:\Users\hp\anaconda3\envs\unet\lib\site-packages\spyder_kernels\console\start.py", line 340, in main
      kernel.start()
    File "C:\Users\hp\anaconda3\envs\unet\lib\site-packages\ipykernel\kernelapp.py", line 712, in start
      self.io_loop.start()
    File "C:\Users\hp\anaconda3\envs\unet\lib\site-packages\tornado\platform\asyncio.py", line 215, in start
      self.asyncio_loop.run_forever()
    File "C:\Users\hp\anaconda3\envs\unet\lib\asyncio\base_events.py", line 596, in run_forever
      self._run_once()
    File "C:\Users\hp\anaconda3\envs\unet\lib\asyncio\base_events.py", line 1890, in _run_once
      handle._run()
    File "C:\Users\hp\anaconda3\envs\unet\lib\asyncio\events.py", line 80, in _run
      self._context.run(self._callback, *self._args)
    File "C:\Users\hp\anaconda3\envs\unet\lib\site-packages\ipykernel\kernelbase.py", line 510, in dispatch_queue
      await self.process_one()
    File "C:\Users\hp\anaconda3\envs\unet\lib\site-packages\ipykernel\kernelbase.py", line 499, in process_one
      await dispatch(*args)
    File "C:\Users\hp\anaconda3\envs\unet\lib\site-packages\ipykernel\kernelbase.py", line 406, in dispatch_shell
      await result
    File "C:\Users\hp\anaconda3\envs\unet\lib\site-packages\ipykernel\kernelbase.py", line 730, in execute_request
      reply_content = await reply_content
    File "C:\Users\hp\anaconda3\envs\unet\lib\site-packages\ipykernel\ipkernel.py", line 390, in do_execute
      res = shell.run_cell(code, store_history=store_history, silent=silent)
    File "C:\Users\hp\anaconda3\envs\unet\lib\site-packages\ipykernel\zmqshell.py", line 528, in run_cell
      return super().run_cell(*args, **kwargs)
    File "C:\Users\hp\anaconda3\envs\unet\lib\site-packages\IPython\core\interactiveshell.py", line 2914, in run_cell
      result = self._run_cell(
    File "C:\Users\hp\anaconda3\envs\unet\lib\site-packages\IPython\core\interactiveshell.py", line 2960, in _run_cell
      return runner(coro)
    File "C:\Users\hp\anaconda3\envs\unet\lib\site-packages\IPython\core\async_helpers.py", line 78, in _pseudo_sync_runner
      coro.send(None)
    File "C:\Users\hp\anaconda3\envs\unet\lib\site-packages\IPython\core\interactiveshell.py", line 3185, in run_cell_async
      has_raised = await self.run_ast_nodes(code_ast.body, cell_name,
    File "C:\Users\hp\anaconda3\envs\unet\lib\site-packages\IPython\core\interactiveshell.py", line 3377, in run_ast_nodes
      if (await self.run_code(code, result,  async_=asy)):
    File "C:\Users\hp\anaconda3\envs\unet\lib\site-packages\IPython\core\interactiveshell.py", line 3457, in run_code
      exec(code_obj, self.user_global_ns, self.user_ns)
    File "C:\Users\hp\AppData\Local\Temp\ipykernel_9760\815882102.py", line 1, in <module>
      runfile('C:/Users/hp/Desktop/Universita_laurea_Magistrale/TIROCINIO/Dataset/codiceprof.py', wdir='C:/Users/hp/Desktop/Universita_laurea_Magistrale/TIROCINIO/Dataset')
    File "C:\Users\hp\anaconda3\envs\unet\lib\site-packages\spyder_kernels\customize\spydercustomize.py", line 524, in runfile
      return _exec_file(
    File "C:\Users\hp\anaconda3\envs\unet\lib\site-packages\spyder_kernels\customize\spydercustomize.py", line 611, in _exec_file
      exec_code(file_code, filename, ns_globals, ns_locals,
    File "C:\Users\hp\anaconda3\envs\unet\lib\site-packages\spyder_kernels\customize\spydercustomize.py", line 469, in exec_code
      exec_fun(compile(ast_code, filename, 'exec'), ns_globals, ns_locals)
    File "C:\Users\hp\anaconda3\envs\unet\lib\site-packages\spyder_kernels\py3compat.py", line 356, in compat_exec
      exec(code, globals, locals)
    File "c:\users\hp\desktop\universita_laurea_magistrale\tirocinio\dataset\codiceprof.py", line 147, in <module>
      storia=model.fit(train_gen, epochs=epochs, validation_data=train_gen)
    File "C:\Users\hp\anaconda3\envs\unet\lib\site-packages\keras\utils\traceback_utils.py", line 65, in error_handler
      return fn(*args, **kwargs)
    File "C:\Users\hp\anaconda3\envs\unet\lib\site-packages\keras\engine\training.py", line 1564, in fit
      tmp_logs = self.train_function(iterator)
    File "C:\Users\hp\anaconda3\envs\unet\lib\site-packages\keras\engine\training.py", line 1160, in train_function
      return step_function(self, iterator)
    File "C:\Users\hp\anaconda3\envs\unet\lib\site-packages\keras\engine\training.py", line 1146, in step_function
      outputs = model.distribute_strategy.run(run_step, args=(data,))
    File "C:\Users\hp\anaconda3\envs\unet\lib\site-packages\keras\engine\training.py", line 1135, in run_step
      outputs = model.train_step(data)
    File "C:\Users\hp\anaconda3\envs\unet\lib\site-packages\keras\engine\training.py", line 994, in train_step
      loss = self.compute_loss(x, y, y_pred, sample_weight)
    File "C:\Users\hp\anaconda3\envs\unet\lib\site-packages\keras\engine\training.py", line 1052, in compute_loss
      return self.compiled_loss(
    File "C:\Users\hp\anaconda3\envs\unet\lib\site-packages\keras\engine\compile_utils.py", line 265, in __call__
      loss_value = loss_obj(y_t, y_p, sample_weight=sw)
    File "C:\Users\hp\anaconda3\envs\unet\lib\site-packages\keras\losses.py", line 152, in __call__
      losses = call_fn(y_true, y_pred)
    File "C:\Users\hp\anaconda3\envs\unet\lib\site-packages\keras\losses.py", line 272, in call
      return ag_fn(y_true, y_pred, **self._fn_kwargs)
    File "C:\Users\hp\anaconda3\envs\unet\lib\site-packages\keras\losses.py", line 2084, in sparse_categorical_crossentropy
      return backend.sparse_categorical_crossentropy(
    File "C:\Users\hp\anaconda3\envs\unet\lib\site-packages\keras\backend.py", line 5630, in sparse_categorical_crossentropy
      res = tf.nn.sparse_softmax_cross_entropy_with_logits(
Node: 'sparse_categorical_crossentropy/SparseSoftmaxCrossEntropyWithLogits/SparseSoftmaxCrossEntropyWithLogits'
logits and labels must have the same first dimension, got logits shape [2048,2] and labels shape [131072]
     [[{{node sparse_categorical_crossentropy/SparseSoftmaxCrossEntropyWithLogits/SparseSoftmaxCrossEntropyWithLogits}}]] [Op:__inference_train_function_14691]

from tensorflow import keras
import numpy as np
from tensorflow.keras.preprocessing.image import load_img
from tensorflow.keras.preprocessing.image import img_to_array
import PIL

from keras.models import Model
from keras.layers import Input, Conv2D, MaxPooling2D, UpSampling2D, concatenate, Conv2DTranspose, BatchNormalization, Dropout, Lambda
from keras.optimizers import Adam
from keras.layers import Activation, MaxPool2D, Concatenate

import glob
import matplotlib
import matplotlib.pyplot as plt
from matplotlib import pyplot as plt
from tensorflow.keras import layers

class leggi_immagini(keras.utils.Sequence):

    def __init__(self, batch_size, img_size, input_img_paths, target_img_paths):
        self.batch_size = batch_size
        self.img_size = img_size
        self.input_img_paths = input_img_paths
        self.target_img_paths = target_img_paths

    def __len__(self):
        return len(self.target_img_paths) // self.batch_size

    def __getitem__(self, idx):
        """Returns tuple (input, target) correspond to batch #idx."""
        i = idx * self.batch_size
        batch_input_img_paths = self.input_img_paths[i : i + self.batch_size]
        batch_target_img_paths = self.target_img_paths[i : i + self.batch_size]
        x = np.zeros((self.batch_size,) + self.img_size +(1,), dtype="float32")
        for j, path in enumerate(batch_input_img_paths):
            #print("eccomi")
            img = load_img(path,  color_mode='grayscale')
            x[j] = img_to_array(img) #/ 8191 # normalizza al massimo
        y = np.zeros((self.batch_size,) + self.img_size + (1,), dtype="uint8")
        for j, path2 in enumerate(batch_target_img_paths):
            img2 = load_img(path2, color_mode="grayscale")
            y[j] = img_to_array(img2) / 255
        return x, y

def get_model(img_size, num_classes):
    inputs = keras.Input(shape=img_size + (1,))

    ### [First half of the network: downsampling inputs] ###

    # Entry block
    x = layers.Conv2D(32, (3,3),strides=2,padding="same",input_shape=(256,256,1))(inputs)# strides=2, padding="same")(inputs)
    x = layers.BatchNormalization()(x)
    x = layers.Activation("relu")(x)

    previous_block_activation = x  # Set aside residual

    # Blocks 1, 2, 3 are identical apart from the feature depth.
    for filters in [64, 128, 256]:
       x = layers.Activation("relu")(x)
       x = layers.SeparableConv2D(filters, 3, padding="same")(x)
       x = layers.BatchNormalization()(x)

       x = layers.Activation("relu")(x)
       x = layers.SeparableConv2D(filters, 3, padding="same")(x)
       x = layers.BatchNormalization()(x)

       x = layers.MaxPooling2D(3, strides=2, padding="same")(x)

      # Project residual
       residual = layers.Conv2D(filters, 1, strides=2, padding="same")(
           previous_block_activation
       )
       x = layers.add([x, residual])  # Add back residual
       previous_block_activation = x  # Set aside next residual

      ### [Second half of the network: upsampling inputs] ###

    for filters in [256, 128, 64, 32]:
       x = layers.Activation("relu")(x)
       x = layers.Conv2DTranspose(filters, 3, padding="same")(x)
       x = layers.BatchNormalization()(x)

       x = layers.Activation("relu")(x)
       x = layers.Conv2DTranspose(filters, 3, padding="same")(x)
       x = layers.BatchNormalization()(x)

       x = layers.UpSampling2D(2)(x)

      # Project residual
       residual = layers.UpSampling2D(2)(previous_block_activation)
       residual = layers.Conv2D(filters, 1, padding="same")(residual)
       x = layers.add([x, residual])  # Add back residual
       previous_block_activation = x  # Set aside next residual

       # Add a per-pixel classification layer
       outputs = layers.Conv2D(num_classes, 3, activation="softmax", padding="same")(x)

       # Define the model
       model = keras.Model(inputs, outputs)
       return model

epochs=5;
batch_size=2;
img_size=(256,256)

inputdir= 'C://Users//hp//Desktop//Universita_laurea_Magistrale//TIROCINIO//Imm//immagine_uscita//'
input_path= glob.glob(inputdir+ '*.tif')

maskdir= 'C://Users//hp//Desktop//Universita_laurea_Magistrale//TIROCINIO//Imm//maschera_uscita//'
mask_path= glob.glob(maskdir+ '*.tif')

train_gen= leggi_immagini(batch_size,img_size,input_path,mask_path)

model= get_model(img_size,num_classes=2) #configuro il modello per il training
model.summary()
model.compile(optimizer="rmsprop", loss="sparse_categorical_crossentropy")
storia=model.fit(train_gen, epochs=epochs, validation_data=train_gen)

valori=model.predict(train_gen)
plt.plot(storia.history['loss'])
plt.plot(storia.history['val_loss'])


问:
How do I implement an auto-calculated field in Django using JavaScript?
I would like to auto-calculate my deposit amount height in a form. Therefore, I included JavaScript to make it happen.
The idea: After entering the net into the form, the suitable deposit height will be displayed in the amount field. And there is nothing to do for the user here.

I really appreciate any suggestions since I am total beginner with Django.

I tried to access the field via known methods like netObj.fishing_type and ['fishing_type'] but I feel like this is not the issue. Somehow I can't access the model fields of the triggered record.

html file:

{% extends 'base.html' %}
{% load crispy_forms_tags %}
{% block content%}

    <form method="POST" action="{% url 'put_deposit' %}" enctype="multipart/form-data">
        {% csrf_token %}
        {{form|crispy}}

        <button type="Submit" class="btn btn-outline-dark">Submit</button>

{% endblock content%}
```
<p>Extract of models.py:</p>
<pre class="lang-py prettyprint-override"><code>class Net(models.Model):
    net_id = models.IntegerField(primary_key=True, default = None)
    prod_date = models.DateField()
    weight = models.DecimalField(default=0, max_digits=6, decimal_places=2)
    material = models.CharField(max_length=100)
    fishing_type = models.CharField(max_length=100, default=None)

    def __str__(self):
       return '{}: {}'.format(self.fishing_type, self.material)

class Deposit(models.Model):
    dep_id = models.BigAutoField(primary_key=True, default=None)
    dep_date = models.DateField()
    harbour = models.CharField(max_length=100)
    vessel = models.ForeignKey(Vessel, to_field='VID', on_delete=models.CASCADE)
    net = models.ForeignKey(Net, to_field='net_id', on_delete=models.CASCADE)
    amount = models.DecimalField(default=0, max_digits=8, decimal_places=2)
</code>```

forms.py:

from django.forms import ModelForm
from myapp.models import *

class UploadForm(ModelForm):

    class Meta:
        model = Deposit
        fields = ['dep_date', 'harbour',
                    'vessel', 'net',
                    'amount']
```

Body:
I would like to auto-calculate my deposit amount height in a form. Therefore, I included JavaScript to make it happen.
The idea: After entering the net into the form, the suitable deposit height will be displayed in the amount field. And there is nothing to do for the user here.

I really appreciate any suggestions since I am total beginner with Django.

I tried to access the field via known methods like netObj.fishing_type and ['fishing_type'] but I feel like this is not the issue. Somehow I can't access the model fields of the triggered record.

html file:

{% extends 'base.html' %}
{% load crispy_forms_tags %}
{% block content%}

    <form method="POST" action="{% url 'put_deposit' %}" enctype="multipart/form-data">
        {% csrf_token %}
        {{form|crispy}}

        <button type="Submit" class="btn btn-outline-dark">Submit</button>

{% endblock content%}

Extract of models.py:

class Net(models.Model):
    net_id = models.IntegerField(primary_key=True, default = None)
    prod_date = models.DateField()
    weight = models.DecimalField(default=0, max_digits=6, decimal_places=2)
    material = models.CharField(max_length=100)
    fishing_type = models.CharField(max_length=100, default=None)

    def __str__(self):
       return '{}: {}'.format(self.fishing_type, self.material)

class Deposit(models.Model):
    dep_id = models.BigAutoField(primary_key=True, default=None)
    dep_date = models.DateField()
    harbour = models.CharField(max_length=100)
    vessel = models.ForeignKey(Vessel, to_field='VID', on_delete=models.CASCADE)
    net = models.ForeignKey(Net, to_field='net_id', on_delete=models.CASCADE)
    amount = models.DecimalField(default=0, max_digits=8, decimal_places=2)

forms.py:

from django.forms import ModelForm
from myapp.models import *

class UploadForm(ModelForm):

    class Meta:
        model = Deposit
        fields = ['dep_date', 'harbour',
                    'vessel', 'net',
                    'amount']


问:
How to log when using Command Pattern
Head First Design Patterns say:

The Command Pattern encapsulates a request as an object, thereby
letting you parameterize other objects with different requests, queue
or log requests, and support undoable operations.

Later the book said:

The semantics of some applications require that we log all actions and
be able to recover after a crash by reinvoking those actions. The
Command Pattern can support these semantics with the addition of two
methods: store() and load(). In Java we could use object serialization
to implement these methods, but the normal caveats for using
serialization for persistence apply.

How does this work? As we execute commands, we store a history of them
on disk. When a crash occurs, we reload the command objects and invoke
their execute() methods in batch and in order.

I am trying to come up with an example code. The code I wrote till now is:

```<code>class Client {
    public static void main(String[] args) {
        Command enableCommand = new EnableCommand();
        enableCommand.execute();
    }
}

interface Command {
    void execute();
    void store();
    void load();
}

class EnableCommand implements Command {

    public EnableCommand() {
    }

    @Override
    public void execute() {
        store();
        System.out.println("Execute Command");
    }

    @Override
    public void store() {
        System.out.println("Storing on Disk");

    }

    @Override
    public void load() {
        // TODO Auto-generated method stub

    }
}
</code>```

How the load() function is supposed to work?

Title: How to log when using Command Pattern

Body:
Head First Design Patterns say:

The Command Pattern encapsulates a request as an object, thereby
letting you parameterize other objects with different requests, queue
or log requests, and support undoable operations.

Later the book said:

The semantics of some applications require that we log all actions and
be able to recover after a crash by reinvoking those actions. The
Command Pattern can support these semantics with the addition of two
methods: store() and load(). In Java we could use object serialization
to implement these methods, but the normal caveats for using
serialization for persistence apply.

How does this work? As we execute commands, we store a history of them
on disk. When a crash occurs, we reload the command objects and invoke
their execute() methods in batch and in order.

I am trying to come up with an example code. The code I wrote till now is:

class Client {
    public static void main(String[] args) {
        Command enableCommand = new EnableCommand();
        enableCommand.execute();
    }
}

interface Command {
    void execute();
    void store();
    void load();
}

class EnableCommand implements Command {

    public EnableCommand() {
    }

    @Override
    public void execute() {
        store();
        System.out.println("Execute Command");
    }

    @Override
    public void store() {
        System.out.println("Storing on Disk");

    }

    @Override
    public void load() {
        // TODO Auto-generated method stub

    }
}

How the load() function is supposed to work?


问:
New images not showing since upgrade to laravel 9
Please help me. I upgraded from laravel 7 to 9

Previous images displays but newly uploaded images are not. Images are saved correctly in the app/public/uploads and generated link is i.e my-domain-name.com/uploads/0000/1/2022/12/06/img-x-150 is correct. When link is entered on browser it aborts to 404 error page. I have read articles that suggest I cleared the cache, delete the storage link folder in app/public and run:

php artisan storage:link

Which I have done with no success.


问:
How to add time frame for candle using plotly library in Python?
I want to add a time frame for candlestick on a chart using plotly library. Is there a way to do that without iterating through data and taking every 4th tick (for 4h chart) and calculating high and low in between and all the calculations done in the background?

```<code>data = requests.get(url).json()

date = []
open = []
high = []
low = []
close = []
i = 0
k = 4
for tick in data:
    date.append(tick['time'])
    open.append(tick['open'])
    high.append(tick['high'])
    low.append(tick['low'])
    close.append(tick['close'])

fig = go.Figure(data=[go.Candlestick
                x=date,
                open=open,
                high=high,
                low=low,
                close=close)])

fig.update_layout(xaxis_rangeslider_visible=False, template='plotly_dark')
</code>```

I couldn't find solution for this that is helpful

Body:
I want to add a time frame for candlestick on a chart using plotly library. Is there a way to do that without iterating through data and taking every 4th tick (for 4h chart) and calculating high and low in between and all the calculations done in the background?

data = requests.get(url).json()

date = []
open = []
high = []
low = []
close = []
i = 0
k = 4
for tick in data:
    date.append(tick['time'])
    open.append(tick['open'])
    high.append(tick['high'])
    low.append(tick['low'])
    close.append(tick['close'])

fig = go.Figure(data=[go.Candlestick
                x=date,
                open=open,
                high=high,
                low=low,
                close=close)])

fig.update_layout(xaxis_rangeslider_visible=False, template='plotly_dark')

I couldn't find solution for this that is helpful


问:
Struggling to implement PySpark map/reduce functions on images from S3
I'm working on a project to run a very simple PySpark image vectorisation (to extract features) then run a PCA reduction on those vectors.

The images are read from an S3 bucket:

```<code>src = spark.read.format("image").option("recursiveFileLookup", "true").load(f"s3a://{BUCKET}/{PATTERN}").cache()
src.printSchema()
</code>```
```<code>root
 |-- image: struct (nullable = true)
 |    |-- origin: string (nullable = true)
 |    |-- height: integer (nullable = true)
 |    |-- width: integer (nullable = true)
 |    |-- nChannels: integer (nullable = true)
 |    |-- mode: integer (nullable = true)
 |    |-- data: binary (nullable = true)
</code>```

Then I am extracting the raw image from that schema:

```<code>@udf(VectorUDT())
def image2vec(image):
    return DenseVector(ImageSchema.toNDArray(image).flatten())
</code>```

Which results in a new dataframe with:

```<code>+--------------------+--------------------+-----------------+--------+
|               image|                vecs|            shape|category|
+--------------------+--------------------+-----------------+--------+
|{s3a://oc-p8-s3-a...|[255.0,255.0,255....|[100.0,100.0,3.0]|  banana|
|{s3a://oc-p8-s3-a...|[255.0,255.0,255....|[100.0,100.0,3.0]|  banana|
|{s3a://oc-p8-s3-a...|[255.0,255.0,255....|[100.0,100.0,3.0]|  banana|
|{s3a://oc-p8-s3-a...|[255.0,255.0,255....|[100.0,100.0,3.0]|  banana|
|{s3a://oc-p8-s3-a...|[255.0,255.0,255....|[100.0,100.0,3.0]|  banana|
|{s3a://oc-p8-s3-a...|[255.0,255.0,255....|[100.0,100.0,3.0]|  banana|
+--------------------+--------------------+-----------------+--------+
</code>```

It's this vecs column that I want to pass to the map function in the following code:

```<code>def vectorise_image(???) -> np.array:
    from tensorflow.keras.applications.vgg16 import VGG16
    from tensorflow.keras.models import Sequential

    model = VGG16(include_top=False, weights='imagenet')
    my_new_model = Sequential()
    my_new_model.add(model)
    my_new_model.layers[0].trainable = False

    image_vector = my_new_model.predict(???)

    return image_vector

partitions = 20
vectorisation_results = spark.sparkContext.parallelize(
    df.select('vecs'), ???
    partitions
).map(vectorise_image).collect()
</code>```

The problem is that I can't figure out what should be passed into the map function 'vectorise_image'.

I've tried passing in many different combinations of arrays, vectors, columns and all of them throw errors.

I'm fairly well-versed in python and pandas, but pyspark's dataframe implementation is throwing curveballs at me. Can anyone help, please?

Body:
I'm working on a project to run a very simple PySpark image vectorisation (to extract features) then run a PCA reduction on those vectors.

The images are read from an S3 bucket:

src = spark.read.format("image").option("recursiveFileLookup", "true").load(f"s3a://{BUCKET}/{PATTERN}").cache()
src.printSchema()

root
 |-- image: struct (nullable = true)
 |    |-- origin: string (nullable = true)
 |    |-- height: integer (nullable = true)
 |    |-- width: integer (nullable = true)
 |    |-- nChannels: integer (nullable = true)
 |    |-- mode: integer (nullable = true)
 |    |-- data: binary (nullable = true)

Then I am extracting the raw image from that schema:

@udf(VectorUDT())
def image2vec(image):
    return DenseVector(ImageSchema.toNDArray(image).flatten())

Which results in a new dataframe with:

+--------------------+--------------------+-----------------+--------+
|               image|                vecs|            shape|category|
+--------------------+--------------------+-----------------+--------+
|{s3a://oc-p8-s3-a...|[255.0,255.0,255....|[100.0,100.0,3.0]|  banana|
|{s3a://oc-p8-s3-a...|[255.0,255.0,255....|[100.0,100.0,3.0]|  banana|
|{s3a://oc-p8-s3-a...|[255.0,255.0,255....|[100.0,100.0,3.0]|  banana|
|{s3a://oc-p8-s3-a...|[255.0,255.0,255....|[100.0,100.0,3.0]|  banana|
|{s3a://oc-p8-s3-a...|[255.0,255.0,255....|[100.0,100.0,3.0]|  banana|
|{s3a://oc-p8-s3-a...|[255.0,255.0,255....|[100.0,100.0,3.0]|  banana|
+--------------------+--------------------+-----------------+--------+

It's this vecs column that I want to pass to the map function in the following code:

def vectorise_image(???) -> np.array:
    from tensorflow.keras.applications.vgg16 import VGG16
    from tensorflow.keras.models import Sequential

    model = VGG16(include_top=False, weights='imagenet')
    my_new_model = Sequential()
    my_new_model.add(model)
    my_new_model.layers[0].trainable = False

    image_vector = my_new_model.predict(???)

    return image_vector

partitions = 20
vectorisation_results = spark.sparkContext.parallelize(
    df.select('vecs'), ???
    partitions
).map(vectorise_image).collect()

The problem is that I can't figure out what should be passed into the map function 'vectorise_image'.

I've tried passing in many different combinations of arrays, vectors, columns and all of them throw errors.

I'm fairly well-versed in python and pandas, but pyspark's dataframe implementation is throwing curveballs at me. Can anyone help, please?


问:
i can't make my timer program work without making it go to 1 fps
i can't add seconds to my program without it slowing the whole program to 1 frame per second
so the screensaver moving "welcome" thing will slow down as well so i don't want that but still
want the timer thingy.
this is the code:

import random
import pygame
pygame.init()
screen = pygame.display.set_mode((1920,1080))
bg = pygame.image.load('C:/Users/zaydz/Desktop/coding/python/python programs/images/backrooms.jpg')
mover = pygame.image.load('C:/Users/zaydz/Desktop/coding/python/python programs/images/welcome.png')
seconds = 0
minutes = 0
hours = 0
mx = random.randrange(400,1520)
my = random.randrange(200,880)
sx = 3
sy = 2
current_time = 0
clock = pygame.time.Clock()
running = True
while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
    current_time = pygame.time.get_ticks()
    if current_time > 1000:
        pygame.time.wait(1000)
        seconds += 1
    if seconds == 60:
        minutes += 1
        seconds = 0
    if minutes == 60:
        hours += 1
        minutes = 0
    if hours == 24:
        seconds = 0
        minutes = 0
        hours = 0
    mx += sx
    my += sy
    if mx <= 0 or mx >= 1520:
        sx *= -1
    if my <=0 or my >= 880:
        sy *= -1
    tume = pygame.font.Font("C:/Users/zaydz/Desktop/coding/python/python programs/fonts/Sitka.ttc",50)
    tumo = tume.render(f"hour : {hours}  minute : {minutes}  second : {seconds}",False,(237, 205, 187))
    screen.blit(bg,(0,0))
    screen.blit(mover,(mx,my))
    screen.blit(tumo,(0,0))
    pygame.display.update()
    clock.tick(50)
```