问:
maven "churchofjesuschrist.org" issue

I have created a dummy java project with IntelliJ using the maven template

Edited my pom.xml and added the following:

```<code><dependency>
  <groupId>com.oracle</groupId>
  <artifactId>ojdbc6</artifactId>
  <version>12.2.0.1</version>
</dependency>
</code>```

The library comes with errors, if I cat the downloaded file at my local repo, this is what I see:

```<code>$ cat .m2/repository/com/oracle/ojdbc6/12.2.0.1/ojdbc6-12.2.0.1.jar

<!DOCTYPE html>
<html xml:lang="en" lang="en">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<title>Out of Service</title>
<style>
... some style ...
</style>
</head>
<body id="error-page">

<div class="supercenter">
        <h1>This website is down for maintenance.</h1>
        <p>We apologize for the inconvenience. Please come back later.</p>
        <p><a href="javascript:history.back()">Go Back</a>.</p>

        <p>Please check the URL for proper spelling and capitalization.
        If you're having trouble locating a page on churchofjesuschrist.org, try visiting
        <a href="https://www.churchofjesuschrist.org/">churchofjesuschrist.org</a>
        or enter a search term in the field below.</p>
        <div id="search">
                <form accept-charset="utf-8" method="get" action="https://www.churchofjesuschrist.org/search">
                        <input type="hidden" name="lang" value="eng">
                        <span class="search-field"><input type="text" name="query" maxlength="150" class="ac_input"></span>
                        <input type="submit" value="⌕" class="search-button">
                </form>
        </div>

        <br>
        <p><a href="https://www.churchofjesuschrist.org/tools/feedback?lang=eng&body=Error%3ahttps%3a//www.churchofjesuschrist.org/lb">Leave Feedback</a></p>
        <div class="pf-logo">
                <a href="https://www.churchofjesuschrist.org/" class="ldschurch-logotype">
                        <span class="ldschurch-logotype__text">The Church of Jesus Christ of Latter-day Saints</span>
                </a>
        </div>
</div>
</body>
</html>
</code>```

Is there some kind of issue/outage with maven central repository ? any ideas?
It is happening with other libs too, I just show one to keep it simple, but this is an old project with many other dependencies, the previous example just show the issue in a simple way so everyone can replicate it

When I run mvn I see this:

```<code>Downloading from codelds: https://code.lds.org/nexus/content/groups/main-repo/com/oracle/ojdbc6/12.2.0.1/ojdbc6-12.2.0.1.pom
</code>```

That URL is the one beign downloaded on all dependency files

答:
So, first of all, mvnrepository.com is not MavenCentral and has nothing to do with it.

MavenCentral does not contain ojdbc6.jar and I don't know whether other sources for it are legal.

That strange repository that is now "down for maintenance" must be somewhere in your settings.xml, your POM or one of your parent POMs or maybe even dependencies.

Title: maven "churchofjesuschrist.org" issue

Body:
I have created a dummy java project with IntelliJ using the maven template

Edited my pom.xml and added the following:

<dependency>
  <groupId>com.oracle</groupId>
  <artifactId>ojdbc6</artifactId>
  <version>12.2.0.1</version>
</dependency>

The library comes with errors, if I cat the downloaded file at my local repo, this is what I see:

$ cat .m2/repository/com/oracle/ojdbc6/12.2.0.1/ojdbc6-12.2.0.1.jar

<!DOCTYPE html>

<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<title>Out of Service</title>

This website is down for maintenance.

We apologize for the inconvenience. Please come back later.

Go Back.

Please check the URL for proper spelling and capitalization.
        If you're having trouble locating a page on churchofjesuschrist.org, try visiting
        churchofjesuschrist.org
        or enter a search term in the field below.

                <form accept-charset="utf-8" method="get" action="https://www.churchofjesuschrist.org/search">
                        <input type="hidden" name="lang" value="eng">
                        <input type="text" name="query" maxlength="150" class="ac_input">
                        <input type="submit" value="⌕" class="search-button">
                </form>

Leave Feedback

                        The Church of Jesus Christ of Latter-day Saints

Is there some kind of issue/outage with maven central repository ? any ideas?
It is happening with other libs too, I just show one to keep it simple, but this is an old project with many other dependencies, the previous example just show the issue in a simple way so everyone can replicate it

When I run mvn I see this:

Downloading from codelds: https://code.lds.org/nexus/content/groups/main-repo/com/oracle/ojdbc6/12.2.0.1/ojdbc6-12.2.0.1.pom

That URL is the one beign downloaded on all dependency files


来源: stackexchange

