问:
Swift Error The data can not be Read because it is missing
I am trying to display the data from API . Here is the API Link .https://coinmap.org/api/v1/venues/ . I want to display the properties of the Vanues Array fields into IOS app . I created model by using Quick type . I use the Map like self.vanues = respone.results.map{$0} but still same result Here is the model .

```<code>import Foundation

// MARK: - Welcome
struct Coin: Codable {
    let venues: [Venue]
}

// MARK: - Venue
struct Venue: Codable {
    let id: Int
    let lat, lon: Double
    let category, name: String
    let createdOn: Int
    let geolocationDegrees: String

    enum CodingKeys: String, CodingKey {
        case id, lat, lon, category, name
        case createdOn = "created_on"
        case geolocationDegrees = "geolocation_degrees"
    }
}

</code>```

I convert that to list by using another swift file . Here is the code .

```<code>import Foundation
struct VanueResponse: Decodable {
    let results: [Venue]
}
</code>```

Here is my Network Manager .

```<code>import Foundation

class NetworkManager {

    func getCoins(from url: String, completion: @escaping (Result<VanueResponse, NetworkError>) -> Void ) {

        guard let url = URL(string: url) else {
            completion(.failure(.badURL))
            return
        }

        URLSession.shared.dataTask(with: url) { data, response, error in

            if let error = error {
                completion(.failure(.other(error)))
                return
            }

            if let data = data {
                //decode
                do {
                    let response = try JSONDecoder().decode(VanueResponse.self, from: data)
                    completion(.success(response))
                } catch let error {
                    completion(.failure(.other(error)))
                }
            }
        }
        .resume()
    }

}
</code>```

Here is the presenter class.

```<code>import Foundation

class VenuePresenter : VanueProtocol{

    // creating instance of the class
    private let view : VanueViewProtocol
    private let networkManager: NetworkManager
    private var vanues = [Venue]()
    var rows: Int{
        return vanues.count
    }
    // initilanize the class
    init(view:VanueViewProtocol , networkmanager:NetworkManager = NetworkManager()){
        self.view = view
        self.networkManager = networkmanager
    }

    func getVanue(){

        let url  = "https://coinmap.org/api/v1/venues/"

        networkManager.getCoins(from: url) { result in

            switch result {
            case.success(let respone):
                self.vanues = respone.results
                DispatchQueue.main.async {
                    self.view.resfreshTableView()
                }
            case .failure(let error):
                DispatchQueue.main.async {
                    self.view.displayError(error.localizedDescription)
                    print(Thread.callStackSymbols)
                }
            }

        }
    }

    func getId(by row: Int) -> Int {
        return vanues[row].id
    }

    func getLat(by row: Int) -> Double {
        return vanues[row].lat
    }

    func getCreated(by row: Int) -> Int {
        return vanues[row].createdOn
    }

    func getLon(by row: Int) -> Double? {
        return vanues[row].lon
    }

}

</code>```

I put the break point and find this in console windows .

Here is the screenshot when I run the Applications .

答:
The Decoding Error is clear:

The key in the root dictionary is venues (not results) so the proper struct is Coin.

In getCoins replace both occurrences of VanueResponse with Coin

Body:
I am trying to display the data from API . Here is the API Link .https://coinmap.org/api/v1/venues/ . I want to display the properties of the Vanues Array fields into IOS app . I created model by using Quick type . I use the Map like self.vanues = respone.results.map{$0} but still same result Here is the model .

import Foundation

// MARK: - Welcome
struct Coin: Codable {
    let venues: [Venue]
}

// MARK: - Venue
struct Venue: Codable {
    let id: Int
    let lat, lon: Double
    let category, name: String
    let createdOn: Int
    let geolocationDegrees: String

    enum CodingKeys: String, CodingKey {
        case id, lat, lon, category, name
        case createdOn = "created_on"
        case geolocationDegrees = "geolocation_degrees"
    }
}

I convert that to list by using another swift file . Here is the code .

import Foundation
struct VanueResponse: Decodable {
    let results: [Venue]
}

Here is my Network Manager .

import Foundation

class NetworkManager {

    func getCoins(from url: String, completion: @escaping (Result<VanueResponse, NetworkError>) -> Void ) {

        guard let url = URL(string: url) else {
            completion(.failure(.badURL))
            return
        }

        URLSession.shared.dataTask(with: url) { data, response, error in

            if let error = error {
                completion(.failure(.other(error)))
                return
            }

            if let data = data {
                //decode
                do {
                    let response = try JSONDecoder().decode(VanueResponse.self, from: data)
                    completion(.success(response))
                } catch let error {
                    completion(.failure(.other(error)))
                }
            }
        }
        .resume()
    }

}

Here is the presenter class.

import Foundation

class VenuePresenter : VanueProtocol{

    // creating instance of the class
    private let view : VanueViewProtocol
    private let networkManager: NetworkManager
    private var vanues = [Venue]()
    var rows: Int{
        return vanues.count
    }
    // initilanize the class
    init(view:VanueViewProtocol , networkmanager:NetworkManager = NetworkManager()){
        self.view = view
        self.networkManager = networkmanager
    }

    func getVanue(){

        let url  = "https://coinmap.org/api/v1/venues/"

        networkManager.getCoins(from: url) { result in

            switch result {
            case.success(let respone):
                self.vanues = respone.results
                DispatchQueue.main.async {
                    self.view.resfreshTableView()
                }
            case .failure(let error):
                DispatchQueue.main.async {
                    self.view.displayError(error.localizedDescription)
                    print(Thread.callStackSymbols)
                }
            }

        }
    }

    func getId(by row: Int) -> Int {
        return vanues[row].id
    }

    func getLat(by row: Int) -> Double {
        return vanues[row].lat
    }

    func getCreated(by row: Int) -> Int {
        return vanues[row].createdOn
    }

    func getLon(by row: Int) -> Double? {
        return vanues[row].lon
    }

}

I put the break point and find this in console windows .

Here is the screenshot when I run the Applications .


来源: stackexchange

问:
Jackson serialise property based on other property value
I'm looking for a solution to serialize a POJO object property based on some other property value within the same POJO using Jackson.

If a property value matches some criteria then other property values should be changed as per requirement.

For example, below is my JSON object:

{
  "testProperty": "testValue",
  "object": [{
    "key": "password",
    "value": "passwordValue"
  },
  {
    "key": "key2",
    "value": "value2"
  }]
}
```

In above case, if key's value matches some criteria then I should be able to change the value of value.

Why this is required:

object is a configuration object

And key-value are configuration settings

In the above example one of the key is password and I need to mask/change the respective value of that.

One more point to add, here in this example the properties are key and value, but if we find some solution to get it applied generically to any other properties dynamically then that would be great.

Annotating the properties can be one way but haven't found any way within Jackson to do so with custom serializers.

Thanks in advance.

Any help will be appreciated.

答:
Jackson has following concepts for that:

Filter: filter and control serialization of properties

How to setup:
The annotation @JsonFilter applies a named filter to a class (bean).
That name can be looked up in a registry to find a custom PropertyFilter implementation (e.g. an extension of abstract SimpleBeanPropertyFilter).
The registry is a FilterProvider which can be configured with your ObjectMapper.

How it works:
So when the ObjectMapper instance is about to serialize your bean it will recognize the filter and use the logic  to a FilterProvider. The FilterProvider then controls if and how the property is serialized.

See:

tutorial on Baeldung (2019): Serialize Only Fields that meet a Custom Criteria with Jackson

article on CowTownCoder (2011): Advanced filtering with Jackson, Json Filters

Modifier: modify serialization at runtime, dynamically/conditional

For example BeanSerializerModifier as solution to hide a field dynamically - based on a runtime value condition. See Skip objects conditionally when serializing with jackson.

Static masking

(Probably not for your variable key/value pairs, but generally good approach for fields designed to hide sensitive data)

See Mask json fields using jackson which tries to add a specific serializer which derives its mask from a custom annotation.

ContentLicense: CC BY-SA 4.0

Body:
I'm looking for a solution to serialize a POJO object property based on some other property value within the same POJO using Jackson.

If a property value matches some criteria then other property values should be changed as per requirement.

For example, below is my JSON object:

{
  "testProperty": "testValue",
  "object": [{
    "key": "password",
    "value": "passwordValue"
  },
  {
    "key": "key2",
    "value": "value2"
  }]
}

In above case, if key's value matches some criteria then I should be able to change the value of value.

Why this is required:

object is a configuration object

And key-value are configuration settings

In the above example one of the key is password and I need to mask/change the respective value of that.

One more point to add, here in this example the properties are key and value, but if we find some solution to get it applied generically to any other properties dynamically then that would be great.

Annotating the properties can be one way but haven't found any way within Jackson to do so with custom serializers.

Thanks in advance.

Any help will be appreciated.


问:
Is there a way I can programmatically attach a large file to an outlook message despite it exceeding the server size limit?
A quick note in case you come upon this question hoping for a solution.... there isn't one. Sadly sometimes one has to accept that the right answer to one's question is "You can't do that".

I am hoping there is something I can do here to ensure that attaching a large file to an Outlook.MailItem works exactly the same as doing so manually.

To be precise... when a user composes an email in Outlook and they attach a file that is too large to the email, Outlook will happily attach the file to the email. Instead of simply refusing to do so, it will attach the file and a message will appear in the Inspector:

However....

When coding a similar action you would get access to an Outlook.MailItem and you would invoke the .Add method on its .Attachments object

```<code>oMailObject.Attachments.Add("<path to a file that is way too big here>")
</code>```

The problem is that that action fails. An error is thrown
"The file you're attaching is bigger than the server allows. Try putting the file in a shared location and sending a link instead."

Yes, we can obviously catch the error and then show a message to the user. That's what we're currently doing. It would, however, be nicer if there were a way I can prevent it from raising the error so it would still attach the file to the MailItem, and then when I show the inspector to the user they would see the same thing they would see if they had attached the attachment manually.

Is there an option on the MailItem to prevent it raising an error? Something in the Attachments.Add method? Any suggestions?

答: You can read PR_MAX_SUBMIT_MESSAGE_SIZE MAPI property (DASL name is "http://schemas.microsoft.com/mapi/proptag/0x666D0003") from the store (use Store.PropertyAccessor.GetProperty) - it returns the size in kB - prior to sending the message. This property is Exchange-specific.

Body:
A quick note in case you come upon this question hoping for a solution.... there isn't one. Sadly sometimes one has to accept that the right answer to one's question is "You can't do that".

I am hoping there is something I can do here to ensure that attaching a large file to an Outlook.MailItem works exactly the same as doing so manually.

To be precise... when a user composes an email in Outlook and they attach a file that is too large to the email, Outlook will happily attach the file to the email. Instead of simply refusing to do so, it will attach the file and a message will appear in the Inspector:

However....

When coding a similar action you would get access to an Outlook.MailItem and you would invoke the .Add method on its .Attachments object

oMailObject.Attachments.Add("<path to a file that is way too big here>")

The problem is that that action fails. An error is thrown
"The file you're attaching is bigger than the server allows. Try putting the file in a shared location and sending a link instead."

Yes, we can obviously catch the error and then show a message to the user. That's what we're currently doing. It would, however, be nicer if there were a way I can prevent it from raising the error so it would still attach the file to the MailItem, and then when I show the inspector to the user they would see the same thing they would see if they had attached the attachment manually.

Is there an option on the MailItem to prevent it raising an error? Something in the Attachments.Add method? Any suggestions?


问:
How to stop inputA from changing?
so how can i make inputA and inputB have different numbers?
right now inputA is the same as inputB
</p>
```<code>const numbers = document.querySelectorAll(".numbers");
numbers.forEach((number) => {
  number.addEventListener("click", () => {
    display.textContent += number.innerHTML;
    inputA = display.textContent;
    console.log(inputA + "a")
  });
});

