问:
hibernate secondary table for same entity relationship
I have a Profile class which holds user's information. One of the features of this application is to "follow" another profiles of your choice. I'm having trouble designing the DB and making the link happen, both writing the model code and the repository (is it just a matter of a save?).

My Profile class looks like this: (irrelevant fields to the question and getters/setters are omitted for the sake of simplicity)

```<code>import javax.persistence.*;
import javax.validation.constraints.Email;
import javax.validation.constraints.Size;
import java.io.Serializable;
import java.lang.reflect.Array;
import java.util.*;

@Entity
@Table(name = "USERS")
public class Profile implements Serializable {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @Size(max = 32)
    @Column(nullable = false)
    private String name;

    @Size(max = 16)
    @Column(unique=true, nullable = false)
    private String username;

    @Email
    @Column(unique=true)
    private String email;

    @ManyToOne
    @JoinColumn(name="profile_id")
    private Profile profile;

    @OneToMany(mappedBy = "profile")
    private List<Profile> friends = new ArrayList<>();

    public Profile() {
    }

    // other getters/setters

    public List<Profile> getFriends() {
        return friends;
    }

    public void setFriends(List<Profile> friends) {
        this.friends = friends;
    }

    public void addFriend(Profile friend) {
        this.friends.add(friend);
    }
}

</code>```

This creates a null field called profile_id in the users' table. I've done some research and it seems like creating another table using @SecondaryTable annotation may do the trick. The tutorials I've looked into did not solve my doubts. I'd like some light into the matter, and if possible avoid creating a different entity.

Ideally, I'd have a table with its own id, the owner's id (the person who is following) and the target's id (the person who is being followed).

Thanks in advance!

答:
Well, implementing a @ManyToMany relationship has two approaches. First is to create a separate table only with the respective Id's of each entity. And that thing, might be easy, but it does not cover all the cases. For example in your case you are implementing a @ManyToMany for user and followers. You also might need a date for that,to show in which date they created that relationship. And that is the case where the things get a little bit complicated(not much), but it results in a piece of beauty code. Anyways let's go for both approaches:

`

```<code>  @ManyToMany(cascade=CascadeType.ALL)
    @JoinTable(
    name = "profile_follower",
    joinColumns = @JoinColumn(name = "profile_id", referencedColumnName="id"),
    inverseJoinColumns = @JoinColumn(name = "following_id", referencedColumnName="id")
    private Set<Profile> profiles;
    @ManyToMany(mappedBy = "profiles")
    private Set<Profile> following= new HashSet<>();
</code>```

`

The other approach is creating a separate class for the relationship.
`

```<code>@Entity
public class ProfilesFollowedByUser{
@EmbeddedId
UserFollower id;//this is a separate class

@ManyToOne
@MapsId("id")
@JoinColumn(name="profile_id", referencedColumnName="id")
private Profile profile;

@ManyToOne
@MapsId("id")
@JoinColumn(name="following_id", referencedColumnName="id")
private Profile profile;

private Date createdAt;}
</code>```

`
And here is the embeddable class:

`

```<code>@Embeddable
public class UserFollower implements Serializable{

    private static final long serialVersionUID = 819015237657421374L;

    @Column(name="profile_id")
    private Long profileId;
    @Column(name="following_id")
    private Long followingId;
}
</code>```

`
The second one is probably a little bit more complicated but in vast majority of scenarios at least in the real world apps, when you have to deal with a relationship created a date at least is always needed. Hope that helps with your problem.

Body:
I have a Profile class which holds user's information. One of the features of this application is to "follow" another profiles of your choice. I'm having trouble designing the DB and making the link happen, both writing the model code and the repository (is it just a matter of a save?).

My Profile class looks like this: (irrelevant fields to the question and getters/setters are omitted for the sake of simplicity)

import javax.persistence.*;
import javax.validation.constraints.Email;
import javax.validation.constraints.Size;
import java.io.Serializable;
import java.lang.reflect.Array;
import java.util.*;

@Entity
@Table(name = "USERS")
public class Profile implements Serializable {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @Size(max = 32)
    @Column(nullable = false)
    private String name;

    @Size(max = 16)
    @Column(unique=true, nullable = false)
    private String username;

    @Email
    @Column(unique=true)
    private String email;

    @ManyToOne
    @JoinColumn(name="profile_id")
    private Profile profile;

    @OneToMany(mappedBy = "profile")
    private List<Profile> friends = new ArrayList<>();

    public Profile() {
    }

    // other getters/setters

    public List<Profile> getFriends() {
        return friends;
    }

    public void setFriends(List<Profile> friends) {
        this.friends = friends;
    }

    public void addFriend(Profile friend) {
        this.friends.add(friend);
    }
}

This creates a null field called profile_id in the users' table. I've done some research and it seems like creating another table using @SecondaryTable annotation may do the trick. The tutorials I've looked into did not solve my doubts. I'd like some light into the matter, and if possible avoid creating a different entity.

Ideally, I'd have a table with its own id, the owner's id (the person who is following) and the target's id (the person who is being followed).

Thanks in advance!

Body:
Well, implementing a @ManyToMany relationship has two approaches. First is to create a separate table only with the respective Id's of each entity. And that thing, might be easy, but it does not cover all the cases. For example in your case you are implementing a @ManyToMany for user and followers. You also might need a date for that,to show in which date they created that relationship. And that is the case where the things get a little bit complicated(not much), but it results in a piece of beauty code. Anyways let's go for both approaches:

`

  @ManyToMany(cascade=CascadeType.ALL)
    @JoinTable(
    name = "profile_follower",
    joinColumns = @JoinColumn(name = "profile_id", referencedColumnName="id"),
    inverseJoinColumns = @JoinColumn(name = "following_id", referencedColumnName="id")
    private Set<Profile> profiles;
    @ManyToMany(mappedBy = "profiles")
    private Set<Profile> following= new HashSet<>();

`

The other approach is creating a separate class for the relationship.
`

@Entity
public class ProfilesFollowedByUser{
@EmbeddedId
UserFollower id;//this is a separate class

@ManyToOne
@MapsId("id")
@JoinColumn(name="profile_id", referencedColumnName="id")
private Profile profile;

@ManyToOne
@MapsId("id")
@JoinColumn(name="following_id", referencedColumnName="id")
private Profile profile;

private Date createdAt;}

`
And here is the embeddable class:

`

@Embeddable
public class UserFollower implements Serializable{

    private static final long serialVersionUID = 819015237657421374L;

    @Column(name="profile_id")
    private Long profileId;
    @Column(name="following_id")
    private Long followingId;
}

`
The second one is probably a little bit more complicated but in vast majority of scenarios at least in the real world apps, when you have to deal with a relationship created a date at least is always needed. Hope that helps with your problem.


来源: stackexchange

问:
Modification of expand.grid function in R
I need to create a matrix of all possible combinations. </p>

```<code>L<-12
vec <- c(0:21)
lst <- lapply(numeric(L), function(x) vec)
Mat1<-as.matrix(expand.grid(lst))
</code>```

<p>Result would be very big matrix and my computer cannot calculate it.
Actually, I need only combinations where value in the first column is greater then value in the second one, in the second column is greater then in the third one and so on. Can I modify expand.grid function somehow to drop unnecessary combinations? </p>

答:
As @AllanCameron identified, what you're after is equivalent to taking all combinations of vec of size 12 -- you can also use the built-in function combn for that:

```<code>do.call(rbind, combn(vec, L, simplify = FALSE))
</code>```

It may be faster to use data.table to manipulate the output of combn into the desired format:

```<code>library(data.table)
setDT(transpose(combn(vec, L, simplify=FALSE))
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I need to create a matrix of all possible combinations.

L<-12
vec <- c(0:21)
lst <- lapply(numeric(L), function(x) vec)
Mat1<-as.matrix(expand.grid(lst))

Result would be very big matrix and my computer cannot calculate it.
Actually, I need only combinations where value in the first column is greater then value in the second one, in the second column is greater then in the third one and so on. Can I modify expand.grid function somehow to drop unnecessary combinations?

Body:
As @AllanCameron identified, what you're after is equivalent to taking all combinations of vec of size 12 -- you can also use the built-in function combn for that:

do.call(rbind, combn(vec, L, simplify = FALSE))

It may be faster to use data.table to manipulate the output of combn into the desired format:

library(data.table)
setDT(transpose(combn(vec, L, simplify=FALSE))


问:
Adding whitenoise to django gives an "ImproperlyConfigured: WSGI application" error
My application works if I were not to add

```<code>"whitenoise.middleware.WhiteNoiseMiddleware"
</code>```

into the MIDDLEWARE in settings.py

but if I were to add it back, then it would not work and would give this error

```<code>django.core.exceptions.ImproperlyConfigured: WSGI application 'story_4.wsgi.application' could not be loaded; Error importing module.
</code>```

This is what is inside my wsgi.py file

```<code>#wsgi.py

import os

from django.core.wsgi import get_wsgi_application

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'story_4.settings')

application = get_wsgi_application()
</code>```

Any answer is appreciated.

答:
Problem solved, Please remember to update your Whitenoise to the latest version with pip install --upgrade whitenoise

Mine was still at 3.3.0 and apparently django didn't like it.

Body:
My application works if I were not to add

"whitenoise.middleware.WhiteNoiseMiddleware"

into the MIDDLEWARE in settings.py

but if I were to add it back, then it would not work and would give this error

django.core.exceptions.ImproperlyConfigured: WSGI application 'story_4.wsgi.application' could not be loaded; Error importing module.

This is what is inside my wsgi.py file

#wsgi.py

import os

from django.core.wsgi import get_wsgi_application

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'story_4.settings')

application = get_wsgi_application()

Any answer is appreciated.


问:
F1 2019 UDP decoding
I am currently working on my own display for an F1 steering wheel.
F1 2019 (by codemasters) sends data through UDP. This data is stored in a byte array.

I am having some issues decoding the array being returned. The problem is that I get a lot of information back, but I don't know what to do with it. I will run you through what I have tried.

I am connecting to the game through port 20777 (standard port for the game):

using System.Net;
using System.Net.Sockets;

var Client = new UdpClient(20777); //Connectionport

```

<p>In this next piece of code, I get the information from the game:</p>

<pre class="lang-cs prettyprint-override"><code>var RemoteIP = new IPEndPoint(IPAddress.Any, 60240);

byte[] received = Client.EndReceive(res, ref RemoteIP);

</code>```

As you can see, the data from the game currently gets stored in a byte array.

Here comes the hard part (for me).

The data F1 2019 sends is packed in structs (from what I understand from their site). But I have no idea how I get the information out of the byte array and into the correct variables (e.g., what the current speed is, or in what gear the car is).

The information about the packets is on the website from codemasters:

https://forums.codemasters.com/topic/44592-f1-2019-udp-specification/

Now the actual question:

When I type this line of code:

short game_version = BitConverter.ToInt16(received, 0);

```

And I display it in a textbox, the variable game_version is now 2019.

I don't understand why, with the indexnumber 0, the bytes are converted in 2019.

And I don't know which index numbers to use to get each of the variables I want.

I hope someone can shine some light on this matter. On the codemasters forum everyone seems to know how to get the data from the byte array.

With kind regards.

答:
Okay so what I have found (Thanks to Jeremy) is that I need to get a structure out of the byte array. I followed these examples:
Example1
Example2

So Codemasters (Makers of F1 2019) are sending a byte array with all the information needed. They have converted structs in to the byte array. These structs contain all the information which the game sends out. So the thing that needs to happen is converting the byte array back to structs. Keep in mind that the structlayout from Codemasters need to stay the same, Else you won't get the right information in the right variable.