问:
Angular CLI: Change REST API URL on build
I want to remove my local server prefix from my REST API URLs (example, http://localhost:8080) when building for production (ng build --prod).

I get that it's something to do with the environment file environment.prod.ts, but can't find any examples of making use of them to achieve the aforementioned.

Would be great if someone helps me get started!

答:
You don't need to hard code the API_URL as mentioned above just use your environment.prod.ts file.
Set-:

production = true.

Change the API_URL to your desired url.

Now run the command ng build --prod=true

It worked for me I guess, will work for you too.

ContentLicense: CC BY-SA 3.0

ContentLicense: CC BY-SA 4.0


问:
Ordering a table that was created from a factor variable in r
Okay, so I have a data frame, df,  with one column: artist name.

```<code>        artist_name
1       Linkin Park
2         Lady Gaga
3        Pink Floyd
4       Linkin Park
5         Lady Gaga
6         Lady Gaga
</code>```

Artist name is a factor variable, and to see how many times each artist appears in this data frame, I would say:

table (df$artist_name)

The only problem is that in my project, I have 17,000s rows (and thousands of artists), and I only want to see the artists with the most appearances in the table. Because there are so many different artists, I am unable to find the most frequent artist names. I know that if I have a data frame, I can use the order () function, but is there any way to sort a table? Thanks so much

答:
We can use count in dplyr

```<code>library(dplyr)
df %>% count(artist_name, sort = TRUE) %>% slice(1:10)
</code>```

Or using top_n :

```<code>df %>% count(artist_name) %>% top_n(10, n)
</code>```

This will return top 10 artists, replace 10 with whatever number you want.

Body:
Okay, so I have a data frame, df,  with one column: artist name.

        artist_name
1       Linkin Park
2         Lady Gaga
3        Pink Floyd
4       Linkin Park
5         Lady Gaga
6         Lady Gaga

Artist name is a factor variable, and to see how many times each artist appears in this data frame, I would say:

table (df$artist_name)

The only problem is that in my project, I have 17,000s rows (and thousands of artists), and I only want to see the artists with the most appearances in the table. Because there are so many different artists, I am unable to find the most frequent artist names. I know that if I have a data frame, I can use the order () function, but is there any way to sort a table? Thanks so much

Body:
We can use count in dplyr

library(dplyr)
df %>% count(artist_name, sort = TRUE) %>% slice(1:10)

Or using top_n :

df %>% count(artist_name) %>% top_n(10, n)

This will return top 10 artists, replace 10 with whatever number you want.


问:
${} is not working on my JSP page. How can i get my ${} html tag to work again?
So ${} did work. But the JSTL jar files that I'm using made to where the ${} doesn't work anymore. These are my JSTL jar files. jstl-1.2 (1).jar, jstl-impl-1.2.jar, jstl-standard.jar. I am following Navin tutorial on Servlet & JSP Tutorial | Full Course on youtube. He skipped JSTL jar files. I'm a junior developer trying to understand why my ${} isn't working anymore.

Question: Why did my ${} tag not work anymore?

Please be gentle. :D

```<code><%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>

    <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!DOCTYPE html >
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>

    <c:forEach items="${students}" var="s" >
         ${s} <br>

    </c:forEach>

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

```<code>package com.Demo;

public class Student {
    int rollno;
    String name;

    @Override
    public String toString() {
        return "Student [rollno=" + rollno + ", name=" + name + "]";
    }

    public int getRollno() {
        return rollno;
    }

    public void setRollno(int rollno) {
        this.rollno = rollno;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Student(int rollno, String name) {
        super();
        this.rollno = rollno;
        this.name = name;
    }

}
</code>```

```<code><?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd" version="4.0">
  <display-name>JSTLexample</display-name>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>
</web-app>
</code>```

```<code>package com.Demo;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet("/DemoServlet")
public class DemoServlet extends HttpServlet{

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

        //String name = "Navin";

        List <Student> studs = Arrays.asList(new Student(1, "brandon"), new Student(2, "Micheal"), new Student (3, "Charles"));

        request.setAttribute("students", studs);

        RequestDispatcher rd = request.getRequestDispatcher("display.jsp");
        rd.forward(request, response);

    }
}
</code>```

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

答:
That "${}" is EL expression language syntax. You require to configure your "web application" web.xml or variant to use the JSTL (Java Standard Tag Library) .jar file in either the servers /commons/lib folder with server.xml (obviously not) or /WEB-INF/lib of your application.
Then call in the names of each tag prefix you wish to use declared at the top of your JSP page.
Tomcat has a few ways of achieving it.

Also your doctype should be

```<code><!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
</code>```

Yout .tld tag library descriptor should be in the WEB-INF folder.

define the taglib location in your web.xml file

```<code>    <jsp-config>
<taglib>
    <taglib-uri>http://java.sun.com/jstl/core</taglib-uri>
        <taglib-location>/WEB-INF/c.tld</taglib-location>
        </taglib>
    </jsp-config>
</code>```

Also, your bean class should be declared in the web.xml and the page declarations to call it in the page at the top too.

Not a bad point to recheck the above if things go wrong.

The servlet you have made is a GET request servlet , they pass parameters on the URL by

?name=**valuOFthisPart&anid=**somethinHere&terminus=

if you use ${Param.student} added as student past the "?" on the url that may be usable to the EL something like this

**?students=name=**valuOFthisPart&next1=somethinHere&next2=somethinHere&terminus=

A POST servlet cannot carry parameters on the URL and is what you are trying to do by the code so is what the request.setAttribute is setting doing is for a POST request (POST requests do carry tokens).

Too, the setAttribute on request object is available by the interface of its class  of which it can be done at class level by a wrapper sub class too as next

```<code>javax.servlet.ServletRequestWrapper requestWrpp = new javax.servlet.ServletRequestWrapper(request);
requestWrpp.setAttribute("students", studs);
</code>```

HOWEVER, while more modern versions of web container recognise complex types such as List and Map (but probably not Student class) you may be able to use the code there by what i vaguely think i remember the clause of use of complex objects in JSP processing is and that being it is understood to be convertible to string.
Student is unrecognizable to the web app parser rules, however if  you wrote Student to extend ( Map int,String ) then the runtime and compiler may be able to use that set up inside as a ( Map K,V )
Actually, this cannot work because you try to do this in the servlet before JSP processing by the response [ ! unless the Student class is only a servlet support class in the classes folder. (not bean syntax class)
see next paragraph ].

You are trying to use a class the way a bean operates , and a bean must be declared both in the web.xml and the page and the servlet notified too with a Student object reference from either classes or /classes/beans folder  !!!
If it is a bean it should be in a bean folder (if it is not a bean and only a support processing class should be in classes with the servlet packaged or not) and called by the response in the JSP parser , but properly loaded, correctly updated current instance of it in the web app user session should be used (something JSF does more easily).
You can obtain current session and beans for servlet instance use by acquiring the web app context and initial instance thread to find the bean you want, its current instance and current state (requires to be a session bean unless the values are constant or it only outputs by set get processing instantly) to get its' current values. Bean classes must be declared throughout the app configuration not dissimilar to servlets but are different with rigid rules of declaration for runtime and syntax.

Final note

```<code>// the first argument should be a string NOT an int
req.setAttribute("String Object",(java.lang.Object)anObject);
</code>```

//NOTE: That object must be convertible to a String from a recognizable java language core class !!!

Just a quick note about post requests, actually it can carry a query string but is considered a bizzarre action inside a Java framework.

Body:
So ${} did work. But the JSTL jar files that I'm using made to where the ${} doesn't work anymore. These are my JSTL jar files. jstl-1.2 (1).jar, jstl-impl-1.2.jar, jstl-standard.jar. I am following Navin tutorial on Servlet & JSP Tutorial | Full Course on youtube. He skipped JSTL jar files. I'm a junior developer trying to understand why my ${} isn't working anymore.

Question: Why did my ${} tag not work anymore?

Please be gentle. :D

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>

    <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!DOCTYPE html >

<meta charset="ISO-8859-1">
<title>Insert title here</title>

    <c:forEach items="${students}" var="s" >
         ${s}

    </c:forEach>

package com.Demo;

public class Student {
    int rollno;
    String name;

    @Override
    public String toString() {
        return "Student [rollno=" + rollno + ", name=" + name + "]";
    }

    public int getRollno() {
        return rollno;
    }

    public void setRollno(int rollno) {
        this.rollno = rollno;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Student(int rollno, String name) {
        super();
        this.rollno = rollno;
        this.name = name;
    }

}

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd" version="4.0">
  <display-name>JSTLexample</display-name>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>
</web-app>

package com.Demo;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet("/DemoServlet")
public class DemoServlet extends HttpServlet{

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

        //String name = "Navin";

        List <Student> studs = Arrays.asList(new Student(1, "brandon"), new Student(2, "Micheal"), new Student (3, "Charles"));

        request.setAttribute("students", studs);

        RequestDispatcher rd = request.getRequestDispatcher("display.jsp");
        rd.forward(request, response);

    }
}

Body:
That "${}" is EL expression language syntax. You require to configure your "web application" web.xml or variant to use the JSTL (Java Standard Tag Library) .jar file in either the servers /commons/lib folder with server.xml (obviously not) or /WEB-INF/lib of your application.
Then call in the names of each tag prefix you wish to use declared at the top of your JSP page.
Tomcat has a few ways of achieving it.

Also your doctype should be

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

Yout .tld tag library descriptor should be in the WEB-INF folder.

define the taglib location in your web.xml file

    <jsp-config>
<taglib>
    <taglib-uri>http://java.sun.com/jstl/core</taglib-uri>
        <taglib-location>/WEB-INF/c.tld</taglib-location>
        </taglib>
    </jsp-config>

Also, your bean class should be declared in the web.xml and the page declarations to call it in the page at the top too.

Not a bad point to recheck the above if things go wrong.

The servlet you have made is a GET request servlet , they pass parameters on the URL by

?name=**valuOFthisPart&anid=**somethinHere&terminus=

if you use ${Param.student} added as student past the "?" on the url that may be usable to the EL something like this

**?students=name=**valuOFthisPart&next1=somethinHere&next2=somethinHere&terminus=

A POST servlet cannot carry parameters on the URL and is what you are trying to do by the code so is what the request.setAttribute is setting doing is for a POST request (POST requests do carry tokens).

Too, the setAttribute on request object is available by the interface of its class  of which it can be done at class level by a wrapper sub class too as next

javax.servlet.ServletRequestWrapper requestWrpp = new javax.servlet.ServletRequestWrapper(request);
requestWrpp.setAttribute("students", studs);

HOWEVER, while more modern versions of web container recognise complex types such as List and Map (but probably not Student class) you may be able to use the code there by what i vaguely think i remember the clause of use of complex objects in JSP processing is and that being it is understood to be convertible to string.
Student is unrecognizable to the web app parser rules, however if  you wrote Student to extend ( Map int,String ) then the runtime and compiler may be able to use that set up inside as a ( Map K,V )
Actually, this cannot work because you try to do this in the servlet before JSP processing by the response [ ! unless the Student class is only a servlet support class in the classes folder. (not bean syntax class)
see next paragraph ].

You are trying to use a class the way a bean operates , and a bean must be declared both in the web.xml and the page and the servlet notified too with a Student object reference from either classes or /classes/beans folder  !!!
If it is a bean it should be in a bean folder (if it is not a bean and only a support processing class should be in classes with the servlet packaged or not) and called by the response in the JSP parser , but properly loaded, correctly updated current instance of it in the web app user session should be used (something JSF does more easily).
You can obtain current session and beans for servlet instance use by acquiring the web app context and initial instance thread to find the bean you want, its current instance and current state (requires to be a session bean unless the values are constant or it only outputs by set get processing instantly) to get its' current values. Bean classes must be declared throughout the app configuration not dissimilar to servlets but are different with rigid rules of declaration for runtime and syntax.

Final note

// the first argument should be a string NOT an int
req.setAttribute("String Object",(java.lang.Object)anObject);

//NOTE: That object must be convertible to a String from a recognizable java language core class !!!

Just a quick note about post requests, actually it can carry a query string but is considered a bizzarre action inside a Java framework.


问:
Can't display elements of array React
I can see my array in state, but I don't know why elements of array doesn't display on the app interface.

```<code>const [members, setMembers] = useState([])

useEffect( () => {
    getMembers();
}, [props.event])

const getMembers = () => {
    let new_members = [];
    console.log(props.event)
    props.event &&  props.event.uczestnicy.map(member => {
        member.get().then(doc => {
            let new_member;
            new_member = {
                ...doc.data(),
                id: doc.id
            }
            new_members.push(new_member)
        })
        setMembers(new_members)
    })
    console.log(new_members)
    console.log(members)
}
</code>```

[...]

```<code>{members && members.map(member => {
    console.log('mem',member)
    return(
        <div key={member.id}>
            {member.nick}
        </div>
    )
})}
</code>```

So I can see this array in Components using React Developer Tools, but even console.log doesn't see it in the moment of performing.

And console.log(new_members) and console.log(members) result :

答:
Your member values are fetch asynchronously, so its ideal if you set state only after all the values are resolved. For this you can use a Promise.all

```<code>const getMembers = async () => {
    let new_members = [];
    console.log(props.event)
    if(props.event) {
      const val  = await Promise.all(props.event.uczestnicy.map(member => {
        return member.get().then(doc => {
            let new_member;
            new_member = {
                ...doc.data(),
                id: doc.id
            }
            return new_member
        })
     });
     setMembers(values);
     console.log(values);
   }
}
</code>```

Title: Can't display elements of array React

Body:
I can see my array in state, but I don't know why elements of array doesn't display on the app interface.

const [members, setMembers] = useState([])

useEffect( () => {
    getMembers();
}, [props.event])

const getMembers = () => {
    let new_members = [];
    console.log(props.event)
    props.event &&  props.event.uczestnicy.map(member => {
        member.get().then(doc => {
            let new_member;
            new_member = {
                ...doc.data(),
                id: doc.id
            }
            new_members.push(new_member)
        })
        setMembers(new_members)
    })
    console.log(new_members)
    console.log(members)
}

[...]

{members && members.map(member => {
    console.log('mem',member)
    return(

            {member.nick}

    )
})}

So I can see this array in Components using React Developer Tools, but even console.log doesn't see it in the moment of performing.

And console.log(new_members) and console.log(members) result :

Body:
Your member values are fetch asynchronously, so its ideal if you set state only after all the values are resolved. For this you can use a Promise.all

const getMembers = async () => {
    let new_members = [];
    console.log(props.event)
    if(props.event) {
      const val  = await Promise.all(props.event.uczestnicy.map(member => {
        return member.get().then(doc => {
            let new_member;
            new_member = {
                ...doc.data(),
                id: doc.id
            }
            return new_member
        })
     });
     setMembers(values);
     console.log(values);
   }
}


问:
Hibernate removes child objects after session.update(parent)
I have a very simple parent-/child relationship between objects of type "Folder", which looks like this:

A folder can have 0-1 parent folders.

A folder can have 0-n child folders
(subfolders).

So, basically, a simplified version of the Java class Folder looks like this:

```<code>public class Folder{
    long id;
    Set<Folder> childFolders;
    Folder parentFolder;
    String path;

    // Getter, setter and other (for this question)
    // not relevant properties omitted

    public boolean equals(Object obj){
            if (obj == null) return false;
            if (obj == this) return true;
            if (obj instanceof Folder){
                    Folder folder = (Folder)obj;
                    return folder.getPath().equals(getPath());
            }
            return false;
    }

    public int hashCode(){
            return getPath().hashCode();
    }

}
</code>```

My simple test hierarchy looks like this:

```<code>  folder1
  folder2
- folder3
   subfolder3-1
</code>```

Using Hibernate, I call:

```<code>session.update(folder1);
session.update(folder2);
session.update(folder3);
</code>```

The first two calls succeed.

The last call for folder3 throws no exception BUT it removes subfolder3-1 from the internal set "childFolders" of folder3.
That means, folder3.childFolders.size() = 0 although it was 1 before the last update call.
Important: In the database, folder "subfolder3-1" still exists!

How can that be?

Here is my mapping file:

```<code><?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
    <class name="test.Folder" table="FOLDERS">

        <id name="id" type="long" access="field">
            <column name="FOLDER_ID" />
            <generator class="native" />
        </id>

        <set name="childFolders" table="FOLDERS" inverse="true" cascade="save-update">
            <key column="PARENT_FOLDER_ID"></key>
            <one-to-many class="test.Folder" />
        </set>

        <many-to-one name="parentFolder" column="PARENT_FOLDER_ID" />

        <property name="path" column="FOLDER_PATH" />
    </class>
</hibernate-mapping>
</code>```

答:
Make sure you're establishing the link properly in the java world.

```<code>  folder3.getChildFolders().add(subfolder3);
  subfolder3.setParent(folder3);
  session.persist(folder3); //cascade here will save subfolder3
</code>```

Here is the hibernate documentation.

Body:
I have a very simple parent-/child relationship between objects of type "Folder", which looks like this:

A folder can have 0-1 parent folders.

A folder can have 0-n child folders
(subfolders).

So, basically, a simplified version of the Java class Folder looks like this:

public class Folder{
    long id;
    Set<Folder> childFolders;
    Folder parentFolder;
    String path;

    // Getter, setter and other (for this question)
    // not relevant properties omitted

    public boolean equals(Object obj){
            if (obj == null) return false;
            if (obj == this) return true;
            if (obj instanceof Folder){
                    Folder folder = (Folder)obj;
                    return folder.getPath().equals(getPath());
            }
            return false;
    }

    public int hashCode(){
            return getPath().hashCode();
    }

}

My simple test hierarchy looks like this:

  folder1
  folder2
- folder3
   subfolder3-1

Using Hibernate, I call:

session.update(folder1);
session.update(folder2);
session.update(folder3);

The first two calls succeed.

The last call for folder3 throws no exception BUT it removes subfolder3-1 from the internal set "childFolders" of folder3.
That means, folder3.childFolders.size() = 0 although it was 1 before the last update call.
Important: In the database, folder "subfolder3-1" still exists!

How can that be?

Here is my mapping file:

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
    <class name="test.Folder" table="FOLDERS">

        <id name="id" type="long" access="field">
            <column name="FOLDER_ID" />
            <generator class="native" />
        </id>

        <set name="childFolders" table="FOLDERS" inverse="true" cascade="save-update">
            <key column="PARENT_FOLDER_ID"></key>
            <one-to-many class="test.Folder" />
        </set>

        <many-to-one name="parentFolder" column="PARENT_FOLDER_ID" />

        <property name="path" column="FOLDER_PATH" />
    </class>
</hibernate-mapping>

Body:
Make sure you're establishing the link properly in the java world.

  folder3.getChildFolders().add(subfolder3);
  subfolder3.setParent(folder3);
  session.persist(folder3); //cascade here will save subfolder3

Here is the hibernate documentation.


问:
How do I get an element with a specific ID from getElementsByClassName?
EDIT: SOLVED. Thanks everyone!

I'm new to programming :D My code is below. Here is the deal: I have multiple buttons, but I want to make it so that the same thing would happen anytime any one of these buttons is clicked, but each button also has a specific value, and I also want that specific value to be printed out. My code goes through the document and looks at all the elements with "editButton" class, and correctly identifies all the buttons, but the problem is that no matter which button I press, I always get the value of the last button, because var id only gets assigned after the for loop finishes and is on the last element. I tried creating a global variable and assigning the value to it, but the result is the same. I tried ending the for loop before moving on to .done (function (data), but I got an error. Can someone help me out? Thanks!

$(document).ready(function() {
  var anchors = document.getElementsByClassName('editButton');
  for (var i = 0; i < anchors.length; i++) {
    var anchor = anchors[i];
    anchor.onclick = function() {
      $.ajax({
        method: "GET",
        url: "/testedit.php",
      }).done(function(data) {
        var id = anchor.value;

        /* from result create a string of data and append to the div */

        var result = data;
        var string = '
ID is ' + id + '

';

        $("#records").html(string);
      });
    }
  }
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="records"></div></code>```

答:
You can use getAttribute. Like:

```<code>var anchors = document.getElementsByClassName('editButton');

// Id of anchors
id_of_anchor = anchors.getAttribute("id");
</code>```

Refs

EDIT

```<code>anchor.onclick = function() {
    id_of_anchor = $(this).attr("id");
});
</code>```

Body:
You can use getAttribute. Like:

var anchors = document.getElementsByClassName('editButton');

// Id of anchors
id_of_anchor = anchors.getAttribute("id");

Refs

EDIT

anchor.onclick = function() {
    id_of_anchor = $(this).attr("id");
});


问:
Is C# a high level language?
Is C# a high level language? I see it as more like medium level, but I am still unsure about this. Would you consider it as high level as some of the popular scripting languages?

Or does it accommodate more than one level?

答: I would personally say that it has a high level of abstraction. A lot of complicated matters are handled by the .NET framework unlike C or C++ where you are responsible for almost everything that happens.</p>

OwnerDisplayName: Joan Venge

ContentLicense: CC BY-SA 2.5

Title: Is C# a high level language?

OwnerDisplayName: Hi my name is GateKiller

LastEditorDisplayName: Rich B


问:
Implementing my own low-pass filter in Java using fft
I'm using: http://introcs.cs.princeton.edu/java/97data/FFT.java.html to implement my own low-pass filter.

How do I rearrange the output from FFT.fft() to zero out the correct values for a correct low-pass filter?

答: I imagine that you would zero out all the values in the y array returned from the fft method that have a frequency (determined by the the array index) above your cut-off.</p>


问:
Unable to find HTML table with Python using BeautifulSoup
I am unable to locate the HTML table with class table-light border rounded. Do you all know why this may be?

Here is my attempt:

```<code>import requests
from bs4 import BeautifulSoup

url = "https://iextrading.com/trading/eligible-symbols/"
r = requests.get(url)
soup = BeautifulSoup(r.text, 'html.parser')
table = soup.find('table', class_ = 'table-light border rounded')
print(table) # returns "None"
</code>```

Note, there is no table tag in the soup object / variable. However, when inspecting the webpage, there is indeed a table tag. I can't seem to locate it.

Any help or guidance is much appreciated. I am trying to create a list of Symbols.

Please see the following screenshots for additional information:

答:
It might be the case that the elements are rendered using js AFTER the page has loaded. So, you only get the page and not the javascript rendered parts.

I personally refer selenium.

You might want to look into https://medium.com/@hoppy/how-to-test-or-scrape-javascript-rendered-websites-with-python-selenium-a-beginner-step-by-c137892216aa

Body:
I am unable to locate the HTML table with class table-light border rounded. Do you all know why this may be?

Here is my attempt:

import requests
from bs4 import BeautifulSoup

url = "https://iextrading.com/trading/eligible-symbols/"
r = requests.get(url)
soup = BeautifulSoup(r.text, 'html.parser')
table = soup.find('table', class_ = 'table-light border rounded')
print(table) # returns "None"

Note, there is no table tag in the soup object / variable. However, when inspecting the webpage, there is indeed a table tag. I can't seem to locate it.

Any help or guidance is much appreciated. I am trying to create a list of Symbols.

Please see the following screenshots for additional information:


问:
Declare a const array
Is it possible to write something similar to the following?</p>

```<code>public const string[] Titles = { "German", "Spanish", "Corrects", "Wrongs" };
</code>```

Title: Declare a const array

Body:
Is it possible to write something similar to the following?

public const string[] Titles = { "German", "Spanish", "Corrects", "Wrongs" };

Body:
Best alternative:

public static readonly byte[] ZeroHash = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };


