问:
Will gcloud using my SSH key to login or I will always need to login via the web?
I am trying to perform a very basic command like:

```<code>gcloud compute machine-types list
</code>```

And I get this error:

ERROR: (gcloud.compute.machine-types.list) There was a problem
  refreshing your current auth tokens: invalid_grant: Bad Request Please
  run:

It tells me to login using 'gcloud auth login' which opens up the browser.

Is it possible to use a ssh key to skip this authentication process or I have to do this always?  ssh keys are for accessing compute instances only?

Just trying to understand what SSH keys are used for and how this web based authorization fits into the picture here.

答:
If you are trying to automate some sort of service, that runs cloud commands on-demand, without operator/browser involved - your best bet would be to create a Service Account for that task, get the key for that account and activate it, using

```<code>gcloud auth activate-service-account --key-file=my-service-account-key-file.json
</code>```

If this service runs on Google Cloud platform - you don't even need to deal with the key. Just associate the service account with an instance you are running.

https://cloud.google.com/compute/docs/access/create-enable-service-accounts-for-instances

Body:
I am trying to perform a very basic command like:

gcloud compute machine-types list

And I get this error:

ERROR: (gcloud.compute.machine-types.list) There was a problem
  refreshing your current auth tokens: invalid_grant: Bad Request Please
  run:

It tells me to login using 'gcloud auth login' which opens up the browser.

Is it possible to use a ssh key to skip this authentication process or I have to do this always?  ssh keys are for accessing compute instances only?

Just trying to understand what SSH keys are used for and how this web based authorization fits into the picture here.

Body:
If you are trying to automate some sort of service, that runs cloud commands on-demand, without operator/browser involved - your best bet would be to create a Service Account for that task, get the key for that account and activate it, using

gcloud auth activate-service-account --key-file=my-service-account-key-file.json

If this service runs on Google Cloud platform - you don't even need to deal with the key. Just associate the service account with an instance you are running.

https://cloud.google.com/compute/docs/access/create-enable-service-accounts-for-instances


来源: stackexchange

问:
Save UITextView String With \n Instead of Line Breaks (Swift)
I have a UITextView in my Swift app in which users can input text. They can input text with as many line breaks as they like but I need to save the string with the newline command (\n). How would I do this?

For example, my user inputs

```<code>Line 1
Line 2
Line 3
</code>```

in the UITextView. If I was to retrieve the string...

```<code>let string = textview.text!
</code>```

this would return

```<code>"Line 1
Line 2
Line 3"
</code>```

when I would like for it to return

```<code>"Line1\nLine2\nLine3"
</code>```

How would I go about doing this? Can I use a form of replacingOccurrences(of:with:)? I feel like I'm missing a fairly obvious solution...

答:
Have you tried replacing \r with \n? or even \r\n with \n?

I hope I am not making an obvious assumption you considered, but maybe this may come in handy:
Is a new line = \n OR \r\n?

ContentLicense: CC BY-SA 4.0

Body:
I have a UITextView in my Swift app in which users can input text. They can input text with as many line breaks as they like but I need to save the string with the newline command (\n). How would I do this?

For example, my user inputs

Line 1
Line 2
Line 3

in the UITextView. If I was to retrieve the string...

let string = textview.text!

this would return

"Line 1
Line 2
Line 3"

when I would like for it to return

"Line1\nLine2\nLine3"

How would I go about doing this? Can I use a form of replacingOccurrences(of:with:)? I feel like I'm missing a fairly obvious solution...


问:
Is there a better way to check if a number is range of two numbers
I am trying to check if a number is in range of integers and returns a number based on which range it lies. I was wondering if is there a better and more efficient way of doing this:

```<code>def checkRange(number):
    if number in range(0, 5499):
        return 5000
    elif number in range(5500, 9499):
        return 10000
    elif number in range(9500, 14499):
        return 15000
    elif number in range(14500, 19499):
        return 20000
    elif number in range(19500, 24499):
        return 25000
    elif number in range(24500, 29499):
        return 30000
    elif number in range(29500, 34499):
        return 35000
    elif number in range(34500, 39499):
        return 40000
    elif number in range(39500, 44499):
        return 45000
</code>```

This felt like a waste of resources and would greatly appreciate if there is a better way to do this.

答:
If by better, you mean faster, it's a good idea to check the lower and upper limits, as the previous comments/answers have suggested.

However, note that in Python3, the range() object does this for you, resulting in the in range() check being a nearly constant time operation, so I don't think the runtime should be bad using your code.

I'd highly recommend reading this thread:

Why is "1000000000000000 in range(1000000000000001)" so fast in Python 3?

Body:
I am trying to check if a number is in range of integers and returns a number based on which range it lies. I was wondering if is there a better and more efficient way of doing this:

def checkRange(number):
    if number in range(0, 5499):
        return 5000
    elif number in range(5500, 9499):
        return 10000
    elif number in range(9500, 14499):
        return 15000
    elif number in range(14500, 19499):
        return 20000
    elif number in range(19500, 24499):
        return 25000
    elif number in range(24500, 29499):
        return 30000
    elif number in range(29500, 34499):
        return 35000
    elif number in range(34500, 39499):
        return 40000
    elif number in range(39500, 44499):
        return 45000

This felt like a waste of resources and would greatly appreciate if there is a better way to do this.


问:
How to delete an item from a list inside of a class in python?
So i am building a shopping cart in python that has several commands such as add, remove, change, output item descriptions, output shopping cart, and quit(which terminates the function).

I am having trouble with removing an item from cart as my output is not the desired output.

So for example, for the input:

```<code>John Doe
February 1, 2016
a
Nike Romaleos
Volt color, Weightlifting shoes
189
2
a
Chocolate Chips
Semi-sweet
3
5
a
Powerbeats 2 Headphones
Bluetooth headphones
128
1
r
Chocolate Chips
o
q
</code>```

When it says r and then Chocolate Chips, Chocolate Chips should be removed from the Cart.

My code so far:

```<code>class ItemToPurchase:
    def __init__(self, item_name='none', item_price=0, item_quantity=0, item_description='none'):
        self.item_name = item_name
        self.item_price = item_price
        self.item_quantity = item_quantity
        self.item_description = item_description

    def print_item_cost(self):
        string = '{} {} @ ${} = ${}'.format(self.item_name, self.item_quantity, self.item_price,
                                            (self.item_quantity * self.item_price))
        cost = self.item_quantity * self.item_price
        return string, cost

    def print_item_description(self):
        string = '{}: {}'.format(self.item_name, self.item_description)
        print(string, end='\n')
        return string

class ShoppingCart:
    def __init__(self, customer_name='none', current_date='January 1, 2016', cart_items=[]):
        self.customer_name = customer_name
        self.current_date = current_date
        self.cart_items = cart_items

    def add_item(self, string):
        print('\nADD ITEM TO CART', end='\n')
        item_name = str(input('Enter the item name:'))
        item_description = str(input('\nEnter the item description:'))
        item_price = int(input('\nEnter the item price:'))
        item_quantity = int(input('\nEnter the item quantity:\n'))
        self.cart_items.append(ItemToPurchase(item_name, item_price, item_quantity, item_description))

    def remove_item(self):
        print('\nREMOVE ITEM FROM CART', end='\n')
        string = str(input('Enter name of item to remove:\n'))
        i = 0
        for item in self.cart_items:
            if (item.item_name == string):
                del self.cart_items[i]
                i += 1
                flag = True
                break
            else:
                flag = False
        if (flag == False):
            print('Item not found in cart. Nothing removed.')

    def modify_item(self):
        print('\nCHANGE ITEM QUANTITY', end='\n')
        name = str(input('Enter the item name: '))
        for item in self.cart_items:
            if (item.item_name == name):
                quantity = int(input('Enter the new quantity: '))
                item.item_quantity = quantity
                flag = True
                break
            else:
                flag = False
        if (flag == False):
            print('Item not found in cart. Nothing modified.')

    def get_num_items_in_cart(self):
        num_items = 0
        for item in self.cart_items:
            num_items = num_items + item.item_quantity
        return num_items

    def get_cost_of_cart(self):
        total_cost = 0
        cost = 0
        for item in self.cart_items:

            cost = (item.item_quantity * item.item_price)

            total_cost += cost

        return total_cost

    def print_total(self):
        total_cost = self.get_cost_of_cart()
        if (total_cost == 0 and cost == 0):
            print('SHOPPING CART IS EMPTY')
        else:
            self.output_cart()

    def print_descriptions(self):
        print('\nOUTPUT ITEMS\' DESCRIPTIONS')
        print('{}\'s Shopping Cart - {}'.format(self.customer_name, self.current_date), end='\n')
        print('\nItem Descriptions', end='\n')
        for item in self.cart_items:
            print('{}: {}'.format(item.item_name, item.item_description), end='\n')

    def output_cart(self):
        new = ShoppingCart()
        print('OUTPUT SHOPPING CART', end='\n')
        print('{}\'s Shopping Cart - {}'.format(self.customer_name, self.current_date), end='\n')
        print('Number of Items:', new.get_num_items_in_cart(), end='\n\n')

        # IF NUMBER OF ITEMS IN THE OUTPUT CART IS 0...
        if new.get_num_items_in_cart() == 0:
            print('SHOPPING CART IS EMPTY')
        tc = 0
        for item in self.cart_items:
            print('{} {} @ ${} = ${}'.format(item.item_name, item.item_quantity,
                                             item.item_price, (item.item_quantity * item.item_price)), end='\n')
            tc += (item.item_quantity * item.item_price)
        print('\nTotal: ${}'.format(tc), end='\n')

def print_menu(ShoppingCart):
    customer_Cart = newCart
    string = ''
    # declare the string menu
    menu = ('\nMENU\n'
            'a - Add item to cart\n'
            'r - Remove item from cart\n'
            'c - Change item quantity\n'
            'i - Output items\' descriptions\n'
            'o - Output shopping cart\n'
            'q - Quit\n')
    command = ''
    while (command != 'q'):
        string = ''
        print(menu, end='\n')
        command = input('Choose an option:\n')
        while (command != 'a' and command != 'o' and command != 'i' and command != 'r'
               and command != 'c' and command != 'q'):
            command = input('Choose an option:\n')
        if (command == 'a'):
            customer_Cart.add_item(string)
        if (command == 'o'):
            customer_Cart.output_cart()
        if (command == 'i'):
            customer_Cart.print_descriptions()
        if (command == 'r'):
            customer_Cart.remove_item()
        if (command == 'c'):
            customer_Cart.modify_item()

customer_name = str(input('Enter customer\'s name:'))
current_date = str(input('\nEnter today\'s date:\n\n'))
print('Customer name:', customer_name, end='\n')
print('Today\'s date:', current_date)
newCart = ShoppingCart(customer_name, current_date)
print_menu(newCart)
</code>```

I tried

```<code>def remove_item(self):
    print('\nREMOVE ITEM FROM CART', end='\n')
    string = str(input('Enter name of item to remove:\n'))
    i = 0
    for item in self.cart_items:
        if (item.item_name == string):
            del self.cart_items[i]
            i += 1
            flag = True
            break
        else:
            flag = False
    if (flag == False):
        print('Item not found in cart. Nothing removed.')
</code>```

But my output (with the input) is:

