问:
divide a list of positive integers by the length of digits
I would like to divide a list of positive integers by the length of digits.

For example, int_list = [1,3,13,888,1004]
-> [1,3] , [13] , [888] , [1004]

I have implemented below:

def seperate_by_digit(int_list):
    len_set = set()  # track how many digits we have

    int_dict = {}  # key : len of digits  / val : list of integer
    for int_ele in int_list:
        n = len(str(int_ele))
        if n not in len_set:
            int_dict[n] = [int_ele]
            len_set.add(n)
        else:
            sub_int_list = int_dict[n]
            sub_int_list.append(int_ele)
            int_dict[n] = sub_int_list
    return int_dict
```

Is there any better, cleaner way to complete this task?

答:
You could use a defaultdict to manage the grouping and length of the string value to get the number of digits:</p>
```<code>from math import log
from collections import defaultdict

int_list = [1,3,13,888,1004]

int_dict = defaultdict(list)
for n in int_list:
    int_dict[len(str(n))].append(n)

print(*int_dict.values())
# [1, 3] [13] [888] [1004]
</code>```

Body:
I would like to divide a list of positive integers by the length of digits.

For example, int_list = [1,3,13,888,1004]
-> [1,3] , [13] , [888] , [1004]

I have implemented below:

def seperate_by_digit(int_list):
    len_set = set()  # track how many digits we have

    int_dict = {}  # key : len of digits  / val : list of integer
    for int_ele in int_list:
        n = len(str(int_ele))
        if n not in len_set:
            int_dict[n] = [int_ele]
            len_set.add(n)
        else:
            sub_int_list = int_dict[n]
            sub_int_list.append(int_ele)
            int_dict[n] = sub_int_list
    return int_dict

Is there any better, cleaner way to complete this task?

Body:
You could use a defaultdict to manage the grouping and length of the string value to get the number of digits:

from math import log
from collections import defaultdict

int_list = [1,3,13,888,1004]

int_dict = defaultdict(list)
for n in int_list:
    int_dict[len(str(n))].append(n)

print(*int_dict.values())
# [1, 3] [13] [888] [1004]


来源: stackexchange

问:
Splitting a list containing ; into another list
I Have the below list which looks like below.

```<code>List<Integer> exa = new ArrayList<Integer>();
exa.add("1234567;345676;57689687;906986985689");
</code>```

Desired Output:

```<code>List<Integer> newExa = new ArrayList<Integer>();
newExa.add("1234567");
newExa.add("345676");
newExa.add("57689687");
newExa.add("906986985689");
</code>```

Now I need to remove the ; and add the numbers to the new list.Can you please let me know how to proceed forward.

Thanks in advance

答:
You can use split(String regex) method of Java's String class for splitting operation and can use Integer.valueOf(String s) method for converting to integer.

However, your current code cannot be compiled successfully. You have one compiler and one runtime error:

The Compiler Error: You cannot add String to an Integer list.

The Runtime Error: The 906986985689 won't fit to the integer.

By the way, for splitting a String into an Integer list, you can use a code something like that:

```<code>ArrayList<Integer> list = new ArrayList<Integer>();
String s = "1234567;345676;57689687;906986985689"
String[] numbersArr = s.split(";")