问:
How can I search ~/Library with the command find on my mac?
I want to find all the files a piece of software has left in my system.
In the terminal I type:

$ find /Users -name software -print

And every time find tries to look into a folder within the Library directory, Terminal returns "operation not permitted".
So I tried:

$ sudo find /Users -name software -print

Same result

So I finally enabled super user, logged in with command su, entered my command: same result.

1 - I do not understand why even the super user is not allowed to search the library.
2 - what is the work around?

Thanks for your help

答:
I have found the answer.

Terminal needs to be added in the System Preferences/Security and Privacy/ full disk access!


问:
Sklearn Voting ensemble with models using different features and testing with k-fold cross validation
I have a data frame with 4 different groups of features.

I need to create 4 different models with these four different feature groups and combine them with the ensemble voting classifier.
Furthermore, I need to test the classifier using k-fold cross validation.

However, I am finding it difficult to combine different feature sets, voting classifier and k-fold cross validation with functionality available in sklearn. Following is the code that I have so far.

```<code>y = df1.index
x = preprocessing.scale(df1)

SVM = svm.SVC(kernel='rbf', C=1)
rf=RandomForestClassifier(n_estimators=200)
ann = MLPClassifier(solver='lbfgs', alpha=1e-5, hidden_layer_sizes=(25, 2), random_state=1)
neigh = KNeighborsClassifier(n_neighbors=10)

models = list()
models.append(('facial', SVM))
models.append(('posture', rf))
models.append(('computer', ann))
models.append(('physio', neigh))

ens = VotingClassifier(estimators=models)

cv = KFold(n_splits=10, random_state=None, shuffle=True)
scores = cross_val_score(ens, x, y, cv=cv, scoring='accuracy')
</code>```

As you can see, this program uses same features for all 4 models. How can I improve this program to achieve my objective?

答:
I did manage to achieve this using Pipelines,