```<code>PacketHeader packetheader = ByteArrayToPacketHeader(received);

PacketHeader ByteArrayToPacketHeader(byte[] bytes)
{
   GCHandle handle = GCHandle.Alloc(bytes, GCHandleType.Pinned);
   PacketHeader stuff;
   try
   {
     stuff = (PacketHeader)Marshal.PtrToStructure(handle.AddrOfPinnedObject(), typeof(PacketHeader));
   }
   finally
   {
   handle.Free();
   }
   return stuff;
   }
</code>```

Currently the code above converts the incoming byte array (received) into the struct PacketHeader.
The struct looks like this:

```<code>public struct PacketHeader
    {
        public ushort m_packetFormat;         // 2019
        public byte m_gameMajorVersion;     // Game major version - "X.00"
        public byte m_gameMinorVersion;     // Game minor version - "1.XX"
        public byte m_packetVersion;        // Version of this packet type, all start from 1
        public byte m_packetId;             // Identifier for the packet type, see below
        public ulong m_sessionUID;           // Unique identifier for the session
        public float m_sessionTime;          // Session timestamp
        public uint m_frameIdentifier;      // Identifier for the frame the data was retrieved on
        public byte m_playerCarIndex;       // Index of player's car in the array
    };
</code>```

Every Packet (struct) with information has a PacketHeader. By converting the Header of each Packet you get the corresponding information in the variable: stuff.

Here you can see the information of the PacketHeader while debugging

I'll try to explain what the code does. I am not sure that I can explain it 100% because I don't understand it fully myself.

```<code>PacketHeader ByteArrayToPacketHeader(byte[] bytes)
{

}
</code>```

First I made a new method. This method will pull the struct out of the byte array.
Then I added the needed variables to the method:

```<code>GCHandle handle = GCHandle.Alloc(bytes, GCHandleType.Pinned);
PacketHeader stuff;
</code>```

I don't really understand the Handle but if it is what I think it is, it pins down the bytes so they can be converted correctly.

I also made a variable: stuff. In this variable the struct will be "stored".
In the next part I added the conversion code:

```<code>try
{
  stuff = (PacketHeader)Marshal.PtrToStructure(handle.AddrOfPinnedObject(), typeof(PacketHeader));
}
finally
{
   handle.Free();
}
return stuff;
</code>```

The conversion is done is this code.
When the PacketHeader is filled in, in the code, the struct layout will be followed and the variables will be filled.

The last part that needs to be done is calling this method.
I did this like this:

```<code>PacketHeader packetheader = ByteArrayToPacketHeader(received);
</code>```

Here you can see that I called the method PacketHeader and created a variable called packetheader. In this variable all the information will be stored.

Important!
Fill in the byte array you want to use in the received slot. This way the method will use that byte array.

If I now want to call a variable out of the PacketHeader struct I simply write this:

```<code>packetheader.m_packetFormat (example)
</code>```

Currently I am able to get the right information out of the PacketHeader but still not out of the other structs. But I am one step closer to completing my project!

I am sorry if the explanation is not entirely correct. (I am still learning myself).
Please contact me if you have any tips or notes about this explanation. I would like to know more about this subject.

Whith kind regards.

Title: F1 2019 UDP decoding

Body:
I am currently working on my own display for an F1 steering wheel.
F1 2019 (by codemasters) sends data through UDP. This data is stored in a byte array.

I am having some issues decoding the array being returned. The problem is that I get a lot of information back, but I don't know what to do with it. I will run you through what I have tried.

I am connecting to the game through port 20777 (standard port for the game):

using System.Net;
using System.Net.Sockets;

var Client = new UdpClient(20777); //Connectionport

In this next piece of code, I get the information from the game:

var RemoteIP = new IPEndPoint(IPAddress.Any, 60240);

byte[] received = Client.EndReceive(res, ref RemoteIP);

As you can see, the data from the game currently gets stored in a byte array.

Here comes the hard part (for me).

The data F1 2019 sends is packed in structs (from what I understand from their site). But I have no idea how I get the information out of the byte array and into the correct variables (e.g., what the current speed is, or in what gear the car is).

The information about the packets is on the website from codemasters:

https://forums.codemasters.com/topic/44592-f1-2019-udp-specification/

Now the actual question:

When I type this line of code:

short game_version = BitConverter.ToInt16(received, 0);

And I display it in a textbox, the variable game_version is now 2019.

I don't understand why, with the indexnumber 0, the bytes are converted in 2019.

And I don't know which index numbers to use to get each of the variables I want.

I hope someone can shine some light on this matter. On the codemasters forum everyone seems to know how to get the data from the byte array.

With kind regards.

Body:
Okay so what I have found (Thanks to Jeremy) is that I need to get a structure out of the byte array. I followed these examples:
Example1
Example2

So Codemasters (Makers of F1 2019) are sending a byte array with all the information needed. They have converted structs in to the byte array. These structs contain all the information which the game sends out. So the thing that needs to happen is converting the byte array back to structs. Keep in mind that the structlayout from Codemasters need to stay the same, Else you won't get the right information in the right variable.

PacketHeader packetheader = ByteArrayToPacketHeader(received);

PacketHeader ByteArrayToPacketHeader(byte[] bytes)
{
   GCHandle handle = GCHandle.Alloc(bytes, GCHandleType.Pinned);
   PacketHeader stuff;
   try
   {
     stuff = (PacketHeader)Marshal.PtrToStructure(handle.AddrOfPinnedObject(), typeof(PacketHeader));
   }
   finally
   {
   handle.Free();
   }
   return stuff;
   }

Currently the code above converts the incoming byte array (received) into the struct PacketHeader.
The struct looks like this:

public struct PacketHeader
    {
        public ushort m_packetFormat;         // 2019
        public byte m_gameMajorVersion;     // Game major version - "X.00"
        public byte m_gameMinorVersion;     // Game minor version - "1.XX"
        public byte m_packetVersion;        // Version of this packet type, all start from 1
        public byte m_packetId;             // Identifier for the packet type, see below
        public ulong m_sessionUID;           // Unique identifier for the session
        public float m_sessionTime;          // Session timestamp
        public uint m_frameIdentifier;      // Identifier for the frame the data was retrieved on
        public byte m_playerCarIndex;       // Index of player's car in the array
    };

Every Packet (struct) with information has a PacketHeader. By converting the Header of each Packet you get the corresponding information in the variable: stuff.

Here you can see the information of the PacketHeader while debugging

I'll try to explain what the code does. I am not sure that I can explain it 100% because I don't understand it fully myself.

PacketHeader ByteArrayToPacketHeader(byte[] bytes)
{

}

First I made a new method. This method will pull the struct out of the byte array.
Then I added the needed variables to the method:

GCHandle handle = GCHandle.Alloc(bytes, GCHandleType.Pinned);
PacketHeader stuff;

I don't really understand the Handle but if it is what I think it is, it pins down the bytes so they can be converted correctly.

I also made a variable: stuff. In this variable the struct will be "stored".
In the next part I added the conversion code:

try
{
  stuff = (PacketHeader)Marshal.PtrToStructure(handle.AddrOfPinnedObject(), typeof(PacketHeader));
}
finally
{
   handle.Free();
}
return stuff;

The conversion is done is this code.
When the PacketHeader is filled in, in the code, the struct layout will be followed and the variables will be filled.

The last part that needs to be done is calling this method.
I did this like this:

PacketHeader packetheader = ByteArrayToPacketHeader(received);

Here you can see that I called the method PacketHeader and created a variable called packetheader. In this variable all the information will be stored.

Important!
Fill in the byte array you want to use in the received slot. This way the method will use that byte array.

If I now want to call a variable out of the PacketHeader struct I simply write this:

packetheader.m_packetFormat (example)

Currently I am able to get the right information out of the PacketHeader but still not out of the other structs. But I am one step closer to completing my project!

I am sorry if the explanation is not entirely correct. (I am still learning myself).
Please contact me if you have any tips or notes about this explanation. I would like to know more about this subject.

Whith kind regards.


问:
Why can't I cast DateTime[] to object[]?
It seems that I can cast DateTime to object, so why can't I cast array DateTime[] to object[]?  I know this has something to do with value/reference types, but doesn't boxing allow me to do this?</p>

答: You can't cast DateTime[] to object[] because it would be unsafe. All arrays of reference types of the same length have the same layout in memory. DateTime is value type, and the array is "flat" (unboxed). You can't safely cast to object[] because the layout in memory is incompatible with object[].

ContentLicense: CC BY-SA 3.0


问:
django admin.autodiscover() import order on urls file
I cloned a sample app for django and run code inspection and found that admin.autodiscover is called before importing the views file, that's used for the patterns later:

```<code>from django.contrib import admin
from django.urls import path

admin.autodiscover()

import hello.views

urlpatterns = [
    path("", hello.views.index, name="index"),
    ...
]
</code>```

This triggers a PEP8 code style warning as the imports are not all on the top of the file.
I'm afraid that moving it may have unintended side effects. Is that the case?

答: According to docs you don't need to call the autodiscover function since django will call in when AdminConfig loads.

Body:
I cloned a sample app for django and run code inspection and found that admin.autodiscover is called before importing the views file, that's used for the patterns later:

from django.contrib import admin
from django.urls import path

admin.autodiscover()

import hello.views

urlpatterns = [
    path("", hello.views.index, name="index"),
    ...
]

This triggers a PEP8 code style warning as the imports are not all on the top of the file.
I'm afraid that moving it may have unintended side effects. Is that the case?


问:
PHP:Problems with Creating a Store Locator on Google Maps
Can anyone tell me whats wrong with the code?I am new to php. I followed the instruction on https://developers.google.com/maps/solutions/store-locator/clothing-store-locator but cant get any result when appending ?

```<code>lat=-33&lng=151.2&radius=100
</code>```

I also changed the code in storelocator.

PHP CODE :

```<code><?php
    require("phpsqlsearch_dbinfo.php");

    // Get parameters from URL
    $center_lat = $_GET["lat"];
    $center_lng = $_GET["lng"];
    $radius = $_GET["radius"];

    // Start XML file, create parent node
    $dom = new DOMDocument("1.0");
    $node = $dom->createElement("markers");
    $parnode = $dom->appendChild($node);

    // Opens a connection to a mySQL server
    $connection=mysqli_connect('localhost','root','');
    if (!$connection) {
        die("Not connected : " . mysql_error());
    }
    // Set the active mySQL database
    $db_selected = mysqli_select_db($connection,'fyp');
    if (!$db_selected) {
        die ("Can\'t use db : " . mysql_error());
    }

    // Search the rows in the markers table
    $query = sprintf("SELECT id, name, address, lat, lng, ( 3959 * acos( cos( radians('%s') ) * cos( radians( lat ) ) * cos( radians( lng ) - radians('%s') ) + sin( radians('%s') ) * sin( radians( lat ) ) ) ) AS distance FROM markers HAVING distance < '%s' ORDER BY distance LIMIT 0 , 20",
    mysqli_real_escape_string($connection,$center_lat),
    mysqli_real_escape_string($connection,$center_lng),
    mysqli_real_escape_string($connection,$center_lat),
    mysqli_real_escape_string($connection,$radius));
    $result = mysqli_query($connection,$query);
    $result = mysqli_query($connection,$query);
    if (!$result) {
        die("Invalid query: " . mysql_error());
    }

    // Iterate through the rows, adding XML nodes for each
    while ($row = $result->fetch_assoc()){
        $node = $dom->createElement("marker");
        $newnode = $parnode->appendChild($node);
        $newnode->setAttribute("id", $row['id']);
        $newnode->setAttribute("name", $row['name']);
        $newnode->setAttribute("address", $row['address']);
        $newnode->setAttribute("lat", $row['lat']);
        $newnode->setAttribute("lng", $row['lng']);
        $newnode->setAttribute("distance", $row['distance']);
    }
    echo $dom->saveXML();
?>
</code>```

