问:
Compression and Encryption in java and Wp7 mismatch
We have implemented Deflate Compression and AES-128 Encryption in both java and WP7.

When Compression and encryption was implemented as seprate modules they were providing same output on both the platforms.

Later we tried to integrate both modules(ie. input String is compressed first, then compressed string is encrypted), After this integration we are not getting same output on both platforms.

Code is given below

String we are using as input is :   "Testing compression(Deflate Algorothjm), encrption(AES algorithm) for WP7."

output for Java : "iJSblymVMAD94KdHSrLt1xLC3lioNc4mNtk4kobuk+qkBEiV4x9Em7ShPxdtXO1EKLjepZVcEvtzCTsmwc5/uGzr4yscgLOvsYvBL8Ku0FM="

output from WP7 :  "muMPnBPUG6Ad+zolHtE7Mi9YWTgmm9dOtTWTtZP19oRucf0I02MiHdwIs488y33EGaaZJjQhd3ymaEDOR+HvVb9quQvRu7nkJwXW3uyZEcI="

Java Integrated Code

```<code>package com.emap.services;

import com.sun.org.apache.xerces.internal.impl.dv.util.Base64;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
import java.util.zip.Deflater;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
public class CompressEncrypt {
    static byte[] ibv = new byte[]{0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a,
        0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10};

    public String compressEncryptData() {

        String strData = "Testing compression(Deflate Algorothjm), encrption(AES algorithm) for WP7.";
        byte[] inputData = strData.getBytes();
        // supporting maximum 10 MB of data
        byte[] outputData = new byte[1024 * 1024 * 10];
        // initiate compressor instance
        Deflater compresser = new Deflater();
        // compressed base64 encoded string

        byte [] compressedByte = null;

        int compressedDataLength = 0;
        //Encrypted String
        String encryptedStr = "";

        try {
            compresser.setInput(inputData, 0, inputData.length);
            compresser.finish();
            compressedDataLength = compresser.deflate(outputData);
            compressedByte = Arrays.copyOfRange(outputData, 0, compressedDataLength);
            System.out.println("Compressed String is : " + compressedByte.toString());
        } catch (Exception ex) {
            System.out.println("Error : " + ex.getMessage());
        }

        try {
            SecretKeySpec skeySpec = new SecretKeySpec("E2D5@eMap_AndIBB".getBytes(), "AES");

            IvParameterSpec iv = new IvParameterSpec(ibv);
            // Instantiate the cipher
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
            cipher.init(Cipher.ENCRYPT_MODE, skeySpec, iv);

            byte[] encrypted = cipher.doFinal(compressedByte);
            System.out.println("Encrypted String is : " + encrypted.toString());
            encryptedStr = Base64.encode(encrypted);
        }  catch (Exception ex) {
            System.out.println("No Such Padding Error: " + ex.getMessage());
            encryptedStr = "No Such Padding Error: " + ex.getMessage();
        }
        System.out.println("Compressed Encrypted Encoded String is : " + encryptedStr);
        return encryptedStr;
    }
}
</code>```

WP7 Integrated Code

```<code>using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.IO;
using ICSharpCode.SharpZipLib.Zip;
using ICSharpCode.SharpZipLib.Zip.Compression;
using ICSharpCode.SharpZipLib.Zip.Compression.Streams;
using System.Text;
using System.Security;
using System.Security.Cryptography;

namespace CompressEncrypt
{
    public class Code
    {
        static byte[] ibv = new byte[]{0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a,
        0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10};
        //public string CompressEncode(string strOrigianl)
        public string CompressEncode(string strOrigianl)
        {
            MemoryStream memoryStream = new MemoryStream();
            byte[] getBytes = System.Text.Encoding.UTF8.GetBytes(strOrigianl);

            memoryStream = Deflate(getBytes);
            byte[] objByte = new byte[memoryStream.Length];
            memoryStream.Read(objByte, 0, (int)(memoryStream.Length));
            string strResult = Convert.ToBase64String(memoryStream.ToArray());

            strResult = Encrypt(memoryStream.ToArray(), "E2D5@eMap_AndIBB");
            return strResult;
        }

        MemoryStream Deflate(byte[] data)
        {
            MemoryStream memoryStream = new MemoryStream();
            {
                Deflater deflater = new Deflater();
                using (DeflaterOutputStream outStream = new DeflaterOutputStream(memoryStream, deflater))
                {
                    outStream.IsStreamOwner = false;
                    outStream.Write(data, 0, data.Length);
                    outStream.Flush();
                    outStream.Finish();

                }
                return memoryStream;
            }
        }

        //********************Encryption*************************************
        public string Encrypt(byte[] data, string password)
        {
            AesManaged aes = null;
            MemoryStream memStream = null;
            CryptoStream crStream = null;
            try
            {

                aes = new AesManaged();
                aes.Key = Encoding.UTF8.GetBytes(password);

                aes.IV = ibv;
                memStream = new MemoryStream();
                crStream = new CryptoStream(memStream, aes.CreateEncryptor(), CryptoStreamMode.Write);
                //byte[] data = Encoding.UTF8.GetBytes(dataToEncrypt);
                crStream.Write(data, 0, data.Length);
                crStream.FlushFinalBlock();
                //Return Base 64 String
                return Convert.ToBase64String(memStream.ToArray());
            }
            finally
            {
                //cleanup
                if (crStream != null)
                    crStream.Close();
                if (memStream != null)
                    memStream.Close();
                if (aes != null)
                    aes.Clear();
            }
        }

    }
}
</code>```

Thanks and Regards
Mohit Leekha

As i already Said Seprate Encryption and Compression are Providing same output on both modules.

What i found till now is:

Using "Testing compression(Deflate Algorothjm), encrption(AES algorithm) for WP7." as input string

Compression
we converted the string in bytes using
byte[] inputData = strData.getBytes();
than compressed these bytes(inputData) using deflater(compressor) we get compressed bytes, after we converted compressd bytes to strin using base64

but in case of WP7 Deflator provide Stream, not bytes
Still when we get the same out put on both platforms.

Encryption
Same 3 steps(1. conversion to bytes, 2. Encryption 3. conversion to string using base64) we followed for encryption and get same output from both platforms

Integration
Problem starts here
In java code we converted input string to bytes, compressed it.
The Compresser provided Byte Araay , Which is directly passed to Encryption Module
ie. skipped 3rd step of compression(conversion of compressed bytes to base64 string) and first step of encryption(conversion of srting to bytes)

When we did this in WP7 we got a stream from the compressor, we converted it to byte array and passed to encryption module, here the output we are getting is different.

Problem with me is my java code is finalized and cannot be altered.

i have a

thanks

答:
I believe this is your problem - or at least a problem:

```<code>memoryStream = Deflate(getBytes);
byte[] objByte = new byte[memoryStream.Length];
memoryStream.Read(objByte, 0, (int)(memoryStream.Length));
</code>```

You're writing to the MemoryStream (in Deflate) and then reading from it without resetting the "cursor" to the start. You're also trying to read after the MemoryStream will have been disposed by the DeflaterOutputStream, I suspect.

Fortunately, you don't have to do this at all. Just use:

```<code>byte[] objByte = memoryStream.ToArray();
</code>```

This will work even though the stream is closed.

I note that you're still using String.getBytes() in the Java code without specifying an encoding, by the way. Please don't do that.

Body:
We have implemented Deflate Compression and AES-128 Encryption in both java and WP7.

When Compression and encryption was implemented as seprate modules they were providing same output on both the platforms.

Later we tried to integrate both modules(ie. input String is compressed first, then compressed string is encrypted), After this integration we are not getting same output on both platforms.

Code is given below

String we are using as input is :   "Testing compression(Deflate Algorothjm), encrption(AES algorithm) for WP7."

output for Java : "iJSblymVMAD94KdHSrLt1xLC3lioNc4mNtk4kobuk+qkBEiV4x9Em7ShPxdtXO1EKLjepZVcEvtzCTsmwc5/uGzr4yscgLOvsYvBL8Ku0FM="

output from WP7 :  "muMPnBPUG6Ad+zolHtE7Mi9YWTgmm9dOtTWTtZP19oRucf0I02MiHdwIs488y33EGaaZJjQhd3ymaEDOR+HvVb9quQvRu7nkJwXW3uyZEcI="

Java Integrated Code

package com.emap.services;

import com.sun.org.apache.xerces.internal.impl.dv.util.Base64;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
import java.util.zip.Deflater;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
public class CompressEncrypt {
    static byte[] ibv = new byte[]{0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a,
        0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10};

    public String compressEncryptData() {

        String strData = "Testing compression(Deflate Algorothjm), encrption(AES algorithm) for WP7.";
        byte[] inputData = strData.getBytes();
        // supporting maximum 10 MB of data
        byte[] outputData = new byte[1024 * 1024 * 10];
        // initiate compressor instance
        Deflater compresser = new Deflater();
        // compressed base64 encoded string

        byte [] compressedByte = null;

        int compressedDataLength = 0;
        //Encrypted String
        String encryptedStr = "";

        try {
            compresser.setInput(inputData, 0, inputData.length);
            compresser.finish();
            compressedDataLength = compresser.deflate(outputData);
            compressedByte = Arrays.copyOfRange(outputData, 0, compressedDataLength);
            System.out.println("Compressed String is : " + compressedByte.toString());
        } catch (Exception ex) {
            System.out.println("Error : " + ex.getMessage());
        }

        try {
            SecretKeySpec skeySpec = new SecretKeySpec("E2D5@eMap_AndIBB".getBytes(), "AES");

            IvParameterSpec iv = new IvParameterSpec(ibv);
            // Instantiate the cipher
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
            cipher.init(Cipher.ENCRYPT_MODE, skeySpec, iv);

            byte[] encrypted = cipher.doFinal(compressedByte);
            System.out.println("Encrypted String is : " + encrypted.toString());
            encryptedStr = Base64.encode(encrypted);
        }  catch (Exception ex) {
            System.out.println("No Such Padding Error: " + ex.getMessage());
            encryptedStr = "No Such Padding Error: " + ex.getMessage();
        }
        System.out.println("Compressed Encrypted Encoded String is : " + encryptedStr);
        return encryptedStr;
    }
}

WP7 Integrated Code

using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.IO;
using ICSharpCode.SharpZipLib.Zip;
using ICSharpCode.SharpZipLib.Zip.Compression;
using ICSharpCode.SharpZipLib.Zip.Compression.Streams;
using System.Text;
using System.Security;
using System.Security.Cryptography;

namespace CompressEncrypt
{
    public class Code
    {
        static byte[] ibv = new byte[]{0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a,
        0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10};
        //public string CompressEncode(string strOrigianl)
        public string CompressEncode(string strOrigianl)
        {
            MemoryStream memoryStream = new MemoryStream();
            byte[] getBytes = System.Text.Encoding.UTF8.GetBytes(strOrigianl);

            memoryStream = Deflate(getBytes);
            byte[] objByte = new byte[memoryStream.Length];
            memoryStream.Read(objByte, 0, (int)(memoryStream.Length));
            string strResult = Convert.ToBase64String(memoryStream.ToArray());

            strResult = Encrypt(memoryStream.ToArray(), "E2D5@eMap_AndIBB");
            return strResult;
        }

