问:
instagram enc_password generation
Im trying to make class for generating base64 string for instagram web auth via C#.
as base for my code i used this node.js sample - click
its looks great and work perfectly but i have no idea how realise this magic:

```<code>const key = crypto.pseudoRandomBytes(32);
publicKey = '5a0b3cd9a12fef6c786afe28cfceef60550d27ea6657bb15be4a271eaadb0903';
const encryptedKey = tweetnacl.sealedbox.seal(key, Buffer.from(publicKey, 'hex'));
</code>```

for aes-256-gcm encrypting i use BouncyCastle library but cant find similar action like tweetnacl.sealedbox.seal
As I understand this action returned uint8array with encrypted publicKey

```<code>import nacl from 'tweetnacl';
import nonceGenerator from './nonce';
import {overheadLength} from './consts';
import {zero} from './utils';

export default function seal(m, pk){
    var c = new Uint8Array(overheadLength + m.length);

//overheadLength = nacl.box.publicKeyLength + nacl.box.overheadLength;

    var ek = nacl.box.keyPair();
    c.set(ek.publicKey);

    var nonce = nonceGenerator(ek.publicKey, pk);
    var boxed = nacl.box(m, nonce, pk, ek.secretKey);
    c.set(boxed, ek.publicKey.length);

    zero(ek.secretKey);

    return c;
};
</code>```

it's very hard for me to do it myself, and I'd be very grateful for any help.

答:
I tried porting to c #, but there were problems with the decrypt

```<code>private static  encryptPassword(string password, string encryptionPubKey, string encryptionKeyId)
 {

            byte[] passwordAsByte = Encoding.ASCII.GetBytes(password);
            byte[] data = Convert.FromBase64String(encryptionPubKey);
            string decoededPubKey = Encoding.UTF8.GetString(data);

            decoededPubKey = decoededPubKey.Replace("-----BEGIN PUBLIC KEY-----", "");
    decoededPubKey = decoededPubKey.Replace("-----END PUBLIC KEY-----", "");
    SecureRandom random = new SecureRandom();
        byte[] randKey = new byte[32];
        random.NextBytes(randKey);
        byte[] iv = new byte[12];
        random.NextBytes(iv);
    //String date = String.valueOf(new Date().getTime() / 1000);
    long tsLong = DateTimeOffset.UtcNow.ToUnixTimeSeconds() / 1000;
        string date = tsLong.ToString();

            var header = new MemoryStream(2);
        header.Write(BitConverter.GetBytes(Convert.ToInt32(1)));
    header.Write(BitConverter.GetBytes(Convert.ToInt32(int.Parse(encryptionKeyId))));
            MemoryStream timeAAD = new MemoryStream(10);
        timeAAD.Write(Encoding.ASCII.GetBytes(date));
//////////////////////////////////////////////////////////////////
    X509EncodedKeySpec publicSpec = new X509EncodedKeySpec(Base64.decode(decoededPubKey, Base64.NO_WRAP));
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        PublicKey publicKey = keyFactory.generatePublic(publicSpec);
        Cipher rsaCipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
        rsaCipher.init(Cipher.ENCRYPT_MODE, publicKey);
    byte[] rsaEncrypted = rsaCipher.doFinal(randKey);

            MemoryStream sizeBuff = new MemoryStream(2);
        sizeBuff.order(ByteOrder.LITTLE_ENDIAN);
    sizeBuff.putChar((char) rsaEncrypted.Length);
///////////////////////////////////////////////////////////////////////
    AeadParameters parameters = new AeadParameters(new KeyParameter(randKey), 128, iv, timeAAD.ToArray());
        GcmBlockCipher gcmEngine = new GcmBlockCipher(new AesFastEngine());
        gcmEngine.Init(true, parameters);
    byte[] gcmText = new byte[gcmEngine.GetOutputSize(passwordAsByte.Length)];
        int len = gcmEngine.ProcessBytes(passwordAsByte, 0, passwordAsByte.Length, gcmText, 0);
        gcmEngine.DoFinal(gcmText, len);
    byte[] encPass = Arrays.CopyOfRange(gcmText, 0, gcmText.Length - 16);
        byte[] authTag = Arrays.CopyOfRange(gcmText, gcmText.Length - 16, gcmText.Length);

            var a = header.Position + iv.Length + sizeBuff.Position + rsaEncrypted.Length + authTag.Length + encPass.Length;
            MemoryStream result = new MemoryStream(a);
        result.Write(header.ToArray());
    result.Write(iv);
    result.Write(sizeBuff.ToArray());
    result.Write(rsaEncrypted);
    result.Write(authTag);
    result.Write(encPass);

    //return new Pair(Convert.ToInt64(date), Base64.encodeToString(result.array(), Base64.NO_WRAP));
 }
</code>```

This is almost ready code, if there are corrections, write in the comments, I will fix it

Title: instagram enc_password generation

Body:
Im trying to make class for generating base64 string for instagram web auth via C#.
as base for my code i used this node.js sample - click
its looks great and work perfectly but i have no idea how realise this magic:

const key = crypto.pseudoRandomBytes(32);
publicKey = '5a0b3cd9a12fef6c786afe28cfceef60550d27ea6657bb15be4a271eaadb0903';
const encryptedKey = tweetnacl.sealedbox.seal(key, Buffer.from(publicKey, 'hex'));

for aes-256-gcm encrypting i use BouncyCastle library but cant find similar action like tweetnacl.sealedbox.seal
As I understand this action returned uint8array with encrypted publicKey

import nacl from 'tweetnacl';
import nonceGenerator from './nonce';
import {overheadLength} from './consts';
import {zero} from './utils';

export default function seal(m, pk){
    var c = new Uint8Array(overheadLength + m.length);

//overheadLength = nacl.box.publicKeyLength + nacl.box.overheadLength;

    var ek = nacl.box.keyPair();
    c.set(ek.publicKey);

    var nonce = nonceGenerator(ek.publicKey, pk);
    var boxed = nacl.box(m, nonce, pk, ek.secretKey);
    c.set(boxed, ek.publicKey.length);

    zero(ek.secretKey);

    return c;
};

it's very hard for me to do it myself, and I'd be very grateful for any help.

Body:
I tried porting to c #, but there were problems with the decrypt

private static  encryptPassword(string password, string encryptionPubKey, string encryptionKeyId)
 {

            byte[] passwordAsByte = Encoding.ASCII.GetBytes(password);
            byte[] data = Convert.FromBase64String(encryptionPubKey);
            string decoededPubKey = Encoding.UTF8.GetString(data);

            decoededPubKey = decoededPubKey.Replace("-----BEGIN PUBLIC KEY-----", "");
    decoededPubKey = decoededPubKey.Replace("-----END PUBLIC KEY-----", "");
    SecureRandom random = new SecureRandom();
        byte[] randKey = new byte[32];
        random.NextBytes(randKey);
        byte[] iv = new byte[12];
        random.NextBytes(iv);
    //String date = String.valueOf(new Date().getTime() / 1000);
    long tsLong = DateTimeOffset.UtcNow.ToUnixTimeSeconds() / 1000;
        string date = tsLong.ToString();

            var header = new MemoryStream(2);
        header.Write(BitConverter.GetBytes(Convert.ToInt32(1)));
    header.Write(BitConverter.GetBytes(Convert.ToInt32(int.Parse(encryptionKeyId))));
            MemoryStream timeAAD = new MemoryStream(10);
        timeAAD.Write(Encoding.ASCII.GetBytes(date));
//////////////////////////////////////////////////////////////////
    X509EncodedKeySpec publicSpec = new X509EncodedKeySpec(Base64.decode(decoededPubKey, Base64.NO_WRAP));
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        PublicKey publicKey = keyFactory.generatePublic(publicSpec);
        Cipher rsaCipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
        rsaCipher.init(Cipher.ENCRYPT_MODE, publicKey);
    byte[] rsaEncrypted = rsaCipher.doFinal(randKey);

            MemoryStream sizeBuff = new MemoryStream(2);
        sizeBuff.order(ByteOrder.LITTLE_ENDIAN);
    sizeBuff.putChar((char) rsaEncrypted.Length);
///////////////////////////////////////////////////////////////////////
    AeadParameters parameters = new AeadParameters(new KeyParameter(randKey), 128, iv, timeAAD.ToArray());
        GcmBlockCipher gcmEngine = new GcmBlockCipher(new AesFastEngine());
        gcmEngine.Init(true, parameters);
    byte[] gcmText = new byte[gcmEngine.GetOutputSize(passwordAsByte.Length)];
        int len = gcmEngine.ProcessBytes(passwordAsByte, 0, passwordAsByte.Length, gcmText, 0);
        gcmEngine.DoFinal(gcmText, len);
    byte[] encPass = Arrays.CopyOfRange(gcmText, 0, gcmText.Length - 16);
        byte[] authTag = Arrays.CopyOfRange(gcmText, gcmText.Length - 16, gcmText.Length);

            var a = header.Position + iv.Length + sizeBuff.Position + rsaEncrypted.Length + authTag.Length + encPass.Length;
            MemoryStream result = new MemoryStream(a);
        result.Write(header.ToArray());
    result.Write(iv);
    result.Write(sizeBuff.ToArray());
    result.Write(rsaEncrypted);
    result.Write(authTag);
    result.Write(encPass);

    //return new Pair(Convert.ToInt64(date), Base64.encodeToString(result.array(), Base64.NO_WRAP));
 }

This is almost ready code, if there are corrections, write in the comments, I will fix it


来源: stackexchange

问:
Transform Numpy Arrays to specific 2 dimensional Form
Currently I work with numpy and have to transform large data sets. Starting point are some one-dimensional arrays. These should be combined to a large 2 dimensional array. I attach a small example how it should look like.

# Returns 16 arrays with four numbers in each array (from 0 to 3)
array = [np.arange(4) for i in range(16)]

# Each of these arrays should be transformed to become a two-dimensional shape=(2,2)
array.reshape((2,2))

1. Step:
# Subsequently, the first of all of them are to be brought together:
[[0,1,0,1,0,1,0,1,0,1, ...,0,1],
[2,3,2,3,2,3,2,3,2,3, ...,2,3]]

2. Step:
# Afterwards, the arrays are to be wrapped on the basis of a length (let's say 8). The result should look like this:
[[0,1,0,1,0,1,0,1],
[2,3,2,3,2,3,2,3],
[0,1,0,1,0,1,0,1],
[2,3,2,3,2,3,2,3]]

