问:
Not able to set/receive cookies cross-domain using Netlify and Heroku
I have run into the issue where I cannot set the cookie in the browser, due to the client being hosted at Netlify and server at Heroku. It worked fine on localhost, so it seems it has something to do with it being cross-domain now.

Having read multiple posts on this it seems like it might have to do with cors or how I'm setting the cookies to begin with.

I read somewhere that it might help adding secure: true and sameSite: "none" when setting the cookie, so I added them but it didn't help. I also have tried adding domain into the cookie when setting it, but it also didn't help unfortunately.

I'm using Chrome and have changed the setting from blocking third party cookies with icognito to allow all cookies, as I have read that this might be an issue sometimes. However it did not yield any new results either.

I have also read that it might require a proxy for whatever reason or that it could be solved by hosting both client and server on Heroku. I would prefer not having to do any of these things if possible, but any ideas are welcome.

Server side with Node js (express) hosted on Heroku:

```<code>const express = require("express");
const app = express();
require("dotenv").config();
const cors = require("cors");
const mysql = require("mysql");
const jwt = require("jsonwebtoken");
const cookieParser = require("cookie-parser");

// port for heroku if needed
const PORT = 3001;

// app objects instantiated on creation of the express server
app.use(
  cors({
    origin: [
      "https://examples.netlify.app",
      "http://localhost:3000",
    ],
    methods: ["GET", "POST", "DELETE"],
    credentials: true,
  })
);
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.use(cookieParser());

/*
 * Handel user login
 */
app.post("/sign-in", (req, res) => {
  const { email, password } = req.body;

  sqlSelectAllUsers = "SELECT * FROM user_db WHERE email = ?";
  db.query(sqlSelectAllUsers, [email], (err, user) => {
    if (err) {
      res.send({ err: err });
    }

    if (user && user.length > 0) {
      // given the email check if the password is correct

      bcrypt.compare(password, user[0].password, (err, compareUser) => {
        if (compareUser) {
          //req.session.email = user;
          // create access token
          const accessToken = createAccessToken(user[0]);
          const refreshToken = createRefreshToken(user[0]);
          // create cookie and store it in users browser
          res.cookie("access-token", accessToken, {
            maxAge: 1000 * 60 * 30, // 30 min
            httpOnly: true, // hinder doing document.cookies as it will be httpOnly which will make it more safe
            secure: true,
            domain: "https://examples.netlify.app/",
            sameSite: "none",
          });
          res.cookie("refresh-token", refreshToken, {
            maxAge: 2.63e9, // approx 1 month
            httpOnly: true,
            secure: true,
            domain: "https://examples.netlify.app/",
            sameSite: "none",
          });

          // update refresh token in database
          const sqlUpdateToken =
            "UPDATE user_db SET refresh_token = ? WHERE email = ?";
          db.query(
            sqlUpdateToken,
            [refreshToken, user[0].email],
            (err, result) => {
              if (err) {
                res.send(err);
              }
              res.sendStatus(200);
            }
          );
        } else {
          res.send({ message: "Wrong email or password" });
        }
      });
    } else {
      res.send({ message: "Wrong email or password" });
    }
  });
});

app.listen(process.env.PORT || PORT, () => {
  console.log(`Server running on port ${PORT}`);
});
</code>```

Client side with React hosted on Netlify:

```<code>  export default function SignIn() {
  const history = useHistory();

  const handleSubmit = (event) => {
    event.preventDefault();
    const data = new FormData(event.currentTarget);
    // eslint-disable-next-line no-console
    axios
      .post(
        "https://example.herokuapp.com/sign-in",
        {
          email: data.get("email"),
          password: data.get("password"),
        },
        { withCredentials: "true" }
      )
      .then((response) => {
        //check if good response then give user a token for valid login
        if (response.data === "OK") {
          history.push("/");
          history.go(0);
        }
      });
  };
}

</code>```

答:
Okay so I finally solved it and thought I would write how I did it here.

Despite what seems to be the common belief, it is actually possible to send cookies between Heroku and Netlify, sort of..

I think that I added domain, sameSite and secure all at the same time when changing the way I set the cookies and did therefore not test the scenario without domain. After removing domain it was possible to set the cookies in heroku which then made it work in netlify. So it worked for login in, however there were 2 major issues with this. Cookies would randomly stop working and as soon as Heroku went into idle mode (which it seems to do on the free version) it would mess up the application and the cookies forcing me to restart all dynos. So even though it seemed possible to do it through Netlify and Heroku, I do NOT recommend using cookies cross domain. (I have also read that using sameSite:none may increase risk of CSRF attacks and is therefore not ideal to use when setting your cookies)

The final solution: I started hosting both client and server on heroku under the same url, using proxy etc. Here is link to the tutorial I followed, which worked great:
https://www.youtube.com/watch?v=xgvLP3f2Y7k&list=LL&index=1&ab_channel=AvanTutor

Now the cookies works like they should and the website is up and running!

Body:
I have run into the issue where I cannot set the cookie in the browser, due to the client being hosted at Netlify and server at Heroku. It worked fine on localhost, so it seems it has something to do with it being cross-domain now.

Having read multiple posts on this it seems like it might have to do with cors or how I'm setting the cookies to begin with.

I read somewhere that it might help adding secure: true and sameSite: "none" when setting the cookie, so I added them but it didn't help. I also have tried adding domain into the cookie when setting it, but it also didn't help unfortunately.

I'm using Chrome and have changed the setting from blocking third party cookies with icognito to allow all cookies, as I have read that this might be an issue sometimes. However it did not yield any new results either.

I have also read that it might require a proxy for whatever reason or that it could be solved by hosting both client and server on Heroku. I would prefer not having to do any of these things if possible, but any ideas are welcome.

Server side with Node js (express) hosted on Heroku:

const express = require("express");
const app = express();
require("dotenv").config();
const cors = require("cors");
const mysql = require("mysql");
const jwt = require("jsonwebtoken");
const cookieParser = require("cookie-parser");

// port for heroku if needed
const PORT = 3001;

// app objects instantiated on creation of the express server
app.use(
  cors({
    origin: [
      "https://examples.netlify.app",
      "http://localhost:3000",
    ],
    methods: ["GET", "POST", "DELETE"],
    credentials: true,
  })
);
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.use(cookieParser());

/*
 * Handel user login
 */
app.post("/sign-in", (req, res) => {
  const { email, password } = req.body;

  sqlSelectAllUsers = "SELECT * FROM user_db WHERE email = ?";
  db.query(sqlSelectAllUsers, [email], (err, user) => {
    if (err) {
      res.send({ err: err });
    }

    if (user && user.length > 0) {
      // given the email check if the password is correct

      bcrypt.compare(password, user[0].password, (err, compareUser) => {
        if (compareUser) {
          //req.session.email = user;
          // create access token
          const accessToken = createAccessToken(user[0]);
          const refreshToken = createRefreshToken(user[0]);
          // create cookie and store it in users browser
          res.cookie("access-token", accessToken, {
            maxAge: 1000 * 60 * 30, // 30 min
            httpOnly: true, // hinder doing document.cookies as it will be httpOnly which will make it more safe
            secure: true,
            domain: "https://examples.netlify.app/",
            sameSite: "none",
          });
          res.cookie("refresh-token", refreshToken, {
            maxAge: 2.63e9, // approx 1 month
            httpOnly: true,
            secure: true,
            domain: "https://examples.netlify.app/",
            sameSite: "none",
          });

          // update refresh token in database
          const sqlUpdateToken =
            "UPDATE user_db SET refresh_token = ? WHERE email = ?";
          db.query(
            sqlUpdateToken,
            [refreshToken, user[0].email],
            (err, result) => {
              if (err) {
                res.send(err);
              }
              res.sendStatus(200);
            }
          );
        } else {
          res.send({ message: "Wrong email or password" });
        }
      });
    } else {
      res.send({ message: "Wrong email or password" });
    }
  });
});

app.listen(process.env.PORT || PORT, () => {
  console.log(`Server running on port ${PORT}`);
});

Client side with React hosted on Netlify:

  export default function SignIn() {
  const history = useHistory();

  const handleSubmit = (event) => {
    event.preventDefault();
    const data = new FormData(event.currentTarget);
    // eslint-disable-next-line no-console
    axios
      .post(
        "https://example.herokuapp.com/sign-in",
        {
          email: data.get("email"),
          password: data.get("password"),
        },
        { withCredentials: "true" }
      )
      .then((response) => {
        //check if good response then give user a token for valid login
        if (response.data === "OK") {
          history.push("/");
          history.go(0);
        }
      });
  };
}


来源: stackexchange

问:
Protect api routes with middleware in nextJS?
I'm new to next.js and I wanted to know if I could protect a whole API route via middleware. So for example if i wanted to protect /api/users Could I create /api/users/_middleware.ts and handle authentication in the middleware and not have to worry about authentication in the actual api endpoints? If so, how would I go about doing that? The library i'm using right now is @auth0\nextjs-auth0 so I guess it would look something like this? (Also please forgive me if I code this wrong, I am doing this in the stackoverflow editor)

export default authMiddleware(req,res)=>{
const {user,error,isLoading} = whateverTheNameOfTheAuth0HookIs()
if(user)
{
// Allow the request to the api route
}
else
{
// Deny the request with HTTP 401
}
}
```

Do I have the general idea correct?

答:
You can use middleware for that, something similar to this example from the documentation.

For a sub-directory inside pages, you can create a _middleware.ts file. It will run for all pages in this directory. It looks something like this:

```<code>import { NextRequest, NextResponse } from 'next/server'

