问:
Throughput of trivially concurrent code does not increase with the number of threads
I am trying to use OpenMP to benchmark the speed of data structure that I implemented. However, I seem to make a fundamental mistake: the throughput decreases instead of increasing with the number of threads no matter what operation I try to benchmark.
Below you can see the code that tries to benchmark the speed of a for-loop, as such I would expect it to scale (somewhat) linearly with the number of threads, it doesn't (compiled on a dualcore laptop with and without -O3 flag on g++ with c++11).

```<code>#include <omp.h>
#include <atomic>
#include <chrono>
#include <iostream>

thread_local const int OPS = 10000;
thread_local const int TIMES = 200;

double get_tp(int THREADS)
{
    double threadtime[THREADS] = {0};

    //Repeat the test many times
    for(int iteration = 0; iteration < TIMES; iteration++)
    {
        #pragma  omp  parallel num_threads(THREADS)
        {
            double start, stop;
            int loc_ops = OPS/float(THREADS);
            int t = omp_get_thread_num();

            //Force all threads to start at the same time
            #pragma  omp  barrier
            start = omp_get_wtime();

            //Do a certain kind of operations loc_ops times
            for(int i = 0; i < loc_ops; i++)
            {
                //Here I would put the operations to benchmark
                //in this case a boring for loop
                int x = 0;
                for(int j = 0; j < 1000; j++)
                    x++;
            }

        stop = omp_get_wtime();
        threadtime[t] += stop-start;
        }
    }

    double total_time = 0;
    std::cout << "\nThread times: ";
    for(int i = 0; i < THREADS; i++)
    {
        total_time += threadtime[i];
        std::cout << threadtime[i] << ", ";
    }
    std::cout << "\nTotal time: " << total_time << "\n";
    double mopss = float(OPS)*TIMES/total_time;
    return mopss;
}

int main()
{
    std::cout << "\n1  " << get_tp(1) << "ops/s\n";
    std::cout << "\n2  " << get_tp(2) << "ops/s\n";
    std::cout << "\n4  " << get_tp(4) << "ops/s\n";
    std::cout << "\n8  " << get_tp(8) << "ops/s\n";
}
</code>```

Outputs with -O3 on a dualcore, so we don't expect the throughput to increase after 2 threads, but it does not even increase when going from 1 to 2 threads it decreases by 50%:

```<code>1 Thread
Thread times: 7.411e-06,
Total time: 7.411e-06
2.69869e+11 ops/s

2 Threads
Thread times: 7.36701e-06, 7.38301e-06,
Total time: 1.475e-05
1.35593e+11ops/s

4 Threads
Thread times: 7.44301e-06, 8.31901e-06, 8.34001e-06, 7.498e-06,
Total time: 3.16e-05
6.32911e+10ops/s

8 Threads
Thread times: 7.885e-06, 8.18899e-06, 9.001e-06, 7.838e-06, 7.75799e-06, 7.783e-06, 8.349e-06, 8.855e-06,
Total time: 6.5658e-05
3.04609e+10ops/s
</code>```

To make sure that the compiler does not remove the loop, I also tried outputting "x" after measuring the time and to the best of my knowledge the problem persists. I also tried the code on a machine with more cores and it behaved very similarly. Without -O3 the throughput also does not scale. So there is clearly something wrong with the way I benchmark. I hope you can help me.

答:
I'm not sure why you are defining performance as the total number of operations per total CPU time and then get surprised by the decreasing function of the number of threads. This will almost always and universally be the case except for when cache effects kick in. The true performance metric is the number of operations per wall-clock time.

It is easy to show with simple mathematical reasoning. Given a total work W and processing capability of each core P, the time on a single core is T_1 = W / P. Dividing the work evenly among n cores means each of them works for T_1,n = (W / n + H) / P, where H is the overhead per thread induced by the parallelisation itself. The sum of those is T_n = n * T_1,n = W / P + n (H / P) = T_1 + n (H / P). The overhead is always a positive value, even in the trivial case of so-called embarrassing parallelism where no two threads need to communicate or synchronise. For example, launching the OpenMP threads takes time. You cannot get rid of the overhead, you can only amortise it over the lifetime of the threads by making sure that each one get a lot to work on. Therefore, T_n > T_1 and with fixed number of operations in both cases the performance on n cores will always be lower than on a single core. The only exception of this rule is the case when the data for work of size W doesn't fit in the lower-level caches but that for work of size W / n does. This results in massive speed-up that exceeds the number of cores, known as superlinear speed-up. You are measuring inside the thread function so you ignore the value of H and T_n should more or less be equal to T_1 within the timer precision, but...

With multiple threads running on multiple CPU cores, they all compete for limited shared CPU resources, namely last-level cache (if any), memory bandwidth, and thermal envelope.

The memory bandwidth is not a problem when you are simply incrementing a scalar variable, but becomes the bottleneck when the code starts actually moving data in and out of the CPU. A canonical example from numerical computing is the sparse matrix-vector multiplication (spMVM) -- a properly optimised spMVM routine working with double non-zero values and long indices eats so much memory bandwidth, that one can completely saturate the memory bus with as low as two threads per CPU socket, making an expensive 64-core CPU a very poor choice in that case. This is true for all algorithms with low arithmetic intensity (operations per unit of data volume).

When it comes to the thermal envelope, most modern CPUs employ dynamic power management and will overclock or clock down the cores depending on how many of them are active. Therefore, while n clocked down cores perform more work in total per unit of time than a single core, a single core outperforms n cores in terms of work per total CPU time, which is the metric you are using.

With all this in mind, there is one last (but not least) thing to consider -- timer resolution and measurement noise. Your run times are in couples of microseconds. Unless your code is running on some specialised hardware that does nothing else but run your code (i.e., no time sharing with daemons, kernel threads, and other processes and no interrupt handing), you need benchmarks that run several orders of magnitude longer, preferably for at least a couple of seconds.

Body:
I am trying to use OpenMP to benchmark the speed of data structure that I implemented. However, I seem to make a fundamental mistake: the throughput decreases instead of increasing with the number of threads no matter what operation I try to benchmark.
Below you can see the code that tries to benchmark the speed of a for-loop, as such I would expect it to scale (somewhat) linearly with the number of threads, it doesn't (compiled on a dualcore laptop with and without -O3 flag on g++ with c++11).

#include <omp.h>
#include <atomic>
#include <chrono>
#include <iostream>

thread_local const int OPS = 10000;
thread_local const int TIMES = 200;

double get_tp(int THREADS)
{
    double threadtime[THREADS] = {0};

    //Repeat the test many times
    for(int iteration = 0; iteration < TIMES; iteration++)
    {
        #pragma  omp  parallel num_threads(THREADS)
        {
            double start, stop;
            int loc_ops = OPS/float(THREADS);
            int t = omp_get_thread_num();

            //Force all threads to start at the same time
            #pragma  omp  barrier
            start = omp_get_wtime();

            //Do a certain kind of operations loc_ops times
            for(int i = 0; i < loc_ops; i++)
            {
                //Here I would put the operations to benchmark
                //in this case a boring for loop
                int x = 0;
                for(int j = 0; j < 1000; j++)
                    x++;
            }

        stop = omp_get_wtime();
        threadtime[t] += stop-start;
        }
    }

    double total_time = 0;
    std::cout << "\nThread times: ";
    for(int i = 0; i < THREADS; i++)
    {
        total_time += threadtime[i];
        std::cout << threadtime[i] << ", ";
    }
    std::cout << "\nTotal time: " << total_time << "\n";
    double mopss = float(OPS)*TIMES/total_time;
    return mopss;
}

int main()
{
    std::cout << "\n1  " << get_tp(1) << "ops/s\n";
    std::cout << "\n2  " << get_tp(2) << "ops/s\n";
    std::cout << "\n4  " << get_tp(4) << "ops/s\n";
    std::cout << "\n8  " << get_tp(8) << "ops/s\n";
}

Outputs with -O3 on a dualcore, so we don't expect the throughput to increase after 2 threads, but it does not even increase when going from 1 to 2 threads it decreases by 50%:

1 Thread
Thread times: 7.411e-06,
Total time: 7.411e-06
2.69869e+11 ops/s

2 Threads
Thread times: 7.36701e-06, 7.38301e-06,
Total time: 1.475e-05
1.35593e+11ops/s

4 Threads
Thread times: 7.44301e-06, 8.31901e-06, 8.34001e-06, 7.498e-06,
Total time: 3.16e-05
6.32911e+10ops/s

8 Threads
Thread times: 7.885e-06, 8.18899e-06, 9.001e-06, 7.838e-06, 7.75799e-06, 7.783e-06, 8.349e-06, 8.855e-06,
Total time: 6.5658e-05
3.04609e+10ops/s

To make sure that the compiler does not remove the loop, I also tried outputting "x" after measuring the time and to the best of my knowledge the problem persists. I also tried the code on a machine with more cores and it behaved very similarly. Without -O3 the throughput also does not scale. So there is clearly something wrong with the way I benchmark. I hope you can help me.


来源: stackexchange

问:
Display Data in List view after SAX Parsing
Can anyone give me a full tutorial series Link or sample eclipse project code Link for displaying data in list view after SAX Parsing of XML in Android.

Thanks in advance.

答:
This is the most comprehensive resource you will find:

http://www.ibm.com/developerworks/opensource/library/x-android/

Basically you need to create an adapter from the data you've parsed and feed it to the ListView. You can extend BaseAdapter to make a custom one, or just use ArrayAdapter.

ContentLicense: CC BY-SA 3.0


问:
Get the last entered id from a table in sql
enter image description hereI have an employee table. In that table I have n number of loan.. Now I want to select all the employees with his last taken loan value and date.. can anyone help me out in this.

There's what I've done so far:

```<code>SELECT employee_id,employee_name,department_name,
       designation_name,PF_type,PF_number,Opening_balance,
       MAX(Loan_id),MAX(loan_date), MAX(loan_amount)
FROM single_roww1
GROUP BY employee_id
</code>```

I tried group by, limit and order by for this but of no use... I also tried to take the last occurence of the employee_id that also didn't work..

答:
With a correlated subquery in the WHERE clause:

```<code>SELECT s.employee_id, s.employee_name, s.department_name,
       s.designation_name, s.PF_type, s.PF_number, s.Opening_balance,
       s.Loan_id, s.loan_date, s.loan_amount
FROM single_roww1 s
WHERE s.Loan_id = (SELECT MAX(Loan_id) FROM single_roww1 WHERE employee_id = s.employee_id)
</code>```

ContentLicense: CC BY-SA 4.0

Body:
enter image description hereI have an employee table. In that table I have n number of loan.. Now I want to select all the employees with his last taken loan value and date.. can anyone help me out in this.

There's what I've done so far:

SELECT employee_id,employee_name,department_name,
       designation_name,PF_type,PF_number,Opening_balance,
       MAX(Loan_id),MAX(loan_date), MAX(loan_amount)