        MemoryStream Deflate(byte[] data)
        {
            MemoryStream memoryStream = new MemoryStream();
            {
                Deflater deflater = new Deflater();
                using (DeflaterOutputStream outStream = new DeflaterOutputStream(memoryStream, deflater))
                {
                    outStream.IsStreamOwner = false;
                    outStream.Write(data, 0, data.Length);
                    outStream.Flush();
                    outStream.Finish();

                }
                return memoryStream;
            }
        }

        //********************Encryption*************************************
        public string Encrypt(byte[] data, string password)
        {
            AesManaged aes = null;
            MemoryStream memStream = null;
            CryptoStream crStream = null;
            try
            {

                aes = new AesManaged();
                aes.Key = Encoding.UTF8.GetBytes(password);

                aes.IV = ibv;
                memStream = new MemoryStream();
                crStream = new CryptoStream(memStream, aes.CreateEncryptor(), CryptoStreamMode.Write);
                //byte[] data = Encoding.UTF8.GetBytes(dataToEncrypt);
                crStream.Write(data, 0, data.Length);
                crStream.FlushFinalBlock();
                //Return Base 64 String
                return Convert.ToBase64String(memStream.ToArray());
            }
            finally
            {
                //cleanup
                if (crStream != null)
                    crStream.Close();
                if (memStream != null)
                    memStream.Close();
                if (aes != null)
                    aes.Clear();
            }
        }

    }
}

Thanks and Regards
Mohit Leekha

As i already Said Seprate Encryption and Compression are Providing same output on both modules.

What i found till now is:

Using "Testing compression(Deflate Algorothjm), encrption(AES algorithm) for WP7." as input string

Compression
we converted the string in bytes using
byte[] inputData = strData.getBytes();
than compressed these bytes(inputData) using deflater(compressor) we get compressed bytes, after we converted compressd bytes to strin using base64

but in case of WP7 Deflator provide Stream, not bytes
Still when we get the same out put on both platforms.

Encryption
Same 3 steps(1. conversion to bytes, 2. Encryption 3. conversion to string using base64) we followed for encryption and get same output from both platforms

Integration
Problem starts here
In java code we converted input string to bytes, compressed it.
The Compresser provided Byte Araay , Which is directly passed to Encryption Module
ie. skipped 3rd step of compression(conversion of compressed bytes to base64 string) and first step of encryption(conversion of srting to bytes)

When we did this in WP7 we got a stream from the compressor, we converted it to byte array and passed to encryption module, here the output we are getting is different.

Problem with me is my java code is finalized and cannot be altered.

i have a

thanks

Body:
I believe this is your problem - or at least a problem:

memoryStream = Deflate(getBytes);
byte[] objByte = new byte[memoryStream.Length];
memoryStream.Read(objByte, 0, (int)(memoryStream.Length));

You're writing to the MemoryStream (in Deflate) and then reading from it without resetting the "cursor" to the start. You're also trying to read after the MemoryStream will have been disposed by the DeflaterOutputStream, I suspect.

Fortunately, you don't have to do this at all. Just use:

byte[] objByte = memoryStream.ToArray();

This will work even though the stream is closed.

I note that you're still using String.getBytes() in the Java code without specifying an encoding, by the way. Please don't do that.


来源: stackexchange

问:
Can you facet grid using cols as the x variable in the plot?
Using the Auto MPG data set as an example, I'd like to create plots showing the relationship between hwy milage ~ year, ~ displacement, ~ cyl. Can you do this using a facet grid where the rows are manufacturer and the cols = c(year, displacement, and cyl)?

I've only been able to do this in three individual plots so far and would like to combine into one plot.

```<code>ggplot(mpg, aes(year, hwy)) +
 geom_smooth(method = "lm", se = FALSE)+
 facet_grid(rows = vars(manufacturer))

ggplot(mpg, aes(displ, hwy)) +
 geom_smooth(method = "lm", se = FALSE)+
 facet_grid(rows = vars(manufacturer))

ggplot(mpg, aes(cyl, hwy)) +
 geom_smooth(method = "lm", se = FALSE)+
 facet_grid(rows = vars(manufacturer))
</code>```

答:
In ggplot2, you can only facet on a single variable. The solution is to pivot your data into long form so that the variables you want to facet on are contained in a single variable. Here we take year, displ, and cyl and convert them into a name column (which we facet on) and a value column which we use for the X-axis value.

Note that we need to set the free scales at least on the X axis, since year the scales are so different between the different variables

```<code>mpg %>%
    pivot_longer(c(year, displ, cyl)) %>%
    ggplot(aes(value, hwy)) +
    geom_smooth(method = "lm", se = FALSE)+
    facet_grid(rows = vars(manufacturer), cols=vars(name), scales = 'free')
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Using the Auto MPG data set as an example, I'd like to create plots showing the relationship between hwy milage ~ year, ~ displacement, ~ cyl. Can you do this using a facet grid where the rows are manufacturer and the cols = c(year, displacement, and cyl)?

I've only been able to do this in three individual plots so far and would like to combine into one plot.

ggplot(mpg, aes(year, hwy)) +
 geom_smooth(method = "lm", se = FALSE)+
 facet_grid(rows = vars(manufacturer))

ggplot(mpg, aes(displ, hwy)) +
 geom_smooth(method = "lm", se = FALSE)+
 facet_grid(rows = vars(manufacturer))

ggplot(mpg, aes(cyl, hwy)) +
 geom_smooth(method = "lm", se = FALSE)+
 facet_grid(rows = vars(manufacturer))

Body:
In ggplot2, you can only facet on a single variable. The solution is to pivot your data into long form so that the variables you want to facet on are contained in a single variable. Here we take year, displ, and cyl and convert them into a name column (which we facet on) and a value column which we use for the X-axis value.

Note that we need to set the free scales at least on the X axis, since year the scales are so different between the different variables

mpg %>%
    pivot_longer(c(year, displ, cyl)) %>%
    ggplot(aes(value, hwy)) +
    geom_smooth(method = "lm", se = FALSE)+
    facet_grid(rows = vars(manufacturer), cols=vars(name), scales = 'free')


问:
Whats the better way of doing this
I've only been coding in python for a month and I tried making something that searches for duplicates in a user made list...</p>
```<code>List = []
count = 0
Val = 0
usernum = int(input("How many numbers are in your list: "))

for i in range(0, usernum):
    values = int(input("What is the number on the list: "))
    List.append(values)

for i in range(0, len(List)):
    if List[i] == List[Val]:
        print("There are duplicates")
        count += 1
        if count == len(List):
            Val += 1
            continue
</code>```

答:
Your code does not work for various reasons:

You're missing your main variable: the list. Add it like this

```<code>List = []
</code>```

BTW: List with a capital L is not an awesome choice, but still a much better choice than list with a lower case L which could cause all kinds of problems.

With that added, enter 1 and 1 and you'll find that even for a single number it will print "There are duplicates". That is because you compare

```<code>List[i] == List[Val]
</code>```

where both i and Val are 0. The item compares against itself. That must no be the case.

All the if-logic is weird. It's unclear to me what you wanted to achieve. A common approach would be a nested loop in order to compare each item against each following item. Note how j starts at i+1

```<code>for i in range(0, len(List)):
    for j in range(i+1, len(List)):
        if List[i] == List[j]:
            print("There are duplicates")
</code>```

An even better approach would be to not implement that yourself at all but use other techniques like

```<code>if len(set(List)) < len(List):
    print("There are duplicates")
</code>```

where set() will give you the unique numbers only. If numbers have been removed because they were not unique (aka. duplicate), that set will have less numbers than the list.

Title: Whats the better way of doing this

Body:
I've only been coding in python for a month and I tried making something that searches for duplicates in a user made list...

List = []
count = 0
Val = 0
usernum = int(input("How many numbers are in your list: "))

for i in range(0, usernum):
    values = int(input("What is the number on the list: "))
    List.append(values)

for i in range(0, len(List)):
    if List[i] == List[Val]:
        print("There are duplicates")
        count += 1
        if count == len(List):
            Val += 1
            continue

Body:
Your code does not work for various reasons:

You're missing your main variable: the list. Add it like this

List = []

BTW: List with a capital L is not an awesome choice, but still a much better choice than list with a lower case L which could cause all kinds of problems.

With that added, enter 1 and 1 and you'll find that even for a single number it will print "There are duplicates". That is because you compare

List[i] == List[Val]

where both i and Val are 0. The item compares against itself. That must no be the case.

All the if-logic is weird. It's unclear to me what you wanted to achieve. A common approach would be a nested loop in order to compare each item against each following item. Note how j starts at i+1

for i in range(0, len(List)):
    for j in range(i+1, len(List)):
        if List[i] == List[j]:
            print("There are duplicates")

An even better approach would be to not implement that yourself at all but use other techniques like

if len(set(List)) < len(List):
    print("There are duplicates")

where set() will give you the unique numbers only. If numbers have been removed because they were not unique (aka. duplicate), that set will have less numbers than the list.


问:
How to make a multiple update on mysql with string replace with value of another column
Hello i'm new in mysql and i have to run a multiple update on my table.
I have 700 records in the table and i have to update them all this way:

table example :
store_id: 1
store_email: storename@gmail.com

for single update i use

```<code>UPDATE stores SET email = '1@gmail.com' WHERE id = 1;
</code>```

i need to update all the emails and replace their name with their id, so it would be like this:

storename@gmail.com --> 1@gmail.com

storename@gmail.com --> 2@gmail.com

storename@gmail.com --> 3@gmail.com

those numers have to be the ID for each store.

Hope you can understand

Thanks for help.

P.S. i need to run it on magento 2

答:
Since you are adding id to String column gmail, you can use contact() fucntion like below :</p>
```<code>  UPDATE stors SET email=CONCAT(id, "@gmail.com") where id=2;
</code>```

Body:
Hello i'm new in mysql and i have to run a multiple update on my table.
I have 700 records in the table and i have to update them all this way:

table example :
store_id: 1
store_email: storename@gmail.com

for single update i use

UPDATE stores SET email = '1@gmail.com' WHERE id = 1;

i need to update all the emails and replace their name with their id, so it would be like this:

storename@gmail.com --> 1@gmail.com

storename@gmail.com --> 2@gmail.com

storename@gmail.com --> 3@gmail.com

those numers have to be the ID for each store.

Hope you can understand

Thanks for help.

P.S. i need to run it on magento 2

Body:
Since you are adding id to String column gmail, you can use contact() fucntion like below :

  UPDATE stors SET email=CONCAT(id, "@gmail.com") where id=2;


问:
Should I use GridFS or some other method to create a file sharing app?
I am currently beginning work on a file sharing app for my company. A simple form to upload a file, the user is then given a download URL and can past that on to anyone so they can download the file (Similar to products such as WeTransfer).

However I am struggling on decided how to do it. I have been playing with MongoDB and GridFS. I have successfully used multer and multer-gridfs-storage to upload files directly into my database. I am struggling to get them to download as I don't know that much about GridFS.

```<code>const storage = new GridFsStorage({
url: 'mongodb://localhost:27017/fileUpload',
file: (req, file) => {
    return new Promise((resolve, reject) => {
        crypto.randomBytes(16, (err, buf) => {
            if (err) {
                return reject(err)
            }
            const filename = buf.toString('hex') + path.extname(file.originalname);
            const fileInfo = {
                filename: filename,
                bucketName: 'uploads'
            };
            resolve(fileInfo)
        });
    });
}
});

