问:
In JavaScript, why pass the context as an argument to a function call when the context is already determined by who calls it?
A read an article on Medium called

You Must Understand These 14 JavaScript Functions by bitfish

In the article the author writes about functions a JavaScript developer must know or understand when/before a Job Interview - for position as a JavaScript developer.

In the examples there is a constant usage of passing in a context as an optional argument. Unfortunately the author does not go into details on why we would pass a context argument like here:

```<code>mappedArr[i] = fn.call(context, arr[i], i, this);
</code>```

My question is "In JavaScript, why pass the context as an argument to a function call when the context is already determined by who calls it?"

Under what condition is it useful to have that context available (another context)?

Here is the code listed below:

```<code>let selfMap = function(fn, context) {

   let arr = Array.prototype.slice.call(this);
   let mappedArr = Array();
   for(let i=0; i < arr.length; i++) {

     if (! arr.hasOwnProperty(i)) continue;

     let info = [];
     info.push({ "context" : context } );
     info.push({ "arr[i]" : arr[i] } );
     info.push({ "i" : i } );
     info.push({ "this" : this } );
     console.log(info);

     mappedArr[i] = fn.call(context, arr[i], i, this);

   }
   return mappedArr;

 };
</code>```

And then call it using:

```<code>Array.prototype. selfMap = selfMap;
[1,2,3].myMap(n => n * 2);
</code>```

Why would one provide a context as a second argument to myMap? I think there may be a JavaScript Design Pattern for this, but at this time I could not find any references, due to all the debris of search results on Google that are unrelated to my search.

I did write a function and passed in the context as a second argument but I am not sure, though I could come up with my own thoughts, what is the main reason for doing this?

Here is my example of using it:

```<code>[1,2,3].selfMap((n, o, p) => {

     let info = [];
     info.push({ "n" : n } );
     info.push({ "o" : o } );
     info.push({ "p" : p } );
     info.push({ "this" : this } );
     console.log(info)
     return n * 2;

});
</code>```

Could pass this or window or {}

Context would be equal to the current context of where we called the method from

```<code>[1,2,3].selfMap((n, o, context) => {

         let info = [];
         info.push({ "n" : n } );
         info.push({ "o" : o } );
         info.push({ "context" : context } );
         info.push({ "this" : this } );
         console.log(info)
         return n * 2;

}, this);
</code>```

Window as context argument

```<code>[1,2,3].selfMap((n, o, context) => {

     let info = [];
     info.push({ "n" : n } );
     info.push({ "o" : o } );
     info.push({ "context" : context } );
     info.push({ "this" : this } );
     console.log(info)
     return n * 2;

}, window);
</code>```

And we could use a custom object

```<code>[1,2,3].selfMap((n, o, context) => {

     let info = [];
     info.push({ "n" : n } );
     info.push({ "o" : o } );
     info.push({ "context" : context } );
     info.push({ "this" : this } );
     console.log(info)
     return n * 2;

}, { something: 1 });
</code>```

So, I know that a context can be passed, but I don't know why I might want to pass in a context.

Please with-in your answer provide not only an explanation but an example(s) to clarify your explanation.

Thank You

答:
There are situation in which the context (this) can be overshadow by the caller, but one might need to refer a different context altogether. In that case, it would be very helpful if you pass the context as argument.

Please consider the following example

class DomManipulation() {

    constructor() {
      this.someValue = "someValue"

      this.registerEvent();
    }

    eventListener() {
      console.log(this);  // can you guess the context of this here
      console.log(this.someValue); // answer is undefined. Since this is pointing to `#oneDomElement` dom here. so access to class DomManipulation variable is overshadowed
    }

    registerEvent() {
      document.querySelector("#oneDomElement").addEventListener('click', this.eventListener);
    }
 }```
<pre class="snippet-code-html lang-html prettyprint-override"><code>    <div id="oneDomElement">Hello</div></code>```

As you can see in the above example, the value of this is over-shadowed by the Dom element since we have setup a listener for the click event. Now it not possible to access the DomManipulation class member variables (ie. someValue)

So, in-order to overcome the problem, we can do the following

```<code>eventListener(event, context) {
      console.log(this); // now this will point to DomManipulation class
      console.log(this.someValue);  // someValue
      // also
      console.log(context) // you can also use DOM `#oneDomElement` context here
}

registerEvent() {
       const self = this;
      document.querySelector("#oneDomElement").addEventListener('click',  (event) => {
           self.eventListener.call(self, event, this);
      });
}
</code>```

With the above solution, you could access to both the context here,
 1. this will point to DomManipulation class
 2.  context will point to the #oneDomElement DOM element.

Body:
A read an article on Medium called

You Must Understand These 14 JavaScript Functions by bitfish

In the article the author writes about functions a JavaScript developer must know or understand when/before a Job Interview - for position as a JavaScript developer.

In the examples there is a constant usage of passing in a context as an optional argument. Unfortunately the author does not go into details on why we would pass a context argument like here:

mappedArr[i] = fn.call(context, arr[i], i, this);

My question is "In JavaScript, why pass the context as an argument to a function call when the context is already determined by who calls it?"

Under what condition is it useful to have that context available (another context)?

Here is the code listed below:

let selfMap = function(fn, context) {

   let arr = Array.prototype.slice.call(this);
   let mappedArr = Array();
   for(let i=0; i < arr.length; i++) {

     if (! arr.hasOwnProperty(i)) continue;

     let info = [];
     info.push({ "context" : context } );
     info.push({ "arr[i]" : arr[i] } );
     info.push({ "i" : i } );
     info.push({ "this" : this } );
     console.log(info);

     mappedArr[i] = fn.call(context, arr[i], i, this);

   }
   return mappedArr;

 };

And then call it using:

Array.prototype. selfMap = selfMap;
[1,2,3].myMap(n => n * 2);

Why would one provide a context as a second argument to myMap? I think there may be a JavaScript Design Pattern for this, but at this time I could not find any references, due to all the debris of search results on Google that are unrelated to my search.

I did write a function and passed in the context as a second argument but I am not sure, though I could come up with my own thoughts, what is the main reason for doing this?

Here is my example of using it:

[1,2,3].selfMap((n, o, p) => {

     let info = [];
     info.push({ "n" : n } );
     info.push({ "o" : o } );
     info.push({ "p" : p } );
     info.push({ "this" : this } );
     console.log(info)
     return n * 2;

});

Could pass this or window or {}

Context would be equal to the current context of where we called the method from

[1,2,3].selfMap((n, o, context) => {

         let info = [];
         info.push({ "n" : n } );
         info.push({ "o" : o } );
         info.push({ "context" : context } );
         info.push({ "this" : this } );
         console.log(info)
         return n * 2;

}, this);

Window as context argument

[1,2,3].selfMap((n, o, context) => {

     let info = [];
     info.push({ "n" : n } );
     info.push({ "o" : o } );
     info.push({ "context" : context } );
     info.push({ "this" : this } );
     console.log(info)
     return n * 2;

}, window);

And we could use a custom object

[1,2,3].selfMap((n, o, context) => {

     let info = [];
     info.push({ "n" : n } );
     info.push({ "o" : o } );
     info.push({ "context" : context } );
     info.push({ "this" : this } );
     console.log(info)
     return n * 2;

}, { something: 1 });

So, I know that a context can be passed, but I don't know why I might want to pass in a context.

Please with-in your answer provide not only an explanation but an example(s) to clarify your explanation.

Thank You

Body:
There are situation in which the context (this) can be overshadow by the caller, but one might need to refer a different context altogether. In that case, it would be very helpful if you pass the context as argument.

Please consider the following example

class DomManipulation() {

    constructor() {
      this.someValue = "someValue"

      this.registerEvent();
    }

    eventListener() {
      console.log(this);  // can you guess the context of this here
      console.log(this.someValue); // answer is undefined. Since this is pointing to `#oneDomElement` dom here. so access to class DomManipulation variable is overshadowed
    }

    registerEvent() {
      document.querySelector("#oneDomElement").addEventListener('click', this.eventListener);
    }
 }

    <div id="oneDomElement">Hello</div>

As you can see in the above example, the value of this is over-shadowed by the Dom element since we have setup a listener for the click event. Now it not possible to access the DomManipulation class member variables (ie. someValue)

So, in-order to overcome the problem, we can do the following

eventListener(event, context) {
      console.log(this); // now this will point to DomManipulation class
      console.log(this.someValue);  // someValue
      // also
      console.log(context) // you can also use DOM `#oneDomElement` context here
}

registerEvent() {
       const self = this;
      document.querySelector("#oneDomElement").addEventListener('click',  (event) => {
           self.eventListener.call(self, event, this);
      });
}

With the above solution, you could access to both the context here,
 1. this will point to DomManipulation class
 2.  context will point to the #oneDomElement DOM element.


来源: stackexchange

问:
Print a type's name at compile time without aborting compilation?
In this question:

Print template typename at compile time

we have a few suggestions regarding how to get typical C++ compilers to print a type's name, at compile time. However, they rely on triggering a compilation error.

My question: Can I get the C++ compiler to print the name of a type without stopping compilation?

In general the answer is "probably not", because a valid program can be compiled into its target object without printing anything anywhere, so I'm asking specifically about GCC and clang, with possible use of preprocessor directives, compiler builtins, or any compiler-specific trick.

Notes:

Obviously, the challenge is printing types behind using/typedef statements, template parameter values, variadic templates etc. If the type is available explicitly you could just use something like #message "my type is unsigned long long" (as @NutCracker suggested). But that's not what the question is about.

Answers relying on C++11 or earlier are preferred to requiring C++14/17/20.

答:
The following mechanism is due to @JonathanWakely, and is specific to GCC:

```<code>int i;

template <typename T>
[[gnu::warning("your type here")]]
bool print_type() { return true; }

bool b = print_type<decltype(i)>();
</code>```

This gives you:

```<code><source>:In function 'void __static_initialization_and_destruction_0(int, int)':
<source>:7:33: warning: call to 'print_type<int>' declared with attribute warning: your
type here [-Wattribute-warning]
    7 | bool b = print_type<decltype(i)>();
      |          ~~~~~~~~~~~~~~~~~~~~~~~^~
</code>```

See it working on Godbolt.

ContentLicense: CC BY-SA 4.0

Body:
The following mechanism is due to @JonathanWakely, and is specific to GCC:

int i;

template <typename T>
[[gnu::warning("your type here")]]
bool print_type() { return true; }

bool b = print_type<decltype(i)>();

This gives you:

<source>:In function 'void __static_initialization_and_destruction_0(int, int)':
<source>:7:33: warning: call to 'print_type<int>' declared with attribute warning: your
type here [-Wattribute-warning]
    7 | bool b = print_type<decltype(i)>();
      |          ~~~~~~~~~~~~~~~~~~~~~~~^~

See it working on Godbolt.