```<code>y = df1.index
x = preprocessing.scale(df1)

phy_features = ['A', 'B', 'C']
phy_transformer = Pipeline(steps=[('imputer', SimpleImputer(strategy='median')), ('scaler', StandardScaler())])
phy_processer = ColumnTransformer(transformers=[('phy', phy_transformer, phy_features)])

fa_features = ['D', 'E', 'F']
fa_transformer = Pipeline(steps=[('imputer', SimpleImputer(strategy='median')), ('scaler', StandardScaler())])
fa_processer = ColumnTransformer(transformers=[('fa', fa_transformer, fa_features)])

pipe_phy = Pipeline(steps=[('preprocessor', phy_processer ),('classifier', SVM)])
pipe_fa = Pipeline(steps=[('preprocessor', fa_processer ),('classifier', SVM)])

ens = VotingClassifier(estimators=[pipe_phy, pipe_fa])

cv = KFold(n_splits=10, random_state=None, shuffle=True)
for train_index, test_index in cv.split(x):
    x_train, x_test = x[train_index], x[test_index]
    y_train, y_test = y[train_index], y[test_index]
    ens.fit(x_train,y_train)
    print(ens.score(x_test, y_test))
</code>```

Please refer sklearn Pipeline: argument of type 'ColumnTransformer' is not iterable for if you are receiving an TypeError when using ColumnTransforms.

Body:
I have a data frame with 4 different groups of features.

I need to create 4 different models with these four different feature groups and combine them with the ensemble voting classifier.
Furthermore, I need to test the classifier using k-fold cross validation.

However, I am finding it difficult to combine different feature sets, voting classifier and k-fold cross validation with functionality available in sklearn. Following is the code that I have so far.

y = df1.index
x = preprocessing.scale(df1)

SVM = svm.SVC(kernel='rbf', C=1)
rf=RandomForestClassifier(n_estimators=200)
ann = MLPClassifier(solver='lbfgs', alpha=1e-5, hidden_layer_sizes=(25, 2), random_state=1)
neigh = KNeighborsClassifier(n_neighbors=10)

models = list()
models.append(('facial', SVM))
models.append(('posture', rf))
models.append(('computer', ann))
models.append(('physio', neigh))

ens = VotingClassifier(estimators=models)

cv = KFold(n_splits=10, random_state=None, shuffle=True)
scores = cross_val_score(ens, x, y, cv=cv, scoring='accuracy')

As you can see, this program uses same features for all 4 models. How can I improve this program to achieve my objective?

Body:
I did manage to achieve this using Pipelines,

y = df1.index
x = preprocessing.scale(df1)

phy_features = ['A', 'B', 'C']
phy_transformer = Pipeline(steps=[('imputer', SimpleImputer(strategy='median')), ('scaler', StandardScaler())])
phy_processer = ColumnTransformer(transformers=[('phy', phy_transformer, phy_features)])

fa_features = ['D', 'E', 'F']
fa_transformer = Pipeline(steps=[('imputer', SimpleImputer(strategy='median')), ('scaler', StandardScaler())])
fa_processer = ColumnTransformer(transformers=[('fa', fa_transformer, fa_features)])

pipe_phy = Pipeline(steps=[('preprocessor', phy_processer ),('classifier', SVM)])
pipe_fa = Pipeline(steps=[('preprocessor', fa_processer ),('classifier', SVM)])

ens = VotingClassifier(estimators=[pipe_phy, pipe_fa])

cv = KFold(n_splits=10, random_state=None, shuffle=True)
for train_index, test_index in cv.split(x):
    x_train, x_test = x[train_index], x[test_index]
    y_train, y_test = y[train_index], y[test_index]
    ens.fit(x_train,y_train)
    print(ens.score(x_test, y_test))

Please refer sklearn Pipeline: argument of type 'ColumnTransformer' is not iterable for if you are receiving an TypeError when using ColumnTransforms.


问:
Using python to edit html, but lxml converts nice html entities to strange encoding
I'm trying to use python (with pyquery and lxml) to alter and clean up some html.

```<code>Eg. html = "<div><!-- word style><bleep><omgz 1,000 tags><--><p>It’s a spicy meatball!</div>"
</code>```

The lxml.html.clean function, clean_html(), works well, except that it replaces the nice html entities like

```<code>’
</code>```

with some unicode string

```<code>\xc2\x92
</code>```

The unicode looks strange in different browsers (firefox and opera using auto encoding, utf8, latin-1, etc), like an empty box.  How can I stop lxml converting the entities?  How can I get it all in latin-1 encoding?  Seems strange that a module built specifically for html would do this.

I can't be sure of which characters are there, so I can't just use

```<code>replace("\xc2\x92","’").
</code>```

I've tried using

```<code>clean_html(html).encode('latin-1')
</code>```

but the unicode persists.

And yes, I'd tell people to stop using word to write html, but then I'd hear the whole

"iz th wayz i liks it u cant mak me chang hitlr".

Edit: a beautifulsoup solution:

```<code>from BeautifulSoup import BeautifulSoup, Comment
soup = BeautifulSoup(str(desc[desc_type]))
                    comments = soup.findAll(text=lambda text:isinstance(text, Comment))
                    [comment.extract() for comment in comments]
                    print soup
</code>```

答:
You could also just convert the utf8 string into ascii with xml characters</p>

```<code>result = result.decode('utf-8').encode('ascii', 'xmlcharrefreplace')
</code>```

Body:
I'm trying to use python (with pyquery and lxml) to alter and clean up some html.

Eg. html = "

It’s a spicy meatball!
"

The lxml.html.clean function, clean_html(), works well, except that it replaces the nice html entities like

’

with some unicode string

\xc2\x92

The unicode looks strange in different browsers (firefox and opera using auto encoding, utf8, latin-1, etc), like an empty box.  How can I stop lxml converting the entities?  How can I get it all in latin-1 encoding?  Seems strange that a module built specifically for html would do this.

I can't be sure of which characters are there, so I can't just use

replace("\xc2\x92","’").

I've tried using

clean_html(html).encode('latin-1')

but the unicode persists.

And yes, I'd tell people to stop using word to write html, but then I'd hear the whole

"iz th wayz i liks it u cant mak me chang hitlr".

Edit: a beautifulsoup solution:

from BeautifulSoup import BeautifulSoup, Comment
soup = BeautifulSoup(str(desc[desc_type]))
                    comments = soup.findAll(text=lambda text:isinstance(text, Comment))
                    [comment.extract() for comment in comments]
                    print soup

Body:
You could also just convert the utf8 string into ascii with xml characters

result = result.decode('utf-8').encode('ascii', 'xmlcharrefreplace')


问:
How to compare with optimal effort whether 2 JAVA NESTED COLLECTIONS of this format List<Map<String, Object>> are equal
How to compare with optimal effort whether 2 JAVA NESTED COLLECTIONS of this format List<Map<String, Object>> are equal

In List<Map<String, Object>> the Object can be List or Map

I need to write unit tests to compare the values of nested collection object parsed from a json and the expected value (another collection which I manually create).
I can do this iteratively by going deep to each of the objects and compare them against the values from the other collection.

But this approach seems to be very tedious since I have to iterate each different test cases.

Is there any other efficient approach?

答:
As pointed out by @Holger this is kind of not efficient!

package im.silentsudo.gradletest;

import com.google.gson.Gson;
import lombok.AllArgsConstructor;
import lombok.NoArgsConstructor;
import org.junit.Assert;
import org.junit.Test;