const upload = multer({ storage })
</code>```

But it got me thinking is this the best way of doing this or would there be a better why or serving those download files (to download to a users computer).

Any advice is greatly appreciated!

答:
GridFS is a specification for storing and retrieving files that exceed the BSON document size limit of 16 MB. GridFS is a convention implemented by all MongoDB drivers that stores binary data across many smaller documents. The binaries are split into the chunks and then the chunks are stored in collections created by GridFS.

Having said that, given the presented use cases i would highly recommend using media server for storage as given the application landscape, that makes a more economical, viable and scalable solution.

Having said that, I would generally, avoid putting BLOBs in the database if there are other storage options that cost less as using a database as BLOB store is generally not a cost optimised solution.
Sure, there are valid reasons for storing blobs in the database, but given the application’s use case (it being media intensive), use the media server for file storage, and databases for data structures.

In such cases, It is often easy to get "cost unoptimized" with time. Plus the database size would grow exponentially with time, bringing it's own challenges with RAM (WiredTiger Cache) management.

All in all - if it was me - I would use media storage for BLOB intensive applications than relying on databases.

Body:
I am currently beginning work on a file sharing app for my company. A simple form to upload a file, the user is then given a download URL and can past that on to anyone so they can download the file (Similar to products such as WeTransfer).

However I am struggling on decided how to do it. I have been playing with MongoDB and GridFS. I have successfully used multer and multer-gridfs-storage to upload files directly into my database. I am struggling to get them to download as I don't know that much about GridFS.

const storage = new GridFsStorage({
url: 'mongodb://localhost:27017/fileUpload',
file: (req, file) => {
    return new Promise((resolve, reject) => {
        crypto.randomBytes(16, (err, buf) => {
            if (err) {
                return reject(err)
            }
            const filename = buf.toString('hex') + path.extname(file.originalname);
            const fileInfo = {
                filename: filename,
                bucketName: 'uploads'
            };
            resolve(fileInfo)
        });
    });
}
});

const upload = multer({ storage })

But it got me thinking is this the best way of doing this or would there be a better why or serving those download files (to download to a users computer).

Any advice is greatly appreciated!


问:
VS Code Remote - Can't run 'code' command in WSL Ubuntu 18 or WSL 2 Ubuntu 20 - wrong path
I'm having an issue when I try to run the code command from Visual Studio Code in WSL Ubuntu. I get the following error:

```<code>$ code .

/mnt/c/Users/Name/.vscode/extensions/ms-vscode-remote.remote-wsl-0.64.2/scripts/wslCode.sh: 63: /mnt/c/Users/Name/.vscode/extensions/ms-vscode-remote.remote-wsl-0.64.2/scripts/wslCode.sh: /home/barry/.vscode/bin/899d46d82c4c95423fb7e10e68eba52050e30ba3/bin/remote-cli/code: not found
</code>```

When I run the following, it installs the VS Code Server and the command works as expected:

```<code>$ /mnt/c/Users/Name/AppData/Local/Programs/Microsoft\ VS\ Code/bin/code .
</code>```

When I run which -a code, I can see I have two paths related to this command and I believe the correct one is /mnt/c/Users/Name/AppData/Local/Programs/Microsoft VS Code/bin/code, but I don't know how to remove the first one or how it even related two paths to this command in the first place?

```<code>barry@RandomName:~$ which -a code
/mnt/c/Program Files/Microsoft VS Code/bin/code
/mnt/c/Users/Name/AppData/Local/Programs/Microsoft VS Code/bin/code
</code>```

Can anyone help please?

答:
In C:\Users<user>.vscode rename path ms-vscode-remote.remote-wsl- to ms-remote-wsl-old

In WSL run: code .

Body:
I'm having an issue when I try to run the code command from Visual Studio Code in WSL Ubuntu. I get the following error:

$ code .

/mnt/c/Users/Name/.vscode/extensions/ms-vscode-remote.remote-wsl-0.64.2/scripts/wslCode.sh: 63: /mnt/c/Users/Name/.vscode/extensions/ms-vscode-remote.remote-wsl-0.64.2/scripts/wslCode.sh: /home/barry/.vscode/bin/899d46d82c4c95423fb7e10e68eba52050e30ba3/bin/remote-cli/code: not found

When I run the following, it installs the VS Code Server and the command works as expected:

$ /mnt/c/Users/Name/AppData/Local/Programs/Microsoft\ VS\ Code/bin/code .

When I run which -a code, I can see I have two paths related to this command and I believe the correct one is /mnt/c/Users/Name/AppData/Local/Programs/Microsoft VS Code/bin/code, but I don't know how to remove the first one or how it even related two paths to this command in the first place?

barry@RandomName:~$ which -a code
/mnt/c/Program Files/Microsoft VS Code/bin/code
/mnt/c/Users/Name/AppData/Local/Programs/Microsoft VS Code/bin/code

Can anyone help please?


问:
Extjs6: gridpanel - multilevel grouping
On a project written with ExtJs 6, I'm looking for the ability to have multi-level grouping on a grid.
I don't want to group the records on multiple columns but on one level, but each column to be grouped on its own level.

I found some examples for ExtJs, but all pages have broken link to source code (old references).

My goal is to be able to group columns on one, two or three levels depending on the user's choice.
Gridpanel ExtJs proposes by default to group only on one level. I'm looking to expand that.

答: Sounds like you could use a Tree Grid, each branch being a level.</p>

Title: Extjs6: gridpanel - multilevel grouping


问:
Customizing CSS classes in ASP.NET
I am working on an application where the user will be allowed to change the font color of header titles.

The header titles use a value from cssClass (the cssClass uses font-size, font-color, font-weight & font-family).

Is there a way that I can allow a custom font-color in the css file itself?

One option would be to eliminate font-color from the cssClass, and use Font-Color in the .aspx page.

答:
You could use a dynamically created css file, i.e. an aspx page that only output css.</p>

```<code><%@ Page Language="C#" %>

h1 {
font-size: 15px;
color: <%= myUsersColor () %>;
}
</code>```

ContentLicense: CC BY-SA 3.0

Title: Customizing CSS classes in ASP.NET

Body:
You could use a dynamically created css file, i.e. an aspx page that only output css.

<%@ Page Language="C#" %>

h1 {
font-size: 15px;
color: <%= myUsersColor () %>;
}


问:
How to set and align ion-select in center on toolbar in ionic
I want to set select-option on toolbar in ionic, but I'm unable to align it to center, I have tried many things... by using these methods I'm unable to do so,

```<code><div text-center>
     <label class="email">
        <input type="email" placeholder="Email" name="email">
     </label>
 </div>
</code>```

This method aligns input box to center but it doesn't align select-option to center. here is a stackblitz

```<code><div text-center>
<ion-item>

              <ion-select [(ngModel)]="gaming" interface="popover">
                <ion-option selected value="empty">empty</ion-option>
                <ion-option value="n64">Nintendo64</ion-option>
                <ion-option value="ps">PlayStation</ion-option>
                <ion-option value="genesis">Sega Genesis</ion-option>
                <ion-option value="saturn">Sega Saturn</ion-option>
                <ion-option value="snes">SNES</ion-option>
              </ion-select>
            </ion-item>
</div>
</code>```

still the results are same

```<code>.item-select{
    position: initial;
    margin-left: 100px;
    width:40%;
    text-align: center;
}
</code>```

This also doesn't affect, can anyone tell me how to set select-option to center on the toolbar in ionic?

答:
You need to put percent for margin-left, margin-right, max-width and width percentage. Below are my example (just take the style):</p>
```<code><ion-select
    name="remark"
    formControlName="event"
    interface="popover"
    [(ngModel)]="remark"
    style="max-width: 100%; width: 80%; height: 25px; margin-left: 10%; margin-right: 10%;"
    (ionChange)="onChange($event)"
    placeholder="Sila pilih satu">
        <ion-option value="Y">Yuran</ion-option>
        <ion-option value="L">Lain-lain Bayaran</ion-option>