答:
The SQL in your question takes user input directly and is potentially vulnerable to SQL injection despite the use of mysqli_real_escape_string so it would be advisable to use a prepared statement. There are comments throughout the following to give further guidance but this works in testing ( using different db connection of course )

```<code><?php

    /* only proceed if the required querystring parameters are present */
    if( isset( $_GET['lat'], $_GET['lng'], $_GET['radius'] ) ){

        # create db connection ( Object Orientated is less verbose! )
        require 'phpsqlsearch_dbinfo.php';
        $db = new mysqli( 'localhost', 'root', '', 'fyp' );

        # assign querystring parameters as variables
        $lat=floatval( $_GET['lat'] );
        $lng=floatval( $_GET['lng'] );
        $radius=intval( $_GET['radius'] );

        # only proceed if these variables are set
        if( $lat && $lng && $radius ){

            # sql with placeholders
            $sql='select
                    id,
                    name,
                    address,
                    lat,
                    lng,
                    ( 3959 * acos( cos( radians( ? ) ) * cos( radians( lat ) ) * cos( radians( lng ) - radians( ? ) ) + sin( radians( ? ) ) * sin( radians( lat ) ) ) ) as distance
                from markers
                    having distance < ?
                order by distance
                    limit 0 , 20';

            $stmt=$db->prepare( $sql );
            if( $stmt ){

                # bind the placeholders to the input variables & execute the query
                $stmt->bind_param('sssd', $lat, $lng, $lat, $radius );
                $res=$stmt->execute();

                # if there are results, generate the XML
                if( $res ){

                    $stmt->store_result();
                    $stmt->bind_result( $id, $name, $address, $lat, $lng, $distance );

                    /* create DOMDocument instance and find root or create new root node */
                    $dom=new DOMDocument;
                    $dom->formatOutput=true;
                    $dom->preserveWhitespace=true;
                    $root=$dom->createElement('markers');
                    $dom->appendChild( $root );

                    # process the recordset
                    while( $stmt->fetch() ){
                        $attribs=array(
                            'id'        =>  $id,
                            'name'      =>  $name,
                            'address'   =>  $address,
                            'lat'       =>  $lat,
                            'lng'       =>  $lng,
                            'distance'  =>  $distance
                        );
                        # create new marker node for each record
                        $marker=$dom->createElement('marker');
                        $root->appendChild( $marker );

                        # add the attributes for the marker node
                        foreach( $attribs as $attr => $value ){
                            $marker->setAttribute( $attr, $value );
                        }
                    }
                    $stmt->free_result();
                    $stmt->close();
                    $db->close();

                    # send the results
                    exit( $dom->saveXML() );
                }else{
                    # no results....
                }
            }else{
                exit('Failed to prepare SQL query');
            }
        }else{
            exit('Values for lat,lng or radius seem incorrect');
        }
    }else{
        exit('No latitude, longitude or radius...');
    }
?>
</code>```

Body:
Can anyone tell me whats wrong with the code?I am new to php. I followed the instruction on https://developers.google.com/maps/solutions/store-locator/clothing-store-locator but cant get any result when appending ?

lat=-33&lng=151.2&radius=100

I also changed the code in storelocator.

PHP CODE :

<?php
    require("phpsqlsearch_dbinfo.php");

    // Get parameters from URL
    $center_lat = $_GET["lat"];
    $center_lng = $_GET["lng"];
    $radius = $_GET["radius"];

    // Start XML file, create parent node
    $dom = new DOMDocument("1.0");
    $node = $dom->createElement("markers");
    $parnode = $dom->appendChild($node);

    // Opens a connection to a mySQL server
    $connection=mysqli_connect('localhost','root','');
    if (!$connection) {
        die("Not connected : " . mysql_error());
    }
    // Set the active mySQL database
    $db_selected = mysqli_select_db($connection,'fyp');
    if (!$db_selected) {
        die ("Can\'t use db : " . mysql_error());
    }

    // Search the rows in the markers table
    $query = sprintf("SELECT id, name, address, lat, lng, ( 3959 * acos( cos( radians('%s') ) * cos( radians( lat ) ) * cos( radians( lng ) - radians('%s') ) + sin( radians('%s') ) * sin( radians( lat ) ) ) ) AS distance FROM markers HAVING distance < '%s' ORDER BY distance LIMIT 0 , 20",
    mysqli_real_escape_string($connection,$center_lat),
    mysqli_real_escape_string($connection,$center_lng),
    mysqli_real_escape_string($connection,$center_lat),
    mysqli_real_escape_string($connection,$radius));
    $result = mysqli_query($connection,$query);
    $result = mysqli_query($connection,$query);
    if (!$result) {
        die("Invalid query: " . mysql_error());
    }

    // Iterate through the rows, adding XML nodes for each
    while ($row = $result->fetch_assoc()){
        $node = $dom->createElement("marker");
        $newnode = $parnode->appendChild($node);
        $newnode->setAttribute("id", $row['id']);
        $newnode->setAttribute("name", $row['name']);
        $newnode->setAttribute("address", $row['address']);
        $newnode->setAttribute("lat", $row['lat']);
        $newnode->setAttribute("lng", $row['lng']);
        $newnode->setAttribute("distance", $row['distance']);
    }
    echo $dom->saveXML();
?>

Body:
The SQL in your question takes user input directly and is potentially vulnerable to SQL injection despite the use of mysqli_real_escape_string so it would be advisable to use a prepared statement. There are comments throughout the following to give further guidance but this works in testing ( using different db connection of course )

<?php

    /* only proceed if the required querystring parameters are present */
    if( isset( $_GET['lat'], $_GET['lng'], $_GET['radius'] ) ){

        # create db connection ( Object Orientated is less verbose! )
        require 'phpsqlsearch_dbinfo.php';
        $db = new mysqli( 'localhost', 'root', '', 'fyp' );

        # assign querystring parameters as variables
        $lat=floatval( $_GET['lat'] );
        $lng=floatval( $_GET['lng'] );
        $radius=intval( $_GET['radius'] );

        # only proceed if these variables are set
        if( $lat && $lng && $radius ){

            # sql with placeholders
            $sql='select
                    id,
                    name,
                    address,
                    lat,
                    lng,
                    ( 3959 * acos( cos( radians( ? ) ) * cos( radians( lat ) ) * cos( radians( lng ) - radians( ? ) ) + sin( radians( ? ) ) * sin( radians( lat ) ) ) ) as distance
                from markers
                    having distance < ?
                order by distance
                    limit 0 , 20';

            $stmt=$db->prepare( $sql );
            if( $stmt ){

                # bind the placeholders to the input variables & execute the query
                $stmt->bind_param('sssd', $lat, $lng, $lat, $radius );
                $res=$stmt->execute();

                # if there are results, generate the XML
                if( $res ){

                    $stmt->store_result();
                    $stmt->bind_result( $id, $name, $address, $lat, $lng, $distance );

                    /* create DOMDocument instance and find root or create new root node */
                    $dom=new DOMDocument;
                    $dom->formatOutput=true;
                    $dom->preserveWhitespace=true;
                    $root=$dom->createElement('markers');
                    $dom->appendChild( $root );

                    # process the recordset
                    while( $stmt->fetch() ){
                        $attribs=array(
                            'id'        =>  $id,
                            'name'      =>  $name,
                            'address'   =>  $address,
                            'lat'       =>  $lat,
                            'lng'       =>  $lng,
                            'distance'  =>  $distance
                        );
                        # create new marker node for each record
                        $marker=$dom->createElement('marker');
                        $root->appendChild( $marker );

                        # add the attributes for the marker node
                        foreach( $attribs as $attr => $value ){
                            $marker->setAttribute( $attr, $value );
                        }
                    }
                    $stmt->free_result();
                    $stmt->close();
                    $db->close();

                    # send the results
                    exit( $dom->saveXML() );
                }else{
                    # no results....
                }
            }else{
                exit('Failed to prepare SQL query');
            }
        }else{
            exit('Values for lat,lng or radius seem incorrect');
        }
    }else{
        exit('No latitude, longitude or radius...');
    }
?>


问:
Default migrate table name rename
Since my project would like to create all the table into an old database,

It would be a problem if I use the default name from Django.

Is there any way to rename all the table like the JPG below?

答:
If you don't mind refer on this extending session and use it in django make abstract session class

if you want extends and change the default class name to use  instead of Session class to AbstractBaseSession

Title: Default migrate table name rename


问:
How to perform element-wise addition of n arrays without simply using a for loop in Java
As the title suggests, I am wondering how to use Java to sum n (where n is an arbitrary number greater than 2) arrays together, in a way that scales as n increases.

It's probably easiest to explain with an example. I used the following code to produce 20 length-5 arrays.

```<code>int n = 20;
int k = 5;

Random rand = new Random();
ArrayList<Integer[]> tuplesList = new ArrayList<>();

for (int i = 0; i < n; i++) {
    Integer[] tuple = new Integer[k];
    Arrays.setAll(tuple, index -> rand.nextInt(30));
    tuplesList.set(i, tuple);
}
</code>```

Now to the bit I am hoping can be improved. My current method of adding arrays together element-wise consists of simply looping through each array and adding their elements to a cumulative sum.

```<code>int[] cumSum = new int[k];

for (Integer[] tup : tuplesList) {
    Arrays.setAll(cumSum, ind -> cumSum[ind] + tup[ind]);
}

System.out.println(Arrays.toString(cumSum));
</code>```

This is of course trivial with only 20 arrays, but can be pretty time-consuming if we had 1,000,000. Is there a better way to do this? I have a vectorised way of summing two arrays element-wise using the Arrays.setAll function, but can this be genericised to adding n arrays together? Note that there is no requirement for the list of arrays don't have to be stored as an ArrayList<Integer[]>, that's just where my mind first went to.

P.S. If anyone wants some example numbers, here's what I got when I ran through my script:

```<code>[12, 20, 12, 22, 14]
[1, 10, 23, 9, 27]
[3, 2, 17, 24, 11]
[6, 11, 22, 5, 15]
[7, 26, 28, 27, 8]
[10, 23, 2, 15, 7]
[13, 5, 19, 3, 9]
[21, 23, 17, 16, 24]
[4, 20, 6, 14, 14]
[19, 4, 16, 24, 4]
[27, 14, 28, 0, 17]
[27, 20, 3, 8, 29]
[2, 21, 0, 24, 26]
[3, 2, 1, 23, 23]
[11, 11, 15, 26, 17]
[10, 26, 10, 8, 3]
[3, 27, 11, 13, 28]
[1, 29, 26, 3, 14]
[20, 1, 10, 29, 8]
[11, 25, 29, 28, 5]

Output:
[211, 320, 295, 321, 303]
</code>```

答:
If you have 1,000,000 arrays, you might want to think about saving memory by using a ArrayList<int[]> instead, or maybe an int[][].

If you did change to int[][], the absolute most efficient way to do it is like this:

```<code>static int[] sum(int[]... input) {
    int maxLen = 0;
    for (int[] arr : input)
        if (arr.length > maxLen)
            maxLen = arr.length;
    int[] sum = new int[maxLen];
    for (int[] arr : input)
        for (int i = 0; i < arr.length; i++)
            sum[i] += arr[i];
    return sum;
}
</code>```

The first half can of course be replaced with maxLen = input[0].length if it is absolutely guaranteed that all arrays are equal length. Since the performance impact of that code is minimal compared to the second half of the code, we might as well keep the first half, even with such a guarantee (defensive programming).

Test