问:
Trying to make a program that checks if a password contains uppercase letter and a number in c
I am trying to make a program that checks whether the password created contains an uppercase letter and a number. Both the for loops execute fine if only one of them is written without the other (one loop works fine if I comment out the other loop), but if I type them both together only the second for loop (that's associated with checking if there is a number or not) works and the other doesn't work.

So with the written code below, if I type a password that does not contain an uppercase letter nor a number I get the "Please make sure that your password contains a number and try again." message only.

Note :

I tried using the assigning the integer i to zero after the first loop and using it in the second loop instead of x but I get the same result.

I am using code::blocks compiler.

Could anyone point out where did I go wrong?

Sorry if the question isn't clear enough this is my first question here in stackoverflow, and thanks in advance.

The code :

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

int main()

{

    char password[25];

    int i;

    int x;

    printf("Create a strong password (must contain an uppercase letter and a number, and must be at least 8 characters) :\n");
    scanf(" %s", password);

    for (i = 0; i <= 25; i++)
    {

        if ( isupper(password[i]) == 1 )
        {
            break;
        }

        if (i == 25)
        {
            printf("\nPlease make sure that your password contains an uppercase letter and try again.\n");
        }

    }

      for (x = 0; x <= 25; x++)
    {

        if (isdigit(password[x]) == 1)
        {
            break;
        }

        if ( x == 25 )
        {
             printf("\nPlease make sure that your password contains a number and try again.\n");
        }

    }

    return 0;
}
</code>```

答:
Here you have a simple function:

```<code>int isCapitalAndDigit(const char *pwd, int minsize)
{
    int isCapitalLetter = 0, isDigit = 0;
    size_t len = 0;

    while(*pwd && (!(isDigit && isCapitalLetter) || len < minsize) )
    {
        if(isdigit(*pwd)) isDigit = 1;
          else if(isalpha(*pwd) && !islower(*pwd)) isCapitalLetter = 1;
        pwd++;
        len++;
    }
    return isDigit && isCapitalLetter && (len >= minsize);
}
</code>```

https://godbolt.org/z/53XrhW

Body:
I am trying to make a program that checks whether the password created contains an uppercase letter and a number. Both the for loops execute fine if only one of them is written without the other (one loop works fine if I comment out the other loop), but if I type them both together only the second for loop (that's associated with checking if there is a number or not) works and the other doesn't work.

So with the written code below, if I type a password that does not contain an uppercase letter nor a number I get the "Please make sure that your password contains a number and try again." message only.

Note :

I tried using the assigning the integer i to zero after the first loop and using it in the second loop instead of x but I get the same result.

I am using code::blocks compiler.

Could anyone point out where did I go wrong?

Sorry if the question isn't clear enough this is my first question here in stackoverflow, and thanks in advance.

The code :

#include <stdio.h>
#include <ctype.h>

int main()

{

    char password[25];

    int i;

    int x;

    printf("Create a strong password (must contain an uppercase letter and a number, and must be at least 8 characters) :\n");
    scanf(" %s", password);

    for (i = 0; i <= 25; i++)
    {

        if ( isupper(password[i]) == 1 )
        {
            break;
        }

        if (i == 25)
        {
            printf("\nPlease make sure that your password contains an uppercase letter and try again.\n");
        }

    }

      for (x = 0; x <= 25; x++)
    {

        if (isdigit(password[x]) == 1)
        {
            break;
        }

        if ( x == 25 )
        {
             printf("\nPlease make sure that your password contains a number and try again.\n");
        }

    }

    return 0;
}

Body:
Here you have a simple function:

int isCapitalAndDigit(const char *pwd, int minsize)
{
    int isCapitalLetter = 0, isDigit = 0;
    size_t len = 0;

    while(*pwd && (!(isDigit && isCapitalLetter) || len < minsize) )
    {
        if(isdigit(*pwd)) isDigit = 1;
          else if(isalpha(*pwd) && !islower(*pwd)) isCapitalLetter = 1;
        pwd++;
        len++;
    }
    return isDigit && isCapitalLetter && (len >= minsize);
}

https://godbolt.org/z/53XrhW


问:
What is the meaning of Generic <> before the return type Class<>
I have seen few examples like below where return type contains generics twice,

what is the meaning of first set  , i understand the method should return a class of array containing elements of type C , but what is first C

```<code>     public static <C> Class<C[]> arrayClass(Class<C> klass) {
        return (Class<C[]>) Array.newInstance(klass, 0).getClass();
    }
</code>```

答:
That's the declaration of a generic parameter, in your case it's named C but it can almost literally be anything. (There are constraints, like reserved keywords and general java-naming restrictions).

It is used to tell java that in the context of your method, C is a generic type.

Without it java would try to resolve C and check if a class, interface etc. would exist.

See this example:

```<code>public static <String> Class<String[]> arrayClass(Class<String> klass) {
    return (Class<String[]>) Array.newInstance(klass, 0).getClass();
}
</code>```

You see that I've declared the generic parameter name to be String, but I don't mean java.lang.String that's just a placeholder name defined by me. So it works fine when I do this:

```<code>Class<Integer[]> klass = arrayClass(Integer.class);
</code>```

But when I remove the <String> from the method, then it will fail, because java now assumes that you meant java.lang.String:

```<code>// compile error:
//    Required type Class<String>
//    provided      Class<Integer>
Class<Integer[]> klass = arrayClass(Integer.class);
</code>```

Body:
I have seen few examples like below where return type contains generics twice,

what is the meaning of first set  , i understand the method should return a class of array containing elements of type C , but what is first C

     public static <C> Class<C[]> arrayClass(Class<C> klass) {
        return (Class<C[]>) Array.newInstance(klass, 0).getClass();
    }

Body:
That's the declaration of a generic parameter, in your case it's named C but it can almost literally be anything. (There are constraints, like reserved keywords and general java-naming restrictions).

It is used to tell java that in the context of your method, C is a generic type.

Without it java would try to resolve C and check if a class, interface etc. would exist.

See this example:

public static <String> Class<String[]> arrayClass(Class<String> klass) {
    return (Class<String[]>) Array.newInstance(klass, 0).getClass();
}

You see that I've declared the generic parameter name to be String, but I don't mean java.lang.String that's just a placeholder name defined by me. So it works fine when I do this:

Class<Integer[]> klass = arrayClass(Integer.class);

But when I remove the <String> from the method, then it will fail, because java now assumes that you meant java.lang.String:

// compile error:
//    Required type Class<String>
//    provided      Class<Integer>
Class<Integer[]> klass = arrayClass(Integer.class);


问:
preg_replace and regexp to get the domain
I have a code which return the clean domain from HTTP_HOST

```<code>preg_replace('#^(.*\.)?(.*\..*)$#', '$2', $_SERVER['HTTP_HOST'])
</code>```

But in case the domain is like somedomain.co.uk - it returns the co.uk only.
Can you pls help me to remake the RegExp to return the correct domain in this case?
Thanks a lot!

答:
You should try this:

```<code>preg_replace('#^(https?:\/\/)?(www\d?\.)?([^\/\?]+)(.*)#', '$3', $url)
</code>```

It works for the following cases:

```<code><?php

$urls = [
    'https://www.somedomain.co.uk',
    'http://www.somedomain.co.uk',
    'www.somedomain.co.uk/something',
    'www.somedomain.co.uk?q=1',
    'www2.somedomain.co.uk/something',
    'somedomain.co.uk',
    '192.168.1.1/something?q=1&x=2',
];

foreach($urls as $url) {
    echo preg_replace('#^(https?:\/\/)?(www\d?\.)?([^\/\?]+)(.*)#', '$3', $url) . '<br>';
}
</code>```

Body:
I have a code which return the clean domain from HTTP_HOST

preg_replace('#^(.*\.)?(.*\..*)$#', '$2', $_SERVER['HTTP_HOST'])

But in case the domain is like somedomain.co.uk - it returns the co.uk only.
Can you pls help me to remake the RegExp to return the correct domain in this case?
Thanks a lot!

Body:
You should try this:

preg_replace('#^(https?:\/\/)?(www\d?\.)?([^\/\?]+)(.*)#', '$3', $url)

It works for the following cases:

<?php

$urls = [
    'https://www.somedomain.co.uk',
    'http://www.somedomain.co.uk',
    'www.somedomain.co.uk/something',
    'www.somedomain.co.uk?q=1',
    'www2.somedomain.co.uk/something',
    'somedomain.co.uk',
    '192.168.1.1/something?q=1&x=2',
];

foreach($urls as $url) {
    echo preg_replace('#^(https?:\/\/)?(www\d?\.)?([^\/\?]+)(.*)#', '$3', $url) . '<br>';
}


问:
Read Emails from outlook mailbox
Outlook product version : 16.0.1073020348

So I made an script to read emails and insert them into a DB.

The problem: The script is reading currently from my Inbox(red flag) and not from the shared mailbox(blue flag)

Desired Solution: Check the shared mailbox(blue flag)

Currently my code looks something like this:

```<code>Set objOutlook = CreateObject("Outlook.Application")

Set objNamespace = objOutlook.GetNamespace("MAPI")
'PROBLEM HERE I GUESS
Set objFolder = objNamespace.GetDefaultFolder(6) 'Inbox

Set colItems = objFolder.Items

Set colFilteredItems = colItems.Restrict("[Unread]=true")

Set colFilteredItems = colFilteredItems.Restrict("[Subject] = SUBJECT")

For k = colFilteredItems.Count to 1 step -1
    set objMessage  = colFilteredItems.Item(k)
    '....
next
</code>```

Any help appreciated

Tried the method suggested by @josefZ , but keep struggling with it
1st try(failing on last line):

```<code>Set myRecipient = objNamespace.CreateRecipient("mailbox@mail.com")

myRecipient.Resolve

Set objFolder = objNamespace.GetSharedDefaultFolder(myRecipient,olFolderInbox).Folders("Bandeja de Entrada")
</code>```

答:
Like this is working:</p>

```<code>Set myRecipient = objNamespace.CreateRecipient("mailbox@mail.com")

myRecipient.Resolve

Set objFolder = objNamespace.GetSharedDefaultFolder(myRecipient,6) 'inbox
</code>```

Title: Read Emails from outlook mailbox

Body:
Outlook product version : 16.0.1073020348

So I made an script to read emails and insert them into a DB.

The problem: The script is reading currently from my Inbox(red flag) and not from the shared mailbox(blue flag)

Desired Solution: Check the shared mailbox(blue flag)

Currently my code looks something like this:

Set objOutlook = CreateObject("Outlook.Application")

Set objNamespace = objOutlook.GetNamespace("MAPI")
'PROBLEM HERE I GUESS
Set objFolder = objNamespace.GetDefaultFolder(6) 'Inbox

Set colItems = objFolder.Items

Set colFilteredItems = colItems.Restrict("[Unread]=true")

Set colFilteredItems = colFilteredItems.Restrict("[Subject] = SUBJECT")

For k = colFilteredItems.Count to 1 step -1
    set objMessage  = colFilteredItems.Item(k)
    '....
next

Any help appreciated

Tried the method suggested by @josefZ , but keep struggling with it
1st try(failing on last line):

Set myRecipient = objNamespace.CreateRecipient("mailbox@mail.com")

myRecipient.Resolve

Set objFolder = objNamespace.GetSharedDefaultFolder(myRecipient,olFolderInbox).Folders("Bandeja de Entrada")

Body:
Like this is working:

Set myRecipient = objNamespace.CreateRecipient("mailbox@mail.com")

myRecipient.Resolve

Set objFolder = objNamespace.GetSharedDefaultFolder(myRecipient,6) 'inbox


问:
How to Get Value of Another Column in The Same Table to Become as a Reference
I want to generate one column named port_filled in m_olt_port using COUNT() where the row's values are generated based on the other table total value which is m_odp and have the same id reference. What i expect to achieve is like this text table below:

m_olt_port

```<code>╔═════════════╦═════════════╗
║ id_olt_port ║ port_filled ║
╠═════════════╬═════════════╣
║ 1           ║ 2           ║
╠═════════════╬═════════════╣
║ 2           ║ 3           ║
╠═════════════╬═════════════╣
║ 3           ║ 5           ║
╠═════════════╬═════════════╣
║ 4           ║ 0           ║
╠═════════════╬═════════════╣
║ 5           ║ 0           ║
╠═════════════╬═════════════╣
║ 6           ║ 0           ║
╠═════════════╬═════════════╣
║ 7           ║ 0           ║
╠═════════════╬═════════════╣
║ 8           ║ 0           ║
╚═════════════╩═════════════╝
</code>```

The m_odp itself is like this:

m_odp

```<code>╔════════╦═════════════╗
║ id_odp ║ id_olt_port ║
╠════════╬═════════════╣
║ 1      ║ 1           ║
╠════════╬═════════════╣
║ 2      ║ 1           ║
╠════════╬═════════════╣
║ 3      ║ 2           ║
╠════════╬═════════════╣
║ 4      ║ 2           ║
╠════════╬═════════════╣
║ 5      ║ 2           ║
╠════════╬═════════════╣
║ 6      ║ 3           ║
╠════════╬═════════════╣
║ 7      ║ 3           ║
╠════════╬═════════════╣
║ 8      ║ 3           ║
╠════════╬═════════════╣
║ 9      ║ 3           ║
╠════════╬═════════════╣
║ 10     ║ 3           ║
╚════════╩═════════════╝
</code>```

The code I've tried is by using nested SELECT to get value from m_odp table to be shown in m_olt_port table, like this:

```<code>SELECT
m_olt_port.*,

(SELECT COUNT(m_odp.id_olt_port)
FROM m_odp
JOIN m_olt_port ON m_odp.id_olt_port = m_olt_port.id_olt_port
WHERE m_odp.id_olt_port = 3) AS port_filled,

m_olt_port.id_olt_port

FROM m_olt_port
</code>```

But the problem is, I can't get the right value to fill inside WHERE condition which is make the result is wrong just like this:

Result

```<code>╔═════════════╦═════════════╗
║ id_olt_port ║ port_filled ║
╠═════════════╬═════════════╣
║ 1           ║ 5           ║
╠═════════════╬═════════════╣
║ 2           ║ 5           ║
╠═════════════╬═════════════╣
║ 3           ║ 5           ║
╠═════════════╬═════════════╣
║ 4           ║ 5           ║
╠═════════════╬═════════════╣
║ 5           ║ 5           ║
╠═════════════╬═════════════╣
║ 6           ║ 5           ║
╠═════════════╬═════════════╣
║ 7           ║ 5           ║
╠═════════════╬═════════════╣
║ 8           ║ 5           ║
╚═════════════╩═════════════╝
</code>```

I think the problem is in the nested where condition which is WHERE m_odp.id_olt_port = 3.   I think if that 3 is dynamically change matching the id_olt_port's value between m_olt_port and m_odp, it will generate different row based on their total count.

But how can I achieve this?

答:
```<code>CREATE TABLE m_odp (id_odp INT, id_olt_port INT);
INSERT INTO m_odp VALUES
(1,1),
(2,1),
(3,2),
(4,2),
(5,2),
(6,3),
(7,3),
(8,3),
(9,3),
(10,3);
SELECT * FROM m_odp;
</code>```

```
id_odp | id_olt_port
-----: | ----------:
     1 |           1
     2 |           1
     3 |           2
     4 |           2
     5 |           2
     6 |           3
     7 |           3
     8 |           3
     9 |           3
    10 |           3
```

```<code>SELECT id_olt_port, COUNT(*) FROM m_odp GROUP BY id_olt_port;
</code>```

```
id_olt_port | COUNT(*)
----------: | -------:
          1 |        2
          2 |        3
          3 |        5
```

db<>fiddle here

It is not possible to obtain the result shown - there is no source data in m_odp table which provided the existence of ports ##4-8.

Body:
I want to generate one column named port_filled in m_olt_port using COUNT() where the row's values are generated based on the other table total value which is m_odp and have the same id reference. What i expect to achieve is like this text table below:

m_olt_port

╔═════════════╦═════════════╗
║ id_olt_port ║ port_filled ║
╠═════════════╬═════════════╣
║ 1           ║ 2           ║
╠═════════════╬═════════════╣
║ 2           ║ 3           ║
╠═════════════╬═════════════╣
║ 3           ║ 5           ║
╠═════════════╬═════════════╣
║ 4           ║ 0           ║
╠═════════════╬═════════════╣
║ 5           ║ 0           ║
╠═════════════╬═════════════╣
║ 6           ║ 0           ║
╠═════════════╬═════════════╣
║ 7           ║ 0           ║
╠═════════════╬═════════════╣
║ 8           ║ 0           ║
╚═════════════╩═════════════╝

The m_odp itself is like this:

m_odp

╔════════╦═════════════╗
║ id_odp ║ id_olt_port ║
╠════════╬═════════════╣
║ 1      ║ 1           ║
╠════════╬═════════════╣
║ 2      ║ 1           ║
╠════════╬═════════════╣
║ 3      ║ 2           ║
╠════════╬═════════════╣
║ 4      ║ 2           ║
╠════════╬═════════════╣
║ 5      ║ 2           ║
╠════════╬═════════════╣
║ 6      ║ 3           ║
╠════════╬═════════════╣
║ 7      ║ 3           ║
╠════════╬═════════════╣
║ 8      ║ 3           ║
╠════════╬═════════════╣
║ 9      ║ 3           ║
╠════════╬═════════════╣
║ 10     ║ 3           ║
╚════════╩═════════════╝

The code I've tried is by using nested SELECT to get value from m_odp table to be shown in m_olt_port table, like this:

SELECT
m_olt_port.*,

(SELECT COUNT(m_odp.id_olt_port)
FROM m_odp
JOIN m_olt_port ON m_odp.id_olt_port = m_olt_port.id_olt_port
WHERE m_odp.id_olt_port = 3) AS port_filled,

m_olt_port.id_olt_port

FROM m_olt_port

But the problem is, I can't get the right value to fill inside WHERE condition which is make the result is wrong just like this:

Result

╔═════════════╦═════════════╗
║ id_olt_port ║ port_filled ║
╠═════════════╬═════════════╣
║ 1           ║ 5           ║
╠═════════════╬═════════════╣
║ 2           ║ 5           ║
╠═════════════╬═════════════╣
║ 3           ║ 5           ║
╠═════════════╬═════════════╣
║ 4           ║ 5           ║
╠═════════════╬═════════════╣
║ 5           ║ 5           ║
╠═════════════╬═════════════╣
║ 6           ║ 5           ║
╠═════════════╬═════════════╣
║ 7           ║ 5           ║
╠═════════════╬═════════════╣
║ 8           ║ 5           ║
╚═════════════╩═════════════╝

I think the problem is in the nested where condition which is WHERE m_odp.id_olt_port = 3.   I think if that 3 is dynamically change matching the id_olt_port's value between m_olt_port and m_odp, it will generate different row based on their total count.

But how can I achieve this?

Body:
CREATE TABLE m_odp (id_odp INT, id_olt_port INT);
INSERT INTO m_odp VALUES
(1,1),
(2,1),
(3,2),
(4,2),
(5,2),
(6,3),
(7,3),
(8,3),
(9,3),
(10,3);
SELECT * FROM m_odp;

id_odp | id_olt_port
-----: | ----------:
     1 |           1
     2 |           1
     3 |           2
     4 |           2
     5 |           2
     6 |           3
     7 |           3
     8 |           3
     9 |           3
    10 |           3

SELECT id_olt_port, COUNT(*) FROM m_odp GROUP BY id_olt_port;

id_olt_port | COUNT(*)
----------: | -------:
          1 |        2
          2 |        3
          3 |        5

db<>fiddle here

It is not possible to obtain the result shown - there is no source data in m_odp table which provided the existence of ports ##4-8.


问:
Iterate over a data frame and combine values from different columns
I have two data frame:

Support data:

```<code>support_data = {
    'index_value': [
        100,
        250,
        500,
        30,
        10
    ]
}
support_df = pd.DataFrame(support_data)

index_value
0   100
1   250
2   500
3   30
4   10
</code>```

Main data:

```<code>data = {
    'link_index': [
        '0', '0',
        '0', '1',
        '2', '3',
        '3', '4',
        '4', '4'
    ],
    'value_1': [
        '1', '2',
        '3', '4',
        '5', '6',
        '7', '8',
        '9', '0'
    ],
    'value_2': [
        '11', '28',
        '33', '40',
        '50', '60',
        '70', '80',
        '90', '100'
    ]
}
df = pd.DataFrame(data)

link_index  value_1 value_2
0   0   1   11
1   0   2   28
2   0   3   33
3   1   4   40
4   2   5   50
5   3   6   60
6   3   7   70
7   4   8   80
8   4   9   90
9   4   0   100
</code>```

I need to slice data frame and to zip value_1 and value_2 and append value from support data frame by link_index.

I have worked solution, but it is slow. Maybe exist more fast decision.

My solution and result:

Function zip values and append value from support data frame.

```<code>def write(group):
    value_1 = group.value_1.tolist()
    value_2 = group.value_2.tolist()
    result = [b for a in zip(value_1, value_2) for b in a]
    index = group.link_index.astype(int).iloc[0]
    result.append(support_df.index_value.iloc[index])
    result = ','.join(str(e) for e in result)
    return result
</code>```

Cycle split data frame on slices with length = nrows and step = overlap:

```<code>overlap = 1
nrows = 2
for i in range(0, len(df) - overlap, nrows - overlap):
    row = write(df.iloc[i : i + nrows])
    result = result.append(pd.DataFrame({'seq' : [row]}), ignore_index=True)
</code>```

Result:

```<code>seq
0   1,11,2,28,100
1   2,28,3,33,100
2   3,33,4,40,100
3   4,40,5,50,250
4   5,50,6,60,500
5   6,60,7,70,30
6   7,70,8,80,30
7   8,80,9,90,10
8   9,90,0,100,10
</code>```

I expect more fast solution.

答:
You can try this (I haven't compared speed but this doesn't involve any for loops):

```<code># prepare data type of link_index to merge
support_df = support_df.reset_index().rename(columns={'index':'link_index'})
support_df['link_index'] = support_df['link_index'].astype(str)
merged = pd.merge(df, support_df, on="link_index")

# split data into two halves with an offset
left = merged[['value_1', 'value_2', 'index_value']].iloc[:-1].reset_index(drop=True)
right = merged[['value_1', 'value_2']].iloc[1:].reset_index(drop=True)

# rename duplicate columns before concatenating them
left = left.rename(columns={'value_1':'left_1', 'value_2':'left_2'})
right = right.rename(columns={'value_1':'right_1', 'value_2':'right_2'})

# rejoin data and convert to Series
result = pd.concat([left, right], axis=1)
result = result[['left_1', 'left_2', 'right_1', 'right_2', 'index_value']]
seq = pd.Series(result.values.tolist())
print(seq)
</code>```

Output:

```<code>0    [1, 11, 2, 28, 100]
1    [2, 28, 3, 33, 100]
2    [3, 33, 4, 40, 100]
3    [4, 40, 5, 50, 250]
4    [5, 50, 6, 60, 500]
5     [6, 60, 7, 70, 30]
6     [7, 70, 8, 80, 30]
7     [8, 80, 9, 90, 10]
8    [9, 90, 0, 100, 10]
</code>```

Body:
I have two data frame:

Support data:

support_data = {
    'index_value': [
        100,
        250,
        500,
        30,
        10
    ]
}
support_df = pd.DataFrame(support_data)

index_value
0   100
1   250
2   500
3   30
4   10

Main data:

data = {
    'link_index': [
        '0', '0',
        '0', '1',
        '2', '3',
        '3', '4',
        '4', '4'
    ],
    'value_1': [
        '1', '2',
        '3', '4',
        '5', '6',
        '7', '8',
        '9', '0'
    ],
    'value_2': [
        '11', '28',
        '33', '40',
        '50', '60',
        '70', '80',
        '90', '100'
    ]
}
df = pd.DataFrame(data)

link_index  value_1 value_2
0   0   1   11
1   0   2   28
2   0   3   33
3   1   4   40
4   2   5   50
5   3   6   60
6   3   7   70
7   4   8   80
8   4   9   90
9   4   0   100

I need to slice data frame and to zip value_1 and value_2 and append value from support data frame by link_index.

I have worked solution, but it is slow. Maybe exist more fast decision.

My solution and result:

Function zip values and append value from support data frame.

def write(group):
    value_1 = group.value_1.tolist()
    value_2 = group.value_2.tolist()
    result = [b for a in zip(value_1, value_2) for b in a]
    index = group.link_index.astype(int).iloc[0]
    result.append(support_df.index_value.iloc[index])
    result = ','.join(str(e) for e in result)
    return result

Cycle split data frame on slices with length = nrows and step = overlap:

overlap = 1
nrows = 2
for i in range(0, len(df) - overlap, nrows - overlap):
    row = write(df.iloc[i : i + nrows])
    result = result.append(pd.DataFrame({'seq' : [row]}), ignore_index=True)

Result:

seq
0   1,11,2,28,100
1   2,28,3,33,100
2   3,33,4,40,100
3   4,40,5,50,250
4   5,50,6,60,500
5   6,60,7,70,30
6   7,70,8,80,30
7   8,80,9,90,10
8   9,90,0,100,10

I expect more fast solution.

Body:
You can try this (I haven't compared speed but this doesn't involve any for loops):

# prepare data type of link_index to merge
support_df = support_df.reset_index().rename(columns={'index':'link_index'})
support_df['link_index'] = support_df['link_index'].astype(str)
merged = pd.merge(df, support_df, on="link_index")

# split data into two halves with an offset
left = merged[['value_1', 'value_2', 'index_value']].iloc[:-1].reset_index(drop=True)
right = merged[['value_1', 'value_2']].iloc[1:].reset_index(drop=True)

# rename duplicate columns before concatenating them
left = left.rename(columns={'value_1':'left_1', 'value_2':'left_2'})
right = right.rename(columns={'value_1':'right_1', 'value_2':'right_2'})

# rejoin data and convert to Series
result = pd.concat([left, right], axis=1)
result = result[['left_1', 'left_2', 'right_1', 'right_2', 'index_value']]
seq = pd.Series(result.values.tolist())
print(seq)

Output:

0    [1, 11, 2, 28, 100]
1    [2, 28, 3, 33, 100]
2    [3, 33, 4, 40, 100]
3    [4, 40, 5, 50, 250]
4    [5, 50, 6, 60, 500]
5     [6, 60, 7, 70, 30]
6     [7, 70, 8, 80, 30]
7     [8, 80, 9, 90, 10]
8    [9, 90, 0, 100, 10]


问:
TypeError: scrollIntoView is not a function
I am new to react-testing-library / jest and attempting to write a test to see if the navigation of routes (using react-router-dom) is performed correctly.  So far I have been following the README and this tutorial on how to use.

One of my components uses scrollIntoView in a local function and this causes the test to fail.

```<code>TypeError: this.messagesEnd.scrollIntoView is not a function

  45 |
  46 |     scrollToBottom = () => {
> 47 |         this.messagesEnd.scrollIntoView({ behavior: "smooth" });
     |                          ^
  48 |     }
  49 |
  50 |
</code>```

This is the function in my chatbot component:

```<code>componentDidUpdate() {
    this.scrollToBottom();
}

scrollToBottom = () => {
    this.messagesEnd.scrollIntoView({ behavior: "smooth" });
}
</code>```

And this is a sample of the tests that fail:

```<code>test('<App> default screen', () => {

    const { getByTestId, getByText } = renderWithRouter(<App />)

    expect(getByTestId('index'))

    const leftClick = {button: 0}
    fireEvent.click(getByText('View Chatbot'), leftClick) <-- test fails

    expect(getByTestId('chatbot'))

})
</code>```

I have tried to use a mock function, however the error still remains.

This is where this.messageEnd is assigned:

```<code>    <div className="chatbot">
        <div className="chatbot-messages">
            //render messages here
        </div>
        <div className="chatbot-actions" ref={(el) => { this.messagesEnd = el; }}>
            //inputs for message actions here
        </div>
    </div>
</code>```

I referenced code from this stack overflow question: How to scroll to bottom in react?

SOLUTION

```<code>test('<App> default screen', () => {

    window.HTMLElement.prototype.scrollIntoView = function() {};

    const { getByTestId, getByText } = renderWithRouter(<App />)

    expect(getByTestId('index'))

    const leftClick = {button: 0}
    fireEvent.click(getByText('View Chatbot'), leftClick)

    expect(getByTestId('chatbot'))

})
</code>```

答:
If we want to unit test 'scrollIntoView' function in a react application using react testing library then we can mock the function using 'jest'.</p>

```<code>window.HTMLElement.prototype.scrollIntoView = jest.fn()
</code>```

Body:
I am new to react-testing-library / jest and attempting to write a test to see if the navigation of routes (using react-router-dom) is performed correctly.  So far I have been following the README and this tutorial on how to use.

One of my components uses scrollIntoView in a local function and this causes the test to fail.

TypeError: this.messagesEnd.scrollIntoView is not a function

  45 |
  46 |     scrollToBottom = () => {
> 47 |         this.messagesEnd.scrollIntoView({ behavior: "smooth" });
     |                          ^
  48 |     }
  49 |
  50 |

This is the function in my chatbot component:

componentDidUpdate() {
    this.scrollToBottom();
}

scrollToBottom = () => {
    this.messagesEnd.scrollIntoView({ behavior: "smooth" });
}

And this is a sample of the tests that fail:

test('<App> default screen', () => {

    const { getByTestId, getByText } = renderWithRouter(<App />)

    expect(getByTestId('index'))

    const leftClick = {button: 0}
    fireEvent.click(getByText('View Chatbot'), leftClick) <-- test fails

    expect(getByTestId('chatbot'))

})

I have tried to use a mock function, however the error still remains.

This is where this.messageEnd is assigned:

            //render messages here

 { this.messagesEnd = el; }}>
            //inputs for message actions here

I referenced code from this stack overflow question: How to scroll to bottom in react?

SOLUTION

test('<App> default screen', () => {

    window.HTMLElement.prototype.scrollIntoView = function() {};

    const { getByTestId, getByText } = renderWithRouter(<App />)

    expect(getByTestId('index'))

    const leftClick = {button: 0}
    fireEvent.click(getByText('View Chatbot'), leftClick)

    expect(getByTestId('chatbot'))

})

Body:
If we want to unit test 'scrollIntoView' function in a react application using react testing library then we can mock the function using 'jest'.

window.HTMLElement.prototype.scrollIntoView = jest.fn()


问:
Replace value across multiple lines in bash
I'm struggling even with all the examples available on stackoverflow and google.

Basically i have the following text

```<code>    /start r.start ""
      GAIN 0x256 __POSITIVE 1 FOO
      OTHER
      OTHER
      /start MACRO
        200
        CODE "r.start" 0x256 0x2 10 0xA3
      /end MACRO
      OTHER
    /end
</code>```

and i need to read through this file searching for a name e.g. r.start which is passed as $1 and substitute e.g. 0x256 with a value that i pass as $2.
There a two instance to substitute, line 2 and line 7.

Things i know:

/start is preceded by 4 spaces

GAIN is preceded by 6 spaces

\r\n or \n might be present

CODE is preceded by 8 spaces

Till now i've reached this point

```<code>pattern="N;s\s\/start r.start \"\"\n      GAIN 0x\(.*\)"
replacement"\/start r.start \"\"\n      GAIN 0x82"
sed -e "$pattern/$replacement/p" test.txt
</code>```

but i get nothing.
I was also able to substitute the first line but for whatever reason it pasted me the first two lines twice on top of each other

the expected value assuming the following call

```<code>./run.sh r.start 0x284569
</code>```

should be

```<code>    /start r.start ""
      GAIN 0x284569 __POSITIVE 1 FOO
      OTHER
      OTHER
      /start MACRO
        200
        CODE "r.start" 0x284569 0x2 10 0xA3
      /end MACRO
      OTHER
    /end
</code>```

Here's my best shot for the second part

```<code>var="r.start"
val="0x48209F82"

pattern="\(CODE \"$var\" \).*\(.*\)"
replacement="\1$val\2"
sed "s/$pattern/$replacement/g" test.txt
</code>```

The problem is that it is deleting everything after the value substitution. I can't put in \2 the following chars

EDIT:

By doing the following

```<code>var="r.start"
val="0x48209F82"

pattern="\(CODE \"$var\" \).*\(\s.*\s.*\s.*\)"
replacement="\1$val\2"
sed "s/$pattern/$replacement/g" test.txt
</code>```

I get what i want but it feels a little bit dirty, how do i reduce the last part in case of a variable number of char? Can i just somehow match everything till end of line?

答:
How about something like the following? It uses a sed range to select everything between the /start and /end, and within the range uses a block to substitute the value for lines which match GAIN and CODE.

```<code>$ cat foo.txt
    /start r.start ""
      GAIN 0x256 __POSITIVE 1 FOO
      OTHER
      OTHER
      /start MACRO
        200
        CODE "r.start" 0x256 0x2 10 0xA3
      /end MACRO
      OTHER
    /end
$ sed '\#/start r\.start#,\#/end#{/\(GAIN\|CODE "r\.start"\)/s/0x[a-fA-F0-9]\+/0x284569/}' foo.txt
    /start r.start ""
      GAIN 0x284569 __POSITIVE 1 FOO
      OTHER
      OTHER
      /start MACRO
        200
        CODE "r.start" 0x284569 0x2 10 0xA3
      /end MACRO
      OTHER
    /end
</code>```

The sed script looks like this when formatted nicely:

\#/start r\.start#,\#/end# {
    /\(GAIN\|CODE "r\.start"\)/s/0x[a-fA-F0-9]\+/0x284569/
}
```

<p>Note</p>

<ul>
<li>the use of <code>\#...#</code> instead of <code>/.../</code> for the range patterns, so we don't have to quote slashes</li>
<li>the use of <code>/patten1/s/pattern2/string/</code> to replace <code>pattern2</code> only for lines containing <code>pattern1</code></li>
<li>the use of a <code>{...}</code> block so that the substitution only applies between <code>/start</code> and <code>/end</code></li>
</ul>

<p>You can parameterise the pattern and value like so:</p>

```#!/bin/bash

var='r\.start'
val='0x48209F82'

sed '\#/start '$var'#,\#/end#{/\(GAIN\|CODE "'$var'"\)/s/0x[0-9a-fA-F]\+/'$val'/}' foo.txt
```

Body:
I'm struggling even with all the examples available on stackoverflow and google.

Basically i have the following text

    /start r.start ""
      GAIN 0x256 __POSITIVE 1 FOO
      OTHER
      OTHER
      /start MACRO
        200
        CODE "r.start" 0x256 0x2 10 0xA3
      /end MACRO
      OTHER
    /end

and i need to read through this file searching for a name e.g. r.start which is passed as $1 and substitute e.g. 0x256 with a value that i pass as $2.
There a two instance to substitute, line 2 and line 7.

Things i know:

/start is preceded by 4 spaces

GAIN is preceded by 6 spaces

\r\n or \n might be present

CODE is preceded by 8 spaces

Till now i've reached this point

pattern="N;s\s\/start r.start \"\"\n      GAIN 0x\(.*\)"
replacement"\/start r.start \"\"\n      GAIN 0x82"
sed -e "$pattern/$replacement/p" test.txt

but i get nothing.
I was also able to substitute the first line but for whatever reason it pasted me the first two lines twice on top of each other

the expected value assuming the following call

./run.sh r.start 0x284569

should be

    /start r.start ""
      GAIN 0x284569 __POSITIVE 1 FOO
      OTHER
      OTHER
      /start MACRO
        200
        CODE "r.start" 0x284569 0x2 10 0xA3
      /end MACRO
      OTHER
    /end

Here's my best shot for the second part

var="r.start"
val="0x48209F82"

pattern="\(CODE \"$var\" \).*\(.*\)"
replacement="\1$val\2"
sed "s/$pattern/$replacement/g" test.txt

The problem is that it is deleting everything after the value substitution. I can't put in \2 the following chars

EDIT:

By doing the following

var="r.start"
val="0x48209F82"

pattern="\(CODE \"$var\" \).*\(\s.*\s.*\s.*\)"
replacement="\1$val\2"
sed "s/$pattern/$replacement/g" test.txt

I get what i want but it feels a little bit dirty, how do i reduce the last part in case of a variable number of char? Can i just somehow match everything till end of line?

Body:
How about something like the following? It uses a sed range to select everything between the /start and /end, and within the range uses a block to substitute the value for lines which match GAIN and CODE.

$ cat foo.txt
    /start r.start ""
      GAIN 0x256 __POSITIVE 1 FOO
      OTHER
      OTHER
      /start MACRO
        200
        CODE "r.start" 0x256 0x2 10 0xA3
      /end MACRO
      OTHER
    /end
$ sed '\#/start r\.start#,\#/end#{/\(GAIN\|CODE "r\.start"\)/s/0x[a-fA-F0-9]\+/0x284569/}' foo.txt
    /start r.start ""
      GAIN 0x284569 __POSITIVE 1 FOO
      OTHER
      OTHER
      /start MACRO
        200
        CODE "r.start" 0x284569 0x2 10 0xA3
      /end MACRO
      OTHER
    /end

The sed script looks like this when formatted nicely:

\#/start r\.start#,\#/end# {
    /\(GAIN\|CODE "r\.start"\)/s/0x[a-fA-F0-9]\+/0x284569/
}