</ion-select>
</code>```

Body:
I want to set select-option on toolbar in ionic, but I'm unable to align it to center, I have tried many things... by using these methods I'm unable to do so,

        <input type="email" placeholder="Email" name="email">

This method aligns input box to center but it doesn't align select-option to center. here is a stackblitz

<ion-item>

              <ion-select [(ngModel)]="gaming" interface="popover">
                <ion-option selected value="empty">empty</ion-option>
                <ion-option value="n64">Nintendo64</ion-option>
                <ion-option value="ps">PlayStation</ion-option>
                <ion-option value="genesis">Sega Genesis</ion-option>
                <ion-option value="saturn">Sega Saturn</ion-option>
                <ion-option value="snes">SNES</ion-option>
              </ion-select>
            </ion-item>

still the results are same

.item-select{
    position: initial;
    margin-left: 100px;
    width:40%;
    text-align: center;
}

This also doesn't affect, can anyone tell me how to set select-option to center on the toolbar in ionic?

Body:
You need to put percent for margin-left, margin-right, max-width and width percentage. Below are my example (just take the style):

<ion-select
    name="remark"
    formControlName="event"
    interface="popover"
    [(ngModel)]="remark"
    style="max-width: 100%; width: 80%; height: 25px; margin-left: 10%; margin-right: 10%;"
    (ionChange)="onChange($event)"
    placeholder="Sila pilih satu">
        <ion-option value="Y">Yuran</ion-option>
        <ion-option value="L">Lain-lain Bayaran</ion-option>
</ion-select>


问:
Azure Durable Functions Large Message Support Issue
I am having an issue returning a large list of objects from an activity function to an orchestrator function.
I have a function that downloads a 180 MB file and parses it. This file will produce a list of objects with over 962K entries. Each object has about 70 properties but only about 20% of them are populated.
When I run the function, the code successfully downloads and parses the file into the list, but when the list is returned, an exception is raised with the following information:

Exception: "Exception while executing function: #######"
- Source: "System.Private.CoreLib"

Inner exception: "Error while handling parameter $return after function returned."
- Source: "Microsoft.Azure.WebJobs.Host"

Inner / Inner exception: "Exception of type 'System.OutOfMemoryException' was thrown."
- Source: "System.Private.CoreLib"

The last nested exception lists the  NewtonsoftJson package as being the one making the call that generates the out of memory error being reported. I am including the full stack trace for this exception at the end.

I understand that I could possibly serialize the list of objects and store them in an Azure blob entry and then just pick it up again in the next function that needs to process it, but I thought the idea behind durable functions was to avoid all this and maintain a leaner workflow? Also, I based the design on the "Large Message Support #26" github post that states that the durable functions extensions would automatically store the function payload in a blob if the size exceeds the queue message limit (see: https://github.com/Azure/azure-functions-durable-extension/issues/26).

Is there anything I need to do to get this working?
The code is pretty simple:

```<code>[FunctionName("GetDataFromSource")]
public static IEnumerable<DataDetail> GetDataFromSource([ActivityTrigger]ISource source, ILogger logger)
{
    try
    {
        string importSettings = Environment.GetEnvironmentVariable(source.SettingsKey);
        if (string.IsNullOrWhiteSpace(importSettings))
        {
            logger.LogError($"No settings key information found for the {source.SourceId} data source");                    }
        else
        {
            List<DataDetail> _Data = source.GetVinData().Distinct().ToList();
            return vinData;
         }
     }
     catch (Exception ex)
     {
         logger.LogCritical($"Error processing the {source.SourceId} Vin data source. *** Exception: {ex}");
     }

      return new List<DataDetail>();
}
</code>```

This is the stack trace for the most inner exception:

```<code>at System.Text.StringBuilder.ExpandByABlock(Int32 minBlockCharCount)
   at System.Text.StringBuilder.Append(Char value, Int32 repeatCount)
   at System.Text.StringBuilder.Append(Char value)
   at System.IO.StringWriter.Write(Char value)
   at Newtonsoft.Json.JsonTextWriter.WritePropertyName(String name, Boolean escape)
   at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeObject(JsonWriter writer, Object value, JsonObjectContract contract, JsonProperty member, JsonContainerContract collectionContract, JsonProperty containerProperty)
   at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeValue(JsonWriter writer, Object value, JsonContract valueContract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerProperty)
   at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeList(JsonWriter writer, IEnumerable values, JsonArrayContract contract, JsonProperty member, JsonContainerContract collectionContract, JsonProperty containerProperty)
   at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeValue(JsonWriter writer, Object value, JsonContract valueContract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerProperty)
   at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.Serialize(JsonWriter jsonWriter, Object value, Type objectType)
   at Newtonsoft.Json.JsonSerializer.SerializeInternal(JsonWriter jsonWriter, Object value, Type objectType)
   at DurableTask.Core.Serializing.JsonDataConverter.Serialize(Object value, Boolean formatted)
   at Microsoft.Azure.WebJobs.Extensions.DurableTask.MessagePayloadDataConverter.Serialize(Object value, Int32 maxSizeInKB) in C:\projects\azure-functions-durable-extension\src\WebJobs.Extensions.DurableTask\MessagePayloadDataConverter.cs:line 55
   at Microsoft.Azure.WebJobs.Extensions.DurableTask.MessagePayloadDataConverter.Serialize(Object value) in C:\projects\azure-functions-durable-extension\src\WebJobs.Extensions.DurableTask\MessagePayloadDataConverter.cs:line 43
   at Microsoft.Azure.WebJobs.DurableActivityContext.SetOutput(Object output) in C:\projects\azure-functions-durable-extension\src\WebJobs.Extensions.DurableTask\DurableActivityContext.cs:line 136
   at Microsoft.Azure.WebJobs.Extensions.DurableTask.ActivityTriggerAttributeBindingProvider.ActivityTriggerBinding.ActivityTriggerReturnValueBinder.SetValueAsync(Object value, CancellationToken cancellationToken) in C:\projects\azure-functions-durable-extension\src\WebJobs.Extensions.DurableTask\Bindings\ActivityTriggerAttributeBindingProvider.cs:line 213
   at Microsoft.Azure.WebJobs.Host.Executors.FunctionExecutor.ParameterHelper.ProcessOutputParameters(CancellationToken cancellationToken) in C:\projects\azure-webjobs-sdk-rqm4t\src\Microsoft.Azure.WebJobs.Host\Executors\FunctionExecutor.cs:line 972
</code>```

答:
The Durable Functions extension will automatically take care of storing large messages in blobs when they don't fit in queues and tables. However, this support assumes that enough memory is available to serialize the payloads so that they can be uploaded to blob. Unfortunately, the design of the Durable Task Framework requires serializing the payload into a string first before uploading to blob, which means there will be a lot of memory pressure.

There are a few things you can try to mitigate this problem:

Make sure your function app is running in 64-bit mode. By default, Function apps are created in 32-bit mode, which has lower memory limits. We've seen several cases where simply switching to 64-bit resolves out-of-memory issues.

Try increasing the memory limit for your particular plan. If you're running in the Azure Functions Consumption plan, maximum memory is fixed. However, if you're running in Elastic Premium or App Service Plans, you have the option of using larger VMs with more memory.

As @stephyness suggested, consider limiting the amount of data your return from your function. This could be returning a subset of the full list or it could be the full list but with smaller payloads (for example, source.GetVinData().Distinct().Select(x => x.VinNumber) (you might even get better results by simply removing .ToList(), which may be creating an unnecessary copy of your data). Essentially, return only the data that the orchestrator absolutely needs to make progress. Returning data the orchestrator doesn't need is unnecessary overhead.

Also be aware that there's a non-trivial performance impact when large message support is used. If you can avoid relying on it, your orchestrations will run much faster.

Other tips for controlling memory usage can be found in the Performance and Scale documentation.

Body:
I am having an issue returning a large list of objects from an activity function to an orchestrator function.
I have a function that downloads a 180 MB file and parses it. This file will produce a list of objects with over 962K entries. Each object has about 70 properties but only about 20% of them are populated.
When I run the function, the code successfully downloads and parses the file into the list, but when the list is returned, an exception is raised with the following information:

Exception: "Exception while executing function: #######"
- Source: "System.Private.CoreLib"

Inner exception: "Error while handling parameter $return after function returned."
- Source: "Microsoft.Azure.WebJobs.Host"

Inner / Inner exception: "Exception of type 'System.OutOfMemoryException' was thrown."
- Source: "System.Private.CoreLib"

The last nested exception lists the  NewtonsoftJson package as being the one making the call that generates the out of memory error being reported. I am including the full stack trace for this exception at the end.

I understand that I could possibly serialize the list of objects and store them in an Azure blob entry and then just pick it up again in the next function that needs to process it, but I thought the idea behind durable functions was to avoid all this and maintain a leaner workflow? Also, I based the design on the "Large Message Support #26" github post that states that the durable functions extensions would automatically store the function payload in a blob if the size exceeds the queue message limit (see: https://github.com/Azure/azure-functions-durable-extension/issues/26).

Is there anything I need to do to get this working?
The code is pretty simple:

[FunctionName("GetDataFromSource")]
public static IEnumerable<DataDetail> GetDataFromSource([ActivityTrigger]ISource source, ILogger logger)
{
    try
    {
        string importSettings = Environment.GetEnvironmentVariable(source.SettingsKey);
        if (string.IsNullOrWhiteSpace(importSettings))
        {
            logger.LogError($"No settings key information found for the {source.SourceId} data source");                    }
        else
        {
            List<DataDetail> _Data = source.GetVinData().Distinct().ToList();
            return vinData;
         }
     }
     catch (Exception ex)
     {
         logger.LogCritical($"Error processing the {source.SourceId} Vin data source. *** Exception: {ex}");
     }

      return new List<DataDetail>();
}

This is the stack trace for the most inner exception:

at System.Text.StringBuilder.ExpandByABlock(Int32 minBlockCharCount)
   at System.Text.StringBuilder.Append(Char value, Int32 repeatCount)
   at System.Text.StringBuilder.Append(Char value)
   at System.IO.StringWriter.Write(Char value)
   at Newtonsoft.Json.JsonTextWriter.WritePropertyName(String name, Boolean escape)
   at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeObject(JsonWriter writer, Object value, JsonObjectContract contract, JsonProperty member, JsonContainerContract collectionContract, JsonProperty containerProperty)
   at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeValue(JsonWriter writer, Object value, JsonContract valueContract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerProperty)
   at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeList(JsonWriter writer, IEnumerable values, JsonArrayContract contract, JsonProperty member, JsonContainerContract collectionContract, JsonProperty containerProperty)
   at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeValue(JsonWriter writer, Object value, JsonContract valueContract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerProperty)
   at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.Serialize(JsonWriter jsonWriter, Object value, Type objectType)
   at Newtonsoft.Json.JsonSerializer.SerializeInternal(JsonWriter jsonWriter, Object value, Type objectType)
   at DurableTask.Core.Serializing.JsonDataConverter.Serialize(Object value, Boolean formatted)
   at Microsoft.Azure.WebJobs.Extensions.DurableTask.MessagePayloadDataConverter.Serialize(Object value, Int32 maxSizeInKB) in C:\projects\azure-functions-durable-extension\src\WebJobs.Extensions.DurableTask\MessagePayloadDataConverter.cs:line 55
   at Microsoft.Azure.WebJobs.Extensions.DurableTask.MessagePayloadDataConverter.Serialize(Object value) in C:\projects\azure-functions-durable-extension\src\WebJobs.Extensions.DurableTask\MessagePayloadDataConverter.cs:line 43
   at Microsoft.Azure.WebJobs.DurableActivityContext.SetOutput(Object output) in C:\projects\azure-functions-durable-extension\src\WebJobs.Extensions.DurableTask\DurableActivityContext.cs:line 136
   at Microsoft.Azure.WebJobs.Extensions.DurableTask.ActivityTriggerAttributeBindingProvider.ActivityTriggerBinding.ActivityTriggerReturnValueBinder.SetValueAsync(Object value, CancellationToken cancellationToken) in C:\projects\azure-functions-durable-extension\src\WebJobs.Extensions.DurableTask\Bindings\ActivityTriggerAttributeBindingProvider.cs:line 213
   at Microsoft.Azure.WebJobs.Host.Executors.FunctionExecutor.ParameterHelper.ProcessOutputParameters(CancellationToken cancellationToken) in C:\projects\azure-webjobs-sdk-rqm4t\src\Microsoft.Azure.WebJobs.Host\Executors\FunctionExecutor.cs:line 972


问:
Static variable placement that used at once in code. Local or class member
What is the better place to declare static variable if I use it in class member once. I can declare it as class member or local variable at class method? What is better for performance or like clean code meaning? For example:

```<code>class Foo
{
public:
  void RunAsMember();
  void RunAsLocal();

private:
  static int RunsMemberCount;
};

int Foo::RunsMemberCount = 0;

void Foo::RunAsMember()
{
  RunsMemberCount++;

  std::cout << "RunAsMember was called " << RunsMemberCount << " time(s) ever." << std::endl;
}

void Foo::RunAsLocal()
{
  static int RunsLocalCount = 0;
  RunsLocalCount++;

  std::cout << "RunAsLocal was called " << RunsLocalCount << " time(s) ever." << std::endl;
}