```<code>REMOVE ITEM FROM CART
Enter name of item to remove:

MENU
a - Add item to cart
r - Remove item from cart
c - Change item quantity
i - Output items' descriptions
o - Output shopping cart
q - Quit

Choose an option:
OUTPUT SHOPPING CART
John Doe's Shopping Cart - February 1, 2016
Number of Items: 6

Chocolate Chips 5 @ $3 = $15
Powerbeats 2 Headphones 1 @ $128 = $128

Total: $143

MENU
a - Add item to cart
r - Remove item from cart
c - Change item quantity
i - Output items' descriptions
o - Output shopping cart
q - Quit

Choose an option:
</code>```

When it should be:

```<code>REMOVE ITEM FROM CART
Enter name of item to remove:

MENU
a - Add item to cart
r - Remove item from cart
c - Change item quantity
i - Output items' descriptions
o - Output shopping cart
q - Quit

Choose an option:
OUTPUT SHOPPING CART
John Doe's Shopping Cart - February 1, 2016
Number of Items: 3

Nike Romaleos 2 @ $189 = $378
Powerbeats 2 Headphones 1 @ $128 = $128

Total: $506

MENU
a - Add item to cart
r - Remove item from cart
c - Change item quantity
i - Output items' descriptions
o - Output shopping cart
q - Quit

Choose an option:
</code>```

As you can see, my code is deleting the Nike Romaleos, $189, at Quantity 2
When it should be deleting the Chocolate Chips, $3, at Quantity 5.
I am not sure why it is deleting the wrong items, as I inputted Chocolate Chips right after 'r', which calls the

```<code>if (command == 'r'):
    customer_Cart.remove_item()
</code>```

If anyone could help that would be greatly appreciated!

答:
The reason is that in remove_item() you are deleting the ith element from cart_items instead of deleting the index of the item which you are receiving as an input.

You can use remove instead of del.

This way you will not need the counter i

```<code>    def remove_item(self):
        print('\nREMOVE ITEM FROM CART', end='\n')
        string = str(input('Enter name of item to remove:\n'))

        for item in self.cart_items:
            if (item.item_name == string):
                self.cart_items.remove(item)
                flag = True
                break
            else:
                flag = False
        if (flag == False):
            print('Item not found in cart. Nothing removed.')

</code>```

Body:
So i am building a shopping cart in python that has several commands such as add, remove, change, output item descriptions, output shopping cart, and quit(which terminates the function).

I am having trouble with removing an item from cart as my output is not the desired output.

So for example, for the input:

John Doe
February 1, 2016
a
Nike Romaleos
Volt color, Weightlifting shoes
189
2
a
Chocolate Chips
Semi-sweet
3
5
a
Powerbeats 2 Headphones
Bluetooth headphones
128
1
r
Chocolate Chips
o
q

When it says r and then Chocolate Chips, Chocolate Chips should be removed from the Cart.

My code so far:

class ItemToPurchase:
    def __init__(self, item_name='none', item_price=0, item_quantity=0, item_description='none'):
        self.item_name = item_name
        self.item_price = item_price
        self.item_quantity = item_quantity
        self.item_description = item_description

    def print_item_cost(self):
        string = '{} {} @ ${} = ${}'.format(self.item_name, self.item_quantity, self.item_price,
                                            (self.item_quantity * self.item_price))
        cost = self.item_quantity * self.item_price
        return string, cost

    def print_item_description(self):
        string = '{}: {}'.format(self.item_name, self.item_description)
        print(string, end='\n')
        return string

class ShoppingCart:
    def __init__(self, customer_name='none', current_date='January 1, 2016', cart_items=[]):
        self.customer_name = customer_name
        self.current_date = current_date
        self.cart_items = cart_items

    def add_item(self, string):
        print('\nADD ITEM TO CART', end='\n')
        item_name = str(input('Enter the item name:'))
        item_description = str(input('\nEnter the item description:'))
        item_price = int(input('\nEnter the item price:'))
        item_quantity = int(input('\nEnter the item quantity:\n'))
        self.cart_items.append(ItemToPurchase(item_name, item_price, item_quantity, item_description))

    def remove_item(self):
        print('\nREMOVE ITEM FROM CART', end='\n')
        string = str(input('Enter name of item to remove:\n'))
        i = 0
        for item in self.cart_items:
            if (item.item_name == string):
                del self.cart_items[i]
                i += 1
                flag = True
                break
            else:
                flag = False
        if (flag == False):
            print('Item not found in cart. Nothing removed.')

    def modify_item(self):
        print('\nCHANGE ITEM QUANTITY', end='\n')
        name = str(input('Enter the item name: '))
        for item in self.cart_items:
            if (item.item_name == name):
                quantity = int(input('Enter the new quantity: '))
                item.item_quantity = quantity
                flag = True
                break
            else:
                flag = False
        if (flag == False):
            print('Item not found in cart. Nothing modified.')

    def get_num_items_in_cart(self):
        num_items = 0
        for item in self.cart_items:
            num_items = num_items + item.item_quantity
        return num_items

    def get_cost_of_cart(self):
        total_cost = 0
        cost = 0
        for item in self.cart_items:

            cost = (item.item_quantity * item.item_price)

            total_cost += cost

        return total_cost

    def print_total(self):
        total_cost = self.get_cost_of_cart()
        if (total_cost == 0 and cost == 0):
            print('SHOPPING CART IS EMPTY')
        else:
            self.output_cart()

    def print_descriptions(self):
        print('\nOUTPUT ITEMS\' DESCRIPTIONS')
        print('{}\'s Shopping Cart - {}'.format(self.customer_name, self.current_date), end='\n')
        print('\nItem Descriptions', end='\n')
        for item in self.cart_items:
            print('{}: {}'.format(item.item_name, item.item_description), end='\n')

    def output_cart(self):
        new = ShoppingCart()
        print('OUTPUT SHOPPING CART', end='\n')
        print('{}\'s Shopping Cart - {}'.format(self.customer_name, self.current_date), end='\n')
        print('Number of Items:', new.get_num_items_in_cart(), end='\n\n')

        # IF NUMBER OF ITEMS IN THE OUTPUT CART IS 0...
        if new.get_num_items_in_cart() == 0:
            print('SHOPPING CART IS EMPTY')
        tc = 0
        for item in self.cart_items:
            print('{} {} @ ${} = ${}'.format(item.item_name, item.item_quantity,
                                             item.item_price, (item.item_quantity * item.item_price)), end='\n')
            tc += (item.item_quantity * item.item_price)
        print('\nTotal: ${}'.format(tc), end='\n')

def print_menu(ShoppingCart):
    customer_Cart = newCart
    string = ''
    # declare the string menu
    menu = ('\nMENU\n'
            'a - Add item to cart\n'
            'r - Remove item from cart\n'
            'c - Change item quantity\n'
            'i - Output items\' descriptions\n'
            'o - Output shopping cart\n'
            'q - Quit\n')
    command = ''
    while (command != 'q'):
        string = ''
        print(menu, end='\n')
        command = input('Choose an option:\n')
        while (command != 'a' and command != 'o' and command != 'i' and command != 'r'
               and command != 'c' and command != 'q'):
            command = input('Choose an option:\n')
        if (command == 'a'):
            customer_Cart.add_item(string)
        if (command == 'o'):
            customer_Cart.output_cart()
        if (command == 'i'):
            customer_Cart.print_descriptions()
        if (command == 'r'):
            customer_Cart.remove_item()
        if (command == 'c'):
            customer_Cart.modify_item()

customer_name = str(input('Enter customer\'s name:'))
current_date = str(input('\nEnter today\'s date:\n\n'))
print('Customer name:', customer_name, end='\n')
print('Today\'s date:', current_date)
newCart = ShoppingCart(customer_name, current_date)
print_menu(newCart)

I tried

def remove_item(self):
    print('\nREMOVE ITEM FROM CART', end='\n')
    string = str(input('Enter name of item to remove:\n'))
    i = 0
    for item in self.cart_items:
        if (item.item_name == string):
            del self.cart_items[i]
            i += 1
            flag = True
            break
        else:
            flag = False
    if (flag == False):
        print('Item not found in cart. Nothing removed.')

But my output (with the input) is:

REMOVE ITEM FROM CART
Enter name of item to remove:

MENU
a - Add item to cart
r - Remove item from cart
c - Change item quantity
i - Output items' descriptions
o - Output shopping cart
q - Quit

Choose an option:
OUTPUT SHOPPING CART
John Doe's Shopping Cart - February 1, 2016
Number of Items: 6

Chocolate Chips 5 @ $3 = $15
Powerbeats 2 Headphones 1 @ $128 = $128

Total: $143

MENU
a - Add item to cart
r - Remove item from cart
c - Change item quantity
i - Output items' descriptions
o - Output shopping cart
q - Quit

Choose an option:

When it should be:

REMOVE ITEM FROM CART
Enter name of item to remove:

MENU
a - Add item to cart
r - Remove item from cart
c - Change item quantity
i - Output items' descriptions
o - Output shopping cart
q - Quit

Choose an option:
OUTPUT SHOPPING CART
John Doe's Shopping Cart - February 1, 2016
Number of Items: 3

Nike Romaleos 2 @ $189 = $378
Powerbeats 2 Headphones 1 @ $128 = $128

Total: $506

MENU
a - Add item to cart
r - Remove item from cart
c - Change item quantity
i - Output items' descriptions
o - Output shopping cart
q - Quit

Choose an option:

As you can see, my code is deleting the Nike Romaleos, $189, at Quantity 2
When it should be deleting the Chocolate Chips, $3, at Quantity 5.
I am not sure why it is deleting the wrong items, as I inputted Chocolate Chips right after 'r', which calls the

if (command == 'r'):
    customer_Cart.remove_item()

If anyone could help that would be greatly appreciated!

Body:
The reason is that in remove_item() you are deleting the ith element from cart_items instead of deleting the index of the item which you are receiving as an input.

You can use remove instead of del.

This way you will not need the counter i

    def remove_item(self):
        print('\nREMOVE ITEM FROM CART', end='\n')
        string = str(input('Enter name of item to remove:\n'))

        for item in self.cart_items:
            if (item.item_name == string):
                self.cart_items.remove(item)
                flag = True
                break
            else:
                flag = False
        if (flag == False):
            print('Item not found in cart. Nothing removed.')


问:
Is there any proguard rules should use while using EncryptedSharedPreferences?
before using EncryptedSharedPreferences my app works fine in release mode with (minifyEnabled = true), After adding the security library (version 1.0.0-rc01) to my application the app crash while opening and if i use (minifyEnabled = false) the app works fine, i think i missing something to add it in proguard-rules.pro but i have searched a lot did not found anything.

答:
This issue has been answered with a more targeted proguard rule here

```<code>-keepclassmembers class * extends com.google.crypto.tink.shaded.protobuf.GeneratedMessageLite {
    <fields>;
}
</code>```

This saves my app ~0.2MB compared to the currently accepted answer

Body:
This issue has been answered with a more targeted proguard rule here

-keepclassmembers class * extends com.google.crypto.tink.shaded.protobuf.GeneratedMessageLite {
    <fields>;
}

This saves my app ~0.2MB compared to the currently accepted answer