FROM single_roww1
GROUP BY employee_id

I tried group by, limit and order by for this but of no use... I also tried to take the last occurence of the employee_id that also didn't work..

Body:
With a correlated subquery in the WHERE clause:

SELECT s.employee_id, s.employee_name, s.department_name,
       s.designation_name, s.PF_type, s.PF_number, s.Opening_balance,
       s.Loan_id, s.loan_date, s.loan_amount
FROM single_roww1 s
WHERE s.Loan_id = (SELECT MAX(Loan_id) FROM single_roww1 WHERE employee_id = s.employee_id)


问:
Template not provided using create-react-app
When I type the create-react-app my-app command in my terminal, it appears to work - downloading all libraries successfully etc. At the end of that process however I get a message that a template was not provided.

Input

```<code>user@users-MacBook-Pro-2 Desktop% create-react-app my-app
</code>```

Output

```<code>Creating a new React app in /Users/user/Desktop/my-app.

Installing packages. This might take a couple of minutes.
Installing react, react-dom, and react-scripts...
..... nothing out of the ordinary here .....
✨  Done in 27.28s.

A template was not provided. This is likely because you're using an outdated version of create-react-app.
Please note that global installs of create-react-app are no longer supported.
</code>```

In package.json of my-app:

```<code>"dependencies": {
  "react": "^16.12.0",
  "react-dom": "^16.12.0",
  "react-scripts": "3.3.0" <-- up-to-date
}
</code>```

I checked out the CRA changelog and it looks like support was added for custom templates - however it doesn't look like the command create-react-app my-app would have changed.

Any idea what is going on here?

答:
If you are getting this error 'Template not provided ...." again and again, then straigt away do the followiong to steps:

npm uninstall -g create-react-app

check the location of your file 'create-react-app' by using the command "which create-react-app"

Now manually delete that file using the command "rm -rf /usr/local/bin/create-react-app" replacing this command with the exact path shown in the previous step.

Finally run 'npx create-react-app '

This will replace your old file 'create-react-app' which is causing the problem with the new file downloaded with npx.

Happy coding...

Body:
When I type the create-react-app my-app command in my terminal, it appears to work - downloading all libraries successfully etc. At the end of that process however I get a message that a template was not provided.

Input

user@users-MacBook-Pro-2 Desktop% create-react-app my-app

Output

Creating a new React app in /Users/user/Desktop/my-app.

Installing packages. This might take a couple of minutes.
Installing react, react-dom, and react-scripts...
..... nothing out of the ordinary here .....
✨  Done in 27.28s.

A template was not provided. This is likely because you're using an outdated version of create-react-app.
Please note that global installs of create-react-app are no longer supported.

In package.json of my-app:

"dependencies": {
  "react": "^16.12.0",
  "react-dom": "^16.12.0",
  "react-scripts": "3.3.0" <-- up-to-date
}

I checked out the CRA changelog and it looks like support was added for custom templates - however it doesn't look like the command create-react-app my-app would have changed.

Any idea what is going on here?


问:
on languages that can link to c++
As I was reflecting on this subject, it seemed to me that if a language is implemented in C++, it might well have a mechanism for linking to C++. As I recall, Java is this way through JNI, though I don't really remember if it goes through C++ or plain C.

However, it seems that in general languages don't link to C++, and are accessible to C++ only through C for various reasons.

So, out of curiosity,

What languages are there that can link to C++ and how and to what extent?

(No credit for the aforementioned C bridge unless it is done in an elegant or interesting way, like Boost.Python)

答:
There is no language that can do this well because the C++ standard does not specify a name mangling scheme.  Because of this, different compilers are free to mangle names differently, and there's no consistent way to link to C++ binaries.

The reason so many things can link to C is because C has simple and consistent linkage.  A function foo is called foo in the object file.  Likewise, things can link to Fortran reasonably well because foo is one of foo, FOO, foo_, or foo__.

This is why there are so many wrapper generators for C++ objects (SWIG, Boost.Python, SIP, etc.).  They define an interface as a set of C calls precisely because that makes things easy to link against.

Something else to keep in mind is whether you really want to link directly to C++ libraries.  Many wrapper generators provide a lot of policy options when you generate wrappers.  Remember, C calls boil down to just functions, but C++ calls typically have a lot of OO semantics you'll need to navigate around.  You need to specify how your C++ objects should be garbage collected in the host language, how things get copied, where vptrs are, how objects are laid out, where objects get allocated, and all the subtle differences between the host language's object model and that of C++.

I know it sounds ideal to just link to a C++ library and be done with it, but it's not that simple, and you're going to want more than just direct linkage in the end anyway.

OwnerDisplayName: Ellery Newcomer

ContentLicense: CC BY-SA 2.5

Title: on languages that can link to c++

OwnerDisplayName: tgamblin

LastEditorDisplayName: tgamblin


问:
cannot send mail using php mail function
Im trying to use PHP mail on my local computer,  but its just not working. I am using the standard script from the php website:

PHP error I'm getting

```<code>SMTP server response: 550 Error sending message: Error: FROM address is invalid
</code>```

actual PHP

```<code>$to      = 'nobody@example.com';
$subject = 'the subject';
$message = 'hello';
$headers = 'From: webmaster@example.com' . "\r\n" .
    'Reply-To: webmaster@example.com' . "\r\n" .
    'X-Mailer: PHP/' . phpversion();

mail($to, $subject, $message, $headers);
</code>```

i downloaded a local mail server, argosoft.  it says the service URL is http://services.argosoft.com/RelayService/Service.asmx . I assume this is what i put in php.ini.

php ini.

```<code> For Win32 only.
 SMTP = services.argosoft.com/RelayService/Service.asmx
 smtp_port = 25
</code>```

答: I have had this error before, and I believe all you have to do is change the email webmaster@example.com to a real email. Make sure you send it to a real email as well.

Body:
Im trying to use PHP mail on my local computer,  but its just not working. I am using the standard script from the php website:

PHP error I'm getting

SMTP server response: 550 Error sending message: Error: FROM address is invalid

actual PHP

$to      = 'nobody@example.com';
$subject = 'the subject';
$message = 'hello';
$headers = 'From: webmaster@example.com' . "\r\n" .
    'Reply-To: webmaster@example.com' . "\r\n" .
    'X-Mailer: PHP/' . phpversion();

mail($to, $subject, $message, $headers);

i downloaded a local mail server, argosoft.  it says the service URL is http://services.argosoft.com/RelayService/Service.asmx . I assume this is what i put in php.ini.

php ini.

 For Win32 only.
 SMTP = services.argosoft.com/RelayService/Service.asmx
 smtp_port = 25


问:
Custom HTTP request header
I'm trying to send a custom header to my web application using Google Http Client library like this:

```<code>    HttpRequest request = requestFactory.buildGetRequest(url);
    HttpHeaders headers = new HttpHeaders();
    headers.set("custom", "somevalue");
    request.setHeaders(headers);
    HttpResponse response = request.execute();
</code>```

However, when I try to enumerate the headers received by my web application, the header I added in my Java client is not there, what could be missing?

答:
You need to prefix your key with X- e.g
httpChannel.setRequestHeader("X-Key", "value")</p>

Title: Custom HTTP request header

Body:
I'm trying to send a custom header to my web application using Google Http Client library like this:

    HttpRequest request = requestFactory.buildGetRequest(url);
    HttpHeaders headers = new HttpHeaders();
    headers.set("custom", "somevalue");
    request.setHeaders(headers);
    HttpResponse response = request.execute();

However, when I try to enumerate the headers received by my web application, the header I added in my Java client is not there, what could be missing?


问:
Why converted promise from Subject (Observable) does not work as expected
Why the second promise doesn't work?

```<code>public upload(): Promise<any> {
    return (this.loader.file as Promise<File>)
        .then(file => {
            const uploadImageUrl$: Subject<string> = new Subject<string>();;
            this.uploadImageService.uploadFile(file).subscribe( data => {
                uploadImageUrl$.next(this.uploadImageService.getImageUrlByResponse(data));
            });
            uploadImageUrl$.subscribe(console.log); //return url
            return uploadImageUrl$.toPromise();
        })
        .then(url => {
            console.log(url); //doesn't work
            return {default: url};
        });
}
</code>```

I was expecting for the returned url

答:
The problem is, as long as your subject is not completed, the Promise can't be resolved and therefore cannot be passed to the next then.

See example:

```<code>import { of, subject } from 'rxjs';
import { map } from 'rxjs/operators';

const subject$ = new Subject<string>();

subject$.toPromise().then(value => console.log(value));

subject$.next('hello!');
subject$.complete();
</code>```

If you comment out the complete in the Stackblitz example, you will see that it works.

https://stackblitz.com/edit/rxjs-n4jib6?file=index.ts

Please let me know if its works, thanks!

Body:
Why the second promise doesn't work?

public upload(): Promise<any> {
    return (this.loader.file as Promise<File>)
        .then(file => {
            const uploadImageUrl$: Subject<string> = new Subject<string>();;
            this.uploadImageService.uploadFile(file).subscribe( data => {
                uploadImageUrl$.next(this.uploadImageService.getImageUrlByResponse(data));
            });
            uploadImageUrl$.subscribe(console.log); //return url
            return uploadImageUrl$.toPromise();
        })
        .then(url => {
            console.log(url); //doesn't work
            return {default: url};
        });
}

I was expecting for the returned url

Body:
The problem is, as long as your subject is not completed, the Promise can't be resolved and therefore cannot be passed to the next then.

See example:

import { of, subject } from 'rxjs';
import { map } from 'rxjs/operators';

const subject$ = new Subject<string>();

subject$.toPromise().then(value => console.log(value));

subject$.next('hello!');
subject$.complete();

If you comment out the complete in the Stackblitz example, you will see that it works.

https://stackblitz.com/edit/rxjs-n4jib6?file=index.ts

Please let me know if its works, thanks!


问:
Filter array of objects by nested array of object value
Suppose I have an array of objects, each of which contains a nested array of objects likes:

```<code>[
  {
    id: 1,
    title: 'Lorem',
    private: false,
    likes: [
      { id: 01, username: 'mike' },
      { id: 02, username: 'john' }
    ]
  },
  {
    id: 2,
    title: 'Ipsum',
    private: true,
    likes: [
      { id: 03, username: 'steve' },
      { id: 04, username: 'mike' },
      { id: 05, username: 'sara' }
    ]
  },
  {
    id: 3,
    title: 'Dolor',
    private: false,
    likes: [
      { id: 06, username: 'brad' },
      { id: 07, username: 'cameron' },
      { id: 08, username: 'liam' }
    ]
  }
]
</code>```

How can I filter the outer array by the username value inside its items nested array? Let's say output the items that contains in its inner arrays objects with property username: 'mike'?

答:
you can use 'map' function to filter the internal array</p>