int main()
{
  std::vector<Foo> vecFoos(10);

  for (auto & foo : vecFoos)
  {
    foo.RunAsMember();
    foo.RunAsLocal();
  }

  return 0;
}
</code>```

Should I use RunAsMember() or RunAsLocal()? What is best practice?

答:
It really depends on the situation.

If the variable is only used in one function, RunAsLocal() is a better choice. Less class member makes easier to read your code.

If the variable is used in more than one function, RunAsMember() is your only choice.

Body:
What is the better place to declare static variable if I use it in class member once. I can declare it as class member or local variable at class method? What is better for performance or like clean code meaning? For example:

class Foo
{
public:
  void RunAsMember();
  void RunAsLocal();

private:
  static int RunsMemberCount;
};

int Foo::RunsMemberCount = 0;

void Foo::RunAsMember()
{
  RunsMemberCount++;

  std::cout << "RunAsMember was called " << RunsMemberCount << " time(s) ever." << std::endl;
}

void Foo::RunAsLocal()
{
  static int RunsLocalCount = 0;
  RunsLocalCount++;

  std::cout << "RunAsLocal was called " << RunsLocalCount << " time(s) ever." << std::endl;
}

int main()
{
  std::vector<Foo> vecFoos(10);

  for (auto & foo : vecFoos)
  {
    foo.RunAsMember();
    foo.RunAsLocal();
  }

  return 0;
}

Should I use RunAsMember() or RunAsLocal()? What is best practice?


问:
How to use current company in BQL query
I need to know how I can get the user's current company so that I can use it in the Where clause of a BQL query.  I'm not talking about the tenant "company".  I'm talking about the companies that are defined on screen CS101500.  I'm not seeing anything on the AccessInfo that seems to indicate the current Company.  The current Branch ID is there but, I need the company to which the branch belongs.

Using version 21.203

TIA!

答:
This is the final code that got what I needed, per Josh's solution.  Van Hoesen for the win!!</p>
```<code>public class CurrentOrganization : IBqlCreator, IBqlOperand
{
    public virtual bool AppendExpression(ref SQLExpression exp, PXGraph graph, BqlCommandInfo info, BqlCommand.Selection selection)
    {
        if ((graph == null) || (!info.BuildExpression))
            return true;

        PXMutableCollection.AddMutableItem(this);

        //exp = new SQLConst(graph.BranchOrganizationID());
        Branch branch = PXSelect<Branch, Where<Branch.branchID, Equal<Current<AccessInfo.branchID>>>>.Select(graph);
        exp = new SQLConst( branch.OrganizationID);

        return true;

    }
    public void Verify(PXCache cache, object item, List<object> pars, ref bool? result, ref object value)
    {
        Branch branch = PXSelect<Branch, Where<Branch.branchID, Equal<Current<AccessInfo.branchID>>>>.Select(cache.Graph);
        value = branch.OrganizationID;
        //value = cache.Graph.BranchOrganizationID();
    }
}
</code>```

Title: How to use current company in BQL query

Body:
This is the final code that got what I needed, per Josh's solution.  Van Hoesen for the win!!

public class CurrentOrganization : IBqlCreator, IBqlOperand
{
    public virtual bool AppendExpression(ref SQLExpression exp, PXGraph graph, BqlCommandInfo info, BqlCommand.Selection selection)
    {
        if ((graph == null) || (!info.BuildExpression))
            return true;

        PXMutableCollection.AddMutableItem(this);

        //exp = new SQLConst(graph.BranchOrganizationID());
        Branch branch = PXSelect<Branch, Where<Branch.branchID, Equal<Current<AccessInfo.branchID>>>>.Select(graph);
        exp = new SQLConst( branch.OrganizationID);

        return true;

    }
    public void Verify(PXCache cache, object item, List<object> pars, ref bool? result, ref object value)
    {
        Branch branch = PXSelect<Branch, Where<Branch.branchID, Equal<Current<AccessInfo.branchID>>>>.Select(cache.Graph);
        value = branch.OrganizationID;
        //value = cache.Graph.BranchOrganizationID();
    }
}


问:
Getopt::Long getting a string with spaces into a variable
I'm making a perl script which uses Getopt::Long to parse command line arguments. However, I have an argument which can accept a string (with spaces). How can I get the whole string into a variable. For example:

```<code>./script.pl --string=blah blah blah blah yup --another-opt
</code>```

I need "blah blah blah blah yup" in variable $string. I know Getopt::Long supports multiple inputs for one argument when you know how many you will have (which I do not). Is this possible?

答:
You need to either put quotes around the argument:

```<code>./script.pl --string="blah blah blah blah yup" --another-opt
</code>```

or escape the spaces:

```<code>./script.pl --string=blah\ blah\ blah\ blah\ yup --another-opt
</code>```

Body:
I'm making a perl script which uses Getopt::Long to parse command line arguments. However, I have an argument which can accept a string (with spaces). How can I get the whole string into a variable. For example:

./script.pl --string=blah blah blah blah yup --another-opt

I need "blah blah blah blah yup" in variable $string. I know Getopt::Long supports multiple inputs for one argument when you know how many you will have (which I do not). Is this possible?

Body:
You need to either put quotes around the argument:

./script.pl --string="blah blah blah blah yup" --another-opt

or escape the spaces:

./script.pl --string=blah\ blah\ blah\ blah\ yup --another-opt


问:
C# how to call this method properly within Next generation
Thank you in advance for the help on this I have been struggling all week and my teacher will not respond.

Below you will find my current code for my Conways Game of life, I can not call the method that actually runs the simulation; can you please pick apart my code and help me find the answer.

You do not have to give me the actual code, just how to get it. I really want to learn this and be able to figure this out by miself in the future, but its due tonight and I have been stuck all week...

I need to call CountNeighborsToroidal() in NextGeneration() it needs to run the game thank you.

```<code>namespace The_Game_of_life
{
    public partial class Form1 : Form
    {

        bool[,] universe = new bool[30, 30];

        Color gridColor = Color.Black;
        Color cellColor = Color.Gray;

        Timer timer = new Timer();

        int generations = 0;

        public Form1()
        {
            InitializeComponent();

            timer.Interval = 100;
            timer.Tick += Timer_Tick;
            timer.Enabled = false;
        }

        // Calculate the next generation of cells
        private void NextGeneration()
        {

            CountNeighborsToroidal(cellRect.X, cellRect.Y);

            // Increment generation count
            generations++;

            // Update status strip generations
            toolStripStatusLabelGenerations.Text = "Generations = " + generations.ToString();
        }

        private void Timer_Tick(object sender, EventArgs e)
        {
            NextGeneration();
        }

        private void graphicsPanel1_Paint(object sender, PaintEventArgs e)
        {

            int cellWidth = graphicsPanel1.ClientSize.Width / universe.GetLength(0);

            int cellHeight = graphicsPanel1.ClientSize.Height / universe.GetLength(1);

            Pen gridPen = new Pen(gridColor, 1);

            Brush cellBrush = new SolidBrush(cellColor);

            for (int y = 0; y < universe.GetLength(1); y++)
            {

                for (int x = 0; x < universe.GetLength(0); x++)
                {

                    Rectangle cellRect = Rectangle.Empty;
                    cellRect.X = x * cellWidth;
                    cellRect.Y = y * cellHeight;
                    cellRect.Width = cellWidth;
                    cellRect.Height = cellHeight;

                    if (universe[x, y] == true)
                    {
                        e.Graphics.FillRectangle(cellBrush, cellRect);
                    }

                    e.Graphics.DrawRectangle(gridPen, cellRect.X, cellRect.Y, cellRect.Width, cellRect.Height);
                }
            }

            gridPen.Dispose();
            cellBrush.Dispose();
        }

        private void graphicsPanel1_MouseClick(object sender, MouseEventArgs e)
        {

            if (e.Button == MouseButtons.Left)
            {

                int cellWidth = graphicsPanel1.ClientSize.Width / universe.GetLength(0);
                int cellHeight = graphicsPanel1.ClientSize.Height / universe.GetLength(1);

                int x = e.X / cellWidth;

                int y = e.Y / cellHeight;

                universe[x, y] = !universe[x, y];

                graphicsPanel1.Invalidate();
            }
        }

        private void exitToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void openToolStripButton_Click(object sender, EventArgs e)
        {

            if (timer.Enabled)
            {
                timer.Enabled = false;
            }
            else
            {
                timer.Enabled = true;
            }
        }

        private void newToolStripMenuItem_Click(object sender, EventArgs e)
        {
            for (int y = 0; y < universe.GetLength(1); y++)
            {
                for (int x = 0; x < universe.GetLength(0); x++)
                {
                    universe[x, y] = false;
                }
            }

            graphicsPanel1.Invalidate();
        }

        private void toolStripButton1_Click(object sender, EventArgs e)
        {
            NextGeneration();
        }

        private int CountNeighborsToroidal(int x, int y)
        {
            int count = 0;
            int xLen = universe.GetLength(0);
            int yLen = universe.GetLength(1);
            for (int yOffset = -1; yOffset <= 1; yOffset++)
            {
                for (int xOffset = -1; xOffset <= 1; xOffset++)
                {
                    int xCheck = x + xOffset;
                    int yCheck = y + yOffset;
                    if ((xCheck - 1 >= 0 && yCheck - 1 > 0) && universe[xCheck - 1, yCheck - 1] == true)
                    {
                        count++;
                    }
                    if ((xCheck - 1 >= 0) && universe[xCheck - 1, yCheck] == true)
                    {
                        count++;
                    }
                    if ((xCheck - 1 >= 0 && yCheck + 1 < yLen) && universe[xCheck - 1, yCheck + 1] == true)
                    {
                        count++;
                    }
                    if ((xCheck - 1 >= 0) && universe[xCheck, yCheck - 1] == true)
                    {
                        count++;
                    }
                    if ((xCheck + 1 < yLen) && universe[xCheck, yCheck + 1] == true)
                    {
                        count++;
                    }
                    if ((xCheck + 1 < xLen && yCheck - 1 >= 0) && universe[xCheck + 1, yCheck - 1] == true)
                    {
                        count++;
                    }
                    if ((xCheck + 1 < xLen) && universe[xCheck + 1, yCheck] == true)
                    {
                        count++;
                    }
                    if ((xCheck + 1 < xLen && yCheck + 1 < yLen) && universe[xCheck + 1, yCheck + 1] == true)
                    {
                        count++;
                    }
                    if (universe[xCheck, yCheck] == true)
                    {
                        count++;
                    }
                }
            }
            return count;
        }
    }
}
</code>```

答:
I don't see any problem calling the CountNeighborsToroidal function from NextGeneration function. The only problem I see here is that the parameters cellRect.x and cellRect.y aren't defined in this piece of code, so you will always get an error.... Try changing CountNeighborsToroidal(cellRect.X, cellRect.Y); with some random int values and see if it works :</p>
```<code> private void NextGeneration()
    {

        CountNeighborsToroidal(22, 12);

        // Increment generation count
        generations++;

        // Update status strip generations
        toolStripStatusLabelGenerations.Text = "Generations = " + generations.ToString();
    }