export function middleware(req: NextRequest) {
  const basicAuth = req.headers.get('authorization')

  if (basicAuth) {
    // do whatever checks you need here
    const hasAccess = ...

    if (hasAccess) {
      // will render the specified page
      return NextResponse.next()
    }
  }

  // will not allow access
  return new Response('No access', {
    status: 401,
    headers: {
      'WWW-Authenticate': 'Basic realm="Secure Area"',
    },
  })
}
</code>```

You can find more info in the documentation.

ContentLicense: CC BY-SA 4.0

Body:
I'm new to next.js and I wanted to know if I could protect a whole API route via middleware. So for example if i wanted to protect /api/users Could I create /api/users/_middleware.ts and handle authentication in the middleware and not have to worry about authentication in the actual api endpoints? If so, how would I go about doing that? The library i'm using right now is @auth0\nextjs-auth0 so I guess it would look something like this? (Also please forgive me if I code this wrong, I am doing this in the stackoverflow editor)

export default authMiddleware(req,res)=>{
const {user,error,isLoading} = whateverTheNameOfTheAuth0HookIs()
if(user)
{
// Allow the request to the api route
}
else
{
// Deny the request with HTTP 401
}
}

Do I have the general idea correct?

Body:
You can use middleware for that, something similar to this example from the documentation.

For a sub-directory inside pages, you can create a _middleware.ts file. It will run for all pages in this directory. It looks something like this:

import { NextRequest, NextResponse } from 'next/server'

export function middleware(req: NextRequest) {
  const basicAuth = req.headers.get('authorization')

  if (basicAuth) {
    // do whatever checks you need here
    const hasAccess = ...

    if (hasAccess) {
      // will render the specified page
      return NextResponse.next()
    }
  }

  // will not allow access
  return new Response('No access', {
    status: 401,
    headers: {
      'WWW-Authenticate': 'Basic realm="Secure Area"',
    },
  })
}

You can find more info in the documentation.


问:
Copy values from one column to another sheet in certain order
I am trying to find a code to create macro in excel sheet that would copy values from sheet called "Panels" and column "C" (starting with C3, C4, etc,) and paste to sheet called "Pack" but in specific order: the first cell would be A10, and then skip B10, then paste to C10, skip D10, paste to E10, skip F10, paste to G10, skip H10, paste to I10, skip J10, and then move to next row "11" with the same order of skip and paste.

The goal of this excel worksheet is that "Panels" sheet has list of all items' needed to be manufactured, and "Pack" sheet will have a list of same items to be shipped.  Operators will then check mark correct items being shipped in "skipped" columns.

Attached is a screenshot of the "Pack" sheet with examples of imaginary items.

答:
Copy and Transpose With Offset

Option Explicit

Sub FillPack()

    Dim wb As Workbook: Set wb = ThisWorkbook ' workbook containing this code

    ' Source (read (copied) from)
    Dim sws As Worksheet: Set sws = wb.Worksheets("Panels") ' Worksheet
    Dim sfRow As Long: sfRow = 3 ' First Row
    Dim slRow As Long ' Last Row
    slRow = sws.Cells(sws.Rows.Count, "C").End(xlUp).Row
    If slRow < sfRow Then Exit Sub ' no data

    ' Destination (written to)
    Dim dws As Worksheet: Set dws = wb.Worksheets("Pack") ' Worksheet
    Dim dfRow As Long: dfRow = 10 ' First Row
    Dim dr As Long: dr = dfRow ' Current Row
    Dim dfCol As Long: dfCol = 1 ' First Column
    Dim dc As Long: dc = dfCol ' Current Column
    Dim dlCol As Long: dlCol = 9 ' Last Column
    Dim dlRow As Long ' Last Row (just to clear the previous data)
    dlRow = dws.Cells(dws.Rows.Count, dfCol).End(xlUp).Row
    If dlRow >= dfRow Then ' Clear previous data
        dws.Range(dws.Cells(dfRow, dfCol), dws.Cells(dlRow, dlCol)).ClearContents
    End If

    Dim sr As Long ' Current Row

    For sr = sfRow To slRow ' loop through cells of column 'C'
        dws.Cells(dr, dc).Value = sws.Cells(sr, "C").Value ' copy value
        If dc < dlCol Then
            dc = dc + 2 ' every other column
        Else
            dr = dr + 1 ' when all columns are filled then next row...
            dc = dfCol ' ... and start with first column
        End If
    Next sr

    MsgBox "Pack filled.", vbInformation

End Sub
```


问:
Spring+JPA+DAO+Tomcat
persistence.xml

```<code><persistence-unit name="myEntityManager" transaction-type="RESOURCE_LOCAL">
<class>com.epam.testapp.model.News</class>
<exclude-unlisted-classes>true</exclude-unlisted-classes>
</code>```

News

```<code>private Integer newsId;
private String title;
private String brief;
private String content;
private Date created;
private String dateCreatedString;

public News() {
}

@Id
@Column(name = "NEWS_ID")
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "news_seq")
@SequenceGenerator(name = "news_seq", sequenceName = "NEWS_SEQ")
public Integer getNewsId() {
    return newsId;
}

public void setNewsId(Integer newsId) {
    this.newsId = newsId;
}

@Column(nullable = false, name = "TITLE")
public String getTitle() {
    return title;
}

public void setTitle(String title) {
    this.title = title;
}

@Column(nullable = false, name = "BRIEF")
public String getBrief() {
    return brief;
}

public void setBrief(String brief) {
    this.brief = brief;
}

@Column(name = "CONTENT")
public String getContent() {
    return content;
}

public void setContent(String content) {
    this.content = content;
}

@Temporal(value = TemporalType.DATE)
@Column(nullable = false, name = "CREATED")
public Date getCreated() {
    return created;
}

public void setCreated(Date created) {
    this.created = created;
}

@Transient
public String getDateCreatedString() {
    return dateCreatedString;
}

public void setDateCreatedString(String dateCreatedString) {
    this.dateCreatedString = dateCreatedString;
}
</code>```

equals and hashcode

xml for spring

```<code>    <bean id="propertyConfigurer"
      class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
    <property name="location" value="/WEB-INF/databaseConfiguration.properties"/>
</bean>

<bean  id="newsDAO"
    class="com.epam.testapp.database.NewsDaoJPA">
    <property name="entityManagerFactory" ref="entityManagerFactory"/>
</bean>

<bean id="entityManagerFactory" class=
  "org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
    <property name="dataSource" ref="dataSource"/>
    <property name="jpaVendorAdapter">
        <bean class="org.springframework.orm.jpa.vendor.OpenJpaVendorAdapter">
            <property name="showSql" value="true"/>
            <property name="database" value="ORACLE"/>
        </bean>
    </property>
    <property name="loadTimeWeaver">
        <bean class="org.springframework.instrument.classloading.SimpleLoadTimeWeaver"/>
    </property>
</bean>

<bean id="dataSource"
 class="org.springframework.jdbc.datasource.DriverManagerDataSource">
    <property name="driverClassName" value="${database.driver}"/>
    <property name="url" value="${database.url}"/>
    <property name="username" value="${database.user}"/>
    <property name="password" value="${database.password}"/>
</bean>

<bean id="transactionManager"
 class="org.springframework.orm.jpa.JpaTransactionManager">
    <property name="entityManagerFactory" ref="entityManagerFactory"/>
    <property name="dataSource" ref="dataSource"/>
</bean>
</code>```

but when call dao method for example

```<code>public List<News> getList() throws DAOException {
    return getJpaTemplate().find("select n from News n");
}
</code>```

i get

```<code>java.lang.IllegalArgumentException: object is not an instance of declaring class
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.invokeProxyMethod(AbstractEntityManagerFactoryBean.java:423)
at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean$ManagedEntityManagerFactoryInvocationHandler.invoke(AbstractEntityManagerFactoryBean.java:485)
at $Proxy4.createEntityManager(Unknown Source)
at org.springframework.orm.jpa.EntityManagerFactoryAccessor.createEntityManager(EntityManagerFactoryAccessor.java:116)
at org.springframework.orm.jpa.JpaTemplate.execute(JpaTemplate.java:176)
at org.springframework.orm.jpa.JpaTemplate.contains(JpaTemplate.java:245)
at com.epam.testapp.database.NewsDaoJPA.getList(NewsDaoJPA.java:26)
at com.epam.testapp.presentation.action.NewsAction.list(NewsAction.java:95)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at org.apache.struts.actions.DispatchAction.dispatchMethod(DispatchAction.java:269)
at org.apache.struts.actions.DispatchAction.execute(DispatchAction.java:170)
at org.apache.struts.actions.LookupDispatchAction.execute(LookupDispatchAction.java:146)
at org.apache.struts.action.RequestProcessor.processActionPerform(RequestProcessor.java:425)
at org.apache.struts.action.RequestProcessor.process(RequestProcessor.java:228)
at org.apache.struts.action.ActionServlet.process(ActionServlet.java:1913)
at org.apache.struts.action.ActionServlet.doGet(ActionServlet.java:449)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:621)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:304)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at com.epam.testapp.utils.filter.EncodingFilter.doFilter(EncodingFilter.java:45)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.netbeans.modules.web.monitor.server.MonitorFilter.doFilter(MonitorFilter.java:393)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:240)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:164)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:498)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:164)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:100)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:562)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:394)
at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:243)
at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:188)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:302)
at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:886)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:908)
at java.lang.Thread.run(Thread.java:619)
</code>```

Have some idea?

答:
Your loadTimeWeaver is a SimpleLoadTimeWeaver, which is usually used in testing environments. From the javadocs

LoadTimeWeaver that builds and exposes a
  SimpleInstrumentableClassLoader.

Mainly intended for testing environments, where it is sufficient to
  perform all class transformation on a newly created ClassLoader
  instance.

According to this entry in the manual on Spring JPA I suspect you'll need something more like this:

```<code><context:load-time-weaver/>
<bean id="entityManagerFactory"
      class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
    <property name="dataSource" ref="dataSource"/>
    <property name="jpaVendorAdapter">
        <bean class="org.springframework.orm.jpa.vendor.OpenJpaVendorAdapter">
            <property name="showSql" value="true"/>
            <property name="database" value="ORACLE"/>
        </bean>
    </property>
</bean>
</code>```

and you according to this may have to modify the tomcat context to tell tomcat to use a custom classloader:

```<code><Context path="/myWebApp" docBase="/my/webApp/location">
    <Loader loaderClass="org.springframework.instrument.classloading.tomcat.TomcatInstrumentableClassLoader"/>
</Context>
</code>```

ContentLicense: CC BY-SA 3.0

Title: Spring+JPA+DAO+Tomcat

Body:
persistence.xml

<persistence-unit name="myEntityManager" transaction-type="RESOURCE_LOCAL">
<class>com.epam.testapp.model.News</class>
<exclude-unlisted-classes>true</exclude-unlisted-classes>

News

private Integer newsId;
private String title;
private String brief;
private String content;
private Date created;
private String dateCreatedString;

public News() {
}

@Id
@Column(name = "NEWS_ID")
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "news_seq")
@SequenceGenerator(name = "news_seq", sequenceName = "NEWS_SEQ")
public Integer getNewsId() {
    return newsId;
}

public void setNewsId(Integer newsId) {
    this.newsId = newsId;
}

@Column(nullable = false, name = "TITLE")
public String getTitle() {
    return title;
}

public void setTitle(String title) {
    this.title = title;
}

@Column(nullable = false, name = "BRIEF")
public String getBrief() {
    return brief;
}

public void setBrief(String brief) {
    this.brief = brief;
}

@Column(name = "CONTENT")
public String getContent() {
    return content;
}

public void setContent(String content) {
    this.content = content;
}

@Temporal(value = TemporalType.DATE)
@Column(nullable = false, name = "CREATED")
public Date getCreated() {
    return created;
}

public void setCreated(Date created) {
    this.created = created;
}

@Transient
public String getDateCreatedString() {
    return dateCreatedString;
}

public void setDateCreatedString(String dateCreatedString) {
    this.dateCreatedString = dateCreatedString;
}

equals and hashcode

xml for spring

    <bean id="propertyConfigurer"
      class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
    <property name="location" value="/WEB-INF/databaseConfiguration.properties"/>
</bean>

<bean  id="newsDAO"
    class="com.epam.testapp.database.NewsDaoJPA">
    <property name="entityManagerFactory" ref="entityManagerFactory"/>
</bean>

<bean id="entityManagerFactory" class=
  "org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
    <property name="dataSource" ref="dataSource"/>
    <property name="jpaVendorAdapter">
        <bean class="org.springframework.orm.jpa.vendor.OpenJpaVendorAdapter">
            <property name="showSql" value="true"/>
            <property name="database" value="ORACLE"/>
        </bean>
    </property>
    <property name="loadTimeWeaver">
        <bean class="org.springframework.instrument.classloading.SimpleLoadTimeWeaver"/>
    </property>
</bean>

<bean id="dataSource"
 class="org.springframework.jdbc.datasource.DriverManagerDataSource">
    <property name="driverClassName" value="${database.driver}"/>
    <property name="url" value="${database.url}"/>
    <property name="username" value="${database.user}"/>
    <property name="password" value="${database.password}"/>
</bean>