```<code>System.out.println(Arrays.toString(sum(
        new int[] { 12, 20, 12, 22, 14 },
        new int[] { 1, 10, 23, 9, 27 },
        new int[] { 3, 2, 17, 24, 11 },
        new int[] { 6, 11, 22, 5, 15 },
        new int[] { 7, 26, 28, 27, 8 },
        new int[] { 10, 23, 2, 15, 7 },
        new int[] { 13, 5, 19, 3, 9 },
        new int[] { 21, 23, 17, 16, 24 },
        new int[] { 4, 20, 6, 14, 14 },
        new int[] { 19, 4, 16, 24, 4 },
        new int[] { 27, 14, 28, 0, 17 },
        new int[] { 27, 20, 3, 8, 29 },
        new int[] { 2, 21, 0, 24, 26 },
        new int[] { 3, 2, 1, 23, 23 },
        new int[] { 11, 11, 15, 26, 17 },
        new int[] { 10, 26, 10, 8, 3 },
        new int[] { 3, 27, 11, 13, 28 },
        new int[] { 1, 29, 26, 3, 14 },
        new int[] { 20, 1, 10, 29, 8 },
        new int[] { 11, 25, 29, 28, 5 }
)));
</code>```

Output

```<code>[211, 320, 295, 321, 303]
</code>```

Body:
As the title suggests, I am wondering how to use Java to sum n (where n is an arbitrary number greater than 2) arrays together, in a way that scales as n increases.

It's probably easiest to explain with an example. I used the following code to produce 20 length-5 arrays.

int n = 20;
int k = 5;

Random rand = new Random();
ArrayList<Integer[]> tuplesList = new ArrayList<>();

for (int i = 0; i < n; i++) {
    Integer[] tuple = new Integer[k];
    Arrays.setAll(tuple, index -> rand.nextInt(30));
    tuplesList.set(i, tuple);
}

Now to the bit I am hoping can be improved. My current method of adding arrays together element-wise consists of simply looping through each array and adding their elements to a cumulative sum.

int[] cumSum = new int[k];

for (Integer[] tup : tuplesList) {
    Arrays.setAll(cumSum, ind -> cumSum[ind] + tup[ind]);
}

System.out.println(Arrays.toString(cumSum));

This is of course trivial with only 20 arrays, but can be pretty time-consuming if we had 1,000,000. Is there a better way to do this? I have a vectorised way of summing two arrays element-wise using the Arrays.setAll function, but can this be genericised to adding n arrays together? Note that there is no requirement for the list of arrays don't have to be stored as an ArrayList<Integer[]>, that's just where my mind first went to.

P.S. If anyone wants some example numbers, here's what I got when I ran through my script:

[12, 20, 12, 22, 14]
[1, 10, 23, 9, 27]
[3, 2, 17, 24, 11]
[6, 11, 22, 5, 15]
[7, 26, 28, 27, 8]
[10, 23, 2, 15, 7]
[13, 5, 19, 3, 9]
[21, 23, 17, 16, 24]
[4, 20, 6, 14, 14]
[19, 4, 16, 24, 4]
[27, 14, 28, 0, 17]
[27, 20, 3, 8, 29]
[2, 21, 0, 24, 26]
[3, 2, 1, 23, 23]
[11, 11, 15, 26, 17]
[10, 26, 10, 8, 3]
[3, 27, 11, 13, 28]
[1, 29, 26, 3, 14]
[20, 1, 10, 29, 8]
[11, 25, 29, 28, 5]

Output:
[211, 320, 295, 321, 303]

Body:
If you have 1,000,000 arrays, you might want to think about saving memory by using a ArrayList<int[]> instead, or maybe an int[][].

If you did change to int[][], the absolute most efficient way to do it is like this:

static int[] sum(int[]... input) {
    int maxLen = 0;
    for (int[] arr : input)
        if (arr.length > maxLen)
            maxLen = arr.length;
    int[] sum = new int[maxLen];
    for (int[] arr : input)
        for (int i = 0; i < arr.length; i++)
            sum[i] += arr[i];
    return sum;
}

The first half can of course be replaced with maxLen = input[0].length if it is absolutely guaranteed that all arrays are equal length. Since the performance impact of that code is minimal compared to the second half of the code, we might as well keep the first half, even with such a guarantee (defensive programming).

Test

System.out.println(Arrays.toString(sum(
        new int[] { 12, 20, 12, 22, 14 },
        new int[] { 1, 10, 23, 9, 27 },
        new int[] { 3, 2, 17, 24, 11 },
        new int[] { 6, 11, 22, 5, 15 },
        new int[] { 7, 26, 28, 27, 8 },
        new int[] { 10, 23, 2, 15, 7 },
        new int[] { 13, 5, 19, 3, 9 },
        new int[] { 21, 23, 17, 16, 24 },
        new int[] { 4, 20, 6, 14, 14 },
        new int[] { 19, 4, 16, 24, 4 },
        new int[] { 27, 14, 28, 0, 17 },
        new int[] { 27, 20, 3, 8, 29 },
        new int[] { 2, 21, 0, 24, 26 },
        new int[] { 3, 2, 1, 23, 23 },
        new int[] { 11, 11, 15, 26, 17 },
        new int[] { 10, 26, 10, 8, 3 },
        new int[] { 3, 27, 11, 13, 28 },
        new int[] { 1, 29, 26, 3, 14 },
        new int[] { 20, 1, 10, 29, 8 },
        new int[] { 11, 25, 29, 28, 5 }
)));

Output

[211, 320, 295, 321, 303]


问:
Implementing Runnable in Enum
I am just playing around with enum and I wanted to see how it behaves under some crazy scenarios. Well, few java nerds might know that we can actually implement a interface in Enums.
So I came up with below code and wanted to know if the thread is created and called. I am curious if anyone can explain why the sysout is not printed. The below code is valid i.e compiles fine and executes. It just prints nothing. Can anyone explain clearly?

Also why values() method is not declared either in Enum class or Object class. Why the values method is provided by java compiler. Why the Sun/Oracle din't think of implementing it in Enum class.

```<code> package com.test;

  enum MyEnum implements Runnable{

      ENUM1,ENUM2,ENUM3;
      public void run() {

          System.out.println("Inside MyEnum"+Thread.currentThread().getName());
      }
}

public class EnumTesting {

    MyEnum en;

      public static void main(String[] args) {

    EnumTesting test = new EnumTesting();

          Thread t = new Thread(test.en);
        t.start();

    }
}
</code>```

答:
It just prints nothing. Can anyone explain clearly?

Note that you did not give en a value. Therefore, it is null. When null is passed to the constructor of Thread, the thread is documented to do nothing:

Parameters:

target - the object whose run method is invoked when this thread is started. If null, this classes run method does nothing.

You can do this instead:

```<code>new Thread(MyEnum.ENUM1).start();
</code>```

Why the Sun/Oracle din't think of implementing it in Enum class.

My speculation is that values, if it were in Enum<T>, should be abstract, but static methods can't be abstract.

Title: Implementing Runnable in Enum

Body:
I am just playing around with enum and I wanted to see how it behaves under some crazy scenarios. Well, few java nerds might know that we can actually implement a interface in Enums.
So I came up with below code and wanted to know if the thread is created and called. I am curious if anyone can explain why the sysout is not printed. The below code is valid i.e compiles fine and executes. It just prints nothing. Can anyone explain clearly?

Also why values() method is not declared either in Enum class or Object class. Why the values method is provided by java compiler. Why the Sun/Oracle din't think of implementing it in Enum class.

 package com.test;

  enum MyEnum implements Runnable{

      ENUM1,ENUM2,ENUM3;
      public void run() {

          System.out.println("Inside MyEnum"+Thread.currentThread().getName());
      }
}

public class EnumTesting {

    MyEnum en;

      public static void main(String[] args) {

    EnumTesting test = new EnumTesting();

          Thread t = new Thread(test.en);
        t.start();

    }
}

Body:
It just prints nothing. Can anyone explain clearly?

Note that you did not give en a value. Therefore, it is null. When null is passed to the constructor of Thread, the thread is documented to do nothing:

Parameters:

target - the object whose run method is invoked when this thread is started. If null, this classes run method does nothing.

You can do this instead:

new Thread(MyEnum.ENUM1).start();

Why the Sun/Oracle din't think of implementing it in Enum class.

My speculation is that values, if it were in Enum<T>, should be abstract, but static methods can't be abstract.


问:
How to get the weekday names using Intl?
I'd like to display in my i18n-ed app a list of the 7 weekdays:

```<code>Sunday, Monday, Tuesday... Saturday
</code>```

I rely on the Intl global object for formatting date/time but I can't find an easy way to get only the weekday names.

I thought I could add some days to the EPOCH time, to reach the first day of the week, but I'm failing to find a formatter printing just the weekday.

```<code>var date = new Date(0);
date.setDate(4 + day);
for (var i = 0; i < 7; i++) {
  var weekday = new Intl.DateTimeFormat(["en"], {
      weekday: "short" // ?? what should I put here
  }).format(date);
  console.log(weekday);
}
</code>```

Output:

```<code>Sunday, January 4, 1970
Monday, January 5, 1970
Tuesday, January 6, 1970
Wednesday, January 7, 1970
Thursday, January 8, 1970
Friday, January 9, 1970
Saturday, January 10, 1970
</code>```

Desired output:

```<code>Sunday
Monday
Tuesday
Wednesday
Thursday
Friday
Saturday
</code>```

I also would like to have a shorter version of the days, such as Sun, Mon, Tue....

Alternatively, is there a way to get the weekday strings from Intl? I tried to explore the object via console but I couldn't find them.

答:
 const weekdayDateMap = {
  Mon: new Date('2020-01-06T00:00:00.000Z'),
  Tue: new Date('2020-01-07T00:00:00.000Z'),
  Wed: new Date('2020-01-08T00:00:00.000Z'),
  Thu: new Date('2020-01-09T00:00:00.000Z'),
  Fri: new Date('2020-01-10T00:00:00.000Z'),
  Sat: new Date('2020-01-11T00:00:00.000Z'),
  Sun: new Date('2020-01-12T00:00:00.000Z'),
};
const shortWeekdays = Object.keys(weekdayDateMap);

const getDayOfWeek = (shortName, locale = 'en-US', length = 'short') =>
  new Intl.DateTimeFormat(locale, { weekday: length }).format(weekdayDateMap[shortName]);

const getDaysOfWeek = (locale = 'en-US', length = 'short') =>
  shortWeekdays.map(shortName => getDayOfWeek(shortName, locale, length));

console.log(getDayOfWeek('Mon', 'de-DE')) // "Mo"

console.log(getDaysOfWeek('de-DE')) // ["Mo", "Di", "Mi", "Do", "Fr", "Sa", "So"]```

Note:

If you're calling the Intl.DateTimeFormat formatter many times a second, it's more efficient to create the formatter once and re-use it.

Body:
I'd like to display in my i18n-ed app a list of the 7 weekdays:

Sunday, Monday, Tuesday... Saturday

I rely on the Intl global object for formatting date/time but I can't find an easy way to get only the weekday names.

I thought I could add some days to the EPOCH time, to reach the first day of the week, but I'm failing to find a formatter printing just the weekday.

var date = new Date(0);
date.setDate(4 + day);
for (var i = 0; i < 7; i++) {
  var weekday = new Intl.DateTimeFormat(["en"], {
      weekday: "short" // ?? what should I put here
  }).format(date);
  console.log(weekday);
}

Output:

Sunday, January 4, 1970
Monday, January 5, 1970
Tuesday, January 6, 1970
Wednesday, January 7, 1970
Thursday, January 8, 1970
Friday, January 9, 1970
Saturday, January 10, 1970

Desired output:

Sunday
Monday
Tuesday
Wednesday
Thursday
Friday
Saturday

I also would like to have a shorter version of the days, such as Sun, Mon, Tue....

