问:
Find a same column in different table in sql
I have a small problem, I have four table, I'm using mysql database

Survey Table Here all survey will be created.

```<code>╔══════════╤════════╗
║ SurveyId │ Name   ║
╠══════════╪════════╣
║ 1        │ First  ║
╟──────────┼────────╢
║ 2        │ Second ║
╚══════════╧════════╝
</code>```

Gauge category table

```<code>╔════════════╤═════════════╗
║ CategoryId │ Title       ║
╠════════════╪═════════════╣
║ 1          │ Stress      ║
╟────────────┼─────────────╢
║ 2          │ Environment ║
╟────────────┼─────────────╢
║ 3          │ Health      ║
╚════════════╧═════════════╝
</code>```

To connect both Gauge Category table with Survey table,

I use another table called Title table

Title table

Here title1,title2 and title3 are foreign keys of Gauge Category table, and surveyId is foreign key of Survey table

```<code>╔══════════════╤════════╤════════╤════════╤══════════╗
║ GaugeTitleId │ title1 │ title2 │ title3 │ surveyId ║
╠══════════════╪════════╪════════╪════════╪══════════╣
║ 1            │ 2      │ 3      │ 1      │ 1        ║
╟──────────────┼────────┼────────┼────────┼──────────╢
║ 2            │ 1      │ 3      │ 2      │ 1        ║
╟──────────────┼────────┼────────┼────────┼──────────╢
║ 3            │ 3      │ 1      │ 2      │ 2        ║
╚══════════════╧════════╧════════╧════════╧══════════╝
</code>```

Another table called called Average_values which has respective value of Title table

Average_values table

```<code>╔═════════╤════════╤════════╤════════╤══════════╤══════════════╗
║ GaugeID │ Gauge1 │ Guage2 │ Gauge3 │ SurveyId │ GaugeTitleId ║
╠═════════╪════════╪════════╪════════╪══════════╪══════════════╣
║ 1       │ 34     │ 76     │ 23     │ 1        │ 1            ║
╟─────────┼────────┼────────┼────────┼──────────┼──────────────╢
║ 2       │ 56     │ 23     │ 67     │ 1        │ 1            ║
╟─────────┼────────┼────────┼────────┼──────────┼──────────────╢
║ 3       │ 14     │ 28     │ 56     │ 1        │ 2            ║
╚═════════╧════════╧════════╧════════╧══════════╧══════════════╝
</code>```

My problem is, If I want to get the Stress values from Average_values table, how can I get it? Because the foreign keys are not in order. The output should be 23,56,28 . Is there any way to get it? I have another alternative idea, that modify the Average_values Table to

```<code>╔═════════╤════════╤════════════╤══════════╗
║ GuageId │ values │ CategoryId │ SurveyId ║
╚═════════╧════════╧════════════╧══════════╝
</code>```

and put the values one by one, Here CategoryId and SurveyID are in foreign key relationship of Gauge category table and Survey Table respectively. But I feel, it won't be an efficient table. Because a lot of data wants to be processed dynamically.

答:
I feel your table design is weird and 2 of those tables need to be "unpivoted" in my view to remove the 1,2,3 suffixes on some fields. It remains a mystery as to what the rest of your question is. There is no clear way to join to a table called Guage but has a key of CategoryID below is a query that does an "unpivot" and attempts to join all tables

SQL Fiddle

MySQL 5.6 Schema Setup:

```<code>CREATE TABLE Survey
    (`SurveyId` int, `Name` varchar(6))
;

INSERT INTO Survey
    (`SurveyId`, `Name`)
VALUES
    (1, 'First'),
    (2, 'Second')
;

CREATE TABLE Gauge
    (`CategoryId` int, `Title` varchar(11))
;

INSERT INTO Gauge
    (`CategoryId`, `Title`)
VALUES
    (1, 'Stress'),
    (2, 'Environment'),
    (3, 'Health')
;

CREATE TABLE Title
    (`GaugeTitleId` int, `title1` int, `title2` int, `title3` int, `surveyId` int)
;

INSERT INTO Title
    (`GaugeTitleId`, `title1`, `title2`, `title3`, `surveyId`)
VALUES
    (1, 2, 3, 1, 1),
    (2, 1, 3, 2, 1),
    (3, 3, 1, 2, 2)
;

CREATE TABLE Average_values
    (`GaugeID` int, `Gauge1` int, `Guage2` int, `Gauge3` int, `SurveyId` int, `GaugeTitleId` int)
;

INSERT INTO Average_values
    (`GaugeID`, `Gauge1`, `Guage2`, `Gauge3`, `SurveyId`, `GaugeTitleId`)
VALUES
    (1, 34, 76, 23, 1, 1),
    (2, 56, 23, 67, 1, 1),
    (3, 14, 28, 56, 1, 2)
;
</code>```

Query 1:

```<code>select
        t.surveyId
      , t.GaugeTitleId
      , g.title Gauge_Title
      , case when cj.n = 1 then t.title1
             when cj.n = 2 then t.title2
             when cj.n = 3 then t.title3
        end Title
      , case when cj.n = 1 then av.Gauge1
             when cj.n = 2 then av.Guage2
             when cj.n = 3 then av.Gauge3
        end Gauge
from Title t
cross join (
  select 1 n union all
  select 2 n union all
  select 3 n) cj
inner join Average_values av on t.surveyId = av.surveyId
                            and t.GaugeTitleId = av.GaugeTitleId
inner join Gauge g on t.GaugeTitleId = g.CategoryId
where g.title = 'Stress'
order by Title, Gauge
</code>```

Results:

```<code>| surveyId | GaugeTitleId | Gauge_Title | Title | Gauge |
|----------|--------------|-------------|-------|-------|
|        1 |            1 |      Stress |     1 |    23 |
|        1 |            1 |      Stress |     1 |    67 |
|        1 |            1 |      Stress |     2 |    34 |
|        1 |            1 |      Stress |     2 |    56 |
|        1 |            1 |      Stress |     3 |    23 |
|        1 |            1 |      Stress |     3 |    76 |
</code>```

Body:
I have a small problem, I have four table, I'm using mysql database

Survey Table Here all survey will be created.

╔══════════╤════════╗
║ SurveyId │ Name   ║
╠══════════╪════════╣
║ 1        │ First  ║
╟──────────┼────────╢
║ 2        │ Second ║
╚══════════╧════════╝

Gauge category table

╔════════════╤═════════════╗
║ CategoryId │ Title       ║
╠════════════╪═════════════╣
║ 1          │ Stress      ║
╟────────────┼─────────────╢
║ 2          │ Environment ║
╟────────────┼─────────────╢
║ 3          │ Health      ║
╚════════════╧═════════════╝

To connect both Gauge Category table with Survey table,

I use another table called Title table

Title table

Here title1,title2 and title3 are foreign keys of Gauge Category table, and surveyId is foreign key of Survey table

╔══════════════╤════════╤════════╤════════╤══════════╗
║ GaugeTitleId │ title1 │ title2 │ title3 │ surveyId ║
╠══════════════╪════════╪════════╪════════╪══════════╣
║ 1            │ 2      │ 3      │ 1      │ 1        ║
╟──────────────┼────────┼────────┼────────┼──────────╢
║ 2            │ 1      │ 3      │ 2      │ 1        ║
╟──────────────┼────────┼────────┼────────┼──────────╢
║ 3            │ 3      │ 1      │ 2      │ 2        ║
╚══════════════╧════════╧════════╧════════╧══════════╝

Another table called called Average_values which has respective value of Title table

Average_values table

╔═════════╤════════╤════════╤════════╤══════════╤══════════════╗
║ GaugeID │ Gauge1 │ Guage2 │ Gauge3 │ SurveyId │ GaugeTitleId ║
╠═════════╪════════╪════════╪════════╪══════════╪══════════════╣
║ 1       │ 34     │ 76     │ 23     │ 1        │ 1            ║
╟─────────┼────────┼────────┼────────┼──────────┼──────────────╢
║ 2       │ 56     │ 23     │ 67     │ 1        │ 1            ║
╟─────────┼────────┼────────┼────────┼──────────┼──────────────╢
║ 3       │ 14     │ 28     │ 56     │ 1        │ 2            ║
╚═════════╧════════╧════════╧════════╧══════════╧══════════════╝

My problem is, If I want to get the Stress values from Average_values table, how can I get it? Because the foreign keys are not in order. The output should be 23,56,28 . Is there any way to get it? I have another alternative idea, that modify the Average_values Table to

╔═════════╤════════╤════════════╤══════════╗
║ GuageId │ values │ CategoryId │ SurveyId ║
╚═════════╧════════╧════════════╧══════════╝

and put the values one by one, Here CategoryId and SurveyID are in foreign key relationship of Gauge category table and Survey Table respectively. But I feel, it won't be an efficient table. Because a lot of data wants to be processed dynamically.

Body:
I feel your table design is weird and 2 of those tables need to be "unpivoted" in my view to remove the 1,2,3 suffixes on some fields. It remains a mystery as to what the rest of your question is. There is no clear way to join to a table called Guage but has a key of CategoryID below is a query that does an "unpivot" and attempts to join all tables

SQL Fiddle

MySQL 5.6 Schema Setup:

CREATE TABLE Survey
    (`SurveyId` int, `Name` varchar(6))
;

INSERT INTO Survey
    (`SurveyId`, `Name`)
VALUES
    (1, 'First'),
    (2, 'Second')
;

CREATE TABLE Gauge
    (`CategoryId` int, `Title` varchar(11))
;

INSERT INTO Gauge
    (`CategoryId`, `Title`)
VALUES
    (1, 'Stress'),
    (2, 'Environment'),
    (3, 'Health')
;

CREATE TABLE Title
    (`GaugeTitleId` int, `title1` int, `title2` int, `title3` int, `surveyId` int)
;

INSERT INTO Title
    (`GaugeTitleId`, `title1`, `title2`, `title3`, `surveyId`)
VALUES
    (1, 2, 3, 1, 1),
    (2, 1, 3, 2, 1),
    (3, 3, 1, 2, 2)
;

CREATE TABLE Average_values
    (`GaugeID` int, `Gauge1` int, `Guage2` int, `Gauge3` int, `SurveyId` int, `GaugeTitleId` int)
;

INSERT INTO Average_values
    (`GaugeID`, `Gauge1`, `Guage2`, `Gauge3`, `SurveyId`, `GaugeTitleId`)
VALUES
    (1, 34, 76, 23, 1, 1),
    (2, 56, 23, 67, 1, 1),
    (3, 14, 28, 56, 1, 2)
;

Query 1:

select
        t.surveyId
      , t.GaugeTitleId
      , g.title Gauge_Title
      , case when cj.n = 1 then t.title1
             when cj.n = 2 then t.title2
             when cj.n = 3 then t.title3
        end Title
      , case when cj.n = 1 then av.Gauge1
             when cj.n = 2 then av.Guage2
             when cj.n = 3 then av.Gauge3
        end Gauge
from Title t
cross join (
  select 1 n union all
  select 2 n union all
  select 3 n) cj
inner join Average_values av on t.surveyId = av.surveyId
                            and t.GaugeTitleId = av.GaugeTitleId
inner join Gauge g on t.GaugeTitleId = g.CategoryId
where g.title = 'Stress'
order by Title, Gauge

Results:

| surveyId | GaugeTitleId | Gauge_Title | Title | Gauge |
|----------|--------------|-------------|-------|-------|
|        1 |            1 |      Stress |     1 |    23 |
|        1 |            1 |      Stress |     1 |    67 |
|        1 |            1 |      Stress |     2 |    34 |
|        1 |            1 |      Stress |     2 |    56 |
|        1 |            1 |      Stress |     3 |    23 |
|        1 |            1 |      Stress |     3 |    76 |


来源: stackexchange

问:
Trying to extract a GUID from a text, using batch (findstr + regexp)
I want to isolate a specific string from a text provided in a variable, using batch, but it doesn't seem to work as intended. I may do the regexp wrong, or maybe I misunderstood the way "findstr" works.