```<code>const data = [
{
    id: 1,
    title: 'Lorem',
    private: false,
    likes: [
      { id: 1, username: 'mike' },
      { id: 2, username: 'john' }
    ]
  },
  {
    id: 2,
    title: 'Ipsum',
    private: true,
    likes: [
      { id: 3, username: 'steve' },
      { id: 4, username: 'mike' },
      { id: 5, username: 'sara' }
    ]
  },
  {
    id: 3,
    title: 'Dolor',
    private: false,
    likes: [
      { id: 6, username: 'brad' },
      { id: 7, username: 'cameron' },
      { id: 8, username: 'liam' }
    ]
  }
]

const res = data.map( item => {
  let likes = item.likes.filter( user => user.username === 'mike')
  if(likes.length > 0 ) {
    item.likes = likes
    return item
  }
  return null
}).filter(item => item !== null )

console.log(res)
</code>```

Body:
Suppose I have an array of objects, each of which contains a nested array of objects likes:

[
  {
    id: 1,
    title: 'Lorem',
    private: false,
    likes: [
      { id: 01, username: 'mike' },
      { id: 02, username: 'john' }
    ]
  },
  {
    id: 2,
    title: 'Ipsum',
    private: true,
    likes: [
      { id: 03, username: 'steve' },
      { id: 04, username: 'mike' },
      { id: 05, username: 'sara' }
    ]
  },
  {
    id: 3,
    title: 'Dolor',
    private: false,
    likes: [
      { id: 06, username: 'brad' },
      { id: 07, username: 'cameron' },
      { id: 08, username: 'liam' }
    ]
  }
]

How can I filter the outer array by the username value inside its items nested array? Let's say output the items that contains in its inner arrays objects with property username: 'mike'?

Body:
you can use 'map' function to filter the internal array

const data = [
{
    id: 1,
    title: 'Lorem',
    private: false,
    likes: [
      { id: 1, username: 'mike' },
      { id: 2, username: 'john' }
    ]
  },
  {
    id: 2,
    title: 'Ipsum',
    private: true,
    likes: [
      { id: 3, username: 'steve' },
      { id: 4, username: 'mike' },
      { id: 5, username: 'sara' }
    ]
  },
  {
    id: 3,
    title: 'Dolor',
    private: false,
    likes: [
      { id: 6, username: 'brad' },
      { id: 7, username: 'cameron' },
      { id: 8, username: 'liam' }
    ]
  }
]

const res = data.map( item => {
  let likes = item.likes.filter( user => user.username === 'mike')
  if(likes.length > 0 ) {
    item.likes = likes
    return item
  }
  return null
}).filter(item => item !== null )

console.log(res)


问:
Syntax shorthand for comparison operator in python
I have an if statement that wants to check:

```<code>if c=="a" or c=="e" or c=="i" or c=="o" or c=="w":
</code>```

Is there a way to write this more efficiently so that I don't have to repeat c=="x" so much.
Something like if c=="a" or "e" or "i" or "o" or "w":

答:
how about</p>

```<code>letters = ["a", "e", "i", "o", "w"]
if c in letters:
    foo
</code>```

Body:
I have an if statement that wants to check:

if c=="a" or c=="e" or c=="i" or c=="o" or c=="w":

Is there a way to write this more efficiently so that I don't have to repeat c=="x" so much.
Something like if c=="a" or "e" or "i" or "o" or "w":

Body:
how about

letters = ["a", "e", "i", "o", "w"]
if c in letters:
    foo


问:
How to clear the terminal screen in Rust after a new line is printed?
I have printed some text using println! and now I need to clear the terminal and write the new text instead of the old. How can I clear all the current text from terminal?

I have tried this code, but it only clears the current line and 1 is still in the output.

```<code>fn main() {
    println!("1");
    print!("2");
    print!("\r");
}
</code>```

答:
```<code>print!("\x1B[2J\x1B[1;1H");
</code>```

This will clear the screen and put the cursor at first row & first col of the screen.

Body:
I have printed some text using println! and now I need to clear the terminal and write the new text instead of the old. How can I clear all the current text from terminal?

I have tried this code, but it only clears the current line and 1 is still in the output.

fn main() {
    println!("1");
    print!("2");
    print!("\r");
}

Body:
print!("\x1B[2J\x1B[1;1H");

This will clear the screen and put the cursor at first row & first col of the screen.


问:
How to pull variables out of a string
I'm looking for a Java class that for a given string "the ${animal} jumped over the ${target}." is able to pull out the variable names, ie 'animal' and 'target'.

I had hoped StrSubstitutor in Commons Lang had a method

getVariables(String str) : List<String>

... but no such luck.

Yes I could write this myself, but I'm certain there must be a 3rd party library that exists out there that does this.

答:
You could just do a simple regex match if you really just want to pull out those values and avoid the dependency of an entire library:

```<code>public List<String> getVariableNames(String source) {
  List<String> vs = new ArrayList<String>();
  Pattern p = Pattern.compile("\\$\\{(\\w+)\\}");
  Matcher m = p.matcher(source);
  while (m.find()) {
    vs.add(m.group(1));
  }
  return vs;
}
</code>```

Storing the pattern as a member variable will improve performance.

Title: How to pull variables out of a string

Body:
You could just do a simple regex match if you really just want to pull out those values and avoid the dependency of an entire library:

public List<String> getVariableNames(String source) {
  List<String> vs = new ArrayList<String>();
  Pattern p = Pattern.compile("\\$\\{(\\w+)\\}");
  Matcher m = p.matcher(source);
  while (m.find()) {
    vs.add(m.group(1));
  }
  return vs;
}

Storing the pattern as a member variable will improve performance.


问:
Can't install apk made by Visual C++
I installed into Visual Studio 2019, mobile development using C++, I created project with Native Activity template, then compiled tried to run on my phone but it didnt install, when i saw youtube video that guy made same thing as me but it did run in his case, i was trying to find anything on internet but there are only tutorials about Xamarin which is not my case, i'm absolutely hopeless, does anyone know any tutorials about this? Even Microsoft docs has almost no documentation about this</p>

答:
In most cases this is caused by the compiler settings.

If you still have your project / IDE open, try to check your compiler / linker settings to see if they match whatever the original project's were which you were following in this tutorial.

Sometimes, the people who make "setup" tutorials wont include these and just assume everyone automatically has the exact necessary instructions for the project-- but in some cases-- they wont, and then the person watching is left assume they did something incorrectly code-wise.

Without any code or other information to this post, this is possibly the most I can assist you with.

Best wishes.

~Fox

Title: Can't install apk made by Visual C++


问:
Reading single key value pairin json string
How to render only Name in react code?

{
    "Name": "Demo",
    "Detail": [
        {
            "role": [
                "dev",
                "qa",
                "BA"
            ],
            "age": "35"
        }
    ]
}

答:
Wrap you prop in curly braces:</p>

```<code>const obj = { "Name": "Demo", "Detail": [ { "role": [ "dev", "qa", "BA" ], "age": "35" } ] }

// ... JSX

<div>{obj.Name}</div>
</code>```

Body:
Wrap you prop in curly braces:

const obj = { "Name": "Demo", "Detail": [ { "role": [ "dev", "qa", "BA" ], "age": "35" } ] }

// ... JSX

<div>{obj.Name}</div>


问:
Among `dctor,copy ctor and copy assignment operator`, why deletes one and leaves the other to be implicitly-defined will most likely result in errors
As per the documentation(https://en.cppreference.com/w/cpp/language/rule_of_three), which says:

Classes that manage non-copyable resources through copyable handles
  may have to declare copy assignment and copy constructor private and
  not provide their definitions or define them as deleted. This is
  another application of the rule of three: deleting one and leaving the
  other to be implicitly-defined will most likely result in errors.

As the subject, i wonder why it occurs.Could sombody explain it in more detail?
Could somebody make it clear by giving some simple example?

答:
The answer is in the previous paragraph:

The implicitly-defined special member functions are typically incorrect if the class is managing a resource whose handle is an object of non-class type (raw pointer, POSIX file descriptor, etc), whose destructor does nothing and copy constructor/assignment operator performs a "shallow copy" (copy the value of the handle, without duplicating the underlying resource).

What the rule of three tells you is that you want all your special members (copy constructor, copy assignment operator, and destructor) to be defined the same way: implicitly, explicitly, or not at all.

A class that manages a non-copyable resource is usually a class that owns some hard-to-copy resource. An example is std::filebuf, that manages a file (it's used by std::fstream). It does not define a copy constructor nor a copy assignment operator: both are deleted. It does explicitly define a destructor in order to close the file.

Now, if the destructor was left implicitly-defined, the file would never be closed and the buffer would stay in memory, causing a memory leak. If either the copy constructor of the copy assignment operator was implicitly-defined, it would copy the pointer to the buffer, and then the destructor would potentially be called multiple times for the same file, attempting to delete the same buffer multiple times (which is undefined behavior).


问:
Use SASS (from command line) and Autoprefixer (for Bootstrap 4.x)
I have recently started using the scss files, especially to customize Bootstrap.

To compile my scss files (and also bootstrap) i use sass from the command line.

Example :

```<code>sass /path/to/scss/bootstrap/mycustom.scss /path/to/css/bootstrap.min.css -t compressed -C --sourcemap=none
</code>```

mycustom.scss is something like that:

```<code> $theme-colors: (
     "custom-primary": "...",
     "custom-secondary": "..."
 );
 ....
 ....
 @import "bootstrap";
</code>```

This way i can customize bootstrap to my pleasure, without problems.

Today, however, i realized that a graphic component (custom-select) was not rendered correctly. After some research i found that this was caused by the lack of Autoprefixer during compilation, and therefore some css properties were not added to my bootstrap.min.css.

I found this on Bootstrap documentation: https://getbootstrap.com/docs/4.2/getting-started/build-tools/#autoprefixer

But i can not find a solution to compile Bootstrap (with sass) using Autoprefixer.

答:
After i have installed globally post-css and autoprefixer

npm install -g postcss-cli autoprefixer

i run the following command to reload  my CSS file with autoprefixer.

postcss assets/theme.css --replace --use autoprefixer

Note: I will update this post once i have worked on for one command that both handle SASS CLI and Autoprefixer

Edit-1: You can combine 2 terminal commands and compile and minify Bootstrap SCSS, then run Autoprefixer to add vendor prefixes like this with just one command:

sass scss/theme.scss:assets/theme.min.css --style=compressed && postcss assets/theme.min.css --replace --use autoprefixer

Body:
I have recently started using the scss files, especially to customize Bootstrap.

To compile my scss files (and also bootstrap) i use sass from the command line.

Example :

sass /path/to/scss/bootstrap/mycustom.scss /path/to/css/bootstrap.min.css -t compressed -C --sourcemap=none

mycustom.scss is something like that:

 $theme-colors: (
     "custom-primary": "...",
     "custom-secondary": "..."
 );
 ....
 ....
 @import "bootstrap";

This way i can customize bootstrap to my pleasure, without problems.

Today, however, i realized that a graphic component (custom-select) was not rendered correctly. After some research i found that this was caused by the lack of Autoprefixer during compilation, and therefore some css properties were not added to my bootstrap.min.css.

I found this on Bootstrap documentation: https://getbootstrap.com/docs/4.2/getting-started/build-tools/#autoprefixer

But i can not find a solution to compile Bootstrap (with sass) using Autoprefixer.


问:
Is it possible to print a certain string base on LocalDateTime in java?
So i use localdatetime to get current time . I want it to print "Good night" when it is morning and "Good night" if it night base on localdatetime . I did find about isBefore() . I also did find some example but it is for date . I need some example .I am sorry if my question is not clear .</p>

```<code>LocalDateTime localDate = LocalDateTime.now();
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("dd MMM YYYY , h:mm a");
</code>```

答:
You can use localDate.getHour() to get current hour of day and use hour to print greeting message. Check below code -

```<code>private void printGrretingMessage()
{
    LocalDateTime currentDateTime = LocalDateTime.now();
    int hour = currentDateTime.getHour();

    if ( hour < 10 ) {
        System.out.println( "Good Morning" );
    } else if ( hour < 16 ) {
        System.out.println( "Good Afternoon" );
    } else if ( hour < 20 ) {
        System.out.println( "Good Evening" );
    } else {
        System.out.println( "Good Night" );
    }
}
</code>```

I hope this works for you. :-)

Body:
So i use localdatetime to get current time . I want it to print "Good night" when it is morning and "Good night" if it night base on localdatetime . I did find about isBefore() . I also did find some example but it is for date . I need some example .I am sorry if my question is not clear .

LocalDateTime localDate = LocalDateTime.now();
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("dd MMM YYYY , h:mm a");

Body:
You can use localDate.getHour() to get current hour of day and use hour to print greeting message. Check below code -

private void printGrretingMessage()
{
    LocalDateTime currentDateTime = LocalDateTime.now();
    int hour = currentDateTime.getHour();

    if ( hour < 10 ) {
        System.out.println( "Good Morning" );
    } else if ( hour < 16 ) {
        System.out.println( "Good Afternoon" );
    } else if ( hour < 20 ) {
        System.out.println( "Good Evening" );
    } else {
        System.out.println( "Good Night" );
    }
}

I hope this works for you. :-)