问:
How to use the Time period in date time
I have a form that sends the value of year and months from an input and then while sending the value to the server I am converting that values to ISO string like that:

```<code>const toIsoString = (year, month, day) => moment(new Date(year, month - 1, day)).toISOString(true).split('.')[0];
</code>```

And then in the values I am using it like this.

```<code>StartDate: toIsoString(data.StartYear, parseInt(data.StartMonth, 10), 1),
</code>```

In that case It is sending the value like this:

```<code>startDate: "2021-01-01T00:00:00"
</code>```

Does anybody know why the Time period is being ignored and how can I also send the time period with the year, month and date values.Any helps would be highly appreciated.Thanks...

答:
Does anybody know why the Time period is being ignored and how can I also send the time period with the year, month and date values.Any helps would be highly appreciated.

The time isn't ignored. In the function:

```<code>const toIsoString = (year, month, day) =>
  moment(new Date(year, month - 1, day)).toISOString(true).split('.')[0];
</code>```

the values for hour, minute, second and millisecond are omitted so they default to 0. What time are you expecting?

If you want the current local time added to the date, then create a date and set the year, month and day to the required values without modifying the time (though I don't know why you'd want to do that).

Rather than creating a string that you then need to further process, tell moment.js the format you want:

function toIsoString (year, month, day) {
  return moment(new Date().setFullYear(year, month-1, day)).format('YYYY-MM-DD HH:mm:ss');
}

console.log(toIsoString('2021','1','1'));```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.26.0/moment.min.js"></script></code>```

You can also do that without a library, see How to format a JavaScript date, e.g.:

function formatDate(year, month, date) {
  let z = n => (n<10?'0':'') + Number(n);
  return `${year}-${z(month)}-${z(date)} ${
    new Date().toLocaleString('en',{
      hour12:false,
      hour:'2-digit',
      minute:'2-digit',
      second:'2-digit'})
  }`;
}

console.log(formatDate('2021','1','01'))```

Title: How to use the Time period in date time

Body:
I have a form that sends the value of year and months from an input and then while sending the value to the server I am converting that values to ISO string like that:

const toIsoString = (year, month, day) => moment(new Date(year, month - 1, day)).toISOString(true).split('.')[0];

And then in the values I am using it like this.

StartDate: toIsoString(data.StartYear, parseInt(data.StartMonth, 10), 1),

In that case It is sending the value like this:

startDate: "2021-01-01T00:00:00"

Does anybody know why the Time period is being ignored and how can I also send the time period with the year, month and date values.Any helps would be highly appreciated.Thanks...

Body:
Does anybody know why the Time period is being ignored and how can I also send the time period with the year, month and date values.Any helps would be highly appreciated.

The time isn't ignored. In the function:

const toIsoString = (year, month, day) =>
  moment(new Date(year, month - 1, day)).toISOString(true).split('.')[0];

the values for hour, minute, second and millisecond are omitted so they default to 0. What time are you expecting?

If you want the current local time added to the date, then create a date and set the year, month and day to the required values without modifying the time (though I don't know why you'd want to do that).

Rather than creating a string that you then need to further process, tell moment.js the format you want:

function toIsoString (year, month, day) {
  return moment(new Date().setFullYear(year, month-1, day)).format('YYYY-MM-DD HH:mm:ss');
}

console.log(toIsoString('2021','1','1'));

<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.26.0/moment.min.js"></script>

You can also do that without a library, see How to format a JavaScript date, e.g.:

function formatDate(year, month, date) {
  let z = n => (n<10?'0':'') + Number(n);
  return `${year}-${z(month)}-${z(date)} ${
    new Date().toLocaleString('en',{
      hour12:false,
      hour:'2-digit',
      minute:'2-digit',
      second:'2-digit'})
  }`;
}

console.log(formatDate('2021','1','01'))


问:
Scala - Handle empty strings when instantiating a class
I have a case class with a couple of String fields. I use the values result of a string split to instantiate the class, but want to get an error when any of the fields is an empty string. For example:

```<code>case class SomeClass(a: String, b: String)
val line = ",a"
val values = line.split(",")
SomeClass(values(0), values(1))
</code>```

Would result in:

```<code>SomeClass = SomeClass(,a)
</code>```

Obviously I can check if each element is empty individually, but is there any more elegant and practical way to prevent instantiating when there is an empty field?

答:
Give this a try.

In the companion object create one or more factory methods that construct and validate the expected parameters. Make the primary constructor private so that the factory method/s can't be circumnavigated.

```<code>case class SomeClass private (a: String, b: String)
object SomeClass {

  def apply(ab: String): Option[SomeClass] = util.Try{
    val Array(a, b) = ab.split(",")
    apply(a, b)
  }.getOrElse(None)

  def apply(a: String, b: String): Option[SomeClass] =
    if (a.isEmpty || b.isEmpty) None
    else Some(new SomeClass(a, b))
}
</code>```

testing:

```<code>SomeClass("aa,bb") //res0: Option[SomeClass] = Some(SomeClass(aa,bb))
SomeClass(",cc")   //res1: Option[SomeClass] = None
SomeClass("g:g")   //res2: Option[SomeClass] = None
new SomeClass("x", "y")  //fails to compile
</code>```

Body:
I have a case class with a couple of String fields. I use the values result of a string split to instantiate the class, but want to get an error when any of the fields is an empty string. For example:

case class SomeClass(a: String, b: String)
val line = ",a"
val values = line.split(",")
SomeClass(values(0), values(1))

Would result in:

SomeClass = SomeClass(,a)

Obviously I can check if each element is empty individually, but is there any more elegant and practical way to prevent instantiating when there is an empty field?

Body:
Give this a try.

In the companion object create one or more factory methods that construct and validate the expected parameters. Make the primary constructor private so that the factory method/s can't be circumnavigated.

case class SomeClass private (a: String, b: String)
object SomeClass {

  def apply(ab: String): Option[SomeClass] = util.Try{
    val Array(a, b) = ab.split(",")
    apply(a, b)
  }.getOrElse(None)

  def apply(a: String, b: String): Option[SomeClass] =
    if (a.isEmpty || b.isEmpty) None
    else Some(new SomeClass(a, b))
}

testing:

SomeClass("aa,bb") //res0: Option[SomeClass] = Some(SomeClass(aa,bb))
SomeClass(",cc")   //res1: Option[SomeClass] = None
SomeClass("g:g")   //res2: Option[SomeClass] = None
new SomeClass("x", "y")  //fails to compile


问:
NLog save entries to database(postgresql),
Search on many post, all compared to almost identical but somehow its doesn't send entries to DB.

logging file works, but database not..

nlog.config

```<code><?xml version="1.0" encoding="utf-8" ?>
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      autoReload="true"
      internalLogLevel="Trace"
      internalLogFile="c:logs\internallog.txt">
  <extensions>
    <add assembly="NLog.Web.AspNetCore" />
  </extensions>
  <targets>
    <target name="database" xsi:type="Database"
            dbProvider="Npgsql.NpgsqlConnection, Npgsql"
            connectionString="User ID=postgres;Password=123456;Host=localhost;Port=5432;Database=Telepati_Dev;">
      <!--//Pooling=true;-->
      <commandText>
        insert into systemlogs(log_date,log_level,log_logger,log_message,log_machine_name, log_user_name, log_call_site, log_thread, log_exception, log_stacktrace) values(@time_stamp, @level, @logger, @message,@machinename, @user_name, @call_site, @threadid, @log_exception, @stacktrace);
      </commandText>
      <parameter name="@time_stamp" layout="${longdate}" />
      <parameter name="@level" layout="${level}" />
      <parameter name="@logger" layout="${logger}" />
      <parameter name="@message" layout="${message}" />
      <parameter name="@machinename" layout="${machinename}" />
      <parameter name="@user_name" layout="${windows-identity:domain=true}" />
      <parameter name="@call_site" layout="${callsite:filename=true}" />
      <parameter name="@threadid" layout="${threadid}" />
      <parameter name="@log_exception" layout="${exception}" />
      <parameter name="@stacktrace" layout="${stacktrace}" />
    </target>
    <target xsi:type="File" name="ownFile-web" fileName="c:\logs\ApplicationLogs-${shortdate}.log"
            layout="${longdate}|${event-properties:item=EventId_Id}|${uppercase:${level}}|${logger}|${message} CorrelationId=${aspnet-item:variable=CorrelationId} ${exception:format=tostring}|url: ${aspnet-request-url}|controller: ${aspnet-MVC-Controller}, action: ${aspnet-mvc-action}" />
  </targets>
  <rules>
    <!--All logs, including from Microsoft-->
    <logger name="*" minlevel="Trace" writeTo="allfile" />

    <!--Skip non-critical Microsoft logs and so log only own logs-->
    <logger name="Microsoft.*" maxlevel="Info" final="true" />
    <!-- BlackHole without writeTo -->
    <logger name="*" minlevel="Trace" writeTo="ownFile-web" />
  </rules>
