问:
shell script in bash using regex in while loop
Hi i am try to validate user inputs to be not empty and is a number or with decimal

```<code>re='^[0-9]+$'
while [ "$num" == "" ] && [[ "$num" ~= $re ]]
do
echo "Please enter the price : "
read num
done
</code>```

I was able to run smooth with just the 1st condition. When i add 2nd condition my program couldn't run.

----EDIT----------

Ok i try changing and the program run. But when i enter a number it still prompting for input.

```<code>re='^[0-9]+$'
while [ "$num" == "" ] && [ "$num" != $re ]
do
echo "Please enter the price : "
read num
done
</code>```

答:
First off, there is the classic logic trap demonstrated in the OP's question:

```<code>while [ "$num" == "" ] && [ "$num" != $re ]
</code>```

The issue here is the && which pretty much means the moment the left expression is false, the entire expression is false. i.e. the moment somebody types a non empty response, it breaks the loop and the regular expression test is never used. To fix the logic problem, one should consider changing && to ||, i.e.

```<code>while [ "$num" == "" ] || [ "$num" != $re ]
</code>```

The second issue, is we are testing for negative matches to regular expression, pattern. So, this is done in two parts, one we need to use [[ "$num" =~ $re ]] for regular expression testing. Then, we need to look for negative matches, i.e. append a ! which yields:

```<code>while [ "$num" == "" ] || ! [[ "$num" =~ $re ]
</code>```

Having got this far, many people observed that there is actually no need to test for the empty string. That edge condition is already covered by the regular expression itself, so, we optimize out the redundant test. The answer now reduces to:

```<code>while ! [[ "$num" =~ $re ]
</code>```

In addition to the above observation, here are my notes about regular expression ( some of the observation has been collated from other answers ):

regular expressions can be tested with the [[ "$str" =~ regex ]] syntax

regular expressions match with $? == 0 ( 0 == no error )

regular expressions do not match with $? == 1 ( 1 == error )

regular expressions do not seem to work when quoted. recommend using [0-9] not "[0-9]"

To implement a number validation, the following pattern seems to work:

```<code>str=""
while ! [[ "${str?}" =~ ^[0-9]+$ ]]
do
  read -p "enter a number: " str
done
</code>```

You can mix regular expression filters with regular arithmetic filters for some really nice validation results:

```<code>str=""
while ! [[ "${str?}" =~ ^[0-9]+$ ]] \
    || (( str < 1 || str > 15 ))
do
  read -p "enter a number between 1 and 15: " str
done
</code>```

N.B. I used the ${str?} syntax ( instead of $str ) for variable expansion as it demonstrates good practice for catching typos.

Body:
Hi i am try to validate user inputs to be not empty and is a number or with decimal

re='^[0-9]+$'
while [ "$num" == "" ] && [[ "$num" ~= $re ]]
do
echo "Please enter the price : "
read num
done

I was able to run smooth with just the 1st condition. When i add 2nd condition my program couldn't run.

----EDIT----------

Ok i try changing and the program run. But when i enter a number it still prompting for input.

re='^[0-9]+$'
while [ "$num" == "" ] && [ "$num" != $re ]
do
echo "Please enter the price : "
read num
done

Body:
First off, there is the classic logic trap demonstrated in the OP's question:

while [ "$num" == "" ] && [ "$num" != $re ]

The issue here is the && which pretty much means the moment the left expression is false, the entire expression is false. i.e. the moment somebody types a non empty response, it breaks the loop and the regular expression test is never used. To fix the logic problem, one should consider changing && to ||, i.e.

while [ "$num" == "" ] || [ "$num" != $re ]

The second issue, is we are testing for negative matches to regular expression, pattern. So, this is done in two parts, one we need to use [[ "$num" =~ $re ]] for regular expression testing. Then, we need to look for negative matches, i.e. append a ! which yields:

while [ "$num" == "" ] || ! [[ "$num" =~ $re ]

Having got this far, many people observed that there is actually no need to test for the empty string. That edge condition is already covered by the regular expression itself, so, we optimize out the redundant test. The answer now reduces to:

while ! [[ "$num" =~ $re ]

In addition to the above observation, here are my notes about regular expression ( some of the observation has been collated from other answers ):

regular expressions can be tested with the [[ "$str" =~ regex ]] syntax

regular expressions match with $? == 0 ( 0 == no error )

regular expressions do not match with $? == 1 ( 1 == error )

regular expressions do not seem to work when quoted. recommend using [0-9] not "[0-9]"

To implement a number validation, the following pattern seems to work:

str=""
while ! [[ "${str?}" =~ ^[0-9]+$ ]]
do
  read -p "enter a number: " str
done

You can mix regular expression filters with regular arithmetic filters for some really nice validation results:

str=""
while ! [[ "${str?}" =~ ^[0-9]+$ ]] \
    || (( str < 1 || str > 15 ))
do
  read -p "enter a number between 1 and 15: " str
done

N.B. I used the ${str?} syntax ( instead of $str ) for variable expansion as it demonstrates good practice for catching typos.


来源: stackexchange

问:
Problem with reading last line of code algorithm - c++
I found this code on Stackoverflow:

```<code>    if (file.is_open())
    {
        file.seekg(-1, std::ios_base::end);
        if (file.peek() == '\n')
        {
            //Start searching for \n occurrences
            file.seekg(-1, std::ios_base::cur);
            int i = file.tellg();
            for (i;i > 0; i--)
            {
                if (file.peek() == '\n')
                {
                    //Found
                    file.get();
                    break;
                }
                //Move one character back
                file.seekg(i, std::ios_base::beg);
            }
                string line;
                getline(file,line);
        }
</code>```

It saves the last line of file in variable 'line', and it works ok, but if the last line is the first line it doesn't read the first character of line (the rest is read). When the last line is eg.the third line everything works. What's the problem?

答:
The problem is that all of your code only runs when the last character is '\n'.

If that is not so, then your program does nothing.

You need to rethink the if (file.peek() == '\n') part.

ContentLicense: CC BY-SA 4.0

Body:
I found this code on Stackoverflow:

    if (file.is_open())
    {
        file.seekg(-1, std::ios_base::end);
        if (file.peek() == '\n')
        {
            //Start searching for \n occurrences
            file.seekg(-1, std::ios_base::cur);
            int i = file.tellg();
            for (i;i > 0; i--)
            {
                if (file.peek() == '\n')
                {
                    //Found
                    file.get();
                    break;
                }
                //Move one character back
                file.seekg(i, std::ios_base::beg);
            }
                string line;
                getline(file,line);
        }

It saves the last line of file in variable 'line', and it works ok, but if the last line is the first line it doesn't read the first character of line (the rest is read). When the last line is eg.the third line everything works. What's the problem?


问:
pytest monkeypatch terminal size
I'm playing with the monkeypatch fixture in pytest, trying to mock the current size of the terminal window.

```<code>import os
import pytest

def get_terminal_size():
    terminal_size = os.popen('stty size', 'r').read()
    return terminal_size

def test_get_terminal_size(monkeypatch):
    # The get_terminal_size() function will return a string 'height width\n'
    def mock_size():
        return '10 20\n'

    monkeypatch.setattr(os.popen('stty size', 'r'), 'read', mock_size)

    assert get_terminal_size() == '10 20\n'
</code>```

When I run pytest I get an assertion error:

```<code>__________________________________________________________________ test_get_terminal_size __________________________________________________________________

monkeypatch = <_pytest.monkeypatch.MonkeyPatch object at 0x7f5bf1ec0cf8>

    def test_get_terminal_size(monkeypatch):
        # The get_terminal_size() function will return a string 'height width\n'
        def mock_size():
            return '10 20\n'

        monkeypatch.setattr(os.popen('stty size', 'r'), 'read', mock_size)

>       assert get_terminal_size() == '10 20\n'
E       AssertionError: assert '' == '10 20\n'
E         + 10 20

test_monkeypatch.py:15: AssertionError
</code>```

So it looks like it isn't setting the mock_size. I've tried following the pattern in the pytest documentation

Any suggestions on getting this to work?

Thanks in advance!

Update:
As pointed out by Kent Shikama in the answer below, for the way I was attempting to capture the output I needed to be using the -s flag to turn off pytest capturing.

But with further research about the usage of popen, specifically, the migration from using os.popen to subprocess.Popen, see here, and some help from this S.O. post on "How to fake Popen" I've come up with a solution.

here is the new setup:

```<code># \mokeypatch_popen.py
from subprocess import Popen

def get_terminal_size():
    terminal_size = Popen('stty size', shell=True)
    return terminal_size
</code>```

The test function:

```<code># \test_monkeypatch.py
import pytest
import monkeypatch_popen

def test_get_terminal_size(monkeypatch):
    # The get_terminal_size() function will return a string 'height width\n'
    def mock_terminal_size(cmd, **kwargs):
        return '10 20\n'

    monkeypatch.setattr(m_patch, 'Popen' , mock_terminal_size)

    assert m_patch.get_terminal_size() == '10 20\n'
</code>```

Not obvious to me at first was the fact that the mock_terminal_size function will be processing the parameters of the Popen method it is mocking, therefore it must accept the parameters used by Popen in the original function. I could have specifically added the shell parameter to mock_terminal_size, but since Popen accepts a long list of kwargs I was a bit more ambiguous.

This now passes when I run pytest and the -s flag is not necessary as I'm no longer attempting to capture an output, but mocking the execution of the Popen method.

答:
First, you need to run pytest with the -s flag or else stty will be captured. And then you should get the assertion error you were probably expecting as follows:

```<code>>       assert get_terminal_size() == '10 20\n'
E       AssertionError: assert '24 80\n' == '10 20\n'
E         - 24 80
E         + 10 20
</code>```

It sounds like you want to mock the read method on the stream such that it always runs "10 20". Usually you would do something like

```<code>from io import TextIOWrapper
monkeypatch.setattr(TextIOWrapper, 'read', mock_size)
</code>```

but unfortunately you can't mock a builtin object. You could try something like forbiddenfruit to overcome this but it feels like you might want to change your approach.

Title: pytest monkeypatch terminal size

Body:
I'm playing with the monkeypatch fixture in pytest, trying to mock the current size of the terminal window.

import os
import pytest

def get_terminal_size():
    terminal_size = os.popen('stty size', 'r').read()
    return terminal_size

def test_get_terminal_size(monkeypatch):
    # The get_terminal_size() function will return a string 'height width\n'
    def mock_size():
        return '10 20\n'

    monkeypatch.setattr(os.popen('stty size', 'r'), 'read', mock_size)

    assert get_terminal_size() == '10 20\n'

When I run pytest I get an assertion error:

__________________________________________________________________ test_get_terminal_size __________________________________________________________________

monkeypatch = <_pytest.monkeypatch.MonkeyPatch object at 0x7f5bf1ec0cf8>

    def test_get_terminal_size(monkeypatch):
        # The get_terminal_size() function will return a string 'height width\n'
        def mock_size():
            return '10 20\n'

        monkeypatch.setattr(os.popen('stty size', 'r'), 'read', mock_size)

>       assert get_terminal_size() == '10 20\n'
E       AssertionError: assert '' == '10 20\n'
E         + 10 20

test_monkeypatch.py:15: AssertionError

So it looks like it isn't setting the mock_size. I've tried following the pattern in the pytest documentation

Any suggestions on getting this to work?

Thanks in advance!

Update:
As pointed out by Kent Shikama in the answer below, for the way I was attempting to capture the output I needed to be using the -s flag to turn off pytest capturing.

But with further research about the usage of popen, specifically, the migration from using os.popen to subprocess.Popen, see here, and some help from this S.O. post on "How to fake Popen" I've come up with a solution.

here is the new setup:

# \mokeypatch_popen.py
from subprocess import Popen

def get_terminal_size():
    terminal_size = Popen('stty size', shell=True)
    return terminal_size

The test function:

# \test_monkeypatch.py
import pytest
import monkeypatch_popen

def test_get_terminal_size(monkeypatch):
    # The get_terminal_size() function will return a string 'height width\n'
    def mock_terminal_size(cmd, **kwargs):
        return '10 20\n'

    monkeypatch.setattr(m_patch, 'Popen' , mock_terminal_size)

    assert m_patch.get_terminal_size() == '10 20\n'

Not obvious to me at first was the fact that the mock_terminal_size function will be processing the parameters of the Popen method it is mocking, therefore it must accept the parameters used by Popen in the original function. I could have specifically added the shell parameter to mock_terminal_size, but since Popen accepts a long list of kwargs I was a bit more ambiguous.

This now passes when I run pytest and the -s flag is not necessary as I'm no longer attempting to capture an output, but mocking the execution of the Popen method.

Body:
First, you need to run pytest with the -s flag or else stty will be captured. And then you should get the assertion error you were probably expecting as follows:

>       assert get_terminal_size() == '10 20\n'
E       AssertionError: assert '24 80\n' == '10 20\n'
E         - 24 80
E         + 10 20

It sounds like you want to mock the read method on the stream such that it always runs "10 20". Usually you would do something like

from io import TextIOWrapper
monkeypatch.setattr(TextIOWrapper, 'read', mock_size)

but unfortunately you can't mock a builtin object. You could try something like forbiddenfruit to overcome this but it feels like you might want to change your approach.


问:
Delete all product attributes magento
What is the fastest way to delete all attribute options from magento.  I'm refering to the stored multi-select options / drop down items that are created when importing.

Thanks.

答:
The easiest way is to run direct sql command:

```<code>DELETE options FROM eav_attribute AS attribute INNER JOIN eav_attribute_option AS options ON attribute.attribute_id = options.attribute_id WHERE attribute.entity_type_id = 4
</code>```

Where "4" is the entity_type_id for catalog_product (double check this value in your eav_entity_type table for entity_code 'catalog_product')

ContentLicense: CC BY-SA 3.0

Title: Delete all product attributes magento

Body:
The easiest way is to run direct sql command:

DELETE options FROM eav_attribute AS attribute INNER JOIN eav_attribute_option AS options ON attribute.attribute_id = options.attribute_id WHERE attribute.entity_type_id = 4

Where "4" is the entity_type_id for catalog_product (double check this value in your eav_entity_type table for entity_code 'catalog_product')


问:
Differing state in select input and dynamic url in React
I have a select input pulling JSON data of Japanese prefectures using React.  Users select prefectures by name.

The select input value is set as state.prefecture, which calls "Tokyo", for example. I'm mapping this data to the select options from a local JSON file.

In the dynamic URL JSON fetch call ${state.prefecture}, I need the prefectural code instead of the name, "13" in the case of Tokyo.

Is there a good way of doing this?

答: I set the option value equal to the prefectural code, then set the select input value to value={(state.prefecture, state.code)}


问:
Read any file (image ,mp3 ,or video ,or text ) in binary format in python
This is my attempt to convert the string in to binary format:

```<code>  std ="this is the code"
  res=''.join(format(ord(i),'b')for i in test_str)
  print(" this is the conversion "+str(res))

</code>```

output:

this  is conversion

  11101001101000110100111100111000001101001111001110000011101001101000110010110000011000111101111110010
  01100101

How to do with type of file(ex.text,video,mp3 etc) in binary format?

答:
I believe your question is not strictly related to Python, but for any language, as the problem relates to: What is a binary file. A binary file is just 0 and 1 (many times is read directly in hexa) for which you have to know how the structure that is saved (usually a struct) is being serialized.

For that reason, you have to know what kind of file you're reading, and have a Parser that will know the binary structure for that specific file. That's why you have libraries. Each library knows one or multiple types of files to read/write. In Linux (for example), the extension is completely irrelevant, the content of the file is the one that's important.

To be more exact for your request, some links to help you drive through How to read/process <your-file-format> in python (know that extension is not important, the file format is important!)

to read .mp3: Read MP3 in Python 3

to read .wmv: Is there a library like pymedia, but more updated?

to read .jpeg: https://www.geeksforgeeks.org/reading-images-in-python/

Body:
This is my attempt to convert the string in to binary format:

  std ="this is the code"
  res=''.join(format(ord(i),'b')for i in test_str)
  print(" this is the conversion "+str(res))

output:

this  is conversion

  11101001101000110100111100111000001101001111001110000011101001101000110010110000011000111101111110010
  01100101

How to do with type of file(ex.text,video,mp3 etc) in binary format?


问:
How to parse JSON data and print on terminal in flutter?
This is my Json data :

```<code>     {
   "result":"0",
   "school_name":"Global Academy International",
   "school_code":"GAIS",
   "dashboard":"{\"privilege\":[{\"activity_id\":159,\"privilege_desc\":\"V4_MYPROFILE\",\"activity_desc\":\"V4_DASHBOARD\",\"privilege_id\":1185},{\"activity_id\":159,\"privilege_desc\":\"V4_MYTIMETABLE\",\"activity_desc\":\"V4_DASHBOARD\",\"privilege_id\":1186},{\"activity_id\":159,\"privilege_desc\":\"V4_MYATTENDANCE\",\"activity_desc\":\"V4_DASHBOARD\",\"privilege_id\":1188},{\"activity_id\":159,\"privilege_desc\":\"V4_MYLEAVESTATUS\",\"activity_desc\":\"V4_DASHBOARD\",\"privilege_id\":1189},{\"activity_id\":159,\"privilege_desc\":\"V4_MEMO\",\"activity_desc\":\"V4_DASHBOARD\",\"privilege_id\":1193},{\"activity_id\":161,\"privilege_desc\":\"V4_SUBJECTWISE\",\"activity_desc\":\"V4_STUDENT_ATTENDANCE\",\"privilege_id\":1198},{\"activity_id\":161,\"privilege_desc\":\"V4_SUBJECTWISELATE\",\"activity_desc\":\"V4_STUDENT_ATTENDANCE\",\"privilege_id\":1201},{\"activity_id\":162,\"privilege_desc\":\"V4_LEAVE_REQUISITION\",\"activity_desc\":\"V4_TEACHER_LEAVE\",\"privilege_id\":1203},{\"activity_id\":164,\"privilege_desc\":\"V4_ASSIGNMENT\",\"activity_desc\":\"V4_STUDENT_ASSIGNMENT\",\"privilege_id\":1206},{\"activity_id\":166,\"privilege_desc\":\"V4_SCHOOL_CALENDAR\",\"activity_desc\":\"V4_CALENDAR\",\"privilege_id\":1208},{\"activity_id\":168,\"privilege_desc\":\"V4_LOGOUT\",\"activity_desc\":\"V4_LOGOUT\",\"privilege_id\":1210}],\"resultPrivilege\":\"0\",\"resultProfile\":\"0\",\"profile\":{\"empid\":\"EMP183\",\"name\":\"BACHIR Raji Kashkash\",\"designation\":\"TEACHER\",\"photo_path\":\"/container/school_data/GAIS/photo/Staff/EMP183.jpg\",\"department_name\":\"HIGH SCHOOL - T\"}}",
   "employee_id":"EMP183",
   "school_url":"http://ict.gaiqatar.com"
}
</code>```

I want to print only  this data from jSON data:

```<code>[{\"activity_id\":159,\"privilege_desc\":\"V4_MYPROFILE\",\"activity_desc\":\"V4_DASHBOARD\",\"privilege_id\":1185},{\"activity_id\":159,\"privilege_desc\":\"V4_MYTIMETABLE\",\"activity_desc\":\"V4_DASHBOARD\",\"privilege_id\":1186},{\"activity_id\":168,\"privilege_desc\":\"V4_LOGOUT\",\"activity_desc\":\"V4_LOGOUT\",\"privilege_id\":1210}]
</code>```

How to get this data from whole jSON data ?

Body:
This is my Json data :

     {
   "result":"0",
   "school_name":"Global Academy International",
   "school_code":"GAIS",
   "dashboard":"{\"privilege\":[{\"activity_id\":159,\"privilege_desc\":\"V4_MYPROFILE\",\"activity_desc\":\"V4_DASHBOARD\",\"privilege_id\":1185},{\"activity_id\":159,\"privilege_desc\":\"V4_MYTIMETABLE\",\"activity_desc\":\"V4_DASHBOARD\",\"privilege_id\":1186},{\"activity_id\":159,\"privilege_desc\":\"V4_MYATTENDANCE\",\"activity_desc\":\"V4_DASHBOARD\",\"privilege_id\":1188},{\"activity_id\":159,\"privilege_desc\":\"V4_MYLEAVESTATUS\",\"activity_desc\":\"V4_DASHBOARD\",\"privilege_id\":1189},{\"activity_id\":159,\"privilege_desc\":\"V4_MEMO\",\"activity_desc\":\"V4_DASHBOARD\",\"privilege_id\":1193},{\"activity_id\":161,\"privilege_desc\":\"V4_SUBJECTWISE\",\"activity_desc\":\"V4_STUDENT_ATTENDANCE\",\"privilege_id\":1198},{\"activity_id\":161,\"privilege_desc\":\"V4_SUBJECTWISELATE\",\"activity_desc\":\"V4_STUDENT_ATTENDANCE\",\"privilege_id\":1201},{\"activity_id\":162,\"privilege_desc\":\"V4_LEAVE_REQUISITION\",\"activity_desc\":\"V4_TEACHER_LEAVE\",\"privilege_id\":1203},{\"activity_id\":164,\"privilege_desc\":\"V4_ASSIGNMENT\",\"activity_desc\":\"V4_STUDENT_ASSIGNMENT\",\"privilege_id\":1206},{\"activity_id\":166,\"privilege_desc\":\"V4_SCHOOL_CALENDAR\",\"activity_desc\":\"V4_CALENDAR\",\"privilege_id\":1208},{\"activity_id\":168,\"privilege_desc\":\"V4_LOGOUT\",\"activity_desc\":\"V4_LOGOUT\",\"privilege_id\":1210}],\"resultPrivilege\":\"0\",\"resultProfile\":\"0\",\"profile\":{\"empid\":\"EMP183\",\"name\":\"BACHIR Raji Kashkash\",\"designation\":\"TEACHER\",\"photo_path\":\"/container/school_data/GAIS/photo/Staff/EMP183.jpg\",\"department_name\":\"HIGH SCHOOL - T\"}}",
   "employee_id":"EMP183",
   "school_url":"http://ict.gaiqatar.com"
}

I want to print only  this data from jSON data:

[{\"activity_id\":159,\"privilege_desc\":\"V4_MYPROFILE\",\"activity_desc\":\"V4_DASHBOARD\",\"privilege_id\":1185},{\"activity_id\":159,\"privilege_desc\":\"V4_MYTIMETABLE\",\"activity_desc\":\"V4_DASHBOARD\",\"privilege_id\":1186},{\"activity_id\":168,\"privilege_desc\":\"V4_LOGOUT\",\"activity_desc\":\"V4_LOGOUT\",\"privilege_id\":1210}]

How to get this data from whole jSON data ?

Body:
The Json Data

final jsonData = """{
   "result":"0",
   "school_name":"Global Academy International",
   "school_code":"GAIS",
   "dashboard":"{\\"privilege\\":[{\\"activity_id\\":159,\\"privilege_desc\\":\\"V4_MYPROFILE\\",\\"activity_desc\\":\\"V4_DASHBOARD\\",\\"privilege_id\\":1185},{\\"activity_id\\":159,\\"privilege_desc\\":\\"V4_MYTIMETABLE\\",\\"activity_desc\\":\\"V4_DASHBOARD\\",\\"privilege_id\\":1186},{\\"activity_id\\":159,\\"privilege_desc\\":\\"V4_MYATTENDANCE\\",\\"activity_desc\\":\\"V4_DASHBOARD\\",\\"privilege_id\\":1188},{\\"activity_id\\":159,\\"privilege_desc\\":\\"V4_MYLEAVESTATUS\\",\\"activity_desc\\":\\"V4_DASHBOARD\\",\\"privilege_id\\":1189},{\\"activity_id\\":159,\\"privilege_desc\\":\\"V4_MEMO\\",\\"activity_desc\\":\\"V4_DASHBOARD\\",\\"privilege_id\\":1193},{\\"activity_id\\":161,\\"privilege_desc\\":\\"V4_SUBJECTWISE\\",\\"activity_desc\\":\\"V4_STUDENT_ATTENDANCE\\",\\"privilege_id\\":1198},{\\"activity_id\\":161,\\"privilege_desc\\":\\"V4_SUBJECTWISELATE\\",\\"activity_desc\\":\\"V4_STUDENT_ATTENDANCE\\",\\"privilege_id\\":1201},{\\"activity_id\\":162,\\"privilege_desc\\":\\"V4_LEAVE_REQUISITION\\",\\"activity_desc\\":\\"V4_TEACHER_LEAVE\\",\\"privilege_id\\":1203},{\\"activity_id\\":164,\\"privilege_desc\\":\\"V4_ASSIGNMENT\\",\\"activity_desc\\":\\"V4_STUDENT_ASSIGNMENT\\",\\"privilege_id\\":1206},{\\"activity_id\\":166,\\"privilege_desc\\":\\"V4_SCHOOL_CALENDAR\\",\\"activity_desc\\":\\"V4_CALENDAR\\",\\"privilege_id\\":1208},{\\"activity_id\\":168,\\"privilege_desc\\":\\"V4_LOGOUT\\",\\"activity_desc\\":\\"V4_LOGOUT\\",\\"privilege_id\\":1210}],\\"resultPrivilege\\":\\"0\\",\\"resultProfile\\":\\"0\\",\\"profile\\":{\\"empid\\":\\"EMP183\\",\\"name\\":\\"BACHIR Raji Kashkash\\",\\"designation\\":\\"TEACHER\\",\\"photo_path\\":\\"/container/school_data/GAIS/photo/Staff/EMP183.jpg\\",\\"department_name\\":\\"HIGH SCHOOL - T\\"}}",
   "employee_id":"EMP183",
   "school_url":"http://ict.gaiqatar.com"
}""";

Used double \\ to scape correctly the char "...

And then:

final parsedJson = json.decode(jsonData);
print(parsedJson['dashboard']);

If you prefer, you can parse only dashboard section to filter some itens programaticaly...

final dashboardParsed = json.decode(parsedJson['dashboard']);
print(dashboardParsed);

Final result

final jsonData = """{
   "result":"0",
   "school_name":"Global Academy International",
   "school_code":"GAIS",
   "dashboard":"{\\"privilege\\":[{\\"activity_id\\":159,\\"privilege_desc\\":\\"V4_MYPROFILE\\",\\"activity_desc\\":\\"V4_DASHBOARD\\",\\"privilege_id\\":1185},{\\"activity_id\\":159,\\"privilege_desc\\":\\"V4_MYTIMETABLE\\",\\"activity_desc\\":\\"V4_DASHBOARD\\",\\"privilege_id\\":1186},{\\"activity_id\\":159,\\"privilege_desc\\":\\"V4_MYATTENDANCE\\",\\"activity_desc\\":\\"V4_DASHBOARD\\",\\"privilege_id\\":1188},{\\"activity_id\\":159,\\"privilege_desc\\":\\"V4_MYLEAVESTATUS\\",\\"activity_desc\\":\\"V4_DASHBOARD\\",\\"privilege_id\\":1189},{\\"activity_id\\":159,\\"privilege_desc\\":\\"V4_MEMO\\",\\"activity_desc\\":\\"V4_DASHBOARD\\",\\"privilege_id\\":1193},{\\"activity_id\\":161,\\"privilege_desc\\":\\"V4_SUBJECTWISE\\",\\"activity_desc\\":\\"V4_STUDENT_ATTENDANCE\\",\\"privilege_id\\":1198},{\\"activity_id\\":161,\\"privilege_desc\\":\\"V4_SUBJECTWISELATE\\",\\"activity_desc\\":\\"V4_STUDENT_ATTENDANCE\\",\\"privilege_id\\":1201},{\\"activity_id\\":162,\\"privilege_desc\\":\\"V4_LEAVE_REQUISITION\\",\\"activity_desc\\":\\"V4_TEACHER_LEAVE\\",\\"privilege_id\\":1203},{\\"activity_id\\":164,\\"privilege_desc\\":\\"V4_ASSIGNMENT\\",\\"activity_desc\\":\\"V4_STUDENT_ASSIGNMENT\\",\\"privilege_id\\":1206},{\\"activity_id\\":166,\\"privilege_desc\\":\\"V4_SCHOOL_CALENDAR\\",\\"activity_desc\\":\\"V4_CALENDAR\\",\\"privilege_id\\":1208},{\\"activity_id\\":168,\\"privilege_desc\\":\\"V4_LOGOUT\\",\\"activity_desc\\":\\"V4_LOGOUT\\",\\"privilege_id\\":1210}],\\"resultPrivilege\\":\\"0\\",\\"resultProfile\\":\\"0\\",\\"profile\\":{\\"empid\\":\\"EMP183\\",\\"name\\":\\"BACHIR Raji Kashkash\\",\\"designation\\":\\"TEACHER\\",\\"photo_path\\":\\"/container/school_data/GAIS/photo/Staff/EMP183.jpg\\",\\"department_name\\":\\"HIGH SCHOOL - T\\"}}",
   "employee_id":"EMP183",
   "school_url":"http://ict.gaiqatar.com"
}""";

final parsedJson = json.decode(jsonData);
print(parsedJson['dashboard']);

final dashboardParsed = json.decode(parsedJson['dashboard']);
print(dashboardParsed);

I Scaped \" because I'm storing the string into a var, if it comes from your web api, should work too.


问:
Undefined property: stdClass::$ELEMENT
I found a tutorial on youtube about the selenium webdriver in windows using php. I already setup the xampp, installed some dependencies, and others like the jar files and geckodriver. And when I execute the php code. I got this error.

```<code>Notice: Undefined property: stdClass::$ELEMENT in C:\xampp\htdocs\sample1\phpwebdriver\WebElement.php on line 28
</code>```

Here is my php code:

<?php
/*
Copyright 2011 3e software house & interactive agency

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

     http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

require_once "phpwebdriver/WebDriver.php";

$webdriver = new WebDriver("localhost", "4444");
$webdriver->connect("firefox");
$webdriver->get("http://google.com");
$element = $webdriver->findElementBy(LocatorStrategy::name, "q");
if ($element) {
    $element->sendKeys(array("hello" ) );
    $element->submit();
}

?>
```

Please somebody help, I've been working for this error for 2days. I don't know what to do. Thanks in advance, really appreciate it if somebody has an answer.

答:
If you use this WebDriver it should be ok.

I think you can not use require_once = phpwebdriver/WebDriver because it should be replaced by vendor/autoload.php like in this original example.

Also I suggest use this.

Title: Undefined property: stdClass::$ELEMENT

Body:
I found a tutorial on youtube about the selenium webdriver in windows using php. I already setup the xampp, installed some dependencies, and others like the jar files and geckodriver. And when I execute the php code. I got this error.

Notice: Undefined property: stdClass::$ELEMENT in C:\xampp\htdocs\sample1\phpwebdriver\WebElement.php on line 28

Here is my php code:

<?php
/*
Copyright 2011 3e software house & interactive agency

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

     http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

require_once "phpwebdriver/WebDriver.php";

$webdriver = new WebDriver("localhost", "4444");
$webdriver->connect("firefox");
$webdriver->get("http://google.com");
$element = $webdriver->findElementBy(LocatorStrategy::name, "q");
if ($element) {
    $element->sendKeys(array("hello" ) );
    $element->submit();
}

?>

Please somebody help, I've been working for this error for 2days. I don't know what to do. Thanks in advance, really appreciate it if somebody has an answer.


问:
list of dictionary: aggregate value by grouping by inner dictionary key
I have this signature:

```<code>def aggregate_by_player_id(input, playerid, fields):
</code>```

By 'fields', i mean fields to sum up grouping by 'playerID' within the 'input'.

I call the function like this:

```<code>aggregate_by_player_id(input, 'player', ['stat1','stat3'])
</code>```

Input look like this:

```<code>[{'player': '1', 'stat1': '3', 'stat2': '4', 'stat3': '5'},
{'player': '1', 'stat1': '1', 'stat2': '4', 'stat3': '1'},
{'player': '2', 'stat1': '1', 'stat2': '2', 'stat3': '3'},
{'player': '2', 'stat1': '1', 'stat2': '2', 'stat3': '1'},
{'player': '3', 'stat1': '4', 'stat2': '1', 'stat3': '6'}]
</code>```

My output structure is:

```<code>nested_dic = {value_of_playerid1: {'playerid': value_of_playerid1, 'stat1': value_of_stat1, 'stat2': value_of_stat2},
              value_of_playerid2: {'playerid': value_of_playerid2, 'stat2': value_of_stat2, 'stat2': value_of_stat2},
              value_of_playerid3: {'playerid': value_of_playerid3, 'stat3': value_of_stat3, 'stat3': value_of_stat3}}
</code>```

Hence the output should look like:

```<code>{'1': {'player': '1', 'stat1': 4, 'stat3': 6},
 '2': {'player': '2', 'stat1': 2, 'stat3': 4},
 '3': {'player': '3', 'stat1': 4, 'stat3': 6}}
</code>```

答:
Capturing the result you're after in a single comprehension might be possible, but is likely not very readable. Here's a simple function that does the work:

```<code>data = [
    {'player': '1', 'stat1': '3', 'stat2': '4', 'stat3': '5'},
    {'player': '1', 'stat1': '1', 'stat2': '4', 'stat3': '1'},
    {'player': '2', 'stat1': '1', 'stat2': '2', 'stat3': '3'},
    {'player': '2', 'stat1': '1', 'stat2': '2', 'stat3': '1'},
    {'player': '3', 'stat1': '4', 'stat2': '1', 'stat3': '6'}
]

def aggregate_dicts(ds, id_field, aggr_fields):
    result = {}
    for d in ds:
        identifier = d[id_field]
        if identifier not in result:
            result[identifier] = {f: 0 for f in aggr_fields}
        for f in aggr_fields:
            result[identifier][f] += int(d[f])
    return result

print(aggregate_dicts(data, 'player', ['stat1', 'stat3']))
</code>```

Result:

```<code>{'1': {'stat1': 4, 'stat3': 6}, '2': {'stat1': 2, 'stat3': 4}, '3': {'stat1': 4, 'stat3': 6}}
</code>```

If you want to repeat the identifier inside the dict, just add this line to the if block:

```<code>            result[identifier][id_field] = identifier
</code>```

Body:
I have this signature:

def aggregate_by_player_id(input, playerid, fields):

By 'fields', i mean fields to sum up grouping by 'playerID' within the 'input'.

I call the function like this:

aggregate_by_player_id(input, 'player', ['stat1','stat3'])

Input look like this:

[{'player': '1', 'stat1': '3', 'stat2': '4', 'stat3': '5'},
{'player': '1', 'stat1': '1', 'stat2': '4', 'stat3': '1'},
{'player': '2', 'stat1': '1', 'stat2': '2', 'stat3': '3'},
{'player': '2', 'stat1': '1', 'stat2': '2', 'stat3': '1'},
{'player': '3', 'stat1': '4', 'stat2': '1', 'stat3': '6'}]

My output structure is:

nested_dic = {value_of_playerid1: {'playerid': value_of_playerid1, 'stat1': value_of_stat1, 'stat2': value_of_stat2},
              value_of_playerid2: {'playerid': value_of_playerid2, 'stat2': value_of_stat2, 'stat2': value_of_stat2},
              value_of_playerid3: {'playerid': value_of_playerid3, 'stat3': value_of_stat3, 'stat3': value_of_stat3}}

Hence the output should look like:

{'1': {'player': '1', 'stat1': 4, 'stat3': 6},
 '2': {'player': '2', 'stat1': 2, 'stat3': 4},
 '3': {'player': '3', 'stat1': 4, 'stat3': 6}}

Body:
Capturing the result you're after in a single comprehension might be possible, but is likely not very readable. Here's a simple function that does the work:

data = [
    {'player': '1', 'stat1': '3', 'stat2': '4', 'stat3': '5'},
    {'player': '1', 'stat1': '1', 'stat2': '4', 'stat3': '1'},
    {'player': '2', 'stat1': '1', 'stat2': '2', 'stat3': '3'},
    {'player': '2', 'stat1': '1', 'stat2': '2', 'stat3': '1'},
    {'player': '3', 'stat1': '4', 'stat2': '1', 'stat3': '6'}
]

def aggregate_dicts(ds, id_field, aggr_fields):
    result = {}
    for d in ds:
        identifier = d[id_field]
        if identifier not in result:
            result[identifier] = {f: 0 for f in aggr_fields}
        for f in aggr_fields:
            result[identifier][f] += int(d[f])
    return result

print(aggregate_dicts(data, 'player', ['stat1', 'stat3']))

Result:

{'1': {'stat1': 4, 'stat3': 6}, '2': {'stat1': 2, 'stat3': 4}, '3': {'stat1': 4, 'stat3': 6}}

If you want to repeat the identifier inside the dict, just add this line to the if block:

            result[identifier][id_field] = identifier


问:
Mongoose is saying I have 46 records, mongoDB says I have zero?
The following test script says I have 46 records:

```<code>var mongoose = require('mongoose'),
    Schema = mongoose.Schema;

var DealSchema = new Schema({
  title : String,
});

var Deal = mongoose.model('Deal', DealSchema);

mongoose.connect('mongodb://localhost/dealsite');
mongoose.connection.on("open", function(){
  console.log("Mongoose connected");
  Deal.count({}, function( err, count){
    console.log( "Records:", count );
  })
});
</code>```

output:

```<code>$ node testmongo.js
Mongoose connected
Records: 46
</code>```

While if I try to read the cords using the mongo shell I get a different story:

```<code>$ mongo localhost/dealsite
MongoDB shell version: 1.4.4
url: localhost/dealsite
connecting to: localhost/dealsite
type "exit" to exit
type "help" for help
> db.dealsite.count()
0
> db.dealsite.Deal.count()
0
</code>```

Where are my records hiding?

答:
In MongoDB, try:

```<code>use dealsite
db.deals.count()
</code>```

If you create a Mongoose model called "Deal", it will create and use a MongoDB collection called "deals".

Body:
The following test script says I have 46 records:

var mongoose = require('mongoose'),
    Schema = mongoose.Schema;

var DealSchema = new Schema({
  title : String,
});

var Deal = mongoose.model('Deal', DealSchema);

mongoose.connect('mongodb://localhost/dealsite');
mongoose.connection.on("open", function(){
  console.log("Mongoose connected");
  Deal.count({}, function( err, count){
    console.log( "Records:", count );
  })
});

output:

$ node testmongo.js
Mongoose connected
Records: 46

While if I try to read the cords using the mongo shell I get a different story:

$ mongo localhost/dealsite
MongoDB shell version: 1.4.4
url: localhost/dealsite
connecting to: localhost/dealsite
type "exit" to exit
type "help" for help
> db.dealsite.count()
0
> db.dealsite.Deal.count()
0

Where are my records hiding?

Body:
In MongoDB, try:

use dealsite
db.deals.count()

If you create a Mongoose model called "Deal", it will create and use a MongoDB collection called "deals".


问:
How do I dynamically add my Ngrok tunnel to config.hosts in Rails 6?
I'm trying to whitelist my ngrok tunnel hostname in config.hosts but it changes every time I start Ngrok. Is there a way to get the public url of my Ngrok tunnel so that I don't have to use hosts.clear?

答:
Ngrok has a built in JSON API that can be found on localhost:4040/api/tunnels.

```<code># lib/ngrok_client.rb
module NgrokClient
  def self.tunnels
    response = Net::HTTP.get(URI('http://localhost:4040/api/tunnels'))
    begin
      JSON.parse(response).dig("tunnels")
    rescue JSON::ParserError => e
      Rails.logger.error %q{
        Failed to parse reponse from Ngroks internal API. Are you sure its running?
      }
    end
  end
  def self.public_urls
    tunnels.select do |h|
      # TODO - don't hardcode the host name
      h.dig("config", "addr") == "http://localhost:3000"
    end.map { |h| URI(h["public_url"]).hostname }.uniq
  end
end
</code>```

```<code># config/environments/development.rb
Rails.application.configure do
  # ...
  require 'ngrok_client'
  config.hosts += NgrokClient.public_urls
end
</code>```

There is also the ngrok-tunnel gem that can be used to start ngrok from the middleware layer as a less hacky soultion.

Body:
Ngrok has a built in JSON API that can be found on localhost:4040/api/tunnels.

# lib/ngrok_client.rb
module NgrokClient
  def self.tunnels
    response = Net::HTTP.get(URI('http://localhost:4040/api/tunnels'))
    begin
      JSON.parse(response).dig("tunnels")
    rescue JSON::ParserError => e
      Rails.logger.error %q{
        Failed to parse reponse from Ngroks internal API. Are you sure its running?
      }
    end
  end
  def self.public_urls
    tunnels.select do |h|
      # TODO - don't hardcode the host name
      h.dig("config", "addr") == "http://localhost:3000"
    end.map { |h| URI(h["public_url"]).hostname }.uniq
  end
end

# config/environments/development.rb
Rails.application.configure do
  # ...
  require 'ngrok_client'
  config.hosts += NgrokClient.public_urls
end

There is also the ngrok-tunnel gem that can be used to start ngrok from the middleware layer as a less hacky soultion.


问:
Phusion Passenger is running as root, and part(s) of the Passenger root path () can be changed by non-root user(s)
```<code>[Thu Jul 05 07:58:30.268108 2018] [core:warn] [pid 7157] AH00117: Ignoring deprecated use of DefaultType in line 111 of /usr/local/apache/conf/httpd.conf.
[Thu Jul 05 07:58:30.268302 2018] [alias:warn] [pid 7157] AH00671: The Alias directive in /usr/local/apache/conf/httpd.conf at line 318 will probably never match because it overlaps an earlier Alias.
[Thu Jul 05 07:58:30.270866 2018] [:notice] [pid 7157] HiveEXEC mechanism enabled (wrapper: /usr/local/1h/sbin/hive_exec)
[Thu Jul 05 07:58:30.276835 2018] [:notice] [pid 28647] FastCGI: process manager initialized (pid 28647)
[ N 2018-07-05 07:58:30.2928 28649/T1 age/Wat/WatchdogMain.cpp:1297 ]: Starting Passenger watchdog...
[ N 2018-07-05 07:58:30.3078 28652/T1 age/Cor/CoreMain.cpp:1202 ]: Starting Passenger core...
[ N 2018-07-05 07:58:30.3079 28652/T1 age/Cor/CoreMain.cpp:252 ]: Passenger core running in multi-application mode.
[ W 2018-07-05 07:58:30.3242 28652/T1 age/Cor/CoreMain.cpp:929 ]: **WARNING: potential privilege escalation vulnerability detected. Phusion Passenger is running as root, and part(s) of the Passenger root path (/usr/local/rvm/gems/ruby-2.4.1@myspace_new/gems/passenger-5.3.2) can be changed by non-root user(s):**

 - /usr/local/rvm/gems/ruby-2.4.1@myspace_new/gems is not secure: it can be modified by group rvm
 - /usr/local/rvm/gems is not secure: it can be modified by group rvm
</code>```

Please either fix up the permissions for the insecure paths, or install Passenger in a different location that can only be modified by root.

```<code>[ N 2018-07-05 07:58:30.3242 28652/T1 age/Cor/CoreMain.cpp:937 ]: Passenger core online, PID 28652
[Thu Jul 05 07:58:30.327114 2018] [mpm_prefork:notice] [pid 7157] AH00163: Apache/2.4.29 (Unix) mod_hive/6.6 OpenSSL/1.0.1e-fips mod_fastcgi/2.4.6 Phusion_Passenger/5.3.2 configured -- resuming normal operations
[Thu Jul 05 07:58:30.327141 2018] [core:notice] [pid 7157] AH00094: Command line: '/usr/local/apache/bin/httpd -D SSL'
[ N 2018-07-05 07:58:30.5457 27311/T1 age/Cor/CoreMain.cpp:1187 ]: **Passenger core shutdown finished**
</code>```

答:
The answer, for me :

1 -
For the website in /opt/redmine/redmine-site-version

```<code>sudo chown www-data:redmine-user -R /opt/redmine/
</code>```

2 -

```<code>cd /opt
sudo chown root:root redmine/
cd /opt/redmine
sudo chown root:root .rvm/
cd /opt/redmine/.rvm
sudo chown root:root gems/
cd /opt/redmine/.rvm/gems
sudo chown root:root ruby-2.4.5@redmine-4.0-stable-prod-unis
cd /opt/redmine/.rvm/gems/ruby-2.4.5@redmine-4.0-stable-prod-unis
sudo chown root:root gems/
cd /opt/redmine/.rvm/gems/ruby-2.4.5@redmine-4.0-stable-prod-unis/gems
sudo chown root:root passenger-6.0.2
</code>```

Restart Apache2

Look your logs.

Redmine RVM 2020 : https://wiki.visionduweb.fr/index.php?title=Installer_Redmine_sur_Debian_avec_RVM#Notes_de_s.C3.A9curit.C3.A9

Body:
[Thu Jul 05 07:58:30.268108 2018] [core:warn] [pid 7157] AH00117: Ignoring deprecated use of DefaultType in line 111 of /usr/local/apache/conf/httpd.conf.
[Thu Jul 05 07:58:30.268302 2018] [alias:warn] [pid 7157] AH00671: The Alias directive in /usr/local/apache/conf/httpd.conf at line 318 will probably never match because it overlaps an earlier Alias.
[Thu Jul 05 07:58:30.270866 2018] [:notice] [pid 7157] HiveEXEC mechanism enabled (wrapper: /usr/local/1h/sbin/hive_exec)
[Thu Jul 05 07:58:30.276835 2018] [:notice] [pid 28647] FastCGI: process manager initialized (pid 28647)
[ N 2018-07-05 07:58:30.2928 28649/T1 age/Wat/WatchdogMain.cpp:1297 ]: Starting Passenger watchdog...
[ N 2018-07-05 07:58:30.3078 28652/T1 age/Cor/CoreMain.cpp:1202 ]: Starting Passenger core...
[ N 2018-07-05 07:58:30.3079 28652/T1 age/Cor/CoreMain.cpp:252 ]: Passenger core running in multi-application mode.
[ W 2018-07-05 07:58:30.3242 28652/T1 age/Cor/CoreMain.cpp:929 ]: **WARNING: potential privilege escalation vulnerability detected. Phusion Passenger is running as root, and part(s) of the Passenger root path (/usr/local/rvm/gems/ruby-2.4.1@myspace_new/gems/passenger-5.3.2) can be changed by non-root user(s):**

 - /usr/local/rvm/gems/ruby-2.4.1@myspace_new/gems is not secure: it can be modified by group rvm
 - /usr/local/rvm/gems is not secure: it can be modified by group rvm

Please either fix up the permissions for the insecure paths, or install Passenger in a different location that can only be modified by root.

[ N 2018-07-05 07:58:30.3242 28652/T1 age/Cor/CoreMain.cpp:937 ]: Passenger core online, PID 28652
[Thu Jul 05 07:58:30.327114 2018] [mpm_prefork:notice] [pid 7157] AH00163: Apache/2.4.29 (Unix) mod_hive/6.6 OpenSSL/1.0.1e-fips mod_fastcgi/2.4.6 Phusion_Passenger/5.3.2 configured -- resuming normal operations
[Thu Jul 05 07:58:30.327141 2018] [core:notice] [pid 7157] AH00094: Command line: '/usr/local/apache/bin/httpd -D SSL'
[ N 2018-07-05 07:58:30.5457 27311/T1 age/Cor/CoreMain.cpp:1187 ]: **Passenger core shutdown finished**

Body:
The answer, for me :

1 -
For the website in /opt/redmine/redmine-site-version

sudo chown www-data:redmine-user -R /opt/redmine/

2 -

cd /opt
sudo chown root:root redmine/
cd /opt/redmine
sudo chown root:root .rvm/
cd /opt/redmine/.rvm
sudo chown root:root gems/
cd /opt/redmine/.rvm/gems
sudo chown root:root ruby-2.4.5@redmine-4.0-stable-prod-unis
cd /opt/redmine/.rvm/gems/ruby-2.4.5@redmine-4.0-stable-prod-unis
sudo chown root:root gems/
cd /opt/redmine/.rvm/gems/ruby-2.4.5@redmine-4.0-stable-prod-unis/gems
sudo chown root:root passenger-6.0.2

Restart Apache2

Look your logs.

Redmine RVM 2020 : https://wiki.visionduweb.fr/index.php?title=Installer_Redmine_sur_Debian_avec_RVM#Notes_de_s.C3.A9curit.C3.A9


问:
How to pull out text within an h3 tag class in selenium using python?
I currently am having difficulty extracting text from the following page:

I have tried browser.find_element_by_class_name("W6bZuc.YMllz").text

and also

browser.find_element_by_tag_name("h3").text

but these all come up empty. Is there a way to get the h3 element consistently using selenium webdriver in python? Thanks.

答:
Try getting textContent

```<code>browser.find_element_by_class_name("W6bZuc.YMllz").get_attribute("textContent")
</code>```

Body:
Try getting textContent

browser.find_element_by_class_name("W6bZuc.YMllz").get_attribute("textContent")


问:
Finding circle function and center in Python
I have a data set (512 X 512), which is a 2D array. This is the figure I plot based on this data set.

Data looks like this:

```<code>[[239 247 214 ... 466 511 415]
 [257 283 254 ... 460 474 474]
 [219 251 268 ... 458 475 496]
 ...
 [372 382 428 ... 641 615 707]
 [394 369 408 ... 681 592 706]
 [357 377 358 ... 696 566 708]]
</code>```

Is there any method that I can get the function and the center position of the circle?

Should I do something about background subtraction to make the circle more clear?

I really don't know where can I start. Need help. Thanks a lot!!!

This is the code of how I draw the figure.

```<code>import matplotlib.pyplot as plt
import numpy as np
import pandas as pd

data = pd.read_csv('D:/data set.csv', header=None)

# create data
data = np.array(data)

#plot data
fig, ax = plt.subplots(figsize=(5, 5))
side = np.linspace(0,512,513)
X,Y = np.meshgrid(side,side)
Z = [[data[i][j] for j in range(len(data[0]))]for i in range(len(data))]
plt.pcolormesh(X,Y,Z, cmap=plt.cm.get_cmap('Greys'))

ax = plt.gca()
ax.set_aspect('equal', 'box')

plt.colorbar(fraction=0.0455)

plt.show()
</code>```

Now I find out I can use HoughCircle to detect the circle in my plot. But is there any method I can get the equation of the green circle and the red center the HoughCircle detect?

This is the coding of HoughCircle:

```<code>import cv2
import numpy as np
import matplotlib.pyplot as plt

bfp = cv2.imread('D:/circle.png')
gray_img = cv2.cvtColor(bfp, cv2.COLOR_BGR2GRAY)
img = cv2.medianBlur(gray_img, 5)
cimg = cv2.cvtColor(img,cv2.COLOR_GRAY2BGR)

circles = cv2.HoughCircles(img,cv2.HOUGH_GRADIENT,1,120,

                           param1=80,param2=40,minRadius=0,maxRadius=0)

circles = np.uint16(np.around(circles))

for i in circles[0,:]:
   # draw the outer circle
   cv2.circle(bfp,(i[0],i[1]),i[2],(0,255,0),2)
   # draw the center of the circle
   cv2.circle(bfp,(i[0],i[1]),2,(0,0,255),3)
   print(cv2.circle(bfp,(i[0],i[1]),2,(0,0,255),3))

cv2.imshow("bfp_HoughCirlces", bfp)
cv2.waitKey()
cv2.destroyAllWindows()
</code>```

答:
(Sorry I couldn't comment on this post)
You can get the maximum and minimum of each dimension. The coordinates of the center will be the mean of maximum and minimum of each dimension.</p>

Body:
I have a data set (512 X 512), which is a 2D array. This is the figure I plot based on this data set.

Data looks like this:

[[239 247 214 ... 466 511 415]
 [257 283 254 ... 460 474 474]
 [219 251 268 ... 458 475 496]
 ...
 [372 382 428 ... 641 615 707]
 [394 369 408 ... 681 592 706]
 [357 377 358 ... 696 566 708]]

Is there any method that I can get the function and the center position of the circle?

Should I do something about background subtraction to make the circle more clear?

I really don't know where can I start. Need help. Thanks a lot!!!

This is the code of how I draw the figure.

import matplotlib.pyplot as plt
import numpy as np
import pandas as pd

data = pd.read_csv('D:/data set.csv', header=None)

# create data
data = np.array(data)

#plot data
fig, ax = plt.subplots(figsize=(5, 5))
side = np.linspace(0,512,513)
X,Y = np.meshgrid(side,side)
Z = [[data[i][j] for j in range(len(data[0]))]for i in range(len(data))]
plt.pcolormesh(X,Y,Z, cmap=plt.cm.get_cmap('Greys'))

ax = plt.gca()
ax.set_aspect('equal', 'box')

plt.colorbar(fraction=0.0455)

plt.show()

Now I find out I can use HoughCircle to detect the circle in my plot. But is there any method I can get the equation of the green circle and the red center the HoughCircle detect?

This is the coding of HoughCircle:

import cv2
import numpy as np
import matplotlib.pyplot as plt

bfp = cv2.imread('D:/circle.png')
gray_img = cv2.cvtColor(bfp, cv2.COLOR_BGR2GRAY)
img = cv2.medianBlur(gray_img, 5)
cimg = cv2.cvtColor(img,cv2.COLOR_GRAY2BGR)

circles = cv2.HoughCircles(img,cv2.HOUGH_GRADIENT,1,120,

                           param1=80,param2=40,minRadius=0,maxRadius=0)

circles = np.uint16(np.around(circles))

for i in circles[0,:]:
   # draw the outer circle
   cv2.circle(bfp,(i[0],i[1]),i[2],(0,255,0),2)
   # draw the center of the circle
   cv2.circle(bfp,(i[0],i[1]),2,(0,0,255),3)
   print(cv2.circle(bfp,(i[0],i[1]),2,(0,0,255),3))

cv2.imshow("bfp_HoughCirlces", bfp)
cv2.waitKey()
cv2.destroyAllWindows()


问:
Program that takes 2 numbers as an input and finds the factorials of those numbers and every number in between?
This piece of code is supposed to take 2 numbers and find the factorial of every number between and incuding said numbers. I'm not getting the right output however and cant figure out what im doing wrong.</p>

```<code>Scanner scan = new Scanner(System.in);
long result = 1;
int m = scan.nextInt();
int n = scan.nextInt();
scan.close();

if (n > 0 && m > 0)             //want factorial greater than zero
for(int j = n; j <= m; j++)
{
    for(int i = 1; i <= j; i++)
    {
        result = result * i;    //find factorial
    }
    System.out.println(result);
}
    if(n <= 0 || m <= 0)        //if value is les than zero
    {
        System.out.println("Not Valid!");
    }
</code>```

答:
Something like should work:

public class RangeFactorial {
    public static void main(String[] args) throws Exception {
        Scanner scan = new Scanner(System.in);
        int max = scan.nextInt();
        int min = scan.nextInt();

        if (max < 0 || min < 0) {
            System.out.println("Invalid Params");
        }

        for (int i = min; i <= max; i++) {
            System.out.println("Factorial for " + i + " is: " + factorial(i));
        }

        scan.close();
    }

    private static int factorial(int i) {
        if (i <= 1) {
            return 1;
        }

        return i * factorial(i-1);
    }
}
```

Note that the code assumes that max/min fall in place, I've omitted the logic to decide the max/min integer from the given inputs. You'll need to add this.

Body:
This piece of code is supposed to take 2 numbers and find the factorial of every number between and incuding said numbers. I'm not getting the right output however and cant figure out what im doing wrong.

Scanner scan = new Scanner(System.in);
long result = 1;
int m = scan.nextInt();
int n = scan.nextInt();
scan.close();

if (n > 0 && m > 0)             //want factorial greater than zero
for(int j = n; j <= m; j++)
{
    for(int i = 1; i <= j; i++)
    {
        result = result * i;    //find factorial
    }
    System.out.println(result);
}
    if(n <= 0 || m <= 0)        //if value is les than zero
    {
        System.out.println("Not Valid!");
    }

Body:
Something like should work:

public class RangeFactorial {
    public static void main(String[] args) throws Exception {
        Scanner scan = new Scanner(System.in);
        int max = scan.nextInt();
        int min = scan.nextInt();

        if (max < 0 || min < 0) {
            System.out.println("Invalid Params");
        }

        for (int i = min; i <= max; i++) {
            System.out.println("Factorial for " + i + " is: " + factorial(i));
        }

        scan.close();
    }

    private static int factorial(int i) {
        if (i <= 1) {
            return 1;
        }

        return i * factorial(i-1);
    }
}

Note that the code assumes that max/min fall in place, I've omitted the logic to decide the max/min integer from the given inputs. You'll need to add this.


问:
Is there a way in jQuery to bring a div to front?
If I had a bunch of absolute positioned divs and they overlapped, how would I get a certain div to come to the front? Thanks again guys!</p>

答:
```<code>element.style.zIndex = Date.now();
</code>```

ContentLicense: CC BY-SA 2.5

Body: element.style.zIndex = Date.now();


问:
Eclipse - Unable to delete project from workspace. NPE
I unable to delete the project from the workspace. Eclipse throws NPE and I have NFI how to resolve this issue.

```
java.lang.NullPointerException
    at org.eclipse.ltk.ui.refactoring.resource.DeleteResourcesWizard$DeleteResourcesRefactoringConfigurationPage.createControl(DeleteResourcesWizard.java:89)
    at org.eclipse.ltk.internal.ui.refactoring.RefactoringWizardDialog2.createContents(RefactoringWizardDialog2.java:631)
    at org.eclipse.jface.window.Window.create(Window.java:431)
    at org.eclipse.jface.dialogs.Dialog.create(Dialog.java:1089)
    at org.eclipse.ltk.ui.refactoring.RefactoringWizardOpenOperation$1.run(RefactoringWizardOpenOperation.java:171)
    at org.eclipse.swt.custom.BusyIndicator.showWhile(BusyIndicator.java:70)
    at org.eclipse.ltk.ui.refactoring.RefactoringWizardOpenOperation.run(RefactoringWizardOpenOperation.java:192)
    at org.eclipse.ltk.ui.refactoring.RefactoringWizardOpenOperation.run(RefactoringWizardOpenOperation.java:115)
    at org.eclipse.ltk.internal.ui.refactoring.actions.DeleteResourcesHandler.execute(DeleteResourcesHandler.java:40)
    at org.eclipse.ui.internal.handlers.HandlerProxy.execute(HandlerProxy.java:293)
    at org.eclipse.core.commands.Command.executeWithChecks(Command.java:476)
    at org.eclipse.core.commands.ParameterizedCommand.executeWithChecks(ParameterizedCommand.java:508)
    at org.eclipse.ui.internal.handlers.HandlerService.executeCommandInContext(HandlerService.java:270)
    at org.eclipse.ui.internal.ide.actions.LTKLauncher.runCommand(LTKLauncher.java:95)
    at org.eclipse.ui.internal.ide.actions.LTKLauncher.openDeleteWizard(LTKLauncher.java:47)
    at org.eclipse.ui.actions.DeleteResourceAction.run(DeleteResourceAction.java:481)
    at org.eclipse.jdt.internal.ui.refactoring.reorg.DeleteAction.run(DeleteAction.java:162)
    at org.eclipse.jdt.ui.actions.SelectionDispatchAction.dispatchRun(SelectionDispatchAction.java:274)
    at org.eclipse.jdt.ui.actions.SelectionDispatchAction.run(SelectionDispatchAction.java:250)
    at org.eclipse.jface.action.Action.runWithEvent(Action.java:498)
    at org.eclipse.jface.commands.ActionHandler.execute(ActionHandler.java:119)
    at org.eclipse.core.commands.Command.executeWithChecks(Command.java:476)
    at org.eclipse.core.commands.ParameterizedCommand.executeWithChecks(ParameterizedCommand.java:508)
    at org.eclipse.ui.internal.handlers.HandlerService.executeCommand(HandlerService.java:169)
    at org.eclipse.ui.internal.keys.WorkbenchKeyboard.executeCommand(WorkbenchKeyboard.java:468)
    at org.eclipse.ui.internal.keys.WorkbenchKeyboard.press(WorkbenchKeyboard.java:786)
    at org.eclipse.ui.internal.keys.WorkbenchKeyboard.processKeyEvent(WorkbenchKeyboard.java:885)
    at org.eclipse.ui.internal.keys.OutOfOrderListener.handleEvent(OutOfOrderListener.java:76)
    at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:84)
    at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:1258)
    at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:1282)
    at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:1267)
    at org.eclipse.swt.widgets.Widget.sendKeyEvent(Widget.java:1294)
    at org.eclipse.swt.widgets.Widget.gtk_key_press_event(Widget.java:730)
    at org.eclipse.swt.widgets.Control.gtk_key_press_event(Control.java:2841)
    at org.eclipse.swt.widgets.Composite.gtk_key_press_event(Composite.java:734)
    at org.eclipse.swt.widgets.Tree.gtk_key_press_event(Tree.java:1977)
    at org.eclipse.swt.widgets.Widget.windowProc(Widget.java:1743)
    at org.eclipse.swt.widgets.Control.windowProc(Control.java:4796)
    at org.eclipse.swt.widgets.Tree.windowProc(Tree.java:3485)
    at org.eclipse.swt.widgets.Display.windowProc(Display.java:4360)
    at org.eclipse.swt.internal.gtk.OS._gtk_main_do_event(Native Method)
    at org.eclipse.swt.internal.gtk.OS.gtk_main_do_event(OS.java:8189)
    at org.eclipse.swt.widgets.Display.eventProc(Display.java:1238)
    at org.eclipse.swt.internal.gtk.OS._g_main_context_iteration(Native Method)
    at org.eclipse.swt.internal.gtk.OS.g_main_context_iteration(OS.java:2237)
    at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:3159)
    at org.eclipse.ui.internal.Workbench.runEventLoop(Workbench.java:2640)
    at org.eclipse.ui.internal.Workbench.runUI(Workbench.java:2604)
    at org.eclipse.ui.internal.Workbench.access$4(Workbench.java:2438)
    at org.eclipse.ui.internal.Workbench$7.run(Workbench.java:671)
    at org.eclipse.core.databinding.observable.Realm.runWithDefault(Realm.java:332)
    at org.eclipse.ui.internal.Workbench.createAndRunWorkbench(Workbench.java:664)
    at org.eclipse.ui.PlatformUI.createAndRunWorkbench(PlatformUI.java:149)
    at org.eclipse.ui.internal.ide.application.IDEApplication.start(IDEApplication.java:115)
    at org.eclipse.equinox.internal.app.EclipseAppHandle.run(EclipseAppHandle.java:196)
    at org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.runApplication(EclipseAppLauncher.java:110)
    at org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.start(EclipseAppLauncher.java:79)
    at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:369)
    at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:179)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
    at java.lang.reflect.Method.invoke(Method.java:597)
    at org.eclipse.equinox.launcher.Main.invokeFramework(Main.java:620)
    at org.eclipse.equinox.launcher.Main.basicRun(Main.java:575)
    at org.eclipse.equinox.launcher.Main.run(Main.java:1408)
    at org.eclipse.equinox.launcher.Main.main(Main.java:1384)

```

and this is my environment :-

```
eclipse.buildId=M20110210-1200
java.version=1.6.0_21
java.vendor=Sun Microsystems Inc.
BootLoader constants: OS=linux, ARCH=x86, WS=gtk, NL=en_AU
Framework arguments:  -product org.eclipse.epp.package.jee.product
Command-line arguments:  -os linux -ws gtk -arch x86 -product
org.eclipse.epp.package.jee.product
```

答:
The closest bug (issue 302791) was fixed in 3.6 (which I suspect you have, with a build Id M20110210-1200)

Your error seems to take place at the very beginning of the process, since it isn't able to create the `DeleteResourcesWizard.

It could be because of:

some strange selection (did you try selecting the project in the Package Explorer? in the Resource Explorer?)

some deleted resources still referenced by the project.

If you can reproduce the problem every time, this can be worth a new Eclipse bug report.

Body:
I unable to delete the project from the workspace. Eclipse throws NPE and I have NFI how to resolve this issue.

java.lang.NullPointerException
    at org.eclipse.ltk.ui.refactoring.resource.DeleteResourcesWizard$DeleteResourcesRefactoringConfigurationPage.createControl(DeleteResourcesWizard.java:89)
    at org.eclipse.ltk.internal.ui.refactoring.RefactoringWizardDialog2.createContents(RefactoringWizardDialog2.java:631)
    at org.eclipse.jface.window.Window.create(Window.java:431)
    at org.eclipse.jface.dialogs.Dialog.create(Dialog.java:1089)
    at org.eclipse.ltk.ui.refactoring.RefactoringWizardOpenOperation$1.run(RefactoringWizardOpenOperation.java:171)
    at org.eclipse.swt.custom.BusyIndicator.showWhile(BusyIndicator.java:70)
    at org.eclipse.ltk.ui.refactoring.RefactoringWizardOpenOperation.run(RefactoringWizardOpenOperation.java:192)
    at org.eclipse.ltk.ui.refactoring.RefactoringWizardOpenOperation.run(RefactoringWizardOpenOperation.java:115)
    at org.eclipse.ltk.internal.ui.refactoring.actions.DeleteResourcesHandler.execute(DeleteResourcesHandler.java:40)
    at org.eclipse.ui.internal.handlers.HandlerProxy.execute(HandlerProxy.java:293)
    at org.eclipse.core.commands.Command.executeWithChecks(Command.java:476)
    at org.eclipse.core.commands.ParameterizedCommand.executeWithChecks(ParameterizedCommand.java:508)
    at org.eclipse.ui.internal.handlers.HandlerService.executeCommandInContext(HandlerService.java:270)
    at org.eclipse.ui.internal.ide.actions.LTKLauncher.runCommand(LTKLauncher.java:95)
    at org.eclipse.ui.internal.ide.actions.LTKLauncher.openDeleteWizard(LTKLauncher.java:47)
    at org.eclipse.ui.actions.DeleteResourceAction.run(DeleteResourceAction.java:481)
    at org.eclipse.jdt.internal.ui.refactoring.reorg.DeleteAction.run(DeleteAction.java:162)
    at org.eclipse.jdt.ui.actions.SelectionDispatchAction.dispatchRun(SelectionDispatchAction.java:274)
    at org.eclipse.jdt.ui.actions.SelectionDispatchAction.run(SelectionDispatchAction.java:250)
    at org.eclipse.jface.action.Action.runWithEvent(Action.java:498)
    at org.eclipse.jface.commands.ActionHandler.execute(ActionHandler.java:119)
    at org.eclipse.core.commands.Command.executeWithChecks(Command.java:476)
    at org.eclipse.core.commands.ParameterizedCommand.executeWithChecks(ParameterizedCommand.java:508)
    at org.eclipse.ui.internal.handlers.HandlerService.executeCommand(HandlerService.java:169)
    at org.eclipse.ui.internal.keys.WorkbenchKeyboard.executeCommand(WorkbenchKeyboard.java:468)
    at org.eclipse.ui.internal.keys.WorkbenchKeyboard.press(WorkbenchKeyboard.java:786)
    at org.eclipse.ui.internal.keys.WorkbenchKeyboard.processKeyEvent(WorkbenchKeyboard.java:885)
    at org.eclipse.ui.internal.keys.OutOfOrderListener.handleEvent(OutOfOrderListener.java:76)
    at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:84)
    at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:1258)
    at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:1282)
    at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:1267)
    at org.eclipse.swt.widgets.Widget.sendKeyEvent(Widget.java:1294)
    at org.eclipse.swt.widgets.Widget.gtk_key_press_event(Widget.java:730)
    at org.eclipse.swt.widgets.Control.gtk_key_press_event(Control.java:2841)
    at org.eclipse.swt.widgets.Composite.gtk_key_press_event(Composite.java:734)
    at org.eclipse.swt.widgets.Tree.gtk_key_press_event(Tree.java:1977)
    at org.eclipse.swt.widgets.Widget.windowProc(Widget.java:1743)
    at org.eclipse.swt.widgets.Control.windowProc(Control.java:4796)
    at org.eclipse.swt.widgets.Tree.windowProc(Tree.java:3485)
    at org.eclipse.swt.widgets.Display.windowProc(Display.java:4360)
    at org.eclipse.swt.internal.gtk.OS._gtk_main_do_event(Native Method)
    at org.eclipse.swt.internal.gtk.OS.gtk_main_do_event(OS.java:8189)
    at org.eclipse.swt.widgets.Display.eventProc(Display.java:1238)
    at org.eclipse.swt.internal.gtk.OS._g_main_context_iteration(Native Method)
    at org.eclipse.swt.internal.gtk.OS.g_main_context_iteration(OS.java:2237)
    at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:3159)
    at org.eclipse.ui.internal.Workbench.runEventLoop(Workbench.java:2640)
    at org.eclipse.ui.internal.Workbench.runUI(Workbench.java:2604)
    at org.eclipse.ui.internal.Workbench.access$4(Workbench.java:2438)
    at org.eclipse.ui.internal.Workbench$7.run(Workbench.java:671)
    at org.eclipse.core.databinding.observable.Realm.runWithDefault(Realm.java:332)
    at org.eclipse.ui.internal.Workbench.createAndRunWorkbench(Workbench.java:664)
    at org.eclipse.ui.PlatformUI.createAndRunWorkbench(PlatformUI.java:149)
    at org.eclipse.ui.internal.ide.application.IDEApplication.start(IDEApplication.java:115)
    at org.eclipse.equinox.internal.app.EclipseAppHandle.run(EclipseAppHandle.java:196)
    at org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.runApplication(EclipseAppLauncher.java:110)
    at org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.start(EclipseAppLauncher.java:79)
    at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:369)
    at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:179)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
    at java.lang.reflect.Method.invoke(Method.java:597)
    at org.eclipse.equinox.launcher.Main.invokeFramework(Main.java:620)
    at org.eclipse.equinox.launcher.Main.basicRun(Main.java:575)
    at org.eclipse.equinox.launcher.Main.run(Main.java:1408)
    at org.eclipse.equinox.launcher.Main.main(Main.java:1384)

and this is my environment :-

eclipse.buildId=M20110210-1200
java.version=1.6.0_21
java.vendor=Sun Microsystems Inc.
BootLoader constants: OS=linux, ARCH=x86, WS=gtk, NL=en_AU
Framework arguments:  -product org.eclipse.epp.package.jee.product
Command-line arguments:  -os linux -ws gtk -arch x86 -product
org.eclipse.epp.package.jee.product


问:
Selecting and Unselecting values from a multi select dropdown in Angular 7
I have made a multi select dropdown which is implemented like below

```<code> MyFilter{
      key: string;      // uniquely identifies selected filter among many filters on page
      order: number;    // display order of filter on page
      options: DropListOption[];  // options in a dropdown
      values: DropListOption[];   // selected values from dropdown
    }

 DropListOption{
    label: string;  // name of option
    value: any;     //value of option
   }
</code>```

I have implemented a method which is called when a checkbox is selected or unselected as below:

```<code>onSelect(key: string, option: DropListOption): void{
  const filtersOpt = this.filters;  // type of filter is MyFilter
  filtersOpt.map((filter) => {
    if(filter.key === key){
      const selected: boolean = !!filter.values.find((opt) => opt.value === option.value);
      filters.values = selected  // filters.values used as property binding to display number of selected values
                      ? filters.values.filter((opt) => opt.value !== option.value)
                      : [...filters.values, option];
    }
    return filter;
  });
  this.updateFilters.emit(filtersOpt); //emitting to parent component
}
</code>```

Although my logic is working fine but being new to Angular/RxJS (front-end development), I am not very sure if my code is good code. Please can you let me know our thoughts or correct me. I would appreciate if someone can tell me any better way of implementing my onSelect() method.

答:
I'm not exactly sure of any improvements that could be done in your html to simplify this method any further, since you didn't show it, but blatantly speaking I'd do as follows.

Solution #1

This solution is not compatible with Internet Explorer due to the Array.prototype.findIndex() method usage. See Solution #2 for a compatible solution.

```<code>onSelect(key: string, option: DropListOption): void {
    const filterOpt = this.filters.find(fil => fil.key === key);
    if (!filterOpt) {
        console.warn('No filter was found with the given key.');
        return;
    }

    const selectedOptIdx =  filterOpt.values.findIndex(opt => opt.value === option.value);

    if (selectedOptIdx > -1) {
        filters.splice(selectedOptIdx, 1);
    } else {
        filters.push(option);
    }
}
</code>```

Pros

less complex solution.

overall, has a slightly better readability.

Solution #2

```<code>onSelect(key: string, option: DropListOption): void {
    const filterOpt = this.filters.find(fil => fil.key === key);
     if (!filterOpt) {
        console.warn('No filter was found with the given key.');
        return;
    }

    const selectedOpt = filterOpt.values.find(opt => opt.value === option.value);

    if (selectedOpt) {
        filters.splice(filters.indexOf(selectedOpt), 1);
    } else {
        filters.push(option);
    }
}
</code>```

Pros

compatible with Internet Explorer.

Overall, I would say that there are a few better approaches that can be done, I would advise you to read about the complexity of some Array.prototype methods so you can have a better understanding of the choices you make along the way and try to understand better what the Array.prototype.map() method does, in particular. I'll leave the sources below.

Sources

performance comparison between splice and filter (and copyWithin). (link)

discussion regarding javascript's array methods' complexities. (link)

Array.prototype.map() from MDN documentation pages (link)

(...) map calls a provided callback function once for each element in an array, in order, and constructs a new array from the results. callback is invoked only for indexes of the array which have assigned values (including undefined). (...)

Body:
I have made a multi select dropdown which is implemented like below

 MyFilter{
      key: string;      // uniquely identifies selected filter among many filters on page
      order: number;    // display order of filter on page
      options: DropListOption[];  // options in a dropdown
      values: DropListOption[];   // selected values from dropdown
    }

 DropListOption{
    label: string;  // name of option
    value: any;     //value of option
   }

I have implemented a method which is called when a checkbox is selected or unselected as below:

onSelect(key: string, option: DropListOption): void{
  const filtersOpt = this.filters;  // type of filter is MyFilter
  filtersOpt.map((filter) => {
    if(filter.key === key){
      const selected: boolean = !!filter.values.find((opt) => opt.value === option.value);
      filters.values = selected  // filters.values used as property binding to display number of selected values
                      ? filters.values.filter((opt) => opt.value !== option.value)
                      : [...filters.values, option];
    }
    return filter;
  });
  this.updateFilters.emit(filtersOpt); //emitting to parent component
}

Although my logic is working fine but being new to Angular/RxJS (front-end development), I am not very sure if my code is good code. Please can you let me know our thoughts or correct me. I would appreciate if someone can tell me any better way of implementing my onSelect() method.

Body:
I'm not exactly sure of any improvements that could be done in your html to simplify this method any further, since you didn't show it, but blatantly speaking I'd do as follows.

Solution #1

This solution is not compatible with Internet Explorer due to the Array.prototype.findIndex() method usage. See Solution #2 for a compatible solution.

onSelect(key: string, option: DropListOption): void {
    const filterOpt = this.filters.find(fil => fil.key === key);
    if (!filterOpt) {
        console.warn('No filter was found with the given key.');
        return;
    }

    const selectedOptIdx =  filterOpt.values.findIndex(opt => opt.value === option.value);

    if (selectedOptIdx > -1) {
        filters.splice(selectedOptIdx, 1);
    } else {
        filters.push(option);
    }
}

Pros

less complex solution.

overall, has a slightly better readability.

Solution #2

onSelect(key: string, option: DropListOption): void {
    const filterOpt = this.filters.find(fil => fil.key === key);
     if (!filterOpt) {
        console.warn('No filter was found with the given key.');
        return;
    }

    const selectedOpt = filterOpt.values.find(opt => opt.value === option.value);

    if (selectedOpt) {
        filters.splice(filters.indexOf(selectedOpt), 1);
    } else {
        filters.push(option);
    }
}

Pros

compatible with Internet Explorer.

Overall, I would say that there are a few better approaches that can be done, I would advise you to read about the complexity of some Array.prototype methods so you can have a better understanding of the choices you make along the way and try to understand better what the Array.prototype.map() method does, in particular. I'll leave the sources below.

Sources

performance comparison between splice and filter (and copyWithin). (link)

discussion regarding javascript's array methods' complexities. (link)

Array.prototype.map() from MDN documentation pages (link)

(...) map calls a provided callback function once for each element in an array, in order, and constructs a new array from the results. callback is invoked only for indexes of the array which have assigned values (including undefined). (...)


问:
Bot Reminding events in one Google calendar
I really find it weird Google doesnt have this as a built in (or maybe I haven't seen) A chatbot that can remind events added to acertain Google calendar.

Does this exist or is there a simple way to create it?

答:
The simplest way to do this is by publishing your events calendar and having a bot subscribe to it. That way it could send you an email/SMS or some other reminder. </p>

<p>I’ve used IFTT in the past to flash my lights if I forget to leave for an event, trouble is it doesn’t tell me what the event is till I pick up my phone & read the alert. </p>

Body:
The simplest way to do this is by publishing your events calendar and having a bot subscribe to it. That way it could send you an email/SMS or some other reminder.

I’ve used IFTT in the past to flash my lights if I forget to leave for an event, trouble is it doesn’t tell me what the event is till I pick up my phone & read the alert.


问:
Modify Pending Order at Mql4
I am trying to figure out an EA which updates its pending orders if current price pass the SL level of pending order both for buy and sell orders. As you can see below pic current price is below the SL point of pending orders. Therefore I want to modify new updated pending orders with openning price of from those SL point (+30 & -30 point) and not only for window currency but also for other currencies which are in the pending order list.

I tried below code but it didn't work out. Could you help me?

//------------------------------------------------------------------------------- 1 --
int start()
  {
   string Symb=Symbol();                        // Symbol
//------------------------------------------------------------------------------- 2 --
   for(int i=1; i<=OrdersTotal(); i++)
     {
      if (OrderSelect(i-1,SELECT_BY_POS)==true)
        {
         //---------------------------------------------------------------------- 3 --
         if (OrderSymbol()== Symb) continue;
         if (OrderType()==OP_BUYSTOP || OrderType()==OP_SELLSTOP) continue;           // Market order
         //---------------------------------------------------------------------- 4 --
           {
            int    Tip   =OrderType();
            int    Ticket=OrderTicket();
            double Price =OrderOpenPrice();
            double SL    =OrderStopLoss();
            double TP    =OrderTakeProfit();
           }
        }
     }
//------------------------------------------------------------------------------- 5 --
   if (Tip==0)
     {
      Alert("For ",Symb," no pending orders available");
      return;
     }
//------------------------------------------------------------------------------- 6 --
   while(true)
     {
      RefreshRates();                           // Update data
      //------------------------------------------------------------------------- 7 --
      double c_bid =MarketInfo(Symb,MODE_BID); // Request for the value of Bid
      double c_ask =MarketInfo(Symb,MODE_ASK); // Request for the value of Ask

      //------------------------------------------------------------------------- 8 --
      string Text="";                           // Not to be modified
      double New_SL=0;
      double New_TP=0;
      switch(Tip)                               // By order type
        {
         case 4:                                // BuyStopt
            if (NormalizeDouble(SL,Digits) > // If it is further than by
                NormalizeDouble(c_ask,Digits))//..the preset value
              {
               double New_Price=SL+30*Point;          // Its new price
               if (NormalizeDouble(SL,Digits)>0)
                  New_SL=New_Price-(Price-SL);  // New StopLoss
               if (NormalizeDouble(TP,Digits)>0)
                  New_TP=New_Price+(TP-Price);  // New TakeProfit
               Text= "BuyStopt ";               // Modify it.
              }
            break;                              // Exit 'switch'
         case 5:                                // SellStop
            if (NormalizeDouble(SL,Digits) < // If it is further than by
                NormalizeDouble(c_bid,Digits))//..the preset value
              {
               New_Price=SL-30*Point;          // Its new price
               if (NormalizeDouble(SL,Digits)>0)
                  New_SL=New_Price+(SL-Price);  // New StopLoss
               if (NormalizeDouble(TP,Digits)>0)
                  New_TP=New_Price-(Price-TP);  // New TakeProfit
               Text= "SellStop ";               // Modify it.
              }
        }
      if (NormalizeDouble(New_SL,Digits)<0)     // Checking SL
         New_SL=0;
      if (NormalizeDouble(New_TP,Digits)<0)     // Checking TP
         New_TP=0;
      if (Text=="")                             // If it is not modified
        {
         Alert("No conditions for modification.");
         break;                                 // Exit 'while'
        }
      //------------------------------------------------------------------------ 10 --
      Alert ("Modification ",Text,Ticket,". Awaiting response..");
      bool Ans=OrderModify(Ticket,New_Price,New_SL,New_TP,0);//Modify it!
      //------------------------------------------------------------------------ 11 --
      if (Ans==true)                            // Got it! :)
        {
         Alert ("Modified order ",Text," ",Ticket," :)");
         break;                                 // Exit the closing cycle
        }
      //------------------------------------------------------------------------ 12 --
      int Error=GetLastError();                 // Failed :(
      switch(Error)                             // Overcomable errors
        {
         case  4: Alert("Trade server is busy. Retrying..");
            Sleep(3000);                        // Simple solution
            continue;                           // At the next iteration
         case 137:Alert("Broker is busy. Retrying..");
            Sleep(3000);                        // Simple solution
            continue;                           // At the next iteration
         case 146:Alert("Trading subsystem is busy. Retrying..");
            Sleep(500);                         // Simple solution
            continue;                           // At the next iteration
        }
      switch(Error)                             // Critical errors
        {
         case 2 : Alert("Common error.");
            break;                              // Exit 'switch'
         case 64: Alert("Account is blocked.");
            break;                              // Exit 'switch'
         case 133:Alert("Trading is prohibited");
            break;                              // Exit 'switch'
         case 139:Alert("Order is blocked and is being processed");
            break;                              // Exit 'switch'
         case 145:Alert("Modification prohibited. ",
                              "Order is too close to the market");
            break;                              // Exit 'switch'
         default: Alert("Occurred error ",Error);//Other alternatives
        }
      break;                                    // Exit the closing cycle
     }                                          // End of closing cycle
//------------------------------------------------------------------------------ 13 --
   Alert ("The script has completed its operations -----------------------");
   return;                                      // Exit start()
  }
//------------------------------------------------------------------------------ 14 --```

答:
Welcome to the Worlds of MQL-4.56789...

Since the early days of the MQL4 language, the specifications 've changed a lot.

Your script suffers from a "recent"-New-MQL4.56789... change, where scope of validity of declared variables got restricted to a syntax-constructor-only ( this was not in the MQL4 original ).

So, declaring an int Tip et al but inside an if(){...}-block causes no Tip-variable to remain visible outside the {...}-block-constructor, not being know there anymore.

Next, your code requires a complete re-design, so as to meet your requirement of :

"not only for window currency but also for other currencies which are in the pending order list."

```<code>// ------------------------------------------------------------------------------- 2 --
for( int i=1; i <= OrdersTotal(); i++ )
   {
      if ( True == OrderSelect( i-1, SELECT_BY_POS ) )
      {
         //---------------------------------------------------------------------- 3 --
         if (  OrderSymbol() == Symb ) continue; // ------------------------^ JIT/LOOP
         if (  OrderType()   == OP_BUYSTOP
            || OrderType()   == OP_SELLSTOP
               ) continue; //-----------------------------------------------^ JIT/LOOP
                           //     btw. was a pending { BUYSTOP || SELLSTOP }
         //---------------------------------------------------------------------- 4 --
         {                 //              a rest goes here :
            int    Tip    = OrderType();
            int    Ticket = OrderTicket();
            double Price  = OrderOpenPrice();
            double SL     = OrderStopLoss();
            double TP     = OrderTakeProfit();
            }
         // ------------------------------ BUT ALL THESE GOT FORGOTTEN RIGHT HERE...
         }
      }
   // ------------------------------------ OK, 've LOOPED THE WHOLE DB-POOL,
   //                                                     BUT DID NOTHING SO FAR
   //                                                         AND NOTHING SO FORTH
</code>```

So, something evolved from this will help to settle the script on the rock-solid grounds :

```<code>#define MASK "(for i==(%3d)) got OrderTKT(%20d) of TYPE{BUY|SELL|BUYLIMIT|SELLLIMIT|BUYSTOP|SELLSTOP}=[%d] in (%10s)-MARKET ... WILL LOOP for a NEXT(?) ONE"

while ( !IsStopped() ) // ----------------------------------------------------------- 1 --
{                     //                             (almost) INFINITE SCRIPT SERVICE LOOP
                     //                           as (almost) HEADLESS Sir NICHOLAS :)
    string TradeSYMBOL;
    int    Tip;
    int    Ticket;
    double Price;
    double SL;
    double TP;

    if ( 1 > OrdersTotal() ) { Sleep( 333 ); continue; } // NOP / NAP ----------^ NOP/LOOP
    // ------------------------------------------------------------------------------ 2 --
    for( int i=0; i < OrdersTotal(); i++ )             //                     DB-POOL LOOP
    {
          if ( OrderSelect( i, SELECT_BY_POS ) )
          {
             //---------------------------------------------------------------------- 3 --
             if (  OrderType()   != OP_BUYSTOP
                && OrderType()   != OP_SELLSTOP
                   ) {
                   PrintFormat( MASK, i, OrderTicket(), OrderType(), OrderSymbol() );
                   continue; //-------------------------------------------------^ JIT/LOOP
                }              //     btw.   ! a pending { BUYSTOP || SELLSTOP }
             //---------------------------------------------------------------------- 4 --
             else
             {                 //              a         { BUYSTOP || SELLSTOP } go here :
             // -------------------------------------------------------------------- SET :
                Tip          = OrderType();
                Ticket       = OrderTicket();
                Price        = OrderOpenPrice();
                SL           = OrderStopLoss();
                TP           = OrderTakeProfit();
                TradeSYMBOL  = OrderSymbol();
             // ------------------------------------------------------------- PROCESS it :
                RefreshRates();
                ...
             // Alert()       - a blocking GUI operation, quite dangerous in auto-trading
             // any
             // OrderModify() - has also to respect the Broker-defined {Stop|Freeze}Level
                ...
                } // { BUYSTOP || SELLSTOP }
             }   //  .SELECT
         }      //   .DB-POOL LOOP________________________________________________________
    }          //    .SERVICE LOOP........................................................
</code>```

Title: Modify Pending Order at Mql4

Body:
Welcome to the Worlds of MQL-4.56789...

Since the early days of the MQL4 language, the specifications 've changed a lot.

Your script suffers from a "recent"-New-MQL4.56789... change, where scope of validity of declared variables got restricted to a syntax-constructor-only ( this was not in the MQL4 original ).

So, declaring an int Tip et al but inside an if(){...}-block causes no Tip-variable to remain visible outside the {...}-block-constructor, not being know there anymore.

Next, your code requires a complete re-design, so as to meet your requirement of :

"not only for window currency but also for other currencies which are in the pending order list."

// ------------------------------------------------------------------------------- 2 --
for( int i=1; i <= OrdersTotal(); i++ )
   {
      if ( True == OrderSelect( i-1, SELECT_BY_POS ) )
      {
         //---------------------------------------------------------------------- 3 --
         if (  OrderSymbol() == Symb ) continue; // ------------------------^ JIT/LOOP
         if (  OrderType()   == OP_BUYSTOP
            || OrderType()   == OP_SELLSTOP
               ) continue; //-----------------------------------------------^ JIT/LOOP
                           //     btw. was a pending { BUYSTOP || SELLSTOP }
         //---------------------------------------------------------------------- 4 --
         {                 //              a rest goes here :
            int    Tip    = OrderType();
            int    Ticket = OrderTicket();
            double Price  = OrderOpenPrice();
            double SL     = OrderStopLoss();
            double TP     = OrderTakeProfit();
            }
         // ------------------------------ BUT ALL THESE GOT FORGOTTEN RIGHT HERE...
         }
      }
   // ------------------------------------ OK, 've LOOPED THE WHOLE DB-POOL,
   //                                                     BUT DID NOTHING SO FAR
   //                                                         AND NOTHING SO FORTH

So, something evolved from this will help to settle the script on the rock-solid grounds :

#define MASK "(for i==(%3d)) got OrderTKT(%20d) of TYPE{BUY|SELL|BUYLIMIT|SELLLIMIT|BUYSTOP|SELLSTOP}=[%d] in (%10s)-MARKET ... WILL LOOP for a NEXT(?) ONE"

while ( !IsStopped() ) // ----------------------------------------------------------- 1 --
{                     //                             (almost) INFINITE SCRIPT SERVICE LOOP
                     //                           as (almost) HEADLESS Sir NICHOLAS :)
    string TradeSYMBOL;
    int    Tip;
    int    Ticket;
    double Price;
    double SL;
    double TP;

    if ( 1 > OrdersTotal() ) { Sleep( 333 ); continue; } // NOP / NAP ----------^ NOP/LOOP
    // ------------------------------------------------------------------------------ 2 --
    for( int i=0; i < OrdersTotal(); i++ )             //                     DB-POOL LOOP
    {
          if ( OrderSelect( i, SELECT_BY_POS ) )
          {
             //---------------------------------------------------------------------- 3 --
             if (  OrderType()   != OP_BUYSTOP
                && OrderType()   != OP_SELLSTOP
                   ) {
                   PrintFormat( MASK, i, OrderTicket(), OrderType(), OrderSymbol() );
                   continue; //-------------------------------------------------^ JIT/LOOP
                }              //     btw.   ! a pending { BUYSTOP || SELLSTOP }
             //---------------------------------------------------------------------- 4 --
             else
             {                 //              a         { BUYSTOP || SELLSTOP } go here :
             // -------------------------------------------------------------------- SET :
                Tip          = OrderType();
                Ticket       = OrderTicket();
                Price        = OrderOpenPrice();
                SL           = OrderStopLoss();
                TP           = OrderTakeProfit();
                TradeSYMBOL  = OrderSymbol();
             // ------------------------------------------------------------- PROCESS it :
                RefreshRates();
                ...
             // Alert()       - a blocking GUI operation, quite dangerous in auto-trading
             // any
             // OrderModify() - has also to respect the Broker-defined {Stop|Freeze}Level
                ...
                } // { BUYSTOP || SELLSTOP }
             }   //  .SELECT
         }      //   .DB-POOL LOOP________________________________________________________
    }          //    .SERVICE LOOP........................................................


问:
filter file with numeric column
I have an excel file with the following structure

```<code>ColumnA  ColumnB
NA       NA
Coord    Value
(1,2,3)  -23
(4,5,6)  -56
</code>```

I need to do the following:

Filter out rows that only have a numeric column in Column B

Once I filter out the rows, I need to create 3 columns from Column A

So for the above, I need a data set that looks like

```<code>x   y   z   value
1   2   3   -23
4   5   6   -56
</code>```

For starters, when I import the dataset, all columns a 'chr' and I'm having trouble forcing Column B to be numeric

答:
We can convert ColumnB to numeric and select rows which are not turned to NA. Remove opening and closing round brackets from the string and use separate to get data in different columns.

```<code>library(dplyr)

df %>%
  filter(!is.na(as.numeric(ColumnB))) %>%
  mutate(ColumnA = gsub('[()]', '', ColumnA)) %>%
  tidyr::separate(ColumnA, into = c("A", "B", "C"), sep = ",")

#  A B C ColumnB
#1 1 2 3     -23
#2 4 5 6     -56
</code>```

data

```<code>df <- structure(list(ColumnA = c(NA, "Coord", "(1,2,3)", "(4,5,6)"), ColumnB = c(NA,
"Value", "-23", "-56")),class = "data.frame", row.names = c(NA, -4L))
</code>```

Title: filter file with numeric column

Body:
I have an excel file with the following structure

ColumnA  ColumnB
NA       NA
Coord    Value
(1,2,3)  -23
(4,5,6)  -56

I need to do the following:

Filter out rows that only have a numeric column in Column B

Once I filter out the rows, I need to create 3 columns from Column A

So for the above, I need a data set that looks like

x   y   z   value
1   2   3   -23
4   5   6   -56

For starters, when I import the dataset, all columns a 'chr' and I'm having trouble forcing Column B to be numeric

Body:
We can convert ColumnB to numeric and select rows which are not turned to NA. Remove opening and closing round brackets from the string and use separate to get data in different columns.

library(dplyr)

df %>%
  filter(!is.na(as.numeric(ColumnB))) %>%
  mutate(ColumnA = gsub('[()]', '', ColumnA)) %>%
  tidyr::separate(ColumnA, into = c("A", "B", "C"), sep = ",")

#  A B C ColumnB
#1 1 2 3     -23
#2 4 5 6     -56

data

df <- structure(list(ColumnA = c(NA, "Coord", "(1,2,3)", "(4,5,6)"), ColumnB = c(NA,
"Value", "-23", "-56")),class = "data.frame", row.names = c(NA, -4L))


问:
How to force right resource file to be used when calling from another module
Here is the scenario  (newbie to spark scala so kindly bear with me)

1) I have  module A  and a config file under resources folder. Class C in module A reads this config to get information about the file paths

2) i am trying to call Class C (module A)  from Module B (after importing the dependencies of Module A in module B)

3) Issue i am facing is  Class C (module) code  when invoked from Module B , is using the config  from Module B instead of its own config in Module A

Note : code works perfectly when i call with in Module A but once i move this code to Module B its using the resources file in Module B instead of Module A resource file.

both the configs have same name.

答:
From the discussion in regard to my original answer, which assumed Lightbend Config (commonly used in the Scala world), it's been discovered that some sort of config.xml is in src/main/resources for the respective modules.  These files both end up on the classpath and each module attempts (by an at this point unspecified means) to load the config.xml resource.

The JVM when asked to load resources always loads the first which matches.

The easiest way in a small set of projects to address this collision is to not collide by giving the configs in each project different names.

An alternative which is viable in a larger set of projects is to use Lightbend Config which allows config file inclusion out of the box, as well as the ability to use environment variables to easily override configurations at runtime.

An elaborate strategy for a larger set of projects, depending on how compatible the XML schemas for the various module's config.xmls are (if they're being read using a schema) is to define a custom Maven build process which embeds config.xmls inside one another so that code in module A and module B can share a config.xml: A only cares about the portion of the config which came from A and B only cares about that from B.  I'm not particularly familiar with how one would do this in Maven, but I can't think of a reason why it wouldn't be possible.