const functions = document.querySelectorAll(".func");
functions.forEach((fnction) => {
  fnction.addEventListener("click", () => {
    display.textContent = "";
    operatorInput = fnction.innerHTML;
    console.log(operatorInput)

      numbers.forEach((number) => {
      number.addEventListener("click", () => {

        inputB = display.textContent;
        console.log(inputB + "b");
      });
    });

  })
})
</code>```

答:
First of all document.querySelectorAll doesnt return array.
The proper usage is:

```<code>Array.from(document.querySelectorAll(selector)).forEach...
</code>```

Please check the reference https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelectorAll

You dont declare variables inputA and inputA (let inputA, let inputB).
What's more, display.textContent in case B is equal to the display.textcontent from the case A.
Because it's the same element. Despite you attempt to clear textContent in the upperscope (case B) it has no effect.

Title: How to stop inputA from changing?

Body:
so how can i make inputA and inputB have different numbers?
right now inputA is the same as inputB

const numbers = document.querySelectorAll(".numbers");
numbers.forEach((number) => {
  number.addEventListener("click", () => {
    display.textContent += number.innerHTML;
    inputA = display.textContent;
    console.log(inputA + "a")
  });
});

const functions = document.querySelectorAll(".func");
functions.forEach((fnction) => {
  fnction.addEventListener("click", () => {
    display.textContent = "";
    operatorInput = fnction.innerHTML;
    console.log(operatorInput)

      numbers.forEach((number) => {
      number.addEventListener("click", () => {

        inputB = display.textContent;
        console.log(inputB + "b");
      });
    });

  })
})

Body:
First of all document.querySelectorAll doesnt return array.
The proper usage is:

Array.from(document.querySelectorAll(selector)).forEach...

Please check the reference https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelectorAll

You dont declare variables inputA and inputA (let inputA, let inputB).
What's more, display.textContent in case B is equal to the display.textcontent from the case A.
Because it's the same element. Despite you attempt to clear textContent in the upperscope (case B) it has no effect.


问:
regex: ignore eveything except the second column
I have a txt file with some text like this:

000001 - AAAAAA - BBBBBBBB - CCCC

000002 - BAAAAA - BBBBBBBB - CCCC

000003 - DAAAAA - BBBBBBBB - CCCC

...

I need a regex that ignore everything except the second colunm(AAAAAA,BAAAAA,DAAAAA,...)

Thank you

答:
Try this:

```<code>[^-]+- ([^ -]+).*
</code>```

[^-]+ matches up to the first non-dash and [^- ]+ matches up to the first character which is neither a space nor a dash.

With a tool like sed the command would be

```<code>sed -E 's/[^-]+- ([^ -]+).*/\1/' input.txt
</code>```

An even better tool for the job, however, is awk which will give the same result with the command

```<code>awk -F ' - ' '{ print $2 }' input.txt
</code>```

Body:
Try this:

[^-]+- ([^ -]+).*

[^-]+ matches up to the first non-dash and [^- ]+ matches up to the first character which is neither a space nor a dash.

With a tool like sed the command would be

sed -E 's/[^-]+- ([^ -]+).*/\1/' input.txt

An even better tool for the job, however, is awk which will give the same result with the command

awk -F ' - ' '{ print $2 }' input.txt


问:
How do I check if a string is a float number or an integer number?
"1.0".isnumeric() -> False

I need to know if that string is actually a float number or an integer number because there although the string is in fact a float number the .isnumeric() returns False

答:
Try this function:

```<code>def is_numeric(some_string):
    try:
        float(some_string)
        return True
    except ValueError:
        return False

if __name__ == "__main__":
    print(is_numeric("123"))
    print(is_numeric("1.0"))
    print(is_numeric("1.0asd"))
</code>```

Output:

```<code>True
True
False
</code>```

Body:
Try this function:

def is_numeric(some_string):
    try:
        float(some_string)
        return True
    except ValueError:
        return False

if __name__ == "__main__":
    print(is_numeric("123"))
    print(is_numeric("1.0"))
    print(is_numeric("1.0asd"))

Output:

True
True
False


问:
How to prevent blur on image resize in Chrome?
The images are really blurry if you use resize an image, for example showing a small image with resized dimensions, like;

```<code><img src="largeimage.jpg" width=30 height=30 \>
</code>```

Its not blurry in other browsers, but in Chrome, its so blurry.
I have looked at in www.twitter.com , their new design has lots of resized images and somehow, they have managed to clear blur in resized images. I have tried these;

```<code>image-rendering: crisp-edges;
image-rendering: pixelated;
</code>```

But unfortunately, it doesn't solve the problem.

Below is a comparison. On the left, you can see that it is quite blurry, compared to that on the right:

What is the correct way to do that ?

答:
I understand that this is an old post and things might have changed since then; thus, I am posting this for future readers who might come accross this question.

You could set image-rendering to pixelated, in order to preserve the original pixelated form. The below should work as expected on Chrome (and Opera) browser as well.

```<code>img {
  image-rendering: pixelated;
}
</code>```

As per the documentation:

pixelated

Using the nearest-neighbor algorithm, the image is scaled up to the next integer multiple that is greater than or equal to its original size, then scaled down to the target size, as for smooth. When scaling up to integer multiples of the original size, this will have the same effect as crisp-edges.

ContentLicense: CC BY-SA 3.0

Body:
The images are really blurry if you use resize an image, for example showing a small image with resized dimensions, like;

Its not blurry in other browsers, but in Chrome, its so blurry.
I have looked at in www.twitter.com , their new design has lots of resized images and somehow, they have managed to clear blur in resized images. I have tried these;

image-rendering: crisp-edges;
image-rendering: pixelated;

But unfortunately, it doesn't solve the problem.

Below is a comparison. On the left, you can see that it is quite blurry, compared to that on the right:

What is the correct way to do that ?

Body:
I understand that this is an old post and things might have changed since then; thus, I am posting this for future readers who might come accross this question.

You could set image-rendering to pixelated, in order to preserve the original pixelated form. The below should work as expected on Chrome (and Opera) browser as well.

img {
  image-rendering: pixelated;
}

As per the documentation:

pixelated

Using the nearest-neighbor algorithm, the image is scaled up to the next integer multiple that is greater than or equal to its original size, then scaled down to the target size, as for smooth. When scaling up to integer multiples of the original size, this will have the same effect as crisp-edges.


问:
posix setuid different process
I'm developing an application for Android and I need to elevate the Dalvik VM to root uid, because in the alternative I need to write a lot of small applications that are started by the Java code using sh scripts (with superuser, they needs to be root) and I really don't want to do that!

While I'm trying to use, right now, capsetp to set CAP_SETUID to the calling process, I don't know if this will be widely supported by all Android kernels so I'm looking for possible alternatives.

My fallback solution would be to start a root process that will first use seteuid to switch to the right user, start Dalvik VM with the application (execl) and, using JNI, switch back to the root user ...

Any alternative?

EDIT

I'm trying this code, but it fails to apply new capabilities (capsetp).

I've partially compiled libcap on Android (cap_file stuff is missing, but I don't need it), but this code doesn't work on a standard distro (Ubuntu).

```<code>#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <unistd.h>
#include <sys/types.h>
#ifndef __user
#define __user
#endif
#include <linux/capability.h>
#include <sys/capability.h>