</nlog>
</code>```

Api project gets dbcontext from data layer so does Npgsql reference

here is API nugget refs;

and data layer packages;

here are some contents of "internallog.txt";

```<code>2020-05-31 02:07:32.3212 Trace Opening c:\logs\ApplicationLogs-2020-05-31.log with allowFileSharedWriting=False
2020-05-31 02:07:32.3503 Trace Opening c:\logs\ApplicationLogs-2020-05-31.log with allowFileSharedWriting=False
2020-05-31 02:07:32.3642 Trace Opening c:\logs\ApplicationLogs-2020-05-31.log with allowFileSharedWriting=False
2020-05-31 02:07:32.3774 Trace Opening c:\logs\ApplicationLogs-2020-05-31.log with allowFileSharedWriting=False
2020-05-31 02:07:32.3934 Trace Opening c:\logs\ApplicationLogs-2020-05-31.log with allowFileSharedWriting=False
2020-05-31 02:07:32.4091 Trace Opening c:\logs\ApplicationLogs-2020-05-31.log with allowFileSharedWriting=False
2020-05-31 02:07:32.4245 Trace Opening c:\logs\ApplicationLogs-2020-05-31.log with allowFileSharedWriting=False
2020-05-31 02:07:32.4403 Trace Opening c:\logs\ApplicationLogs-2020-05-31.log with allowFileSharedWriting=False
2020-05-31 02:07:32.4551 Trace Opening c:\logs\ApplicationLogs-2020-05-31.log with allowFileSharedWriting=False
2020-05-31 02:07:32.4771 Debug Targets for Microsoft.EntityFrameworkCore.Database.Command by level:
2020-05-31 02:07:32.4771 Debug Trace =>
2020-05-31 02:07:32.4771 Debug Debug =>
2020-05-31 02:07:32.4947 Debug Info =>
2020-05-31 02:07:32.4947 Debug Warn => ownFile-web
2020-05-31 02:07:32.4947 Debug Error => ownFile-web
2020-05-31 02:07:32.5119 Debug Fatal => ownFile-web
2020-05-31 02:07:32.5119 Debug Targets for Microsoft.EntityFrameworkCore.Query by level:
2020-05-31 02:07:32.5119 Debug Trace =>
2020-05-31 02:07:32.5279 Debug Debug =>
2020-05-31 02:07:32.5279 Debug Info =>
2020-05-31 02:07:32.5279 Debug Warn => ownFile-web
2020-05-31 02:07:32.5428 Debug Error => ownFile-web
2020-05-31 02:07:32.5428 Debug Fatal => ownFile-web
2020-05-31 02:07:32.5428 Debug Targets for Microsoft.EntityFrameworkCore.Database.Transaction by level:
2020-05-31 02:07:32.5594 Debug Trace =>
2020-05-31 02:07:32.5594 Debug Debug =>
2020-05-31 02:07:32.5704 Debug Info =>
2020-05-31 02:07:32.5704 Debug Warn => ownFile-web
2020-05-31 02:07:32.5704 Debug Error => ownFile-web
2020-05-31 02:07:32.5856 Debug Fatal => ownFile-web
2020-05-31 02:07:32.5856 Debug Targets for Microsoft.EntityFrameworkCore.Database.Connection by level:
2020-05-31 02:07:32.5856 Debug Trace =>
2020-05-31 02:07:32.6033 Debug Debug =>
2020-05-31 02:07:32.6033 Debug Info =>
2020-05-31 02:07:32.6033 Debug Warn => ownFile-web
2020-05-31 02:07:32.6186 Debug Error => ownFile-web
2020-05-31 02:07:32.6186 Debug Fatal => ownFile-web
2020-05-31 02:07:32.6403 Debug Targets for Microsoft.EntityFrameworkCore.Update by level:
</code>```

whats missing here?

答:
There isn't a rule that writes to the database target in your config.

E.g. Replace

```<code><logger name="*" minlevel="Trace" writeTo="ownFile-web" />
</code>```

With

```<code><logger name="*" minlevel="Trace" writeTo="ownFile-web, database" />
</code>```

Body:
Search on many post, all compared to almost identical but somehow its doesn't send entries to DB.

logging file works, but database not..

nlog.config

<?xml version="1.0" encoding="utf-8" ?>
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      autoReload="true"
      internalLogLevel="Trace"
      internalLogFile="c:logs\internallog.txt">
  <extensions>
    <add assembly="NLog.Web.AspNetCore" />
  </extensions>
  <targets>
    <target name="database" xsi:type="Database"
            dbProvider="Npgsql.NpgsqlConnection, Npgsql"
            connectionString="User ID=postgres;Password=123456;Host=localhost;Port=5432;Database=Telepati_Dev;">

      <commandText>
        insert into systemlogs(log_date,log_level,log_logger,log_message,log_machine_name, log_user_name, log_call_site, log_thread, log_exception, log_stacktrace) values(@time_stamp, @level, @logger, @message,@machinename, @user_name, @call_site, @threadid, @log_exception, @stacktrace);
      </commandText>
      <parameter name="@time_stamp" layout="${longdate}" />
      <parameter name="@level" layout="${level}" />
      <parameter name="@logger" layout="${logger}" />
      <parameter name="@message" layout="${message}" />
      <parameter name="@machinename" layout="${machinename}" />
      <parameter name="@user_name" layout="${windows-identity:domain=true}" />
      <parameter name="@call_site" layout="${callsite:filename=true}" />
      <parameter name="@threadid" layout="${threadid}" />
      <parameter name="@log_exception" layout="${exception}" />
      <parameter name="@stacktrace" layout="${stacktrace}" />
    </target>
    <target xsi:type="File" name="ownFile-web" fileName="c:\logs\ApplicationLogs-${shortdate}.log"
            layout="${longdate}|${event-properties:item=EventId_Id}|${uppercase:${level}}|${logger}|${message} CorrelationId=${aspnet-item:variable=CorrelationId} ${exception:format=tostring}|url: ${aspnet-request-url}|controller: ${aspnet-MVC-Controller}, action: ${aspnet-mvc-action}" />
  </targets>
  <rules>

    <logger name="*" minlevel="Trace" writeTo="allfile" />

    <logger name="Microsoft.*" maxlevel="Info" final="true" />

    <logger name="*" minlevel="Trace" writeTo="ownFile-web" />
  </rules>
</nlog>

Api project gets dbcontext from data layer so does Npgsql reference

here is API nugget refs;

and data layer packages;

here are some contents of "internallog.txt";

2020-05-31 02:07:32.3212 Trace Opening c:\logs\ApplicationLogs-2020-05-31.log with allowFileSharedWriting=False
2020-05-31 02:07:32.3503 Trace Opening c:\logs\ApplicationLogs-2020-05-31.log with allowFileSharedWriting=False
2020-05-31 02:07:32.3642 Trace Opening c:\logs\ApplicationLogs-2020-05-31.log with allowFileSharedWriting=False
2020-05-31 02:07:32.3774 Trace Opening c:\logs\ApplicationLogs-2020-05-31.log with allowFileSharedWriting=False
2020-05-31 02:07:32.3934 Trace Opening c:\logs\ApplicationLogs-2020-05-31.log with allowFileSharedWriting=False
2020-05-31 02:07:32.4091 Trace Opening c:\logs\ApplicationLogs-2020-05-31.log with allowFileSharedWriting=False
2020-05-31 02:07:32.4245 Trace Opening c:\logs\ApplicationLogs-2020-05-31.log with allowFileSharedWriting=False
2020-05-31 02:07:32.4403 Trace Opening c:\logs\ApplicationLogs-2020-05-31.log with allowFileSharedWriting=False
2020-05-31 02:07:32.4551 Trace Opening c:\logs\ApplicationLogs-2020-05-31.log with allowFileSharedWriting=False
2020-05-31 02:07:32.4771 Debug Targets for Microsoft.EntityFrameworkCore.Database.Command by level:
2020-05-31 02:07:32.4771 Debug Trace =>
2020-05-31 02:07:32.4771 Debug Debug =>
2020-05-31 02:07:32.4947 Debug Info =>
2020-05-31 02:07:32.4947 Debug Warn => ownFile-web
2020-05-31 02:07:32.4947 Debug Error => ownFile-web
2020-05-31 02:07:32.5119 Debug Fatal => ownFile-web
2020-05-31 02:07:32.5119 Debug Targets for Microsoft.EntityFrameworkCore.Query by level:
2020-05-31 02:07:32.5119 Debug Trace =>
2020-05-31 02:07:32.5279 Debug Debug =>
2020-05-31 02:07:32.5279 Debug Info =>
2020-05-31 02:07:32.5279 Debug Warn => ownFile-web
2020-05-31 02:07:32.5428 Debug Error => ownFile-web
2020-05-31 02:07:32.5428 Debug Fatal => ownFile-web
2020-05-31 02:07:32.5428 Debug Targets for Microsoft.EntityFrameworkCore.Database.Transaction by level:
2020-05-31 02:07:32.5594 Debug Trace =>
2020-05-31 02:07:32.5594 Debug Debug =>
2020-05-31 02:07:32.5704 Debug Info =>
2020-05-31 02:07:32.5704 Debug Warn => ownFile-web
2020-05-31 02:07:32.5704 Debug Error => ownFile-web
2020-05-31 02:07:32.5856 Debug Fatal => ownFile-web
2020-05-31 02:07:32.5856 Debug Targets for Microsoft.EntityFrameworkCore.Database.Connection by level:
2020-05-31 02:07:32.5856 Debug Trace =>
2020-05-31 02:07:32.6033 Debug Debug =>
2020-05-31 02:07:32.6033 Debug Info =>
2020-05-31 02:07:32.6033 Debug Warn => ownFile-web
2020-05-31 02:07:32.6186 Debug Error => ownFile-web
2020-05-31 02:07:32.6186 Debug Fatal => ownFile-web
2020-05-31 02:07:32.6403 Debug Targets for Microsoft.EntityFrameworkCore.Update by level:

whats missing here?

Body:
There isn't a rule that writes to the database target in your config.

E.g. Replace

<logger name="*" minlevel="Trace" writeTo="ownFile-web" />

With

<logger name="*" minlevel="Trace" writeTo="ownFile-web, database" />


问:
how to handle a variable number of arguments in django query
My current project has me building a page where the output can be filtered by category.  Meaning by default you get a full list of items but you can narrow the output by clicking on ( multiple or a single) check boxes.  The idea would be if you only want to see the results from two categories you can choose those two and just see items from those two categories.  (think like an Amazon page where you can can search for an item but filter the results)

This works through a form using the get method.  So the url will look something like:

ip/?family=category_one&family=category_two

My code is as below:

Please note the Firmware model is related to ProductModel through a ManyToManyField and ProductModel is related to Family through a ForeignKey relation

*models

```<code>class Family(models.Model):
    family_id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    slug = models.SlugField(null=False, unique=True)
    family_name = models.CharField(max_length=50, editable=True, unique=True)

class ProductModel(models.Model):
    model_id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    model_number = models.CharField(max_length=25, editable=True, unique=True)
    family_id = models.ForeignKey(Family, on_delete=models.DO_NOTHING, editable=True, null=False, blank=False)

class Firmware(models.Model):
    firmware_id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    version = models.CharField(max_length=50, help_text='The \'version number\' of the firmware',
                               editable=True)
    model_id = models.ManyToManyField(ProductModel, editable=True)
</code>```

*View:

```<code>class FirmwareListView(ListView):
    model = Firmware
    context_object_name = 'firmwares'
    qs = QuerySet()

    def get(self, request, *args, **kwargs):
        requested_families = request.GET.getlist("family")
        if requested_families:
            query = Q(model_id__family_id__family_name__iexact=requested_families[0])
            for f in range(1, len(requested_families)):
                query = query | Q(model_id__family_id__family_name__iexact=requested_families[f])
            self.qs = Firmware.objects.filter(query)
        else:
            self.qs = Firmware.objects.all()
        return super().get(request, *args, **kwargs)

    def get_context_data(self, *, object_list=None, **kwargs):
        context = super().get_context_data()
        context['firmware_list'] = self.qs
        return context
</code>```

The most important parts here are:

```<code>        requested_families = request.GET.getlist("family")
        if requested_families:
            query = Q(model_id__family_id__family_name__iexact=requested_families[0])
            for f in range(1, len(requested_families)):
                query = query | Q(model_id__family_id__family_name__iexact=requested_families[f])
            self.qs = Firmware.objects.filter(query)