Note

the use of \#...# instead of /.../ for the range patterns, so we don't have to quote slashes

the use of /patten1/s/pattern2/string/ to replace pattern2 only for lines containing pattern1

the use of a {...} block so that the substitution only applies between /start and /end

You can parameterise the pattern and value like so:

#!/bin/bash

var='r\.start'
val='0x48209F82'

sed '\#/start '$var'#,\#/end#{/\(GAIN\|CODE "'$var'"\)/s/0x[0-9a-fA-F]\+/'$val'/}' foo.txt


答:
To get a Cartesian product of two arrays of objects you can create a function by lifting merge:

const fn = R.lift(R.merge)

const l1 = [ {"a": 1, "a1": 2}, {"b": 3, "b1": 4}, {"c": 5, "c1": 6} ];
const l2 = [ {"d": 2}, {"e": 2}, {"f": 2} ];

const result = fn(l1, l2)

console.log(result)```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.as-console-wrapper { max-height: 100% !important; top: 0; }</code>```

```

Title: How to combine two array using ramda library?

Body:
I have two array as below

const l1 = [ {"a": 1, "a1": 2}, {"b": 3, "b1": 4}, {"c": 5, "c1": 6} ];
const l2 = [ {"d": 2}, {"e": 2}, {"f": 2} ];

How can I use ramda library to combine these two and get result like

[ {"a": 1, "a1": 2, "d": 2}, {"a": 1, "a1": 2, "e": 2}, {"a": 1, "a1": 2, "f": 2},
{"b": 3, "b1": 4, "d": 2}, {"b": 3, "b1": 4, "e": 2}, {"b": 3, "b1": 4, "f": 2},
{"c": 5, "c1": 6, "d": 2}, {"c": 5, "c1": 6, "e": 2}, {"c": 5, "c1": 6, "f": 2} ]

I used

R.map(R.xprod(__, l2, l1)

But not working since i got object inside array.

Thanks in advance.

Body:
To get a Cartesian product of two arrays of objects you can create a function by lifting merge:

const fn = R.lift(R.merge)

const l1 = [ {"a": 1, "a1": 2}, {"b": 3, "b1": 4}, {"c": 5, "c1": 6} ];
const l2 = [ {"d": 2}, {"e": 2}, {"f": 2} ];

const result = fn(l1, l2)

console.log(result)

.as-console-wrapper { max-height: 100% !important; top: 0; }

<script src="https://cdnjs.cloudflare.com/ajax/libs/ramda/0.27.0/ramda.js" integrity="sha256-buL0byPvI/XRDFscnSc/e0q+sLA65O9y+rbF+0O/4FE=" crossorigin="anonymous"></script>


问:
Recommendation for a server side language (+ IDEs and Tools)

I want to create a server that queries another web service every 5 mins and stores the result in SQL database.

I also want web functions exposed that run queries against the database.

Im not expecting a huge amount of trafic and the code should not be too complex. It a small side project.

I do not know much abou servers, I have a little experience with .NET and MS SQL server, however I want something free (or al least cheap!)

What language should I use and what IDE's and tools might I find useful?

答: I would use ASP.Net, Visual Web Developer Express Edition, and Microsoft SQL Server Express Edition.  They are all powerful toolsets, and all free.  Also, SO has a lot of questions in .NET for dealing with web services and databases that you can reference as you are developing your project.

ContentLicense: CC BY-SA 3.0


问:
Is there a way to omit Active Record casting (from postgres ranges)?
I have a method that checks the date intersections for my model instance.

```<code>def intersections
  Reservation.where("daterange && ?", self.daterange)
