问:
A good way to make classes for more complex playing card types than those found in a standard deck?
I am extremely new to object-oriented programming, and am trying to begin learning in python by making a simple card game (as seems to be traditional!). I have done the following example which works fine, and teaches me about making multiple instances of the PlayingCard() class to create an instance of the Deck() class:

class PlayingCard(object):
    def __init__(self, suit, val):
        self.suit = suit
        self.value = val

    def print_card(self):
        print("{} of {}".format(self.value, self.suit))

class Deck(object):
    def __init__(self):
        self.playingcards = []
        self.build()

    def build(self):
        for s in ["Spades", "Clubs", "Diamonds", "Hearts"]:
            for v in range(1,14):
                self.playingcards.append(PlayingCard(s,v))

deck = Deck()
```

I want to make something now with more complex cards, not just a standard 52 deck (which has nicely incrementing values). The deck I have in mind is the [Monopoly card game][1]:

There are 3 fundamental types of cards - ACTION cards, PROPERTY cards, and MONEY cards. The action cards perform different actions, the property cards belong to different colour sets, and the money cards can have different values. Additionally, the property cards can be "wildcards", and can be used as part of one of two sets. Finally, every card also has an equivalent money value (indicated in the top corner of each card). In the rent action cards, the card can only apply to the colour property indicated on the card.

My question is just generally how to handle a situation like this, and what would be a nice way to include these different cards in a class-based python program? Should I keep my single PlayingCard() class, and just have many inputs, such as PlayingCard(type="PROPERTY", value="3M"). Or would it be better to create seperate classes such as ActionPlayingCard(), PropertyPlayingCard(), etc ? Or is there a better way? As I say, I am at the beginning of my learning here, and how to organise these types of situations in terms of the higher level design.

Many thanks.

答: These are what we call "design decisions". Often the "correct" way is a matter of opinion. As a beginner, I think it would be instructive to try both implementations to see how they work. There will be trade offs no matter which one you pick. You have to decide which of those trade offs are most important. Making these kinds of decisions will be informed as you gain more experience.</p>

Body:
I am extremely new to object-oriented programming, and am trying to begin learning in python by making a simple card game (as seems to be traditional!). I have done the following example which works fine, and teaches me about making multiple instances of the PlayingCard() class to create an instance of the Deck() class:

class PlayingCard(object):
    def __init__(self, suit, val):
        self.suit = suit
        self.value = val

    def print_card(self):
        print("{} of {}".format(self.value, self.suit))

class Deck(object):
    def __init__(self):
        self.playingcards = []
        self.build()

    def build(self):
        for s in ["Spades", "Clubs", "Diamonds", "Hearts"]:
            for v in range(1,14):
                self.playingcards.append(PlayingCard(s,v))

deck = Deck()

I want to make something now with more complex cards, not just a standard 52 deck (which has nicely incrementing values). The deck I have in mind is the [Monopoly card game][1]:

There are 3 fundamental types of cards - ACTION cards, PROPERTY cards, and MONEY cards. The action cards perform different actions, the property cards belong to different colour sets, and the money cards can have different values. Additionally, the property cards can be "wildcards", and can be used as part of one of two sets. Finally, every card also has an equivalent money value (indicated in the top corner of each card). In the rent action cards, the card can only apply to the colour property indicated on the card.

My question is just generally how to handle a situation like this, and what would be a nice way to include these different cards in a class-based python program? Should I keep my single PlayingCard() class, and just have many inputs, such as PlayingCard(type="PROPERTY", value="3M"). Or would it be better to create seperate classes such as ActionPlayingCard(), PropertyPlayingCard(), etc ? Or is there a better way? As I say, I am at the beginning of my learning here, and how to organise these types of situations in terms of the higher level design.

Many thanks.


来源: stackexchange

问:
How do you write a sequence as a vector?
I have a vector "I" which we can take for example to be (0,1,2,3.....) till an unknown length. I want to create a vector such that x^(I-1) so it will be a vector that looks like (0,x,x^2...).
However I do not know how to write this code and I tried (x^I-1) alone doesn't work. </p>

答:
EDIT***  Read r2evan's comments to understand why this is not a recommended solution.

This will take vector z and feed it it into the function to create the resulting vector.  Simply adjust your x value (in this case, the 2)

```<code>z <- c(1:5)

new_vector <- sapply(z, function(y) 2 ^ y)
</code>```

The output values in the new vector then would be x^0, x^1, x^2, x^3... etc.

ContentLicense: CC BY-SA 4.0

Body:
EDIT***  Read r2evan's comments to understand why this is not a recommended solution.

This will take vector z and feed it it into the function to create the resulting vector.  Simply adjust your x value (in this case, the 2)

z <- c(1:5)

new_vector <- sapply(z, function(y) 2 ^ y)

The output values in the new vector then would be x^0, x^1, x^2, x^3... etc.


问:
cmd doesn't output results to a file
I'm trying to use the cmd line, eventually putting it into a .bat to run a program, taking the return value and putting it into a .txt file.  In this script it runs the program, creates the .txt file, but the .txt file is blank, while the program puts out a bunch of text on one line:

This is the command:

```<code>jsonlint test.json -c -q > test1.txt
</code>```

The test1.txt gets create, but is blank.  The program returns this value:

test.json: line 3, col13, found: 'NUMBER' - expected: 'EOF', '}', ':', ',', ']'.**

Why would this return value not be getting saved to the test1.txt file?  Any thoughts or ideas are most appreciated.  Thank you.

答:
As Charles has mentioned, your output is actually an error indicating that your JSON file test.json is syntactically incorrect on line 3 col 13.

If you want to have whatever is output regardless of it being STDOUT or STDERR, then at the end of your command you can add 2>&1 to redirect your STDERR to STDOUT, so it would look like this:

```<code>jsonlint test.json -c -q > test1.txt 2>&1
</code>```

More on redirecting error messages here.

Title: cmd doesn't output results to a file

Body:
I'm trying to use the cmd line, eventually putting it into a .bat to run a program, taking the return value and putting it into a .txt file.  In this script it runs the program, creates the .txt file, but the .txt file is blank, while the program puts out a bunch of text on one line:

This is the command:

jsonlint test.json -c -q > test1.txt

The test1.txt gets create, but is blank.  The program returns this value:

test.json: line 3, col13, found: 'NUMBER' - expected: 'EOF', '}', ':', ',', ']'.**

Why would this return value not be getting saved to the test1.txt file?  Any thoughts or ideas are most appreciated.  Thank you.

Body:
As Charles has mentioned, your output is actually an error indicating that your JSON file test.json is syntactically incorrect on line 3 col 13.

If you want to have whatever is output regardless of it being STDOUT or STDERR, then at the end of your command you can add 2>&1 to redirect your STDERR to STDOUT, so it would look like this:

jsonlint test.json -c -q > test1.txt 2>&1

More on redirecting error messages here.


问:
r loop for filtering through each column
I have a data frame like this:
    gene expression data frame
Assuming column name as different samples and row name as different genes.
Now I want to know the number of genes left after I filter from each column with a number
For example,

```<code>sample1_more_than_5 <- df[(df[,1]>5),]
sample1_more_than_10 <- df[(df[,1]>10),]
sample1_more_than_20 <- df[(df[,1]>20),]
sample1_more_than_30 <- df[(df[,1]>30),]
</code>```

Then,

```<code>sample2_more_than_5 <- df[(df[,2]>5),]
sample2_more_than_10 <- df[(df[,2]>10),]
sample2_more_than_20 <- df[(df[,2]>20),]
sample2_more_than_30 <- df[(df[,2]>30),]
</code>```

But I don't want to repeat this 100 times as I have 100 samples.
Can anyone write a loop for me for this situation? Thank you

答:
We can  loop over the columns and do this  and create the grouping with cut

```<code>lst1 <- lapply(df, function(x) split(x, cut(x, breaks = c(5, 10, 20, 30))))
</code>```

or findInterval  and then split

```<code>lst1 <- lapply(df, function(x) split(x, findInterval(x,  c(5, 10, 20, 30))))
</code>```

If we go by the way the objects are created in the OP's post, there would be 100 * 4 i.e. 400 objects (100 columns) in the global environment.  Instead, it can be single list object.

The objects can be created, but it is not recommended

```<code>v1 <- c(5, 10, 20, 30)
v2 <- seq_along(df)
 for(i in v2) {
     for(j in v1) {
      assign(sprintf('sample%d_more_than_%d', i, j),
               value = df[df[,i] > j,, drop = FALSE])
    }
  }
</code>```

Body:
I have a data frame like this:
    gene expression data frame
Assuming column name as different samples and row name as different genes.
Now I want to know the number of genes left after I filter from each column with a number
For example,

sample1_more_than_5 <- df[(df[,1]>5),]
sample1_more_than_10 <- df[(df[,1]>10),]
sample1_more_than_20 <- df[(df[,1]>20),]
sample1_more_than_30 <- df[(df[,1]>30),]

Then,

sample2_more_than_5 <- df[(df[,2]>5),]
sample2_more_than_10 <- df[(df[,2]>10),]
sample2_more_than_20 <- df[(df[,2]>20),]
sample2_more_than_30 <- df[(df[,2]>30),]

But I don't want to repeat this 100 times as I have 100 samples.
Can anyone write a loop for me for this situation? Thank you

Body:
We can  loop over the columns and do this  and create the grouping with cut

lst1 <- lapply(df, function(x) split(x, cut(x, breaks = c(5, 10, 20, 30))))

or findInterval  and then split

lst1 <- lapply(df, function(x) split(x, findInterval(x,  c(5, 10, 20, 30))))

If we go by the way the objects are created in the OP's post, there would be 100 * 4 i.e. 400 objects (100 columns) in the global environment.  Instead, it can be single list object.

The objects can be created, but it is not recommended

v1 <- c(5, 10, 20, 30)
v2 <- seq_along(df)
 for(i in v2) {
     for(j in v1) {
      assign(sprintf('sample%d_more_than_%d', i, j),
               value = df[df[,i] > j,, drop = FALSE])
    }
  }


问:
Excel formula trouble—need to copy values of adjacent column, but at every 6th row, double the copied value. Combining these 2 has gotten me lost
Currently I've managed to copy the values in column I to column L using =OFFSET(I5,0,0,1)

But I'd like to combine this with another formula somehow...

Values in column I :

```<code>0
200
150
250
430
100
0
250
220
350
90
0
</code>```

Values to be copied to column L :

```<code>0
200
150
250
430
**200**
0
250
220
350
**180**
0
</code>```

I realize that my row is being written horizontally here but it is easier to understand this way, I think.

I am new to excel formulas and thus why I'm stuck.

答:
Perhaps this formula can help you:

```<code>=IF(MOD(ROW(),6)=0,A1*2,A1)
</code>```

Body:
Currently I've managed to copy the values in column I to column L using =OFFSET(I5,0,0,1)

But I'd like to combine this with another formula somehow...

Values in column I :

0
200
150
250
430
100
0
250
220
350
90
0

Values to be copied to column L :

0
200
150
250
430
**200**
0
250
220
350
**180**
0

I realize that my row is being written horizontally here but it is easier to understand this way, I think.

I am new to excel formulas and thus why I'm stuck.

Body:
Perhaps this formula can help you:

=IF(MOD(ROW(),6)=0,A1*2,A1)


问:
How to get AWS access key and secret key using aws-sdk-ruby --aws-sdk-iam,aws-sdk-core
I'm a newbie to aws and ruby. I'm trying to get access key and the secret key using the aws-sdk-ruby, as due to security reasons we do not have access to keys in the AWS Console. I tried to use the 'get_federation_token' 'assume role with SAML' to get the keys, but I was not successful. I tried both the ways as we use the saml2aws and aws-federator to login to the AWS via the CLI. I would want to replicate that and get the keys to able to connect successfully.</p>

答: Have you tried setting up ENV vars in a .env file and then fetching via ENV.fetch('variable_name'), like, ENV.fetch('S3_BUCKET_NAME')? This works consistently for me.


问:
Save/load 2 XDocuments to/from one stream
I've got 2 XDocuments. One is some meta data, the other is a lot of data.

On the Xbox (XNA), I'd like to be able to save both to a file stream, meta data XDoc first, then the actual data XDoc.

I'd then like to be able to access just the meta data XDoc (ignoring the rest of the file stream), and also to be able to access the meta data XDoc and the data XDoc.

Currently i'm saving/loading as follows:

```<code>public void Serialise(Stream SaveStream, object Obj)
{
    XDocument XDoc = new XDocument(new XElement(@"SaveData", new XAttribute(@"Version", @"1.0"),
                                                GetXMLElement(Obj)));

    XDoc.Save(SaveStream);
}