</code>```

This query will work (in that it runs and returns results but the results are wrong.  The results seem to be as if they ignore the exact requirement and only run a contains query.  In other words, if I filter by the category foo I will get results for food and foo.  If I run the query by doing the below:

```<code>self.qs = Firmware.objects.filter(Q(model_id__family_id__family_name__iexact=requested_families[0]) | Q(model_id__family_id__family_name__iexact=requested_families[1]))
</code>```

and I choose two categories the result is perfect.  Of course I cannot use the above method in production since I will never know how many categories a user will choose.

I have seen this post  ( Django query with variable number of filter arguments ) and tried all of the suggestions there with no luck.

I believe the issue is I am trying to filter on a field from a model that runs through a many to many field then a foreign key.  There is no way to get around this (that I can think of at least)

Any help offered is greatly appreciated.  I am a bit stuck on this one but there must be a way to do it.  For now the only method I can think of is to perform a separate query on each term and then combine the results at the end.

答: I had to do something similar. I ended up using a queryset that chained .exclude()'s to those not selected. I used a little javascript in the form to pass the right (those I didn't want) values.</p>

Body:
My current project has me building a page where the output can be filtered by category.  Meaning by default you get a full list of items but you can narrow the output by clicking on ( multiple or a single) check boxes.  The idea would be if you only want to see the results from two categories you can choose those two and just see items from those two categories.  (think like an Amazon page where you can can search for an item but filter the results)

This works through a form using the get method.  So the url will look something like:

ip/?family=category_one&family=category_two

My code is as below:

Please note the Firmware model is related to ProductModel through a ManyToManyField and ProductModel is related to Family through a ForeignKey relation

*models

class Family(models.Model):
    family_id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    slug = models.SlugField(null=False, unique=True)
    family_name = models.CharField(max_length=50, editable=True, unique=True)

class ProductModel(models.Model):
    model_id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    model_number = models.CharField(max_length=25, editable=True, unique=True)
    family_id = models.ForeignKey(Family, on_delete=models.DO_NOTHING, editable=True, null=False, blank=False)

class Firmware(models.Model):
    firmware_id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    version = models.CharField(max_length=50, help_text='The \'version number\' of the firmware',
                               editable=True)
    model_id = models.ManyToManyField(ProductModel, editable=True)

*View:

class FirmwareListView(ListView):
    model = Firmware
    context_object_name = 'firmwares'
    qs = QuerySet()

    def get(self, request, *args, **kwargs):
        requested_families = request.GET.getlist("family")
        if requested_families:
            query = Q(model_id__family_id__family_name__iexact=requested_families[0])
            for f in range(1, len(requested_families)):
                query = query | Q(model_id__family_id__family_name__iexact=requested_families[f])
            self.qs = Firmware.objects.filter(query)
        else:
            self.qs = Firmware.objects.all()
        return super().get(request, *args, **kwargs)

    def get_context_data(self, *, object_list=None, **kwargs):
        context = super().get_context_data()
        context['firmware_list'] = self.qs
        return context

The most important parts here are:

        requested_families = request.GET.getlist("family")
        if requested_families:
            query = Q(model_id__family_id__family_name__iexact=requested_families[0])
            for f in range(1, len(requested_families)):
                query = query | Q(model_id__family_id__family_name__iexact=requested_families[f])
            self.qs = Firmware.objects.filter(query)

This query will work (in that it runs and returns results but the results are wrong.  The results seem to be as if they ignore the exact requirement and only run a contains query.  In other words, if I filter by the category foo I will get results for food and foo.  If I run the query by doing the below:

self.qs = Firmware.objects.filter(Q(model_id__family_id__family_name__iexact=requested_families[0]) | Q(model_id__family_id__family_name__iexact=requested_families[1]))

and I choose two categories the result is perfect.  Of course I cannot use the above method in production since I will never know how many categories a user will choose.

I have seen this post  ( Django query with variable number of filter arguments ) and tried all of the suggestions there with no luck.

I believe the issue is I am trying to filter on a field from a model that runs through a many to many field then a foreign key.  There is no way to get around this (that I can think of at least)

Any help offered is greatly appreciated.  I am a bit stuck on this one but there must be a way to do it.  For now the only method I can think of is to perform a separate query on each term and then combine the results at the end.


问:
MySQL server startup error 'The server quit without updating PID file'
On Mac OS X v10.6 (Snow Leopard), starting MySQL gives the following error:

The server quit without updating PID file

File my.cnf

[mysqld]
port            = 3306

socket          = /tmp/mysql.sock

skip-external-locking

key_buffer_size = 16K

pid-file=/var/run/mysqld/mysqld.pid

[mysqld_safe]

log-error=/var/log/mysqld.log

pid-file=/var/run/mysqld/mysqld.pid
```

答:
This worked for me:

Note: This a hard reinstall. Use when all other options have been exhausted.

On a Mac with Homebrew:

List all instances of MySQL that exists by running

brew services
```
<p>Remove each instance by running</p>
<pre class="lang-none prettyprint-override"><code>brew uninstall <instance_name>
</code>```

Delete the MySQL directory in /usr/local/var/mysql:

rm -rf /usr/local/var/mysql
```
<p>Reinstall MySQL using Homebrew:</p>
```brew install mysql
brew install mysql@<version> #Optional
```
<p>Rerun <em>mysql.server start</em>:</p>
<pre class="lang-none prettyprint-override"><code>mysql.server start
</code>```

Body:
This worked for me:

Note: This a hard reinstall. Use when all other options have been exhausted.

On a Mac with Homebrew:

List all instances of MySQL that exists by running

brew services

Remove each instance by running

brew uninstall <instance_name>

Delete the MySQL directory in /usr/local/var/mysql:

rm -rf /usr/local/var/mysql

Reinstall MySQL using Homebrew:

brew install mysql
brew install mysql@<version> #Optional

Rerun mysql.server start:

mysql.server start


问:
jQuery: Editing user inserted DOM elements
I want to add html items (text and buttons inside a div) to the DOM and each item be editable or deletable.  I used jquery to do this as follows.

```<code><div id="ak"></div>
<input type="text" name="lname" id="itext" size="60"/><br/>
<button id="but">Add Item</button>
<div id="test"></div>

$("#but").click(function(){
        var istring = $("#itext").val();
        $("#ak").append("<div class=\"item\"><p>"+istring+"<button class=\"editable\">Edit</button><button class=\"deletable\">Delete</button></p></div>");
        $("#itext").val("");
});

$(".deletable").click(function(){
    alert("Alert !!");
});
</code>```

However, when I pressed the delete button in each item nothing happens (should give an alert).  I feel something is very wrong.  Any help is appreciated.

答:
I ran into this exact problem a few days ago, but one of my coworkers was kind enough to clear up my confusion.

You need to rebind the click event after you add the HTML to the dom or use jQuery live. Some older versions of jQuery don't support live so you can use alternative means.

The following rebinds the click event after the HTML has been loaded:

```<code>$("#but").click(function(){
        var istring = $("#itext").val();
        $("#ak").append("<div class=\"item\"><p>"+istring+"<button class=\"editable\">Edit</button><button class=\"deletable\">Delete</button></p></div>");
        $("#itext").val("");
        clickEvent();
});
function clickEvent(){
    $(".deletable").click(function(){
        alert("Alert !!");
    });
}
</code>```

Or, using jQuery live:

```<code>$(".deletable").live('click',function(){
    alert("Alert !!");
});
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I want to add html items (text and buttons inside a div) to the DOM and each item be editable or deletable.  I used jquery to do this as follows.

<input type="text" name="lname" id="itext" size="60"/>

<button id="but">Add Item</button>

$("#but").click(function(){
        var istring = $("#itext").val();
        $("#ak").append("

"+istring+"<button class=\"editable\">Edit</button><button class=\"deletable\">Delete</button>

");
        $("#itext").val("");
});

$(".deletable").click(function(){
    alert("Alert !!");
});

However, when I pressed the delete button in each item nothing happens (should give an alert).  I feel something is very wrong.  Any help is appreciated.

Body:
I ran into this exact problem a few days ago, but one of my coworkers was kind enough to clear up my confusion.

You need to rebind the click event after you add the HTML to the dom or use jQuery live. Some older versions of jQuery don't support live so you can use alternative means.

The following rebinds the click event after the HTML has been loaded:

$("#but").click(function(){
        var istring = $("#itext").val();
        $("#ak").append("<div class=\"item\"><p>"+istring+"<button class=\"editable\">Edit</button><button class=\"deletable\">Delete</button></p></div>");
        $("#itext").val("");
        clickEvent();
});
function clickEvent(){
    $(".deletable").click(function(){
        alert("Alert !!");
    });
}

Or, using jQuery live:

$(".deletable").live('click',function(){
    alert("Alert !!");
});


问:
How to save value from totals row in filtered subform to use in another calculation
Trying to find out if there is code to extract the value from the totals row in a filtered subform so that I can use that total in another calculation on the parent form.

I have a form: frmMain, which is bound to tblCustomers,  a subform made from a query: qryDeliveries thesubform is just a datasheet, bound to the parent by way of CustomerID, with the totals row set to total two different fields: wage, tip. frmMain has a set of text boxes to enter in dates in order to filter qryDeliveries by that range. There are two sets of these boxes.  One filters by WageDate and the other by TipDate. txtWageStart, txtWageEnd, txtTipStart, txtTipEnd

What I'm trying to do is to add another text box somewhere on the frmMain, call it txtTotal and after filtering for WageDate, the sum of the wage column is saved, and then after filtering for the TipDate, the sum of the Tip column is saved.  Then both of those numbers added together to give me a combined total and this combined total is display in txtTotal.

I'm quite certain my whole layout is not quite the normal way it would be done, but I know very little about Access, and have spent weeks just piecing what I have together so far, trying to learn, but just about everything about vba is still a mystery as well as what is actually capable of being done or not.

any help would be greatly appreciated.  Thank you.

答:
Cannot reference calculations generated by setting Totals row of a datasheet. Put textboxes in subform's footer section with expression to sum: =Sum([field name]). The textboxes will not display but can be referenced.

=[subform container name].Form.[textboxname]


问:
Tensorflow io.gfile.GFile error - Curl returned error code 60 - If the signature check failed. This could be because of a time skew
I'm using tf.io.gfile.GFile(...) to read a file from an S3 compliant interface. The code that produces this error worked yesterday and stopped working today with no change to the code, so potentially a change on the server side.

```<code>2020-05-30 11:33:01.400501: I tensorflow/core/platform/s3/aws_logging.cc:54] Setting provider to read credentials from /home/davidparks21//.aws/credentials for credentials file and /home/davidparks21//.aws/config for the config file , for use with profile default
2020-05-30 11:33:01.400526: I tensorflow/core/platform/s3/aws_logging.cc:54] Creating AWSHttpResourceClient with max connections2 and scheme http
2020-05-30 11:33:01.400538: I tensorflow/core/platform/s3/aws_logging.cc:54] Initializing CurlHandleContainer with size 2
2020-05-30 11:33:01.400551: I tensorflow/core/platform/s3/aws_logging.cc:54] Creating Instance with default EC2MetadataClient and refresh rate 300000
2020-05-30 11:33:01.400561: I tensorflow/core/platform/s3/aws_logging.cc:54] Added EC2 metadata service credentials provider to the provider chain.
2020-05-30 11:33:01.400643: I tensorflow/core/platform/s3/aws_logging.cc:54] Successfully reloaded configuration.
2020-05-30 11:33:01.400705: I tensorflow/core/platform/s3/aws_logging.cc:54] Initializing CurlHandleContainer with size 25
2020-05-30 11:33:01.401062: I tensorflow/core/platform/s3/aws_logging.cc:54] Pool grown by 2
2020-05-30 11:33:01.401081: I tensorflow/core/platform/s3/aws_logging.cc:54] Connection has been released. Continuing.
2020-05-30 11:33:01.486735: E tensorflow/core/platform/s3/aws_logging.cc:60] Curl returned error code 60
2020-05-30 11:33:01.486780: E tensorflow/core/platform/s3/aws_logging.cc:60] HTTP response code: 684960552
Exception name:
Error message: Unable to connect to endpoint
0 response headers:
2020-05-30 11:33:01.486802: W tensorflow/core/platform/s3/aws_logging.cc:57] If the signature check failed. This could be because of a time skew. Attempting to adjust the signer.
2020-05-30 11:33:01.486823: W tensorflow/core/platform/s3/aws_logging.cc:57] Request failed, now waiting 0 ms before attempting again.
2020-05-30 11:33:01.486993: I tensorflow/core/platform/s3/aws_logging.cc:54] Connection has been released. Continuing.
</code>```

Looking at libcurl error code 60 https://curl.haxx.se/libcurl/c/libcurl-errors.html:

```<code>CURLE_PEER_FAILED_VERIFICATION (60)