</code>```

Body:
Thank you in advance for the help on this I have been struggling all week and my teacher will not respond.

Below you will find my current code for my Conways Game of life, I can not call the method that actually runs the simulation; can you please pick apart my code and help me find the answer.

You do not have to give me the actual code, just how to get it. I really want to learn this and be able to figure this out by miself in the future, but its due tonight and I have been stuck all week...

I need to call CountNeighborsToroidal() in NextGeneration() it needs to run the game thank you.

namespace The_Game_of_life
{
    public partial class Form1 : Form
    {

        bool[,] universe = new bool[30, 30];

        Color gridColor = Color.Black;
        Color cellColor = Color.Gray;

        Timer timer = new Timer();

        int generations = 0;

        public Form1()
        {
            InitializeComponent();

            timer.Interval = 100;
            timer.Tick += Timer_Tick;
            timer.Enabled = false;
        }

        // Calculate the next generation of cells
        private void NextGeneration()
        {

            CountNeighborsToroidal(cellRect.X, cellRect.Y);

            // Increment generation count
            generations++;

            // Update status strip generations
            toolStripStatusLabelGenerations.Text = "Generations = " + generations.ToString();
        }

        private void Timer_Tick(object sender, EventArgs e)
        {
            NextGeneration();
        }

        private void graphicsPanel1_Paint(object sender, PaintEventArgs e)
        {

            int cellWidth = graphicsPanel1.ClientSize.Width / universe.GetLength(0);

            int cellHeight = graphicsPanel1.ClientSize.Height / universe.GetLength(1);

            Pen gridPen = new Pen(gridColor, 1);

            Brush cellBrush = new SolidBrush(cellColor);

            for (int y = 0; y < universe.GetLength(1); y++)
            {

                for (int x = 0; x < universe.GetLength(0); x++)
                {

                    Rectangle cellRect = Rectangle.Empty;
                    cellRect.X = x * cellWidth;
                    cellRect.Y = y * cellHeight;
                    cellRect.Width = cellWidth;
                    cellRect.Height = cellHeight;

                    if (universe[x, y] == true)
                    {
                        e.Graphics.FillRectangle(cellBrush, cellRect);
                    }

                    e.Graphics.DrawRectangle(gridPen, cellRect.X, cellRect.Y, cellRect.Width, cellRect.Height);
                }
            }

            gridPen.Dispose();
            cellBrush.Dispose();
        }

        private void graphicsPanel1_MouseClick(object sender, MouseEventArgs e)
        {

            if (e.Button == MouseButtons.Left)
            {

                int cellWidth = graphicsPanel1.ClientSize.Width / universe.GetLength(0);
                int cellHeight = graphicsPanel1.ClientSize.Height / universe.GetLength(1);

                int x = e.X / cellWidth;

                int y = e.Y / cellHeight;

                universe[x, y] = !universe[x, y];

                graphicsPanel1.Invalidate();
            }
        }

        private void exitToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void openToolStripButton_Click(object sender, EventArgs e)
        {

            if (timer.Enabled)
            {
                timer.Enabled = false;
            }
            else
            {
                timer.Enabled = true;
            }
        }

        private void newToolStripMenuItem_Click(object sender, EventArgs e)
        {
            for (int y = 0; y < universe.GetLength(1); y++)
            {
                for (int x = 0; x < universe.GetLength(0); x++)
                {
                    universe[x, y] = false;
                }
            }

            graphicsPanel1.Invalidate();
        }

        private void toolStripButton1_Click(object sender, EventArgs e)
        {
            NextGeneration();
        }

        private int CountNeighborsToroidal(int x, int y)
        {
            int count = 0;
            int xLen = universe.GetLength(0);
            int yLen = universe.GetLength(1);
            for (int yOffset = -1; yOffset <= 1; yOffset++)
            {
                for (int xOffset = -1; xOffset <= 1; xOffset++)
                {
                    int xCheck = x + xOffset;
                    int yCheck = y + yOffset;
                    if ((xCheck - 1 >= 0 && yCheck - 1 > 0) && universe[xCheck - 1, yCheck - 1] == true)
                    {
                        count++;
                    }
                    if ((xCheck - 1 >= 0) && universe[xCheck - 1, yCheck] == true)
                    {
                        count++;
                    }
                    if ((xCheck - 1 >= 0 && yCheck + 1 < yLen) && universe[xCheck - 1, yCheck + 1] == true)
                    {
                        count++;
                    }
                    if ((xCheck - 1 >= 0) && universe[xCheck, yCheck - 1] == true)
                    {
                        count++;
                    }
                    if ((xCheck + 1 < yLen) && universe[xCheck, yCheck + 1] == true)
                    {
                        count++;
                    }
                    if ((xCheck + 1 < xLen && yCheck - 1 >= 0) && universe[xCheck + 1, yCheck - 1] == true)
                    {
                        count++;
                    }
                    if ((xCheck + 1 < xLen) && universe[xCheck + 1, yCheck] == true)
                    {
                        count++;
                    }
                    if ((xCheck + 1 < xLen && yCheck + 1 < yLen) && universe[xCheck + 1, yCheck + 1] == true)
                    {
                        count++;
                    }
                    if (universe[xCheck, yCheck] == true)
                    {
                        count++;
                    }
                }
            }
            return count;
        }
    }
}

Body:
I don't see any problem calling the CountNeighborsToroidal function from NextGeneration function. The only problem I see here is that the parameters cellRect.x and cellRect.y aren't defined in this piece of code, so you will always get an error.... Try changing CountNeighborsToroidal(cellRect.X, cellRect.Y); with some random int values and see if it works :

 private void NextGeneration()
    {

        CountNeighborsToroidal(22, 12);

        // Increment generation count
        generations++;

        // Update status strip generations
        toolStripStatusLabelGenerations.Text = "Generations = " + generations.ToString();
    }


问:
Trying to do MySQL Concat
I have this below data

```<code>ID     name         page1     page2      page3     page4     page5
1      demo           1         1          1         1         1
10     compliance     1         1          0         0         0
12     compliance     1         1          1         0         0
20     compliance     0         1          0         1         0
25     compliance     1         1          0         0         1
</code>```

I am trying to combine the columns which has 1 into it.

I tried it by Concat like below

```<code>Select id, name,
Concat (
case when page1 = 1 then 'page1, ' End
case when page2 = 1 then 'page2, ' End
case when page3 = 1 then 'page3, ' End
case when page4 = 1 then 'page4, ' End
case when page5 = 1 then 'page5, ' End
)
</code>```

But this gives me below

```<code>ID     name          yes page
1      demo         page1, page2, page3, page4, page5
10     compliance    NULL
12     compliance    NULL
20     compliance    NULL
25     compliance    NULL
</code>```

and I am looking to have something like below

```<code>ID     name          yes page
1      demo         page1, page2, page3, page4, page5,
10     compliance   page1, page2,
12     compliance   page1, page2, page3,
20     compliance   page2, page3, page4,
25     compliance   page1, page2, page5,
</code>```

Please let me know if there is I can do to my concat statement to work, so I can have table like above. Thank you so much for your help!

答:
In MySql, concat honours NULL values and any string being concatenated with NULL results in NULL.

Instead, use concat_ws which ignores NULL values. Ie,

```<code>Concat_ws (', '
  case when page1 = 1 then 'page1' End,
  case when page2 = 1 then 'page2' End...
)
</code>```

Title: Trying to do MySQL Concat

Body:
I have this below data

ID     name         page1     page2      page3     page4     page5
1      demo           1         1          1         1         1
10     compliance     1         1          0         0         0
12     compliance     1         1          1         0         0
20     compliance     0         1          0         1         0
25     compliance     1         1          0         0         1

I am trying to combine the columns which has 1 into it.

I tried it by Concat like below

Select id, name,
Concat (
case when page1 = 1 then 'page1, ' End
case when page2 = 1 then 'page2, ' End
case when page3 = 1 then 'page3, ' End
case when page4 = 1 then 'page4, ' End
case when page5 = 1 then 'page5, ' End
)

But this gives me below

ID     name          yes page
1      demo         page1, page2, page3, page4, page5
10     compliance    NULL
12     compliance    NULL
20     compliance    NULL
25     compliance    NULL

and I am looking to have something like below

ID     name          yes page
1      demo         page1, page2, page3, page4, page5,
10     compliance   page1, page2,
12     compliance   page1, page2, page3,
20     compliance   page2, page3, page4,
25     compliance   page1, page2, page5,

Please let me know if there is I can do to my concat statement to work, so I can have table like above. Thank you so much for your help!

Body:
In MySql, concat honours NULL values and any string being concatenated with NULL results in NULL.

Instead, use concat_ws which ignores NULL values. Ie,

Concat_ws (', '
  case when page1 = 1 then 'page1' End,
  case when page2 = 1 then 'page2' End...
)


问:
Chart.js how to show cursor pointer for labels & legends in line chart
I have the following example of line chart using chart.js. I want to show:

Pointer cursor for legend & labels on hover

Show all the label data on line hover

 var line_chart = new Chart(document.getElementById("line-chart"), {
        type: 'line',
        data: {
            labels: ['May', 'June', 'July'],
            datasets: [{
                    data: [15, 25, 15],
                    label: "My Dataset1",
                    borderColor: "#00F",
                    fill: false
                }, {
                    data: [35, 15, 25],
                    label: "My Dataset2",
                    borderColor: "#F00",
                    fill: false
                }
            ]
        },
        options: {

            tooltips: {
                mode: 'label',
            },
            hover: {
                mode: 'label'
            },
        }
    });```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.5.0/Chart.min.js"></script>

<div style='width:80%'>
<canvas id="line-chart" width="800" height="450"></canvas>
</div></code>```

答:
Took me quite some time, but almost none of the other answers work with the latest version of ChartJS (3.7.0 as of now). In the current version, there is a simple way to configure this behavior for all charts:

Chart.defaults.plugins.legend.onHover = function() {
   document.body.style.cursor = 'pointer';
};

Chart.defaults.plugins.legend.onLeave = function() {
   document.body.style.cursor = 'unset';
};
```

More details can be found in the official documentation: https://www.chartjs.org/docs/latest/configuration/legend.html

Body:
I have the following example of line chart using chart.js. I want to show:

Pointer cursor for legend & labels on hover

Show all the label data on line hover

 var line_chart = new Chart(document.getElementById("line-chart"), {
        type: 'line',
        data: {
            labels: ['May', 'June', 'July'],
            datasets: [{
                    data: [15, 25, 15],
                    label: "My Dataset1",
                    borderColor: "#00F",
                    fill: false
                }, {
                    data: [35, 15, 25],
                    label: "My Dataset2",
                    borderColor: "#F00",
                    fill: false
                }
            ]
        },
        options: {

            tooltips: {
                mode: 'label',
            },
            hover: {
                mode: 'label'
            },
        }
    });

<canvas id="line-chart" width="800" height="450"></canvas>

Body:
Took me quite some time, but almost none of the other answers work with the latest version of ChartJS (3.7.0 as of now). In the current version, there is a simple way to configure this behavior for all charts:

Chart.defaults.plugins.legend.onHover = function() {
   document.body.style.cursor = 'pointer';
};

Chart.defaults.plugins.legend.onLeave = function() {
   document.body.style.cursor = 'unset';
};

More details can be found in the official documentation: https://www.chartjs.org/docs/latest/configuration/legend.html


问:
AWS load balancer log analyzer
I'm new to AWS wolrd. My purpose is to find as soon as possible in case of problems using Elastic Load Balancer logs top ips from requests, if possible who they are or some inspection on it. I only found paid services. Does anyone know a free application or maybe a website that analyzes AWS ELB logs?</p>