Alternatively, is there a way to get the weekday strings from Intl? I tried to explore the object via console but I couldn't find them.

Body:
 const weekdayDateMap = {
  Mon: new Date('2020-01-06T00:00:00.000Z'),
  Tue: new Date('2020-01-07T00:00:00.000Z'),
  Wed: new Date('2020-01-08T00:00:00.000Z'),
  Thu: new Date('2020-01-09T00:00:00.000Z'),
  Fri: new Date('2020-01-10T00:00:00.000Z'),
  Sat: new Date('2020-01-11T00:00:00.000Z'),
  Sun: new Date('2020-01-12T00:00:00.000Z'),
};
const shortWeekdays = Object.keys(weekdayDateMap);

const getDayOfWeek = (shortName, locale = 'en-US', length = 'short') =>
  new Intl.DateTimeFormat(locale, { weekday: length }).format(weekdayDateMap[shortName]);

const getDaysOfWeek = (locale = 'en-US', length = 'short') =>
  shortWeekdays.map(shortName => getDayOfWeek(shortName, locale, length));

console.log(getDayOfWeek('Mon', 'de-DE')) // "Mo"

console.log(getDaysOfWeek('de-DE')) // ["Mo", "Di", "Mi", "Do", "Fr", "Sa", "So"]

Note:

If you're calling the Intl.DateTimeFormat formatter many times a second, it's more efficient to create the formatter once and re-use it.


问:
Jetty how to detect if HTTP connection was closed by client
Problem

Jetty 9 based server is processing time consuming (30-60 sec) and computation heavy (~20 threads involved in parallel processing) requests.

Due to interactive nature, client may cancel HTTP request after few seconds and send a new one.

It is desirable to cancel computation immediately if connection has been closed by client.

Unsuccessful attempts

In case of closed HTTP connection, attempt to write to response output stream would trigger IOException. Though, in case of this application, HTTP status depends on result of whole computation so it is not possible to write anything back to socket in the middle of processing. Thus, this option is not applicable.

Jetty have handy HttpConnection.getCurrentConnection() method which can be used to get references to some internal classes related to HTTP connection including underlying SocketChannel. Though I haven't found a way to check liveliness of connection though SocketChannel or other Jetty's classes related to connection.

答:
The best choice is to use the javax.servlet.AsyncContext and its javax.servlet.AsyncListener.

Start with a call to java.servlet.HttpServletRequest.startAsync() to get the AsyncContext.

Then add a custom AsyncListener of your own, don't forget to also set a timeout on your AsyncContext (as its existence overrides the default Idle Timeout mechanism)

You'll get events that mean something useful to you ...

onComplete - the processing has completed

onError - the processing has failed (such as a unexpected connection termination)

onTimeout - the AsyncContext timeout has fired

This is the mechanism that the Servlet API has provided for exactly your situation: computation or backend heavy processing during an active request that might be terminated early.


问:
Its my first servlet program and I have issues
My index looks like this:

```<code><HTML>
<head>
<title> JSP Servlet Example</title>
</head>
<body>

<div align="center" style="margin-top: 50px;">

    <form action="ServletManager">
        Please enter your Username:  <input type="text" name="username" size="20px"> <br>
        Please enter your Password:  <input type="text" name="password" size="20px"> <br><br>
        <input type="submit" value="submit">
    </form>

</div>

</body>
</HTML>
</code>```

My servlet:

```<code>package helloweb;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

public class ServletManager extends HttpServlet {protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            // reading the user input
    String username = request.getParameter("username");
    String password = request.getParameter("password");
    PrintWriter out = response.getWriter();
    out.println (
        "<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" +" +
        "http://www.w3.org/TR/html4/loose.dtd\">\n" +
        "<html> \n" +
        "<head> \n" +
        "<meta http-equiv=\"Content-Type\" content=\"text/html; " +
        "charset=ISO-8859-1\"> \n" +
        "<title> JSP Servlet Example  </title> \n" +
        "</head> \n" +
        "<body> <div align='center'> \n" +
            "<style= \"font-size=\"12px\" color='black'\"" + "\">" +
            "Username: " + username + " <br> " +
            "Password: " + password +
            "</font></body> \n" +
        "</html>"
            );
        }
    }
</code>```

My XML:

http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
        version="3.0">
    JSPServletExample

```<code>    <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>
<servlet>

    <servlet-name>Hello</servlet-name>
    <servlet-class>helloweb.ServletManager</servlet-class>

</servlet>
<servlet-mapping>

    <servlet-name>Hello</servlet-name>
    <url-pattern>/ServletManager.java</url-pattern>

</servlet-mapping>
</code>```

Here is my issue:

Firefox can’t find the file at /C:/Users/HP/IdeaProjects/ourdemo                                             /web/ServletManager?username=hello&password=hello.`

I host at the tomcat 7 server.

The first page appears. I type in the username and password, and I get this.
Please help.

答:
Please change the url pattern change this in web.xml from /ServletManager.java to /ServletManager and try
https://javabelazy.blogspot.com/2010/02/student-registration-form-in-java.html (Working code)</p>

Body:
My index looks like this:

<title> JSP Servlet Example</title>

    <form action="ServletManager">
        Please enter your Username:  <input type="text" name="username" size="20px">

        Please enter your Password:  <input type="text" name="password" size="20px">

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

My servlet:

package helloweb;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

public class ServletManager extends HttpServlet {protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            // reading the user input
    String username = request.getParameter("username");
    String password = request.getParameter("password");
    PrintWriter out = response.getWriter();
    out.println (
        "<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" +" +
        "http://www.w3.org/TR/html4/loose.dtd\">\n" +
        " \n" +
        " \n" +
        "<meta http-equiv=\"Content-Type\" content=\"text/html; " +
        "charset=ISO-8859-1\"> \n" +
        "<title> JSP Servlet Example  </title> \n" +
        " \n" +
        "
 \n" +
            "


问:
Can't send private messages from my discord bot to user?
I want to send a private message to a specific user with my discord bot. I am using discord==1.0.1
discord.py==1.3.1. I already tried using the docs (https://discordpy.readthedocs.io/en/latest/api.html?highlight=private%20message#discord.DMChannel) but i dont understand that. I tried following code, which didnt worked:</p>

```<code>@client.command()
async def cmds(ctx):
    embed = discord.Embed(title='Discord Server Befehle',
                          description='Description',
                          color=0x374883)

    [...]

    msg = await ctx.send(embed=embed)
    await ctx.author.create_dm('Hi')
    print(f'{command_prefix}help ausgeführt von {ctx.author}')
</code>```

答:
Try using the send function instead of the create_dm. create_dm only creates the channel  between two users which discord does automatically as far as i know.

according to documentation

```<code>This should be rarely called, as this is done transparently for most people.
</code>```

so it should be

```<code>ctx.author.send('Hi')
</code>```

Body:
I want to send a private message to a specific user with my discord bot. I am using discord==1.0.1
discord.py==1.3.1. I already tried using the docs (https://discordpy.readthedocs.io/en/latest/api.html?highlight=private%20message#discord.DMChannel) but i dont understand that. I tried following code, which didnt worked:

@client.command()
async def cmds(ctx):
    embed = discord.Embed(title='Discord Server Befehle',
                          description='Description',
                          color=0x374883)

    [...]

    msg = await ctx.send(embed=embed)
    await ctx.author.create_dm('Hi')
    print(f'{command_prefix}help ausgeführt von {ctx.author}')

Body:
Try using the send function instead of the create_dm. create_dm only creates the channel  between two users which discord does automatically as far as i know.

according to documentation

This should be rarely called, as this is done transparently for most people.

so it should be

ctx.author.send('Hi')


问:
Trouble in knitting to pdf in R
I have the following code which runs when the code block is executed:

```<code>library(boot)
data("FishMercury")
# part a
hist(FishMercury$Mercury)
boxplot(FishMercury$Mercury)

#part b

boot.fish = numeric(10^4)
for(i in 1: 10^4)
{
  boot.fish[i] = mean(sample(FishMercury$Mercury, 10, replace = TRUE))
}
boot.fishMean = mean(boot.fish)
boot.fishSD = sd(boot.fish)

quantile(boot.fish, .025, .0975)

#part c
FishMercury2 <- FishMercury[FishMercury < max(FishMercury)]
for (i in 1:n){boot.mean[i] <- mean(sample(FishMercury2, length(FishMercury2),replace = TRUE))}
mean(boot.mean)
sd(boot.mean)
quantile(boot.mean, prob= c(.025,.975))
</code>```

However when I try to knit to a pdf I get the error:

```<code>Error in eval(expr, envir, enclos) : object 'boot.mean' not found
Calls: <Anonymous> ... handle -> withCallingHandlers -> withVisible -> eval -> eval
Execution halted
</code>```

Can anyone help me resolve this issue??

答:
There are a few things missing in #part c of your code here, which lead to errors.

```<code>
#part c

FishMercury2 <- FishMercury[ FishMercury < max( FishMercury)]

# first error, you use an uninitiated object n
n <- length( FishMercury2)
# second error: you are replacing elements in boot.mean, but never initiated boot.mean.
# so, for example, create one:
boot.mean <- numeric( length = n)

for (i in 1: n){
  boot.mean[i] <- mean(sample(FishMercury2, length(FishMercury2),replace = TRUE))
  }

mean(boot.mean)
sd(boot.mean)
quantile(boot.mean, prob= c(.025,.975))