The remote server's SSL certificate or SSH md5 fingerprint was deemed not OK. This error code has been unified with CURLE_SSL_CACERT since 7.62.0. Its previous value was 51.
</code>```

Tested on TF 1.14.0 and 2.2.0-rc3

答: It turns out that a cert expired on the S3 api-compliant server which was the cause of this. Notably, only libcurl (and we found wget) seems to check this. Other S3 tools like awscli/boto3 do not care.

Body:
I'm using tf.io.gfile.GFile(...) to read a file from an S3 compliant interface. The code that produces this error worked yesterday and stopped working today with no change to the code, so potentially a change on the server side.

2020-05-30 11:33:01.400501: I tensorflow/core/platform/s3/aws_logging.cc:54] Setting provider to read credentials from /home/davidparks21//.aws/credentials for credentials file and /home/davidparks21//.aws/config for the config file , for use with profile default
2020-05-30 11:33:01.400526: I tensorflow/core/platform/s3/aws_logging.cc:54] Creating AWSHttpResourceClient with max connections2 and scheme http
2020-05-30 11:33:01.400538: I tensorflow/core/platform/s3/aws_logging.cc:54] Initializing CurlHandleContainer with size 2
2020-05-30 11:33:01.400551: I tensorflow/core/platform/s3/aws_logging.cc:54] Creating Instance with default EC2MetadataClient and refresh rate 300000
2020-05-30 11:33:01.400561: I tensorflow/core/platform/s3/aws_logging.cc:54] Added EC2 metadata service credentials provider to the provider chain.
2020-05-30 11:33:01.400643: I tensorflow/core/platform/s3/aws_logging.cc:54] Successfully reloaded configuration.
2020-05-30 11:33:01.400705: I tensorflow/core/platform/s3/aws_logging.cc:54] Initializing CurlHandleContainer with size 25
2020-05-30 11:33:01.401062: I tensorflow/core/platform/s3/aws_logging.cc:54] Pool grown by 2
2020-05-30 11:33:01.401081: I tensorflow/core/platform/s3/aws_logging.cc:54] Connection has been released. Continuing.
2020-05-30 11:33:01.486735: E tensorflow/core/platform/s3/aws_logging.cc:60] Curl returned error code 60
2020-05-30 11:33:01.486780: E tensorflow/core/platform/s3/aws_logging.cc:60] HTTP response code: 684960552
Exception name:
Error message: Unable to connect to endpoint
0 response headers:
2020-05-30 11:33:01.486802: W tensorflow/core/platform/s3/aws_logging.cc:57] If the signature check failed. This could be because of a time skew. Attempting to adjust the signer.
2020-05-30 11:33:01.486823: W tensorflow/core/platform/s3/aws_logging.cc:57] Request failed, now waiting 0 ms before attempting again.
2020-05-30 11:33:01.486993: I tensorflow/core/platform/s3/aws_logging.cc:54] Connection has been released. Continuing.

Looking at libcurl error code 60 https://curl.haxx.se/libcurl/c/libcurl-errors.html:

CURLE_PEER_FAILED_VERIFICATION (60)

The remote server's SSL certificate or SSH md5 fingerprint was deemed not OK. This error code has been unified with CURLE_SSL_CACERT since 7.62.0. Its previous value was 51.

Tested on TF 1.14.0 and 2.2.0-rc3


问:
C Program to finding perfect squares inside the given number by user?
I tried to solve this below program but I don't know how to find perfect square inside the given number.
I don't know how to approach this problem. plz help me solve the problem.

Program:-

Write a C program to get a number from user and find the perfect square inside the number and print them in ascending order.

Expeccted Output:-

```<code>User  :- 4673681
Result:- 1,4,36,.81

User  :- 1625649
Result:- 1,16,25,49,64,256,625.
</code>```

I wrote the program like below,
here, what I done is? I initialized  array with some values and make a value as perfect square and then I sorted as a ascending order finally.But, what I expected is totally different. see the above expected output examples for better understanding.

```<code>#include<stdio.h>
int main()
{
    int a[10]={4,6,3,9,7,2,8};
    int i,j,m=8,temp;
   // printf("Enter the elements:");
    //scanf("%d",&m);

    for(i=0;i<m;i++)
    {
        a[i]= a[i]*a[i];
    }
    for(i=0;i<m-1;i++)
    {
        for(j=i+1;j<m;j++)
        {
            if(a[i]>a[j])
            {
                temp = a[i];
                a[i] = a[j];
                a[j] = temp;
            }
        }
    }
    printf("ascending orders:\n");
    for(i=0;i<m;i++)
    {
        printf("%d\n",a[i]);
    }
}
</code>```

答:
Interesting little problem, it was easily solved.

```<code>#include <stdio.h>
#include <math.h>

void findsquares(int num)
{
    for(int x = 1; x*x <= num; ++x)
    {
        int m = pow(10,(int)log10(x*x)+1);
        for(int t = num; t; t /= 10)
        {
            printf((t%m == x*x)? "%d, " : "", x*x);
        }
    }
}

