问:
Modifying array from asynchronous call not modifying the array swift
I'm trying to modify an array of objects that I retrieve from an asynchronous call with the results from another asynchronous call.  Basically I retrieve an array of results and there is a field messages that is returned nil from my server call.  I then need to make another server call with the id of each result in a for loop to get the messages array. I then set the messages to the returned value.

I just learned about using DispatchGroup() about 20 minutes ago from https://stackoverflow.com/a/48718976/3272438, so bear with me.

The issue I get is that when I do print("C0: (self.res)") it prints out all of the items including the messages I just added.  When print("C2: (self.res)") prints in the group.notify(...), all of the messages fields print out nil.  I'm stumped and I have tried everything I could think of. Any help would be much appreciated.

UPDATE
By changing the following group.notify() never gets called

```<code>Service.getMessages(resultId: self.res![index].id, completionHandler: { (latestMessage, response, error) in

        if let latestMessage = latestMessage {
            self.res![index].messages = [latestMessage]
            print("L2: \(self.res![index].messages)")
            print("C0: \(self.res)")
        }
        group.leave() // continue the loop
    })
</code>```

ViewController.Swift

```<code>var res: [ResultDTO]?

override func viewDidLoad() {
    super.viewDidLoad()

    let group0 = DispatchGroup()

    group0.enter()
    Service.getResults { (results, response, error) in
        guard var results = results else { print("PROBLEM"); return }
        self.res = results
        group0.leave()
    }

    group0.notify(queue: .main) {
        print("in group0")
        let group = DispatchGroup() // initialize
        for index in 0..<self.res!.count {
            group.enter() // wait
            Service.getMessages(resultId: self.res![index].id, completionHandler: { (latestMessage, response, error) in

                if let latestMessage = latestMessage {
                    self.res![index].messages = [latestMessage]
                    print("L2: \(self.res![index].messages)")
                    print("C0: \(self.res)")
                }

            })
            group.leave() // continue the loop
        }

        group.notify(queue: .main) {
            print("In group notify")

            do {
                print("C2: \(self.res)")
                for index in 0..< self.res!.count {
                    print("L4: \(self.res![index].messages)")
                }
                // ... configure my view with the data
            } catch {
                print("Error: \(error)")
            }

        }
    }

}
</code>```

答:
I would simplify your data handling by using one dispatch group (since one is all you need):

```<code>class YourViewController: UIViewController {

    private var results: [ResultDTO]?

    override func viewDidLoad() {
        super.viewDidLoad()
        getResults()
    }

    private func getResults() {

        Service.getResults { (results, response, error) in

            guard let results = results,
                results.count > 0 else {
                    return
            }

            let dispatchGroup = DispatchGroup()

            for r in results {

                dispatchGroup.enter()
                Service.getMessages(resultId: r.id, completionHandler: { (latestMessage, response, error) in

                    if let latestMessage = latestMessage {
                        r.messages = [latestMessage]
                    }
                    dispatchGroup.leave()

                }

            }

            dispatchGroup.notify(queue: .main, execute: {
                self.results = results
            })

        }

    }

}
</code>```

Consider this only a starting point. If this were production code, I'd implement error handling and background queueing (assuming the data is returned on the main thread).

Body:
I'm trying to modify an array of objects that I retrieve from an asynchronous call with the results from another asynchronous call.  Basically I retrieve an array of results and there is a field messages that is returned nil from my server call.  I then need to make another server call with the id of each result in a for loop to get the messages array. I then set the messages to the returned value.

I just learned about using DispatchGroup() about 20 minutes ago from https://stackoverflow.com/a/48718976/3272438, so bear with me.

The issue I get is that when I do print("C0: (self.res)") it prints out all of the items including the messages I just added.  When print("C2: (self.res)") prints in the group.notify(...), all of the messages fields print out nil.  I'm stumped and I have tried everything I could think of. Any help would be much appreciated.

UPDATE
By changing the following group.notify() never gets called

Service.getMessages(resultId: self.res![index].id, completionHandler: { (latestMessage, response, error) in

        if let latestMessage = latestMessage {
            self.res![index].messages = [latestMessage]
            print("L2: \(self.res![index].messages)")
            print("C0: \(self.res)")
        }
        group.leave() // continue the loop
    })

ViewController.Swift

var res: [ResultDTO]?

override func viewDidLoad() {
    super.viewDidLoad()

    let group0 = DispatchGroup()

    group0.enter()
    Service.getResults { (results, response, error) in
        guard var results = results else { print("PROBLEM"); return }
        self.res = results
        group0.leave()
    }

    group0.notify(queue: .main) {
        print("in group0")
        let group = DispatchGroup() // initialize
        for index in 0..<self.res!.count {
            group.enter() // wait
            Service.getMessages(resultId: self.res![index].id, completionHandler: { (latestMessage, response, error) in

                if let latestMessage = latestMessage {
                    self.res![index].messages = [latestMessage]
                    print("L2: \(self.res![index].messages)")
                    print("C0: \(self.res)")
                }

            })
            group.leave() // continue the loop
        }

        group.notify(queue: .main) {
            print("In group notify")

            do {
                print("C2: \(self.res)")
                for index in 0..< self.res!.count {
                    print("L4: \(self.res![index].messages)")
                }
                // ... configure my view with the data
            } catch {
                print("Error: \(error)")
            }

        }
    }

}

Body:
I would simplify your data handling by using one dispatch group (since one is all you need):

class YourViewController: UIViewController {

    private var results: [ResultDTO]?

    override func viewDidLoad() {
        super.viewDidLoad()
        getResults()
    }

    private func getResults() {

        Service.getResults { (results, response, error) in

            guard let results = results,
                results.count > 0 else {
                    return
            }

            let dispatchGroup = DispatchGroup()

            for r in results {

                dispatchGroup.enter()
                Service.getMessages(resultId: r.id, completionHandler: { (latestMessage, response, error) in

                    if let latestMessage = latestMessage {
                        r.messages = [latestMessage]
                    }
                    dispatchGroup.leave()

                }

            }

            dispatchGroup.notify(queue: .main, execute: {
                self.results = results
            })

        }

    }

}

Consider this only a starting point. If this were production code, I'd implement error handling and background queueing (assuming the data is returned on the main thread).


来源: stackexchange

问:
Why Oracle changes rowid with fetch?
I have a query like this:

```<code>select w.rowid, w.waclogin
  from tableA w, tableB wa, tableC a
 where wa.alucod = a.alucod
   and w.waclogin = wa.waclogin
   and a.cpf = '31808013875'
   and rownum <= 1;
</code>```

The results are:

```<code>ROWID               WACLOGIN
AAA0CEAHSAABE07ABA  31808013875
</code>```

But when I use fetch (for performance) the rowid returned is different:

```<code>select w.rowid, w.waclogin
  from tableA w, tableB wa, tableC a
 where wa.alucod = a.alucod
   and w.waclogin = wa.waclogin
   and a.cpf = '31808013875'
 fetch first row only;
</code>```

Results in:

```<code>ROWID               WACLOGIN
AAA0DMAHaAAA+ZcAAX  31808013875
</code>```

Why fetch changes the rowid?
For me this no makes sense.

Update

When fetch is used, that row id returned is from table B, instead of table A.

答: There are two rows in tableA with the same wacLogin value (but obviously different rowID values).  Neither of your queries specifies an order by so which of those rows is returned is arbitrary.  Presumably, there is a slightly different query plan being used for both queries so each one returns a different arbitrary row.  Of course, tomorrow, either or both queries could start returning a different arbitrary row if the query plan or physical organization of the table changes.  If you want the same row to be returned in both cases, you'd need to make both queries deterministic with an order by clause that uniquely orders the results.

ContentLicense: CC BY-SA 4.0

Title: Why Oracle changes rowid with fetch?

Body:
I have a query like this:

select w.rowid, w.waclogin
  from tableA w, tableB wa, tableC a
 where wa.alucod = a.alucod
   and w.waclogin = wa.waclogin
   and a.cpf = '31808013875'
   and rownum <= 1;

The results are:

ROWID               WACLOGIN
AAA0CEAHSAABE07ABA  31808013875

But when I use fetch (for performance) the rowid returned is different:

select w.rowid, w.waclogin
  from tableA w, tableB wa, tableC a
 where wa.alucod = a.alucod
   and w.waclogin = wa.waclogin
   and a.cpf = '31808013875'
 fetch first row only;

Results in:

ROWID               WACLOGIN
AAA0DMAHaAAA+ZcAAX  31808013875

Why fetch changes the rowid?
For me this no makes sense.

Update

When fetch is used, that row id returned is from table B, instead of table A.


问:
Given long git commit how to safely get short commit
If I query the bitbucket api for commits, I get the long version:

```<code>bitbucket_curl(){
    curl -H 'Authorization:Basic YW1JyKg==' "https://api.bitbucket.org$@"
}

commits="$(bitbucket_curl '/2.0/repositories/interos/datavana/commits/alex/dockerize?pagelen=3')"

latest_commit="$(echo "$commits" | jq -r '.values[0].hash')"
</code>```

given a long commit: c56cefbd0c81142558cf814cba7d7cd75d7cb6a7

is there a way to reliably get the short commit hash? Isn't it like the last 10 chars or something? Or perhaps there is a way to request the short hash from the Bitbucket API? On that subject I am looking for a reliable way to get the most recent commit for a branch.

答:
I don't know the Bitbucket API well, and whether or not its endpoints require the full SHA-1 hash, but as far as I know there is no official short version of commit hash.  The only general requirement is that the fragment of a hash used can correctly resolve to just a single commit.

Bitbucket web seems to display only the first 7 characters of the SHA-1 hash.  There are roughly 78 billion different hashes of length 7, so it would be unlikely to have a collision on a single page.

Body:
If I query the bitbucket api for commits, I get the long version:

bitbucket_curl(){
    curl -H 'Authorization:Basic YW1JyKg==' "https://api.bitbucket.org$@"
}

commits="$(bitbucket_curl '/2.0/repositories/interos/datavana/commits/alex/dockerize?pagelen=3')"

latest_commit="$(echo "$commits" | jq -r '.values[0].hash')"

given a long commit: c56cefbd0c81142558cf814cba7d7cd75d7cb6a7

is there a way to reliably get the short commit hash? Isn't it like the last 10 chars or something? Or perhaps there is a way to request the short hash from the Bitbucket API? On that subject I am looking for a reliable way to get the most recent commit for a branch.


问:
How to wait on a error/close event for a socket with asyncio?
I am using a networking library who provides a wrapper for using its coroutine functions with asyncio. When I wrote a test that randomly closes the connection (to see if my program is resilient under bad conditions), I found that it hangs indefinitely.

It seemed like a bug in the wrapper provided by the library I was using, because the program hangs waiting on the callback from either loop.add_reader() or loop.add_writer(), but then I could not find how to be notified when the socket is closed.

This is a minimal program that shows what is happening with my program:

```<code>import asyncio
import socket

async def kill_later(c):
    await asyncio.sleep(0.1)
    c.close()

async def main():
    loop = asyncio.get_running_loop()

    c = socket.create_connection(('www.google.com', 80))
    c.setblocking(0)

    ev = asyncio.Event()
    loop.add_reader(c, ev.set)

    # Closes the socket after 0.1 ms:
    asyncio.create_task(kill_later(c))

    print("waiting...")

    #### ↓ THIS WAITS FOREVER ↓ ####
    await ev.wait()

asyncio.run(main())
</code>```

My question: how to be notified a socket is closed by the asyncio loop?

EDIT: due to popular demand, made the socket non-blocking, but it makes no difference, because add_reader() doesn't try to perform any IO on the socket, merely watches for when it is ready.

答:
The issue, at least with your example, is that your socket never receives anything, hence the event is never set. The docs mention in an example:

Wait until a file descriptor received some data using the
  loop.add_reader() method and then close the event loop

In order for your example to work, you'll have to send a request to Google first:

```<code>c = socket.create_connection(('www.google.com', 80))
c.sendall("GET /\r\n".encode())
</code>```

This will set the event, that you await later in your main coro.

epoll considers a file descriptor ready to read if data becomes available on it or if an EOF is signalled, as described in this answer.

add_writer() does not block in such a situation, because a file descriptor is considered ready to write as long as there is still space available on the input buffer.

Calling recv(), as I mentioned in the previous revision of my answer, is not required.

Body:
I am using a networking library who provides a wrapper for using its coroutine functions with asyncio. When I wrote a test that randomly closes the connection (to see if my program is resilient under bad conditions), I found that it hangs indefinitely.

It seemed like a bug in the wrapper provided by the library I was using, because the program hangs waiting on the callback from either loop.add_reader() or loop.add_writer(), but then I could not find how to be notified when the socket is closed.

This is a minimal program that shows what is happening with my program:

import asyncio
import socket

async def kill_later(c):
    await asyncio.sleep(0.1)
    c.close()

async def main():
    loop = asyncio.get_running_loop()