Te specific string that I need to isolate is a GUID (which has a standard format of alphanumeric characters, arranged in groups of characters separated by a "-", like this: 8-4-4-4-12)

```<code>@echo off
setlocal enabledelayedexpansion

SET str="This is a string that has a long uuid: (UUID: 359f975d-2649-4e20-b7c0-b452aaaca4b2)"
SET rx=[a-zA-Z0-9]{8}-[a-zA-Z0-9]{4}-[a-zA-Z0-9]{4}-[a-zA-Z0-9]{4}-[a-zA-Z0-9]{12}

 FOR %%u IN ('FINDSTR /r "!rx!" "!str!"') DO ECHO %%u

endlocal
</code>```

Basically, what I need is to store the GUID in a separate variable, so I can use it later on. If that can be achieved in a different manner, I'm happy to learn!

Thanks!

答:
@ECHO Off
SETLOCAL
SET "str=This is a string that has a long uuid: (UUID: 359f975d-2649-4e20-b7c0-b452aaaca4b2)"

:: Theoretical

SET "hn=[a-f0-9]"
SET "hn4=%hn%%hn%%hn%%hn%"
SET "hn8=%hn4%%hn4%"
SET "wrx=%hn8%-%hn4%-%hn4%-%hn4%-%hn8%%hn4%"
:again
IF NOT DEFINED str ECHO notfound&GOTO done
ECHO %str%|FINDSTR /b /r /i "%wrx%">NUL
IF ERRORLEVEL 1 (
 REM did not find string
 SET "str=%str:~1%"
 GOTO again
)
SET "str=%str:~0,36%"
ECHO found "%str%"

:done

:: BFI method

SET "str=This is a string that has a long uuid: (UUID: 359f975d-2649-4e20-b7c0-b452aaaca4b2)"
SET "hn=[a-f0-9]"
SET "hn4=%hn%%hn%%hn%%hn%"
SET "hn8=%hn4%%hn4%"

:bfiagain
IF NOT DEFINED str ECHO notfound&GOTO donebfi
:: "regex" using brute-force and ignorance
ECHO %str:~0,9%|FINDSTR /b /i /r  "%hn8%-">NUL
IF ERRORLEVEL 1 GOTO bfino
ECHO %str:~9,5%|FINDSTR /b /i /r  "%hn4%-">NUL
IF ERRORLEVEL 1 GOTO bfino
ECHO %str:~14,10%|FINDSTR /b /i /r  "%hn4%-%hn4%-">NUL
IF ERRORLEVEL 1 GOTO bfino
ECHO %str:~24,12%|FINDSTR /b /i /r  "%hn4%%hn8%">NUL
:bfino
IF ERRORLEVEL 1 (
 SET "str=%str:~1%"
 GOTO bfiagain
)
SET "str=%str:~0,36%"
ECHO found "%str%"

:donebfi