```

This is only a miniature example. I'm actually working with an array with the length of 64 that is to be converted to an array with the shape=(8, 8). And at the end I want to create a 2 dimensional array with the dimensions 416x416.

Edit: So my current question is, how do I get to the first and second step in the example above?

ContentLicense: CC BY-SA 4.0

Body:
Currently I work with numpy and have to transform large data sets. Starting point are some one-dimensional arrays. These should be combined to a large 2 dimensional array. I attach a small example how it should look like.

# Returns 16 arrays with four numbers in each array (from 0 to 3)
array = [np.arange(4) for i in range(16)]

# Each of these arrays should be transformed to become a two-dimensional shape=(2,2)
array.reshape((2,2))

1. Step:
# Subsequently, the first of all of them are to be brought together:
[[0,1,0,1,0,1,0,1,0,1, ...,0,1],
[2,3,2,3,2,3,2,3,2,3, ...,2,3]]

2. Step:
# Afterwards, the arrays are to be wrapped on the basis of a length (let's say 8). The result should look like this:
[[0,1,0,1,0,1,0,1],
[2,3,2,3,2,3,2,3],
[0,1,0,1,0,1,0,1],
[2,3,2,3,2,3,2,3]]

This is only a miniature example. I'm actually working with an array with the length of 64 that is to be converted to an array with the shape=(8, 8). And at the end I want to create a 2 dimensional array with the dimensions 416x416.

Edit: So my current question is, how do I get to the first and second step in the example above?

Body:
Well the example you posted explains everything clearly. I don't know what the problem is.
An implementation for your 64 to 8*8 transformation would be like:

import numpy as np

a = np.array([i for i in range(64)]) # defines a 64*1 1-D array
# a = array([ 0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14, 15, 16,
#        17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33,
#        34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50,
#        51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63])
print(a.shape) # (64,)
a = a.reshape((8,8)) # makes "a" an 8*8 2-D array
# array([[ 0,  1,  2,  3,  4,  5,  6,  7],
#        [ 8,  9, 10, 11, 12, 13, 14, 15],
#        [16, 17, 18, 19, 20, 21, 22, 23],
#        [24, 25, 26, 27, 28, 29, 30, 31],
#        [32, 33, 34, 35, 36, 37, 38, 39],
#        [40, 41, 42, 43, 44, 45, 46, 47],
#        [48, 49, 50, 51, 52, 53, 54, 55],
#        [56, 57, 58, 59, 60, 61, 62, 63]])
print(a.shape) # (8, 8)

And the same thing goes for converting a 173056*1 array to a 416*416 one.

Maybe you are confused with the fact that you can use reshape method on a 2-D array. Of course you can!


问:
Merging 2 arrays of same primary IDs
I want to merge these 2 arrays that have the same id (box_id)

```<code>const boxes = [
  { box_id: 1, box_name: "Box 1" },
  { box_id: 2, box_name: "Box 2" },
];

const box_settings = [
  { box_id: 1, box_name: "Box 1", box_settings_id: 1, box_number_of_people: 2, box_total_price: 368 },
  { box_id: 1, box_name: "Box 1", box_settings_id: 2, box_number_of_people: 4, box_total_price: 736 },
  { box_id: 2, box_name: "Box 2", box_settings_id: 3, box_number_of_people: 2, box_total_price: 400 },
  { box_id: 2, box_name: "Box 2", box_settings_id: 4, box_number_of_people: 4, box_total_price: 800 },
];
</code>```

Into this:

```<code>[
  {
    box_id: 1,
    box_name: "Box 1",
    box_settings: [
      { box_settings_id: 1, box_number_of_people: 2, box_total_price: 368 },
      { box_settings_id: 2, box_number_of_people: 4, box_total_price: 736 },
    ],
  },
  {
    box_id: 2,
    box_name: "Box 2",
    box_settings: [
      { box_settings_id: 3, box_number_of_people: 2, box_total_price: 400 },
      { box_settings_id: 4, box_number_of_people: 4, box_total_price: 800 },
    ],
  },
];
</code>```

Thanks in advance. These are arrays produced by MySQL query.

答:
You can map it, and inside that apply filter

var box_settings = [ { box_id: 1, box_name: "Box 1", box_settings_id: 1, box_number_of_people: 2, box_total_price: 368 }, { box_id: 1, box_name: "Box 1", box_settings_id: 2, box_number_of_people: 4, box_total_price: 736 }, { box_id: 2, box_name: "Box 2", box_settings_id: 3, box_number_of_people: 2, box_total_price: 400 }, { box_id: 2, box_name: "Box 2", box_settings_id: 4, box_number_of_people: 4, box_total_price: 800 }];
var boxes = [ { box_id: 1, box_name: "Box 1" }, { box_id: 2, box_name: "Box 2" },];

var result = boxes.map(val=>{
 val.box_settings = box_settings.filter(({box_id})=>box_id==val.box_id).map(({box_id, box_name,...rest})=>rest);
 return val
});
console.log(result);```

Title: Merging 2 arrays of same primary IDs

Body:
I want to merge these 2 arrays that have the same id (box_id)

const boxes = [
  { box_id: 1, box_name: "Box 1" },
  { box_id: 2, box_name: "Box 2" },
];

const box_settings = [
  { box_id: 1, box_name: "Box 1", box_settings_id: 1, box_number_of_people: 2, box_total_price: 368 },
  { box_id: 1, box_name: "Box 1", box_settings_id: 2, box_number_of_people: 4, box_total_price: 736 },
  { box_id: 2, box_name: "Box 2", box_settings_id: 3, box_number_of_people: 2, box_total_price: 400 },
  { box_id: 2, box_name: "Box 2", box_settings_id: 4, box_number_of_people: 4, box_total_price: 800 },
];

Into this:

[
  {
    box_id: 1,
    box_name: "Box 1",
    box_settings: [
      { box_settings_id: 1, box_number_of_people: 2, box_total_price: 368 },
      { box_settings_id: 2, box_number_of_people: 4, box_total_price: 736 },
    ],
  },
  {
    box_id: 2,
    box_name: "Box 2",
    box_settings: [
      { box_settings_id: 3, box_number_of_people: 2, box_total_price: 400 },
      { box_settings_id: 4, box_number_of_people: 4, box_total_price: 800 },
    ],
  },
];

Thanks in advance. These are arrays produced by MySQL query.


问:
Can I sort my code using different function in selenium
```<code>driver.Navigate().GoToUrl("http://demoqa.com/sortable");
var numberOne = driver.FindElement(By.XPath("//*[@id='demo-tabpane-  list']/div/div[1]"));
var numberTwo = driver.FindElement(By.XPath("//*[@id='demo-tabpane-list']/div/div[2]"));

var actions = new Actions(driver);
actions
     .ClickAndHold(numberTwo)
     .MoveToElement(numberOneOne)
     .MoveByOffset(0, 10)
     .Release()
     .Perform();
</code>```

IList
This code helps me to change the position the numbers. But now iI want to (upgrade) him.

How I can do same things by using (IList)?

I using the example with sortable numbers from : http://demoqa.com/sortable

答:
It's difficult to understand what you're exactly asking for here. What do you mean by '(upgrade) him'.

I've put together a bit of code that will handle moving a list item to a different position, but using a method that is re-usable:

```<code>    [TestClass]
    public class UnitTest1
    {
        private IWebDriver _driver;

        [TestMethod]
        public void Test1()
        {
            _driver = new ChromeDriver();
            _driver.Navigate().GoToUrl("http://demoqa.com/sortable");

            // Get the list of items (one to six)
            var listItems = _driver.FindElements(By.XPath("//*[@id='demo-tabpane-list']/div/div"));

            // Use a method to specify what item to movem and where
            Sort(listItems, "One", "Three");
            Sort(listItems, "Three", "Six");

            _driver.Dispose();
        }

        private void Sort(ReadOnlyCollection<IWebElement> list, string itemToMove, string itemToReplace)
        {
            var elToMove = list.First(a => a.Text == itemToMove);
            var elToReplace = list.First(a => a.Text == itemToReplace);

            var actions = new Actions(_driver);
            actions
                 .ClickAndHold(elToMove)
                 .MoveToElement(elToReplace)
                 .MoveByOffset(0, 10)
                 .Release()
                 .Perform();
        }
    }
</code>```

Body:
driver.Navigate().GoToUrl("http://demoqa.com/sortable");
var numberOne = driver.FindElement(By.XPath("//*[@id='demo-tabpane-  list']/div/div[1]"));
var numberTwo = driver.FindElement(By.XPath("//*[@id='demo-tabpane-list']/div/div[2]"));

var actions = new Actions(driver);
actions
     .ClickAndHold(numberTwo)
     .MoveToElement(numberOneOne)
     .MoveByOffset(0, 10)
     .Release()
     .Perform();

IList
This code helps me to change the position the numbers. But now iI want to (upgrade) him.

How I can do same things by using (IList)?

I using the example with sortable numbers from : http://demoqa.com/sortable

Body:
It's difficult to understand what you're exactly asking for here. What do you mean by '(upgrade) him'.

I've put together a bit of code that will handle moving a list item to a different position, but using a method that is re-usable:

    [TestClass]
    public class UnitTest1
    {
        private IWebDriver _driver;

        [TestMethod]
        public void Test1()
        {
            _driver = new ChromeDriver();
            _driver.Navigate().GoToUrl("http://demoqa.com/sortable");

            // Get the list of items (one to six)
            var listItems = _driver.FindElements(By.XPath("//*[@id='demo-tabpane-list']/div/div"));

            // Use a method to specify what item to movem and where
            Sort(listItems, "One", "Three");
            Sort(listItems, "Three", "Six");

            _driver.Dispose();
        }

        private void Sort(ReadOnlyCollection<IWebElement> list, string itemToMove, string itemToReplace)
        {
            var elToMove = list.First(a => a.Text == itemToMove);
            var elToReplace = list.First(a => a.Text == itemToReplace);

            var actions = new Actions(_driver);
            actions
                 .ClickAndHold(elToMove)
                 .MoveToElement(elToReplace)
                 .MoveByOffset(0, 10)
                 .Release()
                 .Perform();
        }
    }