for(String num : numbersArr){
    list.add(Integer.valueOf(s));
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I Have the below list which looks like below.

List<Integer> exa = new ArrayList<Integer>();
exa.add("1234567;345676;57689687;906986985689");

Desired Output:

List<Integer> newExa = new ArrayList<Integer>();
newExa.add("1234567");
newExa.add("345676");
newExa.add("57689687");
newExa.add("906986985689");

Now I need to remove the ; and add the numbers to the new list.Can you please let me know how to proceed forward.

Thanks in advance

Body:
You can use split(String regex) method of Java's String class for splitting operation and can use Integer.valueOf(String s) method for converting to integer.

However, your current code cannot be compiled successfully. You have one compiler and one runtime error:

The Compiler Error: You cannot add String to an Integer list.

The Runtime Error: The 906986985689 won't fit to the integer.

By the way, for splitting a String into an Integer list, you can use a code something like that:

ArrayList<Integer> list = new ArrayList<Integer>();
String s = "1234567;345676;57689687;906986985689"
String[] numbersArr = s.split(";")

for(String num : numbersArr){
    list.add(Integer.valueOf(s));
}


问:
Error nested std::thread inside a thread throws an error
I'm trying to get this simple test to create a nested thread inside another thread, but it keeps failing. Tried removing this nested function and the code works fine on its own.

Code example/test:

```<code>#include <thread>
#include <iostream>
#include <vector>

void simple() {  std::cout << "\nNested Thread";  }

void function(int number, int* sum, std::vector<std::thread>& thread_group) {
    *sum += number;

    // Starting this nested function simple() in a thread causes errors.
    // The problem occurs even when there's only a single iteration of the loop.
    // Without it the code works fine, even with 10000 iterations.
    std::thread ct(simple);
    thread_group.push_back(std::move(ct));
}

int main(){
    // Container for storing threads
    std::vector<std::thread> thread_group;
    int sum = 0;
    for (int n = 1; n <= 10; n++) {
        std::thread t(function, n, &sum, std::ref(r), std::ref(thread_group));
        // Add the newly created thread to the container
        thread_group.push_back(std::move(t));
    }
    // Wait for all threads to finish
    join_all(thread_group);
    return 0;
}
</code>```

That being said, I need to find a way call an independent function that could run without blocking the execution of the rest of the code. Threading or some other way of multiprocessing is very important in my program because each function is recursive and keeps calling multiple copies of itself with different parameters untill a condition is satisfied.

I don't know whether it's even possible in the std::thread library. Tried using Poco and boost, but was faced with other problems, so decided to stick to std::thread instead.

I'm using Visual Studio 2022 on Windows 10.

答:
You are reading and writing to sum and thread_group from multiple threads at the same time. A simple solution is you make sure that only one thread at a time has access to them by using a std::mutex and locking it while accessing those variables. You also need to make sure that all threads are finished working with thread_group before it gets destroyed. I added a counter and a std::condition_variable to take care of that.

Example (using C++20 std::jthreads instead to not have to call the non-existing join_all function):

```<code>#include <condition_variable>
#include <iostream>
#include <list>     // using list instead of vector to avoid realloc
#include <mutex>
#include <thread>
#include <vector>

using container = std::list<std::jthread>;

void simple() {  std::cout << "Nested Thread\n";  }

void function(int& counter, std::mutex& mtx,
              std::condition_variable& cv, container& thread_group)
{
    std::lock_guard lock(mtx);
    thread_group.emplace_back(simple);
    ++counter;       // so that main thread can check that all is done
    cv.notify_one(); // signal main that the work is done
}

int main(){
    // Container for storing threads
    container thread_group;
    std::mutex mtx;
    std::condition_variable cv;

    int starting_threads = 10;
    int counter = 0;
    for (int n = 1; n <= starting_threads; n++) {
        std::lock_guard lock(mtx); // lock while adding thread
        // Add thread to the container
        thread_group.emplace_back(function, std::ref(counter), std::ref(mtx),
                                  std::ref(cv), std::ref(thread_group));
    }

    std::unique_lock lock(mtx);
    // wait until all threads are done with thread_group
    // before letting thread_group go out of scope and get
    // destroyed
    while(counter < starting_threads) cv.wait(lock);

    std::cout << thread_group.size() << '\n';

    // wait for all threads to finish (jthread's auto-join)
}
</code>```

Possible output:

```<code>Nested Thread
Nested Thread
Nested Thread
Nested Thread
Nested Thread
Nested Thread
Nested Thread
Nested Thread
Nested Thread
20
Nested Thread
</code>```

Body:
I'm trying to get this simple test to create a nested thread inside another thread, but it keeps failing. Tried removing this nested function and the code works fine on its own.

Code example/test:

#include <thread>
#include <iostream>
#include <vector>

void simple() {  std::cout << "\nNested Thread";  }

void function(int number, int* sum, std::vector<std::thread>& thread_group) {
    *sum += number;

    // Starting this nested function simple() in a thread causes errors.
    // The problem occurs even when there's only a single iteration of the loop.
    // Without it the code works fine, even with 10000 iterations.
    std::thread ct(simple);
    thread_group.push_back(std::move(ct));
}

int main(){
    // Container for storing threads
    std::vector<std::thread> thread_group;
    int sum = 0;
    for (int n = 1; n <= 10; n++) {
        std::thread t(function, n, &sum, std::ref(r), std::ref(thread_group));
        // Add the newly created thread to the container
        thread_group.push_back(std::move(t));
    }
    // Wait for all threads to finish
    join_all(thread_group);
    return 0;
}

That being said, I need to find a way call an independent function that could run without blocking the execution of the rest of the code. Threading or some other way of multiprocessing is very important in my program because each function is recursive and keeps calling multiple copies of itself with different parameters untill a condition is satisfied.

I don't know whether it's even possible in the std::thread library. Tried using Poco and boost, but was faced with other problems, so decided to stick to std::thread instead.

I'm using Visual Studio 2022 on Windows 10.

Body:
You are reading and writing to sum and thread_group from multiple threads at the same time. A simple solution is you make sure that only one thread at a time has access to them by using a std::mutex and locking it while accessing those variables. You also need to make sure that all threads are finished working with thread_group before it gets destroyed. I added a counter and a std::condition_variable to take care of that.

Example (using C++20 std::jthreads instead to not have to call the non-existing join_all function):

#include <condition_variable>
#include <iostream>
#include <list>     // using list instead of vector to avoid realloc
#include <mutex>
#include <thread>
#include <vector>

using container = std::list<std::jthread>;

void simple() {  std::cout << "Nested Thread\n";  }

void function(int& counter, std::mutex& mtx,
              std::condition_variable& cv, container& thread_group)
{
    std::lock_guard lock(mtx);
    thread_group.emplace_back(simple);
    ++counter;       // so that main thread can check that all is done
    cv.notify_one(); // signal main that the work is done
}

int main(){
    // Container for storing threads
    container thread_group;
    std::mutex mtx;
    std::condition_variable cv;

    int starting_threads = 10;
    int counter = 0;
    for (int n = 1; n <= starting_threads; n++) {
        std::lock_guard lock(mtx); // lock while adding thread
        // Add thread to the container
        thread_group.emplace_back(function, std::ref(counter), std::ref(mtx),
                                  std::ref(cv), std::ref(thread_group));
    }

    std::unique_lock lock(mtx);
    // wait until all threads are done with thread_group
    // before letting thread_group go out of scope and get
    // destroyed
    while(counter < starting_threads) cv.wait(lock);

    std::cout << thread_group.size() << '\n';

    // wait for all threads to finish (jthread's auto-join)
}

Possible output:

Nested Thread
Nested Thread
Nested Thread
Nested Thread
Nested Thread
Nested Thread
Nested Thread
Nested Thread
Nested Thread
20
Nested Thread


问:
Auth0: Invalid access token payload, JWT encrypted with A256GCM algorithm
I'm trying to set up a Vue3 SPA with a NestJS API in the back. I set up my Auth0 tenant and client to integrate with the SPA and plan to send the resulting JWTs to my API. In my SPA, I use the vue-auth0-plugin, which uses @auth0/auth0-spa-js under the hood.

I have successfully set up the Auth Code with PKCE flow, up to the point where I receive id, access and refresh tokens. However, something is wrong with the access token and I cannot understand why it is happening. The payload is invalid JSON and the token contains 2 consecutive .. When I paste the token into jwt.io, the header is decoded as follows:

{
  "alg": "dir",
  "enc": "A256GCM",
  "iss": "https://xyz.auth0.com/"
}
```
<p>I would be expecting:</p>
<pre class="lang-json prettyprint-override"><code>{
  "alg": "RS256",
  "typ": "JWT",
  "kid": "w1-e..."
}
</code>```

I have not enabled JWT encryption as far as I know (I used the wizard to set up the SPA client), could anyone point out to me what I am missing? For the sake of completeness, this is the format of my auth request:

```<code>https://xyz.auth0.com/authorize
    ?client_id=REq...
    &redirect_uri=http%3A%2F%2Flocalhost%3A1337
    &scope=openid%20profile%20email
    &response_type=code
    &response_mode=query
    &state=a2...
    &nonce=bT...
    &code_challenge=GjSw...
    &code_challenge_method=S256
    &auth0Client=eyJu...
</code>```

Many thanks in advance.

答: As Gary said, the token is in JWE format. According to this Auth0 community post, the solution to the missing payload is to provide an audience parameter. You should be able to include that parameter in the query string to the /authorize endpoint.

Body:
I'm trying to set up a Vue3 SPA with a NestJS API in the back. I set up my Auth0 tenant and client to integrate with the SPA and plan to send the resulting JWTs to my API. In my SPA, I use the vue-auth0-plugin, which uses @auth0/auth0-spa-js under the hood.

I have successfully set up the Auth Code with PKCE flow, up to the point where I receive id, access and refresh tokens. However, something is wrong with the access token and I cannot understand why it is happening. The payload is invalid JSON and the token contains 2 consecutive .. When I paste the token into jwt.io, the header is decoded as follows:

{
  "alg": "dir",
  "enc": "A256GCM",
  "iss": "https://xyz.auth0.com/"
}

I would be expecting:

{
  "alg": "RS256",
  "typ": "JWT",
  "kid": "w1-e..."
}

I have not enabled JWT encryption as far as I know (I used the wizard to set up the SPA client), could anyone point out to me what I am missing? For the sake of completeness, this is the format of my auth request:

https://xyz.auth0.com/authorize
    ?client_id=REq...
    &redirect_uri=http%3A%2F%2Flocalhost%3A1337
    &scope=openid%20profile%20email
    &response_type=code
    &response_mode=query
    &state=a2...
    &nonce=bT...
    &code_challenge=GjSw...
    &code_challenge_method=S256
    &auth0Client=eyJu...

Many thanks in advance.


问:
Python: Unable to move between loops correctly
I'm writing an image detection bot and as per the advice from a few members, I refactored some code and separated this section into its own function objectDetection I'm trying to do two things with the array image_list

Iterate through the array and if any image is detected I want to immediately print "Avoided" to the terminal and restart the objectDetection function from the beginning of the array.

I've tried to do this with the flag variable found_anything = True and break it hasn't worked.

Iterate through the full array of images and if nothing at all is found, execute functionTwo()

I tried to do this with the break at the end of my for i in image_list: loop, it also hasn't worked.

So far I've tried....

Reading through these three pages: Break out of two loops and two if statements - Python break out of two loops without disturbing the if statements after it in python Accessing the index in 'for' loops? and I tried both the variable flags and break statements but I can't get either to work.

I also had a look at this: How to break out of multiple loops? but what is the difference between return and break in python? made me think in my case the top answer wouldn't be appropriate as I don't think I'm returning data outside of my function.

Is there a way I can adapt this code to achieve my two uses cases above? Am I missing something obvious? I've been thought all the loop tutorials I can find and I'm still struggling, is this simply a difficult way I'm trying to design things? Or am I simply not getting it and should go back over some tutorials.

```<code>def objectDetection(image_list, threshold, haystack, a):
    for x in range (0, a):

        found_anything = False
        while found_anything is False:

            for i in image_list:
                needle_img = i[0]
                result = cv.matchTemplate(haystack, needle_img, cv.TM_CCORR_NORMED)

                # Get the best match position
                min_val, max_val, min_loc, max_loc = cv.minMaxLoc(result)

                # Define top left and bottom right and threshold
                (H, W) = i[0].shape[:2]
                top_left = max_loc
                bottom_right = (top_left[0] + W, top_left[1] + H)

                if max_val >= threshold:
                    cv.rectangle(haystack, top_left, bottom_right, 255, 2)
                    print("Avoided")
                    found_anything = True
                    break
            break
            functionTwo()

while True:

    # Listener to check if on the correct screen
    if py.locateCenterOnScreen('!.jpg') != None:
        objectDetection(ships_to_avoid, 0.92, window, 10)
        break
</code>```

答:
I'd refactor the whole thing but something like this answers the main question:  Refactor your functions such that you can use 'Return' instead of 'Break'</p>
```<code>def objectDetection(image_list, threshold, haystack, a):
    for i in image_list:

        max_val, top_left = find_needle_in_haystack(haystack, i[0])

        if max_val >= threshold:
            draw_rectangle(i,top_left,haystack)
            print("Avoided")
            return True

    return False

while True:
    if py.locateCenterOnScreen('!.jpg') != None:
        if not objectDetection(ships_to_avoid, 0.92, window, 10):
            function_two()
</code>```

Body:
I'm writing an image detection bot and as per the advice from a few members, I refactored some code and separated this section into its own function objectDetection I'm trying to do two things with the array image_list

Iterate through the array and if any image is detected I want to immediately print "Avoided" to the terminal and restart the objectDetection function from the beginning of the array.

I've tried to do this with the flag variable found_anything = True and break it hasn't worked.

Iterate through the full array of images and if nothing at all is found, execute functionTwo()

I tried to do this with the break at the end of my for i in image_list: loop, it also hasn't worked.

So far I've tried....

Reading through these three pages: Break out of two loops and two if statements - Python break out of two loops without disturbing the if statements after it in python Accessing the index in 'for' loops? and I tried both the variable flags and break statements but I can't get either to work.

I also had a look at this: How to break out of multiple loops? but what is the difference between return and break in python? made me think in my case the top answer wouldn't be appropriate as I don't think I'm returning data outside of my function.

Is there a way I can adapt this code to achieve my two uses cases above? Am I missing something obvious? I've been thought all the loop tutorials I can find and I'm still struggling, is this simply a difficult way I'm trying to design things? Or am I simply not getting it and should go back over some tutorials.

def objectDetection(image_list, threshold, haystack, a):
    for x in range (0, a):

        found_anything = False
        while found_anything is False:

            for i in image_list:
                needle_img = i[0]
                result = cv.matchTemplate(haystack, needle_img, cv.TM_CCORR_NORMED)

                # Get the best match position
                min_val, max_val, min_loc, max_loc = cv.minMaxLoc(result)

                # Define top left and bottom right and threshold
                (H, W) = i[0].shape[:2]
                top_left = max_loc
                bottom_right = (top_left[0] + W, top_left[1] + H)

                if max_val >= threshold:
                    cv.rectangle(haystack, top_left, bottom_right, 255, 2)
                    print("Avoided")
                    found_anything = True
                    break
            break
            functionTwo()

while True:

    # Listener to check if on the correct screen
    if py.locateCenterOnScreen('!.jpg') != None:
        objectDetection(ships_to_avoid, 0.92, window, 10)
        break

Body:
I'd refactor the whole thing but something like this answers the main question:  Refactor your functions such that you can use 'Return' instead of 'Break'

def objectDetection(image_list, threshold, haystack, a):
    for i in image_list:

        max_val, top_left = find_needle_in_haystack(haystack, i[0])

        if max_val >= threshold:
            draw_rectangle(i,top_left,haystack)
            print("Avoided")
            return True

    return False

while True:
    if py.locateCenterOnScreen('!.jpg') != None:
        if not objectDetection(ships_to_avoid, 0.92, window, 10):
            function_two()


问:
Is it possible to send a ping opcode using javascript Websocket?
I have a websocket client and I want it to send a ping frame to my WS server.
According to the RFC 6455  a ping frame is represented by opcode %x9 but I don't know if it's even possible to send from a browser.

Any help will be appreciated

答:
Building on-top of the comments in your original post, you can manually send pings via websocket.

The link by Daniel W. of the ws library has a ping() method which can be called from a valid websocket client. See an example here.

If you have written your own websocket library then you must conform to the standard framing outlined in RFC6455 The Websocket Protocol.

You should be able to pack a buffer with the correct header and control opcode and send it over the upgraded HTTP1.1 TCP connection.

Edit:

Further research shows, at the point of writing, the Ping method is not supported via the native Websocket Client and the send method seems to only support payloads and not command messages, which include opcodes for commands such as ping.

An option could be to go with a WASM based solution which could make non-XHR or non-fetch based TCP connections, however this comes with a whole different set of challenges.


问:
How to identify labels on a Python Tkinter Tab in the event handler
I am placing labels on a Tab in Tkinter with a for loop. How can I identify in the event handler which label was clicked (or its loop index)? I guess it is functionally similar to a ListBox but without the formatting restrictions. I might want to put the labels in a circle or place them diagonally. I tried finding the coordinates of the label but these are available only if the tab is the first one visible or the tab is redrawn when made active. Also the x, y passed in the event handler is the x, y within the label which does not help to identify the label.

I could copy the label code about 10 times and and have about 10 event handlers. This would work but this is no longer 1970!

Perhaps I could bind a handler to the tab canvas and identify the label from its coordinates. The label would need to be on the first tab or the tab drawn when active.

Perhaps I could create a different event handler for each label by holding the event handlers in an array. I would need an event handler for each label. The code would need to change if the number of labels changed.

I am currently trying a label with ''. Would using buttons with command be easier?

What simple part of Python am I missing? I cannot be the first person to need this! Any help or advice would be appreciated.

答:
When you bind events, the function receives an object that includes a reference to the widget that received the event. In the following example, notice how it uses event.widget to refer to the widget that was clicked on.

```<code>import tkinter as tk

def update_label(event):
    event.widget.configure(text="You clicked me")

root = tk.Tk()

for i in range(10):
    l = tk.Label(root, text="Click me", width=20)
    l.pack()
    l.bind("<1>", update_label)

root.mainloop()
</code>```

Body:
When you bind events, the function receives an object that includes a reference to the widget that received the event. In the following example, notice how it uses event.widget to refer to the widget that was clicked on.

import tkinter as tk

def update_label(event):
    event.widget.configure(text="You clicked me")

root = tk.Tk()

for i in range(10):
    l = tk.Label(root, text="Click me", width=20)
    l.pack()
    l.bind("<1>", update_label)

root.mainloop()


问:
Using Grpc in Laravel, Docker, Undefined type 'Grpc\ChannelCredentials'
After setting everything up to use grpc,
my composer.json:

```<code>require: {
    ...
    "grpc/grpc": "^1.34",
    "spiral/php-grpc": "^1.4",
    "spiral/roadrunner": "^1.9",
    ...
}
</code>```

I create new client:

```<code>...
$client = new ExampleClient('localhost:9090',[
    'credentials' => \Grpc\ChannelCredentials::createInsecure(),
]);
...
</code>```

in Docker, i enabled grpc, protobuf:

```<code>docker-php-ext-enable grpc
docker-php-ext-enable protobuf
</code>```

i checked grpc and protobuf in docker enviroment, output:

```<code>/usr/local/etc/php/conf.d/docker-php-ext-grpc.ini,
/usr/local/etc/php/conf.d/docker-php-ext-protobuf.ini,
grpc
grpc support => enabled
grpc module version => 1.43.0
grpc.enable_fork_support => 0 => 0
grpc.grpc_trace => no value => no value
grpc.grpc_verbosity => no value => no value
grpc.log_filename => no value => no value
grpc.poll_strategy => no value => no value
protobuf
protobuf.keep_descriptor_pool_after_request => 0 => 0
</code>```

but Grpc\ChannelCredentials not found

Thank for your support !

答: Grpc\ChannelCredentials is added through the grpc extension (grpc.so), so you won't find the file for it.

Body:
After setting everything up to use grpc,
my composer.json:

require: {
    ...
    "grpc/grpc": "^1.34",
    "spiral/php-grpc": "^1.4",
    "spiral/roadrunner": "^1.9",
    ...
}

I create new client:

...
$client = new ExampleClient('localhost:9090',[
    'credentials' => \Grpc\ChannelCredentials::createInsecure(),
]);
...

in Docker, i enabled grpc, protobuf:

docker-php-ext-enable grpc
docker-php-ext-enable protobuf

i checked grpc and protobuf in docker enviroment, output:

/usr/local/etc/php/conf.d/docker-php-ext-grpc.ini,
/usr/local/etc/php/conf.d/docker-php-ext-protobuf.ini,
grpc
grpc support => enabled
grpc module version => 1.43.0
grpc.enable_fork_support => 0 => 0
grpc.grpc_trace => no value => no value
grpc.grpc_verbosity => no value => no value
grpc.log_filename => no value => no value
grpc.poll_strategy => no value => no value
protobuf
protobuf.keep_descriptor_pool_after_request => 0 => 0

but Grpc\ChannelCredentials not found

Thank for your support !


问:
Why is my django code for POST Method not working?
I am working on a django website and I am trying to receive data from the user through POST Method. The error message is :

```<code>MultiValueDictKeyError at /prediction/
'date1'
Request Method: GET
</code>```

Why is the request Method still GET even though I have POST in my views.py?

Views.py :

```<code>from django.shortcuts import render
from apple.models import predictions

# Create your views here.

def home_view(request):

    pre = predictions.objects.filter(date='2021-01-15')
    return render(request, 'homepage.html', {'prediction': pre})

def read(request):

    final_date = str(request.POST["date1"])
    price = predictions.objects.filter(date=final_date)

    return render(request, 'results.html', {'price':price})
</code>```

This is my 2nd HTML page Results.html :

```<code><!DOCTYPE html>
<html>

<head>
    <link href='https://fonts.googleapis.com/css?family=Pacifico' rel='stylesheet' type='text/css'>
    <link href='https://fonts.googleapis.com/css?family=Arimo' rel='stylesheet' type='text/css'>
    <link href='https://fonts.googleapis.com/css?family=Hind:300' rel='stylesheet' type='text/css'>
    <link href='https://fonts.googleapis.com/css?family=Open+Sans+Condensed:300' rel='stylesheet' type='text/css'>

    <title>Prediction Page</title>
</head>

<body>
    <h1>"The Predicted price for this date is:" +
        "{{price}}"</h1>
</body>

</html>

<style>
    @import url(https://fonts.googleapis.com/css?family=Open+Sans);

    html {
        width: 100%;
        height: 100%;
        overflow: hidden;
    }

    body {
        width: 100%;
        height: 100%;
        font-family: 'Open Sans', sans-serif;
        background: #331952;
        color: #fff;
        font-size: 18px;
        text-align: center;
        letter-spacing: 1.2px;

    }
</style>
</code>```

This is the main HTML Page  - homepage.html ( from where 'date1' is coming from ) :

```<code><!DOCTYPE html>
<html>

<head>
    <link href='https://fonts.googleapis.com/css?family=Pacifico' rel='stylesheet' type='text/css'>
    <link href='https://fonts.googleapis.com/css?family=Arimo' rel='stylesheet' type='text/css'>
    <link href='https://fonts.googleapis.com/css?family=Hind:300' rel='stylesheet' type='text/css'>
    <link href='https://fonts.googleapis.com/css?family=Open+Sans+Condensed:300' rel='stylesheet' type='text/css'>

    <title>Apple Stock Price Predictor</title>
</head>

<body>
    <div class="login">
        <h1>Predict Apple Stock Prices for Tomorrow</h1>
        <h3>Enter the date for tomorrow to predict the Apple Stock Price for tomorrow</h3>

        <form action="read" method="post">
            {% csrf_token %}

            <input type="text" name="date1" placeholder="Tomorrow's Date" id="form-submit" />

            <input type="button" id="button-submit" value="Predict"></input>
        </form>

        <br>
        <br>
        <h3 id = "output"></h3>
    </div>
</body>

</html>

<style>
    @import url(https://fonts.googleapis.com/css?family=Open+Sans);

    #button-submit {
        background-color: #ba0b0b;
        border: none;
        text-align: center;
        border-radius: 8px;
        padding: 14px 40px;
        text-decoration: none;
        display: inline-block;
        font-size: 20px;
        margin: 4px 2px;
        cursor: pointer;
    }

    #button-submit:hover {
        background-color: #770e0e;
        box-shadow: 0 12px 16px 0 rgba(0, 0, 0, 0.24), 0 17px 50px 0 rgba(0, 0, 0, 0.19);
    }

    * {
        -webkit-box-sizing: border-box;
        -moz-box-sizing: border-box;
        -ms-box-sizing: border-box;
        -o-box-sizing: border-box;
        box-sizing: border-box;
    }

    html {
        width: 100%;
        height: 100%;
        overflow: hidden;
    }

    body {
        width: 100%;
        height: 100%;
        font-family: 'Open Sans', sans-serif;
        background: #331952;
        color: #fff;
        font-size: 18px;
        text-align: center;
        letter-spacing: 1.2px;

    }

    .login {
        position: absolute;
        top: 40%;
        left: 50%;
        margin: -150px 0 0 -150px;
        width: 450px;
        height: 400px;
    }

    .login h1 {
        color: #fff;
        text-shadow: 0 0 10px rgba(0, 0, 0, 0.3);
        letter-spacing: 1px;
        text-align: center;
    }

    input {
        width: 100%;
        margin-bottom: 10px;
        background: rgba(134, 56, 56, 0.3);
        border: none;
        outline: none;
        padding: 10px;
        font-size: 13px;
        color: #fff;
        text-shadow: 1px 1px 1px rgba(0, 0, 0, 0.3);
        border: 1px solid rgba(0, 0, 0, 0.3);
        border-radius: 4px;
        box-shadow: inset 0 -5px 45px rgba(100, 100, 100, 0.2), 0 1px 1px rgba(255, 255, 255, 0.2);
        -webkit-transition: box-shadow .5s ease;
        -moz-transition: box-shadow .5s ease;
        -o-transition: box-shadow .5s ease;
        -ms-transition: box-shadow .5s ease;
        transition: box-shadow .5s ease;
    }

    input:focus {
        box-shadow: inset 0 -5px 45px rgba(100, 100, 100, 0.4), 0 1px 1px rgba(255, 255, 255, 0.2);
    }
</style>
</code>```

答:
have you tried to put the view method in a class view ?

```<code>from django.shortcuts import render
from django.views.generic import View

class LoginView(View):
    def post(self, request):

        final_date = str(request.POST["date1"])
        price = predictions.objects.filter(date=final_date)

        return render(request, 'results.html', {'price':price})
</code>```

and use in urlpatterns

from .views  import LoginView

urlpatterns += [
    path("/prediction/", LoginView.as_view())
]
```

Body:
I am working on a django website and I am trying to receive data from the user through POST Method. The error message is :

MultiValueDictKeyError at /prediction/
'date1'
Request Method: GET

Why is the request Method still GET even though I have POST in my views.py?

Views.py :

from django.shortcuts import render
from apple.models import predictions

# Create your views here.

def home_view(request):

    pre = predictions.objects.filter(date='2021-01-15')
    return render(request, 'homepage.html', {'prediction': pre})

def read(request):

    final_date = str(request.POST["date1"])
    price = predictions.objects.filter(date=final_date)

    return render(request, 'results.html', {'price':price})

This is my 2nd HTML page Results.html :

<!DOCTYPE html>

    <link href='https://fonts.googleapis.com/css?family=Pacifico' rel='stylesheet' type='text/css'>
    <link href='https://fonts.googleapis.com/css?family=Arimo' rel='stylesheet' type='text/css'>
    <link href='https://fonts.googleapis.com/css?family=Hind:300' rel='stylesheet' type='text/css'>
    <link href='https://fonts.googleapis.com/css?family=Open+Sans+Condensed:300' rel='stylesheet' type='text/css'>

    <title>Prediction Page</title>

"The Predicted price for this date is:" +
        "{{price}}"

This is the main HTML Page  - homepage.html ( from where 'date1' is coming from ) :

<!DOCTYPE html>

    <link href='https://fonts.googleapis.com/css?family=Pacifico' rel='stylesheet' type='text/css'>
    <link href='https://fonts.googleapis.com/css?family=Arimo' rel='stylesheet' type='text/css'>
    <link href='https://fonts.googleapis.com/css?family=Hind:300' rel='stylesheet' type='text/css'>
    <link href='https://fonts.googleapis.com/css?family=Open+Sans+Condensed:300' rel='stylesheet' type='text/css'>

    <title>Apple Stock Price Predictor</title>

Predict Apple Stock Prices for Tomorrow

Enter the date for tomorrow to predict the Apple Stock Price for tomorrow

        <form action="read" method="post">
            {% csrf_token %}

            <input type="text" name="date1" placeholder="Tomorrow's Date" id="form-submit" />

            <input type="button" id="button-submit" value="Predict"></input>
        </form>

Body:
have you tried to put the view method in a class view ?

from django.shortcuts import render
from django.views.generic import View

class LoginView(View):
    def post(self, request):

        final_date = str(request.POST["date1"])
        price = predictions.objects.filter(date=final_date)

        return render(request, 'results.html', {'price':price})

and use in urlpatterns

from .views  import LoginView

urlpatterns += [
    path("/prediction/", LoginView.as_view())
]


问:
in Azure DevOps, where are the stages of a pipeline actually run?
I'm coming to Azure DevOps from my experience with Jenkins, where it was clear that the code in the pipelines being run is actually run on the Jenkins server (whatever machine is hosting that).  So I assumed that Azure DevOps pipelines were running somehow somewhere on https://dev.azure.com/.  Maybe this is true, maybe it isn't.  Maybe it depends on how the "environment" is set up and what resources are in that environment.  My multi-stage pipeline looks like this:

# ASP.NET
# Build and test ASP.NET projects.
# Add steps that publish symbols, save build artifacts, deploy, and more:
# https://learn.microsoft.com/azure/devops/pipelines/apps/aspnet/build-aspnet-4

trigger:
- master

pool:
  vmImage: 'windows-latest'

variables:
  solution: '**/*.sln'
  buildPlatform: 'Any CPU'
  buildConfiguration: 'Release'

stages:
- stage: build
  displayName: Build
  jobs:
  - job: Build

    steps:

    - checkout: self

    #without this first one, bad things happen!!
    - task: NuGetCommand@2
      inputs:
        command: 'restore'
        restoreSolution: '**/*.sln'
        feedsToUse: 'config'
        nugetConfigPath: 'NuGet.config'

    - task: NuGetToolInstaller@1

    - task: VSBuild@1
      inputs:
        solution: '$(solution)'
        msbuildArgs: '/p:DeployOnBuild=true /p:WebPublishMethod=Package /p:PackageAsSingleFile=true /p:SkipInvalidConfigurations=true /p:PackageLocation="$(build.artifactStagingDirectory)"'
        platform: '$(buildPlatform)'
        configuration: '$(buildConfiguration)'

    - task: VSTest@2
      inputs:
        platform: '$(buildPlatform)'
        configuration: '$(buildConfiguration)'

    - task: PublishBuildArtifacts@1
      inputs:
        PathtoPublish: '$(Build.ArtifactStagingDirectory)'
        ArtifactName: 'drop'
        publishLocation: 'Container'

- stage: Release
  displayName: Release
  condition: and(succeeded(), eq(variables['build.sourceBranch'], 'refs/heads/master'))
  jobs:

  - deployment:
    displayName: Release
    environment:
        name: QA
        resourceType: VirtualMachine
    strategy:
      runOnce:
        deploy:
          steps:
          - task: CopyFiles@2
            inputs:
              SourceFolder: '$(Agent.WorkFolder)\1\drop'
              Contents: '**\*.zip'
              OverWrite: true
              TargetFolder: 'C:\QA\XXX\YYY'```

I know that 'C:\QA\XXX\YYY' is on the server I am deploying to (a resource in the QA Azure DevOps environment).  But where are these locations?

$(Build.ArtifactStagingDirectory)

$(Agent.WorkFolder)

Some of these have "D:" in their path, and yet there is no D: on the server I am deploying to.  Microsoft's documentation never really seems to address this issue, and yet understanding it would seem to be essential to anyone trying to get up to speed with Azure DevOps.

答:
```<code>pool:
   vmImage: 'windows-latest'
</code>```

That's the pool you're specifying where your jobs should run.

Your deployment job is using the runOnce strategy, which is telling it to run that deployment job a single time on the windows-latest agent pool. If you want to run a job across machines within an environment, you need to use an appropriate deployment strategy, such as rolling or canary.

Body:
I'm coming to Azure DevOps from my experience with Jenkins, where it was clear that the code in the pipelines being run is actually run on the Jenkins server (whatever machine is hosting that).  So I assumed that Azure DevOps pipelines were running somehow somewhere on https://dev.azure.com/.  Maybe this is true, maybe it isn't.  Maybe it depends on how the "environment" is set up and what resources are in that environment.  My multi-stage pipeline looks like this:

# ASP.NET
# Build and test ASP.NET projects.
# Add steps that publish symbols, save build artifacts, deploy, and more:
# https://learn.microsoft.com/azure/devops/pipelines/apps/aspnet/build-aspnet-4

trigger:
- master

pool:
  vmImage: 'windows-latest'

variables:
  solution: '**/*.sln'
  buildPlatform: 'Any CPU'
  buildConfiguration: 'Release'

stages:
- stage: build
  displayName: Build
  jobs:
  - job: Build

    steps:

    - checkout: self

    #without this first one, bad things happen!!
    - task: NuGetCommand@2
      inputs:
        command: 'restore'
        restoreSolution: '**/*.sln'
        feedsToUse: 'config'
        nugetConfigPath: 'NuGet.config'

    - task: NuGetToolInstaller@1

    - task: VSBuild@1
      inputs:
        solution: '$(solution)'
        msbuildArgs: '/p:DeployOnBuild=true /p:WebPublishMethod=Package /p:PackageAsSingleFile=true /p:SkipInvalidConfigurations=true /p:PackageLocation="$(build.artifactStagingDirectory)"'
        platform: '$(buildPlatform)'
        configuration: '$(buildConfiguration)'

    - task: VSTest@2
      inputs:
        platform: '$(buildPlatform)'
        configuration: '$(buildConfiguration)'

    - task: PublishBuildArtifacts@1
      inputs:
        PathtoPublish: '$(Build.ArtifactStagingDirectory)'
        ArtifactName: 'drop'
        publishLocation: 'Container'

- stage: Release
  displayName: Release
  condition: and(succeeded(), eq(variables['build.sourceBranch'], 'refs/heads/master'))
  jobs:

  - deployment:
    displayName: Release
    environment:
        name: QA
        resourceType: VirtualMachine
    strategy:
      runOnce:
        deploy:
          steps:
          - task: CopyFiles@2
            inputs:
              SourceFolder: '$(Agent.WorkFolder)\1\drop'
              Contents: '**\*.zip'
              OverWrite: true
              TargetFolder: 'C:\QA\XXX\YYY'

I know that 'C:\QA\XXX\YYY' is on the server I am deploying to (a resource in the QA Azure DevOps environment).  But where are these locations?

$(Build.ArtifactStagingDirectory)

$(Agent.WorkFolder)

Some of these have "D:" in their path, and yet there is no D: on the server I am deploying to.  Microsoft's documentation never really seems to address this issue, and yet understanding it would seem to be essential to anyone trying to get up to speed with Azure DevOps.

Body:
pool:
   vmImage: 'windows-latest'

That's the pool you're specifying where your jobs should run.

Your deployment job is using the runOnce strategy, which is telling it to run that deployment job a single time on the windows-latest agent pool. If you want to run a job across machines within an environment, you need to use an appropriate deployment strategy, such as rolling or canary.


问:
Referencing Other Environment Variables in Systemd
Is is possible to reference other environment variables when setting new ones in systemd?

```<code>[Service]
EnvironmentFile=/etc/environment
Environment=HOSTNAME=$COREOS_PRIVATE_IPV4
Environment=IP=$COREOS_PRIVATE_IPV4
Environment=FELIX_FELIXHOSTNAME=$COREOS_PRIVATE_IPV4
</code>```

The above code does not seem to be working.

答:
In my case, the only way that worked to load the system environment variables into systemd script was to load them inside the script itself, like described here:

https://unix.stackexchange.com/questions/146995/inherit-environment-variables-in-systemd-docker-container

# Import our environment variables from systemd
for e in $(tr "\000" "\n" < /proc/1/environ); do
        eval "export $e"
done
```

ContentLicense: CC BY-SA 3.0

Body:
Is is possible to reference other environment variables when setting new ones in systemd?

[Service]
EnvironmentFile=/etc/environment
Environment=HOSTNAME=$COREOS_PRIVATE_IPV4
Environment=IP=$COREOS_PRIVATE_IPV4
Environment=FELIX_FELIXHOSTNAME=$COREOS_PRIVATE_IPV4

The above code does not seem to be working.


问:
Compress RSA Encoded value in java
I am having a java class in which RSA Encryption is performed for the passed String value. getting encoded value as lengthy.

Input String: justin

RSA Encoded value as output: .eJwdy00OwiAQBtC7zFqS4Ufg8zLNUIaGDZjaxoXx7ja-_fvQc751X3qlB2Wp4kKCU47BZy4A7pa9uuitqNKN5t63PuToY1vO87-wri02gSlSiwloMKhcDZxoSClDAl-zj9exjHkFy0zfH5pUI3w.YfvMdQ.GcmMQuY3BN33JATAfFB3ZyeXO8U

RSA Encryption Code:

```<code>String username="justin";
String encrypteduser=getEncryptedPassword(username);
System.out.println("encrypteduser! " + encrypteduser);
public String getEncryptedPassword(String plainTextPassword)
    {
        String result="";

        try {
            result= getEncryptedPasswd(plainTextPassword);
            log.info("result:   " + result);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return result;
    }

 protected String getEncryptedPasswd(String plain) throws Exception {
            try {
                InputStream is = new ByteArrayInputStream(getCertificate().getBytes());
                CertificateFactory cf = CertificateFactory.getInstance("X.509");
                X509Certificate cert = (X509Certificate) cf.generateCertificate(is);

                PublicKey pubKey = cert.getPublicKey();
                Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
                cipher.init(Cipher.ENCRYPT_MODE, pubKey);

                byte cipherBytes[] = cipher.doFinal(plain.getBytes());
                String encrypted = Base64.getEncoder().encodeToString(cipherBytes);
                return encrypted;
            } catch (Exception ex) {
                ex.printStackTrace();
                return null;
            }
        }

        private String getCertificate() {

        String certStr = "-----BEGIN CERTIFICATE-----\n"
                + "MIIGgDCCBWigAwIBAgIKMvrulAAAAARG5DANBgkqhkiG9w0BAQsFADBbMRMwEQYK"
                + "CZImiZPyLGQBGRYDbmV0MRkwFwYKCZIm"
                + "-----END CERTIFICATE-----";

        return certStr;
    }
</code>```

and my goal here is that wanna compress RSA Encoded value into shorten one.

I hope after conversion(RSA to UTF-8) will get some shortened value.

Note: looking for some compression to the Encoded value if UTF-8 conversion not helps.

Is there any way to achieve this in java 8?

答:
Your cipher text appears to be already UTF-8–encoded. It's base-64–encoded; base-64 uses only US-ASCII characters, and US-ASCII encoding is a subset of UTF-8 encoding.

I believe you are not asking for what you want. Do you want shorter cipher text? If so, UTF-8 has nothing to do with that.

RSA cipher text has a length equal to the modulus of the RSA key. (This also imposes an upper bound on the plain text length.) The key size is chosen according to security requirements. Nowadays 3072 bits or maybe 2048 bits is typical. With those key lengths, the shortest text encoding generally supported is 512 or 342 characters, respectively. (There are some less common binary-to-text encodings that could get it down to 480 or 320 characters, respectively, but they will cause problems in URLs and other contexts because they use more symbols.)

If you want a shorter cipher text, use a different encryption algorithm. For public key cryptography, elliptic curve algorithms give the same level of security with shorter keys (as far as we know, anyway). This means your plain text and cipher text will be shorter. Or, perhaps a symmetric algorithm might work in your scheme. Depending on the mode, these can output cipher text the same length as the plain text (although that leaks information about the plain text and might compromise security).

Cryptographic operations result in strings bytes that can have any value in any sequence. I'm not aware of any single-byte character encodings that map every value to a character, and there isn't a multi-byte character encoding that maps every byte sequence to a character. Taking these facts together, you'll always require something like base-64 encoding to convert your cipher text to actual characters. So your text will be 33% longer on average.

Title: Compress RSA Encoded value in java

Body:
I am having a java class in which RSA Encryption is performed for the passed String value. getting encoded value as lengthy.

Input String: justin

RSA Encoded value as output: .eJwdy00OwiAQBtC7zFqS4Ufg8zLNUIaGDZjaxoXx7ja-_fvQc751X3qlB2Wp4kKCU47BZy4A7pa9uuitqNKN5t63PuToY1vO87-wri02gSlSiwloMKhcDZxoSClDAl-zj9exjHkFy0zfH5pUI3w.YfvMdQ.GcmMQuY3BN33JATAfFB3ZyeXO8U

RSA Encryption Code:

String username="justin";
String encrypteduser=getEncryptedPassword(username);
System.out.println("encrypteduser! " + encrypteduser);
public String getEncryptedPassword(String plainTextPassword)
    {
        String result="";

        try {
            result= getEncryptedPasswd(plainTextPassword);
            log.info("result:   " + result);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return result;
    }

 protected String getEncryptedPasswd(String plain) throws Exception {
            try {
                InputStream is = new ByteArrayInputStream(getCertificate().getBytes());
                CertificateFactory cf = CertificateFactory.getInstance("X.509");
                X509Certificate cert = (X509Certificate) cf.generateCertificate(is);

                PublicKey pubKey = cert.getPublicKey();
                Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
                cipher.init(Cipher.ENCRYPT_MODE, pubKey);

                byte cipherBytes[] = cipher.doFinal(plain.getBytes());
                String encrypted = Base64.getEncoder().encodeToString(cipherBytes);
                return encrypted;
            } catch (Exception ex) {
                ex.printStackTrace();
                return null;
            }
        }

        private String getCertificate() {

        String certStr = "-----BEGIN CERTIFICATE-----\n"
                + "MIIGgDCCBWigAwIBAgIKMvrulAAAAARG5DANBgkqhkiG9w0BAQsFADBbMRMwEQYK"
                + "CZImiZPyLGQBGRYDbmV0MRkwFwYKCZIm"
                + "-----END CERTIFICATE-----";

        return certStr;
    }

and my goal here is that wanna compress RSA Encoded value into shorten one.

I hope after conversion(RSA to UTF-8) will get some shortened value.

Note: looking for some compression to the Encoded value if UTF-8 conversion not helps.

Is there any way to achieve this in java 8?


问:
Using ifelse() statements to get objects of different classes in R
I want to know how to use ifelse() statements to get different kinds of objects in R.

Specifically, I want to do this with the mtcars data, which is a list type object. I used the code below to create a character object version of the name of the data, called mtcars__string_object.

```<code>mtcars__string_object <- c("mtcars")
</code>```

For the object itself, here is the code I want to use to get this data via an ifelse() statement, which does not work:

```<code>test_1 <-
  ifelse(
    ((typeof(mtcars) == "list") == TRUE),
    (mtcars),
    NA
  )
</code>```

It does not work because it doesn't give me the dataset in its original form. Here are the results:

```<code>> test_1
[[1]]
 [1] 21.0 21.0 22.8 21.4 18.7 18.1 14.3 24.4 22.8 19.2 17.8 16.4 17.3 15.2 10.4
[16] 10.4 14.7 32.4 30.4 33.9 21.5 15.5 15.2 13.3 19.2 27.3 26.0 30.4 15.8 19.7
[31] 15.0 21.4
</code>```

When I just use the name of the object, here is the code I want to use to get this data via an ifelse() statement, which does not work:

```<code>test_2 <-
  ifelse(
    ((typeof(mtcars) == "character") == TRUE),
    (get(mtcars__string_object[1])),
    NA
  )
</code>```

It does not work because it doesn't give me the dataset in its original form. Here are the results:

```<code>> test_2
[1] NA
</code>```

I'm not sure how to fix the code to get the desired result. Please advise. Thanks.

Here is the code that I used for the example:

```<code># StackOverflow materials

## sets up data

### name of object
mtcars

### text object with name of dataset
mtcars__string_object <- c("mtcars")

## checks typeof() of objects
typeof(mtcars)
typeof(mtcars__string_object)

## ifelse() statements to call data

### for object itself
# ---- NOTE: creates object
test_1 <-
  ifelse(
    ((typeof(mtcars) == "list") == TRUE),
    (mtcars),
    NA
  )
# ---- NOTE: displays object
test_1
# ---- NOTE: does not work

### for text object with name of dataset
# ---- NOTE: creates object
test_2 <-
  ifelse(
    ((typeof(mtcars) == "character") == TRUE),
    (get(mtcars__string_object[1])),
    NA
  )
# ---- NOTE: displays object
test_2
# ---- NOTE: does not work

</code>```

Body:
I want to know how to use ifelse() statements to get different kinds of objects in R.

Specifically, I want to do this with the mtcars data, which is a list type object. I used the code below to create a character object version of the name of the data, called mtcars__string_object.

mtcars__string_object <- c("mtcars")

For the object itself, here is the code I want to use to get this data via an ifelse() statement, which does not work:

test_1 <-
  ifelse(
    ((typeof(mtcars) == "list") == TRUE),
    (mtcars),
    NA
  )

It does not work because it doesn't give me the dataset in its original form. Here are the results:

> test_1
[[1]]
 [1] 21.0 21.0 22.8 21.4 18.7 18.1 14.3 24.4 22.8 19.2 17.8 16.4 17.3 15.2 10.4
[16] 10.4 14.7 32.4 30.4 33.9 21.5 15.5 15.2 13.3 19.2 27.3 26.0 30.4 15.8 19.7
[31] 15.0 21.4

When I just use the name of the object, here is the code I want to use to get this data via an ifelse() statement, which does not work:

test_2 <-
  ifelse(
    ((typeof(mtcars) == "character") == TRUE),
    (get(mtcars__string_object[1])),
    NA
  )

It does not work because it doesn't give me the dataset in its original form. Here are the results:

> test_2
[1] NA

I'm not sure how to fix the code to get the desired result. Please advise. Thanks.

Here is the code that I used for the example:

# StackOverflow materials

## sets up data

### name of object
mtcars

### text object with name of dataset
mtcars__string_object <- c("mtcars")

## checks typeof() of objects
typeof(mtcars)
typeof(mtcars__string_object)

## ifelse() statements to call data

### for object itself
# ---- NOTE: creates object
test_1 <-
  ifelse(
    ((typeof(mtcars) == "list") == TRUE),
    (mtcars),
    NA
  )
# ---- NOTE: displays object
test_1
# ---- NOTE: does not work

### for text object with name of dataset
# ---- NOTE: creates object
test_2 <-
  ifelse(
    ((typeof(mtcars) == "character") == TRUE),
    (get(mtcars__string_object[1])),
    NA
  )
# ---- NOTE: displays object
test_2
# ---- NOTE: does not work

Body:
use `if`

test_3 <-
  `if`(
    ((typeof(mtcars) == "list") == TRUE),
    (mtcars),
    NA
  )
test_3

you will get answer.

> test_3
                     mpg cyl  disp  hp drat    wt  qsec vs am gear carb
Mazda RX4           21.0   6 160.0 110 3.90 2.620 16.46  0  1    4    4
Mazda RX4 Wag       21.0   6 160.0 110 3.90 2.875 17.02  0  1    4    4
Datsun 710          22.8   4 108.0  93 3.85 2.320 18.61  1  1    4    1
Hornet 4 Drive      21.4   6 258.0 110 3.08 3.215 19.44  1  0    3    1
Hornet Sportabout   18.7   8 360.0 175 3.15 3.440 17.02  0  0    3    2
Valiant             18.1   6 225.0 105 2.76 3.460 20.22  1  0    3    1
Duster 360          14.3   8 360.0 245 3.21 3.570 15.84  0  0    3    4
Merc 240D           24.4   4 146.7  62 3.69 3.190 20.00  1  0    4    2
Merc 230            22.8   4 140.8  95 3.92 3.150 22.90  1  0    4    2
Merc 280            19.2   6 167.6 123 3.92 3.440 18.30  1  0    4    4


问:
What's the difference between OSGi and Java Service Provider Interface?
What is the difference between OSGi and Java SPI? what are the pros and cons?</p>

答:
Java SPI is mainly meant for providing implementations of Java standards. This approach gives some decoupling between clients and providers of the services. The implementing classes are defined in META-INF/services.
It is a very simple model though. An implementation can not be injected with other services and there also is no configuration model. So this mainly works for low level services that have no other dependencies.

OSGi also supports decoupling of clients and providers of services. It also allows configuration and dynamic registration of services. Also there are several programming models like declarative services and CDI which can interoperate.

The downside of OSGi is that it requires all libraries to live in a modular classloader and cope with dynamic loading and unloading of jars (bundles). As not all libraries are built like this there is a limited set of java libraries that actually work well inside of OSGi.


问:
I can't pass arguments to the calling function
I am failing to pass arguments to the calling function.

Specifically, I have a table where when I click on the title I have to open a form where the value of the arguments passed must be copied into the various fields of it. To do this, I call through href (as you can see from the code) the function with the parameters passed.

I get the following error:

Uncaught SyntaxError: missing ) after argument list

Object.entries(results).forEach(item => {
  item = item[1];
  let child = document.createElement("tr");
  child.innerHTML = `
                        ${item.number}
                        ${item.type}	`;
  document.querySelector('#my-table').appendChild(child);
})

function showFrag(id, number, type) {
  return id, number, type;
}

function onLoad() {
  showFrag(id, number, type);
  var id = document.getElementById('id');
  var number = document.getElementById('number');
  var type = document.getElementById('type');
  id.value = id;
  numbr.value = number;
  type.value = type;
}
onLoad();```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="split left">
  <div class="centered">

    <table id="my-table" width="90%">
      <tr>
        <th>Number</th>
        <th>Type</th>

      </tr>

    </table>

    <br><br>

  </div>
</div>

<div class="split right">
  <div class="centered"> <br>
    <div class="container">
      <form method="post" id="save" action="javascript:myFunction()" onload="onLoad()">

        <div class="field">
          <label for="id">ID :</label>
          <input type="number" id="id" name="id" />
        </div>

        <div class="field">
          <label for="number">Number:</label>
          <input type="number" id="number" name="number" />
        </div>
        <div class="field">
          <label for="type">Type:</label>
          <select name="type" id="type" form="typeform">
            <option value="Title">Title</option>
            <option value="Text">Text</option>
            <option value="Video">Video</option>
          </select>
        </div>

        <div class="button">
          <button type="submit" class="full">Save modifiche</button>

        </div>
      </form>
    </div>
  </div>
</div></code>```

myFunction() is not present because it has yet to be done, I am only interested in passing for now the value of the parameters passed in the various fields of the form .

result is:

{6: {…}, 8: {…}, 11: {…}, 20: {…}, 21: {…}}
6: {type: 'Text', number: 4, id: 14}
8: {type: 'Text', number: 2, id: 12}
11: {type: 'Image', number: 3, id: 13}
20: {type: 'Video youtube', number: 5, id: 15}
21: {type: 'Title', number: 1, id: 11}```

答:
You need quotes around ${item.type} in the function call if it's a string.

The code to display the values in a the form should be in showFrag(), not onload().

Object.entries(results).forEach(item => {
  item = item[1];
  let child = document.createElement("tr");
  child.innerHTML = `
                        ${item.number}
                        ${item.type}	`;
  document.querySelector('#my-table').appendChild(child);
})

function showFrag(id, number, type) {
  document.getElementById('id').value = id;
  document.getElementById('number').value = number;
  document.getElementById('type').value = type;
}

function onLoad() {
  # nothing to do for now
}
onLoad();```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="split left">
  <div class="centered">

    <table id="my-table" width="90%">
      <tr>
        <th>Number</th>
        <th>Type</th>

      </tr>

    </table>

    <br><br>

  </div>
</div>

<div class="split right">
  <div class="centered"> <br>
    <div class="container">
      <form method="post" id="save" action="javascript:myFunction()" onload="onLoad()">

        <div class="field">
          <label for="id">ID :</label>
          <input type="number" id="id" name="id" />
        </div>

        <div class="field">
          <label for="number">Number:</label>
          <input type="number" id="number" name="number" />
        </div>
        <div class="field">
          <label for="type">Type:</label>
          <select name="type" id="type" form="typeform">
            <option value="Title">Title</option>
            <option value="Text">Text</option>
            <option value="Video">Video</option>
          </select>
        </div>

        <div class="button">
          <button type="submit" class="full">Save modifiche</button>

        </div>
      </form>
    </div>
  </div>
</div></code>```

Body:
I am failing to pass arguments to the calling function.

Specifically, I have a table where when I click on the title I have to open a form where the value of the arguments passed must be copied into the various fields of it. To do this, I call through href (as you can see from the code) the function with the parameters passed.

I get the following error:

Uncaught SyntaxError: missing ) after argument list

Object.entries(results).forEach(item => {
  item = item[1];
  let child = document.createElement("tr");
  child.innerHTML = `
                        ${item.number}
                        ${item.type}	`;
  document.querySelector('#my-table').appendChild(child);
})

function showFrag(id, number, type) {
  return id, number, type;
}

function onLoad() {
  showFrag(id, number, type);
  var id = document.getElementById('id');
  var number = document.getElementById('number');
  var type = document.getElementById('type');
  id.value = id;
  numbr.value = number;
  type.value = type;
}
onLoad();

        Number
        Type

      <form method="post" id="save" action="javascript:myFunction()" onload="onLoad()">

          ID :
          <input type="number" id="id" name="id" />

          Number:
          <input type="number" id="number" name="number" />

          Type:
          <select name="type" id="type" form="typeform">
            <option value="Title">Title</option>
            <option value="Text">Text</option>
            <option value="Video">Video</option>
          </select>

          <button type="submit" class="full">Save modifiche</button>

      </form>

myFunction() is not present because it has yet to be done, I am only interested in passing for now the value of the parameters passed in the various fields of the form .

result is:

{6: {…}, 8: {…}, 11: {…}, 20: {…}, 21: {…}}
6: {type: 'Text', number: 4, id: 14}
8: {type: 'Text', number: 2, id: 12}
11: {type: 'Image', number: 3, id: 13}
20: {type: 'Video youtube', number: 5, id: 15}
21: {type: 'Title', number: 1, id: 11}

Body:
You need quotes around ${item.type} in the function call if it's a string.

The code to display the values in a the form should be in showFrag(), not onload().

Object.entries(results).forEach(item => {
  item = item[1];
  let child = document.createElement("tr");
  child.innerHTML = `
                        <td>${item.number}</td>
                        <td><a href="javascript:showFrag(${item.id},${item.number},'${item.type}');">${item.type}</a></td>`;
  document.querySelector('#my-table').appendChild(child);
})

function showFrag(id, number, type) {
  document.getElementById('id').value = id;
  document.getElementById('number').value = number;
  document.getElementById('type').value = type;
}

function onLoad() {
  # nothing to do for now
}
onLoad();

<div class="split left">
  <div class="centered">

    <table id="my-table" width="90%">
      <tr>
        <th>Number</th>
        <th>Type</th>

      </tr>

    </table>

    <br><br>

  </div>
</div>

<div class="split right">
  <div class="centered"> <br>
    <div class="container">
      <form method="post" id="save" action="javascript:myFunction()" onload="onLoad()">

        <div class="field">
          <label for="id">ID :</label>
          <input type="number" id="id" name="id" />
        </div>

        <div class="field">
          <label for="number">Number:</label>
          <input type="number" id="number" name="number" />
        </div>
        <div class="field">
          <label for="type">Type:</label>
          <select name="type" id="type" form="typeform">
            <option value="Title">Title</option>
            <option value="Text">Text</option>
            <option value="Video">Video</option>
          </select>
        </div>

        <div class="button">
          <button type="submit" class="full">Save modifiche</button>

        </div>
      </form>
    </div>
  </div>
</div>


问:
How to calculate geographic distance in a Painless script (OpenSearch 1.0)
I have some documents in OpenSearch with a field called location, which is a geo-point. I'm trying to write a sort script that takes into account the distance between the document's location, and some other arbitrary location. How do I calculate this distance inside the script? I found this answer from a few years ago, which uses the method distanceInKm. But when I tried it, it doesn't work. Here's my sort block:

```<code>  "sort": {
    "_script": {
      "type": "number",
      "order": "asc",
      "script": {
        "source": "return doc[\"location\"].distanceInKm(38.7819,-77.19);"
      }
    }
  }
</code>```

(Yes, I realize that I don't need a script if I just want to sort by distance. This is a simplified example.)

From the response:

```<code>          "script_stack" : [
            "return doc[\"location\"].distanceInKm(38.7819,-77.19);",
            "                      ^---- HERE"
          ],
          "script" : "return doc[\"location\"].distanceInKm(38.7819,-77.19);",
          "lang" : "painless",
          "position" : {
            "offset" : 22,
            "start" : 0,
            "end" : 52
          },
          "caused_by" : {
            "type" : "illegal_argument_exception",
            "reason" : "dynamic method [org.opensearch.index.fielddata.ScriptDocValues.GeoPoints, distanceInKm/2] not found"
          }
</code>```

答:
It looks like distanceInKm and distanceInMiles were both replaced some time ago by arcDistance(double lat, double lon) and planeDistance(double lat, double lon) - and all distances are now returned in meters.

See here for an explanation of how these two are different.

Body:
I have some documents in OpenSearch with a field called location, which is a geo-point. I'm trying to write a sort script that takes into account the distance between the document's location, and some other arbitrary location. How do I calculate this distance inside the script? I found this answer from a few years ago, which uses the method distanceInKm. But when I tried it, it doesn't work. Here's my sort block:

  "sort": {
    "_script": {
      "type": "number",
      "order": "asc",
      "script": {
        "source": "return doc[\"location\"].distanceInKm(38.7819,-77.19);"
      }
    }
  }

(Yes, I realize that I don't need a script if I just want to sort by distance. This is a simplified example.)

From the response:

          "script_stack" : [
            "return doc[\"location\"].distanceInKm(38.7819,-77.19);",
            "                      ^---- HERE"
          ],
          "script" : "return doc[\"location\"].distanceInKm(38.7819,-77.19);",
          "lang" : "painless",
          "position" : {
            "offset" : 22,
            "start" : 0,
            "end" : 52
          },
          "caused_by" : {
            "type" : "illegal_argument_exception",
            "reason" : "dynamic method [org.opensearch.index.fielddata.ScriptDocValues.GeoPoints, distanceInKm/2] not found"
          }


问:
How to check if a value exists in every forth or fifth row in Pandas?
Salary is usually paid monthly, but suppose I have weekly data:

```<code>id   week   salary
01     01      100
01     02        0
01     03        0
01     04        0
01     05        0
01     06      100
01     07        0
01     08        0
01     09        0
01     10      100
 ⁝       ⁝        ⁝
02     01        0
02     02        0
02     03        0
02     04      150
02     05        0
02     06        0
02     07        0
02     08        0
02     09        0
02     10        0
</code>```

Since months are roughly 4.5 weeks, how can I make a binary employment column to check if the individual is employed (or has received salary in the next 4 or 5 weeks):

```<code>id   week   salary   employed
01     01      100          1
01     02        0          1
01     03        0          1
01     04        0          1
01     05        0          1
01     06      100          1
01     07        0          1
01     08        0          1
01     09        0          1
01     10      100          1
 ⁝       ⁝        ⁝           ⁝
02     01        0          1
02     02        0          1
02     03        0          1
02     04      150          1
02     05        0          0
02     06        0          0
02     07        0          0
02     08        0          0
02     09        0          0
02     10        0          0
</code>```

Individuals 01 and 02 are paid monthly, so we expect them to have been employed for the past 5 weeks if they are paid in a given week.

Edit: I have removed individual 03 to simplify the question.

答:
You can create a rolling window (of size 4 or 5 in your case) using rolling and check if the max value of the window is greater 0.

df["employed"] = df["salary"].iloc[::-1].rolling(5, min_periods=0).max().astype(bool)
```

Some explanations:

Since rolling creates a window backwards, you first have to revert the order of the DataFrame by applying iloc[::-1] before applying rolling to create a forward window (of size 5 in your case). So that would translate to a paycheck at the end of the month and therefore an employment the 5 weeks before the paycheck (like in your example).

The astype(bool) converts a number to True if it's bigger than 0 and to False if it's 0. If you need it as integer (0 or 1) as in your question you can append .astype(int) to the expression.

Body:
Salary is usually paid monthly, but suppose I have weekly data:

id   week   salary
01     01      100
01     02        0
01     03        0
01     04        0
01     05        0
01     06      100
01     07        0
01     08        0
01     09        0
01     10      100
 ⁝       ⁝        ⁝
02     01        0
02     02        0
02     03        0
02     04      150
02     05        0
02     06        0
02     07        0
02     08        0
02     09        0
02     10        0

Since months are roughly 4.5 weeks, how can I make a binary employment column to check if the individual is employed (or has received salary in the next 4 or 5 weeks):

id   week   salary   employed
01     01      100          1
01     02        0          1
01     03        0          1
01     04        0          1
01     05        0          1
01     06      100          1
01     07        0          1
01     08        0          1
01     09        0          1
01     10      100          1
 ⁝       ⁝        ⁝           ⁝
02     01        0          1
02     02        0          1
02     03        0          1
02     04      150          1
02     05        0          0
02     06        0          0
02     07        0          0
02     08        0          0
02     09        0          0
02     10        0          0

Individuals 01 and 02 are paid monthly, so we expect them to have been employed for the past 5 weeks if they are paid in a given week.

Edit: I have removed individual 03 to simplify the question.

Body:
You can create a rolling window (of size 4 or 5 in your case) using rolling and check if the max value of the window is greater 0.

df["employed"] = df["salary"].iloc[::-1].rolling(5, min_periods=0).max().astype(bool)

Some explanations:

Since rolling creates a window backwards, you first have to revert the order of the DataFrame by applying iloc[::-1] before applying rolling to create a forward window (of size 5 in your case). So that would translate to a paycheck at the end of the month and therefore an employment the 5 weeks before the paycheck (like in your example).

The astype(bool) converts a number to True if it's bigger than 0 and to False if it's 0. If you need it as integer (0 or 1) as in your question you can append .astype(int) to the expression.


答:
considering "exa list" as list of string, you can do it in the following way in java 8 and "906986985689" value does not fit into int category. Hence you can use long data type to achieve you scenario.

```<code>    List<String> exa = new ArrayList<String>();
    exa.add("1234567;345676;57689687;906986985689");

    List<Long> list = exa.stream()
                      .flatMap(a ->Arrays.stream(a.split(";")))
                      .map(Long::valueOf)
                      .collect(Collectors.toList());
</code>```

Title: Splitting a list containing ; into another list

Body:
I Have the below list which looks like below.

List<Integer> exa = new ArrayList<Integer>();
exa.add("1234567;345676;57689687;906986985689");

Desired Output:

List<Integer> newExa = new ArrayList<Integer>();
newExa.add("1234567");
newExa.add("345676");
newExa.add("57689687");
newExa.add("906986985689");

Now I need to remove the ; and add the numbers to the new list.Can you please let me know how to proceed forward.

Thanks in advance

Body:
considering "exa list" as list of string, you can do it in the following way in java 8 and "906986985689" value does not fit into int category. Hence you can use long data type to achieve you scenario.

    List<String> exa = new ArrayList<String>();
    exa.add("1234567;345676;57689687;906986985689");

    List<Long> list = exa.stream()
                      .flatMap(a ->Arrays.stream(a.split(";")))
                      .map(Long::valueOf)
                      .collect(Collectors.toList());


问:
how give max width according to screen flutter

as you can mobile screen width is maxed to width
but in web application it's not streached to max width

Please check this
github link---https://github.com/dhaval7152/demohouse.git

I am new in flutter

答:
Try this:</p>
```<code>Container(
  // this is the width of the screen
  width: MediaQuery.of(context).size.width,
  child: Scaffold(...);
),
</code>```

Body:
Try this:

Container(
  // this is the width of the screen
  width: MediaQuery.of(context).size.width,
  child: Scaffold(...);
),


问:
how to get the ip and port of the client side for each packet of data on grpc server side which implement by java?
I want to get the client ip and port corresponding to each packet of data by java grpc service.

```<code>service Auxiliary {
  rpc ProcessMessage(AuxiliaryGrpcMsgRequest) returns (AuxiliaryGrpcMsgReply) {
  }
}
</code>```

this method is generated by proto

public void processMessage( AuxiliaryGrpcMsgRequest request,
           StreamObserver<AuxiliaryGrpcMsgReply> responseObserver) {

}
```

I want know corresponding IP and port of request . I used ServerInterceptor to get IP, but Interceptor thread is different with this processMessage thread. I don't want to use lock to synchronize the two threads, so I want to see if there is any way to get the ip and port of the client corresponding to the request directly in one thread

I noticed C++ can use context->peer() to achieve this.but java's context have no peer(), is there any way to slove this?

答: This information is available to interceptors via serverCall.getAttributes().get(Grpc.TRANSPORT_ATTR_REMOTE_ADDR). If you want it in the Context, you'd need to use a ServerInterceptor to copy it to the Context.

Body:
I want to get the client ip and port corresponding to each packet of data by java grpc service.

service Auxiliary {
  rpc ProcessMessage(AuxiliaryGrpcMsgRequest) returns (AuxiliaryGrpcMsgReply) {
  }
}

this method is generated by proto

public void processMessage( AuxiliaryGrpcMsgRequest request,
           StreamObserver<AuxiliaryGrpcMsgReply> responseObserver) {

}

I want know corresponding IP and port of request . I used ServerInterceptor to get IP, but Interceptor thread is different with this processMessage thread. I don't want to use lock to synchronize the two threads, so I want to see if there is any way to get the ip and port of the client corresponding to the request directly in one thread

I noticed C++ can use context->peer() to achieve this.but java's context have no peer(), is there any way to slove this?


问:
Excel VBA assign values in Array and Plot in bar chart
I can select several id (numbers) via a list box. The chosen id is taken into account in the For- loop.

Each id contains a value in its line in the sheet Messübersicht, which I determine using the variable PmWERT

Question:

In the next step, I would like to save all determined PmWERT as a new variable. Then plot them as a barchart. How can I create a vector or something like that which save all the PmWERT values behind each other? And how can I plot the values as a barchart then?

Thanks!

```<code>Private Sub Auswerten_Click()

Dim Diagramm As Shape
lastRow = Sheets("Messübersicht").Cells(Rows.Count, 9).End(xlUp).Row

Dim text As String
Dim i As Integer

For i = 0 To Me.ListBox_MessID.ListCount - 1
    If Me.ListBox_MessID.Selected(i) Then
        text = text & Me.ListBox_MessID.List(i) & vbNewLine
        Set foundRng = Sheets("Messübersicht").Range("B:B").Find(Me.ListBox_MessID.List(i))
        MsgBox foundRng.Address
        PMWERT = Sheets("Messübersicht").Cells(foundRng.Row, foundRng.Column + 22).Value
    End If
Next i
End Sub
</code>```

答:
You will have to add a chart, add a newSeries to the chart, and assign to .xValues and .Values a Range or, perhaps, an array (of perhaps Double or Integer):</p>
```<code>    Sub testchart()
    Dim yList() As Double
    ReDim yList(3) ' say there are 4 values
    yList(0) = 6.1
    yList(1) = 8
    yList(2) = 4.3
    yList(3) = 2

    With ActiveSheet.ChartObjects.Add(a, b, 900, 300) ' Left, Top, Width, Height
        With .Chart
            .ChartType = xlBarClustered
            ' need to add the series before you can assign the values/xvalues
            ' calling the "NewSeries" method add one series each time you call it.
            .SeriesCollection.NewSeries
            ' now that the series is added, you may assign (not set) the values/xvalues
            .SeriesCollection(1).XValues = Range("A1:A4") ' it can be a Range or an array
            .SeriesCollection(1).Values = yList ' it can be a Range or an array
        End With
    End With
End Sub
</code>```

Body:
I can select several id (numbers) via a list box. The chosen id is taken into account in the For- loop.

Each id contains a value in its line in the sheet Messübersicht, which I determine using the variable PmWERT

Question:

In the next step, I would like to save all determined PmWERT as a new variable. Then plot them as a barchart. How can I create a vector or something like that which save all the PmWERT values behind each other? And how can I plot the values as a barchart then?

Thanks!

Private Sub Auswerten_Click()

Dim Diagramm As Shape
lastRow = Sheets("Messübersicht").Cells(Rows.Count, 9).End(xlUp).Row

Dim text As String
Dim i As Integer

For i = 0 To Me.ListBox_MessID.ListCount - 1
    If Me.ListBox_MessID.Selected(i) Then
        text = text & Me.ListBox_MessID.List(i) & vbNewLine
        Set foundRng = Sheets("Messübersicht").Range("B:B").Find(Me.ListBox_MessID.List(i))
        MsgBox foundRng.Address
        PMWERT = Sheets("Messübersicht").Cells(foundRng.Row, foundRng.Column + 22).Value
    End If
Next i
End Sub

Body:
You will have to add a chart, add a newSeries to the chart, and assign to .xValues and .Values a Range or, perhaps, an array (of perhaps Double or Integer):

    Sub testchart()
    Dim yList() As Double
    ReDim yList(3) ' say there are 4 values
    yList(0) = 6.1
    yList(1) = 8
    yList(2) = 4.3
    yList(3) = 2

    With ActiveSheet.ChartObjects.Add(a, b, 900, 300) ' Left, Top, Width, Height
        With .Chart
            .ChartType = xlBarClustered
            ' need to add the series before you can assign the values/xvalues
            ' calling the "NewSeries" method add one series each time you call it.
            .SeriesCollection.NewSeries
            ' now that the series is added, you may assign (not set) the values/xvalues
            .SeriesCollection(1).XValues = Range("A1:A4") ' it can be a Range or an array
            .SeriesCollection(1).Values = yList ' it can be a Range or an array
        End With
    End With
End Sub


问:
Relation between two list ? [SharePoint 2010]
Do you know how to do a relationship between two lists in SharePoint? I'd like to get an effect similar to the tables in the relation database. So having two lists:  ListA and ListB, connect them after IDName relationship. I would like to add a ListA button opening ListB and I will be able to add the address of the person.
I'm waiting for yours ideas, how to do this ?
Sorry for my english.

Thanks,
Lukasz

```<code>ListA:

**IDName** Name Telephone

ListB

IDAdress **IDName**  Street Country
</code>```

答:
Have you tried using a lookup column on ListA the points to a column in ListB?

If you want to show the full address in the lookup, you can create a calculated column in ListB to concatenate whatever columns you need and do the lookup on the calculated column.

I think this is the nearest you will get to a proper relationship.

Body:
Do you know how to do a relationship between two lists in SharePoint? I'd like to get an effect similar to the tables in the relation database. So having two lists:  ListA and ListB, connect them after IDName relationship. I would like to add a ListA button opening ListB and I will be able to add the address of the person.
I'm waiting for yours ideas, how to do this ?
Sorry for my english.

Thanks,
Lukasz

ListA:

**IDName** Name Telephone

ListB

IDAdress **IDName**  Street Country


问:
Why do I get an unexpected template string expression error?
Is it possible to use map array data (${adv_event.title}) inside a react-structured-data JSX?

I tried adding backticks with no success: name: "`${adv_event.title}`",

Attempt 1:

```<code><Generic jsonldtype="event" schema={{
  name: "${adv_event.title}",
  description: "",
  startDate: "YYYY-MM-DDT:HH:MM",
  endDate: "YYYY-MM-DDT:HH:MM",
  image: "",
}}>
</code>```

Error:

296:31  warning  Unexpected template string expression
  no-template-curly-in-string

答: Use back quote before and after the expression `${adv_event.title}` instead of "${adv_event.title}".

Body:
Is it possible to use map array data (${adv_event.title}) inside a react-structured-data JSX?

I tried adding backticks with no success: name: "`${adv_event.title}`",

Attempt 1:

<Generic jsonldtype="event" schema={{
  name: "${adv_event.title}",
  description: "",
  startDate: "YYYY-MM-DDT:HH:MM",
  endDate: "YYYY-MM-DDT:HH:MM",
  image: "",
}}>

Error:

296:31  warning  Unexpected template string expression
  no-template-curly-in-string


问:
Resize an image before uploading it to firebase
Firebase storage looks very cool and easy to use, but I'm wondering if there's a way to resize an image before uploading it to Firebase Storage, e.g., run a proccess using ImageMagick in a server and then run the uploading process using Firebase SDK but I notice there aren't storage functions for Firebase SDK Server.</p>

答:
You could also use Firebase Storage + the official Firebase Resize Image extension:
https://firebase.google.com/products/extensions/firebase-storage-resize-images. The downside here is that "To install an extension, your project must be on the Blaze (pay as you go) plan". Bc basically what it will do is spin up a Firebase Function App for you, and it'll get triggered every time you upload a file to the path you specify. You can configure things like the desired size as well as the format or if you want to keep a copy of the original file or not.  Good thing you won't need to worry about the underlying implementation.


问:
How can I use scss files and fonts in Vue project
I created new project with vue-cli and I want to use global scss files in my projects to apply global styles. Also I want to use font-families without importing scss file in every component where I want to use it

I found lots of solutions, but none of them help me. I'm new with webpack, so it is hard to understand what exactly goes wrong.
I install loader npm install sass-loader node-sass --save-dev and try to do lots of things with webpack

webpack.config.js

```<code>var path = require('path')
var webpack = require('webpack')

module.exports = {
  entry: './src/main.js',
  output: {
    path: path.resolve(__dirname, './dist'),
    publicPath: '/dist/',
    filename: 'build.js'
  },
  module: {
    rules: [
      {
        test: /\.css$/,
        use: [
          'vue-style-loader',
          'css-loader'
        ],
      },
      {
        test: /\.scss$/,
        use: [
          'vue-style-loader',
          'css-loader',
          'sass-loader'
        ],
      },
      {
        test: /\.sass$/,
        use: [
          'vue-style-loader',
          'css-loader',
          'sass-loader?indentedSyntax'
        ],
      },
      {
        test: /\.vue$/,
        loader: 'vue-loader',
        options: {
          loaders: {
            // Since sass-loader (weirdly) has SCSS as its default parse mode, we map
            // the "scss" and "sass" values for the lang attribute to the right configs here.
            // other preprocessors should work out of the box, no loader config like this necessary.
            'scss': [
              'vue-style-loader',
              'css-loader',
              'sass-loader'
            ],
            'sass': [
              'vue-style-loader',
              'css-loader',
              'sass-loader?indentedSyntax'
            ]
          }
          // other vue-loader options go here
        }
      },
      {
        test: /\.js$/,
        loader: 'babel-loader',
        exclude: /node_modules/
      },
      {
        test: /\.(png|jpg|gif|svg)$/,
        loader: 'file-loader',
        options: {
          name: '[name].[ext]?[hash]'
        }
      }
    ]
  },
  resolve: {
    alias: {
      'vue$': 'vue/dist/vue.esm.js'
    },
    extensions: ['*', '.js', '.vue', '.json']
  },
  devServer: {
    historyApiFallback: true,
    noInfo: true,
    overlay: true
  },
  performance: {
    hints: false
  },
  devtool: '#eval-source-map'
}

if (process.env.NODE_ENV === 'production') {
  module.exports.devtool = '#source-map'
  // http://vue-loader.vuejs.org/en/workflow/production.html
  module.exports.plugins = (module.exports.plugins || []).concat([
    new webpack.DefinePlugin({
      'process.env': {
        NODE_ENV: '"production"'
      }
    }),
    new webpack.optimize.UglifyJsPlugin({
      sourceMap: true,
      compress: {
        warnings: false
      }
    }),
    new webpack.LoaderOptionsPlugin({
      minimize: true
    })
  ])
}
</code>```

src/assets/scss/fonts.scss

```<code>@font-face {
  font-family: "SuisseIntl";
  src: url("../fonts/SuisseIntl.woff") format("woff");
}
@font-face {
  font-family: "SuisseIntl-Light";
  src: url("../fonts/SuisseIntl-Light.woff") format("woff");
}
@font-face {
  font-family: "SuisseIntl-SemiBold";
  src: url("../fonts/SuisseIntl-SemiBold.woff") format("woff");
}

$body-bg: red;
</code>```

I want to be able to use font families in style tag inside every component and I want to be able to import scss files to component like this@import '../assets/scss/fonts'; , but now this cause error.
Can someone help me, please? What should I do to make it work?

答:
Here is an example that works for me on the latest version of Vue-CLI (@vue/cli 5.0.0-rc.2, vue3) + TS + dart-sass:

I saved my fonts to the assets folder (src/assets/fonts/public-sans-vf.woff2);

Then I created the _fonts.css file in which I describe the rule for the font (src/assets/scss/_fonts.scss);

```<code> @font-face {
   font-family: "Public Sans";
   src: url("~@/assets/fonts/public-sans-vf.woff2")
       format("woff2 supports variations"),
     url("~@/assets/fonts/public-sans-vf.woff2") format("woff2-variations");

   font-style: normal;
   font-weight: 400;
   font-display: swap;
</code>```

}

And then I configure the fonts in vue.config.ts

const { defineConfig } = require('@vue/cli-service');

```<code>module.exports = defineConfig({
  transpileDependencies: true,
  css: {
    loaderOptions: {
      scss: {
        additionalData: `
        @import "@/assets/scss/_variables.scss";
        @import "@/assets/scss/_fonts.scss";
        `,
      },
    },
  },
});
</code>```

Body:
I created new project with vue-cli and I want to use global scss files in my projects to apply global styles. Also I want to use font-families without importing scss file in every component where I want to use it

I found lots of solutions, but none of them help me. I'm new with webpack, so it is hard to understand what exactly goes wrong.
I install loader npm install sass-loader node-sass --save-dev and try to do lots of things with webpack

webpack.config.js

var path = require('path')
var webpack = require('webpack')

module.exports = {
  entry: './src/main.js',
  output: {
    path: path.resolve(__dirname, './dist'),
    publicPath: '/dist/',
    filename: 'build.js'
  },
  module: {
    rules: [
      {
        test: /\.css$/,
        use: [
          'vue-style-loader',
          'css-loader'
        ],
      },
      {
        test: /\.scss$/,
        use: [
          'vue-style-loader',
          'css-loader',
          'sass-loader'
        ],
      },
      {
        test: /\.sass$/,
        use: [
          'vue-style-loader',
          'css-loader',
          'sass-loader?indentedSyntax'
        ],
      },
      {
        test: /\.vue$/,
        loader: 'vue-loader',
        options: {
          loaders: {
            // Since sass-loader (weirdly) has SCSS as its default parse mode, we map
            // the "scss" and "sass" values for the lang attribute to the right configs here.
            // other preprocessors should work out of the box, no loader config like this necessary.
            'scss': [
              'vue-style-loader',
              'css-loader',
              'sass-loader'
            ],
            'sass': [
              'vue-style-loader',
              'css-loader',
              'sass-loader?indentedSyntax'
            ]
          }
          // other vue-loader options go here
        }
      },
      {
        test: /\.js$/,
        loader: 'babel-loader',
        exclude: /node_modules/
      },
      {
        test: /\.(png|jpg|gif|svg)$/,
        loader: 'file-loader',
        options: {
          name: '[name].[ext]?[hash]'
        }
      }
    ]
  },
  resolve: {
    alias: {
      'vue$': 'vue/dist/vue.esm.js'
    },
    extensions: ['*', '.js', '.vue', '.json']
  },
  devServer: {
    historyApiFallback: true,
    noInfo: true,
    overlay: true
  },
  performance: {
    hints: false
  },
  devtool: '#eval-source-map'
}

if (process.env.NODE_ENV === 'production') {
  module.exports.devtool = '#source-map'
  // http://vue-loader.vuejs.org/en/workflow/production.html
  module.exports.plugins = (module.exports.plugins || []).concat([
    new webpack.DefinePlugin({
      'process.env': {
        NODE_ENV: '"production"'
      }
    }),
    new webpack.optimize.UglifyJsPlugin({
      sourceMap: true,
      compress: {
        warnings: false
      }
    }),
    new webpack.LoaderOptionsPlugin({
      minimize: true
    })
  ])
}

src/assets/scss/fonts.scss

@font-face {
  font-family: "SuisseIntl";
  src: url("../fonts/SuisseIntl.woff") format("woff");
}
@font-face {
  font-family: "SuisseIntl-Light";
  src: url("../fonts/SuisseIntl-Light.woff") format("woff");
}
@font-face {
  font-family: "SuisseIntl-SemiBold";
  src: url("../fonts/SuisseIntl-SemiBold.woff") format("woff");
}

$body-bg: red;

I want to be able to use font families in style tag inside every component and I want to be able to import scss files to component like this@import '../assets/scss/fonts'; , but now this cause error.
Can someone help me, please? What should I do to make it work?

Body:
Here is an example that works for me on the latest version of Vue-CLI (@vue/cli 5.0.0-rc.2, vue3) + TS + dart-sass:

I saved my fonts to the assets folder (src/assets/fonts/public-sans-vf.woff2);

Then I created the _fonts.css file in which I describe the rule for the font (src/assets/scss/_fonts.scss);

 @font-face {
   font-family: "Public Sans";
   src: url("~@/assets/fonts/public-sans-vf.woff2")
       format("woff2 supports variations"),
     url("~@/assets/fonts/public-sans-vf.woff2") format("woff2-variations");

   font-style: normal;
   font-weight: 400;
   font-display: swap;

}

And then I configure the fonts in vue.config.ts

const { defineConfig } = require('@vue/cli-service');

module.exports = defineConfig({
  transpileDependencies: true,
  css: {
    loaderOptions: {
      scss: {
        additionalData: `
        @import "@/assets/scss/_variables.scss";
        @import "@/assets/scss/_fonts.scss";
        `,
      },
    },
  },
});


问:
SwiftUI: Pattern matching causes view to animate incorrectly
I'm implementing a very simple view (ChildView) that will slide up from the bottom of ParentView when a button is tapped. I've reproduced the issue below in a minimal example.

struct ChildView: View {
    @Binding var foo: String?

    var body: some View {
        HStack {
            if case .some = foo {
                Text("Foo")
            }

            Spacer()

            Text("Bar")
        }
        .offset(y: foo != nil ? 0 : UIScreen.main.bounds.height)
    }
}

struct ParentView: View {
    @State private var foo: String?

    var body: some View {
        ZStack {
            Button(action: {
                withAnimation {
                    foo = "Foo"
                }
            }) {
                Text("Tap me")
            }

            ChildView(foo: $foo)
        }.frame(width: 300, height: 500)
    }
}
```

I pass a binding into ChildView that is a simple String? here, but ultimately it will be an enum instance which I will switch on inside ChildView.

The problem is that Text("Foo") inside ChildView doesn't slide up from the bottom, but rather fades in place. Text("Bar") slides correctly, and the only difference is that the former touches the foo binding. See GIF below:

One can observe the same thing if foo was an enum and we switched on it.

What is going on?

I saw this question, but the accepted answer didn't work for me.

答:
When the binding changes, the ChildView changes two things: Show "foo" which hadn't been there before, and change the offset of anything else to 0.
So animation will only work on what has been there before. i.e. "Bar".

But you can change the value of elements, that are already there:

```<code>struct ChildView: View {
    @Binding var foo: String?

    var body: some View {
        HStack {
            Text(foo ?? "")

            Spacer()

            Text("Bar")
        }
        .offset(y: foo != nil ? 0 : UIScreen.main.bounds.height)
    }
}
</code>```

Body:
I'm implementing a very simple view (ChildView) that will slide up from the bottom of ParentView when a button is tapped. I've reproduced the issue below in a minimal example.

struct ChildView: View {
    @Binding var foo: String?

    var body: some View {
        HStack {
            if case .some = foo {
                Text("Foo")
            }

            Spacer()

            Text("Bar")
        }
        .offset(y: foo != nil ? 0 : UIScreen.main.bounds.height)
    }
}

struct ParentView: View {
    @State private var foo: String?

    var body: some View {
        ZStack {
            Button(action: {
                withAnimation {
                    foo = "Foo"
                }
            }) {
                Text("Tap me")
            }

            ChildView(foo: $foo)
        }.frame(width: 300, height: 500)
    }
}

I pass a binding into ChildView that is a simple String? here, but ultimately it will be an enum instance which I will switch on inside ChildView.

The problem is that Text("Foo") inside ChildView doesn't slide up from the bottom, but rather fades in place. Text("Bar") slides correctly, and the only difference is that the former touches the foo binding. See GIF below:

One can observe the same thing if foo was an enum and we switched on it.

What is going on?

I saw this question, but the accepted answer didn't work for me.

Body:
When the binding changes, the ChildView changes two things: Show "foo" which hadn't been there before, and change the offset of anything else to 0.
So animation will only work on what has been there before. i.e. "Bar".

But you can change the value of elements, that are already there:

struct ChildView: View {
    @Binding var foo: String?

    var body: some View {
        HStack {
            Text(foo ?? "")

            Spacer()

            Text("Bar")
        }
        .offset(y: foo != nil ? 0 : UIScreen.main.bounds.height)
    }
}


问:
add in object by for in in javascript
I am new in javascript
I have object. When I try to add the city, it doesn't appear in the message.
This object show us the detail person. but when I want to put city (forExample)
it doesn't show in message

```<code>let person = {

  name: 'Sam',
  age: 30,
  employed: true,
  is_maried: false

}
</code>```

and

```<code>for (let key in person){

  let massage = `key: ${key} and the value is ${person[key]}`;
  //this to give you the key name and the value in on line

  if (key in person === 'city'){

    person.city = 'NY';

  }else if (!(key in person !== 'city')){

      person.city = 'UK';

  }

console.log(massage);
}
</code>```

答:
let person = {
  name: 'Sam',
  age: 30,
  employed: true,
  is_maried: false
}

if (person.city) {
  person.city = "NY";
} else {
  person.city = "UK";
}

console.log(person);```

Title: add in object by for in in javascript

Body:
I am new in javascript
I have object. When I try to add the city, it doesn't appear in the message.
This object show us the detail person. but when I want to put city (forExample)
it doesn't show in message

let person = {

  name: 'Sam',
  age: 30,
  employed: true,
  is_maried: false

}

and

for (let key in person){

  let massage = `key: ${key} and the value is ${person[key]}`;
  //this to give you the key name and the value in on line

  if (key in person === 'city'){

    person.city = 'NY';

  }else if (!(key in person !== 'city')){

      person.city = 'UK';

  }

console.log(massage);
}