<bean id="transactionManager"
 class="org.springframework.orm.jpa.JpaTransactionManager">
    <property name="entityManagerFactory" ref="entityManagerFactory"/>
    <property name="dataSource" ref="dataSource"/>
</bean>

but when call dao method for example

public List<News> getList() throws DAOException {
    return getJpaTemplate().find("select n from News n");
}

i get

java.lang.IllegalArgumentException: object is not an instance of declaring class
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.invokeProxyMethod(AbstractEntityManagerFactoryBean.java:423)
at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean$ManagedEntityManagerFactoryInvocationHandler.invoke(AbstractEntityManagerFactoryBean.java:485)
at $Proxy4.createEntityManager(Unknown Source)
at org.springframework.orm.jpa.EntityManagerFactoryAccessor.createEntityManager(EntityManagerFactoryAccessor.java:116)
at org.springframework.orm.jpa.JpaTemplate.execute(JpaTemplate.java:176)
at org.springframework.orm.jpa.JpaTemplate.contains(JpaTemplate.java:245)
at com.epam.testapp.database.NewsDaoJPA.getList(NewsDaoJPA.java:26)
at com.epam.testapp.presentation.action.NewsAction.list(NewsAction.java:95)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at org.apache.struts.actions.DispatchAction.dispatchMethod(DispatchAction.java:269)
at org.apache.struts.actions.DispatchAction.execute(DispatchAction.java:170)
at org.apache.struts.actions.LookupDispatchAction.execute(LookupDispatchAction.java:146)
at org.apache.struts.action.RequestProcessor.processActionPerform(RequestProcessor.java:425)
at org.apache.struts.action.RequestProcessor.process(RequestProcessor.java:228)
at org.apache.struts.action.ActionServlet.process(ActionServlet.java:1913)
at org.apache.struts.action.ActionServlet.doGet(ActionServlet.java:449)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:621)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:304)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at com.epam.testapp.utils.filter.EncodingFilter.doFilter(EncodingFilter.java:45)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.netbeans.modules.web.monitor.server.MonitorFilter.doFilter(MonitorFilter.java:393)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:240)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:164)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:498)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:164)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:100)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:562)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:394)
at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:243)
at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:188)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:302)
at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:886)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:908)
at java.lang.Thread.run(Thread.java:619)

Have some idea?

Body:
Your loadTimeWeaver is a SimpleLoadTimeWeaver, which is usually used in testing environments. From the javadocs

LoadTimeWeaver that builds and exposes a
  SimpleInstrumentableClassLoader.

Mainly intended for testing environments, where it is sufficient to
  perform all class transformation on a newly created ClassLoader
  instance.

According to this entry in the manual on Spring JPA I suspect you'll need something more like this:

<context:load-time-weaver/>
<bean id="entityManagerFactory"
      class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
    <property name="dataSource" ref="dataSource"/>
    <property name="jpaVendorAdapter">
        <bean class="org.springframework.orm.jpa.vendor.OpenJpaVendorAdapter">
            <property name="showSql" value="true"/>
            <property name="database" value="ORACLE"/>
        </bean>
    </property>
</bean>

and you according to this may have to modify the tomcat context to tell tomcat to use a custom classloader:

<Context path="/myWebApp" docBase="/my/webApp/location">
    <Loader loaderClass="org.springframework.instrument.classloading.tomcat.TomcatInstrumentableClassLoader"/>
</Context>


问:
Python error in serverless framework stating - Serverless Error: spawn docker ENOENT
Error:

```<code>Running "serverless" from node_modules

Deploying serverless-flask to stage dev (us-east-1)

✖ Stack serverless-flask-dev failed to deploy (0s)
Environment: darwin, node 16.0.0, framework 3.1.1 (local) 3.1.1v (global), plugin 6.0.0, SDK 4.3.1
Credentials: Local, "default" profile
Docs:        docs.serverless.com
Support:     forum.serverless.com
Bugs:        github.com/serverless/serverless/issues

Error:
Error: spawn docker ENOENT
    at Process.ChildProcess._handle.onexit (node:internal/child_process:282:19)
    at onErrorNT (node:internal/child_process:480:16)
    at processTicksAndRejections (node:internal/process/task_queues:83:21)
</code>```

I'm following these instructions (https://www.serverless.com/blog/flask-python-rest-api-serverless-lambda-dynamodb/) and can't seem to figure this out since the base app is in python and not javascript... most people who have solved this solved it using javascript.

答:
To be able to deploy your project with serverless-python-requirements you need to have docker on your machine (if you are on windows consider using docker desktop or a linux vm)

Why do I need Docker ?

When you do a sls deploy, serverless-python-requirements launch a docker container to install all the dependencies you've put in your requirements.txt file that will be used during the deployement process

You are getting this error because your container is not launch correctly

Body:
Error:

Running "serverless" from node_modules

Deploying serverless-flask to stage dev (us-east-1)

✖ Stack serverless-flask-dev failed to deploy (0s)
Environment: darwin, node 16.0.0, framework 3.1.1 (local) 3.1.1v (global), plugin 6.0.0, SDK 4.3.1
Credentials: Local, "default" profile
Docs:        docs.serverless.com
Support:     forum.serverless.com
Bugs:        github.com/serverless/serverless/issues

Error:
Error: spawn docker ENOENT
    at Process.ChildProcess._handle.onexit (node:internal/child_process:282:19)
    at onErrorNT (node:internal/child_process:480:16)
    at processTicksAndRejections (node:internal/process/task_queues:83:21)

I'm following these instructions (https://www.serverless.com/blog/flask-python-rest-api-serverless-lambda-dynamodb/) and can't seem to figure this out since the base app is in python and not javascript... most people who have solved this solved it using javascript.


问:
Type inference F# - how to generate fresh variables?
i'm trying to develop the algorithm W in f# for type inference, but i would like to understand how to write the function for generating fresh variables properly.

Actually my function is

```<code>let counter = ref -1

let generate_fresh_variable () : string =
    let list_variables = ['a' .. 'z'] |> List.map string
    counter.Value <- !counter + 1
    list_variables.Item(!counter)
</code>```

but i'm not satisfy with this solution, someone can give me other better ideas?

答:
If you really want to do this with an impure function, I would write it like this:

let mutable counter = -1

let generate_fresh_variable () =
    counter <- counter + 1
    counter + int 'a'
        |> char
        |> string
```

Notes:

Reference cells are obsolete. If you need impurity, use mutable variables instead. (Alternatively, if you really want to stick with a reference cell, the canonical way to update it is with :=, rather than assigning directly to the underlying Value.)

There's no need to maintain a list of potential variable names (and there's especially no need to rebuild the entire list each time you generate a fresh variable).

What happens if you need more than 26 variables?

Body:
i'm trying to develop the algorithm W in f# for type inference, but i would like to understand how to write the function for generating fresh variables properly.

Actually my function is

let counter = ref -1

let generate_fresh_variable () : string =
    let list_variables = ['a' .. 'z'] |> List.map string
    counter.Value <- !counter + 1
    list_variables.Item(!counter)

but i'm not satisfy with this solution, someone can give me other better ideas?

Body:
If you really want to do this with an impure function, I would write it like this:

let mutable counter = -1

let generate_fresh_variable () =
    counter <- counter + 1
    counter + int 'a'
        |> char
        |> string

Notes:

Reference cells are obsolete. If you need impurity, use mutable variables instead. (Alternatively, if you really want to stick with a reference cell, the canonical way to update it is with :=, rather than assigning directly to the underlying Value.)

There's no need to maintain a list of potential variable names (and there's especially no need to rebuild the entire list each time you generate a fresh variable).

What happens if you need more than 26 variables?


问:
Parent repo not detecting commits in submodule
I make a change in the submodule and commit it, come back to the parent repo and on checking git status, expect it to say there are changes in the submodule, but nothing is listed. The parent repo doesn't point to the latest commit of the submodule either.

答:
I have intermittently experienced the issue you describe and the following commands have worked for me

```<code>git rm --cached path/to/submodule
git restore --staged path/to/submodule
</code>```

git status should now show the new commit in the submodule

Body:
I have intermittently experienced the issue you describe and the following commands have worked for me

git rm --cached path/to/submodule
git restore --staged path/to/submodule

git status should now show the new commit in the submodule


问:
Keep Google collob running even after internet connection is lost
Is there a way to keep google collab running even after losing internet connection for some time?</p>

答: As far as I know and I found in the online articles Colab doesn't support running without an internet connection.</p>


问:
calculate mean by group with split and sapply
In R, I used sapply+split function to calculate mean of the dataset iris.

"There is a famous dataset in R called "iris". It should already be loaded in R for you. If you type in ?iris you can see some documentation. Familiarize yourself with this dataset.
Now obtain the mean of the first 4 variables, by species, but using only one function call."

This is what I have:

```<code>sapply(split(iris[1:4],iris$Species),mean)
</code>```

I received the error of "argument is not numeric or logical: returning NA"

I do not know where I got wrong, can anyone help?

答:
As split returns a list of dataframes, you need to change mean by colMeans:

```<code>> sapply(split(iris[1:4],iris$Species),colMeans)
             setosa versicolor virginica
Sepal.Length  5.006      5.936     6.588
Sepal.Width   3.428      2.770     2.974
Petal.Length  1.462      4.260     5.552
Petal.Width   0.246      1.326     2.026
</code>```

Body:
In R, I used sapply+split function to calculate mean of the dataset iris.

"There is a famous dataset in R called "iris". It should already be loaded in R for you. If you type in ?iris you can see some documentation. Familiarize yourself with this dataset.
Now obtain the mean of the first 4 variables, by species, but using only one function call."

This is what I have:

sapply(split(iris[1:4],iris$Species),mean)

I received the error of "argument is not numeric or logical: returning NA"

I do not know where I got wrong, can anyone help?

Body:
As split returns a list of dataframes, you need to change mean by colMeans:

> sapply(split(iris[1:4],iris$Species),colMeans)
             setosa versicolor virginica
Sepal.Length  5.006      5.936     6.588
Sepal.Width   3.428      2.770     2.974
Petal.Length  1.462      4.260     5.552
Petal.Width   0.246      1.326     2.026


问:
Cannot t read properties of unknown reading ('cache')
I've been trying to make a welcome embed for a Discord.js bot. My problem is, that I keep getting the error:

```<code>TypeError: Cannot read properties of undefined (reading 'cache')
</code>```

If I modify guild to guilds then I get this error:

```<code>TypeError: Cannot read properties of undefined (reading 'get')
</code>```

I'm trying to display the amount of members in the guild (server). However, this error is preventing me. I've tried googling but I am unable to find any solutions, so I came here. I am using Discord.js v13.6 (the latest version).

The code is supposed to show an embed, when a member joins the guild.
Here, of course, is my code:

const { MessageEmbed } = require('discord.js');

module.exports = {
   name: 'guildMemberAdd',
   once: false,
   execute(member) {
       console.log('New member joined')
       const WelcomeChannel = '941373101277589564'
       const guild =  member.guilds.cache.get('940180806696058910')
       const channel = member.guilds.channels.cache.get(WelcomeChannel)
       let welcomeEmbed = new MessageEmbed()
            .setDescription(`Welcome <@${member.user.id}> to the **Monocle Games** Discord server.\n Member Count: ${guild.memberCount} `)
            .setTimestamp()

        welcomeEmbed.setAuthor({
            name: '**WELCOME**',
            iconURL: member.user.avatarURL()
        })
        channel.send({embeds: [welcomeEmbed]})
   }
}
```