问:
Binary serialization protocol
I have a requirement where i need to transfer information through the wire(binary over tcp) between 2 applications. One is in Java and the other in C++. I need a protocol implementation to transfer objects between these 2 applications. The Object classes are present in both the applications (are mapped accordingly). I just need some encoding scheme on one side which retains the Object representation on one side and can be decoded on the other side as a complete Object.

For eg,

C++ class

```<code>class Person
{
   int age;
   string name;
};
</code>```

Java class

```<code>class Person
{
   int age;
   String name;
}
</code>```

C++ encoding

```<code>Person p;
p.age = 20;
p.name = "somename";
char[] arr = SomeProtocolEncoder.encode(p);
socket.send(arr);
</code>```

Java decoding

```<code>byte[] arr = socket.read();
SomeProtocolIntermediateObject object = SomeProtocolDecoder.decode(arr);
Person p = (Person)ReflectionUtil.get(object);
</code>```

The protocol should provide some intermediate object which maintains the object representational state so that using reflection i can get back the object later.

答: Thrift is what you're looking for. You just create a definition of the structs and methods you need to call and it does all of the heavy lifting. It's got binary protocols (optionally with zlib compression or ssl). It'll probably do your taxes but you didn't hear that from me.</p>

ContentLicense: CC BY-SA 3.0

Title: Binary serialization protocol

Body:
I have a requirement where i need to transfer information through the wire(binary over tcp) between 2 applications. One is in Java and the other in C++. I need a protocol implementation to transfer objects between these 2 applications. The Object classes are present in both the applications (are mapped accordingly). I just need some encoding scheme on one side which retains the Object representation on one side and can be decoded on the other side as a complete Object.

For eg,

C++ class

class Person
{
   int age;
   string name;
};

Java class

class Person
{
   int age;
   String name;
}

C++ encoding

Person p;
p.age = 20;
p.name = "somename";
char[] arr = SomeProtocolEncoder.encode(p);
socket.send(arr);

Java decoding

byte[] arr = socket.read();
SomeProtocolIntermediateObject object = SomeProtocolDecoder.decode(arr);
Person p = (Person)ReflectionUtil.get(object);

The protocol should provide some intermediate object which maintains the object representational state so that using reflection i can get back the object later.


问:
validate form then open mail program
Is there away to validate a form in js and if its valid execute a js function?

basiclly it should check if the form is valid then open the default email program with some entries

like so ->

答:
Yes you can

$('#loginform').validate({
    rules: {
        email: {
            required: true,
            email: true,
            maxlength: 30
        },
        password: {
            required: true,
            minlength: 8,
            maxlength: 20,
        }
    },
    submitHandler: function(form) { // for demo
        return false; // for demo
    }
});