</code>```

Title: Trouble in knitting to pdf in R

Body:
I have the following code which runs when the code block is executed:

library(boot)
data("FishMercury")
# part a
hist(FishMercury$Mercury)
boxplot(FishMercury$Mercury)

#part b

boot.fish = numeric(10^4)
for(i in 1: 10^4)
{
  boot.fish[i] = mean(sample(FishMercury$Mercury, 10, replace = TRUE))
}
boot.fishMean = mean(boot.fish)
boot.fishSD = sd(boot.fish)

quantile(boot.fish, .025, .0975)

#part c
FishMercury2 <- FishMercury[FishMercury < max(FishMercury)]
for (i in 1:n){boot.mean[i] <- mean(sample(FishMercury2, length(FishMercury2),replace = TRUE))}
mean(boot.mean)
sd(boot.mean)
quantile(boot.mean, prob= c(.025,.975))

However when I try to knit to a pdf I get the error:

Error in eval(expr, envir, enclos) : object 'boot.mean' not found
Calls: <Anonymous> ... handle -> withCallingHandlers -> withVisible -> eval -> eval
Execution halted

Can anyone help me resolve this issue??

Body:
There are a few things missing in #part c of your code here, which lead to errors.

#part c

FishMercury2 <- FishMercury[ FishMercury < max( FishMercury)]

# first error, you use an uninitiated object n
n <- length( FishMercury2)
# second error: you are replacing elements in boot.mean, but never initiated boot.mean.
# so, for example, create one:
boot.mean <- numeric( length = n)

for (i in 1: n){
  boot.mean[i] <- mean(sample(FishMercury2, length(FishMercury2),replace = TRUE))
  }

mean(boot.mean)
sd(boot.mean)
quantile(boot.mean, prob= c(.025,.975))


问:
Evil code from the Python standard library
So, we have had this: The 1000% Speedup, or, the stdlib sucks. It demonstrates a rather bad bug that is probably costing the universe a load of cycles even as we speak. It's fixed now, which is great.

So what parts of the standard library have you noticed to be evil?

I would expect all the responsible people to match up an answer with a bug report (if suitable) and a patch (if superman).

答: The rexec module has so many security holes in it that it's almost useless.</p>

OwnerDisplayName: Ali A

OwnerDisplayName: Jason Baker

ContentLicense: CC BY-SA 2.5


问:
Order a table by a key in an array of json (stored as jsonb) in Postgres
I have a postgres which has a jsonb column which is an array of jsons.

```<code>id  array_json
123 [{"end_time": 22, "start_time": 21}]
124 [{"end_time": 22, "start_time": 9}, {"end_time": 20, "start_time": 0}]
126 [{"end_time": 22, "start_time": 0}]
125 [{"end_time": 22, "start_time": 1}, {"end_time": 20, "start_time": 6}]
</code>```

I want to order these by the "start_time". A row has an array of jsons. In such cases, the ordering has to be considering the earliest start time in the entire array. If two arrays have the same start time, it doesnt matter which one comes first.
The final result should be:

```<code>id  array_json
126 [{"end_time": 22, "start_time": 0}]
124 [{"end_time": 22, "start_time": 9}, {"end_time": 20, "start_time": 0}]
125 [{"end_time": 22, "start_time": 1}, {"end_time": 20, "start_time": 6}]
123 [{"end_time": 22, "start_time": 21}]
</code>```

I've created a fiddle of this table. How should this be done?

答:
This will work I think:

```<code>select id, array_json from the_table,
lateral (select min((d->>'start_time')::int) x from jsonb_array_elements(array_json) d) t(x)
order by x
</code>```

Best regards,

Bjarni

Body:
I have a postgres which has a jsonb column which is an array of jsons.

id  array_json
123 [{"end_time": 22, "start_time": 21}]
124 [{"end_time": 22, "start_time": 9}, {"end_time": 20, "start_time": 0}]
126 [{"end_time": 22, "start_time": 0}]
125 [{"end_time": 22, "start_time": 1}, {"end_time": 20, "start_time": 6}]

I want to order these by the "start_time". A row has an array of jsons. In such cases, the ordering has to be considering the earliest start time in the entire array. If two arrays have the same start time, it doesnt matter which one comes first.
The final result should be:

id  array_json
126 [{"end_time": 22, "start_time": 0}]
124 [{"end_time": 22, "start_time": 9}, {"end_time": 20, "start_time": 0}]
125 [{"end_time": 22, "start_time": 1}, {"end_time": 20, "start_time": 6}]
123 [{"end_time": 22, "start_time": 21}]

I've created a fiddle of this table. How should this be done?

Body:
This will work I think:

select id, array_json from the_table,
lateral (select min((d->>'start_time')::int) x from jsonb_array_elements(array_json) d) t(x)
order by x

Best regards,

Bjarni


问:
Using statsd-bridge to push data to prometheus from statsd
I have been using statsd in my python django application for measuring different metrics. Now we have been integrating prometheus io so that we can query those metrics at later point of time. In this context, I have gone through statsd_bridge https://github.com/prometheus/statsd_bridge. I have been using it like following:

./statsd_bridge  -statsd.listen-address="localhost:9090" -statsd.mapping-config="" -web.listen-address="a.b.c.d:8125" -web.telemetry-path="/metrics"

In the above, statsd is running on a.b.c.d on port 8125 and I have set up prometheus on my local machine. But the problem is that I cannot see any of statsd metrics in prometheus i.e. http://localhost:9090/metrics. So if anyone helps me in figuring out what mistakes I am doing here I will be really grateful.

答:
maybe you can use other way, like pushgateway

some code

```<code>from prometheus_client import CollectorRegistry, Gauge, push_to_gateway

registry = CollectorRegistry()
g = Gauge('job_last_success_unixtime', 'Last time a batch job successfully finished', registry=registry)
g.set_to_current_time()
push_to_gateway('localhost:9091', job='batchA', registry=registry)
</code>```

Body:
maybe you can use other way, like pushgateway

some code

from prometheus_client import CollectorRegistry, Gauge, push_to_gateway

registry = CollectorRegistry()
g = Gauge('job_last_success_unixtime', 'Last time a batch job successfully finished', registry=registry)
g.set_to_current_time()
push_to_gateway('localhost:9091', job='batchA', registry=registry)


问:
UIAlertView not working is Xamarin.iOS
My Xamarin.native project targetting Android & iOS. I am not able to show Alert in Xamarin.iOS; thou the following code works fine on Xamarin.Android.

In PCL:

```<code>public interface IDialogProvider
{
    void ShowMessage(string title, string message, string dismissButtonTitle, Action dismissed);
    void Confirm(string title, string message, string okButtonTitle, string dismissButtonTitle, Action confirmed, Action dismissed);
}
</code>```

======================================

In Xamarin.iOS

```<code>public class TouchDialogProvider : IDialogProvider
{
    public void ShowMessage(string title, string message, string dismissButtonTitle, Action dismissed)
    {
        var alert = UIAlertController.Create(title, message, UIAlertControllerStyle.Alert);
        alert.AddAction(UIAlertAction.Create(dismissButtonTitle, UIAlertActionStyle.Default,
        action => { if (null != dismissed) { dismissed.Invoke(); } }));
    }

public void Confirm(string title, string message, string okButtonTitle, string dismissButtonTitle, Action confirmed, Action dismissed)
{
    var alertView = new UIAlertView(title, message, null, dismissButtonTitle, okButtonTitle);
    alertView.Clicked += (object sender, UIButtonEventArgs e) => {
    if (e.ButtonIndex == 1 & null != confirmed)
        { confirmed.Invoke(); }
        if (e.ButtonIndex == 0 & null != dismissed)
            { dismissed.Invoke(); } };
    alertView.Show();
    }
}
</code>```

答:
Please try to use below one to create alert, I always use this one only.</p>

```<code>    void CreateAlert(string title, string buttonTitle, RelayCommand buttonCommand, string error, RelayCommand closeButtonCommand = null)
    {
        var elements = new List<InfoDialogElement>{
            new InfoDialogElement
            {
                Type = InfoDialogElementTypeEnum.Text,
                MarginTop = 25,
                MarginBottom = 25,
                SideMargin = 0,
                Info = error,
                TextSize = 16,
                Font = FontStyleEnum.OoredooHeavy
            }
        };
        var dialog = new OoInfoDialog(title, buttonTitle, buttonCommand, elements);
        if (closeButtonCommand != null)
            dialog.CloseCommand = closeButtonCommand;

        if (DialogBeingPresented != null)
            DialogBeingPresented.PresentDialog(dialog, UIColor.FromRGBA(0, 0, 0, 230));
        else
        {
            var parentViewController = AppDelegate.Current.Window.RootViewController;
            if (parentViewController != null)
            {
                if (parentViewController is UINavigationController)
                {
                    (parentViewController as UINavigationController).TopViewController.PresentDialog(dialog, UIColor.FromRGBA(0, 0, 0, 230));
                } else
                {
                    parentViewController.PresentDialog(dialog, UIColor.FromRGBA(0, 0, 0, 230));
                }
            }
        }
    }
</code>```

Title: UIAlertView not working is Xamarin.iOS

Body:
My Xamarin.native project targetting Android & iOS. I am not able to show Alert in Xamarin.iOS; thou the following code works fine on Xamarin.Android.

In PCL:

public interface IDialogProvider
{
    void ShowMessage(string title, string message, string dismissButtonTitle, Action dismissed);
    void Confirm(string title, string message, string okButtonTitle, string dismissButtonTitle, Action confirmed, Action dismissed);
}

======================================

In Xamarin.iOS

public class TouchDialogProvider : IDialogProvider
{
    public void ShowMessage(string title, string message, string dismissButtonTitle, Action dismissed)
    {
        var alert = UIAlertController.Create(title, message, UIAlertControllerStyle.Alert);
        alert.AddAction(UIAlertAction.Create(dismissButtonTitle, UIAlertActionStyle.Default,
        action => { if (null != dismissed) { dismissed.Invoke(); } }));
    }

public void Confirm(string title, string message, string okButtonTitle, string dismissButtonTitle, Action confirmed, Action dismissed)
{
    var alertView = new UIAlertView(title, message, null, dismissButtonTitle, okButtonTitle);
    alertView.Clicked += (object sender, UIButtonEventArgs e) => {
    if (e.ButtonIndex == 1 & null != confirmed)
        { confirmed.Invoke(); }
        if (e.ButtonIndex == 0 & null != dismissed)
            { dismissed.Invoke(); } };
    alertView.Show();
    }
}

Body:
Please try to use below one to create alert, I always use this one only.

    void CreateAlert(string title, string buttonTitle, RelayCommand buttonCommand, string error, RelayCommand closeButtonCommand = null)
    {
        var elements = new List<InfoDialogElement>{
            new InfoDialogElement
            {
                Type = InfoDialogElementTypeEnum.Text,
                MarginTop = 25,
                MarginBottom = 25,
                SideMargin = 0,
                Info = error,
                TextSize = 16,
                Font = FontStyleEnum.OoredooHeavy
            }
        };
        var dialog = new OoInfoDialog(title, buttonTitle, buttonCommand, elements);
        if (closeButtonCommand != null)
            dialog.CloseCommand = closeButtonCommand;

        if (DialogBeingPresented != null)
            DialogBeingPresented.PresentDialog(dialog, UIColor.FromRGBA(0, 0, 0, 230));
        else
        {
            var parentViewController = AppDelegate.Current.Window.RootViewController;
            if (parentViewController != null)
            {
                if (parentViewController is UINavigationController)
                {
                    (parentViewController as UINavigationController).TopViewController.PresentDialog(dialog, UIColor.FromRGBA(0, 0, 0, 230));
                } else
                {
                    parentViewController.PresentDialog(dialog, UIColor.FromRGBA(0, 0, 0, 230));
                }
            }
        }
    }


问:
Check for existing conda environment in Makefile
I am creating a conda environment inside a Makefile. However, if this environment was created already, I'd like to skip that step. How can I check the following:

Is there already an environment with that name? Would simple directory check suffice?

Is this environment already activated? Optional. It does not hurt if env is activated twice, I think.

```<code>CONDA_ENV_NAME := myname

ifeq (,$(shell which conda))
    HAS_CONDA=False
else
    HAS_CONDA=True
    CONDA_ACTIVATE=source $$(conda info --base)/etc/profile.d/conda.sh ; conda activate ; conda activate
endif

environment:
ifeq (True,$(HAS_CONDA))
    @echo ">>> Detected conda, creating conda environment."
    ## Here I'd like to check if this environment already exists
    conda env create -f environment.yml -n $(CONDA_ENV_NAME)
    ## ... and if the env should be activated (optional)
    $(CONDA_ACTIVATE) $(CONDA_ENV_NAME)
else
    @echo ">>> Install conda first."
endif

</code>```

答:
I solved the problem with the following:</p>

```<code>ifeq (,$(shell which conda))
    HAS_CONDA=False
else
    HAS_CONDA=True
    ENV_DIR=$(shell conda info --base)
    MY_ENV_DIR=$(ENV_DIR)/envs/$(CONDA_ENV_NAME)
    CONDA_ACTIVATE=source $$(conda info --base)/etc/profile.d/conda.sh ; conda activate ; conda activate
endif

environment:
ifeq (True,$(HAS_CONDA))
ifneq ("$(wildcard $(MY_ENV_DIR))","") # check if the directory is there
    @echo ">>> Found $(CONDA_ENV_NAME) environment in $(MY_ENV_DIR). Skipping installation..."
else
    @echo ">>> Detected conda, but $(CONDA_ENV_NAME) is missing in $(ENV_DIR). Installing ..."
    conda env create -f environment.yml -n $(CONDA_ENV_NAME)
endif
else
    @echo ">>> Install conda first."
    exit
