问:
AWS, terraform) How to connect to new instance from another instance which created new instance?
I cannot connect to instance2 from instance1, which creates instance2 by terraform, because instance1 has no key_name.pem, except key_name.pub.

How can I download key_name.pem to the instance1?

Here is what I did:

I created AWS instance 1

generate ssh key

```<code>ssh-keygen -t rsa -b 4096 -C "roy" -f "$HOME/.ssh/test_key" -N ""
</code>```

terraform apply(key resource)

```<code># main.tf
provider "aws"{
    region = "ap-northeast-2"
}

resource "aws_key_pair" "test_key" {
key_name = "test_key"
public_key = "${file("~/.ssh/test_key.pub")}"
}
</code>```

terraform apply(create instance)

```<code>provider "aws"{
    region = "ap-northeast-2"
}
resource "aws_instance" "ec2" {
ami = "ami-06e7b9c5e0c4dd014"
instance_type = "t2.nano"
key_name = "test_key"
tags {
Name = "ec2_instance"
}
</code>```

答:
You can use user_data when creating instance1.
This can be a regular bash script, in which you create the id_rsa (key_name.pem) file for the user ubuntu (if you are using an Ubuntu AMI).

```<code>#!/bin/bash

#create id_rsa

echo "[KEY_DATA]" > /home/ubuntu/.ssh/id_rsa
chmod 0600 /home/ubuntu/.ssh/id_rsa
</code>```

But why do you even need a private key on the instance?
Terraform does not need the private key...

Just in case you are using instance1 as SSH bastion:
You should use SSH forwarding instead of copying your private key to an instance: Run ssh -A instance1_ip and then ssh instance2_ip from instance one. This way you don't need a private key on instance1.

Body:
I cannot connect to instance2 from instance1, which creates instance2 by terraform, because instance1 has no key_name.pem, except key_name.pub.

How can I download key_name.pem to the instance1?

Here is what I did:

I created AWS instance 1

generate ssh key

ssh-keygen -t rsa -b 4096 -C "roy" -f "$HOME/.ssh/test_key" -N ""

terraform apply(key resource)

# main.tf
provider "aws"{
    region = "ap-northeast-2"
}

resource "aws_key_pair" "test_key" {
key_name = "test_key"
public_key = "${file("~/.ssh/test_key.pub")}"
}

terraform apply(create instance)