It is part of an event handler, however that is not related to the problem. My first thought was that the way I was getting the guild was outdated, however, I do believe this is the latest version, so what am I doing wrong?

答:
Member has guild property:

const guild = member.guild
const channel = guild.channels.cache.get(WelcomeChannel)
```

Body:
I've been trying to make a welcome embed for a Discord.js bot. My problem is, that I keep getting the error:

TypeError: Cannot read properties of undefined (reading 'cache')

If I modify guild to guilds then I get this error:

TypeError: Cannot read properties of undefined (reading 'get')

I'm trying to display the amount of members in the guild (server). However, this error is preventing me. I've tried googling but I am unable to find any solutions, so I came here. I am using Discord.js v13.6 (the latest version).

The code is supposed to show an embed, when a member joins the guild.
Here, of course, is my code:

const { MessageEmbed } = require('discord.js');

module.exports = {
   name: 'guildMemberAdd',
   once: false,
   execute(member) {
       console.log('New member joined')
       const WelcomeChannel = '941373101277589564'
       const guild =  member.guilds.cache.get('940180806696058910')
       const channel = member.guilds.channels.cache.get(WelcomeChannel)
       let welcomeEmbed = new MessageEmbed()
            .setDescription(`Welcome <@${member.user.id}> to the **Monocle Games** Discord server.\n Member Count: ${guild.memberCount} `)
            .setTimestamp()

        welcomeEmbed.setAuthor({
            name: '**WELCOME**',
            iconURL: member.user.avatarURL()
        })
        channel.send({embeds: [welcomeEmbed]})
   }
}

It is part of an event handler, however that is not related to the problem. My first thought was that the way I was getting the guild was outdated, however, I do believe this is the latest version, so what am I doing wrong?


问:
Stack and heap misunderstanding in Swift
I've always known that reference type variables are stored in the heap while value type variables are stored in the stack. Recently, I found this picture that says that ints, doubles, strings, etc. are value types, while functions and closures are reference types:

Now I'm really confused. So where are ints, doubles, strings, etc. are kept when they are defined inside a class, aka reference type? At the same type, where are functions are closures kept when defined inside a struct, aka value type?

答:
I've always known that reference type variables are stored in the heap while value type variables are stored in the stack.

This is only partially true in Swift. In general, Swift makes no guarantees about where objects and values are stored, except that:

Reference types have a stable location in memory, so that all references to the same object point to exactly the same place, and

Value types are not guaranteed to have a stable location in memory, and can be copied arbitrarily as the compiler sees fit

This technically means that object types can be stored on the stack if the compiler knows that an object is created and destructed within the same stack frame with no escaping references to it, but in practice, you can basically assume that all objects are allocated on the heap.

For value types, the story is a little more complicated:

Unless a location-based reference is required of a value (e.g., taking a reference to a struct with &), a struct may be located entirely in registers: operating on small structs may place its members in CPU registers so it never even lives in memory. (This is especially the case for small, possibly short-lived value types like Ints and Doubles, which are guaranteed to fit in registers)

Large value types do actually get heap-allocated: although this is an implementation detail of Swift that theoretically could change in the future, structs which are larger than 3 machine words (e.g., larger than 12 bytes on a 32-bit machine, or 24 bytes on a 64-bit machine) are pretty much guaranteed to be allocated and stored on the heap. This doesn't conflict with the value-ness of a value type: it can still be copied arbitrarily as the compiler wishes, and the compiler does a really good job of avoiding unnecessary allocations where it can

So where are ints, doubles, strings, etc. are kept when they are defined inside a class, aka reference type?

This is an excellent question that gets at the heart of what a value type is. One way to think of the storage of a value type is inline, wherever it needs to be. Imagine a

struct Point {
    var x: Double
    var y: Double
}
```
<p>structure, which is laid out in memory. Ignoring the fact that <code>Point</code> itself is a struct for a second, where are <code>x</code> and <code>y</code> stored relative to <code>Point</code>? Well, <em>inline</em> wherever <code>Point</code> goes:</p>
```┌───────────┐
│   Point   │
├─────┬─────┤
│  x  │  y  │
└─────┴─────┘
```
<p>When you need to store a <code>Point</code>, the compiler ensures that you have enough space to store both <code>x</code> and <code>y</code>, usually one immediately following the other. If a <code>Point</code> is stored on the stack, then <code>x</code> and <code>y</code> are stored on the stack, one after the other; if <code>Point</code> is stored on the heap, then <code>x</code> and <code>y</code> live on the <em>heap</em> as <em>part</em> of <code>Point</code>. Wherever Swift places a <code>Point</code>, it always ensures you have enough space, and when you assign to <code>x</code> and <code>y</code>, they are written to that space. It doesn't terribly matter where that is.</p>
<p>And when <code>Point</code> is part of <em>another</em> object? e.g.</p>
<pre class="lang-swift prettyprint-override"><code>class Location {
    var name: String
    var point: Point
}
</code>```

Then Point is also laid out inline wherever it is stored, and its values are laid out inline as well:

```<code>┌──────────────────────┐
│       Location       │
├──────────┬───────────┤
│          │   Point   │
│   name   ├─────┬─────┤
│          │  x  │  y  │
└──────────┴─────┴─────┘
</code>```

In this case, when you create a Location object, the compiler ensures that there's enough space to store a String and two Doubles, and lays them out one after another. Where that is, again, doesn't matter, but in this case, it's all on the heap (because Location is a reference type, which happens to contain values).

As for the other way around, object storage has to components:

The variable you use to access the object, and

The actual storage for the object

Let's say that we changed Point from being a struct to being a class. When before, Location stored the contents of Point directly, now, it only stores a reference to their actual storage in memory:

```<code>┌──────────────────────┐      ┌───────────┐
│       Location       │ ┌───▶│   Point   │
├──────────┬───────────┤ │    ├─────┬─────┤
│   name   │   point ──┼─┘    │  x  │  y  │
└──────────┴───────────┘      └─────┴─────┘
</code>```

Before, when Swift laid out space to create a Location, it was storing one String and two Doubles; now, it stores one String and one pointer to a Point. Unlike in languages like C or C++, you don't actually need to be aware of the fact that Location.point is now a pointer, and it doesn't actually change how you access the object; but under the hood, the size and "shape" of Location has changed.

The same goes for storing all other reference types, including closures. A variable holding a closure is largely just a pointer to some metadata for the closure, and a way to execute the closure's code (though the specifics of this are out of scope for this answer):

```<code>┌───────────────────────────────┐     ┌───────────┐
│           MyStruct            │     │  closure  │
├─────────┬─────────┬───────────┤ ┌──▶│  storage  │
│  prop1  │  prop2  │  closure ─┼─┘   │  + code   │
└─────────┴─────────┴───────────┘     └───────────┘
</code>```

Body:
I've always known that reference type variables are stored in the heap while value type variables are stored in the stack.

This is only partially true in Swift. In general, Swift makes no guarantees about where objects and values are stored, except that:

Reference types have a stable location in memory, so that all references to the same object point to exactly the same place, and

Value types are not guaranteed to have a stable location in memory, and can be copied arbitrarily as the compiler sees fit

This technically means that object types can be stored on the stack if the compiler knows that an object is created and destructed within the same stack frame with no escaping references to it, but in practice, you can basically assume that all objects are allocated on the heap.

For value types, the story is a little more complicated:

Unless a location-based reference is required of a value (e.g., taking a reference to a struct with &), a struct may be located entirely in registers: operating on small structs may place its members in CPU registers so it never even lives in memory. (This is especially the case for small, possibly short-lived value types like Ints and Doubles, which are guaranteed to fit in registers)

Large value types do actually get heap-allocated: although this is an implementation detail of Swift that theoretically could change in the future, structs which are larger than 3 machine words (e.g., larger than 12 bytes on a 32-bit machine, or 24 bytes on a 64-bit machine) are pretty much guaranteed to be allocated and stored on the heap. This doesn't conflict with the value-ness of a value type: it can still be copied arbitrarily as the compiler wishes, and the compiler does a really good job of avoiding unnecessary allocations where it can

So where are ints, doubles, strings, etc. are kept when they are defined inside a class, aka reference type?

This is an excellent question that gets at the heart of what a value type is. One way to think of the storage of a value type is inline, wherever it needs to be. Imagine a

struct Point {
    var x: Double
    var y: Double
}

structure, which is laid out in memory. Ignoring the fact that Point itself is a struct for a second, where are x and y stored relative to Point? Well, inline wherever Point goes:

┌───────────┐
│   Point   │
├─────┬─────┤
│  x  │  y  │
└─────┴─────┘

When you need to store a Point, the compiler ensures that you have enough space to store both x and y, usually one immediately following the other. If a Point is stored on the stack, then x and y are stored on the stack, one after the other; if Point is stored on the heap, then x and y live on the heap as part of Point. Wherever Swift places a Point, it always ensures you have enough space, and when you assign to x and y, they are written to that space. It doesn't terribly matter where that is.

And when Point is part of another object? e.g.

class Location {
    var name: String
    var point: Point
}

Then Point is also laid out inline wherever it is stored, and its values are laid out inline as well:

┌──────────────────────┐
│       Location       │
├──────────┬───────────┤
│          │   Point   │
│   name   ├─────┬─────┤
│          │  x  │  y  │
└──────────┴─────┴─────┘

In this case, when you create a Location object, the compiler ensures that there's enough space to store a String and two Doubles, and lays them out one after another. Where that is, again, doesn't matter, but in this case, it's all on the heap (because Location is a reference type, which happens to contain values).

As for the other way around, object storage has to components:

The variable you use to access the object, and

The actual storage for the object

Let's say that we changed Point from being a struct to being a class. When before, Location stored the contents of Point directly, now, it only stores a reference to their actual storage in memory:

┌──────────────────────┐      ┌───────────┐
│       Location       │ ┌───▶│   Point   │
├──────────┬───────────┤ │    ├─────┬─────┤
│   name   │   point ──┼─┘    │  x  │  y  │
└──────────┴───────────┘      └─────┴─────┘

Before, when Swift laid out space to create a Location, it was storing one String and two Doubles; now, it stores one String and one pointer to a Point. Unlike in languages like C or C++, you don't actually need to be aware of the fact that Location.point is now a pointer, and it doesn't actually change how you access the object; but under the hood, the size and "shape" of Location has changed.

The same goes for storing all other reference types, including closures. A variable holding a closure is largely just a pointer to some metadata for the closure, and a way to execute the closure's code (though the specifics of this are out of scope for this answer):

┌───────────────────────────────┐     ┌───────────┐
│           MyStruct            │     │  closure  │
├─────────┬─────────┬───────────┤ ┌──▶│  storage  │
│  prop1  │  prop2  │  closure ─┼─┘   │  + code   │
└─────────┴─────────┴───────────┘     └───────────┘


问:
Sending and Receiving arrays via Sockets
Is it possible to send an array through UDP Sockets using Python? I am using Python 2.5 and trying to send a simple array but it's not working. It can send the array successfully but when I try to print it with an item of the array the program crashes. I'm not sure what the error is as I take the precaution of converting the data into an array but it's not working. Hope I explained the problem as clearly as possible. I would appreciate the help!</p>

```<code># Client program

from socket import *
import numpy
from array import*