import javax.xml.bind.DatatypeConverter;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class HashComparisionTest {

    @AllArgsConstructor
    @NoArgsConstructor
    static class Post {
        Long id;
        String title;
    }

    static private Map<String, Object> generateUser1PostList() {
        final List<ComparisionMain.Post> posts = new ArrayList<>();
        posts.add(new ComparisionMain.Post(1L, "Post 1"));
        posts.add(new ComparisionMain.Post(2L, "Post 2"));
        final Map<String, Object> userPosts = new HashMap<>();
        userPosts.put("user_a", posts);
        return userPosts;
    }

    static private Map<String, Object> generateUser2PostList() {
        final List<ComparisionMain.Post> posts = new ArrayList<>();
        posts.add(new ComparisionMain.Post(20L, "Post 20"));
        posts.add(new ComparisionMain.Post(21L, "Post 21"));
        final Map<String, Object> userPosts = new HashMap<>();
        userPosts.put("user_b", posts);
        return userPosts;
    }

    static private String getHash(String content) throws NoSuchAlgorithmException {
        MessageDigest messageDigest = MessageDigest.getInstance("MD5");
        messageDigest.update(content.getBytes());
        byte[] digiest = messageDigest.digest();
        return DatatypeConverter.printHexBinary(digiest);
    }

    @Test
    public void testTwoCollectionMeaningfullyEquals() throws NoSuchAlgorithmException {
        System.out.println("------------- testTwoCollectionMeaningfullyEquals --------------");
        final Gson gson = new Gson();
        List<Map<String, Object>> collection1 = new ArrayList<>();
        List<Map<String, Object>> collection2 = new ArrayList<>();

        collection1.add(generateUser1PostList());

        collection2.add(generateUser1PostList());

        final String hash1 = getHash(gson.toJson(collection1));

        System.out.println(hash1);
        final String hash2 = getHash(gson.toJson(collection2));
        System.out.println(hash2);

        Assert.assertEquals(hash1, hash2);

        System.out.println("------------- testTwoCollectionMeaningfullyEquals --------------");
    }

    @Test
    public void testTwoCollectionMeaningfullyNotEquals() throws NoSuchAlgorithmException {
        System.out.println("------------- testTwoCollectionMeaningfullyNotEquals --------------");
        final Gson gson = new Gson();
        List<Map<String, Object>> collection1 = new ArrayList<>();
        List<Map<String, Object>> collection2 = new ArrayList<>();

        collection1.add(generateUser1PostList());

        collection2.add(generateUser2PostList());

        final String hash1 = getHash(gson.toJson(collection1));

        System.out.println(hash1);
        final String hash2 = getHash(gson.toJson(collection2));
        System.out.println(hash2);

        Assert.assertNotEquals(hash1, hash2);

        System.out.println("------------- testTwoCollectionMeaningfullyNotEquals --------------");
    }
}
```

<p>Output of the above program is:</p>

```Testing started at 12:01 PM ...
> Task :cleanTest
> Task :compileJava UP-TO-DATE
> Task :processResources NO-SOURCE
> Task :classes UP-TO-DATE
> Task :compileTestJava
> Task :processTestResources NO-SOURCE
> Task :testClasses
> Task :test
------------- testTwoCollectionMeaningfullyNotEquals --------------
766461F7DB37B8EC031BE0145E6832D3
156636D7A2CF2196783F9D644A994391
------------- testTwoCollectionMeaningfullyNotEquals --------------
------------- testTwoCollectionMeaningfullyEquals --------------
766461F7DB37B8EC031BE0145E6832D3
766461F7DB37B8EC031BE0145E6832D3
------------- testTwoCollectionMeaningfullyEquals --------------
BUILD SUCCESSFUL in 0s
4 actionable tasks: 3 executed, 1 up-to-date
12:01:49 PM: Tasks execution finished ':cleanTest :test --tests "im.silentsudo.gradletest.HashComparisionTest"'.
```

This is very simple implementation, if you need more details on object comparision in java please take a look at https://www.baeldung.com/java-equals-hashcode-contracts

Body:
As pointed out by @Holger this is kind of not efficient!

package im.silentsudo.gradletest;

import com.google.gson.Gson;
import lombok.AllArgsConstructor;
import lombok.NoArgsConstructor;
import org.junit.Assert;
import org.junit.Test;

import javax.xml.bind.DatatypeConverter;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class HashComparisionTest {

    @AllArgsConstructor
    @NoArgsConstructor
    static class Post {
        Long id;
        String title;
    }

    static private Map<String, Object> generateUser1PostList() {
        final List<ComparisionMain.Post> posts = new ArrayList<>();
        posts.add(new ComparisionMain.Post(1L, "Post 1"));
        posts.add(new ComparisionMain.Post(2L, "Post 2"));
        final Map<String, Object> userPosts = new HashMap<>();
        userPosts.put("user_a", posts);
        return userPosts;
    }

    static private Map<String, Object> generateUser2PostList() {
        final List<ComparisionMain.Post> posts = new ArrayList<>();
        posts.add(new ComparisionMain.Post(20L, "Post 20"));
        posts.add(new ComparisionMain.Post(21L, "Post 21"));
        final Map<String, Object> userPosts = new HashMap<>();
        userPosts.put("user_b", posts);
        return userPosts;
    }

    static private String getHash(String content) throws NoSuchAlgorithmException {
        MessageDigest messageDigest = MessageDigest.getInstance("MD5");
        messageDigest.update(content.getBytes());
        byte[] digiest = messageDigest.digest();
        return DatatypeConverter.printHexBinary(digiest);
    }

    @Test
    public void testTwoCollectionMeaningfullyEquals() throws NoSuchAlgorithmException {
        System.out.println("------------- testTwoCollectionMeaningfullyEquals --------------");
        final Gson gson = new Gson();
        List<Map<String, Object>> collection1 = new ArrayList<>();
        List<Map<String, Object>> collection2 = new ArrayList<>();

        collection1.add(generateUser1PostList());

        collection2.add(generateUser1PostList());

        final String hash1 = getHash(gson.toJson(collection1));

        System.out.println(hash1);
        final String hash2 = getHash(gson.toJson(collection2));
        System.out.println(hash2);

        Assert.assertEquals(hash1, hash2);

        System.out.println("------------- testTwoCollectionMeaningfullyEquals --------------");
    }

    @Test
    public void testTwoCollectionMeaningfullyNotEquals() throws NoSuchAlgorithmException {
        System.out.println("------------- testTwoCollectionMeaningfullyNotEquals --------------");
        final Gson gson = new Gson();
        List<Map<String, Object>> collection1 = new ArrayList<>();
        List<Map<String, Object>> collection2 = new ArrayList<>();

        collection1.add(generateUser1PostList());

        collection2.add(generateUser2PostList());

        final String hash1 = getHash(gson.toJson(collection1));

        System.out.println(hash1);
        final String hash2 = getHash(gson.toJson(collection2));
        System.out.println(hash2);

        Assert.assertNotEquals(hash1, hash2);

        System.out.println("------------- testTwoCollectionMeaningfullyNotEquals --------------");
    }
}

Output of the above program is:

Testing started at 12:01 PM ...
> Task :cleanTest
> Task :compileJava UP-TO-DATE
> Task :processResources NO-SOURCE
> Task :classes UP-TO-DATE
> Task :compileTestJava
> Task :processTestResources NO-SOURCE
> Task :testClasses
> Task :test
------------- testTwoCollectionMeaningfullyNotEquals --------------
766461F7DB37B8EC031BE0145E6832D3
156636D7A2CF2196783F9D644A994391
------------- testTwoCollectionMeaningfullyNotEquals --------------
------------- testTwoCollectionMeaningfullyEquals --------------
766461F7DB37B8EC031BE0145E6832D3
766461F7DB37B8EC031BE0145E6832D3
------------- testTwoCollectionMeaningfullyEquals --------------
BUILD SUCCESSFUL in 0s
4 actionable tasks: 3 executed, 1 up-to-date
12:01:49 PM: Tasks execution finished ':cleanTest :test --tests "im.silentsudo.gradletest.HashComparisionTest"'.

This is very simple implementation, if you need more details on object comparision in java please take a look at https://www.baeldung.com/java-equals-hashcode-contracts


问:
What is the long game for Blazor Server and Blazor WebAssembly?
I'm well aware of the pros and cons of Blazor Server vs Blazor WebAssembly.  That said, which one should we use to build, say, a new company website?  While "it depends" might be your answer, it's more than which one checks more boxes in our criteria.

Does anyone know what is Microsoft's long-term roadmap/direction?  If we were to build it in Blazor Server and then learn two years from now that Microsoft wants to deprecate it in favor of WebAssembly, then we will have made a big mistake (like when we chose LINQ over EF but don't get me started on that one!).  If we thought WebAssembly was more future-proof (especially given all the buzz), but both end up being fully touted/supported long-term, then it may have made more sense to have used Blazor Server (depending on criteria).

That said, criteria can change (oh the humanity!).  If we build it in Blazor Server but our CEO then says he wants it to render a calculator even if offline (ok, that's not going to happen but you know what I mean), then we're unable to do that.  Conversely, if we build it WebAssembly and then the business wants something that (I don't know.. for it to show for SEO statistics), it would have been better to have gone the other way with Blazor Server.

In today's world, most companies have a website and a native mobile app (Dominoes, MGM Grand, whatever).  I realize WebAssembly with PWA is a way we smaller companies can have a pseudo-native app without actually having to write one (Xamarin to iOS, Android), but what's the long game here?  You see where I'm going with this question?  It's not about the specific pros and cons of each, it's about trying to survey the landscape five years from now and make the right decision today for that future.  My gut tells me WebAssembly for everything but my gut also told me LINQ over EF.

Thanks in advance for your comments.

答:
Check out this announcement to ONE net, the direction MS is taking:
The Journey to One .NET

Globally speaking we are heading toward cross platform uniformity based on Net.Core, Blazor and Xamarin:

https://devblogs.microsoft.com/dotnet/introducing-net-multi-platform-app-ui/


问:
How to re-render a component (Vue) with its data (and state) intact?
Here's how my code is structured: parent component shuffles through child components via v-if directives, one of the child components is using a state to define its data. Everything works except when I switch between the child components. When I get back, no data can be shown because the state has become null.

Parent component:

```<code><template>
  <div>
   <Welcome v-if="view==0" />
   <Courses v-if="view==1" /> //the component that I'm working on
   <Platforms v-if="view==2" />
  </div>
</template>
</code>```

Courses component:

```<code><template>
  <div>Content</div>
</template>

<script>
export default {
  name: 'Courses',
  computed: {
    ...mapState([
      'courses'
    ])
  },
  data () {
    return {
      courseList: [],
      len: Number,
    }
  },
  created () {
    console.log("state.courses:")
    console.log(this.courses)
    this.courseList = this.courses
    this.len = this.courses.length
  },
}
</script>
</code>```

Let say the default value for "view" is 1, when I load the page, the "Courses" component will be shown (complete with the data). If I click a button to change the value of "view" to 0, the "Welcome" component is shown. However, when I tried to go back to the "Courses" component, the courses component is rendered but is missing all the data.

Upon inspection (via console logging), I found that when the "Courses" component was initially rendered, the state was mapped correctly and I could use it, but if I changed the "view" to another value to render another component and then changed it back to the original value, the "Courses" component still renders but the state became undefined or null.

EDIT: Clarification.

答:
Set courseList to a component name and use <component>
and set some enum

eg.

```<code><template>
   <component :is="this.viewState" />