$("#submit").click(function() {
    if ($('#loginform').valid()) {
     alert("Open mail program");
    }
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.19.2/jquery.validate.min.js" integrity="sha256-+BEKmIvQ6IsL8sHcvidtDrNOdZO3C9LtFPtF2H0dOHI=" crossorigin="anonymous"></script>

<form id="loginform">
                        <div class="form-group">
                            <input class="form-control form-control-lg" id="email"
                                   name="email" type="text" placeholder="Email" autocomplete="off">
                        </div>
                        <div class="form-group">
                            <input class="form-control form-control-lg" id="password" name="password"
                                   type="password" placeholder="Password">
                        </div>
                        <button type="button" id="submit" class="btn btn-primary btn-lg btn-block">Login </button>
                    </form></code>```

Title: validate form then open mail program

Body:
Yes you can

$('#loginform').validate({
    rules: {
        email: {
            required: true,
            email: true,
            maxlength: 30
        },
        password: {
            required: true,
            minlength: 8,
            maxlength: 20,
        }
    },
    submitHandler: function(form) { // for demo
        return false; // for demo
    }
});

$("#submit").click(function() {
    if ($('#loginform').valid()) {
     alert("Open mail program");
    }
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.19.2/jquery.validate.min.js" integrity="sha256-+BEKmIvQ6IsL8sHcvidtDrNOdZO3C9LtFPtF2H0dOHI=" crossorigin="anonymous"></script>

<form id="loginform">
                        <div class="form-group">
                            <input class="form-control form-control-lg" id="email"
                                   name="email" type="text" placeholder="Email" autocomplete="off">
                        </div>
                        <div class="form-group">
                            <input class="form-control form-control-lg" id="password" name="password"
                                   type="password" placeholder="Password">
                        </div>
                        <button type="button" id="submit" class="btn btn-primary btn-lg btn-block">Login </button>
                    </form>


问:
Virtual Environment for Python on mac error with Google API Client?
I created a virtual environment on my Desktop called project_env. I then installed the Google API Python Client from github (https://github.com/googleapis/google-api-python-client). Then created a Python file called youtube.py with the following code. When I run the file I get "ImportError no module googleapiclient"

```<code>  from googleapiclient.discovery import build

  api_key = "My Key"

  youtube = build('youtube', 'v3', developerKeys=api_key)

  request = youtube.channels().list(
   part='statistics',
  forUsername='livelifetothefull'
  )

 response = request.execute()
  print(response)
</code>```

I'm very new to this, so any help would be much appreciated.

答:
You can try these commands :</p>

```<code>cd project_env
source bin/activate
bin/pip install wheel
bin/pip install google-api-python-client
bin/python -c "from googleapiclient.discovery import build"
</code>```

Body:
I created a virtual environment on my Desktop called project_env. I then installed the Google API Python Client from github (https://github.com/googleapis/google-api-python-client). Then created a Python file called youtube.py with the following code. When I run the file I get "ImportError no module googleapiclient"

  from googleapiclient.discovery import build

  api_key = "My Key"

  youtube = build('youtube', 'v3', developerKeys=api_key)

  request = youtube.channels().list(
   part='statistics',
  forUsername='livelifetothefull'
  )

 response = request.execute()
  print(response)

I'm very new to this, so any help would be much appreciated.

Body:
You can try these commands :

cd project_env
source bin/activate
bin/pip install wheel
bin/pip install google-api-python-client
bin/python -c "from googleapiclient.discovery import build"


问:
Container not starting
I made a docker container of my web application.

At the end of the docker build command, I saw (which I suppose means that image was made)

```<code>Successfully tagged App:30may2020
SECURITY WARNING: You are building a Docker image from Windows against a non-Windows Docker host. All files and directories added to build context will have '-rwxr-xr-x' permissions. It is recommended to double check and reset permissions for sensitive files and directories.
</code>```

When I run the container, I get error

docker run  --publish 9000:9000 --detach --name App App:30may2020

```<code>docker: Error response from daemon: Conflict. The container name "/App" is already in use by container "8a641431369c418e99ccb752161f5f2848d3c8f14bb903a18b6bd4aff2966af6". You have to remove (or rename) that container to be able to reuse that name.
</code>```

Question 1 - Does build command also starts the container as I didn't start the container?
Question 2 - I did docker container ls  and docker container ps but I don't see my container running. Then why do I get the error?

答:
Answers to your questions:

Question 1 - Does build command also starts the container as I didn't start the container?

Answer => No, but the command which you mentioned is a run command which will start the container.

```<code>docker run  --publish 9000:9000 --detach --name App App:30may2020
</code>```

As you can see, docker run will start the container from the image App:30may2020.

Question 2 - I did docker container ls and docker container ps but I don't see my container running. Then why do I get the error?

Answer2 => As the error says, App container name is already used by another container. There are below 2 ways to solve this

Run docker rm App, which will remove the container named App and if you want to see this container running run docker ps -a, and you would be able to see the container.

Note:- If you encounter an error while deleting the container, please stop the container first by running docker stop App.

The second way, don't give --name option while running the container and let docker choose the random name.

Title: Container not starting

Body:
I made a docker container of my web application.

At the end of the docker build command, I saw (which I suppose means that image was made)

Successfully tagged App:30may2020
SECURITY WARNING: You are building a Docker image from Windows against a non-Windows Docker host. All files and directories added to build context will have '-rwxr-xr-x' permissions. It is recommended to double check and reset permissions for sensitive files and directories.

When I run the container, I get error

docker run  --publish 9000:9000 --detach --name App App:30may2020

docker: Error response from daemon: Conflict. The container name "/App" is already in use by container "8a641431369c418e99ccb752161f5f2848d3c8f14bb903a18b6bd4aff2966af6". You have to remove (or rename) that container to be able to reuse that name.

Question 1 - Does build command also starts the container as I didn't start the container?
Question 2 - I did docker container ls  and docker container ps but I don't see my container running. Then why do I get the error?

Body:
Answers to your questions:

Question 1 - Does build command also starts the container as I didn't start the container?

Answer => No, but the command which you mentioned is a run command which will start the container.

docker run  --publish 9000:9000 --detach --name App App:30may2020

As you can see, docker run will start the container from the image App:30may2020.

Question 2 - I did docker container ls and docker container ps but I don't see my container running. Then why do I get the error?

Answer2 => As the error says, App container name is already used by another container. There are below 2 ways to solve this

Run docker rm App, which will remove the container named App and if you want to see this container running run docker ps -a, and you would be able to see the container.

Note:- If you encounter an error while deleting the container, please stop the container first by running docker stop App.

The second way, don't give --name option while running the container and let docker choose the random name.


答:
you can use map to return expected array object

const boxes = [
  { box_id: 1, box_name: "Box 1" },
  { box_id: 2, box_name: "Box 2" },
];
const box_settings = [
  { box_id: 1, box_name: "Box 1", box_settings_id: 1, box_number_of_people: 2, box_total_price: 368 },
  { box_id: 1, box_name: "Box 1", box_settings_id: 2, box_number_of_people: 4, box_total_price: 736 },
  { box_id: 2, box_name: "Box 2", box_settings_id: 3, box_number_of_people: 2, box_total_price: 400 },
  { box_id: 2, box_name: "Box 2", box_settings_id: 4, box_number_of_people: 4, box_total_price: 800 },
];

var result=boxes.map(x=>{
  return {
    box_id:x.box_id,
    box_name:x.box_name ,
    box_settings:(box_settings.filter(y=>y.box_id==x.box_id))
    .map(a=> {
      return{
         box_settings_id:a.box_settings_id ,
         box_number_of_people:a.box_number_of_people,
         box_total_price:a.box_total_price
       }
    })
  }
})
console.log(result);```

Title: Merging 2 arrays of same primary IDs


问:
mysql return multiple results with group by
Please note this is regarding a homework problem, the homework is done and works to the spec, but it's slow so I'm trying to lessen how many SQL calls I make. And I'm still learning my SQL-fu.

My table looks like:

```<code>Ticker |Name                  |Industry
A      |Agilent Technologies  |Information Technology
AA     |Alcoa Inc             |Materials
AAPL   |Apple Inc.            |Information Technology
</code>```

Right now I am running a SQL statement like this in a loop. Each iteration I change which industry to look at.

```<code>SELECT ticker FROM company WHERE industry = 'Information Technology'
</code>```

But that means I have to make a call to the database for each industry just to get the tickers related to it. What I want is to make one database call that returns multiple results. So the first result would be a list of all the tickers for the first industry, the second result would be all the tickers for the second industry etc.

I tried this SQL, but it just gave me one ticker for each industry, not a full list

```<code>SELECT ticker, industry FROM company GROUP BY industry
</code>```

答:
Unfortunately, you are probably doing it the best way if you need to have separate result sets for each industry.  However, if you want to do a little manipulation in your code, you could return the entire table ordered by the industry then the ticker.  Then in your code you could read until the industry changed and then do whatever magic you want and then read again until the industry changed again.  Basically, do your loop on the result set instead of using your loop to make database calls.  If you did it this way, your query would look like this:

```<code>SELECT ticker
FROM company
ORDER BY Industry, Ticker
</code>```

You would make one call to the database and do your looping through the results in your code (or wherever you are working on your data).

Body:
Please note this is regarding a homework problem, the homework is done and works to the spec, but it's slow so I'm trying to lessen how many SQL calls I make. And I'm still learning my SQL-fu.

My table looks like:

Ticker |Name                  |Industry
A      |Agilent Technologies  |Information Technology
AA     |Alcoa Inc             |Materials
AAPL   |Apple Inc.            |Information Technology

Right now I am running a SQL statement like this in a loop. Each iteration I change which industry to look at.

SELECT ticker FROM company WHERE industry = 'Information Technology'

But that means I have to make a call to the database for each industry just to get the tickers related to it. What I want is to make one database call that returns multiple results. So the first result would be a list of all the tickers for the first industry, the second result would be all the tickers for the second industry etc.

I tried this SQL, but it just gave me one ticker for each industry, not a full list

SELECT ticker, industry FROM company GROUP BY industry

Body:
Unfortunately, you are probably doing it the best way if you need to have separate result sets for each industry.  However, if you want to do a little manipulation in your code, you could return the entire table ordered by the industry then the ticker.  Then in your code you could read until the industry changed and then do whatever magic you want and then read again until the industry changed again.  Basically, do your loop on the result set instead of using your loop to make database calls.  If you did it this way, your query would look like this:

SELECT ticker
FROM company
ORDER BY Industry, Ticker

You would make one call to the database and do your looping through the results in your code (or wherever you are working on your data).


问:
glGetShaderInfoLog with string
I'm am doing a shader class which have a method returning shader's logs:

```<code>std::string Shader::GetShaderInfoLog(){
    GLint TotalLenght=0;
    GetShaderiv(GL_INFO_LOG_LENGTH,&TotalLenght);
    std::string logs;
    logs.reserve(TotalLenght);
    glGetShaderInfoLog(name, TotalLenght, NULL, &logs[0] );
    return logs;
}
</code>```

For strange reason, logs string is empty even with a shader which have compilation error.
I have tried with a char array :

```<code>std::string Shader::GetShaderInfoLog(){
    GLint TotalLenght=0;
    GetShaderiv(GL_INFO_LOG_LENGTH,&TotalLenght);
    char logs[TotalLenght];
    glGetShaderInfoLog(name, TotalLenght, NULL, logs);
    return std::string(logs);
}
</code>```

And this one work well. So my question is why it don't work with a string ?

答:
reserve just increases the capacity of the string. But does not change it's size.

You need to resize it:

```<code>std::string Shader::GetShaderInfoLog(){
    GLint TotalLenght=0;
    GetShaderiv(GL_INFO_LOG_LENGTH,&TotalLenght);
    std::string logs;
    logs.resize(TotalLenght);
    glGetShaderInfoLog(name, TotalLenght, NULL, &logs[0] );
    return logs;
}
</code>```

Title: glGetShaderInfoLog with string

Body:
I'm am doing a shader class which have a method returning shader's logs:

std::string Shader::GetShaderInfoLog(){
    GLint TotalLenght=0;
    GetShaderiv(GL_INFO_LOG_LENGTH,&TotalLenght);
    std::string logs;
    logs.reserve(TotalLenght);
    glGetShaderInfoLog(name, TotalLenght, NULL, &logs[0] );
    return logs;
}

For strange reason, logs string is empty even with a shader which have compilation error.
I have tried with a char array :

std::string Shader::GetShaderInfoLog(){
    GLint TotalLenght=0;
    GetShaderiv(GL_INFO_LOG_LENGTH,&TotalLenght);
    char logs[TotalLenght];
    glGetShaderInfoLog(name, TotalLenght, NULL, logs);
    return std::string(logs);
}

And this one work well. So my question is why it don't work with a string ?

Body:
reserve just increases the capacity of the string. But does not change it's size.

You need to resize it:

std::string Shader::GetShaderInfoLog(){
    GLint TotalLenght=0;
    GetShaderiv(GL_INFO_LOG_LENGTH,&TotalLenght);
    std::string logs;
    logs.resize(TotalLenght);
    glGetShaderInfoLog(name, TotalLenght, NULL, &logs[0] );
    return logs;
}


问:
Okhttp Interceptor issue
I'm trying to add a header to a simple okhttp (Get) request. How do I add the HttpHeader properly? Can I debug to ensure that my Header is actually sent to the server? </p>

```<code>        Request request = new Request.Builder()
                .url("URL")
                .build();

        OkHttpClient okHttpClient = new OkHttpClient.Builder()
                .addInterceptor(new Interceptor() {
                    @Override
                    public okhttp3.Response intercept(Chain chain) throws IOException {
                        Request originalRequest = chain.request();
                        Request newRequest = originalRequest.newBuilder()
                                .addHeader("Header", "123")
                                .build();
                        return chain.proceed(newRequest);
                    }
                })
                .build();

        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
             }
</code>```

<p>I've looked for basic simple examples but they are with Retrofit, GSON, Interfaces, or in Kotlin. Need to understand it codewise. </p>

答:
Use addHeader() to add headers. header() sets the already added header name to the value.

```<code>Request newRequest = originalRequest.newBuilder()
    .addHeader("Header", "123")
    .build();
</code>```

And to verify it's working correctly, you can use HttpLoggingInterceptor to log your network requests.

Title: Okhttp Interceptor issue

Body:
I'm trying to add a header to a simple okhttp (Get) request. How do I add the HttpHeader properly? Can I debug to ensure that my Header is actually sent to the server?

        Request request = new Request.Builder()
                .url("URL")
                .build();

        OkHttpClient okHttpClient = new OkHttpClient.Builder()
                .addInterceptor(new Interceptor() {
                    @Override
                    public okhttp3.Response intercept(Chain chain) throws IOException {
                        Request originalRequest = chain.request();
                        Request newRequest = originalRequest.newBuilder()
                                .addHeader("Header", "123")
                                .build();
                        return chain.proceed(newRequest);
                    }
                })
                .build();

        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
             }

I've looked for basic simple examples but they are with Retrofit, GSON, Interfaces, or in Kotlin. Need to understand it codewise.

Body:
Use addHeader() to add headers. header() sets the already added header name to the value.

Request newRequest = originalRequest.newBuilder()
    .addHeader("Header", "123")
    .build();

And to verify it's working correctly, you can use HttpLoggingInterceptor to log your network requests.


问:
I want to delete a row in my database with the @Html.ActionLink Delete but its not working. What am I doing wrong?
It can write out the cv.name, it also connects to the database. But I'm doing something wrong with a delete action.

cshtml:

```<code><body>
@{
    foreach( var cv in Model.GetCVs( username))
    {
        <h3 style="color: #193367; "><b> Name: @cv.name</b></h3>     // this works
        <form action="" method="post">
            <input type="submit" name="name" value="@cv.name" />     // this works
        </form>
        @Html.ActionLink("Delete","Delete",new{ id = @cv.id})        // this does not work
    }
}
</body>
</code>```

The markup above is in my cshtml file and the most of it is working all right.

cshtml.cs:

```<code>[BindProperty]
public int id { get; set; }

public const string vv = "Data Source=Tables.sqlite3";

public static SqliteConnection Connection = new SqliteConnection(vv);

static AboutModel()
{
    Connection.Open();
}

public struct CV
{
    public string name;
    public int id;
}

public ActionResult Delete(int? id)
{
    using (var cmd = Connection.CreateCommand())
    {
        cmd.CommandText = "Delete from MyTable1 where id = @id;";
        return RedirectToPage("About");
    }
}
</code>```

This is the code in my cshtml.cs and the Delete method is not working. I don't know how to properly use this delete action. I don't want that it asks back that are you sure want to delete it? I just want that if the user click on the delete button, it should delete that row in a table.

答:
You have two problems. First, you need to add a parameter to your command to correspond to the @id in the command text. Second, and more importantly, you need to actually execute the command. Right now you are just creating a new DbCommand, assigning the CommandText property and then discarding it.

```<code>public ActionResult Delete(int? id)
{
    // handle bad request (id is null) somehow
    if(!ModelState.IsValid)
        return View();

    using (var cmd = Connection.CreateCommand())
    {
        cmd.CommandText = "Delete from MyTable1 where id = @id";

        // set command type Text (or StoredProcedure)
        // Text is the default so not strictly necessary
        cmd.CommandType = CommandType.Text;

        // create new parameter
        var para = cmd.CreateParameter();
        para.Value = id.Value;
        para.ParameterName = "@id";
        para.DbType = DbType.Int32;

        // add parameter to command
        cmd.Parameters.Add(para);

        // need to make sure connection is open
        if (Connection.State == ConnectionState.Closed || Connection.State == ConnectionState.Broken)
            Connection.Open();

        // execute command
        cmd.ExecuteNonQuery();
    }

    return RedirectToPage("About");
}
</code>```

Side note: you really shouldn't hold your connection object in a static field or property. You should create, open, close/dispose as close as possible to where/when the connection is actually needed. Since this is a web application, you are going to get yourself into trouble if you do it this way.

```<code>public ActionResult Delete(int? id)
{
    // handle bad request (id is null) somehow
    if(!ModelState.IsValid)
        return View();

    // create connection when we need it
    using (var conn = new SqliteConnection(vv))
    using (var cmd = conn.CreateCommand())
    {
        cmd.CommandText = "Delete from MyTable1 where id = @id";

        // set command type Text (or StoredProcedure)
        // Text is the default so not strictly necessary
        cmd.CommandType = CommandType.Text;

        // create new parameter
        var para = cmd.CreateParameter();
        para.Value = id.Value;
        para.ParameterName = "@id";
        para.DbType = DbType.Int32;

        // add parameter to command
        cmd.Parameters.Add(para);

        // open the connection
        conn.Open();

        // execute command
        cmd.ExecuteNonQuery();
    }

    return RedirectToPage("About");
}
</code>```

Body:
It can write out the cv.name, it also connects to the database. But I'm doing something wrong with a delete action.

cshtml:

@{
    foreach( var cv in Model.GetCVs( username))
    {

 Name: @cv.name
     // this works
        <form action="" method="post">
            <input type="submit" name="name" value="@cv.name" />     // this works
        </form>
        @Html.ActionLink("Delete","Delete",new{ id = @cv.id})        // this does not work
    }
}

The markup above is in my cshtml file and the most of it is working all right.

cshtml.cs:

[BindProperty]
public int id { get; set; }

public const string vv = "Data Source=Tables.sqlite3";

public static SqliteConnection Connection = new SqliteConnection(vv);

static AboutModel()
{
    Connection.Open();
}

public struct CV
{
    public string name;
    public int id;
}

public ActionResult Delete(int? id)
{
    using (var cmd = Connection.CreateCommand())
    {
        cmd.CommandText = "Delete from MyTable1 where id = @id;";
        return RedirectToPage("About");
    }
}

This is the code in my cshtml.cs and the Delete method is not working. I don't know how to properly use this delete action. I don't want that it asks back that are you sure want to delete it? I just want that if the user click on the delete button, it should delete that row in a table.

Body:
You have two problems. First, you need to add a parameter to your command to correspond to the @id in the command text. Second, and more importantly, you need to actually execute the command. Right now you are just creating a new DbCommand, assigning the CommandText property and then discarding it.

public ActionResult Delete(int? id)
{
    // handle bad request (id is null) somehow
    if(!ModelState.IsValid)
        return View();

    using (var cmd = Connection.CreateCommand())
    {
        cmd.CommandText = "Delete from MyTable1 where id = @id";

        // set command type Text (or StoredProcedure)
        // Text is the default so not strictly necessary
        cmd.CommandType = CommandType.Text;

        // create new parameter
        var para = cmd.CreateParameter();
        para.Value = id.Value;
        para.ParameterName = "@id";
        para.DbType = DbType.Int32;

        // add parameter to command
        cmd.Parameters.Add(para);

        // need to make sure connection is open
        if (Connection.State == ConnectionState.Closed || Connection.State == ConnectionState.Broken)
            Connection.Open();

        // execute command
        cmd.ExecuteNonQuery();
    }

    return RedirectToPage("About");
}

Side note: you really shouldn't hold your connection object in a static field or property. You should create, open, close/dispose as close as possible to where/when the connection is actually needed. Since this is a web application, you are going to get yourself into trouble if you do it this way.

public ActionResult Delete(int? id)
{
    // handle bad request (id is null) somehow
    if(!ModelState.IsValid)
        return View();

    // create connection when we need it
    using (var conn = new SqliteConnection(vv))
    using (var cmd = conn.CreateCommand())
    {
        cmd.CommandText = "Delete from MyTable1 where id = @id";

        // set command type Text (or StoredProcedure)
        // Text is the default so not strictly necessary
        cmd.CommandType = CommandType.Text;

        // create new parameter
        var para = cmd.CreateParameter();
        para.Value = id.Value;
        para.ParameterName = "@id";
        para.DbType = DbType.Int32;

        // add parameter to command
        cmd.Parameters.Add(para);

        // open the connection
        conn.Open();

        // execute command
        cmd.ExecuteNonQuery();
    }

    return RedirectToPage("About");
}


问:
pandas-like resampling with week frequency in DolphinDB
pandas supports resampling with many kinds of frequencies. To implement a pandas-like resampling in DolphinDB, I could use a group-by clause with the group-by column being a function call on a temporal column. For example, to resample with month frequency, I can write a SQL like this:

```<code>select count(*) from t group by month(myDate)
</code>```

Things are a little different when it comes to the week frequency because DolphinDB has no functions like week. In addition, I'd like to resample by a specific day in a week, say, Tuesday.

答:
"W" indicates week frequency:

```<code>orca_dataframe.resample("W", on="myDate").count()
</code>```

To resample every Tuesday of week:

```<code>orca_dataframe.resample("W-TUE", on="myDate").count()
</code>```

Body:
pandas supports resampling with many kinds of frequencies. To implement a pandas-like resampling in DolphinDB, I could use a group-by clause with the group-by column being a function call on a temporal column. For example, to resample with month frequency, I can write a SQL like this:

select count(*) from t group by month(myDate)

Things are a little different when it comes to the week frequency because DolphinDB has no functions like week. In addition, I'd like to resample by a specific day in a week, say, Tuesday.

Body:
"W" indicates week frequency:

orca_dataframe.resample("W", on="myDate").count()

To resample every Tuesday of week:

orca_dataframe.resample("W-TUE", on="myDate").count()


问:
Iterate over list with indices in vavr
I'm using collections from vavr library.
I have a list of elements defined like this:

```<code>List<Integer> integers = List.of(1, 2, 3);
</code>```

How to iterate over elements of the list and have an access to the indices at the same time? In Groovy there is a method eachWithIndex. I'm looking for something similar in vavr. I'd like to use it like this:

```<code>integers.eachWithIndex((int element, int index) -> {
     System.out.println("index = " + index + " element = " + element);
})
</code>```

How can I achieve this in vavr?

答:
JMPL is simple java library, which could emulate some of the features pattern matching, using Java 8 features.
   This library also support simple iterate over collection.</p>

```<code>   Figure figure = new Rectangle();

   foreach(listRectangles, (int w, int h) -> {
      System.out.println("square: " + (w * h));
   });
</code>```

Title: Iterate over list with indices in vavr

Body:
I'm using collections from vavr library.
I have a list of elements defined like this:

List<Integer> integers = List.of(1, 2, 3);

How to iterate over elements of the list and have an access to the indices at the same time? In Groovy there is a method eachWithIndex. I'm looking for something similar in vavr. I'd like to use it like this:

integers.eachWithIndex((int element, int index) -> {
     System.out.println("index = " + index + " element = " + element);
})

How can I achieve this in vavr?

Body:
JMPL is simple java library, which could emulate some of the features pattern matching, using Java 8 features.
   This library also support simple iterate over collection.

   Figure figure = new Rectangle();

   foreach(listRectangles, (int w, int h) -> {
      System.out.println("square: " + (w * h));
   });


问:
Call a function when the content inside a div is changed?
I have a page, on the left there is a list of links users can click, when they are clicked, a div on the right side will load the correct content via Ajax according to the link.

Now I want to fire a function when the right side div's content changed every time.

After a search in Stack Overflow, I learn that there are Mutation Events, I use the DOMSubtreeModified event:

```<code>right_div.addEventListener("DOMSubtreeModified", handler, false);
</code>```

However, when I click the link on the left side, it seems that handler will be called several time.  I want it be called only once when the new contents of it has been loaded. How could I do this?

答:
The DOMSubtreeModified is "a general event for notification of all changes to the document". You can set mutation events for specific mutations:

DOMAttrModified event

DOMCharacterDataModified event

DOMNodeInserted event

DOMNodeInsertedIntoDocument event

DOMNodeRemoved event

DOMNodeRemovedFromDocument event

And there are the following types:

DOMElementNameChanged

DOMAttributeNameChanged

So if you are replacing a node, it might cause two (or more) mutation events - one when the node is removed, another when it is replaced. Futher events may also be dispatched, such as character data modified. if you are listening for an event only when the text content is changed, try the DOMCharacterDataModified event:

A user agent must dispatch this event
  after CharacterData.data or
  ProcessingInstruction.data have been
  modified, but the node itself has not
  been inserted or deleted. The proximal
  event target of this event must be the
  CharacterData node or the
  ProcessingInstruction node.

Body:
I have a page, on the left there is a list of links users can click, when they are clicked, a div on the right side will load the correct content via Ajax according to the link.

Now I want to fire a function when the right side div's content changed every time.

After a search in Stack Overflow, I learn that there are Mutation Events, I use the DOMSubtreeModified event:

right_div.addEventListener("DOMSubtreeModified", handler, false);

However, when I click the link on the left side, it seems that handler will be called several time.  I want it be called only once when the new contents of it has been loaded. How could I do this?


问:
How to retrieve all the document(contain image url & name) from cloud firestore database to website?
I am trying to retrieve user Image and name from cloud firestore database to website. The image and name retrieval work good and the user image and name is appearing on the website screen. But the problem is that it is only fetching only Singal document which contain user Image and name .  I have more document uploaded in the cloud firestore database which also contain different  user Image and name. Pls see the Picture linked below.

Q1: How to fetch all the document which contain user Image and name

Q2: Why it is fetching only singal document?

Js code:

```<code>const list_div= document.querySelector('#list_div');
db.collection('student entry').get().then(function(querySnapshot){
querySnapshot.forEach(function(doc){
  list_div.innerHTML="<div class='col-sm-4 mt-2 mb-1'>"+
"<div class='card'>"+
"<img src='"+doc.data().image+"' style='height:250px;'>"+
"<div class='card-body'><p class='card-text'>"+doc.data().fname+"</p></div></div>"

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

Html code:

```<code><html>
    <head>
        <title>Blogs</title>
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
    </head>
    <body>

        <div class="main-list" id="list_div">
            <div class="list-item">

            </div>
        </div>

<!-- The core Firebase JS SDK is always required and must be listed first...make sure you remove -app from below line -->
<script src="https://www.gstatic.com/firebasejs/7.14.2/firebase.js"></script>

<script>
    // Initialize Firebase
    var config = {
        apiKey: " ",
        authDomain: " ",
       databaseURL: " ",
       projectId: " ",
       storageBucket: " ",
      messagingSenderId: " ",
      appId: " ",
      measurementId: " "
    };
    firebase.initializeApp(config);
    var db = firebase.firestore();
    db.settings({ timestampsInSnapshots: true });
</script>

        <script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script>
        <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script>
        <script src="defualt.js"></script>
    </body>
</html>
</code>```

答:
You're reading and processing all documents from the collection. The only problem is that you're constantly setting the inner HTML of list_div instead of adding to it.

So the solution is to append the new element to the existing contents of list_div:

```<code>const list_div= document.querySelector('#list_div');
db.collection('student entry').get().then(function(querySnapshot){
  list_div.innerHTML = "";
  querySnapshot.forEach(function(doc){
    list_div.innerHTML += "<div class='col-sm-4 mt-2 mb-1'>"+
      "<div class='card'>"+
      "<img src='"+doc.data().image+"' style='height:250px;'>"+
      "<div class='card-body'><p class='card-text'>"+doc.data().fname+"</p></div></div>"
  });
});
</code>```

Aside from some formatting the big change is the addition of a + in list_div.innerHTML += ..., and (as a consequence) clearing the inner HTML before the loop.

Body:
I am trying to retrieve user Image and name from cloud firestore database to website. The image and name retrieval work good and the user image and name is appearing on the website screen. But the problem is that it is only fetching only Singal document which contain user Image and name .  I have more document uploaded in the cloud firestore database which also contain different  user Image and name. Pls see the Picture linked below.

Q1: How to fetch all the document which contain user Image and name

Q2: Why it is fetching only singal document?

Js code:

const list_div= document.querySelector('#list_div');
db.collection('student entry').get().then(function(querySnapshot){
querySnapshot.forEach(function(doc){
  list_div.innerHTML="
"+
"
"+
""+
"

"+doc.data().fname+"

"

});
});

Html code:

        <title>Blogs</title>
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">

Body:
You're reading and processing all documents from the collection. The only problem is that you're constantly setting the inner HTML of list_div instead of adding to it.

So the solution is to append the new element to the existing contents of list_div:

const list_div= document.querySelector('#list_div');
db.collection('student entry').get().then(function(querySnapshot){
  list_div.innerHTML = "";
  querySnapshot.forEach(function(doc){
    list_div.innerHTML += "<div class='col-sm-4 mt-2 mb-1'>"+
      "<div class='card'>"+
      "<img src='"+doc.data().image+"' style='height:250px;'>"+
      "<div class='card-body'><p class='card-text'>"+doc.data().fname+"</p></div></div>"
  });
});

Aside from some formatting the big change is the addition of a + in list_div.innerHTML += ..., and (as a consequence) clearing the inner HTML before the loop.


问:
Java function to detect valid webpage
I am trying to write a Java program that will load pages pointed to by valid links and report other links as broken. My problem is that the Java URL will download the appropriate page if the url is valid, and the search-engine results for the url if the url is invalid.

Is there a Java function that detects if the url resolves to a legitimate page . . . thanks very much,

Joel

答:
You can get the HTTP response code for a URL like so:

```<code>public static int getResponseCode(URL url) throws IOException {
  URLConnection conn = url.openConnection();
  if (!(conn instanceof HttpURLConnection)) {
    throw new IllegalArgumentException("not an HTTP url: " + url);
  }
  HttpURLConnection httpConn = (HttpURLConnection) conn;
  return httpConn.getResponseCode();
}
</code>```

Now the question is, what do you consider a "valid" webpage?  For me, if a URL parses correctly and it's protocol is "http" (or https) and it's response code is in the 200 block or 302 (Found/Redirect) or 304 (Not modified), then it's valid:

```<code>public boolean isValidHttpResponseCode(int code) {
    return ((code / 100) == 2) || (code == 302) || (code == 304);
}
</code>```

Title: Java function to detect valid webpage

Body:
You can get the HTTP response code for a URL like so:

public static int getResponseCode(URL url) throws IOException {
  URLConnection conn = url.openConnection();
  if (!(conn instanceof HttpURLConnection)) {
    throw new IllegalArgumentException("not an HTTP url: " + url);
  }
  HttpURLConnection httpConn = (HttpURLConnection) conn;
  return httpConn.getResponseCode();
}

Now the question is, what do you consider a "valid" webpage?  For me, if a URL parses correctly and it's protocol is "http" (or https) and it's response code is in the 200 block or 302 (Found/Redirect) or 304 (Not modified), then it's valid:

public boolean isValidHttpResponseCode(int code) {
    return ((code / 100) == 2) || (code == 302) || (code == 304);
}


问:
Numpy dot product along specific axes
I have a 512x512 image array and I want to perform operations on 8x8 blocks. At the moment I have something like this:

```<code>output = np.zeros(512, 512)

for i in range(0, 512, 8):
    for j in rangerange(0, 512, 8):
        a = input[i:i+8, j:j+8]
        b = some_other_array[i:i+8, j:j+8]
        output[i:i+8, j:j+8] = np.dot(a, b)
</code>```

where a & b are 8x8 blocks derived from the original array. I would like to speed up this code by using vectorised operations. I have reshaped my inputs like this:

```<code>input = input.reshape(64, 8, 64, 8)
some_other_array = some_other_array.reshape(64, 8, 64, 8)
</code>```

How could I perform a dot product on only axes 1 & 3 to output an array of shape (64, 8, 64, 8)?

I have tried np.tensordot(input, some_other_array, axes=([0, 1], [2, 3])) which gives the correct output shape, but the values do not match the output from the loop above. I've also looked at np.einsum but I haven't come across a simple example with what I'm trying to achieve.

答:
As you suspected, np.einsum can take care of this. If input and some_other_array have shapes (64, 8, 64, 8), then if you write

```<code>output = np.einsum('ijkl,ilkm->ijkm', input, some_other_array)
</code>```

then output will also have shape (64, 8, 64, 8), where matrix multiplication (i.e. np.dot) has been done only on axes 1 and 3.

The string argument to np.einsum looks complicated, but really it's a combination of two things. First, matrix multiplication is given by jl,lm->jm (see e.g. this answer on einsum). Second, we don't want to do anything to axis 0 and 2, so for them I just write ik,ik->ik. Combining the two gives ijkl,ilkm->ijkm.

Title: Numpy dot product along specific axes

Body:
I have a 512x512 image array and I want to perform operations on 8x8 blocks. At the moment I have something like this:

output = np.zeros(512, 512)

for i in range(0, 512, 8):
    for j in rangerange(0, 512, 8):
        a = input[i:i+8, j:j+8]
        b = some_other_array[i:i+8, j:j+8]
        output[i:i+8, j:j+8] = np.dot(a, b)

where a & b are 8x8 blocks derived from the original array. I would like to speed up this code by using vectorised operations. I have reshaped my inputs like this:

input = input.reshape(64, 8, 64, 8)
some_other_array = some_other_array.reshape(64, 8, 64, 8)

How could I perform a dot product on only axes 1 & 3 to output an array of shape (64, 8, 64, 8)?

I have tried np.tensordot(input, some_other_array, axes=([0, 1], [2, 3])) which gives the correct output shape, but the values do not match the output from the loop above. I've also looked at np.einsum but I haven't come across a simple example with what I'm trying to achieve.

Body:
As you suspected, np.einsum can take care of this. If input and some_other_array have shapes (64, 8, 64, 8), then if you write

output = np.einsum('ijkl,ilkm->ijkm', input, some_other_array)

then output will also have shape (64, 8, 64, 8), where matrix multiplication (i.e. np.dot) has been done only on axes 1 and 3.

The string argument to np.einsum looks complicated, but really it's a combination of two things. First, matrix multiplication is given by jl,lm->jm (see e.g. this answer on einsum). Second, we don't want to do anything to axis 0 and 2, so for them I just write ik,ik->ik. Combining the two gives ijkl,ilkm->ijkm.


问:
Axios in Nuxt.js is not catch error properly
As I mentioned above my Axios on Nuxt.js is not catch error properly

I need to know the error, so I can prompt to let the user know their input is not correct but it only console.log the error code status not the message from my API

this is my code

```<code>await axios
  .post(
    "API LINK",
    {
      email: user.email,
      password: "123456",
      name: user.name,
      dob: user.dob ?? null,
      gender: user.gender ?? null,
      profileImage: imageUrl ?? user.profileImage,
      userType: user.userType
    }
  )
  .then(res => {
    console.log("success");
    console.log(res);
  })
  .catch(err => {
    console.log('fail');
    console.log(err)
  })
</code>```

This is what log on a chrome console

```<code>error
add.vue?104b:181 Error: Request failed with status code 400
    at createError (createError.js?2d83:16)
    at settle (settle.js?467f:17)
    at XMLHttpRequest.handleLoad (xhr.js?b50d:61)
</code>```

But what I expect from the console.log(err) is

```<code>(This is response from postman)
{
    "message": "Error creating new user.",
    "error": {
        "code": "auth/invalid-password",
        "message": "The password must be a string with at least 6 characters."
    }
}
</code>```

I have no idea what is happening.

答:
Try this

```<code> console.log(err.response)
</code>```

To make the code cleaner you can destructure the argument:

```<code>  .catch(({ response }) => {
    console.log('fail');
    console.log(response)
  })
</code>```

If you want to use some other property name instead of response you can do it like this:

```<code>  .catch(({ response: err }) => {
    console.log('fail');
    console.log(err)
  })
</code>```

The problem is when the console.log tries to output the error, the string representation is printed, not the object structure, so you do not see the .response property.

Here you can read about https://github.com/axios/axios/issues/960

Body:
As I mentioned above my Axios on Nuxt.js is not catch error properly

I need to know the error, so I can prompt to let the user know their input is not correct but it only console.log the error code status not the message from my API

this is my code

await axios
  .post(
    "API LINK",
    {
      email: user.email,
      password: "123456",
      name: user.name,
      dob: user.dob ?? null,
      gender: user.gender ?? null,
      profileImage: imageUrl ?? user.profileImage,
      userType: user.userType
    }
  )
  .then(res => {
    console.log("success");
    console.log(res);
  })
  .catch(err => {
    console.log('fail');
    console.log(err)
  })

This is what log on a chrome console

error
add.vue?104b:181 Error: Request failed with status code 400
    at createError (createError.js?2d83:16)
    at settle (settle.js?467f:17)
    at XMLHttpRequest.handleLoad (xhr.js?b50d:61)

But what I expect from the console.log(err) is

(This is response from postman)
{
    "message": "Error creating new user.",
    "error": {
        "code": "auth/invalid-password",
        "message": "The password must be a string with at least 6 characters."
    }
}

I have no idea what is happening.

Body:
Try this

 console.log(err.response)

To make the code cleaner you can destructure the argument:

  .catch(({ response }) => {
    console.log('fail');
    console.log(response)
  })

If you want to use some other property name instead of response you can do it like this:

  .catch(({ response: err }) => {
    console.log('fail');
    console.log(err)
  })

The problem is when the console.log tries to output the error, the string representation is printed, not the object structure, so you do not see the .response property.

Here you can read about https://github.com/axios/axios/issues/960


问:
Interested in making a PHP script that increments IP address from defined starting address to defined ending address
I know I can do this easily by converting the IP addresses to decimal notation first using PHP built in functions like up2long and long2ip. I just want to be able to do the same using the standard IP address notation as an exercise.

The problem I am thinking goes like this: Given an starting IP address, say 192.168.1.100, and an ending IP address, say 201.130.22.10. Make the program that prints all the address numbers in that range (192.168.1.100, 192.168.1.101, … , 201.130.22.9, 201.130.22.10).

I was thinking that maybe the way to go would be to make a nested for loop inside a while condition until the first octet of the starting address matches the first octet of the ending address. Then execute the same block of code for the second octet and so on until the program reaches the ending address and finished.

I just started learning to program recently so it is quite possible that my of thinking and or writing code is far from elegant. If you were to this, how would you do it?

答:
Increment (Add to):

```<code><?php

function ipinc($i): string {
    $i = explode(".", $i);

    $a = $i[0];
    $b = $i[1];
    $c = $i[2];
    $d = $i[3];

    $d++;

    if ($d > 255) {
        $d = 0;
        $c++;
    }

    if ($c > 255) {
        $c = 0;
        $b++;
    }

    if ($b > 255) {
        $b = 0;
        $a++;
    }

    if ($a > 255) {
        die("IPv4 Range Exceeded");
    }

    return "$a.$b.$c.$d";
}

?>
</code>```

Decrement (Take from):

```<code><?php

function ipdec($i) {
    $i = explode(".", $i);

    $a = $i[0];
    $b = $i[1];
    $c = $i[2];
    $d = $i[3];

    $d--;

    if ($d < 0) {
        $d = 255;
        $c--;
    }

    if ($c < 0) {
        $c = 255;
        $b--;
    }

    if ($b < 0) {
        $b = 255;
        $a--;
    }

    if ($a < 0) {
        die("IPv4 Range Exceeded");
    }

    return "$a.$b.$c.$d";
}

?>
</code>```

To test both functions, you can write a for loop to generate approximately 16 million IP addresses back and forth, you can pipe the output to a file and store the results that way.

```<code><?php

require 'function.ipinc.php';
require 'function.ipdec.php';

print("Increment:\n");
for ($i = 0, $ip = "100.0.0.0"; $i <= 16777215; $i++) {
    print("$ip\n");
    $ip = ipinc($ip);
}
print("----------\n");

print("Decrement:\n");
for ($i = 0, $ip = "100.255.255.255"; $i <= 16777215; $i++) {
    print("$ip\n");
    $ip = ipdec($ip);
}
print("----------\n");

die("Finished!\n");

?>
</code>```

If you don't like assigning values through variable declarations, modify the functions so you can use pass by reference instead.

ContentLicense: CC BY-SA 2.5

Body:
Increment (Add to):

<?php

function ipinc($i): string {
    $i = explode(".", $i);

    $a = $i[0];
    $b = $i[1];
    $c = $i[2];
    $d = $i[3];

    $d++;

    if ($d > 255) {
        $d = 0;
        $c++;
    }

    if ($c > 255) {
        $c = 0;
        $b++;
    }

    if ($b > 255) {
        $b = 0;
        $a++;
    }

    if ($a > 255) {
        die("IPv4 Range Exceeded");
    }

    return "$a.$b.$c.$d";
}

?>

Decrement (Take from):

<?php

function ipdec($i) {
    $i = explode(".", $i);

    $a = $i[0];
    $b = $i[1];
    $c = $i[2];
    $d = $i[3];

    $d--;

    if ($d < 0) {
        $d = 255;
        $c--;
    }

    if ($c < 0) {
        $c = 255;
        $b--;
    }

    if ($b < 0) {
        $b = 255;
        $a--;
    }

    if ($a < 0) {
        die("IPv4 Range Exceeded");
    }

    return "$a.$b.$c.$d";
}

?>

To test both functions, you can write a for loop to generate approximately 16 million IP addresses back and forth, you can pipe the output to a file and store the results that way.

<?php

require 'function.ipinc.php';
require 'function.ipdec.php';

print("Increment:\n");
for ($i = 0, $ip = "100.0.0.0"; $i <= 16777215; $i++) {
    print("$ip\n");
    $ip = ipinc($ip);
}
print("----------\n");

print("Decrement:\n");
for ($i = 0, $ip = "100.255.255.255"; $i <= 16777215; $i++) {
    print("$ip\n");
    $ip = ipdec($ip);
}
print("----------\n");

die("Finished!\n");

?>

If you don't like assigning values through variable declarations, modify the functions so you can use pass by reference instead.


问:
Pandas : Create new columns from a list of dictionaries in another column
I have a list of arbitrary number of dictionaries in each cell of a pandas column.

```<code> df['Amenities'][0]

 [{'Description': 'Basketball Court(s)'},
 {'Description': 'Bike Rack / Bike Storage'},
 {'Description': 'Bike Rental'},
 {'Description': 'Business Center'},
 {'Description': 'Clubhouse'},
 {'Description': 'Community Garden'},
 {'Description': 'Complex Wifi '},
 {'Description': 'Courtesy Patrol/Officer'},
 {'Description': 'Dog Park'},
 {'Description': 'Health Club / Fitness Center'},
 {'Description': 'Jacuzzi'},
 {'Description': 'Pet Friendly'},
 {'Description': 'Pet Park / Dog Run'},
 {'Description': 'Pool'}]
</code>```

I'd like to do the following.

1) Iterate over list of dicts, Unpack them and create columns with value 1 (Amenities exits).

2) On the subsequent iterations, check if the column label already exists, then add 1 as value to the cell, or create a new column if it doesn't exist.

3) Fill the remaining columns with 0.

Basically, I am trying to create features that hold values 0 and 1 from a list of dictionaries.

The code below creates new columns based on dict values but the part around checking if the column exists , creating a new one if doesn't and assigning 1s and 0s needs a bit of thinking.

```<code> for i, row in df.iterrows():

     dict_obj = row['Amenities']

     for key, val in dict_obj.items():

         if val in df.columns:

            df.loc[i, val] = 1

         else

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

Expected Outcome something like this:

答:
Your code was a great start and very close!

As you said, you need to iterate through the dictionaries. The solution is to use .loc to create the new column on your dataframe (for the amenity currently being processed) if it doesn't yet exist or set its value if it does.

```<code>import pandas as pd

df = pd.DataFrame(
    {
        "Amenities": [
            [
                {"Description": "Basketball Court(s)"},
                {"Description": "Bike Rack / Bike Storage"},
                {"Description": "Bike Rental"},
            ],
            [
                {"Description": "Basketball Court(s)"},
                {"Description": "Courtesy Patrol/Officer"},
                {"Description": "Dog Park"},
            ],
        ]
    }
)

for i, row in df.iterrows():
    amenities_list = row["Amenities"]
    for amenity in amenities_list:
        for k, v in amenity.items():
            df.loc[i, v] = 1

df = df.drop(columns="Amenities")
df = df.fillna(0).astype({i: "int" for i in df.columns})
</code>```

Short description:
i is the row index and v is the name of the amenity (string). df.loc[] takes in row index, column index and creates a new column if the column index is not yet present.

After the for loop, we just drop the no longer needed "Amentities" column, replace all NA values with 0 and then convert all columns to integers (NA values exist only for floats and so by default they are floats to begin with).

Body:
I have a list of arbitrary number of dictionaries in each cell of a pandas column.

 df['Amenities'][0]

 [{'Description': 'Basketball Court(s)'},
 {'Description': 'Bike Rack / Bike Storage'},
 {'Description': 'Bike Rental'},
 {'Description': 'Business Center'},
 {'Description': 'Clubhouse'},
 {'Description': 'Community Garden'},
 {'Description': 'Complex Wifi '},
 {'Description': 'Courtesy Patrol/Officer'},
 {'Description': 'Dog Park'},
 {'Description': 'Health Club / Fitness Center'},
 {'Description': 'Jacuzzi'},
 {'Description': 'Pet Friendly'},
 {'Description': 'Pet Park / Dog Run'},
 {'Description': 'Pool'}]

I'd like to do the following.

1) Iterate over list of dicts, Unpack them and create columns with value 1 (Amenities exits).