end
</code>```

Suppose I have the reservation r = Reservation.last

=> #<Reservation id: 3, home_id: 1, daterange: Sun, 10 Feb 2020...Fri, 21 Feb 2020>

r.intersections

Excepted query:

SELECT "reservations".* FROM "reservations" WHERE (daterange && '[2020-02-10,2020-02-21)')

Actual query:

SELECT "reservations".* FROM "reservations" WHERE (daterange && '2020-02-10','2020-02-11','2020-02-12','2020-02-13','2020-02-14','2020-02-15','2020-02-16','2020-02-17','2020-02-18','2020-02-19','2020-02-20')

schema:

```<code>create_table "reservations", force: :cascade do |t|
  ...
  t.daterange "daterange"
end
</code>```

I tried a lot of variations but it seems that the casting is hidden somewhere deep inside Active Record. Can I just turn it off for this query?

答:
You can use the Attributes API to setup casting.</p>

```<code>class Reservation < ApplicationRecord
  attribute :daterange, range: true

  def intersections
    Reservation.where(
      "daterange && ?", self.daterange
    )
  end
end
</code>```

```<code>irb(main):026:0> Reservation.first.intersections
  Reservation Load (0.6ms)  SELECT "reservations".* FROM "reservations" ORDER BY "reservations"."id" ASC LIMIT $1  [["LIMIT", 1]]
  Reservation Load (0.6ms)  SELECT "reservations".* FROM "reservations" WHERE (daterange && '[2020-02-14,2020-02-16)') LIMIT $1  [["LIMIT", 11]]