GOTO :EOF
```

Well, not so squeezy...

Fundamentally, findstr implements a very small subset of regex. It's intended to locate a character-string in a file.

Theoretically, you could string [a-f0-9] together the requisite number of times and add in the - separators for use as the "regex", then see whether the subject string /b (begins) with such a pattern; lop off the start character if not and repeat until found or subject-string is empty.

Notes here: I believe GUID uses HEX digits only, not alphanumerics. findstr supports /i to have the comparison made case-insensitively (which shortens the individual "character-match" string). Yes - I know ^ can be used in a regex (even one from Uncle Bill's little programmers' toolset) but I prefer /b.

The only small problem with this is that it yielded an out of memory error...

So, feed it small chunks at a time, and it appears happy...

I've done no further testing, and predict stormy weather if your text-string contains characters which cmd regards as specials - the usual suspects like redirectors, % and rabbit's ears.

ContentLicense: CC BY-SA 3.0

Body:
I want to isolate a specific string from a text provided in a variable, using batch, but it doesn't seem to work as intended. I may do the regexp wrong, or maybe I misunderstood the way "findstr" works.

Te specific string that I need to isolate is a GUID (which has a standard format of alphanumeric characters, arranged in groups of characters separated by a "-", like this: 8-4-4-4-12)

@echo off
setlocal enabledelayedexpansion

SET str="This is a string that has a long uuid: (UUID: 359f975d-2649-4e20-b7c0-b452aaaca4b2)"
SET rx=[a-zA-Z0-9]{8}-[a-zA-Z0-9]{4}-[a-zA-Z0-9]{4}-[a-zA-Z0-9]{4}-[a-zA-Z0-9]{12}

 FOR %%u IN ('FINDSTR /r "!rx!" "!str!"') DO ECHO %%u

endlocal

Basically, what I need is to store the GUID in a separate variable, so I can use it later on. If that can be achieved in a different manner, I'm happy to learn!

Thanks!

Body:
@ECHO Off
SETLOCAL
SET "str=This is a string that has a long uuid: (UUID: 359f975d-2649-4e20-b7c0-b452aaaca4b2)"

:: Theoretical

SET "hn=[a-f0-9]"
SET "hn4=%hn%%hn%%hn%%hn%"
SET "hn8=%hn4%%hn4%"
SET "wrx=%hn8%-%hn4%-%hn4%-%hn4%-%hn8%%hn4%"
:again
IF NOT DEFINED str ECHO notfound&GOTO done
ECHO %str%|FINDSTR /b /r /i "%wrx%">NUL
IF ERRORLEVEL 1 (
 REM did not find string
 SET "str=%str:~1%"
 GOTO again
)
SET "str=%str:~0,36%"
ECHO found "%str%"

:done

:: BFI method

SET "str=This is a string that has a long uuid: (UUID: 359f975d-2649-4e20-b7c0-b452aaaca4b2)"
SET "hn=[a-f0-9]"
SET "hn4=%hn%%hn%%hn%%hn%"
SET "hn8=%hn4%%hn4%"

:bfiagain
IF NOT DEFINED str ECHO notfound&GOTO donebfi
:: "regex" using brute-force and ignorance
ECHO %str:~0,9%|FINDSTR /b /i /r  "%hn8%-">NUL
IF ERRORLEVEL 1 GOTO bfino
ECHO %str:~9,5%|FINDSTR /b /i /r  "%hn4%-">NUL
IF ERRORLEVEL 1 GOTO bfino
ECHO %str:~14,10%|FINDSTR /b /i /r  "%hn4%-%hn4%-">NUL
IF ERRORLEVEL 1 GOTO bfino
ECHO %str:~24,12%|FINDSTR /b /i /r  "%hn4%%hn8%">NUL
:bfino
IF ERRORLEVEL 1 (
 SET "str=%str:~1%"
 GOTO bfiagain
)
SET "str=%str:~0,36%"
ECHO found "%str%"

:donebfi

GOTO :EOF

Well, not so squeezy...

Fundamentally, findstr implements a very small subset of regex. It's intended to locate a character-string in a file.

Theoretically, you could string [a-f0-9] together the requisite number of times and add in the - separators for use as the "regex", then see whether the subject string /b (begins) with such a pattern; lop off the start character if not and repeat until found or subject-string is empty.

Notes here: I believe GUID uses HEX digits only, not alphanumerics. findstr supports /i to have the comparison made case-insensitively (which shortens the individual "character-match" string). Yes - I know ^ can be used in a regex (even one from Uncle Bill's little programmers' toolset) but I prefer /b.

The only small problem with this is that it yielded an out of memory error...

So, feed it small chunks at a time, and it appears happy...

I've done no further testing, and predict stormy weather if your text-string contains characters which cmd regards as specials - the usual suspects like redirectors, % and rabbit's ears.


问:
Scapy Installation error in CentOS release 6.9 server?
I am trying to install scapy in server. But I am getting error.
1) I installed pip, python 2.66 was already installed.
2) Then i ran command pip installed scapy

Then in the terminal when i type scapy, i get:

```<code>[root@virgina02 alamin]# scapy
INFO: Can't import matplotlib. Won't be able to plot.
INFO: Can't import PyX. Won't be able to use psdump() or pdfdump().
INFO: No IPv6 support in kernel
WARNING: No route found for IPv6 destination :: (no default route?)
INFO: Can't import python Crypto lib. Won't be able to decrypt WEP.
INFO: Can't import python Crypto lib. Disabled certificate manipulation tools
INFO: Can't import python ecdsa lib. Disabled certificate manipulation tools
Exception RuntimeError: 'maximum recursion depth exceeded while calling a Python object' in <type 'exceptions.AttributeError'> ignored
Exception RuntimeError: 'maximum recursion depth exceeded while calling a Python object' in <type 'exceptions.AttributeError'> ignored
Exception RuntimeError: 'maximum recursion depth exceeded while calling a Python object' in <type 'exceptions.AttributeError'> ignored
Exception RuntimeError: 'maximum recursion depth exceeded in __subclasscheck__' in <type 'exceptions.AttributeError'> ignored
Exception RuntimeError: 'maximum recursion depth exceeded in __subclasscheck__' in <type 'exceptions.AttributeError'> ignored
Exception RuntimeError: 'maximum recursion depth exceeded in __subclasscheck__' in <type 'exceptions.AttributeError'> ignored
Exception RuntimeError: 'maximum recursion depth exceeded in __subclasscheck__' in <type 'exceptions.AttributeError'> ignored
Exception RuntimeError: 'maximum recursion depth exceeded in __subclasscheck__' in <type 'exceptions.AttributeError'> ignored
Exception RuntimeError: 'maximum recursion depth exceeded in __subclasscheck__' in <type 'exceptions.AttributeError'> ignored
Exception RuntimeError: 'maximum recursion depth exceeded in __subclasscheck__' in <type 'exceptions.AttributeError'> ignored
Exception RuntimeError: 'maximum recursion depth exceeded in __subclasscheck__' in <type 'exceptions.AttributeError'> ignored
Exception RuntimeError: 'maximum recursion depth exceeded in __subclasscheck__' in <type 'exceptions.AttributeError'> ignored
Exception RuntimeError: 'maximum recursion depth exceeded in __subclasscheck__' in <type 'exceptions.AttributeError'> ignored
Exception RuntimeError: 'maximum recursion depth exceeded in __subclasscheck__' in <type 'exceptions.AttributeError'> ignored
Exception RuntimeError: 'maximum recursion depth exceeded in __subclasscheck__' in <type 'exceptions.AttributeError'> ignored
Exception RuntimeError: 'maximum recursion depth exceeded in __subclasscheck__' in <type 'exceptions.AttributeError'> ignored
Exception RuntimeError: 'maximum recursion depth exceeded in __subclasscheck__' in <type 'exceptions.AttributeError'> ignored
Exception RuntimeError: 'maximum recursion depth exceeded in __subclasscheck__' in <type 'exceptions.AttributeError'> ignored
Exception RuntimeError: 'maximum recursion depth exceeded in __subclasscheck__' in <type 'exceptions.AttributeError'> ignored
Exception RuntimeError: 'maximum recursion depth exceeded in __subclasscheck__' in <type 'exceptions.AttributeError'> ignored
Exception RuntimeError: 'maximum recursion depth exceeded in __subclasscheck__' in <type 'exceptions.AttributeError'> ignored
Exception RuntimeError: 'maximum recursion depth exceeded in __subclasscheck__' in <type 'exceptions.AttributeError'> ignored
Exception RuntimeError: 'maximum recursion depth exceeded in __subclasscheck__' in <type 'exceptions.AttributeError'> ignored
Exception RuntimeError: 'maximum recursion depth exceeded in __subclasscheck__' in <type 'exceptions.AttributeError'> ignored
Exception RuntimeError: 'maximum recursion depth exceeded in __subclasscheck__' in <type 'exceptions.AttributeError'> ignored
Exception RuntimeError: 'maximum recursion depth exceeded in __subclasscheck__' in <type 'exceptions.AttributeError'> ignored
Exception RuntimeError: 'maximum recursion depth exceeded in __subclasscheck__' in <type 'exceptions.AttributeError'> ignored
Exception RuntimeError: 'maximum recursion depth exceeded in __subclasscheck__' in <type 'exceptions.AttributeError'> ignored
Exception RuntimeError: 'maximum recursion depth exceeded in __subclasscheck__' in <type 'exceptions.AttributeError'> ignored
Exception RuntimeError: 'maximum recursion depth exceeded in __subclasscheck__' in <type 'exceptions.AttributeError'> ignored
Exception RuntimeError: 'maximum recursion depth exceeded in __subclasscheck__' in <type 'exceptions.AttributeError'> ignored
Exception RuntimeError: 'maximum recursion depth exceeded in __subclasscheck__' in <type 'exceptions.AttributeError'> ignored
Exception RuntimeError: 'maximum recursion depth exceeded in __subclasscheck__' in <type 'exceptions.AttributeError'> ignored
Exception RuntimeError: 'maximum recursion depth exceeded in __subclasscheck__' in <type 'exceptions.AttributeError'> ignored
Exception RuntimeError: 'maximum recursion depth exceeded in __subclasscheck__' in <type 'exceptions.AttributeError'> ignored
Exception RuntimeError: 'maximum recursion depth exceeded in __subclasscheck__' in <type 'exceptions.AttributeError'> ignored
Exception RuntimeError: 'maximum recursion depth exceeded in __subclasscheck__' in <type 'exceptions.AttributeError'> ignored
Exception RuntimeError: 'maximum recursion depth exceeded in __subclasscheck__' in <type 'exceptions.AttributeError'> ignored
Exception RuntimeError: 'maximum recursion depth exceeded in __subclasscheck__' in <type 'exceptions.AttributeError'> ignored
Exception RuntimeError: 'maximum recursion depth exceeded in __subclasscheck__' in <type 'exceptions.AttributeError'> ignored
Exception RuntimeError: 'maximum recursion depth exceeded in __subclasscheck__' in <type 'exceptions.AttributeError'> ignored
Exception RuntimeError: 'maximum recursion depth exceeded in __subclasscheck__' in <type 'exceptions.AttributeError'> ignored
Exception RuntimeError: 'maximum recursion depth exceeded in __subclasscheck__' in <type 'exceptions.AttributeError'> ignored
Exception RuntimeError: 'maximum recursion depth exceeded in __subclasscheck__' in <type 'exceptions.AttributeError'> ignored
Exception RuntimeError: 'maximum recursion depth exceeded in __subclasscheck__' in <type 'exceptions.AttributeError'> ignored
Exception RuntimeError: 'maximum recursion depth exceeded in __subclasscheck__' in <type 'exceptions.AttributeError'> ignored
Exception RuntimeError: 'maximum recursion depth exceeded in __subclasscheck__' in <type 'exceptions.AttributeError'> ignored
Exception RuntimeError: 'maximum recursion depth exceeded in __subclasscheck__' in <type 'exceptions.AttributeError'> ignored
Exception RuntimeError: 'maximum recursion depth exceeded in __subclasscheck__' in <type 'exceptions.AttributeError'> ignored
Exception RuntimeError: 'maximum recursion depth exceeded in __subclasscheck__' in <type 'exceptions.AttributeError'> ignored
Exception RuntimeError: 'maximum recursion depth exceeded while calling a Python object' in <type 'exceptions.AttributeError'> ignored
Exception RuntimeError: 'maximum recursion depth exceeded while calling a Python object' in <type 'exceptions.AttributeError'> ignored
Exception RuntimeError: 'maximum recursion depth exceeded while calling a Python object' in <type 'exceptions.AttributeError'> ignored
Exception RuntimeError: 'maximum recursion depth exceeded while calling a Python object' in <type 'exceptions.AttributeError'> ignored
Exception RuntimeError: 'maximum recursion depth exceeded while calling a Python object' in <type 'exceptions.AttributeError'> ignored
Exception RuntimeError: 'maximum recursion depth exceeded while calling a Python object' in <type 'exceptions.AttributeError'> ignored
Exception RuntimeError: 'maximum recursion depth exceeded in __subclasscheck__' in <type 'exceptions.AttributeError'> ignored
Exception RuntimeError: 'maximum recursion depth exceeded in __subclasscheck__' in <type 'exceptions.AttributeError'> ignored
Exception RuntimeError: 'maximum recursion depth exceeded in __subclasscheck__' in <type 'exceptions.AttributeError'> ignored
Exception RuntimeError: 'maximum recursion depth exceeded in __subclasscheck__' in <type 'exceptions.AttributeError'> ignored
Exception RuntimeError: 'maximum recursion depth exceeded in __subclasscheck__' in <type 'exceptions.AttributeError'> ignored
Exception RuntimeError: 'maximum recursion depth exceeded in __subclasscheck__' in <type 'exceptions.AttributeError'> ignored
Exception RuntimeError: 'maximum recursion depth exceeded in __subclasscheck__' in <type 'exceptions.AttributeError'> ignored
Exception RuntimeError: 'maximum recursion depth exceeded in __subclasscheck__' in <type 'exceptions.AttributeError'> ignored
Exception RuntimeError: 'maximum recursion depth exceeded in __subclasscheck__' in <type 'exceptions.AttributeError'> ignored
Exception RuntimeError: 'maximum recursion depth exceeded in __subclasscheck__' in <type 'exceptions.AttributeError'> ignored
Exception RuntimeError: 'maximum recursion depth exceeded in __subclasscheck__' in <type 'exceptions.AttributeError'> ignored
Exception RuntimeError: 'maximum recursion depth exceeded in __subclasscheck__' in <type 'exceptions.AttributeError'> ignored
Welcome to Scapy (2.3.3)
>>
</code>```

now I can still use scapy to send tcp packets but I am getting checksum error. So I was wondering if that checksum error was related to the above error?

答:
try sudo python that might work.

For detailed info, see

Body:
I am trying to install scapy in server. But I am getting error.
1) I installed pip, python 2.66 was already installed.
2) Then i ran command pip installed scapy

Then in the terminal when i type scapy, i get:

[root@virgina02 alamin]# scapy
INFO: Can't import matplotlib. Won't be able to plot.
INFO: Can't import PyX. Won't be able to use psdump() or pdfdump().
INFO: No IPv6 support in kernel
WARNING: No route found for IPv6 destination :: (no default route?)
INFO: Can't import python Crypto lib. Won't be able to decrypt WEP.
INFO: Can't import python Crypto lib. Disabled certificate manipulation tools
INFO: Can't import python ecdsa lib. Disabled certificate manipulation tools
Exception RuntimeError: 'maximum recursion depth exceeded while calling a Python object' in <type 'exceptions.AttributeError'> ignored
Exception RuntimeError: 'maximum recursion depth exceeded while calling a Python object' in <type 'exceptions.AttributeError'> ignored
Exception RuntimeError: 'maximum recursion depth exceeded while calling a Python object' in <type 'exceptions.AttributeError'> ignored
Exception RuntimeError: 'maximum recursion depth exceeded in __subclasscheck__' in <type 'exceptions.AttributeError'> ignored
Exception RuntimeError: 'maximum recursion depth exceeded in __subclasscheck__' in <type 'exceptions.AttributeError'> ignored
Exception RuntimeError: 'maximum recursion depth exceeded in __subclasscheck__' in <type 'exceptions.AttributeError'> ignored
Exception RuntimeError: 'maximum recursion depth exceeded in __subclasscheck__' in <type 'exceptions.AttributeError'> ignored
Exception RuntimeError: 'maximum recursion depth exceeded in __subclasscheck__' in <type 'exceptions.AttributeError'> ignored
Exception RuntimeError: 'maximum recursion depth exceeded in __subclasscheck__' in <type 'exceptions.AttributeError'> ignored
Exception RuntimeError: 'maximum recursion depth exceeded in __subclasscheck__' in <type 'exceptions.AttributeError'> ignored
Exception RuntimeError: 'maximum recursion depth exceeded in __subclasscheck__' in <type 'exceptions.AttributeError'> ignored
Exception RuntimeError: 'maximum recursion depth exceeded in __subclasscheck__' in <type 'exceptions.AttributeError'> ignored
Exception RuntimeError: 'maximum recursion depth exceeded in __subclasscheck__' in <type 'exceptions.AttributeError'> ignored
Exception RuntimeError: 'maximum recursion depth exceeded in __subclasscheck__' in <type 'exceptions.AttributeError'> ignored
Exception RuntimeError: 'maximum recursion depth exceeded in __subclasscheck__' in <type 'exceptions.AttributeError'> ignored
Exception RuntimeError: 'maximum recursion depth exceeded in __subclasscheck__' in <type 'exceptions.AttributeError'> ignored
Exception RuntimeError: 'maximum recursion depth exceeded in __subclasscheck__' in <type 'exceptions.AttributeError'> ignored
Exception RuntimeError: 'maximum recursion depth exceeded in __subclasscheck__' in <type 'exceptions.AttributeError'> ignored
Exception RuntimeError: 'maximum recursion depth exceeded in __subclasscheck__' in <type 'exceptions.AttributeError'> ignored
Exception RuntimeError: 'maximum recursion depth exceeded in __subclasscheck__' in <type 'exceptions.AttributeError'> ignored
Exception RuntimeError: 'maximum recursion depth exceeded in __subclasscheck__' in <type 'exceptions.AttributeError'> ignored
Exception RuntimeError: 'maximum recursion depth exceeded in __subclasscheck__' in <type 'exceptions.AttributeError'> ignored
Exception RuntimeError: 'maximum recursion depth exceeded in __subclasscheck__' in <type 'exceptions.AttributeError'> ignored
Exception RuntimeError: 'maximum recursion depth exceeded in __subclasscheck__' in <type 'exceptions.AttributeError'> ignored
Exception RuntimeError: 'maximum recursion depth exceeded in __subclasscheck__' in <type 'exceptions.AttributeError'> ignored
Exception RuntimeError: 'maximum recursion depth exceeded in __subclasscheck__' in <type 'exceptions.AttributeError'> ignored
Exception RuntimeError: 'maximum recursion depth exceeded in __subclasscheck__' in <type 'exceptions.AttributeError'> ignored
Exception RuntimeError: 'maximum recursion depth exceeded in __subclasscheck__' in <type 'exceptions.AttributeError'> ignored
Exception RuntimeError: 'maximum recursion depth exceeded in __subclasscheck__' in <type 'exceptions.AttributeError'> ignored
Exception RuntimeError: 'maximum recursion depth exceeded in __subclasscheck__' in <type 'exceptions.AttributeError'> ignored
Exception RuntimeError: 'maximum recursion depth exceeded in __subclasscheck__' in <type 'exceptions.AttributeError'> ignored
Exception RuntimeError: 'maximum recursion depth exceeded in __subclasscheck__' in <type 'exceptions.AttributeError'> ignored
Exception RuntimeError: 'maximum recursion depth exceeded in __subclasscheck__' in <type 'exceptions.AttributeError'> ignored
Exception RuntimeError: 'maximum recursion depth exceeded in __subclasscheck__' in <type 'exceptions.AttributeError'> ignored
Exception RuntimeError: 'maximum recursion depth exceeded in __subclasscheck__' in <type 'exceptions.AttributeError'> ignored
Exception RuntimeError: 'maximum recursion depth exceeded in __subclasscheck__' in <type 'exceptions.AttributeError'> ignored
Exception RuntimeError: 'maximum recursion depth exceeded in __subclasscheck__' in <type 'exceptions.AttributeError'> ignored
Exception RuntimeError: 'maximum recursion depth exceeded in __subclasscheck__' in <type 'exceptions.AttributeError'> ignored
Exception RuntimeError: 'maximum recursion depth exceeded in __subclasscheck__' in <type 'exceptions.AttributeError'> ignored
Exception RuntimeError: 'maximum recursion depth exceeded in __subclasscheck__' in <type 'exceptions.AttributeError'> ignored
Exception RuntimeError: 'maximum recursion depth exceeded in __subclasscheck__' in <type 'exceptions.AttributeError'> ignored
Exception RuntimeError: 'maximum recursion depth exceeded in __subclasscheck__' in <type 'exceptions.AttributeError'> ignored
Exception RuntimeError: 'maximum recursion depth exceeded in __subclasscheck__' in <type 'exceptions.AttributeError'> ignored
Exception RuntimeError: 'maximum recursion depth exceeded in __subclasscheck__' in <type 'exceptions.AttributeError'> ignored
Exception RuntimeError: 'maximum recursion depth exceeded in __subclasscheck__' in <type 'exceptions.AttributeError'> ignored
Exception RuntimeError: 'maximum recursion depth exceeded in __subclasscheck__' in <type 'exceptions.AttributeError'> ignored
Exception RuntimeError: 'maximum recursion depth exceeded in __subclasscheck__' in <type 'exceptions.AttributeError'> ignored
Exception RuntimeError: 'maximum recursion depth exceeded in __subclasscheck__' in <type 'exceptions.AttributeError'> ignored
Exception RuntimeError: 'maximum recursion depth exceeded in __subclasscheck__' in <type 'exceptions.AttributeError'> ignored
Exception RuntimeError: 'maximum recursion depth exceeded in __subclasscheck__' in <type 'exceptions.AttributeError'> ignored
Exception RuntimeError: 'maximum recursion depth exceeded while calling a Python object' in <type 'exceptions.AttributeError'> ignored
Exception RuntimeError: 'maximum recursion depth exceeded while calling a Python object' in <type 'exceptions.AttributeError'> ignored
Exception RuntimeError: 'maximum recursion depth exceeded while calling a Python object' in <type 'exceptions.AttributeError'> ignored
Exception RuntimeError: 'maximum recursion depth exceeded while calling a Python object' in <type 'exceptions.AttributeError'> ignored
Exception RuntimeError: 'maximum recursion depth exceeded while calling a Python object' in <type 'exceptions.AttributeError'> ignored
Exception RuntimeError: 'maximum recursion depth exceeded while calling a Python object' in <type 'exceptions.AttributeError'> ignored
Exception RuntimeError: 'maximum recursion depth exceeded in __subclasscheck__' in <type 'exceptions.AttributeError'> ignored
Exception RuntimeError: 'maximum recursion depth exceeded in __subclasscheck__' in <type 'exceptions.AttributeError'> ignored
Exception RuntimeError: 'maximum recursion depth exceeded in __subclasscheck__' in <type 'exceptions.AttributeError'> ignored
Exception RuntimeError: 'maximum recursion depth exceeded in __subclasscheck__' in <type 'exceptions.AttributeError'> ignored
Exception RuntimeError: 'maximum recursion depth exceeded in __subclasscheck__' in <type 'exceptions.AttributeError'> ignored
Exception RuntimeError: 'maximum recursion depth exceeded in __subclasscheck__' in <type 'exceptions.AttributeError'> ignored
Exception RuntimeError: 'maximum recursion depth exceeded in __subclasscheck__' in <type 'exceptions.AttributeError'> ignored
Exception RuntimeError: 'maximum recursion depth exceeded in __subclasscheck__' in <type 'exceptions.AttributeError'> ignored
Exception RuntimeError: 'maximum recursion depth exceeded in __subclasscheck__' in <type 'exceptions.AttributeError'> ignored
Exception RuntimeError: 'maximum recursion depth exceeded in __subclasscheck__' in <type 'exceptions.AttributeError'> ignored
Exception RuntimeError: 'maximum recursion depth exceeded in __subclasscheck__' in <type 'exceptions.AttributeError'> ignored
Exception RuntimeError: 'maximum recursion depth exceeded in __subclasscheck__' in <type 'exceptions.AttributeError'> ignored
Welcome to Scapy (2.3.3)
>>

now I can still use scapy to send tcp packets but I am getting checksum error. So I was wondering if that checksum error was related to the above error?


问:
Graph to bipartite graph by removing edges (not more than edges/2) - algorithm?
so lets say we're given a graph and you're allowed to remove edges (not more than (original graph's edges)/2) until it's a bipartite graph.

Lets say we're given:

```<code>E={ (4, 1),( 1 ,2), (2 ,3),( 7, 2),( 1 ,5),( 8 ,4), (5 ,8),( 8, 9)}
</code>```

and set of vertices:

```<code>V= { 1,2,3,4,5,6,7,8}
</code>```

How one should solve this problem ? Is there any kind of algorithm that does this? Any kind of explanation would be appreciated.

答:
Pick an arbitrary node as the first member of set A. If there is any node linked to it, pick one as the first member of set B. If not, pick any other node as the first member of set B.

Now you have two sets of nodes, A and B. Repeatedly pick a node not in either set. Count the number of edges linking that node to nodes in A and B. If there are more edges linking it to set A, erase the edges linking it to nodes in set B and put it in set B. Otherwise erase the edges linking it to nodes in set A and put it in set A. Note that you erase no more than half the edges linked to that node.

Body:
so lets say we're given a graph and you're allowed to remove edges (not more than (original graph's edges)/2) until it's a bipartite graph.

Lets say we're given:

E={ (4, 1),( 1 ,2), (2 ,3),( 7, 2),( 1 ,5),( 8 ,4), (5 ,8),( 8, 9)}

and set of vertices:

V= { 1,2,3,4,5,6,7,8}

How one should solve this problem ? Is there any kind of algorithm that does this? Any kind of explanation would be appreciated.


问:
How to continue code on next line (code too long)
How do I continue code (record insertion) on the next line?  In the example below I tried using underscore to end a line, then & to begin the next due to suggestions online, but it still doesn't compile.  Any thoughts?

Code Line:

```<code>CurrentDb.Execute "INSERT INTO AIP&BOP (PlanTitle, FileLocation, YearsofData, AnnualImprovedCML, AIP1, AIP1BOP1, AIP2, AIP1BOP2, AIP3, AIP1BOP3, AIP4, AIP1BOP4, AIP5, AIP1BOP5, AIP6, AIP1BOP6, AIP7, AIP1BOP7, AIP8, AIP1BOP8, AIP9, AIP1BOP9, AIP10, AIP1BOP10, AIP11, AIP1BOP11, AIP12, AIP1BOP12, AIP13, AIP1BOP13, AIP14, AIP1BOP14, AIP15, AIP1BOP15, AIP16, AIP1BOP16, AIP17, AIP1BOP17, AIP18, AIP1BOP18, AIP19, AIP1BOP19, AIP20, AIP1BOP20, AIP21, AIP1BOP21, AIP22, AIP1BOP22, AIP23, AIP1BOP23, AIP24, AIP1BOP24) Values ('" & RWPSheetvalues(71) & "', '" & RWPSheetvalues(72) & "', '" & RWPSheetvalues(73) & "', '" & RWPSheetvalues(74) & "','" & RWPSheetvalues(1) & "','" & RWPSheetvalues(2) & "', '" & RWPSheetvalues(3) & "', '" & RWPSheetvalues(4) & "','" & RWPSheetvalues(5) & "','" & RWPSheetvalues(6) & "', '" & RWPSheetvalues(7) & "', '" & RWPSheetvalues(8) & "','" & RWPSheetvalues(9) & "', _
& '" & RWPSheetvalues(10) & "', '" & RWPSheetvalues(11) & "', '" & RWPSheetvalues(12) & "','" & RWPSheetvalues(13) & "','" & RWPSheetvalues(14) & "', '" & RWPSheetvalues(15) & "', '" & RWPSheetvalues(16) & "','" & RWPSheetvalues(17) & "','" & RWPSheetvalues(18) & "', '" & RWPSheetvalues(19) & "', '" & RWPSheetvalues(20) & "','" & RWPSheetvalues(21) & "','" & RWPSheetvalues(22) & "', '" & RWPSheetvalues(23) & "', '" & RWPSheetvalues(24) & "','" & RWPSheetvalues(25) & "','" & RWPSheetvalues(26) & "', '" & RWPSheetvalues(27) & "', '" & RWPSheetvalues(28) & "','" & RWPSheetvalues(29) & "','" & RWPSheetvalues(30) & "', '" & RWPSheetvalues(31) & "', '" & RWPSheetvalues(32) & "','" & RWPSheetvalues(33) & "','" & RWPSheetvalues(34) & "', '" & RWPSheetvalues(35) & "', '" & RWPSheetvalues(36) & "','" & RWPSheetvalues(37) & "','" & RWPSheetvalues(38) & "', '" & RWPSheetvalues(39) & "', '" & RWPSheetvalues(40) & "','" & RWPSheetvalues(41) & "', _
& '" & RWPSheetvalues(42) & "', '" & RWPSheetvalues(43) & "', '" & RWPSheetvalues(44) & "','" & RWPSheetvalues(45) & "','" & RWPSheetvalues(46) & "', '" & RWPSheetvalues(47) & "', '" & RWPSheetvalues(48) & "','" & RWPSheetvalues(49) & "','" & RWPSheetvalues(50) & "', '" & RWPSheetvalues(51) & "', '" & RWPSheetvalues(52) & "','" & RWPSheetvalues(53) & "','" & RWPSheetvalues(54) & "', '" & RWPSheetvalues(55) & "', '" & RWPSheetvalues(56) & "','" & RWPSheetvalues(57) & "','" & RWPSheetvalues(58) & "', '" & RWPSheetvalues(59) & "', '" & RWPSheetvalues(60) & "','" & RWPSheetvalues(61) & "','" & RWPSheetvalues(62) & "', '" & RWPSheetvalues(63) & "', '" & RWPSheetvalues(64) & "','" & RWPSheetvalues(65) & "','" & RWPSheetvalues(66) & "', '" & RWPSheetvalues(67) & "', '" & RWPSheetvalues(68) & "','" & RWPSheetvalues(69) & "','" & RWPSheetvalues(70) & "')"
</code>```

答: You can insert it one by one using loop either create nested array with records pass it to a function which insert it one by one using loop.</p>

Body:
How do I continue code (record insertion) on the next line?  In the example below I tried using underscore to end a line, then & to begin the next due to suggestions online, but it still doesn't compile.  Any thoughts?

Code Line:

CurrentDb.Execute "INSERT INTO AIP&BOP (PlanTitle, FileLocation, YearsofData, AnnualImprovedCML, AIP1, AIP1BOP1, AIP2, AIP1BOP2, AIP3, AIP1BOP3, AIP4, AIP1BOP4, AIP5, AIP1BOP5, AIP6, AIP1BOP6, AIP7, AIP1BOP7, AIP8, AIP1BOP8, AIP9, AIP1BOP9, AIP10, AIP1BOP10, AIP11, AIP1BOP11, AIP12, AIP1BOP12, AIP13, AIP1BOP13, AIP14, AIP1BOP14, AIP15, AIP1BOP15, AIP16, AIP1BOP16, AIP17, AIP1BOP17, AIP18, AIP1BOP18, AIP19, AIP1BOP19, AIP20, AIP1BOP20, AIP21, AIP1BOP21, AIP22, AIP1BOP22, AIP23, AIP1BOP23, AIP24, AIP1BOP24) Values ('" & RWPSheetvalues(71) & "', '" & RWPSheetvalues(72) & "', '" & RWPSheetvalues(73) & "', '" & RWPSheetvalues(74) & "','" & RWPSheetvalues(1) & "','" & RWPSheetvalues(2) & "', '" & RWPSheetvalues(3) & "', '" & RWPSheetvalues(4) & "','" & RWPSheetvalues(5) & "','" & RWPSheetvalues(6) & "', '" & RWPSheetvalues(7) & "', '" & RWPSheetvalues(8) & "','" & RWPSheetvalues(9) & "', _
& '" & RWPSheetvalues(10) & "', '" & RWPSheetvalues(11) & "', '" & RWPSheetvalues(12) & "','" & RWPSheetvalues(13) & "','" & RWPSheetvalues(14) & "', '" & RWPSheetvalues(15) & "', '" & RWPSheetvalues(16) & "','" & RWPSheetvalues(17) & "','" & RWPSheetvalues(18) & "', '" & RWPSheetvalues(19) & "', '" & RWPSheetvalues(20) & "','" & RWPSheetvalues(21) & "','" & RWPSheetvalues(22) & "', '" & RWPSheetvalues(23) & "', '" & RWPSheetvalues(24) & "','" & RWPSheetvalues(25) & "','" & RWPSheetvalues(26) & "', '" & RWPSheetvalues(27) & "', '" & RWPSheetvalues(28) & "','" & RWPSheetvalues(29) & "','" & RWPSheetvalues(30) & "', '" & RWPSheetvalues(31) & "', '" & RWPSheetvalues(32) & "','" & RWPSheetvalues(33) & "','" & RWPSheetvalues(34) & "', '" & RWPSheetvalues(35) & "', '" & RWPSheetvalues(36) & "','" & RWPSheetvalues(37) & "','" & RWPSheetvalues(38) & "', '" & RWPSheetvalues(39) & "', '" & RWPSheetvalues(40) & "','" & RWPSheetvalues(41) & "', _
& '" & RWPSheetvalues(42) & "', '" & RWPSheetvalues(43) & "', '" & RWPSheetvalues(44) & "','" & RWPSheetvalues(45) & "','" & RWPSheetvalues(46) & "', '" & RWPSheetvalues(47) & "', '" & RWPSheetvalues(48) & "','" & RWPSheetvalues(49) & "','" & RWPSheetvalues(50) & "', '" & RWPSheetvalues(51) & "', '" & RWPSheetvalues(52) & "','" & RWPSheetvalues(53) & "','" & RWPSheetvalues(54) & "', '" & RWPSheetvalues(55) & "', '" & RWPSheetvalues(56) & "','" & RWPSheetvalues(57) & "','" & RWPSheetvalues(58) & "', '" & RWPSheetvalues(59) & "', '" & RWPSheetvalues(60) & "','" & RWPSheetvalues(61) & "','" & RWPSheetvalues(62) & "', '" & RWPSheetvalues(63) & "', '" & RWPSheetvalues(64) & "','" & RWPSheetvalues(65) & "','" & RWPSheetvalues(66) & "', '" & RWPSheetvalues(67) & "', '" & RWPSheetvalues(68) & "','" & RWPSheetvalues(69) & "','" & RWPSheetvalues(70) & "')"


问:
How is `tuple.__init__` different from `super().__init__` in a subclass of tuple?
Please see the following code:

```<code>#! /usr/bin/env python3