    c = socket.create_connection(('www.google.com', 80))
    c.setblocking(0)

    ev = asyncio.Event()
    loop.add_reader(c, ev.set)

    # Closes the socket after 0.1 ms:
    asyncio.create_task(kill_later(c))

    print("waiting...")

    #### ↓ THIS WAITS FOREVER ↓ ####
    await ev.wait()

asyncio.run(main())

My question: how to be notified a socket is closed by the asyncio loop?

EDIT: due to popular demand, made the socket non-blocking, but it makes no difference, because add_reader() doesn't try to perform any IO on the socket, merely watches for when it is ready.

Body:
The issue, at least with your example, is that your socket never receives anything, hence the event is never set. The docs mention in an example:

Wait until a file descriptor received some data using the
  loop.add_reader() method and then close the event loop

In order for your example to work, you'll have to send a request to Google first:

c = socket.create_connection(('www.google.com', 80))
c.sendall("GET /\r\n".encode())

This will set the event, that you await later in your main coro.

epoll considers a file descriptor ready to read if data becomes available on it or if an EOF is signalled, as described in this answer.

add_writer() does not block in such a situation, because a file descriptor is considered ready to write as long as there is still space available on the input buffer.

Calling recv(), as I mentioned in the previous revision of my answer, is not required.


问:
In MYSQL, is it possible to SELECT something that will be defined in the WHERE clause?
I have a system which contains items that may each belong to more than one parent. I need to be able to retrieve all of an item's children, and it's children's children.. ad nauseam. OK well there are 5 levels.

Each item has (or should have) a json column named "belongs_to_json" (also more columns such as "id" and whatnot) which contains each parent, order combination. e.g. [{"parent": 2, "order": 4},{"parent": 13, "order": 1}]

I can search for this and others with the same parent by combining PHP and MYSQL (idea found on stackoverflow previously)

First I run a query (codeigniter framework) getting some item parents and put the query in a $qry_classes variable.

```<code>    $sql_classes = "SELECT t.id
    FROM table t
    WHERE JSON_SEARCH(t.belongs_to_json, 'all', '2') LIKE '%.parent%';";
    $qry_classes = $this->db->query($sql_classes);
</code>```

Then I use the results from that query to write a new WHERE statement.

```<code>    $s_rewrite_array = array_map(function($row) {
    return "JSON_SEARCH(t.belongs_to_json, 'all', '{$row->id}') LIKE '%.parent%'";
    }, $qry_classes->return_array() );
    $sections_condition = implode(" OR ", $s_rewrite_array);
    $sql_sections = "
        SELECT  t.id
        FROM    table t
        WHERE   ($sections_condition)
    ";
    $qry_sections = $this->db->query($sql_sections);
</code>```

The problem comes when I have an item with multiple parents and I want to return the parent that was used in the WHERE clause in the SELECT clause.

Something like

```<code>    SELECT t.*, non_existant_column FROM table t WHERE
    JSON_SEARCH(t.belongs_to_json, 'all', '{$row->id}' as non_existant_column) LIKE '%.parent%;
</code>```

obviously not a real thing but I'm hoping there is an equivalent. Or maybe different way to solve the issue.

答:
You can just use put a literal in the SELECT list, you don't need to get it from the WHERE clause.

```<code>SELECT t.*, '{$row->id}' AS parent
FROM table t
WHERE JSON_SEARCH(t.belongs_to_json, 'all', '{$row->id}') LIKE '%.parent%;
</code>```

If you're using MySQL 8.0, you can probably use JSON_TABLE to find parent: 2 instead of your method. See MySQL Return JSON array index based on property value

Body:
I have a system which contains items that may each belong to more than one parent. I need to be able to retrieve all of an item's children, and it's children's children.. ad nauseam. OK well there are 5 levels.

Each item has (or should have) a json column named "belongs_to_json" (also more columns such as "id" and whatnot) which contains each parent, order combination. e.g. [{"parent": 2, "order": 4},{"parent": 13, "order": 1}]

I can search for this and others with the same parent by combining PHP and MYSQL (idea found on stackoverflow previously)

First I run a query (codeigniter framework) getting some item parents and put the query in a $qry_classes variable.

    $sql_classes = "SELECT t.id
    FROM table t
    WHERE JSON_SEARCH(t.belongs_to_json, 'all', '2') LIKE '%.parent%';";
    $qry_classes = $this->db->query($sql_classes);

Then I use the results from that query to write a new WHERE statement.

    $s_rewrite_array = array_map(function($row) {
    return "JSON_SEARCH(t.belongs_to_json, 'all', '{$row->id}') LIKE '%.parent%'";
    }, $qry_classes->return_array() );
    $sections_condition = implode(" OR ", $s_rewrite_array);
    $sql_sections = "
        SELECT  t.id
        FROM    table t
        WHERE   ($sections_condition)
    ";
    $qry_sections = $this->db->query($sql_sections);

The problem comes when I have an item with multiple parents and I want to return the parent that was used in the WHERE clause in the SELECT clause.

Something like

    SELECT t.*, non_existant_column FROM table t WHERE
    JSON_SEARCH(t.belongs_to_json, 'all', '{$row->id}' as non_existant_column) LIKE '%.parent%;

obviously not a real thing but I'm hoping there is an equivalent. Or maybe different way to solve the issue.

Body:
You can just use put a literal in the SELECT list, you don't need to get it from the WHERE clause.

SELECT t.*, '{$row->id}' AS parent
FROM table t
WHERE JSON_SEARCH(t.belongs_to_json, 'all', '{$row->id}') LIKE '%.parent%;

If you're using MySQL 8.0, you can probably use JSON_TABLE to find parent: 2 instead of your method. See MySQL Return JSON array index based on property value


问:
Why won't my self.init autofill in a convenience initializer?
I don't know if this is important or not, but this takes place in an extension.

Anyways, my teacher today had us create a convenience initializer in an extension to our model. When he demonstrated, Xcode's autofill filled in the initializer for him, but gave me nothing. I asked about that, but we couldn't figure it out. Some of us in the class had it work while others didn't.

Essentially, we had this:

extension Entry {

    //existing initializer
    convenience init(title: String, body: String) {
        self.init()
        self.title = title
        self.body = body
    }

    // new initializer we were creating
    convenience init(representation: EntryRepresentation) {
        // this next line would **NOT** autofill no matter what I tried
        // (both waiting, backing up and retyping a little, or hitting esc)
        // it wouldn't even show other, non convenience inits
        self.init(title: representation.title, body: representation.body)
    }
}
```

答:
Later, after a bit of troubleshooting (trust me, cleaning the build folder is ineffective here), I realized that our teacher was working off a template he had from Swift 4.2 days and hadn't updated the template to Swift 5, while I had started a new project and was using Swift 5 as my compiler version. Upon toggling this in Xcode, 4.2 made the autofill work, while 5 broke it.

Obviously, toggling this buried setting is a poopy workaround for this issue, so here's a decent workaround:

In my case, I would write out:

Entry.init(

...which will give me my autofill options

use autofill to get

Entry.init(title: <#String#>, body: <#String#>)

Just replace the class name with "self" to get

self.init(title: <#String#>, body: <#String#>)


问:
Essentially a 2 dimensional Enum?
Not sure how to phrase this, but I have a class called Lane for different lanes of a road.

A Lane has two parts - the Direction (an Enum of left or right or other) and then the number, an integer. So lanes look like this: L1, L2, R1, R3 etc..

There should only be one instance of the lane class for each lane. L1 shouldn't exist twice.

Because of this, I want to be able to assign the Lane of an object the way you can assign an enum, by typing Lane.L1 or Lane.R4 etc.. I currently have to use a method which finds the existing Lane object that corresponds to the Lane I'm trying to reference.

Is this a way to do this better? Like by simply typing lane = Lane.L1, other than making the Lane class have private constructors and manually creating a public Getter for each possible Lane and assigning references in a static constructor for the Lane class?

This is the current state of the lane class:

```<code>public enum Direction { INCREASING = 1, DECREASING = 2, BOTH = 3, OTHER = 4, UNSPECIFIED = 5 }
public class Lane : IComparable
{
    public Direction Direction;
    public int Number = 1;
    public Lane(Direction direction, int number = 1)
    {
        Direction = direction;
        Number = number;
    }

    public override string ToString()
    {
        if (Direction == Direction.UNSPECIFIED)
        {
            return Direction.AsCharLR().ToString();
        }
        return Direction.AsCharLR() + Number.ToString();
    }

    public override bool Equals(object obj)
    {
        if (obj is Lane)
        {
            Lane l = obj as Lane;
            return Direction == l.Direction && Number == l.Number;
        }
        return false;
    }

    public override int GetHashCode()
    {
        return (int)Direction * 100 + Number;
    }

    public static Lane Parse(char lane)
    {
        lane = char.ToUpper(lane);
        switch (lane)
        {
            case 'L':
            case 'I':
                return new Lane(Direction.INCREASING);
            case 'R':
            case 'D':
                return new Lane(Direction.DECREASING);
            case 'B':
                return new Lane(Direction.BOTH);
            case 'U':
                return new Lane(Direction.UNSPECIFIED);
            case 'O':
            default:
                return new Lane(Direction.OTHER);
        }
    }
    public static Lane Parse(string text)
    {
        Lane lane = Parse(text[0]);
        lane.Number = int.Parse(text.Substring(1));
        return lane;
    }