=> #<ActiveRecord::Relation [#<Reservation id: 1, daterange: "[2020-02-14,2020-02-16)", created_at: "2020-02-14 11:13:13", updated_at: "2020-02-14 11:13:13">, #<Reservation id: 2, daterange: "(,)", created_at: "2020-02-14 11:33:16", updated_at: "2020-02-14 11:33:16">]>
</code>```

Body:
I have a method that checks the date intersections for my model instance.

def intersections
  Reservation.where("daterange && ?", self.daterange)
end

Suppose I have the reservation r = Reservation.last

=> #<Reservation id: 3, home_id: 1, daterange: Sun, 10 Feb 2020...Fri, 21 Feb 2020>

r.intersections

Excepted query:

SELECT "reservations".* FROM "reservations" WHERE (daterange && '[2020-02-10,2020-02-21)')

Actual query:

SELECT "reservations".* FROM "reservations" WHERE (daterange && '2020-02-10','2020-02-11','2020-02-12','2020-02-13','2020-02-14','2020-02-15','2020-02-16','2020-02-17','2020-02-18','2020-02-19','2020-02-20')

schema:

create_table "reservations", force: :cascade do |t|
  ...
  t.daterange "daterange"
end

I tried a lot of variations but it seems that the casting is hidden somewhere deep inside Active Record. Can I just turn it off for this query?

Body:
You can use the Attributes API to setup casting.

class Reservation < ApplicationRecord
  attribute :daterange, range: true

  def intersections
    Reservation.where(
      "daterange && ?", self.daterange
    )
  end
end

irb(main):026:0> Reservation.first.intersections
  Reservation Load (0.6ms)  SELECT "reservations".* FROM "reservations" ORDER BY "reservations"."id" ASC LIMIT $1  [["LIMIT", 1]]
  Reservation Load (0.6ms)  SELECT "reservations".* FROM "reservations" WHERE (daterange && '[2020-02-14,2020-02-16)') LIMIT $1  [["LIMIT", 11]]
=> #<ActiveRecord::Relation [#<Reservation id: 1, daterange: "[2020-02-14,2020-02-16)", created_at: "2020-02-14 11:13:13", updated_at: "2020-02-14 11:13:13">, #<Reservation id: 2, daterange: "(,)", created_at: "2020-02-14 11:33:16", updated_at: "2020-02-14 11:33:16">]>


问:
Script to show text if cell value is below zero, otherwise show the calculation
I am completely new to scripts and don't know where to begin, so I hope I can get a bit of help here for this one time task that I have.

My problem is as follows:

If cells in my calculations in column G show values below zero, I would like to write a text message "No help required". But if the value is above zero, the cell should show the value of the calculation.

Any help is appreciated.

答:
paste this formula in row 1:

```<code>=ARRAYFORMULA(IF(G1:G<0; "No help required"; G1:G))
</code>```

UPDATE:

paste in G9:

```<code>=IF(F9-(I9+K9+M9+O9+Q9+S9)<0; "No help required"; F9-(I9+K9+M9+O9+Q9+S9))
</code>```

Body:
paste this formula in row 1:

=ARRAYFORMULA(IF(G1:G<0; "No help required"; G1:G))

UPDATE:

paste in G9:

=IF(F9-(I9+K9+M9+O9+Q9+S9)<0; "No help required"; F9-(I9+K9+M9+O9+Q9+S9))


问:
AutoCloseable-ish method but runs only on catch

I would like to two have two different methods running in catch and final blocks. I have found AutoCloseable interface, but I need something to fire in case of exception only.

Like:

```<code>SomeService service = CreateService().andOpenTransaction()

try {
    service.doSomeMessyThingsInsideDB();
} catch (Exception e) {
    service.rollbackTransaction();
    throw e;
} finally {
    service.closeConnection();
}
</code>```

Is there any way to make it simpler? As I said I am familiar with AutoCloseable, but it helps me only with finally block. I still cannot use it inside the catch.

答:
First step: Handling the exception

You evidently want the exception handled before some close. Then you need inside a try-with-resources to handle the exception.

```<code>/** throws RuntimeException */
void process(Callable<Void> work, Consumer<Exception> onFail) {
    try {
        work.call();
    } catch (Exception e) {
        onFail(e);
    }
}

try (SomeService service = CreateService().andOpenTransaction()) {
    process(() -> service.doSomeMessyThingsInsideDB(),
            e -> {
                service.rollbackTransaction();
                throw new IllegalStateException(e);
            });
}
</code>```

This is not very satisfactory, but again also integrating the AutoCloseable, might give too few use-cases.

Second step: with AutoCloseable

```<code><SV extends AutoCloseable> void processAutoClosing(Supplier<SV> serviceFactory,
                                               Callable<Void> work, Consumer<Exception> onFail) {
try (SV service = serviceFactory.get()) {
    process(work, onFail);
}

}

processAutoClosing(...);
</code>```

Body:
I would like to two have two different methods running in catch and final blocks. I have found AutoCloseable interface, but I need something to fire in case of exception only.

Like:

SomeService service = CreateService().andOpenTransaction()

try {
    service.doSomeMessyThingsInsideDB();
} catch (Exception e) {
    service.rollbackTransaction();
    throw e;
} finally {
    service.closeConnection();
}

Is there any way to make it simpler? As I said I am familiar with AutoCloseable, but it helps me only with finally block. I still cannot use it inside the catch.

Body:
First step: Handling the exception

You evidently want the exception handled before some close. Then you need inside a try-with-resources to handle the exception.

/** throws RuntimeException */
void process(Callable<Void> work, Consumer<Exception> onFail) {
    try {
        work.call();
    } catch (Exception e) {
        onFail(e);
    }
}

try (SomeService service = CreateService().andOpenTransaction()) {
    process(() -> service.doSomeMessyThingsInsideDB(),
            e -> {
                service.rollbackTransaction();
                throw new IllegalStateException(e);
            });
}

This is not very satisfactory, but again also integrating the AutoCloseable, might give too few use-cases.

Second step: with AutoCloseable

<SV extends AutoCloseable> void processAutoClosing(Supplier<SV> serviceFactory,
                                               Callable<Void> work, Consumer<Exception> onFail) {
try (SV service = serviceFactory.get()) {
    process(work, onFail);
}

}

processAutoClosing(...);


问:
select row from orc snappy table in hive
I have created a table employee_orc which is orc format with snappy compression.

```<code>    create table employee_orc(emp_id string, name string)
 row format delimited fields terminated by '\t' stored as orc tblproperties("orc.compress"="SNAPPY");