</template>
<script>
export default {
    // your stuff
    data() {
      return {
         viewState: 'Welcome',
      }
    },
    methods: {
      getComponent(stateNum) {
          const States = { '1': 'Welcome', '2': 'Courses', '3': 'Platforms' }
          Object.freeze(States)
          return States[stateNum]
      }
    },
    created() {
       // do your stuff here
       const view = someTask() // someTask because I don't get it from where you're getting data
       this.viewState = this.getComponent(view)
    }
}
</script>
</code>```

I don't actually understood correctly but here I gave some idea for approaching your problem.

Body:
Here's how my code is structured: parent component shuffles through child components via v-if directives, one of the child components is using a state to define its data. Everything works except when I switch between the child components. When I get back, no data can be shown because the state has become null.

Parent component:

<template>

   <Welcome v-if="view==0" />
   <Courses v-if="view==1" /> //the component that I'm working on
   <Platforms v-if="view==2" />

</template>

Courses component:

<template>

Content

</template>

Let say the default value for "view" is 1, when I load the page, the "Courses" component will be shown (complete with the data). If I click a button to change the value of "view" to 0, the "Welcome" component is shown. However, when I tried to go back to the "Courses" component, the courses component is rendered but is missing all the data.

Upon inspection (via console logging), I found that when the "Courses" component was initially rendered, the state was mapped correctly and I could use it, but if I changed the "view" to another value to render another component and then changed it back to the original value, the "Courses" component still renders but the state became undefined or null.

EDIT: Clarification.

Body:
Set courseList to a component name and use <component>
and set some enum

eg.

<template>
   <component :is="this.viewState" />
</template>
<script>
export default {
    // your stuff
    data() {
      return {
         viewState: 'Welcome',
      }
    },
    methods: {
      getComponent(stateNum) {
          const States = { '1': 'Welcome', '2': 'Courses', '3': 'Platforms' }
          Object.freeze(States)
          return States[stateNum]
      }
    },
    created() {
       // do your stuff here
       const view = someTask() // someTask because I don't get it from where you're getting data
       this.viewState = this.getComponent(view)
    }
}
</script>

I don't actually understood correctly but here I gave some idea for approaching your problem.


问:
Javascript automation to add add-on tool to the toolbar in Acrobat
Hello everyone,

I am a complete beginner in developing Acrobat functionalities, and I had been given a task of adding a button to the toolbar, which on pressing would display a pop-up, using Javascript. I was able to add a button to the add-on toolbar and then I manually added the button from the add-on tools to the toolbar. I have been asked if this manual addition could be automated, I went through the Javascript API reference and found that it provides the execMenuItem method but it only is able to perform some commands such as Save As. Could it be possible to write a script that would automate the manual addition ? The manual addition that I am talking about is Going to View -> Show/Hide -> Toolbar Items -> Customize Quick Tools

I am aware that we can add a button to the toolbar directly using plugins but that would require developing in C++, and our team is trying to explore functionalities that could be achieved using JS scripts

Thanks

答:
You can use addToolButton() from page 100 of the JavaScript for Acrobat API Reference to achieve similar functionality.

However it appears that adding to Quick Tools is not supported through the JavaScript API, according to one AcrobatUsers post:

Note that as of version X you cannot place a button on the toolbar automatically, no matter what code you write - it will ALWAYS appear on the Tools Pane, down at the bottom corner - from where the user has to manually drag it into the Quick Tools area.


问:
Transform a one-liner from Numpy Python to Julia that involves mapping one 2D Array onto another 2D Array
Julia beginner here. I need to so some jugglery with a couple of matrices. My goal is as follows:

Given a certain matrix Matrix1 as:

, and a binary matrix Matrix2 as this:

, I want to allocate the elements from Matrix1 to Matrix2 such that I have a final matrix Matrix3, which looks like:

In Python, the following one liner worked:

Matrix3= Matrix1.flatten()[(np.cumsum(Matrix2).reshape(Matrix2.shape)-1)] * Matrix2

Can anyone help me in writing a similar piece of code (preferably one liner if possible) in Julia?

Extension    -  I have gotten the answer for the above question from @cbk. As an extension to the question above. I was thinking of generalizing it for higher dimensional matrices. So, suppose Matrix1 has dimension (4,6,6) and the binary matrix Matrix2 has dimension (4,12,12). The allocation problem remains the same. How would then you approach it? Can someone kindly help me in it?

答:
The main "gotchas" are that (1) you want to fill Matrix3 with the appropriate type of zero and (2) Julia is column-major, so you need to permute. This should do the trick though:

(Matrix3 = zeros(eltype(Matrix1),size(Matrix2)))'[Matrix2'[:]] .= Matrix1'[:]

A similar option would be

(Matrix3 = zeros(eltype(Matrix1),size(Matrix2)))'[vec(Matrix2')] .= vec(Matrix1')

but this was slightly less efficient than the above, as measured by @btime

edit: If Matrix2 originally contains integers instead of Booleans, you will need to convert before indexing with Matrix2, e.g.:

(Matrix3 = zeros(eltype(Matrix1),size(Matrix2)))'[Bool.(Matrix2'[:])] .= Matrix1'[:]


问:
SSL Handshake Failure Alert for JDK7
I'm using Liferay 6.2 CE GA2 Framework which is running on JDK7.
While calling Discourse Forum API using Apache httpclient it throws exception: javax.net.ssl.SSLHandshakeException: Received fatal alert: handshake_failure.

I think this is because*JDK7 doesn’t implement any GCM cipher suite.

And Discourse Forum is configured with SSL Protocol: TLSv1.2 and Strong Cipher Suites: TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384

How to resolve this issue? Or is there any other way to call Discourse API from Java platform.

Thanks,

Saurabh Khandelwal

答:
First of all: Before you fix this problem, you really need to upgrade and patch.

Which also might bring you closer to a solution: The compatibility matrix for Liferay EE 6.2 lists Java 8 as compatible - I'm not sure when this came in, but there's a good chance that the later GA versions in CE are also compatible. With that, you should have a newer set of TLS algorithms.

Otherwise you'd have to ask the Discourse admins to enable some algorithm that's compatible with your Java version.

(Disclaimer: I've not checked available algorithms in Java7, but it sounds like an unsupported algorithm is indeed a plausible root cause)

Did I mention that you really should update urgently?

Title: SSL Handshake Failure Alert for JDK7


问:
Is returning a list a good programming practice?
So i have a function that has to return 3 values, i haven't found a better way to do this other than returning a list. Is this code a good programming practice? And if not how to fix it.

Example function:

```<code>def func():
    #code
    return [a,b,c]
</code>```

Main code:

```<code>   #code
   list = func()
   k = list[0]
   l = list[1]
   m = list[2]
</code>```

答:
You can pack/unpack directly in python:

def func():
    a = 1
    b = 2
    c = 3
    return a, b, c

k, l, m = func()
```

Body:
So i have a function that has to return 3 values, i haven't found a better way to do this other than returning a list. Is this code a good programming practice? And if not how to fix it.

Example function:

def func():
    #code
    return [a,b,c]

Main code:

   #code
   list = func()
   k = list[0]
   l = list[1]
   m = list[2]


问:
changing text with different duration in javascript
Hello stackoverflow community,

my goal is to create changing text with different duration, meaning that there are certain "markers" or sentences which stay longer then the 2 seconds I have now as of now.
Also, I would like the animation to stop after all the list entries have been displayed.

Here is the code I have for now:

http://jsfiddle.net/eu8L01nv/

Javacript:

```<code>    var terms = $("ul li");

    function rotateTerm() {

     var ct = $("#rotate").data("term") || 0;

     console.log(terms.eq([ct]).text());

      $("#rotate").data("term",
        ct == terms.length -1 ? 0 : ct + 1).text(terms.eq([ct]).text())
      .fadeIn().delay(2000).fadeOut(200, rotateTerm);

    }
    $(rotateTerm);

</code>```

HTML

```<code>    <p><span id="rotate">default</span></p>

    <ul style="display:none">
        <li>This is sentence number one.</li>
        <li>That is sentence number two.</li>
        <li>This is another sentence.</li>
        <li>Another sentence.</li>
    </ul>

</code>```

Thank you!

答:
I hope this solves the issue:

I added this piece of code to it: ct < terms.length -1 && rotateTerm. so that it won't call rotateTerm function after the last element

And I have added a timeDelay array var timeDelay = [1000, 2000, 4000, 8000] to enable different time delays for different sentences.

```<code>var terms = $("ul li");

    function rotateTerm() {

     var timeDelay = [1000, 2000, 4000, 8000];
     var ct = $("#rotate").data("term") || 0;
     console.log(terms.eq([ct]).text());
     console.log(ct)
      $("#rotate").data("term",
        ct == terms.length -1 ? 0 : ct + 1).text(terms.eq([ct]).text())
      .fadeIn().delay(timeDelay[ct]).fadeOut(200, ct < terms.length -1 && rotateTerm);

    }
    $(rotateTerm);
</code>```

Or you could set the delay depending upon the length of the text

```<code>var terms = $("ul li");

function rotateTerm() {

  var ct = $("#rotate").data("term") || 0;
  const text = terms.eq([ct]).text()
  const textLength = text.length;
  console.log(textLength)
  const timeDelay = textLength < 50 ? 2000 : textLength * 50
  $("#rotate").data("term",
      ct == terms.length - 1 ? 0 : ct + 1).text(text)
    .fadeIn().delay(timeDelay).fadeOut(200, ct < terms.length - 1 && rotateTerm);

}
$(rotateTerm);

</code>```

Body:
Hello stackoverflow community,

my goal is to create changing text with different duration, meaning that there are certain "markers" or sentences which stay longer then the 2 seconds I have now as of now.
Also, I would like the animation to stop after all the list entries have been displayed.

Here is the code I have for now:

http://jsfiddle.net/eu8L01nv/

Javacript:

    var terms = $("ul li");

    function rotateTerm() {

     var ct = $("#rotate").data("term") || 0;

     console.log(terms.eq([ct]).text());

      $("#rotate").data("term",
        ct == terms.length -1 ? 0 : ct + 1).text(terms.eq([ct]).text())
      .fadeIn().delay(2000).fadeOut(200, rotateTerm);

    }
    $(rotateTerm);

HTML

default

This is sentence number one.

That is sentence number two.

This is another sentence.

Another sentence.

Thank you!

Body:
I hope this solves the issue:

I added this piece of code to it: ct < terms.length -1 && rotateTerm. so that it won't call rotateTerm function after the last element

And I have added a timeDelay array var timeDelay = [1000, 2000, 4000, 8000] to enable different time delays for different sentences.

var terms = $("ul li");

    function rotateTerm() {

     var timeDelay = [1000, 2000, 4000, 8000];
     var ct = $("#rotate").data("term") || 0;
     console.log(terms.eq([ct]).text());
     console.log(ct)
      $("#rotate").data("term",
        ct == terms.length -1 ? 0 : ct + 1).text(terms.eq([ct]).text())
      .fadeIn().delay(timeDelay[ct]).fadeOut(200, ct < terms.length -1 && rotateTerm);

    }
    $(rotateTerm);

Or you could set the delay depending upon the length of the text

var terms = $("ul li");

function rotateTerm() {

  var ct = $("#rotate").data("term") || 0;
  const text = terms.eq([ct]).text()
  const textLength = text.length;
  console.log(textLength)
  const timeDelay = textLength < 50 ? 2000 : textLength * 50
  $("#rotate").data("term",
      ct == terms.length - 1 ? 0 : ct + 1).text(text)
    .fadeIn().delay(timeDelay).fadeOut(200, ct < terms.length - 1 && rotateTerm);

}
$(rotateTerm);


问:
How to update existing wotkitem(feature) card state through API azure devops without using PATCH http method
I have a Feature card with state New i want to change the state of this card using API. I work on AA tool of RPA which doesn't support PATCH method. i want to update only "System.State" is there API query to update state?</p>

答:
As a workaround ,you can try to change the state via azure cli:</p>