答:
Elastic Load Balancing provides access logs that capture detailed information about requests sent to your load balancer. Each log contains information such as the time the request was received, the client's IP address, latencies, request paths, and server responses.

But keep in mind that access logging is an optional feature of Elastic Load Balancing that is disabled by default. After you enable access logging for your load balancer, Elastic Load Balancing captures the logs and stores them in the Amazon S3 bucket that you specify as compressed files. You can disable access logging at any time.

There are many complex and paid application that returns information regard access log but i advise you a simple, easy to use website that i use when i want to see top requester on our load balancer.

Website is https://vegalog.net

You shoud only upload your log file taken from S3 bucket and it returns to you a report with top requester, who they are (using whois function), response time and other useful informations.

Title: AWS load balancer log analyzer


问:
Google Form Responses deleting Formulas
I have a Google Sheet receiving responses from a Google Form, and I am trying to set up some formulas that dynamically engage with new entries as they come in. However, whether I put the formulas on the same sheet where the data populates in a different column, or if I set up a new sheet to reference the other sheet, each time new data comes in, it deletes everything on that same row.

To be clear, I have formulas set up to use the rows directly below the last line of data, and then when a new entry populates, it deletes everything in that row. I've also tried using a different sheet, copying the data over, and it still deletes all the data on the same row on another sheet as well.

Is there a way to dynamically move the Form Responses data as it comes in to a place where it won't be manipulating other cells?

答: I have no problem with that. Leave the answers in their own columns and create an array formula in subsequent columns. Example:

Title: Google Form Responses deleting Formulas


问:
ActiveRecord - left join on filtered list
I have the following classes:

```<code>Parent
  has_many :children

Child
  belongs_to :parent
  belongs_to :other
</code>```

I want to be able to left join parents and children and also filter the children by the other association. I achieved this by writing a custom join clause:

```<code>joins("LEFT JOIN children ON children.parent_id=parents.id AND children.other_id IN (#{ids.join(",")})")
</code>```

It seems like there should be a more Rails-y way to achieve this that doesn't involve a custom join clause. Any ideas?

答:
You could use Arel for that join, because the ActiveRecord joins doesn't allow bind parameters:

```<code>children = Children.arel_table
parents = Parent.arel_table
join = children
  .join(parents, Arel::Nodes::OuterJoin)
  .on(
    children[:parent_id]
      .eq(parents[:id])
      .and(children[:other_id].in(ids))
  )

Children.joins(join.join_sources)
</code>```

The idea is to create the LEFT (OUTER) JOIN as it normally is, and then add the and(children[:other_id].in(ids)) which makes the AND ... IN (...).

Body:
I have the following classes:

Parent
  has_many :children

Child
  belongs_to :parent
  belongs_to :other

I want to be able to left join parents and children and also filter the children by the other association. I achieved this by writing a custom join clause:

joins("LEFT JOIN children ON children.parent_id=parents.id AND children.other_id IN (#{ids.join(",")})")

It seems like there should be a more Rails-y way to achieve this that doesn't involve a custom join clause. Any ideas?

Body:
You could use Arel for that join, because the ActiveRecord joins doesn't allow bind parameters:

children = Children.arel_table
parents = Parent.arel_table
join = children
  .join(parents, Arel::Nodes::OuterJoin)
  .on(
    children[:parent_id]
      .eq(parents[:id])
      .and(children[:other_id].in(ids))
  )

Children.joins(join.join_sources)

The idea is to create the LEFT (OUTER) JOIN as it normally is, and then add the and(children[:other_id].in(ids)) which makes the AND ... IN (...).


问:
How to show only files that are larger than 2000 on bash in one line?
How to show only files that are larger than 2000 on bash in one line?</p>
```<code>[gooder@GOD]$ find videos/ -type f -printf '%k %p\n' |sort -n |tail -n 20
1760 videos/0-2GBou1t.mp4
1500752 videos/0-2GBout.mp4
2291528 videos/0-2GB1.mkv
</code>```

答:
Assuming you mean 2000 bytes.</p>
```<code>find videos/ -type f -size +2000c
</code>```

Body:
How to show only files that are larger than 2000 on bash in one line?

[gooder@GOD]$ find videos/ -type f -printf '%k %p\n' |sort -n |tail -n 20
1760 videos/0-2GBou1t.mp4
1500752 videos/0-2GBout.mp4
2291528 videos/0-2GB1.mkv

Body:
Assuming you mean 2000 bytes.

find videos/ -type f -size +2000c


问:
How to make conda or mamba verbose using environment variable?
I am looking for an environment variable I can set to make mamba verbose while it is resolving the dependency to see if it is stuck at a certain stage.</p>

答:
This can be done either through Conda configuration (i.e., .condarc) or an environment variable. The environment variable has the highest priority, so I recommend setting default behavior via the configuration such that the environment variable is still available for overriding.

There is an (older) article detailing the Conda configuration system: "The Conda Configuration Engine for Power Users".

Conda Configuration

The configuration variable is verbosity. Here is the description:

$ conda config --describe verbosity
# # verbosity (int)
# #   aliases: verbose
# #   Sets output log level. 0 is warn. 1 is info. 2 is debug. 3 is trace.
# #
# verbosity: 0
```
<p>which shows <code>0</code> is the default. It can be set with</p>
<pre class="lang-bash prettyprint-override"><code>conda config --set verbosity 2  # debug by default
</code>```

Environment Variable

All Conda configuration variables can be set via CONDA_* environment variables. To override the verbosity configuration, one can use:

## temporary setting
CONDA_VERBOSITY=2 conda info

## permanent setting, e.g., in a .bashrc or .bash_profile
export CONDA_VERBOSITY=2
```

Body:
This can be done either through Conda configuration (i.e., .condarc) or an environment variable. The environment variable has the highest priority, so I recommend setting default behavior via the configuration such that the environment variable is still available for overriding.

There is an (older) article detailing the Conda configuration system: "The Conda Configuration Engine for Power Users".

Conda Configuration

The configuration variable is verbosity. Here is the description:

$ conda config --describe verbosity
# # verbosity (int)
# #   aliases: verbose
# #   Sets output log level. 0 is warn. 1 is info. 2 is debug. 3 is trace.
# #
# verbosity: 0

which shows 0 is the default. It can be set with

conda config --set verbosity 2  # debug by default

Environment Variable

All Conda configuration variables can be set via CONDA_* environment variables. To override the verbosity configuration, one can use:

## temporary setting
CONDA_VERBOSITY=2 conda info

## permanent setting, e.g., in a .bashrc or .bash_profile
export CONDA_VERBOSITY=2


问:
How to do a repeatable nested UIView animation?
I need to animate bird fly where the bird image appears with as small pixel, then grows and moves until middle point of the animation. After that the bird shrinks back to small pixels but moves forwardly till end point is reached. And I need this animation to be repeatable. I did that with two animations: the first that grows the image and moves and, in the complete block, the second one that shrinks and moves. The first one animation has repeat option, the recond beginFromCurrentState. The problem is the complete block has never been called. What am I missing, maybe complete block doesn't work for repeatable animations? Here is my code:</p>

```<code>[UIView animateWithDuration:4.0 delay:0 options:(UIViewAnimationCurveEaseIn | UIViewAnimationOptionRepeat | UIViewAnimationOptionAllowUserInteraction) animations:^{
    self.bird1.transform = CGAffineTransformScale(CGAffineTransformIdentity, 1, 1);
    self.bird1.center = bird1MiddlePoint;

} completion:^(BOOL finished){if (finished){

    NSLog(@"doesn't get called");
    [UIView animateWithDuration:4.0 delay:0 options:(UIViewAnimationOptionBeginFromCurrentState | UIViewAnimationOptionAllowUserInteraction) animations:^{

        self.bird1.transform = CGAffineTransformScale(CGAffineTransformIdentity, 0.1, 0.1);
        self.bird1.center = bird1EndPoint;} completion:^(BOOL finished){if (finished && !self.gameManager.isPlaying){

            [UIView setAnimationRepeatCount:0];
            [self.bird1 removeFromSuperview];

    }}];
}}];
</code>```

答: If the parent animation is repeating indefinitely, since you set UIViewAnimationOptionRepeat, its never going to call the completion block because its never finishes. It's as simple as that.

Body:
I need to animate bird fly where the bird image appears with as small pixel, then grows and moves until middle point of the animation. After that the bird shrinks back to small pixels but moves forwardly till end point is reached. And I need this animation to be repeatable. I did that with two animations: the first that grows the image and moves and, in the complete block, the second one that shrinks and moves. The first one animation has repeat option, the recond beginFromCurrentState. The problem is the complete block has never been called. What am I missing, maybe complete block doesn't work for repeatable animations? Here is my code:

[UIView animateWithDuration:4.0 delay:0 options:(UIViewAnimationCurveEaseIn | UIViewAnimationOptionRepeat | UIViewAnimationOptionAllowUserInteraction) animations:^{
    self.bird1.transform = CGAffineTransformScale(CGAffineTransformIdentity, 1, 1);
    self.bird1.center = bird1MiddlePoint;

} completion:^(BOOL finished){if (finished){

    NSLog(@"doesn't get called");
    [UIView animateWithDuration:4.0 delay:0 options:(UIViewAnimationOptionBeginFromCurrentState | UIViewAnimationOptionAllowUserInteraction) animations:^{

        self.bird1.transform = CGAffineTransformScale(CGAffineTransformIdentity, 0.1, 0.1);
        self.bird1.center = bird1EndPoint;} completion:^(BOOL finished){if (finished && !self.gameManager.isPlaying){

            [UIView setAnimationRepeatCount:0];
            [self.bird1 removeFromSuperview];

    }}];
}}];


答:
This is a job for CONCAT_WS() and IF(condition, 'text', NULL).  Fiddle.

SELECT ID, name,
       CONCAT_WS(', ',
         IF(page1, 'page1', NULL),
         IF(page2, 'page2', NULL),
         IF(page3, 'page3', NULL),
         IF(page4, 'page4', NULL),
         IF(page5, 'page5', NULL)) pages
  FROM tbl;
```

CONCAT_WS() takes a list of items and concatenates them ignoring the ones with NULL values. And, it puts in a separator (comma - space) in my example.

Title: Trying to do MySQL Concat

Body:
This is a job for CONCAT_WS() and IF(condition, 'text', NULL).  Fiddle.

SELECT ID, name,
       CONCAT_WS(', ',
         IF(page1, 'page1', NULL),
         IF(page2, 'page2', NULL),
         IF(page3, 'page3', NULL),
         IF(page4, 'page4', NULL),
         IF(page5, 'page5', NULL)) pages
  FROM tbl;

CONCAT_WS() takes a list of items and concatenates them ignoring the ones with NULL values. And, it puts in a separator (comma - space) in my example.


问:
Minimum number of increments
Given an array A of N elements we can perform the following kind of updates on it:

Pick an i and add 1 to all elements in range [i,N]

What is the minimum number of updates such that there is no element in A equal to 0. That is, the minimum number of updates such that for each i A[i] != 0

答:
Observation 1: order in which we apply the increments does not change the result. With this observation there exists the optimal increments where all increments are applied to increasing indices.