endif
</code>```

Body:
I am creating a conda environment inside a Makefile. However, if this environment was created already, I'd like to skip that step. How can I check the following:

Is there already an environment with that name? Would simple directory check suffice?

Is this environment already activated? Optional. It does not hurt if env is activated twice, I think.

CONDA_ENV_NAME := myname

ifeq (,$(shell which conda))
    HAS_CONDA=False
else
    HAS_CONDA=True
    CONDA_ACTIVATE=source $$(conda info --base)/etc/profile.d/conda.sh ; conda activate ; conda activate
endif

environment:
ifeq (True,$(HAS_CONDA))
    @echo ">>> Detected conda, creating conda environment."
    ## Here I'd like to check if this environment already exists
    conda env create -f environment.yml -n $(CONDA_ENV_NAME)
    ## ... and if the env should be activated (optional)
    $(CONDA_ACTIVATE) $(CONDA_ENV_NAME)
else
    @echo ">>> Install conda first."
endif

Body:
I solved the problem with the following:

ifeq (,$(shell which conda))
    HAS_CONDA=False
else
    HAS_CONDA=True
    ENV_DIR=$(shell conda info --base)
    MY_ENV_DIR=$(ENV_DIR)/envs/$(CONDA_ENV_NAME)
    CONDA_ACTIVATE=source $$(conda info --base)/etc/profile.d/conda.sh ; conda activate ; conda activate
endif

environment:
ifeq (True,$(HAS_CONDA))
ifneq ("$(wildcard $(MY_ENV_DIR))","") # check if the directory is there
    @echo ">>> Found $(CONDA_ENV_NAME) environment in $(MY_ENV_DIR). Skipping installation..."
else
    @echo ">>> Detected conda, but $(CONDA_ENV_NAME) is missing in $(ENV_DIR). Installing ..."
    conda env create -f environment.yml -n $(CONDA_ENV_NAME)
endif
else
    @echo ">>> Install conda first."
    exit
endif


问:
Foreach Binding on a Knockout Computed Observable
I have an observableArray, scheduleDays, that looks like below. It represents 1 week of appointments for a selected simulator game.

If the user selects 2 simulator schedules to view, the returned view model looks like this:

```<code>this.scheduleDays = ko.observableArray([
  new ScheduleDay(1, 'Sunday', '02/09/2020', 1111, []),
  new ScheduleDay(4, 'Sunday', '02/09/2020', 2222, []),
  new ScheduleDay(2, 'Monday', '02/10/2020', 1111, []),
  new ScheduleDay(5, 'Monday', '02/10/2020', 2222, []),
  new ScheduleDay(3, 'Tuesday', '02/10/2020', 1111, []),
  new ScheduleDay(6, 'Tuesday', '02/10/2020', 2222, [])
]);
</code>```

That causes the UI to display the results like this:

But what I want is for the data to be sorted by simulator, then by date like this:

The obvious solution is sort it but for learning purposes, I wanted to try solving it by grouping the view models by simulator. So I added this:

```<code>this.groupedScheduleDays = ko.computed(function() {
var result = {};
var original = self.scheduleDays();
console.log(original);

for (var i = 0; i < original.length; i++) {
  var item = original[i];
  result[item.simulatorId] = result[item.simulatorId] || [];
  result[item.simulatorId].push(item);
}

return result;
});
</code>```

And that produced this:

That's what I was expecting. Here is what I came up with so far https://jsfiddle.net/krob636/o48unhsg/58/. My question is how can I bind groupedScheduleDays in a foreach?

答:
You can use Object.keys to get the grouped items, and use a nested foreach:

```<code><div data-bind="foreach: Object.keys(groupedScheduleDays())">
  <div data-bind="foreach: $parent.groupedScheduleDays()[$data]">
    <div class="row">
      <div class="col-2">
        <span data-bind="text: dayOfWeekName"></span>
      </div>
      <div class="col-2">
        <span data-bind="text: simulatorId"></span>
      </div>
    </div>
  </div>
</div>
</code>```

Fiddle: https://jsfiddle.net/thebluenile/L82emswo/

Also, remember that your day properties are observables, so this: result[item.simulatorId] doesn't work, or rather, won't have the desired effect; since observables are technically functions, the actual function will be used as the key. You need to unwrap the observable: result[item.simulatorId()].

Body:
I have an observableArray, scheduleDays, that looks like below. It represents 1 week of appointments for a selected simulator game.

If the user selects 2 simulator schedules to view, the returned view model looks like this:

this.scheduleDays = ko.observableArray([
  new ScheduleDay(1, 'Sunday', '02/09/2020', 1111, []),
  new ScheduleDay(4, 'Sunday', '02/09/2020', 2222, []),
  new ScheduleDay(2, 'Monday', '02/10/2020', 1111, []),
  new ScheduleDay(5, 'Monday', '02/10/2020', 2222, []),
  new ScheduleDay(3, 'Tuesday', '02/10/2020', 1111, []),
  new ScheduleDay(6, 'Tuesday', '02/10/2020', 2222, [])
]);

That causes the UI to display the results like this:

But what I want is for the data to be sorted by simulator, then by date like this:

The obvious solution is sort it but for learning purposes, I wanted to try solving it by grouping the view models by simulator. So I added this:

this.groupedScheduleDays = ko.computed(function() {
var result = {};
var original = self.scheduleDays();
console.log(original);

for (var i = 0; i < original.length; i++) {
  var item = original[i];
  result[item.simulatorId] = result[item.simulatorId] || [];
  result[item.simulatorId].push(item);
}

return result;
});

And that produced this:

That's what I was expecting. Here is what I came up with so far https://jsfiddle.net/krob636/o48unhsg/58/. My question is how can I bind groupedScheduleDays in a foreach?

Body:
You can use Object.keys to get the grouped items, and use a nested foreach:

<div data-bind="foreach: Object.keys(groupedScheduleDays())">
  <div data-bind="foreach: $parent.groupedScheduleDays()[$data]">
    <div class="row">
      <div class="col-2">
        <span data-bind="text: dayOfWeekName"></span>
      </div>
      <div class="col-2">
        <span data-bind="text: simulatorId"></span>
      </div>
    </div>
  </div>
</div>

Fiddle: https://jsfiddle.net/thebluenile/L82emswo/

Also, remember that your day properties are observables, so this: result[item.simulatorId] doesn't work, or rather, won't have the desired effect; since observables are technically functions, the actual function will be used as the key. You need to unwrap the observable: result[item.simulatorId()].


问:
Not able to install shinytest
I am facing some problem while installing shinytest in my laptop. Getting below error message. Can anyone help me here?</p>

```<code>> install.packages("shinytest")
Installing package into ‘E:/Users/AAAA/BBB/R/win-library/3.6’
(as ‘lib’ is unspecified)
also installing the dependencies ‘ps’, ‘desc’, ‘pkgbuild’, ‘png’, ‘rematch2’, ‘processx’, ‘curl’, ‘pkgload’, ‘praise’, ‘showimage’, ‘debugme’, ‘parsedate’, ‘pingr’, ‘callr’, ‘httr’, ‘testthat’, ‘webdriver’, ‘rstudioapi’

  There are binary versions available but the source versions are later:
      binary source needs_compilation
ps     1.3.0  1.3.2              TRUE
callr  3.4.1  3.4.2             FALSE
</code>```

答:
It looks like some dependencies ('ps', 'callr') may be out of date.
Try running update.packages() before installing 'shinytest'.

Alternatively, you may try to install all the listed dependencies on by one ('ps', 'desc', 'pkgbuild', 'png',...)

Title: Not able to install shinytest

Body:
I am facing some problem while installing shinytest in my laptop. Getting below error message. Can anyone help me here?

> install.packages("shinytest")
Installing package into ‘E:/Users/AAAA/BBB/R/win-library/3.6’
(as ‘lib’ is unspecified)
also installing the dependencies ‘ps’, ‘desc’, ‘pkgbuild’, ‘png’, ‘rematch2’, ‘processx’, ‘curl’, ‘pkgload’, ‘praise’, ‘showimage’, ‘debugme’, ‘parsedate’, ‘pingr’, ‘callr’, ‘httr’, ‘testthat’, ‘webdriver’, ‘rstudioapi’

  There are binary versions available but the source versions are later:
      binary source needs_compilation
ps     1.3.0  1.3.2              TRUE
callr  3.4.1  3.4.2             FALSE


问:
Event InventoryClickEvent don't work [Minecraft Bukkit Plugin]
I want to create a minecraft GUI that use a inventory. I have make all the GUI with the items inside. But when I try to interact with the GUI (like clicking on a item), it's make nothing. So I'm pretty sure that it's the InventoryClickEvent that don't work.

This is my code:

```<code>package can.evilestvirus.randomtp;

import java.util.Arrays;

import org.bukkit.Bukkit;
import org.bukkit.Material;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.enchantments.Enchantment;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.inventory.InventoryClickEvent;
import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.ItemFlag;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;
import org.bukkit.plugin.PluginManager;

public class CommandRtp implements CommandExecutor {

@Override
public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) {

    if (sender instanceof Player) {

        Player player = (Player) sender;

        Inventory inv = Bukkit.createInventory(null, 9, "Menu de tp aléatoire");

        ItemStack goldBlock = new ItemStack(Material.GOLD_BLOCK, 1);
        ItemMeta goldBlockM = goldBlock.getItemMeta();
        goldBlockM.setDisplayName("§8[§a+§8] §aRandomTP Normal §8[§a+§8]");
        goldBlockM.setLore(Arrays.asList("§b- §6Distance de TP: 2500 Blocks", "§b- §6Prix: $0", "§b- §6Cooldown de 60 secondes", "§a§lCliquez ici pour utiliser"));
        goldBlockM.addEnchant(Enchantment.DURABILITY, 10, true);
        goldBlockM.addItemFlags(ItemFlag.HIDE_ENCHANTS);
        goldBlock.setItemMeta(goldBlockM);
        inv.setItem(3, goldBlock);

        ItemStack diamondBlock = new ItemStack(Material.DIAMOND_BLOCK, 1);
        ItemMeta diamondBlockM = diamondBlock.getItemMeta();
        diamondBlockM.setDisplayName("§8[§a+§8] §aRandomTP §6§lVIP §8[§a+§8]");
        diamondBlockM.setLore(Arrays.asList("§b- §6Distance de TP: 5000 Blocks", "§b- §6Prix: $1000", "§b- §6Cooldown de 5 minutes", "§a§lCliquez ici pour utiliser"));
        diamondBlockM.addEnchant(Enchantment.DURABILITY, 10, true);
        diamondBlockM.addItemFlags(ItemFlag.HIDE_ENCHANTS);
        diamondBlock.setItemMeta(diamondBlockM);
        inv.setItem(5, diamondBlock);

        player.openInventory(inv);

    }

    return true;

}

@EventHandler
public void onClick(InventoryClickEvent event) {

    Player player = (Player) event.getWhoClicked();
    ItemStack current = event.getCurrentItem();

    if(current == null) return;

    if(event.getInventory().getTitle().equals("Menu de tp aléatoire")) {

        event.setCancelled(true);

        if(current.getType() == Material.GOLD_BLOCK) {

            player.closeInventory();
            player.chat("/rtpPlayer");
        }

        if(current.getType() == Material.DIAMOND_BLOCK) {

            player.closeInventory();
            player.setFlying(true);
        }

    }
}
</code>```

}

The code of my main class is this:

```<code>    package can.evilestvirus.randomtp;

import org.bukkit.Bukkit;
import org.bukkit.event.Listener;
import org.bukkit.plugin.PluginManager;
import org.bukkit.plugin.java.JavaPlugin;

import can.evilestvirus.randomtp.CommandRtpPlayer;