# Set the socket parameters
host = "localhost"
port = 21567
buf = 4096
addr = (host,port)

# Create socket
UDPSock = socket(AF_INET,SOCK_DGRAM)

def_msg = "===Enter message to send to server===";
print "\n",def_msg
a = array('i',[1,3,2])
# Send messages
while (1):
    data = raw_input('yes or now')
    if data!= "yes":
        break
    else:
        if(UDPSock.sendto(a,addr)):
            print "Sending message"

# Close socket
UDPSock.close()

# Server program

from socket import *

# Set the socket parameters
host = "localhost"
port = 21567
buf = 4096
addr = (host,port)

# Create socket and bind to address
UDPSock = socket(AF_INET,SOCK_DGRAM)
UDPSock.bind(addr)

# Receive messages
while 1:
    data,addr = UDPSock.recvfrom(buf)
    L = eval(data)
    if not data:
        print "Client has exited!"
        break
    else:
        print "\nReceived message '", L[1],"'"

# Close socket
UDPSock.close()
</code>```

答:
You could try to pickle the array. Pickle is a python library to en- and decode python objects. It is able to do much more, but it is definitely sufficient to fulfill your task:

on the sender side you pickle the object to a string:

```<code>pickled_string = pickle.dumps(a)
</code>```

on the receiver side you unpickle the object:

```<code>a = pickle.loads(received_string)
# a is now your sent array
</code>```

Body:
Is it possible to send an array through UDP Sockets using Python? I am using Python 2.5 and trying to send a simple array but it's not working. It can send the array successfully but when I try to print it with an item of the array the program crashes. I'm not sure what the error is as I take the precaution of converting the data into an array but it's not working. Hope I explained the problem as clearly as possible. I would appreciate the help!

# Client program

from socket import *
import numpy
from array import*

# Set the socket parameters
host = "localhost"
port = 21567
buf = 4096
addr = (host,port)

# Create socket
UDPSock = socket(AF_INET,SOCK_DGRAM)

def_msg = "===Enter message to send to server===";
print "\n",def_msg
a = array('i',[1,3,2])
# Send messages
while (1):
    data = raw_input('yes or now')
    if data!= "yes":
        break
    else:
        if(UDPSock.sendto(a,addr)):
            print "Sending message"

# Close socket
UDPSock.close()

# Server program

from socket import *

# Set the socket parameters
host = "localhost"
port = 21567
buf = 4096
addr = (host,port)

# Create socket and bind to address
UDPSock = socket(AF_INET,SOCK_DGRAM)
UDPSock.bind(addr)

# Receive messages
while 1:
    data,addr = UDPSock.recvfrom(buf)
    L = eval(data)
    if not data:
        print "Client has exited!"
        break
    else:
        print "\nReceived message '", L[1],"'"

# Close socket
UDPSock.close()

Body:
You could try to pickle the array. Pickle is a python library to en- and decode python objects. It is able to do much more, but it is definitely sufficient to fulfill your task:

on the sender side you pickle the object to a string:

pickled_string = pickle.dumps(a)

on the receiver side you unpickle the object:

a = pickle.loads(received_string)
# a is now your sent array


问:
How to replace dataframe values by other dataframe values, keeping values that are equal to both in R?
I have two dataframes, toy1 and toy2. I would like to create a new dataframe, replacing the different values that are in toy2 in toy1 and keeping the same values (0) that are in toy1. Taking into account that there are different numbers of columns and rows.
So in this example below, i want a result that is a dataframe of 208 columns and 2 rows.

toy1:

```<code>structure(list(revenue = 0, risk = 0, target_amount = 0, company_years = 0,
approved_commitee = 0, score = 0, reason_Capital_giro = 0,
reason_Compra_equip = 0, reason_Compra_estoque = 0, reason_Cons_div = 0,
reason_Expansao = 0, reason_Outros = 0, reason_working_capital = 0,
serasa_0 = 0, serasa_1 = 0, serasa_1.5 = 0, serasa_1.8 = 0,
serasa_2 = 0, serasa_2.6 = 0, serasa_3 = 0, serasa_3.1 = 0,
serasa_3.2 = 0, serasa_3.3 = 0, serasa_3.4 = 0, serasa_3.6 = 0,
serasa_3.8 = 0, serasa_4 = 0, serasa_4.2 = 0, serasa_4.4 = 0,
serasa_4.6 = 0, serasa_5 = 0, pontualidade_0.75neg = 0, pontualidade_0 = 0,
pontualidade_0.25 = 0, pontualidade_0.75 = 0, pontualidade_2.25 = 0,
pontualidade_2.5 = 0, pontualidade_2.75 = 0, pontualidade_3 = 0,
pontualidade_3.25 = 0, pontualidade_3.5 = 0, pontualidade_3.75 = 0,
pontualidade_4 = 0, pontualidade_4.25 = 0, pontualidade_4.5 = 0,
pontualidade_4.75 = 0, pontualidade_5 = 0, qualidade_divida_0 = 0,
qualidade_divida_1 = 0, qualidade_divida_1.4 = 0, qualidade_divida_1.6 = 0,
qualidade_divida_2 = 0, qualidade_divida_2.2 = 0, qualidade_divida_2.8 = 0,
qualidade_divida_3.4 = 0, qualidade_divida_3.5 = 0, qualidade_divida_3.7 = 0,
qualidade_divida_3.8 = 0, qualidade_divida_4 = 0, qualidade_divida_4.2 = 0,
qualidade_divida_4.5 = 0, qualidade_divida_4.6 = 0, qualidade_divida_4.8 = 0,
qualidade_divida_5 = 0, bancabilidade_0 = 0, bancabilidade_0.1 = 0,
bancabilidade_0.2 = 0, bancabilidade_0.5 = 0, bancabilidade_0.6 = 0,
bancabilidade_0.7 = 0, bancabilidade_0.8 = 0, bancabilidade_1 = 0,
bancabilidade_1.2 = 0, bancabilidade_1.3 = 0, bancabilidade_1.4 = 0,
bancabilidade_1.5 = 0, bancabilidade_1.6 = 0, bancabilidade_1.7 = 0,
bancabilidade_1.8 = 0, bancabilidade_2 = 0, bancabilidade_2.1 = 0,
bancabilidade_2.2 = 0, bancabilidade_2.3 = 0, bancabilidade_2.4 = 0,
bancabilidade_2.5 = 0, bancabilidade_2.6 = 0, bancabilidade_2.7 = 0,
bancabilidade_2.8 = 0, bancabilidade_3 = 0, bancabilidade_3.1 = 0,
bancabilidade_3.2 = 0, bancabilidade_3.3 = 0, bancabilidade_3.4 = 0,
bancabilidade_3.5 = 0, bancabilidade_3.6 = 0, bancabilidade_3.8 = 0,
bancabilidade_3.9 = 0, bancabilidade_4 = 0, bancabilidade_4.1 = 0,
bancabilidade_4.2 = 0, bancabilidade_4.4 = 0, bancabilidade_4.5 = 0,
bancabilidade_4.6 = 0, bancabilidade_4.7 = 0, bancabilidade_4.8 = 0,
bancabilidade_5 = 0, alavancagem_0 = 0, alavancagem_0.2 = 0,
alavancagem_1 = 0, alavancagem_1.6 = 0, alavancagem_2 = 0,
alavancagem_2.4 = 0, alavancagem_2.5 = 0, alavancagem_3 = 0,
alavancagem_3.4 = 0, alavancagem_4 = 0, alavancagem_5 = 0,
porte_0 = 0, porte_1 = 0, porte_1.4 = 0, porte_2 = 0, porte_2.4 = 0,
porte_2.8 = 0, porte_3 = 0, porte_3.2 = 0, porte_3.6 = 0,
porte_4 = 0, porte_4.4 = 0, porte_4.6 = 0, porte_4.8 = 0,
porte_5 = 0, receita_recorrencias_0.6 = 0, receita_recorrencias_0.8 = 0,
receita_recorrencias_1 = 0, receita_recorrencias_1.4 = 0,
receita_recorrencias_2 = 0, receita_recorrencias_2.4 = 0,
receita_recorrencias_2.6 = 0, receita_recorrencias_3 = 0,
receita_recorrencias_3.2 = 0, receita_recorrencias_3.4 = 0,
receita_recorrencias_3.8 = 0, receita_recorrencias_4 = 0,
receita_recorrencias_4.4 = 0, receita_recorrencias_5 = 0,
respaldo_patrimonio_0 = 0, respaldo_patrimonio_0.4 = 0, respaldo_patrimonio_0.5 = 0,
respaldo_patrimonio_0.7 = 0, respaldo_patrimonio_0.75 = 0,
respaldo_patrimonio_0.8 = 0, respaldo_patrimonio_1 = 0, respaldo_patrimonio_1.2 = 0,
respaldo_patrimonio_1.3 = 0, respaldo_patrimonio_1.4 = 0,
respaldo_patrimonio_1.5 = 0, respaldo_patrimonio_1.7 = 0,
respaldo_patrimonio_1.9 = 0, respaldo_patrimonio_2.2 = 0,
respaldo_patrimonio_2.3 = 0, respaldo_patrimonio_2.6 = 0,
respaldo_patrimonio_3 = 0, respaldo_patrimonio_3.2 = 0, respaldo_patrimonio_3.5 = 0,
respaldo_patrimonio_3.6 = 0, respaldo_patrimonio_4 = 0, respaldo_patrimonio_4.4 = 0,
respaldo_patrimonio_5 = 0, reputacional_1 = 0, reputacional_2 = 0,
reputacional_2.5 = 0, reputacional_3 = 0, reputacional_3.5 = 0,
reputacional_3.65 = 0, reputacional_4 = 0, reputacional_5 = 0,
impacto_covid_1 = 0, impacto_covid_1.5 = 0, impacto_covid_2 = 0,
impacto_covid_2.5 = 0, impacto_covid_3 = 0, impacto_covid_3.5 = 0,
impacto_covid_3.65 = 0, impacto_covid_4 = 0, impacto_covid_5 = 0,
business_sector_Comercio = 0, business_sector_Industria = 0,
business_sector_Servicos = 0, state_AC = 0, state_AM = 0,
state_BA = 0, state_CE = 0, state_DF = 0, state_GO = 0, state_MG = 0,
state_MS = 0, state_MT = 0, state_PA = 0, state_PB = 0, state_PE = 0,
state_PR = 0, state_RJ = 0, state_RS = 0, state_SC = 0, state_SP = 0,
state_TO = 0, decision_motor_approved = 0, decision_motor_denied = 0), row.names = 1L, class = "data.frame")
</code>```

toy2

```<code> structure(list(revenue = c(4397487.34, 198019.75), risk = c(12137650.06,
469506.24), target_amount = c(150000, 1e+05), company_years = c(18,
9), approved_commitee = structure(c(2L, 2L), .Label = c("NO",
"YES"), class = "factor"), score = c(134, 128), reason_Compra_equip = c(1,
1), serasa_1.8 = c(1, 1), pontualidade_0.25 = c(1, 1), qualidade_divida_1 = c(1,
1), bancabilidade_0.2 = c(1, 1), alavancagem_1.6 = c(1L, 1L),
    porte_4.6 = c(1, 1), receita_recorrencias_3 = c(1, 1), respaldo_patrimonio_0.5 = c(1,
    1), reputacional_5 = c(1, 1), impacto_covid_3 = c(1, 1),
    business_sector_Comercio = c(1, 1), state_GO = c(1, 1)), row.names = c(10L,
12L), class = "data.frame")
</code>```

答:
Because there is a cbind.data.frame method, you could cbind the portion of toy1 that has non-matching column names to all of toy2. R does recycling of needed rows in this situation. Admittedly the column order might not be the same. It could be restored to the original ordering if needed.

```<code>toy1.2 <-cbind(toy1[ ! names(toy1) %in% names(toy2) ], toy2 )
toy1.2
#---------------------------

  reason_Capital_giro reason_Compra_estoque reason_Cons_div reason_Expansao reason_Outros reason_working_capital