```<code>az boards work-item update --id [--state]
</code>```

Body:
As a workaround ,you can try to change the state via azure cli:

az boards work-item update --id [--state]


问:
Store list of Strings in S3
I am new to Amazon AWS S3.
One of my applications processes 40000 updates an hour with a unique identifier for each update.
This identifier is basically a string.
At runtime, I want to store the ID in an S3 bucket for all updates.

But, as far as I understood, we need to store files in s3.

Is there anyway around this?
Should I store a file.. Then read that file each time..append the name and store it again?

Any direction would be very helpful.
Thanks in advance.

I want it to be stored like:

Id1

Id2

Id3
.
.
,
.

Edit: Thanks for the responses, I have added what is asked..

I want to be able to just fetch all these IDs if and when a problem occurs in our system.

I am open to using anything other than s3 as well. I was also looking into DynamoDB. With the ID as the primary key. But, these ID's might be repetitive in 1-2% cases.

答:
In S3, you do not have concept of files and folders. All you have is a bucket and objects inside the bucket. However, the UI of AWS groups objects with common prefixes such that they appear to be in the same folder.

Also, there is nothing like appending to a file in S3. Since S3 has objects, what essentially happens is that the so called append deletes the previous object and creates a new object with the previous object's data appended with some more data.

So, one way to do what I think you're trying is :

Suppose you have all the IDs written at 10:00 in an S3 object called data_corresponding_to_10_00_00. For the next hour(and 40000 updates), if they have all new IDs, you can write them to another S3 object with the name data_corresponding_to_11_00_00.

However, if you do not want multiple entries in both the files, and you need to update the previous file itself, using S3 is not a great idea. Rather use a database indexed on ID so that the performance becomes faster.

Title: Store list of Strings in S3


问:
Can we exclude core components when we use the Maven archetype to create a new repo?
We have AEM env in 6.4.2, and we want to include new repo(adding new website in multi-tenancy env). For this, I am using maven archetype 20 to create a new repo. We already have core components(2.5.0) are available in AEM instance, so I would like to exclude dependency from the newly created repo.
Is there any way we can exclude core components creation from the latest archetypes?</p>

答:
From what I can see in the AEM Project Archetype pom file https://github.com/adobe/aem-project-archetype/blob/master/src/main/archetype/all/pom.xml#L73 AEM core components will be set up as embedded unless you specify your AEM version as "cloud"

Excluding the package from your build once the project is created is quite straightforward though, simply remove the embedded tag from your project's pom file and adjust your <core.wcm.components.version> property to depend on 2.5.0


问:
Xampp-mysql - "Table doesn't exist in engine" #1932
Xampp error after moving xampp folder:

Apache is running fine:

as given below image i'm sucess to run apache but unable to run mysql if in case i moved and run xampp both apache and mysql but its shows error which is fresh and it show the error like "Table doesn't exist in engine" #1932 as given up image. please solve the issue anyone help pls

答:
If you have copied & Pasted files from an old backup folder to new then its simple.
Just copy the old ibdata1 into your new one. You can find it from \xampp\mysql\data
And restart your mysql.


问:
Handling JavaScript events in WKWebView
I'm trying to catch every onClick event in WKWebView.
The website is working only with JavaScript so I cannot handle anything in:

```<code>func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void)
</code>```

How can I do this?

答:
If you want to add click listener only for button with id 'buttonX' (<button id="buttonX">Click me</button>) then

```<code>
let scriptSource = """
var button = document.getElementById('buttonX');
document.body.style.backgroundColor = `red`;
if(button != null) {
    button.addEventListener("click", function(){
        window.webkit.messageHandlers.iosClickListener.postMessage('open_invitation');
        document.body.style.backgroundColor = `green`;
    });
}

"""

        let config = WKWebViewConfiguration()
        let script = WKUserScript(source: scriptSource, injectionTime: .atDocumentEnd, forMainFrameOnly: false)

        config.userContentController.addUserScript(script)
        config.userContentController.add(self, name: "iosClickListener")

        let webView = WKWebView(frame: view.frame, configuration: config)

        view.addSubview(webView)
        webView.loadHTMLString(html, baseURL: nil) //load your html body here

    }

    func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
        if let body = message.body as? String, body == "open_invitation" {
            print("✅ we did it")
        }
    }

</code>```

Also your view controller should conform to WKScriptMessageHandler protocol

Title: Handling JavaScript events in WKWebView

Body:
I'm trying to catch every onClick event in WKWebView.
The website is working only with JavaScript so I cannot handle anything in:

func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void)

How can I do this?

Body:
If you want to add click listener only for button with id 'buttonX' (<button id="buttonX">Click me</button>) then

let scriptSource = """
var button = document.getElementById('buttonX');
document.body.style.backgroundColor = `red`;
if(button != null) {
    button.addEventListener("click", function(){
        window.webkit.messageHandlers.iosClickListener.postMessage('open_invitation');
        document.body.style.backgroundColor = `green`;
    });
}

"""

        let config = WKWebViewConfiguration()
        let script = WKUserScript(source: scriptSource, injectionTime: .atDocumentEnd, forMainFrameOnly: false)

        config.userContentController.addUserScript(script)
        config.userContentController.add(self, name: "iosClickListener")

        let webView = WKWebView(frame: view.frame, configuration: config)

        view.addSubview(webView)
        webView.loadHTMLString(html, baseURL: nil) //load your html body here

    }

    func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
        if let body = message.body as? String, body == "open_invitation" {
            print("✅ we did it")
        }
    }

Also your view controller should conform to WKScriptMessageHandler protocol


问:
How to rotate a two-dimensional array to an arbitrary degree?
Say I have a bool[][], and I want to rotate it by 37 degrees. I am aware that the transformation wouldn't always be perfect, and that's okay. I've ready plenty of answers on here similar to my question, but the only solutions I've found only solve the problem for 90 degree increments. </p>

答: Unless you really, really want to do this yourself, consider using something like AForge -- more specifically AForge.Imaging.Filters.RotateBicubic. This routine handles 24bpp and 8bpp images, so you'd need to rotate the RGB content (as a 24bpp image) separately from the alpha channel (as an 8bpp image).</p>


问:
Show Only One Value In Dropdown If There are Duplicates
Hi i'm trying to get the information of printers by the location. so if i have few printers at the same location ill see them both at the dropdown but i actually want to see only one location on the dropdown if they are the same location.
i know i can solve this in the database level and add relationships but maybe there is a way to do it without it ?

import {
  Component,
  OnInit
} from '@angular/core';
import {
  HttpClient
} from '@angular/common/http';
import {
  DomSanitizer
} from '@angular/platform-browser';
import {
  Values
} from '../Models/Values';

@Component({
  selector: 'app-value',
  templateUrl: './value.component.html',
  styleUrls: ['./value.component.css']
})

export class ValueComponent implements OnInit {
  selectedPrinter: Values;
  values: any;

  constructor(private http: HttpClient, public sanitizer: DomSanitizer) {}

  ngOnInit() {
    this.getValues();

  }

  getValues() {
    this.http.get('http://localhost:5000/api/values/').subscribe(response => {
      this.values = response;
    }, error => {
      console.log(error);
    })
  }

}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><H2>Printer Manager</H2>
<div id="selectCompanyDiv">
  <div class="col-12 col-md-3 col-xl-2 mt-5 bd-sidebar">
    <label for="">Select Location</label>
    <select class="form-control" [(ngModel)]="selectedPrinter">
      <option *ngFor="let each of values " [ngValue]="each.location">{{each.location}} </option>
      <!-- {{each.specificLocation}} -->
    </select>
    <!-- Search -->
    <!-- <input id="test" *ngFor="let each of values " class="form-control" type="search" placeholder="Search"  {{values.location}}>

         <button ondblclick="Access()">click here
        </button> -->
  </div>
  <br>
  <br>
  <div>
    <div *ngFor="let value of values" id="mainDiv">
      <div *ngIf="value.location===selectedPrinter">
        <span>HostName: {{value.hostName}}</span>
        <br>
        <!-- <span>Location: {{value.location}}</span> -->

        <span>Manufacturer: {{value.manufacturer}}</span>
        <br>
        <span>IP: {{value.ip}}</span>
        <br>
        <h2>{{value.location}}</h2>
        <span>{{value.specificLocation}}</span>
        <br>
        Full view
        <div>
          <div *ngIf="value.model==='J480'" class="outerFrame">
            <iframe [src]="sanitizer.bypassSecurityTrustResourceUrl('http://'+value.ip+'/general/status.html')" id="inneriframeBrotherj480" scrolling="no"></iframe>
          </div>
          <div *ngIf="value.model==='6530DW'" class="outerFrame">
            <iframe [src]="sanitizer.bypassSecurityTrustResourceUrl('http://'+value.ip+'/general/status.html')" id="inneriframeBrother6530DW" scrolling="no"></iframe>
          </div>
        </div>
      </div>
    </div></code>```

答:
```<code>getValues() {
    this.http.get('http://localhost:5000/api/values/').subscribe(response => {
      this.values = [...new Set(response)];
    }, error => {
      console.log(error);
    })
  }