class MyTupleT(tuple):
    def __init__(self, contents):
        tuple.__init__(contents)
        self.len = len(contents)

class MyTupleS(tuple):
    def __init__(self, contents):
        super().__init__(contents)
        self.len = len(contents)

t = MyTupleT([0, 1, 2])
print(t.len, t)

s = MyTupleS([0, 1, 2])
print(s.len, s)
</code>```

The output is:

```<code>3 (0, 1, 2)
Traceback (most recent call last):
File "tuple_init.py", line 16, in <module>
    s = MyTupleS([0, 1, 2])
File "tuple_init.py", line 10, in __init__
    super().__init__(contents)
TypeError: object.__init__() takes no parameters
</code>```

The docs say  that super() will:

Return a proxy object that delegates method calls to a parent or sibling class of type

IIUC here super() is the same as super(MyTupleS, self). Now the docs further say that

The search order is same as that used by getattr() except that the type itself is skipped. The __mro__ attribute of the type lists the method resolution search order used by both getattr() and super().

Ohkay but then:

```<code>$ MyTupleS.__mro__
(__main__.MyTupleS, tuple, object)
</code>```

So the super() line should first look within tuple to find __init__ and tuple's __init__ can certainly take one parameter (other than self of course) and is what is being called by the explicit tuple.__init__ line. So why doesn't the super().__init__ call work identical to that? Why is it trying to invoke object.__init__ and failing?

IIUC one should only need to explicitly specify the superclass when one is worried that the inheritance hierarchy can change in a "dynamic execution environment" (phrase from the docs) and wants the method of a particular superclass to be called. But this error effectively makes it mandatory for the superclass to be specified. Why?

NOTE: This is different from another similarly titled question.

答:
If you call tuple.__init__ it returns object.__init__ because tuple has no custom __init__ method and only inherits it from object. The first argument for object.__init__ is self and what object.__init__ does is nothing. So when you pass in contents it's interpreted as self and doesn't throw an Exception. However it probably doesn't do what you think it does because tuple.__new__ is responsible for setting up a new tuple instance.

If you use super().__init__ it also resolves to object.__init__ but it already binds the current "self" as first argument. So when you pass contents to this function it's interpreted as additional argument which doesn't exist for object.__init__ and therefore throws that Error.

Body:
Please see the following code:

#! /usr/bin/env python3

class MyTupleT(tuple):
    def __init__(self, contents):
        tuple.__init__(contents)
        self.len = len(contents)

class MyTupleS(tuple):
    def __init__(self, contents):
        super().__init__(contents)
        self.len = len(contents)

t = MyTupleT([0, 1, 2])
print(t.len, t)

s = MyTupleS([0, 1, 2])
print(s.len, s)

The output is:

3 (0, 1, 2)
Traceback (most recent call last):
File "tuple_init.py", line 16, in <module>
    s = MyTupleS([0, 1, 2])
File "tuple_init.py", line 10, in __init__
    super().__init__(contents)
TypeError: object.__init__() takes no parameters

The docs say  that super() will:

Return a proxy object that delegates method calls to a parent or sibling class of type

IIUC here super() is the same as super(MyTupleS, self). Now the docs further say that

The search order is same as that used by getattr() except that the type itself is skipped. The __mro__ attribute of the type lists the method resolution search order used by both getattr() and super().

Ohkay but then:

$ MyTupleS.__mro__
(__main__.MyTupleS, tuple, object)

So the super() line should first look within tuple to find __init__ and tuple's __init__ can certainly take one parameter (other than self of course) and is what is being called by the explicit tuple.__init__ line. So why doesn't the super().__init__ call work identical to that? Why is it trying to invoke object.__init__ and failing?

IIUC one should only need to explicitly specify the superclass when one is worried that the inheritance hierarchy can change in a "dynamic execution environment" (phrase from the docs) and wants the method of a particular superclass to be called. But this error effectively makes it mandatory for the superclass to be specified. Why?

NOTE: This is different from another similarly titled question.


问:
Remove "Translated Meesage Bar" from top
Once Google has finished the translation it shows a bar on top of the website which ruins my website's look! I dont know how to disable it! Guide me please! This is a HTML website.
enter image description here</p>

答:
Adding this code will hide the "revert to original" bar after translation!

```