1                   0                     0               0               0             0                      0
2                   0                     0               0               0             0                      0
  serasa_0 serasa_1 serasa_1.5 serasa_2 serasa_2.6 serasa_3 serasa_3.1 serasa_3.2 serasa_3.3 serasa_3.4 serasa_3.6
1        0        0          0        0          0        0          0          0          0          0          0
2        0        0          0        0          0        0          0          0          0          0          0
#snipped a bunch of rows, leaving the new data from toy2

    revenue       risk target_amount company_years approved_commitee score reason_Compra_equip serasa_1.8
1 4397487.3 12137650.1        150000            18               YES   134                   1          1
2  198019.8   469506.2        100000             9               YES   128                   1          1
  pontualidade_0.25 qualidade_divida_1 bancabilidade_0.2 alavancagem_1.6 porte_4.6 receita_recorrencias_3
1                 1                  1                 1               1         1                      1
2                 1                  1                 1               1         1                      1
  respaldo_patrimonio_0.5 reputacional_5 impacto_covid_3 business_sector_Comercio state_GO
1                       1              1               1                        1        1
2                       1              1               1                        1        1
</code>```

Body:
I have two dataframes, toy1 and toy2. I would like to create a new dataframe, replacing the different values that are in toy2 in toy1 and keeping the same values (0) that are in toy1. Taking into account that there are different numbers of columns and rows.
So in this example below, i want a result that is a dataframe of 208 columns and 2 rows.

toy1:

structure(list(revenue = 0, risk = 0, target_amount = 0, company_years = 0,
approved_commitee = 0, score = 0, reason_Capital_giro = 0,
reason_Compra_equip = 0, reason_Compra_estoque = 0, reason_Cons_div = 0,
reason_Expansao = 0, reason_Outros = 0, reason_working_capital = 0,
serasa_0 = 0, serasa_1 = 0, serasa_1.5 = 0, serasa_1.8 = 0,
serasa_2 = 0, serasa_2.6 = 0, serasa_3 = 0, serasa_3.1 = 0,
serasa_3.2 = 0, serasa_3.3 = 0, serasa_3.4 = 0, serasa_3.6 = 0,
serasa_3.8 = 0, serasa_4 = 0, serasa_4.2 = 0, serasa_4.4 = 0,
serasa_4.6 = 0, serasa_5 = 0, pontualidade_0.75neg = 0, pontualidade_0 = 0,
pontualidade_0.25 = 0, pontualidade_0.75 = 0, pontualidade_2.25 = 0,
pontualidade_2.5 = 0, pontualidade_2.75 = 0, pontualidade_3 = 0,
pontualidade_3.25 = 0, pontualidade_3.5 = 0, pontualidade_3.75 = 0,
pontualidade_4 = 0, pontualidade_4.25 = 0, pontualidade_4.5 = 0,
pontualidade_4.75 = 0, pontualidade_5 = 0, qualidade_divida_0 = 0,
qualidade_divida_1 = 0, qualidade_divida_1.4 = 0, qualidade_divida_1.6 = 0,
qualidade_divida_2 = 0, qualidade_divida_2.2 = 0, qualidade_divida_2.8 = 0,
qualidade_divida_3.4 = 0, qualidade_divida_3.5 = 0, qualidade_divida_3.7 = 0,
qualidade_divida_3.8 = 0, qualidade_divida_4 = 0, qualidade_divida_4.2 = 0,
qualidade_divida_4.5 = 0, qualidade_divida_4.6 = 0, qualidade_divida_4.8 = 0,
qualidade_divida_5 = 0, bancabilidade_0 = 0, bancabilidade_0.1 = 0,
bancabilidade_0.2 = 0, bancabilidade_0.5 = 0, bancabilidade_0.6 = 0,
bancabilidade_0.7 = 0, bancabilidade_0.8 = 0, bancabilidade_1 = 0,
bancabilidade_1.2 = 0, bancabilidade_1.3 = 0, bancabilidade_1.4 = 0,
bancabilidade_1.5 = 0, bancabilidade_1.6 = 0, bancabilidade_1.7 = 0,
bancabilidade_1.8 = 0, bancabilidade_2 = 0, bancabilidade_2.1 = 0,
bancabilidade_2.2 = 0, bancabilidade_2.3 = 0, bancabilidade_2.4 = 0,
bancabilidade_2.5 = 0, bancabilidade_2.6 = 0, bancabilidade_2.7 = 0,
bancabilidade_2.8 = 0, bancabilidade_3 = 0, bancabilidade_3.1 = 0,
bancabilidade_3.2 = 0, bancabilidade_3.3 = 0, bancabilidade_3.4 = 0,
bancabilidade_3.5 = 0, bancabilidade_3.6 = 0, bancabilidade_3.8 = 0,
bancabilidade_3.9 = 0, bancabilidade_4 = 0, bancabilidade_4.1 = 0,
bancabilidade_4.2 = 0, bancabilidade_4.4 = 0, bancabilidade_4.5 = 0,
bancabilidade_4.6 = 0, bancabilidade_4.7 = 0, bancabilidade_4.8 = 0,
bancabilidade_5 = 0, alavancagem_0 = 0, alavancagem_0.2 = 0,
alavancagem_1 = 0, alavancagem_1.6 = 0, alavancagem_2 = 0,
alavancagem_2.4 = 0, alavancagem_2.5 = 0, alavancagem_3 = 0,
alavancagem_3.4 = 0, alavancagem_4 = 0, alavancagem_5 = 0,
porte_0 = 0, porte_1 = 0, porte_1.4 = 0, porte_2 = 0, porte_2.4 = 0,
porte_2.8 = 0, porte_3 = 0, porte_3.2 = 0, porte_3.6 = 0,
porte_4 = 0, porte_4.4 = 0, porte_4.6 = 0, porte_4.8 = 0,
porte_5 = 0, receita_recorrencias_0.6 = 0, receita_recorrencias_0.8 = 0,
receita_recorrencias_1 = 0, receita_recorrencias_1.4 = 0,
receita_recorrencias_2 = 0, receita_recorrencias_2.4 = 0,
receita_recorrencias_2.6 = 0, receita_recorrencias_3 = 0,
receita_recorrencias_3.2 = 0, receita_recorrencias_3.4 = 0,
receita_recorrencias_3.8 = 0, receita_recorrencias_4 = 0,
receita_recorrencias_4.4 = 0, receita_recorrencias_5 = 0,
respaldo_patrimonio_0 = 0, respaldo_patrimonio_0.4 = 0, respaldo_patrimonio_0.5 = 0,
respaldo_patrimonio_0.7 = 0, respaldo_patrimonio_0.75 = 0,
respaldo_patrimonio_0.8 = 0, respaldo_patrimonio_1 = 0, respaldo_patrimonio_1.2 = 0,
respaldo_patrimonio_1.3 = 0, respaldo_patrimonio_1.4 = 0,
respaldo_patrimonio_1.5 = 0, respaldo_patrimonio_1.7 = 0,
respaldo_patrimonio_1.9 = 0, respaldo_patrimonio_2.2 = 0,
respaldo_patrimonio_2.3 = 0, respaldo_patrimonio_2.6 = 0,
respaldo_patrimonio_3 = 0, respaldo_patrimonio_3.2 = 0, respaldo_patrimonio_3.5 = 0,
respaldo_patrimonio_3.6 = 0, respaldo_patrimonio_4 = 0, respaldo_patrimonio_4.4 = 0,
respaldo_patrimonio_5 = 0, reputacional_1 = 0, reputacional_2 = 0,
reputacional_2.5 = 0, reputacional_3 = 0, reputacional_3.5 = 0,
reputacional_3.65 = 0, reputacional_4 = 0, reputacional_5 = 0,
impacto_covid_1 = 0, impacto_covid_1.5 = 0, impacto_covid_2 = 0,
impacto_covid_2.5 = 0, impacto_covid_3 = 0, impacto_covid_3.5 = 0,
impacto_covid_3.65 = 0, impacto_covid_4 = 0, impacto_covid_5 = 0,
business_sector_Comercio = 0, business_sector_Industria = 0,
business_sector_Servicos = 0, state_AC = 0, state_AM = 0,
state_BA = 0, state_CE = 0, state_DF = 0, state_GO = 0, state_MG = 0,
state_MS = 0, state_MT = 0, state_PA = 0, state_PB = 0, state_PE = 0,
state_PR = 0, state_RJ = 0, state_RS = 0, state_SC = 0, state_SP = 0,
state_TO = 0, decision_motor_approved = 0, decision_motor_denied = 0), row.names = 1L, class = "data.frame")

toy2

 structure(list(revenue = c(4397487.34, 198019.75), risk = c(12137650.06,
469506.24), target_amount = c(150000, 1e+05), company_years = c(18,
9), approved_commitee = structure(c(2L, 2L), .Label = c("NO",
"YES"), class = "factor"), score = c(134, 128), reason_Compra_equip = c(1,
1), serasa_1.8 = c(1, 1), pontualidade_0.25 = c(1, 1), qualidade_divida_1 = c(1,
1), bancabilidade_0.2 = c(1, 1), alavancagem_1.6 = c(1L, 1L),
    porte_4.6 = c(1, 1), receita_recorrencias_3 = c(1, 1), respaldo_patrimonio_0.5 = c(1,
    1), reputacional_5 = c(1, 1), impacto_covid_3 = c(1, 1),
    business_sector_Comercio = c(1, 1), state_GO = c(1, 1)), row.names = c(10L,
12L), class = "data.frame")

Body:
Because there is a cbind.data.frame method, you could cbind the portion of toy1 that has non-matching column names to all of toy2. R does recycling of needed rows in this situation. Admittedly the column order might not be the same. It could be restored to the original ordering if needed.

toy1.2 <-cbind(toy1[ ! names(toy1) %in% names(toy2) ], toy2 )
toy1.2
#---------------------------

  reason_Capital_giro reason_Compra_estoque reason_Cons_div reason_Expansao reason_Outros reason_working_capital
1                   0                     0               0               0             0                      0
2                   0                     0               0               0             0                      0
  serasa_0 serasa_1 serasa_1.5 serasa_2 serasa_2.6 serasa_3 serasa_3.1 serasa_3.2 serasa_3.3 serasa_3.4 serasa_3.6
1        0        0          0        0          0        0          0          0          0          0          0
2        0        0          0        0          0        0          0          0          0          0          0
#snipped a bunch of rows, leaving the new data from toy2

    revenue       risk target_amount company_years approved_commitee score reason_Compra_equip serasa_1.8
1 4397487.3 12137650.1        150000            18               YES   134                   1          1
2  198019.8   469506.2        100000             9               YES   128                   1          1
  pontualidade_0.25 qualidade_divida_1 bancabilidade_0.2 alavancagem_1.6 porte_4.6 receita_recorrencias_3
1                 1                  1                 1               1         1                      1
2                 1                  1                 1               1         1                      1
  respaldo_patrimonio_0.5 reputacional_5 impacto_covid_3 business_sector_Comercio state_GO
1                       1              1               1                        1        1
2                       1              1               1                        1        1


问:
Find the lowest and highest NUMBERS in a collection
I have a List<BigDecimal> collection which contains (for the sake of simplicity) BigDecimal prices. I would like to process the collection and get:

All of the highest prices.

All of the lowest prices.

My initial thoughts are to approach this using look-behind in order to decide if the numbers are moving in an up or down trend. When the trend changes - determine which of the previous numbers are "highest" or "lowest" prices and then add them to the respectful List<BigDecimal> lowestPrices and List<BigDecimal highestPrices collections. For example, the first 3 dots are in an up-trend, but the 4th changes the trend to a down-trend. So can now determine the min/max of the numbers before the change (0,1,2) and get the prices.

I am not entirely sure if this isn't a naive approach so I was wondering if there would be the best approach to solving this issue in java?
Maybe a library that can already do this? (probably better not to re-invent the wheel)

答:
I decided to try implementing this, although I'm sure my implementation could be improved. The idea is just as you say, to keep track of the trend and record a local minimum or local maximum whenever the trend changes. There are two additional details to consider: first, initially we are not trending up or down, but the first value is either a minimum or maximum, so we have a third possibility for the trend, in addition to increasing or decreasing: inchoate; second, after the end of the loop we have to add the last item as either a minimum or maximum, depending on the direction the trend was going when we finished. Note that it will never add null if the list of prices is empty, because in that case, the trend would never have changed from inchoate.</p>
```<code>import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Map;
import java.util.List;