    public int CompareTo(object l)
    {
        return GetHashCode() - l.GetHashCode();
    }
}
</code>```

答:
Ok, you said you didn't want private constructors, but what if you had public static attributes, like the following?:

```<code>public class Lane
{
    private Direction direction;
    private int number;

    public static Lane L1 = new Lane(Direction.INCREASING, 1);
    public static Lane L2 = new Lane(Direction.INCREASING, 2);
    //add more ...

    private Lane() { }

    private Lane(Direction d, int n)
    {
        this.direction = d;
        this.number = n;
    }

    public enum Direction
    {
        INCREASING = 1, DECREASING = 2, BOTH = 3, OTHER = 4, UNSPECIFIED = 5
    }
}
</code>```

This way you can type lane = Lane.L1, and it always return the same instance.
Is this enough?

Title: Essentially a 2 dimensional Enum?

Body:
Not sure how to phrase this, but I have a class called Lane for different lanes of a road.

A Lane has two parts - the Direction (an Enum of left or right or other) and then the number, an integer. So lanes look like this: L1, L2, R1, R3 etc..

There should only be one instance of the lane class for each lane. L1 shouldn't exist twice.

Because of this, I want to be able to assign the Lane of an object the way you can assign an enum, by typing Lane.L1 or Lane.R4 etc.. I currently have to use a method which finds the existing Lane object that corresponds to the Lane I'm trying to reference.

Is this a way to do this better? Like by simply typing lane = Lane.L1, other than making the Lane class have private constructors and manually creating a public Getter for each possible Lane and assigning references in a static constructor for the Lane class?

This is the current state of the lane class:

public enum Direction { INCREASING = 1, DECREASING = 2, BOTH = 3, OTHER = 4, UNSPECIFIED = 5 }
public class Lane : IComparable
{
    public Direction Direction;
    public int Number = 1;
    public Lane(Direction direction, int number = 1)
    {
        Direction = direction;
        Number = number;
    }

    public override string ToString()
    {
        if (Direction == Direction.UNSPECIFIED)
        {
            return Direction.AsCharLR().ToString();
        }
        return Direction.AsCharLR() + Number.ToString();
    }

    public override bool Equals(object obj)
    {
        if (obj is Lane)
        {
            Lane l = obj as Lane;
            return Direction == l.Direction && Number == l.Number;
        }
        return false;
    }

    public override int GetHashCode()
    {
        return (int)Direction * 100 + Number;
    }

    public static Lane Parse(char lane)
    {
        lane = char.ToUpper(lane);
        switch (lane)
        {
            case 'L':
            case 'I':
                return new Lane(Direction.INCREASING);
            case 'R':
            case 'D':
                return new Lane(Direction.DECREASING);
            case 'B':
                return new Lane(Direction.BOTH);
            case 'U':
                return new Lane(Direction.UNSPECIFIED);
            case 'O':
            default:
                return new Lane(Direction.OTHER);
        }
    }
    public static Lane Parse(string text)
    {
        Lane lane = Parse(text[0]);
        lane.Number = int.Parse(text.Substring(1));
        return lane;
    }

    public int CompareTo(object l)
    {
        return GetHashCode() - l.GetHashCode();
    }
}

Body:
Ok, you said you didn't want private constructors, but what if you had public static attributes, like the following?:

public class Lane
{
    private Direction direction;
    private int number;

    public static Lane L1 = new Lane(Direction.INCREASING, 1);
    public static Lane L2 = new Lane(Direction.INCREASING, 2);
    //add more ...

    private Lane() { }

    private Lane(Direction d, int n)
    {
        this.direction = d;
        this.number = n;
    }

    public enum Direction
    {
        INCREASING = 1, DECREASING = 2, BOTH = 3, OTHER = 4, UNSPECIFIED = 5
    }
}

This way you can type lane = Lane.L1, and it always return the same instance.
Is this enough?


问:
Running Google BigQuery sample network analysis script, I get a syntax error: Was expecting: <EOF>
I am trying to use sample code  for Google BigQuery.  The query is in legacy SQL.

I have this set in BigQuery query:

SELECT
  a.name,
  b.name,
  COUNT(*) AS count
FROM (FLATTEN(
    SELECT
      GKGRECORDID,
      UNIQUE(REGEXP_REPLACE(SPLIT(V2Persons,';'), r',.*', "))
name
FROM [gdelt-bq:gdeltv2.gkg]
WHERE DATE>20150302000000 and DATE < 20150304000000 and V2Persons like
'%Tsipras%'
,name)) a
JOIN EACH (
SELECT GKGRECORDID, UNIQUE(REGEXP_REPLACE(SPLIT(V2Persons,';'), r',.*', ")) name
    FROM
      [gdelt-bq:gdeltv2.gkg]
    WHERE
      DATE>20150302000000
      AND DATE < 20150304000000
      AND V2Persons LIKE '%Tsipras%')) b
ON
  a.GKGRECORDID=b.GKGRECORDID
WHERE
  a.name<b.name
GROUP EACH BY
  1,
  2
ORDER BY
  3 DESC
LIMIT
  250
```

But it raises the error:

Error: Encountered " "ON" "ON "" at line 11, column 1. Was expecting:

答:
Not sure 100% if this is exactly what you expected  - but at least from syntax prospective the fix is below

```<code>SELECT a.name, b.name, COUNT(*) AS COUNT
FROM (FLATTEN(
SELECT GKGRECORDID, UNIQUE(REGEXP_REPLACE(SPLIT(V2Persons,';'), r',.*', ''))
name
FROM [gdelt-bq:gdeltv2.gkg]
WHERE DATE>20150302000000 AND DATE < 20150304000000 AND V2Persons LIKE
'%Tsipras%'
,name)) a
JOIN EACH (
SELECT GKGRECORDID, UNIQUE(REGEXP_REPLACE(SPLIT(V2Persons,';'), r',.*', ''))
name
FROM [gdelt-bq:gdeltv2.gkg]
WHERE DATE>20150302000000 AND DATE < 20150304000000 AND V2Persons LIKE
'%Tsipras%') b
ON a.GKGRECORDID=b.GKGRECORDID
WHERE a.name<b.name
GROUP EACH BY 1,2
ORDER BY 3 DESC
LIMIT 250
</code>```

Fixes are in line 3, 10 and 14

In lines 3 and 10 - I replaced " with ''

In line 14 - I removed extra )