int main(int argc, char** argv)
{
    cap_t caps;
    cap_value_t cap_list[1];

    pid_t process_id = atoi(argv[1]);

    caps = cap_get_pid(process_id);
    if (caps == NULL)
    {
        perror("Failed to get capabilities");
        exit(-1);
    }

    printf("%s\n", cap_to_text(caps, NULL));

    cap_list[0] = CAP_SETUID;

    if (cap_set_flag(caps, CAP_EFFECTIVE, 1, cap_list, CAP_SET) == -1)
    {
        perror("Failed to add new capability");
        exit(-1);
    }

    if (capsetp(process_id, caps) == -1)
    {
        perror("Failed to apply capabilities");
        exit(-1);
    }

    cap_free(&caps);

    return 0;
}
</code>```

答: I don't think there's a way to elevate another process's privileges directly. The canonical way to do things like this is to exec a setuid-root binary which then determines whether to grant your program privileges before re-execing your program. Think su or sudo. Of course your setuid-root program like that could communicate with the original root process to determine if it's safe to grant root. Keep in mind that there could be lots of dangerous corner cases.

Title: posix setuid different process

Body:
I'm developing an application for Android and I need to elevate the Dalvik VM to root uid, because in the alternative I need to write a lot of small applications that are started by the Java code using sh scripts (with superuser, they needs to be root) and I really don't want to do that!

While I'm trying to use, right now, capsetp to set CAP_SETUID to the calling process, I don't know if this will be widely supported by all Android kernels so I'm looking for possible alternatives.

My fallback solution would be to start a root process that will first use seteuid to switch to the right user, start Dalvik VM with the application (execl) and, using JNI, switch back to the root user ...

Any alternative?

EDIT

I'm trying this code, but it fails to apply new capabilities (capsetp).

I've partially compiled libcap on Android (cap_file stuff is missing, but I don't need it), but this code doesn't work on a standard distro (Ubuntu).

#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <unistd.h>
#include <sys/types.h>
#ifndef __user
#define __user
#endif
#include <linux/capability.h>
#include <sys/capability.h>

int main(int argc, char** argv)
{
    cap_t caps;
    cap_value_t cap_list[1];

    pid_t process_id = atoi(argv[1]);

    caps = cap_get_pid(process_id);
    if (caps == NULL)
    {
        perror("Failed to get capabilities");
        exit(-1);
    }

    printf("%s\n", cap_to_text(caps, NULL));

    cap_list[0] = CAP_SETUID;

    if (cap_set_flag(caps, CAP_EFFECTIVE, 1, cap_list, CAP_SET) == -1)
    {
        perror("Failed to add new capability");
        exit(-1);
    }

    if (capsetp(process_id, caps) == -1)
    {
        perror("Failed to apply capabilities");
        exit(-1);
    }

    cap_free(&caps);

    return 0;
}


问:
data directory was initialized by PostgreSQL version 13, which is not compatible with this version 14.0
I have downloaded Portainer onto my server and created a PostgreSQL database in a container there.
Today I could no longer get access to the database. The log shows a message that there is a version problem.

I already read into some similar issues like Postgres container crashes with `database files are incompatible with server` after container's image has been updated to the latest one and Postgres container crashes with `database files are incompatible with server` after container's image has been updated to the latest one

and the solutions brew postgresql-upgrade-database did not work.

What can I do?

LOG

```<code>2021-10-03  [1] FATAL:  database files are incompatible with server
2021-10-03  [1] DETAIL:  The data directory was initialized by PostgreSQL version 13, which is not compatible with this version 14.0 (Debian 14.0-1.pgdg110+1).