public class Partition {
    public static void main(String[] args) {
        List<String> values = List.of("10.99", "15.99", "19.99", "12.99", "24.99",
            "21.99", "17.99", "11.99", "22.99", "29.99", "35.99", "27.99", "20.99");
        List<BigDecimal> prices = values.stream().map(BigDecimal::new).toList();
        Map<Extrema, List<BigDecimal>> part = new Partition().partitionExtrema(prices);
        System.out.format("Minima: %s%n", part.get(Extrema.MINIMA));
        System.out.format("Maxima: %s%n", part.get(Extrema.MAXIMA));
    }

    public Map<Extrema, List<BigDecimal>> partitionExtrema(List<BigDecimal> prices) {
        Trend trend = Trend.INCHOATE; // intially we don't know if we're going up or down
        List<BigDecimal> maxima = new ArrayList<>();
        List<BigDecimal> minima = new ArrayList<>();
        BigDecimal previous = null;
        for (BigDecimal current : prices) {
            int direction = previous == null ? 0 : current.compareTo(previous);
            if (direction > 0) {
                if (trend != Trend.DECREASING) {
                    minima.add(previous); // switching from decreasing to increasing
                }
                trend = Trend.INCREASING;
            }
            if (direction < 0) {
                if (trend != Trend.INCREASING) {
                    maxima.add(previous); // switching from increasing to decreasing
                }
                trend = Trend.DECREASING;
            }
            previous = current;
        }
        if (trend == trend.INCREASING) {
            maxima.add(previous);
        } else if (trend == trend.DECREASING) {
            minima.add(previous);
        }
        return Map.of(Extrema.MINIMA, minima, Extrema.MAXIMA, maxima);
    }
}

public enum Trend {
    INCREASING,
    DECREASING,
    INCHOATE
}

public enum Extrema {
    MAXIMA,
    MINIMA
}
</code>```

Body:
I decided to try implementing this, although I'm sure my implementation could be improved. The idea is just as you say, to keep track of the trend and record a local minimum or local maximum whenever the trend changes. There are two additional details to consider: first, initially we are not trending up or down, but the first value is either a minimum or maximum, so we have a third possibility for the trend, in addition to increasing or decreasing: inchoate; second, after the end of the loop we have to add the last item as either a minimum or maximum, depending on the direction the trend was going when we finished. Note that it will never add null if the list of prices is empty, because in that case, the trend would never have changed from inchoate.

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Map;
import java.util.List;

public class Partition {
    public static void main(String[] args) {
        List<String> values = List.of("10.99", "15.99", "19.99", "12.99", "24.99",
            "21.99", "17.99", "11.99", "22.99", "29.99", "35.99", "27.99", "20.99");
        List<BigDecimal> prices = values.stream().map(BigDecimal::new).toList();
        Map<Extrema, List<BigDecimal>> part = new Partition().partitionExtrema(prices);
        System.out.format("Minima: %s%n", part.get(Extrema.MINIMA));
        System.out.format("Maxima: %s%n", part.get(Extrema.MAXIMA));
    }

    public Map<Extrema, List<BigDecimal>> partitionExtrema(List<BigDecimal> prices) {
        Trend trend = Trend.INCHOATE; // intially we don't know if we're going up or down
        List<BigDecimal> maxima = new ArrayList<>();
        List<BigDecimal> minima = new ArrayList<>();
        BigDecimal previous = null;
        for (BigDecimal current : prices) {
            int direction = previous == null ? 0 : current.compareTo(previous);
            if (direction > 0) {
                if (trend != Trend.DECREASING) {
                    minima.add(previous); // switching from decreasing to increasing
                }
                trend = Trend.INCREASING;
            }
            if (direction < 0) {
                if (trend != Trend.INCREASING) {
                    maxima.add(previous); // switching from increasing to decreasing
                }
                trend = Trend.DECREASING;
            }
            previous = current;
        }
        if (trend == trend.INCREASING) {
            maxima.add(previous);
        } else if (trend == trend.DECREASING) {
            minima.add(previous);
        }
        return Map.of(Extrema.MINIMA, minima, Extrema.MAXIMA, maxima);
    }
}

public enum Trend {
    INCREASING,
    DECREASING,
    INCHOATE
}

public enum Extrema {
    MAXIMA,
    MINIMA
}


问:
Why is sveltekit fetching for favicon.png in subpath?
I have a very basic sveltekit project(:3000) with a simple route structure that consumes a backend(:5000):

```<code>├── ./src
│   ├── ./src/app.html
│   ├── ./src/routes
│   │   ├── ./src/routes/index.svelte
│   │   ├── ./src/routes/__layout.svelte
│   │   └── ./src/routes/view
│   │       ├── ./src/routes/view/[id].svelte
│   │       └── ./src/routes/view/index.svelte
</code>```

Imagine a listing of companys in routes/index.svelte which prefetches on hovering the data of the listed companys with ....

In Chrome devtools it shows that this is working correctly, with http://localhost:5000/company/6203a1d7c36d6f78f5979f26. Yet for some reason, as soon as I click the link, sveltekit is fetching for http://localhost:3000/view/favicon.png, which obviously does not exists, because it is living in app/src/static/favicon.png.

Does anybody have ever seen this? Am I missing an obvious point on how to handle static assets that are called by subpaths? Or rather: why is the subpath route even calling a root asset?

Code for /routes/view/[id].svelte:

{company.name}

...
```
<p>The <code>/routes/view/index.svelte</code> file should not be a problem, that handles a simple redirection:</p>
<pre class="lang-html prettyprint-override"><code><script context="module" lang="ts">
    export async function load() {
        return {
            status: 302, redirect: "/"
        }
    }
</script>

<script>
    load();
</script>
</code>```

答:
This is usually caused when the code inside app.html uses favicon.png instead of /favicon.png which makes sveltekit looks for the favicon in the subpath it's currently at. Here's an example:

<!DOCTYPE html>

        <meta charset="utf-8" />

        <link rel="icon" href="/favicon.png" />
        <meta name="viewport" content="width=device-width, initial-scale=1" />

        %svelte.head%

%svelte.body%

```
<p>This happened to me so many times.</p>
<p>And on newer versions of sveltekit, inside the app.html, they have standardized this:</p>
<pre class="lang-html prettyprint-override"><code><!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="utf-8" />
        <meta name="description" content="Svelte demo app" />
        <!-- Notice the %svelte.assets% -->
        <link rel="icon" href="%svelte.assets%/favicon.png" />
        <meta name="viewport" content="width=device-width, initial-scale=1" />
        %svelte.head%
    </head>
    <body>
        <div>%svelte.body%</div>
    </body>
</html>

</code>```

Body:
I have a very basic sveltekit project(:3000) with a simple route structure that consumes a backend(:5000):

├── ./src
│   ├── ./src/app.html
│   ├── ./src/routes
│   │   ├── ./src/routes/index.svelte
│   │   ├── ./src/routes/__layout.svelte
│   │   └── ./src/routes/view
│   │       ├── ./src/routes/view/[id].svelte
│   │       └── ./src/routes/view/index.svelte

Imagine a listing of companys in routes/index.svelte which prefetches on hovering the data of the listed companys with ....

In Chrome devtools it shows that this is working correctly, with http://localhost:5000/company/6203a1d7c36d6f78f5979f26. Yet for some reason, as soon as I click the link, sveltekit is fetching for http://localhost:3000/view/favicon.png, which obviously does not exists, because it is living in app/src/static/favicon.png.

Does anybody have ever seen this? Am I missing an obvious point on how to handle static assets that are called by subpaths? Or rather: why is the subpath route even calling a root asset?

Code for /routes/view/[id].svelte:

{company.name}

...

The /routes/view/index.svelte file should not be a problem, that handles a simple redirection:

Body:
This is usually caused when the code inside app.html uses favicon.png instead of /favicon.png which makes sveltekit looks for the favicon in the subpath it's currently at. Here's an example:

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="utf-8" />
        <!-- Make sure there is a leading slash (/) to tell it to look in the root path -->
        <link rel="icon" href="/favicon.png" />
        <meta name="viewport" content="width=device-width, initial-scale=1" />

        %svelte.head%
    </head>
    <body>
        <div id="svelte">%svelte.body%</div>
    </body>
</html>

This happened to me so many times.

And on newer versions of sveltekit, inside the app.html, they have standardized this:

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="utf-8" />
        <meta name="description" content="Svelte demo app" />
        <!-- Notice the %svelte.assets% -->
        <link rel="icon" href="%svelte.assets%/favicon.png" />
        <meta name="viewport" content="width=device-width, initial-scale=1" />
        %svelte.head%
    </head>
    <body>
        <div>%svelte.body%</div>
    </body>
</html>


问:
NOT GROUP By issue
I try to make a sum in this formula but I have one issue, not group by expression ?

WHo is the problem ?

```<code>SELECT ROUND( SUM( FACT_WLT_AGENT.WLT_LHV_PO_FNGF +
                   FACT_WLT_AGENT.WLT_LHV_PO_ENA +
                   FACT_WLT_AGENT.WLT_LHV_PO_EEIND +
                   FACT_WLT_AGENT.WLT_LHV_PO_PAQ
              ) /
         3600 * 10
       )
FROM FACT_WLT_AGENT,
     dim_reorganization reorg
WHERE FACT_WLT_AGENT.reorg_id = reorg.reorg_id
  AND is_last_master_reorg    = 'Y'
HAVING FACT_WLT_AGENT.WLT_LHV_PO_FNGF +
       FACT_WLT_AGENT.WLT_LHV_PO_ENA +
       FACT_WLT_AGENT.WLT_LHV_PO_EEIND +
       FACT_WLT_AGENT.WLT_LHV_PO_PAQ /
       3600 > 0