问:
How can I make my HorizontalBarChart scrollable?
Currently trying to implement a HorizontalBarChart using MPAndroidChart. However, there are too many bars and they won't all fit on the screen. HorizontalBarChart will scroll only if I zoom in, but will never go past what was already on the screen. Not sure if this is an XML problem (I have the HorizontalBarChart in a Relative Layout, tried ScrollView but didn't work) or if there's already an implementation like chart.enableScroll() (which I have tried, and it doesn't work).</p>

答:
```<code>chart.setData(...); // first set data
// now modify viewport
chart.setVisibleXRangeMaximum(5); // allow 5 values to be displayed
chart.moveViewToX(1);// set the left edge of the chart to x-index 1
</code>```

You can use above way

Body:
chart.setData(...); // first set data
// now modify viewport
chart.setVisibleXRangeMaximum(5); // allow 5 values to be displayed
chart.moveViewToX(1);// set the left edge of the chart to x-index 1

You can use above way


问:
Javascript Bootstrap | Open bootstrap modal with javascript and not with button
How can we open bootstrap modal with javascript and not with button? I need to open without button, because another javascript program will decide when to open the modal.

JAVASCRIPT:

```

<p><strong>HTML:</strong></p>

<pre class="lang-html prettyprint-override"><code><!-- Button trigger modal -->
<button type="button" class="btn btn-primary" data-toggle="modal" data-target="#exampleModalCenter">
  Launch demo modal
</button>

<!-- Modal -->
<div id="modalElement" class="modal fade" id="exampleModalCenter" tabindex="-1" role="dialog" aria-labelledby="exampleModalCenterTitle" aria-hidden="true">
  <div class="modal-dialog modal-dialog-centered" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" id="exampleModalLongTitle">Modal title</h5>
        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">×</span>
        </button>
      </div>
      <div class="modal-body">
        ...
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
        <button type="button" class="btn btn-primary">Save changes</button>
      </div>
    </div>
  </div>
</div>
</code>```

答:
Use .modal('show').

With jQuery it will be: $('#modalElement').modal('show')

Extracted from Bootstrap Modal API

Body:
How can we open bootstrap modal with javascript and not with button? I need to open without button, because another javascript program will decide when to open the modal.

JAVASCRIPT:

HTML:

<button type="button" class="btn btn-primary" data-toggle="modal" data-target="#exampleModalCenter">
  Launch demo modal
</button>

Modal title

        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
          ×
        </button>

        ...

        <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
        <button type="button" class="btn btn-primary">Save changes</button>


问:
Hover over a building floor in HTML/CSS
I'm trying to change the color of a floor when I hover it.
https://imgur.com/a/pXEmNXp this is the image on which I'm trying to do it.

I tried the answer on this post: How can we draw 3D bulding structure from existing image Jquery,Css? but when I actually hover the floor it doesn't work, it only shows when I hover in a random place on the bottom of the image.

How can I do it so it shows that specific floor when I hover it, and how can I actually implement the map attribute for every floor?

Here's my code if it helps:

$(document).ready(function () {

        $('map').on('mouseenter', function () {
            $('.highlight-4').show();
        })

        $('map').on('mouseleave', function () {
            $('.highlight-4').hide();
        })
    });```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.highlight {
     z-index: 9999;
     display: none;
     pointer-events: none;
  }

  .building {
     position: absolute;
     margin-left: 11%;
     box-shadow: 0 15px 30px rgba(0, 0, 0, .6);;
  }</code>```

HTML

        <map name="image-map">
            <area target="" alt="" title="" href="" coords="1121,326,197,662,191,747,1130,473,1398,664,1387,544"
                shape="poly">
        </map>```

答:
Best way seems to implement your building image as an SVG file with <polyline> overlays. This way you can use CSS selectors and have much more control over your layouts. You can use  inside SVG, javascript, etc.

I took your image and loaded it in Draw SVG to create the required top floor <polyline>. After having saved the DrawSVG drawing locally I simply copied the <polyline> into my own SVG file, which, as you can see, works without any further HTML and added some CSS to do the highlighting on :hover.

You can insert this SVG into you html as if it were an , it is just another tag (with benefits).

UPDATE

Revisited the original code I posted and replaced it with completely new code. The code is now a HTML page using an SVG file with the OPs image and showing how to use an  with some demo text on :hover (top floor again).

The HTML page has also been made 'responsive' by using math in CSS calc() and @media queries (go 'full-page' and resize browser, also check the page on various devices with the browser Developer Tools, 'portrait' and 'landscape' mode).

Explanation of the math can be found in other answers I gave on SO:

SO 62033317

SO 61867702

Now you create the other floors....

/*
    Visit below answers on Stackoverflow for an explanation
    of the math used for responsive sizing of elements.

    https://stackoverflow.com/a/62033317/2015909
    https://stackoverflow.com/a/61867702/2015909
*/
/**************************/
/* preferred global rules */
/**************************/
html,body               { box-sizing: border-box; width: 100%; max-width: 100%; height: 100% }
*::before,*::after, *   { box-sizing: inherit }
body                    { margin: 0 }

/* responsive base font size using y = mx + b */
html    { font-size: calc(0.625vmin + 0.75rem) } /* (320,14)(1280,20) */
body    { font-size: 1rem }

[band]  { display: flex; flex-flow: column wrap; align-content: center }

[padded="1"], [padded="0"] [band*="padded"] {
/*
    responsive page padding
    and responsive band padding (same as responsive page padding, but at band level)
    p1(320,32) p2(1920, 72) => 0.025x + 24
    p3(320, 8) p4(1920,320) => 0.195x - 54.4

    'Band padding' is only active when 'page padding' is off
*/
    padding: calc( 2.5vh + 24px) calc(19.5vw - 54.4px);
}

/* Making sure the image fits in any viewport, either portrait or landscape */
@media (orientation: portrait ) { #construction-site { height: auto; width: 100% } }
@media (orientation: landscape) { #construction-site { height: 100%; width: auto } }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><body padded="0">
<div id="construction-site" band="padded">
    <svg viewbox="0 0 1600 1200"
         xmlns="http://www.w3.org/2000/svg"
         xmlns:xlink="http://www.w3.org/1999/xlink">

        <style>
            .line       { stroke: Black; stroke-opacity: 0; stroke-width: 2px; cursor: pointer }
            .polyline   { fill  : Red  ; fill-opacity  : 0 }

            .floor-text { fill: Black; stroke: none; fill-opacity: 0;
                          cursor: default; pointer-events: none;
                          font-weight: bold; font-family: sans-serif;
                          /* responsive font using y = mx + b */
                          font-size: calc(-1vmin + 51.2px); /* (320,48)(1920,32) */
                        }

            .floor:hover>.line       { fill-opacity: .4; stroke-opacity: .8 }
            .floor:hover>.floor-text { fill-opacity: .7 }
        </style>

        <image href="https://i.imgur.com/0i4N0d3.jpg"/>

            <polyline class="line polyline"
                points="201.242,678.473 1121.43, 333.16 1370.24,
                        553.473 1387.74, 668.473 1127.49,
                        474.098 189.242, 753.473 202.242, 678.973"/>

            <line class="line" x1="1121.42" y1="333.472" x2="1127.45" y2="474.097"/>
            <text class="floor-text" x="800" y="150" text-anchor="middle">top floor demo text</text>

    </svg>
</div>
</body></code>```

Title: Hover over a building floor in HTML/CSS

Body:
I'm trying to change the color of a floor when I hover it.
https://imgur.com/a/pXEmNXp this is the image on which I'm trying to do it.

I tried the answer on this post: How can we draw 3D bulding structure from existing image Jquery,Css? but when I actually hover the floor it doesn't work, it only shows when I hover in a random place on the bottom of the image.

How can I do it so it shows that specific floor when I hover it, and how can I actually implement the map attribute for every floor?

Here's my code if it helps:

$(document).ready(function () {

        $('map').on('mouseenter', function () {
            $('.highlight-4').show();
        })

        $('map').on('mouseleave', function () {
            $('.highlight-4').hide();
        })
    });

.highlight {
     z-index: 9999;
     display: none;
     pointer-events: none;
  }

  .building {
     position: absolute;
     margin-left: 11%;
     box-shadow: 0 15px 30px rgba(0, 0, 0, .6);;
  }

HTML

        <map name="image-map">
            <area target="" alt="" title="" href="" coords="1121,326,197,662,191,747,1130,473,1398,664,1387,544"
                shape="poly">
        </map>

Body:
Best way seems to implement your building image as an SVG file with <polyline> overlays. This way you can use CSS selectors and have much more control over your layouts. You can use <a> inside SVG, javascript, etc.