PostgreSQL Database directory appears to contain a database; Skipping initialization
</code>```

I also found this https://www.postgresql.org/docs/14/upgrading.html but the commands didn't work. Do I need to do this in the container somehow, or what commands will work to keep it running in the container?

答:
You need to update the data file to the new format with this command:</p>
```<code>$ brew postgresql-upgrade-database
</code>```

Body:
I have downloaded Portainer onto my server and created a PostgreSQL database in a container there.
Today I could no longer get access to the database. The log shows a message that there is a version problem.

I already read into some similar issues like Postgres container crashes with `database files are incompatible with server` after container's image has been updated to the latest one and Postgres container crashes with `database files are incompatible with server` after container's image has been updated to the latest one

and the solutions brew postgresql-upgrade-database did not work.

What can I do?

LOG

2021-10-03  [1] FATAL:  database files are incompatible with server
2021-10-03  [1] DETAIL:  The data directory was initialized by PostgreSQL version 13, which is not compatible with this version 14.0 (Debian 14.0-1.pgdg110+1).

PostgreSQL Database directory appears to contain a database; Skipping initialization

I also found this https://www.postgresql.org/docs/14/upgrading.html but the commands didn't work. Do I need to do this in the container somehow, or what commands will work to keep it running in the container?

Body:
You need to update the data file to the new format with this command:

$ brew postgresql-upgrade-database


问:
VSCode Snippet Help/Chaining transform
I thought I was getting the hang of making my own snippets, but I can't figure out to transform a tab stop so that 'Ignore/Before/Slashes/Oh Hey Text' becomes 'OhHeyText'.

so far I have this

```<code>${4/.*\\/(.+$)/$1/g}
</code>```

or

```<code>${4/\\s//g}
</code>```

But I can't figure out how to chain the transforms together. I've read through 5 or 6 posts here on SO already, but I'm having a lot of trouble grokking the actual transformation syntax, and extrapolating that to my use case.

Thanks for any help you can give!

答:
You can use

"${TM_DIRECTORY/^.*[\\/\\\\]|\\s+//g}"
```

See the regex demo. Details:

^.*[\/\\] - start of string, any zero or more chars other than line break chars as many as possible, and then / or \

| - or

\s+ - one or more whitespaces.

Title: VSCode Snippet Help/Chaining transform

Body:
I thought I was getting the hang of making my own snippets, but I can't figure out to transform a tab stop so that 'Ignore/Before/Slashes/Oh Hey Text' becomes 'OhHeyText'.

so far I have this

${4/.*\\/(.+$)/$1/g}

or

${4/\\s//g}

But I can't figure out how to chain the transforms together. I've read through 5 or 6 posts here on SO already, but I'm having a lot of trouble grokking the actual transformation syntax, and extrapolating that to my use case.

Thanks for any help you can give!

Body:
You can use

"${TM_DIRECTORY/^.*[\\/\\\\]|\\s+//g}"

See the regex demo. Details:

^.*[\/\\] - start of string, any zero or more chars other than line break chars as many as possible, and then / or \

| - or

\s+ - one or more whitespaces.


问:
My body arrive null in my backend when mapping to the model(axios/vue.js/c#)
I'm trying to send my vue data to my backend and map it to the FilterModel and it's always null, whatever I tried I was ending up with null : this is the console.log result you see in getFilteredLogs :

```<code>{
    "searchQuery": "e",
    "dateTimeRange": {},
    "logTypeFilter": {
        "error": false,
        "warning": false,
        "critical": false
    }
}
</code>```

I tried mapping to just LogTypeFilter which is part of FilterModel and it worked I received 3 Booleans value for error, warning and critical.

I thought maybe it was the dates, but I even tried hardcoding dates or changing them to string and it didn't do anything.

Any idea ? Thanks a lot.

I have this data in my vue component which is the complex object I am trying to send to my backend:

```<code>data() {
    return {
          filterModel:{
            searchQuery: '',
            dateTimeRange:{
                sartDateTime: Date,
                endDateTime: Date
            },
            logTypeLevel:{
              error: false,
              warning: false,
              critical: false
            }
          }
    }
}
</code>```

This is my call to my backend :

```<code>getFilteredLogs(filterModel) {
      //console.log(JSON.stringify(filterModel))
      return client.post(
           '/logs/filter', {
               headers: { "Content-Type": "application/json" },
               body: JSON.stringify(filterModel)
           }
      )
}
</code>```

This is my controller code in the back end where the FilterModel is null (note I added [FromBody] just to try it out, didn't change anything) :

```<code>[HttpPost]
[Route("filter")]
public IActionResult FilterLogs([FromBody] FilterModel filter)
{
     return Ok(_logLogic.FilterLogs(filter));
}
</code>```

This is my model (added serializable just try out, didn't change anything) :

```<code>[Serializable]
public class FilterModel
{
      public string SearchQuery { get; set; }
      public DateTimeRange DateTimeRange { get; set; }
      public LogTypeFilter LogTypeFilter { get; set; }
}

[Serializable]
public class DateTimeRange
{
      public DateTime StartDateTime { get; set; }
      public DateTime EndDateTime { get; set; }
}

[Serializable]
public class LogTypeFilter
{
       public bool Critical { get; set; }
       public bool Error { get; set; }
       public bool Warning { get; set; }
}
</code>```

答:
The main issue your code isn't working is because of your axios post. It wasn't sending the body of the post at all. You can diagnose this in the future by looking at the payload section of a request in the browser network tab of the developer tools. e.g. in the image below, you can see it's sending the headers in post body.

You can also see on axios that there's no method that supports axios.post that sends the config as the second parameter and the data as the third parameter.

Below is the working solution with controller and html file that I used to reproduce your issue.

LogController.cs

```<code>namespace TestApplication.Controllers
{
    [ApiController]
    [Route("[controller]")]
    public class LogsController : ControllerBase
    {
        [HttpPost]
        [Route("filter")]
        public IActionResult FilterLogs([FromBody] FilterModel filter)
        {
            return Ok();
        }
    }

    [Serializable]
    public class FilterModel
    {
        public string SearchQuery { get; set; }
        public DateTimeRange DateTimeRange { get; set; }
        public LogTypeFilter LogTypeFilter { get; set; }
    }

    [Serializable]
    public class DateTimeRange
    {
        public DateTime StartDateTime { get; set; }
        public DateTime EndDateTime { get; set; }
    }

    [Serializable]
    public class LogTypeFilter
    {
        public bool Critical { get; set; }
        public bool Error { get; set; }
        public bool Warning { get; set; }
    }
}
</code>```

Index.html

```<code><html>
    <head>
        <script src="https://cdn.jsdelivr.net/npm/vue@2.6.14"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.25.0/axios.min.js" integrity="sha512-/Q6t3CASm04EliI1QyIDAA/nDo9R8FQ/BULoUFyN4n/BDdyIxeH7u++Z+eobdmr11gG5D/6nPFyDlnisDwhpYA==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
    </head>
    <body>
        <div id="app"></div>
        <script>
            new Vue({
                el: "#app",
                data() {
                    return {
                        filterModel: {
                            searchQuery: "Test",
                            dateTimeRange: {
                                startDateTime: new Date(),
                                endDateTime: new Date()
                            },
                            logTypeFilter: {
                                error: false,
                                warning: false,
                                critical: false
                            }
                        }
                    };
                },
                mounted() {
                    this.getFilteredLogs(this.filterModel);
                },
                methods: {
                    getFilteredLogs(filterModel) {
                        return axios.post("/logs/filter", this.filterModel,
                        {
                                headers: { "Content-Type": "application/json" }
                        })
                    }
                }
            })
        </script>
    </body>
</html>
</code>```

Body:
I'm trying to send my vue data to my backend and map it to the FilterModel and it's always null, whatever I tried I was ending up with null : this is the console.log result you see in getFilteredLogs :

{
    "searchQuery": "e",
    "dateTimeRange": {},
    "logTypeFilter": {
        "error": false,
        "warning": false,
        "critical": false
    }
}

I tried mapping to just LogTypeFilter which is part of FilterModel and it worked I received 3 Booleans value for error, warning and critical.

I thought maybe it was the dates, but I even tried hardcoding dates or changing them to string and it didn't do anything.

Any idea ? Thanks a lot.

I have this data in my vue component which is the complex object I am trying to send to my backend:

data() {
    return {
          filterModel:{
            searchQuery: '',
            dateTimeRange:{
                sartDateTime: Date,
                endDateTime: Date
            },
            logTypeLevel:{
              error: false,
              warning: false,
              critical: false
            }
          }
    }
}

This is my call to my backend :

getFilteredLogs(filterModel) {
      //console.log(JSON.stringify(filterModel))
      return client.post(
           '/logs/filter', {
               headers: { "Content-Type": "application/json" },
               body: JSON.stringify(filterModel)
           }
      )
}

This is my controller code in the back end where the FilterModel is null (note I added [FromBody] just to try it out, didn't change anything) :

[HttpPost]
[Route("filter")]
public IActionResult FilterLogs([FromBody] FilterModel filter)
{
     return Ok(_logLogic.FilterLogs(filter));
}

This is my model (added serializable just try out, didn't change anything) :

[Serializable]
public class FilterModel
{
      public string SearchQuery { get; set; }
      public DateTimeRange DateTimeRange { get; set; }
      public LogTypeFilter LogTypeFilter { get; set; }
}

[Serializable]
public class DateTimeRange
{
      public DateTime StartDateTime { get; set; }
      public DateTime EndDateTime { get; set; }
}

[Serializable]
public class LogTypeFilter
{
       public bool Critical { get; set; }
       public bool Error { get; set; }
       public bool Warning { get; set; }
}

Body:
The main issue your code isn't working is because of your axios post. It wasn't sending the body of the post at all. You can diagnose this in the future by looking at the payload section of a request in the browser network tab of the developer tools. e.g. in the image below, you can see it's sending the headers in post body.

You can also see on axios that there's no method that supports axios.post that sends the config as the second parameter and the data as the third parameter.

Below is the working solution with controller and html file that I used to reproduce your issue.

LogController.cs

namespace TestApplication.Controllers
{
    [ApiController]
    [Route("[controller]")]
    public class LogsController : ControllerBase
    {
        [HttpPost]
        [Route("filter")]
        public IActionResult FilterLogs([FromBody] FilterModel filter)
        {
            return Ok();
        }
    }

    [Serializable]
    public class FilterModel
    {
        public string SearchQuery { get; set; }
        public DateTimeRange DateTimeRange { get; set; }
        public LogTypeFilter LogTypeFilter { get; set; }
    }

    [Serializable]
    public class DateTimeRange
    {
        public DateTime StartDateTime { get; set; }
        public DateTime EndDateTime { get; set; }
    }

    [Serializable]
    public class LogTypeFilter
    {
        public bool Critical { get; set; }
        public bool Error { get; set; }
        public bool Warning { get; set; }
    }
}

Index.html

<html>
    <head>
        <script src="https://cdn.jsdelivr.net/npm/vue@2.6.14"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.25.0/axios.min.js" integrity="sha512-/Q6t3CASm04EliI1QyIDAA/nDo9R8FQ/BULoUFyN4n/BDdyIxeH7u++Z+eobdmr11gG5D/6nPFyDlnisDwhpYA==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
    </head>
    <body>
        <div id="app"></div>
        <script>
            new Vue({
                el: "#app",
                data() {
                    return {
                        filterModel: {
                            searchQuery: "Test",
                            dateTimeRange: {
                                startDateTime: new Date(),
                                endDateTime: new Date()
                            },
                            logTypeFilter: {
                                error: false,
                                warning: false,
                                critical: false
                            }
                        }
                    };
                },
                mounted() {
                    this.getFilteredLogs(this.filterModel);
                },
                methods: {
                    getFilteredLogs(filterModel) {
                        return axios.post("/logs/filter", this.filterModel,
                        {
                                headers: { "Content-Type": "application/json" }
                        })
                    }
                }
            })
        </script>
    </body>
</html>


问:
Can a Wildcard Search Be Performed Amongst Fields
Always grateful for the infinite wisdom from everyone on this site.

I deal with some massive databases that are often difficult to search in. One of which is a lead database with over 1.4k columns and 3 million records.

Sometimes, I just want to query to see if a certain value exists anywhere in the database within ANY field. (Like a ctrl+F in Excel) Is it possible to perform a query that searches for a particular string or integer in all records and within any field in the database? I assume this would take a lot of computing power but it would save me a lot of time instead of trying to search for the correct field I need to be using as there are multiple fields with similar names and no concrete ER Diagram

答:
Below example shows how to do so

```<code>with your_table as (
  select 1 x, 'abc' y, 'table1' z union all
  select 2, 'xyz', 'desk3'
)
select format('%t', t) record,
  contains_substr(t, 'xyz') has_xyz,
  contains_substr(t, '1') has_1,
  contains_substr(t, '3') has_3,
from your_table t
</code>```

with output

Body:
Below example shows how to do so

with your_table as (
  select 1 x, 'abc' y, 'table1' z union all
  select 2, 'xyz', 'desk3'
)
select format('%t', t) record,
  contains_substr(t, 'xyz') has_xyz,
  contains_substr(t, '1') has_1,
  contains_substr(t, '3') has_3,
from your_table t

with output


问:
Using CSV module (*no pandas*): How to print the rows in a header column?
Define the function getColumn() below that takes a column name and returns the data in that column as a list of strings to print the items in a header.

My getColumn(name) function fails and gives the error message
unhashable type:list

```<code>import csv
from csv import DictReader
from collections import defaultdict

with open('training_set_features.csv') as new_csv_file:
    new_csv_file = csv.DictReader(new_csv_file,fieldnames=headers)
    data = list(new_csv_file)

column_names = list(data[0].keys())
print("List of column names : ", column_names)

# This part of my code is where I am stuck so it is incomplete
def getColumn(name):
    empty_list=[]
    column=dict[column_names]
    for row in rows:
        return

 print(getColumn('doctor_recc_h1n1'))
</code>```

答:
The will do what's needed using something called a "list comprehension" which extracts the data for the named column from each row and returns it.

Note that because getColumn(name) is only passed one argument, the column name, it is forced it to use the global variable data. If would be better to pass it data as as a second argument to avoid needing to do that because it's generally best to avoid them as much as possible.

```<code>import csv

def getColumn(name):
    return [row[name] for row in data]

with open('training_set_features.csv', newline='') as new_csv_file:
    new_csv_file = csv.DictReader(new_csv_file)
    data = list(new_csv_file)

column_names = list(data[0].keys())
print("List of column names : ", column_names)

print(getColumn('doctor_recc_h1n1'))
</code>```

Body:
Define the function getColumn() below that takes a column name and returns the data in that column as a list of strings to print the items in a header.

My getColumn(name) function fails and gives the error message
unhashable type:list

import csv
from csv import DictReader
from collections import defaultdict

with open('training_set_features.csv') as new_csv_file:
    new_csv_file = csv.DictReader(new_csv_file,fieldnames=headers)
    data = list(new_csv_file)

column_names = list(data[0].keys())
print("List of column names : ", column_names)

# This part of my code is where I am stuck so it is incomplete
def getColumn(name):
    empty_list=[]
    column=dict[column_names]
    for row in rows:
        return

 print(getColumn('doctor_recc_h1n1'))

Body:
The will do what's needed using something called a "list comprehension" which extracts the data for the named column from each row and returns it.

Note that because getColumn(name) is only passed one argument, the column name, it is forced it to use the global variable data. If would be better to pass it data as as a second argument to avoid needing to do that because it's generally best to avoid them as much as possible.

import csv

def getColumn(name):
    return [row[name] for row in data]

with open('training_set_features.csv', newline='') as new_csv_file:
    new_csv_file = csv.DictReader(new_csv_file)
    data = list(new_csv_file)

column_names = list(data[0].keys())
print("List of column names : ", column_names)

print(getColumn('doctor_recc_h1n1'))


问:
CQRS Projection One-To-Many / Many-to-Many
Let's assume i want to create a sports event Event-Sourcing Project with CQRS.

A Team as many players

A Game has 1 winner

A Game has 2 Teams

A Game has n Events (Points are added, Fouls, Timeouts, etc.)

How would i create the projection for that?

Game with Winner

GameID
Location
TeamNameOne
TeamNameTwo
Winner
PointsTeamOne
PointsTeamTwo

1234
Munich
Avengers
Suicide Squad
Avengers
48
30

But how would i design the Team has many players projection?
With a JSON Field?

TeamID
TeamName
Players

432
Avengers
[{"name": "Man, Iron", "number": 34}, {"name": "America, Captain": "number": 1}...]

Or with a line for each player?

TeamId
TeamName
PlayerId
PlayerName

432
Avengers
34
Stark, Tony

432
Avengers
1
America, Captain

The same with Events for each Game, that could be much, depending on how granular i want to track each activity.

I thought about a DocumentBased Database for the Events in a Game, so each Game could include all the activities in one Field (Like in the Players-Column for the Teams). But then it would get complex too, because Game contains Acitvity contains Acitvity's Player

Is a GraphDB like Neo4J better for that? I think, but then i have to start creating "queries" and the projectors are not independent anymore.

And then the question for the Aggregate design. Because i am not sure if i should add a List of Player IDs in a TeamAggregate and a List of Events for a Game.

答:
I've been thinking about this issue a lot myself, and it seems to me that the more 'read-optimised' you want, the more data you have to store (and the more complex the writing becomes).

Your point about each activity containing a copy of the user record is a great example.

You could imagine on the front-end, that there is a tool-tip for each activity that happens, which when the user hovers over the tool-tip displays a link to that particular player and their profile picture.

Having that read-model 'ready-to-view' would mean potentially copying user data many times into each event.

Then if a user changes details (like a new profile picture), then you have to iterate over large data structures and update the new value across the board.  This adds a lot of complexity to making updates to this projection.

In terms of how to store this data, I'd probably go with a key-value document.  I find those well suited to displaying on a front-end because they form a hierarchal tree, which is the same as HMTL, so there is a natural mapping between the two.

Like many things in software, there are trade-offs.  The less joining and more 'ready-to-view' you want the data, the more data duplication and more complexity of keeping consistency.

You can make the joins cheaper by using key-value stores (as they have near constant lookup time).

So you could have this type of structure:

{
  gameId:'sdk',
  gameEvents: [
    {
      playerId: 'abc',
      eventType: 'FOUL',
    }
    // etc.
  ],
  players: {
    abc: {
      name: 'billy',
      profilePicture: 'billy.png',
    },
    // etc.
  }
}
```
<p>Then all your front-end has to do, is each component where the tool-tip is rendered, you can do like:</p>
<pre class="lang-html prettyprint-override"><code><div>
  <tooltip>
    <content> {{ event.eventType }} </content>
    <hover> {{ data.players[event.playerId].name }} </content>
  </tooltip>
</div>
</code>```

Body:
I've been thinking about this issue a lot myself, and it seems to me that the more 'read-optimised' you want, the more data you have to store (and the more complex the writing becomes).

Your point about each activity containing a copy of the user record is a great example.

You could imagine on the front-end, that there is a tool-tip for each activity that happens, which when the user hovers over the tool-tip displays a link to that particular player and their profile picture.

Having that read-model 'ready-to-view' would mean potentially copying user data many times into each event.

Then if a user changes details (like a new profile picture), then you have to iterate over large data structures and update the new value across the board.  This adds a lot of complexity to making updates to this projection.

In terms of how to store this data, I'd probably go with a key-value document.  I find those well suited to displaying on a front-end because they form a hierarchal tree, which is the same as HMTL, so there is a natural mapping between the two.

Like many things in software, there are trade-offs.  The less joining and more 'ready-to-view' you want the data, the more data duplication and more complexity of keeping consistency.

You can make the joins cheaper by using key-value stores (as they have near constant lookup time).

So you could have this type of structure:

{
  gameId:'sdk',
  gameEvents: [
    {
      playerId: 'abc',
      eventType: 'FOUL',
    }
    // etc.
  ],
  players: {
    abc: {
      name: 'billy',
      profilePicture: 'billy.png',
    },
    // etc.
  }
}

Then all your front-end has to do, is each component where the tool-tip is rendered, you can do like:

<div>
  <tooltip>
    <content> {{ event.eventType }} </content>
    <hover> {{ data.players[event.playerId].name }} </content>
  </tooltip>
</div>


问:
Generic C# method with type constraint does not compile
I have an extension method with a generic type constraint. To my surprise, this code does not compile.

namespace N
{
    public interface M
    {
    }

    public class X : M
    {
        public static void DoSomething()
        {
            var x = new X();
            // ERROR: CS0407 'M X.DoSomethingWith(M)' has the wrong return type
            x.Configure(DoSomethingWith);
        }

        private static M DoSomethingWith(M obj)
        {
            return obj;
        }
    }

    public static class Extensions
    {
        public static T Configure<T>(this T obj, Func<T, T> action) where T : M
        {
            return action(obj);
        }
    }
}
```
<p>A similar construct, with a <code>void</code>-typed extension method, does compile:</p>
<pre class="lang-cs prettyprint-override"><code>    public interface M
    {
    }

    public class X : M
    {
        public static void DoSomething()
        {
            var x = new X();

            // compiles fine
            x.Configure(DoSomethingWith);
        }

        private static void DoSomethingWith(M obj)
        {
        }
    }

    public static class Extensions
    {
        public static void Configure<T>(this T obj, Action<T> action) where T : M
        {
        }
    }
</code>```

What is happening here and why is the first version not valid?

答:
This is due to the variance support in delegates for matching method signatures:

This means that you can assign to delegates not only methods that have matching signatures, but also methods that return more derived types (covariance) or that accept parameters that have less derived types (contravariance) than that specified by the delegate type. This includes both generic and non-generic delegates.

x.Configure(DoSomethingWith) will be resolved at compile time as Configure<X> and the input parameter of Action<T> (and Func<T,TResult> also) is contravariant (i.e. since X is M it is fine to up-cast it for DoSomethingWith) while the return type of DoSomethingWith is not guaranteed to be X (for Func<T,TResult> case).

There are multiple solutions, for example you can explicitly specify generic type parameter for Configure as M:

x.Configure<M>(DoSomethingWith);
```
<p>Or change signature of <code>Configure</code>:</p>
<pre class="lang-cs prettyprint-override"><code>private static X DoSomethingWith(X obj) => return obj;
</code>```

Note that changing only return type of DoSomethingWith will also work due to the variance in the delegates (though may not fit your desired logic):

private static X DoSomethingWith(M obj) => obj as X ?? new X();
```

Body:
I have an extension method with a generic type constraint. To my surprise, this code does not compile.

namespace N
{
    public interface M
    {
    }

    public class X : M
    {
        public static void DoSomething()
        {
            var x = new X();
            // ERROR: CS0407 'M X.DoSomethingWith(M)' has the wrong return type
            x.Configure(DoSomethingWith);
        }

        private static M DoSomethingWith(M obj)
        {
            return obj;
        }
    }

    public static class Extensions
    {
        public static T Configure<T>(this T obj, Func<T, T> action) where T : M
        {
            return action(obj);
        }
    }
}

A similar construct, with a void-typed extension method, does compile:

    public interface M
    {
    }

    public class X : M
    {
        public static void DoSomething()
        {
            var x = new X();

            // compiles fine
            x.Configure(DoSomethingWith);
        }

        private static void DoSomethingWith(M obj)
        {
        }
    }

    public static class Extensions
    {
        public static void Configure<T>(this T obj, Action<T> action) where T : M
        {
        }
    }

What is happening here and why is the first version not valid?

Body:
This is due to the variance support in delegates for matching method signatures:

This means that you can assign to delegates not only methods that have matching signatures, but also methods that return more derived types (covariance) or that accept parameters that have less derived types (contravariance) than that specified by the delegate type. This includes both generic and non-generic delegates.

x.Configure(DoSomethingWith) will be resolved at compile time as Configure<X> and the input parameter of Action<T> (and Func<T,TResult> also) is contravariant (i.e. since X is M it is fine to up-cast it for DoSomethingWith) while the return type of DoSomethingWith is not guaranteed to be X (for Func<T,TResult> case).

There are multiple solutions, for example you can explicitly specify generic type parameter for Configure as M:

x.Configure<M>(DoSomethingWith);

Or change signature of Configure:

private static X DoSomethingWith(X obj) => return obj;

Note that changing only return type of DoSomethingWith will also work due to the variance in the delegates (though may not fit your desired logic):

private static X DoSomethingWith(M obj) => obj as X ?? new X();


问:
Found the synthetic property @state. Please include either "BrowserAnimationsModule" or "NoopAnimationsModule" in your application
I get this error when adding animations into my application.

I found: Angular 4 - Import BrowserAnimationsModule or NoopAnimationsModule. I added the entries to systemjs.config.js:

```<code>'@angular/animations': 'node_modules/@angular/animations/bundles/animations.umd.min.js',
'@angular/animations/browser':'node_modules/@angular/animations/bundles/animations-browser.umd.js',
'@angular/platform-browser/animations': 'node_modules/@angular/platform-browser/bundles/platform-browser-animations.umd.js'
</code>```

I added the imports to app.module.ts (root module):

```<code>import { NgModule }         from '@angular/core';
import { BrowserModule }    from '@angular/platform-browser';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';

@NgModule({
    imports:      [
        BrowserModule,
        BrowserAnimationsModule,
    ],
    declarations: [
      ...
    ],
    bootstrap:    [
        AppComponent
    ],
    providers:    [
        ...
    ]
})
export class AppModule { }
</code>```

And I also installed the animations package:

```<code>npm install @angular/animations@latest --save
</code>```

What might I be missing?

edit:
I know this question looks very much like an exact duplicate of the question I linked, which has various answers. Going through them didn't help though, which is why I am asking for something I am overlooking.

edit2:
I also checked Importing BrowserAnimationsModule Throws 404 - SystemJS Config Issue? which aimed at the same solutions already named in Angular 4 - Import BrowserAnimationsModule... (above)

edit3:
As the comments mentioned:
I have imported BrowserModule and BrowserAnimationsModule. The code section above was updated to reflect that.

edit4:
As I have the animations in a child module of my application, I tried all three variants: Doing the imports in the root module, importing in the child module and importing in both.

edit5:
I checked the package versions with npm outdated and, reading How to update the angular2 version to the latest, found out about this bug: npm update --save duplicates devDependencies as dependencies. I realized I had always been updating my packages with npm update --save, that's why many packages were outdated. Sadly now they are up2date but it's still not working.

```<code>Package         Current   Wanted   Latest  Location
@types/jasmine   2.5.36   2.5.36   2.5.52  kidzpointz
@types/node      6.0.78   6.0.78    8.0.1  kidzpointz
jasmine-core      2.4.1    2.4.1    2.6.4  kidzpointz
protractor       4.0.14   4.0.14    5.1.2  kidzpointz
rxjs              5.0.1    5.0.1    5.4.1  kidzpointz
systemjs        0.19.40  0.19.40  0.20.14  kidzpointz
tslint           3.15.1   3.15.1    5.4.3  kidzpointz
typescript        2.4.0    2.4.0    2.3.4  kidzpointz
</code>```

答:
I received this error because I fat-fingered the ID on a child component:

HTML:

```<code><childComp @childID ...></childComp>
</code>```

TS:

```<code>@ViewChild("childID")
myChildComp: ChildComponent;
</code>```

Of course, the HTML should have been:

```<code><childComp #childID ...></childComp>
</code>```

Body:
I get this error when adding animations into my application.

I found: Angular 4 - Import BrowserAnimationsModule or NoopAnimationsModule. I added the entries to systemjs.config.js:

'@angular/animations': 'node_modules/@angular/animations/bundles/animations.umd.min.js',
'@angular/animations/browser':'node_modules/@angular/animations/bundles/animations-browser.umd.js',
'@angular/platform-browser/animations': 'node_modules/@angular/platform-browser/bundles/platform-browser-animations.umd.js'

I added the imports to app.module.ts (root module):

import { NgModule }         from '@angular/core';
import { BrowserModule }    from '@angular/platform-browser';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';

@NgModule({
    imports:      [
        BrowserModule,
        BrowserAnimationsModule,
    ],
    declarations: [
      ...
    ],
    bootstrap:    [
        AppComponent
    ],
    providers:    [
        ...
    ]
})
export class AppModule { }

And I also installed the animations package:

npm install @angular/animations@latest --save

What might I be missing?

edit:
I know this question looks very much like an exact duplicate of the question I linked, which has various answers. Going through them didn't help though, which is why I am asking for something I am overlooking.

edit2:
I also checked Importing BrowserAnimationsModule Throws 404 - SystemJS Config Issue? which aimed at the same solutions already named in Angular 4 - Import BrowserAnimationsModule... (above)

edit3:
As the comments mentioned:
I have imported BrowserModule and BrowserAnimationsModule. The code section above was updated to reflect that.

edit4:
As I have the animations in a child module of my application, I tried all three variants: Doing the imports in the root module, importing in the child module and importing in both.

edit5:
I checked the package versions with npm outdated and, reading How to update the angular2 version to the latest, found out about this bug: npm update --save duplicates devDependencies as dependencies. I realized I had always been updating my packages with npm update --save, that's why many packages were outdated. Sadly now they are up2date but it's still not working.

Package         Current   Wanted   Latest  Location
@types/jasmine   2.5.36   2.5.36   2.5.52  kidzpointz
@types/node      6.0.78   6.0.78    8.0.1  kidzpointz
jasmine-core      2.4.1    2.4.1    2.6.4  kidzpointz
protractor       4.0.14   4.0.14    5.1.2  kidzpointz
rxjs              5.0.1    5.0.1    5.4.1  kidzpointz
systemjs        0.19.40  0.19.40  0.20.14  kidzpointz
tslint           3.15.1   3.15.1    5.4.3  kidzpointz
typescript        2.4.0    2.4.0    2.3.4  kidzpointz

Body:
I received this error because I fat-fingered the ID on a child component:

HTML:

<childComp @childID ...></childComp>

TS:

@ViewChild("childID")
myChildComp: ChildComponent;

Of course, the HTML should have been:

<childComp #childID ...></childComp>


问:
INSERT 6000 Rows - best practice
I have a PHP script that calls an API method that can easily return 6k+ results.

I use PEAR DB_DataObject to write each row in a foreach loop to the DB.

The above script is batch processing 20 users at a time - and although some will only have a few results from the API others will have more. Worst case is that all have 1000's of results.

The loop to call the API seems to be ok, batches of 20 every 5 minutes works fine. My only concern is 1000's of mysql INSERTs for each user (with a long pause between each user for fresh API calls)

Is there a good way to do this? Or am I doing it a good way?!

答:
Like Kalium said, check where the bottleneck is.
If it is really the database, you could try the bulk import feature some DBMS offer.

In DB2, for example, it is called LOAD.
It works without SQL, but reads directly from a named pipe.
It is especially designed to be fast when you need to bring a large number of new rows
into the database.
It can be configured to skip checks and index building, making it even faster.

ContentLicense: CC BY-SA 2.5

Title: INSERT 6000 Rows - best practice


问:
appMobi XDK simulated device orientation change
Is the content rendered in appMobi's device emulator supposed to respond (in the emulator) to simulated orientation changes?  Mine doesn't, and I'm wondering if that's a problem with my installation or whether that level of sophistication is not (yet) available in the emulator.</p>

答:
The XDK should throw an "appMobi.device.orientation.change" Javascript event when the simulated orientation changes.  Any other rendering changes would depend on how your HTML is structured.  Do you see that event?

Make sure to use the "Rotate Orientation" button rather than simply rotating the application using the accelerometer controls.


问:
Using innerHTML to get a whole page content
I am still a beginner in Javascript and I wondering if I can use innerHTML to post the whole HTML content from another page.
I have used innerHTML to just post an HTML code within the same .js page. For example:

I have main.js that contains this

class MyComponent extends HTMLElement {
  connectedCallback() {
this.innerHTML = `<h1>Hello world</h1>`;
  }
}

customElements.define('my-component', MyComponent);```
</div>
</div>
</p>
<p>and in the <strong>index.html</strong> I use this code to implement the main.js</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><!doctype html>
<html lang="en">
<head>
<script type="application/javascript" src="js/main.js"></script>
</head>

<body>
    <my-component></my-component>
</body>
</html></code>```

The question is can I include an HTML page instead
Hello world
 like header.html to get the whole HTML code from it? if not, Is there any way to do that?
Thanks.

Edit: I mean for example if I have a page named footer.html and in that page, I have an h1 ex. "Hello world" And I need to use the same h1 in another page index.html without rewrite it again. Can I make that h1 as a template to use in any other page using javascript?
My idea that I was looking for is:

Making main.js

get h1 from footer.html in main.js

import that script in index.html

using h1 in index.html
I know that I can do that using "include" in PHP but I am just trying to do it by javascript.

答:
You can try:

```<code>document.body.innerHTML
</code>```

to access page content.

Body:
I am still a beginner in Javascript and I wondering if I can use innerHTML to post the whole HTML content from another page.
I have used innerHTML to just post an HTML code within the same .js page. For example:

I have main.js that contains this

class MyComponent extends HTMLElement {
  connectedCallback() {
this.innerHTML = `<h1>Hello world</h1>`;
  }
}

customElements.define('my-component', MyComponent);

and in the index.html I use this code to implement the main.js

<!doctype html>

    <my-component></my-component>

The question is can I include an HTML page instead
Hello world
 like header.html to get the whole HTML code from it? if not, Is there any way to do that?
Thanks.

Edit: I mean for example if I have a page named footer.html and in that page, I have an h1 ex. "Hello world" And I need to use the same h1 in another page index.html without rewrite it again. Can I make that h1 as a template to use in any other page using javascript?
My idea that I was looking for is:

Making main.js

get h1 from footer.html in main.js

import that script in index.html

using h1 in index.html
I know that I can do that using "include" in PHP but I am just trying to do it by javascript.

Body:
You can try:

document.body.innerHTML

to access page content.


问:
Selenium Chromedriver: Unable to find an exact match for CDP version 98, so returning the closest version found: 97
Im trying to get Selenium working with Java. I'm using Maven. My pom.xml file looks like this

```<code><dependency>
  <groupId>org.seleniumhq.selenium</groupId>
  <artifactId>selenium-java</artifactId>
  <version>4.1.2</version>
</dependency>
</code>```

When i try to run my programm the following error shows up. Chrome starts but does not open any sites. Ive tried chrome webdriver version 98 97 and 96. Does my normal chrome version matter?

```<code>Starting ChromeDriver 97.0.4692.71 (adefa7837d02a07a604c1e6eff0b3a09422ab88d-refs/branch-heads/4692@{#1247}) on port 61659
Only local connections are allowed.
Please see https://chromedriver.chromium.org/security-considerations for suggestions on keeping ChromeDriver safe.
ChromeDriver was started successfully.
[1644353402.048][WARNING]: This version of ChromeDriver has not been tested with Chrome version 98.
Feb. 08, 2022 9:50:02 PM org.openqa.selenium.remote.ProtocolHandshake createSession
INFO: Detected dialect: W3C
Feb. 08, 2022 9:50:02 PM org.openqa.selenium.devtools.CdpVersionFinder findNearestMatch
WARNING: Unable to find an exact match for CDP version 98, so returning the closest version found: 97
Feb. 08, 2022 9:50:02 PM org.openqa.selenium.devtools.CdpVersionFinder findNearestMatch
INFO: Found CDP implementation for version 98 of 97
</code>```

答:
Sadly, Selenium 4.1.2 doesnt support v98 yet. Here is the changelog:

v4.1.2

Supported CDP versions: 85, 95, 96, 97

Add new desktop cast command for Chromium

...

This doesnt mean though that it wont work, in my case, it works perfectly. But yeah you may experience some stuff not working.

Body:
Im trying to get Selenium working with Java. I'm using Maven. My pom.xml file looks like this

<dependency>
  <groupId>org.seleniumhq.selenium</groupId>
  <artifactId>selenium-java</artifactId>
  <version>4.1.2</version>
</dependency>

When i try to run my programm the following error shows up. Chrome starts but does not open any sites. Ive tried chrome webdriver version 98 97 and 96. Does my normal chrome version matter?

Starting ChromeDriver 97.0.4692.71 (adefa7837d02a07a604c1e6eff0b3a09422ab88d-refs/branch-heads/4692@{#1247}) on port 61659
Only local connections are allowed.
Please see https://chromedriver.chromium.org/security-considerations for suggestions on keeping ChromeDriver safe.
ChromeDriver was started successfully.
[1644353402.048][WARNING]: This version of ChromeDriver has not been tested with Chrome version 98.
Feb. 08, 2022 9:50:02 PM org.openqa.selenium.remote.ProtocolHandshake createSession
INFO: Detected dialect: W3C
Feb. 08, 2022 9:50:02 PM org.openqa.selenium.devtools.CdpVersionFinder findNearestMatch
WARNING: Unable to find an exact match for CDP version 98, so returning the closest version found: 97
Feb. 08, 2022 9:50:02 PM org.openqa.selenium.devtools.CdpVersionFinder findNearestMatch
INFO: Found CDP implementation for version 98 of 97


问:
Ensure That Node Cron Job is Only Configured Once
I'm writing a Discord bot and having it schedule a cron job when it starts up using node-cron. I've defined it as follows (very basic so far):

```<code>    cron.schedule('15 1,3,5,7,9,11,13,15,17,19,21,23 * * *', () => {
        GameUpdater.sendGameUpdatesToLeagueChannels(this.guilds);
    });
</code>```

The problem is, Discord bots will often reconnect which will rerun the portion of the code where this has to be. I'm considering having a check of an external value, perhaps in my database, that manages whether or not it's run recently or is already running or something like that, but I was wondering if there was a proper way to make a cron job unique using node-cron?

答:
You can you use logger to keep track of restaring or starting time of your server.
You can use winston Click HERE

It will help to generate your server log so that you can read it before starting of your server, so that you can take your action. Like say adjust the time etc

Body:
I'm writing a Discord bot and having it schedule a cron job when it starts up using node-cron. I've defined it as follows (very basic so far):

    cron.schedule('15 1,3,5,7,9,11,13,15,17,19,21,23 * * *', () => {
        GameUpdater.sendGameUpdatesToLeagueChannels(this.guilds);
    });

The problem is, Discord bots will often reconnect which will rerun the portion of the code where this has to be. I'm considering having a check of an external value, perhaps in my database, that manages whether or not it's run recently or is already running or something like that, but I was wondering if there was a proper way to make a cron job unique using node-cron?


问:
How to pull stock price when each line has a different ticker and date?
I'm trying to pull the Adj Close Price for the separate Tickers and Dates below. The formula I'm using is below

```<code>new_data = []
i = 0

while True:
    if i <= len(dfh3['TICKER']):
        bio_ticker = dfh3.iloc[i,0]
        bio_lockup = dfh3.iloc[i,7]
        new_data.append(web.DataReader(bio_ticker,'yahoo',bio_lockup,bio_lockup)['Adj Close'])
        i = i +1

dfh3['Adj Close'] = new_data
</code>```

However, instead of only adding the 'Adj Close' Price. It's adding all the information pulled from DataReader (see below)

Original Dataframe:

Ticker
Lockup Date

ADGI
2022-02-02

INAB
2022-01-26

OMGA
2022-01-26

Current Output from my code:

Ticker
Lockup Date
Adj Close Price

ADGI
2022-02-02
Date 2022-02-02    7.9 Name Adj Close, dtype...

INAB
2022-01-26
Date 2022-01-26    3.19 Name Adj Close, dtype...

OMGA
2022-01-26
Date 2022-01-26    11 Name Adj Close, dtype: ..

Desired Output:

Ticker
Lockup Date
Adj Close Price

ADGI
2022-02-02
7.9

INAB
2022-01-26
3.19

OMGA
2022-01-26
11

I think the problem is stemming from the original creation of the 'new_data' list, but I'm not sure of an alternative approach.

答:
From the current output you provided it seems that every output is the same format:

"Date" space "the data" space "the price"...

So you can use the split method on the Adj Close Price string and grab the third item:

```<code>ADJ = "Date 2022-02-02 7.9 Name Adj Close, dtype...".split(" ")
print(ADJ[2])
</code>```

output:

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

You can read more about the split method here: docs for split

Body:
I'm trying to pull the Adj Close Price for the separate Tickers and Dates below. The formula I'm using is below

new_data = []
i = 0

while True:
    if i <= len(dfh3['TICKER']):
        bio_ticker = dfh3.iloc[i,0]
        bio_lockup = dfh3.iloc[i,7]
        new_data.append(web.DataReader(bio_ticker,'yahoo',bio_lockup,bio_lockup)['Adj Close'])
        i = i +1

dfh3['Adj Close'] = new_data

However, instead of only adding the 'Adj Close' Price. It's adding all the information pulled from DataReader (see below)

Original Dataframe:

Ticker
Lockup Date

ADGI
2022-02-02

INAB
2022-01-26

OMGA
2022-01-26

Current Output from my code:

Ticker
Lockup Date
Adj Close Price

ADGI
2022-02-02
Date 2022-02-02    7.9 Name Adj Close, dtype...

INAB
2022-01-26
Date 2022-01-26    3.19 Name Adj Close, dtype...

OMGA
2022-01-26
Date 2022-01-26    11 Name Adj Close, dtype: ..

Desired Output:

Ticker
Lockup Date
Adj Close Price

ADGI
2022-02-02
7.9

INAB
2022-01-26
3.19

OMGA
2022-01-26
11

I think the problem is stemming from the original creation of the 'new_data' list, but I'm not sure of an alternative approach.

Body:
From the current output you provided it seems that every output is the same format:

"Date" space "the data" space "the price"...

So you can use the split method on the Adj Close Price string and grab the third item:

ADJ = "Date 2022-02-02 7.9 Name Adj Close, dtype...".split(" ")
print(ADJ[2])

output:

7.9

You can read more about the split method here: docs for split


问:
Drawing on bitmap vs directly on canvas
In my application I need to draw a large network (basically, little boxes connected with lines) and the user will be able to zoom and pan it around.

My first option was to draw the network directly to the canvas, but I thought that was not very efficient, because each time a pan event occurs, the drawing process begins again.

So I tried to use a large mutable bitmap and draw my entire network only once (or at least whenever zoom occurs), and blit the necessary areas to the canvas.

My problem is, since the network is rather big, I get OOM exception when creating the bitmap…

What should I do? Draw directly to the canvas? Use several smaller bitmaps?

Thanks,
Direz

答:
My first question to you is how many sprites you have going at once? By far, the fastest mechanism for having many sprites on the screen is to use OpenGL due to the hardware accelleration. The besy way, on Android, I have found to do this is to use the Cocos2d android (not to be confused with the ios version) which is available on Google Projects. You will have to use the IOS documentation in order to understand it though and there are a few decent tutorials to get started with online..in particular, the hello world template here... Www.sketchydroide.com/Blog/p?=8. It is out of date compared to the latest IOS cocos2d but thats to be expected. I have found that the programs run MUCH faster when not connected to an active debugger session in my experiments.

If you want to stick with your current approach or the above is still not fast enough, you are going to have to attempt to cull any drawing which does not appear n the screen meaning a general function of the form "if the sprite's x and y values are outside the bounds of the visible area, dont draw it" which is basically how most tile base games handle the issue.

It sounds like you are doing the drawing manually if you are doing little squares. I think it is more adviseable to go ahead and draw on the canvas but to be very careful about managing your sprite counts and to avoid heavy for loop iteratiins that occur on
the frame update loops where possible. It is rather easy to max out your little handset with drawing operations.

Another option might be to draw the entire bitmap once into memory and then use a copy rectangle operation to transfer the image to the screen without drawing the full bitmap you have created. I think that copy rect should be a fast operation normally but if you are using it to draw the whole screen it seems like overkill and probably wont work as well.

Title: Drawing on bitmap vs directly on canvas


问:
TicTacToe Heavy Win Condition
I made a TicTacToe game in Ruby. I am pretty new to Ruby OOP. My win conditions for checking row, column and diagonals are really heavy and they take too much code line and look pretty horrible. My code also always repeating.

So my question is how to implement the below win conditions into my code?

 WIN_COMBINATIONS = [
[0,1,2], # top_row
[3,4,5], # middle_row
[6,7,8], # bottom_row
[0,3,6], # left_column
[1,4,7], # center_column
[2,5,8], # right_column
[0,4,8], # left_diagonal
[6,4,2] # right_diagonal
]
```
<p>Here is my win conditions:</p>
<pre class="lang-rb prettyprint-override"><code>module CheckWinner
  def check_horizontal(player1, player2)
    player1_win = false
    player2_win = false
    @board.each do |row|
      player1_win = row.all?(player1)
      player2_win = row.all?(player2)
      break if player1_win || player2_win
    end
    puts "#{player1} won!" if player1_win
    puts "#{player2} won!" if player2_win
    player1_win || player2_win
  end

  def check_vertical(player1, player2)
    player1_win = false
    player2_win = false
    @board.transpose.each do |row|
      player1_win = row.all?(player1)
      player2_win = row.all?(player2)
      break if player1_win || player2_win
    end
    puts "#{player1} won!" if player1_win
    puts "#{player2} won!" if player2_win
    player1_win || player2_win
  end

  def check_diagonal(player1, player2)
    if @board[0][0] == player1 && board[1][1] == player1 && board[2][2] == player1 ||
       @board[0][2] == player1 && board[1][1] == player1 && board[2][0] == player1
      puts "#{@player1} won!"
      true

    elsif @board[0][0] == player2 && board[1][1] == player2 && board[2][2] == player2 ||
          @board[0][2] == player2 && board[1][1] == player2 && board[2][0] == player2
      puts "#{@player2} won!"
      true
    end
  end
end
</code>```

I invoke these conditions from this line of code:

def game
    choosing_player
    loop do
      player1(@player1)
      break if check_vertical(@player1,@player2) == true || check_diagonal(@player1,@player2) == true || check_horizontal(@player1,@player2) == true || full?

      player2(@player2)
      break if check_vertical(@player1,@player2) == true || check_diagonal(@player1,@player2) == true || check_horizontal(@player1,@player2) == true || full?
    end
  end
end

```
<p>Here is my full of project that it is correctly working.</p>
<pre class="lang-rb prettyprint-override"><code>module CheckWinner
  def check_horizontal(player1, player2)
    player1_win = false
    player2_win = false
    @board.each do |row|
      player1_win = row.all?(player1)
      player2_win = row.all?(player2)
      break if player1_win || player2_win
    end
    puts "#{player1} won!" if player1_win
    puts "#{player2} won!" if player2_win
    player1_win || player2_win
  end

  def check_vertical(player1, player2)
    player1_win = false
    player2_win = false
    @board.transpose.each do |row|
      player1_win = row.all?(player1)
      player2_win = row.all?(player2)
      break if player1_win || player2_win
    end
    puts "#{player1} won!" if player1_win
    puts "#{player2} won!" if player2_win
    player1_win || player2_win
  end

  def check_diagonal(player1, player2)
    if @board[0][0] == player1 && board[1][1] == player1 && board[2][2] == player1 ||
       @board[0][2] == player1 && board[1][1] == player1 && board[2][0] == player1
      puts "#{@player1} won!"
      true

    elsif @board[0][0] == player2 && board[1][1] == player2 && board[2][2] == player2 ||
          @board[0][2] == player2 && board[1][1] == player2 && board[2][0] == player2
      puts "#{@player2} won!"
      true
    end
  end
end

# TicTacToe Board
class Board
  include CheckWinner
  attr_accessor :board

  def initialize
    @board = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
  end

  def print_board
    puts '-------------'
    @board.each do |row|
      print '|'
      row.each do |col|
        print " #{col}"
        print ' | '
      end
      puts
    end
    puts '-------------'
  end

  def twodimentional_board
    @board = @board.each_slice(3).map { |el| el }
  end

  def occupied_error(value)
    puts 'There is a value or wrong place! Try Again!'
    twodimentional_board
    print_board
    value == @player1 ? player2(@player1) : player1(@player2) # Stay same player
  end

  def move_if_possible(place, value)
    @board.flatten!
    if @board[place - 1] == 'X' || @board[place - 1] == 'O' || !place.between?(1, 9)
      occupied_error(value)
    else
      @board[place - 1] = value
      twodimentional_board
      @board
    end
  end

  def full?
    if @board.flatten.all?(String)
      puts 'Draw!'
      true
    end
  end

  def choosing_player
    puts 'Choose for Player1(X or O)'
    loop do
      @player1 = gets.chomp!
      break if @player1 == 'X' || @player1 == 'O'

      puts 'Try Again!(X or O)'
    end
    puts "Player 1 is: #{@player1}"

    @player1 == 'X' ? @player2 = 'O' : @player2 = 'X'
    puts "Player 2 is: #{@player2}"
    print_board
  end

  def player1(player1)
    puts "Choice #{player1} Place on a board(1 to 10)"
    @place = gets.chomp!.to_i
    move_if_possible(@place, player1)
    print_board
  end

  def player2(player2)
    puts "Choice #{player2} Place on a board(1 to 10)"
    @place = gets.chomp!.to_i
    move_if_possible(@place, player2)
    print_board
  end

  def game
    choosing_player
    loop do
      player1(@player1)
      break if check_vertical(@player1,@player2) == true || check_diagonal(@player1,@player2) == true || check_horizontal(@player1,@player2) == true || full?

      player2(@player2)
      break if check_vertical(@player1,@player2) == true || check_diagonal(@player1,@player2) == true || check_horizontal(@player1,@player2) == true || full?
    end
  end
end

board = Board.new
board.game
</code>```

If you want to live preview here is repl link

答:
Here's a different approach to determining if the board indicates a win, and if it does, who wins.

Let board be an array of three elements, each an array of three elements, each element being 'X', 'O' or '_', the last indicating the cell has not yet been marked.

Let's create some methods.

```<code>def row_win?(board)
  board.each { |row| return row.first if row_uniq.size == 1 }
  nil
end
</code>```

This method returns 'X' if 'X' wins in a row, 'O' if 'O' wins in a row and nil if neither player wins in a row.

```<code>def column_win?(board)
  row_win?(board.transpose)
end
</code>```

This method similarly returns 'X', 'O' or nil, indicating if there is a win in a column, and if so, who wins.

```<code>def diagonal_win?(board)
  row_win? [[board[0][0], board[1][1], board[2][2]],
            [board[0][2], board[1][1], board[2][0]]]
end
</code>```

This method does the same for the two diagonals.

Lastly,

```<code>def win?(board)
  row_win?(board) || column_win?(board) || diagonal_win?(board)
end
</code>```

nil is returned if there is no winner.

Let's try it.

```<code>win? [['X', '_', 'X'],
      ['_', 'X', 'O'],
      ['X', 'O', 'O']]
  #=> 'X'
</code>```

```<code>win? [['X', 'O', 'X'],
      ['_', 'O', 'X'],
      ['X', 'O', 'O']]
  #=> 'O'
</code>```

```<code>win? [['X', 'O', 'X'],
      ['O', 'O', 'X'],
      ['X', 'X', 'O']]
  #=> nil

</code>```

Title: TicTacToe Heavy Win Condition

Body:
I made a TicTacToe game in Ruby. I am pretty new to Ruby OOP. My win conditions for checking row, column and diagonals are really heavy and they take too much code line and look pretty horrible. My code also always repeating.

So my question is how to implement the below win conditions into my code?

 WIN_COMBINATIONS = [
[0,1,2], # top_row
[3,4,5], # middle_row
[6,7,8], # bottom_row
[0,3,6], # left_column
[1,4,7], # center_column
[2,5,8], # right_column
[0,4,8], # left_diagonal
[6,4,2] # right_diagonal
]

Here is my win conditions:

module CheckWinner
  def check_horizontal(player1, player2)
    player1_win = false
    player2_win = false
    @board.each do |row|
      player1_win = row.all?(player1)
      player2_win = row.all?(player2)
      break if player1_win || player2_win
    end
    puts "#{player1} won!" if player1_win
    puts "#{player2} won!" if player2_win
    player1_win || player2_win
  end

  def check_vertical(player1, player2)
    player1_win = false
    player2_win = false
    @board.transpose.each do |row|
      player1_win = row.all?(player1)
      player2_win = row.all?(player2)
      break if player1_win || player2_win
    end
    puts "#{player1} won!" if player1_win
    puts "#{player2} won!" if player2_win
    player1_win || player2_win
  end

  def check_diagonal(player1, player2)
    if @board[0][0] == player1 && board[1][1] == player1 && board[2][2] == player1 ||
       @board[0][2] == player1 && board[1][1] == player1 && board[2][0] == player1
      puts "#{@player1} won!"
      true

    elsif @board[0][0] == player2 && board[1][1] == player2 && board[2][2] == player2 ||
          @board[0][2] == player2 && board[1][1] == player2 && board[2][0] == player2
      puts "#{@player2} won!"
      true
    end
  end
end

I invoke these conditions from this line of code:

def game
    choosing_player
    loop do
      player1(@player1)
      break if check_vertical(@player1,@player2) == true || check_diagonal(@player1,@player2) == true || check_horizontal(@player1,@player2) == true || full?

      player2(@player2)
      break if check_vertical(@player1,@player2) == true || check_diagonal(@player1,@player2) == true || check_horizontal(@player1,@player2) == true || full?
    end
  end
end

Here is my full of project that it is correctly working.

module CheckWinner
  def check_horizontal(player1, player2)
    player1_win = false
    player2_win = false
    @board.each do |row|
      player1_win = row.all?(player1)
      player2_win = row.all?(player2)
      break if player1_win || player2_win
    end
    puts "#{player1} won!" if player1_win
    puts "#{player2} won!" if player2_win
    player1_win || player2_win
  end

  def check_vertical(player1, player2)
    player1_win = false
    player2_win = false
    @board.transpose.each do |row|
      player1_win = row.all?(player1)
      player2_win = row.all?(player2)
      break if player1_win || player2_win
    end
    puts "#{player1} won!" if player1_win
    puts "#{player2} won!" if player2_win
    player1_win || player2_win
  end

  def check_diagonal(player1, player2)
    if @board[0][0] == player1 && board[1][1] == player1 && board[2][2] == player1 ||
       @board[0][2] == player1 && board[1][1] == player1 && board[2][0] == player1
      puts "#{@player1} won!"
      true

    elsif @board[0][0] == player2 && board[1][1] == player2 && board[2][2] == player2 ||
          @board[0][2] == player2 && board[1][1] == player2 && board[2][0] == player2
      puts "#{@player2} won!"
      true
    end
  end
end

# TicTacToe Board
class Board
  include CheckWinner
  attr_accessor :board

  def initialize
    @board = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
  end

  def print_board
    puts '-------------'
    @board.each do |row|
      print '|'
      row.each do |col|
        print " #{col}"
        print ' | '
      end
      puts
    end
    puts '-------------'
  end

  def twodimentional_board
    @board = @board.each_slice(3).map { |el| el }
  end

  def occupied_error(value)
    puts 'There is a value or wrong place! Try Again!'
    twodimentional_board
    print_board
    value == @player1 ? player2(@player1) : player1(@player2) # Stay same player
  end

  def move_if_possible(place, value)
    @board.flatten!
    if @board[place - 1] == 'X' || @board[place - 1] == 'O' || !place.between?(1, 9)
      occupied_error(value)
    else
      @board[place - 1] = value
      twodimentional_board
      @board
    end
  end

  def full?
    if @board.flatten.all?(String)
      puts 'Draw!'
      true
    end
  end

  def choosing_player
    puts 'Choose for Player1(X or O)'
    loop do
      @player1 = gets.chomp!
      break if @player1 == 'X' || @player1 == 'O'

      puts 'Try Again!(X or O)'
    end
    puts "Player 1 is: #{@player1}"

    @player1 == 'X' ? @player2 = 'O' : @player2 = 'X'
    puts "Player 2 is: #{@player2}"
    print_board
  end

  def player1(player1)
    puts "Choice #{player1} Place on a board(1 to 10)"
    @place = gets.chomp!.to_i
    move_if_possible(@place, player1)
    print_board
  end

  def player2(player2)
    puts "Choice #{player2} Place on a board(1 to 10)"
    @place = gets.chomp!.to_i
    move_if_possible(@place, player2)
    print_board
  end

  def game
    choosing_player
    loop do
      player1(@player1)
      break if check_vertical(@player1,@player2) == true || check_diagonal(@player1,@player2) == true || check_horizontal(@player1,@player2) == true || full?

      player2(@player2)
      break if check_vertical(@player1,@player2) == true || check_diagonal(@player1,@player2) == true || check_horizontal(@player1,@player2) == true || full?
    end
  end
end

board = Board.new
board.game

If you want to live preview here is repl link

Body:
Here's a different approach to determining if the board indicates a win, and if it does, who wins.

Let board be an array of three elements, each an array of three elements, each element being 'X', 'O' or '_', the last indicating the cell has not yet been marked.

Let's create some methods.

def row_win?(board)
  board.each { |row| return row.first if row_uniq.size == 1 }
  nil
end

This method returns 'X' if 'X' wins in a row, 'O' if 'O' wins in a row and nil if neither player wins in a row.

def column_win?(board)
  row_win?(board.transpose)
end

This method similarly returns 'X', 'O' or nil, indicating if there is a win in a column, and if so, who wins.

def diagonal_win?(board)
  row_win? [[board[0][0], board[1][1], board[2][2]],
            [board[0][2], board[1][1], board[2][0]]]
end

This method does the same for the two diagonals.

Lastly,

def win?(board)
  row_win?(board) || column_win?(board) || diagonal_win?(board)
end

nil is returned if there is no winner.

Let's try it.

win? [['X', '_', 'X'],
      ['_', 'X', 'O'],
      ['X', 'O', 'O']]
  #=> 'X'

win? [['X', 'O', 'X'],
      ['_', 'O', 'X'],
      ['X', 'O', 'O']]
  #=> 'O'

win? [['X', 'O', 'X'],
      ['O', 'O', 'X'],
      ['X', 'X', 'O']]
  #=> nil


问:
Google analytics anonymous ip
I'm working on some wordpress sites, using the Divi theme. I have added this code in the head (Divi -> integration):

```<code>window.dataLayer = window.dataLayer || [];
  function gtag(){dataLayer.push(arguments);}
  gtag('js', new Date());
gtag('config', '<GA_TRACKING_ID>', { 'anonymize_ip': true });
</code>```

I have replaced '<GA_TRACKING_ID>' with the right id.

When I inspect it to see if it works, I can't find aip=1. It only says "ep.anonymize_ip: true" at the end of the Request Url and the Query String Parameter inside the collect...>.

Does this make the IP anonymous?

答: if you use Google Analytics 4, or the one with the code in this pattern G-XXXXXXX (instead of UA-XXXXXXX-XX), you don't have to specify the anonymize_ip since it is already active by default.

Title: Google analytics anonymous ip

Body:
I'm working on some wordpress sites, using the Divi theme. I have added this code in the head (Divi -> integration):

window.dataLayer = window.dataLayer || [];
  function gtag(){dataLayer.push(arguments);}
  gtag('js', new Date());
gtag('config', '<GA_TRACKING_ID>', { 'anonymize_ip': true });

I have replaced '<GA_TRACKING_ID>' with the right id.

When I inspect it to see if it works, I can't find aip=1. It only says "ep.anonymize_ip: true" at the end of the Request Url and the Query String Parameter inside the collect...>.

Does this make the IP anonymous?