</code>```

答:
To illustrate the problem, I'll use modified Scott's sample schema.

```<code>SQL> select sal, comm from emp where deptno = 10;

       SAL       COMM
---------- ----------
      2450        245
      5000        500
      1300        130

SQL>
</code>```

This is your current code (which doesn't work):

```<code>SQL> select sum(sal + comm) result
  2  from emp
  3  where deptno = 10
  4  having sal + comm > 0;
having sal + comm > 0
       *
ERROR at line 4:
ORA-00979: not a GROUP BY expression

SQL>
</code>```

Now, you can "fix" it by adding a group by clause, but I don't think that this is what you want:

```<code>SQL> select sum(sal + comm) result
  2  from emp
  3  where deptno = 10
  4  group by sal + comm
  5  having sal + comm > 0;

    RESULT
----------
      5500
      2695
      1430

SQL>
</code>```

I believe that you actually want this - use aggregation in having clause:

```<code>SQL> select sum(sal + comm) result
  2  from emp
  3  where deptno = 10
  4  having sum(sal + comm) > 0;

    RESULT
----------
      9625

SQL>
</code>```

Or, in your case:

```<code>SELECT ROUND( SUM( FACT_WLT_AGENT.WLT_LHV_PO_FNGF +
                   FACT_WLT_AGENT.WLT_LHV_PO_ENA +
                   FACT_WLT_AGENT.WLT_LHV_PO_EEIND +
                   FACT_WLT_AGENT.WLT_LHV_PO_PAQ
              ) /
         3600 * 10
       )
FROM FACT_WLT_AGENT,
     dim_reorganization reorg
WHERE FACT_WLT_AGENT.reorg_id = reorg.reorg_id
  AND is_last_master_reorg    = 'Y'
HAVING sum(FACT_WLT_AGENT.WLT_LHV_PO_FNGF +
           FACT_WLT_AGENT.WLT_LHV_PO_ENA +
           FACT_WLT_AGENT.WLT_LHV_PO_EEIND +
           FACT_WLT_AGENT.WLT_LHV_PO_PAQ) > 0;
</code>```

Title: NOT GROUP By issue

Body:
I try to make a sum in this formula but I have one issue, not group by expression ?

WHo is the problem ?

SELECT ROUND( SUM( FACT_WLT_AGENT.WLT_LHV_PO_FNGF +
                   FACT_WLT_AGENT.WLT_LHV_PO_ENA +
                   FACT_WLT_AGENT.WLT_LHV_PO_EEIND +
                   FACT_WLT_AGENT.WLT_LHV_PO_PAQ
              ) /
         3600 * 10
       )
FROM FACT_WLT_AGENT,
     dim_reorganization reorg
WHERE FACT_WLT_AGENT.reorg_id = reorg.reorg_id
  AND is_last_master_reorg    = 'Y'
HAVING FACT_WLT_AGENT.WLT_LHV_PO_FNGF +
       FACT_WLT_AGENT.WLT_LHV_PO_ENA +
       FACT_WLT_AGENT.WLT_LHV_PO_EEIND +
       FACT_WLT_AGENT.WLT_LHV_PO_PAQ /
       3600 > 0

Body:
To illustrate the problem, I'll use modified Scott's sample schema.

SQL> select sal, comm from emp where deptno = 10;

       SAL       COMM
---------- ----------
      2450        245
      5000        500
      1300        130

SQL>

This is your current code (which doesn't work):

SQL> select sum(sal + comm) result
  2  from emp
  3  where deptno = 10
  4  having sal + comm > 0;
having sal + comm > 0
       *
ERROR at line 4:
ORA-00979: not a GROUP BY expression

SQL>

Now, you can "fix" it by adding a group by clause, but I don't think that this is what you want:

SQL> select sum(sal + comm) result
  2  from emp
  3  where deptno = 10
  4  group by sal + comm
  5  having sal + comm > 0;

    RESULT
----------
      5500
      2695
      1430

SQL>

I believe that you actually want this - use aggregation in having clause:

SQL> select sum(sal + comm) result
  2  from emp
  3  where deptno = 10
  4  having sum(sal + comm) > 0;

    RESULT
----------
      9625

SQL>

Or, in your case:

SELECT ROUND( SUM( FACT_WLT_AGENT.WLT_LHV_PO_FNGF +
                   FACT_WLT_AGENT.WLT_LHV_PO_ENA +
                   FACT_WLT_AGENT.WLT_LHV_PO_EEIND +
                   FACT_WLT_AGENT.WLT_LHV_PO_PAQ
              ) /
         3600 * 10
       )
FROM FACT_WLT_AGENT,
     dim_reorganization reorg
WHERE FACT_WLT_AGENT.reorg_id = reorg.reorg_id
  AND is_last_master_reorg    = 'Y'
HAVING sum(FACT_WLT_AGENT.WLT_LHV_PO_FNGF +
           FACT_WLT_AGENT.WLT_LHV_PO_ENA +
           FACT_WLT_AGENT.WLT_LHV_PO_EEIND +
           FACT_WLT_AGENT.WLT_LHV_PO_PAQ) > 0;


问:
The binary operator Add is not defined for the types 'System.Byte' and 'System.Byte'
I am working on a project that constructs lambda expressions dynamically.
In s specific scenario I've constructed dynamically an expression which equals to this one:

byte i = 1;

   byte j = 1;

  var firstConstant = Expression.Constant(i);

  var secondConstant = Expression.Constant(j);

  var lambda = Expression.Lambda(Expression.Add(firstConstant, secondConstant));

  lambda.Compile().DynamicInvoke();

I Know that primitive types don't have operators overloading and the compiler actually cast the variables/constants to int before the addition and the result back to byte which i don't therefore the exception is being raised.
My question is what is the logic to perform add operations without knowing the types and without loosing some data in case I need to handle float point types?

答:
That might not be possible. The Expression.Add does not perform overflow checking and it looks for the implementation of the Binary + operator. The other overload allows to specify the MethodInfo to select the method to perform the Add.

If you can ensure that all your types going in, support this method you can use the above logic. It does work for short because the binary + operator is defined. The same is not present for the System.Byte class and hence you have the problem. Even with the Compiler implementation, you cannot do:

```<code>byte i = 1;
byte j = 2;
byte sum = i+j; // Cannot implicitly convert type 'int' to 'byte'. An explicit conversion exists (are you missing a cast?)
</code>```

Body:
That might not be possible. The Expression.Add does not perform overflow checking and it looks for the implementation of the Binary + operator. The other overload allows to specify the MethodInfo to select the method to perform the Add.

If you can ensure that all your types going in, support this method you can use the above logic. It does work for short because the binary + operator is defined. The same is not present for the System.Byte class and hence you have the problem. Even with the Compiler implementation, you cannot do:

byte i = 1;
byte j = 2;
byte sum = i+j; // Cannot implicitly convert type 'int' to 'byte'. An explicit conversion exists (are you missing a cast?)


问:
Facing problem while converting string DateTime to Date only in Ms Access
Question:
I have two datetime fields which I have imported as string using CSV import in ms-access.
However now in access these string datetime, I want only date and that is in short date format.

Following are the two fields in string format in ms-access table imported using CSV

Start Date: 1/12/2022 8:36
End Date: 1/13/2022 3:25

However, when I use DateValue() function to get the date part from each of the above two fields the "Start Date" format automatically set to mm/dd/yyyy, while the "End Date" field format sets to dd/mm/yyyy.

Now, when I calculate the difference in the two dates one is appearing as (1/12/2022 = 01-Dec-2022) and other is appearing as (1/13/2022 = 13-Jan-2022), which is resulting in wrong calculation of the difference of dates.

I have used formatdate(), CDate(), DateValue() and other function as well. However, no gain achieved. The surprise is that the datetime as string in ms-access is showing same in both the fields, but when I convert them to DateValue() the format get changed automatically.

Seeking a prompt reply.

Regards,
Faisal

答:
Difference in two dates can be calculated using the expression below

=CDate([enddatestring])-CDate([startdatestring])
// the above expression will convert the date value from string to date

The format of the calculated control field should be general number

i have attached two images that demos it.


问:
String Compare [('3:1',....]
```<code>w=['3:1', '2:1', '1:1', '1:3']
</code>```

how i can compare 3 with 1 and 2 with 1 the thing is first number is for team second for  opponent so i want to collect the point for matches

thanks

答: You can use list comprehension, to iterate through each element and then check for the first element and the second element.</p>

Title: String Compare [('3:1',....]

Body:
w=['3:1', '2:1', '1:1', '1:3']

how i can compare 3 with 1 and 2 with 1 the thing is first number is for team second for  opponent so i want to collect the point for matches

thanks


问:
css grid-column span doesn't work well with auto-fit or auto-fill
I achieve grid wrapping by using auto-fit. Now I have a special div where it takes two column. Now when ever the grid is suppose to wrap to one column, the even div's disappears

Now you can see it here when viewport is below 670px the pink box disappears.

How can I solve this problem?

.grid {
  gap: 20px;
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
}

.box,
.special-box {
  height: 200px;
}

.box:nth-child(even) {
  background-color: pink;

}

.box:nth-child(odd) {
  background-color: orange;

}

.special-box {
  background-color: purple;
  grid-column: span 2;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="grid">
  <div class="box"></div>
  <div class="box"></div>
  <div class="box"></div>
  <div class="box"></div>
  <div class="box"></div>
 <div class="special-box"></div>
</div></code>```

答:
The problem you're having is due to Grid Blowout.

The code snippet tool on SO has a viewport size that is too small for the boxes, the pink grid elements are pushed to the right side outside of the viewable area since they are on the odd indexes. If you run the code snippet tool in full screen and then zoom in and out with CNTRL + mousewheel you can see this in action.

Here is an article that explains the topic quite well.

The fr field in repeat(auto-fill, minmax(300px, 1fr)) determines if an element will fill the rest of the row when this happens, you can avoid this problem by changing 1fr to 0fr like so:

.grid {
  gap: 20px;
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 0fr));
}

.box,
.special-box {
  height: 200px;
}

.box:nth-child(even) {
  background-color: pink;

}

.box:nth-child(odd) {
  background-color: orange;
}

.special-box {
  background-color: purple;
  grid-column: span 2;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="grid">
  <div class="box"></div>
  <div class="box"></div>
  <div class="box"></div>
  <div class="box"></div>
  <div class="box"></div>
 <div class="special-box"></div>
</div></code>```

Body:
The problem you're having is due to Grid Blowout.

The code snippet tool on SO has a viewport size that is too small for the boxes, the pink grid elements are pushed to the right side outside of the viewable area since they are on the odd indexes. If you run the code snippet tool in full screen and then zoom in and out with CNTRL + mousewheel you can see this in action.

Here is an article that explains the topic quite well.

The fr field in repeat(auto-fill, minmax(300px, 1fr)) determines if an element will fill the rest of the row when this happens, you can avoid this problem by changing 1fr to 0fr like so:

.grid {
  gap: 20px;
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 0fr));
}

.box,
.special-box {
  height: 200px;
}

.box:nth-child(even) {
  background-color: pink;

}

.box:nth-child(odd) {
  background-color: orange;
}

.special-box {
  background-color: purple;
  grid-column: span 2;
}

<div class="grid">
  <div class="box"></div>
  <div class="box"></div>
  <div class="box"></div>
  <div class="box"></div>
  <div class="box"></div>
 <div class="special-box"></div>
</div>