I took your image and loaded it in Draw SVG to create the required top floor <polyline>. After having saved the DrawSVG drawing locally I simply copied the <polyline> into my own SVG file, which, as you can see, works without any further HTML and added some CSS to do the highlighting on :hover.

You can insert this SVG into you html as if it were an <img>, it is just another tag (with benefits).

UPDATE

Revisited the original code I posted and replaced it with completely new code. The code is now a HTML page using an SVG file with the OPs image and showing how to use an <a> with some demo text on :hover (top floor again).

The HTML page has also been made 'responsive' by using math in CSS calc() and @media queries (go 'full-page' and resize browser, also check the page on various devices with the browser Developer Tools, 'portrait' and 'landscape' mode).

Explanation of the math can be found in other answers I gave on SO:

SO 62033317

SO 61867702

Now you create the other floors....

/*
    Visit below answers on Stackoverflow for an explanation
    of the math used for responsive sizing of elements.

    https://stackoverflow.com/a/62033317/2015909
    https://stackoverflow.com/a/61867702/2015909
*/
/**************************/
/* preferred global rules */
/**************************/
html,body               { box-sizing: border-box; width: 100%; max-width: 100%; height: 100% }
*::before,*::after, *   { box-sizing: inherit }
body                    { margin: 0 }

/* responsive base font size using y = mx + b */
html    { font-size: calc(0.625vmin + 0.75rem) } /* (320,14)(1280,20) */
body    { font-size: 1rem }

[band]  { display: flex; flex-flow: column wrap; align-content: center }

[padded="1"], [padded="0"] [band*="padded"] {
/*
    responsive page padding
    and responsive band padding (same as responsive page padding, but at band level)
    p1(320,32) p2(1920, 72) => 0.025x + 24
    p3(320, 8) p4(1920,320) => 0.195x - 54.4

    'Band padding' is only active when 'page padding' is off
*/
    padding: calc( 2.5vh + 24px) calc(19.5vw - 54.4px);
}