Body:
Adding this code will hide the "revert to original" bar after translation!

<style>.goog-te-banner-frame.skiptranslate {
    display: none !important;
    }
body {
    top: 0px !important;
    }</style>


问:
Passing an array of structs to a function as a parameter
I know this question has come up a lot of time in stackoverflow and I am posting this question after checking all the questions suggested by stackoverflow when I started this question.

Basically, I want to achieve this. Big picture: Pass an array of structs from c++ dll to a c# application. The catch here is that, the size of the array can only be determined by the c++ dll. Now I only know that getting an array of anything from c++ to c# is possible with the out parameter as a function argument. And yes, I can pass a ref to a c++ function as an out parameter whose size is not known but is initialized to NULL. But I am not sure if this is right or if it will work! And another way is, to get the array of structs as a return value, for which I didn't find any example in c#.

So what I did: Simplified this problem into a c++ problem:

I tried some sample examples to return an array of structs from a function to my main(), from a c++ dll to a test c++ application. --> Works fine. So as a return value, an array of structs works fine. Obviously, because I do not have to initialize my array of structs with the exact size, in the beginning before calling my function to populate the array!

But the catch is, I need to implement it in a way which will be feasible to be received by the c# end! So, as an out parameter to the function, and not as a return value (if anybody knows how to receive an array of structs from c++ dll to c#, please help!).

All the questions in stackoverflow or in google about passing an array of structs to a function have their size determined previously. But in my case, the function will only be able to decide the size. I do not know the size of the array prior to calling the function. And, I am really trying to complete the tasks in a single function call and hence, I cannot have 2 APIs, one for computing the size and one for getting the array. It would be a repetitive task since the same functionality has to be executed twice, once to only get the size and another time to get the actual array, which is not feasible!

I have a sample code. If anyone can help, it would be really appreciated.

```<code>// structsEx.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"

#include <iostream>
#include <conio.h>
#include <vector>
#include <string>

using namespace std;
using std::vector;
using std::string;

struct example
{
    char* name; // char* or const char*. But not sure if I can have an
                // std::string.
    int age;
    char* company;
};

void passStructsRef(struct example** ex)  // Again, not sure if I can have
                                          // std::array or std::vector since
                                          // this will be the API I expose
                                          // to C# side.
{
    vector<string> names = {"AAA", "BBB", "CCC", "DDD", "EEE"};
    vector<int> ages = {25, 26, 27, 28, 29, 30};
    vector<string> companies = { "AAA1", "BBB2", "CCC3", "DDD4", "EEE5" };

    *ex = new example[5];  // I think this is a problem. It only initializes
                           // the first element and hence, I get only the
                           // first item.
    for (int i = 0; i < 5; i++)
    {
        ex[i] = new example();  // Is this right? Not sure..
        ex[i]->age = ages[i];
        ex[i]->name = _strdup(names[i].c_str());
        ex[i]->company = _strdup(companies[i].c_str());
    }

    cout << "2 in function" << endl;
    for (int i = 0; i < 5; i++)
    {
        cout << ex[i]->name << "\t" << ex[i]->age << "\t" << ex[i]->company << endl;
    }
}

int main()
{
    example ex;
    ex.age = 30;
    ex.name = "AEIOU";
    ex.company = "ABCDE";

    cout << "1" << endl;
    cout << ex.name << "\t" << ex.age << "\t" << ex.company << endl;

    cout << "2" << endl;
    example *ex2 = nullptr;
    passStructsRef(&ex2);

    for (int i = 0; i < 5; i++)
    {
        cout << ex2[i].name << "\t" << ex2[i].age << "\t" << ex2[i].company << endl;
    }

    _getch();
    return 0;
}
</code>```

Following the comment, I think I have to give a bit of comments on my code. I am not sure if I can use STL arrays or vectors or std::string in my code which I am going to expose to C# application. Which is why I am using new operator here. Next question which might arise is where is delete? Well, I have to have another API calling delete to delete the memory allocated for the structure. Which will be called by my C# application when it has successfully received all the data I have returned and processed them. That is not a problem. But sending data to C# is a problem which has led me to write this sample C++ test application.

There is no big syntax or any special code to write to send data to C#. If it works in C++, it has to work in C#, if the parameters and APIs are exported properly. Which is why I am trying to get my C++ side perfect.

Hope this helps. Thanks a lot in advance.

答:
There’re actually two questions here.

One is how to return array of structures.

The classical way is this:

C++:

```<code>int getStructsLength();
int getStructs( int bufferLength, struct example* buffer ); // Returns the count of structures actually written
</code>```

C#

```<code>static extern int getStructsLength();
static extern int getStructs( int bufferLength, [Out, MarshalAs( UnmanagedType.LPArray, SizeParamIndex = 0 )] example[] buffer );
</code>```

Another one is how to return strings in these structures.

If you don’t have too much data or too many calls and running on Windows, one simple way is change const char* into BSTR, and adjust C++ code accordingly. These are Unicode strings every language knows how to properly allocate/deallocate across DLL boundaries; the only downside is they’re relatively slow.

Another method, more complex, declare the following field in your C# structure:

```<code> [MarshalAs(UnmanagedType.LPStr)] public string name;
</code>```

In C++, replace strdup with CoTaskMemAlloc and strcpy calls (don’t forget about terminating '\0' when allocating). This way the interop will free memory used by these strings after making .NET strings from the pointers.

Another way, most performant, is do manual marshalling, i.e. declare the following fields in your C# structure:

```<code> public IntPtr name;
</code>```

In C++, change the code to just write c_str() there without making copies.

In C#, use Marshal.PtrToStringAnsi to convert them to .NET strings. But beware if your C++ will change any of these strings before you’re done with your custom marshalling, your app will crash.

Body:
I know this question has come up a lot of time in stackoverflow and I am posting this question after checking all the questions suggested by stackoverflow when I started this question.