2) On the subsequent iterations, check if the column label already exists, then add 1 as value to the cell, or create a new column if it doesn't exist.

3) Fill the remaining columns with 0.

Basically, I am trying to create features that hold values 0 and 1 from a list of dictionaries.

The code below creates new columns based on dict values but the part around checking if the column exists , creating a new one if doesn't and assigning 1s and 0s needs a bit of thinking.

 for i, row in df.iterrows():

     dict_obj = row['Amenities']

     for key, val in dict_obj.items():

         if val in df.columns:

            df.loc[i, val] = 1

         else

            .......

Expected Outcome something like this:

Body:
Your code was a great start and very close!

As you said, you need to iterate through the dictionaries. The solution is to use .loc to create the new column on your dataframe (for the amenity currently being processed) if it doesn't yet exist or set its value if it does.

import pandas as pd

df = pd.DataFrame(
    {
        "Amenities": [
            [
                {"Description": "Basketball Court(s)"},
                {"Description": "Bike Rack / Bike Storage"},
                {"Description": "Bike Rental"},
            ],
            [
                {"Description": "Basketball Court(s)"},
                {"Description": "Courtesy Patrol/Officer"},
                {"Description": "Dog Park"},
            ],
        ]
    }
)

for i, row in df.iterrows():
    amenities_list = row["Amenities"]
    for amenity in amenities_list:
        for k, v in amenity.items():
            df.loc[i, v] = 1