I am not sure with line 14 - as it might be that openning ( is actually missing

Body:
I am trying to use sample code  for Google BigQuery.  The query is in legacy SQL.

I have this set in BigQuery query:

SELECT
  a.name,
  b.name,
  COUNT(*) AS count
FROM (FLATTEN(
    SELECT
      GKGRECORDID,
      UNIQUE(REGEXP_REPLACE(SPLIT(V2Persons,';'), r',.*', "))
name
FROM [gdelt-bq:gdeltv2.gkg]
WHERE DATE>20150302000000 and DATE < 20150304000000 and V2Persons like
'%Tsipras%'
,name)) a
JOIN EACH (
SELECT GKGRECORDID, UNIQUE(REGEXP_REPLACE(SPLIT(V2Persons,';'), r',.*', ")) name
    FROM
      [gdelt-bq:gdeltv2.gkg]
    WHERE
      DATE>20150302000000
      AND DATE < 20150304000000
      AND V2Persons LIKE '%Tsipras%')) b
ON
  a.GKGRECORDID=b.GKGRECORDID
WHERE
  a.name<b.name
GROUP EACH BY
  1,
  2
ORDER BY
  3 DESC
LIMIT
  250

But it raises the error:

Error: Encountered " "ON" "ON "" at line 11, column 1. Was expecting:

Body:
Not sure 100% if this is exactly what you expected  - but at least from syntax prospective the fix is below

SELECT a.name, b.name, COUNT(*) AS COUNT
FROM (FLATTEN(
SELECT GKGRECORDID, UNIQUE(REGEXP_REPLACE(SPLIT(V2Persons,';'), r',.*', ''))
name
FROM [gdelt-bq:gdeltv2.gkg]
WHERE DATE>20150302000000 AND DATE < 20150304000000 AND V2Persons LIKE
'%Tsipras%'
,name)) a
JOIN EACH (
SELECT GKGRECORDID, UNIQUE(REGEXP_REPLACE(SPLIT(V2Persons,';'), r',.*', ''))
name
FROM [gdelt-bq:gdeltv2.gkg]
WHERE DATE>20150302000000 AND DATE < 20150304000000 AND V2Persons LIKE
'%Tsipras%') b
ON a.GKGRECORDID=b.GKGRECORDID
WHERE a.name<b.name
GROUP EACH BY 1,2
ORDER BY 3 DESC
LIMIT 250

Fixes are in line 3, 10 and 14

In lines 3 and 10 - I replaced " with ''

In line 14 - I removed extra )

I am not sure with line 14 - as it might be that openning ( is actually missing


问:
Screen scraping web page after delay
I'm trying to scrape a web page using C#, however after the page loads, it executes some JavaScript which loads more elements into the DOM which I need to scrape. A standard scraper simply grabs the html of the page on load and doesn't pick up the DOM changes made via JavaScript. How do I put in some sort of functionality to wait for a second or two and then grab the source?

Here is my current code:

private string ScrapeWebpage(string url, DateTime? updateDate)
{
    HttpWebRequest request = null;
    HttpWebResponse response = null;
    Stream responseStream = null;
    StreamReader reader = null;
    string html = null;
    try
    {
        //create request (which supports http compression)
        request = (HttpWebRequest)WebRequest.Create(url);
        request.Pipelined = true;
        request.Headers.Add(HttpRequestHeader.AcceptEncoding, "gzip,deflate");
        if (updateDate != null)
            request.IfModifiedSince = updateDate.Value;
        //get response.
        response = (HttpWebResponse)request.GetResponse();
        responseStream = response.GetResponseStream();
        if (response.ContentEncoding.ToLower().Contains("gzip"))
            responseStream = new GZipStream(responseStream,
                CompressionMode.Decompress);
        else if (response.ContentEncoding.ToLower().Contains("deflate"))
            responseStream = new DeflateStream(responseStream,
                CompressionMode.Decompress);
        //read html.
        reader = new StreamReader(responseStream, Encoding.Default);
        html = reader.ReadToEnd();
    }
    catch
    {
        throw;
    }
    finally
    {
        //dispose of objects.
        request = null;
        if (response != null)
        {
            response.Close();
            response = null;
        }
        if (responseStream != null)
        {
            responseStream.Close();
            responseStream.Dispose();
        }
        if (reader != null)
        {
            reader.Close();
            reader.Dispose();
        }
    }
    return html;
}
```

Here's a sample URL:

http://www.realtor.com/realestateandhomes-search/geneva_ny#listingType-any/pg-4

You'll see when the page first loads it says 134 listings found, then after a second it says 187 properties found.

答: The answer to this similar question says to use a web browser control to read the page in and process it before scraping it. Perhaps with some kind of timer delay to give the javascript some time to execute and return results.</p>

Title: Screen scraping web page after delay

Body:
I'm trying to scrape a web page using C#, however after the page loads, it executes some JavaScript which loads more elements into the DOM which I need to scrape. A standard scraper simply grabs the html of the page on load and doesn't pick up the DOM changes made via JavaScript. How do I put in some sort of functionality to wait for a second or two and then grab the source?

Here is my current code:

private string ScrapeWebpage(string url, DateTime? updateDate)
{
    HttpWebRequest request = null;
    HttpWebResponse response = null;
    Stream responseStream = null;
    StreamReader reader = null;
    string html = null;
    try
    {
        //create request (which supports http compression)
        request = (HttpWebRequest)WebRequest.Create(url);
        request.Pipelined = true;
        request.Headers.Add(HttpRequestHeader.AcceptEncoding, "gzip,deflate");
        if (updateDate != null)
            request.IfModifiedSince = updateDate.Value;
        //get response.
        response = (HttpWebResponse)request.GetResponse();
        responseStream = response.GetResponseStream();
        if (response.ContentEncoding.ToLower().Contains("gzip"))
            responseStream = new GZipStream(responseStream,
                CompressionMode.Decompress);
        else if (response.ContentEncoding.ToLower().Contains("deflate"))
            responseStream = new DeflateStream(responseStream,
                CompressionMode.Decompress);
        //read html.
        reader = new StreamReader(responseStream, Encoding.Default);
        html = reader.ReadToEnd();
    }
    catch
    {
        throw;
    }
    finally
    {
        //dispose of objects.
        request = null;
        if (response != null)
        {
            response.Close();
            response = null;
        }
        if (responseStream != null)
        {
            responseStream.Close();
            responseStream.Dispose();
        }
        if (reader != null)
        {
            reader.Close();
            reader.Dispose();
        }
    }
    return html;
}

Here's a sample URL:

http://www.realtor.com/realestateandhomes-search/geneva_ny#listingType-any/pg-4

You'll see when the page first loads it says 134 listings found, then after a second it says 187 properties found.

ContentLicense: CC BY-SA 3.0


问:
Show entries of cache via Spring Boots Actuator Endpoint /caches
I have a Spring Boot application with Actuator and Caching running.
When I call

```<code>http://localhost:8080/actuator/caches/myCacheName
</code>```

I only get some basic information about target, name and cacheManager.

But I want to see all entries of this particular cache.

So is it possible to customize this endpoint that it gives me more information?

答:
you can customize current endpoints by extending them. This is an example using the @EndpointWebExtension annotation to extend the standard info actuator endpoint with more functionality.

example is taken from here:
Extend actuator endpoints

Here is springs official documentation about extending endpoints:
Spring extending endpoints

```<code>@Component
@EndpointWebExtension(endpoint = InfoEndpoint.class)
public class InfoWebEndpointExtension {

    private InfoEndpoint delegate;

    // standard constructor

    @ReadOperation
    public WebEndpointResponse<Map> info() {
        Map<String, Object> info = this.delegate.info();
        Integer status = getStatus(info);
        return new WebEndpointResponse<>(info, status);
    }

    private Integer getStatus(Map<String, Object> info) {
        // return 5xx if this is a snapshot
        return 200;
    }
}
</code>```

Body:
I have a Spring Boot application with Actuator and Caching running.
When I call

http://localhost:8080/actuator/caches/myCacheName

I only get some basic information about target, name and cacheManager.

But I want to see all entries of this particular cache.

So is it possible to customize this endpoint that it gives me more information?

Body:
you can customize current endpoints by extending them. This is an example using the @EndpointWebExtension annotation to extend the standard info actuator endpoint with more functionality.

example is taken from here:
Extend actuator endpoints

Here is springs official documentation about extending endpoints:
Spring extending endpoints

@Component
@EndpointWebExtension(endpoint = InfoEndpoint.class)
public class InfoWebEndpointExtension {

    private InfoEndpoint delegate;

    // standard constructor

    @ReadOperation
    public WebEndpointResponse<Map> info() {
        Map<String, Object> info = this.delegate.info();
        Integer status = getStatus(info);
        return new WebEndpointResponse<>(info, status);
    }

    private Integer getStatus(Map<String, Object> info) {
        // return 5xx if this is a snapshot
        return 200;
    }
}


问:
How do I create a javascript function that add html elements dynamically?
I’m trying to creat a javascript function that adds new html elements, with new ID's for each element. for example this form; To let the user submit languages he can speak and his level on each one. But he can add a new input to type other languages if he speaks many.

```<code><form id="form">
Language spoken1: <input id="language1">
Level: <input id="level1">
<form>
<input type="button" value="add new language" id="add" onclick="myFunction">
</code>```

To get a result like this

```<code><form id="form">
Language spoken1: <input id="language1">
Level: <input id="level1">
Language spoken2: <input id="language2">
Level: <input id="level2">
<form>
<input type="button" value="add new language" id="add" onclick="myFunction">
</code>```

And when he submit result like this will be on the page

Language spoken1: English, level: native
Language spoken2: Spanish, level: good

答:
Each time you click the button, it will create two input elements, count the existing inputs and find the number of new input-ids. I've also added auto-focus to input, after adding... and delete button)

(function(){

let form = document.getElementById('form');

document.getElementById('add').addEventListener('click', function(){
  let lang  = document.createElement('input');
  let level = document.createElement('input');
  let number = document.querySelectorAll('#form input').length / 2 + 1;

  lang.id = 'language' + number;
  level.id = 'level' + number;

  lang.placeholder = 'Language spoken' + number;
  level.placeholder = 'Level';

  form.innerHTML += '
';
  form.appendChild(lang);
  form.appendChild(level);

  lang.focus();
});

document.getElementById('delete').addEventListener('click', function(){
  let inp = document.querySelectorAll('#form input');
  if(inp.length == 2){ return; }
  /* removing last two elements */
  inp[inp.length-1].remove();
  inp[inp.length-2].remove();

  let br = document.querySelectorAll('#form br');
  br[br.length-1].remove();
});

})();```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#delete {
  color: white;
  background-color: #c00;
  border: 2px solid #c00;
  outline: none;
  cursor: pointer;
}
#form {white-space: inherit;}
input {margin: 2px 5px;}</code>```

<form id="form">
  <input id="language1" placeholder="Language spoken1"><input id="level1" placeholder="Level">
</form>

<input type="button" value="add a new language" id="add">
<input type="button" value="X" id="delete">```

Any questions?)

Body:
I’m trying to creat a javascript function that adds new html elements, with new ID's for each element. for example this form; To let the user submit languages he can speak and his level on each one. But he can add a new input to type other languages if he speaks many.

<form id="form">
Language spoken1: <input id="language1">
Level: <input id="level1">
<form>
<input type="button" value="add new language" id="add" onclick="myFunction">

To get a result like this

<form id="form">
Language spoken1: <input id="language1">
Level: <input id="level1">
Language spoken2: <input id="language2">
Level: <input id="level2">
<form>
<input type="button" value="add new language" id="add" onclick="myFunction">

And when he submit result like this will be on the page

Language spoken1: English, level: native
Language spoken2: Spanish, level: good

Body:
Each time you click the button, it will create two input elements, count the existing inputs and find the number of new input-ids. I've also added auto-focus to input, after adding... and delete button)

(function(){

let form = document.getElementById('form');

document.getElementById('add').addEventListener('click', function(){
  let lang  = document.createElement('input');
  let level = document.createElement('input');
  let number = document.querySelectorAll('#form input').length / 2 + 1;

  lang.id = 'language' + number;
  level.id = 'level' + number;

  lang.placeholder = 'Language spoken' + number;
  level.placeholder = 'Level';

  form.innerHTML += '<br>';
  form.appendChild(lang);
  form.appendChild(level);

  lang.focus();
});

document.getElementById('delete').addEventListener('click', function(){
  let inp = document.querySelectorAll('#form input');
  if(inp.length == 2){ return; }
  /* removing last two elements */
  inp[inp.length-1].remove();
  inp[inp.length-2].remove();

  let br = document.querySelectorAll('#form br');
  br[br.length-1].remove();
});

})();

#delete {
  color: white;
  background-color: #c00;
  border: 2px solid #c00;
  outline: none;
  cursor: pointer;
}
#form {white-space: inherit;}
input {margin: 2px 5px;}

<form id="form">
  <input id="language1" placeholder="Language spoken1"><input id="level1" placeholder="Level">
</form>

<br>

<input type="button" value="add a new language" id="add">
<input type="button" value="X" id="delete">

Any questions?)


问:
Writing data classes with builder pattern
I have a data class which uses a builder to create the object and stores the data in a buffer in serialized form. I am planning to change the class to add and remove some fields. There are systems that will use both version of the class to create data i.e. the current version with all fields and newer version with removed/added fields. I am trying to see what is the best way to do this so that this is backward compatible(without breaking any consumer)?

I have couple of suggestions on how to do this but I am having a difficult time to pick one over the other.

Requirements:

The data stored has to be in binary.

Length of serialized record is same in both versions

Existing code

```<code>public class A implements Comparable<A>, Serializable {

private final Buffer buffer;
public static final Builder {
  private Header header//header with version
  private long creationTime;
  private SomeObject someObject;//this is removed in next version
  private OtherObject otherObject;//this is added in next version

  public Builder() { }

 //bunch of getters setters for fields

  public A build() {return new A(this);}

  private A(Builder b) {
   //build the object and put into the buffer
   validate()
  }
  private void validate() {//validates the object}

  public A(Buffer buf) {
   this.buffer=buf;
   validate();
  }
  public A(String encodedString) {
   this(ByteBuffer.wrap(encodedString));
  }
}
// consumers use this to get creationTime for object A
public long getCreationTime() {
 return buffer.getLong(OFFSET_CREATION_DATE);
}
}

</code>```

Solution1: add new fields in the builder and use version in the header to decide which fields to use at build time (in build method) to create the object. Problem with this approach is that all the methods will exist at compile time to the consumers and unless they test their code every object will be valid. So it will be difficult to reason about which fields are required for which version at build time.

Solution2: Add a new builder in the class with the fields that you want. There will be duplicate fields that are in the existing builder.
Consumers can then use the builder that they want. This seems to be cleaner because builders will be completely independent. Problem with this approach is that since we are adding and removing fields, fields will be at different offsets so the getters will have to change to use an offset based on versionType. This is also problematic for future versions because then we will have this gigantic class with lots of builders and logic in getters for every version