Observation 2: if we have a correct solution and at the moment of application of increment to range [i, N] it is true that A[i] != 0 the solution where this increment is replaced with increment [i + 1, N] is also correct.

With these two observations in mind we know that there is an optimal solution where increments are applied left to right and every increment is applied at index i such that A[i] == 0. That makes the following algorithm correct (written in pseudocode):

```<code>increments=0
for i=1 to N
  if A[i] + increments == 0
    increments += 1
</code>```

Here to add 1 to the suffix as i am looping with increasing indices i just store in the variable how many increments would affect current index, and it so happens that after the loop finishes it also contains the answer.

Title: Minimum number of increments

Body:
Observation 1: order in which we apply the increments does not change the result. With this observation there exists the optimal increments where all increments are applied to increasing indices.

Observation 2: if we have a correct solution and at the moment of application of increment to range [i, N] it is true that A[i] != 0 the solution where this increment is replaced with increment [i + 1, N] is also correct.

With these two observations in mind we know that there is an optimal solution where increments are applied left to right and every increment is applied at index i such that A[i] == 0. That makes the following algorithm correct (written in pseudocode):

increments=0
for i=1 to N
  if A[i] + increments == 0
    increments += 1

Here to add 1 to the suffix as i am looping with increasing indices i just store in the variable how many increments would affect current index, and it so happens that after the loop finishes it also contains the answer.


问:
How to set input type date's default value to today?
Given an input element:

<input type="date" />
```

Is there any way to set the default value of the date field to today's date?

答:
Nowadays, we should not use anymore moment.js but day.js to handle that without any side-effect. Moment.js was great, but it is not pushing forward, and it is relatively big but was very useful. day.js has good feature enough to be the new candidate to use for future years.

```<code>let now = dayjs(); /* same as now = dayjs(new Date()); */
</code>```

Body:
Given an input element:

<input type="date" />

Is there any way to set the default value of the date field to today's date?

Body:
Nowadays, we should not use anymore moment.js but day.js to handle that without any side-effect. Moment.js was great, but it is not pushing forward, and it is relatively big but was very useful. day.js has good feature enough to be the new candidate to use for future years.

let now = dayjs(); /* same as now = dayjs(new Date()); */


问:
how I can delete empty lines and lines starting from '/publications'?
my code:

```<code>import requests
from bs4 import BeautifulSoup
request = requests.get("https://news.google.com/topics/CAAqRggKIkBDQklTS2pvUVkyOTJhV1JmZEdWNGRGOXhkV1Z5ZVlJQkZRb0lMMjB2TURKcU56RVNDUzl0THpBeFkzQjVlU2dBUAE/sections/CAQqSggAKkYICiJAQ0JJU0tqb1FZMjkyYVdSZmRHVjRkRjl4ZFdWeWVZSUJGUW9JTDIwdk1ESnFOekVTQ1M5dEx6QXhZM0I1ZVNnQVAB?hl=en-US&gl=US&ceid=US%3Aen")
content = BeautifulSoup(request.content, 'html.parser')
find = content.find('div', class_='ajwQHc BL5WZb')
#open('test.html', 'w').write(findstr.find)
h3 = find.find_all('h3')
time = find.find_all('time')
link = find.find_all('article')#.find_all('a').get('href').replace('.', '')
result = []
#print('https://news.google.com' + link)
for result in link:
    alinks = result.find_all('a')
    alinks1 = []
    for alinks1 in alinks:
        alinks2 = alinks1.get('href')
        alinksreplace = str(alinks2)
        alinksreplace1 = alinksreplace.replace(".", "")
        alinksreplace2 = alinksreplace1.replace("None", "")
        print(alinksreplace2)[![enter image description here]
</code>```

I want remove empty lines and links started with /publications:

I tried a lot of ways but nothing works

```<code>/articles/CBMinQFodHRwczovL3d3dy5rcHZpLmNvbS9uZXdzL25hdGlvbmFsX25ld3MvZGFpbHktd3lvbWluZy1jb3JvbmF2aXJ1cy11cGRhdGUtNDA0LW5ldy1jYXNlcy0xLTAxNi1uZXctcmVjb3Zlcmllcy9hcnRpY2xlX2JlZmMxN2MyLTI1NGYtNTQxOS1hOGIwLTIyYmUwNjNlY2NhYi5odG1s0gEA?hl=en-US&gl=US&ceid=US%3Aen
/publications/CAAqBwgKMInn9gowidnVAg?hl=en-US&gl=US&ceid=US%3Aen
</code>```

答:
There's a lot to go over here. Let's go over your misconceptions first

```<code>result = []
for result in link:
    #...
</code>```

and

```<code>    alinks1 = []
    for alinks1 in alinks:
        #...
</code>```

You keep instantiating variables before your for loop unnecessarily and incorrectly. Neither alinks1 or result will be a list unless the returns from the RSE (right side expression) are a list. It would be better to assume you have no idea what will be returned and just accept it for whatever it is.

```<code>        alinks2 = alinks1.get('href')
        alinksreplace = str(alinks2)
        alinksreplace1 = alinksreplace.replace(".", "")
        alinksreplace2 = alinksreplace1.replace("None", "")
</code>```

This could get ridiculous and cumbersome very quickly. If you need to do this much formatting to the data you should be using regex.

Below is a heavily reformatted version of your code that examples what you want to do. The main portion is not trivial.

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

REP = re.compile(r'None|\n|publications/|\.') #content to remove

req = requests.get("https://news.google.com/topics/CAAqRggKIkBDQklTS2pvUVkyOTJhV1JmZEdWNGRGOXhkV1Z5ZVlJQkZRb0lMMjB2TURKcU56RVNDUzl0THpBeFkzQjVlU2dBUAE/sections/CAQqSggAKkYICiJAQ0JJU0tqb1FZMjkyYVdSZmRHVjRkRjl4ZFdWeWVZSUJGUW9JTDIwdk1ESnFOekVTQ1M5dEx6QXhZM0I1ZVNnQVAB?hl=en-US&gl=US&ceid=US%3Aen")

if find := BeautifulSoup(req.content, 'html.parser').find('div', class_='ajwQHc BL5WZb'):
    links = list(filter(lambda a: bool(a), [REP.sub('', str(link.get('href'))) for result in find.find_all('article') for link in result.find_all('a')]))
    print(*links, sep='\n')
else:
    print('No content was found.')
</code>```

The main thing to note is this part of the main line:

list(filter(lambda a: bool(a), [REP.sub('', str(link.get('href')))

Start from right to left to understand it. First we get the link, but convert it to a string (no matter what) in order to catch None. Then the value is processed through the replacement regex. We then dump the results into a filter so we can skip all occurrences of '', and finally convert it to a list, which may or may not be actually necessary ... it depends on your skill and needs.

Body:
my code:

import requests
from bs4 import BeautifulSoup
request = requests.get("https://news.google.com/topics/CAAqRggKIkBDQklTS2pvUVkyOTJhV1JmZEdWNGRGOXhkV1Z5ZVlJQkZRb0lMMjB2TURKcU56RVNDUzl0THpBeFkzQjVlU2dBUAE/sections/CAQqSggAKkYICiJAQ0JJU0tqb1FZMjkyYVdSZmRHVjRkRjl4ZFdWeWVZSUJGUW9JTDIwdk1ESnFOekVTQ1M5dEx6QXhZM0I1ZVNnQVAB?hl=en-US&gl=US&ceid=US%3Aen")
content = BeautifulSoup(request.content, 'html.parser')
find = content.find('div', class_='ajwQHc BL5WZb')
#open('test.html', 'w').write(findstr.find)
h3 = find.find_all('h3')
time = find.find_all('time')
link = find.find_all('article')#.find_all('a').get('href').replace('.', '')
result = []
#print('https://news.google.com' + link)
for result in link:
    alinks = result.find_all('a')
    alinks1 = []
    for alinks1 in alinks:
        alinks2 = alinks1.get('href')
        alinksreplace = str(alinks2)
        alinksreplace1 = alinksreplace.replace(".", "")
        alinksreplace2 = alinksreplace1.replace("None", "")
        print(alinksreplace2)[![enter image description here]

I want remove empty lines and links started with /publications:

I tried a lot of ways but nothing works

/articles/CBMinQFodHRwczovL3d3dy5rcHZpLmNvbS9uZXdzL25hdGlvbmFsX25ld3MvZGFpbHktd3lvbWluZy1jb3JvbmF2aXJ1cy11cGRhdGUtNDA0LW5ldy1jYXNlcy0xLTAxNi1uZXctcmVjb3Zlcmllcy9hcnRpY2xlX2JlZmMxN2MyLTI1NGYtNTQxOS1hOGIwLTIyYmUwNjNlY2NhYi5odG1s0gEA?hl=en-US&gl=US&ceid=US%3Aen
/publications/CAAqBwgKMInn9gowidnVAg?hl=en-US&gl=US&ceid=US%3Aen

Body:
There's a lot to go over here. Let's go over your misconceptions first

result = []
for result in link:
    #...

and

    alinks1 = []
    for alinks1 in alinks:
        #...

You keep instantiating variables before your for loop unnecessarily and incorrectly. Neither alinks1 or result will be a list unless the returns from the RSE (right side expression) are a list. It would be better to assume you have no idea what will be returned and just accept it for whatever it is.

        alinks2 = alinks1.get('href')
        alinksreplace = str(alinks2)
        alinksreplace1 = alinksreplace.replace(".", "")
        alinksreplace2 = alinksreplace1.replace("None", "")

This could get ridiculous and cumbersome very quickly. If you need to do this much formatting to the data you should be using regex.

Below is a heavily reformatted version of your code that examples what you want to do. The main portion is not trivial.

import requests, re
from bs4 import BeautifulSoup

REP = re.compile(r'None|\n|publications/|\.') #content to remove

req = requests.get("https://news.google.com/topics/CAAqRggKIkBDQklTS2pvUVkyOTJhV1JmZEdWNGRGOXhkV1Z5ZVlJQkZRb0lMMjB2TURKcU56RVNDUzl0THpBeFkzQjVlU2dBUAE/sections/CAQqSggAKkYICiJAQ0JJU0tqb1FZMjkyYVdSZmRHVjRkRjl4ZFdWeWVZSUJGUW9JTDIwdk1ESnFOekVTQ1M5dEx6QXhZM0I1ZVNnQVAB?hl=en-US&gl=US&ceid=US%3Aen")

if find := BeautifulSoup(req.content, 'html.parser').find('div', class_='ajwQHc BL5WZb'):
    links = list(filter(lambda a: bool(a), [REP.sub('', str(link.get('href'))) for result in find.find_all('article') for link in result.find_all('a')]))
    print(*links, sep='\n')
else:
    print('No content was found.')

The main thing to note is this part of the main line:

list(filter(lambda a: bool(a), [REP.sub('', str(link.get('href')))

Start from right to left to understand it. First we get the link, but convert it to a string (no matter what) in order to catch None. Then the value is processed through the replacement regex. We then dump the results into a filter so we can skip all occurrences of '', and finally convert it to a list, which may or may not be actually necessary ... it depends on your skill and needs.