df = df.drop(columns="Amenities")
df = df.fillna(0).astype({i: "int" for i in df.columns})

Short description:
i is the row index and v is the name of the amenity (string). df.loc[] takes in row index, column index and creates a new column if the column index is not yet present.

After the for loop, we just drop the no longer needed "Amentities" column, replace all NA values with 0 and then convert all columns to integers (NA values exist only for floats and so by default they are floats to begin with).


问:
Prevent Modal Rerendering when only Modal Content Change: React Hooks useReducer
I have a parent-child component Modal and ModalContent in my React App both functional.

1) I have created an AppContext in App.js for accessing it globally in all components.

const [state, dispatch] = useReducer(reducer, {modalOpen: false, content: []});

```<code>    <AppContext.Provider value={{ state, dispatch }} >
      //BrowserRouter and Routes Definition
    </App>
</code>```

Here reducer is a fairly plain function with toggle for modalOpen and push/pop functionality in content(array).

2) My Modal Component makes use of

```<code>const { state, dispatch } = useContext(AppContext);
<Modal open={state.modalOpen} />
</code>```

to get the state of modal visibility to set it open/closed.

3) My ModalContent Component makes use of

```<code>const { state, dispatch } = useContext(AppContext);
<ModalContent data={state.content} />
  //Dispatch from the `ModalContent`
  dispatch({ type: 'UPDATE_CONTENT', data: 'newata' });
</code>```