Solution3: Create a new class (let's say B) that extends A and have its own builder. This way the code is more modular. Problem is that now there will need to be some logic somewhere to differentiate and know which constructor to call. For example , if a consumer is passing base64 to get an object A, it will need to figure out which version it is.

```<code>String encodedString = "someString form of A"
A a = new A(encodedString);
</code>```

Is there a recommended way to code these data classes with builder patterns to make it both future and backwards compatible.

答:
Aproach 2 combined with aproach 1 + correct binary representation is the answere. Choosing correct format for your binary representation, the simplest thing would be to pick up json . Make concrete builders for V1 and V2 object and use the byte buffer to construct them. Each builder/Factory would be interested only in the fields it recognizes. You may consider using a version field if a builder/factory attempts to deserialize wrong version exception may be thrown. The concrete builder/factory will be build only objects of the version it recognizes.

Subclassing is unnessessary in my opinion. You can separate the Builder/factory class from the object class. See "StreamSerializer" from Hazelcast as an example, completly external class to the entity dedicated only to doing marshaling.

Using proper format will fix your problem with offset from Aproach two.  If you must have it in binary form then a workaround would be to use flat format where record size is bigger than nessesary and you have reserved free space for changes. In the old Cobol days this is how they were doing it. I don't recommend you to do that though. Use json :) it is simplest may be not most effecient. You can also check https://developers.google.com/protocol-buffers/ protocol buffers.

Depending on what layout you choose for serialization when demarshaling you may configure chain of responsibility that attempts to deserialize a stream portion. When you deprecate a version, the marshaler will be just removed/deactivated from the chain.

Body:
I have a data class which uses a builder to create the object and stores the data in a buffer in serialized form. I am planning to change the class to add and remove some fields. There are systems that will use both version of the class to create data i.e. the current version with all fields and newer version with removed/added fields. I am trying to see what is the best way to do this so that this is backward compatible(without breaking any consumer)?

I have couple of suggestions on how to do this but I am having a difficult time to pick one over the other.

Requirements:

The data stored has to be in binary.

Length of serialized record is same in both versions

Existing code

public class A implements Comparable, Serializable {

private final Buffer buffer;
public static final Builder {
  private Header header//header with version
  private long creationTime;
  private SomeObject someObject;//this is removed in next version
  private OtherObject otherObject;//this is added in next version

  public Builder() { }

 //bunch of getters setters for fields

  public A build() {return new A(this);}

  private A(Builder b) {
   //build the object and put into the buffer
   validate()
  }
  private void validate() {//validates the object}

  public A(Buffer buf) {
   this.buffer=buf;
   validate();
  }
  public A(String encodedString) {
   this(ByteBuffer.wrap(encodedString));
  }
}
// consumers use this to get creationTime for object A
public long getCreationTime() {
 return buffer.getLong(OFFSET_CREATION_DATE);
}
}

Solution1: add new fields in the builder and use version in the header to decide which fields to use at build time (in build method) to create the object. Problem with this approach is that all the methods will exist at compile time to the consumers and unless they test their code every object will be valid. So it will be difficult to reason about which fields are required for which version at build time.

Solution2: Add a new builder in the class with the fields that you want. There will be duplicate fields that are in the existing builder.
Consumers can then use the builder that they want. This seems to be cleaner because builders will be completely independent. Problem with this approach is that since we are adding and removing fields, fields will be at different offsets so the getters will have to change to use an offset based on versionType. This is also problematic for future versions because then we will have this gigantic class with lots of builders and logic in getters for every version

Solution3: Create a new class (let's say B) that extends A and have its own builder. This way the code is more modular. Problem is that now there will need to be some logic somewhere to differentiate and know which constructor to call. For example , if a consumer is passing base64 to get an object A, it will need to figure out which version it is.

String encodedString = "someString form of A"
A a = new A(encodedString);

Is there a recommended way to code these data classes with builder patterns to make it both future and backwards compatible.


问:
How can I use a remote GPU for hardware accelerated 3D rendering?
I know how to use VirtualGL to remotely connect to a server and run OpenGL applications. VirtualGL allows the 2D elements of the graphic application to pass from the server machine to the client machine through the SSH connection, but intercepts the 3D elements and renders them on the server machine and then sends the images in the form of a stream to the client X Server.

But I want to be able to run graphics applications installed on the client machine in such a manner that the 2D elements are rendered locally, while the 3D commands are sent after encapsulation through a high speed network to the server where they are rendered, and the images in the form of a stream are then sent back. Is there an existing solution or a configuration of VirtualGL that works in this manner?

答:
I think it's impossible with VirtualGL. VirtualGL works by intercepting GLX calls, redirecting them to a another Xorg server, rendering frames using GL_ARB_pixel_buffer_object extension, and sending compressed images over network to client.

VirtualGL does not solve the issue of sending GLX calls over network.

I tried "indirect rendering", but there are many problems:

It's disabled by default, due to security issues,

Performance is terrible,

It doesn't provide GL_ARB_pixel_buffer_object extension required by VirtualGL.


问:
Is there a ready utility for web sites to collect user information?
The basic requirement is in look and feel.

It should look professional,have an good user interface.

I don't know if someone has already developed such a tool especially for doing this kind of job.

答:
Check out http://wufoo.com/

Like the survey packages mentioned, this is a hosted service. But Wufoo prvoides generic HTML forms and other predefined web data collection templates. It lets you create your form or select one of their predesigned forms, it gives you javascript or HTML snippet to embed the form in your web page, and it gives you online tools to review and report on the submitted data.

On a programming site like this, most folks would just write their own web app to do this, but Wufoo and other sites offer comparable solutions for non-programmers.

ContentLicense: CC BY-SA 2.5


问:
tearing when plotting polygons with holes in ggplot2
I'm trying to plot these body maps and can't get the face to show correctly. The "heads" are made up of two polygons: one is the face (solid oval) and the other is the rest of the head (donut-shaped, hole in the center). These should be colored based on the value of the "score" column. I've tried so many variations on where the group=group gets placed and the fill=scale.

```<code>  ggplot(data=Patients, aes(y=lat,
                            x=long,
                            fill=factor(score),
                            group=group))+
    geom_polygon(color="black")+
    facet_wrap(~Patient,
               ncol = 5)+
    scale_fill_manual(values=scoreColor)+
    coord_fixed()
</code>```

Any help would be appreciated.

I've included my attempt at a reproducible example below.

```<code>library(ggplot2)
fortifyResults <-read.table(header=T, stringsAsFactors = F, text="
                  long  lat order   hole    piece   group   id  score
                  1 1   1   FALSE   1   Outer.1 Outer   20
                  1 4   2   FALSE   1   Outer.1 Outer   20
                  4 4   3   FALSE   1   Outer.1 Outer   20
                  4 1   4   FALSE   1   Outer.1 Outer   20
                  1 1   5   FALSE   1   Outer.1 Outer   20
                  2 2   6   TRUE    2   Outer.2 Outer   20
                  3 2   7   TRUE    2   Outer.2 Outer   20
                  3 3   8   TRUE    2   Outer.2 Outer   20
                  2 3   9   TRUE    2   Outer.2 Outer   20
                  2 2   10  TRUE    2   Outer.2 Outer   20
                  2 2   11  FALSE   1   Inner.1 Inner   10
                  2 3   12  FALSE   1   Inner.1 Inner   10
                  3 3   13  FALSE   1   Inner.1 Inner   10
                  3 2   14  FALSE   1   Inner.1 Inner   10
                  2 2   15  FALSE   1   Inner.1 Inner   10
                  ")
</code>```

This version of the code doesn't show both pieces (even though they are in the legend)

```<code>ggplot(data=fortifyResults, aes(y=lat, x=long, group=group))+
  geom_polygon(aes(fill=factor(score)),color="black")
</code>```

And this one causes tearing

```<code>ggplot(data=fortifyResults, aes(y=lat, x=long), group=group)+
  geom_polygon(aes(fill=factor(score)),color="black")
</code>```

I read that the direction of the points makes a difference. This is how the direction comes out.

```<code>ggplot(data= fortifyResults, aes(y=lat, x=long, group=group))+
  geom_polygon(fill="yellow", color="black")+
  geom_text(aes(label=order),hjust=0, vjust=-0.3)+
  facet_wrap(~id)
</code>```

Again, the one titled "outer" here should have a hole in the middle (hole==TRUE). From what I've read, they should go in the other direction. I've tried inverting the logic, changing the direction of the points, and a bunch of other stuff. I hope you folks can help.

答:
```<code>library(ggpolypath)

ggplot(data = fortifyResults, aes(y = lat, x = long, group = group)) +
    geom_polypath(aes(fill = factor(score)), color = "black")
</code>```

Body:
I'm trying to plot these body maps and can't get the face to show correctly. The "heads" are made up of two polygons: one is the face (solid oval) and the other is the rest of the head (donut-shaped, hole in the center). These should be colored based on the value of the "score" column. I've tried so many variations on where the group=group gets placed and the fill=scale.

  ggplot(data=Patients, aes(y=lat,
                            x=long,
                            fill=factor(score),
                            group=group))+
    geom_polygon(color="black")+
    facet_wrap(~Patient,
               ncol = 5)+
    scale_fill_manual(values=scoreColor)+
    coord_fixed()

Any help would be appreciated.

I've included my attempt at a reproducible example below.

library(ggplot2)
fortifyResults <-read.table(header=T, stringsAsFactors = F, text="
                  long  lat order   hole    piece   group   id  score
                  1 1   1   FALSE   1   Outer.1 Outer   20
                  1 4   2   FALSE   1   Outer.1 Outer   20
                  4 4   3   FALSE   1   Outer.1 Outer   20
                  4 1   4   FALSE   1   Outer.1 Outer   20
                  1 1   5   FALSE   1   Outer.1 Outer   20
                  2 2   6   TRUE    2   Outer.2 Outer   20
                  3 2   7   TRUE    2   Outer.2 Outer   20
                  3 3   8   TRUE    2   Outer.2 Outer   20
                  2 3   9   TRUE    2   Outer.2 Outer   20
                  2 2   10  TRUE    2   Outer.2 Outer   20
                  2 2   11  FALSE   1   Inner.1 Inner   10
                  2 3   12  FALSE   1   Inner.1 Inner   10
                  3 3   13  FALSE   1   Inner.1 Inner   10
                  3 2   14  FALSE   1   Inner.1 Inner   10
                  2 2   15  FALSE   1   Inner.1 Inner   10
                  ")

This version of the code doesn't show both pieces (even though they are in the legend)

ggplot(data=fortifyResults, aes(y=lat, x=long, group=group))+
  geom_polygon(aes(fill=factor(score)),color="black")

And this one causes tearing

ggplot(data=fortifyResults, aes(y=lat, x=long), group=group)+
  geom_polygon(aes(fill=factor(score)),color="black")

I read that the direction of the points makes a difference. This is how the direction comes out.

ggplot(data= fortifyResults, aes(y=lat, x=long, group=group))+
  geom_polygon(fill="yellow", color="black")+
  geom_text(aes(label=order),hjust=0, vjust=-0.3)+
  facet_wrap(~id)

Again, the one titled "outer" here should have a hole in the middle (hole==TRUE). From what I've read, they should go in the other direction. I've tried inverting the logic, changing the direction of the points, and a bunch of other stuff. I hope you folks can help.


问:
How to correctly change state of a multiple nested array of objects in React?
What would be the best way to change the state of multiple nested arrays of objects in React? Let's see the example below: I have a component that will display the top playlist for each genre. I have a property genre which is an array of objects and each object has a property songs which is also an array of objects. If I want to change the song named Soldier of Fortune to Child in Time (Let's suppose in Change function as parameters I have indexes of Song and Genre already provided from the UI change). How can I access multiple levels of nested objects and not mutate the state?

```<code>this.state = {
    title: 'Top playlists',
    genres: [
      {
        genreName: 'pop',
        followers: 2456,
        songs: [
          {
            title: 'Soldier of fortune',
            author: 'Deep Purple',
          },
        ],
      },
    ],
  };

handleChangeSongName = (e, genreIndex, songIndex) => {
    // genreIndex = 0;
    // songIndex = 0;
    // e.target.name = title;
    // e.target.value = "Child in time"
    ...What to do here?
  }

</code>```

答:
I would change your state like this:

```<code>this.state = {
      title: "Top playlists",
      genres: [
        {
          followers: 2456,
          genreName: "pop",
          songs: [
            {
              title: "Soldier of fortune",
              author: "Deep Purple"
            }
          ]
        }
      ]
    };
</code>```

and then

```<code>handleChangeSongName = (e, genreIndex, songIndex) => {
    // genreIndex = 0;
    // songIndex = 0;
    // e.target.name = title;
    // e.target.value = "Child in time"
    ...What to do here?

    const genres = _.cloneDeep(this.state.genres); // create deep copy with underscore
    // or like this
    // const genres = JSON.parse(JSON.stringify(this.state.genres))

    if(genres.length && genres[genreIndex] && genres[genreIndex].songs.length && genres[genreIndex].songs[songIndex]) {
        genres[genreIndex].songs[songIndex][e.target.name] = e.target.value;

        this.setState({
            genres: genres
        });
     }

  }
</code>```

Body:
What would be the best way to change the state of multiple nested arrays of objects in React? Let's see the example below: I have a component that will display the top playlist for each genre. I have a property genre which is an array of objects and each object has a property songs which is also an array of objects. If I want to change the song named Soldier of Fortune to Child in Time (Let's suppose in Change function as parameters I have indexes of Song and Genre already provided from the UI change). How can I access multiple levels of nested objects and not mutate the state?

this.state = {
    title: 'Top playlists',
    genres: [
      {
        genreName: 'pop',
        followers: 2456,
        songs: [
          {
            title: 'Soldier of fortune',
            author: 'Deep Purple',
          },
        ],
      },
    ],
  };

handleChangeSongName = (e, genreIndex, songIndex) => {
    // genreIndex = 0;
    // songIndex = 0;
    // e.target.name = title;
    // e.target.value = "Child in time"
    ...What to do here?
  }

Body:
I would change your state like this:

this.state = {
      title: "Top playlists",
      genres: [
        {
          followers: 2456,
          genreName: "pop",
          songs: [
            {
              title: "Soldier of fortune",
              author: "Deep Purple"
            }
          ]
        }
      ]
    };

and then

handleChangeSongName = (e, genreIndex, songIndex) => {
    // genreIndex = 0;
    // songIndex = 0;
    // e.target.name = title;
    // e.target.value = "Child in time"
    ...What to do here?

    const genres = _.cloneDeep(this.state.genres); // create deep copy with underscore
    // or like this
    // const genres = JSON.parse(JSON.stringify(this.state.genres))

    if(genres.length && genres[genreIndex] && genres[genreIndex].songs.length && genres[genreIndex].songs[songIndex]) {
        genres[genreIndex].songs[songIndex][e.target.name] = e.target.value;

        this.setState({
            genres: genres
        });
     }

  }


问:
Handle multiple transformation on an Image
I'm running a project that will do more or less the same as CameraRaw/Photoshop does. The thing is, how do I handle multiple mods on the image matrix?

let me explain, I read the image Using OpenCV function, and I built a simple Ui in QtCreator, with a few sliders for contrast, exposure etc..
so I got my sliders that, on triggered action, call the function contrast(); on where I pass my Image, and the sliders value (sliders can go from -100 to 100).

Here's the problem: if I set the exposure to +50, then my Image will increase it to +50. From that, if I try to decrease it, to +30, then the exposure will be +50 +30, as I wrote on my pixels image.

So, in order to decrease from +50 to +30, I made a copy of my image, that will be modified , and when I recall the exposure(), then the filter will be applied on the original Image.

So far so good, but, what if I'll apply contrast() and exposure() at the same time? As I done for now, calling one of the twos will exclude the firstly called.

Is there anybody that can help with figure out a way for handling that?

答:
Paul92's answers already answers your question and is probably the easiest and cleanest solution to your problem.

If you really wish/need to keep the latest transformed image instead of the original one, you can store the value of the sliders position at the latest transformation and use a delta to do the actual transformation :

```<code>brightnessDelta = brightnessSlider->value() - latestBrightnessSlider;
constrastDelta = contrastSlider->value() - latestContrastSlider;

latestTransformedImage = getImage();
applyBrightness(latestTransformedImage, brightnessDelta);
applyContrast(latestTransformedImage, contrastDelta);
</code>```

Body:
Paul92's answers already answers your question and is probably the easiest and cleanest solution to your problem.

If you really wish/need to keep the latest transformed image instead of the original one, you can store the value of the sliders position at the latest transformation and use a delta to do the actual transformation :

brightnessDelta = brightnessSlider->value() - latestBrightnessSlider;
constrastDelta = contrastSlider->value() - latestContrastSlider;

latestTransformedImage = getImage();
applyBrightness(latestTransformedImage, brightnessDelta);
applyContrast(latestTransformedImage, contrastDelta);


问:
Reading and parsing a CSV file in Python with Regex first column
I have a CSV file (calendar), 5 columns that I want to read and parse with the following conditions using a script:

Deleting headers (done)

Change the format of the first column from 01/01/2019 to 20190101 in the First column

The first part of the script is done to skip headers. The second part I think a regex is required but I just don't know how to first remove the / and then move the 0101 from before 2019 to after 2019 so that the result is 20190101

If someone could help that would be great!

```<code>def parse_calendar(infile, outfile):
    with open(outfile, 'w', newline='') as output:
        with open(infile, newline='') as input:
            reader = csv.reader(input, delimiter=',', quotechar='"')
            next(reader, None)  # skip the headers
            writer = csv.writer(output, delimiter=',', quotechar='"')
            for row in reader:   # process each row
                writer.writerow(row)
</code>```

I expect the output to be like the following compared to the initial file:

01/01/2019  New Year's Day  N   C   US

20190101    New Year's Day  N   C   US

答:
Thanks guys for the responses.

So with this code I get the following output:

```<code>import csv

def parse_calendar(infile, outfile):
    with open(outfile, 'w', newline='') as output:
        with open(infile, newline='') as input:
            reader = csv.reader(input, delimiter=',', quotechar='"')
            next(reader, None)  # skip the headers
            writer = csv.writer(output, delimiter=',', quotechar='"')
            for row in reader: # process each row
                replaced = row[0].replace('/','')
                row[0] = replaced
                writer.writerow(row)
</code>```

01012018,New Year's Day,N,C,US

01012018,New Year's Day,N,C,CA

01152018,Martin L. King Day,N,C,US

What code do I need to add to the script get the formatting different now from 01012018 to 20180101 given the type is a String? For each line then off course.

Appreciate it alot thanks

Body:
I have a CSV file (calendar), 5 columns that I want to read and parse with the following conditions using a script:

Deleting headers (done)

Change the format of the first column from 01/01/2019 to 20190101 in the First column

The first part of the script is done to skip headers. The second part I think a regex is required but I just don't know how to first remove the / and then move the 0101 from before 2019 to after 2019 so that the result is 20190101

If someone could help that would be great!

def parse_calendar(infile, outfile):
    with open(outfile, 'w', newline='') as output:
        with open(infile, newline='') as input:
            reader = csv.reader(input, delimiter=',', quotechar='"')
            next(reader, None)  # skip the headers
            writer = csv.writer(output, delimiter=',', quotechar='"')
            for row in reader:   # process each row
                writer.writerow(row)

I expect the output to be like the following compared to the initial file:

01/01/2019  New Year's Day  N   C   US

20190101    New Year's Day  N   C   US

Body:
Thanks guys for the responses.

So with this code I get the following output:

import csv

def parse_calendar(infile, outfile):
    with open(outfile, 'w', newline='') as output:
        with open(infile, newline='') as input:
            reader = csv.reader(input, delimiter=',', quotechar='"')
            next(reader, None)  # skip the headers
            writer = csv.writer(output, delimiter=',', quotechar='"')
            for row in reader: # process each row
                replaced = row[0].replace('/','')
                row[0] = replaced
                writer.writerow(row)

01012018,New Year's Day,N,C,US

01012018,New Year's Day,N,C,CA

01152018,Martin L. King Day,N,C,US

What code do I need to add to the script get the formatting different now from 01012018 to 20180101 given the type is a String? For each line then off course.

Appreciate it alot thanks


问:
How to select a window of values from the list?
I have a stream of data which is of the type

```<code>list  = [22 , 15 , 6 ,12 ,30 , 45, 200 , 238 , 220 , 6000, 6250 , 6900, 6700,6500, 0 , 250 , 6000 ,6800,220, 250,200]
</code>```

As you can see the stream of data has some very high values in the middle which is what we desire to extract. This block can also contain low values (0 and 250 in the above list) but definitely higher values at the start and end of block ( 6000,6500). How can we extract this particular window of data.

The output should be

```<code>new_list = [6000,6250,6900,600,6500,0, 250 , 6000 , 6800]
</code>```

I usually work on MATLAB. So the way i would do this is by finding the first and the last peak in the data

答:
You could establish a treshold between the highest and lowest values in the data, then find the first and last indexes of entries that are over the treshold to form a range in the list:</p>

```<code>data     = [22 , 15 , 6 ,12 ,30 , 45, 200 , 238 , 220 , 6000, 6250 , 6900, 6700,6500, 0 , 250 , 6000 ,6800,220, 250,200]
treshold = (min(data)+max(data))/2
start    = next(i for i,v in enumerate(data) if v >= treshold)
end      = len(data) - next(i for i,v in enumerate(data[::-1]) if v >= treshold)
result   = data[start:end]

print(result)
# [6000, 6250, 6900, 6700, 6500, 0, 250, 6000, 6800]
</code>```

Body:
I have a stream of data which is of the type

list  = [22 , 15 , 6 ,12 ,30 , 45, 200 , 238 , 220 , 6000, 6250 , 6900, 6700,6500, 0 , 250 , 6000 ,6800,220, 250,200]

As you can see the stream of data has some very high values in the middle which is what we desire to extract. This block can also contain low values (0 and 250 in the above list) but definitely higher values at the start and end of block ( 6000,6500). How can we extract this particular window of data.

The output should be

new_list = [6000,6250,6900,600,6500,0, 250 , 6000 , 6800]

I usually work on MATLAB. So the way i would do this is by finding the first and the last peak in the data

Body:
You could establish a treshold between the highest and lowest values in the data, then find the first and last indexes of entries that are over the treshold to form a range in the list:

data     = [22 , 15 , 6 ,12 ,30 , 45, 200 , 238 , 220 , 6000, 6250 , 6900, 6700,6500, 0 , 250 , 6000 ,6800,220, 250,200]
treshold = (min(data)+max(data))/2
start    = next(i for i,v in enumerate(data) if v >= treshold)
end      = len(data) - next(i for i,v in enumerate(data[::-1]) if v >= treshold)
result   = data[start:end]

print(result)
# [6000, 6250, 6900, 6700, 6500, 0, 250, 6000, 6800]


问:
How to use variables defined in inventory
i have multiple servers and on each of server have multiple containers in my inventory. some servers would be in one group, some in other group and i want to specify for each container url variable.
my inventory:

can i loop over these URL's like a with_dict? and if yes, how?

my inventory:

```<code>all:
  hosts:
    <1st-server-ip>:
      ansible_host: <IP>
    <2nd-server-ip>:
      ansible_host: <IP>
    <3rd-server-ip>:
      ansible_host: <IP>
  children:
    <1st-GROUP>:
      hosts:
        <1st-server-ip>:
          <containers>:
            <app-1>:
              url: '<URL>'
            <app-2>:
              url: '<URL>'
            <app-3>:
              url: '<URL>'
    <2nd-GROUP>:
      hosts:
        <2nd-server-ip>:
          <containers>:
            <app-4>:
              url: '<URL>'
            <app-5>:
              url: '<URL>'
    <3rd-GROUP>:
      hosts:
        <3rd-server-ip>:
          <containers>:
            <app-6>:
              url: '<URL>'
            <app-7>:
              url: '<URL>'
            <app-8>:
              url: '<URL>'
</code>```

答:
json_query is able to reduce the structure to the list of lists which can be iterated with include_tasks.

The play below

```<code>- include_tasks: loop-url.yml
  loop: "{{ all.children|json_query('*.hosts.*.containers[]') }}"
  loop_control:
    loop_var: outer_item
</code>```

with included tasks

```<code>> cat loop-url.yml
- debug:
    msg: "key: {{ item.key }} value: {{ item.value.url }}"
  loop: "{{ outer_item|dict2items }}"
</code>```

gives (grep msg):

```<code>"msg": "key: app-7 value: URL"
"msg": "key: app-6 value: URL"
"msg": "key: app-8 value: URL"
"msg": "key: app-5 value: URL"
"msg": "key: app-4 value: URL"
"msg": "key: app-3 value: URL"
"msg": "key: app-2 value: URL"
"msg": "key: app-1 value: URL"
</code>```

(tag signs <> were removed from the data)

Body:
i have multiple servers and on each of server have multiple containers in my inventory. some servers would be in one group, some in other group and i want to specify for each container url variable.
my inventory:

can i loop over these URL's like a with_dict? and if yes, how?

my inventory:

all:
  hosts:
    <1st-server-ip>:
      ansible_host: <IP>
    <2nd-server-ip>:
      ansible_host: <IP>
    <3rd-server-ip>:
      ansible_host: <IP>
  children:
    <1st-GROUP>:
      hosts:
        <1st-server-ip>:
          <containers>:
            <app-1>:
              url: '<URL>'
            <app-2>:
              url: '<URL>'
            <app-3>:
              url: '<URL>'
    <2nd-GROUP>:
      hosts:
        <2nd-server-ip>:
          <containers>:
            <app-4>:
              url: '<URL>'
            <app-5>:
              url: '<URL>'
    <3rd-GROUP>:
      hosts:
        <3rd-server-ip>:
          <containers>:
            <app-6>:
              url: '<URL>'
            <app-7>:
              url: '<URL>'
            <app-8>:
              url: '<URL>'

Body:
json_query is able to reduce the structure to the list of lists which can be iterated with include_tasks.

The play below

- include_tasks: loop-url.yml
  loop: "{{ all.children|json_query('*.hosts.*.containers[]') }}"
  loop_control:
    loop_var: outer_item

with included tasks

> cat loop-url.yml
- debug:
    msg: "key: {{ item.key }} value: {{ item.value.url }}"
  loop: "{{ outer_item|dict2items }}"

gives (grep msg):

"msg": "key: app-7 value: URL"
"msg": "key: app-6 value: URL"
"msg": "key: app-8 value: URL"
"msg": "key: app-5 value: URL"
"msg": "key: app-4 value: URL"
"msg": "key: app-3 value: URL"
"msg": "key: app-2 value: URL"
"msg": "key: app-1 value: URL"

(tag signs <> were removed from the data)


问:
How to create a HUGE multi-dimensional array in Traditional ASP
I'm trying to handle a massive array in Traditional ASP, but am getting to the limits....

Essensially I need an array of (70 x Sheets, 10000 Rows, 200 Columns) to prepare an XML Spreadsheet and PDF document.

I've tried nesting dictionary objects (see below), but they are painfully slow.

Any suggestions at all would be greatly appreciated.....

Regards,

Paul

Using Dictionary Object:-

```<code>Dim HugeArray = CreateObject("Scripting.Dictionary")

Sub AddCell(x,y,z,aText)
    Dim NewCol

    if not HugeArray.exists(x) then
        set NewCol = CreateObject("Scripting.Dictionary")
        HugeArray.Add x,NewCol
        set NewCol = nothing
    end if

    if not HugeArray(x).exists(y) then
        set NewCol = CreateObject("Scripting.Dictionary")
        HugeArray(x).Add y,NewCol
        set NewCol = nothing
    end if

    if HugeArray(x).Exists(y) then
        set y=HugeArray(x)(y)
        if not y.Exists(z) then
            y.Add z,aText
        else
            y(z)=aText
        end if
    end if

End Sub

Function GetCell(x,y,z)
    Dim a
    GetCell=""
    if HugeArray(x).Exists(y) then
        set a=HugeArray(x)(y)
        GetCell=a(z)
    end if
End Function
</code>```

答:
just an idea: Have you ever tried to go with the json object? See Homepage of Json
And I think the limit of the size is the memory of your webserver.</p>

Body:
I'm trying to handle a massive array in Traditional ASP, but am getting to the limits....

Essensially I need an array of (70 x Sheets, 10000 Rows, 200 Columns) to prepare an XML Spreadsheet and PDF document.

I've tried nesting dictionary objects (see below), but they are painfully slow.

Any suggestions at all would be greatly appreciated.....

Regards,

Paul

Using Dictionary Object:-

Dim HugeArray = CreateObject("Scripting.Dictionary")

Sub AddCell(x,y,z,aText)
    Dim NewCol

    if not HugeArray.exists(x) then
        set NewCol = CreateObject("Scripting.Dictionary")
        HugeArray.Add x,NewCol
        set NewCol = nothing
    end if

    if not HugeArray(x).exists(y) then
        set NewCol = CreateObject("Scripting.Dictionary")
        HugeArray(x).Add y,NewCol
        set NewCol = nothing
    end if

    if HugeArray(x).Exists(y) then
        set y=HugeArray(x)(y)
        if not y.Exists(z) then
            y.Add z,aText
        else
            y(z)=aText
        end if
    end if

End Sub

Function GetCell(x,y,z)
    Dim a
    GetCell=""
    if HugeArray(x).Exists(y) then
        set a=HugeArray(x)(y)
        GetCell=a(z)
    end if
End Function


问:
How can I split a list of comma separated words in a Pandas column?
I was querying Stackoverflow to get some data (https://data.stackexchange.com/stackoverflow/query/new), and I have a data frame with Tags as a column. The tags originally were of the form

```<code><html><css>
</code>```

I managed to get them in the form of

```<code>html,css
</code>```

I think an image of my Jupyter notebook can display it best:

How can I separate the tags so that they can become categorical variables, and I can transform them using something like get_dummies?
Everything I've seen refers to actual lists, like [html,css], rather than just comma separated words.

答: For this purpose, we can use df['Tags'].str.get_dummies(','), which basically performs split and converts each element to its own one-hot encoded column.

Body:
I was querying Stackoverflow to get some data (https://data.stackexchange.com/stackoverflow/query/new), and I have a data frame with Tags as a column. The tags originally were of the form

<css>

I managed to get them in the form of

html,css

I think an image of my Jupyter notebook can display it best:

How can I separate the tags so that they can become categorical variables, and I can transform them using something like get_dummies?
Everything I've seen refers to actual lists, like [html,css], rather than just comma separated words.


问:
Typescript: Get the type of the last parameter of a function type
Assume I have a function type, e.g.

```<code>type somefntype = (a: number, b: string, c: boolean) => void
</code>```

I need the type of that function types last parameter:

```<code>type lastparamtype = LastParameter<somefntype> // lastparamtype == boolean
</code>```

How do I define LastParameter?

答:
For function with 3 args solution wil be

```<code>type somefntype = (a: number, b: string, ddd: boolean) => void
type LastParameter<T> = T extends (a: infer A1, b: infer A2, c: infer A3) => any ? A3 : never;

type lastArg = LastParameter<somefntype>;  // === boolean
</code>```

Name of function agruments does not metter.

For function with arbitrary number of arguments task become a bit complicated. We may use ...rest but it will be array.

```<code>type LastParameter<T> = T extends (...rest: infer A3) => any ?
    A3 : never;
type lastArg = LastParameter<somefntype>; // lastArg === [number, string, boolean]
</code>```

Get last element of resulting tuple is a bit challenging. One possible solution has been inspired from this article.

```<code>type Prev<T extends number> = [-1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62][T];
type GetLength<original extends any[]> = original extends { length: infer L } ? L : never;
type GetLast<original extends any[]> = original[Prev<GetLength<original>>]

type somefntype = (a: number, b: string, ddd: boolean) => void
type LastParameter1<T> = T extends (...rest: infer A3) => any ?
    A3 extends any[] ? GetLast<A3> : never
    : never;
type lastArg = LastParameter<somefntype>; // boolean for 3 arg function
</code>```

Second solution has limitaion on number of arguments of the function.

Body:
Assume I have a function type, e.g.

type somefntype = (a: number, b: string, c: boolean) => void

I need the type of that function types last parameter:

type lastparamtype = LastParameter<somefntype> // lastparamtype == boolean

How do I define LastParameter?

Body:
For function with 3 args solution wil be

type somefntype = (a: number, b: string, ddd: boolean) => void
type LastParameter<T> = T extends (a: infer A1, b: infer A2, c: infer A3) => any ? A3 : never;

type lastArg = LastParameter<somefntype>;  // === boolean

Name of function agruments does not metter.

For function with arbitrary number of arguments task become a bit complicated. We may use ...rest but it will be array.

type LastParameter<T> = T extends (...rest: infer A3) => any ?
    A3 : never;
type lastArg = LastParameter<somefntype>; // lastArg === [number, string, boolean]

Get last element of resulting tuple is a bit challenging. One possible solution has been inspired from this article.

type Prev<T extends number> = [-1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62][T];
type GetLength<original extends any[]> = original extends { length: infer L } ? L : never;
type GetLast<original extends any[]> = original[Prev<GetLength<original>>]

type somefntype = (a: number, b: string, ddd: boolean) => void
type LastParameter1<T> = T extends (...rest: infer A3) => any ?
    A3 extends any[] ? GetLast<A3> : never
    : never;
type lastArg = LastParameter<somefntype>; // boolean for 3 arg function

Second solution has limitaion on number of arguments of the function.


问:
Why storage class attribute is missing for boto3 s3 object?
When running retrieval of Storage Class

```<code>import boto3

s3 = boto3.resource('s3')
key = s3.Object('bucket_name','key')
print key.storage_class
</code>```

it returns None

答:
My experimenting shows that Standard storage class returns a value of None (as it did for you).

However, I managed to obtain valid values for other storage classes such as STANDARD_IA and GLACIER.

Body:
When running retrieval of Storage Class

import boto3

s3 = boto3.resource('s3')
key = s3.Object('bucket_name','key')
print key.storage_class

it returns None


问:
Simultaneously fit two linear functions with a single slope
I have two sets of experimental data, as shown on the figure
For  the measured data must be the same for the two sets. Therefore, I would like to fit both sets simultaneously, defining a single y-intercept and two slopes. As far as I understand, this question does not solve my problem.

答:
I think you are going to do a simple linear regression. The problem here is to minimize the error for two linear functions with identical interception. The error function is:

```<code>def f(params):
    alpha, betha_1, betha_2 = params
    e_1 = np.power(y1- alpha - (betha_1 * x),2)
    e_2 = np.power(y2- alpha - (betha_2 * x),2)
    error = np.sum(e_1 + e_2)
    return error
</code>```

I used scipy.optimize.minimize to get optimum parameters. The final code is:

```<code>import numpy as np
from scipy.optimize import minimize
import matplotlib.pyplot as plt

y2 = [9, 11, 10, 12, 13, 12, 12]
y1 = [10, 12, 11, 12, 12, 13, 14]
x = [0, 1, 2, 3, 4, 5, 6]
x, y1, y2 = np.array(x), np.array(y1), np.array(y2)

def f(params):
    alpha, betha_1, betha_2 = params
    e_1 = np.power(y1- alpha - (betha_1 * x),2)
    e_2 = np.power(y2- alpha - (betha_2 * x),2)
    error = np.sum(e_1 + e_2)
    return error

initial_guess = [1, 1, 1]
result = minimize(f, initial_guess)

xfine = np.arange(0, 6, 0.001)
y1_reg = result.x[0] + result.x[1]*xfine
y2_reg = result.x[0] + result.x[2]*xfine

plt.plot(x, y1, 'bo', x, y2, 'go', xfine, y1_reg, 'b', xfine, y2_reg, 'g')
plt.show()
</code>```

and the result:

Body:
I think you are going to do a simple linear regression. The problem here is to minimize the error for two linear functions with identical interception. The error function is:

def f(params):
    alpha, betha_1, betha_2 = params
    e_1 = np.power(y1- alpha - (betha_1 * x),2)
    e_2 = np.power(y2- alpha - (betha_2 * x),2)
    error = np.sum(e_1 + e_2)
    return error

I used scipy.optimize.minimize to get optimum parameters. The final code is:

import numpy as np
from scipy.optimize import minimize
import matplotlib.pyplot as plt

y2 = [9, 11, 10, 12, 13, 12, 12]
y1 = [10, 12, 11, 12, 12, 13, 14]
x = [0, 1, 2, 3, 4, 5, 6]
x, y1, y2 = np.array(x), np.array(y1), np.array(y2)

def f(params):
    alpha, betha_1, betha_2 = params
    e_1 = np.power(y1- alpha - (betha_1 * x),2)
    e_2 = np.power(y2- alpha - (betha_2 * x),2)
    error = np.sum(e_1 + e_2)
    return error

initial_guess = [1, 1, 1]
result = minimize(f, initial_guess)

xfine = np.arange(0, 6, 0.001)
y1_reg = result.x[0] + result.x[1]*xfine
y2_reg = result.x[0] + result.x[2]*xfine

plt.plot(x, y1, 'bo', x, y2, 'go', xfine, y1_reg, 'b', xfine, y2_reg, 'g')
plt.show()

and the result:


问:
firebase.database is not a function
I am trying to upgrade from earlier firebase version to the latest in my ionic project. I followed this tutorial for upgrade. In step 4 from this page I am stuck on the last statement firebase.database().ref();.

Error message

```<code>TypeError: firebase.database is not a function
</code>```

Below is my code. Kindly help.

```<code>...

// Initialize Firebase
this.config = {
    apiKey: "some-api-key",
    authDomain: "myapp.firebaseapp.com",
    databaseURL: "https://myapp.firebaseio.com",
    storageBucket: "project-somenumber.appspot.com",
};

...

this.authWithOAuthPopup = function(type) {
    var deferred = $q.defer();
    console.log(service.config);    // ---> Object {apiKey: "some-api-key", authDomain: "myapp.firebaseapp.com", databaseURL: "https://myapp.firebaseio.com", storageBucket: "project-somenumber.appspot.com"}
    firebase.initializeApp(service.config);
    console.log(firebase);  // ---> Object {SDK_VERSION: "3.0.5", INTERNAL: Object}
    service.rootRef = firebase.database().ref(); //new Firebase("https://rsb2.firebaseio.com"); ---> I am getting error on this line "TypeError: firebase.database is not a function"
    service.rootRef.authWithOAuthPopup(type, function(error, authData) {
        if (error) {
            service.authError = error;
            switch (error.code) {
                case "INVALID_EMAIL":
                    console.log("The specified user account email is invalid.");
                    break;
                case "INVALID_PASSWORD":
                    console.log("The specified user account password is incorrect.");
                    break;
                case "INVALID_USER":
                    console.log("The specified user account does not exist.");
                    break;
                default:
                    console.log("Error logging user in:", error);
            }
            deferred.resolve(service.authError);
        } else {
            service.authData = authData;
            console.log("Authenticated successfully with payload:", authData);
            deferred.resolve(service.authData);
        }
        return deferred.promise;
    });
    return deferred.promise;
}

var service = this;
</code>```

Update

After adding latest database library this questions problem is solved.

Updating my code here

```<code>this.authWithOAuthPopup = function(type) {
    var deferred = $q.defer();
    console.log(service.config);
    firebase.initializeApp(service.config);
    console.log(firebase);
    service.rootRef = firebase.database(); //.ref(); //new Firebase("https://rsb2.firebaseio.com");

    var provider = new firebase.auth.FacebookAuthProvider();
    firebase.auth().signInWithRedirect(provider);
    firebase.auth().getRedirectResult().then(function(result) {
        if (result.credential) {
            // This gives you a Facebook Access Token. You can use it to access the Facebook API.
            var token = result.credential.accessToken;
            console.log(result);
            // ...
        }
        // The signed-in user info.
        var user = result.user;
    }).catch(function(error) {
        // Handle Errors here.
        var errorCode = error.code;
        var errorMessage = error.message;
        // The email of the user's account used.
        var email = error.email;
        // The firebase.auth.AuthCredential type that was used.
        var credential = error.credential;
        // ...
    });
    return deferred.promise;
}
</code>```

答:
I have the same error -firebase.database is not a function- but with different situation you just need to add

above  and  the link of javascript that contain the Firebase configuration.

You may also try to use the defer Attribute in your script as it will not load the scripts until page elements are loaded.

Title: firebase.database is not a function

Body:
I am trying to upgrade from earlier firebase version to the latest in my ionic project. I followed this tutorial for upgrade. In step 4 from this page I am stuck on the last statement firebase.database().ref();.

Error message

TypeError: firebase.database is not a function

Below is my code. Kindly help.

...

// Initialize Firebase
this.config = {
    apiKey: "some-api-key",
    authDomain: "myapp.firebaseapp.com",
    databaseURL: "https://myapp.firebaseio.com",
    storageBucket: "project-somenumber.appspot.com",
};

...

this.authWithOAuthPopup = function(type) {
    var deferred = $q.defer();
    console.log(service.config);    // ---> Object {apiKey: "some-api-key", authDomain: "myapp.firebaseapp.com", databaseURL: "https://myapp.firebaseio.com", storageBucket: "project-somenumber.appspot.com"}
    firebase.initializeApp(service.config);
    console.log(firebase);  // ---> Object {SDK_VERSION: "3.0.5", INTERNAL: Object}
    service.rootRef = firebase.database().ref(); //new Firebase("https://rsb2.firebaseio.com"); ---> I am getting error on this line "TypeError: firebase.database is not a function"
    service.rootRef.authWithOAuthPopup(type, function(error, authData) {
        if (error) {
            service.authError = error;
            switch (error.code) {
                case "INVALID_EMAIL":
                    console.log("The specified user account email is invalid.");
                    break;
                case "INVALID_PASSWORD":
                    console.log("The specified user account password is incorrect.");
                    break;
                case "INVALID_USER":
                    console.log("The specified user account does not exist.");
                    break;
                default:
                    console.log("Error logging user in:", error);
            }
            deferred.resolve(service.authError);
        } else {
            service.authData = authData;
            console.log("Authenticated successfully with payload:", authData);
            deferred.resolve(service.authData);
        }
        return deferred.promise;
    });
    return deferred.promise;
}

var service = this;

Update

After adding latest database library this questions problem is solved.

Updating my code here

this.authWithOAuthPopup = function(type) {
    var deferred = $q.defer();
    console.log(service.config);
    firebase.initializeApp(service.config);
    console.log(firebase);
    service.rootRef = firebase.database(); //.ref(); //new Firebase("https://rsb2.firebaseio.com");

    var provider = new firebase.auth.FacebookAuthProvider();
    firebase.auth().signInWithRedirect(provider);
    firebase.auth().getRedirectResult().then(function(result) {
        if (result.credential) {
            // This gives you a Facebook Access Token. You can use it to access the Facebook API.
            var token = result.credential.accessToken;
            console.log(result);
            // ...
        }
        // The signed-in user info.
        var user = result.user;
    }).catch(function(error) {
        // Handle Errors here.
        var errorCode = error.code;
        var errorMessage = error.message;
        // The email of the user's account used.
        var email = error.email;
        // The firebase.auth.AuthCredential type that was used.
        var credential = error.credential;
        // ...
    });
    return deferred.promise;
}


问:
EventBus - threadMode not regonized as @Subscribe annotation property :cannot resolve method threadMode
I am using GreenRobot EventBus ,  I wanted to define some Threading properties, according to docs,

However, when I write:

```<code> @Subscribe(threadMode = ThreadMode.MAIN)
    public void onShowNotification(NotificationEvent event) {
        if(event == NotificationEvent.bannerEvent) {
            updateContents();
        }
    }
</code>```

I get an error that threadMode is not recognized by compiler specifying method:  cannot resolve method 'threadMode'

i have on my gradle file:

```<code>implementation 'org.greenrobot:eventbus:3.1.1'
</code>```

答:
I suspect that your project uses another library which also has a @Subscribe keyword. Can you try CMD+B when the cursor in the @Subscriber and go to the definition, does it go to org.greenrobot.eventbu.Subscribe?

The takeaway here: when error cannot resolve method happens, you can always go to the definition to check what happens there :)

Body:
I am using GreenRobot EventBus ,  I wanted to define some Threading properties, according to docs,

However, when I write:

 @Subscribe(threadMode = ThreadMode.MAIN)
    public void onShowNotification(NotificationEvent event) {
        if(event == NotificationEvent.bannerEvent) {
            updateContents();
        }
    }

I get an error that threadMode is not recognized by compiler specifying method:  cannot resolve method 'threadMode'

i have on my gradle file:

implementation 'org.greenrobot:eventbus:3.1.1'