Basically, I want to achieve this. Big picture: Pass an array of structs from c++ dll to a c# application. The catch here is that, the size of the array can only be determined by the c++ dll. Now I only know that getting an array of anything from c++ to c# is possible with the out parameter as a function argument. And yes, I can pass a ref to a c++ function as an out parameter whose size is not known but is initialized to NULL. But I am not sure if this is right or if it will work! And another way is, to get the array of structs as a return value, for which I didn't find any example in c#.

So what I did: Simplified this problem into a c++ problem:

I tried some sample examples to return an array of structs from a function to my main(), from a c++ dll to a test c++ application. --> Works fine. So as a return value, an array of structs works fine. Obviously, because I do not have to initialize my array of structs with the exact size, in the beginning before calling my function to populate the array!

But the catch is, I need to implement it in a way which will be feasible to be received by the c# end! So, as an out parameter to the function, and not as a return value (if anybody knows how to receive an array of structs from c++ dll to c#, please help!).

All the questions in stackoverflow or in google about passing an array of structs to a function have their size determined previously. But in my case, the function will only be able to decide the size. I do not know the size of the array prior to calling the function. And, I am really trying to complete the tasks in a single function call and hence, I cannot have 2 APIs, one for computing the size and one for getting the array. It would be a repetitive task since the same functionality has to be executed twice, once to only get the size and another time to get the actual array, which is not feasible!

I have a sample code. If anyone can help, it would be really appreciated.

// structsEx.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"

#include <iostream>
#include <conio.h>
#include <vector>
#include <string>

using namespace std;
using std::vector;
using std::string;

struct example
{
    char* name; // char* or const char*. But not sure if I can have an
                // std::string.
    int age;
    char* company;
};

void passStructsRef(struct example** ex)  // Again, not sure if I can have
                                          // std::array or std::vector since
                                          // this will be the API I expose
                                          // to C# side.
{
    vector<string> names = {"AAA", "BBB", "CCC", "DDD", "EEE"};
    vector<int> ages = {25, 26, 27, 28, 29, 30};
    vector<string> companies = { "AAA1", "BBB2", "CCC3", "DDD4", "EEE5" };

    *ex = new example[5];  // I think this is a problem. It only initializes
                           // the first element and hence, I get only the
                           // first item.
    for (int i = 0; i < 5; i++)
    {
        ex[i] = new example();  // Is this right? Not sure..
        ex[i]->age = ages[i];
        ex[i]->name = _strdup(names[i].c_str());
        ex[i]->company = _strdup(companies[i].c_str());
    }

    cout << "2 in function" << endl;
    for (int i = 0; i < 5; i++)
    {
        cout << ex[i]->name << "\t" << ex[i]->age << "\t" << ex[i]->company << endl;
    }
}

int main()
{
    example ex;
    ex.age = 30;
    ex.name = "AEIOU";
    ex.company = "ABCDE";

    cout << "1" << endl;
    cout << ex.name << "\t" << ex.age << "\t" << ex.company << endl;

    cout << "2" << endl;
    example *ex2 = nullptr;
    passStructsRef(&ex2);

    for (int i = 0; i < 5; i++)
    {
        cout << ex2[i].name << "\t" << ex2[i].age << "\t" << ex2[i].company << endl;
    }

    _getch();
    return 0;
}

Following the comment, I think I have to give a bit of comments on my code. I am not sure if I can use STL arrays or vectors or std::string in my code which I am going to expose to C# application. Which is why I am using new operator here. Next question which might arise is where is delete? Well, I have to have another API calling delete to delete the memory allocated for the structure. Which will be called by my C# application when it has successfully received all the data I have returned and processed them. That is not a problem. But sending data to C# is a problem which has led me to write this sample C++ test application.

There is no big syntax or any special code to write to send data to C#. If it works in C++, it has to work in C#, if the parameters and APIs are exported properly. Which is why I am trying to get my C++ side perfect.

Hope this helps. Thanks a lot in advance.

Body:
There’re actually two questions here.

One is how to return array of structures.

The classical way is this:

C++:

int getStructsLength();
int getStructs( int bufferLength, struct example* buffer ); // Returns the count of structures actually written

C#

static extern int getStructsLength();
static extern int getStructs( int bufferLength, [Out, MarshalAs( UnmanagedType.LPArray, SizeParamIndex = 0 )] example[] buffer );

Another one is how to return strings in these structures.

If you don’t have too much data or too many calls and running on Windows, one simple way is change const char* into BSTR, and adjust C++ code accordingly. These are Unicode strings every language knows how to properly allocate/deallocate across DLL boundaries; the only downside is they’re relatively slow.

Another method, more complex, declare the following field in your C# structure:

 [MarshalAs(UnmanagedType.LPStr)] public string name;

In C++, replace strdup with CoTaskMemAlloc and strcpy calls (don’t forget about terminating '\0' when allocating). This way the interop will free memory used by these strings after making .NET strings from the pointers.

Another way, most performant, is do manual marshalling, i.e. declare the following fields in your C# structure:

 public IntPtr name;

In C++, change the code to just write c_str() there without making copies.

In C#, use Marshal.PtrToStringAnsi to convert them to .NET strings. But beware if your C++ will change any of these strings before you’re done with your custom marshalling, your app will crash.


问:
convnet suddenly drop accuracy
I was trying to train an emotion recognition model on the fer2013 dataset using the architecture proposed in this paper

The paper uses different dataset than mine so I did some modifications on on the stride and filter size.
After a couple hours of training, accuracy on both training and test set suddenly drops.

After that the accuracy just stay around 0.1-0.2 for both set, never improve anymore.
Does anybody know about this phenomenon?

答:
In any neural network training, if both accuracies i.e. training and validation improves at first and then starts decreasing, it is a sign that your network is failing to converge. More appropriately, your optimizer has started overshooting.

One most likely reason for this could be high learning rate. Reduce your learning rate and then check your example again. Also, in your linked paper, (at least in first glimpse), I couldn't see learning rate mentioned. Since your data is different from the paper's, same learning rate might not work as well.

Title: convnet suddenly drop accuracy


问:
Any idea why my functions are not working?
Trying to create a simple password generator but my functions arent giving me the intended result or outcome i want. I.e. not adding up to expand the empty list. Should i be changing anything?</p>

```<code>import random

def passstrength():
    return input("Please state how strong you have the password to be? (1 = strongest, 2 = medium, 3 = weakest): ")

passstrength = passstrength()

list1 = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','q','r','s','t','u','v','x','y','z']

list2 = ['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','Q','R','S','T','U','V','X','Y','Z']

list3 = [1,2,3,4,5,6,7,8,9,0]

list4 = ["@","$","%","&"]

r = []

def getpass(x):
    return random.sample(x,2)

def mergepass(first,second,third):
    if passstrength == 1:
        a = getpass(first)
        b = getpass(second)
        c = getpass(third)
        r = (a + b + c)
        return r
    elif passstrength == 2:
        a = getpass(first)
        b = getpass(second)
        r = (a + b)
        return r
    else:
        a = getpass(first)
        r = (a)
        return r

print (mergepass(list1,list2,list3))
</code>```

答:
passstrength is passed as a string so when you compare it to int it fails.

You can fix it by doing:

```<code>passstrength = int(passstrength())
</code>```

Body:
Trying to create a simple password generator but my functions arent giving me the intended result or outcome i want. I.e. not adding up to expand the empty list. Should i be changing anything?

import random

def passstrength():
    return input("Please state how strong you have the password to be? (1 = strongest, 2 = medium, 3 = weakest): ")

passstrength = passstrength()

list1 = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','q','r','s','t','u','v','x','y','z']

list2 = ['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','Q','R','S','T','U','V','X','Y','Z']

list3 = [1,2,3,4,5,6,7,8,9,0]

list4 = ["@","$","%","&"]

r = []

def getpass(x):
    return random.sample(x,2)

def mergepass(first,second,third):
    if passstrength == 1:
        a = getpass(first)
        b = getpass(second)
        c = getpass(third)
        r = (a + b + c)
        return r
    elif passstrength == 2:
        a = getpass(first)
        b = getpass(second)
        r = (a + b)
        return r
    else:
        a = getpass(first)
        r = (a)
        return r

print (mergepass(list1,list2,list3))

Body:
passstrength is passed as a string so when you compare it to int it fails.

You can fix it by doing:

passstrength = int(passstrength())


问:
AVL tree not balancing correctly
I have an assignment to write a self balancing binary search tree. I decided to use an AVL tree as it is what we have discussed in class. Then with the given input of { 3, 5, 61, 9, 32, 7, 1, 45, 26, 6} I'm expecting an output of:

```<code>               7
         6-----|-----32
    3----|      9----|----45
1---|           |---26    |---61
</code>```

That is, unless I have grossly misunderstood and thus miscalculated what an AVL tree is supposed to do when it balances itself. The output I'm getting is quite different:

```<code>              5
        3-----|-----61
   1----|      9----|
           7---|---32
        6--|    26--|--45
</code>```

Again, unless I am completely wrong, that tree is not balanced. The function I'm using to set up the tree is defined as such:

```<code>node* insertKeyAVL(node* n, int e)
{
    int cmpVal;

    if (n == NULL){
            n = create_node();
            n->data = e;
    } else if (e < n->data) {
            if (n->left == NULL){
                    n->left = create_node();
                    n->left->data = e;
                    n->left->parent = n;
            } else {
                    n->left = insertKeyAVL(n->left, e);
            }

            cmpVal = height(n->left) - height(n->right);

    } else {
            if (n->right == NULL){
                    n->right = create_node();
                    n->right->data = e;
                    n->right->parent = n;
            } else {
                    n->right = insertKeyAVL(n->right, e);
            }

            cmpVal = height(n->right) - height(n->left);
    }

    if (cmpVal > 2){
            if (n->left){
                    if (e < n->left->data)
                            n = rotate_left(n);
                    else
                            n = rotate_right_left(n);
            } else if (n->right){
                    if (e > n->right->data)
                            n = rotate_right(n);
                    else
                            n = rotate_left_right(n);
            }
    }

    n->height = max(height(n->left), height(n->right)) + 1;

    return n;
}
</code>```

The structure I'm using to store all the data is defined as such:

```<code>typedef struct node
{

    struct node *parent;
    struct node*  left;
    struct node*  right;

    int data;

    int height;
} node;
</code>```

The functions rotate_left_right and rotate_right_left are basic functions that rotate the direction of the first post-fix then the second post-fix, and are both reliant on rotate_left and rotate_right for their respective direction. rotate left is defined as such:

```<code>node* rotate_left(node* n)
{
    node* tmp = n->left;
    n->left = tmp->right;
    tmp->right = n;

    tmp->parent = n->parent;
    n->parent = tmp;

    n->height = max(height(n->left), height(n->right)) + 1;
    tmp->height = max(height(tmp->left), n->height) + 1;

    return tmp;
}
</code>```

rotate_right is similar but adjusted for a rotation right.

I'm wondering where this code messes up so that it doesn't produce the desired output.

答: when you add 26 in your expected result cmpval for 5 become 2 which is not valid that's why code re-execute and give result as yours.</p>

Title: AVL tree not balancing correctly

Body:
I have an assignment to write a self balancing binary search tree. I decided to use an AVL tree as it is what we have discussed in class. Then with the given input of { 3, 5, 61, 9, 32, 7, 1, 45, 26, 6} I'm expecting an output of:

               7
         6-----|-----32
    3----|      9----|----45
1---|           |---26    |---61

That is, unless I have grossly misunderstood and thus miscalculated what an AVL tree is supposed to do when it balances itself. The output I'm getting is quite different:

              5
        3-----|-----61
   1----|      9----|
           7---|---32
        6--|    26--|--45

Again, unless I am completely wrong, that tree is not balanced. The function I'm using to set up the tree is defined as such:

node* insertKeyAVL(node* n, int e)
{
    int cmpVal;

    if (n == NULL){
            n = create_node();
            n->data = e;
    } else if (e < n->data) {
            if (n->left == NULL){
                    n->left = create_node();
                    n->left->data = e;
                    n->left->parent = n;
            } else {
                    n->left = insertKeyAVL(n->left, e);
            }

            cmpVal = height(n->left) - height(n->right);

    } else {
            if (n->right == NULL){
                    n->right = create_node();
                    n->right->data = e;
                    n->right->parent = n;
            } else {
                    n->right = insertKeyAVL(n->right, e);
            }

            cmpVal = height(n->right) - height(n->left);
    }

    if (cmpVal > 2){
            if (n->left){
                    if (e < n->left->data)
                            n = rotate_left(n);
                    else
                            n = rotate_right_left(n);
            } else if (n->right){
                    if (e > n->right->data)
                            n = rotate_right(n);
                    else
                            n = rotate_left_right(n);
            }
    }

    n->height = max(height(n->left), height(n->right)) + 1;

    return n;
}

The structure I'm using to store all the data is defined as such:

typedef struct node
{

    struct node *parent;
    struct node*  left;
    struct node*  right;

    int data;

    int height;
} node;

The functions rotate_left_right and rotate_right_left are basic functions that rotate the direction of the first post-fix then the second post-fix, and are both reliant on rotate_left and rotate_right for their respective direction. rotate left is defined as such:

node* rotate_left(node* n)
{
    node* tmp = n->left;
    n->left = tmp->right;
    tmp->right = n;

    tmp->parent = n->parent;
    n->parent = tmp;

    n->height = max(height(n->left), height(n->right)) + 1;
    tmp->height = max(height(tmp->left), n->height) + 1;

    return tmp;
}

rotate_right is similar but adjusted for a rotation right.

I'm wondering where this code messes up so that it doesn't produce the desired output.


问:
Databinding a ObservableCollection<T> in MVVM
I have a ListView with a Datatemplate that holds a list of Movies. It is databinded to a ObservableColection but whenever I edit the Movie.Name it does not update the ListView even though "Name" is called in my PropertyChangedEventHandler is called with "Name".

I add 2 "Movie"s to my collection in my initializer and these are shown correct (Klovn the Movie, Taken)

So when I click Edit it should change the text of the selected movie and change the Name of it to "Test" and is is changed but the change is not shown in the ListView but if I output Collection with a foreach then Name is Test.

View.xaml

<Window x:Class="MovieDB3.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525">
    <DockPanel>
        <Menu DockPanel.Dock="Top">
            <MenuItem Header="File">
                <MenuItem Header="Edit" Click="MenuEditClick"/>
            </MenuItem>
        </Menu>
        <Grid DockPanel.Dock="Top">
            <Grid.ColumnDefinitions>
                <ColumnDefinition/>
                <ColumnDefinition/>
            </Grid.ColumnDefinitions>
            <Grid.RowDefinitions>
                <RowDefinition/>
            </Grid.RowDefinitions>
            <ListView VerticalAlignment="Stretch" Name="ListViewMovies" ItemsSource="{Binding Path=Collection}" IsSynchronizedWithCurrentItem="True" >
                <ListView.ItemTemplate>
                    <DataTemplate>
                        <WrapPanel>
                            <TextBlock Text="{Binding Path=Name}"/>
                        </WrapPanel>
                    </DataTemplate>
                </ListView.ItemTemplate>
            </ListView>
        </Grid>
    </DockPanel>
</Window>
```

<p>View.cs</p>

```using System;
using System.Windows;
using MovieDB3.Models;
using MovieDB3.ViewModels;

namespace MovieDB3
{
    ///
    /// Interaction logic for MainWindow.xaml
    ///
    public partial class MainWindow : Window
    {
        private MainViewModel MVM;
        public MainWindow()
        {
            InitializeComponent();
            MVM = new MainViewModel();
            DataContext = MVM;
        }

        private void MenuEditClick(object sender, RoutedEventArgs e)
        {
            MVM.setMovieName((Movie)ListViewMovies.SelectedItem, "test");
        }
    }
}
```

<p>The ViewModel</p>

```using System;
using System.ComponentModel;
using MovieDB3.Models;
using System.Collections.ObjectModel;

namespace MovieDB3.ViewModels
{
    class MainViewModel : INotifyPropertyChanged
    {
        public ObservableCollection<Movie> Collection {get; set;}

        public MainViewModel()
        {
            Collection = new ObservableCollection<Movie>();

            //Test kode
            Movie movie = new Movie();
            movie.Name = "Klovn The Movie";
            Collection.Add(movie);
            movie = new Movie();
            movie.Name = "Taken";
            Collection.Add(movie);
        }

        public void setMovieName(Movie movie, string newName)
        {
            //movie.Name = newName;
            Console.WriteLine("CurrentName: " + movie.Name);
            int i = Collection.IndexOf(movie);
            Collection[i].Name = newName;
            Console.WriteLine("NewName: " + movie.Name);
            NotifyPropertyChanged("Name");
        }

        public void setMovieName(string currentName, string newName)
        {
            foreach (Movie movie in Collection)
            {
                if (movie.Name.Equals(currentName))
                {
                    movie.Name = newName;
                    NotifyPropertyChanged("Name");
                    return;
                }
            }
        }

        //public string MovieName
        //{
        //    set
        //    {

        //        NotifyPropertyChanged("MovieName");
        //    }
        //}

        public event PropertyChangedEventHandler PropertyChanged;

        private void NotifyPropertyChanged(String info)
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(info));
            }
        }
    }
}
```

<p>Movie.cs</p>

```using System;

namespace MovieDB3.Models
{
    class Movie
    {
        public string Name { get; set; }
        public int Id { get; set; }
        public double Rating { get; set; }
        public DateTime Release { get; set; }
        public TimeSpan Runtime { get; set; }
        public String Trailer { get; set; }
    }
}
```

答:
INotifyPropertyChanged needs to be Implemented in your Movie class, also avoid raising the event manually.
(Right now you are telling the View that the ViewModel's property "Name" changed, which does not exist)

What your class might look like:

```<code>public class Movie : INotifyPropertyChanged
{
    private string _name = String.Empty;
    public string Name
    {
        get { return _name; }
        set
        {
            if (_name != value)
            {
                _name = value;
                NotifyPropertyChanged("Name");
            }
        }
    }

    //...All the other properties (the same way)...

    public event PropertyChangedEventHandler PropertyChanged;

    public void NotifyPropertyChanged(string propertyName)
    {
        if (PropertyChanged != null)
        {
            PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }
    }
}
</code>```

What your changing method is reduced to:

```<code>    public void setMovieName(Movie movie, string newName)
    {
        Console.WriteLine("CurrentName: " + movie.Name);
        movie.Name = newName; //The notification is now raised automatically in the setter of the property in the movie class
        Console.WriteLine("NewName: " + movie.Name);
    }
</code>```

Body:
I have a ListView with a Datatemplate that holds a list of Movies. It is databinded to a ObservableColection but whenever I edit the Movie.Name it does not update the ListView even though "Name" is called in my PropertyChangedEventHandler is called with "Name".

I add 2 "Movie"s to my collection in my initializer and these are shown correct (Klovn the Movie, Taken)

So when I click Edit it should change the text of the selected movie and change the Name of it to "Test" and is is changed but the change is not shown in the ListView but if I output Collection with a foreach then Name is Test.

View.xaml

<Window x:Class="MovieDB3.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525">
    <DockPanel>
        <Menu DockPanel.Dock="Top">
            <MenuItem Header="File">
                <MenuItem Header="Edit" Click="MenuEditClick"/>
            </MenuItem>
        </Menu>
        <Grid DockPanel.Dock="Top">
            <Grid.ColumnDefinitions>
                <ColumnDefinition/>
                <ColumnDefinition/>
            </Grid.ColumnDefinitions>
            <Grid.RowDefinitions>
                <RowDefinition/>
            </Grid.RowDefinitions>
            <ListView VerticalAlignment="Stretch" Name="ListViewMovies" ItemsSource="{Binding Path=Collection}" IsSynchronizedWithCurrentItem="True" >
                <ListView.ItemTemplate>
                    <DataTemplate>
                        <WrapPanel>
                            <TextBlock Text="{Binding Path=Name}"/>
                        </WrapPanel>
                    </DataTemplate>
                </ListView.ItemTemplate>
            </ListView>
        </Grid>
    </DockPanel>
</Window>

View.cs

using System;
using System.Windows;
using MovieDB3.Models;
using MovieDB3.ViewModels;

namespace MovieDB3
{
    ///
    /// Interaction logic for MainWindow.xaml
    ///
    public partial class MainWindow : Window
    {
        private MainViewModel MVM;
        public MainWindow()
        {
            InitializeComponent();
            MVM = new MainViewModel();
            DataContext = MVM;
        }

        private void MenuEditClick(object sender, RoutedEventArgs e)
        {
            MVM.setMovieName((Movie)ListViewMovies.SelectedItem, "test");
        }
    }
}

The ViewModel

using System;
using System.ComponentModel;
using MovieDB3.Models;
using System.Collections.ObjectModel;

namespace MovieDB3.ViewModels
{
    class MainViewModel : INotifyPropertyChanged
    {
        public ObservableCollection<Movie> Collection {get; set;}

        public MainViewModel()
        {
            Collection = new ObservableCollection<Movie>();

            //Test kode
            Movie movie = new Movie();
            movie.Name = "Klovn The Movie";
            Collection.Add(movie);
            movie = new Movie();
            movie.Name = "Taken";
            Collection.Add(movie);
        }

        public void setMovieName(Movie movie, string newName)
        {
            //movie.Name = newName;
            Console.WriteLine("CurrentName: " + movie.Name);
            int i = Collection.IndexOf(movie);
            Collection[i].Name = newName;
            Console.WriteLine("NewName: " + movie.Name);
            NotifyPropertyChanged("Name");
        }

        public void setMovieName(string currentName, string newName)
        {
            foreach (Movie movie in Collection)
            {
                if (movie.Name.Equals(currentName))
                {
                    movie.Name = newName;
                    NotifyPropertyChanged("Name");
                    return;
                }
            }
        }

        //public string MovieName
        //{
        //    set
        //    {

        //        NotifyPropertyChanged("MovieName");
        //    }
        //}

        public event PropertyChangedEventHandler PropertyChanged;

        private void NotifyPropertyChanged(String info)
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(info));
            }
        }
    }
}

Movie.cs

using System;

namespace MovieDB3.Models
{
    class Movie
    {
        public string Name { get; set; }
        public int Id { get; set; }
        public double Rating { get; set; }
        public DateTime Release { get; set; }
        public TimeSpan Runtime { get; set; }
        public String Trailer { get; set; }
    }
}

Body:
INotifyPropertyChanged needs to be Implemented in your Movie class, also avoid raising the event manually.
(Right now you are telling the View that the ViewModel's property "Name" changed, which does not exist)

What your class might look like:

public class Movie : INotifyPropertyChanged
{
    private string _name = String.Empty;
    public string Name
    {
        get { return _name; }
        set
        {
            if (_name != value)
            {
                _name = value;
                NotifyPropertyChanged("Name");
            }
        }
    }

    //...All the other properties (the same way)...

    public event PropertyChangedEventHandler PropertyChanged;

    public void NotifyPropertyChanged(string propertyName)
    {
        if (PropertyChanged != null)
        {
            PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }
    }
}

What your changing method is reduced to:

    public void setMovieName(Movie movie, string newName)
    {
        Console.WriteLine("CurrentName: " + movie.Name);
        movie.Name = newName; //The notification is now raised automatically in the setter of the property in the movie class
        Console.WriteLine("NewName: " + movie.Name);
    }

ContentLicense: CC BY-SA 2.5


问:
Node js App stoping When Console is closed
Am new to node , created my first express based app and deployed in my development server.

```<code>node app.js
</code>```

given above command no errors and working properly , after logoff my putty application seems to be stopped ,how can i solve this issue .

Is there any other way for running node apps.

答:
Run NodeJS as a Service on Ubuntu

With Node you can write very fast JavaScript programs serverside. It's pretty easy to install Node, code your program, and run it. But > how do you make it run nicely in the background like a true server

```<code>Go to `/etc/init/`
$ sudo nano yourapp.conf`
Paste **script.conf**
$ sudo start yourapp`
</code>```

And when you wanna kill the process $ sudo stop yourapp

```<code>  description "node.js server"
  author      "your name"

  # used to be: start on startup
  # until we found some mounts weren't ready yet while booting

  start on started mountall
  stop on shutdown

  # automatically respawn

  respawn
  respawn limit 99 5

 script

        export HOME="/root"
        exec /usr/bin/nodejs /path/to/yourapp.js >> /var/log/node.log 2>&1

 end script

 post-start script

   # optionally put a script here that will notifiy you node has (re)started
   # /root/bin/hoptoad.sh "node.js has started!"

 end script