4) Here is my reducer.

```<code>export const reducer = (state, action) => {
switch (action.type) {
    case 'TOGGLE_MODAL':
            return {...state, modalOpen: !state.modalOpen};
    case 'UPDATE_CONTENT':
        return { ...state, content: [...state.content, action.data]};
    default:
        return {modalOpen: false,content: []};
 }
}
</code>```

I have set up some code in ModalContent to update the data content property using dispatch and the reducer store is updated perfectly and returns fresh/updated:

```<code> {modalOpen: true/false, content: updatedContentArray}
</code>```

The issue is: Whenever I dispatch an action via ModalContent complete state is returned(expected), by the reducer and Modal reopens itself as it listens to state.modalOpen.

Unsuccessful Attempt: I attempted to specifically pull required properties in respective components. But the Modal component still rerenders even when just content is changed. Is there any way to watch for specific state only

How can make this work by rerendering only ModalContent not Modal.

Edit: Updated question with my mock(working) reducer code and dispatch statement from the ModalContent itself.

答:
The reason both Modal and ModalContent get re-rendered when Content changes is because both the components make use of the same context and when a context value changes all components listening to the context are re-rendered

A way to fix this re-rendering thing is to make use of multiple contexts like

```<code> const modalContextVal = useMemo(() => ({ modalOpen: state.modalOpen, dispatch}), [state.modalOpen]);
   const contentContextVal = useMemo(() => ({ content: state.content, dispatch}), [state.content]);
   ....
   <ModalContext.Provider value={modalContextVal}>
      <ContentContext.Provider value={contentContextVal}>
      //BrowserRouter and Routes Definition
      </ContentContext.Provider>
    </ModalContext.Provider>
</code>```