public object Deserialise(Stream ObjectStream)
{
    XDocument XDoc = XDocument.Load(ObjectStream); // Error line

    switch (XDoc.Element(@"SaveData").Attribute(@"Version").Value)
    {
        case @"1.0":
            return GetObject(XDoc.Element(@"SaveData").FirstNode as XElement);
        default:
            throw new NotSupportedException("This save file version (" + XDoc.Element(@"SaveData").Attribute(@"Version").Value +
                                            " is not supported, please upgrade your game.");
    }
}
</code>```

To save meta data followed by actual data i'm just calling serialise twice on the same stream.

I get a file as below:

```<code><?xml version="1.0" encoding="utf-8"?>
<SaveData Version="1.0">
    ....
</SaveData><?xml version="1.0" encoding="utf-8"?>
<SaveData Version="1.0">
    ....
</SaveData>
</code>```

The problem comes when i try and read the first XDoc: Unexpected XML declaration. The XML declaration must be the first node in the document, and no white space characters are allowed to appear before it. Line 18, position 14.

Any help would be greatly appreciated.

答:
I ended up writing my own Stream, which can be thought of as a multistream. It allows you to treat one stream as multiple stream in succession. i.e. pass a multistream to an xml parser (or anything else) and i'll read up to a marker, which says 'this is the end of the stream'. If you then pass that same stream to another xml parser, it'll read from that marker, to the next one or EOF:</p>

```<code>public class MultiStream : Stream
{
    private readonly byte[] _RandomBytes = "410801dd-6f14-4d68-8e0e-29686d212cb2".Select(c => (byte)c).ToArray();

    private Queue<byte> _RollingBytesRead;

    private Stream _UnderlyingStream;

    private bool UnderlyingEOF = false;
    private bool EOFMarker = false;
    private int BufferedBytesToRead = 0;

    public MultiStream(Stream UnderlyingStream)
        : base()
    {
        _UnderlyingStream = UnderlyingStream;
        _RollingBytesRead = new Queue<byte>(_RandomBytes.Length);
    }

    public override bool CanRead
    {
        get { return !UnderlyingEOF || _UnderlyingStream.CanRead; }
    }

    public override bool CanSeek
    {
        get { return false; }
    }

    public override bool CanWrite
    {
        get { return _UnderlyingStream.CanWrite; }
    }

    public override void Flush()
    {
        _UnderlyingStream.Flush();
    }

    public override long Length
    {
        get { throw new NotSupportedException(); }
    }

    public override long Position
    {
        get
        {
            throw new NotSupportedException();
        }
        set
        {
            throw new NotSupportedException();
        }
    }

    public override int ReadByte()
    {
        if (EOFMarker)
            return -1;

        // This should read the next byte from the underlying stream, check for the random bytes EOF marker, then return the next byte from the buffer

        // If our buffer is smaller than the random bytes and we've not hit the EOF, then we need to fill it
        while (!UnderlyingEOF && _RollingBytesRead.Count < _RandomBytes.Length)
        {
            int BytesRead = _UnderlyingStream.ReadByte();
            if (BytesRead == -1)
            {
                UnderlyingEOF = true;
                BufferedBytesToRead = _RollingBytesRead.Count;
            }
            else
            {
                _RollingBytesRead.Enqueue((byte)BytesRead);
            }
        }

        if (EncounteredEndOfStreamBytes()) // Now check to see if the buffer matches our EOF marker
        {
            // If it does stop now, since we don't want to output any of the EOF marker.
            BufferedBytesToRead = 0;
            _RollingBytesRead.Clear();
            EOFMarker = true;
            return -1;
        }
        else if (UnderlyingEOF) // If we've already encountered the end of the underlying stream and have a buffer,
                                // then output the next byte since it's not part of the EOF marker, it's part of the stream
        {
            if (BufferedBytesToRead != 0)
            {
                BufferedBytesToRead--;
                return _RollingBytesRead.Dequeue();
            }
            else
            {
                return -1;
            }
        }
        else
        {
            int ByteRead = _UnderlyingStream.ReadByte();

            if (ByteRead == -1)
            {
                // We've reached the end so we should output the buffer
                UnderlyingEOF = true;
                BufferedBytesToRead = _RollingBytesRead.Count;

                // Recurse once just to avoid repeating code above
                return ReadByte();
            }
            else
            {
                byte BufferedByte = _RollingBytesRead.Dequeue();
                _RollingBytesRead.Enqueue((byte)ByteRead);

                return BufferedByte;
            }
        }
    }

    public override int Read(byte[] buffer, int offset, int count)
    {
        bool EncounteredEOF = false;

        int BufferIndex = 0;

        while (offset > 0)
        {
            if (ReadByte() == -1)
            {
                EncounteredEOF = true;
            }

            offset--;
        }

        while (!EncounteredEOF && count > 0)
        {
            // Read the next byte (includes checks for our end of stream marker) and actually returns the buffered byte (not the next underlying stream read byte)
            int ByteRead = ReadByte();

            if (ByteRead == -1)
            {
                break;
            }
            else
            {
                buffer[BufferIndex] = (byte)ByteRead;

                count--;
                BufferIndex++;
            }
        }

        return BufferIndex;
    }

    private bool EncounteredEndOfStreamBytes()
    {
        if (_RollingBytesRead.Count != _RandomBytes.Length)
            return false;

        byte[] QueueArray = _RollingBytesRead.ToArray();

        for (int i = 0; i < _RandomBytes.Length; i++)
        {
            if (_RandomBytes[i] != QueueArray[i])
                return false;
        }
        return true;
    }

    public override long Seek(long offset, SeekOrigin origin)
    {
        throw new NotSupportedException();
    }

    public override void SetLength(long value)
    {
        throw new NotSupportedException();
    }

    public override void Write(byte[] buffer, int offset, int count)
    {
        _UnderlyingStream.Write(buffer, offset, count);
    }

    public void WriteStreamSeperator()
    {
        Write(_RandomBytes, 0, _RandomBytes.Length);
    }

    public void AdvanceToNextStream()
    {
        if (UnderlyingEOF)
            throw new InvalidOperationException("No more streams");

        // If we're not currently at an EOF marker, advance until we get to one.
        while (!EOFMarker)
        {
            ReadByte();
        }

        EOFMarker = false;
        _RollingBytesRead.Clear();
    }
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I've got 2 XDocuments. One is some meta data, the other is a lot of data.

On the Xbox (XNA), I'd like to be able to save both to a file stream, meta data XDoc first, then the actual data XDoc.

I'd then like to be able to access just the meta data XDoc (ignoring the rest of the file stream), and also to be able to access the meta data XDoc and the data XDoc.

Currently i'm saving/loading as follows:

public void Serialise(Stream SaveStream, object Obj)
{
    XDocument XDoc = new XDocument(new XElement(@"SaveData", new XAttribute(@"Version", @"1.0"),
                                                GetXMLElement(Obj)));

    XDoc.Save(SaveStream);
}

public object Deserialise(Stream ObjectStream)
{
    XDocument XDoc = XDocument.Load(ObjectStream); // Error line

    switch (XDoc.Element(@"SaveData").Attribute(@"Version").Value)
    {
        case @"1.0":
            return GetObject(XDoc.Element(@"SaveData").FirstNode as XElement);
        default:
            throw new NotSupportedException("This save file version (" + XDoc.Element(@"SaveData").Attribute(@"Version").Value +
                                            " is not supported, please upgrade your game.");
    }
}

To save meta data followed by actual data i'm just calling serialise twice on the same stream.

I get a file as below:

<?xml version="1.0" encoding="utf-8"?>
<SaveData Version="1.0">
    ....
</SaveData><?xml version="1.0" encoding="utf-8"?>
<SaveData Version="1.0">
    ....
</SaveData>

The problem comes when i try and read the first XDoc: Unexpected XML declaration. The XML declaration must be the first node in the document, and no white space characters are allowed to appear before it. Line 18, position 14.

Any help would be greatly appreciated.

Body:
I ended up writing my own Stream, which can be thought of as a multistream. It allows you to treat one stream as multiple stream in succession. i.e. pass a multistream to an xml parser (or anything else) and i'll read up to a marker, which says 'this is the end of the stream'. If you then pass that same stream to another xml parser, it'll read from that marker, to the next one or EOF:

public class MultiStream : Stream
{
    private readonly byte[] _RandomBytes = "410801dd-6f14-4d68-8e0e-29686d212cb2".Select(c => (byte)c).ToArray();

    private Queue<byte> _RollingBytesRead;

    private Stream _UnderlyingStream;

    private bool UnderlyingEOF = false;
    private bool EOFMarker = false;
    private int BufferedBytesToRead = 0;

    public MultiStream(Stream UnderlyingStream)
        : base()
    {
        _UnderlyingStream = UnderlyingStream;
        _RollingBytesRead = new Queue<byte>(_RandomBytes.Length);
    }

    public override bool CanRead
    {
        get { return !UnderlyingEOF || _UnderlyingStream.CanRead; }
    }

    public override bool CanSeek
    {
        get { return false; }
    }

    public override bool CanWrite
    {
        get { return _UnderlyingStream.CanWrite; }
    }

    public override void Flush()
    {
        _UnderlyingStream.Flush();
    }

    public override long Length
    {
        get { throw new NotSupportedException(); }
    }

    public override long Position
    {
        get
        {
            throw new NotSupportedException();
        }
        set
        {
            throw new NotSupportedException();
        }
    }

    public override int ReadByte()
    {
        if (EOFMarker)
            return -1;

        // This should read the next byte from the underlying stream, check for the random bytes EOF marker, then return the next byte from the buffer

        // If our buffer is smaller than the random bytes and we've not hit the EOF, then we need to fill it
        while (!UnderlyingEOF && _RollingBytesRead.Count < _RandomBytes.Length)
        {
            int BytesRead = _UnderlyingStream.ReadByte();
            if (BytesRead == -1)
            {
                UnderlyingEOF = true;
                BufferedBytesToRead = _RollingBytesRead.Count;
            }
            else
            {
                _RollingBytesRead.Enqueue((byte)BytesRead);
            }
        }

        if (EncounteredEndOfStreamBytes()) // Now check to see if the buffer matches our EOF marker
        {
            // If it does stop now, since we don't want to output any of the EOF marker.
            BufferedBytesToRead = 0;
            _RollingBytesRead.Clear();
            EOFMarker = true;
            return -1;
        }
        else if (UnderlyingEOF) // If we've already encountered the end of the underlying stream and have a buffer,
                                // then output the next byte since it's not part of the EOF marker, it's part of the stream
        {
            if (BufferedBytesToRead != 0)
            {
                BufferedBytesToRead--;
                return _RollingBytesRead.Dequeue();
            }
            else
            {
                return -1;
            }
        }
        else
        {
            int ByteRead = _UnderlyingStream.ReadByte();

            if (ByteRead == -1)
            {
                // We've reached the end so we should output the buffer
                UnderlyingEOF = true;
                BufferedBytesToRead = _RollingBytesRead.Count;

                // Recurse once just to avoid repeating code above
                return ReadByte();
            }
            else
            {
                byte BufferedByte = _RollingBytesRead.Dequeue();
                _RollingBytesRead.Enqueue((byte)ByteRead);

                return BufferedByte;
            }
        }
    }

    public override int Read(byte[] buffer, int offset, int count)
    {
        bool EncounteredEOF = false;

        int BufferIndex = 0;

        while (offset > 0)
        {
            if (ReadByte() == -1)
            {
                EncounteredEOF = true;
            }

            offset--;
        }

        while (!EncounteredEOF && count > 0)
        {
            // Read the next byte (includes checks for our end of stream marker) and actually returns the buffered byte (not the next underlying stream read byte)
            int ByteRead = ReadByte();

            if (ByteRead == -1)
            {
                break;
            }
            else
            {
                buffer[BufferIndex] = (byte)ByteRead;

                count--;
                BufferIndex++;
            }
        }

        return BufferIndex;
    }

    private bool EncounteredEndOfStreamBytes()
    {
        if (_RollingBytesRead.Count != _RandomBytes.Length)
            return false;

        byte[] QueueArray = _RollingBytesRead.ToArray();

        for (int i = 0; i < _RandomBytes.Length; i++)
        {
            if (_RandomBytes[i] != QueueArray[i])
                return false;
        }
        return true;
    }

    public override long Seek(long offset, SeekOrigin origin)
    {
        throw new NotSupportedException();
    }

    public override void SetLength(long value)
    {
        throw new NotSupportedException();
    }

    public override void Write(byte[] buffer, int offset, int count)
    {
        _UnderlyingStream.Write(buffer, offset, count);
    }

    public void WriteStreamSeperator()
    {
        Write(_RandomBytes, 0, _RandomBytes.Length);
    }

    public void AdvanceToNextStream()
    {
        if (UnderlyingEOF)
            throw new InvalidOperationException("No more streams");

        // If we're not currently at an EOF marker, advance until we get to one.
        while (!EOFMarker)
        {
            ReadByte();
        }

        EOFMarker = false;
        _RollingBytesRead.Clear();
    }
}


问:
Camera Preview black in Android 7
I'm using a straight forwards Camera API, for backwards compatibility. The camera view itself is overlayed slightly by an imageview and my surfaceChanged does this:

```<code>camera.setPreviewCallback((data, arg1) -> LiveView.this.invalidate());
camera.setPreviewDisplay(mHolder);
camera.startPreview();
</code>```

which works fine on all older devices. I set the preview size to the largest available  size earlier in surfaceCreated.
However on Android 7.1, it's suddenly black (on a Nexus 6 and Moto X Play, probably others - so on different devices).
The SurfaceView itself is greyed out in the Layout Inspector (willNotDraw = true), but VISIBLE (and hardware accelerated).
Strangely, I'm still able to take photos, event without preview, and the data in the preview callback contains an image.

At the same time I get the following log

```<code>E/mm-camera: mct_pipeline_send_ctrl_events: Send Set Parm events
E/QCamera2HWI: static void* qcamera::QCameraCbNotifier::cbNotifyRoutine(void*) : cb message type 32768 not enabled!
E/QCamera2HWI: static void* qcamera::QCameraCbNotifier::cbNotifyRoutine(void*) : cb message type 32768 not enabled!
D/QCameraParameters: setSnapshotSkipHint: preview hint 3 fps 15.019738
</code>```

Has anybody else experienced a completely black image in Android 7? Are there any easy fixes? (Like drawing the content of data directly?)

答:
i had this issue whit camera and quick fix whit adding this code to cameraPreview
just add camera.stopPreview() before startPreview().

```<code>public void surfaceCreated(SurfaceHolder surfaceHolder) {
    try {
        this.mCamera.stopPreview();
        this.mCamera.setPreviewDisplay(surfaceHolder);
        this.mCamera.startPreview();
    } catch (IOException unused) {
        Log.d("camera", "Error setting camera preview: " + unused.getMessage());
    }
}
</code>```

Title: Camera Preview black in Android 7

Body:
I'm using a straight forwards Camera API, for backwards compatibility. The camera view itself is overlayed slightly by an imageview and my surfaceChanged does this:

camera.setPreviewCallback((data, arg1) -> LiveView.this.invalidate());
camera.setPreviewDisplay(mHolder);
camera.startPreview();

which works fine on all older devices. I set the preview size to the largest available  size earlier in surfaceCreated.
However on Android 7.1, it's suddenly black (on a Nexus 6 and Moto X Play, probably others - so on different devices).
The SurfaceView itself is greyed out in the Layout Inspector (willNotDraw = true), but VISIBLE (and hardware accelerated).
Strangely, I'm still able to take photos, event without preview, and the data in the preview callback contains an image.

At the same time I get the following log

E/mm-camera: mct_pipeline_send_ctrl_events: Send Set Parm events
E/QCamera2HWI: static void* qcamera::QCameraCbNotifier::cbNotifyRoutine(void*) : cb message type 32768 not enabled!
E/QCamera2HWI: static void* qcamera::QCameraCbNotifier::cbNotifyRoutine(void*) : cb message type 32768 not enabled!
D/QCameraParameters: setSnapshotSkipHint: preview hint 3 fps 15.019738

Has anybody else experienced a completely black image in Android 7? Are there any easy fixes? (Like drawing the content of data directly?)

Body:
i had this issue whit camera and quick fix whit adding this code to cameraPreview
just add camera.stopPreview() before startPreview().

public void surfaceCreated(SurfaceHolder surfaceHolder) {
    try {
        this.mCamera.stopPreview();
        this.mCamera.setPreviewDisplay(surfaceHolder);
        this.mCamera.startPreview();
    } catch (IOException unused) {
        Log.d("camera", "Error setting camera preview: " + unused.getMessage());
    }
}


问:
glmnet coefficients differ between versions (2.0.16 vs 3.0.2)
I manage an internal code base that relies heavily upon the glmnet package. Upon upgrading to the newest version (v3.0.2) my unit tests started failing for the coefficients of a Cox model. The previous version of glmnet was v2.0.16 (R 3.5.2). I am now running R v3.6.2.

I have noticed that there is a new relax = argument that appears to use un-regularized fits in the path and I'd imagine this could cause a slight difference in the fits, however the default is relax = FALSE, so I doubt that is the issue.

Below is a reprex based on the mtcars dataset, fitting 2 randomly chosen features and renaming two variables to time and status so as to allow fitting of a Cox model. A proper reprex comparison is difficult as it would require different R installations, but this should allow anyone to reproduce the issue.

```<code>library(magrittr)
library(dplyr)
library(glmnet)
dat <- mtcars %>%
    select(mpg, disp, status = vs, time = hp) %>%   # select 2 features; assign time & status
    mutate_at(1:2, ~ {
      log10(.x) %>% subtract(mean(.)) %>% divide_by(sd(.))   # center & scale
    }) %>% as.matrix()
glmnet(dat[, 1:2], dat[, 3:4], family = "cox", lambda = 0)$beta   # fit model
</code>```

The result for v3.0.2 is:

```<code>#> 2 x 1 sparse Matrix of class "dgCMatrix"
#>              s0
#> mpg   0.2293535
#> disp -1.8160387
</code>```

The result for v2.0.16 is:

```<code>#> 2 x 1 sparse Matrix of class "dgCMatrix"
#>              s0
#> mpg   0.2154324
#> disp -1.8172714
</code>```

Have others noticed similar discrepancies? I am somewhat surprised not to have found anyone else bumping into this same issue. Am I going to have to update all my unit tests :(

Insights and/or explanations greatly appreciated.
Thanks in advance.

答:
Slightly too long for a comment:

I reproduced your results on Ubuntu 16.04 (using devtools::install_version(), see below).

2.0-16 to 3.0-2 spans several releases (and several more internally labeled, unreleased versions): the NEWS file makes several references to coxnet (presumably the internal function called for family="cox":

2.0-20:

Fixed a bug in internal function coxnet.deviance to do with input pred, as well as saturated loglike (missing) and weights

added a coxgrad function for computing the gradient

2.0-19:
  Fixed a bug in coxnet to do with ties between death set and risk set

I would suggest using

```<code>devtools::install_version("glmnet",version=...,lib=<version-specific>)
</code>```

to install every version from 2.0-16 to 3.0-2 inclusive, each in a separate library, to make it easy (via library("glmnet", lib.loc=...) to load different package versions and bisect to find the specific change. (The intermediate versions were unreleased, so you'll be jumping from 2.0-18 to 3.0.)

I'm guessing that one of those coxnet bug fixes is (intentionally or as a side effect) responsible for the changes.

If it were in an accessible git repository you could use git bisect with a local copy to automate the process (maybe not worth it for such a small number of changepoints, but it doesn't look like the development tree is available: there's a nice pkgdown website but I don't see any links to a version control system.

If you have a lot of time on your hands you can download all of the archived tarballs and hunt through them for changes ...

Body:
I manage an internal code base that relies heavily upon the glmnet package. Upon upgrading to the newest version (v3.0.2) my unit tests started failing for the coefficients of a Cox model. The previous version of glmnet was v2.0.16 (R 3.5.2). I am now running R v3.6.2.

I have noticed that there is a new relax = argument that appears to use un-regularized fits in the path and I'd imagine this could cause a slight difference in the fits, however the default is relax = FALSE, so I doubt that is the issue.

Below is a reprex based on the mtcars dataset, fitting 2 randomly chosen features and renaming two variables to time and status so as to allow fitting of a Cox model. A proper reprex comparison is difficult as it would require different R installations, but this should allow anyone to reproduce the issue.

library(magrittr)
library(dplyr)
library(glmnet)
dat <- mtcars %>%
    select(mpg, disp, status = vs, time = hp) %>%   # select 2 features; assign time & status
    mutate_at(1:2, ~ {
      log10(.x) %>% subtract(mean(.)) %>% divide_by(sd(.))   # center & scale
    }) %>% as.matrix()
glmnet(dat[, 1:2], dat[, 3:4], family = "cox", lambda = 0)$beta   # fit model

The result for v3.0.2 is:

#> 2 x 1 sparse Matrix of class "dgCMatrix"
#>              s0
#> mpg   0.2293535
#> disp -1.8160387

The result for v2.0.16 is:

#> 2 x 1 sparse Matrix of class "dgCMatrix"
#>              s0
#> mpg   0.2154324
#> disp -1.8172714

Have others noticed similar discrepancies? I am somewhat surprised not to have found anyone else bumping into this same issue. Am I going to have to update all my unit tests :(

Insights and/or explanations greatly appreciated.
Thanks in advance.

Body:
Slightly too long for a comment:

I reproduced your results on Ubuntu 16.04 (using devtools::install_version(), see below).

2.0-16 to 3.0-2 spans several releases (and several more internally labeled, unreleased versions): the NEWS file makes several references to coxnet (presumably the internal function called for family="cox":

2.0-20:

Fixed a bug in internal function coxnet.deviance to do with input pred, as well as saturated loglike (missing) and weights

added a coxgrad function for computing the gradient

2.0-19:
  Fixed a bug in coxnet to do with ties between death set and risk set

I would suggest using

devtools::install_version("glmnet",version=...,lib=<version-specific>)

to install every version from 2.0-16 to 3.0-2 inclusive, each in a separate library, to make it easy (via library("glmnet", lib.loc=...) to load different package versions and bisect to find the specific change. (The intermediate versions were unreleased, so you'll be jumping from 2.0-18 to 3.0.)

I'm guessing that one of those coxnet bug fixes is (intentionally or as a side effect) responsible for the changes.

If it were in an accessible git repository you could use git bisect with a local copy to automate the process (maybe not worth it for such a small number of changepoints, but it doesn't look like the development tree is available: there's a nice pkgdown website but I don't see any links to a version control system.

If you have a lot of time on your hands you can download all of the archived tarballs and hunt through them for changes ...


问:
Invoke private method by Java ASM
I would like to invoke a private method without using Reflection: is it possible to hook a private native method by using ASM and invoke it?</p>

答:
The challenge is not to generate a class invoking the private method via ASM or a similar bytecode generation tool. The challenge is to get the bytecode into the JVM without being rejected by the verifier.

For OpenJDK/HotSpot, there is sun.misc.Unsafe which has the method defineAnonymousClass(Class<?>, byte[], Object[]) which is used for generating accessor classes, like the runtime classes implementing functional interfaces and invoking the private synthetic methods holding a lambda expression’s body.

You could use this to load your bytecode, using the private method’s declaring class as first argument, to make the method accessible. On the other hand, the JRE’s own use case implies that you don’t even need to generate such bytecode yourself:

```<code>MethodHandles.Lookup l = MethodHandles.privateLookupIn(Class.class, MethodHandles.lookup());
MethodHandle target = l.findSpecial(Class.class, "getDeclaredFields0",
    MethodType.methodType(Field[].class, boolean.class), Class.class);
BiFunction<Class<?>,Boolean,Field[]> a = (BiFunction)LambdaMetafactory.metafactory(
    l, "apply", MethodType.methodType(BiFunction.class), target.type().generic(),
    target, target.type().changeParameterType(1, Boolean.class))
    .getTarget().invokeExact();
</code>```

Then, you can call, e.g. a.apply(Class.class, false) which will invoke getDeclaredFields0 without Reflection.

privateLookupIn is a Java 9 method which will work if you’re in non-modular code or provide the necessary --add-opens option at JVM startup, to open java.base to your module. There will be a warning about the Reflection access and well, it is right about noting that such access “will be denied in a future release”. Anyway, How to hide warning "Illegal reflective access" in java 9 without JVM argument? might be interesting.

For Java 8, you’d need to hack into the Lookup class to get an appropriate lookup instance. This answer shows a solution, here is another approach.

Title: Invoke private method by Java ASM

Body:
The challenge is not to generate a class invoking the private method via ASM or a similar bytecode generation tool. The challenge is to get the bytecode into the JVM without being rejected by the verifier.

For OpenJDK/HotSpot, there is sun.misc.Unsafe which has the method defineAnonymousClass(Class<?>, byte[], Object[]) which is used for generating accessor classes, like the runtime classes implementing functional interfaces and invoking the private synthetic methods holding a lambda expression’s body.

You could use this to load your bytecode, using the private method’s declaring class as first argument, to make the method accessible. On the other hand, the JRE’s own use case implies that you don’t even need to generate such bytecode yourself:

MethodHandles.Lookup l = MethodHandles.privateLookupIn(Class.class, MethodHandles.lookup());
MethodHandle target = l.findSpecial(Class.class, "getDeclaredFields0",
    MethodType.methodType(Field[].class, boolean.class), Class.class);
BiFunction<Class<?>,Boolean,Field[]> a = (BiFunction)LambdaMetafactory.metafactory(
    l, "apply", MethodType.methodType(BiFunction.class), target.type().generic(),
    target, target.type().changeParameterType(1, Boolean.class))
    .getTarget().invokeExact();

Then, you can call, e.g. a.apply(Class.class, false) which will invoke getDeclaredFields0 without Reflection.

privateLookupIn is a Java 9 method which will work if you’re in non-modular code or provide the necessary --add-opens option at JVM startup, to open java.base to your module. There will be a warning about the Reflection access and well, it is right about noting that such access “will be denied in a future release”. Anyway, How to hide warning "Illegal reflective access" in java 9 without JVM argument? might be interesting.

For Java 8, you’d need to hack into the Lookup class to get an appropriate lookup instance. This answer shows a solution, here is another approach.


问:
How to validate data so no incorrect data is saved to the database, using javascript
I would like to validate my code for adding a product to sqlite database, but dont know how I do that in the best way. I have been using this:

routes.post('/product/', async (req, res)

and await for adding a product to the sqlite database, which was successful.
What I would like to accomplish is to check so the same product can't be added twice. Do you have any tips for how I can do that?
I was thinking if I could use an if statement to check that..

答: One option is to get all the product from the db inside routes.post('/product/', async (req, res) and compare it with the request


问:
How can I use SSL encryption in WCF
I have simple application from this tutorial: WCF 4 Getting Started Tutorial

How can I implement some encryption? Something like HTTPS (SSL?).

Example code from tutorial.

```<code>static void Main(string[] args)
    {

        // Step 1 of the address configuration procedure: Create a URI to serve as the base address.
        Uri baseAddress = new Uri("http://localhost:8000/ServiceModelSamples/Service");

        // Step 2 of the hosting procedure: Create ServiceHost
        ServiceHost selfHost = new ServiceHost(typeof(CalculatorService), baseAddress);

        try
        {

            // Step 3 of the hosting procedure: Add a service endpoint.
            selfHost.AddServiceEndpoint(
                typeof(ICalculator),
                new WSHttpBinding(),
                "CalculatorService");

            // Step 4 of the hosting procedure: Enable metadata exchange.
            ServiceMetadataBehavior smb = new ServiceMetadataBehavior();
            smb.HttpGetEnabled = true;
            selfHost.Description.Behaviors.Add(smb);

            // Step 5 of the hosting procedure: Start (and then stop) the service.
            selfHost.Open();
            Console.WriteLine("The service is ready.");
            Console.WriteLine("Press <ENTER> to terminate service.");
            Console.WriteLine();
            Console.ReadLine();

            // Close the ServiceHostBase to shutdown the service.
            selfHost.Close();
        }
        catch (CommunicationException ce)
        {
            Console.WriteLine("An exception occurred: {0}", ce.Message);
            selfHost.Abort();
        }

    }
</code>```

答:
The easiest way is probably to use transport security. See HTTP Transport Security. It describes how to configure SSL for both self-hosted and IIS-hosted services.

If all you need is encryption, then that's it. If you also want client authentication, then the client should use its own certificate which the service must accept.

Title: How can I use SSL encryption in WCF

Body:
I have simple application from this tutorial: WCF 4 Getting Started Tutorial

How can I implement some encryption? Something like HTTPS (SSL?).

Example code from tutorial.

static void Main(string[] args)
    {

        // Step 1 of the address configuration procedure: Create a URI to serve as the base address.
        Uri baseAddress = new Uri("http://localhost:8000/ServiceModelSamples/Service");

        // Step 2 of the hosting procedure: Create ServiceHost
        ServiceHost selfHost = new ServiceHost(typeof(CalculatorService), baseAddress);

        try
        {

            // Step 3 of the hosting procedure: Add a service endpoint.
            selfHost.AddServiceEndpoint(
                typeof(ICalculator),
                new WSHttpBinding(),
                "CalculatorService");

            // Step 4 of the hosting procedure: Enable metadata exchange.
            ServiceMetadataBehavior smb = new ServiceMetadataBehavior();
            smb.HttpGetEnabled = true;
            selfHost.Description.Behaviors.Add(smb);

            // Step 5 of the hosting procedure: Start (and then stop) the service.
            selfHost.Open();
            Console.WriteLine("The service is ready.");
            Console.WriteLine("Press <ENTER> to terminate service.");
            Console.WriteLine();
            Console.ReadLine();

            // Close the ServiceHostBase to shutdown the service.
            selfHost.Close();
        }
        catch (CommunicationException ce)
        {
            Console.WriteLine("An exception occurred: {0}", ce.Message);
            selfHost.Abort();
        }

    }


问:
Firestore transaction with multiple get
I'm trying to run a transaction with a variable number of read operations.
I put the read () operations before than update ().

Reading the Firestore doc on https://cloud.google.com/firestore/docs/manage-data/transactions

"A transaction consists of any number of get() operations followed by any number of write operations such as set(), update(), or delete()"

And

When using transactions, note that:

Read operations must come before write operations.

A function calling a transaction (transaction function) might run more         than once if a current edit affects a document that the
  transaction reads.

Transaction functions should not directly modify application state.

But is not provided an implementation.
When I try to run the code below, I get that the transaction function is runned more time and then I obtain an exception.
But if I try with only one get all goes OK.

```<code>const reservationCol = this.db.firestore.collection('reservations');
        return this.db.firestore.runTransaction(t => {
         return Promise.all([
            t.get(reservationCol.doc('id1')),
            t.get(reservationCol.doc(('id2')))]
        ).then((responses) => {

        let found = false;
        responses.forEach(resp => {
               if (resp.exists)
                    found = true;
         });
         if (!found)
         {
               entity.id='id1';
               t.set(reservationCol.doc(entity.id), entity);
               return Promise.resolve('ok');
          }
          else
              return Promise.reject('exist');
         });
    });
</code>```

答:
I was facing the same problem and decided to use a combination of a batched write and "normal" reads.
The decision was guided by the fact that I needed to make many reads that did not rely on each other. At first I used a method similar to the one proposed by Derrick above, but it proved not sustainable for may reads.
The code dictates that every loop is blocking to the next one.
What I did was to batch all the reads to run in parallel with Promise.all
The disadvantage of this is that you dont take advantage of transaction features, but since the field I was iterested in was not changing, it made sense
Here's my sample code

```<code>const batch = firestore().batch()
 const readPromises = invoiceValues.map(val => {
                        return orderCollection(omcId).where(<query field>, '<query operation>', <query>).get()
                    })

                    return Promise.all(readPromises).then(orderDocs => {
                  //Perform batch operations here
                        return batch.commit()
                     })
</code>```

This has proven to be more efficient for many reads, while remaining safe since the fields I'm interested in dont change

Title: Firestore transaction with multiple get

Body:
I'm trying to run a transaction with a variable number of read operations.
I put the read () operations before than update ().

Reading the Firestore doc on https://cloud.google.com/firestore/docs/manage-data/transactions

"A transaction consists of any number of get() operations followed by any number of write operations such as set(), update(), or delete()"

And

When using transactions, note that:

Read operations must come before write operations.

A function calling a transaction (transaction function) might run more         than once if a current edit affects a document that the
  transaction reads.

Transaction functions should not directly modify application state.

But is not provided an implementation.
When I try to run the code below, I get that the transaction function is runned more time and then I obtain an exception.
But if I try with only one get all goes OK.

const reservationCol = this.db.firestore.collection('reservations');
        return this.db.firestore.runTransaction(t => {
         return Promise.all([
            t.get(reservationCol.doc('id1')),
            t.get(reservationCol.doc(('id2')))]
        ).then((responses) => {

        let found = false;
        responses.forEach(resp => {
               if (resp.exists)
                    found = true;
         });
         if (!found)
         {
               entity.id='id1';
               t.set(reservationCol.doc(entity.id), entity);
               return Promise.resolve('ok');
          }
          else
              return Promise.reject('exist');
         });
    });

Body:
I was facing the same problem and decided to use a combination of a batched write and "normal" reads.
The decision was guided by the fact that I needed to make many reads that did not rely on each other. At first I used a method similar to the one proposed by Derrick above, but it proved not sustainable for may reads.
The code dictates that every loop is blocking to the next one.
What I did was to batch all the reads to run in parallel with Promise.all
The disadvantage of this is that you dont take advantage of transaction features, but since the field I was iterested in was not changing, it made sense
Here's my sample code

const batch = firestore().batch()
 const readPromises = invoiceValues.map(val => {
                        return orderCollection(omcId).where(<query field>, '<query operation>', <query>).get()
                    })

                    return Promise.all(readPromises).then(orderDocs => {
                  //Perform batch operations here
                        return batch.commit()
                     })

This has proven to be more efficient for many reads, while remaining safe since the fields I'm interested in dont change


问:
Solr Container
What is better container for SOLR: Tomcat or Jetty</p>

答:
Don't think it especially matters, they'll both work.

If you're using either of them already, stick with it.

If not... well, given that Solr and Lucene are both Apache projects, it seems simpler to also go with Tomcat.

If you do want to go with Jetty though, you can.

OwnerDisplayName: Mote

ContentLicense: CC BY-SA 2.5

Title: Solr Container

OwnerDisplayName: Peter Boughton


问:
jqGrid hiding Plus icon
I am using jqGrid with subGrid. But at some row i do not want to show the Plus icon. Because i do not want to allow user to view the subgrid on that perticular row. So can any body help me how to hide the plus icon over there. I tried with the below code but no luck.

```<code>afterInsertRow : function(rowid, rowdata, rowelem) {
$("tr[id="+rowid+"]>td.ui-sgcollapsed>a")
                           .click(function(){return false;})
}
</code>```

By doing above i can disable the Plus icon that is on click of plus icon subgrid will not open. But, my requirement is to not to show the Plus icon at all.
when i am doing like below then borders are not coming in IE6 while in mozila borders are coming.

```<code>$("tr#1.ui-widget-content td:first span").removeAttr("class");
</code>```

Also by wrting above code it is on click of the cell again Plus icon comes up.

Can any body tell me how to hide plus icon. and disable its click event?

答:
This works even if you have activate multiselect. (:first referres to checkbox column)</p>

```<code>afterInsertRow: function(rowid, rowdata, rowelem) {
   $("tr[id=" + rowid + "]>td[aria-describedby$=_subgrid]").removeAttr("class");
   $("tr[id=" + rowid + "]>td[aria-describedby$=_subgrid]").html(" ");
}
</code>```

Title: jqGrid hiding Plus icon

Body:
I am using jqGrid with subGrid. But at some row i do not want to show the Plus icon. Because i do not want to allow user to view the subgrid on that perticular row. So can any body help me how to hide the plus icon over there. I tried with the below code but no luck.

afterInsertRow : function(rowid, rowdata, rowelem) {
$("tr[id="+rowid+"]>td.ui-sgcollapsed>a")
                           .click(function(){return false;})
}

By doing above i can disable the Plus icon that is on click of plus icon subgrid will not open. But, my requirement is to not to show the Plus icon at all.
when i am doing like below then borders are not coming in IE6 while in mozila borders are coming.

$("tr#1.ui-widget-content td:first span").removeAttr("class");

Also by wrting above code it is on click of the cell again Plus icon comes up.

Can any body tell me how to hide plus icon. and disable its click event?

Body:
This works even if you have activate multiselect. (:first referres to checkbox column)

afterInsertRow: function(rowid, rowdata, rowelem) {
   $("tr[id=" + rowid + "]>td[aria-describedby$=_subgrid]").removeAttr("class");
   $("tr[id=" + rowid + "]>td[aria-describedby$=_subgrid]").html("&nbsp;");
}


问:
Pagination trouble with php and postgresql
I am trying to do a simple pagination exercise with HTML table but only page 2 shows info. It doesn't show table information when I hit 'previous' button.

For example, when I open the page, it shows nothing. When I click on page 2, there is information. When I reach the end, all is ok but then I click 'previous' button or page 1 and it does not show anything again.

```<code>$rowperpage = 5; // Total rows display
 $row = 0;

 if(isset($_GET['page'])){
  $row = $_GET['page']-1;
  if($row < 0){
   $row = 0;
  }
 }

$link = pg_connect("host=127.0.0.1 port=5432 dbname=swxxxg5_en user=swapng5_control password=xxxxxxxx");
$query = "select id from registrados";
$resultfichados = pg_query($link, $query);
$totalfichados = pg_num_rows($resultfichados);
$allcount = pg_num_rows($resultfichados);
//echo $allcount;
$limitrow = $row*$rowperpage;

$db = pg_connect("host=127.0.0.1 port=5432 dbname=swxxxg5_en user=swapng5_control password=xxxxxxxxxxxxx");
$result = pg_query($db,"select
id,
usuario,
nombre,
apellido,
flag,
reputacion,
ingreso,
lastlogin,
passport,
loyalty,
certified
from registrados order by id asc limit " . $limitrow . " offset 0");
//from registrados order by reputacion asc limit 5 offset 0");

?>
<table align='center' class='table table-hover table-striped' id='t01'>
<td align='center' style='font-weight:bold; color:#fff; background: #3498db;'>id</td>
<td align='center' style='font-weight:bold; color:#fff; background: #3498db;'>Usuario</td>
<td align='center' style='font-weight:bold; color:#fff; background: #3498db;'>Nombre</td>
<td align='center' style='font-weight:bold; color:#fff; background: #3498db;'>Apellido</td>
<td align='center' style='font-weight:bold; color:#fff; background: #3498db;'>Flag</td>
<td align='center' style='font-weight:bold; color:#fff; background: #3498db;'>Reputacion</td>
<td align='center' style='font-weight:bold; color:#fff; background: #3498db;'>Ingreso</td>
<td align='center' style='font-weight:bold; color:#fff; background: #3498db;'>Lastlogin</td>
<td align='center' style='font-weight:bold; color:#fff; background: #3498db;'>Passport</td>
<td align='center' style='font-weight:bold; color:#fff; background: #3498db;'>Loyalty</td>
<td align='center' style='font-weight:bold; color:#fff; background: #3498db;'>Certified</td>
<?php
while($rowdatauser=pg_fetch_assoc($result)){
echo "<tr>";
echo "<td align='center' width='200' style='color:#7f8c8d; font-weight:bold;'>" . $rowdatauser['id'] . "</td>";
echo "<td align='center' width='200' style='color:#7f8c8d; font-weight:bold;'>" . $rowdatauser['usuario'] . "</td>";
echo "<td align='center' width='200'>" . $rowdatauser['nombre'] . "</td>";
echo "<td align='center' width='60'>" .  $rowdatauser['apellido'] . "</td>";
echo "<td align='center' width='60'  style='background: #e74c3c; color:#fff; font-weight:bold;'>" .  $rowdatauser['flag'] . "</td>";
echo "<td align='center' width='200' style='background: #ff9900; font-weight:bold;'>" . $rowdatauser['reputacion'] . "</td>";
echo "<td align='center' width='200'>" . $rowdatauser['ingreso'] . "</td>";
echo "<td align='center' width='200' style='background: #58c0ce;'>" . $rowdatauser['lastlogin'] . "</td>";
echo "<td align='center' width='200'>" . $rowdatauser['passport'] . "</td>";
echo "<td align='center' width='200'style='background: #7863a0; color:white; font-weight:bold;'>" . $rowdatauser['loyalty'] . "</td>";
echo "<td align='center' width='200'>" . $rowdatauser['certified'] . "</td>";
echo "</tr>";
}
echo "   <td align='center' style='background: #fff;'></td>";
echo "   <td align='center' style='background: #fff;'></td>";
echo "   <td align='center' style='background: #fff;'></td>";
echo "   <td align='center' style='background: #fff;'></td>";
echo "   <td align='center' style='background: #fff;'></td>";
echo "   <td align='center' style='background: #fff;'></td>";
echo "   <td align='center' style='background: #fff;'></td>";
echo "   <td align='center' style='background: #fff;'></td>";
echo "   <td align='center' style='background: #fff;'></td>";
echo "   <td align='center' style='background: #4567;'>TOTALES</td>";
echo "<td align='center' width='200' style='background: #eee;'>", $totalfichados ,"</td>";
echo "</table>";

?>

 <!-- Number list (start) -->
 <ul class="pagination">

 <?php
 // calculate total pages
 $total_pages = ceil($allcount / $rowperpage);

 $i = 1;$prev = 0;

 // Total number list show
 $numpages = 5;

 // Set previous page number and start page
 if(isset($_GET['next'])){
  $i = $_GET['next']+1;
  $prev = $_GET['next'] - ($numpages);
 }

 if($prev <= 0) $prev = 1;
 if($i == 0) $i=1;

 // Previous button next page number

 $prevnext = 0;
 if(isset($_GET['next'])){
  $prevnext = ($_GET['next'])-($numpages+1);
  if($prevnext < 0){
   $prevnext = 0;
  }
 }

 // Previous Button
 echo '<li ><a href="?page='.$prev.'&next='.$prevnext.'">Previous</a></li>';

 if($i != 1){
  echo '<li ><a href="?page='.($i-1).'&next='.$_GET['next'].'" ';
  if( ($i-1) == $_GET['page'] ){
   echo ' class="active" ';
  }
  echo ' >'.($i-1).'</a></li>';
 }

 // Number List
 for ($shownum = 0; $i<=$total_pages; $i++,$shownum++) {
  if($i%($numpages+1) == 0){
   break;
  }

  if(isset($_GET['next'])){
   echo "<li><a href='?page=".$i."&next=".$_GET['next']."'";
  }else{
   echo "<li><a href='?page=".$i."'";
  }

  // Active
  if(isset($_GET['page'])){
   if ($i==$_GET['page'])
    echo " class='active'";
   }
   echo ">".$i."</a></li> ";
  }

  // Set next button
  $next = $i+$rowperpage;
  if(($next*$rowperpage) > $allcount){
   $next = ($next-$rowperpage)*$rowperpage;
  }

  // Next Button
  if( ($next-$rowperpage) < $allcount ){
   if($shownum == ($numpages)){
    echo '<li ><a href="?page='.$i.'&next='.$i.'">Next</a></li>';
   }
  }

  ?>
 </ul>
 <!-- Numbered List (end) -->
</code>```

答:
I guess you are trying to paginaate using LIMIT a OFFSET b system. In that case, your a should be the page size and b the place where you start.
This system has it's limitations, like when rows are added or removed the same time you are viewing data, but if this is acceptable, then it might be the easiest way.

Other ways to paginate are shown in this article.

Two notes: One DB handle is enough, you don't need two connections. And if you want to count the rows in yous set, SELECT count(*) FROM... is easier than pg_num_rows()

Body:
I am trying to do a simple pagination exercise with HTML table but only page 2 shows info. It doesn't show table information when I hit 'previous' button.

For example, when I open the page, it shows nothing. When I click on page 2, there is information. When I reach the end, all is ok but then I click 'previous' button or page 1 and it does not show anything again.

$rowperpage = 5; // Total rows display
 $row = 0;

 if(isset($_GET['page'])){
  $row = $_GET['page']-1;
  if($row < 0){
   $row = 0;
  }
 }

$link = pg_connect("host=127.0.0.1 port=5432 dbname=swxxxg5_en user=swapng5_control password=xxxxxxxx");
$query = "select id from registrados";
$resultfichados = pg_query($link, $query);
$totalfichados = pg_num_rows($resultfichados);
$allcount = pg_num_rows($resultfichados);
//echo $allcount;
$limitrow = $row*$rowperpage;

$db = pg_connect("host=127.0.0.1 port=5432 dbname=swxxxg5_en user=swapng5_control password=xxxxxxxxxxxxx");
$result = pg_query($db,"select
id,
usuario,
nombre,
apellido,
flag,
reputacion,
ingreso,
lastlogin,
passport,
loyalty,
certified
from registrados order by id asc limit " . $limitrow . " offset 0");
//from registrados order by reputacion asc limit 5 offset 0");

?>

id
Usuario
Nombre
Apellido
Flag
Reputacion
Ingreso
Lastlogin
Passport
Loyalty
Certified
<?php
while($rowdatauser=pg_fetch_assoc($result)){
echo "
";
echo "" . $rowdatauser['id'] . "	";
echo "" . $rowdatauser['usuario'] . "	";
echo "" . $rowdatauser['nombre'] . "	";
echo "" .  $rowdatauser['apellido'] . "	";
echo "" .  $rowdatauser['flag'] . "	";
echo "" . $rowdatauser['reputacion'] . "	";
echo "" . $rowdatauser['ingreso'] . "	";
echo "" . $rowdatauser['lastlogin'] . "	";
echo "" . $rowdatauser['passport'] . "	";
echo "" . $rowdatauser['loyalty'] . "	";
echo "" . $rowdatauser['certified'] . "	";
echo "
";
}
echo "   	";
echo "   	";
echo "   	";
echo "   	";
echo "   	";
echo "   	";
echo "   	";
echo "   	";
echo "   	";
echo "   TOTALES	";
echo "", $totalfichados ,"	";
echo "
";

?>

 <?php
 // calculate total pages
 $total_pages = ceil($allcount / $rowperpage);

 $i = 1;$prev = 0;

 // Total number list show
 $numpages = 5;

 // Set previous page number and start page
 if(isset($_GET['next'])){
  $i = $_GET['next']+1;
  $prev = $_GET['next'] - ($numpages);
 }

 if($prev <= 0) $prev = 1;
 if($i == 0) $i=1;

 // Previous button next page number

 $prevnext = 0;
 if(isset($_GET['next'])){
  $prevnext = ($_GET['next'])-($numpages+1);
  if($prevnext < 0){
   $prevnext = 0;
  }
 }

 // Previous Button
 echo '
Previous
';

 if($i != 1){
  echo '
'.($i-1).'
';
 }

 // Number List
 for ($shownum = 0; $i<=$total_pages; $i++,$shownum++) {
  if($i%($numpages+1) == 0){
   break;
  }

  if(isset($_GET['next'])){
   echo "
<a href='?page=".$i."&next=".$_GET['next']."'";
  }else{
   echo "
".$i."
 ";
  }

  // Set next button
  $next = $i+$rowperpage;
  if(($next*$rowperpage) > $allcount){
   $next = ($next-$rowperpage)*$rowperpage;
  }

  // Next Button
  if( ($next-$rowperpage) < $allcount ){
   if($shownum == ($numpages)){
    echo '
Next
';
   }
  }

  ?>


问:
Flask SQLAlchemy query with order_by returns error no such column
Here is my models:

```<code>from flask import Flask
from flask_sqlalchemy import SQLAlchemy

app = Flask(__name__)
db = SQLAlchemy(app)

class Person(db.Model):
    __tablename__ = 'persons'
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(64), nullable=False, unique=True)
    pets = db.relationship('Pet', backref='owner', lazy='dynamic')

    def __init__(self, *args, **kwargs):
        super(Person, self).__init__(*args, **kwargs)

    def __repr__(self):
        return f'<Person id:{self.id} name:{self.name}>'

class Pet(db.Model):
    __tablename__ = 'pets'
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(64), nullable=False, unique=True)
    owner_id = db.Column(db.Integer, db.ForeignKey('persons.id'), nullable=False)

    def __init__(self, *args, **kwargs):
        super(Pet, self).__init__(*args, **kwargs)

    def __repr__(self):
        return f'<Pet id:{self.id} name:{self.name} owner_id:{self.owner_id}>'
</code>```

I`m trying to get persons list ordered by count of pets with this query:

```<code>persons = Person.query.order_by(Person.pets).all()
</code>```

And getting this error:

```<code>sqlalchemy.exc.OperationalError: (sqlite3.OperationalError) no such column: pets.owner_id
[SQL: SELECT persons.id AS persons_id, persons.name AS persons_name
FROM persons ORDER BY persons.id = pets.owner_id]
</code>```

What I`m doing wrong?
I have a suggestion that I need to make a request with join(), but research in google did not give working solutions.

答:
If you inspect the SQL, you'll note that there is no FROM item pets, and so ORDER BY persons.id = pets.owner_id fails. This happens because the relationship attribute Person.pets renders as its ON clause in query context, or in other words as persons.id = pets.owner_id. There are many ways to form the proper query, for example using a JOIN and GROUP BY:

```<code>Person.query.\
    outerjoin(Person.pets).\
    group_by(Person.id).\
    order_by(func.count(Pet.id)).\
    all()
</code>```

The LEFT OUTER JOIN ensures that persons without pets are considered as well.

Body:
Here is my models:

from flask import Flask
from flask_sqlalchemy import SQLAlchemy

app = Flask(__name__)
db = SQLAlchemy(app)

class Person(db.Model):
    __tablename__ = 'persons'
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(64), nullable=False, unique=True)
    pets = db.relationship('Pet', backref='owner', lazy='dynamic')

    def __init__(self, *args, **kwargs):
        super(Person, self).__init__(*args, **kwargs)

    def __repr__(self):
        return f'<Person id:{self.id} name:{self.name}>'

class Pet(db.Model):
    __tablename__ = 'pets'
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(64), nullable=False, unique=True)
    owner_id = db.Column(db.Integer, db.ForeignKey('persons.id'), nullable=False)

    def __init__(self, *args, **kwargs):
        super(Pet, self).__init__(*args, **kwargs)

    def __repr__(self):
        return f'<Pet id:{self.id} name:{self.name} owner_id:{self.owner_id}>'

I`m trying to get persons list ordered by count of pets with this query:

persons = Person.query.order_by(Person.pets).all()

And getting this error:

sqlalchemy.exc.OperationalError: (sqlite3.OperationalError) no such column: pets.owner_id
[SQL: SELECT persons.id AS persons_id, persons.name AS persons_name
FROM persons ORDER BY persons.id = pets.owner_id]

What I`m doing wrong?
I have a suggestion that I need to make a request with join(), but research in google did not give working solutions.

Body:
If you inspect the SQL, you'll note that there is no FROM item pets, and so ORDER BY persons.id = pets.owner_id fails. This happens because the relationship attribute Person.pets renders as its ON clause in query context, or in other words as persons.id = pets.owner_id. There are many ways to form the proper query, for example using a JOIN and GROUP BY:

Person.query.\
    outerjoin(Person.pets).\
    group_by(Person.id).\
    order_by(func.count(Pet.id)).\
    all()

The LEFT OUTER JOIN ensures that persons without pets are considered as well.


Title: Get Start and Stop Values For Incrementing Groups in NumPy Vector

Body:
I have a NumPy vector that is sorted and contains no repeats like:

[  1,   2,   6,  12,  13,  14,  16,  18,  19,  22,  23,  26,  29,
  31,  32,  34,  37,  38,  39,  40,  42,  43,  44,  49,  50,  52,
  55,  63,  64,  67,  68,  75,  78,  82,  84,  86,  88,  90,  93,
  95,  97,  98, 100, 103, 104, 106, 114, 119, 123, 124, 127, 129,
 130, 131, 134, 137, 139, 141, 142, 146, 149, 151, 153, 154, 155,
 159, 160, 161, 162, 165, 166, 167, 171, 173, 180, 181, 184, 186,
 189, 191, 194, 195, 196, 202, 208, 210, 212, 215, 216, 218, 223,
 224, 225, 226, 231, 233, 235, 239, 240, 241, 245, 248, 252, 253,
 259, 260, 261, 264, 271, 272, 273, 276, 279, 280, 285, 287, 290,
 291, 292, 293, 296, 297, 301, 304, 306, 307, 311, 312, 313, 319,
 320, 323, 324, 325, 326, 332, 335, 336, 337, 338, 339, 341, 342,
 345, 346, 349, 352, 355, 359, 364, 365, 367, 369, 373, 376, 378,
 380, 382, 386, 387, 388, 391, 399, 400, 401, 405, 408, 409, 410,
 413, 414, 415, 416, 423, 427, 428, 429, 432, 433, 434, 435, 437,
 439, 440, 443, 448, 449, 451, 453, 455, 459, 461, 464, 465, 466,
 467, 468, 470, 471, 473, 476, 478, 482, 487, 488, 491, 495, 498,
 501, 502, 503, 505, 506, 507, 514, 518, 519, 520, 522, 523, 525,
 528, 530, 532, 534, 538, 539, 540, 544, 550, 551, 556, 558, 568,
 571, 573, 577, 578, 582, 584, 585, 592, 597, 599, 603, 605, 607,
 609, 610, 612, 616, 618, 621, 623, 625, 626, 628, 630, 631, 632,
 633, 636, 637, 639, 642, 644, 647, 651, 653, 654, 656, 661, 662,
 666, 668, 670, 672, 673, 674, 675, 676, 682, 684, 687, 688, 690,
 692, 693, 694, 696, 697, 698, 699, 705, 706, 707, 708, 713, 714,
 719, 726, 727, 729, 730, 736, 737, 739, 740, 741, 742, 744, 748,
 749, 753, 758, 759, 762, 766, 771, 772, 774, 775, 778, 780, 782,
 786, 787, 789, 791, 793, 796, 797, 798, 799, 803, 804, 807, 809,
 811, 814, 815, 817, 819, 821, 827, 831, 833, 837, 842, 846, 849,
 851, 854, 855, 858, 865, 866, 867, 868, 870, 872, 873, 874, 880,
 881, 882, 884, 885, 890, 892, 893, 894, 895, 896, 897, 899, 900,
 902, 908, 912, 913, 915, 916, 920, 921, 924, 927, 930, 933, 941,
 942, 946, 950, 953, 957, 960, 963, 964, 967, 969, 972, 973, 975,
 978, 981, 983, 985, 986, 991, 992, 993, 995]

What I need is to find the start and stop values where consecutive (increment by one) numbers exist. So the output would be something like:

[[  1,  2],
 [  6,  6],
 [ 12, 14],
 [ 16, 16],
 [ 18, 19],
 [ 22, 23],
 [ 26, 26],
 [ 29, 29],
 [ 31, 32],
 [ 34, 34],
 [ 37, 40],
 [ 42, 44],
 .
 .
 .]

I think that I could do something like (x[:-1] - x[1:]) == 1 to build a True/False vector but then I'd have to loop through this vector to identify the start/stop values. I can't seem to come up with a vectorized solution beyond this.

Body:
A similar answer for identifying consecutive zeros offers the following function:

def zero_runs(a):  # from link
    iszero = np.concatenate(([0], np.equal(a, 0).view(np.int8), [0]))
    absdiff = np.abs(np.diff(iszero))
    ranges = np.where(absdiff == 1)[0].reshape(-1, 2)
    return ranges

So, we can do:

x = np.array(
[  1,   2,   6,  12,  13,  14,  16,  18,  19,  22,  23,  26,  29,
  31,  32,  34,  37,  38,  39,  40,  42,  43,  44,  49,  50,  52,
  55,  63,  64,  67,  68,  75,  78,  82,  84,  86,  88,  90,  93,
  95,  97,  98, 100, 103, 104, 106, 114, 119, 123, 124, 127, 129,
 130, 131, 134, 137, 139, 141, 142, 146, 149, 151, 153, 154, 155,
 159, 160, 161, 162, 165, 166, 167, 171, 173, 180, 181, 184, 186,
 189, 191, 194, 195, 196, 202, 208, 210, 212, 215, 216, 218, 223,
 224, 225, 226, 231, 233, 235, 239, 240, 241, 245, 248, 252, 253,
 259, 260, 261, 264, 271, 272, 273, 276, 279, 280, 285, 287, 290,
 291, 292, 293, 296, 297, 301, 304, 306, 307, 311, 312, 313, 319,
 320, 323, 324, 325, 326, 332, 335, 336, 337, 338, 339, 341, 342,
 345, 346, 349, 352, 355, 359, 364, 365, 367, 369, 373, 376, 378,
 380, 382, 386, 387, 388, 391, 399, 400, 401, 405, 408, 409, 410,
 413, 414, 415, 416, 423, 427, 428, 429, 432, 433, 434, 435, 437,
 439, 440, 443, 448, 449, 451, 453, 455, 459, 461, 464, 465, 466,
 467, 468, 470, 471, 473, 476, 478, 482, 487, 488, 491, 495, 498,
 501, 502, 503, 505, 506, 507, 514, 518, 519, 520, 522, 523, 525,
 528, 530, 532, 534, 538, 539, 540, 544, 550, 551, 556, 558, 568,
 571, 573, 577, 578, 582, 584, 585, 592, 597, 599, 603, 605, 607,
 609, 610, 612, 616, 618, 621, 623, 625, 626, 628, 630, 631, 632,
 633, 636, 637, 639, 642, 644, 647, 651, 653, 654, 656, 661, 662,
 666, 668, 670, 672, 673, 674, 675, 676, 682, 684, 687, 688, 690,
 692, 693, 694, 696, 697, 698, 699, 705, 706, 707, 708, 713, 714,
 719, 726, 727, 729, 730, 736, 737, 739, 740, 741, 742, 744, 748,
 749, 753, 758, 759, 762, 766, 771, 772, 774, 775, 778, 780, 782,
 786, 787, 789, 791, 793, 796, 797, 798, 799, 803, 804, 807, 809,
 811, 814, 815, 817, 819, 821, 827, 831, 833, 837, 842, 846, 849,
 851, 854, 855, 858, 865, 866, 867, 868, 870, 872, 873, 874, 880,
 881, 882, 884, 885, 890, 892, 893, 894, 895, 896, 897, 899, 900,
 902, 908, 912, 913, 915, 916, 920, 921, 924, 927, 930, 933, 941,
 942, 946, 950, 953, 957, 960, 963, 964, 967, 969, 972, 973, 975,
 978, 981, 983, 985, 986, 991, 992, 993, 995]
)

indices = zero_runs(np.diff(x)-1)

out = np.vstack((y[inx[:, 0]], y[inx[:, 1]])).T

And out returns only the places where there are runs (and not single values, which is what I want):

array([[  1,   2],
       [ 12,  14],
       [ 18,  19],
       [ 22,  23],
       [ 31,  32],
       [ 37,  40],
       [ 42,  44],
       [ 49,  50],
       [ 63,  64],
       [ 67,  68],
       [ 97,  98],
       [103, 104],
       [123, 124],
       [129, 131],
       [141, 142],
       [153, 155],
       [159, 162],
       [165, 167],
       [180, 181],
       [194, 196],
       [215, 216],
       [223, 226],
       [239, 241],
       [252, 253],
       [259, 261],
       [271, 273],
       [279, 280],
       [290, 293],
       [296, 297],
       [306, 307],
       [311, 313],
       [319, 320],
       [323, 326],
       [335, 339],
       [341, 342],
       [345, 346],
       [364, 365],
       [386, 388],
       [399, 401],
       [408, 410],
       [413, 416],
       [427, 429],
       [432, 435],
       [439, 440],
       [448, 449],
       [464, 468],
       [470, 471],
       [487, 488],
       [501, 503],
       [505, 507],
       [518, 520],
       [522, 523],
       [538, 540],
       [550, 551],
       [577, 578],
       [584, 585],
       [609, 610],
       [625, 626],
       [630, 633],
       [636, 637],
       [653, 654],
       [661, 662],
       [672, 676],
       [687, 688],
       [692, 694],
       [696, 699],
       [705, 708],
       [713, 714],
       [726, 727],
       [729, 730],
       [736, 737],
       [739, 742],
       [748, 749],
       [758, 759],
       [771, 772],
       [774, 775],
       [786, 787],
       [796, 799],
       [803, 804],
       [814, 815],
       [854, 855],
       [865, 868],
       [872, 874],
       [880, 882],
       [884, 885],
       [892, 897],
       [899, 900],
       [912, 913],
       [915, 916],
       [920, 921],
       [941, 942],
       [963, 964],
       [972, 973],
       [985, 986],
       [991, 993]])


问:
FileExist returns false
I have a folder with 700+ .jpgs. I also have a Textbox with one filename per line.
I want to check which file does not exist in the folder, but should be there.

This is my code:

```<code>Dim Counter As Integer = 0
For Each Line As String In tbFileNames.Lines
    Counter = Counter + 1
    If (IO.File.Exists(tbFolder.Text & "\" & tbFileNames.Lines(Counter - 1).ToString & ".jpg")) = False Then
        tbNotExistingFiles.Text = tbNotExistingFiles.Text & vbNewLine & (tbFileNames.Lines(Counter - 1).ToString)
    Else
    End If
Next
</code>```

Problem: I get more than 300 "missing" files, but there should be only 7. When I search for the output filenames, they are in the folder, so the FileExists functions returns false, but it shouldn't.

Where is the problem? Is it the amount of files?

答:
According to this line:

If (IO.File.Exists(tbFolder.Text & "\" & tbFileNames.Lines(Counter - 1).ToString & ".jpg")) = False
```

<p>Which can be interpreted as:</p>

<ul>
<li>The <code>tbFolder</code> TextBox contains the directory's path where the images are located.</li>
<li>The <code>tbFileNames</code> TextBox contains the main and complete file names. One file name per line.</li>
<li>Appending the extension <code>& ".jpg"</code> means that the file names in the <code>tbFileNames</code> TextBox are without extensions. And,</li>
<li>You need to get a list of the missing files in that directory and show the result in the <code>tbNotExistingFiles</code> TextBox.</li>
</ul>

<p>If my interpretation is correct, then you can achieve that using the extension methods like:</p>

<pre class="lang-vb prettyprint-override"><code>Imports System.IO
'...

Dim missingFiles = tbFileNames.Lines.
    Select(Function(x) $"{x.ToLower}.jpg").
    Except(Directory.GetFiles(tbFolder.Text).
    Select(Function(x) Path.GetFileName(x.ToLower)))

tbNotExistingFiles.Text = String.Join(ControlChars.NewLine, missingFiles)
</code>```

Or by a LINQ query:

Dim missingFiles = From x In tbFileNames.Lines
                    Where (
                        Aggregate y In Directory.EnumerateFiles(tbFolder.Text)
                            Where Path.GetFileName(y).ToLower.Equals($"{x.ToLower}.jpg")
                                Into Count()
                        ) = 0
                    Select x

'Alternative to tbNotExistingFiles.Text = ...
tbNotExistingFiles.Lines = missingFiles.ToArray
```

<p>Note that, there's no need nor use for the <code>File.Exists(..)</code> function in the preceding snippets. Just in case you prefer your approach using <code>For..Loop</code> and <code>File.Exists(..)</code> function, then you can do:</p>

<pre class="lang-vb prettyprint-override"><code>Dim missingFiles As New List(Of String)

For Each line In tbFileNames.Lines
    If Not File.Exists(Path.Combine(tbFolder.Text, $"{line}.jpg")) Then
        missingFiles.Add(line)
    End If
Next

tbNotExistingFiles.Lines = missingFiles.ToArray
</code>```

Title: FileExist returns false

Body:
I have a folder with 700+ .jpgs. I also have a Textbox with one filename per line.
I want to check which file does not exist in the folder, but should be there.

This is my code:

Dim Counter As Integer = 0
For Each Line As String In tbFileNames.Lines
    Counter = Counter + 1
    If (IO.File.Exists(tbFolder.Text & "\" & tbFileNames.Lines(Counter - 1).ToString & ".jpg")) = False Then
        tbNotExistingFiles.Text = tbNotExistingFiles.Text & vbNewLine & (tbFileNames.Lines(Counter - 1).ToString)
    Else
    End If
Next

Problem: I get more than 300 "missing" files, but there should be only 7. When I search for the output filenames, they are in the folder, so the FileExists functions returns false, but it shouldn't.

Where is the problem? Is it the amount of files?

Body:
According to this line:

If (IO.File.Exists(tbFolder.Text & "\" & tbFileNames.Lines(Counter - 1).ToString & ".jpg")) = False

Which can be interpreted as:

The tbFolder TextBox contains the directory's path where the images are located.

The tbFileNames TextBox contains the main and complete file names. One file name per line.

Appending the extension & ".jpg" means that the file names in the tbFileNames TextBox are without extensions. And,

You need to get a list of the missing files in that directory and show the result in the tbNotExistingFiles TextBox.

If my interpretation is correct, then you can achieve that using the extension methods like:

Imports System.IO
'...

Dim missingFiles = tbFileNames.Lines.
    Select(Function(x) $"{x.ToLower}.jpg").
    Except(Directory.GetFiles(tbFolder.Text).
    Select(Function(x) Path.GetFileName(x.ToLower)))

tbNotExistingFiles.Text = String.Join(ControlChars.NewLine, missingFiles)

Or by a LINQ query:

Dim missingFiles = From x In tbFileNames.Lines
                    Where (
                        Aggregate y In Directory.EnumerateFiles(tbFolder.Text)
                            Where Path.GetFileName(y).ToLower.Equals($"{x.ToLower}.jpg")
                                Into Count()
                        ) = 0
                    Select x

'Alternative to tbNotExistingFiles.Text = ...
tbNotExistingFiles.Lines = missingFiles.ToArray

Note that, there's no need nor use for the File.Exists(..) function in the preceding snippets. Just in case you prefer your approach using For..Loop and File.Exists(..) function, then you can do:

Dim missingFiles As New List(Of String)

For Each line In tbFileNames.Lines
    If Not File.Exists(Path.Combine(tbFolder.Text, $"{line}.jpg")) Then
        missingFiles.Add(line)
    End If
Next

tbNotExistingFiles.Lines = missingFiles.ToArray


问:
How can I check if code is executed in the IPython notebook?
I have some Python code example I'd like to share that should do something different if executed in the terminal Python / IPython or in the IPython notebook.

How can I check from my Python code if it's running in the IPython notebook?

答:
All you have to do is to place these two cells at the beginning of your notebook:

Cell 1: (marked as "code"):

```<code>is_notebook = True
</code>```

Cell 2: (marked as "Raw NBConvert"):

```<code>is_notebook = False
</code>```

The first cell will always be executed, but the second cell will only be executed when you export the notebook as a Python script.

Later, you can check:

```<code>if is_notebook:
    notebook_code()
else:
    script_code()
</code>```

Hope this helps.

Body:
All you have to do is to place these two cells at the beginning of your notebook:

Cell 1: (marked as "code"):

is_notebook = True

Cell 2: (marked as "Raw NBConvert"):

is_notebook = False

The first cell will always be executed, but the second cell will only be executed when you export the notebook as a Python script.

Later, you can check:

if is_notebook:
    notebook_code()
else:
    script_code()

Hope this helps.


问:
Using a custom class as a JAX-WS return type?
I'm using NetBeans's Web Service generation tools. I've looked at the tutorials available, but cannot find anything on how to use a custom class as a return type. Most of the tutorials I've read are no more complex than Hello World: they take and return simple types like Strings.

So say I want a class that has 3 fields: a String, an int and a double[]. So far, the only way I can pass my own classes is by creating "envelope classes", with no methods, a parameter-less constructor, and with all fields declared public. I'd prefer to write standard Java classes. Obviously I cannot send the methods across SOAP, but I would have thought there was a way to ignore the methods when Marshalling the class, and only Marshall the fields.

Somebody has told me there are Annotations that facilitate this, but I can't find any tutorials on how to implement them. Any guidance would be greatly appreciated.

答:
If you are using NetBeans interface to design your ws.

Click on add new operation

Select return type, browse for your class (as shown)


问:
React Click Counter: Updating State of just one element
This should be pretty simple, but I can't figure out how to do it.

I have a component with multiple buttons, each with a "count" value, set with state. When a user clicks, the count goes up.

Right now, when I click one of the buttons, both counters change. How can I make it so only the div that was clicked updates, using the same state?

Edit: I don't want to have different counts, as I'd like for this component to render buttons dynamically. What if I don't know how many buttons I'll have at first?

```<code>class Block extends React.Component {
  state = {
    count: 0
  };

  handleClick = e => {
    const count = this.state.count;
    this.setState({ count: count + 1 });
  };

  render() {
    return (
      <div>
        <button className="block" onClick={this.handleClick}>
          <div className="counter">{this.state.count}</div>
        </button>
        <button className="block" onClick={this.handleClick}>
          <div className="counter">{this.state.count}</div>
        </button>
      </div>
    );
  }
}
</code>```

答:
you should define two state and when press each button update the current state and you can render the current state in the dome like this

```<code>state = {
  firstCount: 0,
  secondCount: 0
}
</code>```

and write your action (function) to handle update state like this

```<code>handleUpdateCount = stateName => {
  this.setState({
    [stateName]= this.state[stateName] + 1
  })
}
</code>```

then you should called this function like this =>

```<code>this.handleUpdateCount('firstCount')
</code>```

Body:
This should be pretty simple, but I can't figure out how to do it.

I have a component with multiple buttons, each with a "count" value, set with state. When a user clicks, the count goes up.

Right now, when I click one of the buttons, both counters change. How can I make it so only the div that was clicked updates, using the same state?

Edit: I don't want to have different counts, as I'd like for this component to render buttons dynamically. What if I don't know how many buttons I'll have at first?

class Block extends React.Component {
  state = {
    count: 0
  };

  handleClick = e => {
    const count = this.state.count;
    this.setState({ count: count + 1 });
  };

  render() {
    return (

        <button className="block" onClick={this.handleClick}>

{this.state.count}

        </button>
        <button className="block" onClick={this.handleClick}>

{this.state.count}

        </button>

    );
  }
}

Body:
you should define two state and when press each button update the current state and you can render the current state in the dome like this

state = {
  firstCount: 0,
  secondCount: 0
}

and write your action (function) to handle update state like this

handleUpdateCount = stateName => {
  this.setState({
    [stateName]= this.state[stateName] + 1
  })
}

then you should called this function like this =>

this.handleUpdateCount('firstCount')


问:
How can I compare two time strings in the format HH:MM:SS?
I have two time strings in HH:MM:SS format. For example, str1 contains 10:20:45,  str2 contains 5:10:10.

How can I compare the above values?

答:
Convert to seconds those strings:</p>
```<code>var str1 = '10:20:45';
var str2 = '5:10:10';

str1 =  str1.split(':');
str2 =  str2.split(':');

totalSeconds1 = parseInt(str1[0] * 3600 + str1[1] * 60 + str1[2]);
totalSeconds2 = parseInt(str2[0] * 3600 + str2[1] * 60 + str2[2]);

// compare them

if (totalSeconds1 > totalSeconds2 ) { // etc...
</code>```

Body:
Convert to seconds those strings:

var str1 = '10:20:45';
var str2 = '5:10:10';

str1 =  str1.split(':');
str2 =  str2.split(':');

totalSeconds1 = parseInt(str1[0] * 3600 + str1[1] * 60 + str1[2]);
totalSeconds2 = parseInt(str2[0] * 3600 + str2[1] * 60 + str2[2]);

// compare them

if (totalSeconds1 > totalSeconds2 ) { // etc...


问:
Dockeried setup for Node and Reactjs
I want to run two docker containers: one is node server(backend) and other has react js code(frontend).

My node contains an API as shown below:

```<code>app.get('/build', function (req, res) {
    ...
    ...
});

app.listen(3001);
console.log("Listening to PORT 3001");
</code>```

I am using this API in my react code as follows:

```<code>componentDidMount() {

axios.get('http://localhost:3001/build', { headers: {"x-access-token": this.state.token}
      })
           .then(response => {
              const builds = response.data.message;
              //console.log("builds",builds);
              this.setState({ builds: builds,done: true });
           });
}
</code>```

But when I run 2 different Docker containers, exposing 3001 for backend container and exposing 3000 for frontend container and access http://aws-ip:3000 (aws-ip is the public IP of my AWS instance where I am running the two docker containers), the request made is

http://localhost:3001/build due to which I am not able to hit the node api of docker container.

What changes should I make in the existing setup so that my react application can fetch the data from node server which is running on the same AWS instance?

答:
As you said it right, the frontend app accessed in the browser cannot reach your API via http://localhost:3001. Instead, your react application should access the API via http://[ec2-instance-elastic-ip]:3001. Your react app should store in its code. Your ec2 instance security group should allow incoming traffic via port 3001.

The above setup is enough to solve the problem.

but here are some additional tips.

assign an elastic IP to your instance. Otherwise, the public IP address of the instance will change if you stop/start the instance.

setup a domain name for your API for flexibility, easy to remember, can redeploy anywhere and point the domain name to the new address. (many ways to do this such as setting up a load balancer, set up CloudFront with ec2 origin)

setup SSL for the better security (many ways to do this such as setting up a load balancer, set up CloudFront with ec2 origin)

Since your react app is a static website, you can easily set up a static s3 website

Hope this helps.

Title: Dockeried setup for Node and Reactjs

Body:
I want to run two docker containers: one is node server(backend) and other has react js code(frontend).

My node contains an API as shown below:

app.get('/build', function (req, res) {
    ...
    ...
});

app.listen(3001);
console.log("Listening to PORT 3001");

I am using this API in my react code as follows:

componentDidMount() {

axios.get('http://localhost:3001/build', { headers: {"x-access-token": this.state.token}
      })
           .then(response => {
              const builds = response.data.message;
              //console.log("builds",builds);
              this.setState({ builds: builds,done: true });
           });
}

But when I run 2 different Docker containers, exposing 3001 for backend container and exposing 3000 for frontend container and access http://aws-ip:3000 (aws-ip is the public IP of my AWS instance where I am running the two docker containers), the request made is

http://localhost:3001/build due to which I am not able to hit the node api of docker container.

What changes should I make in the existing setup so that my react application can fetch the data from node server which is running on the same AWS instance?


问:
Unable to multiply two variables in Smarty on Prestashop
In my prestashop store, I have two variables per_sqft_price and per_box_price. per_sqft_price is having currency ($) sign before. I am trying to print the multiplied value of those 2 variables. But it is always printing 0.

```<code>{assign var = per_sqft_price value = $product.price}
{assign var = per_box_price value = $product.features[0].value}

<meta itemprop="per_sqft_price" content="{$per_sqft_price|replace:'$':''}"/>
{math equation = "x * y" x = $per_sqft_price  y = $per_box_price }
</code>```

Please help me how can i solve this. Thanks in advance

答:
Try this code:

```<code>{$result = ($per_sqft_price|intval) * ($per_box_price|intval)}
</code>```

It's not a standard way but it may work

Body:
In my prestashop store, I have two variables per_sqft_price and per_box_price. per_sqft_price is having currency ($) sign before. I am trying to print the multiplied value of those 2 variables. But it is always printing 0.

{assign var = per_sqft_price value = $product.price}
{assign var = per_box_price value = $product.features[0].value}

<meta itemprop="per_sqft_price" content="{$per_sqft_price|replace:'$':''}"/>
{math equation = "x * y" x = $per_sqft_price  y = $per_box_price }

Please help me how can i solve this. Thanks in advance

Body:
Try this code:

{$result = ($per_sqft_price|intval) * ($per_box_price|intval)}

It's not a standard way but it may work