问:
Mako templates inline if statement
I have a template variable, c.is_friend, that I would like to use to determine whether or not a class is applied.  For example:

```<code>if c.is_friend is True
<a href="#" class="friend">link</a>

if c.is_friend is False
<a href="#">link</a>
</code>```

Is there some way to do this inline, like:

```<code><a href="#" ${if c.is_friend is True}class="friend"{/if}>link</a>
</code>```

Or something like that?

答:
More General Solution

If you need to come up with a more general solution, let's say you need to put a variable called relationship inside the class tag instead of a static string, you could do it like this with the old string formatting:

```<code><a href="#" ${'class="%s"' % relationship if c.has_relation is True else ''}>link</a>
</code>```

or without string formatting:

```<code><a href="#"
% if c.has_relation is True:
class="${relationship}"
% endif
>link</a>
</code>```

This should work for Python 2.7+ and 3+

WARNING (for older versions)

Pay attention to the {} inside ${}!

The solution with the ternary operator mentioned by Jochen is also correct but can lead to unexpected behavior when combining with str.format().

You need to avoid {} inside Mako's ${}, because apparently Mako stops parsing the expression after finding the first }. This means you shouldn't use for example:

${'{}'.format(a_str)}. Instead use ${'%s' % a_str}.

${'%(first)s %(second)s' % {'first': a_str1, 'second': a_str2}}. Instead use

${'%(first)s %(second)s' % dict(first=a_str1, second=a_str2)}

Title: Mako templates inline if statement

Body:
I have a template variable, c.is_friend, that I would like to use to determine whether or not a class is applied.  For example:

if c.is_friend is True
link

if c.is_friend is False
link

Is there some way to do this inline, like:

link

Or something like that?

Body:
More General Solution

If you need to come up with a more general solution, let's say you need to put a variable called relationship inside the class tag instead of a static string, you could do it like this with the old string formatting:

<a href="#" ${'class="%s"' % relationship if c.has_relation is True else ''}>link</a>

or without string formatting:

<a href="#"
% if c.has_relation is True:
class="${relationship}"
% endif
>link</a>

This should work for Python 2.7+ and 3+

WARNING (for older versions)

Pay attention to the {} inside ${}!

The solution with the ternary operator mentioned by Jochen is also correct but can lead to unexpected behavior when combining with str.format().

You need to avoid {} inside Mako's ${}, because apparently Mako stops parsing the expression after finding the first }. This means you shouldn't use for example:

${'{}'.format(a_str)}. Instead use ${'%s' % a_str}.

${'%(first)s %(second)s' % {'first': a_str1, 'second': a_str2}}. Instead use

${'%(first)s %(second)s' % dict(first=a_str1, second=a_str2)}


来源: stackexchange

问:
Setting GHCi prompt inside multiline blocks
GHCi's prompt can be set as follows, which is in my .ghci:

```<code>:set prompt "λ> "
</code>```

However, a different prompt appears in multiline blocks, and I can't figure out how to change it. It is completely unreadable if too many modules are imported:

```<code>λ> :{
Prelude Control.Arrow Control.Applicative Control.Monad Control.Concurrent Control.Concurrent.Async Control.Parallel Data.String Data.Char Data.List Data.Maybe Data.Monoid Control.Monad.IO.Class|
</code>```

Is there a way to set this secondary prompt? Alternatively, are there other good ways to run Haskell interactively where multiline expressions are displayed in a more friendly manner?

答:
You can't use prompt2 for GHC 8.2.1 and newer anymore because interface is changed. Previously it was:

```<code>   :set prompt <prompt>        set the prompt used in GHCi
   :set prompt2 <prompt>       set the continuation prompt used in GHCi
</code>```

Now it's:

```<code>   :set prompt <prompt>        set the prompt used in GHCi
   :set prompt-cont <prompt>   set the continuation prompt used in GHCi
   :set prompt-function <expr> set the function to handle the prompt
   :set prompt-cont-function <expr> set the function to handle the continuation prompt
</code>```

Some typical usages of these functions (just type in your GHCi or add in ~/.ghc/ghci.conf to apply settings globally):

```<code>:set prompt      λ:
:set prompt-cont λ|
</code>```

or

```<code>:set prompt      ghci>
:set prompt-cont ghci|
</code>```

Note: space at the end of each line

ContentLicense: CC BY-SA 3.0

Body:
GHCi's prompt can be set as follows, which is in my .ghci:

:set prompt "λ> "

However, a different prompt appears in multiline blocks, and I can't figure out how to change it. It is completely unreadable if too many modules are imported:

λ> :{
Prelude Control.Arrow Control.Applicative Control.Monad Control.Concurrent Control.Concurrent.Async Control.Parallel Data.String Data.Char Data.List Data.Maybe Data.Monoid Control.Monad.IO.Class|

Is there a way to set this secondary prompt? Alternatively, are there other good ways to run Haskell interactively where multiline expressions are displayed in a more friendly manner?

Body:
You can't use prompt2 for GHC 8.2.1 and newer anymore because interface is changed. Previously it was:

   :set prompt <prompt>        set the prompt used in GHCi
   :set prompt2 <prompt>       set the continuation prompt used in GHCi

Now it's:

   :set prompt <prompt>        set the prompt used in GHCi
   :set prompt-cont <prompt>   set the continuation prompt used in GHCi
   :set prompt-function <expr> set the function to handle the prompt
   :set prompt-cont-function <expr> set the function to handle the continuation prompt

Some typical usages of these functions (just type in your GHCi or add in ~/.ghc/ghci.conf to apply settings globally):

:set prompt      λ:
:set prompt-cont λ|

or

:set prompt      ghci>
:set prompt-cont ghci|

Note: space at the end of each line

ContentLicense: CC BY-SA 4.0


问:
Case in mysql to execute another query based on condition
I have a problem, the concept is value from @count to perform if and execute the query. What should I do to fix it?

Here is my code:

```<code>SELECT
    CASE WHEN ((SELECT COUNT(*) FROM tb_dana_user WHERE userid=1234 AND password=1234) = 0)
            THEN (SELECT * FROM tb_dana_user)
            ELSE (SELECT 'bar')
    END
</code>```

When I change SELECT * FROM tb_dana_user to SELECT 'its true', it's working properly. How to fix this case? Sorry for bad english  .the concept is when its true then the query will execute SELECT * FROM tb_dana_user

答:
The CASE expression evaluates to a value, i.e. it is used to evaluate to one of a set of results, based on some condition.
Example:

```<code>SELECT CASE
    WHEN type = 1 THEN 'foo'
    WHEN type = 2 THEN 'bar'
    ELSE 'foo-bar'
END AS column_name
FROM sometable`
</code>```

The CASE statement executes one of a set of statements returns one result, based on some condition.

then statement has a query(select * from tb_dana_user) which returns multiple rows.

In your case either you can limit the value returned for select * from tb_dana_user to one at the same time column also one.

```<code>SELECT
    CASE WHEN ((SELECT COUNT(*) FROM tb_dana_user WHERE userid=1234 AND password=1234) = 0)
            THEN (SELECT id FROM tb_dana_user limit 1)
            ELSE (SELECT 'bar')
    END
</code>```

Body:
I have a problem, the concept is value from @count to perform if and execute the query. What should I do to fix it?

Here is my code:

SELECT
    CASE WHEN ((SELECT COUNT(*) FROM tb_dana_user WHERE userid=1234 AND password=1234) = 0)
            THEN (SELECT * FROM tb_dana_user)
            ELSE (SELECT 'bar')
    END

When I change SELECT * FROM tb_dana_user to SELECT 'its true', it's working properly. How to fix this case? Sorry for bad english  .the concept is when its true then the query will execute SELECT * FROM tb_dana_user

Body:
The CASE expression evaluates to a value, i.e. it is used to evaluate to one of a set of results, based on some condition.
Example:

SELECT CASE
    WHEN type = 1 THEN 'foo'
    WHEN type = 2 THEN 'bar'
    ELSE 'foo-bar'
END AS column_name
FROM sometable`

The CASE statement executes one of a set of statements returns one result, based on some condition.

then statement has a query(select * from tb_dana_user) which returns multiple rows.

In your case either you can limit the value returned for select * from tb_dana_user to one at the same time column also one.

SELECT
    CASE WHEN ((SELECT COUNT(*) FROM tb_dana_user WHERE userid=1234 AND password=1234) = 0)
            THEN (SELECT id FROM tb_dana_user limit 1)
            ELSE (SELECT 'bar')
    END


问:
Displaying corresponding values in data frame in R
Please check the code below, I have created a data frame using three variables below, the variable "y123" computes the similarity between columns a2 with a1. The variable "y123" gives me total 16 values where every a1 value gets compared with a2. My need is that when a particular "a1" value is compared with a particular "a2" value, I want the corresponding "a3" value next to "a2" be displayed besides. So the result should be a data frame with column y123 and a second column with corresponding "a3" column appearing four times i.e 16 values. Thanks and please help.

```<code>library(stringdist)
library(RecordLinkage)
a1 = c(103,120,142,153)
a2 = c(113,453,142,102)
a3 = c("a1","b1","c1","d1")
a1 = as.character(a1)
a2 = as.character(a2)
a3 = as.character(a3)
a123 = data.frame(a1,a2,a3)
y123 = sapply(a1, function(i) RecordLinkage::levenshteinSim(i,a2))
b1 = c(y123)
b1
</code>```

I need something list this:

```<code>new_data = data.frame(b1,new_column)
</code>```

Body:
Please check the code below, I have created a data frame using three variables below, the variable "y123" computes the similarity between columns a2 with a1. The variable "y123" gives me total 16 values where every a1 value gets compared with a2. My need is that when a particular "a1" value is compared with a particular "a2" value, I want the corresponding "a3" value next to "a2" be displayed besides. So the result should be a data frame with column y123 and a second column with corresponding "a3" column appearing four times i.e 16 values. Thanks and please help.

library(stringdist)
library(RecordLinkage)
a1 = c(103,120,142,153)
a2 = c(113,453,142,102)
a3 = c("a1","b1","c1","d1")
a1 = as.character(a1)
a2 = as.character(a2)
a3 = as.character(a3)
a123 = data.frame(a1,a2,a3)
y123 = sapply(a1, function(i) RecordLinkage::levenshteinSim(i,a2))
b1 = c(y123)
b1

I need something list this:

new_data = data.frame(b1,new_column)

Body:
I think this is what you want. I modified your sapply function:

data.frame(y123 = c(y123), a3 = rep(a3, times = length(a3)))
#        y123 a3
#1  0.6666667 a1
#2  0.3333333 b1
#3  0.3333333 c1
#4  0.6666667 d1
#5  0.3333333 a1
#6  0.0000000 b1
#7  0.3333333 c1
#8  0.3333333 d1
#9  0.3333333 a1
#10 0.0000000 b1
#11 1.0000000 c1
#12 0.6666667 d1
#13 0.6666667 a1
#14 0.6666667 b1
#15 0.3333333 c1
#16 0.3333333 d1


问:
half yearly colorbar in matplotlib and pandas
I have a panda dataframe. I am making scatter plot and tried to categorize the data based on colorbar. I did it for monthly classification and quality classification as shown in the example code below.

```<code>a = np.random.rand(366)
b = np.random.rand(366)*0.4
index = (pd.date_range(pd.to_datetime('01-01-2000'), periods=366))
df = pd.DataFrame({'a':a,'b':b},index = index)
plt.scatter(df['a'],df['b'],c = df.index.month)
plt.colorbar()
</code>```

And also for quality:

```<code>plt.scatter(df['a'],df['b'],c = df.index.quarter)
plt.colorbar()
</code>```

My question: is there any way to categorize by half yearly. for example from the month 1-6 and 7-12 and also by month like: 10-3 and 4-9
Thank you and your help/suggestion will be highly appreciated.

答:
I would opt for a solution which does not completely truncate the monthly information. Using colors which are similar but distinguishable for the months allows to visually classify by half-year as well as month.

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

a = np.random.rand(366)
b = np.random.rand(366)*0.4
index = (pd.date_range(pd.to_datetime('01-01-2000'), periods=366))
df = pd.DataFrame({'a':a,'b':b},index = index)

colors=["crimson", "orange", "darkblue", "skyblue"]
cdic = list(zip([0,.499,.5,1],colors))
cmap = matplotlib.colors.LinearSegmentedColormap.from_list("name", cdic,12 )
norm = matplotlib.colors.BoundaryNorm(np.arange(13)+.5,12)

plt.scatter(df['a'],df['b'],c = df.index.month, cmap=cmap, norm=norm)
plt.colorbar(ticks=np.arange(1,13))

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

Body:
I have a panda dataframe. I am making scatter plot and tried to categorize the data based on colorbar. I did it for monthly classification and quality classification as shown in the example code below.

a = np.random.rand(366)
b = np.random.rand(366)*0.4
index = (pd.date_range(pd.to_datetime('01-01-2000'), periods=366))
df = pd.DataFrame({'a':a,'b':b},index = index)
plt.scatter(df['a'],df['b'],c = df.index.month)
plt.colorbar()

And also for quality:

plt.scatter(df['a'],df['b'],c = df.index.quarter)
plt.colorbar()

My question: is there any way to categorize by half yearly. for example from the month 1-6 and 7-12 and also by month like: 10-3 and 4-9
Thank you and your help/suggestion will be highly appreciated.

Body:
I would opt for a solution which does not completely truncate the monthly information. Using colors which are similar but distinguishable for the months allows to visually classify by half-year as well as month.

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

a = np.random.rand(366)
b = np.random.rand(366)*0.4
index = (pd.date_range(pd.to_datetime('01-01-2000'), periods=366))
df = pd.DataFrame({'a':a,'b':b},index = index)

colors=["crimson", "orange", "darkblue", "skyblue"]
cdic = list(zip([0,.499,.5,1],colors))
cmap = matplotlib.colors.LinearSegmentedColormap.from_list("name", cdic,12 )
norm = matplotlib.colors.BoundaryNorm(np.arange(13)+.5,12)

plt.scatter(df['a'],df['b'],c = df.index.month, cmap=cmap, norm=norm)
plt.colorbar(ticks=np.arange(1,13))

plt.show()


问:
reading results of icacls /save with FSO object of VBScript fails
I need to save the results of running ICACLS command, change them, and restore the changed permissions back. I use vbscript to do that. The issue is that reading lines or whole data from the saved gives me 1 character and a bunch of spaces in result. But if I try reading the contents of the resulting data, been uploaded by ICACLS, char-by-char, and printing it on the fly, it shows the proper contents.

```<code>Const ForReading=1 'I/O modes
dim FolderToSetPermissions,ShellObj,FSO,EffectivePermissionsFile,CurrentLine,ParentFolderName,ParentFolderObj
FolderToSetPermissions="c:\test"
Set FSO = CreateObject("Scripting.FileSystemObject")
ParentFolderName=FSO.GetParentFolderName(wscript.ScriptFullName)
Set ParentFolderObj =fso.GetFolder(ParentFolderName)
Set ShellObj = WScript.CreateObject("WScript.Shell")
ShellObj.run "icacls.exe """&FolderToSetPermissions&"""\* /save " & ParentFolderObj.path & "\EffectivePermissions.txt /t", 0, True
set EffectivePermissionsFile =FSO.OpenTextFile(ParentFolderObj.path & "\EffectivePermissions.txt",ForReading,False)
Do Until EffectivePermissionsFile.AtEndOfStream
'CurrentLine=EffectivePermissionsFile.Read(1) ' works fine if prints right after
 'reading from file. Concatenating all the chars in file causes the same result as
 'reading the file by lines or with .ReadAll function of FSO
 CurrentLine= EffectivePermissionsFile.ReadLine
 WScript.Echo CurrentLine
Loop
EffectivePermissionsFile.Close
</code>```

I suspect, the issue is in the ICACLS itself: it doesn't write a really text file. I found another person who run into the situation (https://windowssecrets.com/forums/showthread.php/150866-Win7-ICACLS-redirected-output-and-NOTEPAD-don-t-play-well-together).

P.S: CACLS writes correct text files which are read with no problems. But unfortunately it can't do a recurse throughout of a folder.

答:
Reading through hundreds of pages I finally found the solution! This function converts the text created by icacls <file or folder> /save <filename> /T from UCS-2 codepage to UTF-8 one:

```<code>Sub UTFConvert(filename)
  Set fso = CreateObject("Scripting.FileSystemObject")
  txt = fso.OpenTextFile(filename, 1, False, -1).ReadAll

  Set stream = CreateObject("ADODB.Stream")
  stream.Open
  stream.Type     = 2 'text
  stream.Position = 0
  stream.Charset  = "utf-8"
  stream.WriteText txt
  stream.SaveToFile filename, 2
  stream.Close
End Sub
</code>```

The resulting text becomes readable with VBScript afterwards.

Took the answer from here: UCS-2 Little Endian to UTF-8 conversion leaves file with many unwanted characters

Body:
I need to save the results of running ICACLS command, change them, and restore the changed permissions back. I use vbscript to do that. The issue is that reading lines or whole data from the saved gives me 1 character and a bunch of spaces in result. But if I try reading the contents of the resulting data, been uploaded by ICACLS, char-by-char, and printing it on the fly, it shows the proper contents.

Const ForReading=1 'I/O modes
dim FolderToSetPermissions,ShellObj,FSO,EffectivePermissionsFile,CurrentLine,ParentFolderName,ParentFolderObj
FolderToSetPermissions="c:\test"
Set FSO = CreateObject("Scripting.FileSystemObject")
ParentFolderName=FSO.GetParentFolderName(wscript.ScriptFullName)
Set ParentFolderObj =fso.GetFolder(ParentFolderName)
Set ShellObj = WScript.CreateObject("WScript.Shell")
ShellObj.run "icacls.exe """&FolderToSetPermissions&"""\* /save " & ParentFolderObj.path & "\EffectivePermissions.txt /t", 0, True
set EffectivePermissionsFile =FSO.OpenTextFile(ParentFolderObj.path & "\EffectivePermissions.txt",ForReading,False)
Do Until EffectivePermissionsFile.AtEndOfStream
'CurrentLine=EffectivePermissionsFile.Read(1) ' works fine if prints right after
 'reading from file. Concatenating all the chars in file causes the same result as
 'reading the file by lines or with .ReadAll function of FSO
 CurrentLine= EffectivePermissionsFile.ReadLine
 WScript.Echo CurrentLine
Loop
EffectivePermissionsFile.Close

I suspect, the issue is in the ICACLS itself: it doesn't write a really text file. I found another person who run into the situation (https://windowssecrets.com/forums/showthread.php/150866-Win7-ICACLS-redirected-output-and-NOTEPAD-don-t-play-well-together).

P.S: CACLS writes correct text files which are read with no problems. But unfortunately it can't do a recurse throughout of a folder.

Body:
Reading through hundreds of pages I finally found the solution! This function converts the text created by icacls <file or folder> /save <filename> /T from UCS-2 codepage to UTF-8 one:

Sub UTFConvert(filename)
  Set fso = CreateObject("Scripting.FileSystemObject")
  txt = fso.OpenTextFile(filename, 1, False, -1).ReadAll

  Set stream = CreateObject("ADODB.Stream")
  stream.Open
  stream.Type     = 2 'text
  stream.Position = 0
  stream.Charset  = "utf-8"
  stream.WriteText txt
  stream.SaveToFile filename, 2
  stream.Close
End Sub

The resulting text becomes readable with VBScript afterwards.

Took the answer from here: UCS-2 Little Endian to UTF-8 conversion leaves file with many unwanted characters


问:
Different activity title in different intent actions
I have one activity and three intet filters, each with different label set on, (AndroidManifiest.xml below)

```<code>    <activity android:name=".activities.RecordActivity">
        <intent-filter>
            <category android:name="android.intent.category.DEFAULT" />
            <action android:name="com.keitai.enigma.OPEN_RECORD" />
        </intent-filter>
        <intent-filter android:label="@string/newRecord">
            <category android:name="android.intent.category.DEFAULT" />
            <action android:name="com.keitai.enigma.NEW_RECORD" />
        </intent-filter>
        <intent-filter android:label="@string/editRecord">
            <category android:name="android.intent.category.DEFAULT" />
            <action android:name="com.keitai.enigma.EDIT_RECORD" />
        </intent-filter>
    </activity>
</code>```

But activity title is not changing to label set in intent filter :( Activity always contains application label.

What I'm donig wrong?

答:
Actually, from your example I'd suggest that you use separate activities (which can specify labels that are shown as titles!).
In Android, one activity usually corresponds to one use case - so if OPEN_RECORD shows a dialog where the user can select a record and EDIT_RECORD allows to edit a record, than you would usually have two different activities.

Have a look at the notepad tutorial for an example.

ContentLicense: CC BY-SA 2.5

Body:
I have one activity and three intet filters, each with different label set on, (AndroidManifiest.xml below)

    <activity android:name=".activities.RecordActivity">
        <intent-filter>
            <category android:name="android.intent.category.DEFAULT" />
            <action android:name="com.keitai.enigma.OPEN_RECORD" />
        </intent-filter>
        <intent-filter android:label="@string/newRecord">
            <category android:name="android.intent.category.DEFAULT" />
            <action android:name="com.keitai.enigma.NEW_RECORD" />
        </intent-filter>
        <intent-filter android:label="@string/editRecord">
            <category android:name="android.intent.category.DEFAULT" />
            <action android:name="com.keitai.enigma.EDIT_RECORD" />
        </intent-filter>
    </activity>

But activity title is not changing to label set in intent filter :( Activity always contains application label.

What I'm donig wrong?


问:
Aggregate date Range Mongoose
Dear,

I'am trying to count value in my mongo db but the aggregation return empty array.

My query look like this:

```<code>Order.aggregate(
            [
                {
                    '$match': {
                        createdAt : {
                            '$gte' : new Date("2017-11-29").setHours(14,43,0,0),
                            '$lt' : new Date()
                        }
                    }
                },
                {
                    $group: {
                        _id: null,
                        count: {
                            $sum: 1
                        }
                    }
                }
            ]
        ).exec().then(r => {
            console.log(r); // []
        });
</code>```

An other (and dirty) query works fine:

```<code>Order.find({
            createdAt : {
                '$gte' : new Date("2017-11-29").setHours(14,43,0,0),
                '$lt' : new Date()
            }
        }).exec().then(orders => {
            console.log(orders.length);// 1463

        })
</code>```

Did I miss something?

Thanks in advance

答:
why not</p>

```<code>Order.count({
            createdAt : {
                '$gte' : new Date("2017-11-29").setHours(14,43,0,0),
                '$lt' : new Date()
            }
        }).exec().then(count=> {
            console.log(count);// 1463

        })
</code>```

Title: Aggregate date Range Mongoose

Body:
Dear,

I'am trying to count value in my mongo db but the aggregation return empty array.

My query look like this:

Order.aggregate(
            [
                {
                    '$match': {
                        createdAt : {
                            '$gte' : new Date("2017-11-29").setHours(14,43,0,0),
                            '$lt' : new Date()
                        }
                    }
                },
                {
                    $group: {
                        _id: null,
                        count: {
                            $sum: 1
                        }
                    }
                }
            ]
        ).exec().then(r => {
            console.log(r); // []
        });

An other (and dirty) query works fine:

Order.find({
            createdAt : {
                '$gte' : new Date("2017-11-29").setHours(14,43,0,0),
                '$lt' : new Date()
            }
        }).exec().then(orders => {
            console.log(orders.length);// 1463

        })

Did I miss something?

Thanks in advance

Body:
why not

Order.count({
            createdAt : {
                '$gte' : new Date("2017-11-29").setHours(14,43,0,0),
                '$lt' : new Date()
            }
        }).exec().then(count=> {
            console.log(count);// 1463

        })


问:
mysql function that returns all addresses with character string when enter customer number
I have this mysql command create, but I am totally new, it gives me error of:

Not allowed to return a result set from a function.

Here is how I create my sql function:

```<code>-> delimiter $$
-> create function myFunction(in_id INT)
-> returns VARCHAR(255)
-> begin
-> select concat(addr01, ',', addr02) as addfound from dtb_customer where customer_id = in_id;
-> return(addfound);
-> end$$
</code>```

Please help me edit the code.

答:
You can't make Functions in MySQL from PHP.

May be that can be possible If Function is created in PHPMyAdmin and invoked somehow..... (I am not sure even this is possible)

Body:
I have this mysql command create, but I am totally new, it gives me error of:

Not allowed to return a result set from a function.

Here is how I create my sql function:

-> delimiter $$
-> create function myFunction(in_id INT)
-> returns VARCHAR(255)
-> begin
-> select concat(addr01, ',', addr02) as addfound from dtb_customer where customer_id = in_id;
-> return(addfound);
-> end$$

Please help me edit the code.


问:
Jquery on hover add class to another element simply not working
I appreciate there are many similar posts on here but none seem to address why this code is not working.

The idea is, when a menu li is hovered the background of the menu should change using CSS.

I found the code on StackOverflow

add class to a div when hover another one (Javascript)

but in my case, it simply does not work even when running at the very end of the footer.

```<code><script>
   jQuery(document).ready(function() {
     jQuery('#responsive-menu-item-48473').hover(function(){
           jQuery('#responsive-menu-container').addClass('blue');
       },function(){
          jQuery('#responsive-menu-container').removeClass('blue');
       });
   });
</script>
</code>```

Additional info...

cut down html for the menu:

```<code><button id="responsive-menu-button" class="responsive-menu-button responsive-menu-boring responsive-menu-accessible" type="button" aria-label="Menu">
    <span class="responsive-menu-label responsive-menu-label-left">
        <span class="responsive-menu-button-text">Menu</span>
    </span>

    <span class="responsive-menu-box">
        <span class="responsive-menu-inner"></span>
    </span>
</button>

<div id="responsive-menu-container" class="slide-left">
    <div id="responsive-menu-wrapper">
        <div id="responsive-menu-title">
            Main Menu
        </div>

        <ul id="responsive-menu" class="">
            <li id="responsive-menu-item-57071" class=" menu-item menu-item-type-custom menu-item-object-custom responsive-menu-item"><a href="http://localhost/wordpress-updates/fx/my-account/customer-logout/" class="responsive-menu-item-link">Logout</a></li>
            <li id="responsive-menu-item-48473" class=" menu-item menu-item-type-post_type menu-item-object-page menu-item-home current-menu-item page_item page-item-16137 current_page_item responsive-menu-item responsive-menu-current-item"><a title="Home" href="http://localhost/wordpress-updates/" class="responsive-menu-item-link">Home</a></li>
        </ul>
    </div>
</div>
</code>```

Haven't got as far creating the classes yet, not that that should matter?

答:
Its working good.

  jQuery(document).ready(function() {
     jQuery('#responsive-menu-item-48473').hover(function(){
           jQuery('#responsive-menu-container').addClass('blue');
       },function(){
          jQuery('#responsive-menu-container').removeClass('blue');
       });
   });```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.blue{
color:green;
background:red;
}</code>```

            Menu

    </button>

                Main Menu

Logout

Home

```

Body:
I appreciate there are many similar posts on here but none seem to address why this code is not working.

The idea is, when a menu li is hovered the background of the menu should change using CSS.

I found the code on StackOverflow

add class to a div when hover another one (Javascript)

but in my case, it simply does not work even when running at the very end of the footer.

Additional info...

cut down html for the menu:

<button id="responsive-menu-button" class="responsive-menu-button responsive-menu-boring responsive-menu-accessible" type="button" aria-label="Menu">

        Menu

</button>

            Main Menu

Logout

Home

Haven't got as far creating the classes yet, not that that should matter?

Body:
Its working good.

  jQuery(document).ready(function() {
     jQuery('#responsive-menu-item-48473').hover(function(){
           jQuery('#responsive-menu-container').addClass('blue');
       },function(){
          jQuery('#responsive-menu-container').removeClass('blue');
       });
   });

.blue{
color:green;
background:red;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span class="responsive-menu-label responsive-menu-label-left">
            <span class="responsive-menu-button-text">Menu</span>
        </span>

        <span class="responsive-menu-box">
            <span class="responsive-menu-inner"></span>
        </span>

    </button><div id="responsive-menu-container" class="slide-left">
        <div id="responsive-menu-wrapper">
            <div id="responsive-menu-title">
                Main Menu
            </div>

    <ul id="responsive-menu" class="">
        <li id="responsive-menu-item-57071" class=" menu-item menu-item-type-custom menu-item-object-custom responsive-menu-item"><a href="http://localhost/wordpress-updates/fx/my-account/customer-logout/" class="responsive-menu-item-link">Logout</a></li>
        <li id="responsive-menu-item-48473" class=" menu-item menu-item-type-post_type menu-item-object-page menu-item-home current-menu-item page_item page-item-16137 current_page_item responsive-menu-item responsive-menu-current-item"><a title="Home" href="http://localhost/wordpress-updates/" class="responsive-menu-item-link">Home</a></li>
    </ul>
</div>
</div>


问:
Opening modal window after clicking on image
I'm trying to open modal window with full picture inside for every thumbnail on list after clicking on it. There is my code with my tries of doing that. Does anyone know how should I do that?</p>

```<code>            <?php
                $directory = 'uploads/delivery-pictures/';
                // Zamieniamy znaki, bo w nazwach plikow nie ma znaku /
                $npsNumber = str_replace('/', '_', $model->getNps());
                $images = glob($directory . $npsNumber . '_' . $model->delivery_no . '*' .'*_m.jpg', GLOB_BRACE);
                $i = 0;
                if (empty($images)) {
                    echo 'Brak zdjęć';
                }
                foreach($images as $image) {
                    $i = $i + 1;
                    $id = $npsNumber . '_' . $model->delivery_no . '_' . $i;
                    echo '<img id=' . $id . ' src=https://produkcja.onix.lh/' . $image . ' />';
                }

                Modal::begin([
                        'header'=>'<h4>Zdjęcie dla dostawy'. $model->delivery_no .'</h4>',
                        'id' => 'modal',
                        'size'=>'modal-lg',
                ]);
                echo "<div id='modalContent'>Zawartosc</div>";
                Modal::end();

                $this->registerJs(
                    "
                        $('".$id."').click(function (){
                            $('#modal').modal('show')
                                .find('#modalContent');
                                //.load($(this).attr('value'));
                        });
                    "
                );
            ?>
</code>```

答:
I have found the solution, if someone is interested in it, I have pasted my code below.</p>

```<code>            <?php
                $directory = 'uploads/delivery-pictures/';
                // Zamieniamy znaki, bo w nazwach plikow nie ma znaku /
                $npsNumber = str_replace('/', '_', $model->getNps());
                $images = glob($directory . $npsNumber . '_' . $model->delivery_no . '*' .'*_m.jpg', GLOB_BRACE);
                $i = 0;
                if (empty($images)) {
                    echo 'Brak zdjęć';
                }
                echo "<script>
                    function showImg(srcImg){
                        console.log('debug2');
                        $('#modalImg').attr('src', srcImg);
                        $('#modal').modal('show');
                    };
                </script>";
                foreach($images as $image) {
                    $i = $i + 1;
                    $id = $npsNumber . '_' . $model->delivery_no . '_' . $i;
                    $fullImage = str_replace('_m', '_d', $image);
                    echo '<img id="' . $id . '" src="https://produkcja.onix.lh/' . $image . '" />';
                    echo "<script>
                            var currentId =  \"".$id."\";
                            console.log(currentId);
                            $('#".$id."').click(function(){showImg(\"https://produkcja.onix.lh/" . $fullImage . "\")});
                         </script>";
                }

                Modal::begin([
                    'header'=>'<center><h4>Zdjęcie dla dostawy '. $model->delivery_no .'</h4></center>',
                    'id' => 'modal',
                    'size'=>'modal-lg',
                ]);
                echo '<center><img id="modalImg" src="https://produkcja.onix.lh/' . $fullImage . '" /></center>';
                Modal::end();
            ?>
</code>```

Body:
I'm trying to open modal window with full picture inside for every thumbnail on list after clicking on it. There is my code with my tries of doing that. Does anyone know how should I do that?

            <?php
                $directory = 'uploads/delivery-pictures/';
                // Zamieniamy znaki, bo w nazwach plikow nie ma znaku /
                $npsNumber = str_replace('/', '_', $model->getNps());
                $images = glob($directory . $npsNumber . '_' . $model->delivery_no . '*' .'*_m.jpg', GLOB_BRACE);
                $i = 0;
                if (empty($images)) {
                    echo 'Brak zdjęć';
                }
                foreach($images as $image) {
                    $i = $i + 1;
                    $id = $npsNumber . '_' . $model->delivery_no . '_' . $i;
                    echo '';
                }

                Modal::begin([
                        'header'=>'
Zdjęcie dla dostawy'. $model->delivery_no .'
',
                        'id' => 'modal',
                        'size'=>'modal-lg',
                ]);
                echo "
Zawartosc
";
                Modal::end();

                $this->registerJs(
                    "
                        $('".$id."').click(function (){
                            $('#modal').modal('show')
                                .find('#modalContent');
                                //.load($(this).attr('value'));
                        });
                    "
                );
            ?>

Body:
I have found the solution, if someone is interested in it, I have pasted my code below.

            <?php
                $directory = 'uploads/delivery-pictures/';
                // Zamieniamy znaki, bo w nazwach plikow nie ma znaku /
                $npsNumber = str_replace('/', '_', $model->getNps());
                $images = glob($directory . $npsNumber . '_' . $model->delivery_no . '*' .'*_m.jpg', GLOB_BRACE);
                $i = 0;
                if (empty($images)) {
                    echo 'Brak zdjęć';
                }
                echo "<script>
                    function showImg(srcImg){
                        console.log('debug2');
                        $('#modalImg').attr('src', srcImg);
                        $('#modal').modal('show');
                    };
                </script>";
                foreach($images as $image) {
                    $i = $i + 1;
                    $id = $npsNumber . '_' . $model->delivery_no . '_' . $i;
                    $fullImage = str_replace('_m', '_d', $image);
                    echo '<img id="' . $id . '" src="https://produkcja.onix.lh/' . $image . '" />';
                    echo "<script>
                            var currentId =  \"".$id."\";
                            console.log(currentId);
                            $('#".$id."').click(function(){showImg(\"https://produkcja.onix.lh/" . $fullImage . "\")});
                         </script>";
                }

                Modal::begin([
                    'header'=>'<center><h4>Zdjęcie dla dostawy '. $model->delivery_no .'</h4></center>',
                    'id' => 'modal',
                    'size'=>'modal-lg',
                ]);
                echo '<center><img id="modalImg" src="https://produkcja.onix.lh/' . $fullImage . '" /></center>';
                Modal::end();
            ?>


问:
Join and count number of values in each subcategory
Lets say a have a data frame that looks like this:

```<code> V290   V311
0   GOOD    TOP QUARTER
1   NK-UNASCERTAIN  MIDDLE HALF
2   AVERAGE TOP QUARTER
3   POOR    NK-UNASCERTAIN
4   POOR    MIDDLE HALF
5   GOOD    MIDDLE HALF
6   POOR    TOP QUARTER
7   AVERAGE MIDDLE HALF
8   POOR    MIDDLE HALF
9   AVERAGE MIDDLE HALF
10  POOR    MIDDLE HALF
11  POOR    MIDDLE HALF
12  AVERAGE MIDDLE HALF
13  AVERAGE TOP QUARTER
</code>```

And i want to group this data by ['V311'] and see how many GOOD or POOR would be in Every ['V311'] Subcategory.
I want to make something like this:

```<code>  Top Quarter:GOOD:12
              POOR:30
              Average:15
  Middle half:GOOD:5
              POOR:19
              Average:3
</code>```

And so on...

答:
Use dict comprehenion with groupby, value_counts and convert to dict:

```<code>d = {k:v.value_counts().to_dict() for k,v in df.groupby('V311')['V290']}
print (d)
{'NK-UNASCERTAIN': {'POOR': 1},
'MIDDLE HALF': {'POOR': 4, 'NK-UNASCERTAIN': 1, 'AVERAGE': 3, 'GOOD': 1},
'TOP QUARTER': {'POOR': 1, 'AVERAGE': 2, 'GOOD': 1}}
</code>```

For output as Series:

```<code>s = df.groupby('V311')['V290'].value_counts()
print (s)
V311            V290
MIDDLE HALF     POOR              4
                AVERAGE           3
                GOOD              1
                NK-UNASCERTAIN    1
NK-UNASCERTAIN  POOR              1
TOP QUARTER     AVERAGE           2
                GOOD              1
                POOR              1
Name: V290, dtype: int64
</code>```

EDIT: If need relative frequencies:

```<code>s = df.groupby('V311')['V290'].value_counts(normalize=True)
print (s)
V311            V290
MIDDLE HALF     POOR              0.444444
                AVERAGE           0.333333
                GOOD              0.111111
                NK-UNASCERTAIN    0.111111
NK-UNASCERTAIN  POOR              1.000000
TOP QUARTER     AVERAGE           0.500000
                GOOD              0.250000
                POOR              0.250000
Name: V290, dtype: float64
</code>```

EDIT1:

If want all missing categories too:

```<code>s = df.groupby('V311')['V290'].value_counts()
s = s.reindex(pd.MultiIndex.from_product(s.index.levels), fill_value=0)
print (s)
MIDDLE HALF     AVERAGE           3
                GOOD              1
                NK-UNASCERTAIN    1
                POOR              4
NK-UNASCERTAIN  AVERAGE           0
                GOOD              0
                NK-UNASCERTAIN    0
                POOR              1
TOP QUARTER     AVERAGE           2
                GOOD              1
                NK-UNASCERTAIN    0
                POOR              1
Name: V290, dtype: int64
</code>```

Body:
Lets say a have a data frame that looks like this:

 V290   V311
0   GOOD    TOP QUARTER
1   NK-UNASCERTAIN  MIDDLE HALF
2   AVERAGE TOP QUARTER
3   POOR    NK-UNASCERTAIN
4   POOR    MIDDLE HALF
5   GOOD    MIDDLE HALF
6   POOR    TOP QUARTER
7   AVERAGE MIDDLE HALF
8   POOR    MIDDLE HALF
9   AVERAGE MIDDLE HALF
10  POOR    MIDDLE HALF
11  POOR    MIDDLE HALF
12  AVERAGE MIDDLE HALF
13  AVERAGE TOP QUARTER

And i want to group this data by ['V311'] and see how many GOOD or POOR would be in Every ['V311'] Subcategory.
I want to make something like this:

  Top Quarter:GOOD:12
              POOR:30
              Average:15
  Middle half:GOOD:5
              POOR:19
              Average:3

And so on...

Body:
Use dict comprehenion with groupby, value_counts and convert to dict:

d = {k:v.value_counts().to_dict() for k,v in df.groupby('V311')['V290']}
print (d)
{'NK-UNASCERTAIN': {'POOR': 1},
'MIDDLE HALF': {'POOR': 4, 'NK-UNASCERTAIN': 1, 'AVERAGE': 3, 'GOOD': 1},
'TOP QUARTER': {'POOR': 1, 'AVERAGE': 2, 'GOOD': 1}}

For output as Series:

s = df.groupby('V311')['V290'].value_counts()
print (s)
V311            V290
MIDDLE HALF     POOR              4
                AVERAGE           3
                GOOD              1
                NK-UNASCERTAIN    1
NK-UNASCERTAIN  POOR              1
TOP QUARTER     AVERAGE           2
                GOOD              1
                POOR              1
Name: V290, dtype: int64

EDIT: If need relative frequencies:

s = df.groupby('V311')['V290'].value_counts(normalize=True)
print (s)
V311            V290
MIDDLE HALF     POOR              0.444444
                AVERAGE           0.333333
                GOOD              0.111111
                NK-UNASCERTAIN    0.111111
NK-UNASCERTAIN  POOR              1.000000
TOP QUARTER     AVERAGE           0.500000
                GOOD              0.250000
                POOR              0.250000
Name: V290, dtype: float64

EDIT1:

If want all missing categories too:

s = df.groupby('V311')['V290'].value_counts()
s = s.reindex(pd.MultiIndex.from_product(s.index.levels), fill_value=0)
print (s)
MIDDLE HALF     AVERAGE           3
                GOOD              1
                NK-UNASCERTAIN    1
                POOR              4
NK-UNASCERTAIN  AVERAGE           0
                GOOD              0
                NK-UNASCERTAIN    0
                POOR              1
TOP QUARTER     AVERAGE           2
                GOOD              1
                NK-UNASCERTAIN    0
                POOR              1
Name: V290, dtype: int64


问:
how can we use OWASP ZAP tool to check the validation quality of an application
I want to check the quality of login page validation. So can I use OWASP zap to achieve this. I want to regonice the weak password as well as generation of weak session tokens, error messages and etc. Is it possible in Zed Attack Proxy</p>

答:
You can use Zap passive scan for some of those things. If you share more information about your setup, I can help you with adding Zap to your CI.

Please note that Zap could not help you configure a password policy. It is not a good practice to run Zap in production. So I would not use it to test live user password quality.


问:
Spring boot, read yml properties via integration test case
Hi I am using Spring Boot, I want to inject the values of the .yml file in the Bean. I have written the integration test case but looks like via Integration test case it not injecting the values.

Problem is value of urls and keyspaceApp is null

Bean

```<code>    @ConfigurationProperties(prefix="cassandra")
public class TestBean {

    @Value("${urls}")
    private String urls;

    @Value("${keyspaceApp}")
    private String app;

    public void print() {
        System.out.println(urls);
        System.out.println(app);
    }

    public String getUrls() {
        return urls;
    }

    public void setUrls(String urls) {
        this.urls = urls;
    }
}
</code>```

Integration Test case

```<code>@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = TestBean.class)
@IntegrationTest
public class CassandraClientTest {

    @Autowired
    private TestBean bean;

    @Test
    public void test() {
        bean.print();
    }
}
</code>```

Application yml file

```<code>cassandra:
  urls: lllaaa.com
  keyspaceApp: customer
  createDevKeyspace: true
</code>```

答:
SpringApplicationConfiguration is deprecated in spring [Spring Boot v1.4.x] and removed in: [Spring Boot v1.5.x]. So, this is an updated answer.

MyTestClass class is like:

```<code>import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.ConfigFileApplicationContextInitializer;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringRunner;
import static org.assertj.core.api.Assertions.assertThat;

@RunWith(SpringRunner.class)
@ContextConfiguration(classes = MyConfiguration.class, initializers = ConfigFileApplicationContextInitializer.class)
public class MyTestClass {
    @Autowired
    private MyYmlProperties myYmlProperties;

    @Test
    public void testSpringYmlProperties() {
        assertThat(myYmlProperties.getProperty()).isNotEmpty();
    }
}
</code>```

MyYmlProperties class is like:

```<code>import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;

@Configuration
@ConfigurationProperties(prefix = "my")
public class MyYmlProperties {
    private String property;
    public String getProperty() { return property; }
    public void setProperty(String property) { this.property = property; }
}
</code>```

My application.yml is like:

```<code>my:
  property: Hello
</code>```

Finally MyConfiguration is really empty :-) you can fill it with what you want:

```<code>import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Configuration;

@Configuration
@EnableConfigurationProperties(value = MyYmlProperties.class)
public class MyConfiguration {
}
</code>```

Body:
Hi I am using Spring Boot, I want to inject the values of the .yml file in the Bean. I have written the integration test case but looks like via Integration test case it not injecting the values.

Problem is value of urls and keyspaceApp is null

Bean

    @ConfigurationProperties(prefix="cassandra")
public class TestBean {

    @Value("${urls}")
    private String urls;

    @Value("${keyspaceApp}")
    private String app;

    public void print() {
        System.out.println(urls);
        System.out.println(app);
    }

    public String getUrls() {
        return urls;
    }

    public void setUrls(String urls) {
        this.urls = urls;
    }
}

Integration Test case

@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = TestBean.class)
@IntegrationTest
public class CassandraClientTest {

    @Autowired
    private TestBean bean;

    @Test
    public void test() {
        bean.print();
    }
}

Application yml file

cassandra:
  urls: lllaaa.com
  keyspaceApp: customer
  createDevKeyspace: true

Body:
SpringApplicationConfiguration is deprecated in spring [Spring Boot v1.4.x] and removed in: [Spring Boot v1.5.x]. So, this is an updated answer.

MyTestClass class is like:

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.ConfigFileApplicationContextInitializer;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringRunner;
import static org.assertj.core.api.Assertions.assertThat;

@RunWith(SpringRunner.class)
@ContextConfiguration(classes = MyConfiguration.class, initializers = ConfigFileApplicationContextInitializer.class)
public class MyTestClass {
    @Autowired
    private MyYmlProperties myYmlProperties;

    @Test
    public void testSpringYmlProperties() {
        assertThat(myYmlProperties.getProperty()).isNotEmpty();
    }
}

MyYmlProperties class is like:

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;

@Configuration
@ConfigurationProperties(prefix = "my")
public class MyYmlProperties {
    private String property;
    public String getProperty() { return property; }
    public void setProperty(String property) { this.property = property; }
}

My application.yml is like:

my:
  property: Hello

Finally MyConfiguration is really empty :-) you can fill it with what you want:

import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Configuration;

@Configuration
@EnableConfigurationProperties(value = MyYmlProperties.class)
public class MyConfiguration {
}


问:
How to convert SDK PageMod() to Webextension
I use pageMod() in my Firefox SDK app, and i want to convert to Webextension.

I declare on top on my background js file:

```<code>var pageMod = require("sdk/page-mod");
</code>```

I have undesrtood in Webextension is declared in manifest.json

```<code>"content_scripts": [
    {
      "matches": ["*://*.mytestsite.com/*"],
      "js": ["background.js"]
    }
  ]
</code>```

But i call pageMod() inside my background script and i have a lot of attachment and other. I dont know how i can convert this.

For example what i want convert:

```<code>pageMod.PageMod({
  include: "*.mytestsite.com",
  contentScriptFile: [self.data.url("jquery-2.0.3.min.js"), self.data.url("jquery-ui.min.js"), self.data.url("site_modal_min.js"), self.data.url("timerreview.js")],
  onAttach: function onAttach(worker) {
</code>```

How use my PageMod() call with Webxtension

答:
Please note that in manifest.json, you cannot have background.js inside of a content_scripts tag. You would instead do it like this (assuming your match selector for the domain is correct):

```<code>"background": {
    "scripts": ["background.js"]
},

"content_scripts": [
  {
    "matches": ["*://*.mytestsite.com/*"],
    "js": ["timerreview.js", "jquery.js"]
  }
]
</code>```

If you want to communicate (variables, etc) use messaging between the background script and the content script. This is especially useful since most of the WebExtensions API is only available for background scripts.

In the content script, add:

```<code>// Listen for messages from the background script
browser.runtime.onMessage.addListener(onMessage);

function onMessage(message) {
    switch(message.action)
        case "testAction":
            testAction(message.data);
            break;
        default:
            break;
    }
}

function sendMessage(action, data){
    browser.runtime.sendMessage({"action": action, "data": data});
}
</code>```

In the background script, add:

```<code>// listen for messages from the content or options script
browser.runtime.onMessage.addListener(function(message) {
    switch (message.action) {
        case "actionFromContent":
            doSomething(); // message.data is not needed
            break;
        default:
            break;
    }
});

// See also https://developer.mozilla.org/en-US/Add-ons/WebExtensions/API/Tabs/sendMessage
function sendMessage(action, data){
    function logTabs(tabs) {
        for (tab of tabs) {
            browser.tabs.sendMessage(tab.id, {"action": action, "data": data}).catch(function(){
                onError("failed to execute " + action + "with data " + data);
            });
        }
    }

    browser.tabs.query({currentWindow: true, active: true}).then(logTabs, onError);
}

function onError(error){
    console.error(error);
}
</code>```

Now you can use:

```<code>sendMessage("actionFromContent") from within the content script to send a message to the background script
sendMessage("testAction", "someData") from within the background script to the active content script (the active tab)
</code>```

Body:
I use pageMod() in my Firefox SDK app, and i want to convert to Webextension.

I declare on top on my background js file:

var pageMod = require("sdk/page-mod");

I have undesrtood in Webextension is declared in manifest.json

"content_scripts": [
    {
      "matches": ["*://*.mytestsite.com/*"],
      "js": ["background.js"]
    }
  ]

But i call pageMod() inside my background script and i have a lot of attachment and other. I dont know how i can convert this.

For example what i want convert:

pageMod.PageMod({
  include: "*.mytestsite.com",
  contentScriptFile: [self.data.url("jquery-2.0.3.min.js"), self.data.url("jquery-ui.min.js"), self.data.url("site_modal_min.js"), self.data.url("timerreview.js")],
  onAttach: function onAttach(worker) {

How use my PageMod() call with Webxtension

Body:
Please note that in manifest.json, you cannot have background.js inside of a content_scripts tag. You would instead do it like this (assuming your match selector for the domain is correct):

"background": {
    "scripts": ["background.js"]
},

"content_scripts": [
  {
    "matches": ["*://*.mytestsite.com/*"],
    "js": ["timerreview.js", "jquery.js"]
  }
]

If you want to communicate (variables, etc) use messaging between the background script and the content script. This is especially useful since most of the WebExtensions API is only available for background scripts.

In the content script, add:

// Listen for messages from the background script
browser.runtime.onMessage.addListener(onMessage);

function onMessage(message) {
    switch(message.action)
        case "testAction":
            testAction(message.data);
            break;
        default:
            break;
    }
}

function sendMessage(action, data){
    browser.runtime.sendMessage({"action": action, "data": data});
}

In the background script, add:

// listen for messages from the content or options script
browser.runtime.onMessage.addListener(function(message) {
    switch (message.action) {
        case "actionFromContent":
            doSomething(); // message.data is not needed
            break;
        default:
            break;
    }
});

// See also https://developer.mozilla.org/en-US/Add-ons/WebExtensions/API/Tabs/sendMessage
function sendMessage(action, data){
    function logTabs(tabs) {
        for (tab of tabs) {
            browser.tabs.sendMessage(tab.id, {"action": action, "data": data}).catch(function(){
                onError("failed to execute " + action + "with data " + data);
            });
        }
    }

    browser.tabs.query({currentWindow: true, active: true}).then(logTabs, onError);
}

function onError(error){
    console.error(error);
}

Now you can use:

sendMessage("actionFromContent") from within the content script to send a message to the background script
sendMessage("testAction", "someData") from within the background script to the active content script (the active tab)


问:
Regex: find text between @ and the first occuring space/sign
I'm looking for a way to find a pattern in a string.

Input is: Could you do that for me @jdoe?

Expected result: @jdoe

Requirements:

Needs to start with @ sign

Needs to stop at space or special characters like ,.?! hello @jdoe, how are you?

Also needs to stop at end of sentence like hello @jdoe

Minimum length is after @ sign is 1 character

Characters after @ sign are a-z or A-Z or both

What i've got at the moment is: @([^"]*)([^\s]+)

This regex does start with the @ sign, stops after a space but continues whenever I keep on typing after that first occurring space sign. Can someone help me trying to find a way to create a regex which suits my requirements?

答:
Here's a quick one you can play with:

@\w+

https://regex101.com/r/ZuifZb/1

Be aware that \w matches a-z A-Z 0-9 and _.

If you only want a-z A-Z, you can use:

@[a-zA-Z]+

If you don't want 'Hello @test1' to be a match (@test), you can use negative lookahead:

@[a-zA-Z]+(?!\w)


问:
React Redirect will redirect to 404 page if query param is inserted by hashHistory
There is a problem when using hashHistory provided by react-router on adding query param to url:

Router - react-router@3.2.0

```<code><Router history={hashHistory}>
    <Route path="home" component={Home} />
    <Route path="contact" component={Contact} />
    <Redirect from="*" to="/home" />
</Router>
</code>```

Adding query param with hashHistory:

JS

```<code>hashHistory.push({
    query: {
        someParam: 'paramValue'
    }
});
</code>```

Scenario

I am on /contact page and on click i want to add query param someParam to the url. I use above code with hashHistory.
Result of this action is redirection to /home?someParam=paramValue.

It seems that method push(), provided only with query, will treat new url as /. So being that as it is, Redirect will go to home with give parameter.

答:
Solution

To avoid being redirected to /home or any other page that is set as redirect page, pathname needs to be provided for push() method:

JS

```<code>const currentLocation = hashHistory.getCurrentLocation();

hashHistory.push({
    pathname: currentLocation.pathname,
    query: {
        someParam: 'paramValue'
    }
});
</code>```

We can extract current path from hashHistory's getCurrentLocation() method.

Body:
There is a problem when using hashHistory provided by react-router on adding query param to url:

Router - react-router@3.2.0

<Router history={hashHistory}>
    <Route path="home" component={Home} />
    <Route path="contact" component={Contact} />
    <Redirect from="*" to="/home" />
</Router>

Adding query param with hashHistory:

JS

hashHistory.push({
    query: {
        someParam: 'paramValue'
    }
});

Scenario

I am on /contact page and on click i want to add query param someParam to the url. I use above code with hashHistory.
Result of this action is redirection to /home?someParam=paramValue.

It seems that method push(), provided only with query, will treat new url as /. So being that as it is, Redirect will go to home with give parameter.

Body:
Solution

To avoid being redirected to /home or any other page that is set as redirect page, pathname needs to be provided for push() method:

JS

const currentLocation = hashHistory.getCurrentLocation();

hashHistory.push({
    pathname: currentLocation.pathname,
    query: {
        someParam: 'paramValue'
    }
});

We can extract current path from hashHistory's getCurrentLocation() method.


问:
Appending span next to clicked link
I'm aiming to auto append information to a form based on a users click.

Specifically when a user clicks one of the following 'Book' links:

I want a information from the hidden span next to it to be auto populated into the form input labeled 'Course':

I'm planning to use a variable that gets created on click and then appended to the form, however I don't know how to create a variable which targets a sibling span.

JSfiddle to demonstrate:
https://jsfiddle.net/cm4Lu2ch/

$('.mailenquiry').click(function(e) {
  var nearestspan = 'How do I target the hidden span next to the clicked on link?'
  $('.custom-contact div:nth-of-type(2) input').val(nearestspan);
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>table.table td span {
  display: none;
}</code>```

      Date
      Module
      Price
      Venue
      Enquire

      Mon 11/Dec/17
      Foo 1
      £55 (+VAT & DVSA Upload)
      London
      BookEnquiry about Foo 1 on Mon 11/Dec/17

      Tue 12/Dec/17
      Foo 2
      £55 (+VAT & DVSA Upload)
      London
      BookEnquiry about Foo 2 on Tue 12/Dec/17

<form class="custom-contact" action="/my-handling-form-page" method="post">

    Name:
    <input type="text" id="name" name="user_name">

    Course:
    <input type="text" id="name" name="user_name">

    E-mail:
    <input type="email" id="mail" name="user_mail">

    Message:
    <textarea id="msg" name="user_message"></textarea>

</form>```

答:
$('.mailenquiry').click(function(e) {
  var nearestspan = $(this).next().html();
  $('.custom-contact div:nth-of-type(2) input').val(nearestspan);
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>table.table td span {
  display: none;
}</code>```

      Date
      Module
      Price
      Venue
      Enquire

      Mon 11/Dec/17
      Foo 1
      £55 (+VAT & DVSA Upload)
      London
      BookEnquiry about Foo 1 on Mon 11/Dec/17

      Tue 12/Dec/17
      Foo 2
      £55 (+VAT & DVSA Upload)
      London
      BookEnquiry about Foo 2 on Tue 12/Dec/17

<form class="custom-contact" action="/my-handling-form-page" method="post">

    Name:
    <input type="text" id="name" name="user_name">

    Course:
    <input type="text" id="name" name="user_name">

    E-mail:
    <input type="email" id="mail" name="user_mail">

    Message:
    <textarea id="msg" name="user_message"></textarea>

</form>```

Title: Appending span next to clicked link

Body:
I'm aiming to auto append information to a form based on a users click.

Specifically when a user clicks one of the following 'Book' links:

I want a information from the hidden span next to it to be auto populated into the form input labeled 'Course':

I'm planning to use a variable that gets created on click and then appended to the form, however I don't know how to create a variable which targets a sibling span.

JSfiddle to demonstrate:
https://jsfiddle.net/cm4Lu2ch/

$('.mailenquiry').click(function(e) {
  var nearestspan = 'How do I target the hidden span next to the clicked on link?'
  $('.custom-contact div:nth-of-type(2) input').val(nearestspan);
});

table.table td span {
  display: none;
}

      Date
      Module
      Price
      Venue
      Enquire

      Mon 11/Dec/17
      Foo 1
      £55 (+VAT & DVSA Upload)
      London
      BookEnquiry about Foo 1 on Mon 11/Dec/17

      Tue 12/Dec/17
      Foo 2
      £55 (+VAT & DVSA Upload)
      London
      BookEnquiry about Foo 2 on Tue 12/Dec/17

<form class="custom-contact" action="/my-handling-form-page" method="post">

    Name:
    <input type="text" id="name" name="user_name">

    Course:
    <input type="text" id="name" name="user_name">

    E-mail:
    <input type="email" id="mail" name="user_mail">

    Message:
    <textarea id="msg" name="user_message"></textarea>

</form>

Body:
$('.mailenquiry').click(function(e) {
  var nearestspan = $(this).next().html();
  $('.custom-contact div:nth-of-type(2) input').val(nearestspan);
});

table.table td span {
  display: none;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<table id="theTable" class="footable table outerBorder footable-loaded">
  <thead>
    <tr>
      <th id="thCol0" data-type="alpha">Date</th>
      <th id="thCol1" data-type="alpha">Module</th>
      <th id="thCol2" data-type="alpha">Price</th>
      <th id="thCol3" data-type="alpha">Venue</th>
      <th>Enquire</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>Mon 11/Dec/17</td>
      <td>Foo 1</td>
      <td>£55 (+VAT &amp; DVSA Upload)</td>
      <td>London</td>
      <td><a class="mailenquiry" href="#contact-now">Book</a><span>Enquiry about Foo 1 on Mon 11/Dec/17</span></td>
    </tr>
    <tr>
      <td>Tue 12/Dec/17</td>
      <td>Foo 2</td>
      <td>£55 (+VAT &amp; DVSA Upload)</td>
      <td>London</td>
      <td><a class="mailenquiry" href="#contact-now">Book</a><span>Enquiry about Foo 2 on Tue 12/Dec/17</span></td>
    </tr>
  </tbody>
</table>
<br><br>
<a id="contact-now"></a>
<form class="custom-contact" action="/my-handling-form-page" method="post">
  <div>
    <label for="name">Name:</label>
    <input type="text" id="name" name="user_name">
  </div>
  <div>
    <label for="name">Course:</label>
    <input type="text" id="name" name="user_name">
  </div>
  <div>
    <label for="mail">E-mail:</label>
    <input type="email" id="mail" name="user_mail">
  </div>
  <div>
    <label for="msg">Message:</label>
    <textarea id="msg" name="user_message"></textarea>
  </div>
</form>


问:
Haskell: accessing lists from back
Today I started learning Haskell. I'm kind of new with functional languages, and I'm enjoying Haskell a lot.

However I've got a question about its design which is bugging me: from what I understood so far it looks like accessing an element to the back of a list is a lot more complicated that accessing the element to the front (something like xs:x where xs::[a] and x::a doesn't seem to be possible).

(From what I understood) it's possible to append a list to another one (xs++[a]), but it'll cost more at run time (it requires to traverse the whole list) and it cannot be used for pattern matching.

Why is Haskell missing such operation?

答:
The list data type in Haskell is a linked list, so a lookup uses O(n) time. If you need frequent access to the back of a list you might want to take a look at Data.Sequence
which has O(1) add to beginning and end.

To answer why Haskell uses this data structure as a "standard container" (like C and arrays), it's because Haskell is a pure functional language, and therefore has a preference to purely functional data structures (immutable and persistent.) For further reading look at this wiki page. To use non-functional data structures in Haskell would require it to be inside the IO or ST monad.

Title: Haskell: accessing lists from back


问:
How do I view model.feature_importances_ output with the names of the features?
I've built a DecisionTreeClassifier model in python and would like to see the importance of each feature.  As I'm using sklearn I've converted all my classes to numbers. Here's how I've imported the data:

```<code>raw_data = pd.read_csv('Video_Games_Sales_as_at_22_Dec_2016.csv')
no_na_df = raw_data.dropna(how='any')
</code>```

after getting rid of NAs I created my DF for numeric conversion:

```<code>numeric_df = no_na_df.copy()
cols = ['Platform','Genre','Publisher','Developer','Rating']
numeric_df[cols] = numeric_df[cols].apply(lambda x: pd.factorize(x)[0]+1)
</code>```

Once that's done, I created the test and train split:

```<code>X = numeric_df.drop(['Name','Global_Sales_Bin','Global_Sales','NA_Sales','EU_Sales','JP_Sales','Other_Sales'], axis = 1)
y = numeric_df['Global_Sales_Bin']

X = np.array(X)
y = np.array(y)

X_train, X_test, y_train, y_test = train_test_split(X,y,test_size = 0.3, random_state = 0)
</code>```

ran the model etc, got my results, and then I wanted to see the importance of each feature:

```<code>model.feature_importances_
</code>```

which output this:

```<code>array([ 0.08518705,  0.07874186,  0.06322593,  0.08446309,  0.08410844,
        0.08097326,  0.07744228,  0.1851621 ,  0.23597441,  0.02472158])
</code>```

I don't know how to match up the features in the model with the numbers above. both 'X' and 'model' are stored as numpy arrays and the orginal dataframe has been cut down to fit the model so the features don't align properly. I think I might have to use a for loop and zip, but not sure how.

Thanks.

Body:
I've built a DecisionTreeClassifier model in python and would like to see the importance of each feature.  As I'm using sklearn I've converted all my classes to numbers. Here's how I've imported the data:

raw_data = pd.read_csv('Video_Games_Sales_as_at_22_Dec_2016.csv')
no_na_df = raw_data.dropna(how='any')

after getting rid of NAs I created my DF for numeric conversion:

numeric_df = no_na_df.copy()
cols = ['Platform','Genre','Publisher','Developer','Rating']
numeric_df[cols] = numeric_df[cols].apply(lambda x: pd.factorize(x)[0]+1)

Once that's done, I created the test and train split:

X = numeric_df.drop(['Name','Global_Sales_Bin','Global_Sales','NA_Sales','EU_Sales','JP_Sales','Other_Sales'], axis = 1)
y = numeric_df['Global_Sales_Bin']

X = np.array(X)
y = np.array(y)

X_train, X_test, y_train, y_test = train_test_split(X,y,test_size = 0.3, random_state = 0)

ran the model etc, got my results, and then I wanted to see the importance of each feature:

model.feature_importances_

which output this:

array([ 0.08518705,  0.07874186,  0.06322593,  0.08446309,  0.08410844,
        0.08097326,  0.07744228,  0.1851621 ,  0.23597441,  0.02472158])

I don't know how to match up the features in the model with the numbers above. both 'X' and 'model' are stored as numpy arrays and the orginal dataframe has been cut down to fit the model so the features don't align properly. I think I might have to use a for loop and zip, but not sure how.

Thanks.

Body:
This ended up working list(zip(X_columns, model.feature_importances_))

X_columns = X.columns

Output:

[('Platform', 0.085187050413710552),
 ('Year_of_Release', 0.078741862224430401),
 ('Genre', 0.063225925635322172),
 ('Publisher', 0.084463091000316695),
 ('Critic_Score', 0.084108440698256848),
 ('Critic_Count', 0.080973259803115372),
 ('User_Score', 0.077442278687036153),
 ('User_Count', 0.18516210213713488),
 ('Developer', 0.23597440837370295),
 ('Rating', 0.024721581026973961)]


问:
The Django make ORM query
```<code>class Task(models.Model):
    subject = models.CharField(max_length=256)
    description = models.TextField(max_length=1024)
    reward = models.PositiveIntegerField()
    begin_date = models.DateField()
    number_of_people = models.PositiveIntegerField(default=1)

class TaskDetail(models.Model):
    user = models.ForeignKey(User, related_name='tasks')
    task = models.ForeignKey(Task, related_name='tasks')
</code>```

This is a simple task assignment system model designed by me.
and I have a question.I attempt to make a user report that include the number of task user've done.but I don't know how to make ORM query.

```<code>users = User.objects.all
</code>```

Does anyone know how to solve this issue? Thx

答:
Let's assume that you are trying to count the tasks that a user with id=1 has accomplished.

```<code>the_user = User.objects.filter(id=1)  # Does not hit the database
data = TaskDetail.objects.filter(user__in=the_user) # It selects all tasks by the user
result = data.count()  #It hits the database to count
print(result)
</code>```

Here are the relevant docs.

However, you can just use one table -if this is the complete layout- and put the user ForeignKey to the table Task as a ManyToManyField.

The way you have built it, it is possible to have stray tasks because a user forgot to assign the task to himself.

Title: The Django make ORM query

Body:
class Task(models.Model):
    subject = models.CharField(max_length=256)
    description = models.TextField(max_length=1024)
    reward = models.PositiveIntegerField()
    begin_date = models.DateField()
    number_of_people = models.PositiveIntegerField(default=1)

class TaskDetail(models.Model):
    user = models.ForeignKey(User, related_name='tasks')
    task = models.ForeignKey(Task, related_name='tasks')

This is a simple task assignment system model designed by me.
and I have a question.I attempt to make a user report that include the number of task user've done.but I don't know how to make ORM query.

users = User.objects.all

Does anyone know how to solve this issue? Thx

Body:
Let's assume that you are trying to count the tasks that a user with id=1 has accomplished.

the_user = User.objects.filter(id=1)  # Does not hit the database
data = TaskDetail.objects.filter(user__in=the_user) # It selects all tasks by the user
result = data.count()  #It hits the database to count
print(result)

Here are the relevant docs.

However, you can just use one table -if this is the complete layout- and put the user ForeignKey to the table Task as a ManyToManyField.

The way you have built it, it is possible to have stray tasks because a user forgot to assign the task to himself.


问:
Getting a PhotoImage object from a tkinter label
Is there any way to get a tkinter.PhotoImage object from a tkinter.Label instance? I know there's this question, which has a partially satisfying answer, but I really need to get a PhotoImage object:

```<code>>>> import tkinter as tk
>>>
>>> root = tk.Tk()
>>>
>>> image1 = tk.PhotoImage(file="img.gif")
>>> image2 = tk.PhotoImage(file="img.gif")
>>>
>>> label = tk.Label(root, image=image1)
>>> label._image_ref = image1
>>> label.cget("image") == image2
False
</code>```

Is there perhaps a function which allows me to get an image object from a pyimage string? I.e. one obtained from label.cget("image")?

The answer is, apparantly, you can't. The closest you can get to doing this is getting the image source (file or data) and checking (probably by hashing) whether or not the two images are the same. tkinter.PhotoImage does not implement an __eq__, so you can't just compare two images for equal data. Here's a final example which solves the problem (mostly):

```<code>import hashlib
import os
import tkinter as tk

_BUFFER_SIZE = 65536

def _read_buffered(filename):
    """Read bytes from a file, in chunks.
    Arguments:
    - filename: str: The name of the file to read from.
    Returns:
    - bytes: The file's contents.
    """
    contents = []
    with open(filename, "rb") as fd:
        while True:
            chunk = fd.read(_BUFFER_SIZE)
            if not chunk:
                break
            contents.append(chunk)
        return bytes().join(contents)

def displays_image(image_file, widget):
    """Check whether or not 'widget' displays 'image_file'.
    Reading an entire image from a file is computationally expensive!
    Note that this function will always return False if 'widget' is not mapped.
    This doesn't work for images that were initialized from bytes.
    Arguments:
    - image_file: str: The path to an image file.
    - widget: tk.Widget: A tkinter widget capable of displaying images.
    Returns:
    - bool: True if the image is being displayed, else False.
    """
    expected_hash = hashlib.sha256(_read_buffered(image_file)).hexdigest()
    if widget.winfo_ismapped():
        widget_file = widget.winfo_toplevel().call(
            widget.cget("image"), "cget", "-file"
        )
        if os.path.getsize(widget_file) != os.path.getsize(image_file):
            # Size differs, the contents can never be the same.
            return False
        image_hash = hashlib.sha256(
            _read_buffered(widget_file)
        ).hexdigest()
        return image_hash == expected_hash
</code>```

答:
As a tkinter is a wrapper over tk , so does PhotoImage in same fashion is a wrapper over image. And it's clear that you can't just move backwards and create a PhotoImage, from that image.

But still, because you can execute tk commands and both PhotoImage and image have similar structure, your best bet would be something like this:

```<code>import tkinter as tk

root = tk.Tk()

image1 = tk.PhotoImage(file="img.gif")
image2 = tk.PhotoImage(file="img.gif")

label = tk.Label(root, image=image1)
label._image_ref = image1

foo = root.call(label.cget('image'), 'cget', '-file')
bar = image2['file']
print('1st image:\t%s\n2nd image:\t%s\nEqual:\t%r' % (foo, bar, foo == bar))
</code>```

tk image

tk photo

Body:
Is there any way to get a tkinter.PhotoImage object from a tkinter.Label instance? I know there's this question, which has a partially satisfying answer, but I really need to get a PhotoImage object:

>>> import tkinter as tk
>>>
>>> root = tk.Tk()
>>>
>>> image1 = tk.PhotoImage(file="img.gif")
>>> image2 = tk.PhotoImage(file="img.gif")
>>>
>>> label = tk.Label(root, image=image1)
>>> label._image_ref = image1
>>> label.cget("image") == image2
False

Is there perhaps a function which allows me to get an image object from a pyimage string? I.e. one obtained from label.cget("image")?

The answer is, apparantly, you can't. The closest you can get to doing this is getting the image source (file or data) and checking (probably by hashing) whether or not the two images are the same. tkinter.PhotoImage does not implement an __eq__, so you can't just compare two images for equal data. Here's a final example which solves the problem (mostly):

import hashlib
import os
import tkinter as tk

_BUFFER_SIZE = 65536

def _read_buffered(filename):
    """Read bytes from a file, in chunks.
    Arguments:
    - filename: str: The name of the file to read from.
    Returns:
    - bytes: The file's contents.
    """
    contents = []
    with open(filename, "rb") as fd:
        while True:
            chunk = fd.read(_BUFFER_SIZE)
            if not chunk:
                break
            contents.append(chunk)
        return bytes().join(contents)

def displays_image(image_file, widget):
    """Check whether or not 'widget' displays 'image_file'.
    Reading an entire image from a file is computationally expensive!
    Note that this function will always return False if 'widget' is not mapped.
    This doesn't work for images that were initialized from bytes.
    Arguments:
    - image_file: str: The path to an image file.
    - widget: tk.Widget: A tkinter widget capable of displaying images.
    Returns:
    - bool: True if the image is being displayed, else False.
    """
    expected_hash = hashlib.sha256(_read_buffered(image_file)).hexdigest()
    if widget.winfo_ismapped():
        widget_file = widget.winfo_toplevel().call(
            widget.cget("image"), "cget", "-file"
        )
        if os.path.getsize(widget_file) != os.path.getsize(image_file):
            # Size differs, the contents can never be the same.
            return False
        image_hash = hashlib.sha256(
            _read_buffered(widget_file)
        ).hexdigest()
        return image_hash == expected_hash

Body:
As a tkinter is a wrapper over tk , so does PhotoImage in same fashion is a wrapper over image. And it's clear that you can't just move backwards and create a PhotoImage, from that image.

But still, because you can execute tk commands and both PhotoImage and image have similar structure, your best bet would be something like this:

import tkinter as tk

root = tk.Tk()

image1 = tk.PhotoImage(file="img.gif")
image2 = tk.PhotoImage(file="img.gif")

label = tk.Label(root, image=image1)
label._image_ref = image1

foo = root.call(label.cget('image'), 'cget', '-file')
bar = image2['file']
print('1st image:\t%s\n2nd image:\t%s\nEqual:\t%r' % (foo, bar, foo == bar))

tk image

tk photo


问:
How to consume rest service with basic auth from angular 4
Hi present i am developing angular 4 application. In this we have to consume rest service with basic authorization. so please help how to consume rest service with basic auth.

thanks in advance.

答:
.this is what i do usually for auth and store the token in my localstorage ..
it consume a WebAPI Asp.net REst endpint (but it is indifferent) .. only one things..this is in Content - Type : application/x-www-form-urlencoded

so if you want to use the normal application/json ..you simply DON'T HAVE TO OVERRIDE the headers of the login calls (

```<code>let headersForm = new Headers();
    headersForm.append('Content-Type', 'application/x-www-form-urlencoded');
</code>```

)

```<code>import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs/Rx';
import { Auth, LoginData } from '../models/index';
import { environment } from '../../../environments/environment';
import { URLSearchParams, RequestOptions } from '@angular/http';

@Injectable()
export class AuthService {
  private loggedIn = false;

  constructor(private http: HttpClient) {
    this.loggedIn = !!localStorage.getItem('auth_token');
  }

  /**
   * METHOD TO DO LOGIN TO BACK END and STORE IN LOCALSTORAGE
   * @return {Auth} Auth data
   */
  public Login(data: LoginData): Observable<Auth> {

    let headersForm = new Headers();
    headersForm.append('Content-Type', 'application/x-www-form-urlencoded');

    let dataForm = new URLSearchParams();

    dataForm.append('grant_type', 'password');
    dataForm.append('userName', data.userName);
    dataForm.append('password', data.password);
    let body = dataForm.toString();
    //  let body = 'userName=' + data.userName + '&password=' + data.password + '&grant_type=password';

    //var encoded = "grant_type=password&userName=" + data.userName + "&password=" + data.password;
    return this.http.post<Auth>(environment.API_URL + 'Token', body)

      .map((res) => {
        if (res && res.access_token) {
          localStorage.setItem('AuthData', JSON.stringify({ access_token: res.access_token, username: res.userName }));
          this.loggedIn = true;

          if (localStorage.getItem("Settings") === null) {
            let settingObj = {
              unit: 'min',
              refreshTime: 1,
              help: false,
              autoRefresh: false
            }

            localStorage.setItem('Settings', JSON.stringify(settingObj));
          }

        }

        return res as Auth;
      });
  }

  /**
   * MEthod to Log Out
   */
  public logout(): Observable<void> {
    return this.http.post(environment.API_URL + 'Account/LogOut',{data:1}).map(() => {
      localStorage.removeItem('AuthData');
      localStorage.removeItem('CurrentUser');
      localStorage.removeItem('filterDashboard');
      this.loggedIn = false;

    });

  }

  /**
   *  Method to know if is logged or not
   */
  public isLoggedIn(): boolean {
    return this.loggedIn;
  }

  /**
   *  Method to set logged
   */
  public setLoggd() {
    this.loggedIn = true;
  }

}
</code>```

and Auth.ts class file:

```<code>export class Auth {
    public access_token: string;
    public userName: string;

}
</code>```

Hope it helps you!

Body:
.this is what i do usually for auth and store the token in my localstorage ..
it consume a WebAPI Asp.net REst endpint (but it is indifferent) .. only one things..this is in Content - Type : application/x-www-form-urlencoded

so if you want to use the normal application/json ..you simply DON'T HAVE TO OVERRIDE the headers of the login calls (

let headersForm = new Headers();
    headersForm.append('Content-Type', 'application/x-www-form-urlencoded');

)

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs/Rx';
import { Auth, LoginData } from '../models/index';
import { environment } from '../../../environments/environment';
import { URLSearchParams, RequestOptions } from '@angular/http';

@Injectable()
export class AuthService {
  private loggedIn = false;

  constructor(private http: HttpClient) {
    this.loggedIn = !!localStorage.getItem('auth_token');
  }

  /**
   * METHOD TO DO LOGIN TO BACK END and STORE IN LOCALSTORAGE
   * @return {Auth} Auth data
   */
  public Login(data: LoginData): Observable<Auth> {

    let headersForm = new Headers();
    headersForm.append('Content-Type', 'application/x-www-form-urlencoded');

    let dataForm = new URLSearchParams();

    dataForm.append('grant_type', 'password');
    dataForm.append('userName', data.userName);
    dataForm.append('password', data.password);
    let body = dataForm.toString();
    //  let body = 'userName=' + data.userName + '&password=' + data.password + '&grant_type=password';

    //var encoded = "grant_type=password&userName=" + data.userName + "&password=" + data.password;
    return this.http.post<Auth>(environment.API_URL + 'Token', body)

      .map((res) => {
        if (res && res.access_token) {
          localStorage.setItem('AuthData', JSON.stringify({ access_token: res.access_token, username: res.userName }));
          this.loggedIn = true;

          if (localStorage.getItem("Settings") === null) {
            let settingObj = {
              unit: 'min',
              refreshTime: 1,
              help: false,
              autoRefresh: false
            }

            localStorage.setItem('Settings', JSON.stringify(settingObj));
          }

        }

        return res as Auth;
      });
  }

  /**
   * MEthod to Log Out
   */
  public logout(): Observable<void> {
    return this.http.post(environment.API_URL + 'Account/LogOut',{data:1}).map(() => {
      localStorage.removeItem('AuthData');
      localStorage.removeItem('CurrentUser');
      localStorage.removeItem('filterDashboard');
      this.loggedIn = false;

    });

  }

  /**
   *  Method to know if is logged or not
   */
  public isLoggedIn(): boolean {
    return this.loggedIn;
  }

  /**
   *  Method to set logged
   */
  public setLoggd() {
    this.loggedIn = true;
  }

}

and Auth.ts class file:

export class Auth {
    public access_token: string;
    public userName: string;

}

Hope it helps you!


问:
resolution needed, argument 1 must have a 'write' method. make a dictionary into a csv
i cant seem to get my code working its keeps giving me the same 'argument 1 must have a 'write' method </p>

```<code>import csv
tank1 = [{'tank':1, 'product':['condenstate'], 'temp':12,'ullage':21000, 'level':70000}]
tank2 = [{'tank':2, 'product':['condenstate'], 'temp':12,'ullage':21000, 'level':70000}]
key1 = tank1,tank2[0].keys()
with open('motherwell.csv','w',newline='') as output_file:
    writer = csv.writer

    writer = csv.writer(output_file, key1)
    writer = csv.writer(key1)
</code>```

答:
Not certain what you are trying to achieve, but you probably need just this:

```<code>with open('motherwell.csv','w', newline='') as output_file:
    writer = csv.writer(output_file)
    writer.writerow(tank1)
    writer.writerow(tank2)
</code>```

Note:  this is for Python 3, for Python 2 you need to open the file as binary (wb).

Body:
i cant seem to get my code working its keeps giving me the same 'argument 1 must have a 'write' method

import csv
tank1 = [{'tank':1, 'product':['condenstate'], 'temp':12,'ullage':21000, 'level':70000}]
tank2 = [{'tank':2, 'product':['condenstate'], 'temp':12,'ullage':21000, 'level':70000}]
key1 = tank1,tank2[0].keys()
with open('motherwell.csv','w',newline='') as output_file:
    writer = csv.writer

    writer = csv.writer(output_file, key1)
    writer = csv.writer(key1)

Body:
Not certain what you are trying to achieve, but you probably need just this:

with open('motherwell.csv','w', newline='') as output_file:
    writer = csv.writer(output_file)
    writer.writerow(tank1)
    writer.writerow(tank2)

Note:  this is for Python 3, for Python 2 you need to open the file as binary (wb).


问:
Is there a way to compile program with RAD Studio XE7 to work in windows 98?
I uninstall delphi7 For a while and i install RAD Studio XE7

Is there a way to compile program with RAD Studio to work in windows 98 without reinstall delphi 7?

答:
You cannot target Windows 9x using modern Delphi. There are plenty of reasons for this but the big one is Unicode. Since Delphi 2009 the Delphi libraries target the Unicode variant of the Win32 API. Windows 9x does not support Unicode.

If you wish to continue targeting Windows 9x, do so the way you always have done. Use Delphi 7.


问:
OpenLayers function to switch many layers on by a loop
I have a layer switch control contains (dates) named (yyyy-mm-dd_hhmmss) and they are working properly when I click on them.

Also, I have labels to enter(start) and(end) and a button to loop layers between these two values.

What I need is a function  to make this button activate the layers (dates) or make them switched on by loop with interval

PS: here we can use title as refernce and displayInLayerSwitcher,true and setVisible(true)

My code as follows

singleLayer = {}
singleLayer['1'] = new ol.layer.Tile({
  title: "1",
   baseLayer: false,
   visible: false,
   source: new ol.source.XYZ({
   projection: 'EPSG:4326',
    wrapX: false,
    url: 'folder/yyyy-mm-dd_hhmmss/{z}/{x}/{-y}.png'
   })
 })
singleLayer['2'] = new ol.layer.Tile({
  title: "2",
   baseLayer: false,
   visible: false,
   source: new ol.source.XYZ({
   projection: 'EPSG:4326',
    wrapX: false,
    url: 'folder/yyyy-mm-dd_hhmmss/{z}/{x}/{-y}.png'
   })
  })

 singleLayer['3'] = new ol.layer.Tile({
   title: "3",
    baseLayer: false,
    visible: false,
    source: new ol.source.XYZ({
    projection: 'EPSG:4326',
     wrapX: false,
     url: 'folder/yyyy-mm-dd_hhmmss/{z}/{x}/{-y}.png'
    })
  })
      })

 var dates = new ol.layer.Group({
  openInLayerSwitcher: false,
  visible: false,
  layers:[
   singleLayer['1'],
   singleLayer['2'],
   singleLayer['3'],
  ]
 });```
<pre class="snippet-code-html lang-html prettyprint-override"><code><p>Loop Layers<p>
              <p>From date: <input type="text" name="fromdate" id="fromdate" value="yyyy-mm-dd_hhmmss"></p>
              <p>To date: <input type="text" name="todate" id="todate" value="yyyy-mm-dd_hhmmss"></p>
              <button onclick="loopLayer()">Loop layer by time interval</button>

function loopLayer() {
  .........
  }</code>```

答:
```<code>var time = new ol.layer.Group({ ....... });

let intervalHandle = null;
let activeLayerIndex = -1;

function startAnimation() {
  // check if interval is already running
  if (!intervalHandle) {
    activeLayerIndex = 0;
    // make sure all layers of the group are hidden
    time.getLayers().forEach(layer => layer.setVisible(false));

    intervalHandle = setInterval(function() {
      const allLayers = time.getLayers();
      if (activeLayerIndex >= allLayers.getLength()) {
        // we reached the end, stop animating
        stopAnimation();
      }
      allLayers.item(activeLayerIndex).setVisible(true);

      if (activeLayerIndex > 0) {
        // hide the previous layer
        allLayers.item(activeLayerIndex -1).setVisible(false);
      }
      activeLayerIndex += 1;
    }, 500 /* milliseconds */);
  }
}

function stopAnimation() {
  if(intervalHandle) {
    clearInterval(intervalHandle);
    intervalHandle = null;
  }
}
</code>```

Body:
I have a layer switch control contains (dates) named (yyyy-mm-dd_hhmmss) and they are working properly when I click on them.

Also, I have labels to enter(start) and(end) and a button to loop layers between these two values.

What I need is a function  to make this button activate the layers (dates) or make them switched on by loop with interval

PS: here we can use title as refernce and displayInLayerSwitcher,true and setVisible(true)

My code as follows

singleLayer = {}
singleLayer['1'] = new ol.layer.Tile({
  title: "1",
   baseLayer: false,
   visible: false,
   source: new ol.source.XYZ({
   projection: 'EPSG:4326',
    wrapX: false,
    url: 'folder/yyyy-mm-dd_hhmmss/{z}/{x}/{-y}.png'
   })
 })
singleLayer['2'] = new ol.layer.Tile({
  title: "2",
   baseLayer: false,
   visible: false,
   source: new ol.source.XYZ({
   projection: 'EPSG:4326',
    wrapX: false,
    url: 'folder/yyyy-mm-dd_hhmmss/{z}/{x}/{-y}.png'
   })
  })

 singleLayer['3'] = new ol.layer.Tile({
   title: "3",
    baseLayer: false,
    visible: false,
    source: new ol.source.XYZ({
    projection: 'EPSG:4326',
     wrapX: false,
     url: 'folder/yyyy-mm-dd_hhmmss/{z}/{x}/{-y}.png'
    })
  })
      })

 var dates = new ol.layer.Group({
  openInLayerSwitcher: false,
  visible: false,
  layers:[
   singleLayer['1'],
   singleLayer['2'],
   singleLayer['3'],
  ]
 });

Loop Layers

From date: <input type="text" name="fromdate" id="fromdate" value="yyyy-mm-dd_hhmmss">

To date: <input type="text" name="todate" id="todate" value="yyyy-mm-dd_hhmmss">

              <button onclick="loopLayer()">Loop layer by time interval</button>

function loopLayer() {
  .........
  }


答:
Couple ways to do this:

1) Go up a level to the parent

Go up to the parent() and find() the span, then get its text and store it in your nearestspan variable

```<code>$('.mailenquiry').click(function(e) {
  var nearestspan = $(this).parent().find('span').text();
  $('.custom-contact div:nth-of-type(2) input').val(nearestspan);
});
</code>```

$('.mailenquiry').click(function(e) {
  var nearestspan = $(this).parent().find('span').text();
  $('.custom-contact div:nth-of-type(2) input').val(nearestspan);
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>table.table td span {
  display: none;
}</code>```

      Date
      Module
      Price
      Venue
      Enquire

      Mon 11/Dec/17
      Foo 1
      £55 (+VAT & DVSA Upload)
      London
      BookEnquiry about Foo 1 on Mon 11/Dec/17

      Tue 12/Dec/17
      Foo 2
      £55 (+VAT & DVSA Upload)
      London
      BookEnquiry about Foo 2 on Tue 12/Dec/17

<form class="custom-contact" action="/my-handling-form-page" method="post">

    Name:
    <input type="text" id="name" name="user_name">

    Course:
    <input type="text" id="name" name="user_name">

    E-mail:
    <input type="email" id="mail" name="user_mail">

    Message:
    <textarea id="msg" name="user_message"></textarea>

</form>```
</div>
</div>
</p>

<hr>

<h2>2) Get the next element</h2>

<p>you can use <code>next()</code> and get the span that way</p>

```$('.mailenquiry').click(function(e) {
  var nearestspan = $(this).next().text();
  $('.custom-contact div:nth-of-type(2) input').val(nearestspan);
});
```

<p><div class="snippet" data-lang="js" data-hide="true" data-console="true" data-babel="false">
<div class="snippet-code snippet-currently-hidden">
<pre class="snippet-code-js lang-js prettyprint-override"><code>$('.mailenquiry').click(function(e) {
  var nearestspan = $(this).next().text();
  $('.custom-contact div:nth-of-type(2) input').val(nearestspan);
});</code>```

table.table td span {
  display: none;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<table id="theTable" class="footable table outerBorder footable-loaded">
  <thead>
    <tr>
      <th id="thCol0" data-type="alpha">Date</th>
      <th id="thCol1" data-type="alpha">Module</th>
      <th id="thCol2" data-type="alpha">Price</th>
      <th id="thCol3" data-type="alpha">Venue</th>
      <th>Enquire</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>Mon 11/Dec/17</td>
      <td>Foo 1</td>
      <td>£55 (+VAT & DVSA Upload)</td>
      <td>London</td>
      <td>Book<span>Enquiry about Foo 1 on Mon 11/Dec/17</span></td>
    </tr>
    <tr>
      <td>Tue 12/Dec/17</td>
      <td>Foo 2</td>
      <td>£55 (+VAT & DVSA Upload)</td>
      <td>London</td>
      <td>Book<span>Enquiry about Foo 2 on Tue 12/Dec/17</span></td>
    </tr>
  </tbody>
</table>
<br><br>

<form class="custom-contact" action="/my-handling-form-page" method="post">
  <div>
    <label for="name">Name:</label>
    <input type="text" id="name" name="user_name">
  </div>
  <div>
    <label for="name">Course:</label>
    <input type="text" id="name" name="user_name">
  </div>
  <div>
    <label for="mail">E-mail:</label>
    <input type="email" id="mail" name="user_mail">
  </div>
  <div>
    <label for="msg">Message:</label>
    <textarea id="msg" name="user_message"></textarea>
  </div>
</form></code>```

Title: Appending span next to clicked link

Body:
Couple ways to do this:

1) Go up a level to the parent

Go up to the parent() and find() the span, then get its text and store it in your nearestspan variable

$('.mailenquiry').click(function(e) {
  var nearestspan = $(this).parent().find('span').text();
  $('.custom-contact div:nth-of-type(2) input').val(nearestspan);
});

$('.mailenquiry').click(function(e) {
  var nearestspan = $(this).parent().find('span').text();
  $('.custom-contact div:nth-of-type(2) input').val(nearestspan);
});

table.table td span {
  display: none;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<table id="theTable" class="footable table outerBorder footable-loaded">
  <thead>
    <tr>
      <th id="thCol0" data-type="alpha">Date</th>
      <th id="thCol1" data-type="alpha">Module</th>
      <th id="thCol2" data-type="alpha">Price</th>
      <th id="thCol3" data-type="alpha">Venue</th>
      <th>Enquire</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>Mon 11/Dec/17</td>
      <td>Foo 1</td>
      <td>£55 (+VAT &amp; DVSA Upload)</td>
      <td>London</td>
      <td><a class="mailenquiry" href="#contact-now">Book</a><span>Enquiry about Foo 1 on Mon 11/Dec/17</span></td>
    </tr>
    <tr>
      <td>Tue 12/Dec/17</td>
      <td>Foo 2</td>
      <td>£55 (+VAT &amp; DVSA Upload)</td>
      <td>London</td>
      <td><a class="mailenquiry" href="#contact-now">Book</a><span>Enquiry about Foo 2 on Tue 12/Dec/17</span></td>
    </tr>
  </tbody>
</table>
<br><br>
<a id="contact-now"></a>
<form class="custom-contact" action="/my-handling-form-page" method="post">
  <div>
    <label for="name">Name:</label>
    <input type="text" id="name" name="user_name">
  </div>
  <div>
    <label for="name">Course:</label>
    <input type="text" id="name" name="user_name">
  </div>
  <div>
    <label for="mail">E-mail:</label>
    <input type="email" id="mail" name="user_mail">
  </div>
  <div>
    <label for="msg">Message:</label>
    <textarea id="msg" name="user_message"></textarea>
  </div>
</form>

2) Get the next element

you can use next() and get the span that way

$('.mailenquiry').click(function(e) {
  var nearestspan = $(this).next().text();
  $('.custom-contact div:nth-of-type(2) input').val(nearestspan);
});

$('.mailenquiry').click(function(e) {
  var nearestspan = $(this).next().text();
  $('.custom-contact div:nth-of-type(2) input').val(nearestspan);
});

table.table td span {
  display: none;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<table id="theTable" class="footable table outerBorder footable-loaded">
  <thead>
    <tr>
      <th id="thCol0" data-type="alpha">Date</th>
      <th id="thCol1" data-type="alpha">Module</th>
      <th id="thCol2" data-type="alpha">Price</th>
      <th id="thCol3" data-type="alpha">Venue</th>
      <th>Enquire</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>Mon 11/Dec/17</td>
      <td>Foo 1</td>
      <td>£55 (+VAT &amp; DVSA Upload)</td>
      <td>London</td>
      <td><a class="mailenquiry" href="#contact-now">Book</a><span>Enquiry about Foo 1 on Mon 11/Dec/17</span></td>
    </tr>
    <tr>
      <td>Tue 12/Dec/17</td>
      <td>Foo 2</td>
      <td>£55 (+VAT &amp; DVSA Upload)</td>
      <td>London</td>
      <td><a class="mailenquiry" href="#contact-now">Book</a><span>Enquiry about Foo 2 on Tue 12/Dec/17</span></td>
    </tr>
  </tbody>
</table>
<br><br>
<a id="contact-now"></a>
<form class="custom-contact" action="/my-handling-form-page" method="post">
  <div>
    <label for="name">Name:</label>
    <input type="text" id="name" name="user_name">
  </div>
  <div>
    <label for="name">Course:</label>
    <input type="text" id="name" name="user_name">
  </div>
  <div>
    <label for="mail">E-mail:</label>
    <input type="email" id="mail" name="user_mail">
  </div>
  <div>
    <label for="msg">Message:</label>
    <textarea id="msg" name="user_message"></textarea>
  </div>
</form>