And use it like

In Modal.js

```<code>const {modalOpen, dispatch} = useContext(ModalContext);
</code>```

In ModalContent.js

```<code>const {content, dispatch} = useContext(ContentContext);
</code>```

Body:
I have a parent-child component Modal and ModalContent in my React App both functional.

1) I have created an AppContext in App.js for accessing it globally in all components.

const [state, dispatch] = useReducer(reducer, {modalOpen: false, content: []});

    <AppContext.Provider value={{ state, dispatch }} >
      //BrowserRouter and Routes Definition
    </App>

Here reducer is a fairly plain function with toggle for modalOpen and push/pop functionality in content(array).

2) My Modal Component makes use of

const { state, dispatch } = useContext(AppContext);
<Modal open={state.modalOpen} />

to get the state of modal visibility to set it open/closed.

3) My ModalContent Component makes use of

const { state, dispatch } = useContext(AppContext);
<ModalContent data={state.content} />
  //Dispatch from the `ModalContent`
  dispatch({ type: 'UPDATE_CONTENT', data: 'newata' });

4) Here is my reducer.

export const reducer = (state, action) => {
switch (action.type) {
    case 'TOGGLE_MODAL':
            return {...state, modalOpen: !state.modalOpen};
    case 'UPDATE_CONTENT':
        return { ...state, content: [...state.content, action.data]};
    default:
        return {modalOpen: false,content: []};
 }
}

I have set up some code in ModalContent to update the data content property using dispatch and the reducer store is updated perfectly and returns fresh/updated:

 {modalOpen: true/false, content: updatedContentArray}

The issue is: Whenever I dispatch an action via ModalContent complete state is returned(expected), by the reducer and Modal reopens itself as it listens to state.modalOpen.

Unsuccessful Attempt: I attempted to specifically pull required properties in respective components. But the Modal component still rerenders even when just content is changed. Is there any way to watch for specific state only

How can make this work by rerendering only ModalContent not Modal.

Edit: Updated question with my mock(working) reducer code and dispatch statement from the ModalContent itself.

Body:
The reason both Modal and ModalContent get re-rendered when Content changes is because both the components make use of the same context and when a context value changes all components listening to the context are re-rendered

A way to fix this re-rendering thing is to make use of multiple contexts like

 const modalContextVal = useMemo(() => ({ modalOpen: state.modalOpen, dispatch}), [state.modalOpen]);
   const contentContextVal = useMemo(() => ({ content: state.content, dispatch}), [state.content]);
   ....
   <ModalContext.Provider value={modalContextVal}>
      <ContentContext.Provider value={contentContextVal}>
      //BrowserRouter and Routes Definition
      </ContentContext.Provider>
    </ModalContext.Provider>

And use it like

In Modal.js

const {modalOpen, dispatch} = useContext(ModalContext);

In ModalContent.js

const {content, dispatch} = useContext(ContentContext);


问:
(-215:Assertion failed) number < max_number in function 'cv::icvExtractPattern' error?
I'm trying to run this python script as an exe file - using pyinstaller, and it raise me this error:

[ERROR:0] global C:\projects\opencv-python\opencv\modules\videoio\src\cap.cpp (415) cv::VideoWriter::open VIDEOIO(CV_IMAGES): raised OpenCV exception:
  OpenCV(4.2.0) C:\projects\opencv-python\opencv\modules\videoio\src\cap_images.cpp:267: error: (-215:Assertion failed) number < max_number in function 'cv::icvExtractPattern'

When I'm running it as a python script, it works well.
the python script:

```<code>SCREEN_SIZE = (1920, 1080)
FPS = 20.0
fourcc = cv2.VideoWriter_fourcc(*"XVID")
out = cv2.VideoWriter("output.avi", fourcc, FPS, SCREEN_SIZE)
</code>```

I'm using pyinstaller in the command line:

```<code>pyinstaller --onefile python_script.py
</code>```

what should I change to make it work?

答:
Main solution: It could be a DLL error.

I suppose your problem is connected to this issue. There is a workaround suggested in this comment. It suggests to run pyinstaller as

pyinstaller -F --add-data opencv_ffmpeg410_64.dll;. python_script.py

Make sure to adapt to your OpenCV version. Make sure this dll exists anywhere.

Alternative:
I believe the error

python\opencv\modules\videoio\src\cap_images.cpp:267: error: (-215:Assertion failed) number < max_number in function 'cv::icvExtractPattern'

is caused by this line here fourcc = cv2.VideoWriter_fourcc(*"XVID") where the value that is set is > the max value.

You can try to set the fourcc to -1. Then, it will give you a choice of video codecs to use for writing. I have seen that uncompressed video choice works fine for most of the platforms.

Body:
I'm trying to run this python script as an exe file - using pyinstaller, and it raise me this error:

[ERROR:0] global C:\projects\opencv-python\opencv\modules\videoio\src\cap.cpp (415) cv::VideoWriter::open VIDEOIO(CV_IMAGES): raised OpenCV exception:
  OpenCV(4.2.0) C:\projects\opencv-python\opencv\modules\videoio\src\cap_images.cpp:267: error: (-215:Assertion failed) number < max_number in function 'cv::icvExtractPattern'

When I'm running it as a python script, it works well.
the python script:

SCREEN_SIZE = (1920, 1080)
FPS = 20.0
fourcc = cv2.VideoWriter_fourcc(*"XVID")
out = cv2.VideoWriter("output.avi", fourcc, FPS, SCREEN_SIZE)

I'm using pyinstaller in the command line:

pyinstaller --onefile python_script.py

what should I change to make it work?


答:
one way is to explode the column Amenities, then create a dataframe, use str.get_dummies on the column and sum on the level=0 like:

```<code>#data example
df = pd.DataFrame({
    'Amenities': [
        [{'Description': 'Basketball Court(s)'},
         {'Description': 'Bike Rental'}],
        [{'Description': 'Basketball Court(s)'},
         {'Description': 'Clubhouse'},
         {'Description': 'Community Garden'}]
    ]})

# explode
s = df['Amenities'].explode()
# create dataframe, use get_dummies and sum on the level=0 of index
df_ = pd.DataFrame(s.tolist(), s.index)['Description'].str.get_dummies().sum(level=0)
print (df_)
   Basketball Court(s)  Bike Rental  Clubhouse  Community Garden
0                    1            1          0                 0
1                    1            0          1                 1
</code>```

Title: Pandas : Create new columns from a list of dictionaries in another column

Body:
one way is to explode the column Amenities, then create a dataframe, use str.get_dummies on the column and sum on the level=0 like:

#data example
df = pd.DataFrame({
    'Amenities': [
        [{'Description': 'Basketball Court(s)'},
         {'Description': 'Bike Rental'}],
        [{'Description': 'Basketball Court(s)'},
         {'Description': 'Clubhouse'},
         {'Description': 'Community Garden'}]
    ]})

# explode
s = df['Amenities'].explode()
# create dataframe, use get_dummies and sum on the level=0 of index
df_ = pd.DataFrame(s.tolist(), s.index)['Description'].str.get_dummies().sum(level=0)
print (df_)
   Basketball Court(s)  Bike Rental  Clubhouse  Community Garden
0                    1            1          0                 0
1                    1            0          1                 1