</code>```

Body:
Hi i'm trying to get the information of printers by the location. so if i have few printers at the same location ill see them both at the dropdown but i actually want to see only one location on the dropdown if they are the same location.
i know i can solve this in the database level and add relationships but maybe there is a way to do it without it ?

import {
  Component,
  OnInit
} from '@angular/core';
import {
  HttpClient
} from '@angular/common/http';
import {
  DomSanitizer
} from '@angular/platform-browser';
import {
  Values
} from '../Models/Values';

@Component({
  selector: 'app-value',
  templateUrl: './value.component.html',
  styleUrls: ['./value.component.css']
})

export class ValueComponent implements OnInit {
  selectedPrinter: Values;
  values: any;

  constructor(private http: HttpClient, public sanitizer: DomSanitizer) {}

  ngOnInit() {
    this.getValues();

  }

  getValues() {
    this.http.get('http://localhost:5000/api/values/').subscribe(response => {
      this.values = response;
    }, error => {
      console.log(error);
    })
  }

}

Printer Manager

    Select Location
    <select class="form-control" [(ngModel)]="selectedPrinter">
      <option *ngFor="let each of values " [ngValue]="each.location">{{each.location}} </option>

    </select>

        HostName: {{value.hostName}}

        Manufacturer: {{value.manufacturer}}

        IP: {{value.ip}}

{{value.location}}

        {{value.specificLocation}}

        Full view


问:
how to export only selected rows from handsontable into csv
I am trying to export csv file from handsontable only for selected rows

I have tried this code using html 5 and angularJS:

```<code>exportPlugin = hot.getPlugin('exportFile');
$scope.exportToExcel = function(){
    if(exportPlugin!=null && exportPlugin != undefined){
        exportPlugin.downloadFile('csv', {filename: 'file1',columnHeaders: true});
    }
}
</code>```

I expect if I select 3 rows out of 7 rows it exports 3 rows into csv file

答:
Below code worked for me
first i have created array of selected rows if array has 1 or more than one record i have passed each row and column values to range property</p>

```<code>function export(){
                if(exportPlugin!=null && exportPlugin != undefined){
                    var selectedRows = getSelectedRows();
                    if(selectedRows.length > 0)
                       exportPlugin.downloadFile('csv', {filename: 'filename',columnHeaders: true, range: [selectedRows[0], 0, selectedRows[selectedRows.length-1], htGridControl.getColHeader().length-1] });
                    else
                       exportPlugin.downloadFile('csv', {filename: 'filename',columnHeaders: true});
                }
              }
</code>```

Body:
I am trying to export csv file from handsontable only for selected rows

I have tried this code using html 5 and angularJS:

exportPlugin = hot.getPlugin('exportFile');
$scope.exportToExcel = function(){
    if(exportPlugin!=null && exportPlugin != undefined){
        exportPlugin.downloadFile('csv', {filename: 'file1',columnHeaders: true});
    }
}

I expect if I select 3 rows out of 7 rows it exports 3 rows into csv file

Body:
Below code worked for me
first i have created array of selected rows if array has 1 or more than one record i have passed each row and column values to range property

function export(){
                if(exportPlugin!=null && exportPlugin != undefined){
                    var selectedRows = getSelectedRows();
                    if(selectedRows.length > 0)
                       exportPlugin.downloadFile('csv', {filename: 'filename',columnHeaders: true, range: [selectedRows[0], 0, selectedRows[selectedRows.length-1], htGridControl.getColHeader().length-1] });
                    else
                       exportPlugin.downloadFile('csv', {filename: 'filename',columnHeaders: true});
                }
              }


问:
nginx php-fpm with dynamic url segments not being parsed by php-fpm
so this one is a weird one! I have these nginx stanzas. I used an online tool to convert .htaccess rules into nginx capable ones.

```<code>location / {
        rewrite ^/(([^/]+/)*)login/$ /login.php?path=$1&$query_string break;
        rewrite ^/(([^/]+/)*)comment/$ /comment.php?path=$1&$query_string break;
        rewrite "^/([^/]+/){4}$" /asset.php break;
        rewrite ^/(\d\w+)/$ /public.php?ticket=$1 break;
        rewrite "^/(\d\w+)/([^/]+/){2}?$" /public-asset.php?ticket=$1 break;
        if (!-e $request_filename){
                rewrite ^/(([^/]+/)*) /index.php?path=$1&$query_string break;
        }
        try_files $uri $uri/ /index.php$is_args$args;
}

location ~ \.php$ {
        include snippets/fastcgi-php.conf;
        fastcgi_param  SCRIPT_FILENAME  $document_root$fastcgi_script_name;
        fastcgi_pass   unix:/var/run/php/vh1-fpm.sock;
        include fastcgi_params;
}
</code>```

going to https://example.test/ ok

going to https://example.test/login/ all heck break loose and PHP code is flooded onto the screen.

The regex routing works because the redirects take place. but once the redirect it done, it's like the masked .php file is not caught. All this is fixed if I encapsulate the PHP checks within the / location block.

答:
You cannot use rewrite ... break when the rewritten URI is to be processed in a different location block.

Use: rewrite...last

Also, there is no need to tack &$query_string on the end of the rewritten URI, as rewrite will do it anyway unless the rewritten URI ends with a ?.

See this document for details.

Body:
so this one is a weird one! I have these nginx stanzas. I used an online tool to convert .htaccess rules into nginx capable ones.

location / {
        rewrite ^/(([^/]+/)*)login/$ /login.php?path=$1&$query_string break;
        rewrite ^/(([^/]+/)*)comment/$ /comment.php?path=$1&$query_string break;
        rewrite "^/([^/]+/){4}$" /asset.php break;
        rewrite ^/(\d\w+)/$ /public.php?ticket=$1 break;
        rewrite "^/(\d\w+)/([^/]+/){2}?$" /public-asset.php?ticket=$1 break;
        if (!-e $request_filename){
                rewrite ^/(([^/]+/)*) /index.php?path=$1&$query_string break;
        }
        try_files $uri $uri/ /index.php$is_args$args;
}

location ~ \.php$ {
        include snippets/fastcgi-php.conf;
        fastcgi_param  SCRIPT_FILENAME  $document_root$fastcgi_script_name;
        fastcgi_pass   unix:/var/run/php/vh1-fpm.sock;
        include fastcgi_params;
}

going to https://example.test/ ok

going to https://example.test/login/ all heck break loose and PHP code is flooded onto the screen.

The regex routing works because the redirects take place. but once the redirect it done, it's like the masked .php file is not caught. All this is fixed if I encapsulate the PHP checks within the / location block.


问:
SQL OneToMany Relationship
Im new to SQL relations, Im using spring, and im wanting to make a OneToMany relationship between a customer and a ticket, eg Customer can have multiple tickets but ticket cant have multiple customers, heres what ive got,

```<code>@Entity
@Table(name = "tickets")
data class Ticket(
    @Id
    val id:Long,
    val ticketId:String,
    val price:Int,
    val openDate:LocalDateTime,
    val closeDate:LocalDateTime,
    @ManyToOne
    val customer:Customer
)

@Entity
@Table(name = "customers")
data class Customer(
    @Id
    val id:Long,
    val email:String,
    val discordUserId:String,
    val amountSpent:Int,
    @OneToMany
    @JoinColumn(name = "ticket_id", table = "tickets")
    val tickets:Set<Ticket>
)
</code>```

However, I get an error on startup

Caused by: org.hibernate.cfg.NotYetImplementedException: Collections having FK in secondary table

Just wondering how I can resolve this,

答:
You should implement bidirectional relationship between your classes like this:</p>

```<code>@Entity
@Table(name = "customers")
data class Customer(
    @Id @GeneratedValue(strategy = GenerationType.IDENTITY)
    var id:Long,
    var email:String,
    var discordUserId:String,
    var amountSpent:Int,
    @OneToMany(mappedBy = "customer", cascade = [CascadeType.ALL], orphanRemoval = true, fetch = FetchType.EAGER)
    var tickets:Set<Ticket> = setOf()
)

@Entity
@Table(name = "tickets")
data class Ticket(
    @Id @GeneratedValue(strategy = GenerationType.IDENTITY)
    var id:Long,
    var ticketId:String,
    var price:Int,
    var openDate:LocalDateTime,
    var closeDate:LocalDateTime,
    @ManyToOne(fetch = FetchType.EAGER)
    @JoinColumn(name="customer_id", nullable=false)
    var customer: Customer? = null
)
</code>```

Title: SQL OneToMany Relationship

Body:
Im new to SQL relations, Im using spring, and im wanting to make a OneToMany relationship between a customer and a ticket, eg Customer can have multiple tickets but ticket cant have multiple customers, heres what ive got,

@Entity
@Table(name = "tickets")
data class Ticket(
    @Id
    val id:Long,
    val ticketId:String,
    val price:Int,
    val openDate:LocalDateTime,
    val closeDate:LocalDateTime,
    @ManyToOne
    val customer:Customer
)

@Entity
@Table(name = "customers")
data class Customer(
    @Id
    val id:Long,
    val email:String,
    val discordUserId:String,
    val amountSpent:Int,
    @OneToMany
    @JoinColumn(name = "ticket_id", table = "tickets")
    val tickets:Set<Ticket>
)

However, I get an error on startup

Caused by: org.hibernate.cfg.NotYetImplementedException: Collections having FK in secondary table

Just wondering how I can resolve this,

Body:
You should implement bidirectional relationship between your classes like this:

@Entity
@Table(name = "customers")
data class Customer(
    @Id @GeneratedValue(strategy = GenerationType.IDENTITY)
    var id:Long,
    var email:String,
    var discordUserId:String,
    var amountSpent:Int,
    @OneToMany(mappedBy = "customer", cascade = [CascadeType.ALL], orphanRemoval = true, fetch = FetchType.EAGER)
    var tickets:Set<Ticket> = setOf()
)

@Entity
@Table(name = "tickets")
data class Ticket(
    @Id @GeneratedValue(strategy = GenerationType.IDENTITY)
    var id:Long,
    var ticketId:String,
    var price:Int,
    var openDate:LocalDateTime,
    var closeDate:LocalDateTime,
    @ManyToOne(fetch = FetchType.EAGER)
    @JoinColumn(name="customer_id", nullable=false)
    var customer: Customer? = null
)


问:
Cronjob Javascript, how to fire job limited times? ( set counter and max limit )
I'm new to Cronjob and looking for a way to fire it with interval but only 5 times.
Im firing an API call with cron and do not want to loop it.
Is it possible to set a counter and max limit of how many times cron has been executed?
or is there another better way of making delayed API calls with nodejs 5 times during 5 min ?</p>

答:
You can use setInterval and clearInterval for this purpose and keep a counter of the number of times you've called the api. For example:

// Set this to whatever you wish. For one minute interval this will be 60000
const intervalDuration = 5000;

function callApi(count) {
    console.log("Calling api: count:", count);
    /* Call API here... */
}

function startCallingApi(callCount) {

    let context = { count: 0 };
    callApi(++context.count);
    let timeout = setInterval((context) => {
        callApi(++context.count);
        if (context.count >= callCount) {
            console.log("Call count reached, clearing interval...");
            clearInterval(timeout);
        }
    }, intervalDuration, context);

}

startCallingApi(5);```