</code>```

for further reference https://gist.github.com/jobsamuel/6d6095d52228461f3c53

Body:
Am new to node , created my first express based app and deployed in my development server.

node app.js

given above command no errors and working properly , after logoff my putty application seems to be stopped ,how can i solve this issue .

Is there any other way for running node apps.

Body:
Run NodeJS as a Service on Ubuntu

With Node you can write very fast JavaScript programs serverside. It's pretty easy to install Node, code your program, and run it. But > how do you make it run nicely in the background like a true server

Go to `/etc/init/`
$ sudo nano yourapp.conf`
Paste **script.conf**
$ sudo start yourapp`

And when you wanna kill the process $ sudo stop yourapp

  description "node.js server"
  author      "your name"

  # used to be: start on startup
  # until we found some mounts weren't ready yet while booting

  start on started mountall
  stop on shutdown

  # automatically respawn

  respawn
  respawn limit 99 5

 script

        export HOME="/root"
        exec /usr/bin/nodejs /path/to/yourapp.js >> /var/log/node.log 2>&1

 end script

 post-start script

   # optionally put a script here that will notifiy you node has (re)started
   # /root/bin/hoptoad.sh "node.js has started!"

 end script

for further reference https://gist.github.com/jobsamuel/6d6095d52228461f3c53


问:
Query to select data between two dates with the format m/d/yyyy
I am facing problem when i'm trying to select records from a table between two dates.

m using the following query

```<code>select * from xxx where dates between '10/10/2012' and '10/12/2012'
</code>```

this query works for me but when the dates are in format like 1/1/2013.. it doesn't work..

plz solve my problem ASAP.

答:
you have to split the datetime and then store it with your desired format like dd/MM/yyyy. then you can use this query with between but i have objection using this becasue it will search every single data on your database,so i suggest you can use datediff.

```<code>        Dim start = txtstartdate.Text.Trim()
        Dim endday = txtenddate.Text.Trim()
        Dim arr()
        arr = Split(start, "/")
        Dim dt As New DateTime
        dt = New Date(Val(arr(2).ToString), Val(arr(1).ToString), Val(arr(0).ToString))
        Dim arry()
        arry = Split(endday, "/")
        Dim dt2 As New DateTime
        dt2 = New Date(Val(arry(2).ToString), Val(arry(1).ToString), Val(arry(0).ToString))

        qry = "SELECT * FROM [calender] WHERE datediff(day,'" & dt & "',[date])>=0 and datediff(day,'" & dt2 & "',[date])<=0 "
</code>```

here i have used dd/MM/yyyy format.

Body:
I am facing problem when i'm trying to select records from a table between two dates.

m using the following query

select * from xxx where dates between '10/10/2012' and '10/12/2012'

this query works for me but when the dates are in format like 1/1/2013.. it doesn't work..

plz solve my problem ASAP.

Body:
you have to split the datetime and then store it with your desired format like dd/MM/yyyy. then you can use this query with between but i have objection using this becasue it will search every single data on your database,so i suggest you can use datediff.

        Dim start = txtstartdate.Text.Trim()
        Dim endday = txtenddate.Text.Trim()
        Dim arr()
        arr = Split(start, "/")
        Dim dt As New DateTime
        dt = New Date(Val(arr(2).ToString), Val(arr(1).ToString), Val(arr(0).ToString))
        Dim arry()
        arry = Split(endday, "/")
        Dim dt2 As New DateTime
        dt2 = New Date(Val(arry(2).ToString), Val(arry(1).ToString), Val(arry(0).ToString))

        qry = "SELECT * FROM [calender] WHERE datediff(day,'" & dt & "',[date])>=0 and datediff(day,'" & dt2 & "',[date])<=0 "

here i have used dd/MM/yyyy format.


问:
Get logged status from API with react-router
React component with router in it. There's an api request in componentDidMount to check if user logged in. Problem is that only LoginPage component shows up. Could it be because of react component App reloads on every route change, so state.isLogged gets initial value false all the time? How can I fix it?

```<code>class App extends Component {

state = {
    logged: false,
}

async componentDidMount() {
    let logged = await getLoggedStatus(`${serverUrl}:/login`);
    this.setState({ logged: logged });
}

render() {
    return (
        <div style={{ height: '100%' }}>
            <Router>
                <div style={{ height: '100%' }}>
                    <Route path="/login" component={loginPage} />
                    <Route exact path="/dashboard" render={() => (
                        this.state.logged ?
                        (
                            <Dashboard/>
                        ) :
                        (
                            <Redirect to="/login" />
                        )

                    )} />
                </div>
            </Router>
       </div>
    )
}
}
</code>```

答:
Two things that you should do are:

First: Keep a loading state so that the till the response of your API request is not available you are not taking any decision on whether to redirect to the user to login page or not.

Secondly: Check for the loading state variable to decide whether you want to make a decision or show a loader

```<code>class App extends Component {

    state = {
        logged: false,
        loading: true
    }

    async componentDidMount() {
        let logged = await getLoggedStatus(`${serverUrl}:/login`);
        this.setState({ logged: logged, loading: false });
    }
    render() {
        if(this.state.loading) {
            return <div>Loading...</div>
        }
        return (
            <div style={{ height: '100%' }}>
                <Router>
                    <div style={{ height: '100%' }}>
                        <Route path="/login" component={loginPage} />
                        <Route exact path="/dashboard" render={() => (
                            this.state.logged ?
                            (
                                <Dashboard/>
                            ) :
                            (
                                <Redirect to="/login" />
                            )

                        )} />
                    </div>
                </Router>
           </div>
        )
    }

}
</code>```

You code doesn't work because you have your request set up in componentDidMount which is executed after the render and hence you are redirected even before the request evaluates

Body:
React component with router in it. There's an api request in componentDidMount to check if user logged in. Problem is that only LoginPage component shows up. Could it be because of react component App reloads on every route change, so state.isLogged gets initial value false all the time? How can I fix it?

class App extends Component {

state = {
    logged: false,
}

async componentDidMount() {
    let logged = await getLoggedStatus(`${serverUrl}:/login`);
    this.setState({ logged: logged });
}

render() {
    return (

            <Router>

                    <Route path="/login" component={loginPage} />
                    <Route exact path="/dashboard" render={() => (
                        this.state.logged ?
                        (
                            <Dashboard/>
                        ) :
                        (
                            <Redirect to="/login" />
                        )

                    )} />

            </Router>

    )
}
}

Body:
Two things that you should do are:

First: Keep a loading state so that the till the response of your API request is not available you are not taking any decision on whether to redirect to the user to login page or not.

Secondly: Check for the loading state variable to decide whether you want to make a decision or show a loader

class App extends Component {

    state = {
        logged: false,
        loading: true
    }

    async componentDidMount() {
        let logged = await getLoggedStatus(`${serverUrl}:/login`);
        this.setState({ logged: logged, loading: false });
    }
    render() {
        if(this.state.loading) {
            return <div>Loading...</div>
        }
        return (
            <div style={{ height: '100%' }}>
                <Router>
                    <div style={{ height: '100%' }}>
                        <Route path="/login" component={loginPage} />
                        <Route exact path="/dashboard" render={() => (
                            this.state.logged ?
                            (
                                <Dashboard/>
                            ) :
                            (
                                <Redirect to="/login" />
                            )

                        )} />
                    </div>
                </Router>
           </div>
        )
    }

}

You code doesn't work because you have your request set up in componentDidMount which is executed after the render and hence you are redirected even before the request evaluates


问:
Javascript setting innerHTML null issue
When i run an ajax query, i get back an array of results. I want to create a new element and set its inner html to the results. The results are working fine, im getting them no problem. They contain the correct data. I can create the element with an id based on the result fine as well i just get:

Uncaught TypeError: Cannot set property 'innerHTML' of null

on this line:

```<code>document.getElementById(result[i]).innerHTML = result[i];
</code>```

Do you know what is the issue?

Javascript:

```<code>function SearchReviews() {
    $(document).ready(function() {

        searchData = "searchData=" + $("#searchReviews").val() + "&action=" + "searchReviews";
        urlPath = "../index.php";

        if ($.trim($("#searchReviews").val()).length > 0) { // client is typing
            // Send the search data to database
            $.ajax({
                type: "POST",
                url: urlPath,
                data: searchData,
                dataType: 'JSON',
                success: function (result) {
                    console.log(result[0]);
                    console.log(result.length);

                    $("#searchText").empty(); // we want to refresh the results

                    for (i = 0; i < result.length; i++) {
                        var html = '<p id=' + result[i] + '></p><hr>';
                        $("#searchText").append(html);
                        document.getElementById(result[i]).innerHTML = result[i];
                    }
                },
                error: function(xhr, status, error) {
                    alert("Error" + xhr.responseText);
                }
            })
        } else {
            $("#searchText").empty();
        }
    })
}
</code>```

HTML

```<code>            <div class="col-sm-5">
                <p class="text-center">Reviews</p> <hr>
                <div class="input-group">
                <input type="text" class="form-control" id="searchReviews" placeholder="Search reviews" onkeydown="SearchReviews();">
                </div>
                <p class="text-center" id="searchText"></p>
            </div>
</code>```

答:
You don't need to get the element from DOM, As you can create it using jQuery and set its text.

```<code>var html = $('<p>', { id: result[i] , text : result[i] });
$("#searchText").append(html).append('<hr>');
</code>```

You can just put text in
 using string concatenation

```<code>var html = '<p id="' + result[i] + '">' + result[i] + '</p><hr>';
$("#searchText").append(html);
</code>```

Note: ID attribute can't have spaces in them and should always wrap attributes in quotes.

I guess result[i] contains spaces thus you got NULL on statement  document.getElementById(result[i])

Title: Javascript setting innerHTML null issue

Body:
When i run an ajax query, i get back an array of results. I want to create a new element and set its inner html to the results. The results are working fine, im getting them no problem. They contain the correct data. I can create the element with an id based on the result fine as well i just get:

Uncaught TypeError: Cannot set property 'innerHTML' of null

on this line:

document.getElementById(result[i]).innerHTML = result[i];

Do you know what is the issue?

Javascript:

function SearchReviews() {
    $(document).ready(function() {

        searchData = "searchData=" + $("#searchReviews").val() + "&action=" + "searchReviews";
        urlPath = "../index.php";

        if ($.trim($("#searchReviews").val()).length > 0) { // client is typing
            // Send the search data to database
            $.ajax({
                type: "POST",
                url: urlPath,
                data: searchData,
                dataType: 'JSON',
                success: function (result) {
                    console.log(result[0]);
                    console.log(result.length);

                    $("#searchText").empty(); // we want to refresh the results

                    for (i = 0; i < result.length; i++) {
                        var html = '

';
                        $("#searchText").append(html);
                        document.getElementById(result[i]).innerHTML = result[i];
                    }
                },
                error: function(xhr, status, error) {
                    alert("Error" + xhr.responseText);
                }
            })
        } else {
            $("#searchText").empty();
        }
    })
}

HTML

Reviews

                <input type="text" class="form-control" id="searchReviews" placeholder="Search reviews" onkeydown="SearchReviews();">

Body:
You don't need to get the element from DOM, As you can create it using jQuery and set its text.

var html = $('<p>', { id: result[i] , text : result[i] });
$("#searchText").append(html).append('<hr>');

You can just put text in <p> using string concatenation

var html = '<p id="' + result[i] + '">' + result[i] + '</p><hr>';
$("#searchText").append(html);

Note: ID attribute can't have spaces in them and should always wrap attributes in quotes.

I guess result[i] contains spaces thus you got NULL on statement  document.getElementById(result[i])