</code>```

I have uploaded data into the table using the insert statement.

```<code>employee_orc table has 1000 records.
</code>```

When I run the below query, it shows all the records

```<code>select * from employee_orc;
</code>```

But when run the below query, it shows zero results even though the records exist.

```<code>select * from employee_orc where emp_id = "EMP456";
</code>```

Why I am unable to retrieve a single record from the employee_orc table?

答:
The record does not exist.  You may think they are the same because they look the same, but there is some difference.  One possibility are spaces at the beginning or end of the string.  For this, you can use like:

```<code>where emp_id like '%EMP456%'
</code>```

This might help you.

Body:
I have created a table employee_orc which is orc format with snappy compression.

    create table employee_orc(emp_id string, name string)
 row format delimited fields terminated by '\t' stored as orc tblproperties("orc.compress"="SNAPPY");

I have uploaded data into the table using the insert statement.

employee_orc table has 1000 records.

When I run the below query, it shows all the records

select * from employee_orc;

But when run the below query, it shows zero results even though the records exist.

select * from employee_orc where emp_id = "EMP456";

Why I am unable to retrieve a single record from the employee_orc table?

Body:
The record does not exist.  You may think they are the same because they look the same, but there is some difference.  One possibility are spaces at the beginning or end of the string.  For this, you can use like:

where emp_id like '%EMP456%'

This might help you.


问:
Can't get display resolution for all devices using EnumDisplaySettings
I need to get the current display resolution of all monitors attached to the computer.

I can succesfully enum the display devices using the EnumDisplayDevicesA API but for an unknown reason I can't get the current display resolution for the device \\.\DISPLAY2 using the EnumDisplayDevicesA API.
Here is the code:

```<code>displays = 0;
result = 1;

for (index = 0; result != 0; index++)
{
    devices[index].cb = sizeof(DISPLAY_DEVICEA);
    result = EnumDisplayDevicesA(NULL, index, &(devices[displays] ), 0);

    if (result == 0)
    {
            break;
    }

    settings[index].dmSize = sizeof(DEVMODEA);
    mode = 0;

    // Collect the settings
    while(EnumDisplaySettingsA(devices[index].DeviceName, mode, (DEVMODEA *)&(settings[displays] ) ) )
    {
        mode++;
    };

    // Read the current settings
    result = EnumDisplaySettingsA(devices[index].DeviceName, ENUM_CURRENT_SETTINGS, (DEVMODEA *)&(settings[displays] ) );

    if (result != 0)
    {
        displays++;
    }
    else
    {
        result = GetLastError();
        printf("Error while readind display settings %d\n", result);

        //Skip this device
        result = 1;
    }
}
</code>```

Note that this code works flawlessly on some computers while on computers with multiple video cards it fails. For examle it fails on a laptop with an Intel HD Graphicw 630 + Nvidia Quadro M1200 where the active displays are the main laptop display and an exteral display attached through either the HDMI or DP port). More precisely on these computers I can get the correct resolution for the first display device (\\.\DISPLAY1) but on the second display device (\\.\DISPLAY2) the returned width and height is 0.

The EnumDisplaySettingsA API just return 0 as well as the GetLastError API.

What does  devices represent ? Are they a monitor attached to a single video card or are they just monitors attached to whatever video card ?

NOTE: Using EnumDisplayMonitors I can get the resolution of all monitors while EnumDisplaySettingsA fails.

答:
Could it be that more than two devices can be obtained by iterating over EnumDisplayDevices?

For me there were like 7 \.\DISPLAYX entries, even though I only have the Laptop Display and two external Monitors.

And when calling EnumDisplaySettings with a not connected Display, the results are like in your case 0. For me DISPLAY1, DISPLAY4 and DISPLAY5 were the ones I needed to use.

Body:
I need to get the current display resolution of all monitors attached to the computer.

I can succesfully enum the display devices using the EnumDisplayDevicesA API but for an unknown reason I can't get the current display resolution for the device \\.\DISPLAY2 using the EnumDisplayDevicesA API.
Here is the code:

displays = 0;
result = 1;

for (index = 0; result != 0; index++)
{
    devices[index].cb = sizeof(DISPLAY_DEVICEA);
    result = EnumDisplayDevicesA(NULL, index, &(devices[displays] ), 0);

    if (result == 0)
    {
            break;
    }

    settings[index].dmSize = sizeof(DEVMODEA);
    mode = 0;

    // Collect the settings
    while(EnumDisplaySettingsA(devices[index].DeviceName, mode, (DEVMODEA *)&(settings[displays] ) ) )
    {
        mode++;
    };

    // Read the current settings
    result = EnumDisplaySettingsA(devices[index].DeviceName, ENUM_CURRENT_SETTINGS, (DEVMODEA *)&(settings[displays] ) );

    if (result != 0)
    {
        displays++;
    }
    else
    {
        result = GetLastError();
        printf("Error while readind display settings %d\n", result);

        //Skip this device
        result = 1;
    }
}

Note that this code works flawlessly on some computers while on computers with multiple video cards it fails. For examle it fails on a laptop with an Intel HD Graphicw 630 + Nvidia Quadro M1200 where the active displays are the main laptop display and an exteral display attached through either the HDMI or DP port). More precisely on these computers I can get the correct resolution for the first display device (\\.\DISPLAY1) but on the second display device (\\.\DISPLAY2) the returned width and height is 0.

The EnumDisplaySettingsA API just return 0 as well as the GetLastError API.

What does  devices represent ? Are they a monitor attached to a single video card or are they just monitors attached to whatever video card ?

NOTE: Using EnumDisplayMonitors I can get the resolution of all monitors while EnumDisplaySettingsA fails.


问:
Most accurate city level GeoIP tracking service?
Can anyone provide a suggestion for a highly accurate GeoIP service that can locate a user down to the city?

Currently I am using MaxMind GeoLite but it is only 78% accurate. Even their premium is only 80%.

I was hoping to find something greater then 90% accurate at city look up based on IP.

Thanks.

答:
I've been looking into this myself, but since there are so many that I could only recommend you to take a look at this lengthy blog post:

https://medium.com/@ipdata_co/what-is-the-best-commercial-ip-geolocation-api-d8195cda7027

It's from one provider, but they compare other offers.


问:
How to Use Keyboard service as an app?
I know that keyboard is a service  but i want to show it like an app on my desktop just like any other app  i'm using sample softkeyboard code  as a reference

Any Idea

答:
I'm not sure if I understand your question correctly, but perhaps this will help. You want to show the 'keyboard like an app' on your desktop? Does this mean that you want an icon to click on that opens the soft keyboard? If so, perhaps the following code may be of use to you. This will simply display the soft keyboard.

```<code>InputMethodManager inputMgr = (InputMethodManager)mContext.getSystemService(Context.INPUT_METHOD_SERVICE);
inputMgr.toggleSoftInput(0, 0);
</code>```

More info on this approach here.

Title: How to Use Keyboard service as an app?

Body:
I'm not sure if I understand your question correctly, but perhaps this will help. You want to show the 'keyboard like an app' on your desktop? Does this mean that you want an icon to click on that opens the soft keyboard? If so, perhaps the following code may be of use to you. This will simply display the soft keyboard.

InputMethodManager inputMgr = (InputMethodManager)mContext.getSystemService(Context.INPUT_METHOD_SERVICE);
inputMgr.toggleSoftInput(0, 0);

More info on this approach here.


问:
Plotting graph using python and dispaying it using HTML
I want build an offline application using plotly for displaying graphs . I am using python(flask) at the back end and HTML(javascript) for the front end . Currently I am able to plot the graph by sending the graph data as JSON object to front end and building the graph using plotly.js at the front end itself . But what I actually want is to build the graph at the server(backend ie python) side itself and then display the data in HTML . I have gone through the plotly documentation that builds the graph in python , but I dont know how to send the build graph to front end for display :(
Can someone help me on that ?
PS : I want to build an offline application
Updated Code</p>

```<code>$(window).resize(function() {
         var divheight = $("#section").height();
         var divwidth = $("#section").width();
         var update = {
                  width:divwidth,  // or any new width
                  height:divheight // " "
                };

          var arr = $('#section > div').get();
          alert(arr[1]);
        Plotly.relayout(arr[0], update);
            }).resize();
         });
</code>```

答:
You can use the .to_html() method:

https://plot.ly/python-api-reference/generated/plotly.graph_objects.Figure.html#plotly.graph_objects.Figure.to_html

```<code>import plotly.express as px

fig = px.scatter(x=[0, 1, 2, 3, 4], y=[0, 1, 4, 9, 16])

div = fig.to_html(full_html=False)  # Get the <div> to send to your frontend and embed in an html page
</code>```

Body:
I want build an offline application using plotly for displaying graphs . I am using python(flask) at the back end and HTML(javascript) for the front end . Currently I am able to plot the graph by sending the graph data as JSON object to front end and building the graph using plotly.js at the front end itself . But what I actually want is to build the graph at the server(backend ie python) side itself and then display the data in HTML . I have gone through the plotly documentation that builds the graph in python , but I dont know how to send the build graph to front end for display :(
Can someone help me on that ?
PS : I want to build an offline application
Updated Code

$(window).resize(function() {
         var divheight = $("#section").height();
         var divwidth = $("#section").width();
         var update = {
                  width:divwidth,  // or any new width
                  height:divheight // " "
                };

          var arr = $('#section > div').get();
          alert(arr[1]);
        Plotly.relayout(arr[0], update);
            }).resize();
         });

Body:
You can use the .to_html() method:

https://plot.ly/python-api-reference/generated/plotly.graph_objects.Figure.html#plotly.graph_objects.Figure.to_html

import plotly.express as px

fig = px.scatter(x=[0, 1, 2, 3, 4], y=[0, 1, 4, 9, 16])

div = fig.to_html(full_html=False)  # Get the <div> to send to your frontend and embed in an html page


问:
Installing ROracle
I have downloaded the compiled ROracle package from the Oracle website. I have set my working directory with setwd(). Then I tried to install the package as follows:

```<code>install.packages("ROracle-1.3.2.zip", repos=NULL)
</code>```

It failed and I got the following error message:

```<code>Error in read.dcf(file.path(pkgname, "DESCRIPTION"), c("Package", "Type")) :
  cannot open the connection
In addition: Warning message:
In read.dcf(file.path(pkgname, "DESCRIPTION"), c("Package", "Type")) :
  cannot open compressed file 'ROracle-1.3.2/DESCRIPTION', probable reason 'No such file or directory'
</code>```

I also tried from command line just in case:

```<code>R CMD INSTALL ROracle-1.3.2.zip
</code>```

It also failed and I got the following error message:

```<code>* installing to library 'Z:/R/R-3.6.1/library'
Warning in read.dcf(file.path(pkgname, "DESCRIPTION"), c("Package", "Type")) :
  cannot open compressed file 'ROracle-1.3.2/DESCRIPTION', probable reason 'No such file or directory'
Error in read.dcf(file.path(pkgname, "DESCRIPTION"), c("Package", "Type")) :
  cannot open the connection