/* Making sure the image fits in any viewport, either portrait or landscape */
@media (orientation: portrait ) { #construction-site { height: auto; width: 100% } }
@media (orientation: landscape) { #construction-site { height: 100%; width: auto } }

<body padded="0">
<div id="construction-site" band="padded">
    <svg viewbox="0 0 1600 1200"
         xmlns="http://www.w3.org/2000/svg"
         xmlns:xlink="http://www.w3.org/1999/xlink">

        <style>
            .line       { stroke: Black; stroke-opacity: 0; stroke-width: 2px; cursor: pointer }
            .polyline   { fill  : Red  ; fill-opacity  : 0 }

            .floor-text { fill: Black; stroke: none; fill-opacity: 0;
                          cursor: default; pointer-events: none;
                          font-weight: bold; font-family: sans-serif;
                          /* responsive font using y = mx + b */
                          font-size: calc(-1vmin + 51.2px); /* (320,48)(1920,32) */
                        }

            .floor:hover>.line       { fill-opacity: .4; stroke-opacity: .8 }
            .floor:hover>.floor-text { fill-opacity: .7 }
        </style>

        <image href="https://i.imgur.com/0i4N0d3.jpg"/>

        <a id="top-floor" class="floor" rel="noopener" target="_blank" href="javascript:void(0)" title="top floor, click for details...">
            <polyline class="line polyline"
                points="201.242,678.473 1121.43, 333.16 1370.24,
                        553.473 1387.74, 668.473 1127.49,
                        474.098 189.242, 753.473 202.242, 678.973"/>

            <line class="line" x1="1121.42" y1="333.472" x2="1127.45" y2="474.097"/>
            <text class="floor-text" x="800" y="150" text-anchor="middle">top floor demo text</text>
        </a>
    </svg>
</div>
</body>


问:
Why is there a text node that contains the database record inside the html page?
so on my website, there is an unwanted text node that contains the record of my databse. There is no tag or element whatsoever on the html code, but somehow it exist.

I reckon it is caused by this line of code:

```<code><%= @workspace.items.each do |item| %>

<tr>
    <td><%= item.name %></td>
    <td><%= item.owner %></td>
    <td><%= item.quantity %></td>
    <td><%= item.details %></td>

    <td><%= link_to 'Edit Item', edit_workspace_item_path(@workspace,item) %></td>

    <td><%= link_to 'Delete', [item.workspace, item],
            method: :delete,
            data: { confirm: 'Are you sure?' } %></td>
</tr>
</code>```

The view.html.erb:

```<code><p>
    <strong>Name:</strong>
    <%= @workspace.name %>
</p>
<p>
    <strong>maxitem:</strong>
    <%= @workspace.max %>
</p>
<p>
    <strong>details:</strong>
    <%= @workspace.details %>
</p>
<p>
    <%= link_to 'Edit Phase', edit_workspace_path(@workspace) %>
</p>
<p><strong>Items</strong>
</p>
<p>
    <%= link_to 'Add Item', new_workspace_item_path(@workspace) %></br>
</p>
<table>
    <tr>
    <tr>
        <th><strong>Name</strong>
        <th><strong>Owner</strong>
        <th><strong>Quantity</strong>
        <th><strong>Details</strong>
    </tr>
    <%= render 'items/item' %>
</table>
<%= link_to 'Back to List of Phases', workspaces_path %>
</code>```

I don't know why this suddenly show up on my website
like this

答:
```<code><%= @workspace.items.each do |item| %>
</code>```

is the issue as <%= %> in ERB stands for "print this". Should be <% %> which will execute the Ruby code without rendering it.

Body:
so on my website, there is an unwanted text node that contains the record of my databse. There is no tag or element whatsoever on the html code, but somehow it exist.

I reckon it is caused by this line of code:

<%= @workspace.items.each do |item| %>

    <%= item.name %>
    <%= item.owner %>
    <%= item.quantity %>
    <%= item.details %>

    <%= link_to 'Edit Item', edit_workspace_item_path(@workspace,item) %>

    <%= link_to 'Delete', [item.workspace, item],
            method: :delete,
            data: { confirm: 'Are you sure?' } %>

The view.html.erb:

    Name:
    <%= @workspace.name %>

    maxitem:
    <%= @workspace.max %>

    details:
    <%= @workspace.details %>

    <%= link_to 'Edit Phase', edit_workspace_path(@workspace) %>

Items

    <%= link_to 'Add Item', new_workspace_item_path(@workspace) %>

        Name
        Owner
        Quantity
        Details

    <%= render 'items/item' %>

<%= link_to 'Back to List of Phases', workspaces_path %>

I don't know why this suddenly show up on my website
like this

Body:
<%= @workspace.items.each do |item| %>

is the issue as <%= %> in ERB stands for "print this". Should be <% %> which will execute the Ruby code without rendering it.


问:
How can I send an abstract argument to a web service?
I want to send an abstract object as an argument in a webservice method.

These are my classes:
The abstract class:

```<code>@XmlSeeAlso({Male.class, Female.class})

public abstract class Person {
    public String name;

    public void setName(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }
}
</code>```

The extending children:

```<code>@XmlRootElement(name = "person")
public class Male extends Person {

private boolean male;

/**
 * @return the male
 */
public boolean isMale() {
    return male;
}

/**
 * @param male the male to set
 */
public void setMale(boolean male) {
    this.male = male;
}
}
</code>```

and

```<code>@XmlRootElement(name = "person")
public class Female extends Person{
    private boolean female;

    /**
     * @return the female
     */
    public boolean isFemale() {
        return female;
    }

    /**
     * @param female the female to set
     */
    public void setFemale(boolean female) {
        this.female = female;
    }
}
</code>```

And this is my webservice Interface:

```<code>@WebService
public interface wsTest {
    @WebMethod
    int getInt();

    @WebMethod
    String getString(String s);

    @WebMethod
    Map<String, String> getMap(Map<String, String> map);

    @WebMethod
    String getMaleStr(Male male);

    @WebMethod
    String getIsMale(@WebParam(name = "param")Person person);
}
</code>```

My problem is that I want to send to the webMethod: getIsMale an object of type Male but the soap message doesn't send it of type Male thus stripping off its "male" member as follows:

The Request when sending:

```<code>Male male   = new Male();
male.name   = "Avi";
male.setMale(true);
System.out.println("Calling: getIsMale...");
System.out.println("Response is: " + ws.getIsMale(male));
</code>```

Is as follows:

```<code>[?xml version="1.0" standalone="yes"?]
[soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"]
  [soap:Body]
    [ns1:getIsMale xmlns:ns1="http://ws.xconnect.com/"]
      [ns1:param]
        [ns2:name xmlns:ns2="http://ws.xconnect.com"]Avi[/ns2:name]
      [/ns1:param]
    [/ns1:getIsMale]
  [/soap:Body]
[/soap:Envelope]
</code>```

答:
Honestly, I'm surprised JAXB doesn't throw an exception at startup.  You have two types defining the same XmlRootElement.

What you should do is have @XmlType(name="Male"), @XmlType(name="Female"), @XmlType(name="Person) on the classes.   That will setup the TYPE hierarchy correctly.  I wouldn't put an XmlRootElement on any of them.  Let CXF handle that based on the @WebParam's and such.

Body:
I want to send an abstract object as an argument in a webservice method.

These are my classes:
The abstract class:

@XmlSeeAlso({Male.class, Female.class})

public abstract class Person {
    public String name;

    public void setName(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }
}

The extending children:

@XmlRootElement(name = "person")
public class Male extends Person {

private boolean male;

/**
 * @return the male
 */
public boolean isMale() {
    return male;
}

/**
 * @param male the male to set
 */
public void setMale(boolean male) {
    this.male = male;
}
}

and

@XmlRootElement(name = "person")
public class Female extends Person{
    private boolean female;

    /**
     * @return the female
     */
    public boolean isFemale() {
        return female;
    }

    /**
     * @param female the female to set
     */
    public void setFemale(boolean female) {
        this.female = female;
    }
}

And this is my webservice Interface:

@WebService
public interface wsTest {
    @WebMethod
    int getInt();

    @WebMethod
    String getString(String s);

    @WebMethod
    Map<String, String> getMap(Map<String, String> map);

    @WebMethod
    String getMaleStr(Male male);

    @WebMethod
    String getIsMale(@WebParam(name = "param")Person person);
}

My problem is that I want to send to the webMethod: getIsMale an object of type Male but the soap message doesn't send it of type Male thus stripping off its "male" member as follows:

The Request when sending:

Male male   = new Male();
male.name   = "Avi";
male.setMale(true);
System.out.println("Calling: getIsMale...");
System.out.println("Response is: " + ws.getIsMale(male));

Is as follows:

[?xml version="1.0" standalone="yes"?]
[soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"]
  [soap:Body]
    [ns1:getIsMale xmlns:ns1="http://ws.xconnect.com/"]
      [ns1:param]
        [ns2:name xmlns:ns2="http://ws.xconnect.com"]Avi[/ns2:name]
      [/ns1:param]
    [/ns1:getIsMale]
  [/soap:Body]
[/soap:Envelope]


问:
Datastudio non calculated fields create
I connect datastudio with BigQuery.
I try to use user functions in BigQuery and past personal Query in datastudio, but user functions (CREATE TEMP FUNCTION) is not supported in datastudio.
Then I try use new non calculated field with categories, but something wrong:

```<code>CASE WHEN REGEXP_MATCH(campaign, '*-Moskva-*','*-moskva-*') THEN 'Москва' ELSE 'other' END
</code>```

Error: Invalid formula

答:
It could be achieved using either of the following CASE statements:

1) WHEN campaign Contains -Moskva- or -moskva- THEN Москва

CASE
  WHEN REGEXP_MATCH(campaign, ".*(-[Mm]oskva-).*") THEN "Москва"
  ELSE "other"
END
```

<p>2) WHEN <code>campaign</code> Contains <code>Moskva</code> or <code>moskva</code> THEN <code>Москва</code></p>

<pre class="lang-sql prettyprint-override"><code>CASE
  WHEN REGEXP_MATCH(campaign, ".*([Mm]oskva).*") THEN "Москва"
  ELSE "other"
END
</code>```

Created a Google Data Studio Report and GIF to elaborate:

Title: Datastudio non calculated fields create

Body:
I connect datastudio with BigQuery.
I try to use user functions in BigQuery and past personal Query in datastudio, but user functions (CREATE TEMP FUNCTION) is not supported in datastudio.
Then I try use new non calculated field with categories, but something wrong:

CASE WHEN REGEXP_MATCH(campaign, '*-Moskva-*','*-moskva-*') THEN 'Москва' ELSE 'other' END

Error: Invalid formula

Body:
It could be achieved using either of the following CASE statements:

1) WHEN campaign Contains -Moskva- or -moskva- THEN Москва

CASE
  WHEN REGEXP_MATCH(campaign, ".*(-[Mm]oskva-).*") THEN "Москва"
  ELSE "other"
END

2) WHEN campaign Contains Moskva or moskva THEN Москва

CASE
  WHEN REGEXP_MATCH(campaign, ".*([Mm]oskva).*") THEN "Москва"
  ELSE "other"
END

Created a Google Data Studio Report and GIF to elaborate:


问:
C#- Need to access JSON Data values from my Dynamic object
I have a json data as below -

```<code>{
    "request": {
        "type": "",
        "query": "",
        "language": "en",
        "unit": "m"
    },
    "location": {
        "name": "",
        "country": "",
        "region": "",
        "lat": "",
        "lon": "",
        "timezone_id": "Asia/Kolkata",
        "localtime": "2020-05-29 23:30",
        "localtime_epoch": 1590795000,
        "utc_offset": "5.50"
    },
    "current": {
        "observation_time": "06:00 PM",
        "temperature": 40,
        "weather_code": 116,
        "weather_icons": [
            ""
        ],
        "weather_descriptions": [
            "Partly cloudy"
        ],
        "wind_speed": 9,
        "wind_degree": 230,
        "wind_dir": "SW",
        "pressure": 1006,
        "precip": 0,
        "humidity": 26,
        "cloudcover": 25,
        "feelslike": 42,
        "uv_index": 1,
        "visibility": 6,
        "is_day": "no"
    },
    "forecast": {
        "2020-05-28": {
            "date": "2020-05-28",
            "date_epoch": 1590624000,
            "astro": {
                "sunrise": "05:41 AM",
                "sunset": "06:46 PM",
                "moonrise": "10:29 AM",
                "moonset": "11:48 PM",
                "moon_phase": "First Quarter",
                "moon_illumination": 39
            },
            "mintemp": 32,
            "maxtemp": 44,
            "avgtemp": 38,
            "totalsnow": 0,
            "sunhour": 13.1,
            "uv_index": 9
        }
    }
}
</code>```

First Three nodes("request","location","current") are binding properly but for "forecast" since the first node is a date time. I have written in the following way-

```<code>var dataObjects = JsonConvert.DeserializeObject<Location_Weather.Weather>(customerJsonString);
var dataObjects23 = JsonConvert.DeserializeObject<Dictionary<string, dynamic>> (customerJsonString);
dynamic forecast_details = dataObjects23["forecast"];
</code>```

This is my Model->

```<code>public class New_Location_Weather
    {

        [JsonProperty("request")]
        public Request Request { get; set; }

        [JsonProperty("location")]
        public Location Location { get; set; }

        [JsonProperty("current")]
        public Current Current { get; set; }

        [JsonProperty("forecast")]
        public Forecast Forecast { get; set; }
    }

    public partial class Current
    {
        [JsonProperty("observation_time")]
        public string ObservationTime { get; set; }

        [JsonProperty("temperature")]
        public long Temperature { get; set; }

        [JsonProperty("weather_code")]
        public long WeatherCode { get; set; }

        [JsonProperty("weather_icons")]
        public Uri[] WeatherIcons { get; set; }

        [JsonProperty("weather_descriptions")]
        public string[] WeatherDescriptions { get; set; }

        [JsonProperty("wind_speed")]
        public long WindSpeed { get; set; }

        [JsonProperty("wind_degree")]
        public long WindDegree { get; set; }

        [JsonProperty("wind_dir")]
        public string WindDir { get; set; }

        [JsonProperty("pressure")]
        public long Pressure { get; set; }

        [JsonProperty("precip")]
        public long Precip { get; set; }

        [JsonProperty("humidity")]
        public long Humidity { get; set; }

        [JsonProperty("cloudcover")]
        public long Cloudcover { get; set; }

        [JsonProperty("feelslike")]
        public long Feelslike { get; set; }

        [JsonProperty("uv_index")]
        public long UvIndex { get; set; }

        [JsonProperty("visibility")]
        public long Visibility { get; set; }

        [JsonProperty("is_day")]
        public string IsDay { get; set; }
    }

    public partial class Forecast
    {
        [JsonProperty("2020-05-28")]
        public The20200528 The20200528 { get; set; }
    }

    public partial class The20200528
    {
        [JsonProperty("date")]
        public DateTimeOffset Date { get; set; }

        [JsonProperty("date_epoch")]
        public long DateEpoch { get; set; }

        [JsonProperty("astro")]
        public Astro Astro { get; set; }

        [JsonProperty("mintemp")]
        public long Mintemp { get; set; }

        [JsonProperty("maxtemp")]
        public long Maxtemp { get; set; }

        [JsonProperty("avgtemp")]
        public long Avgtemp { get; set; }

        [JsonProperty("totalsnow")]
        public long Totalsnow { get; set; }

        [JsonProperty("sunhour")]
        public double Sunhour { get; set; }

        [JsonProperty("uv_index")]
        public long UvIndex { get; set; }
    }

    public partial class Astro
    {
        [JsonProperty("sunrise")]
        public string Sunrise { get; set; }

        [JsonProperty("sunset")]
        public string Sunset { get; set; }

        [JsonProperty("moonrise")]
        public string Moonrise { get; set; }

        [JsonProperty("moonset")]
        public string Moonset { get; set; }

        [JsonProperty("moon_phase")]
        public string MoonPhase { get; set; }

        [JsonProperty("moon_illumination")]
        public long MoonIllumination { get; set; }
    }

    public partial class Location
    {
        [JsonProperty("name")]
        public string Name { get; set; }

        [JsonProperty("country")]
        public string Country { get; set; }

        [JsonProperty("region")]
        public string Region { get; set; }

        [JsonProperty("lat")]
        public string Lat { get; set; }

        [JsonProperty("lon")]
        public string Lon { get; set; }

        [JsonProperty("timezone_id")]
        public string TimezoneId { get; set; }

        [JsonProperty("localtime")]
        public string Localtime { get; set; }

        [JsonProperty("localtime_epoch")]
        public long LocaltimeEpoch { get; set; }

        [JsonProperty("utc_offset")]
        public string UtcOffset { get; set; }
    }

    public partial class Request
    {
        [JsonProperty("type")]
        public string Type { get; set; }

        [JsonProperty("query")]
        public string Query { get; set; }

        [JsonProperty("language")]
        public string Language { get; set; }

        [JsonProperty("unit")]
        public string Unit { get; set; }
    }
</code>```

Now issue is I am not able to get the values. I need some guidance on how to get this values from the dynamic object which is forecast_details into my C# code.
Below is the screenshot of the values which I need to access them in my c# code

While debugging the dynamic object I found the values in my result view. But I am not sure how to access those values in my c# code.

Please do let me know on how to get these values from my C# dynamic object(forecast_details).

答:
Look at this question, there is two answers that can help you.

How to add properties at runtime to JSON (C#)

You can parse your forecast json to JObject, and get all values from it with foreach.

Body:
I have a json data as below -

{
    "request": {
        "type": "",
        "query": "",
        "language": "en",
        "unit": "m"
    },
    "location": {
        "name": "",
        "country": "",
        "region": "",
        "lat": "",
        "lon": "",
        "timezone_id": "Asia/Kolkata",
        "localtime": "2020-05-29 23:30",
        "localtime_epoch": 1590795000,
        "utc_offset": "5.50"
    },
    "current": {
        "observation_time": "06:00 PM",
        "temperature": 40,
        "weather_code": 116,
        "weather_icons": [
            ""
        ],
        "weather_descriptions": [
            "Partly cloudy"
        ],
        "wind_speed": 9,
        "wind_degree": 230,
        "wind_dir": "SW",
        "pressure": 1006,
        "precip": 0,
        "humidity": 26,
        "cloudcover": 25,
        "feelslike": 42,
        "uv_index": 1,
        "visibility": 6,
        "is_day": "no"
    },
    "forecast": {
        "2020-05-28": {
            "date": "2020-05-28",
            "date_epoch": 1590624000,
            "astro": {
                "sunrise": "05:41 AM",
                "sunset": "06:46 PM",
                "moonrise": "10:29 AM",
                "moonset": "11:48 PM",
                "moon_phase": "First Quarter",
                "moon_illumination": 39
            },
            "mintemp": 32,
            "maxtemp": 44,
            "avgtemp": 38,
            "totalsnow": 0,
            "sunhour": 13.1,
            "uv_index": 9
        }
    }
}

First Three nodes("request","location","current") are binding properly but for "forecast" since the first node is a date time. I have written in the following way-

var dataObjects = JsonConvert.DeserializeObject<Location_Weather.Weather>(customerJsonString);
var dataObjects23 = JsonConvert.DeserializeObject<Dictionary<string, dynamic>> (customerJsonString);
dynamic forecast_details = dataObjects23["forecast"];

This is my Model->

public class New_Location_Weather
    {

        [JsonProperty("request")]
        public Request Request { get; set; }

        [JsonProperty("location")]
        public Location Location { get; set; }

        [JsonProperty("current")]
        public Current Current { get; set; }

        [JsonProperty("forecast")]
        public Forecast Forecast { get; set; }
    }

    public partial class Current
    {
        [JsonProperty("observation_time")]
        public string ObservationTime { get; set; }

        [JsonProperty("temperature")]
        public long Temperature { get; set; }

        [JsonProperty("weather_code")]
        public long WeatherCode { get; set; }

        [JsonProperty("weather_icons")]
        public Uri[] WeatherIcons { get; set; }

        [JsonProperty("weather_descriptions")]
        public string[] WeatherDescriptions { get; set; }

        [JsonProperty("wind_speed")]
        public long WindSpeed { get; set; }

        [JsonProperty("wind_degree")]
        public long WindDegree { get; set; }

        [JsonProperty("wind_dir")]
        public string WindDir { get; set; }

        [JsonProperty("pressure")]
        public long Pressure { get; set; }

        [JsonProperty("precip")]
        public long Precip { get; set; }

        [JsonProperty("humidity")]
        public long Humidity { get; set; }

        [JsonProperty("cloudcover")]
        public long Cloudcover { get; set; }

        [JsonProperty("feelslike")]
        public long Feelslike { get; set; }

        [JsonProperty("uv_index")]
        public long UvIndex { get; set; }

        [JsonProperty("visibility")]
        public long Visibility { get; set; }

        [JsonProperty("is_day")]
        public string IsDay { get; set; }
    }

    public partial class Forecast
    {
        [JsonProperty("2020-05-28")]
        public The20200528 The20200528 { get; set; }
    }

    public partial class The20200528
    {
        [JsonProperty("date")]
        public DateTimeOffset Date { get; set; }

        [JsonProperty("date_epoch")]
        public long DateEpoch { get; set; }

        [JsonProperty("astro")]
        public Astro Astro { get; set; }

        [JsonProperty("mintemp")]
        public long Mintemp { get; set; }

        [JsonProperty("maxtemp")]
        public long Maxtemp { get; set; }

        [JsonProperty("avgtemp")]
        public long Avgtemp { get; set; }

        [JsonProperty("totalsnow")]
        public long Totalsnow { get; set; }

        [JsonProperty("sunhour")]
        public double Sunhour { get; set; }

        [JsonProperty("uv_index")]
        public long UvIndex { get; set; }
    }

    public partial class Astro
    {
        [JsonProperty("sunrise")]
        public string Sunrise { get; set; }

        [JsonProperty("sunset")]
        public string Sunset { get; set; }

        [JsonProperty("moonrise")]
        public string Moonrise { get; set; }

        [JsonProperty("moonset")]
        public string Moonset { get; set; }

        [JsonProperty("moon_phase")]
        public string MoonPhase { get; set; }

        [JsonProperty("moon_illumination")]
        public long MoonIllumination { get; set; }
    }

    public partial class Location
    {
        [JsonProperty("name")]
        public string Name { get; set; }

        [JsonProperty("country")]
        public string Country { get; set; }

        [JsonProperty("region")]
        public string Region { get; set; }

        [JsonProperty("lat")]
        public string Lat { get; set; }

        [JsonProperty("lon")]
        public string Lon { get; set; }

        [JsonProperty("timezone_id")]
        public string TimezoneId { get; set; }

        [JsonProperty("localtime")]
        public string Localtime { get; set; }

        [JsonProperty("localtime_epoch")]
        public long LocaltimeEpoch { get; set; }

        [JsonProperty("utc_offset")]
        public string UtcOffset { get; set; }
    }

    public partial class Request
    {
        [JsonProperty("type")]
        public string Type { get; set; }

        [JsonProperty("query")]
        public string Query { get; set; }

        [JsonProperty("language")]
        public string Language { get; set; }

        [JsonProperty("unit")]
        public string Unit { get; set; }
    }

Now issue is I am not able to get the values. I need some guidance on how to get this values from the dynamic object which is forecast_details into my C# code.
Below is the screenshot of the values which I need to access them in my c# code

While debugging the dynamic object I found the values in my result view. But I am not sure how to access those values in my c# code.

Please do let me know on how to get these values from my C# dynamic object(forecast_details).


答:
you can try any() and all() funcs. In your case

if any(c==l for l in ['a','e','o','w']):
    # do stuff
```

Title: Syntax shorthand for comparison operator in python

Body:
I have an if statement that wants to check:

if c=="a" or c=="e" or c=="i" or c=="o" or c=="w":

Is there a way to write this more efficiently so that I don't have to repeat c=="x" so much.
Something like if c=="a" or "e" or "i" or "o" or "w":


问:
How to merge date and time in Pandas?
I am a beginner of Pandas, so my question is very basic. I have a dataset, which has seperate columns for date and time as following

```<code>    Date        Time    Ooen    High    Low     Close   Vol
0   2000.12.22  12:00   0.91810 0.92620 0.91650 0.92320 2244
1   2000.12.22  16:00   0.92260 0.92520 0.92220 0.92310 1688
2   2000.12.22  20:00   0.92300 0.92580 0.92260 0.92420 955
3   2000.12.23  00:01   0.92410 0.92450 0.92270 0.92320 168
4   2000.12.25  00:00   0.92300 0.92460 0.92300 0.92420 260
</code>```

The type of Date and Time are

```<code>type(df['Date'])
pandas.core.series.Series

type(df['Time'])
pandas.core.series.Series
</code>```

I don't know how to merge them into a timestamp like

```<code>'2015-07-04 00:00:00'
</code>```

Could anyone please help me?

答:
try given below code.

df['datetime'] = df[df.columns[1:]].apply(lambda x: ','.join(x.dropna().astype(str)),axis=1)

Title: How to merge date and time in Pandas?

Body:
I am a beginner of Pandas, so my question is very basic. I have a dataset, which has seperate columns for date and time as following

    Date        Time    Ooen    High    Low     Close   Vol
0   2000.12.22  12:00   0.91810 0.92620 0.91650 0.92320 2244
1   2000.12.22  16:00   0.92260 0.92520 0.92220 0.92310 1688
2   2000.12.22  20:00   0.92300 0.92580 0.92260 0.92420 955
3   2000.12.23  00:01   0.92410 0.92450 0.92270 0.92320 168
4   2000.12.25  00:00   0.92300 0.92460 0.92300 0.92420 260

The type of Date and Time are

type(df['Date'])
pandas.core.series.Series

type(df['Time'])
pandas.core.series.Series

I don't know how to merge them into a timestamp like

'2015-07-04 00:00:00'

Could anyone please help me?


问:
Cannot install apk file /run app after add admob library in flutter project
Please help me resolve the problem, I've completed my flutter project without admob  library. It run well. Then, I add admob library as below:

Of course, I've tried some admob versions but they are the same problem. I stuck on installing apk file.

installing apk file is not able to finish. If I remove admob library, it works well again. How can I fix the problem ?

Thanks in advance!!!

答:
Look for your MainActivity package and your AndroidManifest package info. They need to be the same. In MainActivity it is the very first line in the file usually. In android manifest it's the second line of the file usually.

In my case, I changed the name of the app and MainActivity package changed names too.  After changing it to reflect the exactly same of AndroidManifest, it worked fine.


问:
How to store a list in a column of a database table
So, per Mehrdad's answer to a related question, I get it that a "proper" database table column doesn't store a list.  Rather, you should create another table that effectively holds the elements of said list and then link to it directly or through a junction table.  However, the type of list I want to create will be composed of unique items (unlike the linked question's fruit example).  Furthermore, the items in my list are explicitly sorted - which means that if I stored the elements in another table, I'd have to sort them every time I accessed them.  Finally, the list is basically atomic in that any time I wish to access the list, I will want to access the entire list rather than just a piece of it - so it seems silly to have to issue a database query to gather together pieces of the list.

AKX's solution (linked above) is to serialize the list and store it in a binary column.  But this also seems inconvenient because it means that I have to worry about serialization and deserialization.

Is there any better solution?  If there is no better solution, then why?  It seems that this problem should come up from time to time.

... just a little more info to let you know where I'm coming from.  As soon as I had just begun understanding SQL and databases in general, I was turned on to LINQ to SQL, and so now I'm a little spoiled because I expect to deal with my programming object model without having to think about how the objects are queried or stored in the database.

Thanks All!

John

UPDATE:  So in the first flurry of answers I'm getting, I see "you can go the CSV/XML route... but DON'T!".  So now I'm looking for explanations of why.  Point me to some good references.

Also, to give you a better idea of what I'm up to:  In my database I have a Function table that will have a list of (x,y) pairs.  (The table will also have other information that is of no consequence for our discussion.)  I will never need to see part of the list of (x,y) pairs.  Rather, I will take all of them and plot them on the screen.  I will allow the user to drag the nodes around to change the values occasionally or add more values to the plot.

答:
Many SQL databases allow a table to contain a subtable as a component.  The usual method is to allow the domain of one of the columns to be a table.  This is in addition to using some convention like CSV to encode the substructure in ways unknown to the DBMS.

When Ed Codd was developing the relational model in 1969-1970, he specifically defined a normal form that would disallow this kind of nesting of tables.  Normal form was later called First Normal Form.  He then went on to show that for every database, there is a database in first normal form that expresses the same information.

Why bother with this?  Well, databases in first normal form permit keyed access to all data.  If you provide a table name,  a key value into that table,  and a column name,   the database will contain at most one cell containing one item of data.

If you allow a cell to contain a list or a table or any other collection, now you can't provide keyed access to the sub items, without completely reworking the idea of a key.

Keyed access to all data is fundamental to the relational model.  Without this concept,  the model isn't relational.  As to why the relational model is a good idea, and what might be the limitations of that good idea, you have to look at the 50 years worth of accumulated experience with the relational model.


问:
Using Any data type in Scala spark
I am writing a generic spark job where I do not know the aggregate keys beforehand. The intention is that a user can select any random column and the job will start creating aggregates based on that. Lets take a small sample for example

```<code>Col_A Int
Col_B String
Col_C Long
</code>```

A user can select any of them in the group by clause and select a measure. This job has to now run as a stream.

For implementing this, created an object

```<code>class AggregateValue(var value: Any)
</code>```

This object will hold the value of the key. Since I do not know the type, I am keeping as Any. Now, I want to understand if Any is the best option to do this. Is there any disadvantage of using Any as the type in terms of performance etc.

Also, I understand type safety is a problem with Any. Do you guys expect any performance impact or other impact due to this.
Any help is appreciated

答:
If you google here and elsewhere you will find that UDFs cannot use Any nor a map.

Spark SQL and DFs and DSs do not support Any in a schema. So, it is not a good idea.

I have encountered an Any on occasion and it cannot really be solved.

In short: Any type is a signal to look for other ways to do things.

Title: Using Any data type in Scala spark

Body:
I am writing a generic spark job where I do not know the aggregate keys beforehand. The intention is that a user can select any random column and the job will start creating aggregates based on that. Lets take a small sample for example

Col_A Int
Col_B String
Col_C Long

A user can select any of them in the group by clause and select a measure. This job has to now run as a stream.

For implementing this, created an object

class AggregateValue(var value: Any)

This object will hold the value of the key. Since I do not know the type, I am keeping as Any. Now, I want to understand if Any is the best option to do this. Is there any disadvantage of using Any as the type in terms of performance etc.

Also, I understand type safety is a problem with Any. Do you guys expect any performance impact or other impact due to this.
Any help is appreciated


问:
Overloading [] and + simultaneously
I have class which has array inside.

Suppose we have class A and array12 inside it.

All I need to do is A[index]+value so I suppose add to array12[index] that value.

```<code>int &operator[](int index)
{
    return array12[index];
}
</code>```

But what I need write when I overload operator +?

How do I know element index when overloading +?

答:
You can't directly overload an operator to solve this as operator+ takes only argument. This is not possible:

```<code>void operator+(int idx, int num) // error: 2 parameters
{
    a[idx] += num;
}
</code>```

One way to solve this would be to use a member currentIndex and a setter function. E.g:

```<code>void setCurrentIndex(int idx)
{
   currentIndex = idx;
}

void operator+(int el)
{
    array12[currentIndex] += el;
}

//usage:
A a;
a.setCurrentIndex(0);
a + 1;
</code>```

As a side note, if you have operator[] defined, you can directly do addition:

```<code>A a;
a[0] += 10;
</code>```

This will need some extra code to make it work if the underlying type is complex.

Title: Overloading [] and + simultaneously

Body:
I have class which has array inside.

Suppose we have class A and array12 inside it.

All I need to do is A[index]+value so I suppose add to array12[index] that value.

int &operator[](int index)
{
    return array12[index];
}

But what I need write when I overload operator +?

How do I know element index when overloading +?

Body:
You can't directly overload an operator to solve this as operator+ takes only argument. This is not possible:

void operator+(int idx, int num) // error: 2 parameters
{
    a[idx] += num;
}

One way to solve this would be to use a member currentIndex and a setter function. E.g:

void setCurrentIndex(int idx)
{
   currentIndex = idx;
}

void operator+(int el)
{
    array12[currentIndex] += el;
}

//usage:
A a;
a.setCurrentIndex(0);
a + 1;

As a side note, if you have operator[] defined, you can directly do addition:

A a;
a[0] += 10;

This will need some extra code to make it work if the underlying type is complex.


问:
How to have Text with Icon in center Flutter?
I am using a package fab_circular_menu, That package is for an animated floating action button which opens up a circular menu. within it I want a widget as a menu item such that there is an icon and a text below. the icon is centered with text.

e.g.

How can I achieve this, as of now I am using the code below but it does not work well with different screen size.

```<code>FlatButton(
 splashColor: Colors.transparent,
 highlightColor: Colors.transparent,
 shape: RoundedRectangleBorder(
        borderRadius: BorderRadius.circular(100),
 ),
 padding: EdgeInsets.only(bottom: 15),
 onPressed: () async {
   await _auth.signOut().then((value) {
   Navigator.of(context).popUntil((route) => route.isFirst);
   });
 },
 child: Stack(
       overflow: Overflow.visible,
       children: <Widget>[
                Icon(Icons.power_settings_new),
                  Positioned(
                    bottom: -12,
                    right: -10,
                    child: Text('Logout'),
                  ),
                ],
      ),
 ),
</code>```

答:
Another Solution which could use in many ways</p>

```<code>   Wrap(
        direction: Axis.vertical,
          crossAxisAlignment: WrapCrossAlignment.center,
        children: <Widget>[
          Icon(Icons.power_settings_new),
          Text('Logout'),
        ],
      ),
</code>```

Body:
I am using a package fab_circular_menu, That package is for an animated floating action button which opens up a circular menu. within it I want a widget as a menu item such that there is an icon and a text below. the icon is centered with text.

e.g.

How can I achieve this, as of now I am using the code below but it does not work well with different screen size.

FlatButton(
 splashColor: Colors.transparent,
 highlightColor: Colors.transparent,
 shape: RoundedRectangleBorder(
        borderRadius: BorderRadius.circular(100),
 ),
 padding: EdgeInsets.only(bottom: 15),
 onPressed: () async {
   await _auth.signOut().then((value) {
   Navigator.of(context).popUntil((route) => route.isFirst);
   });
 },
 child: Stack(
       overflow: Overflow.visible,
       children: <Widget>[
                Icon(Icons.power_settings_new),
                  Positioned(
                    bottom: -12,
                    right: -10,
                    child: Text('Logout'),
                  ),
                ],
      ),
 ),

Body:
Another Solution which could use in many ways

   Wrap(
        direction: Axis.vertical,
          crossAxisAlignment: WrapCrossAlignment.center,
        children: <Widget>[
          Icon(Icons.power_settings_new),
          Text('Logout'),
        ],
      ),


问:
How do I correct the "Command output already redirected" error
Sorry if this is a newbie question. But I have been experimenting with gcloud Text to Speech API and tring to get the output saved as a text file.

I did that by adding | out-file result.txt to the final line of instructions below.It worked once but since that it just returns an error that output is already redirected.

Any ideas as how to solve this?

```<code>$cred = gcloud auth application-default print-access-token
>> $headers = @{ "Authorization" = "Bearer $cred" }
>>
>> Invoke-WebRequest `
>>   -Method POST `
>>   -Headers $headers `
>>   -ContentType: "application/json; charset=utf-8" `
>>   -InFile f:\request.json `
>>   -Uri "https://texttospeech.googleapis.com/v1/text:synthesize" | Select-Object -Expand Content

//**Errors:**
At line:6 char:1
+ >>   -Headers $headers `
+ ~~~~~~~~~~~~~
The output stream for this command is already redirected.
At line:7 char:1
+ >>   -ContentType: "application/json; charset=utf-8" `
+ ~~~~~~~~~~~~~~~~~~
The output stream for this command is already redirected.
At line:8 char:1
+ >>   -InFile f:\request.json `
+ ~~~~~~~~~~~~
The output stream for this command is already redirected.
At line:9 char:1
+ >>   -Uri "https://texttospeech.googleapis.com/v1/text:synthesize" |  ...
+ ~~~~~~~~~
The output stream for this command is already redirected.
    + CategoryInfo          : ParserError: (:) [], ParentContainsErrorRecordException
    + FullyQualifiedErrorId : StreamAlreadyRedirected
</code>```

答:
Thanks 7cc - this was the answer:
Remove >> in the beginning of each line. It seems you have copied the command from the console window including Continuation Prompts. And they were interpreted as redirect commands.</p>

Body:
Sorry if this is a newbie question. But I have been experimenting with gcloud Text to Speech API and tring to get the output saved as a text file.

I did that by adding | out-file result.txt to the final line of instructions below.It worked once but since that it just returns an error that output is already redirected.

Any ideas as how to solve this?

$cred = gcloud auth application-default print-access-token
>> $headers = @{ "Authorization" = "Bearer $cred" }
>>
>> Invoke-WebRequest `
>>   -Method POST `
>>   -Headers $headers `
>>   -ContentType: "application/json; charset=utf-8" `
>>   -InFile f:\request.json `
>>   -Uri "https://texttospeech.googleapis.com/v1/text:synthesize" | Select-Object -Expand Content

//**Errors:**
At line:6 char:1
+ >>   -Headers $headers `
+ ~~~~~~~~~~~~~
The output stream for this command is already redirected.
At line:7 char:1
+ >>   -ContentType: "application/json; charset=utf-8" `
+ ~~~~~~~~~~~~~~~~~~
The output stream for this command is already redirected.
At line:8 char:1
+ >>   -InFile f:\request.json `
+ ~~~~~~~~~~~~
The output stream for this command is already redirected.
At line:9 char:1
+ >>   -Uri "https://texttospeech.googleapis.com/v1/text:synthesize" |  ...
+ ~~~~~~~~~
The output stream for this command is already redirected.
    + CategoryInfo          : ParserError: (:) [], ParentContainsErrorRecordException
    + FullyQualifiedErrorId : StreamAlreadyRedirected


问:
Photo stitching/panorama API/DLL/Library anyone?
For a special project, I need to find an API/DLL/Library to help me create a big image using parts of this image. For example, if someone take 4 pictures representing the 360 degrees around him, he will be able to create one big image (panorama) by stitching the 4 images together using special algorithm that recognize some patterns.

I know how to do this in Photoshop and I know there are a lot of programs that to this on the internet. But I want one that will be controlled by programming. This can be in C, C++, or .NET. If you have something in another language, you can tell answer too, I may consider to write a wrapper.

答:
As far as i know Hugin is best which comes with source for both mac and windows

http://hugin.sourceforge.net/

It's using one of the best stitching algorithm which many industry big names in this field use it

Also Take a look at GIMP

and pano12 from panotools which is core of ptstitcher

And

For preview your pano files use devalvr

http://www.devalvr.com/

u can extract installer and use ocx within installer it's fastest for stand-alone projects with many parameters , commands , methods , etc


问:
In iOS Swift How can I convert the time from the format "Tue Aug 27 2019 07:01:59 GMT+0530 (India Standard Time)" to YYYY-MM-DD
From backend i am getting date as "Tue Aug 27 2019 07:01:59 GMT+0530 (India Standard Time)".
In iOS Swift, How can I convert the time from the format "Tue Aug 27 2019 07:01:59 GMT+0530 (India Standard Time)" to YYYY-MM-DD.</p>

答:
Removed 'GMT+0530 (India Standard Time)' from date string what are you getting from server
then use this - </p>

```<code> let date = self.convertDateStringToFormatString1(dateString:
 "Tue Aug 27 2019 07:01:59", fromFormat: "E MMM dd  yyyy hh:mm:ss" , toFormat:
 "YYYY-MM-dd")

 func convertDateStringToFormatString1(dateString:String, fromFormat : String,
 toFormat : String) -> String {
        let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = fromFormat
        let date = dateFormatter.date(from: dateString)
        dateFormatter.dateFormat = toFormat
        dateFormatter.locale = NSLocale.current
        return dateFormatter.string(from: date!)
    }
</code>```

Body:
Removed 'GMT+0530 (India Standard Time)' from date string what are you getting from server
then use this -

 let date = self.convertDateStringToFormatString1(dateString:
 "Tue Aug 27 2019 07:01:59", fromFormat: "E MMM dd  yyyy hh:mm:ss" , toFormat:
 "YYYY-MM-dd")

 func convertDateStringToFormatString1(dateString:String, fromFormat : String,
 toFormat : String) -> String {
        let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = fromFormat
        let date = dateFormatter.date(from: dateString)
        dateFormatter.dateFormat = toFormat
        dateFormatter.locale = NSLocale.current
        return dateFormatter.string(from: date!)
    }