int main(void) {
    int num = 1625649;

    findsquares(num);

    return 0;
}
</code>```

Output

```<code>Success #stdin #stdout 0s 4360KB
1, 4, 9, 16, 25, 49, 64, 256, 625,
</code>```

Body:
I tried to solve this below program but I don't know how to find perfect square inside the given number.
I don't know how to approach this problem. plz help me solve the problem.

Program:-

Write a C program to get a number from user and find the perfect square inside the number and print them in ascending order.

Expeccted Output:-

User  :- 4673681
Result:- 1,4,36,.81

User  :- 1625649
Result:- 1,16,25,49,64,256,625.

I wrote the program like below,
here, what I done is? I initialized  array with some values and make a value as perfect square and then I sorted as a ascending order finally.But, what I expected is totally different. see the above expected output examples for better understanding.

#include<stdio.h>
int main()
{
    int a[10]={4,6,3,9,7,2,8};
    int i,j,m=8,temp;
   // printf("Enter the elements:");
    //scanf("%d",&m);

    for(i=0;i<m;i++)
    {
        a[i]= a[i]*a[i];
    }
    for(i=0;i<m-1;i++)
    {
        for(j=i+1;j<m;j++)
        {
            if(a[i]>a[j])
            {
                temp = a[i];
                a[i] = a[j];
                a[j] = temp;
            }
        }
    }
    printf("ascending orders:\n");
    for(i=0;i<m;i++)
    {
        printf("%d\n",a[i]);
    }
}

Body:
Interesting little problem, it was easily solved.

#include <stdio.h>
#include <math.h>

void findsquares(int num)
{
    for(int x = 1; x*x <= num; ++x)
    {
        int m = pow(10,(int)log10(x*x)+1);
        for(int t = num; t; t /= 10)
        {
            printf((t%m == x*x)? "%d, " : "", x*x);
        }
    }
}

int main(void) {
    int num = 1625649;

    findsquares(num);

    return 0;
}

Output

Success #stdin #stdout 0s 4360KB
1, 4, 9, 16, 25, 49, 64, 256, 625,


问:
Is Amazon EC2 free tier server appropriate for my little web application?
I'm building a little software activation web service in Java, so I need a cloud-based server which will run Apache and Tomcat and MySQL.

It will get very little usage as I don't expect to sell very much product at first.  I'll be very lucky if the server handles one quick activation a day ... if it got 20 in a day that would be an amazing success.

I'm looking at Amazon EC2 pricing here ...

https://aws.amazon.com/free/?all-free-tier.sort-by=item.additionalFields.SortRank&all-free-tier.sort-order=asc

I see that there is a "Free Tier" which provides "750 hours per month of Linux t2.micro or t3.micro instance".  And it's free for year.

STUPID QUESTION #1: 24h/day x 31 days/month is 744 hours ... so, does that mean I'm getting a free linux server running 24/7 for a year or is there a catch that I'm missing?

STUPID QUESTION #2: t2.micro/t2.micro has 1 vCPU, 1GB Memory ... is that enough power to run a simple Apache + Tomcat + MySQL web service reliably?

STUPID QUESTION #3: Any reason why I should skip the free tier and invest in a powerful pay $$$ option?

答:
Yes. No catch. It's just not a very strong server.

That really depends on what that service does. Performance wise you need to pay attention to t2 instances being optimized for burst operations. That means they run full speed for a little while and then get throttled. But if you're talking about reliability, it's a whole other story. Just one machine is usually not enough for that. You want multiple machines in multiple data centers. What if one machine goes down? What if the whole data center goes down? It really depends on just how reliable you want it.

That really depends on what you're looking for. If you don't know yet, stick to free until you figure it out. I would even go for something simpler like Heroku at first. At least you won't have to take care of the reliability aspect as much.


问:
Dragging condition draw - Openlayers
I'm currently developing a webapp that allows the end-user to draw different shapes. I've set the draw-object up with a condition to check for various things. This includes checking for intersections with other geometry objects.

The issue i have is that the condition is always called, and only returns the "pointerdown"-event. Basically if the user clicks and hold down the mouse (dragging), this leads to the segment not being added drawing due to the "clickTolerance":

https://openlayers.org/en/latest/apidoc/module-ol_interaction_Draw-Draw.html

This is fine, and i don't want to change this. The user should be able to drag the map while drawing. But the problem is that the condition is always called, even though the segment is not added to the drawing.

Is there any way around this?

答:
I think these examples covers your use case:

Free hand drawing:

https://openlayers.org/en/latest/examples/draw-freehand.html

Drawing shapes:

https://openlayers.org/en/latest/examples/draw-shapes.html

Hope this helps!

Title: Dragging condition draw - Openlayers


答: Yes, i have developed an low to medium web application as mysql backend.But, please be sure about number of users , as it depends on the performance and scalability.</p>

Title: Is Amazon EC2 free tier server appropriate for my little web application?

Body:
I'm building a little software activation web service in Java, so I need a cloud-based server which will run Apache and Tomcat and MySQL.

It will get very little usage as I don't expect to sell very much product at first.  I'll be very lucky if the server handles one quick activation a day ... if it got 20 in a day that would be an amazing success.

I'm looking at Amazon EC2 pricing here ...

https://aws.amazon.com/free/?all-free-tier.sort-by=item.additionalFields.SortRank&all-free-tier.sort-order=asc

I see that there is a "Free Tier" which provides "750 hours per month of Linux t2.micro or t3.micro instance".  And it's free for year.

STUPID QUESTION #1: 24h/day x 31 days/month is 744 hours ... so, does that mean I'm getting a free linux server running 24/7 for a year or is there a catch that I'm missing?

STUPID QUESTION #2: t2.micro/t2.micro has 1 vCPU, 1GB Memory ... is that enough power to run a simple Apache + Tomcat + MySQL web service reliably?

STUPID QUESTION #3: Any reason why I should skip the free tier and invest in a powerful pay $$$ option?


Title: reducing a nested object in javascript

Body:
I have an object with the structure

"Office": {
    "California" : {
        "Contract1": {
            1: {Price: 1000, Count: 5},
            2: {Price: 2000, Count: 11},
            3: {Price: 3000, Count: 3},
            4: {Price: 2000, Count: 1},...
        },
        "Contract2": {
            1: {Price: 7000, Count: 6},
            2: {Price: 1000, Count: 4},
            3: {Price: 67000, Count: 6},
            4: {Price: 500, Count: 2},...
        },
        "Contract3": {
            1: {Price: 4000, Count: 4},
            2: {Price: 4000, Count: 1},
            3: {Price: 5000, Count: 12},
            4: {Price: 5000, Count: 2},...
        }
    },
    "North Carolina" : {
        "Contract1": {
            1: {Price: 7000, Count: 4},
            2: {Price: 7000, Count: 4},
            3: {Price: 7000, Count: 4},
            4: {Price: 7000, Count: 4},...
        },
        "Contract2": {
            1: {Price: 6000, Count: 4},
            2: {Price: 2000, Count: 10},
            3: {Price: 3000, Count: 3},
            4: {Price: 2000, Count: 3},...
        },
        "Contract3": {
            1: {Price: 4000, Count: 5},
            2: {Price: 2000, Count: 4},
            3: {Price: 4000, Count: 3},
            4: {Price: 2000, Count: 4},...
        },...
}

And I want to reduce it to this:

"Office": {
    "California" : {
        "Contract1": {
            1: {Price: 6000, Count: 19},
            2: {Price: 2000, Count: 1},...
        },
        "Contract2": {
            1: {Price: 75000, Count: 16},
            2: {Price: 500, Count: 2},...
        },
        "Contract3": {
            1: {Price: 13000, Count: 17},
            2: {Price: 5000, Count: 2},...
        }
    },
    "North Carolina" : {
        "Contract1": {
            1: {Price: 21000, Count: 12},
            2: {Price: 7, Count: 4},...
        },
        "Contract2": {
            1: {Price: 11000, Count: 17},
            2: {Price: 2000, Count: 3},...
        },
        "Contract3": {
            1: {Price: 10000, Count: 12},
            2: {Price: 2000, Count: 4},...
        },...
}

The number objects under each contract on the first structure represent the months past. In the second structure I want to sum up the properties of the first 3 number objects can call this 1. Then the second 3 would be 2. These are quarters.

I think I can do this with some sort of combination of map, reduce and filter but these are array functions and I have an object so I’m not sure how to do it. I need to do this for a non ES6 solution.

Any guidance would be really appreciated.

Body:
You can do it this way using a special map function I wrote that works on objects

const { pipe, fork, map, reduce, get } = rubico

const data = { "Office": {
    "California" : {
        "Contract1": {
            1: {Price: 1000, Count: 5}, 2: {Price: 2000, Count: 11},
            3: {Price: 3000, Count: 3}, 4: {Price: 2000, Count: 1},
            5: {Price: 1000, Count: 5}, 6: {Price: 2000, Count: 11},
            7: {Price: 3000, Count: 3}, 8: {Price: 2000, Count: 1},
            9: {Price: 1000, Count: 5}, 10: {Price: 2000, Count: 11},
            11: {Price: 3000, Count: 3}, 12: {Price: 2000, Count: 1},
        },
        "Contract2": {
            1: {Price: 7000, Count: 6}, 2: {Price: 1000, Count: 4},
            3: {Price: 67000, Count: 6}, 4: {Price: 500, Count: 2},
            5: {Price: 7000, Count: 6}, 6: {Price: 1000, Count: 4},
            7: {Price: 67000, Count: 6}, 8: {Price: 500, Count: 2},
            9: {Price: 7000, Count: 6}, 10: {Price: 1000, Count: 4},
            11: {Price: 67000, Count: 6}, 12: {Price: 500, Count: 2},
        },
        "Contract3": {
            1: {Price: 4000, Count: 4}, 2: {Price: 4000, Count: 1},
            3: {Price: 5000, Count: 12}, 4: {Price: 5000, Count: 2},
            5: {Price: 4000, Count: 4}, 6: {Price: 4000, Count: 1},
            7: {Price: 5000, Count: 12}, 8: {Price: 5000, Count: 2},
            9: {Price: 4000, Count: 4}, 10: {Price: 4000, Count: 1},
            11: {Price: 5000, Count: 12}, 12: {Price: 5000, Count: 2},
        }
    },
    "North Carolina" : {
        "Contract1": {
            1: {Price: 7000, Count: 4}, 2: {Price: 7000, Count: 4},
            3: {Price: 7000, Count: 4}, 4: {Price: 7000, Count: 4},
            5: {Price: 7000, Count: 4}, 6: {Price: 7000, Count: 4},
            7: {Price: 7000, Count: 4}, 8: {Price: 7000, Count: 4},
            9: {Price: 7000, Count: 4}, 10: {Price: 7000, Count: 4},
            11: {Price: 7000, Count: 4}, 12: {Price: 7000, Count: 4},
        },
        "Contract2": {
            1: {Price: 6000, Count: 4}, 2: {Price: 2000, Count: 10},
            3: {Price: 3000, Count: 3}, 4: {Price: 2000, Count: 3},
            5: {Price: 6000, Count: 4}, 6: {Price: 2000, Count: 10},
            7: {Price: 3000, Count: 3}, 8: {Price: 2000, Count: 3},
            9: {Price: 6000, Count: 4}, 10: {Price: 2000, Count: 10},
            11: {Price: 3000, Count: 3}, 12: {Price: 2000, Count: 3},
        },
        "Contract3": {
            1: {Price: 4000, Count: 5}, 2: {Price: 2000, Count: 4},
            3: {Price: 4000, Count: 3}, 4: {Price: 2000, Count: 4},
            5: {Price: 4000, Count: 5}, 6: {Price: 2000, Count: 4},
            7: {Price: 4000, Count: 3}, 8: {Price: 2000, Count: 4},
            9: {Price: 4000, Count: 5}, 10: {Price: 2000, Count: 4},
            11: {Price: 4000, Count: 3}, 12: {Price: 2000, Count: 4},
        },
    },
} }

const addContracts = (total, contract) => ({
  Price: total.Price + contract.Price,
  Count: total.Count + contract.Count,
})

const monthNumbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]

const sumMonthsToQuarters = contract => {
  const quartered = {
    1: { Price: 0, Count: 0 },
    2: { Price: 0, Count: 0 },
    3: { Price: 0, Count: 0 },
    4: { Price: 0, Count: 0 },
  }
  for (const monthNum of monthNumbers) {
    const quarterNum = Math.ceil(monthNum / 3)
    quartered[quarterNum] = addContracts(quartered[quarterNum], contract[monthNum])
  }
  return quartered
}

const x = map(map(map(sumMonthsToQuarters)))(data)

console.log(JSON.stringify(x))

<script src="https://unpkg.com/rubico/index.js" crossorigin></script>


问:
Trading view alerts to trigger market order through python and Oanda's API
I'm trying to trigger a python module (market order for Oanda) using web hooks(from trading view).

Similar to this

1) https://www.youtube.com/watch?v=88kRDKvAWMY&feature=youtu.be
and this
2)https://github.com/Robswc/tradingview-webhooks-bot

But my broker is Oanda so I'm using python to place the trade. This link has more information.
https://github.com/hootnot/oanda-api-v20

The method is web hook->ngrok->python. When a web hook is sent, the ngrok (while script is also running) shows a 500 internal service error and that the server encountered an internal error and was unable to complete your request. Either the server is overloaded or there is an error in the application.

This is what my script says when its running (see picture);

First says some stuff related the market order then;
running script  picture
One thing I noticed is that after Debug it doesn't say Running on... (so maybe my flask is not active?

Here is the python script;

```<code>from flask import Flask
import market_orders
# Create Flask object called app.
app = Flask(__name__)
# Create root to easily let us know its on/working.
@app.route('/')
def root():
    return 'online'
@app.route('/webhook', methods=['POST'])
def webhook():
    if request.method == 'POST':
        # Parse the string data from tradingview into a python dict
        print(market_orders.myfucn())
    else:
        print('do nothing')
if __name__ == '__main__':
    app.run()
</code>```

Let me know if there is any other information that would be helpful.

Thanks for your help.

答:
I fixed it!!!! Google FTW

The first thing I learned was how to make my module a FLASK server. I followed these websites to figure this out;

This link helped me set up the flask file in a virtual environment. I also moved my Oanda modules to this new folder. And opened the ngrok app while in this folder via the command window. I also ran the module from within the command window using flask run.
https://topherpedersen.blog/2019/12/28/how-to-setup-a-new-flask-app-on-a-mac/

This link showed me how to set the FLASK_APP and the FLASK_ENV
Flask not displaying http address when I run it

Then I fixed the internal service error by adding return 'okay' after print(do nothing) in my script. This I learned from;

Flask Value error view function did not return a response

Body:
I'm trying to trigger a python module (market order for Oanda) using web hooks(from trading view).

Similar to this

1) https://www.youtube.com/watch?v=88kRDKvAWMY&feature=youtu.be
and this
2)https://github.com/Robswc/tradingview-webhooks-bot

But my broker is Oanda so I'm using python to place the trade. This link has more information.
https://github.com/hootnot/oanda-api-v20

The method is web hook->ngrok->python. When a web hook is sent, the ngrok (while script is also running) shows a 500 internal service error and that the server encountered an internal error and was unable to complete your request. Either the server is overloaded or there is an error in the application.

This is what my script says when its running (see picture);

First says some stuff related the market order then;
running script  picture
One thing I noticed is that after Debug it doesn't say Running on... (so maybe my flask is not active?

Here is the python script;

from flask import Flask
import market_orders
# Create Flask object called app.
app = Flask(__name__)
# Create root to easily let us know its on/working.
@app.route('/')
def root():
    return 'online'
@app.route('/webhook', methods=['POST'])
def webhook():
    if request.method == 'POST':
        # Parse the string data from tradingview into a python dict
        print(market_orders.myfucn())
    else:
        print('do nothing')
if __name__ == '__main__':
    app.run()

Let me know if there is any other information that would be helpful.

Thanks for your help.


问:
Can't find .zshrc file
Recently I installed someone else .dotfiles and as excepted overwrited my configuration.

The thing is that I want to use my custom settings for my ZSH but I can't find .zshrc inside ~/, I have other .zshrc.files but editing none of these is working.

Also the dotfiles I've installed are in `~/.dotfiles but seems that none of these contains config.

Can someone please explain me how to edit the ZSH now, can I revert my old .zshrc?

答:
Go to home directory typing cd

Type the command zsh and Press Enter

Select the option (2)  Populate your ~/.zshrc with the configuration
recommended
    by the system administrator and exit (you will need to edit
    the file by hand, if so desired).

(You have to type "2" to select it and press enter)...

then all the files will be created on the directory..

Title: Can't find .zshrc file


答:
If your ranges are set in stone you could loop through a list of your ranges:

```<code>ranges = [[0,5499],[5500,9499],[9500,14499],[14500,19499],[19500,24499],[24500,29499],[29500,34499],[34500,39499],[39500,44499]]
returns = [5000,10000,15000,20000,25000,30000,35000,40000,45000]

def checkRange(number):
    for i in range(len(returns)):
        if number in range(ranges[i][0], ranges[i][1]):
            return returns[i]

# Test a few values:
print(checkRange(10))
print(checkRange(6000))
</code>```

I get output:

```<code>5000
10000
</code>```

Also, be sure to fix your 8th entry so that it is a range and not a single int.

Title: Is there a better way to check if a number is range of two numbers

Body:
I am trying to check if a number is in range of integers and returns a number based on which range it lies. I was wondering if is there a better and more efficient way of doing this:

def checkRange(number):
    if number in range(0, 5499):
        return 5000
    elif number in range(5500, 9499):
        return 10000
    elif number in range(9500, 14499):
        return 15000
    elif number in range(14500, 19499):
        return 20000
    elif number in range(19500, 24499):
        return 25000
    elif number in range(24500, 29499):
        return 30000
    elif number in range(29500, 34499):
        return 35000
    elif number in range(34500, 39499):
        return 40000
    elif number in range(39500, 44499):
        return 45000

This felt like a waste of resources and would greatly appreciate if there is a better way to do this.

Body:
If your ranges are set in stone you could loop through a list of your ranges:

ranges = [[0,5499],[5500,9499],[9500,14499],[14500,19499],[19500,24499],[24500,29499],[29500,34499],[34500,39499],[39500,44499]]
returns = [5000,10000,15000,20000,25000,30000,35000,40000,45000]

def checkRange(number):
    for i in range(len(returns)):
        if number in range(ranges[i][0], ranges[i][1]):
            return returns[i]

# Test a few values:
print(checkRange(10))
print(checkRange(6000))

I get output:

5000
10000

Also, be sure to fix your 8th entry so that it is a range and not a single int.


问:
Multi Value in Query Select PrestoDB
I'm trying to perfom some query to Prestodb like this:

```<code>SELECT *
FROM (
     VALUES
     concat('<a href="https:test?preselect_filters=',
     url_encode(concat('{"27":{','"column_name":["', CAST({{ "'" +
     "','".join(filter_values('column_name', concat('#value1', '#value2'))) +
     "'" }} AS VARCHAR), '"]', ',','}}')),
     '#TAB-bEGT8cU5h">Qun', '</a>')
         ) dashboard_link (links)
</code>```

my problem is concat('#value1','#value2'), any idea to select an array of values?

答:
Is this what you need?

```<code>select * from (values concat(ARRAY [1,2,3], ARRAY [4,5,6]));
</code>```

You can refer to prestodb doc

Title: Multi Value in Query Select PrestoDB

Body:
I'm trying to perfom some query to Prestodb like this:

SELECT *
FROM (
     VALUES
     concat('Qun', '')
         ) dashboard_link (links)

my problem is concat('#value1','#value2'), any idea to select an array of values?

Body:
Is this what you need?

select * from (values concat(ARRAY [1,2,3], ARRAY [4,5,6]));

You can refer to prestodb doc


问:
Script to find the last cell edited in a Google sheet has recently stopped
Firstly I am NO programmer - but I found a pretty simple script that we have been running for years on a shared Google sheet that simply finds the last edited cell in a large amount of data. It worked brilliantly, you open the sheet and in no time you're looking at the last line that had been edited and you can begin your data entry. Recently - it simply stopped?
I'm seeing posts about V8 but looking at the script - it says it's running on V8?

```<code>function onOpen() {
  var ThisSheet = SpreadsheetApp.getActiveSpreadsheet();
  var StartingTab = ThisSheet.getSheetByName("Key# 20-30K");  // The default tab being opened
  var LastRow = ThisSheet.getLastRow() + 1;  // One past the last row that has been entered in the spreadsheet
  var LastCellString = "A"+LastRow+":A"+LastRow;  // The string representing the last cell to position to
  var LastCell = ThisSheet.getRange(LastCellString); // The internal variable of the last cell
  StartingTab.setActiveRange(LastCell)  // Actually perform the repositioning to the last cell
}
</code>```

This is the script - any help would be very cool.

Grant

答: Thanks for your answers - it's working again. It looks like I just needed to re-authorise it as per Cooper's suggestion (??) I hadn't moved it but it most certainly wasn't working before I did?? – Grant Cooper just</p>

Body:
Firstly I am NO programmer - but I found a pretty simple script that we have been running for years on a shared Google sheet that simply finds the last edited cell in a large amount of data. It worked brilliantly, you open the sheet and in no time you're looking at the last line that had been edited and you can begin your data entry. Recently - it simply stopped?
I'm seeing posts about V8 but looking at the script - it says it's running on V8?

function onOpen() {
  var ThisSheet = SpreadsheetApp.getActiveSpreadsheet();
  var StartingTab = ThisSheet.getSheetByName("Key# 20-30K");  // The default tab being opened
  var LastRow = ThisSheet.getLastRow() + 1;  // One past the last row that has been entered in the spreadsheet
  var LastCellString = "A"+LastRow+":A"+LastRow;  // The string representing the last cell to position to
  var LastCell = ThisSheet.getRange(LastCellString); // The internal variable of the last cell
  StartingTab.setActiveRange(LastCell)  // Actually perform the repositioning to the last cell
}

This is the script - any help would be very cool.

Grant


问:
How to filter Spark sql by nested array field (array within array)?
My spark Dataframe schema

```<code>|-- goods: array (nullable = true)
 |    |-- element: struct (containsNull = true)
 |    |    |-- brand_id: array (nullable = true)
 |    |    |    |-- element: string (containsNull = true)
 |    |    |-- product_id: string (nullable = true)
</code>```

I'm able to filter the Dataframe by product_id

```<code>select * from goodsInfo where array_contains(goods.product_id, 'f31ee3f8-9ba2-49cb-86e2-ceb44e34efd9')
</code>```

But I'm unable to filter by brand_id which is an array within array..

I get the error when I try

```<code>select * from goodsInfo where array_contains(goods.brand_id, '45c060b9-3645-49ad-86eb-65f3cd4e9081')
</code>```

Error:

```<code>function array_contains should have been array followed by a value with same element type, but it's [array<array<string>>, string].; line 1 pos 45;
</code>```

Can someone please help ?

Thanks in advance

答:
function array_contains should have been array followed by a value with same element type, but it's [array<array<string>>, string].; line 1 pos 45;

This is because brand_id is of type array<array<string>> & you are passing value is of type string, You have to wrap your value inside array i.e

array_contains(goods.brand_id, array('45c060b9-3645-49ad-86eb-65f3cd4e9081'))

Above will work only if we pass exact number of brand_id values i.e. array_contains(goods.brand_id, array('<should match same number of elements in brand_id>'))

Check below code.

```<code>scala> df.printSchema
root
 |-- goods: array (nullable = true)
 |    |-- element: struct (containsNull = true)
 |    |    |-- brand_id: array (nullable = true)
 |    |    |    |-- element: string (containsNull = true)
 |    |    |-- product_id: string (nullable = true)

scala> spark.sql("select * from goodsInfo").show(false)
+----------------------+
|goods                 |
+----------------------+
|[[[B100, B101], P100]]|
|[[[B200, B200], P200]]|
|[[[B300], P300]]      |
+----------------------+

scala> spark.sql("select * from goodsInfo where array_contains(goods.brand_id, array('B300'))").show(false) // Exact one element
+----------------+
|goods           |
+----------------+
|[[[B300], P300]]|
+----------------+

scala> spark.sql("select * from goodsInfo where array_contains(goods.brand_id, array('B100'))").show(false) // Passing single element from array. It will not give result.
+-----+
|goods|
+-----+
+-----+

scala> spark.sql("select * from goodsInfo where array_contains(goods.brand_id, array('B100','B101'))").show(false) // Pass complete array, It will give result.
+----------------------+
|goods                 |
+----------------------+
|[[[B100, B101], P100]]|
+----------------------+

</code>```

Instead of array_contains try using LATERAL VIEW explode to explode nested array values, Check below query.

```<code>SELECT
 goods
,brand_id
FROM goodsInfo
LATERAL VIEW explode(goods.brand_id) brands as brands
LATERAL VIEW explode(brands) brand_id as brand_id
WHERE brand_id = '45c060b9-3645-49ad-86eb-65f3cd4e9081';

</code>```

Body:
My spark Dataframe schema

|-- goods: array (nullable = true)
 |    |-- element: struct (containsNull = true)
 |    |    |-- brand_id: array (nullable = true)
 |    |    |    |-- element: string (containsNull = true)
 |    |    |-- product_id: string (nullable = true)

I'm able to filter the Dataframe by product_id

select * from goodsInfo where array_contains(goods.product_id, 'f31ee3f8-9ba2-49cb-86e2-ceb44e34efd9')

But I'm unable to filter by brand_id which is an array within array..

I get the error when I try

select * from goodsInfo where array_contains(goods.brand_id, '45c060b9-3645-49ad-86eb-65f3cd4e9081')

Error:

function array_contains should have been array followed by a value with same element type, but it's [array<array<string>>, string].; line 1 pos 45;

Can someone please help ?

Thanks in advance

Body:
function array_contains should have been array followed by a value with same element type, but it's [array<array<string>>, string].; line 1 pos 45;

This is because brand_id is of type array<array<string>> & you are passing value is of type string, You have to wrap your value inside array i.e

array_contains(goods.brand_id, array('45c060b9-3645-49ad-86eb-65f3cd4e9081'))

Above will work only if we pass exact number of brand_id values i.e. array_contains(goods.brand_id, array('<should match same number of elements in brand_id>'))

Check below code.

scala> df.printSchema
root
 |-- goods: array (nullable = true)
 |    |-- element: struct (containsNull = true)
 |    |    |-- brand_id: array (nullable = true)
 |    |    |    |-- element: string (containsNull = true)
 |    |    |-- product_id: string (nullable = true)

scala> spark.sql("select * from goodsInfo").show(false)
+----------------------+
|goods                 |
+----------------------+
|[[[B100, B101], P100]]|
|[[[B200, B200], P200]]|
|[[[B300], P300]]      |
+----------------------+

scala> spark.sql("select * from goodsInfo where array_contains(goods.brand_id, array('B300'))").show(false) // Exact one element
+----------------+
|goods           |
+----------------+
|[[[B300], P300]]|
+----------------+

scala> spark.sql("select * from goodsInfo where array_contains(goods.brand_id, array('B100'))").show(false) // Passing single element from array. It will not give result.
+-----+
|goods|
+-----+
+-----+

scala> spark.sql("select * from goodsInfo where array_contains(goods.brand_id, array('B100','B101'))").show(false) // Pass complete array, It will give result.
+----------------------+
|goods                 |
+----------------------+
|[[[B100, B101], P100]]|
+----------------------+

Instead of array_contains try using LATERAL VIEW explode to explode nested array values, Check below query.

SELECT
 goods
,brand_id
FROM goodsInfo
LATERAL VIEW explode(goods.brand_id) brands as brands
LATERAL VIEW explode(brands) brand_id as brand_id
WHERE brand_id = '45c060b9-3645-49ad-86eb-65f3cd4e9081';