public class Main extends JavaPlugin {
    @Override
    public void onEnable() {
        System.out.println("HELLO PEOPLE!");
         this.getCommand("rtpplayer").setExecutor(new CommandRtpPlayer());
         this.getCommand("rtp").setExecutor(new CommandRtp());
         Bukkit.getPluginManager().registerEvents((Listener) this, Bukkit.getPluginManager().getPlugins()[0]);
         Bukkit.getPluginManager().registerEvents((Listener) new CommandRtp(), this);

    }
}
</code>```

答:
You can use this event:

```<code>@EventHandler
public void onInventoryClick(InventoryClickEvent event)  {

}
</code>```

For me it works

Body:
I want to create a minecraft GUI that use a inventory. I have make all the GUI with the items inside. But when I try to interact with the GUI (like clicking on a item), it's make nothing. So I'm pretty sure that it's the InventoryClickEvent that don't work.

This is my code:

package can.evilestvirus.randomtp;

import java.util.Arrays;

import org.bukkit.Bukkit;
import org.bukkit.Material;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.enchantments.Enchantment;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.inventory.InventoryClickEvent;
import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.ItemFlag;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;
import org.bukkit.plugin.PluginManager;

public class CommandRtp implements CommandExecutor {

@Override
public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) {

    if (sender instanceof Player) {

        Player player = (Player) sender;

        Inventory inv = Bukkit.createInventory(null, 9, "Menu de tp aléatoire");

        ItemStack goldBlock = new ItemStack(Material.GOLD_BLOCK, 1);
        ItemMeta goldBlockM = goldBlock.getItemMeta();
        goldBlockM.setDisplayName("§8[§a+§8] §aRandomTP Normal §8[§a+§8]");
        goldBlockM.setLore(Arrays.asList("§b- §6Distance de TP: 2500 Blocks", "§b- §6Prix: $0", "§b- §6Cooldown de 60 secondes", "§a§lCliquez ici pour utiliser"));
        goldBlockM.addEnchant(Enchantment.DURABILITY, 10, true);
        goldBlockM.addItemFlags(ItemFlag.HIDE_ENCHANTS);
        goldBlock.setItemMeta(goldBlockM);
        inv.setItem(3, goldBlock);

        ItemStack diamondBlock = new ItemStack(Material.DIAMOND_BLOCK, 1);
        ItemMeta diamondBlockM = diamondBlock.getItemMeta();
        diamondBlockM.setDisplayName("§8[§a+§8] §aRandomTP §6§lVIP §8[§a+§8]");
        diamondBlockM.setLore(Arrays.asList("§b- §6Distance de TP: 5000 Blocks", "§b- §6Prix: $1000", "§b- §6Cooldown de 5 minutes", "§a§lCliquez ici pour utiliser"));
        diamondBlockM.addEnchant(Enchantment.DURABILITY, 10, true);
        diamondBlockM.addItemFlags(ItemFlag.HIDE_ENCHANTS);
        diamondBlock.setItemMeta(diamondBlockM);
        inv.setItem(5, diamondBlock);

        player.openInventory(inv);

    }

    return true;

}

@EventHandler
public void onClick(InventoryClickEvent event) {

    Player player = (Player) event.getWhoClicked();
    ItemStack current = event.getCurrentItem();

    if(current == null) return;

    if(event.getInventory().getTitle().equals("Menu de tp aléatoire")) {

        event.setCancelled(true);

        if(current.getType() == Material.GOLD_BLOCK) {

            player.closeInventory();
            player.chat("/rtpPlayer");
        }

        if(current.getType() == Material.DIAMOND_BLOCK) {

            player.closeInventory();
            player.setFlying(true);
        }

    }
}

}

The code of my main class is this:

    package can.evilestvirus.randomtp;

import org.bukkit.Bukkit;
import org.bukkit.event.Listener;
import org.bukkit.plugin.PluginManager;
import org.bukkit.plugin.java.JavaPlugin;

import can.evilestvirus.randomtp.CommandRtpPlayer;

public class Main extends JavaPlugin {
    @Override
    public void onEnable() {
        System.out.println("HELLO PEOPLE!");
         this.getCommand("rtpplayer").setExecutor(new CommandRtpPlayer());
         this.getCommand("rtp").setExecutor(new CommandRtp());
         Bukkit.getPluginManager().registerEvents((Listener) this, Bukkit.getPluginManager().getPlugins()[0]);
         Bukkit.getPluginManager().registerEvents((Listener) new CommandRtp(), this);

    }
}

Body:
You can use this event:

@EventHandler
public void onInventoryClick(InventoryClickEvent event)  {

}

For me it works


问:
How to center ngb-timepicker in a col-nn
I have a time picker component in Angular 8, with bootstrap 4. I'm trying to center a ngb-timepicker in a col-12 inside this component.

```<code><div class="row pickerContainer">
  <div class="col-12 pickerCenterer">
    <h2>Title</h2>
    <ngb-timepicker [(ngModel)]="time"></ngb-timepicker>
    <hr>
    ```Selected time: {{time | json}}```
  </div>
</div>

.pickerContainer{
  text-align:center;
}
.pickerCenterer{
  display:inline-block;
  margin:0 auto;
}
</code>```

This results with text being centered, but not the time picker. Stackblitz example here: https://cqutyi.run.stackblitz.io/

How do I center the time-picker itself?

答:
You can make use of row class instead of col-12 like below.

```<code><div class="row pickerContainer">
  <div class="row pickerCenterer">
    <h2>Title</h2>
    <ngb-timepicker [(ngModel)]="time"></ngb-timepicker>
    <hr>
    ```Selected time: {{time | json}}```
  </div>
</div>
</code>```

Demo is here - https://stackblitz.com/edit/angular-zzvzn7

Body:
I have a time picker component in Angular 8, with bootstrap 4. I'm trying to center a ngb-timepicker in a col-12 inside this component.

Title

    <ngb-timepicker [(ngModel)]="time"></ngb-timepicker>

Selected time: {{time | json}}

.pickerContainer{
  text-align:center;
}
.pickerCenterer{
  display:inline-block;
  margin:0 auto;
}

This results with text being centered, but not the time picker. Stackblitz example here: https://cqutyi.run.stackblitz.io/

How do I center the time-picker itself?

Body:
You can make use of row class instead of col-12 like below.

<div class="row pickerContainer">
  <div class="row pickerCenterer">
    <h2>Title</h2>
    <ngb-timepicker [(ngModel)]="time"></ngb-timepicker>
    <hr>
    <pre>Selected time: {{time | json}}</pre>
  </div>
</div>

Demo is here - https://stackblitz.com/edit/angular-zzvzn7


问:
REACT Jest - Test suite failed to run
I have created sample react project and added JEST, enzyme dependencies to test my component. But getting below error while running test suite:
ERROR:
 Cannot find module 'components/Add' from 'App.js'

```<code>However, Jest was able to find:
    'components/Add.js'

You might want to include a file extension in your import, or update your 'moduleFileExtensions', which is currently ['web.js', 'js', 'web.ts', 'ts', 'web.tsx', 'tsx', 'json', 'web.jsx', 'jsx', 'node'].

See https://jestjs.io/docs/en/configuration#modulefileextensions-array-string

However, Jest was able to find:
    './App.css'
    './App.js'
    './App.test.js'

You might want to include a file extension in your import, or update your 'moduleFileExtensions', which is currently ['web.js', 'js', 'web.ts', 'ts', 'web.tsx', 'tsx', 'json', 'web.jsx', 'jsx', 'node'].

See https://jestjs.io/docs/en/configuration#modulefileextensions-array-string

  1 | import React from 'react';
> 2 | import Add from 'components/Add';
    | ^
  3 |
  4 |
  5 | function App() {

  at Resolver.resolveModule (node_modules/jest-resolve/build/index.js:259:17)
  at Object.<anonymous> (src/App.js:2:1)
</code>```

Test Suites: 1 failed, 1 total
Tests:       0 total
Snapshots:   0 total
Time:        4.035s
Ran all test suites.

Can anyone please help to resolve this issue, will be happy to share more details.

答:
The way your imports are written, you're probably using aliases for your paths. If you're using webpack, check webpack.config.json for resolve.alias field to confirm this.

If you do have aliases set up, You will have to add them to your jest configurations also. This is done using moduleNameMapper. For example,

```<code>{
  "moduleNameMapper": {
    "components/(.*)$": "<rootDir>/PATH_TO_COMPONENTS/$1",
  }

</code>```

}

Title: REACT Jest - Test suite failed to run

Body:
I have created sample react project and added JEST, enzyme dependencies to test my component. But getting below error while running test suite:
ERROR:
 Cannot find module 'components/Add' from 'App.js'

However, Jest was able to find:
    'components/Add.js'

You might want to include a file extension in your import, or update your 'moduleFileExtensions', which is currently ['web.js', 'js', 'web.ts', 'ts', 'web.tsx', 'tsx', 'json', 'web.jsx', 'jsx', 'node'].

See https://jestjs.io/docs/en/configuration#modulefileextensions-array-string

However, Jest was able to find:
    './App.css'
    './App.js'
    './App.test.js'

You might want to include a file extension in your import, or update your 'moduleFileExtensions', which is currently ['web.js', 'js', 'web.ts', 'ts', 'web.tsx', 'tsx', 'json', 'web.jsx', 'jsx', 'node'].

See https://jestjs.io/docs/en/configuration#modulefileextensions-array-string

  1 | import React from 'react';
> 2 | import Add from 'components/Add';
    | ^
  3 |
  4 |
  5 | function App() {

  at Resolver.resolveModule (node_modules/jest-resolve/build/index.js:259:17)
  at Object.<anonymous> (src/App.js:2:1)

Test Suites: 1 failed, 1 total
Tests:       0 total
Snapshots:   0 total
Time:        4.035s
Ran all test suites.

Can anyone please help to resolve this issue, will be happy to share more details.

Body:
The way your imports are written, you're probably using aliases for your paths. If you're using webpack, check webpack.config.json for resolve.alias field to confirm this.

If you do have aliases set up, You will have to add them to your jest configurations also. This is done using moduleNameMapper. For example,

{
  "moduleNameMapper": {
    "components/(.*)$": "<rootDir>/PATH_TO_COMPONENTS/$1",
  }

}


问:
How to generate certs for secured connection from Celery to Redis
I'm following this tutorial, and adjusting the Celery-background related code to my project.

In my case I am operating in a Docker environment, and I have a secured site (i.e. https://localhost) which requires secured ssl communication.

The documentation in here shows an example on how to provide cert related files (keyfile, certfile, ca_certs).

But it is not clear to me how to create these files in the first place.

The tutorial in here shows how to create a custom certificate authority, and how to sign a certificate with it.

I followed the steps and created the 3 files:

keyfile - dev.mergebot.com.crt  - the signed certificate (signed by myCA.pem)

ca_certs - dev.mergebot.com.key - private key to create a signed cert with "self-trusted CA"

certfile - myCA.pem - "self-trusted CA" certificate (filename in the tutorial: myCA.pem)

Note that I created these 3 files completely unrelated to Celery or Redis or Docker.
They were created in my local machine outside Docker. The files don't have the name of the Redis container and the Common Name in the cert was set to "foo"

When I use these files in my webapp, there is no connection from Celery to Redis.

Without ssl I do get a connection, so the overall environment aside from ssl is OK - see here

Is there any specific requirements to create the cert related files? (e.g. should the Common Name in the cert have the container name "redis", etc... )

Is there a way to test the validity of the certs without the app, e.g. by issuing a command from the container shell?

Thanks

答:
Yes the certificate comman name should match the host name also the issuer of the certificate should be trusted by the client .

In your case since you are using a custom CA and generating the certs , the public cert of the CA should be in the trusted root of the client .

Additionally the certificate should be issued to the hostname in your case it will be localhost . Please do note that if you access the site from a remote machine by either using the fqdn or the Up the browser will flag an alert as invalid.

Also to verify the certificates , you can use the OpenSSL Verify option.