provider "aws"{
    region = "ap-northeast-2"
}
resource "aws_instance" "ec2" {
ami = "ami-06e7b9c5e0c4dd014"
instance_type = "t2.nano"
key_name = "test_key"
tags {
Name = "ec2_instance"
}

Body:
You can use user_data when creating instance1.
This can be a regular bash script, in which you create the id_rsa (key_name.pem) file for the user ubuntu (if you are using an Ubuntu AMI).

#!/bin/bash

#create id_rsa

echo "[KEY_DATA]" > /home/ubuntu/.ssh/id_rsa
chmod 0600 /home/ubuntu/.ssh/id_rsa

But why do you even need a private key on the instance?
Terraform does not need the private key...

Just in case you are using instance1 as SSH bastion:
You should use SSH forwarding instead of copying your private key to an instance: Run ssh -A instance1_ip and then ssh instance2_ip from instance one. This way you don't need a private key on instance1.


来源: stackexchange

问:
ORM vs Handcoded Data Access Layer
I'm a bit scared to ask this question as it may start a religous war so I want to be really clear on what I'm looking for. I'm looking for a reason(s) why you would or have jumped one way or the other and also for items to add to my lists. I'm looking for the big ticket, big bang items. Also, items specific to a product, maybe, if they are really relevant. At this point I'm trying to evaluate ORM vs Manual not product A vs product B.

ORM Advantages

```
 - Quick to code and low maintenance (in some/most scenarios)
 - Additional features for "free" (no developer effort)
```

Hand Coded Advantages

```
 - More Efficient (at runtime, maybe not at dev time?)
 - Less layers of complexity
 - Most ORMS seem to struggle with being retricted to sprocs only
```

In the interests of full disclosure, I really don't like the idea of "something" executing code against my database that I can't directly modify, if I see fit but I can see the potentially massive development time advatages of an ORM.

Its probably also worth noting I'm in a .Net world

[edit]
(the question at Using an ORM or plain SQL? seems to answer many of the questions and reinforce the point about performance)

So, to alter my question slightly

Has any built an app using an ORM in the early stages and then gradually replaced with with a handcoded DAL? What were the pitfalls of this approach?

[Further Edit - getting to the heart of the problem now]
Having a website be able to execute any SQL against my database is scary. If all access is through sprocs my database lives in nice, safe, comfortable isolation. Using exclusively sprocs removes a lot of, if not all, SQL injection attack vectors. Any comments on that?

答:
I have struggled with this for a few years. Looked at a lot of things. And have over the last 3 months realized "why am I wasting all this time on this". I kind of view the ORM as a solved problem. I would rather trust some team that has complete focus on ORM to write an ORM layer than me. Mentally, I'm just ready for new challenges.

My choice is NHibernate. I'm really a newb to this right now. But I like the potential to use Fluent NHibernate or Castle ACtiveRecord also. This seems to be where the mindshare is.

But not sure what I would do in an "everything is a sproc" world.

OwnerDisplayName: Frustrating Developments

ContentLicense: CC BY-SA 2.5

Title: ORM vs Handcoded Data Access Layer

Body:
I'm a bit scared to ask this question as it may start a religous war so I want to be really clear on what I'm looking for. I'm looking for a reason(s) why you would or have jumped one way or the other and also for items to add to my lists. I'm looking for the big ticket, big bang items. Also, items specific to a product, maybe, if they are really relevant. At this point I'm trying to evaluate ORM vs Manual not product A vs product B.

ORM Advantages

 - Quick to code and low maintenance (in some/most scenarios)
 - Additional features for "free" (no developer effort)

Hand Coded Advantages

 - More Efficient (at runtime, maybe not at dev time?)
 - Less layers of complexity
 - Most ORMS seem to struggle with being retricted to sprocs only

In the interests of full disclosure, I really don't like the idea of "something" executing code against my database that I can't directly modify, if I see fit but I can see the potentially massive development time advatages of an ORM.

Its probably also worth noting I'm in a .Net world

[edit]
(the question at Using an ORM or plain SQL? seems to answer many of the questions and reinforce the point about performance)

So, to alter my question slightly

Has any built an app using an ORM in the early stages and then gradually replaced with with a handcoded DAL? What were the pitfalls of this approach?

[Further Edit - getting to the heart of the problem now]
Having a website be able to execute any SQL against my database is scary. If all access is through sprocs my database lives in nice, safe, comfortable isolation. Using exclusively sprocs removes a lot of, if not all, SQL injection attack vectors. Any comments on that?

LastEditorDisplayName: Frustrating Developments

OwnerDisplayName: Bruno Tyndall


问:
Is there a way to have currency conversions from Google Finance stick?
I need to find a way to automatically copy the output of the below GoogleFinance formula into another cell and make it stick, i.e. doesn't change when the exchange rate changes.

```<code>=A1*GOOGLEFINANCE("currency:AUDGBP")
</code>```

I was going to use something like =value(x) but this would change every time the above formula generated a new value, whereas I want something to stick as soon as it's output an answer.

答:
There are many options, including:

Ctrl+C followed by Ctrl+
Shift+V (but could be tedious)

GAS (with help for which SO expects some demonstration of effort on your part - or already answered)

turn on iterative calculation (but in your case seems inadvisable)

perhaps the Spreadsheet Freezer add-on from one of our esteemed members (I've not tried it)

ContentLicense: CC BY-SA 4.0

Body:
I need to find a way to automatically copy the output of the below GoogleFinance formula into another cell and make it stick, i.e. doesn't change when the exchange rate changes.

=A1*GOOGLEFINANCE("currency:AUDGBP")

I was going to use something like =value(x) but this would change every time the above formula generated a new value, whereas I want something to stick as soon as it's output an answer.


问:
how can I distinguish from detail_page to the list_page?
How can I distinguish the

I have a Vue project, when I from list_page go to its detail_page, then I can use the this.$router.go(-1) to go back to the list_page.

and I can from other_pages to the the list_page, but how can I distinguish  the two ways to the list_page?

答:
You can do a router.push() with query parameters.

this. $router.push({ name: 'list-page-name`, query: { fromRoute: this. $route.name}

Now on the list-page you can get source from this.$route.query.fromRoute


问:
Replace multiple (special) characters - most efficient way?
At the texts that I have, I want to replace the following special characters with a single space:

```<code>symbols = ["`", "~", "!", "@", "#", "$", "%", "^", "&", "*", "(", ")", "_", "-", "+", "=", "{", "[", "]", "}", "|", "\\", ":", ";", "\"", "<", ",", ">", ".", "?", "/"]
</code>```

What is the most efficient way (in terms of time of code execution) to do this?

For example, I want this:

```<code>(Hello World)] *!
</code>```

to become this:

```<code>Hello World
</code>```

The candidate methods seem to be the following:

list comprehension

.replace()

.translate()

regular expressions

答:
My code replaces symbols with spaces and does NOT remove those spaces.

For short strings .join() is fast, but for larger strings .translate() is faster if there is a lot to replace. Surprisingly, .replace() is still very fast if there are few replacements to be made.

```<code>text: '(Hello World)] *!'
using_replace                     0.046
using_join                        0.016
using_translate                   0.031

text: '~this@is!a^test@'
using_replace                     0.046
using_join                        0.017
using_translate                   0.029

text: '~/()&this@isasd!&=)(/as/dw&%#a^test@~/()&this@isasd!&=)(/as/dw&%#a^test@~/()&this@isasd!&=)(/as/dw&%#a^test@~/()&this@isasd!&=)(/as/dw&%#a^test@~/()&this@isasd!&=)(/as/dw&%#a^test@~/()&this@isasd!&=)(/as/dw&%#a^test@~/()&this@isasd!&=)(/as/dw&%#a^test@~/()&this@isasd!&=)(/as/dw&%#a^test@~/()&this@isasd!&=)(/as/dw&%#a^test@~/()&this@isasd!&=)(/as/dw&%#a^test@~/()&this@isasd!&=)(/as/dw&%#a^test@~/()&this@isasd!&=)(/as/dw&%#a^test@~/()&this@isasd!&=)(/as/dw&%#a^test@~/()&this@isasd!&=)(/as/dw&%#a^test@~/()&this@isasd!&=)(/as/dw&%#a^test@~/()&this@isasd!&=)(/as/dw&%#a^test@~/()&this@isasd!&=)(/as/dw&%#a^test@~/()&this@isasd!&=)(/as/dw&%#a^test@~/()&this@isasd!&=)(/as/dw&%#a^test@~/()&this@isasd!&=)(/as/dw&%#a^test@~/()&this@isasd!&=)(/as/dw&%#a^test@~/()&this@isasd!&=)(/as/dw&%#a^test@~/()&this@isasd!&=)(/as/dw&%#a^test@~/()&this@isasd!&=)(/as/dw&%#a^test@~/()&this@isasd!&=)(/as/dw&%#a^test@~/()&this@isasd!&=)(/as/dw&%#a^test@~/()&this@isasd!&=)(/as/dw&%#a^test@~/()&this@isasd!&=)(/as/dw&%#a^test@~/()&this@isasd!&=)(/as/dw&%#a^test@~/()&this@isasd!&=)(/as/dw&%#a^test@~/()&this@isasd!&=)(/as/dw&%#a^test@~/()&this@isasd!&=)(/as/dw&%#a^test@~/()&this@isasd!&=)(/as/dw&%#a^test@~/()&this@isasd!&=)(/as/dw&%#a^test@~/()&this@isasd!&=)(/as/dw&%#a^test@~/()&this@isasd!&=)(/as/dw&%#a^test@~/()&this@isasd!&=)(/as/dw&%#a^test@~/()&this@isasd!&=)(/as/dw&%#a^test@~/()&this@isasd!&=)(/as/dw&%#a^test@~/()&this@isasd!&=)(/as/dw&%#a^test@~/()&this@isasd!&=)(/as/dw&%#a^test@~/()&this@isasd!&=)(/as/dw&%#a^test@~/()&this@isasd!&=)(/as/dw&%#a^test@~/()&this@isasd!&=)(/as/dw&%#a^test@~/()&this@isasd!&=)(/as/dw&%#a^test@~/()&this@isasd!&=)(/as/dw&%#a^test@~/()&this@isasd!&=)(/as/dw&%#a^test@~/()&this@isasd!&=)(/as/dw&%#a^test@~/()&this@isasd!&=)(/as/dw&%#a^test@~/()&this@isasd!&=)(/as/dw&%#a^test@~/()&this@isasd!&=)(/as/dw&%#a^test@~/()&this@isasd!&=)(/as/dw&%#a^test@~/()&this@isasd!&=)(/as/dw&%#a^test@~/()&this@isasd!&=)(/as/dw&%#a^test@~/()&this@isasd!&=)(/as/dw&%#a^test@~/()&this@isasd!&=)(/as/dw&%#a^test@~/()&this@isasd!&=)(/as/dw&%#a^test@~/()&this@isasd!&=)(/as/dw&%#a^test@~/()&this@isasd!&=)(/as/dw&%#a^test@~/()&this@isasd!&=)(/as/dw&%#a^test@~/()&this@isasd!&=)(/as/dw&%#a^test@~/()&this@isasd!&=)(/as/dw&%#a^test@~/()&this@isasd!&=)(/as/dw&%#a^test@~/()&this@isasd!&=)(/as/dw&%#a^test@~/()&this@isasd!&=)(/as/dw&%#a^test@~/()&this@isasd!&=)(/as/dw&%#a^test@~/()&this@isasd!&=)(/as/dw&%#a^test@~/()&this@isasd!&=)(/as/dw&%#a^test@~/()&this@isasd!&=)(/as/dw&%#a^test@~/()&this@isasd!&=)(/as/dw&%#a^test@~/()&this@isasd!&=)(/as/dw&%#a^test@~/()&this@isasd!&=)(/as/dw&%#a^test@~/()&this@isasd!&=)(/as/dw&%#a^test@~/()&this@isasd!&=)(/as/dw&%#a^test@~/()&this@isasd!&=)(/as/dw&%#a^test@~/()&this@isasd!&=)(/as/dw&%#a^test@~/()&this@isasd!&=)(/as/dw&%#a^test@~/()&this@isasd!&=)(/as/dw&%#a^test@~/()&this@isasd!&=)(/as/dw&%#a^test@~/()&this@isasd!&=)(/as/dw&%#a^test@~/()&this@isasd!&=)(/as/dw&%#a^test@~/()&this@isasd!&=)(/as/dw&%#a^test@~/()&this@isasd!&=)(/as/dw&%#a^test@~/()&this@isasd!&=)(/as/dw&%#a^test@~/()&this@isasd!&=)(/as/dw&%#a^test@~/()&this@isasd!&=)(/as/dw&%#a^test@~/()&this@isasd!&=)(/as/dw&%#a^test@~/()&this@isasd!&=)(/as/dw&%#a^test@~/()&this@isasd!&=)(/as/dw&%#a^test@~/()&this@isasd!&=)(/as/dw&%#a^test@~/()&this@isasd!&=)(/as/dw&%#a^test@~/()&this@isasd!&=)(/as/dw&%#a^test@~/()&this@isasd!&=)(/as/dw&%#a^test@~/()&this@isasd!&=)(/as/dw&%#a^test@~/()&this@isasd!&=)(/as/dw&%#a^test@~/()&this@isasd!&=)(/as/dw&%#a^test@~/()&this@isasd!&=)(/as/dw&%#a^test@~/()&this@isasd!&=)(/as/dw&%#a^test@~/()&this@isasd!&=)(/as/dw&%#a^test@~/()&this@isasd!&=)(/as/dw&%#a^test@'
using_replace                     0.195
using_join                        2.327
using_translate                   0.061

text: 'a long text without chars to replacea long text without chars to replacea long text without chars to replacea long text without chars to replacea long text without chars to replacea long text without chars to replacea long text without chars to replacea long text without chars to replacea long text without chars to replacea long text without chars to replacea long text without chars to replacea long text without chars to replacea long text without chars to replacea long text without chars to replacea long text without chars to replacea long text without chars to replacea long text without chars to replacea long text without chars to replacea long text without chars to replacea long text without chars to replacea long text without chars to replacea long text without chars to replacea long text without chars to replacea long text without chars to replacea long text without chars to replacea long text without chars to replacea long text without chars to replacea long text without chars to replacea long text without chars to replacea long text without chars to replacea long text without chars to replacea long text without chars to replacea long text without chars to replacea long text without chars to replacea long text without chars to replacea long text without chars to replacea long text without chars to replacea long text without chars to replacea long text without chars to replacea long text without chars to replacea long text without chars to replacea long text without chars to replacea long text without chars to replacea long text without chars to replacea long text without chars to replacea long text without chars to replacea long text without chars to replacea long text without chars to replacea long text without chars to replacea long text without chars to replacea long text without chars to replacea long text without chars to replacea long text without chars to replacea long text without chars to replacea long text without chars to replacea long text without chars to replacea long text without chars to replacea long text without chars to replacea long text without chars to replacea long text without chars to replacea long text without chars to replacea long text without chars to replacea long text without chars to replacea long text without chars to replacea long text without chars to replacea long text without chars to replacea long text without chars to replacea long text without chars to replacea long text without chars to replacea long text without chars to replacea long text without chars to replacea long text without chars to replacea long text without chars to replacea long text without chars to replacea long text without chars to replacea long text without chars to replacea long text without chars to replacea long text without chars to replacea long text without chars to replacea long text without chars to replacea long text without chars to replacea long text without chars to replacea long text without chars to replacea long text without chars to replacea long text without chars to replacea long text without chars to replacea long text without chars to replacea long text without chars to replacea long text without chars to replacea long text without chars to replacea long text without chars to replacea long text without chars to replacea long text without chars to replacea long text without chars to replacea long text without chars to replacea long text without chars to replacea long text without chars to replacea long text without chars to replacea long text without chars to replacea long text without chars to replace'
using_replace                     0.051
using_join                        2.100
using_translate                   0.064
</code>```

Comparing some strategies:

```<code>def using_replace(text, symbols_to_replace, replacement=' '):
    for char in symbols_to_replace:
        text = text.replace(char, replacement)

    return text

def using_join(text, symbols_to_replace, replacement=' '):
    return ''.join(
        replacement if char in symbols_to_replace else char
        for char in text)

def using_translate(text, symbols_to_replace, replacement=' '):
    translation_dict = str.maketrans(
        dict.fromkeys(symbols_to_replace, replacement))

    return text.translate(translation_dict)
</code>```

with this timeit code for different texts:

```<code>    # a 'set' for faster lookup
    symbols = {
        '`', '~', '!', '@', '#', '$', '%', '^', '&', '*',
        '(', ')', '_', '-', '+', '=', '{', '[', ']', '}',
        '|', '/', ':', ';', '"', '<', ',', '>', '.', '?',
        '\\',
    }

    text_list = [
        '(Hello World)] *!',
        '~this@is!a^test@',
        '~/()&this@isasd!&=)(/as/dw&%#a^test@' * 1000,
        'a long text without chars to replace' * 1000,
    ]
    for s in text_list:
        assert (
                using_replace(s, symbols)
                == using_join(s, symbols)
                == using_translate(s, symbols))

    for s in text_list:
        print()
        print('text:', repr(s))
        for func in [using_replace, using_join, using_translate]:
            t = timeit.timeit(
                'func(s, symbols)',
                'from __main__ import func, s, symbols',
                number=10000)
            print('{:30s} {:8.3f}'.format(func.__name__, t))
</code>```

Body:
At the texts that I have, I want to replace the following special characters with a single space:

symbols = ["`", "~", "!", "@", "#", "$", "%", "^", "&", "*", "(", ")", "_", "-", "+", "=", "{", "[", "]", "}", "|", "\\", ":", ";", "\"", "<", ",", ">", ".", "?", "/"]

What is the most efficient way (in terms of time of code execution) to do this?

For example, I want this:

(Hello World)] *!

to become this:

Hello World

The candidate methods seem to be the following:

list comprehension

.replace()

.translate()

regular expressions

Body:
My code replaces symbols with spaces and does NOT remove those spaces.

For short strings .join() is fast, but for larger strings .translate() is faster if there is a lot to replace. Surprisingly, .replace() is still very fast if there are few replacements to be made.

text: '(Hello World)] *!'
using_replace                     0.046
using_join                        0.016
using_translate                   0.031

text: '~this@is!a^test@'
using_replace                     0.046
using_join                        0.017
using_translate                   0.029

text: '~/()&this@isasd!&=)(/as/dw&%#a^test@~/()&this@isasd!&=)(/as/dw&%#a^test@~/()&this@isasd!&=)(/as/dw&%#a^test@~/()&this@isasd!&=)(/as/dw&%#a^test@~/()&this@isasd!&=)(/as/dw&%#a^test@~/()&this@isasd!&=)(/as/dw&%#a^test@~/()&this@isasd!&=)(/as/dw&%#a^test@~/()&this@isasd!&=)(/as/dw&%#a^test@~/()&this@isasd!&=)(/as/dw&%#a^test@~/()&this@isasd!&=)(/as/dw&%#a^test@~/()&this@isasd!&=)(/as/dw&%#a^test@~/()&this@isasd!&=)(/as/dw&%#a^test@~/()&this@isasd!&=)(/as/dw&%#a^test@~/()&this@isasd!&=)(/as/dw&%#a^test@~/()&this@isasd!&=)(/as/dw&%#a^test@~/()&this@isasd!&=)(/as/dw&%#a^test@~/()&this@isasd!&=)(/as/dw&%#a^test@~/()&this@isasd!&=)(/as/dw&%#a^test@~/()&this@isasd!&=)(/as/dw&%#a^test@~/()&this@isasd!&=)(/as/dw&%#a^test@~/()&this@isasd!&=)(/as/dw&%#a^test@~/()&this@isasd!&=)(/as/dw&%#a^test@~/()&this@isasd!&=)(/as/dw&%#a^test@~/()&this@isasd!&=)(/as/dw&%#a^test@~/()&this@isasd!&=)(/as/dw&%#a^test@~/()&this@isasd!&=)(/as/dw&%#a^test@~/()&this@isasd!&=)(/as/dw&%#a^test@~/()&this@isasd!&=)(/as/dw&%#a^test@~/()&this@isasd!&=)(/as/dw&%#a^test@~/()&this@isasd!&=)(/as/dw&%#a^test@~/()&this@isasd!&=)(/as/dw&%#a^test@~/()&this@isasd!&=)(/as/dw&%#a^test@~/()&this@isasd!&=)(/as/dw&%#a^test@~/()&this@isasd!&=)(/as/dw&%#a^test@~/()&this@isasd!&=)(/as/dw&%#a^test@~/()&this@isasd!&=)(/as/dw&%#a^test@~/()&this@isasd!&=)(/as/dw&%#a^test@~/()&this@isasd!&=)(/as/dw&%#a^test@~/()&this@isasd!&=)(/as/dw&%#a^test@~/()&this@isasd!&=)(/as/dw&%#a^test@~/()&this@isasd!&=)(/as/dw&%#a^test@~/()&this@isasd!&=)(/as/dw&%#a^test@~/()&this@isasd!&=)(/as/dw&%#a^test@~/()&this@isasd!&=)(/as/dw&%#a^test@~/()&this@isasd!&=)(/as/dw&%#a^test@~/()&this@isasd!&=)(/as/dw&%#a^test@~/()&this@isasd!&=)(/as/dw&%#a^test@~/()&this@isasd!&=)(/as/dw&%#a^test@~/()&this@isasd!&=)(/as/dw&%#a^test@~/()&this@isasd!&=)(/as/dw&%#a^test@~/()&this@isasd!&=)(/as/dw&%#a^test@~/()&this@isasd!&=)(/as/dw&%#a^test@~/()&this@isasd!&=)(/as/dw&%#a^test@~/()&this@isasd!&=)(/as/dw&%#a^test@~/()&this@isasd!&=)(/as/dw&%#a^test@~/()&this@isasd!&=)(/as/dw&%#a^test@~/()&this@isasd!&=)(/as/dw&%#a^test@~/()&this@isasd!&=)(/as/dw&%#a^test@~/()&this@isasd!&=)(/as/dw&%#a^test@~/()&this@isasd!&=)(/as/dw&%#a^test@~/()&this@isasd!&=)(/as/dw&%#a^test@~/()&this@isasd!&=)(/as/dw&%#a^test@~/()&this@isasd!&=)(/as/dw&%#a^test@~/()&this@isasd!&=)(/as/dw&%#a^test@~/()&this@isasd!&=)(/as/dw&%#a^test@~/()&this@isasd!&=)(/as/dw&%#a^test@~/()&this@isasd!&=)(/as/dw&%#a^test@~/()&this@isasd!&=)(/as/dw&%#a^test@~/()&this@isasd!&=)(/as/dw&%#a^test@~/()&this@isasd!&=)(/as/dw&%#a^test@~/()&this@isasd!&=)(/as/dw&%#a^test@~/()&this@isasd!&=)(/as/dw&%#a^test@~/()&this@isasd!&=)(/as/dw&%#a^test@~/()&this@isasd!&=)(/as/dw&%#a^test@~/()&this@isasd!&=)(/as/dw&%#a^test@~/()&this@isasd!&=)(/as/dw&%#a^test@~/()&this@isasd!&=)(/as/dw&%#a^test@~/()&this@isasd!&=)(/as/dw&%#a^test@~/()&this@isasd!&=)(/as/dw&%#a^test@~/()&this@isasd!&=)(/as/dw&%#a^test@~/()&this@isasd!&=)(/as/dw&%#a^test@~/()&this@isasd!&=)(/as/dw&%#a^test@~/()&this@isasd!&=)(/as/dw&%#a^test@~/()&this@isasd!&=)(/as/dw&%#a^test@~/()&this@isasd!&=)(/as/dw&%#a^test@~/()&this@isasd!&=)(/as/dw&%#a^test@~/()&this@isasd!&=)(/as/dw&%#a^test@~/()&this@isasd!&=)(/as/dw&%#a^test@~/()&this@isasd!&=)(/as/dw&%#a^test@~/()&this@isasd!&=)(/as/dw&%#a^test@~/()&this@isasd!&=)(/as/dw&%#a^test@~/()&this@isasd!&=)(/as/dw&%#a^test@~/()&this@isasd!&=)(/as/dw&%#a^test@~/()&this@isasd!&=)(/as/dw&%#a^test@~/()&this@isasd!&=)(/as/dw&%#a^test@~/()&this@isasd!&=)(/as/dw&%#a^test@~/()&this@isasd!&=)(/as/dw&%#a^test@~/()&this@isasd!&=)(/as/dw&%#a^test@~/()&this@isasd!&=)(/as/dw&%#a^test@~/()&this@isasd!&=)(/as/dw&%#a^test@'
using_replace                     0.195
using_join                        2.327
using_translate                   0.061

text: 'a long text without chars to replacea long text without chars to replacea long text without chars to replacea long text without chars to replacea long text without chars to replacea long text without chars to replacea long text without chars to replacea long text without chars to replacea long text without chars to replacea long text without chars to replacea long text without chars to replacea long text without chars to replacea long text without chars to replacea long text without chars to replacea long text without chars to replacea long text without chars to replacea long text without chars to replacea long text without chars to replacea long text without chars to replacea long text without chars to replacea long text without chars to replacea long text without chars to replacea long text without chars to replacea long text without chars to replacea long text without chars to replacea long text without chars to replacea long text without chars to replacea long text without chars to replacea long text without chars to replacea long text without chars to replacea long text without chars to replacea long text without chars to replacea long text without chars to replacea long text without chars to replacea long text without chars to replacea long text without chars to replacea long text without chars to replacea long text without chars to replacea long text without chars to replacea long text without chars to replacea long text without chars to replacea long text without chars to replacea long text without chars to replacea long text without chars to replacea long text without chars to replacea long text without chars to replacea long text without chars to replacea long text without chars to replacea long text without chars to replacea long text without chars to replacea long text without chars to replacea long text without chars to replacea long text without chars to replacea long text without chars to replacea long text without chars to replacea long text without chars to replacea long text without chars to replacea long text without chars to replacea long text without chars to replacea long text without chars to replacea long text without chars to replacea long text without chars to replacea long text without chars to replacea long text without chars to replacea long text without chars to replacea long text without chars to replacea long text without chars to replacea long text without chars to replacea long text without chars to replacea long text without chars to replacea long text without chars to replacea long text without chars to replacea long text without chars to replacea long text without chars to replacea long text without chars to replacea long text without chars to replacea long text without chars to replacea long text without chars to replacea long text without chars to replacea long text without chars to replacea long text without chars to replacea long text without chars to replacea long text without chars to replacea long text without chars to replacea long text without chars to replacea long text without chars to replacea long text without chars to replacea long text without chars to replacea long text without chars to replacea long text without chars to replacea long text without chars to replacea long text without chars to replacea long text without chars to replacea long text without chars to replacea long text without chars to replacea long text without chars to replacea long text without chars to replacea long text without chars to replacea long text without chars to replacea long text without chars to replace'
using_replace                     0.051
using_join                        2.100
using_translate                   0.064

Comparing some strategies:

def using_replace(text, symbols_to_replace, replacement=' '):
    for char in symbols_to_replace:
        text = text.replace(char, replacement)

    return text

def using_join(text, symbols_to_replace, replacement=' '):
    return ''.join(
        replacement if char in symbols_to_replace else char
        for char in text)

def using_translate(text, symbols_to_replace, replacement=' '):
    translation_dict = str.maketrans(
        dict.fromkeys(symbols_to_replace, replacement))

    return text.translate(translation_dict)

with this timeit code for different texts:

    # a 'set' for faster lookup
    symbols = {
        '`', '~', '!', '@', '#', '$', '%', '^', '&', '*',
        '(', ')', '_', '-', '+', '=', '{', '[', ']', '}',
        '|', '/', ':', ';', '"', '<', ',', '>', '.', '?',
        '\\',
    }

    text_list = [
        '(Hello World)] *!',
        '~this@is!a^test@',
        '~/()&this@isasd!&=)(/as/dw&%#a^test@' * 1000,
        'a long text without chars to replace' * 1000,
    ]
    for s in text_list:
        assert (
                using_replace(s, symbols)
                == using_join(s, symbols)
                == using_translate(s, symbols))

    for s in text_list:
        print()
        print('text:', repr(s))
        for func in [using_replace, using_join, using_translate]:
            t = timeit.timeit(
                'func(s, symbols)',
                'from __main__ import func, s, symbols',
                number=10000)
            print('{:30s} {:8.3f}'.format(func.__name__, t))


问:
Hibernate not links entities to Generic
I have class Template:

```<code>@Entity
@Table(name = "templates")
public class Template extends AbstractEntity {

    private List<AbstractField> fields;
}
</code>```

It composes from fields, and I get any like quiz.

I have entities, whick inherits AbstractField:

```<code>@Setter
@MappedSuperclass
public abstract class AbstractField extends AbstractEntity {

    private FieldType fieldType;
    private String title;
    private Template template;
}
</code>```

As we see, we have an abstract class of field (checkbox, radio button etc.), & all fields extends this abstract field, like below:

```<code>@Entity
@Table(name = "field_checkbox")
@Setter
@ToString
@EqualsAndHashCode(callSuper = true)
public class CheckBoxField extends AbstractField {

    private Boolean selection = false;
}
</code>```

I need to link fields with one-to-many dependency. I did it with this way:

```<code>@Entity
@Table(name = "appeal_templates")
public class Template<F extends AbstractField> extends AbstractEntity {

    private List<F> fields;

    @OneToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL, mappedBy = "template")
    public List<F> getFields() {
        return fields;
    }
}
</code>```

As we see, I decided to do it with generic. And I get exception:

Caused by: org.hibernate.AnnotationException: Property
  ru.model.representation.appeal.template.Template.fields has an unbound
  type and no explicit target entity. Resolve this Generic usage issue
  or set an explicit target attribute (eg @OneToMany(target=) or use an
  explicit @Type

As I understand, Hibernate not allow to map to generic. But I plan to store many types of fields, extended AbstractField. What to do?

答:
It's not possible to do with different tables for subclasses. Check this comment why

What you can do is to define single table inheritance type:

```<code>@Entity
@Table(name = "fields")
@Inheritance(strategy=InheritanceType.SINGLE_TABLE)
public abstract class AbstractField extends AbstractEntity {

    private FieldType fieldType;
    private String title;
    private Template template;
}
</code>```

And then you can use List<AbstractField> fields in Template class.

Title: Hibernate not links entities to Generic

Body:
I have class Template:

@Entity
@Table(name = "templates")
public class Template extends AbstractEntity {

    private List<AbstractField> fields;
}

It composes from fields, and I get any like quiz.

I have entities, whick inherits AbstractField:

@Setter
@MappedSuperclass
public abstract class AbstractField extends AbstractEntity {

    private FieldType fieldType;
    private String title;
    private Template template;
}

As we see, we have an abstract class of field (checkbox, radio button etc.), & all fields extends this abstract field, like below:

@Entity
@Table(name = "field_checkbox")
@Setter
@ToString
@EqualsAndHashCode(callSuper = true)
public class CheckBoxField extends AbstractField {

    private Boolean selection = false;
}

I need to link fields with one-to-many dependency. I did it with this way:

@Entity
@Table(name = "appeal_templates")
public class Template<F extends AbstractField> extends AbstractEntity {

    private List<F> fields;

    @OneToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL, mappedBy = "template")
    public List<F> getFields() {
        return fields;
    }
}

As we see, I decided to do it with generic. And I get exception:

Caused by: org.hibernate.AnnotationException: Property
  ru.model.representation.appeal.template.Template.fields has an unbound
  type and no explicit target entity. Resolve this Generic usage issue
  or set an explicit target attribute (eg @OneToMany(target=) or use an
  explicit @Type

As I understand, Hibernate not allow to map to generic. But I plan to store many types of fields, extended AbstractField. What to do?

Body:
It's not possible to do with different tables for subclasses. Check this comment why

What you can do is to define single table inheritance type:

@Entity
@Table(name = "fields")
@Inheritance(strategy=InheritanceType.SINGLE_TABLE)
public abstract class AbstractField extends AbstractEntity {

    private FieldType fieldType;
    private String title;
    private Template template;
}

And then you can use List<AbstractField> fields in Template class.


问:
Leaflet map has incorrect dimensions within Django template blocks
I am using a leaflet map on a website and I am trying to use the template blocks within Django to have a more flexible webpage design whilst keeping common elements. However, when I attempted to implement this, my leaflet map changed dimensions for no apparent reason. The code is the same except it is now within template blocks.

This is what the site should look like (Ignore the grey background, it's just due to the scrolling screenshot)

This is what it looks like with the template blocks

Here is the Github of the project. The correct look of the webpage is the accueil.html file and the new version is based on base.html and accueil_base.html.

I haven't been able to determine what is causing the dimensions issue. Even when I inspect the map element, all the map components are there, only the dimensions are modified.

My apologies regarding the lack of code in this post (I felt it would make this question much longer than needed). I also feel you may have issues recreating my problem since you don't have a database with the corresponding points.

Thanks in advance and please tell me if you need any precise information regarding my problem.

答:
I found that the issue I had was that I forgot to implement the
```

The #map element is inserted into a block that is definer just before the  tag in the base.html file. Since this is all on Github, you should easily be able to see the changes.

Body:
I found that the issue I had was that I forgot to implement the <style> of the map container which is as follows

<style>
    #map {
        width: 100%;
        height: 600px;
    }
</style>

The #map element is inserted into a block that is definer just before the <head> tag in the base.html file. Since this is all on Github, you should easily be able to see the changes.


问:
How can I retrieve the URL of a video I have just uploaded?
I have a Python script that pushes a video file to our Vimeo page via the api, which works perfectly. I'm just having trouble retrieving the link for the video we just uploaded. I found a snippet in the example documentation but it doesnt seem to work.

```<code>import vimeo
import sys

client = vimeo.VimeoClient(
  token="xxxxx",
  key="xxxxx",
  secret="xxxxx"
)

# Make the request to the server for the "/me" endpoint.
about_me = client.get("/me")

# Make sure we got back a successful response.
assert about_me.status_code == 200

# Load the body"s JSON data. WORKS UP TO THIS LINE ENABLE BELOW
print (about_me.json())
#sys.exit(0)

# Path to upload file
path_to_file = r"C:\Users\mydocs\Documents\SS19xGEN.mp4"

print('Uploading: %s' % path_to_file)

# Push file with credentials
client.upload(path_to_file, data={'name': 'TEST', 'description': 'test'})

# Return the uri
print("The uri for the video is %s" % (client))

video_data = client.get(client + 'fields=link').json()
print(('"%s" has been uploaded to %s' % (path_to_file, video_data['link'])))
</code>```

The script works well up until the last two lines, which is my attempt at retrieving the URL of the video I just uploaded in the script, but that gives me the error = "Exception has occurred: TypeError
unsupported operand type(s) for +: 'VimeoClient' and 'str'"

I have poured through the documentation and can't find any examples of how to do this, apologies for the beginner question!

答:
Other way is to receive list of videos using parameters sort and per_page=1

```<code>video_data = client.get('https://api.vimeo.com/me/videos?sort=date&per_page=1').json()
</code>```

Add fields you need in the end of url

Body:
I have a Python script that pushes a video file to our Vimeo page via the api, which works perfectly. I'm just having trouble retrieving the link for the video we just uploaded. I found a snippet in the example documentation but it doesnt seem to work.

import vimeo
import sys

client = vimeo.VimeoClient(
  token="xxxxx",
  key="xxxxx",
  secret="xxxxx"
)

# Make the request to the server for the "/me" endpoint.
about_me = client.get("/me")

# Make sure we got back a successful response.
assert about_me.status_code == 200

# Load the body"s JSON data. WORKS UP TO THIS LINE ENABLE BELOW
print (about_me.json())
#sys.exit(0)

# Path to upload file
path_to_file = r"C:\Users\mydocs\Documents\SS19xGEN.mp4"

print('Uploading: %s' % path_to_file)

# Push file with credentials
client.upload(path_to_file, data={'name': 'TEST', 'description': 'test'})

# Return the uri
print("The uri for the video is %s" % (client))

video_data = client.get(client + 'fields=link').json()
print(('"%s" has been uploaded to %s' % (path_to_file, video_data['link'])))

The script works well up until the last two lines, which is my attempt at retrieving the URL of the video I just uploaded in the script, but that gives me the error = "Exception has occurred: TypeError
unsupported operand type(s) for +: 'VimeoClient' and 'str'"

I have poured through the documentation and can't find any examples of how to do this, apologies for the beginner question!

Body:
Other way is to receive list of videos using parameters sort and per_page=1

video_data = client.get('https://api.vimeo.com/me/videos?sort=date&per_page=1').json()

Add fields you need in the end of url


问:
Check if passed argument value is nil or empty
I am trying to re-write the C# code which i have wrote previously to Swift.

```<code>public static string Right( string value, int length)
{
    if (String.IsNullOrEmpty(value)) return string.Empty;
    return value.Length <= length ? value : value.Substring(value.Length - length);
}
</code>```

I am not able to write if statement effectively in swift.

答:
It can be done as simple as that:</p>

```<code>func right(value: String, length: Int) -> String {
    guard value.count > length, length > 0 else { return value }
    return String(
        value.dropLast(length) // we just drop `length` number of elements from the end
    )
}
</code>```

Body:
I am trying to re-write the C# code which i have wrote previously to Swift.

public static string Right( string value, int length)
{
    if (String.IsNullOrEmpty(value)) return string.Empty;
    return value.Length <= length ? value : value.Substring(value.Length - length);
}

I am not able to write if statement effectively in swift.

Body:
It can be done as simple as that:

func right(value: String, length: Int) -> String {
    guard value.count > length, length > 0 else { return value }
    return String(
        value.dropLast(length) // we just drop `length` number of elements from the end
    )
}


问:
MySQL Query Between Multiple Dates in another table
Feel like this should be something easy that I'm missing. I have a table with multiple timestamps throughout a day, and another table with date ranges. I want to select from the first table whenever it's timestamp is in any of the date ranges in the other table, for a specific day... Anyone have any clue how that could work or if it's even possible?

Edit

```<code>SELECT count(*) FROM Completed /* Returns 59 */

SELECT count(u.user_id) AS Total FROM Completed c
LEFT JOIN users u ON c.user_id = u.user_id
LEFT JOIN logins l ON c.user_id = l.user_id
WHERE c.start BETWEEN l.signIn AND l.signOut
AND c.users_id = 1400
GROUP BY c.type, c.user_id
ORDER BY c.type, Total /* Returns 57 Total */
</code>```

So, my three tables are:

User. user_id int, fullname varchar.

Complete. user_id int, type varchar, start datetime

Logins. user_id int, signIn datetime, signOut datetime

Essentialy I have multiple rows in the complete table, and I want to know how much that the user did, versus how much they had an opportunity to do. "Having the opportunity" is simply being signed in, so I'm trying to get a breakdown of each users total worked, versus available for any work that came in while they were signed in. The thing is they'll have multiple sign in periods throughout one day. I thought I was close above, but no cigar.

Edit 2

Okay, here's what the tables might look like. In the example below I'd want to see that John had the opportunity to work 4 and worked 2 of them. I wouldn't want to count complete_id 4 because he wasn't at work yet. My ideal result would look something like:

```<code>name | type | available | worked | sign in             | sign out
Jack | SUV  | 1         |      1 | 2011-04-08 12:30:00 | 2011-04-08 13:00:00
Jack | SUV  | 3         |      0 | 2011-04-08 13:30:00 | 2011-04-08 14:00:00 // Had An Opportunity to work, but didn't work any
Jack | SUV  | 5         |      2 | 2011-04-08 14:30:00 | 2011-04-08 15:00:00  // Worked two
</code>```

users table

```<code>user_id | fullname
1400    | Jack
1401    | John
</code>```

complete table

```<code>complete_id | user_id | type | start
1           | 1400    | Car  | 2011-04-08 18:36:22
2           | 1400    | Boat | 2011-04-08 12:31:42
3           | 1401    | SUV  | 2011-04-08 11:14:12
4           | 1400    | Car  | 2011-04-08 1:56:52
5           | 1401    | Car  | 2011-04-08 16:11:23
</code>```

logins table

```<code>login_id | user_id | signIn             | signOut
1        | 1400    | 2011-04-08 1:00:00 | 2011-04-08 21:00:00
1        | 1401    | 2011-04-08 11:00:00 | 2011-04-08 21:00:00
</code>```

答:
The following SQL should work for you to get the counts you are looking for.  The only thing which is missing is the type of work completed.  Only having that in the completed tables complicates things a bit, but I am sure it is doable with a bit more thinking.

The basic idea here is we are building a complete dataset of values and aggregating the counts we need.  I use this method a lot when working across date ranges.  It is usually pretty efficient too.

```<code>SELECT Users.Name, Users.SignIn, Users.SignOut,
SUM(CASE WHEN Complete.Start BETWEEN Users.SignIn AND Users.SignOut THEN 1 Else 0) as Available,
SUM(CASE WHEN Complete.Start BETWEEN Users.SignIn AND Users.SignOut AND Users.User_Id = Complete.User_Id THEN 1 ELSE 0) as Worked
FROM Users inner join logins on users.user_id = logins.user_id, Complete
GROUP BY Users.Name, Users.SignIn, Users.SignOut
</code>```

You may want to add a WHERE statement to restrict the date range (and number of rows) of the query including complete and logins tables.

ContentLicense: CC BY-SA 3.0

Body:
Feel like this should be something easy that I'm missing. I have a table with multiple timestamps throughout a day, and another table with date ranges. I want to select from the first table whenever it's timestamp is in any of the date ranges in the other table, for a specific day... Anyone have any clue how that could work or if it's even possible?

Edit

SELECT count(*) FROM Completed /* Returns 59 */

SELECT count(u.user_id) AS Total FROM Completed c
LEFT JOIN users u ON c.user_id = u.user_id
LEFT JOIN logins l ON c.user_id = l.user_id
WHERE c.start BETWEEN l.signIn AND l.signOut
AND c.users_id = 1400
GROUP BY c.type, c.user_id
ORDER BY c.type, Total /* Returns 57 Total */

So, my three tables are:

User. user_id int, fullname varchar.

Complete. user_id int, type varchar, start datetime

Logins. user_id int, signIn datetime, signOut datetime

Essentialy I have multiple rows in the complete table, and I want to know how much that the user did, versus how much they had an opportunity to do. "Having the opportunity" is simply being signed in, so I'm trying to get a breakdown of each users total worked, versus available for any work that came in while they were signed in. The thing is they'll have multiple sign in periods throughout one day. I thought I was close above, but no cigar.

Edit 2

Okay, here's what the tables might look like. In the example below I'd want to see that John had the opportunity to work 4 and worked 2 of them. I wouldn't want to count complete_id 4 because he wasn't at work yet. My ideal result would look something like:

name | type | available | worked | sign in             | sign out
Jack | SUV  | 1         |      1 | 2011-04-08 12:30:00 | 2011-04-08 13:00:00
Jack | SUV  | 3         |      0 | 2011-04-08 13:30:00 | 2011-04-08 14:00:00 // Had An Opportunity to work, but didn't work any
Jack | SUV  | 5         |      2 | 2011-04-08 14:30:00 | 2011-04-08 15:00:00  // Worked two

users table

user_id | fullname
1400    | Jack
1401    | John

complete table

complete_id | user_id | type | start
1           | 1400    | Car  | 2011-04-08 18:36:22
2           | 1400    | Boat | 2011-04-08 12:31:42
3           | 1401    | SUV  | 2011-04-08 11:14:12
4           | 1400    | Car  | 2011-04-08 1:56:52
5           | 1401    | Car  | 2011-04-08 16:11:23

logins table

login_id | user_id | signIn             | signOut
1        | 1400    | 2011-04-08 1:00:00 | 2011-04-08 21:00:00
1        | 1401    | 2011-04-08 11:00:00 | 2011-04-08 21:00:00

Body:
The following SQL should work for you to get the counts you are looking for.  The only thing which is missing is the type of work completed.  Only having that in the completed tables complicates things a bit, but I am sure it is doable with a bit more thinking.

The basic idea here is we are building a complete dataset of values and aggregating the counts we need.  I use this method a lot when working across date ranges.  It is usually pretty efficient too.

SELECT Users.Name, Users.SignIn, Users.SignOut,
SUM(CASE WHEN Complete.Start BETWEEN Users.SignIn AND Users.SignOut THEN 1 Else 0) as Available,
SUM(CASE WHEN Complete.Start BETWEEN Users.SignIn AND Users.SignOut AND Users.User_Id = Complete.User_Id THEN 1 ELSE 0) as Worked
FROM Users inner join logins on users.user_id = logins.user_id, Complete
GROUP BY Users.Name, Users.SignIn, Users.SignOut

You may want to add a WHERE statement to restrict the date range (and number of rows) of the query including complete and logins tables.


问:
Arithmetic operation in PHP String with colon ( : ) punctuation
I'm trying to solve the problem comparing two-time string and it's working fine. Here's code.

Somehow I'm not getting why it's working. How String with colon ( : )  punctuation is correctly comparing?

$start = "10:00";
$end = "22:00";

if($start > $end) {
    echo "Start time is more than End time.";
} else {
    echo "End time is less than Start time.";
}
```

Now everything is working fine and output is:

End time is less than Start time.

Sorry if I'm missing something kindly provide details into this.

Thank you.

答:
it is just comparing strings like below

```<code>if("overflow"=="stock"){
   echo "right";
}else{
   echo "wrong";
}
</code>```

if you want to compare the actual values in the variable better to convert them to numbers

thank you

Body:
I'm trying to solve the problem comparing two-time string and it's working fine. Here's code.

Somehow I'm not getting why it's working. How String with colon ( : )  punctuation is correctly comparing?

$start = "10:00";
$end = "22:00";

if($start > $end) {
    echo "Start time is more than End time.";
} else {
    echo "End time is less than Start time.";
}

Now everything is working fine and output is:

End time is less than Start time.

Sorry if I'm missing something kindly provide details into this.

Thank you.

Body:
it is just comparing strings like below

if("overflow"=="stock"){
   echo "right";
}else{
   echo "wrong";
}

if you want to compare the actual values in the variable better to convert them to numbers

thank you


问:
How to find nodes with exact info_hash in Bittorrent DHT?
In the documentation of DHT protocol for bittorrent,it is given that get_peers method is used for finding nodes with given info_hash.It says that if response contains "values" key,the queried node has returned the information about nodes containing exact info_hash.If node returns "nodes" key,it has returned K nodes closest to the result.Should we recursively call get_peers on returned nodes(closest) in order to reach till exact nodes(with same info_hash)?</p>

答:
Should we recursively call get_peers on returned nodes(closest) in order to reach till exact nodes(with same info_hash)?

Yes and no. You could use a recursive function if you are the LISP kind. That said, a while loop will do the job. Here is some python code that implement the FIND_VALUE algorithm with some comments:

```<code>async def _get(self, key):
    """Fetch the value associated with KEY from the network"""
    uid = key
    queried = set()
    while True:
        # retrieve the k nearest peers and remove already queried peers
        peers = nearest(k, self.peers)
        # no more peer to query, the key is not found in the dht
        if not peers:
            raise KeyError(uid)
        # query selected peers
        responses = dict()
        for address in peers:
            response = self._protocol.rpc(address, "value", uid)
            responses[address] = response
        # check responses: look for the value or add peers more near KEY
        for (address, response) in responses.items():
            queried.add(address)
            if isinstance(response, Exception):
                continue
            elif response[0] == b"VALUE":
                # value is found, return it
                value = response[1]
                if hash(value) == unpack(uid):
                    # at last!
                    return value
                else:
                    log.warning(
                        "[%r] bad value returned from %r", self._uid, address
                    )
                    await self.blacklist(address)
                    continue
            elif response[0] == b"PEERS":
                # value not found but we got peers that are more near KEY
                await self._welcome_peers(response[1])
</code>```

This code is based on qadom's peer.py

Body:
Should we recursively call get_peers on returned nodes(closest) in order to reach till exact nodes(with same info_hash)?

Yes and no. You could use a recursive function if you are the LISP kind. That said, a while loop will do the job. Here is some python code that implement the FIND_VALUE algorithm with some comments:

async def _get(self, key):
    """Fetch the value associated with KEY from the network"""
    uid = key
    queried = set()
    while True:
        # retrieve the k nearest peers and remove already queried peers
        peers = nearest(k, self.peers)
        # no more peer to query, the key is not found in the dht
        if not peers:
            raise KeyError(uid)
        # query selected peers
        responses = dict()
        for address in peers:
            response = self._protocol.rpc(address, "value", uid)
            responses[address] = response
        # check responses: look for the value or add peers more near KEY
        for (address, response) in responses.items():
            queried.add(address)
            if isinstance(response, Exception):
                continue
            elif response[0] == b"VALUE":
                # value is found, return it
                value = response[1]
                if hash(value) == unpack(uid):
                    # at last!
                    return value
                else:
                    log.warning(
                        "[%r] bad value returned from %r", self._uid, address
                    )
                    await self.blacklist(address)
                    continue
            elif response[0] == b"PEERS":
                # value not found but we got peers that are more near KEY
                await self._welcome_peers(response[1])

This code is based on qadom's peer.py


问:
Problem with image tag on upload in tinymce
i have a problem when i upload image with copy paste in tinymce editor.

I get something like this:

```<code>[img]data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAA/gAAADsCAYAAADAdA2HAAAgAElEQVR4Ae3dDXBd1X0g8L+xEeBaQEQc8xFsTDPrVGNcOihWa7BTUFrsZAvNtsLehYEJnWHN7jhuGNEs9GOnbdYUrGkhnnZdmrIDNbtgZUugm5XZjUhiL+7IKE1wjBJnSBwb4mIcXMCOjWUb79z3IT1JT7Kk+6R3Zf8049F9995z7v/8zn3P+t977nlTTp48eTLG+PPugQNxfl3dGEsr....
</code>```

but what i want is

Any suggestion how can i achive that?

this is my setup:

```<code>tinymceFunction() {
    tinymce.init({
        relative_urls: false,
        document_base_url: window.location.protocol + '//' + window.location.host + '/' + window.location.pathname.split('/')[1],
        skin_url: 'assets/skins/lightgray',
        paste_data_images: true,
        menubar: true,
        statusbar: false,
        selector: '#' + this.elementId,
        branding: false,
        plugins: ['link', 'table', 'autoresize', 'code', 'bbcode', "image paste"],
        toolbar: 'undo redo | styleselect  | bold italic | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | link',
        autoresize_min_height: 50,
        autoresize_max_height: 300,
        setup: (editor: any) => {
            this.editor = editor;
            editor.on('keyup change', () => {
                const content = editor.getContent();
                this.onEditorContentChange.emit(content);
            });
        },
        images_dataimg_filter: function (img) {
            return img.hasAttribute('internal-blob');
        }
    });
</code>```

答:
You are loading the bbcode plugin:  https://www.tiny.cloud/docs/plugins/bbcode/

That plugin will make TinyMCE return bbcode to you as opposed to HTML.  If you want HTML I would remove the bbcode plugin.

Body:
i have a problem when i upload image with copy paste in tinymce editor.

I get something like this:

[img]data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAA/gAAADsCAYAAADAdA2HAAAgAElEQVR4Ae3dDXBd1X0g8L+xEeBaQEQc8xFsTDPrVGNcOihWa7BTUFrsZAvNtsLehYEJnWHN7jhuGNEs9GOnbdYUrGkhnnZdmrIDNbtgZUugm5XZjUhiL+7IKE1wjBJnSBwb4mIcXMCOjWUb79z3IT1JT7Kk+6R3Zf8049F9995z7v/8zn3P+t977nlTTp48eTLG+PPugQNxfl3dGEsr....

but what i want is

Any suggestion how can i achive that?

this is my setup:

tinymceFunction() {
    tinymce.init({
        relative_urls: false,
        document_base_url: window.location.protocol + '//' + window.location.host + '/' + window.location.pathname.split('/')[1],
        skin_url: 'assets/skins/lightgray',
        paste_data_images: true,
        menubar: true,
        statusbar: false,
        selector: '#' + this.elementId,
        branding: false,
        plugins: ['link', 'table', 'autoresize', 'code', 'bbcode', "image paste"],
        toolbar: 'undo redo | styleselect  | bold italic | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | link',
        autoresize_min_height: 50,
        autoresize_max_height: 300,
        setup: (editor: any) => {
            this.editor = editor;
            editor.on('keyup change', () => {
                const content = editor.getContent();
                this.onEditorContentChange.emit(content);
            });
        },
        images_dataimg_filter: function (img) {
            return img.hasAttribute('internal-blob');
        }
    });


问:
How to ignore items List<T> inside Dictionary<K, List<T>> in c#
I have to ignore the items(List) whose product type is not contains in a given string which is inside a dictionary.

I tried to iterate the dictionary in a foreach loop and check the product type inside the loop and it works fine, but I wanted to use without iterating it, Is there anyway to achieve this?

```<code>private ConcurrentDictionary<string, List<PAAMsg>> FilterAllowedProductsTrades(ConcurrentDictionary<string, List<PAAMsg>> allPAA)
{
    ConcurrentDictionary<string, List<PAAMsg>> newPAA = new ConcurrentDictionary<string, List<PAAMsg>>();
    string productType = "BFO,BFT,BOND FWD,CAP,FEE,FEX,FRA,FUT,FxFUT,MFO,SWP,OFT,SWT";

    foreach (var item in allPAA)
    {
        newPAA.TryAdd(
            item.Key,
            item.Value.FindAll((x => productType.Split(',').Contains(x.ProductType)))
        .ToList());
    }
    return newPAA;
}
</code>```

I wants to avoid the below iteration and should be in a single line.

```<code>foreach (var item in allPAA)
{
    newPAA.TryAdd(
        item.Key,
        item.Value.FindAll((x => productType.Split(',').Contains(x.ProductType))).ToList());
}
</code>```

答:
I don't think it's possible to avoid the loop, LINQ will just bury it behind its syntax. So it's a matter of preference.

One possible alternative looks like this:

```<code>private ConcurrentDictionary<string, List<PAAMsg>> FilterAllowedProductsTrades(ConcurrentDictionary<string, List<PAAMsg>> allPAA)
{
    string productType = "BFO,BFT,BOND FWD,CAP,FEE,FEX,FRA,FUT,FxFUT,MFO,SWP,OFT,SWT";
    var productTypes = productType.Split(',');

    var enumeration = allPAA.ToDictionary(
            x => x.Key,
            x => x.Value.Where(p => productTypes.Contains(p.ProductType)).ToList());

    return new ConcurrentDictionary<string, List<PAAMsg>>(enumeration);
}
</code>```

Also I would suggest to move Split operation out of the loop.

Body:
I have to ignore the items(List) whose product type is not contains in a given string which is inside a dictionary.

I tried to iterate the dictionary in a foreach loop and check the product type inside the loop and it works fine, but I wanted to use without iterating it, Is there anyway to achieve this?

private ConcurrentDictionary<string, List<PAAMsg>> FilterAllowedProductsTrades(ConcurrentDictionary<string, List<PAAMsg>> allPAA)
{
    ConcurrentDictionary<string, List<PAAMsg>> newPAA = new ConcurrentDictionary<string, List<PAAMsg>>();
    string productType = "BFO,BFT,BOND FWD,CAP,FEE,FEX,FRA,FUT,FxFUT,MFO,SWP,OFT,SWT";

    foreach (var item in allPAA)
    {
        newPAA.TryAdd(
            item.Key,
            item.Value.FindAll((x => productType.Split(',').Contains(x.ProductType)))
        .ToList());
    }
    return newPAA;
}

I wants to avoid the below iteration and should be in a single line.

foreach (var item in allPAA)
{
    newPAA.TryAdd(
        item.Key,
        item.Value.FindAll((x => productType.Split(',').Contains(x.ProductType))).ToList());
}

Body:
I don't think it's possible to avoid the loop, LINQ will just bury it behind its syntax. So it's a matter of preference.

One possible alternative looks like this:

private ConcurrentDictionary<string, List<PAAMsg>> FilterAllowedProductsTrades(ConcurrentDictionary<string, List<PAAMsg>> allPAA)
{
    string productType = "BFO,BFT,BOND FWD,CAP,FEE,FEX,FRA,FUT,FxFUT,MFO,SWP,OFT,SWT";
    var productTypes = productType.Split(',');

    var enumeration = allPAA.ToDictionary(
            x => x.Key,
            x => x.Value.Where(p => productTypes.Contains(p.ProductType)).ToList());

    return new ConcurrentDictionary<string, List<PAAMsg>>(enumeration);
}

Also I would suggest to move Split operation out of the loop.


问:
Exponentiation on a point on elliptic curve unreasonably fast in SageMath
I am working on elliptic curves in sagemath. I was trying to collect benchmarks for group operation and exponentiation of points on NIST P-256 elliptic curve. When I tried to perform a group operation on 2 points on the curve, it takes roughly 2 micro seconds. When I tried to perform exponentiation on a point in elliptic curve with a random exponent, it takes only 3 micro seconds. How is this even possible? Since I am exponentiating with a 256 bit value, this should at least take time required for 256 group operations, which is more than 0.5ms. I am worried if my code is wrong!</p>

```<code>p = 115792089210356248762697446949407573530086143415290314195533631308867097853951
order = 115792089210356248762697446949407573529996955224135760342422259061068512044369
b = 0x5ac635d8aa3a93e7b3ebbd55769886bc651d06b0cc53b0f63bce3c3e27d2604b
F = GF(p)
E = EllipticCurve(F, [-3,b])
runs = 10000
G = E.abelian_group()

F2 = GF(order)
exponent = [F2.random_element() for i in range(runs)]
e2 = [G.random_element() for i in range(runs)]

t1 = time()
for i in range(runs):
      e = Integer(exponent[i])*e2[i]
t2 = time()
print  "Time per operation = ", (t2 - t1)/runs , " seconds"

e1 = [G.random_element() for i in range(runs)]
e2 = [G.random_element() for i in range(runs)]
t1 = time()
for i in range(runs):
         e = e1[i]+e2[i]
t2 = time()
print  "Time per operation = ", (t2 - t1)/runs , " seconds"
</code>```

Body:
I am working on elliptic curves in sagemath. I was trying to collect benchmarks for group operation and exponentiation of points on NIST P-256 elliptic curve. When I tried to perform a group operation on 2 points on the curve, it takes roughly 2 micro seconds. When I tried to perform exponentiation on a point in elliptic curve with a random exponent, it takes only 3 micro seconds. How is this even possible? Since I am exponentiating with a 256 bit value, this should at least take time required for 256 group operations, which is more than 0.5ms. I am worried if my code is wrong!

p = 115792089210356248762697446949407573530086143415290314195533631308867097853951
order = 115792089210356248762697446949407573529996955224135760342422259061068512044369
b = 0x5ac635d8aa3a93e7b3ebbd55769886bc651d06b0cc53b0f63bce3c3e27d2604b
F = GF(p)
E = EllipticCurve(F, [-3,b])
runs = 10000
G = E.abelian_group()

F2 = GF(order)
exponent = [F2.random_element() for i in range(runs)]
e2 = [G.random_element() for i in range(runs)]

t1 = time()
for i in range(runs):
      e = Integer(exponent[i])*e2[i]
t2 = time()
print  "Time per operation = ", (t2 - t1)/runs , " seconds"

e1 = [G.random_element() for i in range(runs)]
e2 = [G.random_element() for i in range(runs)]
t1 = time()
for i in range(runs):
         e = e1[i]+e2[i]
t2 = time()
print  "Time per operation = ", (t2 - t1)/runs , " seconds"

Body:
Do not use E.abelian_group() if your goal is to time the elliptic curve scalar multiplication:

sage: P = G.random_element()
sage: P.parent()
Additive abelian group isomorphic to Z/115792089210356248762697446949407573529996955224135760342422259061068512044369 embedded in Abelian group of points on Elliptic Curve defined by y^2 = x^3 + 115792089210356248762697446949407573530086143415290314195533631308867097853948*x + 41058363725152142129326129780047268409114441015993725554835256314039467401291 over Finite Field of size 115792089210356248762697446949407573530086143415290314195533631308867097853951
sage: P.__class__
<class 'sage.groups.additive_abelian.additive_abelian_wrapper.AdditiveAbelianGroupWrapper_with_category.element_class'>
sage: Q = E.random_element()
sage: Q.parent()
Abelian group of points on Elliptic Curve defined by y^2 = x^3 + 115792089210356248762697446949407573530086143415290314195533631308867097853948*x + 41058363725152142129326129780047268409114441015993725554835256314039467401291 over Finite Field of size 115792089210356248762697446949407573530086143415290314195533631308867097853951
sage: Q.__class__
<class 'sage.schemes.elliptic_curves.ell_point.EllipticCurvePoint_finite_field'>

E.abelian_group() is a discrete log representation of E(_p): one (or more) generator for the group is chosen:

sage: G.gens()
((20722840521025081260844746572646324413063607211611059363846436737341554936251 : 92859506829486198345561119925850006904261672023969849576492780649068338418688 : 1),)

and points are represented as vectors of exponents:

sage: P.vector()
(115792089210356248762697446949407573529996955224135760342422259061068512044368)

hence c*P simply multiplies the exponent by c and reduces modulo the order of the curve.

Use E.random_element() to get points of the curve and perform true elliptic curve operations:

sage: c = 2^100
sage: %timeit c*Q
100 loops, best of 3: 3.88 ms per loop
sage: c = 2^1000
sage: %timeit c*Q
10 loops, best of 3: 32.4 ms per loop
sage: c = 2^10000
sage: %timeit c*Q
1 loop, best of 3: 321 ms per loop


问:
Retrieving Time Dependent Data Statistics (counts) by flag, split on foreign id, across multiple tables, returned in one dataset
I have a table of items that are split on a siteId and a status.

```<code>CREATE TABLE ItemDetail (
    ItemNumber    long,
    SiteId        int,
    Status        int,
    Created       datetime
)
</code>```

And then I also have a user's table

```<code>CREATE TABLE UserDetail (
    UserId        int,
    Suspended     int
)
</code>```

Status has 7 possible values (0-6) representing different queues.  Let's call this variable x.  Suspended, should only have 0 (active) or 1 (suspended).  (don't ask me why it's an int, I didn't build it).  Data is shown per site in a configurable time frame.  Default is 5 days back.  Let's call this variable a.  I want to return, in one call, a dataset like this:

```<code>ActiveUserCount        int
SuspendedUserCount     int,
Queue0Count            int,
Queue0TodayCount       int,
Queue1Count            int,
Queue1TodayCount       int,
...
</code>```

Where QueueXCount is everything in the last a days by status and siteid. QueueXTodayCount is everything with status x that happened today.  So far, I have started a sproc like this

```<code>CREATE PROCEDURE GetSiteStatistics
    @SiteId       int,
    @Window       int
AS
BEGIN
DECLARE @Today datetime
DECLARE @Tomorrow datetime
DECLARE @CutOff datetime

SET @Today = (CAST(YEAR(getdate()) as varchar) +
    RIGHT('00' + CAST(MONTH(getdate()) as varchar), 2) +
    RIGHT('00' + CAST(DAY(getdate()) as varchar), 2))

SET @Tomorrow  = DATEADD(dd, 1, @Today)

SET @CutOff = DATEADD(dd, @Window + 1, @Today)

DECLARE
    @SuspendedUserCount         int,
    @ActiveUserCount            int,
    @Queue0Count                int,
    @Queue0TodayCount           int,
    ...

SELECT @SuspendedUserCount = count(UserId) FROM UserDetail WHERE Suspended = 1 AND SiteId = @SiteId
SELECT @ActiveUserCount = count(UserId) FROM UserDetail WHERE Suspended = 0 AND SiteId = @SiteId
SELECT @Queue0Count = count(ItemNumber) FROM ItemDetail WHERE Status = 0 AND SiteId = @SiteId   AND Created >= @Today AND Created < @CutOff
SELECT @Queue0TodayCount = count(ItemNumber) FROM ItemDetail WHERE Status = 0 AND SiteId = @SiteId AND Created >= @Today AND Created < @Tomorrow
...

SELECT @SuspendedUserCount AS SuspendedUsers, @ActiveUserCount AS ActiveUsers, @Queue0Count AS Queue0, @Queue0TodayCount AS @Queue0Today...
END
</code>```

As if that isn't complicated enough, I am using Fluent Nhibernate.  I'm not against using a sproc if I have to, but I have considered creating a view with the counts by day, pulling that in using nhibernate and a query to pick by date range, and then summing the amounts where appropriate in code.

I just have a feeling I am making this more complicated than I have to.  There must be a better way.

答:
I created a view using CTE and a pivot

```<code>CREATE VIEW [dbo].[SiteQueueDailyStatistics]
AS

WITH statCTE AS (
    SELECT
        Count(ItemNumber)as ItemCount,
        SiteId,
        Status,
        DATEADD(dd, 0, DATEDIFF(dd, 0, ScanDate)) AS ScanDay
    FROM
        ItemDetail
    group by  SiteId, Status, DATEADD(dd, 0, DATEDIFF(dd, 0, ScanDate))
)

SELECT
    SiteId,
    ScanDay,
    ISNULL([0], 0) AS Queue0,
    ISNULL([1], 0) AS Queue1,
    ISNULL([2], 0) AS Queue2,
    ISNULL([3], 0) AS Queue3,
    ISNULL([4], 0) AS Queue4,
    ISNULL([5], 0) AS Queue5,
    ISNULL([6], 0) AS Queue6
FROM
    statCTE
PIVOT
(
    SUM(ItemCount)
    FOR [Status] IN ([0], [1], [2], [3], [4], [5], [6])
)
AS p

GO
</code>```

And then I get all my data and populate a composite object in my model that holds the statistics across multiple tables.

Body:
I have a table of items that are split on a siteId and a status.

CREATE TABLE ItemDetail (
    ItemNumber    long,
    SiteId        int,
    Status        int,
    Created       datetime
)

And then I also have a user's table

CREATE TABLE UserDetail (
    UserId        int,
    Suspended     int
)

Status has 7 possible values (0-6) representing different queues.  Let's call this variable x.  Suspended, should only have 0 (active) or 1 (suspended).  (don't ask me why it's an int, I didn't build it).  Data is shown per site in a configurable time frame.  Default is 5 days back.  Let's call this variable a.  I want to return, in one call, a dataset like this:

ActiveUserCount        int
SuspendedUserCount     int,
Queue0Count            int,
Queue0TodayCount       int,
Queue1Count            int,
Queue1TodayCount       int,
...

Where QueueXCount is everything in the last a days by status and siteid. QueueXTodayCount is everything with status x that happened today.  So far, I have started a sproc like this

CREATE PROCEDURE GetSiteStatistics
    @SiteId       int,
    @Window       int
AS
BEGIN
DECLARE @Today datetime
DECLARE @Tomorrow datetime
DECLARE @CutOff datetime

SET @Today = (CAST(YEAR(getdate()) as varchar) +
    RIGHT('00' + CAST(MONTH(getdate()) as varchar), 2) +
    RIGHT('00' + CAST(DAY(getdate()) as varchar), 2))

SET @Tomorrow  = DATEADD(dd, 1, @Today)

SET @CutOff = DATEADD(dd, @Window + 1, @Today)

DECLARE
    @SuspendedUserCount         int,
    @ActiveUserCount            int,
    @Queue0Count                int,
    @Queue0TodayCount           int,
    ...

SELECT @SuspendedUserCount = count(UserId) FROM UserDetail WHERE Suspended = 1 AND SiteId = @SiteId
SELECT @ActiveUserCount = count(UserId) FROM UserDetail WHERE Suspended = 0 AND SiteId = @SiteId
SELECT @Queue0Count = count(ItemNumber) FROM ItemDetail WHERE Status = 0 AND SiteId = @SiteId   AND Created >= @Today AND Created < @CutOff
SELECT @Queue0TodayCount = count(ItemNumber) FROM ItemDetail WHERE Status = 0 AND SiteId = @SiteId AND Created >= @Today AND Created < @Tomorrow
...

SELECT @SuspendedUserCount AS SuspendedUsers, @ActiveUserCount AS ActiveUsers, @Queue0Count AS Queue0, @Queue0TodayCount AS @Queue0Today...
END

As if that isn't complicated enough, I am using Fluent Nhibernate.  I'm not against using a sproc if I have to, but I have considered creating a view with the counts by day, pulling that in using nhibernate and a query to pick by date range, and then summing the amounts where appropriate in code.

I just have a feeling I am making this more complicated than I have to.  There must be a better way.

Body:
I created a view using CTE and a pivot

CREATE VIEW [dbo].[SiteQueueDailyStatistics]
AS

WITH statCTE AS (
    SELECT
        Count(ItemNumber)as ItemCount,
        SiteId,
        Status,
        DATEADD(dd, 0, DATEDIFF(dd, 0, ScanDate)) AS ScanDay
    FROM
        ItemDetail
    group by  SiteId, Status, DATEADD(dd, 0, DATEDIFF(dd, 0, ScanDate))
)

SELECT
    SiteId,
    ScanDay,
    ISNULL([0], 0) AS Queue0,
    ISNULL([1], 0) AS Queue1,
    ISNULL([2], 0) AS Queue2,
    ISNULL([3], 0) AS Queue3,
    ISNULL([4], 0) AS Queue4,
    ISNULL([5], 0) AS Queue5,
    ISNULL([6], 0) AS Queue6
FROM
    statCTE
PIVOT
(
    SUM(ItemCount)
    FOR [Status] IN ([0], [1], [2], [3], [4], [5], [6])
)
AS p

GO

And then I get all my data and populate a composite object in my model that holds the statistics across multiple tables.


问:
Disable spark catalyst optimizer
To give some background, I am trying to run TPCDS benchmark on Spark with and without Spark's catalyst optimizer. For complicated queries on smaller datasets, we might be spending more time optimizing the plans than actually executing the plans. Hence wanted to measure the performance impact of optimizers on overall execution of the query

Is there a way to disable some or all of the spark catalyst optimization rules?

答:
This ability has been added as part of Spark-2.4.0 in SPARK-24802.

```<code>val OPTIMIZER_EXCLUDED_RULES = buildConf("spark.sql.optimizer.excludedRules")
    .doc("Configures a list of rules to be disabled in the optimizer, in which the rules are " +
      "specified by their rule names and separated by comma. It is not guaranteed that all the " +
      "rules in this configuration will eventually be excluded, as some rules are necessary " +
      "for correctness. The optimizer will log the rules that have indeed been excluded.")
    .stringConf
    .createOptional

</code>```

You could find the list of optimizer rules here.

But ideally, we shouldn't be disabling the rules, since most of them provide performance benefits. We should identify the rule that consumes time and check if is not useful for the query and then disable them.

Title: Disable spark catalyst optimizer

Body:
This ability has been added as part of Spark-2.4.0 in SPARK-24802.

val OPTIMIZER_EXCLUDED_RULES = buildConf("spark.sql.optimizer.excludedRules")
    .doc("Configures a list of rules to be disabled in the optimizer, in which the rules are " +
      "specified by their rule names and separated by comma. It is not guaranteed that all the " +
      "rules in this configuration will eventually be excluded, as some rules are necessary " +
      "for correctness. The optimizer will log the rules that have indeed been excluded.")
    .stringConf
    .createOptional

You could find the list of optimizer rules here.

But ideally, we shouldn't be disabling the rules, since most of them provide performance benefits. We should identify the rule that consumes time and check if is not useful for the query and then disable them.


问:
How to export a table with code into a file
I would like to export a table from Firebird database into a CSV file. With MySQL, I can use an SQL with additional commands like INTO OUTFILE. Here is an example:

```<code>SELECT a,b,a+b INTO OUTFILE '/tmp/result.csv'
FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '"'
LINES TERMINATED BY '\n'
FROM test_table;
</code>```

This query can be submitted on several sql-query-tools (MySQL WB, HeidiSQL, ccenter).
Is it possible using, for example FlameRobin, to submit an SQL statement like above to export data from Firebird?
I may use FlameRobin using the menu or another tool like FBexport, but I prefer the one-code solution without clicking on the menu or using additional tools (FBexport).

答:
I know its a lil bit late... But
There is a way to export it using OUTPUT ISQL command.

It will be like:

```<code>`OUTPUT C:\file_name.txt;`
`SELECT A, B, A+B FROM EXMAPLE_TABLE;`
`OUTPUT;`
</code>```

So the content of your select statement will be on your txt file.

Remember to create the empty file before using the OUTPUT;

Body:
I would like to export a table from Firebird database into a CSV file. With MySQL, I can use an SQL with additional commands like INTO OUTFILE. Here is an example:

SELECT a,b,a+b INTO OUTFILE '/tmp/result.csv'
FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '"'
LINES TERMINATED BY '\n'
FROM test_table;

This query can be submitted on several sql-query-tools (MySQL WB, HeidiSQL, ccenter).
Is it possible using, for example FlameRobin, to submit an SQL statement like above to export data from Firebird?
I may use FlameRobin using the menu or another tool like FBexport, but I prefer the one-code solution without clicking on the menu or using additional tools (FBexport).

Body:
I know its a lil bit late... But
There is a way to export it using OUTPUT ISQL command.

It will be like:

`OUTPUT C:\file_name.txt;`
`SELECT A, B, A+B FROM EXMAPLE_TABLE;`
`OUTPUT;`

So the content of your select statement will be on your txt file.

Remember to create the empty file before using the OUTPUT;


问:
How to close Python application by messagebox
I am absolute beginner in Python.

I would like to check if the file exists before my application started.
If the file does not exist I think there should be error messagebox with one button which closes the app.

Here is my code

```<code>from PyQt5 import QtWidgets
from PyQt5.QtWidgets import QMessageBox

from decryptwindow import Ui_Dialog  # importing our generated file

import sys
import os

class mywindow(QtWidgets.QMainWindow):
    def __init__(self):
        super(mywindow, self).__init__()
        self.ui = Ui_Dialog()
        self.ui.setupUi(self)

ini_file = 'config.ini'
ini_file_exists = os.path.isfile(ini_file)

if ini_file_exists:
    # just for testing
    print(ini_file + ' is found')
    # let`s show the main window
    app = QtWidgets.QApplication([])
    application = mywindow()
    application.show()
    sys.exit(app.exec())
else:
    # just for testing
    print(ini_file + ' is not found')
    app = QtWidgets.QApplication([])
    application = mywindow()
    application.show()
    error_dialog = QtWidgets.QErrorMessage()
    error_dialog.showMessage(ini_file + ' is not found')
    # after message I would like just close the application
    sys.exit(app.exec())
</code>```

答:
Well, that was simple.
Shame on me I didn`t try before posting.

Removing these 2 lines solved the issue

```<code>application = mywindow()
application.show()
</code>```

Body:
I am absolute beginner in Python.

I would like to check if the file exists before my application started.
If the file does not exist I think there should be error messagebox with one button which closes the app.

Here is my code

from PyQt5 import QtWidgets
from PyQt5.QtWidgets import QMessageBox

from decryptwindow import Ui_Dialog  # importing our generated file

import sys
import os

class mywindow(QtWidgets.QMainWindow):
    def __init__(self):
        super(mywindow, self).__init__()
        self.ui = Ui_Dialog()
        self.ui.setupUi(self)

ini_file = 'config.ini'
ini_file_exists = os.path.isfile(ini_file)

if ini_file_exists:
    # just for testing
    print(ini_file + ' is found')
    # let`s show the main window
    app = QtWidgets.QApplication([])
    application = mywindow()
    application.show()
    sys.exit(app.exec())
else:
    # just for testing
    print(ini_file + ' is not found')
    app = QtWidgets.QApplication([])
    application = mywindow()
    application.show()
    error_dialog = QtWidgets.QErrorMessage()
    error_dialog.showMessage(ini_file + ' is not found')
    # after message I would like just close the application
    sys.exit(app.exec())

Body:
Well, that was simple.
Shame on me I didn`t try before posting.

Removing these 2 lines solved the issue

application = mywindow()
application.show()


问:
Getting mouse position relative to center of rotated image
I'm trying to write some code that allows a user to arbitrarily drag an image around a canvas, resize the image, and rotate the image using their mouse. I am having some trouble with my trigonometry.

All points of interest are relative to the center of the image. In the illustration below the mouse is at the absolute position 850, 400 (relative to the canvas' upper left). Since there is no rotation I can easily figure out that the mouse is in the relative position 250, 0 (relative to the center of the image).

After I rotate the image 270° and put the mouse in the same position, the absolute is 600, 150. The relative position is exactly the same as it was before the rotation though (250, 0).

Given the absolute coordinates of the image's center point, it's rotation, and the absolute position of the mouse, how can I determine the transformed, rotated coordinates of the mouse relative to the center of the image?

I've tried many things and attempted to adapt answers from similar StackOverflow questions. My current attempt uses a Matrix class someone published in a Gist.

```<code>layerRelativePoint(x, y, layer){
    var radians = layer.rotation * (Math.PI/180);
    var matrix = new Matrix();
    matrix.translate(-layer.x, -layer.y);
    matrix.rotate(radians);
    var [x, y] = matrix.transformPoint(x, y);
    return {x, y};
}
</code>```

Demo: https://plnkr.co/edit/T9XCfpZVlMWLMY67bOvW?p=preview

答:
I've found an answer on Math.se.

Here is the implementation I came up with:

```<code>/**
 * Translate a point's absolute coordinates to it's coordinates
 * relative to a possibly rotated center point
 * -------------------------------------------------------------
 * @param {number} absPointX - The absolute x ordinate of the point to translate
 * @param {number} absPointY - The absolute y ordinate of the point to translate
 * @param {number} centerX - The absolute x ordinate of the center point of rotation
 * @param {number} centerY - The absolute y ordinate of the center point of rotation
 * @param {number} rotationDegrees - The angle of rotation in degrees
 * @returns {x, y} - The translated point's coordinates
 */
function translatePoint(absPointX, absPointY, centerX, centerY, rotationDegrees=0) {
    // Get coordinates relative to center point
    absPointX -= centerX;
    absPointY -= centerY;

    // Convert degrees to radians
    var radians = rotationDegrees * (Math.PI / 180);

    // Translate rotation
    var cos = Math.cos(radians);
    var sin = Math.sin(radians);
    var x = (absPointX * cos) + (absPointY * sin);
    var y = (-absPointX * sin) + (absPointY * cos);

    // Round to nearest hundredths place
    x = Math.floor(x * 100) / 100;
    y = Math.floor(y * 100) / 100;

    return {x, y};
}
</code>```

Body:
I'm trying to write some code that allows a user to arbitrarily drag an image around a canvas, resize the image, and rotate the image using their mouse. I am having some trouble with my trigonometry.

All points of interest are relative to the center of the image. In the illustration below the mouse is at the absolute position 850, 400 (relative to the canvas' upper left). Since there is no rotation I can easily figure out that the mouse is in the relative position 250, 0 (relative to the center of the image).

After I rotate the image 270° and put the mouse in the same position, the absolute is 600, 150. The relative position is exactly the same as it was before the rotation though (250, 0).

Given the absolute coordinates of the image's center point, it's rotation, and the absolute position of the mouse, how can I determine the transformed, rotated coordinates of the mouse relative to the center of the image?

I've tried many things and attempted to adapt answers from similar StackOverflow questions. My current attempt uses a Matrix class someone published in a Gist.

layerRelativePoint(x, y, layer){
    var radians = layer.rotation * (Math.PI/180);
    var matrix = new Matrix();
    matrix.translate(-layer.x, -layer.y);
    matrix.rotate(radians);
    var [x, y] = matrix.transformPoint(x, y);
    return {x, y};
}

Demo: https://plnkr.co/edit/T9XCfpZVlMWLMY67bOvW?p=preview

Body:
I've found an answer on Math.se.

Here is the implementation I came up with:

/**
 * Translate a point's absolute coordinates to it's coordinates
 * relative to a possibly rotated center point
 * -------------------------------------------------------------
 * @param {number} absPointX - The absolute x ordinate of the point to translate
 * @param {number} absPointY - The absolute y ordinate of the point to translate
 * @param {number} centerX - The absolute x ordinate of the center point of rotation
 * @param {number} centerY - The absolute y ordinate of the center point of rotation
 * @param {number} rotationDegrees - The angle of rotation in degrees
 * @returns {x, y} - The translated point's coordinates
 */
function translatePoint(absPointX, absPointY, centerX, centerY, rotationDegrees=0) {
    // Get coordinates relative to center point
    absPointX -= centerX;
    absPointY -= centerY;

    // Convert degrees to radians
    var radians = rotationDegrees * (Math.PI / 180);

    // Translate rotation
    var cos = Math.cos(radians);
    var sin = Math.sin(radians);
    var x = (absPointX * cos) + (absPointY * sin);
    var y = (-absPointX * sin) + (absPointY * cos);

    // Round to nearest hundredths place
    x = Math.floor(x * 100) / 100;
    y = Math.floor(y * 100) / 100;

    return {x, y};
}


问:
Spring @RequestBody from interface
I have classes generated from .raml file. In the generated interface for controller I have @RequestBody on my parameter. If I try to make request, mapping works correct but every time I have null fields in my Object annotated with @RequestBody from parameters. Looks like this annotation is ignored. How can I make it work from interface.

For testing without Raml I tried to create a simple interface for controller with simple implementation and I'm still getting null fields values in my request object.

Controller interface generated from .raml

```<code>@RestController
@RequestMapping("/kbm")
public interface KbmController {

    @RequestMapping(value = "", method = RequestMethod.PUT)
    public ResponseEntity<KbmCalcResponse> updateKbm(
        @Valid
        @RequestBody
        KbmCalcRequest kbmCalcRequest);
}
</code>```

My implementation

```<code>@Component
@RequiredArgsConstructor
public class CalcKbmControllerImpl implements KbmController {

  private final KbmService kbmService;

  @Override
  public ResponseEntity<KbmCalcResponse> updateKbm(KbmCalcRequest kbmCalcRequest) {
    System.out.println(kbmCalcRequest.getInsurerID());
    return ResponseEntity.ok(kbmService.calculate(kbmCalcRequest));
  }
}
</code>```

Request model generated from .raml

```<code>public class KbmCalcRequest implements Serializable
{

    final static long serialVersionUID = 1692733266431420440L;

    private String insurerID;

    public KbmCalcRequest() {
        super();
    }

    public KbmCalcRequest(String insurerID {
        super();
        this.insurerID = insurerID;
    }

    public String getInsurerID() {
        return insurerID;
    }

    public void setInsurerID(String insurerID) {
        this.insurerID = insurerID;
    }

    public int hashCode() {
        return new HashCodeBuilder().append(insurerID).toHashCode();
    }

    public boolean equals(Object other) {
        if (other == null) {
            return false;
        }
        if (other == this) {
            return true;
        }
        if (this.getClass()!= other.getClass()) {
            return false;
        }
        KbmCalcRequest otherObject = ((KbmCalcRequest) other);
        return new EqualsBuilder().append(insurerID, otherObject.insurerID).isEquals();
    }

    public String toString() {
        return new ToStringBuilder(this).append("insurerID", insurerID).toString();
    }

}
</code>```

答:
The problem was in a spring boot starter. We have used an old version of the spring-boot-starter-parent - 2.0.1.RELEASE which took the spring web 4.3.5. But the feature of inheriting annotations from method's params to the implementations of these methods were added at 5.1.0.RELEASE of spring web. So, I've just put the latest version (2.1.5.RELEASE for now) in my pom file and it solved my problem.</p>

```<code><parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.1.5.RELEASE</version>
    <relativePath/>
</parent>
</code>```

Title: Spring @RequestBody from interface

Body:
I have classes generated from .raml file. In the generated interface for controller I have @RequestBody on my parameter. If I try to make request, mapping works correct but every time I have null fields in my Object annotated with @RequestBody from parameters. Looks like this annotation is ignored. How can I make it work from interface.

For testing without Raml I tried to create a simple interface for controller with simple implementation and I'm still getting null fields values in my request object.

Controller interface generated from .raml

@RestController
@RequestMapping("/kbm")
public interface KbmController {

    @RequestMapping(value = "", method = RequestMethod.PUT)
    public ResponseEntity<KbmCalcResponse> updateKbm(
        @Valid
        @RequestBody
        KbmCalcRequest kbmCalcRequest);
}

My implementation

@Component
@RequiredArgsConstructor
public class CalcKbmControllerImpl implements KbmController {

  private final KbmService kbmService;

  @Override
  public ResponseEntity<KbmCalcResponse> updateKbm(KbmCalcRequest kbmCalcRequest) {
    System.out.println(kbmCalcRequest.getInsurerID());
    return ResponseEntity.ok(kbmService.calculate(kbmCalcRequest));
  }
}

Request model generated from .raml

public class KbmCalcRequest implements Serializable
{

    final static long serialVersionUID = 1692733266431420440L;

    private String insurerID;

    public KbmCalcRequest() {
        super();
    }

    public KbmCalcRequest(String insurerID {
        super();
        this.insurerID = insurerID;
    }

    public String getInsurerID() {
        return insurerID;
    }

    public void setInsurerID(String insurerID) {
        this.insurerID = insurerID;
    }

    public int hashCode() {
        return new HashCodeBuilder().append(insurerID).toHashCode();
    }

    public boolean equals(Object other) {
        if (other == null) {
            return false;
        }
        if (other == this) {
            return true;
        }
        if (this.getClass()!= other.getClass()) {
            return false;
        }
        KbmCalcRequest otherObject = ((KbmCalcRequest) other);
        return new EqualsBuilder().append(insurerID, otherObject.insurerID).isEquals();
    }

    public String toString() {
        return new ToStringBuilder(this).append("insurerID", insurerID).toString();
    }

}

Body:
The problem was in a spring boot starter. We have used an old version of the spring-boot-starter-parent - 2.0.1.RELEASE which took the spring web 4.3.5. But the feature of inheriting annotations from method's params to the implementations of these methods were added at 5.1.0.RELEASE of spring web. So, I've just put the latest version (2.1.5.RELEASE for now) in my pom file and it solved my problem.

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.1.5.RELEASE</version>
    <relativePath/>
</parent>


问:
table written in vanilla typescript. havent used any plugin or widget.want to add pagination to that table.I dont want to use any plugin
I have a data table hard coded in my ts and html file. i want to add pagination and search functionality without using any plugin or widgets. can someone please tell me the logic how to implement it? i have hardcoded the table and have not used in plugins.</p>

答:
you could use many plugins available on the web for angular . however you can get help from below url.
How to add pagination in Angular 4 for a table?</p>


问:
How to handle null value in JSON in SWIFT
I have a problem with JSON decoding. I have UpdateNickname and UpdateNicknameMessage structs and variable Message inside UpdateNickname could be a null. I got an error whenever it is a null. I want to handle this problem. Here is my struct:

```<code>struct UpdateNicknameMessage: Codable {
 let id: Int
 let nickname: String
 let email: String
}

struct UpdateNickname: Codable {
 var Status: Int
 var Result: String
 var Message: UpdateNicknameMessage

enum CodingKeys: String, CodingKey {
    case Status = "Status"
    case Result = "Result"
    case Message = "Message"
}

init?(from jsonObject: AnyObject) {
    guard let Status1: Int = jsonObject.object(forKey: "Status") as? Int,
        let Result1: String = jsonObject.object(forKey: "Result") as? String,
        let Message1: UpdateNicknameMessage = jsonObject.object(forKey: "Message") as? UpdateNicknameMessage
        else { return nil }

    Status = Status1
    Result = Result1
    Message = Message1
  }
}
</code>```

and JSON looks like this:

```<code>{"Message": {
    email = "123@123.com";
    id = 56;
    nickname = testNickname;
},
 "Status": 200,
 "Result": success}
</code>```

And this is my code for decoding JSON in swift. I use try catch to handle my error.

```<code>            let decoder = JSONDecoder()
            do {
                let model = try decoder.decode(UpdateNickname.self, from: data)
                let serverStatus = model.Status

                if serverStatus == 200 {
                     //EVERYTHING IS FINE
                } else {
                     //server not working
                }
            } catch {
               //cant convert JSON into struct
               print(error.localizedDescription)
            }
</code>```

so my variable Message can return null if something goes wrong with the server.

```<code>{"Message": null,
 "Status": 400,
 "Result": problem}
</code>```

When i try to decode JSON when Message is null i get an error

The data couldn’t be read because it is missing.

How can i fix this problem and handle null value?

答:
Change this line:

```<code>var Message: UpdateNicknameMessage
</code>```

to this one:

```<code>var Message: UpdateNicknameMessage?
</code>```

Everything will work fine now.

Body:
I have a problem with JSON decoding. I have UpdateNickname and UpdateNicknameMessage structs and variable Message inside UpdateNickname could be a null. I got an error whenever it is a null. I want to handle this problem. Here is my struct:

struct UpdateNicknameMessage: Codable {
 let id: Int
 let nickname: String
 let email: String
}

struct UpdateNickname: Codable {
 var Status: Int
 var Result: String
 var Message: UpdateNicknameMessage

enum CodingKeys: String, CodingKey {
    case Status = "Status"
    case Result = "Result"
    case Message = "Message"
}

init?(from jsonObject: AnyObject) {
    guard let Status1: Int = jsonObject.object(forKey: "Status") as? Int,
        let Result1: String = jsonObject.object(forKey: "Result") as? String,
        let Message1: UpdateNicknameMessage = jsonObject.object(forKey: "Message") as? UpdateNicknameMessage
        else { return nil }

    Status = Status1
    Result = Result1
    Message = Message1
  }
}

and JSON looks like this:

{"Message": {
    email = "123@123.com";
    id = 56;
    nickname = testNickname;
},
 "Status": 200,
 "Result": success}

And this is my code for decoding JSON in swift. I use try catch to handle my error.

            let decoder = JSONDecoder()
            do {
                let model = try decoder.decode(UpdateNickname.self, from: data)
                let serverStatus = model.Status

                if serverStatus == 200 {
                     //EVERYTHING IS FINE
                } else {
                     //server not working
                }
            } catch {
               //cant convert JSON into struct
               print(error.localizedDescription)
            }

so my variable Message can return null if something goes wrong with the server.

{"Message": null,
 "Status": 400,
 "Result": problem}

When i try to decode JSON when Message is null i get an error

The data couldn’t be read because it is missing.

How can i fix this problem and handle null value?

Body:
Change this line:

var Message: UpdateNicknameMessage

to this one:

var Message: UpdateNicknameMessage?

Everything will work fine now.


问:
Angular 2 - Dynamically find base url to use in the http requests (services)
I'm wondering if there is a dynamic way of getting the base url, to use in the http requests?

Is there any way of getting the http://192.123.24.2:8080 dynamically?

```<code>public getAllTickets() {
    this._http.get('http://192.123.24.2:8080/services/', {
        method: 'GET',
        headers: new Headers([
            'Accept', 'application/json',
            'Content-Type', 'application/json'
        ])
    })
</code>```

So, I my request would look something like:

```<code>public getAvailableVersions() {
    this._http.get('../services', {
        method: 'GET',
        headers: new Headers([
            'Accept', 'application/json',
            'Content-Type', 'application/json'
        ])
    })
</code>```

I'm looking for a way to not having to hard code the URL for the REST calls. Or is the only option to have a global variable with the URL?

Thanks!

答:
you can get your application context root as below

this.baseURL = document.getElementsByTagName('base')[0].href;

Body:
I'm wondering if there is a dynamic way of getting the base url, to use in the http requests?

Is there any way of getting the http://192.123.24.2:8080 dynamically?

public getAllTickets() {
    this._http.get('http://192.123.24.2:8080/services/', {
        method: 'GET',
        headers: new Headers([
            'Accept', 'application/json',
            'Content-Type', 'application/json'
        ])
    })

So, I my request would look something like:

public getAvailableVersions() {
    this._http.get('../services', {
        method: 'GET',
        headers: new Headers([
            'Accept', 'application/json',
            'Content-Type', 'application/json'
        ])
    })

I'm looking for a way to not having to hard code the URL for the REST calls. Or is the only option to have a global variable with the URL?

Thanks!