</code>```

The DESCRIPTION file certainly exists in ROracle-1.3.2.zip. I opened it up and looked at - just a normal DESCRIPTION file.

I am using Windows 7.

How do I install ROracle?

答:
You need to follow the following procedure:

Create a folder called "ROracle" and put the downloaded zip ROracle-1.3.2.zip in there

Unzip the .zip file in the folder. Now you have all the contents of the zip file (including the original zip file) in the ROracle folder that you created in step 1

Remove the original .zip file from the folder. Now the folder "ROracle" you created in step 1 only contains the contents of the original .zip file

Add the "ROracle" folder to a zip file called "ROracle.zip"

Got down into this solution by comparing hierarchy of earlier ROracle_1.3-1.zip -file which i got working well in earlier R version.

After following all these steps the outcome is that the DESCRIPTION file can be found in ROracle.zip/ROracle/DESCRIPTION instead of ROracle-1.3.2.zip/DESCRIPTION

With the newly zip-file from step 4 the installation is a quite straightforward.

```<code>setwd("THEPLACEWHERETHE ROracle.zip file is located)
install.packages('ROracle.zip', repos = NULL)
</code>```

My .Renviron contains these lines if that matters

```<code>    # PATH="C:/Rtools/bin;C:/oracle/instantclient_19_5;$PATH"
    # OCI_LIB64 = C:/oracle/instantclient_19_5
    # BINPREF="C:/Rtools/mingw_$(WIN)/bin/"
</code>```

OS is WIN10.
R version 3.6.2 (2019-12-12) -- "Dark and Stormy Night"
Platform: x86_64-w64-mingw32/x64 (64-bit)
ROracle 1.3-2

Title: Installing ROracle

Body:
I have downloaded the compiled ROracle package from the Oracle website. I have set my working directory with setwd(). Then I tried to install the package as follows:

install.packages("ROracle-1.3.2.zip", repos=NULL)

It failed and I got the following error message:

Error in read.dcf(file.path(pkgname, "DESCRIPTION"), c("Package", "Type")) :
  cannot open the connection
In addition: Warning message:
In read.dcf(file.path(pkgname, "DESCRIPTION"), c("Package", "Type")) :
  cannot open compressed file 'ROracle-1.3.2/DESCRIPTION', probable reason 'No such file or directory'

I also tried from command line just in case:

R CMD INSTALL ROracle-1.3.2.zip

It also failed and I got the following error message:

* installing to library 'Z:/R/R-3.6.1/library'
Warning in read.dcf(file.path(pkgname, "DESCRIPTION"), c("Package", "Type")) :
  cannot open compressed file 'ROracle-1.3.2/DESCRIPTION', probable reason 'No such file or directory'
Error in read.dcf(file.path(pkgname, "DESCRIPTION"), c("Package", "Type")) :
  cannot open the connection

The DESCRIPTION file certainly exists in ROracle-1.3.2.zip. I opened it up and looked at - just a normal DESCRIPTION file.

I am using Windows 7.

How do I install ROracle?

Body:
You need to follow the following procedure:

Create a folder called "ROracle" and put the downloaded zip ROracle-1.3.2.zip in there

Unzip the .zip file in the folder. Now you have all the contents of the zip file (including the original zip file) in the ROracle folder that you created in step 1

Remove the original .zip file from the folder. Now the folder "ROracle" you created in step 1 only contains the contents of the original .zip file

Add the "ROracle" folder to a zip file called "ROracle.zip"

Got down into this solution by comparing hierarchy of earlier ROracle_1.3-1.zip -file which i got working well in earlier R version.

After following all these steps the outcome is that the DESCRIPTION file can be found in ROracle.zip/ROracle/DESCRIPTION instead of ROracle-1.3.2.zip/DESCRIPTION

With the newly zip-file from step 4 the installation is a quite straightforward.

setwd("THEPLACEWHERETHE ROracle.zip file is located)
install.packages('ROracle.zip', repos = NULL)

My .Renviron contains these lines if that matters

    # PATH="C:/Rtools/bin;C:/oracle/instantclient_19_5;$PATH"
    # OCI_LIB64 = C:/oracle/instantclient_19_5
    # BINPREF="C:/Rtools/mingw_$(WIN)/bin/"

OS is WIN10.
R version 3.6.2 (2019-12-12) -- "Dark and Stormy Night"
Platform: x86_64-w64-mingw32/x64 (64-bit)
ROracle 1.3-2


问:
MDBootsrap Form Input text overlapping label & label not working as expected onClick
I am trying to add a material design bootstrap form login from here.

The form is displaying like so:

But when I click on one of the input controls, the text is overlapping, & the label isn't moving above the input field as expected.

Here is the expected result:

And here is the actual result

Here is my HTML:

```<code><!-- Form -->
<form class="text-center" style="color: #757575;" action="#!">

  <!-- Email -->
  <div class="md-form">
    <input type="email" id="materialLoginFormEmail" class="form-control">
    <label for="materialLoginFormEmail">E-mail</label>
  </div>

  <!-- Password -->
  <div class="md-form">
    <input type="password" id="materialLoginFormPassword" class="form-control">
    <label for="materialLoginFormPassword">Password</label>
  </div>

  <div class="d-flex justify-content-around">
    <div>
      <!-- Forgot password -->
      <a href="">Forgot password?</a>
    </div>
  </div>

  <!-- Sign in button -->
  <button class="btn btn-outline-info btn-rounded btn-block my-4 waves-effect z-depth-0" type="submit">Sign
    in</button>

  <!-- Register -->
  <p>Not a member?
    <a href="">Register</a>
  </p>

</form>
<!-- Form -->
</code>```

And here are some values in my angular.json:

```<code>"styles": [
          "node_modules/@fortawesome/fontawesome-free/scss/fontawesome.scss",
          "node_modules/@fortawesome/fontawesome-free/scss/solid.scss",
          "node_modules/@fortawesome/fontawesome-free/scss/regular.scss",
          "node_modules/@fortawesome/fontawesome-free/scss/brands.scss",
          "node_modules/angular-bootstrap-md/assets/scss/bootstrap/bootstrap.scss",
          "node_modules/angular-bootstrap-md/assets/scss/mdb.scss",
          "./node_modules/quill/dist/quill.core.css",
          "./node_modules/quill/dist/quill.snow.css",
          "node_modules/animate.css/animate.css",
          "src/styles.css"
        ],
        "scripts": [
          "node_modules/chart.js/dist/Chart.js",
          "node_modules/hammerjs/hammer.min.js",
          "./node_modules/quill/dist/quill.js"
        ]
</code>```

Can someone please tell me what I'm missing, & why the form isn't working as expected? I've copied the code exactly from the tutorial I linked above.

答:
You use jQuery code, here is MDB Angular version:

https://mdbootstrap.com/docs/angular/forms/basic/

For the label to work correctly you need to add mdbInput directive to the input element.

Body:
I am trying to add a material design bootstrap form login from here.

The form is displaying like so:

But when I click on one of the input controls, the text is overlapping, & the label isn't moving above the input field as expected.

Here is the expected result:

And here is the actual result

Here is my HTML:

<form class="text-center" style="color: #757575;" action="#!">

    <input type="email" id="materialLoginFormEmail" class="form-control">
    E-mail

    <input type="password" id="materialLoginFormPassword" class="form-control">
    Password

      Forgot password?

  <button class="btn btn-outline-info btn-rounded btn-block my-4 waves-effect z-depth-0" type="submit">Sign
    in</button>

Not a member?
    Register

</form>

And here are some values in my angular.json:

"styles": [
          "node_modules/@fortawesome/fontawesome-free/scss/fontawesome.scss",
          "node_modules/@fortawesome/fontawesome-free/scss/solid.scss",
          "node_modules/@fortawesome/fontawesome-free/scss/regular.scss",
          "node_modules/@fortawesome/fontawesome-free/scss/brands.scss",
          "node_modules/angular-bootstrap-md/assets/scss/bootstrap/bootstrap.scss",
          "node_modules/angular-bootstrap-md/assets/scss/mdb.scss",
          "./node_modules/quill/dist/quill.core.css",
          "./node_modules/quill/dist/quill.snow.css",
          "node_modules/animate.css/animate.css",
          "src/styles.css"
        ],
        "scripts": [
          "node_modules/chart.js/dist/Chart.js",
          "node_modules/hammerjs/hammer.min.js",
          "./node_modules/quill/dist/quill.js"
        ]

Can someone please tell me what I'm missing, & why the form isn't working as expected? I've copied the code exactly from the tutorial I linked above.


问:
Problem with nested SQL
I have a problem with nested select in MySQL.

This one works, but I need to get two of them.

Example:

```<code>SELECT `a`.`title` , `a`.`askprice` , `a`.`picture`
, `a`.`description` , `a`.`userid` , `a`.`id`
FROM (
`mm_ads_fields_values` AS afv
)
LEFT JOIN `mm_ads` AS a ON `a`.`id` = `afv`.`aid`
WHERE `afv`.`value` = '38'
AND `a`.`category` = '227'
AND `a`.`status` =1
AND a.id
IN (
    SELECT a.id
    FROM mm_ads AS a
    LEFT JOIN mm_ads_fields_values AS afv ON afv.aid = a.id
    WHERE afv.value = '2913'
)
ORDER BY `id` DESC
LIMIT 20
</code>```

This one works. But I need SQL statement like this one:

```<code>SELECT `a`.`title` , `a`.`askprice` , `a`.`picture`
, `a`.`description` , `a`.`userid` , `a`.`id`
FROM (
`mm_ads_fields_values` AS afv
)
LEFT JOIN `mm_ads` AS a ON `a`.`id` = `afv`.`aid`
WHERE `afv`.`value` = '38'
AND `a`.`category` = '227'
AND `a`.`status` =1
AND a.id
IN (
   SELECT a.id
   FROM mm_ads AS a
   LEFT JOIN mm_ads_fields_values AS afv ON afv.aid = a.id
   WHERE afv.value = '2913'
)
AND a.id
IN (
    SELECT a.id
    FROM mm_ads AS a
    LEFT JOIN mm_ads_fields_values AS afv ON afv.aid = a.id
    WHERE afv.value = '51'
)
ORDER BY `id` DESC
LIMIT 20
</code>```

And this one, last one, won't work. Its loading, loading and never nothing happen..

What am I doing wrong?

Regards, Mario

Sorry for my bad English..

答:
Glib answer: shouldn't the second IN statement use OR instead of AND? (edit: and use correct operator precedence.)</p>

```<code>...
AND
( a.id
  IN (
     SELECT a.id
     FROM mm_ads AS a
     LEFT JOIN mm_ads_fields_values AS afv ON afv.aid = a.id
     WHERE afv.value = '2913'
  )
  OR a.id
  IN (
      SELECT a.id
      FROM mm_ads AS a
      LEFT JOIN mm_ads_fields_values AS afv ON afv.aid = a.id
      WHERE afv.value = '51'
  )
)
...
</code>```

Title: Problem with nested SQL

Body:
I have a problem with nested select in MySQL.

This one works, but I need to get two of them.

Example:

SELECT `a`.`title` , `a`.`askprice` , `a`.`picture`
, `a`.`description` , `a`.`userid` , `a`.`id`
FROM (
`mm_ads_fields_values` AS afv
)
LEFT JOIN `mm_ads` AS a ON `a`.`id` = `afv`.`aid`
WHERE `afv`.`value` = '38'
AND `a`.`category` = '227'
AND `a`.`status` =1
AND a.id
IN (
    SELECT a.id
    FROM mm_ads AS a
    LEFT JOIN mm_ads_fields_values AS afv ON afv.aid = a.id
    WHERE afv.value = '2913'
)
ORDER BY `id` DESC
LIMIT 20

This one works. But I need SQL statement like this one:

SELECT `a`.`title` , `a`.`askprice` , `a`.`picture`
, `a`.`description` , `a`.`userid` , `a`.`id`
FROM (
`mm_ads_fields_values` AS afv
)
LEFT JOIN `mm_ads` AS a ON `a`.`id` = `afv`.`aid`
WHERE `afv`.`value` = '38'
AND `a`.`category` = '227'
AND `a`.`status` =1
AND a.id
IN (
   SELECT a.id
   FROM mm_ads AS a
   LEFT JOIN mm_ads_fields_values AS afv ON afv.aid = a.id
   WHERE afv.value = '2913'
)
AND a.id
IN (
    SELECT a.id
    FROM mm_ads AS a
    LEFT JOIN mm_ads_fields_values AS afv ON afv.aid = a.id
    WHERE afv.value = '51'
)
ORDER BY `id` DESC
LIMIT 20

And this one, last one, won't work. Its loading, loading and never nothing happen..

What am I doing wrong?

Regards, Mario

Sorry for my bad English..

Body:
Glib answer: shouldn't the second IN statement use OR instead of AND? (edit: and use correct operator precedence.)

...
AND
( a.id
  IN (
     SELECT a.id
     FROM mm_ads AS a
     LEFT JOIN mm_ads_fields_values AS afv ON afv.aid = a.id
     WHERE afv.value = '2913'
  )
  OR a.id
  IN (
      SELECT a.id
      FROM mm_ads AS a
      LEFT JOIN mm_ads_fields_values AS afv ON afv.aid = a.id
      WHERE afv.value = '51'
  )
)
...


问:
Does ngx-cookie-service a complete way to do authentication for Angular Universal apps
I'm building an Angular Universal MEAN (MongoDB, Express, Angular, Node) app, but I'm looking for the correct way to handle security. I know you can't use localStorage with Angular Universal. Is ngx-cookie-service a complete way to handle security, authorization, etc.? Would implementing something like this...

```<code>https://www.npmjs.com/package/ngx-cookie-service
</code>```

...or this...

```<code>https://itnext.io/angular-8-how-to-use-cookies-14ab3f2e93fc
</code>```

Do cookies replace using tokens?

Would it replace code like this in app.js on the backend:

```<code>    app.use((req, res, next) => {
  res.setHeader("Access-Control-Allow-Origin", "*");
  res.setHeader(
    "Access-Control-Allow-Headers",
    "Origin, X-Requested-With, Content-Type, Accept, Authorization"
  );
  res.setHeader(
    "Access-Control-Allow-Methods",
    "GET, POST, PATCH, PUT, DELETE, OPTIONS"
  );
  next();
});
</code>```

app.use("/api/posts", postsRoutes);

And this on the backend...

```<code>const jwt = require("jsonwebtoken");

module.exports = (req, res, next) => {
  try {
    const token = req.headers.authorization.split(" ")[1];
    const decodedToken = jwt.verify(token, process.env.JWT_KEY);
    req.userData = { email: decodedToken.email, userId: decodedToken.userId, isAdmin: decodedToken.isAdmin };
    next();
  } catch (error) {
    res.status(401).json({ message: "You are not authenticated!" });
  }
};
</code>```

If you have a link to a good example of the code for a simple MEAN stack Angular Univeral app demonstrating the correct way to use cookies, please share. Or perhaps an article with the broad strokes explained if it is a complex explanation. Thank you for your time. It's greatly appreciated.

K

答:
ngx-cookies does not provide a 'complete' way to perform authentication, just an easy way to set/get cookies when using angular universal.

In your backend, install and use cookieParser

```<code>const cookieParser = require('cookie-parser');
app.use(cookieParser());
</code>```

Then, instead of getting your jwt from a custom Authorization header, get it from the cookie

```<code>const token = req.cookies.authorization.split(" ")[1];
</code>```

Body:
I'm building an Angular Universal MEAN (MongoDB, Express, Angular, Node) app, but I'm looking for the correct way to handle security. I know you can't use localStorage with Angular Universal. Is ngx-cookie-service a complete way to handle security, authorization, etc.? Would implementing something like this...

https://www.npmjs.com/package/ngx-cookie-service

...or this...

https://itnext.io/angular-8-how-to-use-cookies-14ab3f2e93fc

Do cookies replace using tokens?

Would it replace code like this in app.js on the backend:

    app.use((req, res, next) => {
  res.setHeader("Access-Control-Allow-Origin", "*");
  res.setHeader(
    "Access-Control-Allow-Headers",
    "Origin, X-Requested-With, Content-Type, Accept, Authorization"
  );
  res.setHeader(
    "Access-Control-Allow-Methods",
    "GET, POST, PATCH, PUT, DELETE, OPTIONS"
  );
  next();
});

app.use("/api/posts", postsRoutes);

And this on the backend...

const jwt = require("jsonwebtoken");

module.exports = (req, res, next) => {
  try {
    const token = req.headers.authorization.split(" ")[1];
    const decodedToken = jwt.verify(token, process.env.JWT_KEY);
    req.userData = { email: decodedToken.email, userId: decodedToken.userId, isAdmin: decodedToken.isAdmin };
    next();
  } catch (error) {
    res.status(401).json({ message: "You are not authenticated!" });
  }
};

If you have a link to a good example of the code for a simple MEAN stack Angular Univeral app demonstrating the correct way to use cookies, please share. Or perhaps an article with the broad strokes explained if it is a complex explanation. Thank you for your time. It's greatly appreciated.

K

Body:
ngx-cookies does not provide a 'complete' way to perform authentication, just an easy way to set/get cookies when using angular universal.

In your backend, install and use cookieParser

const cookieParser = require('cookie-parser');
app.use(cookieParser());

Then, instead of getting your jwt from a custom Authorization header, get it from the cookie

const token = req.cookies.authorization.split(" ")[1];


问:
Is it safe to remove an entry within the foreach loop of a mutable.Map in Scala?
I know we should be cautious when removing an entry while traversing a collection in many languages like C++ or Java, but not sure if Scala makes any difference.

So is below code snippet safe?

val mutableMap: [String, List[String]] = ...
mutableMap.foreach { case (k, list) =>
  // do sth. to list
  if (list.isEmtpy) mutableMap -= k
}
```

<p>What's the recommended way if I want to update the value for a <code>(k -> v)</code> mapping?</p>

<pre class="lang-scala prettyprint-override"><code>val mutableMap: [String, List[String]] = ...
mutableMap.foreach { case (k, list) =>
  mutableMap += (k, anotherList) // is this safe?
}
</code>```

Thanks!

答:
I guess you can achieve same with an immutable map like below;

```<code>val map: Map[String, List[Int]] = Map(
    "apple"     -> List(),
    "orange"    -> List(1),
    "banana"    -> List(1, 2),
    "pineapple" -> List(1, 2, 3),
    "kiwi"      -> List(1, 2, 3, 4)
  )

def doSomething(list: List[Int]) = ()

map.foldLeft(map) {
    case (acc, (key, value)) =>
      doSomething(value)
      if (value.isEmpty) acc - key else acc
  }
</code>```

but I expect doSomething method is probably doing something that would count as a side effect. If you can afford using the cats library i would suggest you to do it in a way like below;

```<code>import cats.effect.IO
import cats.implicits._

def doSomething(list: List[Int]): IO[Option[List[Int]]] = IO.pure(Some(list).filter(_.nonEmpty))

val program = map.toList
    .traverseFilter { case (key, value) => doSomething(value).map(_.map(key -> _))}
    .map(_.toMap)

program.unsafeRunSync()
</code>```

Body:
I know we should be cautious when removing an entry while traversing a collection in many languages like C++ or Java, but not sure if Scala makes any difference.

So is below code snippet safe?

val mutableMap: [String, List[String]] = ...
mutableMap.foreach { case (k, list) =>
  // do sth. to list
  if (list.isEmtpy) mutableMap -= k
}

What's the recommended way if I want to update the value for a (k -> v) mapping?

val mutableMap: [String, List[String]] = ...
mutableMap.foreach { case (k, list) =>
  mutableMap += (k, anotherList) // is this safe?
}

Thanks!

Body:
I guess you can achieve same with an immutable map like below;

val map: Map[String, List[Int]] = Map(
    "apple"     -> List(),
    "orange"    -> List(1),
    "banana"    -> List(1, 2),
    "pineapple" -> List(1, 2, 3),
    "kiwi"      -> List(1, 2, 3, 4)
  )

def doSomething(list: List[Int]) = ()

map.foldLeft(map) {
    case (acc, (key, value)) =>
      doSomething(value)
      if (value.isEmpty) acc - key else acc
  }

but I expect doSomething method is probably doing something that would count as a side effect. If you can afford using the cats library i would suggest you to do it in a way like below;

import cats.effect.IO
import cats.implicits._

def doSomething(list: List[Int]): IO[Option[List[Int]]] = IO.pure(Some(list).filter(_.nonEmpty))

val program = map.toList
    .traverseFilter { case (key, value) => doSomething(value).map(_.map(key -> _))}
    .map(_.toMap)

program.unsafeRunSync()


问:
Is there a way to cue a Youtube video in an iframe to rounded seconds?
I am using the YouTube Iframe API during playing the video i want to play something else quite simultaneously.
I get in trouble when the video is cued to a specific point, because it is not possible to get the milliseconds.

My thought was to to round down the current time by using the code below:

```<code>function onPlayerStateChange(event) {
    if(event.data == YT.PlayerState.CUED){
         player.seekTo(player.getCurrentTime())
    }
  }
</code>```

But this is not working, if the video was cued to 23.4 seconds it just stays at 23.4.

答:
I solved this problem by using a newer Version of the API where player.getCurrentTime() returns a float.

Read the docs here

Body:
I am using the YouTube Iframe API during playing the video i want to play something else quite simultaneously.
I get in trouble when the video is cued to a specific point, because it is not possible to get the milliseconds.

My thought was to to round down the current time by using the code below:

function onPlayerStateChange(event) {
    if(event.data == YT.PlayerState.CUED){
         player.seekTo(player.getCurrentTime())
    }
  }

But this is not working, if the video was cued to 23.4 seconds it just stays at 23.4.


问:
Symfony2: Pass a second object to a Voter
I'm using a voter to determine whether or not the logged in user can edit a given object. One of the criteria requires a comparison with another object but I'm not sure how to pass this into the voter. I cannot use the constructor arguments as it is not a predefined value.

Basically I would like to do something like this:

```<code> protected function voteOnAttribute($attribute, $subject, TokenInterface $token, $comparedObject)
            { if ($subject->getProperty1 == $comparedObject)
    {return true;}
    }
</code>```

Any help would be appreciated.

答:
It's a bit late but maybe this answer is going to be helpfull for someone.

One thing that you can do is pass an array of values instance of a single $subject object.

For example, from Twig you use your function as:

```<code>{% set data =  { 'subject': yourRealSubject, 'compared_object': comparedObject } %}
{% if is_granted('can_edit', data) %}
...
...
{% endif %}
</code>```

(You can do the same from PHP code).

So then in your Voter:

```<code>class MyVoter  extends Voter{

        // ...

        protected function voteOnAttribute($attribute, $data, TokenInterface $token) {

                $subject = isset($data['subject']) ? $data['subject'] : null;
                $comparedObject = isset($data['compared_object']) ? $data['compared_object'] : null;

                if(!$subject || !$subject instanceof \Namespace\To\Subject){
                      throw new Exception('Missing or invalid subject!!!'');
                }

                // do whatever you want ...

        }
}
</code>```

Body:
I'm using a voter to determine whether or not the logged in user can edit a given object. One of the criteria requires a comparison with another object but I'm not sure how to pass this into the voter. I cannot use the constructor arguments as it is not a predefined value.

Basically I would like to do something like this:

 protected function voteOnAttribute($attribute, $subject, TokenInterface $token, $comparedObject)
            { if ($subject->getProperty1 == $comparedObject)
    {return true;}
    }

Any help would be appreciated.

Body:
It's a bit late but maybe this answer is going to be helpfull for someone.

One thing that you can do is pass an array of values instance of a single $subject object.

For example, from Twig you use your function as:

{% set data =  { 'subject': yourRealSubject, 'compared_object': comparedObject } %}
{% if is_granted('can_edit', data) %}
...
...
{% endif %}

(You can do the same from PHP code).

So then in your Voter:

class MyVoter  extends Voter{

        // ...

        protected function voteOnAttribute($attribute, $data, TokenInterface $token) {

                $subject = isset($data['subject']) ? $data['subject'] : null;
                $comparedObject = isset($data['compared_object']) ? $data['compared_object'] : null;

                if(!$subject || !$subject instanceof \Namespace\To\Subject){
                      throw new Exception('Missing or invalid subject!!!'');
                }

                // do whatever you want ...

        }
}


问:
Python "list order"
I have 2 troubles with my data, can anyone help me:

How can I get from this:

1.

```<code>k=[['1','7', 'U1'],
 ['1.5', '8', 'U1'],
 ['2', '5.5', 'U1']]
</code>```

get this

```<code>1,7,U1
1.5,8,U1
2,5.5,U1
</code>```

EDIT 2   I MAKE SOME CHANGE ON  second case:, still searching solution for this one:

2. And how to get, from this

```<code>l=array([[[ 4.24231542], 'U1'],
       [[ 3.41424819], 'U1'],
       [[ 2.17214734], 'U1'],], dtype=object)
</code>```

get

```<code>4.24231542,U1
3.41424819,U1
2.17214734,U1
</code>```

Thanks

Title: Python "list order"

Body:
I have 2 troubles with my data, can anyone help me:

How can I get from this:

1.

k=[['1','7', 'U1'],
 ['1.5', '8', 'U1'],
 ['2', '5.5', 'U1']]

get this

1,7,U1
1.5,8,U1
2,5.5,U1

EDIT 2   I MAKE SOME CHANGE ON  second case:, still searching solution for this one:

2. And how to get, from this

l=array([[[ 4.24231542], 'U1'],
       [[ 3.41424819], 'U1'],
       [[ 2.17214734], 'U1'],], dtype=object)

get

4.24231542,U1
3.41424819,U1
2.17214734,U1

Thanks

Body:
Here is a single solution that will work for both 1 and 2:

k = [['1', '7', 'U1'], ['1.5', '8', 'U1'], ['2', '5.5', 'U1']]
l = [[[4.2423154199999997], 'U1'], [[3.4142481899999999], 'U1'], [[2.17214734], 'U1']]

make_string = lambda x: ",".join(map(make_string, x)) if isinstance(x, list) else str(x)

print "\n".join(map(make_string, k))
print "\n".join(map(make_string, l))